예제 #1
0
def mock_make_child(parent_state,
                    parent_hash,
                    skips,
                    attester_share=0.8,
                    checkpoint_shards=[]):
    parent_attestation_hash = parent_hash + \
                              parent_state.checkpoint_hash + \
                              parent_state.epoch.to_bytes(32, 'big') + \
                              parent_state.source_epoch.to_bytes(32, 'big')
    checkpoint_attestation_hash = b'\x00' * 32 + \
                              parent_state.checkpoint_hash + \
                              parent_state.epoch.to_bytes(32, 'big') + \
                              parent_state.source_epoch.to_bytes(32, 'big')
    validator_count = len(parent_state.active_validators)
    indices = get_shuffling(parent.randao_state, validator_count,
                            min(parent_state.active_validators, 128))
    # Randomly pick indices to include
    bitfield = [1 if random.random() < attester_share else 0 for i in indices]
    # Attestations
    sigs = [
        bls.sign(parent_attestation_hash,
                 keymap[parent_state.active_validators[indices[i]].pubkey])
        for i in range(len(indices)) if bitfield[i]
    ]
    attestation_aggregate_sig = bls.aggregate_sig(sigs)
    attestation_bitmask = bytearray((len(bitfield) - 1) // 8 + 1)
    for i, b in enumerate(bitfield):
        attestation_bitmask[i // 8] ^= (128 >> (i % 8)) * b
    # Randomly pick indices to include for checkpoints
    shard_aggregate_votes = []
    for shard, crosslinker_share in checkpoint_shards:
        indices = parent_state.shuffling[(validator_count * shard) //
                                         100:(validator_count *
                                              (shard + 1)) // 100]
        bitfield = [
            1 if random.random() < crosslinker_share else 0 for i in indices
        ]
        bitmask = bytearray((len(bitfield) - 1) // 8 + 1)
        checkpoint = blake(bytes([shard]))
        sigs = [
            bls.sign(checkpoint,
                     keymap[parent_state.active_validators[indices[i]].pubkey])
            for i in range(len(indices)) if bitfield[i]
        ]
        shard_aggregate_votes.append(
            AggregateVote(shard, checkpoint, bitmask, bls.aggregate_sig(sigs)))
    # State calculations

    o = BlockHeader(parent.hash, skips,
                    blake(str(random.random()).encode('utf-8')),
                    attestation_bitmask, attestation_aggregate_sig,
                    shard_aggregate_votes, b'\x00' * 32, state.hash,
                    state.height)
    # Main signature
    o.sign(keymap[parent_state.active_validators[indices[-1]].pubkey])
    return o
예제 #2
0
def test_signature_aggregation():
    n = 5
    t = 3

    sk, bls_pk = bls.keygen()
    msg = 'test message'
    sig = bls.sign(sk, msg)

    sk_shares, _ = vss.share(sk, n, t)
    partial_sigs = [bls.sign(partial_sk, msg) for partial_sk in sk_shares]
    indexed_partial_sigs = [(i, sig) for i, sig in zip(range(1, n + 1), partial_sigs)]

    for selected_partial_sigs in itertools.combinations(indexed_partial_sigs, t):
        aggregated_sig = vss.recover_point(selected_partial_sigs)
        assert sig == aggregated_sig
예제 #3
0
def test_all_to_all_signature_aggregation():
    n = 5
    t = 3

    sks = [crypto.random_scalar() for _ in range(n)]
    master_sk = sum(sks) % crypto.CURVE_ORDER
    msg = 'test message'
    sig = bls.sign(master_sk, msg)

    agg_sks = [0] * n
    for sk in sks:
        sk_shares, _ = vss.share(sk, n, t)
        for i, sk_share in enumerate(sk_shares):
            agg_sks[i] += sk_share

    partial_sigs = [bls.sign(psk, msg) for psk in agg_sks]
    indexed_partial_sigs = [(i, sig) for i, sig in zip(range(1, n + 1), partial_sigs)]

    for selected_partial_sigs in itertools.combinations(indexed_partial_sigs, t):
        aggregated_sig = vss.recover_point(selected_partial_sigs)
        assert sig == aggregated_sig
예제 #4
0
def test_verification_of_aggregate_signature():
    # generates and verfies a signature under the master key derived for contract
    # 0x64eB9cbc8AAc7723A7A94b178b7Ac4c18D7E6269
    # see ../evaluation/testnet-execution for the transscripts

    master_pk = (
        16185756129160603637125524807239031401829819645832054270709340132395400777397,
        8519501919971397775891715048167089286600326398415030764834336433929153469650,
        18597752777763136713734159587276505878060020022295659236248459536349704859281,
        451510684427994150648572847494629298315616628846799867117722216880750483787
    )

    msg = 'test message'
    msg_hash = hashlib.sha3_256(msg.encode()).digest()

    # ids for the 3 correct nodes A, B, C (assigned durign registration)
    id_A, id_B, id_C = 3, 2, 1

    # group secret keys for the 3 correct nodes A, B and C
    gsk_A = (
        19063102076674778359749742475275688996157982969842615782345982391516317582432
    )
    gsk_B = (
        25409986690480885131491958594328734819629294462429970027081157236075400972958
    )
    gsk_C = (
        48802012483270245949082675044770005030925758437990233282811259804203609665090
    )

    sig_A = bls.sign(gsk_A, msg_hash)
    sig_B = bls.sign(gsk_B, msg_hash)
    sig_C = bls.sign(gsk_C, msg_hash)

    # three signature shares are sufficient to generate a signature which successfully verifies under the master pk
    sig = bls.aggregate([(id_A, sig_A), (id_B, sig_B), (id_C, sig_C)])
    assert bls.verify(master_pk, msg_hash, sig)

    # verify that the signature can also be verified in the smart contract
    contract = utils.deploy_contract('DKG')
    assert contract.verify_signature(master_pk, msg_hash, sig)
예제 #5
0
def genValidSignature(message, sk, pk, g):
    sig = bls.sign(sk, message)
    assert bls.verify(pk, message, sig, g)
    return sig
예제 #6
0
    case03_private_to_public_key = []
    #  Used in later cases
    pubkeys = [bls.privtopub(privkey) for privkey in PRIVKEYS]
    #  Used in public key aggregation
    pubkeys_serial = ['0x' + pubkey.hex() for pubkey in pubkeys]
    case03_private_to_public_key = [{
        'input': int_to_hex(privkey),
        'output': pubkey_serial,
    } for privkey, pubkey_serial in zip(PRIVKEYS, pubkeys_serial)]

    case04_sign_messages = []
    sigs = []  # used in verify
    for privkey in PRIVKEYS:
        for message in MESSAGES:
            for domain in DOMAINS:
                sig = bls.sign(message, privkey, domain)
                case04_sign_messages.append({
                    'input': {
                        'privkey': int_to_hex(privkey),
                        'message': '0x' + message.hex(),
                        'domain': int_to_hex(domain)
                    },
                    'output': '0x' + sig.hex()
                })
                sigs.append(sig)

    # TODO: case05_verify_messages: Verify messages signed in case04
    # It takes too long, empty for now

    case06_aggregate_sigs = []
    for domain in DOMAINS:
예제 #7
0
    sign, privtopub, aggregate_sigs, aggregate_pubs, verify

from simpleserialize import serialize, deserialize, eq

from full_pos import ActiveState, CheckpointRecord

for x in (1, 5, 124, 735, 127409812145, 90768492698215092512159, 0):
    print('Testing with privkey %d' % x)
    p1 = multiply(G1, x)
    p2 = multiply(G2, x)
    msg = str(x).encode('utf-8')
    msghash = hash_to_G2(msg)
    assert normalize(decompress_G1(compress_G1(p1))) == normalize(p1)
    assert normalize(decompress_G2(compress_G2(p2))) == normalize(p2)
    assert normalize(decompress_G2(compress_G2(msghash))) == normalize(msghash)
    sig = sign(msg, x)
    pub = privtopub(x)
    assert verify(msg, pub, sig)

print('Testing signature aggregation')
msg = b'cow'
keys = [1, 5, 124, 735, 127409812145, 90768492698215092512159, 0]
sigs = [sign(msg, k) for k in keys]
pubs = [privtopub(k) for k in keys]
aggsig = aggregate_sigs(sigs)
aggpub = aggregate_pubs(pubs)
assert verify(msg, aggpub, aggsig)

print('Testing basic serialization')

assert serialize(5, 'int8') == b'\x05'
예제 #8
0
def genValidSignature(message, sk, pk, g):
    sig = bls.sign(sk, message)
    assert bls.verify(pk, message, sig, g)
    return sig
예제 #9
0
def test_signing():
    sk, bls_pk = bls.keygen()
    msg = 'test message'
    sig = bls.sign(sk, msg)
    assert bls.verify(bls_pk, msg, sig)
예제 #10
0
def mock_make_child(parent_state,
                    parent,
                    skips,
                    attester_share=0.8,
                    crosslink_shards=[]):
    crystallized_state, active_state = parent_state
    parent_attestation = serialize(parent)
    validator_count = len(crystallized_state.active_validators)
    indices, main_signer = get_attesters_and_signer(crystallized_state,
                                                    active_state, skips)
    print('Selected indices: %r' % indices)
    print('Selected main signer: %d' % main_signer)
    # Randomly pick indices to include
    bitfield = [1 if random.random() < attester_share else 0 for i in indices]
    # Attestations
    sigs = [
        bls.sign(
            parent_attestation,
            keymap[crystallized_state.active_validators[indices[i]].pubkey])
        for i in range(len(indices)) if bitfield[i]
    ]
    attestation_aggregate_sig = bls.aggregate_sigs(sigs)
    print('Aggregated sig')
    attestation_bitmask = bytearray((len(bitfield) - 1) // 8 + 1)
    for i, b in enumerate(bitfield):
        attestation_bitmask[i // 8] ^= (128 >> (i % 8)) * b
    print('Aggregate bitmask:', bin(int.from_bytes(attestation_bitmask,
                                                   'big')))
    # Randomly pick indices to include for crosslinks
    shard_aggregate_votes = []
    for shard, crosslinker_share in crosslink_shards:
        print('Making crosslink in shard %d' % shard)
        indices = get_shard_attesters(crystallized_state, shard)
        print('Indices: %r' % indices)
        bitfield = [
            1 if random.random() < crosslinker_share else 0 for i in indices
        ]
        bitmask = bytearray((len(bitfield) + 7) // 8)
        for i, b in enumerate(bitfield):
            bitmask[i // 8] ^= (128 >> (i % 8)) * b
        print('Bitmask:', bin(int.from_bytes(bitmask, 'big')))
        shard_block_hash = blake(bytes([shard]))
        crosslink_attestation_hash = get_crosslink_aggvote_msg(
            shard, shard_block_hash, crystallized_state)
        sigs = [
            bls.sign(
                crosslink_attestation_hash, keymap[
                    crystallized_state.active_validators[indices[i]].pubkey])
            for i in range(len(indices)) if bitfield[i]
        ]
        v = AggregateVote(shard_id=shard,
                          shard_block_hash=shard_block_hash,
                          signer_bitmask=bitmask,
                          aggregate_sig=list(bls.aggregate_sigs(sigs)))
        shard_aggregate_votes.append(v)
    print('Added %d shard aggregate votes' % len(crosslink_shards))
    # State calculations
    o = Block(parent_hash=blake(parent_attestation),
              skip_count=skips,
              randao_reveal=blake(str(random.random()).encode('utf-8')),
              attestation_bitmask=attestation_bitmask,
              attestation_aggregate_sig=list(attestation_aggregate_sig),
              shard_aggregate_votes=shard_aggregate_votes,
              main_chain_ref=b'\x00' * 32,
              state_hash=b'\x00' * 64)
    print('Generated preliminary block header')
    new_crystallized_state, new_active_state = \
        compute_state_transition((crystallized_state, active_state), parent, o, verify_sig=False)
    print('Calculated state transition')
    if crystallized_state == new_crystallized_state:
        o.state_hash = blake(parent.state_hash[:32] +
                             blake(serialize(new_active_state)))
    else:
        o.state_hash = blake(
            blake(serialize(new_crystallized_state)) +
            blake(serialize(new_active_state)))
    # Main signature
    o.sign(keymap[crystallized_state.active_validators[main_signer].pubkey])
    print('Signed')
    return o, new_crystallized_state, new_active_state
예제 #11
0
 def sign(self, key):
     self.sig = [0, 0]
     self.sig = list(sign(serialize(self), key))
예제 #12
0
#!/usr/bin/env python3

from charm.toolbox.pairinggroup import PairingGroup, ZR, G1, G2, GT, pair

from bls import step_0 as sign
from utils import jencode, jdecode

if __name__ == "__main__":
    # Read {g, sk [,pk]}
    s = jdecode(input("priv: "))
    s.update(jdecode(input("m: ")))

    # Sign message m
    print(jencode(sign(s)))
예제 #13
0
 def sign(self, message: Any) -> PointG1:
     return bls.sign(self.group_sk, message)