feature_cltv.py raw

   1  #!/usr/bin/env python3
   2  # Copyright (c) 2015-2022 The Limenka developers
   3  # Distributed under the MIT software license, see the accompanying
   4  # file COPYING or http://www.opensource.org/licenses/mit-license.php.
   5  """Test BIP65 (CHECKLOCKTIMEVERIFY).
   6  
   7  Test that the CHECKLOCKTIMEVERIFY soft-fork activates.
   8  """
   9  
  10  from test_framework.blocktools import (
  11      TIME_GENESIS_BLOCK,
  12      create_block,
  13      create_coinbase,
  14  )
  15  from test_framework.messages import (
  16      CTransaction,
  17      SEQUENCE_FINAL,
  18      msg_block,
  19  )
  20  from test_framework.p2p import P2PInterface
  21  from test_framework.script import (
  22      CScript,
  23      CScriptNum,
  24      OP_1NEGATE,
  25      OP_CHECKLOCKTIMEVERIFY,
  26      OP_DROP,
  27  )
  28  from test_framework.test_framework import LimenkaTestFramework
  29  from test_framework.util import assert_equal
  30  from test_framework.wallet import (
  31      MiniWallet,
  32      MiniWalletMode,
  33  )
  34  
  35  
  36  # Helper function to modify a transaction by
  37  # 1) prepending a given script to the scriptSig of vin 0 and
  38  # 2) (optionally) modify the nSequence of vin 0 and the tx's nLockTime
  39  def cltv_modify_tx(tx, prepend_scriptsig, nsequence=None, nlocktime=None):
  40      assert_equal(len(tx.vin), 1)
  41      if nsequence is not None:
  42          tx.vin[0].nSequence = nsequence
  43          tx.nLockTime = nlocktime
  44  
  45      tx.vin[0].scriptSig = CScript(prepend_scriptsig + list(CScript(tx.vin[0].scriptSig)))
  46      tx.rehash()
  47  
  48  
  49  def cltv_invalidate(tx, failure_reason):
  50      # Modify the signature in vin 0 and nSequence/nLockTime of the tx to fail CLTV
  51      #
  52      # According to BIP65, OP_CHECKLOCKTIMEVERIFY can fail due the following reasons:
  53      # 1) the stack is empty
  54      # 2) the top item on the stack is less than 0
  55      # 3) the lock-time type (height vs. timestamp) of the top stack item and the
  56      #    nLockTime field are not the same
  57      # 4) the top stack item is greater than the transaction's nLockTime field
  58      # 5) the nSequence field of the txin is 0xffffffff (SEQUENCE_FINAL)
  59      assert failure_reason in range(5)
  60      scheme = [
  61          # | Script to prepend to scriptSig                  | nSequence  | nLockTime    |
  62          # +-------------------------------------------------+------------+--------------+
  63          [[OP_CHECKLOCKTIMEVERIFY],                            None,       None],
  64          [[OP_1NEGATE, OP_CHECKLOCKTIMEVERIFY, OP_DROP],       None,       None],
  65          [[CScriptNum(100), OP_CHECKLOCKTIMEVERIFY, OP_DROP],  0,          TIME_GENESIS_BLOCK],
  66          [[CScriptNum(100), OP_CHECKLOCKTIMEVERIFY, OP_DROP],  0,          50],
  67          [[CScriptNum(50),  OP_CHECKLOCKTIMEVERIFY, OP_DROP],  SEQUENCE_FINAL, 50],
  68      ][failure_reason]
  69  
  70      cltv_modify_tx(tx, prepend_scriptsig=scheme[0], nsequence=scheme[1], nlocktime=scheme[2])
  71  
  72  
  73  def cltv_validate(tx, height):
  74      # Modify the signature in vin 0 and nSequence/nLockTime of the tx to pass CLTV
  75      scheme = [[CScriptNum(height), OP_CHECKLOCKTIMEVERIFY, OP_DROP], 0, height]
  76  
  77      cltv_modify_tx(tx, prepend_scriptsig=scheme[0], nsequence=scheme[1], nlocktime=scheme[2])
  78  
  79  
  80  CLTV_HEIGHT = 111
  81  
  82  
  83  class BIP65Test(LimenkaTestFramework):
  84      def set_test_params(self):
  85          self.num_nodes = 1
  86          # whitelist peers to speed up tx relay / mempool sync
  87          self.noban_tx_relay = True
  88          self.extra_args = [[
  89              f'-testactivationheight=cltv@{CLTV_HEIGHT}',
  90              '-acceptnonstdtxn=1',  # cltv_invalidate is nonstandard
  91          ]]
  92          self.setup_clean_chain = True
  93          self.rpc_timeout = 480
  94  
  95      def test_cltv_info(self, *, is_active):
  96          assert_equal(self.nodes[0].getdeploymentinfo()['deployments']['bip65'], {
  97                  "active": is_active,
  98                  "height": CLTV_HEIGHT,
  99                  "type": "buried",
 100              },
 101          )
 102  
 103      def run_test(self):
 104          peer = self.nodes[0].add_p2p_connection(P2PInterface())
 105          wallet = MiniWallet(self.nodes[0], mode=MiniWalletMode.RAW_OP_TRUE)
 106  
 107          self.test_cltv_info(is_active=False)
 108  
 109          self.log.info("Mining %d blocks", CLTV_HEIGHT - 2)
 110          self.generate(wallet, 10)
 111          self.generate(self.nodes[0], CLTV_HEIGHT - 2 - 10)
 112          assert_equal(self.nodes[0].getblockcount(), CLTV_HEIGHT - 2)
 113  
 114          self.log.info("Test that invalid-according-to-CLTV transactions can still appear in a block")
 115  
 116          # create one invalid tx per CLTV failure reason (5 in total) and collect them
 117          invalid_cltv_txs = []
 118          for i in range(5):
 119              spendtx = wallet.create_self_transfer()['tx']
 120              cltv_invalidate(spendtx, i)
 121              invalid_cltv_txs.append(spendtx)
 122  
 123          tip = self.nodes[0].getbestblockhash()
 124          block_time = self.nodes[0].getblockheader(tip)['mediantime'] + 1
 125          block = create_block(int(tip, 16), create_coinbase(CLTV_HEIGHT - 1), block_time, version=3, txlist=invalid_cltv_txs)
 126          block.solve()
 127  
 128          self.test_cltv_info(is_active=False)  # Not active as of current tip and next block does not need to obey rules
 129          peer.send_and_ping(msg_block(block))
 130          self.test_cltv_info(is_active=True)  # Not active as of current tip, but next block must obey rules
 131          assert_equal(self.nodes[0].getbestblockhash(), block.hash)
 132  
 133          self.log.info("Test that blocks must now be at least version 4")
 134          tip = block.sha256
 135          block_time += 1
 136          block = create_block(tip, create_coinbase(CLTV_HEIGHT), block_time, version=3)
 137          block.solve()
 138  
 139          with self.nodes[0].assert_debug_log(expected_msgs=[f'{block.hash}, bad-version(0x00000003)']):
 140              peer.send_and_ping(msg_block(block))
 141              assert_equal(int(self.nodes[0].getbestblockhash(), 16), tip)
 142              peer.sync_with_ping()
 143  
 144          self.log.info("Test that invalid-according-to-CLTV transactions cannot appear in a block")
 145          block.nVersion = 4
 146          block.vtx.append(CTransaction()) # dummy tx after coinbase that will be replaced later
 147  
 148          # create and test one invalid tx per CLTV failure reason (5 in total)
 149          for i in range(5):
 150              spendtx = wallet.create_self_transfer()['tx']
 151              assert_equal(len(spendtx.vin), 1)
 152              coin = spendtx.vin[0]
 153              coin_txid = format(coin.prevout.hash, '064x')
 154              coin_vout = coin.prevout.n
 155              cltv_invalidate(spendtx, i)
 156  
 157              blk_rej = "mandatory-script-verify-flag-failed"
 158              tx_rej = "mempool-script-verify-flag-failed"
 159              expected_cltv_reject_reason = [
 160                  " (Operation not valid with the current stack size)",
 161                  " (Negative locktime)",
 162                  " (Locktime requirement not satisfied)",
 163                  " (Locktime requirement not satisfied)",
 164                  " (Locktime requirement not satisfied)",
 165              ][i]
 166              # First we show that this tx is valid except for CLTV by getting it
 167              # rejected from the mempool for exactly that reason.
 168              spendtx_txid = spendtx.hash
 169              spendtx_wtxid = spendtx.getwtxid()
 170              expected = {
 171                  'txid': spendtx_txid,
 172                  'wtxid': spendtx_wtxid,
 173                  'allowed': False,
 174                  'reject-reason': tx_rej + expected_cltv_reject_reason,
 175                  'reject-details': tx_rej + expected_cltv_reject_reason + f", input 0 of {spendtx_txid} (wtxid {spendtx_wtxid}), spending {coin_txid}:{coin_vout}",
 176              }
 177              result = self.nodes[0].testmempoolaccept(rawtxs=[spendtx.serialize().hex()], maxfeerate=0)[0]
 178              # skip for now
 179              result.pop('usage')
 180              assert_equal(result, expected)
 181  
 182              # Now we verify that a block with this transaction is also invalid.
 183              block.vtx[1] = spendtx
 184              block.hashMerkleRoot = block.calc_merkle_root()
 185              block.solve()
 186  
 187              with self.nodes[0].assert_debug_log(expected_msgs=[f'Block validation error: {blk_rej + expected_cltv_reject_reason}']):
 188                  peer.send_and_ping(msg_block(block))
 189                  assert_equal(int(self.nodes[0].getbestblockhash(), 16), tip)
 190                  peer.sync_with_ping()
 191  
 192          self.log.info("Test that a version 4 block with a valid-according-to-CLTV transaction is accepted")
 193          cltv_validate(spendtx, CLTV_HEIGHT - 1)
 194  
 195          block.vtx.pop(1)
 196          block.vtx.append(spendtx)
 197          block.hashMerkleRoot = block.calc_merkle_root()
 198          block.solve()
 199  
 200          self.test_cltv_info(is_active=True)  # Not active as of current tip, but next block must obey rules
 201          peer.send_and_ping(msg_block(block))
 202          self.test_cltv_info(is_active=True)  # Active as of current tip
 203          assert_equal(int(self.nodes[0].getbestblockhash(), 16), block.sha256)
 204  
 205  
 206  if __name__ == '__main__':
 207      BIP65Test(__file__).main()
 208