2015-04-28 18:39:47 +02:00
|
|
|
# blocktools.py - utilities for manipulating blocks and transactions
|
2015-01-05 21:40:24 +01:00
|
|
|
# Copyright (c) 2015 The Bitcoin Core developers
|
2015-04-28 18:39:47 +02:00
|
|
|
# Distributed under the MIT/X11 software license, see the accompanying
|
|
|
|
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
|
|
|
#
|
|
|
|
|
|
|
|
from mininode import *
|
2015-12-02 18:12:23 +01:00
|
|
|
from script import CScript, OP_TRUE, OP_CHECKSIG
|
2015-04-28 18:39:47 +02:00
|
|
|
|
|
|
|
# Create a block (with regtest difficulty)
|
|
|
|
def create_block(hashprev, coinbase, nTime=None):
|
|
|
|
block = CBlock()
|
|
|
|
if nTime is None:
|
|
|
|
import time
|
|
|
|
block.nTime = int(time.time()+600)
|
|
|
|
else:
|
|
|
|
block.nTime = nTime
|
|
|
|
block.hashPrevBlock = hashprev
|
|
|
|
block.nBits = 0x207fffff # Will break after a difficulty adjustment...
|
|
|
|
block.vtx.append(coinbase)
|
|
|
|
block.hashMerkleRoot = block.calc_merkle_root()
|
|
|
|
block.calc_sha256()
|
|
|
|
return block
|
|
|
|
|
|
|
|
def serialize_script_num(value):
|
|
|
|
r = bytearray(0)
|
|
|
|
if value == 0:
|
|
|
|
return r
|
|
|
|
neg = value < 0
|
|
|
|
absvalue = -value if neg else value
|
|
|
|
while (absvalue):
|
|
|
|
r.append(chr(absvalue & 0xff))
|
|
|
|
absvalue >>= 8
|
|
|
|
if r[-1] & 0x80:
|
|
|
|
r.append(0x80 if neg else 0)
|
|
|
|
elif neg:
|
|
|
|
r[-1] |= 0x80
|
|
|
|
return r
|
|
|
|
|
2015-08-05 23:47:34 +02:00
|
|
|
# Create a coinbase transaction, assuming no miner fees.
|
|
|
|
# If pubkey is passed in, the coinbase output will be a P2PK output;
|
|
|
|
# otherwise an anyone-can-spend output.
|
|
|
|
def create_coinbase(height, pubkey = None):
|
2015-04-28 18:39:47 +02:00
|
|
|
coinbase = CTransaction()
|
|
|
|
coinbase.vin.append(CTxIn(COutPoint(0, 0xffffffff),
|
2015-08-05 23:47:34 +02:00
|
|
|
ser_string(serialize_script_num(height)), 0xffffffff))
|
2015-04-28 18:39:47 +02:00
|
|
|
coinbaseoutput = CTxOut()
|
2015-12-22 10:43:46 +01:00
|
|
|
coinbaseoutput.nValue = 50 * COIN
|
2015-08-05 23:47:34 +02:00
|
|
|
halvings = int(height/150) # regtest
|
2015-04-28 18:39:47 +02:00
|
|
|
coinbaseoutput.nValue >>= halvings
|
2015-08-05 23:47:34 +02:00
|
|
|
if (pubkey != None):
|
|
|
|
coinbaseoutput.scriptPubKey = CScript([pubkey, OP_CHECKSIG])
|
|
|
|
else:
|
|
|
|
coinbaseoutput.scriptPubKey = CScript([OP_TRUE])
|
2015-04-28 18:39:47 +02:00
|
|
|
coinbase.vout = [ coinbaseoutput ]
|
|
|
|
coinbase.calc_sha256()
|
|
|
|
return coinbase
|
|
|
|
|
|
|
|
# Create a transaction with an anyone-can-spend output, that spends the
|
|
|
|
# nth output of prevtx.
|
|
|
|
def create_transaction(prevtx, n, sig, value):
|
|
|
|
tx = CTransaction()
|
|
|
|
assert(n < len(prevtx.vout))
|
|
|
|
tx.vin.append(CTxIn(COutPoint(prevtx.sha256, n), sig, 0xffffffff))
|
|
|
|
tx.vout.append(CTxOut(value, ""))
|
|
|
|
tx.calc_sha256()
|
|
|
|
return tx
|