PageRenderTime 61ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/test/functional/test_framework/wallet.py

http://github.com/bitcoin/bitcoin
Python | 400 lines | 361 code | 10 blank | 29 comment | 7 complexity | 3da3a33eb95b9817f7f1f753b1391253 MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause, MIT
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2020-2021 The Bitcoin Core developers
  3. # Distributed under the MIT software license, see the accompanying
  4. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. """A limited-functionality wallet, which may replace a real wallet in tests"""
  6. from copy import deepcopy
  7. from decimal import Decimal
  8. from enum import Enum
  9. from random import choice
  10. from typing import (
  11. Any,
  12. List,
  13. Optional,
  14. )
  15. from test_framework.address import (
  16. base58_to_byte,
  17. create_deterministic_address_bcrt1_p2tr_op_true,
  18. key_to_p2pkh,
  19. key_to_p2sh_p2wpkh,
  20. key_to_p2wpkh,
  21. )
  22. from test_framework.descriptors import descsum_create
  23. from test_framework.key import ECKey
  24. from test_framework.messages import (
  25. COIN,
  26. COutPoint,
  27. CTransaction,
  28. CTxIn,
  29. CTxInWitness,
  30. CTxOut,
  31. tx_from_hex,
  32. )
  33. from test_framework.script import (
  34. CScript,
  35. LegacySignatureHash,
  36. LEAF_VERSION_TAPSCRIPT,
  37. OP_NOP,
  38. OP_TRUE,
  39. SIGHASH_ALL,
  40. )
  41. from test_framework.script_util import (
  42. key_to_p2pk_script,
  43. key_to_p2pkh_script,
  44. key_to_p2sh_p2wpkh_script,
  45. key_to_p2wpkh_script,
  46. keyhash_to_p2pkh_script,
  47. scripthash_to_p2sh_script,
  48. )
  49. from test_framework.util import (
  50. assert_equal,
  51. assert_greater_than_or_equal,
  52. )
  53. DEFAULT_FEE = Decimal("0.0001")
  54. class MiniWalletMode(Enum):
  55. """Determines the transaction type the MiniWallet is creating and spending.
  56. For most purposes, the default mode ADDRESS_OP_TRUE should be sufficient;
  57. it simply uses a fixed bech32m P2TR address whose coins are spent with a
  58. witness stack of OP_TRUE, i.e. following an anyone-can-spend policy.
  59. However, if the transactions need to be modified by the user (e.g. prepending
  60. scriptSig for testing opcodes that are activated by a soft-fork), or the txs
  61. should contain an actual signature, the raw modes RAW_OP_TRUE and RAW_P2PK
  62. can be useful. Summary of modes:
  63. | output | | tx is | can modify | needs
  64. mode | description | address | standard | scriptSig | signing
  65. ----------------+-------------------+-----------+----------+------------+----------
  66. ADDRESS_OP_TRUE | anyone-can-spend | bech32m | yes | no | no
  67. RAW_OP_TRUE | anyone-can-spend | - (raw) | no | yes | no
  68. RAW_P2PK | pay-to-public-key | - (raw) | yes | yes | yes
  69. """
  70. ADDRESS_OP_TRUE = 1
  71. RAW_OP_TRUE = 2
  72. RAW_P2PK = 3
  73. class MiniWallet:
  74. def __init__(self, test_node, *, mode=MiniWalletMode.ADDRESS_OP_TRUE):
  75. self._test_node = test_node
  76. self._utxos = []
  77. self._priv_key = None
  78. self._address = None
  79. assert isinstance(mode, MiniWalletMode)
  80. if mode == MiniWalletMode.RAW_OP_TRUE:
  81. self._scriptPubKey = bytes(CScript([OP_TRUE]))
  82. elif mode == MiniWalletMode.RAW_P2PK:
  83. # use simple deterministic private key (k=1)
  84. self._priv_key = ECKey()
  85. self._priv_key.set((1).to_bytes(32, 'big'), True)
  86. pub_key = self._priv_key.get_pubkey()
  87. self._scriptPubKey = key_to_p2pk_script(pub_key.get_bytes())
  88. elif mode == MiniWalletMode.ADDRESS_OP_TRUE:
  89. self._address, self._internal_key = create_deterministic_address_bcrt1_p2tr_op_true()
  90. self._scriptPubKey = bytes.fromhex(self._test_node.validateaddress(self._address)['scriptPubKey'])
  91. def get_balance(self):
  92. return sum(u['value'] for u in self._utxos)
  93. def rescan_utxos(self):
  94. """Drop all utxos and rescan the utxo set"""
  95. self._utxos = []
  96. res = self._test_node.scantxoutset(action="start", scanobjects=[self.get_descriptor()])
  97. assert_equal(True, res['success'])
  98. for utxo in res['unspents']:
  99. self._utxos.append({'txid': utxo['txid'], 'vout': utxo['vout'], 'value': utxo['amount'], 'height': utxo['height']})
  100. def scan_tx(self, tx):
  101. """Scan the tx for self._scriptPubKey outputs and add them to self._utxos"""
  102. for out in tx['vout']:
  103. if out['scriptPubKey']['hex'] == self._scriptPubKey.hex():
  104. self._utxos.append({'txid': tx['txid'], 'vout': out['n'], 'value': out['value'], 'height': 0})
  105. def sign_tx(self, tx, fixed_length=True):
  106. """Sign tx that has been created by MiniWallet in P2PK mode"""
  107. assert self._priv_key is not None
  108. (sighash, err) = LegacySignatureHash(CScript(self._scriptPubKey), tx, 0, SIGHASH_ALL)
  109. assert err is None
  110. # for exact fee calculation, create only signatures with fixed size by default (>49.89% probability):
  111. # 65 bytes: high-R val (33 bytes) + low-S val (32 bytes)
  112. # with the DER header/skeleton data of 6 bytes added, this leads to a target size of 71 bytes
  113. der_sig = b''
  114. while not len(der_sig) == 71:
  115. der_sig = self._priv_key.sign_ecdsa(sighash)
  116. if not fixed_length:
  117. break
  118. tx.vin[0].scriptSig = CScript([der_sig + bytes(bytearray([SIGHASH_ALL]))])
  119. tx.rehash()
  120. def generate(self, num_blocks, **kwargs):
  121. """Generate blocks with coinbase outputs to the internal address, and append the outputs to the internal list"""
  122. blocks = self._test_node.generatetodescriptor(num_blocks, self.get_descriptor(), **kwargs)
  123. for b in blocks:
  124. block_info = self._test_node.getblock(blockhash=b, verbosity=2)
  125. cb_tx = block_info['tx'][0]
  126. self._utxos.append({'txid': cb_tx['txid'], 'vout': 0, 'value': cb_tx['vout'][0]['value'], 'height': block_info['height']})
  127. return blocks
  128. def get_scriptPubKey(self):
  129. return self._scriptPubKey
  130. def get_descriptor(self):
  131. return descsum_create(f'raw({self._scriptPubKey.hex()})')
  132. def get_address(self):
  133. return self._address
  134. def get_utxo(self, *, txid: str = '', vout: Optional[int] = None, mark_as_spent=True) -> dict:
  135. """
  136. Returns a utxo and marks it as spent (pops it from the internal list)
  137. Args:
  138. txid: get the first utxo we find from a specific transaction
  139. """
  140. self._utxos = sorted(self._utxos, key=lambda k: (k['value'], -k['height'])) # Put the largest utxo last
  141. if txid:
  142. utxo_filter: Any = filter(lambda utxo: txid == utxo['txid'], self._utxos)
  143. else:
  144. utxo_filter = reversed(self._utxos) # By default the largest utxo
  145. if vout is not None:
  146. utxo_filter = filter(lambda utxo: vout == utxo['vout'], utxo_filter)
  147. index = self._utxos.index(next(utxo_filter))
  148. if mark_as_spent:
  149. return self._utxos.pop(index)
  150. else:
  151. return self._utxos[index]
  152. def get_utxos(self, *, mark_as_spent=True):
  153. """Returns the list of all utxos and optionally mark them as spent"""
  154. utxos = deepcopy(self._utxos)
  155. if mark_as_spent:
  156. self._utxos = []
  157. return utxos
  158. def send_self_transfer(self, **kwargs):
  159. """Create and send a tx with the specified fee_rate. Fee may be exact or at most one satoshi higher than needed."""
  160. tx = self.create_self_transfer(**kwargs)
  161. self.sendrawtransaction(from_node=kwargs['from_node'], tx_hex=tx['hex'])
  162. return tx
  163. def send_to(self, *, from_node, scriptPubKey, amount, fee=1000):
  164. """
  165. Create and send a tx with an output to a given scriptPubKey/amount,
  166. plus a change output to our internal address. To keep things simple, a
  167. fixed fee given in Satoshi is used.
  168. Note that this method fails if there is no single internal utxo
  169. available that can cover the cost for the amount and the fixed fee
  170. (the utxo with the largest value is taken).
  171. Returns a tuple (txid, n) referring to the created external utxo outpoint.
  172. """
  173. tx = self.create_self_transfer(from_node=from_node, fee_rate=0, mempool_valid=False)['tx']
  174. assert_greater_than_or_equal(tx.vout[0].nValue, amount + fee)
  175. tx.vout[0].nValue -= (amount + fee) # change output -> MiniWallet
  176. tx.vout.append(CTxOut(amount, scriptPubKey)) # arbitrary output -> to be returned
  177. txid = self.sendrawtransaction(from_node=from_node, tx_hex=tx.serialize().hex())
  178. return txid, 1
  179. def send_self_transfer_multi(self, **kwargs):
  180. """
  181. Create and send a transaction that spends the given UTXOs and creates a
  182. certain number of outputs with equal amounts.
  183. Returns a dictionary with
  184. - txid
  185. - serialized transaction in hex format
  186. - transaction as CTransaction instance
  187. - list of newly created UTXOs, ordered by vout index
  188. """
  189. tx = self.create_self_transfer_multi(**kwargs)
  190. txid = self.sendrawtransaction(from_node=kwargs['from_node'], tx_hex=tx.serialize().hex())
  191. return {'new_utxos': [self.get_utxo(txid=txid, vout=vout) for vout in range(len(tx.vout))],
  192. 'txid': txid, 'hex': tx.serialize().hex(), 'tx': tx}
  193. def create_self_transfer_multi(
  194. self, *, from_node,
  195. utxos_to_spend: Optional[List[dict]] = None,
  196. num_outputs=1,
  197. sequence=0,
  198. fee_per_output=1000):
  199. """
  200. Create and return a transaction that spends the given UTXOs and creates a
  201. certain number of outputs with equal amounts.
  202. """
  203. utxos_to_spend = utxos_to_spend or [self.get_utxo()]
  204. # create simple tx template (1 input, 1 output)
  205. tx = self.create_self_transfer(
  206. fee_rate=0, from_node=from_node,
  207. utxo_to_spend=utxos_to_spend[0], sequence=sequence, mempool_valid=False)['tx']
  208. # duplicate inputs, witnesses and outputs
  209. tx.vin = [deepcopy(tx.vin[0]) for _ in range(len(utxos_to_spend))]
  210. tx.wit.vtxinwit = [deepcopy(tx.wit.vtxinwit[0]) for _ in range(len(utxos_to_spend))]
  211. tx.vout = [deepcopy(tx.vout[0]) for _ in range(num_outputs)]
  212. # adapt input prevouts
  213. for i, utxo in enumerate(utxos_to_spend):
  214. tx.vin[i] = CTxIn(COutPoint(int(utxo['txid'], 16), utxo['vout']))
  215. # adapt output amounts (use fixed fee per output)
  216. inputs_value_total = sum([int(COIN * utxo['value']) for utxo in utxos_to_spend])
  217. outputs_value_total = inputs_value_total - fee_per_output * num_outputs
  218. for o in tx.vout:
  219. o.nValue = outputs_value_total // num_outputs
  220. return tx
  221. def create_self_transfer(self, *, fee_rate=Decimal("0.003"), from_node=None, utxo_to_spend=None, mempool_valid=True, locktime=0, sequence=0):
  222. """Create and return a tx with the specified fee_rate. Fee may be exact or at most one satoshi higher than needed.
  223. Checking mempool validity via the testmempoolaccept RPC can be skipped by setting mempool_valid to False."""
  224. from_node = from_node or self._test_node
  225. utxo_to_spend = utxo_to_spend or self.get_utxo()
  226. if self._priv_key is None:
  227. vsize = Decimal(104) # anyone-can-spend
  228. else:
  229. vsize = Decimal(168) # P2PK (73 bytes scriptSig + 35 bytes scriptPubKey + 60 bytes other)
  230. send_value = int(COIN * (utxo_to_spend['value'] - fee_rate * (vsize / 1000)))
  231. assert send_value > 0
  232. tx = CTransaction()
  233. tx.vin = [CTxIn(COutPoint(int(utxo_to_spend['txid'], 16), utxo_to_spend['vout']), nSequence=sequence)]
  234. tx.vout = [CTxOut(send_value, self._scriptPubKey)]
  235. tx.nLockTime = locktime
  236. if not self._address:
  237. # raw script
  238. if self._priv_key is not None:
  239. # P2PK, need to sign
  240. self.sign_tx(tx)
  241. else:
  242. # anyone-can-spend
  243. tx.vin[0].scriptSig = CScript([OP_NOP] * 43) # pad to identical size
  244. else:
  245. tx.wit.vtxinwit = [CTxInWitness()]
  246. tx.wit.vtxinwit[0].scriptWitness.stack = [CScript([OP_TRUE]), bytes([LEAF_VERSION_TAPSCRIPT]) + self._internal_key]
  247. tx_hex = tx.serialize().hex()
  248. if mempool_valid:
  249. tx_info = from_node.testmempoolaccept([tx_hex])[0]
  250. assert_equal(tx_info['allowed'], True)
  251. assert_equal(tx_info['vsize'], vsize)
  252. assert_equal(tx_info['fees']['base'], utxo_to_spend['value'] - Decimal(send_value) / COIN)
  253. return {'txid': tx.rehash(), 'wtxid': tx.getwtxid(), 'hex': tx_hex, 'tx': tx}
  254. def sendrawtransaction(self, *, from_node, tx_hex, maxfeerate=0, **kwargs):
  255. txid = from_node.sendrawtransaction(hexstring=tx_hex, maxfeerate=maxfeerate, **kwargs)
  256. self.scan_tx(from_node.decoderawtransaction(tx_hex))
  257. return txid
  258. def getnewdestination(address_type='bech32'):
  259. """Generate a random destination of the specified type and return the
  260. corresponding public key, scriptPubKey and address. Supported types are
  261. 'legacy', 'p2sh-segwit' and 'bech32'. Can be used when a random
  262. destination is needed, but no compiled wallet is available (e.g. as
  263. replacement to the getnewaddress/getaddressinfo RPCs)."""
  264. key = ECKey()
  265. key.generate()
  266. pubkey = key.get_pubkey().get_bytes()
  267. if address_type == 'legacy':
  268. scriptpubkey = key_to_p2pkh_script(pubkey)
  269. address = key_to_p2pkh(pubkey)
  270. elif address_type == 'p2sh-segwit':
  271. scriptpubkey = key_to_p2sh_p2wpkh_script(pubkey)
  272. address = key_to_p2sh_p2wpkh(pubkey)
  273. elif address_type == 'bech32':
  274. scriptpubkey = key_to_p2wpkh_script(pubkey)
  275. address = key_to_p2wpkh(pubkey)
  276. # TODO: also support bech32m (need to generate x-only-pubkey)
  277. else:
  278. assert False
  279. return pubkey, scriptpubkey, address
  280. def address_to_scriptpubkey(address):
  281. """Converts a given address to the corresponding output script (scriptPubKey)."""
  282. payload, version = base58_to_byte(address)
  283. if version == 111: # testnet pubkey hash
  284. return keyhash_to_p2pkh_script(payload)
  285. elif version == 196: # testnet script hash
  286. return scripthash_to_p2sh_script(payload)
  287. # TODO: also support other address formats
  288. else:
  289. assert False
  290. def make_chain(node, address, privkeys, parent_txid, parent_value, n=0, parent_locking_script=None, fee=DEFAULT_FEE):
  291. """Build a transaction that spends parent_txid.vout[n] and produces one output with
  292. amount = parent_value with a fee deducted.
  293. Return tuple (CTransaction object, raw hex, nValue, scriptPubKey of the output created).
  294. """
  295. inputs = [{"txid": parent_txid, "vout": n}]
  296. my_value = parent_value - fee
  297. outputs = {address : my_value}
  298. rawtx = node.createrawtransaction(inputs, outputs)
  299. prevtxs = [{
  300. "txid": parent_txid,
  301. "vout": n,
  302. "scriptPubKey": parent_locking_script,
  303. "amount": parent_value,
  304. }] if parent_locking_script else None
  305. signedtx = node.signrawtransactionwithkey(hexstring=rawtx, privkeys=privkeys, prevtxs=prevtxs)
  306. assert signedtx["complete"]
  307. tx = tx_from_hex(signedtx["hex"])
  308. return (tx, signedtx["hex"], my_value, tx.vout[0].scriptPubKey.hex())
  309. def create_child_with_parents(node, address, privkeys, parents_tx, values, locking_scripts, fee=DEFAULT_FEE):
  310. """Creates a transaction that spends the first output of each parent in parents_tx."""
  311. num_parents = len(parents_tx)
  312. total_value = sum(values)
  313. inputs = [{"txid": tx.rehash(), "vout": 0} for tx in parents_tx]
  314. outputs = {address : total_value - fee}
  315. rawtx_child = node.createrawtransaction(inputs, outputs)
  316. prevtxs = []
  317. for i in range(num_parents):
  318. prevtxs.append({"txid": parents_tx[i].rehash(), "vout": 0, "scriptPubKey": locking_scripts[i], "amount": values[i]})
  319. signedtx_child = node.signrawtransactionwithkey(hexstring=rawtx_child, privkeys=privkeys, prevtxs=prevtxs)
  320. assert signedtx_child["complete"]
  321. return signedtx_child["hex"]
  322. def create_raw_chain(node, first_coin, address, privkeys, chain_length=25):
  323. """Helper function: create a "chain" of chain_length transactions. The nth transaction in the
  324. chain is a child of the n-1th transaction and parent of the n+1th transaction.
  325. """
  326. parent_locking_script = None
  327. txid = first_coin["txid"]
  328. chain_hex = []
  329. chain_txns = []
  330. value = first_coin["amount"]
  331. for _ in range(chain_length):
  332. (tx, txhex, value, parent_locking_script) = make_chain(node, address, privkeys, txid, value, 0, parent_locking_script)
  333. txid = tx.rehash()
  334. chain_hex.append(txhex)
  335. chain_txns.append(tx)
  336. return (chain_hex, chain_txns)
  337. def bulk_transaction(tx, node, target_weight, privkeys, prevtxs=None):
  338. """Pad a transaction with extra outputs until it reaches a target weight (or higher).
  339. returns CTransaction object
  340. """
  341. tx_heavy = deepcopy(tx)
  342. assert_greater_than_or_equal(target_weight, tx_heavy.get_weight())
  343. while tx_heavy.get_weight() < target_weight:
  344. random_spk = "6a4d0200" # OP_RETURN OP_PUSH2 512 bytes
  345. for _ in range(512*2):
  346. random_spk += choice("0123456789ABCDEF")
  347. tx_heavy.vout.append(CTxOut(0, bytes.fromhex(random_spk)))
  348. # Re-sign the transaction
  349. if privkeys:
  350. signed = node.signrawtransactionwithkey(tx_heavy.serialize().hex(), privkeys, prevtxs)
  351. return tx_from_hex(signed["hex"])
  352. # OP_TRUE
  353. tx_heavy.wit.vtxinwit = [CTxInWitness()]
  354. tx_heavy.wit.vtxinwit[0].scriptWitness.stack = [CScript([OP_TRUE])]
  355. return tx_heavy