tapyrus 0.1.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/.gitignore +10 -0
- data/.rspec +2 -0
- data/.ruby-gemset +1 -0
- data/.ruby-version +1 -0
- data/.travis.yml +12 -0
- data/CODE_OF_CONDUCT.md +49 -0
- data/Gemfile +6 -0
- data/LICENSE.txt +21 -0
- data/README.md +100 -0
- data/Rakefile +6 -0
- data/bin/console +14 -0
- data/bin/setup +8 -0
- data/exe/tapyrusrb-cli +5 -0
- data/exe/tapyrusrbd +41 -0
- data/lib/openassets/marker_output.rb +20 -0
- data/lib/openassets/payload.rb +54 -0
- data/lib/openassets/util.rb +28 -0
- data/lib/openassets.rb +9 -0
- data/lib/tapyrus/base58.rb +38 -0
- data/lib/tapyrus/block.rb +77 -0
- data/lib/tapyrus/block_header.rb +88 -0
- data/lib/tapyrus/bloom_filter.rb +78 -0
- data/lib/tapyrus/chain_params.rb +90 -0
- data/lib/tapyrus/chainparams/mainnet.yml +41 -0
- data/lib/tapyrus/chainparams/regtest.yml +38 -0
- data/lib/tapyrus/chainparams/testnet.yml +41 -0
- data/lib/tapyrus/constants.rb +195 -0
- data/lib/tapyrus/descriptor.rb +147 -0
- data/lib/tapyrus/ext_key.rb +337 -0
- data/lib/tapyrus/key.rb +296 -0
- data/lib/tapyrus/key_path.rb +26 -0
- data/lib/tapyrus/logger.rb +42 -0
- data/lib/tapyrus/merkle_tree.rb +149 -0
- data/lib/tapyrus/message/addr.rb +35 -0
- data/lib/tapyrus/message/base.rb +28 -0
- data/lib/tapyrus/message/block.rb +46 -0
- data/lib/tapyrus/message/block_transaction_request.rb +45 -0
- data/lib/tapyrus/message/block_transactions.rb +31 -0
- data/lib/tapyrus/message/block_txn.rb +27 -0
- data/lib/tapyrus/message/cmpct_block.rb +42 -0
- data/lib/tapyrus/message/error.rb +10 -0
- data/lib/tapyrus/message/fee_filter.rb +27 -0
- data/lib/tapyrus/message/filter_add.rb +28 -0
- data/lib/tapyrus/message/filter_clear.rb +17 -0
- data/lib/tapyrus/message/filter_load.rb +39 -0
- data/lib/tapyrus/message/get_addr.rb +17 -0
- data/lib/tapyrus/message/get_block_txn.rb +27 -0
- data/lib/tapyrus/message/get_blocks.rb +29 -0
- data/lib/tapyrus/message/get_data.rb +21 -0
- data/lib/tapyrus/message/get_headers.rb +28 -0
- data/lib/tapyrus/message/header_and_short_ids.rb +57 -0
- data/lib/tapyrus/message/headers.rb +35 -0
- data/lib/tapyrus/message/headers_parser.rb +24 -0
- data/lib/tapyrus/message/inv.rb +21 -0
- data/lib/tapyrus/message/inventories_parser.rb +23 -0
- data/lib/tapyrus/message/inventory.rb +51 -0
- data/lib/tapyrus/message/mem_pool.rb +17 -0
- data/lib/tapyrus/message/merkle_block.rb +42 -0
- data/lib/tapyrus/message/network_addr.rb +63 -0
- data/lib/tapyrus/message/not_found.rb +21 -0
- data/lib/tapyrus/message/ping.rb +30 -0
- data/lib/tapyrus/message/pong.rb +26 -0
- data/lib/tapyrus/message/prefilled_tx.rb +29 -0
- data/lib/tapyrus/message/reject.rb +46 -0
- data/lib/tapyrus/message/send_cmpct.rb +43 -0
- data/lib/tapyrus/message/send_headers.rb +16 -0
- data/lib/tapyrus/message/tx.rb +30 -0
- data/lib/tapyrus/message/ver_ack.rb +17 -0
- data/lib/tapyrus/message/version.rb +69 -0
- data/lib/tapyrus/message.rb +70 -0
- data/lib/tapyrus/mnemonic/wordlist/chinese_simplified.txt +2048 -0
- data/lib/tapyrus/mnemonic/wordlist/chinese_traditional.txt +2048 -0
- data/lib/tapyrus/mnemonic/wordlist/english.txt +2048 -0
- data/lib/tapyrus/mnemonic/wordlist/french.txt +2048 -0
- data/lib/tapyrus/mnemonic/wordlist/italian.txt +2048 -0
- data/lib/tapyrus/mnemonic/wordlist/japanese.txt +2048 -0
- data/lib/tapyrus/mnemonic/wordlist/spanish.txt +2048 -0
- data/lib/tapyrus/mnemonic.rb +77 -0
- data/lib/tapyrus/network/connection.rb +73 -0
- data/lib/tapyrus/network/message_handler.rb +241 -0
- data/lib/tapyrus/network/peer.rb +223 -0
- data/lib/tapyrus/network/peer_discovery.rb +42 -0
- data/lib/tapyrus/network/pool.rb +135 -0
- data/lib/tapyrus/network.rb +13 -0
- data/lib/tapyrus/node/cli.rb +112 -0
- data/lib/tapyrus/node/configuration.rb +38 -0
- data/lib/tapyrus/node/spv.rb +79 -0
- data/lib/tapyrus/node.rb +7 -0
- data/lib/tapyrus/opcodes.rb +178 -0
- data/lib/tapyrus/out_point.rb +44 -0
- data/lib/tapyrus/rpc/http_server.rb +65 -0
- data/lib/tapyrus/rpc/request_handler.rb +150 -0
- data/lib/tapyrus/rpc/tapyrus_core_client.rb +72 -0
- data/lib/tapyrus/rpc.rb +7 -0
- data/lib/tapyrus/script/multisig.rb +92 -0
- data/lib/tapyrus/script/script.rb +551 -0
- data/lib/tapyrus/script/script_error.rb +111 -0
- data/lib/tapyrus/script/script_interpreter.rb +668 -0
- data/lib/tapyrus/script/tx_checker.rb +81 -0
- data/lib/tapyrus/script_witness.rb +38 -0
- data/lib/tapyrus/secp256k1/native.rb +174 -0
- data/lib/tapyrus/secp256k1/ruby.rb +123 -0
- data/lib/tapyrus/secp256k1.rb +12 -0
- data/lib/tapyrus/slip39/share.rb +122 -0
- data/lib/tapyrus/slip39/sss.rb +245 -0
- data/lib/tapyrus/slip39/wordlist/english.txt +1024 -0
- data/lib/tapyrus/slip39.rb +93 -0
- data/lib/tapyrus/store/chain_entry.rb +67 -0
- data/lib/tapyrus/store/db/level_db.rb +98 -0
- data/lib/tapyrus/store/db.rb +9 -0
- data/lib/tapyrus/store/spv_chain.rb +101 -0
- data/lib/tapyrus/store.rb +9 -0
- data/lib/tapyrus/tx.rb +347 -0
- data/lib/tapyrus/tx_in.rb +89 -0
- data/lib/tapyrus/tx_out.rb +74 -0
- data/lib/tapyrus/util.rb +133 -0
- data/lib/tapyrus/validation.rb +115 -0
- data/lib/tapyrus/version.rb +3 -0
- data/lib/tapyrus/wallet/account.rb +151 -0
- data/lib/tapyrus/wallet/base.rb +162 -0
- data/lib/tapyrus/wallet/db.rb +81 -0
- data/lib/tapyrus/wallet/master_key.rb +110 -0
- data/lib/tapyrus/wallet.rb +8 -0
- data/lib/tapyrus.rb +219 -0
- data/tapyrusrb.conf.sample +0 -0
- data/tapyrusrb.gemspec +47 -0
- metadata +451 -0
@@ -0,0 +1,81 @@
|
|
1
|
+
module Tapyrus
|
2
|
+
class TxChecker
|
3
|
+
|
4
|
+
attr_reader :tx
|
5
|
+
attr_reader :input_index
|
6
|
+
attr_reader :amount
|
7
|
+
|
8
|
+
def initialize(tx: nil, amount: 0, input_index: nil)
|
9
|
+
@tx = tx
|
10
|
+
@amount = amount
|
11
|
+
@input_index = input_index
|
12
|
+
end
|
13
|
+
|
14
|
+
# check signature
|
15
|
+
# @param [String] script_sig
|
16
|
+
# @param [String] pubkey
|
17
|
+
# @param [Tapyrus::Script] script_code
|
18
|
+
# @param [Integer] sig_version
|
19
|
+
def check_sig(script_sig, pubkey, script_code, sig_version)
|
20
|
+
return false if script_sig.empty?
|
21
|
+
script_sig = script_sig.htb
|
22
|
+
hash_type = script_sig[-1].unpack('C').first
|
23
|
+
sig = script_sig[0..-2]
|
24
|
+
sighash = tx.sighash_for_input(input_index, script_code, hash_type: hash_type,
|
25
|
+
amount: amount, sig_version: sig_version)
|
26
|
+
key_type = pubkey.start_with?('02') || pubkey.start_with?('03') ? Key::TYPES[:compressed] : Key::TYPES[:uncompressed]
|
27
|
+
key = Key.new(pubkey: pubkey, key_type: key_type)
|
28
|
+
key.verify(sig, sighash)
|
29
|
+
end
|
30
|
+
|
31
|
+
def check_locktime(locktime)
|
32
|
+
# There are two kinds of nLockTime: lock-by-blockheight and lock-by-blocktime,
|
33
|
+
# distinguished by whether nLockTime < LOCKTIME_THRESHOLD.
|
34
|
+
|
35
|
+
# We want to compare apples to apples, so fail the script unless the type of nLockTime being tested is the same as the nLockTime in the transaction.
|
36
|
+
unless ((tx.lock_time < LOCKTIME_THRESHOLD && locktime < LOCKTIME_THRESHOLD) ||
|
37
|
+
(tx.lock_time >= LOCKTIME_THRESHOLD && locktime >= LOCKTIME_THRESHOLD))
|
38
|
+
return false
|
39
|
+
end
|
40
|
+
|
41
|
+
# Now that we know we're comparing apples-to-apples, the comparison is a simple numeric one.
|
42
|
+
return false if locktime > tx.lock_time
|
43
|
+
|
44
|
+
# Finally the nLockTime feature can be disabled and thus CHECKLOCKTIMEVERIFY bypassed if every txin has been finalized by setting nSequence to maxint.
|
45
|
+
# The transaction would be allowed into the blockchain, making the opcode ineffective.
|
46
|
+
# Testing if this vin is not final is sufficient to prevent this condition.
|
47
|
+
# Alternatively we could test all inputs, but testing just this input minimizes the data required to prove correct CHECKLOCKTIMEVERIFY execution.
|
48
|
+
return false if TxIn::SEQUENCE_FINAL == tx.inputs[input_index].sequence
|
49
|
+
|
50
|
+
true
|
51
|
+
end
|
52
|
+
|
53
|
+
def check_sequence(sequence)
|
54
|
+
tx_sequence = tx.inputs[input_index].sequence
|
55
|
+
# Fail if the transaction's version number is not set high enough to trigger BIP 68 rules.
|
56
|
+
return false if tx.version < 2
|
57
|
+
|
58
|
+
# Sequence numbers with their most significant bit set are not consensus constrained.
|
59
|
+
# Testing that the transaction's sequence number do not have this bit set prevents using this property to get around a CHECKSEQUENCEVERIFY check.
|
60
|
+
return false unless tx_sequence & TxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG == 0
|
61
|
+
|
62
|
+
# Mask off any bits that do not have consensus-enforced meaning before doing the integer comparisons
|
63
|
+
locktime_mask = TxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | TxIn::SEQUENCE_LOCKTIME_MASK
|
64
|
+
tx_sequence_masked = tx_sequence & locktime_mask
|
65
|
+
sequence_masked = sequence & locktime_mask
|
66
|
+
|
67
|
+
# There are two kinds of nSequence: lock-by-blockheight and lock-by-blocktime,
|
68
|
+
# distinguished by whether sequence_masked < TxIn#SEQUENCE_LOCKTIME_TYPE_FLAG.
|
69
|
+
# We want to compare apples to apples, so fail the script
|
70
|
+
# unless the type of nSequenceMasked being tested is the same as the nSequenceMasked in the transaction.
|
71
|
+
unless ((tx_sequence_masked < TxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && sequence_masked < TxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
|
72
|
+
(tx_sequence_masked >= TxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && sequence_masked >= TxIn::SEQUENCE_LOCKTIME_TYPE_FLAG))
|
73
|
+
return false
|
74
|
+
end
|
75
|
+
|
76
|
+
# Now that we know we're comparing apples-to-apples, the comparison is a simple numeric one.
|
77
|
+
sequence_masked <= tx_sequence_masked
|
78
|
+
end
|
79
|
+
|
80
|
+
end
|
81
|
+
end
|
@@ -0,0 +1,38 @@
|
|
1
|
+
module Tapyrus
|
2
|
+
|
3
|
+
# witness
|
4
|
+
class ScriptWitness
|
5
|
+
|
6
|
+
attr_reader :stack
|
7
|
+
|
8
|
+
def initialize(stack = [])
|
9
|
+
@stack = stack
|
10
|
+
end
|
11
|
+
|
12
|
+
def self.parse_from_payload(payload)
|
13
|
+
buf = payload.is_a?(StringIO) ? payload : StringIO.new(payload)
|
14
|
+
size = Tapyrus.unpack_var_int_from_io(buf)
|
15
|
+
stack = size.times.map do
|
16
|
+
buf.read(Tapyrus.unpack_var_int_from_io(buf))
|
17
|
+
end
|
18
|
+
self.new(stack)
|
19
|
+
end
|
20
|
+
|
21
|
+
def empty?
|
22
|
+
stack.empty?
|
23
|
+
end
|
24
|
+
|
25
|
+
def to_payload
|
26
|
+
p = Tapyrus.pack_var_int(stack.size)
|
27
|
+
p << stack.map { |s|
|
28
|
+
Tapyrus.pack_var_int(s.bytesize) << s
|
29
|
+
}.join
|
30
|
+
end
|
31
|
+
|
32
|
+
def to_s
|
33
|
+
stack.map{|s|s.bth}.join(' ')
|
34
|
+
end
|
35
|
+
|
36
|
+
end
|
37
|
+
|
38
|
+
end
|
@@ -0,0 +1,174 @@
|
|
1
|
+
# Porting part of the code from bitcoin-ruby. see the license.
|
2
|
+
# https://github.com/lian/bitcoin-ruby/blob/master/COPYING
|
3
|
+
|
4
|
+
module Tapyrus
|
5
|
+
module Secp256k1
|
6
|
+
|
7
|
+
# binding for secp256k1 (https://github.com/bitcoin/bitcoin/tree/v0.14.2/src/secp256k1)
|
8
|
+
# tag: v0.14.2
|
9
|
+
# this is not included by default, to enable set shared object path to ENV['SECP256K1_LIB_PATH']
|
10
|
+
# for linux, ENV['SECP256K1_LIB_PATH'] = '/usr/local/lib/libsecp256k1.so'
|
11
|
+
# for mac,
|
12
|
+
module Native
|
13
|
+
include ::FFI::Library
|
14
|
+
extend self
|
15
|
+
|
16
|
+
SECP256K1_FLAGS_TYPE_MASK = ((1 << 8) - 1)
|
17
|
+
SECP256K1_FLAGS_TYPE_CONTEXT = (1 << 0)
|
18
|
+
SECP256K1_FLAGS_TYPE_COMPRESSION = (1 << 1)
|
19
|
+
|
20
|
+
SECP256K1_FLAGS_BIT_CONTEXT_VERIFY = (1 << 8)
|
21
|
+
SECP256K1_FLAGS_BIT_CONTEXT_SIGN = (1 << 9)
|
22
|
+
SECP256K1_FLAGS_BIT_COMPRESSION = (1 << 8)
|
23
|
+
|
24
|
+
# Flags to pass to secp256k1_context_create.
|
25
|
+
SECP256K1_CONTEXT_VERIFY = (SECP256K1_FLAGS_TYPE_CONTEXT | SECP256K1_FLAGS_BIT_CONTEXT_VERIFY)
|
26
|
+
SECP256K1_CONTEXT_SIGN = (SECP256K1_FLAGS_TYPE_CONTEXT | SECP256K1_FLAGS_BIT_CONTEXT_SIGN)
|
27
|
+
|
28
|
+
# Flag to pass to secp256k1_ec_pubkey_serialize and secp256k1_ec_privkey_export.
|
29
|
+
SECP256K1_EC_COMPRESSED = (SECP256K1_FLAGS_TYPE_COMPRESSION | SECP256K1_FLAGS_BIT_COMPRESSION)
|
30
|
+
SECP256K1_EC_UNCOMPRESSED = (SECP256K1_FLAGS_TYPE_COMPRESSION)
|
31
|
+
|
32
|
+
module_function
|
33
|
+
|
34
|
+
def init
|
35
|
+
raise 'secp256k1 library dose not found.' unless File.exist?(ENV['SECP256K1_LIB_PATH'])
|
36
|
+
ffi_lib(ENV['SECP256K1_LIB_PATH'])
|
37
|
+
load_functions
|
38
|
+
end
|
39
|
+
|
40
|
+
def load_functions
|
41
|
+
attach_function(:secp256k1_context_create, [:uint], :pointer)
|
42
|
+
attach_function(:secp256k1_context_destroy, [:pointer], :void)
|
43
|
+
attach_function(:secp256k1_context_randomize, [:pointer, :pointer], :int)
|
44
|
+
attach_function(:secp256k1_ec_pubkey_create, [:pointer, :pointer, :pointer], :int)
|
45
|
+
attach_function(:secp256k1_ec_seckey_verify, [:pointer, :pointer], :int)
|
46
|
+
attach_function(:secp256k1_ecdsa_sign, [:pointer, :pointer, :pointer, :pointer, :pointer, :pointer], :int)
|
47
|
+
attach_function(:secp256k1_ec_pubkey_serialize, [:pointer, :pointer, :pointer, :pointer, :uint], :int)
|
48
|
+
attach_function(:secp256k1_ecdsa_signature_serialize_der, [:pointer, :pointer, :pointer, :pointer], :int)
|
49
|
+
attach_function(:secp256k1_ec_pubkey_parse, [:pointer, :pointer, :pointer, :size_t], :int)
|
50
|
+
attach_function(:secp256k1_ecdsa_signature_parse_der, [:pointer, :pointer, :pointer, :size_t], :int)
|
51
|
+
attach_function(:secp256k1_ecdsa_signature_normalize, [:pointer, :pointer, :pointer], :int)
|
52
|
+
attach_function(:secp256k1_ecdsa_verify, [:pointer, :pointer, :pointer, :pointer], :int)
|
53
|
+
end
|
54
|
+
|
55
|
+
def with_context(flags: (SECP256K1_CONTEXT_VERIFY | SECP256K1_CONTEXT_SIGN))
|
56
|
+
init
|
57
|
+
begin
|
58
|
+
context = secp256k1_context_create(flags)
|
59
|
+
ret, tries, max = 0, 0, 20
|
60
|
+
while ret != 1
|
61
|
+
raise 'secp256k1_context_randomize failed.' if tries >= max
|
62
|
+
tries += 1
|
63
|
+
ret = secp256k1_context_randomize(context, FFI::MemoryPointer.from_string(SecureRandom.random_bytes(32)))
|
64
|
+
end
|
65
|
+
yield(context) if block_given?
|
66
|
+
ensure
|
67
|
+
secp256k1_context_destroy(context)
|
68
|
+
end
|
69
|
+
end
|
70
|
+
|
71
|
+
# generate ec private key and public key
|
72
|
+
def generate_key_pair(compressed: true)
|
73
|
+
with_context do |context|
|
74
|
+
ret, tries, max = 0, 0, 20
|
75
|
+
while ret != 1
|
76
|
+
raise 'secp256k1_ec_seckey_verify in generate_key_pair failed.' if tries >= max
|
77
|
+
tries += 1
|
78
|
+
priv_key = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, SecureRandom.random_bytes(32))
|
79
|
+
ret = secp256k1_ec_seckey_verify(context, priv_key)
|
80
|
+
end
|
81
|
+
private_key = priv_key.read_string(32).bth
|
82
|
+
[private_key , generate_pubkey_in_context(context, private_key, compressed: compressed) ]
|
83
|
+
end
|
84
|
+
end
|
85
|
+
|
86
|
+
# generate tapyrus key object
|
87
|
+
def generate_key(compressed: true)
|
88
|
+
privkey, pubkey = generate_key_pair(compressed: compressed)
|
89
|
+
Tapyrus::Key.new(priv_key: privkey, pubkey: pubkey, compressed: compressed)
|
90
|
+
end
|
91
|
+
|
92
|
+
def generate_pubkey(priv_key, compressed: true)
|
93
|
+
with_context do |context|
|
94
|
+
generate_pubkey_in_context(context, priv_key, compressed: compressed)
|
95
|
+
end
|
96
|
+
end
|
97
|
+
|
98
|
+
# sign data.
|
99
|
+
# @param [String] data a data to be signed with binary format
|
100
|
+
# @param [String] privkey a private key using sign
|
101
|
+
# @param [String] extra_entropy a extra entropy for rfc6979
|
102
|
+
# @return [String] signature data with binary format
|
103
|
+
def sign_data(data, privkey, extra_entropy)
|
104
|
+
with_context do |context|
|
105
|
+
secret = FFI::MemoryPointer.new(:uchar, privkey.htb.bytesize).put_bytes(0, privkey.htb)
|
106
|
+
raise 'priv_key invalid' unless secp256k1_ec_seckey_verify(context, secret)
|
107
|
+
|
108
|
+
internal_signature = FFI::MemoryPointer.new(:uchar, 64)
|
109
|
+
msg32 = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, data)
|
110
|
+
entropy = extra_entropy ? FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, extra_entropy) : nil
|
111
|
+
|
112
|
+
ret, tries, max = 0, 0, 20
|
113
|
+
|
114
|
+
while ret != 1
|
115
|
+
raise 'secp256k1_ecdsa_sign failed.' if tries >= max
|
116
|
+
tries += 1
|
117
|
+
ret = secp256k1_ecdsa_sign(context, internal_signature, msg32, secret, nil, entropy)
|
118
|
+
end
|
119
|
+
|
120
|
+
signature = FFI::MemoryPointer.new(:uchar, 72)
|
121
|
+
signature_len = FFI::MemoryPointer.new(:uint64).put_uint64(0, 72)
|
122
|
+
result = secp256k1_ecdsa_signature_serialize_der(context, signature, signature_len, internal_signature)
|
123
|
+
raise 'secp256k1_ecdsa_signature_serialize_der failed' unless result
|
124
|
+
|
125
|
+
signature.read_string(signature_len.read_uint64)
|
126
|
+
end
|
127
|
+
end
|
128
|
+
|
129
|
+
def verify_sig(data, sig, pub_key)
|
130
|
+
with_context do |context|
|
131
|
+
return false if data.bytesize == 0
|
132
|
+
|
133
|
+
pubkey = FFI::MemoryPointer.new(:uchar, pub_key.htb.bytesize).put_bytes(0, pub_key.htb)
|
134
|
+
internal_pubkey = FFI::MemoryPointer.new(:uchar, 64)
|
135
|
+
result = secp256k1_ec_pubkey_parse(context, internal_pubkey, pubkey, pubkey.size)
|
136
|
+
return false unless result
|
137
|
+
|
138
|
+
signature = FFI::MemoryPointer.new(:uchar, sig.bytesize).put_bytes(0, sig)
|
139
|
+
internal_signature = FFI::MemoryPointer.new(:uchar, 64)
|
140
|
+
result = secp256k1_ecdsa_signature_parse_der(context, internal_signature, signature, signature.size)
|
141
|
+
return false unless result
|
142
|
+
|
143
|
+
# libsecp256k1's ECDSA verification requires lower-S signatures, which have not historically been enforced in Bitcoin, so normalize them first.
|
144
|
+
secp256k1_ecdsa_signature_normalize(context, internal_signature, internal_signature)
|
145
|
+
|
146
|
+
msg32 = FFI::MemoryPointer.new(:uchar, 32).put_bytes(0, data)
|
147
|
+
result = secp256k1_ecdsa_verify(context, internal_signature, msg32, internal_pubkey)
|
148
|
+
|
149
|
+
result == 1
|
150
|
+
end
|
151
|
+
end
|
152
|
+
|
153
|
+
private
|
154
|
+
|
155
|
+
def generate_pubkey_in_context(context, privkey, compressed: true)
|
156
|
+
internal_pubkey = FFI::MemoryPointer.new(:uchar, 64)
|
157
|
+
result = secp256k1_ec_pubkey_create(context, internal_pubkey, privkey.htb)
|
158
|
+
raise 'error creating pubkey' unless result
|
159
|
+
|
160
|
+
pubkey = FFI::MemoryPointer.new(:uchar, 65)
|
161
|
+
pubkey_len = FFI::MemoryPointer.new(:uint64)
|
162
|
+
result = if compressed
|
163
|
+
pubkey_len.put_uint64(0, 33)
|
164
|
+
secp256k1_ec_pubkey_serialize(context, pubkey, pubkey_len, internal_pubkey, SECP256K1_EC_COMPRESSED)
|
165
|
+
else
|
166
|
+
pubkey_len.put_uint64(0, 65)
|
167
|
+
secp256k1_ec_pubkey_serialize(context, pubkey, pubkey_len, internal_pubkey, SECP256K1_EC_UNCOMPRESSED)
|
168
|
+
end
|
169
|
+
raise 'error serialize pubkey' unless result || pubkey_len.read_uint64 > 0
|
170
|
+
pubkey.read_string(pubkey_len.read_uint64).bth
|
171
|
+
end
|
172
|
+
end
|
173
|
+
end
|
174
|
+
end
|
@@ -0,0 +1,123 @@
|
|
1
|
+
module Tapyrus
|
2
|
+
module Secp256k1
|
3
|
+
|
4
|
+
# secp256 module using ecdsa gem
|
5
|
+
# https://github.com/DavidEGrayson/ruby_ecdsa
|
6
|
+
module Ruby
|
7
|
+
|
8
|
+
module_function
|
9
|
+
|
10
|
+
# generate ec private key and public key
|
11
|
+
def generate_key_pair(compressed: true)
|
12
|
+
private_key = 1 + SecureRandom.random_number(GROUP.order - 1)
|
13
|
+
public_key = GROUP.generator.multiply_by_scalar(private_key)
|
14
|
+
privkey = ECDSA::Format::IntegerOctetString.encode(private_key, 32)
|
15
|
+
pubkey = ECDSA::Format::PointOctetString.encode(public_key, compression: compressed)
|
16
|
+
[privkey.bth, pubkey.bth]
|
17
|
+
end
|
18
|
+
|
19
|
+
# generate tapyrus key object
|
20
|
+
def generate_key(compressed: true)
|
21
|
+
privkey, pubkey = generate_key_pair(compressed: compressed)
|
22
|
+
Tapyrus::Key.new(priv_key: privkey, pubkey: pubkey, compressed: compressed)
|
23
|
+
end
|
24
|
+
|
25
|
+
def generate_pubkey(privkey, compressed: true)
|
26
|
+
public_key = ECDSA::Group::Secp256k1.generator.multiply_by_scalar(privkey.to_i(16))
|
27
|
+
ECDSA::Format::PointOctetString.encode(public_key, compression: compressed).bth
|
28
|
+
end
|
29
|
+
|
30
|
+
# sign data.
|
31
|
+
# @param [String] data a data to be signed with binary format
|
32
|
+
# @param [String] privkey a private key using sign
|
33
|
+
# @return [String] signature data with binary format
|
34
|
+
def sign_data(data, privkey, extra_entropy)
|
35
|
+
privkey = privkey.htb
|
36
|
+
private_key = ECDSA::Format::IntegerOctetString.decode(privkey)
|
37
|
+
extra_entropy ||= ''
|
38
|
+
nonce = generate_rfc6979_nonce(data, privkey, extra_entropy)
|
39
|
+
|
40
|
+
# port form ecdsa gem.
|
41
|
+
r_point = GROUP.new_point(nonce)
|
42
|
+
|
43
|
+
point_field = ECDSA::PrimeField.new(GROUP.order)
|
44
|
+
r = point_field.mod(r_point.x)
|
45
|
+
return nil if r.zero?
|
46
|
+
|
47
|
+
e = ECDSA.normalize_digest(data, GROUP.bit_length)
|
48
|
+
s = point_field.mod(point_field.inverse(nonce) * (e + r * private_key))
|
49
|
+
|
50
|
+
if s > (GROUP.order / 2) # convert low-s
|
51
|
+
s = GROUP.order - s
|
52
|
+
end
|
53
|
+
|
54
|
+
return nil if s.zero?
|
55
|
+
|
56
|
+
signature = ECDSA::Signature.new(r, s).to_der
|
57
|
+
public_key = Tapyrus::Key.new(priv_key: privkey.bth).pubkey
|
58
|
+
raise 'Creation of signature failed.' unless Tapyrus::Secp256k1::Ruby.verify_sig(data, signature, public_key)
|
59
|
+
signature
|
60
|
+
end
|
61
|
+
|
62
|
+
# verify signature using public key
|
63
|
+
# @param [String] digest a SHA-256 message digest with binary format
|
64
|
+
# @param [String] sig a signature for +data+ with binary format
|
65
|
+
# @param [String] pubkey a public key corresponding to the private key used for sign
|
66
|
+
# @return [Boolean] verify result
|
67
|
+
def verify_sig(digest, sig, pubkey)
|
68
|
+
begin
|
69
|
+
k = ECDSA::Format::PointOctetString.decode(repack_pubkey(pubkey), GROUP)
|
70
|
+
signature = ECDSA::Format::SignatureDerString.decode(sig)
|
71
|
+
ECDSA.valid_signature?(k, digest, signature)
|
72
|
+
rescue Exception
|
73
|
+
false
|
74
|
+
end
|
75
|
+
end
|
76
|
+
|
77
|
+
# if +pubkey+ is hybrid public key format, it convert uncompressed format.
|
78
|
+
# https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2012-June/001578.html
|
79
|
+
def repack_pubkey(pubkey)
|
80
|
+
p = pubkey.htb
|
81
|
+
case p[0]
|
82
|
+
when "\x06", "\x07"
|
83
|
+
p[0] = "\x04"
|
84
|
+
p
|
85
|
+
else
|
86
|
+
pubkey.htb
|
87
|
+
end
|
88
|
+
end
|
89
|
+
|
90
|
+
INITIAL_V = '0101010101010101010101010101010101010101010101010101010101010101'.htb
|
91
|
+
INITIAL_K = '0000000000000000000000000000000000000000000000000000000000000000'.htb
|
92
|
+
ZERO_B = '00'.htb
|
93
|
+
ONE_B = '01'.htb
|
94
|
+
|
95
|
+
# generate temporary key k to be used when ECDSA sign.
|
96
|
+
# https://tools.ietf.org/html/rfc6979#section-3.2
|
97
|
+
def generate_rfc6979_nonce(data, privkey, extra_entropy)
|
98
|
+
v = INITIAL_V # 3.2.b
|
99
|
+
k = INITIAL_K # 3.2.c
|
100
|
+
# 3.2.d
|
101
|
+
k = Tapyrus.hmac_sha256(k, v + ZERO_B + privkey + data + extra_entropy)
|
102
|
+
# 3.2.e
|
103
|
+
v = Tapyrus.hmac_sha256(k, v)
|
104
|
+
# 3.2.f
|
105
|
+
k = Tapyrus.hmac_sha256(k, v + ONE_B + privkey + data + extra_entropy)
|
106
|
+
# 3.2.g
|
107
|
+
v = Tapyrus.hmac_sha256(k, v)
|
108
|
+
# 3.2.h
|
109
|
+
t = ''
|
110
|
+
10000.times do
|
111
|
+
v = Tapyrus.hmac_sha256(k, v)
|
112
|
+
t = (t + v)
|
113
|
+
t_num = t.bth.to_i(16)
|
114
|
+
return t_num if 1 <= t_num && t_num < GROUP.order
|
115
|
+
k = Tapyrus.hmac_sha256(k, v + '00'.htb)
|
116
|
+
v = Tapyrus.hmac_sha256(k, v)
|
117
|
+
end
|
118
|
+
raise 'A valid nonce was not found.'
|
119
|
+
end
|
120
|
+
end
|
121
|
+
|
122
|
+
end
|
123
|
+
end
|
@@ -0,0 +1,122 @@
|
|
1
|
+
module Tapyrus
|
2
|
+
module SLIP39
|
3
|
+
|
4
|
+
# Share of Shamir's Secret Sharing Scheme
|
5
|
+
class Share
|
6
|
+
|
7
|
+
attr_accessor :id # 15 bits, Integer
|
8
|
+
attr_accessor :iteration_exp # 5 bits, Integer
|
9
|
+
attr_accessor :group_index # 4 bits, Integer
|
10
|
+
attr_accessor :group_threshold # 4 bits, Integer
|
11
|
+
attr_accessor :group_count # 4 bits, Integer
|
12
|
+
attr_accessor :member_index # 4 bits, Integer
|
13
|
+
attr_accessor :member_threshold # 4 bits, Integer
|
14
|
+
attr_accessor :value # 8n bits, hex string.
|
15
|
+
attr_accessor :checksum # 30 bits, Integer
|
16
|
+
|
17
|
+
# Recover Share from the mnemonic words
|
18
|
+
# @param [Array{String}] words the mnemonic words
|
19
|
+
# @return [Tapyrus::SLIP39::Share] a share
|
20
|
+
def self.from_words(words)
|
21
|
+
raise ArgumentError, 'Mnemonics should be an array of strings' unless words.is_a?(Array)
|
22
|
+
indices = words.map do |word|
|
23
|
+
index = Tapyrus::SLIP39::WORDS.index(word.downcase)
|
24
|
+
raise IndexError, 'word not found in words list.' unless index
|
25
|
+
index
|
26
|
+
end
|
27
|
+
|
28
|
+
raise ArgumentError, 'Invalid mnemonic length.' if indices.size < MIN_MNEMONIC_LENGTH_WORDS
|
29
|
+
raise ArgumentError, 'Invalid mnemonic checksum.' unless verify_rs1024_checksum(indices)
|
30
|
+
|
31
|
+
padding_length = (RADIX_BITS * (indices.size - METADATA_LENGTH_WORDS)) % 16
|
32
|
+
raise ArgumentError, 'Invalid mnemonic length.' if padding_length > 8
|
33
|
+
data = indices.map{|i|i.to_s(2).rjust(10, '0')}.join
|
34
|
+
|
35
|
+
s = self.new
|
36
|
+
s.id = data[0...ID_LENGTH_BITS].to_i(2)
|
37
|
+
s.iteration_exp = data[ID_LENGTH_BITS...(ID_LENGTH_BITS + ITERATION_EXP_LENGTH_BITS)].to_i(2)
|
38
|
+
s.group_index = data[20...24].to_i(2)
|
39
|
+
s.group_threshold = data[24...28].to_i(2) + 1
|
40
|
+
s.group_count = data[28...32].to_i(2) + 1
|
41
|
+
raise ArgumentError, "Invalid mnemonic. Group threshold(#{s.group_threshold}) cannot be greater than group count(#{s.group_count})." if s.group_threshold > s.group_count
|
42
|
+
s.member_index = data[32...36].to_i(2)
|
43
|
+
s.member_threshold = data[36...40].to_i(2) + 1
|
44
|
+
value_length = data.length - 70
|
45
|
+
start_index = 40 + padding_length
|
46
|
+
end_index = start_index + value_length - padding_length
|
47
|
+
padding_value = data[40...(40 + padding_length)]
|
48
|
+
raise ArgumentError, "Invalid mnemonic. padding must only zero." unless padding_value.to_i(2) == 0
|
49
|
+
s.value = data[start_index...end_index].to_i(2).to_even_length_hex
|
50
|
+
s.checksum = data[(40 + value_length)..-1].to_i(2)
|
51
|
+
s
|
52
|
+
end
|
53
|
+
|
54
|
+
# Generate mnemonic words
|
55
|
+
# @return [Array[String]] array of mnemonic word.
|
56
|
+
def to_words
|
57
|
+
indices = build_word_indices
|
58
|
+
indices.map{|index| Tapyrus::SLIP39::WORDS[index]}
|
59
|
+
end
|
60
|
+
|
61
|
+
# Calculate checksum using current fields
|
62
|
+
# @return [Integer] checksum
|
63
|
+
def calculate_checksum
|
64
|
+
indices = build_word_indices(false)
|
65
|
+
create_rs1024_checksum(indices).map{|i|i.to_bits(10)}.join.to_i(2)
|
66
|
+
end
|
67
|
+
|
68
|
+
def self.rs1024_polymod(values)
|
69
|
+
gen = [0xe0e040, 0x1c1c080, 0x3838100, 0x7070200, 0xe0e0009, 0x1c0c2412, 0x38086c24, 0x3090fc48, 0x21b1f890, 0x3f3f120]
|
70
|
+
chk = 1
|
71
|
+
values.each do |v|
|
72
|
+
b = (chk >> 20)
|
73
|
+
chk = (chk & 0xfffff) << 10 ^ v
|
74
|
+
10.times do |i|
|
75
|
+
chk ^= (((b >> i) & 1 == 1) ? gen[i] : 0)
|
76
|
+
end
|
77
|
+
end
|
78
|
+
chk
|
79
|
+
end
|
80
|
+
|
81
|
+
private
|
82
|
+
|
83
|
+
# Create word indices from this share.
|
84
|
+
# @param [Boolean] include_checksum whether include checksum when creating indices.
|
85
|
+
# @param [Array[Integer]] the array of index
|
86
|
+
def build_word_indices(include_checksum = true)
|
87
|
+
s = id.to_bits(ID_LENGTH_BITS)
|
88
|
+
s << iteration_exp.to_bits(ITERATION_EXP_LENGTH_BITS)
|
89
|
+
s << group_index.to_bits(4)
|
90
|
+
s << (group_threshold - 1).to_bits(4)
|
91
|
+
s << (group_count - 1).to_bits(4)
|
92
|
+
raise StandardError, "Group threshold(#{group_threshold}) cannot be greater than group count(#{group_count})." if group_threshold > group_count
|
93
|
+
s << member_index.to_bits(4)
|
94
|
+
s << (member_threshold - 1).to_bits(4)
|
95
|
+
value_length = value.to_i(16).bit_length
|
96
|
+
padding_length = RADIX_BITS - (value_length % RADIX_BITS)
|
97
|
+
s << value.to_i(16).to_bits(value_length + padding_length)
|
98
|
+
s << checksum.to_bits(30) if include_checksum
|
99
|
+
s.chars.each_slice(10).map{|index| index.join.to_i(2)}
|
100
|
+
end
|
101
|
+
|
102
|
+
# Verify RS1024 checksum
|
103
|
+
# @param [Array[Integer] data the array of mnemonic word index
|
104
|
+
# @return [Boolean] verify result
|
105
|
+
def self.verify_rs1024_checksum(data)
|
106
|
+
rs1024_polymod(CUSTOMIZATION_STRING + data) == 1
|
107
|
+
end
|
108
|
+
|
109
|
+
# Create RS1024 checksum
|
110
|
+
# @param [Array[Integer] data the array of mnemonic word index without checksum
|
111
|
+
# @return [Array[Integer]] the array of checksum integer
|
112
|
+
def create_rs1024_checksum(data)
|
113
|
+
values = CUSTOMIZATION_STRING + data + Array.new(CHECKSUM_LENGTH_WORDS, 0)
|
114
|
+
polymod = Tapyrus::SLIP39::Share.rs1024_polymod(values) ^ 1
|
115
|
+
CHECKSUM_LENGTH_WORDS.times.to_a.reverse.map {|i|(polymod >> (10 * i)) & 1023 }
|
116
|
+
end
|
117
|
+
|
118
|
+
private_class_method :verify_rs1024_checksum
|
119
|
+
|
120
|
+
end
|
121
|
+
end
|
122
|
+
end
|