forked from bitbegin/eth-wallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bip32-addr.red
71 lines (62 loc) · 1.7 KB
/
bip32-addr.red
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
Red [
Title: "bip32-addr"
Author: "bitbegin"
File: %bip32-addr.red
Tabs: 4
License: "BSD-3 - https://github.com/red/red/blob/master/BSD-3-License.txt"
]
#include %ripemd160.red
bip32-addr: context [
prefix: [
'P2PKH 0
'P2SH 5
'PRIV 80h
'BIP32-PUBKEY 0488B21Eh
'BIP32-PRIKEY 0488ADE4h
'TEST-P2PKH 6Fh
'TEST-P2SH C4h
'TEST-PRIV EFh
'TEST-BIP32-PUBKEY 043587CFh
'TEST-BIP32-PRIKEY 04358394h
]
encode58-check: func [data [binary!] return: [string!]][
append data copy/part checksum checksum data 'sha256 'sha256 4
enbase/base data 58
]
decode58-check: func [data [string!] return: [binary!]
/local bin len raw hash hash2
][
bin: debase/base data 58
if 4 >= len: length? bin [do make error! "invalid string!"]
raw: copy/part bin len - 4
hash: copy/part skip bin len - 4 4
hash2: copy/part checksum checksum raw 'sha256 'sha256 4
if hash <> hash2 [do make error! "invalid string!"]
raw
]
hash160: func [pubkey [binary!] return: [binary!]][
ripemd160 checksum pubkey 'sha256
]
pubkey-to-legacy-addr: func [pubkey [binary!] type [word!] return: [string!]
/local hash
][
insert hash: hash160 pubkey select prefix type
encode58-check hash
]
pubkey-to-addr: func [pubkey [binary!] type [word!] return: [string!]][
case [
any [type = 'P2PKH type = 'TEST-P2PKH][pubkey-to-legacy-addr pubkey type]
any [type = 'P2SH type = 'TEST-P2SH][pubkey-to-segwit-addr pubkey type]
true [none]
]
]
pubkey-to-segwit-addr: func [pubkey [binary!] type [word!] return: [string!]][
pubkey-to-legacy-addr pubkey-to-script pubkey type
]
pubkey-to-script: func [pubkey [binary!] return: [binary!]
/local hash
][
insert hash: hash160 pubkey #{0014}
hash
]
]