def parse(cls, s):
     amount = little_endian_to_int(4)
     script_pub = Script.parse(s)
     return cls(amount, script_pub)
Beispiel #2
0
from helper import decode_base58, little_endian_to_int, hash256, SIGHASH_ALL
from script import p2pkh_script, Script
from tx import TxIn, TxOut, Tx
from ecc import PrivateKey

# use 2 txin to send to mwJn1YPMq7y5F8J3LkC5Hxg9PHyZ5K4cFv

# our old private key

private_key = PrivateKey(little_endian_to_int(
    hash256(b'dat_test_private_key')))

# some sats from a previous tx

prev_tx1 = bytes.fromhex(
    '74699b8cc3dd67bdd54314283603c72b76a09368e5646b5b29c28028d5ae0076')
prev_index1 = 1

# sats from change of the tx of previous exercise

prev_tx2 = bytes.fromhex(
    '47c0095c4e40c79128037c3861445c7f7d93e6ff9b55c10274395798f3503da8')
prev_index2 = 1

tx_in1 = TxIn(prev_tx1, prev_index1)
tx_in2 = TxIn(prev_tx2, prev_index2)

# where we send our sats

tx_outs = []
target_amount = 200000
Beispiel #3
0
from helper import decode_base58, little_endian_to_int, hash256, SIGHASH_ALL, hash160, h160_to_p2sh_address
from script import p2pkh_script, p2sh_script, Script
from tx import TxIn, TxOut, Tx
from ecc import PrivateKey

# we send to a p2sh address

secret1 = little_endian_to_int(hash256(b'dat_test_private_key_p2sh1'))

secret2 = little_endian_to_int(hash256(b'dat_test_private_key2_p2sh2'))

private_key1 = PrivateKey(secret1)
private_key2 = PrivateKey(secret2)

print(private_key1.point.address(
    testnet=True))  #mfchv5Xq63UuQTAVwzqhWVHAZVkiZrhDKh
print(private_key2.point.address(
    testnet=True))  #ms4kdy8Hn4WfxK2J2VpbonTit5NeNy6vJS

## first we create the scriptPubKey of the redeemscript or redeem script

# we decode our previous pubkey to put them in script commands

public_key1 = decode_base58('mfchv5Xq63UuQTAVwzqhWVHAZVkiZrhDKh')
public_key2 = decode_base58('ms4kdy8Hn4WfxK2J2VpbonTit5NeNy6vJS')

#redeem script as op code

dat_redeem_script_op = Script([0x52, public_key1, public_key2, 0x52, 0xae])
print('dat_redeem_script_op:{}'.format(dat_redeem_script_op))
Beispiel #4
0
def target(self):
    exponent = self.bits[-1]
    coefficient = little_endian_to_int(self.bits[:-1])
    return coefficient * 256**(exponent - 3)
Beispiel #5
0
print("Amount available to spend (after fees): " +str(amount_available/sat_in_bit) + " tBTC")

''' Construct Outputs '''
tx_outs = []
num_outputs= int(input("How many outputs (NOT including the output for left-over change)? "))
tx_outs  = get_output_info(num_outputs, amount_available)

''' Construct Transaction object '''
tx_obj = Tx(1, tx_ins, tx_outs, 0, True)


''' Signing the inputs '''
for i in range(len(tx_ins)):
    print("Enter your private key passphrase to prove that you can sign input "+str(i)+":")
    password = getpass.getpass('Passphrase:')
    private_key = PrivateKey(little_endian_to_int(hash256(str.encode(password))))
    tx_obj.sign_input(i, private_key)



if(tx_obj.verify()):
    print("-------Transaction Successfully Signed-------")
    print("===>raw transaction:")
    tx_serial = tx_obj.serialize().hex()
    print(tx_serial)
    #p.sendrawtransaction(tx_serial)
    #print("===>transaction successfully published<====")
    print("==> use this with 'bitcoin-cli sendrawtransaction <raw_tx>' in order to broadcast it")
else:
    print("Incorrect Signature for this Transaction")
Beispiel #6
0
 def parse(cls, s):
     amount = little_endian_to_int(s.read(8))
     script_pubkey = Script.parse(s)
     return cls(amount, script_pubkey)
Beispiel #7
0
 def test_example_2(self):
     bits = bytes.fromhex('e93c0118')
     exponent = bits[-1]
     coefficient = little_endian_to_int(bits[:-1])
     target = coefficient * 256**(exponent - 3)
     self.assertEqual('{:x}'.format(target).zfill(64), '0000000000000000013ce9000000000000000000000000000000000000000000')
def create_btc_address(passphrase):
    secret = little_endian_to_int(hash256(passphrase))
    publicKey = PrivateKey(secret).point
    print(publicKey.sec())
    address = publicKey.address(testnet=True)
    return address
Beispiel #9
0
 def parse(cls, s):
     txo = TXO.parse(s)
     spending_tx_id = s.read(32)
     spending_tx_index = little_endian_to_int(s.read(4))
     return cls(txo, spending_tx_id, spending_tx_index)
Beispiel #10
0
 def test_broadcast(self):
     from bloomfilter import BloomFilter
     last_block_hex = '00000000000000a03f9432ac63813c6710bfe41712ac5ef6faab093fe2917636'
     secret = little_endian_to_int(hash256(b'Jimmy Song'))
     private_key = PrivateKey(secret=secret)
     h160 = private_key.point.hash160()
     addr = private_key.point.address(testnet=True)
     target_address = 'mwJn1YPMq7y5F8J3LkC5Hxg9PHyZ5K4cFv'
     target_h160 = decode_base58(target_address)
     target_script = p2pkh_script(target_h160)
     fee = 5000  # fee in satoshis
     # connect to programmingblockchain.com in testnet mode
     node = SimpleNode('programmingblockchain.com', testnet=True)
     # create a bloom filter of size 30 and 5 functions. Add a tweak.
     bf = BloomFilter(30, 5, 90210)
     # add the h160 to the bloom filter
     bf.add(h160)
     # load the bloom filter with the filterload command
     node.send(bf.filterload())
     # set start block to last_block from above
     start_block = bytes.fromhex(last_block_hex)
     # send a getheaders message with the starting block
     getheaders = GetHeadersMessage(start_block=start_block)
     node.send(getheaders)
     # wait for the headers message
     headers = node.wait_for(HeadersMessage)
     block_hashes = [b.hash() for b in headers.blocks]
     # initialize prev_tx, prev_index and prev_amount to None
     prev_tx, prev_index, prev_amount = None, None, None
     for h, tx_obj in node.get_filtered_block_txs(block_hashes):
         self.assertEqual(h, tx_obj.hash())
         tx_obj.testnet = True
         # loop through the tx outs
         for i, tx_out in enumerate(tx_obj.tx_outs):
             # if our output has the same address as our address we found it
             if tx_out.script_pubkey.address(testnet=True) == addr:
                 # we found our utxo. set prev_tx, prev_index, and tx
                 prev_tx = h
                 prev_index = i
                 prev_amount = tx_out.amount
                 self.assertEqual(
                     h.hex(),
                     'b2cddd41d18d00910f88c31aa58c6816a190b8fc30fe7c665e1cd2ec60efdf3f'
                 )
                 self.assertEqual(i, 7)
                 break
         if prev_tx:
             break
     # create the TxIn
     tx_in = TxIn(prev_tx, prev_index)
     # calculate the output amount (previous amount minus the fee)
     output_amount = prev_amount - fee
     # create a new TxOut to the target script with the output amount
     tx_out = TxOut(output_amount, target_script)
     # create a new transaction with the one input and one output
     tx_obj = Tx(1, [tx_in], [tx_out], 0, testnet=True)
     # sign the only input of the transaction
     self.assertTrue(tx_obj.sign_input_p2pkh(0, private_key))
     # serialize and hex to see what it looks like
     want = '01000000013fdfef60ecd21c5e667cfe30fcb890a116688ca51ac3880f91008dd141ddcdb2070000006b483045022100ff77d2559261df5490ed00d231099c4b8ea867e6ccfe8e3e6d077313ed4f1428022033a1db8d69eb0dc376f89684d1ed1be75719888090388a16f1e8eedeb8067768012103dc585d46cfca73f3a75ba1ef0c5756a21c1924587480700c6eb64e3f75d22083ffffffff019334e500000000001976a914ad346f8eb57dee9a37981716e498120ae80e44f788ac00000000'
     self.assertEqual(tx_obj.serialize().hex(), want)
     # send this signed transaction on the network
     node.send_tx(tx_obj)
Beispiel #11
0
from ecc import PrivateKey
from helper import hash256, little_endian_to_int

passphrase = b'jiboiamutante'
secret = little_endian_to_int(hash256(passphrase))
priv = PrivateKey(secret)
print(priv.point.address(testnet = True))

'''Address: mkHc2s6q11EqgwLGdg9Adh6qM7C6yUfXqv'''
Beispiel #12
0
def bits_to_target(bits):
    exponent = bits[-1]
    coefficient = little_endian_to_int(bits[:-1])
    return coefficient * 256**(exponent - 3)
Beispiel #13
0
def coinbase_height(self):
    if not self.is_coinbase():
        return None
    element = self.tx_ins[0].script_sig.instructions[0]
    return little_endian_to_int(element)
Beispiel #14
0
 def coinbase_height(self):
     if self.is_coinbase():
         return little_endian_to_int(self.tx_ins[0].script_sig.cmds[0])
     else:
         return None
Beispiel #15
0
 def tx_in_parse(cls, s):
     prev_tx = s.read(32)[::-1]
     prev_index = little_endian_to_int(s.read(4))
     script_sig = Script.parse(s)
     sequence = little_endian_to_int(s.read(4))
     return cls(prev_tx, prev_index, script_sig, sequence)
 def __init__(self, passphrase):
     self.secret = little_endian_to_int(hash256(passphrase))
     self.private_key = PrivateKey(self.secret)
     self.public_key = self.private_key.point
     self.address = self.public_key.address(testnet=True)
Beispiel #17
0
 def bits_to_target(self):
     exponent = self.bits[-1]
     coefficient = little_endian_to_int(self.bits[:-1])
     target = coefficient * pow(256, exponent - 3)
     return target
Beispiel #18
0
def H(*args):
    return little_endian_to_int(H_(*args))
Beispiel #19
0
 def check_pow(self):
     h256 = hash256(self.serialize())
     work = little_endian_to_int(h256)
     return work < self.target()
Beispiel #20
0
 def coinbase_height(self):
     if not is_coinbase(self):
         return None
     return little_endian_to_int(self.tx_ins[0].script_sig.commands[0])
Beispiel #21
0
from helper import decode_base58, little_endian_to_int, hash256, SIGHASH_ALL, hash160, h160_to_p2sh_address
from script import p2pkh_script, Script
from tx import TxIn, TxOut, Tx
from ecc import PrivateKey

# -- try of a 2 of 2 musig p2sh --

# 2 private key because 2 of 2

secret1 = little_endian_to_int(hash256(b'dat_test_private_key_p2sh1'))

secret2 = little_endian_to_int(hash256(b'dat_test_private_key2_p2sh2'))

# derived pubkeys

private_key1 = PrivateKey(secret1)
private_key2 = PrivateKey(secret2)

print(private_key1.point.address(testnet=True))

print(private_key2.point.address(testnet=True))

## first we create the scriptPubKey of the redeemscript or redeem script

# we decode our previous pubkey to put them in script commands

public_key1 = decode_base58('mvEg6eZ3sUApodedYQrkpEPMMALsr1K1k1')
public_key2 = decode_base58('mwjg9Y1jeFdNu7DQBAW7DUbJqj6jMmhd74')

#dat_redeem_script_t1 = 0x52, public_key1, public_key2, 0x52, 0xae
Beispiel #22
0
    def parse(cls, s):
        # get the length of the entire field
        #print(s)
        length = read_varint(s)
        #print(f"length script: {length}")
        # initialize the cmds array
        cmds = []
        # initialize the number of bytes we've read to 0
        count = 0
        # loop until we've read length bytes
        while count < length:
            # get the current byte
            #print(f"WHILE: count {count} and length {length}")
            current = s.read(1)
            # increment the bytes we've read
            count += 1
            # convert the current byte to an integer
            current_byte = current[0]
            #print(f"current_byte : {current_byte}")
            # if the current byte is between 1 and 75 inclusive
            if current_byte >= 1 and current_byte <= 75:
                # we have an cmd set n to be the current byte
                n = current_byte
                # add the next n bytes as an cmd
                cmds.append(s.read(n))
                # increase the count by n
                count += n
            elif current_byte == 76:
                # op_pushdata1
                data_length = little_endian_to_int(s.read(1))

                if (data_length + count) > length:
                    print(
                        f"BAD SCRIPT: original script data_length {data_length} "
                    )
                    data_length = length - count - 1
                    print(f"Fixed script data_length to {data_length }")
                    s.read(data_length)
                    raise SyntaxError('parsing script failed')

                cmds.append(s.read(data_length))
                count += data_length + 1
            elif current_byte == 77:
                # op_pushdata2
                data_length = little_endian_to_int(s.read(2))

                if (data_length + count) > length:
                    print(
                        f"BAD SCRIPT: original script data_length {data_length} "
                    )
                    data_length = length - count - 2
                    print(f"Fixed script data_length to {data_length}")
                    s.read(data_length)
                    raise SyntaxError('parsing script failed')

                cmds.append(s.read(data_length))
                count += data_length + 2
            else:
                # we have an opcode. set the current byte to op_code
                op_code = current_byte
                #print(f"op_code : {op_code}")
                # add the op_code to the list of cmds
                cmds.append(op_code)
        if count != length:
            raise SyntaxError('parsing script failed')
        return cls(cmds)
Beispiel #23
0
 def parse(cls, s):
     type_ = little_endian_to_int(s.read(4))
     hash_ = s.read(32)
     return cls(type_, hash_)
Beispiel #24
0
def coinbase_height(self):
    if not self.is_coinbase():
        return None
    first_input = self.tx_ins[0]
    first_element = first_input.script_sig.commands[0]
    return little_endian_to_int(first_element)
from ecc import PrivateKey
from helper import hash256, little_endian_to_int, decode_base58, SIGHASH_ALL
from script import p2pkh_script, Script
from tx import TxIn, TxOut, Tx

secret = little_endian_to_int(hash256(b'my first secret key'))
private_key = PrivateKey(secret)
print(private_key.point.address(testnet=True))

prev_tx = bytes.fromhex(
    '6e7657754799fe7a906b213aa57b6920ad2d660f349fcb52dd384568aaddc2ef')
prev_index = 1
tx_in = TxIn(prev_tx, prev_index)

tx_outs = []
change_amount = int(0.004 * 10000000)
change_h160 = decode_base58('mxUJg9m1dsqpHnbhV15mwJ3GjwPBVMHVmu')
change_script = p2pkh_script(change_h160)
change_output = TxOut(change_amount, change_script)

target_amount = int(0.007 * 10000000)
target_h160 = decode_base58('mwJn1YPMq7y5F8J3LkC5Hxg9PHyZ5K4cFv')
target_script = p2pkh_script(target_h160)
target_output = TxOut(target_amount, target_script)

tx_obj = Tx(1, [tx_in], [change_output, target_output], 0, True)
print(tx_obj.sign_input(0, private_key))
print(tx_obj.serialize().hex())
Beispiel #26
0
def check_pow(self):
    h256 = hash256(self.serialize())
    proof = little_endian_to_int(h256)
    return proof < self.target()
Beispiel #27
0
 def test_exercise_8(self):
     passphrase = b'Jimmy Song Programming Blockchain'
     secret = little_endian_to_int(hash256(passphrase))
     point = secret * G
     self.assertEqual(point.address(testnet=True),
                      'mwJn1YPMq7y5F8J3LkC5Hxg9PHyZ5K4cFv')