Пример #1
0
def request(inputs, reference_inputs, parameters, clear_m, hidden_m, pub,
            *args):
    # execute PrepareMixSign
    q = loads(inputs[0])['q']
    params = setup(q)
    (cm, c, proof) = prepare_mix_sign(params, clear_m, hidden_m, pub)

    # new petition object
    request = {
        'type': 'CoCoRequest',
        'instance': loads(inputs[0]),
        'clear_m': pet_pack(clear_m),
        'cm': pack(cm),
        'c': [(pack(ci[0]), pack(ci[1])) for ci in c],
        'sigs': []
    }

    # create dependency
    # @Mustafa: we need to modify the framework to make possible to pass a callback here;
    # i.e., make possible to execute callback_function(args) for any function passed as argument
    hello_contract.init(args)

    # return
    return {
        'outputs': (inputs[0], dumps(request)),
        'extra_parameters': (pet_pack(proof), pack(pub))
    }
Пример #2
0
def sign(inputs, reference_inputs, parameters, priv_signer, sig, vvk):
    # ini petition, list and parameters
    old_petition = loads(inputs[0])
    new_petition = loads(inputs[0])
    old_list = loads(inputs[1])
    new_list = loads(inputs[1])
    new_values = loads(parameters[0])

    # update petition values
    for i in range(0, len(new_values)):
        new_petition['scores'][i] = old_petition['scores'][i] + new_values[i]

    # prepare showing of credentials
    UUID = pet_unpack(old_petition['UUID'])
    bp_params = bp_setup()
    (kappa, nu, proof_v) = show_coconut_petition(bp_params, vvk, priv_signer,
                                                 UUID)
    #print(coconut_petition_verify(bp_params, vvk, kappa, sig, proof_v, UUID, nu))

    # update spent list
    new_list['list'].append(pack(nu))

    # pack sig
    packed_sig = (pack(sig[0]), pack(sig[1]))

    # return
    return {
        'outputs': (dumps(new_petition), dumps(new_list)),
        'extra_parameters':
        (packed_sig, pack(kappa), pack(nu), pet_pack(proof_v))
    }
Пример #3
0
def issue(inputs, reference_inputs, parameters, sk, index):
    # extract data
    request = loads(inputs[0])
    updated_request = loads(inputs[0])
    instance = request['instance']
    q = instance['q']
    params = setup(q)
    cm = unpackG1(params, request['cm'])
    c = [(unpackG1(params, packed_ci[0]), unpackG1(params, packed_ci[1]))
         for packed_ci in request['c']]
    clear_m = pet_unpack(request['clear_m'])

    # sign
    (h, enc_epsilon) = mix_sign(params, sk, cm, c, clear_m)
    packed_enc_sig = (pack(h), (pack(enc_epsilon[0]), pack(enc_epsilon[1])))

    # update request
    # NOTE: indexes are used to re-order the signature for threshold aggregation
    updated_request['sigs'].append((index, packed_enc_sig))

    # return
    return {
        'outputs': (dumps(updated_request), ),
        'extra_parameters': ((index, packed_enc_sig), )
    }
Пример #4
0
def create_petition(inputs, reference_inputs, parameters, UUID, options,
                    priv_owner, pub_owner, vvk):
    # inital score
    scores = [0 for _ in options]

    # pack vvk
    packed_vvk = (pack(vvk[0]), pack(vvk[1]), pack(vvk[2]))

    # new petition object
    new_petition = {
        'type': 'PObject',
        'UUID': pet_pack(UUID),  # unique ID of the petition
        'owner': pet_pack(pub_owner),  # entity creating the petition
        'verifier':
        packed_vvk,  # entity delivering credentials to participate to the petition
        'options': options,  # the options to sign
        'scores': scores  # the signatures per option
    }

    # ID lists
    signed_list = {'type': 'PList', 'list': []}

    # signature
    pet_params = pet_setup()
    hasher = sha256()
    hasher.update(dumps(new_petition).encode('utf8'))
    sig = do_ecdsa_sign(pet_params[0], priv_owner, hasher.digest())

    # return
    return {
        'outputs': (inputs[0], dumps(new_petition), dumps(signed_list)),
        'extra_parameters': (pet_pack(sig), )
    }
Пример #5
0
def create_tumbler(inputs, reference_inputs, parameters, vvk, sig):
    # pack vvk
    packed_vvk = (pack(vvk[0]),pack(vvk[1]),pack(vvk[2]))

    # ID lists
    spent_list = {
        'type' : 'TList',
        'list' : [],
        'vvk'  : packed_vvk
    }

    # return
    return {
        'outputs': (inputs[0], dumps(spent_list)),
        'extra_parameters' : (pet_pack(sig),)
    }
Пример #6
0
def redeem(inputs, reference_inputs, parameters, sig, vvk):
    # ini petition, list and parameters
    old_list = loads(inputs[0])
    new_list = loads(inputs[0])
    ID = loads(parameters[0])

    # update spent list
    new_list['list'].append(ID)

    # pack sig
    packed_sig = (pack(sig[0]),pack(sig[1]))

    # return
    return {
        'outputs': (dumps(new_list),),
        'extra_parameters' : (packed_sig,)
    }
Пример #7
0
def create(inputs, reference_inputs, parameters, q, t, n, callback, vvk, sig):
    # pack sig and vvk
    packed_sig = (pack(sig[0]), pack(sig[1]))
    packed_vvk = (pack(vvk[0]), pack(vvk[1]),
                  [pack(vvk[2][i]) for i in range(q)])

    # new petition object
    instance = {
        'type': 'CoCoInstance',
        'q': q,
        't': t,
        'n': n,
        'callback': callback,
        'verifier': packed_vvk
    }

    # return
    return {
        'outputs': (inputs[0], dumps(instance)),
        'extra_parameters': (packed_sig, )
    }
Пример #8
0
def verify(inputs, reference_inputs, parameters, clear_m, hidden_m):
    #start_time = time.time()

    # load instance
    instance = loads(reference_inputs[0])

    # build proof
    params = setup(instance['q'])
    packed_vvk = instance['verifier']
    vvk = (unpackG2(params, packed_vvk[0]), unpackG2(params, packed_vvk[1]),
           [unpackG2(params, y) for y in packed_vvk[2]])
    (kappa, proof_v) = show_mix_sign(params, vvk, hidden_m)

    tnm = (dumps(clear_m), pack(kappa), pet_pack(proof_v))
    #end_time = time.time(); print((end_time-start_time)*1000)

    # returns
    return {
        'returns': (dumps(True), ),
        'extra_parameters': (dumps(clear_m), pack(kappa), pet_pack(proof_v))
    }
Пример #9
0
####################################################################
# authenticated bank transfer
####################################################################
# crypto parameters
t, n = 4, 5  # threshold and total numbero of authorities
bp_params = bp_setup()  # bp system's parameters
(sk, vk, vvk) = ttp_th_keygen(bp_params, t, n)  # signers keys

# tumbler parameter
ID = 10  # random ID
merchant_addr = 'merchant_addr'  # merchant address

# some crypto
# ------------------------------------
packed_vvk = (pack(vvk[0]), pack(vvk[1]), pack(vvk[2]))
instance = {'type': 'TList', 'list': [], 'vvk': packed_vvk}
hasher = sha256()
hasher.update(dumps(instance).encode('utf8'))
m = Bn.from_binary(hasher.digest())
auth_sigs = [sign(bp_params, ski, m) for ski in sk]
auth_sig = aggregate_th_sign(bp_params, auth_sigs)
#print(verify(bp_params, vvk, m, auth_sig))


class Test(unittest.TestCase):
    # --------------------------------------------------------------
    # test init
    # --------------------------------------------------------------
    def test_init(self):
        ## run service
def main():
    coconut.contract._populate_empty_checkers()
    print "operation\t\tmean (ms)\t\tsd (ms)\t\truns"

    # == init ===============
    init_tx = coconut.init()

    # == create ===============
    # gen
    times = []
    for i in range(RUNS):
        start_time = time.time()
        coconut.create((init_tx['transaction']['outputs'][0], ), None, None, q,
                       t, n, callback, vvk, auth_sig)
        end_time = time.time()
        times.append((end_time - start_time) * 1000)
    mean = numpy.mean(times)
    sd = numpy.std(times)
    print "[g] create tx\t{:.10f}\t\t{:.10f}\t{}".format(mean, sd, RUNS)

    # check
    create_tx = coconut.create((init_tx['transaction']['outputs'][0], ), None,
                               None, q, t, n, callback, vvk, auth_sig)
    solution = transaction_to_solution(create_tx)
    times = []
    for i in range(RUNS):
        start_time = time.time()
        coconut.contract.checkers['create'](
            solution['inputs'],
            solution['referenceInputs'],
            solution['parameters'],
            solution['outputs'],
            solution['returns'],
            solution['dependencies'],
        )
        end_time = time.time()
        times.append((end_time - start_time) * 1000)
    mean = numpy.mean(times)
    sd = numpy.std(times)
    print "[c] create tx\t{:.10f}\t\t{:.10f}\t{}".format(mean, sd, RUNS)

    # == request ===============
    # gen
    times = []
    for i in range(RUNS):
        start_time = time.time()
        coconut.request((create_tx['transaction']['outputs'][1], ), None, None,
                        clear_m, hidden_m, pub)
        end_time = time.time()
        times.append((end_time - start_time) * 1000)
    mean = numpy.mean(times)
    sd = numpy.std(times)
    print "[g] request tx\t{:.10f}\t\t{:.10f}\t{}".format(mean, sd, RUNS)

    # check
    request_tx = coconut.request((create_tx['transaction']['outputs'][1], ),
                                 None, None, clear_m, hidden_m, pub)
    solution = transaction_to_solution(request_tx)
    times = []
    for i in range(RUNS):
        start_time = time.time()
        coconut.contract.checkers['request'](
            solution['inputs'],
            solution['referenceInputs'],
            solution['parameters'],
            solution['outputs'],
            solution['returns'],
            solution['dependencies'],
        )
        end_time = time.time()
        times.append((end_time - start_time) * 1000)
    mean = numpy.mean(times)
    sd = numpy.std(times)
    print "[c] request tx\t{:.10f}\t\t{:.10f}\t{}".format(mean, sd, RUNS)

    # == issue ===============
    # gen
    times = []
    for i in range(RUNS):
        start_time = time.time()
        coconut.issue((request_tx['transaction']['outputs'][1], ), None, None,
                      sk[0], 0)
        end_time = time.time()
        times.append((end_time - start_time) * 1000)
    mean = numpy.mean(times)
    sd = numpy.std(times)
    print "[g] issue tx\t{:.10f}\t\t{:.10f}\t{}".format(mean, sd, RUNS)

    # check
    issue_tx = coconut.issue((request_tx['transaction']['outputs'][1], ), None,
                             None, sk[0], 0)
    solution = transaction_to_solution(issue_tx)
    times = []
    for i in range(RUNS):
        start_time = time.time()
        coconut.contract.checkers['issue'](
            solution['inputs'],
            solution['referenceInputs'],
            solution['parameters'],
            solution['outputs'],
            solution['returns'],
            solution['dependencies'],
        )
        end_time = time.time()
        times.append((end_time - start_time) * 1000)
    mean = numpy.mean(times)
    sd = numpy.std(times)
    print "[c] issue tx\t{:.10f}\t\t{:.10f}\t{}".format(mean, sd, RUNS)

    # == verify ===============
    # gen

    # issue t signatures
    old_request = request_tx['transaction']['outputs'][1]
    for i in range(t):
        transaction = coconut.issue((old_request, ), None, None, sk[i], i)
        old_request = transaction['transaction']['outputs'][0]

    # some crypto
    # ------------------------------------
    packet = loads(old_request)['sigs']
    (indexes, packed_enc_sigs) = zip(*packet)
    (h, packed_enc_epsilon) = zip(*packed_enc_sigs)
    enc_epsilon = [(unpackG1(params, x[0]), unpackG1(params, x[1]))
                   for x in packed_enc_epsilon]
    dec_sigs = [(unpackG1(params, h[0]), elgamal_dec(params, priv, enc))
                for enc in enc_epsilon]
    aggr = aggregate_th_sign(params, dec_sigs)
    aggr = randomize(params, aggr)
    packed_sig = (pack(aggr[0]), pack(aggr[1]))
    # ------------------------------------

    times = []
    for i in range(RUNS):
        start_time = time.time()
        coconut.verify(None, (create_tx['transaction']['outputs'][1], ),
                       (packed_sig, ), clear_m, hidden_m)
        end_time = time.time()
        times.append((end_time - start_time) * 1000)
    mean = numpy.mean(times)
    sd = numpy.std(times)
    print "[g] verify tx\t{:.10f}\t\t{:.10f}\t{}".format(mean, sd, RUNS)

    # check
    verify_tx = coconut.verify(None,
                               (create_tx['transaction']['outputs'][1], ),
                               (packed_sig, ), clear_m, hidden_m)
    solution = transaction_to_solution(verify_tx)
    times = []
    for i in range(RUNS):
        start_time = time.time()
        coconut.contract.checkers['verify'](
            solution['inputs'],
            solution['referenceInputs'],
            solution['parameters'],
            solution['outputs'],
            solution['returns'],
            solution['dependencies'],
        )
        end_time = time.time()
        times.append((end_time - start_time) * 1000)
    mean = numpy.mean(times)
    sd = numpy.std(times)
    print "[c] verify tx\t{:.10f}\t\t{:.10f}\t{}".format(mean, sd, RUNS)
    '''
from chainspacecontract.examples.coconut_lib import verify, show_mix_sign, mix_verify, prepare_mix_sign, mix_sign
from bplib.bp import BpGroup, G2Elem

# crypto parameters
q = 1  # max number of messages
t, n = 2, 2  # threshold and total numbero of authorities
callback = 'hello.init'  # id of the callback contract
params = setup(q)  # system's parameters
clear_m = []  # messages for plaintext signature
hidden_m = [1]  # messages for blind signature
(priv, pub) = elgamal_keygen(params)  # user's key pair
(sk, vk, vvk) = mix_ttp_th_keygen(params, t, n, q)  # signers keys

# some crypto
# ------------------------------------
packed_vvk = (pack(vvk[0]), pack(vvk[1]), [pack(vvk[2][i]) for i in range(q)])
instance = {
    'type': 'CoCoInstance',
    'q': q,
    't': t,
    'n': n,
    'callback': callback,
    'verifier': packed_vvk
}
hasher = sha256()
hasher.update(dumps(instance).encode('utf8'))
m = Bn.from_binary(hasher.digest())
sigs = [mix_sign(params, ski, None, [], [m]) for ski in sk]
auth_sig = aggregate_th_sign(params, sigs)
#print(mix_verify(params, vvk, None, sig, None, [m]))
# ------------------------------------
Пример #12
0
    def test_verify(self):
        with coconut_contract.test_service():

            ## create transactions
            # init
            init_transaction = coconut.init()
            token = init_transaction['transaction']['outputs'][0]
            # create instance
            create_transaction = coconut.create(
                (token,),
                None,
                None,
                q,
                t,
                n,
                callback, 
                vvk,
                sig
            )
            instance = create_transaction['transaction']['outputs'][1]
            # request
            request_transaction = coconut.request(
                (instance,),
                None,
                None,
                clear_m, 
                hidden_m, 
                pub
            )
            old_request = request_transaction['transaction']['outputs'][1]

            # issue t signatures
            for i in range(t):
                transaction = coconut.issue(
                    (old_request,),
                    None,
                    None,
                    sk[i],
                    i
                )
                old_request = transaction['transaction']['outputs'][0]

            # some crypto
            # ------------------------------------
            packet = loads(old_request)['sigs']
            (indexes, packed_enc_sigs) = zip(*packet)
            (h, packed_enc_epsilon) = zip(*packed_enc_sigs)
            enc_epsilon = [(unpackG1(params,x[0]), unpackG1(params,x[1])) for x in packed_enc_epsilon]
            dec_sigs = [(unpackG1(params,h[0]), elgamal_dec(params, priv, enc)) for enc in enc_epsilon]
            aggr = aggregate_th_sign(params, dec_sigs)
            aggr = randomize(params, aggr)
            packed_sig = (pack(aggr[0]),pack(aggr[1]))
            # ------------------------------------

            # verify signature
            start_time = time.time()
            transaction = coconut.verify(
                None,
                (instance,),
                (packed_sig,),
                clear_m,
                hidden_m
            )
            end_time = time.time(); print((end_time-start_time)*1000)

            ## submit t ransaction
            response = requests.post(
                'http://127.0.0.1:5000/' + coconut_contract.contract_name 
                + '/verify', json=transaction_to_solution(transaction)
            )
            self.assertTrue(response.json()['success'])

            print("\n\n=================== VERIFICATION ===================\n")
            print(transaction['transaction']['returns'][0])
            print("\n====================================================\n\n")