Esempio n. 1
0
def create_vote(inputs, reference_inputs, parameters, options, participants,
                tally_priv, tally_pub):

    # genrate param
    params = setup()
    pub = unpack(tally_pub)

    # encrypt initial score
    (a, b, k) = binencrypt(params, pub, 0)  # encryption of a zero
    c = (a, b)
    scores = [pack(c) for _ in loads(options)]

    # new vote object
    new_vote = {
        'type': 'VoteObject',
        'options': loads(options),
        'scores': scores,
        'participants': loads(participants),
        'tally_pub': tally_pub
    }

    # proof that all init values are zero
    proof_init = provezero(params, pub, c, unpack(tally_priv))

    # return
    return {
        'outputs': (inputs[0], dumps(new_vote)),
        'extra_parameters': {
            'proof_init': pack(proof_init)
        }
    }
Esempio n. 2
0
def add_reading(inputs, reference_inputs, parameters, meter_priv, reading,
                opening):

    # compute output
    old_meter = loads(inputs[0])
    new_meter = loads(inputs[0])

    # create commitement to the reading
    (G, g, (h0, _, _, _), _) = setup()
    commitment = loads(reading) * g + unpack(opening) * h0

    # update readings
    new_meter['readings'].append(pack(commitment))

    # hash message to sign
    hasher = sha256()
    hasher.update(dumps(old_meter).encode('utf8'))
    hasher.update(dumps(pack(commitment)).encode('utf8'))

    # sign message
    sig = do_ecdsa_sign(G, unpack(meter_priv), hasher.digest())

    # return
    return {
        'outputs': (dumps(new_meter), ),
        'extra_parameters': {
            'reading': pack(commitment),
            'signature': pack(sig)
        }
    }
Esempio n. 3
0
    def test_submit_bid(self):
        ##
        ## run service
        ##
        checker_service_process = Process(
            target=energy_bidding_contract.run_checker_service)
        checker_service_process.start()
        time.sleep(0.1)

        ##
        ## create transaction
        ##
        # generate crypto params
        G = setup()[0]
        (provider_priv, provider_pub) = key_gen(setup())

        # init
        init_transaction = energy_bidding.init()
        token = init_transaction['transaction']['outputs'][0]

        # create meter
        create_meter_transaction = energy_bidding.create_meter(
            (token, ),
            None,
            None,
            pack(provider_pub),
            'Some info about the meter.',
            dumps([5, 3, 5, 3, 5]),  # the tariffs
            dumps(764)  # billing period         
        )
        token = create_meter_transaction['transaction']['outputs'][0]
        meter = create_meter_transaction['transaction']['outputs'][1]

        # Submit bid
        transaction = energy_bidding.submit_bid((token, ), (meter, ),
                                                (dumps({
                                                    'type': 'EBBuy',
                                                    'energy': 10,
                                                    'price': 50
                                                }), ), pack(provider_priv))
        token = bid_transaction['transaction']['outputs'][0]
        bid = bid_transaction['transaction']['outputs'][1]
        print transaction

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

        ##
        ## stop service
        ##
        checker_service_process.terminate()
        checker_service_process.join()
Esempio n. 4
0
    def test_add_many_reading(self):
        ##
        ## run service
        ##
        checker_service_process = Process(
            target=smart_meter_contract.run_checker_service)
        checker_service_process.start()
        time.sleep(0.1)

        ##
        ## create transaction
        ##
        # generate crypto params
        G = setup()[0]
        (provider_priv, provider_pub) = key_gen(setup())

        # set init values
        tariffs = [5, 3, 5, 3, 5]
        readings = [10, 20, 30, 10, 50]
        openings = [G.order().random() for _ in tariffs]
        billing_period = 764

        # init
        init_transaction = smart_meter.init()
        token = init_transaction['transaction']['outputs'][0]

        # create meter
        create_meter_transaction = smart_meter.create_meter(
            (token, ), None, None,
            pack(provider_pub), 'Some info about the meter.', dumps(tariffs),
            dumps(billing_period))
        meter = create_meter_transaction['transaction']['outputs'][1]

        # add a readings
        transaction = {}
        input_obj = meter
        for i in range(0, len(tariffs)):
            transaction = smart_meter.add_reading((input_obj, ), None, None,
                                                  pack(provider_priv),
                                                  dumps(readings[i]),
                                                  pack(openings[i]))
            input_obj = transaction['transaction']['outputs'][0]

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

        ##
        ## stop service
        ##
        checker_service_process.terminate()
        checker_service_process.join()
Esempio n. 5
0
    def test_add_reading(self):
        ##
        ## run service
        ##
        checker_service_process = Process(
            target=smart_meter_contract.run_checker_service)
        checker_service_process.start()
        time.sleep(0.1)

        ##
        ## create transaction
        ##
        # generate crypto params
        G = setup()[0]
        (provider_priv, provider_pub) = key_gen(setup())

        # init
        init_transaction = smart_meter.init()
        token = init_transaction['transaction']['outputs'][0]

        # create meter
        create_meter_transaction = smart_meter.create_meter(
            (token, ),
            None,
            None,
            pack(provider_pub),
            'Some info about the meter.',
            dumps([5, 3, 5, 3, 5]),  # the tariffs
            dumps(764)  # billing period         
        )
        meter = create_meter_transaction['transaction']['outputs'][1]

        # add a reading
        transaction = smart_meter.add_reading(
            (meter, ),
            None,
            None,
            pack(provider_priv),
            dumps(10),  # the new reading 
            pack(G.order().random())  # the opening value
        )
        print transaction

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

        ##
        ## stop service
        ##
        checker_service_process.terminate()
        checker_service_process.join()
Esempio n. 6
0
    def test_many_auth_transfer(self):
        ##
        ## run service
        ##
        checker_service_process = Process(
            target=bank_authenticated_contract.run_checker_service)
        checker_service_process.start()
        time.sleep(0.1)

        ##
        ## create transaction
        ##
        # create alice's and bob public key
        num_transfers = 7
        transfer_amount = 1
        params = setup()
        (alice_priv, alice_pub) = key_gen(params)
        (bob_priv, bob_pub) = key_gen(params)

        # init
        init_transaction = bank_authenticated.init()['transaction']
        token = init_transaction['outputs'][0]

        # create alice's account
        create_alice_account_transaction = bank_authenticated.create_account(
            (token, ), None, None, pack(alice_pub))['transaction']
        token = create_alice_account_transaction['outputs'][0]
        alice_account = create_alice_account_transaction['outputs'][1]

        # create bob's account
        create_bob_account_transaction = bank_authenticated.create_account(
            (token, ), None, None, pack(bob_pub))['transaction']
        bob_account = create_bob_account_transaction['outputs'][1]

        # pack transaction
        transaction = {}
        input_obj = [alice_account, bob_account]
        for i in range(0, num_transfers):
            transaction_dict = bank_authenticated.auth_transfer(
                input_obj, None, [dumps(transfer_amount)], pack(alice_priv))
            input_obj = transaction_dict['transaction']['outputs']

        ##
        ## submit transaction
        ##
        response = requests.post(
            'http://127.0.0.1:5000/' +
            bank_authenticated_contract.contract_name + '/auth_transfer',
            json=transaction_to_solution(transaction_dict))
        self.assertTrue(response.json()['success'])

        ##
        ## stop service
        ##
        checker_service_process.terminate()
        checker_service_process.join()
Esempio n. 7
0
 def cast_csc_vote(self, client_pub):
     cast_csc_vote_txn = cast_csc_vote(
         (self.vote_slip, ),
         None,
         None,
         pack(self.priv),
         pack(client_pub),
     )
     vote_token = cast_csc_vote_txn['transaction']['outputs'][0]
     self.vote_slip = cast_csc_vote_txn['transaction']['outputs'][1]
     self.cs_client.process_transaction(cast_csc_vote_txn)
     return vote_token
Esempio n. 8
0
def add_signature(inputs, reference_inputs, parameters, added_signature):

    old_signature = loads(inputs[0])
    new_signature = loads(inputs[0])
    added_signature = loads(added_signature)

    params = setup()
    tally_pub = unpack(old_signature['tally_pub'])

    # encrypt signatures & proofs to build
    enc_added_signatures = []  # encrypted signatures
    proof_bin = [
    ]  # signatures are binary, well-formed, and the prover know the signature's value
    sum_a, sum_b, sum_k = (0, 0, 0)  # sum of signatures equals 1

    # loop over signatures
    for i in range(0, len(added_signature)):
        # encrypt added signature
        (a, b, k) = binencrypt(params, tally_pub, added_signature[i])
        c = (a, b)
        enc_added_signatures.append(pack(c))

        # update new scores
        new_c = add(unpack(old_signature['scores'][i]), c)
        new_signature['scores'][i] = pack(new_c)

        # construct proof of binary
        tmp1 = provebin(params, tally_pub, (a, b), k, added_signature[i])
        proof_bin.append(pack(tmp1))

        # update sum of signature
        if i == 0:
            sum_a, sum_b, sum_k = (a, b, k)
        else:
            sum_c = (sum_a, sum_b)
            sum_a, sum_b, sum_k = add_side(sum_c, c, sum_k, k)

    # build proof that sum of signatures equals 1
    sum_c = (sum_a, sum_b)
    proof_sum = proveone(params, tally_pub, sum_c, sum_k)

    # compute signature
    (G, _, _, _) = params
    hasher = sha256()
    hasher.update(dumps(old_signature).encode('utf8'))
    hasher.update(dumps(enc_added_signatures).encode('utf8'))

    # return
    return {
        'outputs': (dumps(new_signature), ),
        'extra_parameters':
        (dumps(enc_added_signatures), dumps(proof_bin), pack(proof_sum))
    }
Esempio n. 9
0
    def test_create_vote(self):
        ##
        ## run service
        ##
        checker_service_process = Process(target=vote_contract.run_checker_service)
        checker_service_process.start()
        time.sleep(0.1)

        ##
        ## create transaction
        ##
        # create keys
        params = setup()
        (tally_priv, tally_pub)  = key_gen(params)
        (_, voter1_pub) = key_gen(params)
        (_, voter2_pub) = key_gen(params)
        (_, voter3_pub) = key_gen(params)

        # set up options, particpants, and tally's key
        options      = ['alice', 'bob']
        participants = [pack(voter1_pub), pack(voter2_pub), pack(voter3_pub)]

        # init
        init_transaction = vote.init()
        token = init_transaction['transaction']['outputs'][0]

        # initialise vote (all votes are zero)
        transaction = vote.create_vote(
            (token, ),
            None,
            None,
            dumps(options),
            dumps(participants),
            pack(tally_priv),
            pack(tally_pub)
        )
        print transaction

        ##
        ## submit transaction
        ##
        response = requests.post(
            'http://127.0.0.1:5000/' + vote_contract.contract_name + '/create_vote', json=transaction_to_solution(transaction)
        )
        print response.json()
        self.assertTrue(response.json()['success'])

        ##
        ## stop service
        ##
        checker_service_process.terminate()
        checker_service_process.join()
Esempio n. 10
0
 def create_centra_client(self, token):
     if type(token) is not tuple:
         token = (token, )
     create_centra_client_txn = create_centra_client(
         token,
         None,
         (pack(self.pub), ),
         pack(self.priv),
     )
     self.centra_client = create_centra_client_txn['transaction'][
         'outputs'][0]
     self.vote_slip = create_centra_client_txn['transaction']['outputs'][1]
     self.ebtoken = create_centra_client_txn['transaction']['outputs'][2]
     self.cs_client.process_transaction(create_centra_client_txn)
Esempio n. 11
0
 def cast_lrep_vote(self, rep_pub, queue=None):
     cast_lrep_vote_txn = cast_lrep_vote(
         (self.vote_slip, ),
         None,
         None,
         pack(self.priv),
         pack(rep_pub),
     )
     vote_token = cast_lrep_vote_txn['transaction']['outputs'][0]
     self.vote_slip = cast_lrep_vote_txn['transaction']['outputs'][1]
     self.cs_client.process_transaction(cast_lrep_vote_txn)
     if queue:
         queue.put(vote_token)
     return vote_token
Esempio n. 12
0
def compute_bill(inputs, reference_inputs, parameters, readings, openings,
                 tariffs):

    # get meter
    meter = loads(inputs[0])

    # compute total bill
    G = setup()[0]
    total_bill = sum(r * t for r, t in zip(loads(readings), loads(tariffs)))
    sum_openings = sum(
        o * t for o, t in zip(unpack(openings), loads(tariffs))) % G.order()

    # new bill
    bill = {
        'type': 'SMBill',
        'info': meter['info'],
        'total_bill': total_bill,
        'billing_period': meter['billing_period'],
        'tariffs': meter['tariffs']
    }

    # return
    return {
        'outputs': (dumps(bill), ),
        'extra_parameters': {
            'total_bill': dumps(total_bill),
            'sum_openings': pack(sum_openings),
        }
    }
Esempio n. 13
0
 def create_lrep_client(self,
                        host='127.0.0.1',
                        lrep_port=5000,
                        vote_tokens=None):
     self.lrep_cs_client = ChainspaceClient(host=host,
                                            port=lrep_port,
                                            max_wait=lrep_port - 5000)
     create_lrep_client_txn = create_lrep_client(
         vote_tokens,
         None,
         (pack(self.pub), ),
         pack(self.priv),
     )
     self.vote_slip = create_lrep_client_txn['transaction']['outputs'][1]
     self.lrep_client = create_lrep_client_txn['transaction']['outputs'][0]
     self.lrep_cs_client.process_transaction(create_lrep_client_txn)
Esempio n. 14
0
def transfer(inputs, reference_inputs, parameters, *args):
    # compute outputs
    amount = loads(parameters[0])
    new_from_account = loads(inputs[0])
    new_to_account = loads(inputs[1])
    new_from_account["balance"] -= amount
    new_to_account["balance"] += amount

    if loads(inputs[0])['callback'] == None:
        hasher = sha256()
        hasher.update(dumps(inputs).encode('utf8'))
        hasher.update(dumps(parameters[0]).encode('utf8'))
        G = setup()[0]
        priv = args[0]
        sig = do_ecdsa_sign(G, priv, hasher.digest())
    else:
        # 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()
        sig = setup()[0].order().random() # dump

    # return
    return {
        'outputs': (dumps(new_from_account), dumps(new_to_account)),
        'extra_parameters' : (pack(sig),)
    }
Esempio n. 15
0
    def accept_bids(self):
        time.sleep(DELTA)
        bid_proofs = self.lrep_cs_client.get_objects({
            'location':
            loads(self.lrep_client)['location'],
            'type':
            'BidProof'
        })
        bidders = {}
        for bid in bid_proofs:
            bid = loads(bid)
            bidders[str(bid['quantity_sig'])] = True

        time.sleep(2 * DELTA)
        buy_bids = self.lrep_cs_client.get_objects({
            'location':
            loads(self.lrep_client)['location'],
            'type':
            'EBBuy'
        })
        sell_bids = self.lrep_cs_client.get_objects({
            'location':
            loads(self.lrep_client)['location'],
            'type':
            'EBSell'
        })
        # process bid
        accepted_bids = []
        for bid in buy_bids:
            if not bidders.has_key(loads(bid)['quantity_sig']):
                continue
            accepted_bids.append(bid)
        for bid in sell_bids:
            if not bidders.has_key(loads(bid)['quantity_sig']):
                continue
            accepted_bids.append(bid)
        if len(accepted_bids) == 0:
            return None
        accept_bids_txn = accept_bids(
            tuple(accepted_bids),
            None,
            (pack(self.pub), ),
            pack(self.priv),
        )
        bid_accept = accept_bids_txn['transaction']['outputs'][0]
        self.lrep_cs_client.process_transaction(accept_bids_txn)
        return bid_accept
Esempio n. 16
0
def add_signature_checker(inputs, reference_inputs, parameters, outputs,
                          returns, dependencies):
    try:

        print "CHECKING - parameters " + str(parameters)

        # retrieve petition
        old_signature = loads(inputs[0])
        new_signature = loads(outputs[0])
        num_options = len(old_signature['options'])

        # check format
        if len(inputs) != 1 or len(reference_inputs) != 0 or len(
                outputs) != 1 or len(returns) != 0:
            return False
        if num_options != len(new_signature['scores']) or num_options != len(
                new_signature['scores']):
            return False
        if old_signature['tally_pub'] != new_signature['tally_pub']:
            return False

        print "CHECKING - tokens"
        if new_signature['type'] != 'PetitionEncObject':
            return False

        print "CHECKING - Generate params"
        # generate params, retrieve tally's public key and the parameters
        params = setup()
        tally_pub = unpack(old_signature['tally_pub'])
        added_signature = loads(parameters[0])
        proof_bin = loads(parameters[1])
        proof_sum = unpack(parameters[2])

        print "CHECKING - verify proofs of binary (Signatures have to be bin values)"
        for i in range(0, num_options):
            if not verifybin(params, tally_pub, unpack(added_signature[i]),
                             unpack(proof_bin[i])):
                return False

        print "CHECKING - verify proof of sum of signatures (sum of signatures has to be 1)"
        sum_a, sum_b = unpack(added_signature[-1])
        sum_c = (sum_a, sum_b)
        for i in range(0, num_options - 1):
            sum_c = add(sum_c, unpack(added_signature[i]))
        if not verifyone(params, tally_pub, sum_c, proof_sum):
            return False

        print "CHECKING - verify that output == input + signature"
        for i in range(0, num_options):
            tmp_c = add(unpack(old_signature['scores'][i]),
                        unpack(added_signature[i]))
            if not new_signature['scores'][i] == pack(tmp_c):
                return False

        # otherwise
        return True

    except (KeyError, Exception):
        return False
Esempio n. 17
0
def generate_sig(priv, msg="proof"):
    hasher = sha256()
    hasher.update(msg)

    # sign message
    G = setup()[0]
    sig = do_ecdsa_sign(G, unpack(priv), hasher.digest())
    return pack(sig)
Esempio n. 18
0
    def __create_petition(self, petition_token):
        inputs = (petition_token, )

        votes = ['YES', 'NO']
        gender = ['ANY', 'M', 'F', 'U']
        age = ['ANY', '0-19', '20-29', '30-39', '40+']
        options = [
            "%s-%s-%s" % (v, g, a) for v in votes for g in gender for a in age
        ]
        options = json.dumps(options)

        transaction = self.contract.create_petition(inputs,
                                                    self.reference_inputs,
                                                    self.parameters, options,
                                                    pack(self.private_key),
                                                    pack(self.public_key))
        self.chainspace_repository.process_transaction(transaction)
        return transaction['transaction']['outputs'][1]
Esempio n. 19
0
def tally(inputs, reference_inputs, parameters, tally_priv, tally_pub):

    # retrieve last vote
    vote = loads(inputs[0])

    # generate params & retrieve tally's public key
    params = setup()
    table = make_table(params)
    (G, _, (h0, _, _, _), _) = params

    # decrypt aggregated results
    outcome = []
    for item in vote['scores']:
        outcome.append(dec(params, table, unpack(tally_priv), unpack(item)))

    # proof of decryption
    proof_dec = []
    for i in range(0, len(vote['scores'])):
        a, b = unpack(vote['scores'][i])
        ciphertext = (a, b - outcome[i] * h0)
        tmp = provezero(params, unpack(tally_pub), ciphertext,
                        unpack(tally_priv))
        proof_dec.append(pack(tmp))

    # signature
    hasher = sha256()
    hasher.update(dumps(vote).encode('utf8'))
    hasher.update(dumps(outcome).encode('utf8'))
    sig = do_ecdsa_sign(G, unpack(tally_priv), hasher.digest())

    # pack result
    result = {'type': 'VoteResult', 'outcome': outcome}

    # return
    return {
        'outputs': (dumps(result), ),
        'extra_parameters': {
            'proof_dec': dumps(proof_dec),
            'signature': pack(sig)
        }
    }
Esempio n. 20
0
    def test_create_vote(self):

        ##
        ## init
        ##
        transaction = vote.init()
        response = requests.post('http://127.0.0.1:' + port + '/api/' +
                                 version + '/transaction/process',
                                 json=transaction)
        self.assertTrue(response.json()['success'])

        ##
        ## create transaction
        ##
        # create keys
        params = setup()
        (tally_priv, tally_pub) = key_gen(params)
        (_, voter1_pub) = key_gen(params)
        (_, voter2_pub) = key_gen(params)
        (_, voter3_pub) = key_gen(params)

        # set up options, particpants, and tally's key
        options = ['alice', 'bob']
        participants = [pack(voter1_pub), pack(voter2_pub), pack(voter3_pub)]

        # init
        init_transaction = vote.init()
        token = init_transaction['transaction']['outputs'][0]

        # initialise vote (all votes are zero)
        transaction = vote.create_vote((token, ), None, None, dumps(options),
                                       dumps(participants), pack(tally_priv),
                                       pack(tally_pub))

        ##
        ## submit transaction
        ##
        response = requests.post('http://127.0.0.1:' + port + '/api/' +
                                 version + '/transaction/process',
                                 json=transaction)
        self.assertTrue(response.json()['success'])
Esempio n. 21
0
    def get_results(self):
        inputs = [self.__get_chainspace_objects_of_last_transaction()[-1]]

        try:
            transaction = self.contract.tally(inputs, self.reference_inputs,
                                              self.parameters,
                                              pack(self.private_key),
                                              pack(self.public_key))
        except Exception as err:
            if str(err) == "'scores'":
                raise TallyClosedPetitionException()
            raise

        self.chainspace_repository.process_transaction(transaction)

        outcome = json.loads(
            transaction['transaction']['outputs'][0])['outcome']

        result_yes = reduce((lambda x, y: x + y), outcome[:len(outcome) / 2])
        result_no = reduce((lambda x, y: x + y), outcome[len(outcome) / 2:])

        return [result_yes, result_no]
Esempio n. 22
0
def create_account(inputs, reference_inputs, parameters, pub, callback):

    # new account
    new_account = {
        'type' : 'BankAccount', 
        'pub' : pack(pub), 
        'balance' : 10,
        'callback' : callback
    }

    # return
    return {
        'outputs': (inputs[0], dumps(new_account))
    }
Esempio n. 23
0
    def test_create_account(self):
        
        ## create transaction
        transaction = bank_authenticated.init()
        
        ## submit transaction
        response = requests.post('http://127.0.0.1:' +port+ '/api/' +version+ '/transaction/process', json=transaction)
        #print response.json()
        self.assertTrue(response.json()['success'])


        ## create transaction
        transaction = bank_authenticated.init()

        ## submit transaction
        response = requests.post(
            'http://127.0.0.1:' +port+ '/api/' +version+ '/transaction/process', json=transaction
        )
        #print response.json()
        self.assertTrue(response.json()['success'])

        

        ##
        ## create transaction
        ##
        # create alice's public key
        (_, alice_pub) = key_gen(setup())

        # init
        init_transaction = bank_authenticated.init()['transaction']
        token = init_transaction['outputs'][0]

        # create bank account
        transaction = bank_authenticated.create_account(
            (token,),
            None,
            None,
            pack(alice_pub)
        )

        ##
        ## submit transaction
        ##
        response = requests.post(
            'http://127.0.0.1:' +port+ '/api/' +version+ '/transaction/process', json=transaction
        )
        #print response.json()
        self.assertTrue(response.json()['success'])
Esempio n. 24
0
    def test_create_meter(self):
        ##
        ## run service
        ##
        checker_service_process = Process(
            target=energy_bidding_contract.run_checker_service)
        checker_service_process.start()
        time.sleep(0.1)

        ##
        ## create transaction
        ##
        # create provider's public key
        (_, provider_pub) = key_gen(setup())

        # init
        init_transaction = energy_bidding.init()
        token = init_transaction['transaction']['outputs'][0]

        # create meter
        transaction = energy_bidding.create_meter(
            (token, ),
            None,
            None,
            pack(provider_pub),
            'Some info about the meter.',  # some info about the meter
            dumps([5, 3, 5, 3, 5]),  # the tariffs 
            dumps(764)  # the billing period
        )
        print transaction

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

        ##
        ## stop service
        ##
        checker_service_process.terminate()
        checker_service_process.join()
Esempio n. 25
0
    def test_create_account(self):
        ##
        ## run service
        ##
        checker_service_process = Process(
            target=bank_authenticated_contract.run_checker_service)
        checker_service_process.start()
        time.sleep(0.1)

        ##
        ## create transaction
        ##
        # create alice's public key
        (_, alice_pub) = key_gen(setup())

        # init
        init_transaction = bank_authenticated.init()['transaction']
        token = init_transaction['outputs'][0]

        # create bank account
        transaction_dict = bank_authenticated.create_account((token, ), None,
                                                             None,
                                                             pack(alice_pub))

        ##
        ## submit transaction
        ##
        response = requests.post(
            'http://127.0.0.1:5000/' +
            bank_authenticated_contract.contract_name + '/create_account',
            json=transaction_to_solution(transaction_dict))
        self.assertTrue(response.json()['success'])

        ##
        ## stop service
        ##
        checker_service_process.terminate()
        checker_service_process.join()
    def test_create_meter(self):
        ##
        ## init
        ##
        transaction = smart_meter.init()
        response = requests.post('http://127.0.0.1:' + port + '/api/' +
                                 version + '/transaction/process',
                                 json=transaction)
        self.assertTrue(response.json()['success'])

        ##
        ## create transaction
        ##
        # create provider's public key
        (_, provider_pub) = key_gen(setup())

        # init
        init_transaction = smart_meter.init()
        token = init_transaction['transaction']['outputs'][0]

        # create meter
        transaction = smart_meter.create_meter(
            (token, ),
            None,
            None,
            pack(provider_pub),
            'Some info about the meter.',  # some info about the meter
            dumps([5, 3, 5, 3, 5]),  # the tariffs 
            dumps(764)  # the billing period
        )

        ##
        ## submit transaction
        ##
        response = requests.post('http://127.0.0.1:' + port + '/api/' +
                                 version + '/transaction/process',
                                 json=transaction)
        self.assertTrue(response.json()['success'])
Esempio n. 27
0
def submit_bid(inputs, reference_inputs, parameters, meter_priv):

    # Extract bid object from paramters
    bid = loads(parameters[0])
    smart_meter = loads(reference_inputs[0])
    token = loads(inputs[0])
    bid['pub'] = smart_meter['pub']
    # Create a hash digest of inputs and parameters
    hasher = sha256()
    hasher.update(dumps(token).encode('utf8'))
    hasher.update(dumps(smart_meter).encode('utf8'))
    hasher.update(dumps(bid).encode('utf8'))

    # sign message
    G = setup()[0]
    sig = do_ecdsa_sign(G, unpack(meter_priv), hasher.digest())
    # return
    return {
        'outputs': (inputs[0],dumps(bid)),
        'extra_parameters' : (
            pack(sig),
        )
    }
def auth_transfer(inputs, reference_inputs, parameters, priv):

    # compute outputs
    amount = loads(parameters[0])
    new_from_account = loads(inputs[0])
    new_to_account   = loads(inputs[1])
    new_from_account["balance"] -= amount
    new_to_account["balance"]   += amount

    # hash message to sign
    hasher = sha256()
    hasher.update(dumps(inputs).encode('utf8'))
    hasher.update(dumps(reference_inputs).encode('utf8'))
    hasher.update(dumps(parameters[0]).encode('utf8'))

    # sign message
    G = setup()[0]
    sig = do_ecdsa_sign(G, unpack(priv), hasher.digest())

    # return
    return {
        'outputs': (dumps(new_from_account), dumps(new_to_account)),
        'extra_parameters' : (pack(sig),)
    }
Esempio n. 29
0
 def submit_bid(self, bid_type, quantity):
     bid_proof_txn = submit_bid_proof((self.ebtoken, ), None, (bid_type, ),
                                      pack(self.priv), quantity)
     bid_proof = bid_proof_txn['transaction']['outputs'][0]
     self.ebtoken = bid_proof_txn['transaction']['outputs'][1]
     self.cs_client.process_transaction(bid_proof_txn)
Esempio n. 30
0
def main():
    ## get contract and init pint
    vote.contract._populate_empty_checkers()
    print "operation\t\tmean (s)\t\tsd (s)\t\truns"

    # ---------------------------------------------------------
    # get functions
    # ---------------------------------------------------------
    # params
    params = setup()
    (tally_priv, tally_pub) = key_gen(params)
    (voter1_priv, voter1_pub) = key_gen(params)
    options = ['alice', 'bob']
    participants = [pack(voter1_pub)]

    # init
    init_tx = vote.init()
    token = init_tx['transaction']['outputs'][0]

    # create vote
    create_vote_tx = vote.create_vote((token, ), None, None, dumps(options),
                                      dumps(participants), pack(tally_priv),
                                      pack(tally_pub))
    vote_obj = create_vote_tx['transaction']['outputs'][1]

    # add vote
    add_vote_tx = vote.add_vote((vote_obj, ), None, None, dumps([1]),
                                pack(voter1_priv), pack(voter1_pub))

    # tally
    last_vote_obj = add_vote_tx['transaction']['outputs'][0]
    tally_tx = vote.tally((last_vote_obj, ), None, None, pack(tally_priv),
                          pack(tally_pub))

    # ---------------------------------------------------------
    # test create_vote
    # ---------------------------------------------------------
    # [gen]
    tester(RUNS, "create_vote [g]", vote.create_vote, (token, ), None, None,
           dumps(options), dumps(participants), pack(tally_priv),
           pack(tally_pub))
    # [check]
    solution = transaction_to_solution(create_vote_tx)
    tester(
        RUNS,
        "create_vote [c]",
        vote.contract.checkers['create_vote'],
        solution['inputs'],
        solution['referenceInputs'],
        solution['parameters'],
        solution['outputs'],
        solution['returns'],
        solution['dependencies'],
    )

    # ---------------------------------------------------------
    # test add_vote
    # ---------------------------------------------------------
    # [gen]
    tester(RUNS, "add_vote [g]\t", vote.add_vote, (vote_obj, ), None, None,
           dumps([1, 0]), pack(voter1_priv), pack(voter1_pub))
    # [check]
    solution = transaction_to_solution(add_vote_tx)
    tester(
        RUNS,
        "add_vote [c]\t",
        vote.contract.checkers['add_vote'],
        solution['inputs'],
        solution['referenceInputs'],
        solution['parameters'],
        solution['outputs'],
        solution['returns'],
        solution['dependencies'],
    )

    # ---------------------------------------------------------
    # test compute bill
    # ---------------------------------------------------------
    # [gen]
    tester(RUNS, "tally [g]\t", vote.tally, (last_vote_obj, ), None, None,
           pack(tally_priv), pack(tally_pub))
    # [check]
    solution = transaction_to_solution(tally_tx)
    tester(
        RUNS,
        "tally [c]\t",
        vote.contract.checkers['tally'],
        solution['inputs'],
        solution['referenceInputs'],
        solution['parameters'],
        solution['outputs'],
        solution['returns'],
        solution['dependencies'],
    )