def setUp(self) -> None: self.source_identity = Entity() self.multi_sig_identity = Entity() self.multi_sig_board = [Entity() for _ in range(4)] self.target_identity = Entity() self.tx = TokenTxFactory.transfer(self.source_identity, Identity(self.target_identity), 500, 500, [self.source_identity]) self.mstx = TokenTxFactory.transfer(self.multi_sig_identity, Identity(self.target_identity), 500, 500, self.multi_sig_board)
def main(): # create the APIs txs = TransactionApi(HOST, PORT) tokens = TokenApi(HOST, PORT) # generate a random identity identity = Identity() print('Balance Before:', tokens.balance(identity.public_key)) # create and send the transaction to the ledger capturing the tx hash tx = tokens.wealth(identity.private_key_bytes, 1000) # wait while we poll to see when this transaction has been completed prev_status = None while True: status = txs.status(tx) # print the changes in tx status if status != prev_status: print('Current Status:', status) prev_status = status # exit the wait loop once the transaction has been executed if status == "Executed": break time.sleep(1) # check the balance now print('Balance After:', tokens.balance(identity.public_key))
def main(): args = parse_commandline() # build up the stake information individual_balance = TOTAL_SUPPLY // len(args.addresses) individual_stake = (min(args.stake_percentage, 100) * individual_balance) // 100 max_cabinet = 0 if not args.max_cabinet: max_cabinet = len(args.addresses) else: max_cabinet = args.max_cabinet # build up the configuration for all the stakers members = [] for address in args.addresses: members.append(( Identity.from_base64(address), individual_balance, individual_stake, )) # create the genesis configuration genesis = GenesisFile(members, max_cabinet, args.when_start, args.block_interval) # flush the file to disk genesis.dump_to_file(args.output, args.no_formatting)
def __init__(self, private_key_path: Optional[str] = None): """ Instantiate a fetchai crypto object. :param private_key_path: the private key path of the agent """ super().__init__(private_key_path=private_key_path) self._address = str(FetchaiAddress(Identity.from_hex(self.public_key)))
def decode(stream: io.BytesIO) -> Identity: header = stream.read(1)[0] if UNCOMPRESSED_SCEP256K1_PUBLIC_KEY == header: public_key_bytes = stream.read(UNCOMPRESSED_SCEP256K1_PUBLIC_KEY_LEN) return Identity(public_key_bytes) else: raise RuntimeError('Unsupported identity type')
def get_address_from_public_key(cls, public_key: str) -> Address: """ Get the address from the public key. :param public_key: the public key :return: str """ identity = Identity.from_hex(public_key) return Address(identity)
def __init__(self, private_key_path: Optional[str] = None): """ Instantiate a fetchai crypto object. :param private_key_path: the private key path of the agent """ self._entity = (self._generate_private_key() if private_key_path is None else self._load_private_key_from_path(private_key_path)) self._address = str(Address(Identity.from_hex(self.public_key)))
def get_address_from_public_key(public_key: str) -> Address: """ Get the address from the public key. :param public_key: the public key :return: str """ identity = Identity.from_hex(public_key) address = str(FetchaiAddress(identity)) return address
def sign_transaction(self, transaction: Any) -> Any: """ Sign a transaction in bytes string form. :param transaction: the transaction to be signed :return: signed transaction """ identity = Identity.from_hex(self.public_key) transaction.add_signer(identity) transaction.sign(self.entity) return transaction
def __init__(self, public_key: str, oef_addr: str, oef_port: int = 3333): super().__init__(public_key, oef_addr, oef_port) self.identity = Identity() self.txs = TransactionApi("ledger.economicagents.com" , 80) self.tokens = TokenApi("ledger.economicagents.com" , 80) print('Submitting wealth creation...') self.wait_for_tx(self.txs, self.tokens.wealth(self.identity.private_key_bytes, 1000)) self.cost = 0 self.pending_cfp = 0 self.received_proposals = [] self.received_declines = 0
def main(): # create the APIs txs = TransactionApi(HOST, PORT) tokens = TokenApi(HOST, PORT) # generate a random identity identity1 = Identity() identity2 = Identity() # create the balance print('Submitting wealth creation...') wait_for_tx(txs, tokens.wealth(identity1.private_key_bytes, 1000)) # submit and wait for the transfer to be complete print('Submitting transfer...') wait_for_tx( txs, tokens.transfer(identity1.private_key_bytes, identity2.public_key_bytes, 250)) print('Balance 1:', tokens.balance(identity1.public_key)) print('Balance 2:', tokens.balance(identity2.public_key))
def __init__(self, public_key: str, oef_addr: str, db_source: str, oef_port: int = 3333): super().__init__(public_key, oef_addr, oef_port) self.scheme = {} self.scheme['country'] = None self.scheme['city'] = None self.description = None self.db = db_communication.Db_communication(db_source) self.identity = Identity() self.tokens = TokenApi("ledger.economicagents.com", 80) self.balance = self.tokens.balance(self.identity.public_key) self.fetched_data = None self.price_per_row = 0.02 self.totalPrice = 0
def main(): args = parse_commandline() max_cabinet = len(args.addresses) # build up the configuration for all the stakers accounts = [] stakers = [] for n, address in enumerate(args.addresses): identity = Identity.from_base64(address) if n == 0: balance = TOTAL_SUPPLY - (max_cabinet * DEFAULT_STAKE) else: balance = 0 accounts.append({ 'address': str(Address(identity)), 'balance': balance, 'stake': DEFAULT_STAKE, }) stakers.append({ 'identity': identity.public_key, 'amount': DEFAULT_STAKE * TEN_ZERO, }) genesis = { 'version': 4, 'accounts': accounts, 'consensus': { 'aeonOffset': 100, 'aeonPeriodicity': 25, 'cabinetSize': max_cabinet, 'entropyRunahead': 2, 'minimumStake': DEFAULT_STAKE, 'startTime': int(time.time()) + args.when_start, 'stakers': stakers, } } # create the genesis configuration with open(args.output, 'w') as genesis_file: json.dump(genesis, genesis_file)
from fetchai.ledger.bitvector import BitVector from fetchai.ledger.crypto import Entity, Identity from fetchai.ledger.serialisation import encode_transaction, decode_transaction, bytearray, sha256_hash from fetchai.ledger.transaction import Transaction _PRIVATE_KEYS = ( '1411d53f88e736eac7872430dbe5b55ac28c17a3e648c388e0bd1b161ab04427', '3436c184890d498b25bc2b5cb0afb6bad67379ebd778eae1de40b6e0f0763825', '4a56a19355f934174f6388b3c80598abb151af79c23d5a7af45a13357fb71253', 'f9d67ec139eb7a1cb1f627357995847392035c1e633e8530de5ab5d04c6e9c33', '80f0e1c69e5f1216f32647c20d744c358e0894ebc855998159017a5acda208ba', ) ENTITIES = [Entity.from_hex(x) for x in _PRIVATE_KEYS] IDENTITIES = [Identity(x) for x in ENTITIES] def _calculate_integer_stream_size(length: int) -> int: if length < 0x80: return 1 elif length < 0x100: return 2 elif length < 0x1000: return 4 else: return 8 class TransactionSerialisation(unittest.TestCase): EXPECTED_SIGNATURE_BYTE_LEN = 64
def test_compare(self): tx = TokenTxFactory.transfer(self.source_identity, Identity(self.target_identity), 500, 500, [self.source_identity]) # encode the transaction so that copies can be made afterwards encoded_tx = tx.encode_partial() # Test comparison fails if any data changed _, tx2 = Transaction.decode_partial(encoded_tx) tx2.from_address = Entity() self.assertNotEqual(tx, tx2) _, tx2 = Transaction.decode_partial(encoded_tx) tx2.add_transfer(Entity(), 500) self.assertNotEqual(tx, tx2) _, tx2 = Transaction.decode_partial(encoded_tx) tx2.valid_from = 999 self.assertNotEqual(tx, tx2) _, tx2 = Transaction.decode_partial(encoded_tx) tx2.valid_until = 999 self.assertNotEqual(tx, tx2) _, tx2 = Transaction.decode_partial(encoded_tx) tx2.charge_rate = 999 self.assertNotEqual(tx, tx2) _, tx2 = Transaction.decode_partial(encoded_tx) tx2.charge_limit = 999 self.assertNotEqual(tx, tx2) _, tx2 = Transaction.decode_partial(encoded_tx) tx2._contract_address = Address(Entity()) self.assertNotEqual(tx, tx2) _, tx2 = Transaction.decode_partial(encoded_tx) tx2._chain_code = 'changed' self.assertNotEqual(tx, tx2) _, tx2 = Transaction.decode_partial(encoded_tx) tx2._action = 'changed' self.assertNotEqual(tx, tx2) _, tx2 = Transaction.decode_partial(encoded_tx) tx2._shard_mask = BitVector(size=16) self.assertNotEqual(tx, tx2) _, tx2 = Transaction.decode_partial(encoded_tx) tx2.data = b'changed' self.assertNotEqual(tx, tx2) _, tx2 = Transaction.decode_partial(encoded_tx) tx2.add_signer(Entity()) self.assertNotEqual(tx, tx2) _, tx2 = Transaction.decode_partial(encoded_tx) tx2._counter = 999 self.assertNotEqual(tx, tx2) _, tx2 = Transaction.decode_partial(encoded_tx) tx2._is_synergetic = True self.assertNotEqual(tx, tx2)
def main(): # ************************************* # ***** Working with Private Keys ***** # ************************************* # Create a new (random) private key by instantiating an entity object entity = Entity() # Return the private key as a hexadecimal string private_key_hex = entity.private_key_hex print('\nThe new private key in hexadecimal is:', private_key_hex) # Return the private key in bytes private_key_bytes = entity.private_key_bytes # Get the public key associated with the private key of an Entity object print('\nThe associated public key in hexadecimal is: ', entity.public_key_hex) # Construct an Entity from bytes entity2 = Entity(private_key_bytes) # Construct an entity from a private key stored as a base64 string entity3 = entity.from_base64(base64.b64encode(private_key_bytes).decode()) assert entity.private_key_hex == entity3.private_key_hex, 'Private keys should match\n' # ************************************* # ***** Serializing Private Keys ****** # ************************************* # serialize to JSON with AES serialized = entity.dumps(PASSWORD) print('\nThis serializes to the the following encrypted JSON string :\n', serialized) # Re-create an entity from an encrypted JSON string entity4 = entity.loads(serialized, PASSWORD) print( '\nWhich can be de-serialized to an entity containing the following hex private key:', entity4.private_key_hex) # Check if a password is strong enough to be accepted by our serialization functionality. # A password must contain 14 chars or more, with one or more uppercase, lowercase, numeric and a one or more special char strong = 'is strong enough' if Entity.is_strong_password( PASSWORD) else 'is not strong enough' print( '\nOur example password: {} upon testing {} to be used with our serialization functionality\n' .format(PASSWORD, strong)) # We can also encrypt a password from the terminal using our prompt functionality. with open(ENCRYPTED_KEY_FP, 'w') as private_key_file: entity.prompt_dump(private_key_file) private_key_file.close() print( "\nSuccess! Private key, encrypted with the password has been saved in examples." ) print( "\nUse the same password as just before to reload the entity saved in file\n" ) # Load private key from the terminal using our prompt functionality. with open(ENCRYPTED_KEY_FP, 'r') as private_key_file: loaded_entity = entity.prompt_load(private_key_file) if loaded_entity.public_key_hex == entity.public_key_hex: print('\nLoaded public/private key pair match, saved in file: ' + ENCRYPTED_KEY_FP) # ************************************* # ***** Working with Public keys ****** # ************************************* # Identity represents only a public key; where an entity objects represent a public/private key pair identity = Identity(entity) # Obtain public key as a string encoded in hexadecimal public_key_hex = identity.public_key_hex # Obtain public key as a string encoded in base64 public_key_base64 = identity.public_key # Obtain public key as a Buffer in Nodejs or a Uint8Array in the browser public_key_bytes = identity.public_key_bytes # Construct an identity from a hexadecimal-encoded public key ident2 = identity.from_hex(public_key_hex) # Construct an identity from a public key in base64 form ident3 = identity.from_base64(public_key_base64) print('An Identity object represents a public key\n') # Construct an identity from bytes ident4 = Identity(public_key_bytes) # ************************************* # ****** Working with Addresses ******* # ************************************* # Construct an address from an entity object address = Address(entity) # Construct an Address from a base58-encoded string: the public representation of an Address address2 = Address(ADDRESS) # Validate that a string is a valid address (verify checksum, valid base58-encoding and length) valid_address = 'is valid.' if Address.is_address( ADDRESS) else 'is not valid.' print('The Address generated from our entity {}'.format(valid_address)) # We can get the base 58 value of an address from an address object as follows: public_address = str(address) print('\nThe public base58 representation of this Address is:', public_address) # ************************************* # ****** Working with a Ledger ******** # ************************************* host = '127.0.0.1' port = 8000 # The LedgerApi class has some general methods for working with the Ledger and # builds and holds references to various subclasses which encompass different functions to be performed against # against a Ledger Nodes public API. # See the Bootstrap examples file for further details relating to finding a Host and Port of an available print("\nTrying to connect to a Ledger Node...") api = LedgerApi(host, port) print("\nConnected to Ledger Node at Host: {} and Port {} ...".format( host, port)) # The TokenApi Class has methods for staking in our Proof-of-stake model, checking the # balance of an account, and performing transfers of funds between accounts. # See the staking example file in this folder for further details. assert isinstance( api.tokens, TokenApi), "token property should be instance of TokenApi class" # We can get the nodes current block number block_number = api.tokens.current_block_number() print("\nThe current block number of the Ledger is:", block_number) # ContractsApi allows contract submition, and for contracts to be called on them # See the contracts example file in this folder for further details. assert isinstance( api.contracts, ContractsApi), "contracts property should be instance of ContractsApi" # TransactionApi contains methods to query the status of a submitted transaction # See the tx example file in this folder for further details. # TODO add tx example file, then delete this comment. assert isinstance( api.tx, TransactionApi), "tx property should be instance of TransactionApi"