Beispiel #1
0
 def check_pow(self):
     '''Returns whether this block satisfies proof of work'''
     dat_hash = hash256(self.serialize())
     dat_hash = little_endian_to_int(dat_hash)
     return dat_hash < self.target()
Beispiel #2
0
def op_hash256(stack):
    if len(stack) < 1:
        return False
    element = stack.pop()
    stack.append(hash256(element))
    return True
from ecc import PrivateKey
from helper import hash256, little_endian_to_int

mypass = b'KBU_201601071_PARKDONGHYUNE'
mysecret = little_endian_to_int(hash256(mypass))

P = PrivateKey(mysecret)

print(P.point.address(testnet=True))
Beispiel #4
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

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

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

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

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

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

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

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

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

dat_redeem_script_op = Script([0x52, public_key1, public_key2, 0x52, 0xae])

# make a transact to mwJn1YPMq7y5F8J3LkC5Hxg9PHyZ5K4cFv with 60% of a UTXO and send back the change

secret = little_endian_to_int(hash256(b'dat_test_private_key'))

private_key = PrivateKey(secret)
Beispiel #5
0
"""
"""
dat_s = io.BytesIO(b'abc')
print(little_endian_to_int(dat_s.read(4)))

"""

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

# make a transact to mwJn1YPMq7y5F8J3LkC5Hxg9PHyZ5K4cFv with 60% of a UTXO and send back the change

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

print(private_key.point.address(testnet=True, dat_h160=False))

# UTXO that we gonna receive

prev_tx = bytes.fromhex(
    '1ed5583812bda08b71a71c2fa1e6788dac956efa9d2c26b6c9fd10f6e885658f')
prev_index = 1

# create the txin with the output of the UTXO we have been given

tx_in = TxIn(prev_tx, prev_index)
tx_outs = []
change_amount = int(0.00003 * 100000000)
Beispiel #6
0
 def hash(self):
     return hash256(self.serialize())[::-1]
Beispiel #7
0
def check_pow(self):
    h256 = hash256(self.serialize())
    proof = little_endian_to_int(h256)
    return proof < self.target()
Beispiel #8
0
def hash(self):
    s = self.serialize()
    sha = hash256(s)
    return sha[::-1]
Beispiel #9
0
z = 0xec208baa0fc1c19f708a9ca96fdeff3ac3f230bb4a7ba4aede4942ad003c0f60
r = 0xac8d1c87e51d0d441be8b3dd5b05c8795b48875dffe00b7ffcfac23010d3a395
s = 0x68342ceff8935ededd102dd876ffd6ba72d6a427a3edb13d26eb0781cb423c4

s_inv = pow(s, N - 2, N)
u = z * s_inv % N
v = r * s_inv % N
print(((u * G) + (v * Point)).x.num == r)

#2
z = 0x7c076ff316692a3d7eb3c3bb0f8b1488cf72e1afcd929e29307032997a838a3d
r = 0xeff69ef2b1bd93a66ed5219add4fb51e11a840f404876325a1e8ffe0529a2c
s = 0xc7207fee197d27c618aea621406f6bf5ef6fca38681d82b2f06fddbdce6feab6

s_inv = pow(s, N - 2, N)
u = z * s_inv % N
v = r * s_inv % N
print((u * G + v * Point).x.num == r)

e = 12345
z = int.from_bytes(hash256(b'Programming Bitcoin!'), 'big')

k = 3333
r = (k * G).x.num
k_inv = pow(k, N - 2, N)
s = (z + r * 2) * k_inv % N
Point = e * G
print(Point)
print(hex(z))
print(hex(r))
Beispiel #10
0
tx_in1 = TxIn(prev_tx1, prev_index1)
tx_in2 = TxIn(prev_tx1, prev_index1)
target_amount = int(9000)

# output address that will receive the sat we have not spend

target_h160 = decode_base58('mvEg6eZ3sUApodedYQrkpEPMMALsr1K1k1')
target_script = p2pkh_script(target_h160)
target_output = TxOut(amount=target_amount, script_pubkey=target_script)

# output address that will receive our sat

target_script = p2pkh_script(target_h160)
target_output = TxOut(amount=target_amount, script_pubkey=target_script)
tx_obj = Tx(1, [tx_in], [target_output], 0, True)
#print(tx_obj).hex()

# now we sign the transaction

z = tx_obj.sig_hash(0)
private_key = PrivateKey(little_endian_to_int(
    hash256(b'dat_test_private_key')))
der = private_key.sign(z).der()
sig = der + SIGHASH_ALL.to_bytes(1, 'big')
sec = private_key.point.sec()
script_sig = Script([sig, sec])
tx_obj.tx_ins[0].script_sig = script_sig
print(tx_obj.serialize().hex())

# end
Beispiel #11
0
der = bytes.fromhex(hex_der)
redeem_script = Script.parse(BytesIO(bytes.fromhex(hex_redeem_script)))
stream = BytesIO(bytes.fromhex(hex_tx))

tx = Tx.parse(stream, False)
dat_s = int_to_little_endian(tx.version, 4)
dat_s += encode_varint(len(tx.tx_ins))
dat_s += TxIn(
    prev_tx = tx.tx_ins[0].prev_tx,
    prev_index = tx.tx_ins[0].prev_index,
    script_sig = redeem_script,
    sequence = tx.tx_ins[0].sequence,
    ).serialize()
dat_s += encode_varint(len(tx.tx_outs))
for tx_out in tx.tx_outs:
    dat_s += tx_out.serialize()
dat_s += int_to_little_endian(tx.locktime, 4)
dat_s += int_to_little_endian(SIGHASH_ALL, 4)
dat_h256 = hash256(dat_s)
dat_z = int.from_bytes(dat_h256, 'big')

dat_256Point = S256Point.parse(sec)
dat_sig = Signature.parse(der)
#dat_combined = redeem_script + dat_S
print(dat_256Point.verify(dat_z, dat_sig))

# dat_s = little_endian_to_int(stream.read(4))
# dat_s = read_varint(stream)

#dat_s = int_to_little_endian(stream, stream.read(4))
Beispiel #12
0
 def hash256(self):
     h256 = hash256(self.serialize())
     return h256[::-1]
Beispiel #13
0
 def hash(self):
     block_hash = hash256(self.serialize())
     return block_hash[::-1]
Beispiel #14
0
 def hash(self):
     '''Returns the hash256 interpreted little endian of the block'''
     return hash256(self.serialize())[::-1]
Beispiel #15
0
def createAddress(passphrase):
    secret = little_endian_to_int(hash256(passphrase))
    publicKey = PrivateKey(secret).point
    address = publicKey.address(testnet=True)
    return address


def is_unspent(txid, index, proxy):
    return proxy.gettxout(txid, index) == None


p = RawProxy(service_port=18332)

# Sender Information
sender_secret = b'[email protected] Tranquility Cracks is a hidden gem that many seek but few find'
secret = little_endian_to_int(hash256(sender_secret))
private_key = PrivateKey(secret)
public_key = private_key.point
sender_address = public_key.address(testnet=True)

# Receiver Information
receiver_address = createAddress(b'some salt for this receiver address')

# What is in our wallet that we can spend? (this one has 0.01 tBTC)
tx_in_id = 'acf22005638e60379aa43d4cd2a5eb47a0fa1fefc5883eecf83329a607431d50'
tx_in_index = 1
tx_input = TxIn(bytes.fromhex(tx_in_id), tx_in_index)

# Checking spentness of the inputs. Should be False
print("Spentness of input " + str(tx_in_index) + ": " +
      str(is_unspent(tx_in_id, tx_in_index, p)))
Beispiel #16
0
 def update(self, stop_height=None):
     if stop_height is None:
         stop_height = self.node.latest_block
     start_height = self.store_height()
     previous = self.headers[-1]
     # find the first epoch timestamp
     epoch_first_block = self.headers[(len(self.headers) // 2016) * 2016]
     epoch_first_timestamp = epoch_first_block.timestamp
     epoch_bits = epoch_first_block.bits
     # download blocks we don't have
     current_height = start_height + 1
     while current_height <= stop_height:
         LOGGER.info('downloading headers {} to {}'.format(current_height, current_height+1999))
         # ask for headers
         getheaders = GetHeadersMessage(start_block=previous.hash())
         self.node.send(getheaders)
         headers = self.node.wait_for(HeadersMessage)
         # validate headers
         for header in headers.blocks:
             if not header.check_pow():
                 raise RuntimeError('{}: PoW is invalid'.format(current_height))
             if header.prev_block != previous.hash():
                 raise RuntimeError('{}: not sequential'.format(current_height))
             if current_height % 2016 == 0:
                 # difficulty adjustment
                 time_diff = previous.timestamp - epoch_first_timestamp
                 epoch_bits = calculate_new_bits(previous.bits, time_diff)
                 expected_bits = epoch_bits
                 epoch_first_timestamp = header.timestamp
             elif self.testnet and header.timestamp > previous.timestamp + 20 * 60:
                 expected_bits = LOWEST_BITS
             else:
                 expected_bits = epoch_bits
             if header.bits != expected_bits:
                 raise RuntimeError('{}: bad bits {} vs {}'.format(
                     current_height, header.bits.hex(), expected_bits.hex()))
             previous = header
             current_height += 1
             self.headers.append(header)
             self.headers_lookup[header.hash()] = header
             if current_height > stop_height:
                 break
     LOGGER.info('downloaded headers to {} inclusive'.format(stop_height))
     # download compact filter checkpoints
     getcfcheckpoint = GetCFCheckPointMessage(stop_hash=self.headers[-1].hash())
     self.node.send(getcfcheckpoint)
     cfcheckpoint = self.node.wait_for(CFCheckPointMessage)
     # download all cfheaders
     prev_filter_header = b'\x00' * 32
     cfcheckpoint.filter_headers.append(None)
     for i, cpfilter_header in enumerate(cfcheckpoint.filter_headers):
         if i == 0:
             start = 0
         else:
             start = i * 1000 + 1
         end = (i+1) * 1000
         if end <= start_height:
             prev_filter_header = cpfilter_header
             continue
         if end > stop_height:
             end = stop_height
             stop_hash = self.headers[-1].hash()
         else:
             stop_hash = self.header_by_height(end).hash()
         LOGGER.info('getting filters range {} to {}'.format(start, end))
         getcfheaders = GetCFHeadersMessage(
             start_height=start, stop_hash=stop_hash)
         self.node.send(getcfheaders)
         cfheaders = self.node.wait_for(CFHeadersMessage)
         if prev_filter_header != cfheaders.previous_filter_header:
             raise RuntimeError('Non-sequential CF headers')
         # validate all cfheaders
         for j, filter_hash in enumerate(cfheaders.filter_hashes):
             header = self.header_by_height(start + j)
             filter_header = hash256(filter_hash[::-1] + prev_filter_header[::-1])[::-1]
             prev_filter_header = filter_header
             header.cfhash = filter_hash
             header.cfheader = filter_header
         if cpfilter_header is not None and cpfilter_header != prev_filter_header:
             raise RuntimeError('CF header not what we expected')
Beispiel #17
0
def createAddress(passphrase):
    secret = little_endian_to_int(hash256(passphrase))
    publicKey = PrivateKey(secret).point
    address = publicKey.address(testnet=True)
    return address
Beispiel #18
0
 def whash(self):
     if not self.segwit:
         return self.hash()
     return hash256(self.serialize_segwit())[::-1]
Beispiel #19
0
def hash(self):
    s = self.serialize()
    h256 = hash256(s)
    return h256[::-1]
Beispiel #20
0
def op_hash256(stack: List[bytes]) -> bool:
    if len(stack) < 1:
        return False
    element = stack.pop()
    stack.append(hash256(element))
    return True
Beispiel #21
0
from ecc import PrivateKey
from helper import decode_base58, little_endian_to_int, hash256
from script import p2pkh_script
from tx import TxIn, TxOut, Tx

#PRIVATE  KEY
SEMILLA = b'HolaHashgerTraines'
SECRETO = little_endian_to_int(hash256(SEMILLA))
PrivKey = PrivateKey(SECRETO)
print('Mi llave privada es: ', PrivKey.hex())
ADDRESS = PrivKey.point.address(testnet=True)
print('Mi direecion  Bitcoin testenet es: ', ADDRESS)

#INPUTS
tx_previa = bytes.fromhex(
    'b685879f3939fa9531899b729394ed85edab8b6850b72a9e378ea31af96a304a')
index_tx_previa = 1

tx_inputs = []
tx_inputs.append(TxIn(tx_previa, index_tx_previa))

#OUPUTS
tx_outputs = []
destinatario = 'mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB'
monto = .00008
change_adress = ADDRESS
cambio = .00001
#SEND OUTPUT
h160 = decode_base58(destinatario)
script_pubkey = p2pkh_script(h160)
monto_satoshis = int(monto * 100_000_000)
Beispiel #22
0
1574e6b3c192ecfb52cc8984ee7b6c568700000000'

hex_sec = '03b287eaf122eea69030a0e9feed096bed8045c8b98bec453e1ffac7fbdbd4b\
b71'

hex_der = '3045022100da6bee3c93766232079a01639d07fa869598749729ae323eab8ee\
f53577d611b02207bef15429dcadce2121ea07f233115c6f09034c0be68db99980b9a6c5e75402\
2'

hex_redeem_script = '475221022626e955ea6ea6d98850c994f9107b036b1334f18ca88\
30bfff1295d21cfdb702103b287eaf122eea69030a0e9feed096bed8045c8b98bec453e1ffac7f\
bdbd4bb7152ae'

sec = bytes.fromhex(hex_sec)
der = bytes.fromhex(hex_der)
redeem_script = Script.parse(BytesIO(bytes.fromhex(hex_redeem_script)))
stream = BytesIO(bytes.fromhex(hex_tx))
tx_obj = Tx.parse(stream)
s = int_to_little_endian(tx_obj.version, 4)
s += encode_varint(len(tx_obj.tx_ins))
i = tx_obj.tx_ins[0]
s += TxIn(i.prev_tx, i.prev_index, redeem_script, i.sequence).serialize()
s += encode_varint(len(tx_obj.tx_outs))
for tx_out in tx_obj.tx_outs:
    s += tx_out.serialize()
s += int_to_little_endian(tx_obj.locktime, 4)
s += int_to_little_endian(SIGHASH_ALL, 4)
z = int.from_bytes(hash256(s), 'big')
point = S256Point.parse(sec)
sig = Signature.parse(der)
print(point.verify(z, sig))
# signature 2
z = 0x7c076ff316692a3d7eb3c3bb0f8b1488cf72e1afcd929e29307032997a838a3d
r = 0xeff69ef2b1bd93a66ed5219add4fb51e11a840f404876325a1e8ffe0529a2c
s = 0xc7207fee197d27c618aea621406f6bf5ef6fca38681d82b2f06fddbdce6feab6
u = z * pow(s, N-2, N) % N
v = r * pow(s, N-2, N) % N
print((u * G + v * point).x.num == r)
# result : True


# In[16]:


from ecc import S256Point, G, N
from helper import hash256
e = int.from_bytes(hash256(b'my secret'), 'big')
z = int.from_bytes(hash256(b'my message'), 'big')
k = 1234567890
r = (k*G).x.num
k_inv = pow(k, N-2, N)
s = (z+r*e) * k_inv % N
point = e*G
print(point)
print(hex(z))
print(hex(r))
print(hex(s))


# ### Exercise 7
# 
# Sign the following message with the secret
Beispiel #24
0
 def test_exercise_9(self):
     passphrase = b'[email protected] my secret'
     secret = helper.little_endian_to_int(hash256(passphrase))
     priv = PrivateKey(secret)
     self.assertEqual(priv.point.address(testnet=True),
                      'mft9LRNtaBNtpkknB8xgm17UvPedZ4ecYL')
Beispiel #25
0
from ecc import PrivateKey
from helper import hash256, little_endian_to_int

passphrase = b'pickmeupimscared1419'
secret = little_endian_to_int(hash256(passphrase))
priv = PrivateKey(secret)
print(priv.point.address(testnet=True))
Beispiel #26
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')
Beispiel #27
0
def encode_base58_checksum(raw):
    checksum = hash256(raw)[:4]
    base58 = encode_base58(raw + checksum)
    return base58.decode('ascii')
Beispiel #28
0
    else:
        amounts_valid = True
        print("Sufficient Funds")


# get target address
target_address = input("Enter address of recipient: ")
target_h160 = decode_base58(target_address)
target_script = p2pkh_script(target_h160)
target_output = TxOut(amount = target_amount, script_pubkey = target_script)


# Sender Information
print("Enter your private key passphrase to prove that you can sign the inputs:")
password = getpass.getpass('Passphrase:')
secret = little_endian_to_int(hash256(str.encode(password)))
private_key = PrivateKey(secret)
public_key = private_key.point
sender_address = public_key.address(testnet=True)
print("Your Address: " + sender_address)

#send change back to sender
change_amount = int(amount_available - target_amount - fee_amount)
change_160 = decode_base58(sender_address)
change_script = p2pkh_script(change_160)
change_output = TxOut(amount = change_amount, script_pubkey = change_script)

#create the Tx object
tx_obj = Tx(1, tx_ins, [change_output, target_output], 0, True)

#signing the transaction
Beispiel #29
0
 def hash(self):  # <4>
     '''Binary hash of the legacy serialization'''
     return hash256(self.serialize())[::-1]
Beispiel #30
0
    def __init__(self,
                 ft: Transaction,
                 id_l: Id,
                 id_r: Id,
                 val_l: float,
                 val_r: float,
                 fee: float,
                 timelockCT: int = consts.timelockCT):
        self.ft = ft
        self.id_l = id_l
        self.id_r = id_r
        self.fee = fee
        self.timelockCT = timelockCT
        self.timelock = consts.timelock
        self.val_l = val_l
        self.val_r = val_r

        self.transactions = []

        secret_rev = gen_secret()

        ct_l = txs.get_standard_ct(TxInput(ft.get_txid(), 0),
                                   id_l,
                                   id_r,
                                   hash256(secret_rev),
                                   val_l,
                                   val_r,
                                   fee,
                                   l=True,
                                   timelock=0x2)
        ct_script = ct_l.outputs[0].script_pubkey.script
        ct_l_to_l = txs.get_standard_ct_spend(TxInput(ct_l.get_txid(),
                                                      0), id_l, ct_script,
                                              val_l - 0.5 * self.fee, fee)
        ct_l_punish = txs.get_standard_ct_punish(TxInput(ct_l.get_txid(),
                                                         0), self.id_r,
                                                 ct_script, secret_rev,
                                                 val_l - 0.5 * self.fee, fee)
        self.transactions.append(('CT_l', ct_l))
        self.transactions.append(('CT_l_to_l', ct_l_to_l))
        self.transactions.append(
            ('CT_l_punish', ct_l_punish)
        )  # in the real world, this is added only when this state is revoked

        secret_rev_r = gen_secret()
        ct_r = txs.get_standard_ct(TxInput(ft.get_txid(), 0),
                                   id_l,
                                   id_r,
                                   hash256(secret_rev_r),
                                   val_l,
                                   val_r,
                                   fee,
                                   l=False,
                                   timelock=0x2)
        ct_r_script = ct_r.outputs[0].script_pubkey.script
        ct_r_to_r = txs.get_standard_ct_spend(TxInput(ct_r.get_txid(),
                                                      0), id_r, ct_r_script,
                                              val_r - 0.5 * self.fee, fee)
        ct_r_punish = txs.get_standard_ct_punish(TxInput(ct_r.get_txid(),
                                                         0), self.id_l,
                                                 ct_script, secret_rev_r,
                                                 val_r - 0.5 * self.fee, fee)
        self.transactions.append(('CT_r', ct_l))
        self.transactions.append(('CT_r_to_r', ct_r_to_r))
        self.transactions.append(
            ('CT_r_punish', ct_r_punish)
        )  # in the real world, this is added only when this state is revoked