Esempio n. 1
0
def test_vectors4():
    sk1 = PrivateKey.from_seed(bytes([1, 2, 3, 4, 5]))
    sk2 = PrivateKey.from_seed(bytes([1, 2, 3, 4, 5, 6]))

    pk1 = sk1.get_public_key()
    pk2 = sk2.get_public_key()

    m1 = bytes([7, 8, 9])
    m2 = bytes([10, 11, 12])

    sig9 = sk1.sign_prepend(m1)
    sig10 = sk2.sign_prepend(m2)

    assert (sig9.serialize() == bytes.fromhex(
        "d2135ad358405d9f2d4e68dc253d64b6049a821797817cffa5aa804086a8fb7b135175bb7183750e3aa19513db1552180f0b0ffd513c322f1c0c30a0a9c179f6e275e0109d4db7fa3e09694190947b17d890f3d58fe0b1866ec4d4f5a59b16ed"
    ))
    assert (sig10.serialize() == bytes.fromhex(
        "cc58c982f9ee5817d4fbf22d529cfc6792b0fdcf2d2a8001686755868e10eb32b40e464e7fbfe30175a962f1972026f2087f0495ba6e293ac3cf271762cd6979b9413adc0ba7df153cf1f3faab6b893404c2e6d63351e48cd54e06e449965f08"
    ))

    agg_sig = PrependSignature.aggregate([sig9, sig9, sig10])
    message_hashes = [hash256(m1), hash256(m1), hash256(m2)]
    pks = [pk1, pk1, pk2]
    assert (agg_sig.serialize() == bytes.fromhex(
        "c37077684e735e62e3f1fd17772a236b4115d4b581387733d3b97cab08b90918c7e91c23380c93e54be345544026f93505d41e6000392b82ab3c8af1b2e3954b0ef3f62c52fc89f99e646ff546881120396c449856428e672178e5e0e14ec894"
    ))
    assert (agg_sig.verify(message_hashes, pks))
Esempio n. 2
0
def hash_all_txis(tx):
    if tx["hash_all"] is None:
        all_prevouts = b''
        all_sequence = b''
        for txi in tx["txis"]:
            all_prevouts += txi["txid"][::-1] + util.int_to_little_endian(txi["idx"], 4)
            all_sequence += util.int_to_little_endian(txi["seq.no"], 4)
        tx["hash_all"] = (util.hash256(all_prevouts), util.hash256(all_sequence))
    return tx["hash_all"]
Esempio n. 3
0
def parent_sk_to_lamport_pk(parent_sk: PrivateKey, index: int) -> bytes:
    salt = index.to_bytes(4, "big")
    ikm = bytes(parent_sk)
    not_ikm = bytes([e ^ 0xFF for e in ikm])  # Flip bits
    lamport0 = ikm_to_lamport_sk(ikm, salt)
    lamport1 = ikm_to_lamport_sk(not_ikm, salt)

    lamport_pk = bytes()
    for i in range(255):
        lamport_pk += hash256(lamport0[i * 32:(i + 1) * 32])
    for i in range(255):
        lamport_pk += hash256(lamport1[i * 32:(i + 1) * 32])

    return hash256(lamport_pk)
Esempio n. 4
0
    def hash_pks(num_outputs, public_keys):
        """
        Construction from https://eprint.iacr.org/2018/483.pdf
        Two hashes are performed for speed.
        """
        input_bytes = b''.join([pk.serialize() for pk in public_keys])
        pk_hash = hash256(input_bytes)
        order = public_keys[0].value.ec.n

        computed_Ts = []
        for i in range(num_outputs):
            t = int.from_bytes(hash256(i.to_bytes(4, "big") + pk_hash), "big")
            computed_Ts.append(t % order)

        return computed_Ts
Esempio n. 5
0
    def deserialize(self, f):
        self.magic, self.network = f.deserialize_magic()
        self.version = f.deser_uint8()
        self.flag = f.read(1)
        assert self.flag == b'\x20'
        self.key = f.read(32)
        self.new = f.deser_int32()
        self.tried = f.deser_int32()
        self.no_buckets = f.deser_int32() ^ 1 << 30

        for _ in range(self.new):
            new_addr = AddrInfo()
            new_addr.deserialize(f)

            self.new_table.append(new_addr)

        for _ in range(self.tried):
            tried_addr = AddrInfo()
            tried_addr.deserialize(f)

            self.tried_table.append(tried_addr)

        for _ in range(self.no_buckets):
            bucket = []
            bucket_size = f.deser_int32()
            for __ in range(bucket_size):
                bucket.append(f.deser_int32())
            self.bucket_matrix.append(bucket)

        # Verify the checksum
        position = f.tell()
        f.seek(0)
        if hash256(f.read(position)) != f.read(32):
            raise SerializationError("File checksum incorrect")
Esempio n. 6
0
def sig_hash_bip143(prev_tx, tx, txi, redeem_script=None, witness_script=None, testnet=False):
    """
    bip143
    1:04LE       version
    2:32         hash prevouts
    3:32         hash sequence
    4:32+4LE     outpoint
    5:*          script_code of the input
    6:08LE       value of output spent
    7:04LE       n_sequence of the input
    8:32         hash outputs
    9:4LE        n_locktime
    10:4LE       sighash
    """
    s = util.int_to_little_endian(tx["version"], 4)  # 1
    hash_all_prevouts, hash_all_sequence = hash_all_txis(tx)
    s += hash_all_prevouts + hash_all_sequence  # 2,3
    s += txi["txid"][::-1] + util.int_to_little_endian(txi["idx"], 4)  # 4

    # 5
    if witness_script:
        script_code = script.serialize(witness_script)
    elif redeem_script:
        script_code = script.serialize(script.p2pkh_script(redeem_script[1]))
    else:
        script_code = script.serialize(script.p2pkh_script(prev_tx["txos"][txi["idx"]]["script"][1]))
    s += script_code

    s += util.int_to_little_endian(prev_tx["txos"][txi["idx"]]["amount"], 8)  # 6
    s += util.int_to_little_endian(txi["seq.no"], 4)  # 7
    s += hash_all_txos(tx)  # 8
    s += util.int_to_little_endian(tx["locktime"], 4)  # 9
    s += util.int_to_little_endian(util.SIGHASH_ALL, 4)  # 10
    return int.from_bytes(util.hash256(s), 'big')
Esempio n. 7
0
def parse_msg(s, testnet=False):
    """Takes a stream and creates a NetworkEnvelope"""
    # check the network magic
    magic = s.read(4)
    if magic == b'':
        raise RuntimeError('Connection reset!')
    if testnet:
        expected_magic = TESTNET_MAGIC
    else:
        expected_magic = MAINNET_MAGIC
    if magic != expected_magic:
        raise RuntimeError('magic is not right {} vs {}'.format(
            magic.hex(), expected_magic.hex()))
    # command 12 bytes
    command = s.read(12)
    # strip the trailing 0's
    command = command.strip(b'\x00')
    # payload length 4 bytes, little endian
    payload_length = util.little_endian_to_int(s.read(4))
    # checksum 4 bytes, first four of hash256 of payload
    checksum = s.read(4)
    # payload is of length payload_length
    payload_bytes = s.read(payload_length)
    # verify checksum
    calculated_checksum = util.hash256(payload_bytes)[:4]
    if calculated_checksum != checksum:
        raise RuntimeError('checksum does not match')

    # return msg
    return {"magic": magic, "command": command, "payload_bytes": payload_bytes}
Esempio n. 8
0
def derive_child_sk_unhardened(parent_sk: PrivateKey,
                               index: int) -> PrivateKey:
    """
    Derives an unhardened BIP-32 child private key, from a parent private key,
    at the specified index. WARNING: this key is not as secure as a hardened key.
    """
    h = hash256(bytes(parent_sk.get_g1()) + index.to_bytes(4, "big"))
    return PrivateKey.aggregate([PrivateKey.from_bytes(h), parent_sk])
Esempio n. 9
0
def derive_child_g2_unhardened(parent_pk: JacobianPoint,
                               index: int) -> JacobianPoint:
    """
    Derives an unhardened BIP-32 child public key, from a parent public key,
    at the specified index. WARNING: this key is not as secure as a hardened key.
    """
    h = hash256(bytes(parent_pk) + index.to_bytes(4, "big"))
    return parent_pk + PrivateKey.from_bytes(h) * G2Generator()
Esempio n. 10
0
def check_pow(obj):
    """Returns whether this block satisfies proof of work"""
    # get the hash256 of the serialization of this block
    h256 = util.hash256(serialize(obj))
    # interpret this hash as a little-endian number
    proof = util.little_endian_to_int(h256)
    # return whether this integer is less than the target
    return proof < target(obj)
Esempio n. 11
0
 def to_primitive(body):
     user = None
     username = body.get("username")
     password = body.get("password")
     if body and username and password:
         user = User()
         user.username = username
         user.password = util.hash256(password)
         # Set user deactivated
         user.enabled = False
     return user
Esempio n. 12
0
def serialize_msg(msg):
    """Returns the byte serialization of the entire network message"""
    # add the network magic
    result = msg['magic']
    # command 12 bytes
    # fill with 0's
    result += msg['command'] + b'\x00' * (12 - len(msg['command']))
    # payload length 4 bytes, little endian
    result += util.int_to_little_endian(len(msg['payload_bytes']), 4)
    # checksum 4 bytes, first four of hash256 of payload
    result += util.hash256(msg['payload_bytes'])[:4]
    # payload
    result += msg['payload_bytes']
    return result
Esempio n. 13
0
    def deserialize(self, f):
        self.magic, self.network = f.deserialize_magic()
        bl_len = f.deser_compact_size()

        for _ in range(bl_len):
            ban = Ban()
            ban.deserialize(f)

            self.banmap[ban.subnet] = ban.ban_entry

        # Verify the checksum
        position = f.tell()
        f.seek(0)
        if hash256(f.read(position)) != f.read(32):
            raise SerializationError("File checksum incorrect")
Esempio n. 14
0
def public_key_to_bc_address(public_key):
    """Return the base58 address for a public key."""

    # RIPEMD160(SHA256()) the pubkey
    h160 = hash160(public_key)

    # Prepend version (0 for P2PKH)
    vh160 = b"\x00" + h160

    # Calculate and postpend the checksum
    h3 = hash256(vh160)
    addr = vh160 + h3[0:4]

    # Convert the byte array to base58 and return
    return bytes_to_base58(addr)
Esempio n. 15
0
def sig_hash(tx, idx, lock_script):
    tx4sig = copy.deepcopy(tx)
    for i, txi in enumerate(tx4sig['txis']):
        if i != idx:
            # script.len is calculated when it is serialized.
            # txi["script.len"] = 0
            txi["script"] = []
        else:
            # script.len is calculated when it is serialized.
            # script = serialize_script(script_unlock)
            # txi["script.len"] = len(script)
            txi["script"] = lock_script
    s = serialize(tx4sig)
    s += util.int_to_little_endian(util.SIGHASH_ALL, 4)
    h256 = util.hash256(s)
    return int.from_bytes(h256, 'big')
Esempio n. 16
0
    def verify(self, message_hashes, public_keys):
        """
        Verifies messages using the prepend method. It prepends public keys
        to message hashes before verifying.
        """
        assert (len(message_hashes) == len(public_keys))
        mapped_hashes = [
            hash_to_point_prehashed_Fq2(
                hash256(public_keys[i].serialize() + message_hashes[i]))
            for i in range(len(message_hashes))
        ]
        keys = [pk.value.to_affine() for pk in public_keys]

        g1 = Fq(default_ec.n, -1) * generator_Fq()
        Ps = [g1] + keys
        Qs = [self.value.to_affine()] + mapped_hashes
        res = ate_pairing_multi(Ps, Qs, default_ec)
        return res == Fq12.one(default_ec.q)
Esempio n. 17
0
def get_txid(tx):
    return util.hash256(serialize_legacy(tx))[::-1]  # return 32bytes, not hex value.
Esempio n. 18
0
 def sign_prepend_prehashed(self, h):
     final_message = hash256(self.get_public_key().serialize() + h)
     r = hash_to_point_prehashed_Fq2(final_message).to_jacobian()
     return PrependSignature(self.value * r)
Esempio n. 19
0
 def sign_prepend(self, m):
     return self.sign_prepend_prehashed(hash256(m))
Esempio n. 20
0
def op_hash256(stack):
    if len(stack) < 1:
        return False
    element = stack.pop()
    stack.append(util.hash256(element))
    return True
Esempio n. 21
0
def hash_all_txos(tx):
    all_txo = b''
    for txo in tx["txos"]:
        all_txo += serialize_txo(txo)
    return util.hash256(all_txo)
Esempio n. 22
0
from getpass import getpass
import sys

from util import decodeGameKey, hash256

if len(sys.argv) < 2:
    print("no game key supplied")

reader = input
if "--noecho" in sys.argv:
    reader = getpass

gameKeyEnc = sys.argv[len(sys.argv) - 1]

try:
    net, _, doubleHash, _, challengeAddr = decodeGameKey(gameKeyEnc)
except Exception as e:
    exit(f"Error decoding game key '{gameKeyEnc}': {str(e)}")

print(f"network = {net.Name}")
print(f"challenge address = {challengeAddr.string()}")

answer = reader("What is the solution?\n").strip().encode("utf-8")
if hash256(hash256(answer)) != doubleHash:
    exit(f"!!! Solution failed verification !!!")

exit("Sucess! Solution passed verification")
Esempio n. 23
0
def hash_to_point_Fq2(m, ec=default_ec_twist):
    h = hash256(m)
    return hash_to_point_prehashed_Fq2(h, ec)
Esempio n. 24
0
def hash_to_point_Fq(m, ec=default_ec):
    h = hash256(m)
    return hash_to_point_prehashed_Fq(h, ec)
Esempio n. 25
0
 def get_fingerprint(self):
     ser = self.serialize()
     return int.from_bytes(hash256(ser)[:4], "big")
Esempio n. 26
0
 def from_msg(pk, message):
     return AggregationInfo.from_msg_hash(pk, hash256(message))
Esempio n. 27
0
def merkle_parent(hash1, hash2):
    """Takes the binary hashes and calculates the hash256"""
    # return the hash256 of hash1 + hash2
    return util.hash256(hash1 + hash2)
Esempio n. 28
0
from decred.crypto.secp256k1.curve import generateKey

from util import hash256, scriptVersion

# --mainnet flag must be specified to use mainnet.
isTestNet = "--testnet" in sys.argv
isSimNet = "--simnet" in sys.argv
net = nets.simnet if isSimNet else nets.testnet if isTestNet else nets.mainnet
print(f"Using {net.Name}")

# Get the answer from stdin. Strip whitespace from the ends, but nothing else,
# i.e. input is not converted to lower-case.
answer = input("What is the solution?\n").strip().encode("utf-8")

# The actual input needed to spend the transaction is the hash of the answer.
answerHash = hash256(answer)
# The input will be checked against its hash (the double-hash of the answer) to
# satisfy the script.
doubleHash = hash256(answerHash)

# Build the script. The first opcode says to hash the input in-place on the
# stack.
redeemScript = ByteArray(opcode.OP_SHA256)
# Add the doubleHash to the stack.
redeemScript += txscript.addData(doubleHash)

# Start with OP_EQUALVERIFY because we don't want to leave a TRUE/FALSE on the
# stack, we just want to if the answer is wrong.
redeemScript += opcode.OP_EQUALVERIFY
# We need to generate a key pair for the game key.
priv = generateKey() # The "Game Key".
Esempio n. 29
0
 def get_fingerprint(self) -> int:
     ser = bytes(self)
     return int.from_bytes(hash256(ser)[:4], "big")
Esempio n. 30
0
def hash_header(obj):
    """Returns the hash256 interpreted little endian of the block"""
    s = serialize(obj)
    h256 = util.hash256(s)
    return h256[::-1]