def test_version_bytes(self): xprv_headers_b58 = { 'standard': 'tprv', 'p2wpkh-p2sh': 'uprv', 'p2wsh-p2sh': 'Uprv', 'p2wpkh': 'vprv', 'p2wsh': 'Vprv', } xpub_headers_b58 = { 'standard': 'tpub', 'p2wpkh-p2sh': 'upub', 'p2wsh-p2sh': 'Upub', 'p2wpkh': 'vpub', 'p2wsh': 'Vpub', } for xtype, xkey_header_bytes in constants.net.XPRV_HEADERS.items(): xkey_header_bytes = bfh("%08x" % xkey_header_bytes) xkey_bytes = xkey_header_bytes + bytes([0] * 74) xkey_b58 = EncodeBase58Check(xkey_bytes) self.assertTrue(xkey_b58.startswith(xprv_headers_b58[xtype])) xkey_bytes = xkey_header_bytes + bytes([255] * 74) xkey_b58 = EncodeBase58Check(xkey_bytes) self.assertTrue(xkey_b58.startswith(xprv_headers_b58[xtype])) for xtype, xkey_header_bytes in constants.net.XPUB_HEADERS.items(): xkey_header_bytes = bfh("%08x" % xkey_header_bytes) xkey_bytes = xkey_header_bytes + bytes([0] * 74) xkey_b58 = EncodeBase58Check(xkey_bytes) self.assertTrue(xkey_b58.startswith(xpub_headers_b58[xtype])) xkey_bytes = xkey_header_bytes + bytes([255] * 74) xkey_b58 = EncodeBase58Check(xkey_bytes) self.assertTrue(xkey_b58.startswith(xpub_headers_b58[xtype]))
def test_key_derivation(self): # BOLT3, Appendix E base_secret = 0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f per_commitment_secret = 0x1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100 revocation_basepoint_secret = 0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f base_point = secret_to_pubkey(base_secret) self.assertEqual( base_point, bfh('036d6caac248af96f6afa7f904f550253a0f3ef3f5aa2fe6838a95b216691468e2' )) per_commitment_point = secret_to_pubkey(per_commitment_secret) self.assertEqual( per_commitment_point, bfh('025f7117a78150fe2ef97db7cfc83bd57b2e2c0d0dd25eaf467a4a1c2a45ce1486' )) localpubkey = derive_pubkey(base_point, per_commitment_point) self.assertEqual( localpubkey, bfh('0235f2dbfaa89b57ec7b055afe29849ef7ddfeb1cefdb9ebdc43f5494984db29e5' )) localprivkey = derive_privkey(base_secret, per_commitment_point) self.assertEqual( localprivkey, 0xcbced912d3b21bf196a766651e436aff192362621ce317704ea2f75d87e7be0f) revocation_basepoint = secret_to_pubkey(revocation_basepoint_secret) self.assertEqual( revocation_basepoint, bfh('036d6caac248af96f6afa7f904f550253a0f3ef3f5aa2fe6838a95b216691468e2' )) revocationpubkey = derive_blinded_pubkey(revocation_basepoint, per_commitment_point) self.assertEqual( revocationpubkey, bfh('02916e326636d19c33f13e8c0c3a03dd157f332f3e99c317c141dd865eb01f8ff0' ))
def htlc_tx(self, htlc, htlc_output_index, amount_msat, htlc_payment_preimage, remote_htlc_sig, success, cltv_timeout, local_feerate_per_kw, our_commit_tx): _script, our_htlc_tx_output = make_htlc_tx_output( amount_msat=amount_msat, local_feerate=local_feerate_per_kw, revocationpubkey=local_revocation_pubkey, local_delayedpubkey=local_delayedpubkey, success=success, to_self_delay=local_delay) our_htlc_tx_inputs = make_htlc_tx_inputs( htlc_output_txid=our_commit_tx.txid(), htlc_output_index=htlc_output_index, amount_msat=amount_msat, witness_script=bh2u(htlc)) our_htlc_tx = make_htlc_tx( cltv_expiry=cltv_timeout, inputs=our_htlc_tx_inputs, output=our_htlc_tx_output) local_sig = our_htlc_tx.sign_txin(0, local_privkey[:-1]) our_htlc_tx_witness = make_htlc_tx_witness( remotehtlcsig=bfh(remote_htlc_sig) + b"\x01", # 0x01 is SIGHASH_ALL localhtlcsig=bfh(local_sig), payment_preimage=htlc_payment_preimage if success else b'', # will put 00 on witness if timeout witness_script=htlc) our_htlc_tx._inputs[0].witness = our_htlc_tx_witness return str(our_htlc_tx)
def test_encode_decode_msg__missing_optional_field_will_not_appear_in_decoded_dict(self): # "channel_update": optional field "htlc_maximum_msat" missing -> does not get put into dict self.assertEqual(bfh("010200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b2e06110329c448f1578e48a25a88b639dcfaaa6a6b297d0c6e03bbace06b1a200d43100006f00025e6ed0830100009000000000000000c8000001f400000023"), encode_msg( "channel_update", short_channel_id=ShortChannelID.from_components(54321, 111, 2), channel_flags=b'\x00', message_flags=b'\x01', cltv_expiry_delta=144, htlc_minimum_msat=200, fee_base_msat=500, fee_proportional_millionths=35, chain_hash=constants.net.rev_genesis_bytes(), timestamp=1584320643, )) self.assertEqual(('channel_update', {'chain_hash': b'CI\x7f\xd7\xf8&\x95q\x08\xf4\xa3\x0f\xd9\xce\xc3\xae\xbay\x97 \x84\xe9\x0e\xad\x01\xea3\t\x00\x00\x00\x00', 'channel_flags': b'\x00', 'cltv_expiry_delta': 144, 'fee_base_msat': 500, 'fee_proportional_millionths': 35, 'htlc_minimum_msat': 200, 'message_flags': b'\x01', 'short_channel_id': b'\x00\xd41\x00\x00o\x00\x02', 'signature': bytes(64), 'timestamp': 1584320643} ), decode_msg(bfh("01020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000043497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea33090000000000d43100006f00025e6ed0830100009000000000000000c8000001f400000023")))
def parse_output(self, x) -> bytes: try: address = self.parse_address(x) return bfh(bitcoin.address_to_script(address)) except: script = self.parse_script(x) return bfh(script)
def tx_inputs(self, tx, for_sig=False): inputs = [] for txin in tx.inputs(): txinputtype = self.types.TxInputType() if txin['type'] == 'coinbase': prev_hash = b"\x00"*32 prev_index = 0xffffffff # signed int -1 else: if for_sig: x_pubkeys = txin['x_pubkeys'] if len(x_pubkeys) == 1: x_pubkey = x_pubkeys[0] xpub, s = parse_xpubkey(x_pubkey) xpub_n = self.client_class.expand_path(self.xpub_path[xpub]) txinputtype._extend_address_n(xpub_n + s) txinputtype.script_type = self.get_safet_input_script_type(txin['type']) else: def f(x_pubkey): xpub, s = parse_xpubkey(x_pubkey) return self._make_node_path(xpub, s) pubkeys = list(map(f, x_pubkeys)) multisig = self.types.MultisigRedeemScriptType( pubkeys=pubkeys, signatures=list(map(lambda x: bfh(x)[:-1] if x else b'', txin.get('signatures'))), m=txin.get('num_sig'), ) script_type = self.get_safet_input_script_type(txin['type']) txinputtype = self.types.TxInputType( script_type=script_type, multisig=multisig ) # find which key is mine for x_pubkey in x_pubkeys: if is_xpubkey(x_pubkey): xpub, s = parse_xpubkey(x_pubkey) if xpub in self.xpub_path: xpub_n = self.client_class.expand_path(self.xpub_path[xpub]) txinputtype._extend_address_n(xpub_n + s) break prev_hash = unhexlify(txin['prevout_hash']) prev_index = txin['prevout_n'] if 'value' in txin: txinputtype.amount = txin['value'] txinputtype.prev_hash = prev_hash txinputtype.prev_index = prev_index if txin.get('scriptSig') is not None: script_sig = bfh(txin['scriptSig']) txinputtype.script_sig = script_sig txinputtype.sequence = txin.get('sequence', 0xffffffff - 1) inputs.append(txinputtype) return inputs
def test_verify_fail_f_tx_even(self): """Raise if inner node of merkle branch is valid tx. ('even' fake leaf position)""" # last 32 bytes of T encoded as hash fake_branch_node = hash_encode(bfh(VALID_64_BYTE_TX[64:])) fake_mbranch = [fake_branch_node] + MERKLE_BRANCH # first 32 bytes of T encoded as hash f_tx_hash = hash_encode(bfh(VALID_64_BYTE_TX[:64])) with self.assertRaises(InnerNodeOfSpvProofIsValidTx): SPV.hash_merkle_root(fake_mbranch, f_tx_hash, 6)
def parse_script(self, x): script = '' for word in x.split(): if word[0:3] == 'OP_': opcode_int = opcodes[word] script += construct_script([opcode_int]) else: bfh(word) # to test it is hex data script += construct_script([word]) return script
def parse_script(self, x): script = '' for word in x.split(): if word[0:3] == 'OP_': opcode_int = opcodes[word] assert opcode_int < 256 # opcode is single-byte script += bitcoin.int_to_hex(opcode_int) else: bfh(word) # to test it is hex data script += push_script(word) return script
def parse_output(self, x) -> bytes: try: address = self.parse_address(x) return bfh(bitcoin.address_to_script(address)) except Exception: pass try: script = self.parse_script(x) return bfh(script) except Exception: pass raise Exception("Invalid address or script.")
def test_read_tlv_stream_tests3(self): # from https://github.com/lightningnetwork/lightning-rfc/blob/452a0eb916fedf4c954137b4fd0b61b5002b34ad/01-messaging.md#tlv-stream-decoding-failure lnser = LNSerializer() with self.assertRaises(MsgInvalidFieldOrder): lnser.read_tlv_stream(fd=io.BytesIO(bfh("0208000000000000022601012a")), tlv_stream_name="n1") with self.assertRaises(MsgInvalidFieldOrder): lnser.read_tlv_stream(fd=io.BytesIO(bfh("0208000000000000023102080000000000000451")), tlv_stream_name="n1") with self.assertRaises(MsgInvalidFieldOrder): lnser.read_tlv_stream(fd=io.BytesIO(bfh("1f000f012a")), tlv_stream_name="n1") with self.assertRaises(MsgInvalidFieldOrder): lnser.read_tlv_stream(fd=io.BytesIO(bfh("1f001f012a")), tlv_stream_name="n1") with self.assertRaises(MsgInvalidFieldOrder): lnser.read_tlv_stream(fd=io.BytesIO(bfh("ffffffffffffffffff000000")), tlv_stream_name="n2")
def parse_script(self, x): from electrum_mona.transaction import opcodes, push_script script = '' for word in x.split(): if word[0:3] == 'OP_': assert word in opcodes.lookup opcode_int = opcodes.lookup[word] assert opcode_int < 256 # opcode is single-byte script += bitcoin.int_to_hex(opcode_int) else: bfh(word) # to test it is hex data script += push_script(word) return script
def test_decode_onion_error(self): # test vector from bolt-04 payment_path_pubkeys = [ bfh('02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619' ), bfh('0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c' ), bfh('027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007' ), bfh('032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991' ), bfh('02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145' ), ] session_key = bfh( '4141414141414141414141414141414141414141414141414141414141414141') error_packet_for_node_0 = bfh( '9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d' ) decoded_error, index_of_sender = _decode_onion_error( error_packet_for_node_0, payment_path_pubkeys, session_key) self.assertEqual( bfh('4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' ), decoded_error) self.assertEqual(4, index_of_sender) failure_msg, index_of_sender = decode_onion_error( error_packet_for_node_0, payment_path_pubkeys, session_key) self.assertEqual(4, index_of_sender) self.assertEqual(OnionFailureCode.TEMPORARY_NODE_FAILURE, failure_msg.code) self.assertEqual(b'', failure_msg.data)
def do_send(self, tx): def on_success(result): window.show_message( _("Your transaction was sent to the cosigning pool.") + '\n' + _("Open your cosigner wallet to retrieve it.")) def on_failure(exc_info): e = exc_info[1] try: self.logger.error("on_failure", exc_info=exc_info) except OSError: pass window.show_error( _("Failed to send transaction to cosigning pool") + ':\n' + repr(e)) for window, xpub, K, _hash in self.cosigner_list: if not self.cosigner_can_sign(tx, xpub): continue # construct message raw_tx_bytes = bfh(str(tx)) public_key = ecc.ECPubkey(K) message = public_key.encrypt_message(raw_tx_bytes).decode('ascii') # send message task = lambda: server.put(_hash, message) msg = _('Sending transaction to cosigning pool...') WaitingDialog(window, msg, task, on_success, on_failure)
def show_qr(self): text = bfh(str(self.tx)) text = base_encode(text, base=43) try: self.main_window.show_qrcode(text, 'Transaction', parent=self) except Exception as e: self.show_message(str(e))
def test_encode_decode_msg__ints_can_be_passed_as_bytes(self): self.assertEqual( bfh("010200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b2e06110329c448f1578e48a25a88b639dcfaaa6a6b297d0c6e03bbace06b1a200d43100006f00025e6ed0830100009000000000000000c8000001f400000023000000003b9aca00" ), encode_msg( "channel_update", short_channel_id=ShortChannelID.from_components(54321, 111, 2), channel_flags=b'\x00', message_flags=b'\x01', cltv_expiry_delta=int.to_bytes(144, length=2, byteorder="big", signed=False), htlc_minimum_msat=int.to_bytes(200, length=8, byteorder="big", signed=False), htlc_maximum_msat=int.to_bytes(1_000_000_000, length=8, byteorder="big", signed=False), fee_base_msat=int.to_bytes(500, length=4, byteorder="big", signed=False), fee_proportional_millionths=int.to_bytes(35, length=4, byteorder="big", signed=False), chain_hash=constants.net.rev_genesis_bytes(), timestamp=int.to_bytes(1584320643, length=4, byteorder="big", signed=False), ))
def get_noise_map( cls, versioned_seed: VersionedSeed) -> Dict[Tuple[int, int], int]: """Returns a map from (x,y) coordinate to pixel value 0/1, to be used as rawnoise.""" w, h = cls.SIZE version = versioned_seed.version hex_seed = versioned_seed.seed checksum = versioned_seed.checksum noise_map = {} if version == '0': random.seed(int(hex_seed, 16)) for x in range(w): for y in range(h): noise_map[(x, y)] = random.randint(0, 1) elif version == '1': prng_seed = bfh(hex_seed + version + checksum) drbg = DRBG(prng_seed) num_noise_bytes = 1929 # ~ w*h noise_array = bin( int.from_bytes(drbg.generate(num_noise_bytes), 'big'))[2:] # there's an approx 1/1024 chance that the generated number is 'too small' # and we would get IndexError below. easiest backwards compat fix: noise_array += '0' * (w * h - len(noise_array)) i = 0 for x in range(w): for y in range(h): noise_map[(x, y)] = int(noise_array[i]) i += 1 else: raise Exception(f"unexpected revealer version: {version}") return noise_map
def xfp_from_xpub(xpub): # sometime we need to BIP32 fingerprint value: 4 bytes of ripemd(sha256(pubkey)) # UNTESTED kk = bfh(Xpub.get_pubkey_from_xpub(xpub, [])) assert len(kk) == 33 xfp, = unpack('<I', hash_160(kk)[0:4]) return xfp
def show_address(self, wallet, address, keystore: 'Coldcard_KeyStore' = None): if keystore is None: keystore = wallet.get_keystore() if not self.show_address_helper(wallet, address, keystore): return txin_type = wallet.get_txin_type(address) # Standard_Wallet => not multisig, must be bip32 if type(wallet) is Standard_Wallet: sequence = wallet.get_address_index(address) keystore.show_address(sequence, txin_type) elif type(wallet) is Multisig_Wallet: assert isinstance(wallet, Multisig_Wallet) # only here for type-hints in IDE # More involved for P2SH/P2WSH addresses: need M, and all public keys, and their # derivation paths. Must construct script, and track fingerprints+paths for # all those keys pubkey_deriv_info = wallet.get_public_keys_with_deriv_info(address) pubkey_hexes = sorted([pk.hex() for pk in list(pubkey_deriv_info)]) xfp_paths = [] for pubkey in pubkey_deriv_info: ks, der_suffix = pubkey_deriv_info[pubkey] fp_bytes, der_full = ks.get_fp_and_derivation_to_be_used_in_partial_tx(der_suffix, only_der_suffix=False) xfp_int = xfp_int_from_xfp_bytes(fp_bytes) xfp_paths.append([xfp_int] + list(der_full)) script = bfh(wallet.pubkeys_to_scriptcode(pubkey_hexes)) keystore.show_p2sh_address(wallet.m, script, xfp_paths, txin_type) else: keystore.handler.show_error(_('This function is only available for standard wallets when using {}.').format(self.device)) return
def test_write_bigsize_int(self): self.assertEqual(bfh("00"), write_bigsize_int(0)) self.assertEqual(bfh("fc"), write_bigsize_int(252)) self.assertEqual(bfh("fd00fd"), write_bigsize_int(253)) self.assertEqual(bfh("fdffff"), write_bigsize_int(65535)) self.assertEqual(bfh("fe00010000"), write_bigsize_int(65536)) self.assertEqual(bfh("feffffffff"), write_bigsize_int(4294967295)) self.assertEqual(bfh("ff0000000100000000"), write_bigsize_int(4294967296)) self.assertEqual(bfh("ffffffffffffffffff"), write_bigsize_int(18446744073709551615))
def test_base58check(self): data_hex = '0cd394bef396200774544c58a5be0189f3ceb6a41c8da023b099ce547dd4d8071ed6ed647259fba8c26382edbf5165dfd2404e7a8885d88437db16947a116e451a5d1325e3fd075f9d370120d2ab537af69f32e74fc0ba53aaaa637752964b3ac95cfea7' data_bytes = bfh(data_hex) data_base58check = EncodeBase58Check(data_bytes) self.assertEqual( "4GCCJsjHqFbHxWbFBvRg35cSeNLHKeNqkXqFHW87zRmz6iP1dJU9Tk2KHZkoKj45jzVsSV4ZbQ8GpPwko6V3Z7cRfux3zJhUw7TZB6Kpa8Vdya8cMuUtL5Ry3CLtMetaY42u52X7Ey6MAH", data_base58check) self.assertEqual(data_bytes, DecodeBase58Check(data_base58check))
def f(x_pubkey): if is_xpubkey(x_pubkey): xpub, s = parse_xpubkey(x_pubkey) else: xpub = xpub_from_pubkey(0, bfh(x_pubkey)) s = [] node = self.ckd_public.deserialize(xpub) return self.types.HDNodePathType(node=node, address_n=s)
def test_base43(self): tx_hex = "020000000001021cd0e96f9ca202e017ca3465e3c13373c0df3a4cdd91c1fd02ea42a1a65d2a410000000000fdffffff757da7cf8322e5063785e2d8ada74702d2648fa2add2d533ba83c52eb110df690200000000fdffffff02d07e010000000000160014b544c86eaf95e3bb3b6d2cabb12ab40fc59cad9ca086010000000000232102ce0d066fbfcf150a5a1bbc4f312cd2eb080e8d8a47e5f2ce1a63b23215e54fb5ac02483045022100a9856bf10a950810abceeabc9a86e6ba533e130686e3d7863971b9377e7c658a0220288a69ef2b958a7c2ecfa376841d4a13817ed24fa9a0e0a6b9cb48e6439794c701210324e291735f83ff8de47301b12034950b80fa4724926a34d67e413d8ff8817c53024830450221008f885978f7af746679200ed55fe2e86c1303620824721f95cc41eb7965a3dfcf02207872082ac4a3c433d41a203e6d685a459e70e551904904711626ac899238c20a0121023d4c9deae1aacf3f822dd97a28deaec7d4e4ff97be746d124a63d20e582f5b290a971600" tx_bytes = bfh(tx_hex) tx_base43 = base_encode(tx_bytes, 43) self.assertEqual( "3E2DH7.J3PKVZJ3RCOXQVS3Y./6-WE.75DDU0K58-0N1FRL565N8ZH-DG1Z.1IGWTE5HK8F7PWH5P8+V3XGZZ6GQBPHNDE+RD8CAQVV1/6PQEMJIZTGPMIJ93B8P$QX+Y2R:TGT9QW8S89U4N2.+FUT8VG+34USI/N/JJ3CE*KLSW:REE8T5Y*9:U6515JIUR$6TODLYHSDE3B5DAF:5TF7V*VAL3G40WBOM0DO2+CFKTTM$G-SO:8U0EW:M8V:4*R9ZDX$B1IRBP9PLMDK8H801PNTFB4$HL1+/U3F61P$4N:UAO88:N5D+J:HI4YR8IM:3A7K1YZ9VMRC/47$6GGW5JEL1N690TDQ4XW+TWHD:V.1.630QK*JN/.EITVU80YS3.8LWKO:2STLWZAVHUXFHQ..NZ0:.J/FTZM.KYDXIE1VBY7/:PHZMQ$.JZQ2.XT32440X/HM+UY/7QP4I+HTD9.DUSY-8R6HDR-B8/PF2NP7I2-MRW9VPW3U9.S0LQ.*221F8KVMD5ANJXZJ8WV4UFZ4R.$-NXVE+-FAL:WFERGU+WHJTHAP", tx_base43) self.assertEqual(tx_bytes, base_decode(tx_base43, None, 43))
def test_base58(self): data_hex = '0cd394bef396200774544c58a5be0189f3ceb6a41c8da023b099ce547dd4d8071ed6ed647259fba8c26382edbf5165dfd2404e7a8885d88437db16947a116e451a5d1325e3fd075f9d370120d2ab537af69f32e74fc0ba53aaaa637752964b3ac95cfea7' data_bytes = bfh(data_hex) data_base58 = base_encode(data_bytes, 58) self.assertEqual( "VuvZ2K5UEcXCVcogny7NH4Evd9UfeYipsTdWuU4jLDhyaESijKtrGWZTFzVZJPjaoC9jFBs3SFtarhDhQhAxkXosUD8PmUb5UXW1tafcoPiCp8jHy7Fe2CUPXAbYuMvAyrkocbe6", data_base58) self.assertEqual(data_bytes, base_decode(data_base58, None, 58))
def sign_transaction(self, keystore, tx: PartialTransaction, prev_tx): prev_tx = { bfh(txhash): self.electrum_tx_to_txtype(tx) for txhash, tx in prev_tx.items() } client = self.get_client(keystore) inputs = self.tx_inputs(tx, for_sig=True, keystore=keystore) outputs = self.tx_outputs(tx, keystore=keystore) details = SignTx(lock_time=tx.locktime, version=tx.version) signatures, _ = client.sign_tx(self.get_coin_name(), inputs, outputs, details=details, prev_txes=prev_tx) signatures = [(bh2u(x) + '01') for x in signatures] tx.update_signatures(signatures)
def write_kv(ktype, val, key=b''): # serialize helper: write w/ size and key byte out_fd.write(my_var_int(1 + len(key))) out_fd.write(bytes([ktype]) + key) if isinstance(val, str): val = bfh(val) out_fd.write(my_var_int(len(val))) out_fd.write(val)
def generate_masternode_key(self): G = generator_secp256k1 _r = G.order() pvk = ecdsa.util.randrange(pow(2, 256)) % _r privateKey = secret = '%064x'%pvk prefix = bytes([constants.net.WIF_PREFIX]) suffix = b'' vchIn = prefix + bfh(secret) + suffix base58_wif = EncodeBase58Check(vchIn) return base58_wif
def show_qr(self): text = bfh(str(self.tx)) text = base_encode(text, base=43) try: self.main_window.show_qrcode(text, 'Transaction', parent=self) except qrcode.exceptions.DataOverflowError: self.show_error(_('Failed to display QR code.') + '\n' + _('Transaction is too large in size.')) except Exception as e: self.show_error(_('Failed to display QR code.') + '\n' + repr(e))
def test_decode_onion_error(self): orf = OnionRoutingFailure.from_bytes(bfh("400f0000000017d2d8b0001d9458")) self.assertEqual(('incorrect_or_unknown_payment_details', {'htlc_msat': 399694000, 'height': 1938520}), OnionWireSerializer.decode_msg(orf.to_bytes())) self.assertEqual({'htlc_msat': 399694000, 'height': 1938520}, orf.decode_data()) orf2 = OnionRoutingFailure(26399, bytes.fromhex("0000000017d2d8b0001d9458")) with self.assertRaises(UnknownMsgType): OnionWireSerializer.decode_msg(orf2.to_bytes()) self.assertEqual(None, orf2.decode_data())
def tx_inputs(self, tx, xpub_path, for_sig=False): inputs = [] for txin in tx.inputs(): txinputtype = TxInputType() if txin['type'] == 'coinbase': prev_hash = b"\x00" * 32 prev_index = 0xffffffff # signed int -1 else: if for_sig: x_pubkeys = txin['x_pubkeys'] xpubs = [parse_xpubkey(x) for x in x_pubkeys] multisig = self._make_multisig(txin.get('num_sig'), xpubs, txin.get('signatures')) script_type = self.get_trezor_input_script_type( txin['type']) txinputtype = TxInputType(script_type=script_type, multisig=multisig) # find which key is mine for xpub, deriv in xpubs: if xpub in xpub_path: xpub_n = parse_path(xpub_path[xpub]) txinputtype.address_n = xpub_n + deriv break prev_hash = bfh(txin['prevout_hash']) prev_index = txin['prevout_n'] if 'value' in txin: txinputtype.amount = txin['value'] txinputtype.prev_hash = prev_hash txinputtype.prev_index = prev_index if txin.get('scriptSig') is not None: script_sig = bfh(txin['scriptSig']) txinputtype.script_sig = script_sig txinputtype.sequence = txin.get('sequence', 0xffffffff - 1) inputs.append(txinputtype) return inputs