本文整理汇总了Python中test_framework.key.CECKey.get_pubkey方法的典型用法代码示例。如果您正苦于以下问题:Python CECKey.get_pubkey方法的具体用法?Python CECKey.get_pubkey怎么用?Python CECKey.get_pubkey使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类test_framework.key.CECKey
的用法示例。
在下文中一共展示了CECKey.get_pubkey方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: FullBlockTest
# 需要导入模块: from test_framework.key import CECKey [as 别名]
# 或者: from test_framework.key.CECKey import get_pubkey [as 别名]
class FullBlockTest(ComparisonTestFramework):
# Can either run this test as 1 node with expected answers, or two and compare them.
# Change the "outcome" variable from each TestInstance object to only do
# the comparison.
def __init__(self):
super().__init__()
self.num_nodes = 1
self.block_heights = {}
self.coinbase_key = CECKey()
self.coinbase_key.set_secretbytes(b"fatstacks")
self.coinbase_pubkey = self.coinbase_key.get_pubkey()
self.tip = None
self.blocks = {}
self.excessive_block_size = 16 * ONE_MEGABYTE
self.extra_args = [['-norelaypriority',
'-whitelist=127.0.0.1',
'-limitancestorcount=9999',
'-limitancestorsize=9999',
'-limitdescendantcount=9999',
'-limitdescendantsize=9999',
'-maxmempool=999',
"-excessiveblocksize=%d"
% self.excessive_block_size]]
def add_options(self, parser):
super().add_options(parser)
parser.add_option(
"--runbarelyexpensive", dest="runbarelyexpensive", default=True)
def run_test(self):
self.test = TestManager(self, self.options.tmpdir)
self.test.add_all_connections(self.nodes)
# Start up network handling in another thread
NetworkThread().start()
# Set the blocksize to 2MB as initial condition
self.nodes[0].setexcessiveblock(self.excessive_block_size)
self.test.run()
def add_transactions_to_block(self, block, tx_list):
[tx.rehash() for tx in tx_list]
block.vtx.extend(tx_list)
# this is a little handier to use than the version in blocktools.py
def create_tx(self, spend_tx, n, value, script=CScript([OP_TRUE])):
tx = create_transaction(spend_tx, n, b"", value, script)
return tx
# sign a transaction, using the key we know about
# this signs input 0 in tx, which is assumed to be spending output n in
# spend_tx
def sign_tx(self, tx, spend_tx, n):
scriptPubKey = bytearray(spend_tx.vout[n].scriptPubKey)
if (scriptPubKey[0] == OP_TRUE): # an anyone-can-spend
tx.vin[0].scriptSig = CScript()
return
sighash = SignatureHashForkId(
spend_tx.vout[n].scriptPubKey, tx, 0, SIGHASH_ALL | SIGHASH_FORKID, spend_tx.vout[n].nValue)
tx.vin[0].scriptSig = CScript(
[self.coinbase_key.sign(sighash) + bytes(bytearray([SIGHASH_ALL | SIGHASH_FORKID]))])
def create_and_sign_transaction(self, spend_tx, n, value, script=CScript([OP_TRUE])):
tx = self.create_tx(spend_tx, n, value, script)
self.sign_tx(tx, spend_tx, n)
tx.rehash()
return tx
def next_block(self, number, spend=None, additional_coinbase_value=0, script=None, extra_sigops=0, block_size=0, solve=True):
"""
Create a block on top of self.tip, and advance self.tip to point to the new block
if spend is specified, then 1 satoshi will be spent from that to an anyone-can-spend
output, and rest will go to fees.
"""
if self.tip == None:
base_block_hash = self.genesis_hash
block_time = int(time.time()) + 1
else:
base_block_hash = self.tip.sha256
block_time = self.tip.nTime + 1
# First create the coinbase
height = self.block_heights[base_block_hash] + 1
coinbase = create_coinbase(height, self.coinbase_pubkey)
coinbase.vout[0].nValue += additional_coinbase_value
if (spend != None):
coinbase.vout[0].nValue += spend.tx.vout[
spend.n].nValue - 1 # all but one satoshi to fees
coinbase.rehash()
block = create_block(base_block_hash, coinbase, block_time)
spendable_output = None
if (spend != None):
tx = CTransaction()
# no signature yet
tx.vin.append(
CTxIn(COutPoint(spend.tx.sha256, spend.n), b"", 0xffffffff))
# We put some random data into the first transaction of the chain
# to randomize ids
tx.vout.append(
CTxOut(0, CScript([random.randint(0, 255), OP_DROP, OP_TRUE])))
if script == None:
#.........这里部分代码省略.........
示例2: FullBlockTest
# 需要导入模块: from test_framework.key import CECKey [as 别名]
# 或者: from test_framework.key.CECKey import get_pubkey [as 别名]
class FullBlockTest(ComparisonTestFramework):
''' Can either run this test as 1 node with expected answers, or two and compare them.
Change the "outcome" variable from each TestInstance object to only do the comparison. '''
def __init__(self):
self.num_nodes = 1
self.block_heights = {}
self.coinbase_key = CECKey()
self.coinbase_key.set_secretbytes(b"horsebattery")
self.coinbase_pubkey = self.coinbase_key.get_pubkey()
self.block_time = int(time.time())+1
self.tip = None
self.blocks = {}
def run_test(self):
test = TestManager(self, self.options.tmpdir)
test.add_all_connections(self.nodes)
NetworkThread().start() # Start up network handling in another thread
test.run()
def add_transactions_to_block(self, block, tx_list):
[ tx.rehash() for tx in tx_list ]
block.vtx.extend(tx_list)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
return block
# Create a block on top of self.tip, and advance self.tip to point to the new block
# if spend is specified, then 1 satoshi will be spent from that to an anyone-can-spend output,
# and rest will go to fees.
def next_block(self, number, spend=None, additional_coinbase_value=0, script=None):
if self.tip == None:
base_block_hash = self.genesis_hash
else:
base_block_hash = self.tip.sha256
# First create the coinbase
height = self.block_heights[base_block_hash] + 1
coinbase = create_coinbase(height, self.coinbase_pubkey)
coinbase.vout[0].nValue += additional_coinbase_value
if (spend != None):
coinbase.vout[0].nValue += spend.tx.vout[spend.n].nValue - 1 # all but one satoshi to fees
coinbase.rehash()
block = create_block(base_block_hash, coinbase, self.block_time)
if (spend != None):
tx = CTransaction()
tx.vin.append(CTxIn(COutPoint(spend.tx.sha256, spend.n), b"", 0xffffffff)) # no signature yet
# This copies the java comparison tool testing behavior: the first
# txout has a garbage scriptPubKey, "to make sure we're not
# pre-verifying too much" (?)
tx.vout.append(CTxOut(0, CScript([random.randint(0,255), height & 255])))
if script == None:
tx.vout.append(CTxOut(1, CScript([OP_TRUE])))
else:
tx.vout.append(CTxOut(1, script))
# Now sign it if necessary
scriptSig = b""
scriptPubKey = bytearray(spend.tx.vout[spend.n].scriptPubKey)
if (scriptPubKey[0] == OP_TRUE): # looks like an anyone-can-spend
scriptSig = CScript([OP_TRUE])
else:
# We have to actually sign it
(sighash, err) = SignatureHash(spend.tx.vout[spend.n].scriptPubKey, tx, 0, SIGHASH_ALL)
scriptSig = CScript([self.coinbase_key.sign(sighash) + bytes(bytearray([SIGHASH_ALL]))])
tx.vin[0].scriptSig = scriptSig
# Now add the transaction to the block
block = self.add_transactions_to_block(block, [tx])
block.solve()
self.tip = block
self.block_heights[block.sha256] = height
self.block_time += 1
assert number not in self.blocks
self.blocks[number] = block
return block
def get_tests(self):
self.genesis_hash = int(self.nodes[0].getbestblockhash(), 16)
self.block_heights[self.genesis_hash] = 0
spendable_outputs = []
# save the current tip so it can be spent by a later block
def save_spendable_output():
spendable_outputs.append(self.tip)
# get an output that we previous marked as spendable
def get_spendable_output():
return PreviousSpendableOutput(spendable_outputs.pop(0).vtx[0], 0)
# returns a test case that asserts that the current tip was accepted
def accepted():
return TestInstance([[self.tip, True]])
# returns a test case that asserts that the current tip was rejected
def rejected(reject = None):
if reject is None:
return TestInstance([[self.tip, False]])
else:
return TestInstance([[self.tip, reject]])
# move the tip back to a previous block
def tip(number):
#.........这里部分代码省略.........
示例3: run_test
# 需要导入模块: from test_framework.key import CECKey [as 别名]
# 或者: from test_framework.key.CECKey import get_pubkey [as 别名]
def run_test(self):
p2p0 = self.nodes[0].add_p2p_connection(BaseNode())
# Build the blockchain
self.tip = int(self.nodes[0].getbestblockhash(), 16)
self.block_time = self.nodes[0].getblock(self.nodes[0].getbestblockhash())['time'] + 1
self.blocks = []
# Get a pubkey for the coinbase TXO
coinbase_key = CECKey()
coinbase_key.set_secretbytes(b"horsebattery")
coinbase_pubkey = coinbase_key.get_pubkey()
# Create the first block with a coinbase output to our key
height = 1
block = create_block(self.tip, create_coinbase(height, coinbase_pubkey), self.block_time)
self.blocks.append(block)
self.block_time += 1
block.solve()
# Save the coinbase for later
self.block1 = block
self.tip = block.sha256
height += 1
# Bury the block 100 deep so the coinbase output is spendable
for i in range(100):
block = create_block(self.tip, create_coinbase(height), self.block_time)
block.solve()
self.blocks.append(block)
self.tip = block.sha256
self.block_time += 1
height += 1
# Create a transaction spending the coinbase output with an invalid (null) signature
tx = CTransaction()
tx.vin.append(CTxIn(COutPoint(self.block1.vtx[0].sha256, 0), scriptSig=b""))
tx.vout.append(CTxOut(49 * 100000000, CScript([OP_TRUE])))
tx.calc_sha256()
block102 = create_block(self.tip, create_coinbase(height), self.block_time)
self.block_time += 1
block102.vtx.extend([tx])
block102.hashMerkleRoot = block102.calc_merkle_root()
block102.rehash()
block102.solve()
self.blocks.append(block102)
self.tip = block102.sha256
self.block_time += 1
height += 1
# Bury the assumed valid block 2100 deep
for i in range(2100):
block = create_block(self.tip, create_coinbase(height), self.block_time)
block.nVersion = 4
block.solve()
self.blocks.append(block)
self.tip = block.sha256
self.block_time += 1
height += 1
self.nodes[0].disconnect_p2ps()
# Start node1 and node2 with assumevalid so they accept a block with a bad signature.
self.start_node(1, extra_args=["-assumevalid=" + hex(block102.sha256)])
self.start_node(2, extra_args=["-assumevalid=" + hex(block102.sha256)])
p2p0 = self.nodes[0].add_p2p_connection(BaseNode())
p2p1 = self.nodes[1].add_p2p_connection(BaseNode())
p2p2 = self.nodes[2].add_p2p_connection(BaseNode())
# send header lists to all three nodes
p2p0.send_header_for_blocks(self.blocks[0:2000])
p2p0.send_header_for_blocks(self.blocks[2000:])
p2p1.send_header_for_blocks(self.blocks[0:2000])
p2p1.send_header_for_blocks(self.blocks[2000:])
p2p2.send_header_for_blocks(self.blocks[0:200])
# Send blocks to node0. Block 102 will be rejected.
self.send_blocks_until_disconnected(p2p0)
self.assert_blockchain_height(self.nodes[0], 101)
# Send all blocks to node1. All blocks will be accepted.
for i in range(2202):
p2p1.send_message(msg_block(self.blocks[i]))
# Syncing 2200 blocks can take a while on slow systems. Give it plenty of time to sync.
p2p1.sync_with_ping(120)
assert_equal(self.nodes[1].getblock(self.nodes[1].getbestblockhash())['height'], 2202)
# Send blocks to node2. Block 102 will be rejected.
self.send_blocks_until_disconnected(p2p2)
self.assert_blockchain_height(self.nodes[2], 101)
示例4: PIVX_FakeStakeTest
# 需要导入模块: from test_framework.key import CECKey [as 别名]
# 或者: from test_framework.key.CECKey import get_pubkey [as 别名]
#.........这里部分代码省略.........
# Even if PoS blocks have empty coinbase vout, the height is required for the vin script
coinbase = create_coinbase(height)
coinbase.vout[0].nValue = 0
coinbase.vout[0].scriptPubKey = b""
coinbase.nTime = nTime
coinbase.rehash()
# Create Block with coinbase
block = create_block(int(hashPrevBlock, 16), coinbase, nTime)
# Find valid kernel hash - Create a new private key used for block signing.
if not block.solve_stake(stakingPrevOuts):
raise Exception("Not able to solve for any prev_outpoint")
self.log.info("Stake found. Signing block...")
# Sign coinstake TX and add it to the block
signed_stake_tx = self.sign_stake_tx(block, stakingPrevOuts[block.prevoutStake][0], fZPoS)
block.vtx.append(signed_stake_tx)
# Remove coinstake input prevout unless we want to try double spending in the same block.
# Skip for zPoS as the spendingPrevouts are just regular UTXOs
if not fZPoS and not fStakeDoubleSpent:
del spendingPrevOuts[block.prevoutStake]
# remove a random prevout from the list
# (to randomize block creation if the same height is picked two times)
del spendingPrevOuts[choice(list(spendingPrevOuts))]
# Create spam for the block. Sign the spendingPrevouts
self.log.info("Creating spam TXes...")
for outPoint in spendingPrevOuts:
value_out = int(spendingPrevOuts[outPoint][0] - self.DEFAULT_FEE * COIN)
tx = create_transaction(outPoint, b"", value_out, nTime, scriptPubKey=CScript([self.block_sig_key.get_pubkey(), OP_CHECKSIG]))
# sign txes
signed_tx_hex = self.node.signrawtransaction(bytes_to_hex_str(tx.serialize()))['hex']
signed_tx = CTransaction()
signed_tx.deserialize(BytesIO(hex_str_to_bytes(signed_tx_hex)))
block.vtx.append(signed_tx)
# Get correct MerkleRoot and rehash block
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
# Sign block with coinstake key and return it
block.sign_block(self.block_sig_key)
return block
def spend_utxo(self, utxo, address_list):
''' spend amount from previously unspent output to a provided address
:param utxo: (JSON) returned from listunspent used as input
addresslist: (string) destination address
:return: txhash: (string) tx hash if successful, empty string otherwise
'''
try:
inputs = [{"txid":utxo["txid"], "vout":utxo["vout"]}]
out_amount = (float(utxo["amount"]) - self.DEFAULT_FEE)/len(address_list)
outputs = {}
for address in address_list:
outputs[address] = out_amount
spendingTx = self.node.createrawtransaction(inputs, outputs)
spendingTx_signed = self.node.signrawtransaction(spendingTx)
if spendingTx_signed["complete"]:
txhash = self.node.sendrawtransaction(spendingTx_signed["hex"])
return txhash
示例5: run_test
# 需要导入模块: from test_framework.key import CECKey [as 别名]
# 或者: from test_framework.key.CECKey import get_pubkey [as 别名]
def run_test(self):
# Connect to node0
node0 = BaseNode()
connections = []
connections.append(
NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], node0))
node0.add_connection(connections[0])
NetworkThread().start() # Start up network handling in another thread
node0.wait_for_verack()
# Build the blockchain
self.tip = int(self.nodes[0].getbestblockhash(), 16)
self.block_time = self.nodes[0].getblock(
self.nodes[0].getbestblockhash())['time'] + 1
self.blocks = []
# Get a pubkey for the coinbase TXO
coinbase_key = CECKey()
coinbase_key.set_secretbytes(b"horsebattery")
coinbase_pubkey = coinbase_key.get_pubkey()
# Create the first block with a coinbase output to our key
height = 1
block = create_block(self.tip, create_coinbase(
height, coinbase_pubkey), self.block_time)
self.blocks.append(block)
self.block_time += 1
block.solve()
# Save the coinbase for later
self.block1 = block
self.tip = block.sha256
height += 1
# Bury the block 100 deep so the coinbase output is spendable
for i in range(100):
block = create_block(
self.tip, create_coinbase(height), self.block_time)
block.solve()
self.blocks.append(block)
self.tip = block.sha256
self.block_time += 1
height += 1
# Create a transaction spending the coinbase output with an invalid
# (null) signature
tx = CTransaction()
tx.vin.append(
CTxIn(COutPoint(self.block1.vtx[0].sha256, 0), scriptSig=b""))
tx.vout.append(CTxOut(49 * 100000000, CScript([OP_TRUE])))
tx.calc_sha256()
block102 = create_block(
self.tip, create_coinbase(height), self.block_time)
self.block_time += 1
block102.vtx.extend([tx])
block102.hashMerkleRoot = block102.calc_merkle_root()
block102.rehash()
block102.solve()
self.blocks.append(block102)
self.tip = block102.sha256
self.block_time += 1
height += 1
# Bury the assumed valid block 2100 deep
for i in range(2100):
block = create_block(
self.tip, create_coinbase(height), self.block_time)
block.nVersion = 4
block.solve()
self.blocks.append(block)
self.tip = block.sha256
self.block_time += 1
height += 1
# Start node1 and node2 with assumevalid so they accept a block with a
# bad signature.
self.nodes.append(start_node(1, self.options.tmpdir,
["-assumevalid=" + hex(block102.sha256)]))
node1 = BaseNode() # connects to node1
connections.append(
NodeConn('127.0.0.1', p2p_port(1), self.nodes[1], node1))
node1.add_connection(connections[1])
node1.wait_for_verack()
self.nodes.append(start_node(2, self.options.tmpdir,
["-assumevalid=" + hex(block102.sha256)]))
node2 = BaseNode() # connects to node2
connections.append(
NodeConn('127.0.0.1', p2p_port(2), self.nodes[2], node2))
node2.add_connection(connections[2])
node2.wait_for_verack()
# send header lists to all three nodes
node0.send_header_for_blocks(self.blocks[0:2000])
node0.send_header_for_blocks(self.blocks[2000:])
node1.send_header_for_blocks(self.blocks[0:2000])
node1.send_header_for_blocks(self.blocks[2000:])
#.........这里部分代码省略.........
示例6: FullBlockTest
# 需要导入模块: from test_framework.key import CECKey [as 别名]
# 或者: from test_framework.key.CECKey import get_pubkey [as 别名]
class FullBlockTest(ComparisonTestFramework):
''' Can either run this test as 1 node with expected answers, or two and compare them.
Change the "outcome" variable from each TestInstance object to only do the comparison. '''
def __init__(self):
self.num_nodes = 1
self.block_heights = {}
self.coinbase_key = CECKey()
self.coinbase_key.set_secretbytes(bytes("horsebattery"))
self.coinbase_pubkey = self.coinbase_key.get_pubkey()
self.block_time = int(time.time())+1
self.tip = None
self.blocks = {}
def run_test(self):
test = TestManager(self, self.options.tmpdir)
test.add_all_connections(self.nodes)
NetworkThread().start() # Start up network handling in another thread
test.run()
def add_transactions_to_block(self, block, tx_list):
[ tx.rehash() for tx in tx_list ]
block.vtx.extend(tx_list)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
return block
# Create a block on top of self.tip, and advance self.tip to point to the new block
# if spend is specified, then 1 satoshi will be spent from that to an anyone-can-spend output,
# and rest will go to fees.
def next_block(self, number, spend=None, additional_coinbase_value=0, script=None):
if self.tip == None:
base_block_hash = self.genesis_hash
else:
base_block_hash = self.tip.sha256
# First create the coinbase
height = self.block_heights[base_block_hash] + 1
coinbase = create_coinbase(height, self.coinbase_pubkey)
coinbase.vout[0].nValue += additional_coinbase_value
if (spend != None):
coinbase.vout[0].nValue += spend.tx.vout[spend.n].nValue - 1 # all but one satoshi to fees
coinbase.rehash()
block = create_block(base_block_hash, coinbase, self.block_time)
if (spend != None):
tx = CTransaction()
tx.vin.append(CTxIn(COutPoint(spend.tx.sha256, spend.n), "", 0xffffffff)) # no signature yet
# This copies the java comparison tool testing behavior: the first
# txout has a garbage scriptPubKey, "to make sure we're not
# pre-verifying too much" (?)
tx.vout.append(CTxOut(0, CScript([random.randint(0,255), height & 255])))
if script == None:
tx.vout.append(CTxOut(1, CScript([OP_TRUE])))
else:
tx.vout.append(CTxOut(1, script))
# Now sign it if necessary
scriptSig = ""
scriptPubKey = bytearray(spend.tx.vout[spend.n].scriptPubKey)
if (scriptPubKey[0] == OP_TRUE): # looks like an anyone-can-spend
scriptSig = CScript([OP_TRUE])
else:
# We have to actually sign it
(sighash, err) = SignatureHash(spend.tx.vout[spend.n].scriptPubKey, tx, 0, SIGHASH_ALL)
scriptSig = CScript([self.coinbase_key.sign(sighash) + bytes(bytearray([SIGHASH_ALL]))])
tx.vin[0].scriptSig = scriptSig
# Now add the transaction to the block
block = self.add_transactions_to_block(block, [tx])
block.solve()
self.tip = block
self.block_heights[block.sha256] = height
self.block_time += 1
assert number not in self.blocks
self.blocks[number] = block
return block
def get_tests(self):
self.genesis_hash = int(self.nodes[0].getbestblockhash(), 16)
self.block_heights[self.genesis_hash] = 0
spendable_outputs = []
# save the current tip so it can be spent by a later block
def save_spendable_output():
spendable_outputs.append(self.tip)
# get an output that we previous marked as spendable
def get_spendable_output():
return PreviousSpendableOutput(spendable_outputs.pop(0).vtx[0], 0)
# returns a test case that asserts that the current tip was accepted
def accepted():
return TestInstance([[self.tip, True]])
# returns a test case that asserts that the current tip was rejected
def rejected():
return TestInstance([[self.tip, False]])
# move the tip back to a previous block
def tip(number):
self.tip = self.blocks[number]
# creates a new block and advances the tip to that block
#.........这里部分代码省略.........
示例7: get_tests
# 需要导入模块: from test_framework.key import CECKey [as 别名]
# 或者: from test_framework.key.CECKey import get_pubkey [as 别名]
#.........这里部分代码省略.........
extra_sigops=MAX_BLOCK_SIGOPS_PER_MB + 1, block_size=2 * ONE_MEGABYTE)
yield rejected(RejectResult(16, b'bad-blk-sigops'))
# Rewind bad block
tip(22)
# Accept 60k sigops per block > 2MB and <= 3MB
block(25, spend=out[20], script=lots_of_checksigs, extra_sigops=2 *
MAX_BLOCK_SIGOPS_PER_MB, block_size=2 * ONE_MEGABYTE + 1)
yield accepted()
# Accept 60k sigops per block > 2MB and <= 3MB
block(26, spend=out[21], script=lots_of_checksigs,
extra_sigops=2 * MAX_BLOCK_SIGOPS_PER_MB, block_size=3 * ONE_MEGABYTE)
yield accepted()
# Reject more than 40k sigops per block > 1MB and <= 2MB.
block(27, spend=out[22], script=lots_of_checksigs, extra_sigops=2 *
MAX_BLOCK_SIGOPS_PER_MB + 1, block_size=2 * ONE_MEGABYTE + 1)
yield rejected(RejectResult(16, b'bad-blk-sigops'))
# Rewind bad block
tip(26)
# Reject more than 40k sigops per block > 1MB and <= 2MB.
block(28, spend=out[22], script=lots_of_checksigs, extra_sigops=2 *
MAX_BLOCK_SIGOPS_PER_MB + 1, block_size=3 * ONE_MEGABYTE)
yield rejected(RejectResult(16, b'bad-blk-sigops'))
# Rewind bad block
tip(26)
# Too many sigops in one txn
too_many_tx_checksigs = CScript(
[OP_CHECKSIG] * (MAX_BLOCK_SIGOPS_PER_MB + 1))
block(
29, spend=out[22], script=too_many_tx_checksigs, block_size=ONE_MEGABYTE + 1)
yield rejected(RejectResult(16, b'bad-txn-sigops'))
# Rewind bad block
tip(26)
# Generate a key pair to test P2SH sigops count
private_key = CECKey()
private_key.set_secretbytes(b"fatstacks")
public_key = private_key.get_pubkey()
# P2SH
# Build the redeem script, hash it, use hash to create the p2sh script
redeem_script = CScript(
[public_key] + [OP_2DUP, OP_CHECKSIGVERIFY] * 5 + [OP_CHECKSIG])
redeem_script_hash = hash160(redeem_script)
p2sh_script = CScript([OP_HASH160, redeem_script_hash, OP_EQUAL])
# Create a p2sh transaction
p2sh_tx = self.create_tx(out[22], 1, p2sh_script)
# Add the transaction to the block
block(30)
update_block(30, [p2sh_tx])
yield accepted()
# Creates a new transaction using the p2sh transaction included in the
# last block
def spend_p2sh_tx(output_script=CScript([OP_TRUE])):
# Create the transaction
spent_p2sh_tx = CTransaction()
spent_p2sh_tx.vin.append(CTxIn(COutPoint(p2sh_tx.sha256, 0), b''))
spent_p2sh_tx.vout.append(CTxOut(1, output_script))
# Sign the transaction using the redeem script
sighash = SignatureHashForkId(
redeem_script, spent_p2sh_tx, 0, SIGHASH_ALL | SIGHASH_FORKID, p2sh_tx.vout[0].nValue)
sig = private_key.sign(sighash) + \
bytes(bytearray([SIGHASH_ALL | SIGHASH_FORKID]))
spent_p2sh_tx.vin[0].scriptSig = CScript([sig, redeem_script])
spent_p2sh_tx.rehash()
return spent_p2sh_tx
# Sigops p2sh limit
p2sh_sigops_limit = MAX_BLOCK_SIGOPS_PER_MB - \
redeem_script.GetSigOpCount(True)
# Too many sigops in one p2sh txn
too_many_p2sh_sigops = CScript([OP_CHECKSIG] * (p2sh_sigops_limit + 1))
block(31, spend=out[23], block_size=ONE_MEGABYTE + 1)
update_block(31, [spend_p2sh_tx(too_many_p2sh_sigops)])
yield rejected(RejectResult(16, b'bad-txn-sigops'))
# Rewind bad block
tip(30)
# Max sigops in one p2sh txn
max_p2sh_sigops = CScript([OP_CHECKSIG] * (p2sh_sigops_limit))
block(32, spend=out[23], block_size=ONE_MEGABYTE + 1)
update_block(32, [spend_p2sh_tx(max_p2sh_sigops)])
yield accepted()
# Submit a very large block via RPC
large_block = block(
33, spend=out[24], block_size=self.excessive_block_size)
node.submitblock(ToHex(large_block))
示例8: get_tests
# 需要导入模块: from test_framework.key import CECKey [as 别名]
# 或者: from test_framework.key.CECKey import get_pubkey [as 别名]
def get_tests(self):
self.genesis_hash = int(self.nodes[0].getbestblockhash(), 16)
self.block_heights[self.genesis_hash] = 0
spendable_outputs = []
# save the current tip so it can be spent by a later block
def save_spendable_output():
spendable_outputs.append(self.tip)
# get an output that we previously marked as spendable
def get_spendable_output():
return PreviousSpendableOutput(spendable_outputs.pop(0).vtx[0], 0)
# returns a test case that asserts that the current tip was accepted
def accepted():
return TestInstance([[self.tip, True]])
# returns a test case that asserts that the current tip was rejected
def rejected(reject=None):
if reject is None:
return TestInstance([[self.tip, False]])
else:
return TestInstance([[self.tip, reject]])
# move the tip back to a previous block
def tip(number):
self.tip = self.blocks[number]
# adds transactions to the block and updates state
def update_block(block_number, new_transactions):
[tx.rehash() for tx in new_transactions]
block = self.blocks[block_number]
block.vtx.extend(new_transactions)
old_sha256 = block.sha256
block.hashMerkleRoot = block.calc_merkle_root()
block.solve()
# Update the internal state just like in next_block
self.tip = block
if block.sha256 != old_sha256:
self.block_heights[
block.sha256] = self.block_heights[old_sha256]
del self.block_heights[old_sha256]
self.blocks[block_number] = block
return block
# shorthand for functions
block = self.next_block
node = self.nodes[0]
# Create a new block
block(0)
save_spendable_output()
yield accepted()
# Now we need that block to mature so we can spend the coinbase.
test = TestInstance(sync_every_block=False)
for i in range(99):
block(5000 + i)
test.blocks_and_transactions.append([self.tip, True])
save_spendable_output()
yield test
# collect spendable outputs now to avoid cluttering the code later on
out = []
for i in range(100):
out.append(get_spendable_output())
# Generate a key pair to test P2SH sigops count
private_key = CECKey()
private_key.set_secretbytes(b"replayprotection")
public_key = private_key.get_pubkey()
# This is a little handier to use than the version in blocktools.py
def create_fund_and_spend_tx(spend, forkvalue=0):
# Fund transaction
script = CScript([public_key, OP_CHECKSIG])
txfund = create_transaction(
spend.tx, spend.n, b'', 50 * COIN, script)
txfund.rehash()
# Spend transaction
txspend = CTransaction()
txspend.vout.append(CTxOut(50 * COIN - 1000, CScript([OP_TRUE])))
txspend.vin.append(CTxIn(COutPoint(txfund.sha256, 0), b''))
# Sign the transaction
sighashtype = (forkvalue << 8) | SIGHASH_ALL | SIGHASH_FORKID
sighash = SignatureHashForkId(
script, txspend, 0, sighashtype, 50 * COIN)
sig = private_key.sign(sighash) + \
bytes(bytearray([SIGHASH_ALL | SIGHASH_FORKID]))
txspend.vin[0].scriptSig = CScript([sig])
txspend.rehash()
return [txfund, txspend]
def send_transaction_to_mempool(tx):
tx_id = node.sendrawtransaction(ToHex(tx))
assert(tx_id in set(node.getrawmempool()))
return tx_id
#.........这里部分代码省略.........
示例9: FullBlockTest
# 需要导入模块: from test_framework.key import CECKey [as 别名]
# 或者: from test_framework.key.CECKey import get_pubkey [as 别名]
class FullBlockTest(ComparisonTestFramework):
# Can either run this test as 1 node with expected answers, or two and compare them.
# Change the "outcome" variable from each TestInstance object to only do
# the comparison.
def set_test_params(self):
self.num_nodes = 1
self.setup_clean_chain = True
self.block_heights = {}
self.coinbase_key = CECKey()
self.coinbase_key.set_secretbytes(b"horsebattery")
self.coinbase_pubkey = self.coinbase_key.get_pubkey()
self.tip = None
self.blocks = {}
def setup_network(self):
self.extra_args = [['-norelaypriority']]
self.add_nodes(self.num_nodes, self.extra_args)
self.start_nodes()
def add_options(self, parser):
super().add_options(parser)
parser.add_option(
"--runbarelyexpensive", dest="runbarelyexpensive", default=True)
def run_test(self):
self.test = TestManager(self, self.options.tmpdir)
self.test.add_all_connections(self.nodes)
# Start up network handling in another thread
NetworkThread().start()
self.test.run()
def add_transactions_to_block(self, block, tx_list):
[tx.rehash() for tx in tx_list]
block.vtx.extend(tx_list)
# this is a little handier to use than the version in blocktools.py
def create_tx(self, spend_tx, n, value, script=CScript([OP_TRUE])):
tx = create_transaction(spend_tx, n, b"", value, script)
return tx
# sign a transaction, using the key we know about
# this signs input 0 in tx, which is assumed to be spending output n in
# spend_tx
def sign_tx(self, tx, spend_tx, n):
scriptPubKey = bytearray(spend_tx.vout[n].scriptPubKey)
if (scriptPubKey[0] == OP_TRUE): # an anyone-can-spend
tx.vin[0].scriptSig = CScript()
return
sighash = SignatureHashForkId(
spend_tx.vout[n].scriptPubKey, tx, 0, SIGHASH_ALL | SIGHASH_FORKID, spend_tx.vout[n].nValue)
tx.vin[0].scriptSig = CScript(
[self.coinbase_key.sign(sighash) + bytes(bytearray([SIGHASH_ALL | SIGHASH_FORKID]))])
def create_and_sign_transaction(self, spend_tx, n, value, script=CScript([OP_TRUE])):
tx = self.create_tx(spend_tx, n, value, script)
self.sign_tx(tx, spend_tx, n)
tx.rehash()
return tx
def next_block(self, number, spend=None, additional_coinbase_value=0, script=CScript([OP_TRUE])):
if self.tip == None:
base_block_hash = self.genesis_hash
block_time = int(time.time()) + 1
else:
base_block_hash = self.tip.sha256
block_time = self.tip.nTime + 1
# First create the coinbase
height = self.block_heights[base_block_hash] + 1
coinbase = create_coinbase(height, self.coinbase_pubkey)
coinbase.vout[0].nValue += additional_coinbase_value
coinbase.rehash()
if spend == None:
block = create_block(base_block_hash, coinbase, block_time)
else:
# all but one satoshi to fees
coinbase.vout[0].nValue += spend.tx.vout[
spend.n].nValue - 1
coinbase.rehash()
block = create_block(base_block_hash, coinbase, block_time)
# spend 1 satoshi
tx = create_transaction(spend.tx, spend.n, b"", 1, script)
self.sign_tx(tx, spend.tx, spend.n)
self.add_transactions_to_block(block, [tx])
block.hashMerkleRoot = block.calc_merkle_root()
# Do PoW, which is very inexpensive on regnet
block.solve()
self.tip = block
self.block_heights[block.sha256] = height
assert number not in self.blocks
self.blocks[number] = block
return block
def get_tests(self):
self.genesis_hash = int(self.nodes[0].getbestblockhash(), 16)
self.block_heights[self.genesis_hash] = 0
spendable_outputs = []
# save the current tip so it can be spent by a later block
#.........这里部分代码省略.........
示例10: run_test
# 需要导入模块: from test_framework.key import CECKey [as 别名]
# 或者: from test_framework.key.CECKey import get_pubkey [as 别名]
#.........这里部分代码省略.........
block = create_block(tip, coinbase, cur_time + 600)
block.nVersion = 0x20000000
block.rehash()
hexblk = ToHex(block)
# ------
self.nodes[0].validateblocktemplate(hexblk)
block.solve()
hexblk = ToHex(block)
self.nodes[0].submitblock(hexblk)
self.sync_all()
prev_block = block
# out_value is less than 50BTC because regtest halvings happen every 150 blocks, and is in Satoshis
out_value = block.vtx[0].vout[0].nValue
tx1 = create_transaction(prev_block.vtx[0], 0, b'\x51', [int(out_value / 2), int(out_value / 2)])
height = self.nodes[0].getblockcount()
tip = int(self.nodes[0].getblockhash(height), 16)
coinbase = create_coinbase(height + 1)
next_time = cur_time + 1200
logging.info("no coinbase")
block = create_block(tip, None, next_time, [tx1])
block.nVersion = 0x20000000
block.rehash()
hexblk = ToHex(block)
expectException(lambda: self.nodes[0].validateblocktemplate(hexblk),
JSONRPCException, "invalid block: bad-cb-missing")
logging.info("double coinbase")
coinbase_key = CECKey()
coinbase_key.set_secretbytes(b"horsebattery")
coinbase_pubkey = coinbase_key.get_pubkey()
coinbase2 = create_coinbase(height + 1, coinbase_pubkey)
block = create_block(tip, coinbase, next_time, [coinbase2, tx1])
block.nVersion = 0x20000000
block.rehash()
hexblk = ToHex(block)
expectException(lambda: self.nodes[0].validateblocktemplate(hexblk),
JSONRPCException, "invalid block: bad-cb-multiple")
logging.info("premature coinbase spend")
block = create_block(tip, coinbase, next_time, [tx1])
block.nVersion = 0x20000000
block.rehash()
hexblk = ToHex(block)
expectException(lambda: self.nodes[0].validateblocktemplate(hexblk),
JSONRPCException, "invalid block: bad-txns-premature-spend-of-coinbase")
self.nodes[0].generate(100)
self.sync_all()
height = self.nodes[0].getblockcount()
tip = int(self.nodes[0].getblockhash(height), 16)
coinbase = create_coinbase(height + 1)
next_time = cur_time + 1200
logging.info("inputs below outputs")
tx6 = create_transaction(prev_block.vtx[0], 0, b'\x51', [out_value + 1000])
block = create_block(tip, coinbase, next_time, [tx6])
block.nVersion = 0x20000000
block.rehash()
hexblk = ToHex(block)
expectException(lambda: self.nodes[0].validateblocktemplate(hexblk),
JSONRPCException, "invalid block: bad-txns-in-belowout")