Welcome to python-graphenelib’s documentation!

Graphene is a blockchain technology (i.e. software) that allows for fast transactions and decentralized trading of assets as well as customized on-chain smart contracts. Graphene itself is a platform to develop customized blockchains like BitShares, Steem or PeerPlays.

In practice, Graphene is only a concept implementation and does not directly have its own public blockchain.

The first public blockchain to use the Graphene technology is BitShares 2.0. However, this library should be able to interface with any other Graphene-based blockchain, too.

This library serves as a core library that bundles core features for these platforms, which have their own libraries build on top of this library.

Python-Graphene Libraries

Installation

Dependencies

$ sudo apt-get install libffi-dev libssl-dev python-dev

Install Library

Install with pip:

$ pip3 install graphenelib

Manual installation:

$ git clone https://github.com/xeroc/python-graphenlib/
$ cd python-graphenlib
$ python3 setup.py install --user

Upgrade

$ pip install --user --upgrade graphenelib

Classes

The library comes with a set of classes that are separated in different packages:

API Package

RPC Interface

Note

This is a low level class that can be used in combination with GrapheneClient

We now need to distinguish functionalities. If we want to only access the blockchain and do not want to perform on-chain operations like transfers or orders, we are fine to interface with any accessible witness node. In contrast, if we want to perform operations that modify the current blockchain state, e.g. construct and broadcast transactions, we are required to interface with a cli_wallet that has the required private keys imported. We here assume:

  • port: 8090 - witness
  • port: 8092 - wallet

Note

The witness API has a different instruction set than the wallet!

Definition
class grapheneapi.grapheneapi.GrapheneAPI(host, port, username='', password='')

Graphene JSON-HTTP-RPC API

This class serves as an abstraction layer for easy use of the Grapehene API.

Parameters:
  • host (str) – Host of the API server
  • port (int) – Port to connect to
  • username (str) – Username for Authentication (if required, defaults to “”)
  • password (str) – Password for Authentication (if required, defaults to “”)

All RPC commands of the Graphene client are exposed as methods in the class grapheneapi. Once an instance of GrapheneAPI is created with host, port, username, and password, e.g.,

from grapheneapi import GrapheneAPI
rpc = GrapheneAPI("localhost", 8092, "", "")

any call available to that port can be issued using the instance via the syntax rpc.*command*(parameters). Example:

rpc.info()

Note

A distinction has to be made whether the connection is made to a witness/full node which handles the blockchain and P2P network, or a cli-wallet that handles wallet related actions! The available commands differ drastically!

If you are connected to a wallet, you can simply initiate a transfer with:

res = client.transfer("sender","receiver","5", "USD", "memo", True);

Again, the witness node does not offer access to construct any transactions, and hence the calls available to the witness-rpc can be seen as read-only for the blockchain.

__getattr__(name)

Map all methods to RPC calls and pass through the arguments

rpcexec(payload)

Manual execute a command on API (internally used)

param str payload: The payload containing the request return: Servers answer to the query rtype: json raises RPCConnection: if no connction can be made raises UnauthorizedError: if the user is not authorized raise ValueError: if the API returns a non-JSON formated answer

It is not recommended to use this method directly, unless you know what you are doing. All calls available to the API will be wrapped to methods directly:

info -> grapheneapi.info()
WebsocketRPC

Note

This is a low level class that can be used in combination with GrapheneClient

This class allows to call API methods exposed by the witness node via websockets. It does not support notifications and is not run asynchronously.

Base Package

Base58 Class

This class serves as an abstraction layer to deal with base58 encoded strings and their corresponding hex and binary representation throughout the library.

Examples:
format(Base58("02b52e04a0acfe611a4b6963462aca94b6ae02b24e321eda86507661901adb49"),"wif")
repr(Base58("5HqUkGuo62BfcJU5vNhTXKJRXuUi9QSE6jp8C3uBJ2BVHtB8WSd"))

Output::

"5HqUkGuo62BfcJU5vNhTXKJRXuUi9QSE6jp8C3uBJ2BVHtB8WSd"
"02b52e04a0acfe611a4b6963462aca94b6ae02b24e321eda86507661901adb49"
Definitions
class graphenebase.base58.Base58(data, prefix=None)

Base58 base class

This class serves as an abstraction layer to deal with base58 encoded strings and their corresponding hex and binary representation throughout the library.

Parameters:
  • data (hex, wif, bip38 encrypted wif, base58 string) – Data to initialize object, e.g. pubkey data, address data, …
  • prefix (str) – Prefix to use for Address/PubKey strings (defaults to GPH)
Returns:

Base58 object initialized with data

Return type:

Base58

Raises:

ValueError – if data cannot be decoded

  • bytes(Base58): Returns the raw data
  • str(Base58): Returns the readable Base58CheckEncoded data.
  • repr(Base58): Gives the hex representation of the data.
  • format(Base58,_format) Formats the instance according to
    _format: * "wif": prefixed with 0x00. Yields a valid wif key * "bts": prefixed with BTS * etc.
Account Module
Address Class
class graphenebase.account.Address(address, prefix=None)

Address class

This class serves as an address representation for Public Keys.

Parameters:
  • address (str) – Base58 encoded address (defaults to None)
  • pubkey (str) – Base58 encoded pubkey (defaults to None)
  • prefix (str) – Network prefix (defaults to GPH)

Example:

Address("GPHFN9r6VYzBK8EKtMewfNbfiGCr56pHDBFi")
__bytes__()

Returns the raw content of the Base58CheckEncoded address

__format__(_format)

May be issued to get valid “MUSE”, “PLAY” or any other Graphene compatible address with corresponding prefix.

__repr__()

Gives the hex representation of the GrapheneBase58CheckEncoded Graphene address.

__str__()

Returns the readable Graphene address. This call is equivalent to format(Address, "GPH")

PublicKey Class
class graphenebase.account.PublicKey(pk, prefix=None)

This class deals with Public Keys and inherits Address.

Parameters:
  • pk (str) – Base58 encoded public key
  • prefix (str) – Network prefix (defaults to GPH)

Example::

PublicKey("GPH6UtYWWs3rkZGV8JA86qrgkG6tyFksgECefKE1MiH4HkLD8PFGL")

Note

By default, graphene-based networks deal with compressed public keys. If an uncompressed key is required, the method unCompressed can be used:

PublicKey("xxxxx").unCompressed()
__bytes__()

Returns the raw public key (has length 33)

__format__(_format)

Formats the instance of:doc:Base58 <base58> according to _format

__repr__()

Gives the hex representation of the Graphene public key.

__str__()

Returns the readable Graphene public key. This call is equivalent to format(PublicKey, "GPH")

PrivateKey Class
class graphenebase.account.PrivateKey(wif=None, prefix=None)

Derives the compressed and uncompressed public keys and constructs two instances of PublicKey:

Parameters:
  • wif (str) – Base58check-encoded wif key
  • prefix (str) – Network prefix (defaults to GPH)

Example::

PrivateKey("5HqUkGuo62BfcJU5vNhTXKJRXuUi9QSE6jp8C3uBJ2BVHtB8WSd")

Compressed vs. Uncompressed:

  • PrivateKey("w-i-f").pubkey:
    Instance of PublicKey using compressed key.
  • PrivateKey("w-i-f").pubkey.address:
    Instance of Address using compressed key.
  • PrivateKey("w-i-f").uncompressed:
    Instance of PublicKey using uncompressed key.
  • PrivateKey("w-i-f").uncompressed.address:
    Instance of Address using uncompressed key.
child(offset256)

Derive new private key from this key and a sha256 “offset”

derive_from_seed(offset)

Derive private key using “generate_from_seed” method. Here, the key itself serves as a seed, and offset is expected to be a sha256 digest.

derive_private_key(sequence)

Derive new private key from this private key and an arbitrary sequence number

get_secret()

Get sha256 digest of the wif key.

Brainkey
class graphenebase.account.BrainKey(brainkey=None, sequence=0, prefix=None)

Brainkey implementation similar to the graphene-ui web-wallet.

Parameters:
  • brainkey (str) – Brain Key
  • sequence (int) – Sequence number for consecutive keys

Keys in Graphene are derived from a seed brain key which is a string of 16 words out of a predefined dictionary with 49744 words. It is a simple single-chain key derivation scheme that is not compatible with BIP44 but easy to use.

Given the brain key, a private key is derived as:

privkey = SHA256(SHA512(brainkey + " " + sequence))

Incrementing the sequence number yields a new key that can be regenerated given the brain key.

get_blind_private()

Derive private key from the brain key (and no sequence number)

get_brainkey()

Return brain key of this instance

get_private()

Derive private key from the brain key and the current sequence number

next_sequence()

Increment the sequence number by 1

normalize(brainkey)

Correct formating with single whitespace syntax and no trailing space

static suggest()

Suggest a new random brain key. Randomness is provided by the operating system using os.urandom().

Remarks
Format vs. Repr
print("Private Key             : " + format(private_key,"WIF"))
print("Secret Exponent (hex)   : " + repr(private_key))
print("BTS PubKey (hex)        : " + repr(private_key.pubkey))
print("BTS PubKey              : " + format(private_key.pubkey, "BTS"))
print("BTS Address             : " + format(private_key.address,"BTS"))

Output:

Private Key             : 5Jdv8JHh4r2tUPtmLq8hp8DkW5vCp9y4UGgj6udjJQjG747FCMc
Secret Exponent (hex)   : 6c2662a6ac41bd9132a9f846847761ab4f80c82d519cdf92f40dfcd5e97ec5b5
BTS PubKey (hex)        : 021760b78d93878af16f8c11d22f0784c54782a12a88bbd36be847ab0c8b2994de
BTS PubKey              : BTS54nWRnewkASXXTwpn3q4q8noadzXmw4y1KpED3grup7VrDDRmx
BTS Address             : BTSCmUwH8G1t3VSZRH5kwxx31tiYDNrzWvyW
Compressed vs. Uncompressed
print("BTC uncomp. Pubkey (hex): " + repr(private_key.uncompressed.pubkey))
print("BTC Address (uncompr)   : " + format(private_key.uncompressed.address,"BTC"))
print("BTC comp. Pubkey (hex)  : " + repr(private_key.pubkey))
print("BTC Address (compr)     : " + format(private_key.address,"BTC"))

Output:

BTC uncomp. Pubkey (hex): 041760b78d93878af16f8c11d22f0784c54782a12a88bbd36be847ab0c8b2994de4d5abd46cabab34222023cd9034e1e6c0377fac5579a9c01e46b9498529aaf46
BTC Address (uncompr)   : 1JidAV2npbyLn77jGYQtkpJDjx6Yt5eJSh
BTC comp. Pubkey (hex)  : 021760b78d93878af16f8c11d22f0784c54782a12a88bbd36be847ab0c8b2994de
BTC Address (compr)     : 1GZ1JCW3kdL4LoCWbzHK4oV6V8JcUGG8HF
Bip38 Encrypted Private Keys

BIP 38 allows to encrypt and decrypt private keys in the WIF format.

Examples
from graphenebase import PrivateKey
from graphenebase.bip38 import encrypt

format(encrypt(PrivateKey("5HqUkGuo62BfcJU5vNhTXKJRXuUi9QSE6jp8C3uBJ2BVHtB8WSd"),"SecretPassPhrase"), "encwif")

>> "6PRN5mjUTtud6fUXbJXezfn6oABoSr6GSLjMbrGXRZxSUcxThxsUW8epQi",
from graphenebase import PrivateKey
from graphenebase.bip38 import decrypt

format(decrypt("6PRN5mjUTtud6fUXbJXezfn6oABoSr6GSLjMbrGXRZxSUcxThxsUW8epQi","SecretPassPhrase"),"wif"),

>> "5HqUkGuo62BfcJU5vNhTXKJRXuUi9QSE6jp8C3uBJ2BVHtB8WSd",
Definitions
graphenebase.bip38.encrypt(privkey, passphrase)

BIP0038 non-ec-multiply encryption. Returns BIP0038 encrypted privkey.

Parameters:
  • privkey (Base58) – Private key
  • passphrase (str) – UTF-8 encoded passphrase for encryption
Returns:

BIP0038 non-ec-multiply encrypted wif key

Return type:

Base58

graphenebase.bip38.decrypt(encrypted_privkey, passphrase)

BIP0038 non-ec-multiply decryption. Returns WIF privkey.

Parameters:
  • encrypted_privkey (Base58) – Private key
  • passphrase (str) – UTF-8 encoded passphrase for decryption
Returns:

BIP0038 non-ec-multiply decrypted key

Return type:

Base58

Raises:

SaltException – if checksum verification failed (e.g. wrong password)

Asyncio support

The library has full support of asyncio, though you need to be aware it has some limitations.

Example

A very basic example on how to do raw API call:

import asyncio
from grapheneapi.aio.websocket import Websocket

import logging
logger = logging.getLogger('websockets')
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())

loop = asyncio.get_event_loop()
ws = Websocket('wss://eu.nodes.bitshares.ws', loop=loop)
props = loop.run_until_complete(ws.get_dynamic_global_properties())
print(props)

Limitations

  • Most of the classes requires async init because during instantiation some API calls has to be performed:
await Amount('10 FOO')
  • Several math operations are not available for graphenecommon.aio.Amount, graphenecommon.aio.Price objects. This includes multiplication, division etc. This limitation is due to unability to define python magic methods (__mul__, __div__, etc) as async coroutines

Concurrent RPC calls

When using async version, you can perform multiple RPC calls from different coroutines concurrently. The library will send requests immediately in non-blocking manner. Incoming responses will be properly matched with queries by using “id” field of json-rpc query.

Subscriptions

In asyncio version subscription notifications are not handled in callback-based manner. Instead, they are available in self.notifications queue which is asyncio.Queue.

Debugging

To enable debugging on RPC level, you can raise loglevel on following loggers (don’t forget to set formatter as well):

log = logging.getLogger("websockets")
log.setLevel(logging.DEBUG)

log = logging.getLogger("grapheneapi")
log.setLevel(logging.DEBUG)

Tests

Current testsuite uses pre-populated object cache, so it doesn’t cover lots of functionality. Asyncio-specific tests could be run via pytest -v tests/test_*aio*.py

Graphene API

Graphene Blockchain Objects

In contrast to most cryptocurrency wallets, the BitShares 2.0 has a different model to represent the blockchain, its transactions and accounts. This chapter wants to given an introduction to the concepts of objects as they are used by the BitShares 2.0 client. Furthermore, we will briefly introduce the API and show how to subscribe to object changes (such as new blocks or incoming deposits). Afterwards, we will show how exchange may monitor their accounts and credit incoming funds to their corresponding users.

Objects

On the BitShares blockchains there are no addresses, but objects identified by a unique id, an type and a space in the form::

space.type.id

Some examples::

1.2.15   # protocol space / account / id: 15
1.6.105  # protocol space / witness / id: 105
1.14.7   # protocol space / worker / id: 7

2.1.0    # implementation space / dynamic global properties
2.3.8    # implementation space / asset . id: 8

A programmatic description of all fields can be found in the [sources](https://github.com/cryptonomex/graphene/blob/master/libraries/chain/include/graphene/chain/protocol/types.hpp).

Accounts

The BitShares blockchain users are requires to register each account with a unique username and a public key on the blockchain. The blockchain assigns an incremental user id and offers to resolve the name-to-id pair. For instance 1.2.15:

2.6.80    # implementation space / account-balance / id: 80
2.7.80    # implementation space / account-statistics / id: 80
2.10.80   # implementation space / account-transactions / id: 80
2.8.80    # implementation space / transactions / id: 80
2.9.80    # implementation space / block-summary / id: 80

Remote Procedure Calls

We provide several different API’s. Each API has its own ID. When running witness_node, initially two API’s are available:

  • API 0: provides read-only access to the database
  • API 1 is used to login and gain access to additional, restricted API’s.

Unrestricted Calls

Since API 0 is state-less it is accessible via regular JSON-RPC calls like::

$ curl --data '{"jsonrpc": "2.0", "method": "get_accounts", "params": [["1.2.0"]], "id": 1}' http://127.0.0.1:8090/rpc

We can do the same thing using an HTTP client such as curl for API’s which do not require login or other session state::

$ curl --data '{"jsonrpc": "2.0", "method": "call", "params": [0, "get_accounts", [["1.2.0"]]], "id": 1}' http://127.0.0.1:8090/rpc
{"id":1,"result":[{"id":"1.2.0","annotations":[],"membership_expiration_date":"1969-12-31T23:59:59","registrar":"1.2.0","referrer":"1.2.0","lifetime_referrer":"1.2.0","network_fee_percentage":2000,"lifetime_referrer_fee_percentage":8000,"referrer_rewards_percentage":0,"name":"committee-account","owner":{"weight_threshold":1,"account_auths":[],"key_auths":[],"address_auths":[]},"active":{"weight_threshold":6,"account_auths":[["1.2.5",1],["1.2.6",1],["1.2.7",1],["1.2.8",1],["1.2.9",1],["1.2.10",1],["1.2.11",1],["1.2.12",1],["1.2.13",1],["1.2.14",1]],"key_auths":[],"address_auths":[]},"options":{"memo_key":"GPH1111111111111111111111111111111114T1Anm","voting_account":"1.2.0","num_witness":0,"num_committee":0,"votes":[],"extensions":[]},"statistics":"2.7.0","whitelisting_accounts":[],"blacklisting_accounts":[]}]}

Restricted Calls

However, the restricted APIs require login and are only accessible over the websocket RPC. Here is an example using wscat package from npm for websockets::

$ npm install -g wscat
$ wscat -c ws://127.0.0.1:8090
> {"id":1, "method":"call", "params":[0,"get_accounts",[["1.2.0"]]]}
< {"id":1,"result":[{"id":"1.2.0","annotations":[],"membership_expiration_date":"1969-12-31T23:59:59","registrar":"1.2.0","referrer":"1.2.0","lifetime_referrer":"1.2.0","network_fee_percentage":2000,"lifetime_referrer_fee_percentage":8000,"referrer_rewards_percentage":0,"name":"committee-account","owner":{"weight_threshold":1,"account_auths":[],"key_auths":[],"address_auths":[]},"active":{"weight_threshold":6,"account_auths":[["1.2.5",1],["1.2.6",1],["1.2.7",1],["1.2.8",1],["1.2.9",1],["1.2.10",1],["1.2.11",1],["1.2.12",1],["1.2.13",1],["1.2.14",1]],"key_auths":[],"address_auths":[]},"options":{"memo_key":"GPH1111111111111111111111111111111114T1Anm","voting_account":"1.2.0","num_witness":0,"num_committee":0,"votes":[],"extensions":[]},"statistics":"2.7.0","whitelisting_accounts":[],"blacklisting_accounts":[]}]}
APIs

The graphene witness node distinguishes sever different APIs for security reasons:

  • database_api
  • history_api
  • network_broadcast_api
  • network_node_api
  • login_api

The most important api for polling blockchain data is the database_api. A list of all available calls can be found in graphene/libraries/app/include/graphene/app/database_api.hpp.

Witness

A witness node represents a full node in the network that verifies all transactions and blocks against its local state. Hence, we recommend all service providers to run an maintain their own witness nodes for reliability and security reasons.

It takes a –data-dir parameter to define a working and data directory to store the configuration, blockchain and local databases. Those will be automatically created with default settings if they don’t exist locally set.

Launching a witness node

The witness is launched according to:

./programs/witness_node/witness_node --data-dir="mydata"

Configuration

The configuration file config.ini in mydata is commented and contains the following essential settings:

# Endpoint for P2P node to listen on
# p2p-endpoint =

# P2P nodes to connect to on startup (may specify multiple times)
# seed-node =

# Pairs of [BLOCK_NUM,BLOCK_ID] that should be enforced as checkpoints.
# checkpoint =

# Endpoint for websocket RPC to listen on
# rpc-endpoint = 0.0.0.0:8090

# Endpoint for TLS websocket RPC to listen on
# rpc-tls-endpoint =

# The TLS certificate file for this server
# server-pem =

# Password for this certificate
# server-pem-password =

# File to read Genesis State from
# genesis-json = sep-18-testnet-genesis.json

# JSON file specifying API permissions
# api-access = apiaccess.json

# Enable block production, even if the chain is stale.
enable-stale-production = false

# Percent of witnesses (0-99) that must be participating in order to produce blocks
required-participation = false

# Allow block production, even if the last block was produced by the same witness.
allow-consecutive = false

# ID of witness controlled by this node (e.g. "1.6.5", quotes are required, may specify multiple times)
# witness-id =

# Tuple of [PublicKey, WIF private key] (may specify multiple times)
# private-key = ["pubkey","wif-key"]

# Account ID to track history for (may specify multiple times)
# track-account =

# Track market history by grouping orders into buckets of equal size measured in seconds specified as a JSON array of numbers
# bucket-size = [15,60,300,3600,86400]

# How far back in time to track history for each bucket size, measured in the number of buckets (default: 1000)
# history-per-size = 1000

Enabling Remote Procedure Calls (RPC)

In order to allow RPC calls for blockchain operations you need to modify the following entry in the configuration file:

rpc-endpoint = 0.0.0.0:8090

This will open the port 8090 for global queries only. Since the witness node only maintains the blockchain and (unless you are an actively block producing witness) no private keys are involved, it is safe to expose your witness to the internet.

Restarting the witness node

When restarting the witness node, it may be required to append the –replay-blockchain parameter to regenerate the local (in-memory) blockchain state.

Console Wallet

The following will explain how to use the console wallet (not GUI).

Launching

The cli_wallet creates a local wallet.json file that contains the encrypted private keys required to access the funds in your account. It requires a running witness node (not necessarily locally) and can be launched with

programs/cli_wallet/cli_wallet -s ws://127.0.0.1:8090

Depending on the actual chain that you want to connect to your may need to specifiy –chain-id.

Enabling Remote Procedure Calls (RPC)

In order to allow RPC calls for wallet operations (spend, buy, sell, …) you can choose between pure RPC or RPC-HTTP requests. In this tutorial, the latter is prefered since well established libraries make use of the RPC-HTTP protocol. To enable RPC-HTTP in your wallet you need to run

programs/cli_wallet/cli_wallet --rpc-http-endpoint="127.0.0.1:8092"

This will open the port 8092 for local queries only. It is not recommended to publicly expose your wallet!

Packages

python-graphenelib

grapheneapi package

Subpackages
grapheneapi.aio package
Submodules
grapheneapi.aio.api module
class grapheneapi.aio.api.Api(*args, **kwargs)

Bases: grapheneapi.api.Api

cache_chain_properties()

Cache chain properties to prevent turning lots of methods into async

chain_params
connect()
disconnect()
find_next()

Find the next url in the list

get_cached_chain_properties()
get_network()
next()
updated_connection()
grapheneapi.aio.http module
class grapheneapi.aio.http.Http(*args, **kwargs)

Bases: grapheneapi.aio.rpc.Rpc

RPC Calls

connect()
disconnect()
rpcexec(payload)

Execute a RPC call

Parameters:payload (dict) – json-rpc request in format: {“jsonrpc”: “2.0”, “method”: “call”, “params”: “[x, y, z]”, “id”: 1}
grapheneapi.aio.rpc module
class grapheneapi.aio.rpc.Rpc(url, *args, loop=None, **kwargs)

Bases: grapheneapi.rpc.Rpc

parse_response(*args, **kwargs)
grapheneapi.aio.websocket module
class grapheneapi.aio.websocket.Websocket(*args, **kwargs)

Bases: grapheneapi.aio.rpc.Rpc

connect()
disconnect()
get_response_by_id(request_id)

Pop response from dict containing all query results

Parameters:request_id (int) – request id to get response to
parse_messages()

Listen websocket for incoming messages in infinity manner

Messages which are responses (has id) are stored in dict, while messages which are notifies are stored in asyncio queue and are supposed to be processed later by whom who sets the subscribtion callback

rpcexec(payload)

Execute a RPC call

Parameters:payload (dict) – json-rpc request in format: {“jsonrpc”: “2.0”, “method”: “call”, “params”: “[x, y, z]”, “id”: 1}
Module contents
Submodules
grapheneapi.api module
class grapheneapi.api.Api(urls, user=None, password=None, connect=True, **kwargs)

Bases: object

api_id

This allows to list api_ids, if they have been registered through api_register() – LEGACY

In previous API version, one would connect and register to APIs like this

self.api_id["database"] = self.database(api_id=1)
self.api_id["history"] = self.history(api_id=1)
self.api_id["network_broadcast"] = self.network_broadcast(
    api_id=1)
chain_params
connect()
connection
error_url()
find_next()

Find the next url in the list

get_network()
next()
post_process_exception(exception)
register_apis()

This method is called right after connection and has previously been used to register to different APIs within the backend that are considered default. The requirement to register to APIs has been removed in some systems.

reset_counter()

reset the failed connection counters

updated_connection()
grapheneapi.exceptions module
exception grapheneapi.exceptions.HttpInvalidStatusCode

Bases: Exception

exception grapheneapi.exceptions.NumRetriesReached

Bases: Exception

exception grapheneapi.exceptions.RPCConnection

Bases: Exception

exception grapheneapi.exceptions.RPCError

Bases: Exception

exception grapheneapi.exceptions.RPCRequestError

Bases: Exception

exception grapheneapi.exceptions.UnauthorizedError

Bases: Exception

grapheneapi.grapheneapi module
class grapheneapi.grapheneapi.GrapheneAPI(host, port, username='', password='')

Bases: object

Graphene JSON-HTTP-RPC API

This class serves as an abstraction layer for easy use of the Grapehene API.

Parameters:
  • host (str) – Host of the API server
  • port (int) – Port to connect to
  • username (str) – Username for Authentication (if required, defaults to “”)
  • password (str) – Password for Authentication (if required, defaults to “”)

All RPC commands of the Graphene client are exposed as methods in the class grapheneapi. Once an instance of GrapheneAPI is created with host, port, username, and password, e.g.,

from grapheneapi import GrapheneAPI
rpc = GrapheneAPI("localhost", 8092, "", "")

any call available to that port can be issued using the instance via the syntax rpc.*command*(parameters). Example:

rpc.info()

Note

A distinction has to be made whether the connection is made to a witness/full node which handles the blockchain and P2P network, or a cli-wallet that handles wallet related actions! The available commands differ drastically!

If you are connected to a wallet, you can simply initiate a transfer with:

res = client.transfer("sender","receiver","5", "USD", "memo", True);

Again, the witness node does not offer access to construct any transactions, and hence the calls available to the witness-rpc can be seen as read-only for the blockchain.

rpcexec(payload)

Manual execute a command on API (internally used)

param str payload: The payload containing the request return: Servers answer to the query rtype: json raises RPCConnection: if no connction can be made raises UnauthorizedError: if the user is not authorized raise ValueError: if the API returns a non-JSON formated answer

It is not recommended to use this method directly, unless you know what you are doing. All calls available to the API will be wrapped to methods directly:

info -> grapheneapi.info()
grapheneapi.http module
class grapheneapi.http.Http(*args, **kwargs)

Bases: grapheneapi.rpc.Rpc

RPC Calls

get_request_session() → requests.sessions.Session

Store current HTTP session

proxies()
rpcexec(payload, retry=None)

Execute a call by sending the payload

Parameters:

payload (json) – Payload data

Raises:
  • ValueError – if the server does not respond in proper JSON format
  • HttpInvalidStatusCode – if the server returns a status code that is not 200
grapheneapi.rpc module
class grapheneapi.rpc.Rpc(url, **kwargs)

Bases: object

This class allows to call API methods synchronously, without callbacks.

Parameters:
  • url (str) – A single REST endpoint URL
  • num_retries (int) – Try x times to num_retries to a node on disconnect, -1 for indefinitely
  • proxy (str) – Proxy URL (e.g. socks5://localhost:9050), None by default.

Usage:

ws = GrapheneHTTPRPC("https://api.node.com")
print(ws.get_account_count())
connect()
disconnect()
get_proxy_url()
get_request_id()
parse_response(query, log_on_debug=True)
rpcexec(**kwargs)
setup_proxy(options)
grapheneapi.websocket module
class grapheneapi.websocket.Websocket(*args, **kwargs)

Bases: grapheneapi.rpc.Rpc

connect()
disconnect()
rpcexec(payload)

Execute a call by sending the payload

Parameters:payload (json) – Payload data
Raises:ValueError – if the server does not respond in proper JSON format
Module contents

graphenebase package

Submodules
graphenebase.account module
class graphenebase.account.Address(address, prefix=None)

Bases: graphenebase.prefix.Prefix

Address class

This class serves as an address representation for Public Keys.

Parameters:
  • address (str) – Base58 encoded address (defaults to None)
  • pubkey (str) – Base58 encoded pubkey (defaults to None)
  • prefix (str) – Network prefix (defaults to GPH)

Example:

Address("GPHFN9r6VYzBK8EKtMewfNbfiGCr56pHDBFi")
classmethod from_pubkey(pubkey, compressed=True, version=56, prefix=None)

Load an address provided the public key.

Version: 56 => PTS

class graphenebase.account.BitcoinAddress(address, prefix=None)

Bases: graphenebase.account.Address

classmethod from_pubkey(pubkey, compressed=False, version=56, prefix=None)

Load an address provided the public key.

Version: 56 => PTS

class graphenebase.account.BitcoinPublicKey(pk, prefix=None)

Bases: graphenebase.account.PublicKey

address

Obtain a GrapheneAddress from a public key

class graphenebase.account.BrainKey(brainkey=None, sequence=0, prefix=None)

Bases: graphenebase.prefix.Prefix

Brainkey implementation similar to the graphene-ui web-wallet.

Parameters:
  • brainkey (str) – Brain Key
  • sequence (int) – Sequence number for consecutive keys

Keys in Graphene are derived from a seed brain key which is a string of 16 words out of a predefined dictionary with 49744 words. It is a simple single-chain key derivation scheme that is not compatible with BIP44 but easy to use.

Given the brain key, a private key is derived as:

privkey = SHA256(SHA512(brainkey + " " + sequence))

Incrementing the sequence number yields a new key that can be regenerated given the brain key.

get_blind_private()

Derive private key from the brain key (and no sequence number)

get_brainkey()

Return brain key of this instance

get_private()

Derive private key from the brain key and the current sequence number

get_private_key()
get_public()
get_public_key()
next_sequence()

Increment the sequence number by 1

normalize(brainkey)

Correct formating with single whitespace syntax and no trailing space

static suggest()

Suggest a new random brain key. Randomness is provided by the operating system using os.urandom().

class graphenebase.account.GrapheneAddress(address, prefix=None)

Bases: graphenebase.account.Address

Graphene Addresses are different. Hence we have a different class

classmethod from_pubkey(pubkey, compressed=True, version=56, prefix=None)

Load an address provided the public key.

Version: 56 => PTS

class graphenebase.account.PasswordKey(account, password, role='active', prefix=None)

Bases: graphenebase.prefix.Prefix

This class derives a private key given the account name, the role and a password. It leverages the technology of Brainkeys and allows people to have a secure private key by providing a passphrase only.

get_private()

Derive private key from the brain key and the current sequence number

get_private_key()
get_public()
get_public_key()
class graphenebase.account.PrivateKey(wif=None, prefix=None)

Bases: graphenebase.prefix.Prefix

Derives the compressed and uncompressed public keys and constructs two instances of PublicKey:

Parameters:
  • wif (str) – Base58check-encoded wif key
  • prefix (str) – Network prefix (defaults to GPH)

Example::

PrivateKey("5HqUkGuo62BfcJU5vNhTXKJRXuUi9QSE6jp8C3uBJ2BVHtB8WSd")

Compressed vs. Uncompressed:

  • PrivateKey("w-i-f").pubkey:
    Instance of PublicKey using compressed key.
  • PrivateKey("w-i-f").pubkey.address:
    Instance of Address using compressed key.
  • PrivateKey("w-i-f").uncompressed:
    Instance of PublicKey using uncompressed key.
  • PrivateKey("w-i-f").uncompressed.address:
    Instance of Address using uncompressed key.
address
bitcoin
child(offset256)

Derive new private key from this key and a sha256 “offset”

compressed
derive_from_seed(offset)

Derive private key using “generate_from_seed” method. Here, the key itself serves as a seed, and offset is expected to be a sha256 digest.

derive_private_key(sequence)

Derive new private key from this private key and an arbitrary sequence number

get_secret()

Get sha256 digest of the wif key.

pubkey
uncompressed
class graphenebase.account.PublicKey(pk, prefix=None)

Bases: graphenebase.prefix.Prefix

This class deals with Public Keys and inherits Address.

Parameters:
  • pk (str) – Base58 encoded public key
  • prefix (str) – Network prefix (defaults to GPH)

Example::

PublicKey("GPH6UtYWWs3rkZGV8JA86qrgkG6tyFksgECefKE1MiH4HkLD8PFGL")

Note

By default, graphene-based networks deal with compressed public keys. If an uncompressed key is required, the method unCompressed can be used:

PublicKey("xxxxx").unCompressed()
add(digest256)

Derive new public key from this key and a sha256 “digest”

address

Obtain a GrapheneAddress from a public key

child(offset256)

Derive new public key from this key and a sha256 “offset”

compressed()

returns the compressed key

compressed_key
classmethod from_privkey(privkey, prefix=None)

Derive uncompressed public key

point()

Return the point for the public key

pubkey
unCompressed()

Alias for self.uncompressed() - LEGACY

uncompressed()

Derive uncompressed key

graphenebase.aes module
class graphenebase.aes.AESCipher(key)

Bases: object

A classical AES Cipher. Can use any size of data and any size of password thanks to padding. Also ensure the coherence and the type of the data with a unicode to byte converter.

decrypt(enc)
encrypt(raw)
static str_to_bytes(data)
graphenebase.base58 module
class graphenebase.base58.Base58(data, prefix=None)

Bases: graphenebase.prefix.Prefix

Base58 base class

This class serves as an abstraction layer to deal with base58 encoded strings and their corresponding hex and binary representation throughout the library.

Parameters:
  • data (hex, wif, bip38 encrypted wif, base58 string) – Data to initialize object, e.g. pubkey data, address data, …
  • prefix (str) – Prefix to use for Address/PubKey strings (defaults to GPH)
Returns:

Base58 object initialized with data

Return type:

Base58

Raises:

ValueError – if data cannot be decoded

  • bytes(Base58): Returns the raw data
  • str(Base58): Returns the readable Base58CheckEncoded data.
  • repr(Base58): Gives the hex representation of the data.
  • format(Base58,_format) Formats the instance according to
    _format: * "wif": prefixed with 0x00. Yields a valid wif key * "bts": prefixed with BTS * etc.
graphenebase.base58.b58decode(v)
graphenebase.base58.b58encode(v)
graphenebase.base58.base58CheckDecode(s)
graphenebase.base58.base58CheckEncode(version, payload)
graphenebase.base58.base58decode(base58_str)
graphenebase.base58.base58encode(hexstring)
graphenebase.base58.doublesha256(s)
graphenebase.base58.gphBase58CheckDecode(s)
graphenebase.base58.gphBase58CheckEncode(s)
graphenebase.base58.ripemd160(s)
graphenebase.bip38 module
exception graphenebase.bip38.SaltException

Bases: Exception

graphenebase.bip38.decrypt(encrypted_privkey, passphrase)

BIP0038 non-ec-multiply decryption. Returns WIF privkey.

Parameters:
  • encrypted_privkey (Base58) – Private key
  • passphrase (str) – UTF-8 encoded passphrase for decryption
Returns:

BIP0038 non-ec-multiply decrypted key

Return type:

Base58

Raises:

SaltException – if checksum verification failed (e.g. wrong password)

graphenebase.bip38.encrypt(privkey, passphrase)

BIP0038 non-ec-multiply encryption. Returns BIP0038 encrypted privkey.

Parameters:
  • privkey (Base58) – Private key
  • passphrase (str) – UTF-8 encoded passphrase for encryption
Returns:

BIP0038 non-ec-multiply encrypted wif key

Return type:

Base58

graphenebase.chains module
graphenebase.dictionary module
graphenebase.ecdsa module
graphenebase.ecdsa.compressedPubkey(pk)
graphenebase.ecdsa.recoverPubkeyParameter(message, digest, signature, pubkey)

Use to derive a number that allows to easily recover the public key from the signature

graphenebase.ecdsa.recover_public_key(digest, signature, i, message=None)

Recover the public key from the the signature

graphenebase.ecdsa.sign_message(message, wif, hashfn=<built-in function openssl_sha256>)

Sign a digest with a wif key

Parameters:wif (str) – Private key in
graphenebase.ecdsa.tweakaddPubkey(pk, digest256, SECP256K1_MODULE='ecdsa')
graphenebase.ecdsa.verify_message(message, signature, hashfn=<built-in function openssl_sha256>)
graphenebase.memo module
graphenebase.memo.decode_memo(priv, pub, nonce, message)

Decode a message with a shared secret between Alice and Bob

Parameters:
  • priv (PrivateKey) – Private Key (of Bob)
  • pub (PublicKey) – Public Key (of Alice)
  • nonce (int) – Nonce used for Encryption
  • message (bytes) – Encrypted Memo message
Returns:

Decrypted message

Return type:

str

Raises:

ValueError – if message cannot be decoded as valid UTF-8 string

graphenebase.memo.encode_memo(priv, pub, nonce, message)

Encode a message with a shared secret between Alice and Bob

Parameters:
  • priv (PrivateKey) – Private Key (of Alice)
  • pub (PublicKey) – Public Key (of Bob)
  • nonce (int) – Random nonce
  • message (str) – Memo message
Returns:

Encrypted message

Return type:

hex

graphenebase.memo.get_shared_secret(priv, pub)

Derive the share secret between priv and pub

Parameters:
Returns:

Shared secret

Return type:

hex

The shared secret is generated such that:

Pub(Alice) * Priv(Bob) = Pub(Bob) * Priv(Alice)
graphenebase.memo.init_aes(shared_secret, nonce)

Initialize AES instance

Parameters:
  • shared_secret (hex) – Shared Secret to use as encryption key
  • nonce (int) – Random nonce
Returns:

AES instance

Return type:

AES

graphenebase.objects module
class graphenebase.objects.Asset(*args, **kwargs)

Bases: graphenebase.objects.GrapheneObject

detail(*args, **kwargs)
class graphenebase.objects.GrapheneObject(*args, **kwargs)

Bases: collections.OrderedDict

Core abstraction class

This class is used for any JSON reflected object in Graphene.

  • instance.__json__(): encodes data into json format
  • bytes(instance): encodes data into wire format
  • str(instances): dumps json object as string
data

Read data explicitly (backwards compatibility)

json()
toJson()
class graphenebase.objects.Operation(op, **kwargs)

Bases: list

The superclass for an operation. This class i used to instanciate an operation, identify the operationid/name and serialize the operation into bytes.

fromlist = ['operations']
getOperationIdForName(name)
getOperationNameForId(i)

Convert an operation id into the corresponding string

id
json()
klass()
klass_name
module = 'graphenebase.operations'
op
opId
operation
operations = {'account_create': 5, 'demooepration': 0, 'newdemooepration': 1, 'newdemooepration2': 2, 'nonexisting2': 3, 'nonexisting3': 4}
ops
set(**data)
toJson()
graphenebase.objects.isArgsThisClass(self, args)
graphenebase.objecttypes module
graphenebase.objecttypes.object_type = {'OBJECT_TYPE_COUNT': 4, 'account': 2, 'asset': 3, 'base': 1, 'null': 0}

Object types for object ids

graphenebase.operationids module
graphenebase.operationids.getOperationName(id: str)

This method returns the name representation of an operation given its value as used in the API

graphenebase.operationids.getOperationNameForId(i: int)

Convert an operation id into the corresponding string

graphenebase.operationids.ops = ['demooepration', 'newdemooepration', 'newdemooepration2', 'nonexisting2', 'nonexisting3', 'account_create']

Operation ids

graphenebase.operations module
class graphenebase.operations.AccountOptions(*args, **kwargs)

Bases: graphenebase.objects.GrapheneObject

detail(*args, **kwargs)
class graphenebase.operations.Account_create(*args, **kwargs)

Bases: graphenebase.objects.GrapheneObject

detail(*args, **kwargs)
class graphenebase.operations.Demooepration(*args, **kwargs)

Bases: graphenebase.objects.GrapheneObject

class graphenebase.operations.Newdemooepration(*args, **kwargs)

Bases: graphenebase.objects.GrapheneObject

detail(*args, **kwargs)
class graphenebase.operations.Newdemooepration2(*args, **kwargs)

Bases: graphenebase.objects.GrapheneObject

detail(*args, **kwargs)
class graphenebase.operations.Permission(*args, **kwargs)

Bases: graphenebase.objects.GrapheneObject

detail(*args, **kwargs)
graphenebase.prefix module
class graphenebase.prefix.Prefix

Bases: object

This class is meant to allow changing the prefix. The prefix is used to link a public key to a specific blockchain.

prefix = 'GPH'
set_prefix(prefix)
graphenebase.ripemd160 module
graphenebase.ripemd160.compress(h0, h1, h2, h3, h4, block)

Compress state (h0, h1, h2, h3, h4) with block.

graphenebase.ripemd160.fi(x, y, z, i)

The f1, f2, f3, f4, and f5 functions from the specification.

graphenebase.ripemd160.ripemd160(data)

Compute the RIPEMD-160 hash of data.

graphenebase.ripemd160.rol(x, i)

Rotate the bottom 32 bits of x left by i bits.

graphenebase.signedtransactions module
exception graphenebase.signedtransactions.MissingSignatureForKey

Bases: Exception

class graphenebase.signedtransactions.Signed_Transaction(*args, **kwargs)

Bases: graphenebase.objects.GrapheneObject

Create a signed transaction and offer method to create the signature

Parameters:
  • refNum (num) – parameter ref_block_num (see getBlockParams)
  • refPrefix (num) – parameter ref_block_prefix (see getBlockParams)
  • expiration (str) – expiration date
  • operations (Array) – array of operations
default_prefix = 'GPH'
deriveDigest(chain)
detail(*args, **kwargs)
getChainParams(chain)
getKnownChains()
getOperationKlass()
get_default_prefix()
id

The transaction id of this transaction

known_chains = {'GPH': {'chain_id': 'b8d1603965b3eb1acba27e62ff59f74efa3154d43a4188d381088ac7cdf35539', 'core_symbol': 'CORE', 'prefix': 'GPH'}, 'TEST': {'chain_id': '39f5e2ede1f8bc1a3a54a7914414e3779e33193f1f5693510e73cb7a87617447', 'core_symbol': 'TEST', 'prefix': 'TEST'}}
operation_klass

alias of graphenebase.objects.Operation

sign(wifkeys, chain=None)

Sign the transaction with the provided private keys.

Parameters:
  • wifkeys (array) – Array of wif keys
  • chain (str) – identifier for the chain
verify(pubkeys=[], chain=None)
graphenebase.transactions module
graphenebase.transactions.formatTimeFromNow(secs=0)

Properly Format Time that is x seconds in the future

Parameters:secs (int) – Seconds to go in the future (x>0) or the past (x<0)
Returns:Properly formated time for Graphene (%Y-%m-%dT%H:%M:%S)
Return type:str
graphenebase.transactions.getBlockParams(ws, use_head_block=False)

Auxiliary method to obtain ref_block_num and ref_block_prefix. Requires a websocket connection to a witness node!

graphenebase.types module
class graphenebase.types.Array(d)

Bases: object

class graphenebase.types.Bool(d)

Bases: graphenebase.types.Uint8

class graphenebase.types.Bytes(d)

Bases: object

Initializes from and stores internally as a string of hex digits. Byte-serializes as a length-prefixed series of bytes represented by those hex digits.

Ex: len(str(Bytes(“deadbeef”)) == 8 # Eight hex chars
len(bytes(Bytes(“deadbeef”)) == 5 # Four data bytes plus varint length

Implements __json__() method to disambiguate between string and numeric in event where hex digits include only numeric digits and no alpha digits.

class graphenebase.types.Enum8(selection)

Bases: graphenebase.types.Uint8

options = []
class graphenebase.types.Fixed_array

Bases: object

class graphenebase.types.FullObjectId(object_str)

Bases: object

Encodes object ids - serializes to a full object id

class graphenebase.types.Hash(d)

Bases: graphenebase.types.Bytes

json()
class graphenebase.types.Hash160(a)

Bases: graphenebase.types.Hash

class graphenebase.types.Id(d)

Bases: object

class graphenebase.types.Int16(d)

Bases: object

class graphenebase.types.Int64(d)

Bases: object

graphenebase.types.JsonObj(data)

Return json object from data

If data has a __json__() method, use that, else assume it follows the convention that its string representation is interprettable as valid json. (The latter can be problematic if str(data) returns, e.g., “1234”. Was this supposed to be the string “1234” or the number 1234? If this ambiguity exists, the data type must implement __json__().)

class graphenebase.types.Map(data)

Bases: object

class graphenebase.types.ObjectId(object_str, type_verify=None)

Bases: object

Encodes protocol ids - serializes to the instance only!

object_types = {'OBJECT_TYPE_COUNT': 4, 'account': 2, 'asset': 3, 'base': 1, 'null': 0}
class graphenebase.types.Optional(d)

Bases: object

isempty()
class graphenebase.types.PointInTime(d)

Bases: object

class graphenebase.types.Ripemd160(a)

Bases: graphenebase.types.Hash

class graphenebase.types.Set(d)

Bases: graphenebase.types.Array

class graphenebase.types.Sha1(a)

Bases: graphenebase.types.Hash

class graphenebase.types.Sha256(a)

Bases: graphenebase.types.Hash

class graphenebase.types.Signature(d)

Bases: object

class graphenebase.types.Static_variant(d, type_id)

Bases: object

class graphenebase.types.String(d)

Bases: object

class graphenebase.types.Uint16(d)

Bases: object

class graphenebase.types.Uint32(d)

Bases: object

class graphenebase.types.Uint64(d)

Bases: object

class graphenebase.types.Uint8(d)

Bases: object

class graphenebase.types.Varint32(d)

Bases: object

class graphenebase.types.Void

Bases: object

class graphenebase.types.VoteId(vote)

Bases: object

graphenebase.types.variable_buffer(s)

Encode variable length buffer

graphenebase.types.varint(n)

Varint encoding

graphenebase.types.varintdecode(data)

Varint decoding

graphenebase.utils module
graphenebase.utils.formatTime(t)

Properly Format Time for permlinks

graphenebase.utils.formatTimeFromNow(secs=0)

Properly Format Time that is x seconds in the future

Parameters:secs (int) – Seconds to go in the future (x>0) or the past (x<0)
Returns:Properly formated time for Graphene (%Y-%m-%dT%H:%M:%S)
Return type:str
graphenebase.utils.formatTimeString(t)

Properly Format Time for permlinks

graphenebase.utils.parse_time(block_time)

Take a string representation of time from the blockchain, and parse it into datetime object.

graphenebase.utils.unicodify(data)
Module contents

graphenecommon package

Subpackages
graphenecommon.aio package
Submodules
graphenecommon.aio.account module
class graphenecommon.aio.account.Account(*args, **kwargs)

Bases: graphenecommon.aio.blockchainobject.BlockchainObject, graphenecommon.account.Account

This class allows to easily access Account data

Parameters:
  • account_name (str) – Name of the account
  • blockchain_instance (instance) – instance to use when accesing a RPC
  • full (bool) – Obtain all account data including orders, positions, etc.
  • lazy (bool) – Use lazy loading
  • full – Obtain all account data including orders, positions, etc.
Returns:

Account data

Return type:

dictionary

Raises:

exceptions.AccountDoesNotExistsException – if account does not exist

Instances of this class are dictionaries that come with additional methods (see below) that allow dealing with an account and it’s corresponding functions.

from aio.account import Account
account = await Account("init0")
print(account)

Note

This class comes with its own caching function to reduce the load on the API server. Instances of this class can be refreshed with await Account.refresh().

balance(symbol)

Obtain the balance of a specific Asset. This call returns instances of amount.Amount.

balances

List balances of an account. This call returns instances of amount.Amount.

blacklist(account)

Add an other account to the blacklist of this account

ensure_full()
history(first=0, last=0, limit=-1, only_ops=[], exclude_ops=[])

Returns a generator for individual account transactions. The latest operation will be first. This call can be used in a for loop.

Parameters:
  • first (int) – sequence number of the first transaction to return (optional)
  • last (int) – sequence number of the last transaction to return (optional)
  • limit (int) – limit number of transactions to return (optional)
  • only_ops (array) – Limit generator by these operations (optional)
  • exclude_ops (array) – Exclude these operations from generator (optional).
… note::
only_ops and exclude_ops takes an array of strings: The full list of operation ID’s can be found in operationids.py. Example: [‘transfer’, ‘fill_order’]
nolist(account)

Remove an other account from any list of this account

refresh()

Refresh/Obtain an account’s data from the API server

upgrade()

Upgrade account to life time member

whitelist(account)

Add an other account to the whitelist of this account

class graphenecommon.aio.account.AccountUpdate(data, *args, **kwargs)

Bases: graphenecommon.account.AccountUpdate

This purpose of this class is to keep track of account updates as they are pushed through by notify.Notify.

Instances of this class are dictionaries and take the following form:

… code-block: js

{‘id’: ‘2.6.29’,
‘lifetime_fees_paid’: ‘44261516129’, ‘most_recent_op’: ‘2.9.0’, ‘owner’: ‘1.2.29’, ‘pending_fees’: 0, ‘pending_vested_fees’: 16310, ‘total_core_in_orders’: ‘6788845277634’, ‘total_ops’: 0}
account

In oder to obtain the actual account.Account from this class, you can use the account attribute.

graphenecommon.aio.amount module
class graphenecommon.aio.amount.Amount(*args, **kwargs)

Bases: graphenecommon.amount.Amount

asset

Returns the asset as instance of asset.Asset

copy()

Copy the instance and make sure not to use a reference

graphenecommon.aio.asset module
class graphenecommon.aio.asset.Asset(*args, **kwargs)

Bases: graphenecommon.aio.blockchainobject.BlockchainObject, graphenecommon.asset.Asset

Deals with Assets of the network.

Parameters:
  • Asset (str) – Symbol name or object id of an asset
  • full (bool) – Also obtain bitasset-data and dynamic asset data
  • blockchain_instance (instance) – instance to use when accesing a RPC
Returns:

All data of an asset

Return type:

dict

Note

This class comes with its own caching function to reduce the load on the API server. Instances of this class can be refreshed with await Asset.refresh().

ensure_full()
refresh()

Refresh the data from the API server

update_cer(cer, account=None, **kwargs)

Update the Core Exchange Rate (CER) of an asset

graphenecommon.aio.block module
class graphenecommon.aio.block.Block(*args, use_cache=False, **kwargs)

Bases: graphenecommon.aio.blockchainobject.BlockchainObject, graphenecommon.block.Block

Read a single block from the chain

Parameters:
  • block (int) – block number
  • blockchain_instance (instance) – instance to use when accesing a RPC
  • lazy (bool) – Use lazy loading
  • loop – asyncio event loop

Instances of this class are dictionaries that come with additional methods (see below) that allow dealing with a block and it’s corresponding functions.

from aio.block import Block
block = await Block(1)
print(block)
refresh()

Even though blocks never change, you freshly obtain its contents from an API with this method

class graphenecommon.aio.block.BlockHeader(*args, use_cache=False, **kwargs)

Bases: graphenecommon.aio.blockchainobject.BlockchainObject, graphenecommon.block.BlockHeader

refresh()

Even though blocks never change, you freshly obtain its contents from an API with this method

graphenecommon.aio.blockchain module
class graphenecommon.aio.blockchain.Blockchain(*args, **kwargs)

Bases: graphenecommon.blockchain.Blockchain

This class allows to access the blockchain and read data from it

Parameters:
  • blockchain_instance (instance) – instance to use when accesing a RPC
  • mode (str) – (default) Irreversible block (irreversible) or actual head block (head)
  • max_block_wait_repetition (int) – (default) 3 maximum wait time for next block ismax_block_wait_repetition * block_interval

This class let’s you deal with blockchain related data and methods.

awaitTxConfirmation(transaction, limit=10)

Returns the transaction as seen by the blockchain after being included into a block

Note

If you want instant confirmation, you need to instantiate class:.blockchain.Blockchain with mode="head", otherwise, the call will wait until confirmed in an irreversible block.

Note

This method returns once the blockchain has included a transaction with the same signature. Even though the signature is not usually used to identify a transaction, it still cannot be forfeited and is derived from the transaction contented and thus identifies a transaction uniquely.

block_time(block_num)

Returns a datetime of the block with the given block number.

Parameters:block_num (int) – Block number
block_timestamp(block_num)

Returns the timestamp of the block with the given block number.

Parameters:block_num (int) – Block number
blocks(start=None, stop=None)

Yields blocks starting from start.

Parameters:
  • start (int) – Starting block
  • stop (int) – Stop at this block
  • mode (str) – We here have the choice between “head” (the last block) and “irreversible” (the block that is confirmed by 2/3 of all block producers and is thus irreversible)
chainParameters()

The blockchain parameters, such as fees, and committee-controlled parameters are returned here

config()

Returns object 2.0.0

get_all_accounts(start='', stop='', steps=1000.0, **kwargs)

Yields account names between start and stop.

Parameters:
  • start (str) – Start at this account name
  • stop (str) – Stop at this account name
  • steps (int) – Obtain steps ret with a single call from RPC
get_block_interval()

This call returns the block interval

get_chain_properties()

Return chain properties

get_current_block()

This call returns the current block

Note

The block number returned depends on the mode used when instanciating from this class.

get_current_block_num()

This call returns the current block

Note

The block number returned depends on the mode used when instanciating from this class.

get_network()

Identify the network

Returns:Network parameters
Return type:dict
info()

This call returns the dynamic global properties

ops(start=None, stop=None, **kwargs)

Yields all operations (excluding virtual operations) starting from start.

Parameters:
  • start (int) – Starting block
  • stop (int) – Stop at this block
  • mode (str) – We here have the choice between “head” (the last block) and “irreversible” (the block that is confirmed by 2/3 of all block producers and is thus irreversible)
  • only_virtual_ops (bool) – Only yield virtual operations

This call returns a list that only carries one operation and its type!

participation_rate
stream(opNames=[], *args, **kwargs)

Yield specific operations (e.g. comments) only

Parameters:
  • opNames (array) – List of operations to filter for
  • start (int) – Start at this block
  • stop (int) – Stop at this block
  • mode (str) –

    We here have the choice between * “head”: the last block * “irreversible”: the block that is confirmed by 2/3 of all

    block producers and is thus irreversible!

The dict output is formated such that type caries the operation type, timestamp and block_num are taken from the block the operation was stored in and the other key depend on the actualy operation.

update_chain_parameters()
wait_for_and_get_block(block_number, blocks_waiting_for=None)

Get the desired block from the chain, if the current head block is smaller (for both head and irreversible) then we wait, but a maxmimum of blocks_waiting_for * max_block_wait_repetition time before failure.

Parameters:
  • block_number (int) – desired block number
  • blocks_waiting_for (int) – (default) difference between block_number and current head how many blocks we are willing to wait, positive int
graphenecommon.aio.blockchainobject module
class graphenecommon.aio.blockchainobject.BlockchainObject(data, klass=None, lazy=False, use_cache=True, *args, **kwargs)

Bases: graphenecommon.aio.blockchainobject.Caching, graphenecommon.blockchainobject.BlockchainObject

class graphenecommon.aio.blockchainobject.BlockchainObjects(*args, **kwargs)

Bases: graphenecommon.aio.blockchainobject.Caching, list

class graphenecommon.aio.blockchainobject.Caching(*args, **kwargs)

Bases: graphenecommon.blockchainobject.Caching

items()

This overrides items() so that refresh() is called if the object is not already fetched

class graphenecommon.aio.blockchainobject.Object(data, klass=None, lazy=False, use_cache=True, *args, **kwargs)

Bases: graphenecommon.aio.blockchainobject.BlockchainObject, graphenecommon.aio.instance.AbstractBlockchainInstanceProvider

This class is a basic class that allows to obtain any object from the blockchyin by fetching it through the API

refresh()

This is the refresh method that overloads the prototype in BlockchainObject.

graphenecommon.aio.chain module
class graphenecommon.aio.chain.AbstractGrapheneChain(*args, **kwargs)

Bases: graphenecommon.chain.AbstractGrapheneChain

broadcast(tx=None)

Broadcast a transaction to the Blockchain

Parameters:tx (tx) – Signed transaction to broadcast
connect()

Connect to blockchain network

Async version does wallet initialization after connect because wallet depends on prefix which is available after connection only, and we want to keep __init__() synchronous.

finalizeOp(ops, account, permission, **kwargs)

This method obtains the required private keys if present in the wallet, finalizes the transaction, signs it and broadacasts it

Parameters:
  • ops (operation) – The operation (or list of operaions) to broadcast
  • account (operation) – The account that authorizes the operation
  • permission (string) – The required permission for signing (active, owner, posting)
  • append_to (object) – This allows to provide an instance of ProposalsBuilder (see new_proposal()) or TransactionBuilder (see new_tx()) to specify where to put a specific operation.
… note:: append_to is exposed to every method used in the
this class

… note:

If ``ops`` is a list of operation, they all need to be
signable by the same key! Thus, you cannot combine ops
that require active permission with ops that require
posting permission. Neither can you use different
accounts for different operations!
… note:: This uses txbuffer as instance of
transactionbuilder.TransactionBuilder. You may want to use your own txbuffer
info()

Returns the global properties

sign(tx=None, wifs=[])

Sign a provided transaction witht he provided key(s)

Parameters:
  • tx (dict) – The transaction to be signed and returned
  • wifs (string) – One or many wif keys to use for signing a transaction. If not present, the keys will be loaded from the wallet as defined in “missing_signatures” key of the transactions.
graphenecommon.aio.committee module
class graphenecommon.aio.committee.Committee(*args, **kwargs)

Bases: graphenecommon.aio.blockchainobject.BlockchainObject, graphenecommon.committee.Committee

Read data about a Committee Member in the chain

Parameters:
  • member (str) – Name of the Committee Member
  • blockchain_instance (instance) – instance to use when accesing a RPC
  • lazy (bool) – Use lazy loading
account
refresh()
graphenecommon.aio.genesisbalance module
class graphenecommon.aio.genesisbalance.GenesisBalance(*args, **kwargs)

Bases: graphenecommon.aio.blockchainobject.BlockchainObject, graphenecommon.genesisbalance.GenesisBalance

Deals with Assets of the network.

Parameters:
  • Asset (str) – Symbol name or object id of an asset
  • lazy (bool) – Lazy loading
  • full (bool) – Also obtain bitasset-data and dynamic asset data
  • blockchain_instance (instance) – instance to use when accesing a RPC
Returns:

All data of an asset

Return type:

dict

Note

This class comes with its own caching function to reduce the load on the API server. Instances of this class can be refreshed with Asset.refresh().

claim(account=None, **kwargs)

Claim a balance from the genesis block

Parameters:
  • balance_id (str) – The identifier that identifies the balance to claim (1.15.x)
  • account (str) – (optional) the account that owns the bet (defaults to default_account)
refresh()
class graphenecommon.aio.genesisbalance.GenesisBalances(**kwargs)

Bases: graphenecommon.genesisbalance.GenesisBalances

List genesis balances that can be claimed from the keys in the wallet

graphenecommon.aio.instance module
class graphenecommon.aio.instance.AbstractBlockchainInstanceProvider(*args, **kwargs)

Bases: graphenecommon.instance.AbstractBlockchainInstanceProvider

classmethod inject(cls)
graphenecommon.aio.instance.BlockchainInstance

alias of graphenecommon.aio.instance.AbstractBlockchainInstanceProvider

class graphenecommon.aio.instance.SharedInstance

Bases: object

config = {}
instance = None
graphenecommon.aio.memo module
class graphenecommon.aio.memo.Memo(from_account=None, to_account=None, **kwargs)

Bases: graphenecommon.memo.Memo

Deals with Memos that are attached to a transfer

Parameters:
  • from_account (account.Account) – Account that has sent the memo
  • to_account (account.Account) – Account that has received the memo
  • blockchain_instance (instance) – instance to use when accesing a RPC

A memo is encrypted with a shared secret derived from a private key of the sender and a public key of the receiver. Due to the underlying mathematics, the same shared secret can be derived by the private key of the receiver and the public key of the sender. The encrypted message is perturbed by a nonce that is part of the transmitted message.

from .memo import Memo
m = await Memo("from-account", "to-account")
m.blockchain.wallet.unlock("secret")
enc = (m.encrypt("foobar"))
print(enc)
>> {'nonce': '17329630356955254641', 'message': '8563e2bb2976e0217806d642901a2855'}
print(m.decrypt(enc))
>> foobar

To decrypt a memo, simply use

from memo import Memo
m = await Memo()
m.blockchain.wallet.unlock("secret")
print(memo.decrypt(op_data["memo"]))

if op_data being the payload of a transfer operation.

graphenecommon.aio.message module
class graphenecommon.aio.message.Message(*args, **kwargs)

Bases: graphenecommon.message.Message, graphenecommon.aio.message.MessageV1, graphenecommon.aio.message.MessageV2

sign(*args, **kwargs)

Sign a message with an account’s memo key

Parameters:account (str) – (optional) the account that owns the bet (defaults to default_account)
Raises:ValueError – If not account for signing is provided
Returns:the signed message encapsulated in a known format
supported_formats = (<class 'graphenecommon.aio.message.MessageV1'>, <class 'graphenecommon.aio.message.MessageV2'>)
valid_exceptions = (<class 'graphenecommon.exceptions.AccountDoesNotExistsException'>, <class 'graphenecommon.exceptions.InvalidMessageSignature'>, <class 'graphenecommon.exceptions.WrongMemoKey'>, <class 'graphenecommon.exceptions.InvalidMemoKeyException'>)
verify(**kwargs)

Verify a message with an account’s memo key

Parameters:account (str) – (optional) the account that owns the bet (defaults to default_account)
Returns:True if the message is verified successfully

:raises InvalidMessageSignature if the signature is not ok

class graphenecommon.aio.message.MessageV1(*args, **kwargs)

Bases: graphenecommon.message.MessageV1

Allow to sign and verify Messages that are sigend with a private key

sign(account=None, **kwargs)

Sign a message with an account’s memo key

Parameters:account (str) – (optional) the account that owns the bet (defaults to default_account)
Raises:ValueError – If not account for signing is provided
Returns:the signed message encapsulated in a known format
verify(**kwargs)

Verify a message with an account’s memo key

Parameters:account (str) – (optional) the account that owns the bet (defaults to default_account)
Returns:True if the message is verified successfully

:raises InvalidMessageSignature if the signature is not ok

class graphenecommon.aio.message.MessageV2(*args, **kwargs)

Bases: graphenecommon.message.MessageV2

Allow to sign and verify Messages that are sigend with a private key

sign(account=None, **kwargs)

Sign a message with an account’s memo key

Parameters:account (str) – (optional) the account that owns the bet (defaults to default_account)
Raises:ValueError – If not account for signing is provided
Returns:the signed message encapsulated in a known format
verify(**kwargs)

Verify a message with an account’s memo key

Parameters:account (str) – (optional) the account that owns the bet (defaults to default_account)
Returns:True if the message is verified successfully

:raises InvalidMessageSignature if the signature is not ok

graphenecommon.aio.price module
class graphenecommon.aio.price.Price(*args, base=None, quote=None, base_asset=None, **kwargs)

Bases: graphenecommon.price.Price

This class deals with all sorts of prices of any pair of assets to simplify dealing with the tuple:

(quote, base)

each being an instance of amount.Amount. The amount themselves define the price.

Note

The price (floating) is derived as base/quote

Parameters:
  • args (list) – Allows to deal with different representations of a price
  • base (asset.Asset) – Base asset
  • quote (asset.Asset) – Quote asset
  • blockchain_instance (instance) – instance to use when accesing a RPC
Returns:

All data required to represent a price

Return type:

dict

Way to obtain a proper instance:

  • args is a str with a price and two assets
  • args can be a floating number and base and quote being instances of asset.Asset
  • args can be a floating number and base and quote being instances of str
  • args can be dict with keys price, base, and quote (graphene balances)
  • args can be dict with keys base and quote
  • args can be dict with key receives (filled orders)
  • args being a list of [quote, base] both being instances of amount.Amount
  • args being a list of [quote, base] both being instances of str (amount symbol)
  • base and quote being instances of asset.Amount

This allows instanciations like:

  • Price("0.315 USD/BTS")
  • Price(0.315, base="USD", quote="BTS")
  • Price(0.315, base=self.asset_class("USD"), quote=self.asset_class("BTS"))
  • Price({"base": {"amount": 1, "asset_id": "1.3.0"}, "quote": {"amount": 10, "asset_id": "1.3.106"}})
  • Price({"receives": {"amount": 1, "asset_id": "1.3.0"}, "pays": {"amount": 10, "asset_id": "1.3.106"}}, base_asset=self.asset_class("1.3.0"))
  • Price(quote="10 GOLD", base="1 USD")
  • Price("10 GOLD", "1 USD")
  • Price(self.amount_class("10 GOLD"), self.amount_class("1 USD"))
  • Price(1.0, "USD/GOLD")

Instances of this class can be used in regular mathematical expressions (+-*/%) such as:

>>> from price import Price
>>> Price("0.3314 USD/BTS") * 2
0.662600000 USD/BTS
as_base(base)

Returns the price instance so that the base asset is base.

Note: This makes a copy of the object!

as_quote(quote)

Returns the price instance so that the quote asset is quote.

Note: This makes a copy of the object!

copy() → a shallow copy of D
invert()

Invert the price (e.g. go from USD/BTS into BTS/USD)

graphenecommon.aio.proposal module
class graphenecommon.aio.proposal.Proposal(data, *args, **kwargs)

Bases: graphenecommon.aio.blockchainobject.BlockchainObject, graphenecommon.proposal.Proposal

Read data about a Proposal Balance in the chain

Parameters:
  • id (str) – Id of the proposal
  • blockchain_instance (instance) – instance to use when accesing a RPC
proposer

Return the proposer of the proposal if available in the backend, else returns None

refresh()
class graphenecommon.aio.proposal.Proposals(account, *args, **kwargs)

Bases: graphenecommon.aio.blockchainobject.BlockchainObjects, graphenecommon.proposal.Proposals

Obtain a list of pending proposals for an account

Parameters:
  • account (str) – Account name
  • blockchain_instance (instance) – instance to use when accesing a RPC
refresh(*args, **kwargs)

Interface that needs to be implemented. This method is called when an object is requested that has not yet been fetched/stored

graphenecommon.aio.transactionbuilder module
class graphenecommon.aio.transactionbuilder.ProposalBuilder(proposer, proposal_expiration=None, proposal_review=None, parent=None, *args, **kwargs)

Bases: graphenecommon.transactionbuilder.ProposalBuilder

Proposal Builder allows us to construct an independent Proposal that may later be added to an instance ot TransactionBuilder

Parameters:
  • proposer (str) – Account name of the proposing user
  • proposal_expiration (int) – Number seconds until the proposal is supposed to expire
  • proposal_review (int) – Number of seconds for review of the proposal
  • transactionbuilder.TransactionBuilder – Specify your own instance of transaction builder (optional)
  • blockchain_instance (instance) – Blockchain instance
broadcast()
get_raw()

Returns an instance of base “Operations” for further processing

json()

Return the json formated version of this proposal

class graphenecommon.aio.transactionbuilder.TransactionBuilder(tx={}, proposer=None, **kwargs)

Bases: graphenecommon.transactionbuilder.TransactionBuilder

This class simplifies the creation of transactions by adding operations and signers.

addSigningInformation(account, permission)

This is a private method that adds side information to a unsigned/partial transaction in order to simplify later signing (e.g. for multisig or coldstorage)

FIXME: Does not work with owner keys!

add_required_fees(ops, asset_id='1.3.0')

Auxiliary method to obtain the required fees for a set of operations. Requires a websocket connection to a witness node!

appendSigner(accounts, permission)

Try to obtain the wif key from the wallet by telling which account and permission is supposed to sign the transaction

broadcast()

Broadcast a transaction to the blockchain network

Parameters:tx (tx) – Signed transaction to broadcast
constructTx()

Construct the actual transaction and store it in the class’s dict store

get_block_params(use_head_block=False)

Auxiliary method to obtain ref_block_num and ref_block_prefix. Requires a websocket connection to a witness node!

json()

Show the transaction as plain json

list_operations()
sign()

Sign a provided transaction with the provided key(s)

Parameters:
  • tx (dict) – The transaction to be signed and returned
  • wifs (string) – One or many wif keys to use for signing a transaction. If not present, the keys will be loaded from the wallet as defined in “missing_signatures” key of the transactions.
verify_authority()

Verify the authority of the signed transaction

graphenecommon.aio.vesting module
class graphenecommon.aio.vesting.Vesting(*args, **kwargs)

Bases: graphenecommon.aio.blockchainobject.BlockchainObject, graphenecommon.vesting.Vesting

Read data about a Vesting Balance in the chain

Parameters:
  • id (str) – Id of the vesting balance
  • blockchain_instance (instance) – instance to use when accesing a RPC
account
claim(amount=None)
claimable
refresh()
graphenecommon.aio.wallet module
class graphenecommon.aio.wallet.Wallet(*args, **kwargs)

Bases: graphenecommon.wallet.Wallet

The wallet is meant to maintain access to private keys for your accounts. It either uses manually provided private keys or uses a SQLite database managed by storage.py.

Parameters:keys (array,dict,string) – Predefine the wif keys to shortcut the wallet database

Note

Wallet should be instantiated synchroously e.g.

w = Wallet()

Three wallet operation modes are possible:

  • Wallet Database: Here, the library loads the keys from the locally stored wallet SQLite database (see storage.py).
  • Providing Keys: Here, you can provide the keys for your accounts manually. All you need to do is add the wif keys for the accounts you want to use as a simple array using the keys parameter to your blockchain instance.
  • Force keys: This more is for advanced users and requires that you know what you are doing. Here, the keys parameter is a dictionary that overwrite the active, owner, posting or memo keys for any account. This mode is only used for foreign signatures!
getAccountFromPublicKey(pub)

Obtain the first account name from public key

getAccounts()

Return all accounts installed in the wallet database

getAccountsFromPublicKey(pub)

Obtain all accounts associated with a public key

getActiveKeyForAccount(name)

Obtain owner Active Key for an account from the wallet database

getMemoKeyForAccount(name)

Obtain owner Memo Key for an account from the wallet database

getOwnerKeyForAccount(name)

Obtain owner Private Key for an account from the wallet database

graphenecommon.aio.witness module
class graphenecommon.aio.witness.Witness(*args, **kwargs)

Bases: graphenecommon.aio.blockchainobject.BlockchainObject, graphenecommon.witness.Witness

Read data about a witness in the chain

Parameters:
  • account_name (str) – Name of the witness
  • blockchain_instance (instance) – instance to use when accesing a RPC
account
is_active
refresh()
weight
class graphenecommon.aio.witness.Witnesses(*args, only_active=False, lazy=False, **kwargs)

Bases: graphenecommon.aio.blockchainobject.BlockchainObjects, graphenecommon.witness.Witnesses

Obtain a list of active witnesses and the current schedule

Parameters:
  • only_active (bool) – (False) Only return witnesses that are actively producing blocks
  • blockchain_instance (instance) – instance to use when accesing a RPC
refresh(*args, **kwargs)

Interface that needs to be implemented. This method is called when an object is requested that has not yet been fetched/stored

graphenecommon.aio.worker module
class graphenecommon.aio.worker.Worker(*args, **kwargs)

Bases: graphenecommon.aio.blockchainobject.BlockchainObject, graphenecommon.worker.Worker

Read data about a worker in the chain

Parameters:
  • id (str) – id of the worker
  • blockchain_instance (instance) – instance to use when accesing a RPC
account
refresh()
class graphenecommon.aio.worker.Workers(*args, account_name=None, lazy=False, **kwargs)

Bases: graphenecommon.aio.blockchainobject.BlockchainObjects, graphenecommon.worker.Workers

Obtain a list of workers for an account

Parameters:
  • account_name/id (str) – Name/id of the account (optional)
  • blockchain_instance (instance) – instance to use when accesing a RPC
refresh(*args, **kwargs)

Interface that needs to be implemented. This method is called when an object is requested that has not yet been fetched/stored

Module contents
Submodules
graphenecommon.account module
class graphenecommon.account.Account(*args, **kwargs)

Bases: graphenecommon.blockchainobject.BlockchainObject, graphenecommon.instance.AbstractBlockchainInstanceProvider

This class allows to easily access Account data

Parameters:
  • account_name (str) – Name of the account
  • blockchain_instance (instance) – instance to use when accesing a RPC
  • full (bool) – Obtain all account data including orders, positions, etc.
  • lazy (bool) – Use lazy loading
  • full – Obtain all account data including orders, positions, etc.
Returns:

Account data

Return type:

dictionary

Raises:

exceptions.AccountDoesNotExistsException – if account does not exist

Instances of this class are dictionaries that come with additional methods (see below) that allow dealing with an account and it’s corresponding functions.

from .account import Account
account = Account("init0")
print(account)

Note

This class comes with its own caching function to reduce the load on the API server. Instances of this class can be refreshed with Account.refresh().

balance(symbol)

Obtain the balance of a specific Asset. This call returns instances of amount.Amount.

balances

List balances of an account. This call returns instances of amount.Amount.

blacklist(account)

Add an other account to the blacklist of this account

ensure_full()
history(first=0, last=0, limit=-1, only_ops=[], exclude_ops=[])

Returns a generator for individual account transactions. The latest operation will be first. This call can be used in a for loop.

Parameters:
  • first (int) – sequence number of the first transaction to return (optional)
  • last (int) – sequence number of the last transaction to return (optional)
  • limit (int) – limit number of transactions to return (optional)
  • only_ops (array) – Limit generator by these operations (optional)
  • exclude_ops (array) – Exclude these operations from generator (optional).
… note::
only_ops and exclude_ops takes an array of strings: The full list of operation ID’s can be found in operationids.py. Example: [‘transfer’, ‘fill_order’]
is_fully_loaded

Is this instance fully loaded / e.g. all data available?

is_ltm

Is the account a lifetime member (LTM)?

name
nolist(account)

Remove an other account from any list of this account

refresh()

Refresh/Obtain an account’s data from the API server

upgrade()

Upgrade account to life time member

whitelist(account)

Add an other account to the whitelist of this account

class graphenecommon.account.AccountUpdate(data, *args, **kwargs)

Bases: dict, graphenecommon.instance.AbstractBlockchainInstanceProvider

This purpose of this class is to keep track of account updates as they are pushed through by notify.Notify.

Instances of this class are dictionaries and take the following form:

… code-block: js

{‘id’: ‘2.6.29’,
‘lifetime_fees_paid’: ‘44261516129’, ‘most_recent_op’: ‘2.9.0’, ‘owner’: ‘1.2.29’, ‘pending_fees’: 0, ‘pending_vested_fees’: 16310, ‘total_core_in_orders’: ‘6788845277634’, ‘total_ops’: 0}
account

In oder to obtain the actual account.Account from this class, you can use the account attribute.

graphenecommon.amount module
class graphenecommon.amount.Amount(*args, **kwargs)

Bases: dict, graphenecommon.instance.AbstractBlockchainInstanceProvider

This class deals with Amounts of any asset to simplify dealing with the tuple:

(amount, asset)
Parameters:
  • args (list) – Allows to deal with different representations of an amount
  • amount (float) – Let’s create an instance with a specific amount
  • asset (str) – Let’s you create an instance with a specific asset (symbol)
  • blockchain_instance (instance) – instance to use when accesing a RPC
Returns:

All data required to represent an Amount/Asset

Return type:

dict

Raises:

ValueError – if the data provided is not recognized

from peerplays.amount import Amount
from peerplays.asset import Asset
a = Amount("1 USD")
b = Amount(1, "USD")
c = Amount("20", self.asset_class("USD"))
a + b
a * 2
a += b
a /= 2.0

Way to obtain a proper instance:

  • args can be a string, e.g.: “1 USD”
  • args can be a dictionary containing amount and asset_id
  • args can be a dictionary containing amount and asset
  • args can be a list of a float and str (symbol)
  • args can be a list of a float and a asset.Asset
  • amount and asset are defined manually

An instance is a dictionary and comes with the following keys:

  • amount (float)
  • symbol (str)
  • asset (instance of asset.Asset)

Instances of this class can be used in regular mathematical expressions (+-*/%) such as:

Amount("1 USD") * 2
Amount("15 GOLD") + Amount("0.5 GOLD")
amount

Returns the amount as float

asset

Returns the asset as instance of asset.Asset

copy()

Copy the instance and make sure not to use a reference

json()
symbol

Returns the symbol of the asset

tuple()
graphenecommon.asset module
class graphenecommon.asset.Asset(*args, **kwargs)

Bases: graphenecommon.blockchainobject.BlockchainObject, graphenecommon.instance.AbstractBlockchainInstanceProvider

Deals with Assets of the network.

Parameters:
  • Asset (str) – Symbol name or object id of an asset
  • lazy (bool) – Lazy loading
  • full (bool) – Also obtain bitasset-data and dynamic asset data
  • blockchain_instance (instance) – instance to use when accesing a RPC
Returns:

All data of an asset

Return type:

dict

Note

This class comes with its own caching function to reduce the load on the API server. Instances of this class can be refreshed with Asset.refresh().

ensure_full()
flags

List the permissions that are currently used (flags)

is_bitasset

Is the asset a market pegged asset?

is_fully_loaded

Is this instance fully loaded / e.g. all data available?

permissions

List the permissions for this asset that the issuer can obtain

precision
refresh()

Refresh the data from the API server

symbol
update_cer(cer, account=None, **kwargs)

Update the Core Exchange Rate (CER) of an asset

graphenecommon.block module
class graphenecommon.block.Block(*args, use_cache=False, **kwargs)

Bases: graphenecommon.blockchainobject.BlockchainObject, graphenecommon.instance.AbstractBlockchainInstanceProvider

Read a single block from the chain

Parameters:
  • block (int) – block number
  • blockchain_instance (instance) – instance to use when accesing a RPC
  • lazy (bool) – Use lazy loading

Instances of this class are dictionaries that come with additional methods (see below) that allow dealing with a block and it’s corresponding functions.

from block import Block
block = Block(1)
print(block)

Note

This class comes with its own caching function to reduce the load on the API server. Instances of this class can be refreshed with Account.refresh().

refresh()

Even though blocks never change, you freshly obtain its contents from an API with this method

time()

Return a datatime instance for the timestamp of this block

type_id = 'n/a'
class graphenecommon.block.BlockHeader(*args, use_cache=False, **kwargs)

Bases: graphenecommon.blockchainobject.BlockchainObject, graphenecommon.instance.AbstractBlockchainInstanceProvider

refresh()

Even though blocks never change, you freshly obtain its contents from an API with this method

time()

Return a datatime instance for the timestamp of this block

type_id = 'n/a'
graphenecommon.blockchain module
class graphenecommon.blockchain.Blockchain(blockchain_instance=None, mode='irreversible', max_block_wait_repetition=None, *args, **kwargs)

Bases: graphenecommon.instance.AbstractBlockchainInstanceProvider

This class allows to access the blockchain and read data from it

Parameters:
  • blockchain_instance (instance) – instance to use when accesing a RPC
  • mode (str) – (default) Irreversible block (irreversible) or actual head block (head)
  • max_block_wait_repetition (int) – (default) 3 maximum wait time for next block ismax_block_wait_repetition * block_interval

This class let’s you deal with blockchain related data and methods.

awaitTxConfirmation(transaction, limit=10)

Returns the transaction as seen by the blockchain after being included into a block

Note

If you want instant confirmation, you need to instantiate class:.blockchain.Blockchain with mode="head", otherwise, the call will wait until confirmed in an irreversible block.

Note

This method returns once the blockchain has included a transaction with the same signature. Even though the signature is not usually used to identify a transaction, it still cannot be forfeited and is derived from the transaction contented and thus identifies a transaction uniquely.

block_time(block_num)

Returns a datetime of the block with the given block number.

Parameters:block_num (int) – Block number
block_timestamp(block_num)

Returns the timestamp of the block with the given block number.

Parameters:block_num (int) – Block number
blocks(start=None, stop=None)

Yields blocks starting from start.

Parameters:
  • start (int) – Starting block
  • stop (int) – Stop at this block
  • mode (str) – We here have the choice between “head” (the last block) and “irreversible” (the block that is confirmed by 2/3 of all block producers and is thus irreversible)
chainParameters()

The blockchain parameters, such as fees, and committee-controlled parameters are returned here

config()

Returns object 2.0.0

get_all_accounts(start='', stop='', steps=1000.0, **kwargs)

Yields account names between start and stop.

Parameters:
  • start (str) – Start at this account name
  • stop (str) – Stop at this account name
  • steps (int) – Obtain steps ret with a single call from RPC
get_block_interval()

This call returns the block interval

get_chain_properties()

Return chain properties

get_current_block()

This call returns the current block

Note

The block number returned depends on the mode used when instanciating from this class.

get_current_block_num()

This call returns the current block

Note

The block number returned depends on the mode used when instanciating from this class.

get_network()

Identify the network

Returns:Network parameters
Return type:dict
info()

This call returns the dynamic global properties

is_irreversible_mode()
ops(start=None, stop=None, **kwargs)

Yields all operations (excluding virtual operations) starting from start.

Parameters:
  • start (int) – Starting block
  • stop (int) – Stop at this block
  • mode (str) – We here have the choice between “head” (the last block) and “irreversible” (the block that is confirmed by 2/3 of all block producers and is thus irreversible)
  • only_virtual_ops (bool) – Only yield virtual operations

This call returns a list that only carries one operation and its type!

participation_rate
stream(opNames=[], *args, **kwargs)

Yield specific operations (e.g. comments) only

Parameters:
  • opNames (array) – List of operations to filter for
  • start (int) – Start at this block
  • stop (int) – Stop at this block
  • mode (str) –

    We here have the choice between * “head”: the last block * “irreversible”: the block that is confirmed by 2/3 of all

    block producers and is thus irreversible!

The dict output is formated such that type caries the operation type, timestamp and block_num are taken from the block the operation was stored in and the other key depend on the actualy operation.

update_chain_parameters()
wait_for_and_get_block(block_number, blocks_waiting_for=None)

Get the desired block from the chain, if the current head block is smaller (for both head and irreversible) then we wait, but a maxmimum of blocks_waiting_for * max_block_wait_repetition time before failure.

Parameters:
  • block_number (int) – desired block number
  • blocks_waiting_for (int) – (default) difference between block_number and current head how many blocks we are willing to wait, positive int
graphenecommon.blockchainobject module
class graphenecommon.blockchainobject.BlockchainObject(data, klass=None, lazy=False, use_cache=True, *args, **kwargs)

Bases: graphenecommon.blockchainobject.Caching, dict

This class deals with objects from graphene-based blockchains. It is used to validate object ids, store entire objects in the cache and deal with indexing thereof.

classmethod cache_object(data, key=None)

This classmethod allows to feed an object into the cache is is mostly used for testing

identifier = None
static objectid_valid(i)

Test if a string looks like a regular object id of the form::

xxxx.yyyyy.zzzz

with those being numbers.

perform_id_tests = True
space_id = 1
store(data, key='id')

Cache the list

Parameters:data (list) – List of objects to cache
test_valid_objectid(i)

Alias for objectid_valid

testid(id)

In contrast to validity, this method tests if the objectid matches the type_id provided in self.type_id or self.type_ids

type_id = None
type_ids = []
class graphenecommon.blockchainobject.BlockchainObjects(*args, **kwargs)

Bases: graphenecommon.blockchainobject.Caching, list

This class is used internally to store lists of objects and deal with the cache and indexing thereof.

cache(key)

(legacy) store the current object with key key.

classmethod cache_objects(data, key=None)

This classmethod allows to feed multiple objects into the cache is is mostly used for testing

identifier = None
refresh(*args, **kwargs)

Interface that needs to be implemented. This method is called when an object is requested that has not yet been fetched/stored

store(data, key=None, *args, **kwargs)

Cache the list

Parameters:data (list) – List of objects to cache
class graphenecommon.blockchainobject.Caching(*args, **kwargs)

Bases: object

This class implements a few common methods that are used to either cache lists or dicts

classmethod clear_cache()

Clear/Reset the entire Cache

getfromcache(id)

Get an element from the cache explicitly

incached(id)

Is an element cached?

items()

This overwrites items() so that refresh() is called if the object is not already fetched

static set_cache_store(klass, *args, **kwargs)
class graphenecommon.blockchainobject.Object(data, klass=None, lazy=False, use_cache=True, *args, **kwargs)

Bases: graphenecommon.blockchainobject.BlockchainObject, graphenecommon.instance.AbstractBlockchainInstanceProvider

This class is a basic class that allows to obtain any object from the blockchyin by fetching it through the API

refresh()

This is the refresh method that overloads the prototype in BlockchainObject.

graphenecommon.chain module
class graphenecommon.chain.AbstractGrapheneChain(node='', rpcuser='', rpcpassword='', debug=False, skip_wallet_init=False, **kwargs)

Bases: object

broadcast(tx=None)

Broadcast a transaction to the Blockchain

Parameters:tx (tx) – Signed transaction to broadcast
clear()
clear_cache()

Clear Caches

connect(node='', rpcuser='', rpcpassword='', **kwargs)

Connect to blockchain network (internal use only)

define_classes()
finalizeOp(ops, account, permission, **kwargs)

This method obtains the required private keys if present in the wallet, finalizes the transaction, signs it and broadacasts it

Parameters:
  • ops (operation) – The operation (or list of operaions) to broadcast
  • account (operation) – The account that authorizes the operation
  • permission (string) – The required permission for signing (active, owner, posting)
  • append_to (object) – This allows to provide an instance of ProposalsBuilder (see new_proposal()) or TransactionBuilder (see new_tx()) to specify where to put a specific operation.
… note:: append_to is exposed to every method used in the
this class

… note:

If ``ops`` is a list of operation, they all need to be
signable by the same key! Thus, you cannot combine ops
that require active permission with ops that require
posting permission. Neither can you use different
accounts for different operations!
… note:: This uses txbuffer as instance of
transactionbuilder.TransactionBuilder. You may want to use your own txbuffer
info()

Returns the global properties

is_connected()
newWallet(pwd)
new_proposal(parent=None, proposer=None, proposal_expiration=None, proposal_review=None, **kwargs)
new_tx(*args, **kwargs)

Let’s obtain a new txbuffer

Returns int txid:
 id of the new txbuffer
new_wallet(pwd)

Create a new wallet. This method is basically only calls wallet.Wallet.create().

Parameters:pwd (str) – Password to use for the new wallet
Raises:exceptions.WalletExists – if there is already a wallet created
prefix

Contains the prefix of the blockchain

propbuffer

Return the default proposal buffer

proposal(proposer=None, proposal_expiration=None, proposal_review=None)

Return the default proposal buffer

… note:: If any parameter is set, the default proposal
parameters will be changed!
set_blocking(block=True)

This sets a flag that forces the broadcast to block until the transactions made it into a block

set_default_account(account)

Set the default account to be used

set_shared_instance()

This method allows to set the current instance as default

sign(tx=None, wifs=[])

Sign a provided transaction witht he provided key(s)

Parameters:
  • tx (dict) – The transaction to be signed and returned
  • wifs (string) – One or many wif keys to use for signing a transaction. If not present, the keys will be loaded from the wallet as defined in “missing_signatures” key of the transactions.
tx()

Returns the default transaction buffer

txbuffer

Returns the currently active tx buffer

unlock(*args, **kwargs)

Unlock the internal wallet

graphenecommon.committee module
class graphenecommon.committee.Committee(*args, **kwargs)

Bases: graphenecommon.blockchainobject.BlockchainObject, graphenecommon.instance.AbstractBlockchainInstanceProvider

Read data about a Committee Member in the chain

Parameters:
  • member (str) – Name of the Committee Member
  • blockchain_instance (instance) – instance to use when accesing a RPC
  • lazy (bool) – Use lazy loading
account
account_id
refresh()
graphenecommon.exceptions module
exception graphenecommon.exceptions.AccountDoesNotExistsException

Bases: Exception

exception graphenecommon.exceptions.AssetDoesNotExistsException

Bases: Exception

exception graphenecommon.exceptions.BlockDoesNotExistsException

Bases: Exception

exception graphenecommon.exceptions.CommitteeMemberDoesNotExistsException

Bases: Exception

exception graphenecommon.exceptions.GenesisBalanceDoesNotExistsException

Bases: Exception

exception graphenecommon.exceptions.InsufficientAuthorityError

Bases: Exception

exception graphenecommon.exceptions.InvalidAssetException

Bases: Exception

exception graphenecommon.exceptions.InvalidMemoKeyException

Bases: Exception

exception graphenecommon.exceptions.InvalidMessageSignature

Bases: Exception

exception graphenecommon.exceptions.InvalidWifError

Bases: Exception

The provided private Key has an invalid format

exception graphenecommon.exceptions.KeyAlreadyInStoreException

Bases: Exception

The key is already stored in the store

exception graphenecommon.exceptions.KeyNotFound

Bases: Exception

Key not found

exception graphenecommon.exceptions.MissingKeyError

Bases: Exception

exception graphenecommon.exceptions.NoWalletException

Bases: Exception

No Wallet could be found, please use wallet.create() to create a new wallet

exception graphenecommon.exceptions.OfflineHasNoRPCException

Bases: Exception

When in offline mode, we don’t have RPC

exception graphenecommon.exceptions.ProposalDoesNotExistException

Bases: Exception

exception graphenecommon.exceptions.VestingBalanceDoesNotExistsException

Bases: Exception

exception graphenecommon.exceptions.WalletExists

Bases: Exception

A wallet has already been created and requires a password to be unlocked by means of wallet.unlock().

exception graphenecommon.exceptions.WalletLocked

Bases: Exception

Wallet is locked

exception graphenecommon.exceptions.WitnessDoesNotExistsException

Bases: Exception

The witness does not exist

exception graphenecommon.exceptions.WorkerDoesNotExistsException

Bases: Exception

Worker does not exist

exception graphenecommon.exceptions.WrongMemoKey

Bases: Exception

The memo provided is not equal the one on the blockchain

graphenecommon.genesisbalance module
class graphenecommon.genesisbalance.GenesisBalance(*args, **kwargs)

Bases: graphenecommon.blockchainobject.BlockchainObject, graphenecommon.instance.AbstractBlockchainInstanceProvider

Deals with Assets of the network.

Parameters:
  • Asset (str) – Symbol name or object id of an asset
  • lazy (bool) – Lazy loading
  • full (bool) – Also obtain bitasset-data and dynamic asset data
  • blockchain_instance (instance) – instance to use when accesing a RPC
Returns:

All data of an asset

Return type:

dict

Note

This class comes with its own caching function to reduce the load on the API server. Instances of this class can be refreshed with Asset.refresh().

claim(account=None, **kwargs)

Claim a balance from the genesis block

Parameters:
  • balance_id (str) – The identifier that identifies the balance to claim (1.15.x)
  • account (str) – (optional) the account that owns the bet (defaults to default_account)
refresh()
class graphenecommon.genesisbalance.GenesisBalances(**kwargs)

Bases: list, graphenecommon.instance.AbstractBlockchainInstanceProvider

List genesis balances that can be claimed from the keys in the wallet

graphenecommon.instance module
class graphenecommon.instance.AbstractBlockchainInstanceProvider(*args, **kwargs)

Bases: object

This is a class that allows compatibility with previous naming conventions. It will extract ‘blockchain_instance’ from the key word arguments and ensure that self.blockchain contains an instance of the main chain instance

blockchain
chain

Short form for blockchain (for the lazy)

define_classes()

Needs to define instance variables that provide classes

get_instance_class()

Should return the Chain instance class, e.g. bitshares.BitShares

classmethod inject(cls)
classmethod set_shared_blockchain_instance(instance)

This method allows us to override default instance for all users of SharedInstance.instance.

Parameters:instance (chaininstance) – Chain instance
classmethod set_shared_config(config)

This allows to set a config that will be used when calling shared_blockchain_instance and allows to define the configuration without requiring to actually create an instance

set_shared_instance()

This method allows to set the current instance as default

shared_blockchain_instance()

This method will initialize SharedInstance.instance and return it. The purpose of this method is to have offer single default instance that can be reused by multiple classes.

graphenecommon.instance.BlockchainInstance

alias of graphenecommon.instance.AbstractBlockchainInstanceProvider

class graphenecommon.instance.SharedInstance

Bases: object

This class merely offers a singelton for the Blockchain Instance

config = {}
instance = None
graphenecommon.instance.set_shared_blockchain_instance(instance)
graphenecommon.instance.set_shared_config(config)
graphenecommon.instance.shared_blockchain_instance()
graphenecommon.memo module
class graphenecommon.memo.Memo(from_account=None, to_account=None, **kwargs)

Bases: graphenecommon.instance.AbstractBlockchainInstanceProvider

Deals with Memos that are attached to a transfer

Parameters:
  • from_account (account.Account) – Account that has sent the memo
  • to_account (account.Account) – Account that has received the memo
  • blockchain_instance (instance) – instance to use when accesing a RPC

A memo is encrypted with a shared secret derived from a private key of the sender and a public key of the receiver. Due to the underlying mathematics, the same shared secret can be derived by the private key of the receiver and the public key of the sender. The encrypted message is perturbed by a nonce that is part of the transmitted message.

from .memo import Memo
m = Memo("from-account", "to-account")
m.blockchain.wallet.unlock("secret")
enc = (m.encrypt("foobar"))
print(enc)
>> {'nonce': '17329630356955254641', 'message': '8563e2bb2976e0217806d642901a2855'}
print(m.decrypt(enc))
>> foobar

To decrypt a memo, simply use

from memo import Memo
m = Memo()
m.blockchain.wallet.unlock("secret")
print(memo.decrypt(op_data["memo"]))

if op_data being the payload of a transfer operation.

decrypt(message)

Decrypt a message

Parameters:message (dict) – encrypted memo message
Returns:decrypted message
Return type:str
encrypt(message)

Encrypt a memo

Parameters:message (str) – clear text memo message
Returns:encrypted message
Return type:str
unlock_wallet(*args, **kwargs)

Unlock the library internal wallet

graphenecommon.message module
class graphenecommon.message.Message(*args, **kwargs)

Bases: graphenecommon.message.MessageV1, graphenecommon.message.MessageV2

sign(*args, **kwargs)

Sign a message with an account’s memo key

Parameters:account (str) – (optional) the account that owns the bet (defaults to default_account)
Raises:ValueError – If not account for signing is provided
Returns:the signed message encapsulated in a known format
supported_formats = (<class 'graphenecommon.message.MessageV1'>, <class 'graphenecommon.message.MessageV2'>)
valid_exceptions = (<class 'graphenecommon.exceptions.AccountDoesNotExistsException'>, <class 'graphenecommon.exceptions.InvalidMessageSignature'>, <class 'graphenecommon.exceptions.WrongMemoKey'>, <class 'graphenecommon.exceptions.InvalidMemoKeyException'>)
verify(**kwargs)

Verify a message with an account’s memo key

Parameters:account (str) – (optional) the account that owns the bet (defaults to default_account)
Returns:True if the message is verified successfully

:raises InvalidMessageSignature if the signature is not ok

class graphenecommon.message.MessageV1(message, *args, **kwargs)

Bases: graphenecommon.instance.AbstractBlockchainInstanceProvider

Allow to sign and verify Messages that are sigend with a private key

MESSAGE_SPLIT = ('-----BEGIN GRAPHENE SIGNED MESSAGE-----', '-----BEGIN META-----', '-----BEGIN SIGNATURE-----', '-----END GRAPHENE SIGNED MESSAGE-----')
SIGNED_MESSAGE_ENCAPSULATED = '\n{MESSAGE_SPLIT[0]}\n{message}\n{MESSAGE_SPLIT[1]}\naccount={meta[account]}\nmemokey={meta[memokey]}\nblock={meta[block]}\ntimestamp={meta[timestamp]}\n{MESSAGE_SPLIT[2]}\n{signature}\n{MESSAGE_SPLIT[3]}'
SIGNED_MESSAGE_META = '{message}\naccount={meta[account]}\nmemokey={meta[memokey]}\nblock={meta[block]}\ntimestamp={meta[timestamp]}'
sign(account=None, **kwargs)

Sign a message with an account’s memo key

Parameters:account (str) – (optional) the account that owns the bet (defaults to default_account)
Raises:ValueError – If not account for signing is provided
Returns:the signed message encapsulated in a known format
verify(**kwargs)

Verify a message with an account’s memo key

Parameters:account (str) – (optional) the account that owns the bet (defaults to default_account)
Returns:True if the message is verified successfully

:raises InvalidMessageSignature if the signature is not ok

class graphenecommon.message.MessageV2(message, *args, **kwargs)

Bases: graphenecommon.instance.AbstractBlockchainInstanceProvider

Allow to sign and verify Messages that are sigend with a private key

sign(account=None, **kwargs)

Sign a message with an account’s memo key

Parameters:account (str) – (optional) the account that owns the bet (defaults to default_account)
Raises:ValueError – If not account for signing is provided
Returns:the signed message encapsulated in a known format
verify(**kwargs)

Verify a message with an account’s memo key

Parameters:account (str) – (optional) the account that owns the bet (defaults to default_account)
Returns:True if the message is verified successfully

:raises InvalidMessageSignature if the signature is not ok

graphenecommon.objectcache module
class graphenecommon.objectcache.ObjectCacheInMemory(initial_data={}, default_expiration=60, no_overwrite=False, max_length=1000)

Bases: expiringdict.ExpiringDict, graphenecommon.objectcache.ObjectCacheInterface

This class implements an object/dict cache that comes with an expiration. Expired items are removed from the cache. The cache has a max_length.

get_expiration()

Return the default expiration

set_expiration(expiration)

Set new default expiration time in seconds (default: 10s)

class graphenecommon.objectcache.ObjectCacheInterface

Bases: object

get(key, default_value=None)
get_expiration()
set_expiration(value)
graphenecommon.price module
class graphenecommon.price.Price(*args, base=None, quote=None, base_asset=None, **kwargs)

Bases: dict, graphenecommon.instance.AbstractBlockchainInstanceProvider

This class deals with all sorts of prices of any pair of assets to simplify dealing with the tuple:

(quote, base)

each being an instance of amount.Amount. The amount themselves define the price.

Note

The price (floating) is derived as base/quote

Parameters:
  • args (list) – Allows to deal with different representations of a price
  • base (asset.Asset) – Base asset
  • quote (asset.Asset) – Quote asset
  • blockchain_instance (instance) – instance to use when accesing a RPC
Returns:

All data required to represent a price

Return type:

dict

Way to obtain a proper instance:

  • args is a str with a price and two assets
  • args can be a floating number and base and quote being instances of asset.Asset
  • args can be a floating number and base and quote being instances of str
  • args can be dict with keys price, base, and quote (graphene balances)
  • args can be dict with keys base and quote
  • args can be dict with key receives (filled orders)
  • args being a list of [quote, base] both being instances of amount.Amount
  • args being a list of [quote, base] both being instances of str (amount symbol)
  • base and quote being instances of asset.Amount

This allows instanciations like:

  • Price("0.315 USD/BTS")
  • Price(0.315, base="USD", quote="BTS")
  • Price(0.315, base=self.asset_class("USD"), quote=self.asset_class("BTS"))
  • Price({"base": {"amount": 1, "asset_id": "1.3.0"}, "quote": {"amount": 10, "asset_id": "1.3.106"}})
  • Price({"receives": {"amount": 1, "asset_id": "1.3.0"}, "pays": {"amount": 10, "asset_id": "1.3.106"}}, base_asset=self.asset_class("1.3.0"))
  • Price(quote="10 GOLD", base="1 USD")
  • Price("10 GOLD", "1 USD")
  • Price(self.amount_class("10 GOLD"), self.amount_class("1 USD"))
  • Price(1.0, "USD/GOLD")

Instances of this class can be used in regular mathematical expressions (+-*/%) such as:

>>> from price import Price
>>> Price("0.3314 USD/BTS") * 2
0.662600000 USD/BTS
as_base(base)

Returns the price instance so that the base asset is base.

Note: This makes a copy of the object!

as_quote(quote)

Returns the price instance so that the quote asset is quote.

Note: This makes a copy of the object!

copy() → a shallow copy of D
invert()

Invert the price (e.g. go from USD/BTS into BTS/USD)

json()
return {
“base”: self[“base”].json(), “quote”: self[“quote”].json()

}

symbols()
graphenecommon.proposal module
class graphenecommon.proposal.Proposal(data, *args, **kwargs)

Bases: graphenecommon.blockchainobject.BlockchainObject, graphenecommon.instance.AbstractBlockchainInstanceProvider

Read data about a Proposal Balance in the chain

Parameters:
  • id (str) – Id of the proposal
  • blockchain_instance (instance) – instance to use when accesing a RPC
expiration
is_in_review
proposed_operations
proposer

Return the proposer of the proposal if available in the backend, else returns None

refresh()
review_period
class graphenecommon.proposal.Proposals(account, *args, **kwargs)

Bases: graphenecommon.blockchainobject.BlockchainObjects, graphenecommon.instance.AbstractBlockchainInstanceProvider

Obtain a list of pending proposals for an account

Parameters:
  • account (str) – Account name
  • blockchain_instance (instance) – instance to use when accesing a RPC
refresh(*args, **kwargs)

Interface that needs to be implemented. This method is called when an object is requested that has not yet been fetched/stored

graphenecommon.transactionbuilder module
class graphenecommon.transactionbuilder.ProposalBuilder(proposer, proposal_expiration=None, proposal_review=None, parent=None, *args, **kwargs)

Bases: graphenecommon.instance.AbstractBlockchainInstanceProvider

Proposal Builder allows us to construct an independent Proposal that may later be added to an instance of TransactionBuilder

Parameters:
  • proposer (str) – Account name of the proposing user
  • proposal_expiration (int) – Number seconds until the proposal is supposed to expire
  • proposal_review (int) – Number of seconds for review of the proposal
  • transactionbuilder.TransactionBuilder – Specify your own instance of transaction builder (optional)
  • blockchain_instance (instance) – Blockchain instance
appendOps(ops, append_to=None)

Append op(s) to the transaction builder

Parameters:ops (list) – One or a list of operations
broadcast()
get_parent()

This allows to referr to the actual parent of the Proposal

get_raw()

Returns an instance of base “Operations” for further processing

is_empty()
json()

Return the json formated version of this proposal

list_operations()
set_expiration(p)
set_parent(p)
set_proposer(p)
set_review(p)
class graphenecommon.transactionbuilder.TransactionBuilder(tx={}, proposer=None, **kwargs)

Bases: dict, graphenecommon.instance.AbstractBlockchainInstanceProvider

This class simplifies the creation of transactions by adding operations and signers.

addSigningInformation(account, permission)

This is a private method that adds side information to a unsigned/partial transaction in order to simplify later signing (e.g. for multisig or coldstorage)

FIXME: Does not work with owner keys!

add_required_fees(ops, asset_id='1.3.0')

Auxiliary method to obtain the required fees for a set of operations. Requires a websocket connection to a witness node!

appendMissingSignatures()

Store which accounts/keys are supposed to sign the transaction

This method is used for an offline-signer!

appendOps(ops, append_to=None)

Append op(s) to the transaction builder

Parameters:ops (list) – One or a list of operations
appendSigner(accounts, permission)

Try to obtain the wif key from the wallet by telling which account and permission is supposed to sign the transaction

Parameters:
  • accounts (str,list,tuple,set) – accounts to sign transaction with
  • permission (str) – type of permission, e.g. “active”, “owner” etc
appendWif(wif)

Add a wif that should be used for signing of the transaction.

broadcast()

Broadcast a transaction to the blockchain network

Parameters:tx (tx) – Signed transaction to broadcast
clear()

Clear the transaction builder and start from scratch

constructTx()

Construct the actual transaction and store it in the class’s dict store

get_block_params(use_head_block=False)

Auxiliary method to obtain ref_block_num and ref_block_prefix. Requires a websocket connection to a witness node!

get_parent()

TransactionBuilders don’t have parents, they are their own parent

is_empty()
json()

Show the transaction as plain json

list_operations()
permission_types = ['active', 'owner']

Some graphene chains support more than just owner, active (e.g. steem also has ‘posting’)

set_expiration(p)
set_fee_asset(fee_asset)

Set asset to fee

sign()

Sign a provided transaction with the provided key(s)

Parameters:
  • tx (dict) – The transaction to be signed and returned
  • wifs (string) – One or many wif keys to use for signing a transaction. If not present, the keys will be loaded from the wallet as defined in “missing_signatures” key of the transactions.
verify_authority()

Verify the authority of the signed transaction

graphenecommon.utils module
graphenecommon.utils.assets_from_string(text)

Correctly split a string containing an asset pair.

Splits the string into two assets with the separator being on of the following: :, /, or -.

graphenecommon.utils.formatTime(t)

Properly Format Time for permlinks

graphenecommon.utils.formatTimeFromNow(secs=None)

Properly Format Time that is x seconds in the future

Parameters:secs (int) – Seconds to go in the future (x>0) or the past (x<0)
Returns:Properly formated time for Graphene (%Y-%m-%dT%H:%M:%S)
Return type:str
graphenecommon.utils.formatTimeString(t)

Properly Format Time for permlinks

graphenecommon.utils.parse_time(block_time)

Take a string representation of time from the blockchain, and parse it into datetime object.

graphenecommon.vesting module
class graphenecommon.vesting.Vesting(*args, **kwargs)

Bases: graphenecommon.blockchainobject.BlockchainObject, graphenecommon.instance.AbstractBlockchainInstanceProvider

Read data about a Vesting Balance in the chain

Parameters:
  • id (str) – Id of the vesting balance
  • blockchain_instance (instance) – instance to use when accesing a RPC
account
claim(amount=None)
claimable
refresh()
graphenecommon.wallet module
class graphenecommon.wallet.Wallet(*args, **kwargs)

Bases: graphenecommon.instance.AbstractBlockchainInstanceProvider

The wallet is meant to maintain access to private keys for your accounts. It either uses manually provided private keys or uses a SQLite database managed by storage.py.

Parameters:keys (array,dict,string) – Predefine the wif keys to shortcut the wallet database

Three wallet operation modes are possible:

  • Wallet Database: Here, the library loads the keys from the locally stored wallet SQLite database (see storage.py).
  • Providing Keys: Here, you can provide the keys for your accounts manually. All you need to do is add the wif keys for the accounts you want to use as a simple array using the keys parameter to your blockchain instance.
  • Force keys: This more is for advanced users and requires that you know what you are doing. Here, the keys parameter is a dictionary that overwrite the active, owner, posting or memo keys for any account. This mode is only used for foreign signatures!
addPrivateKey(wif)

Add a private key to the wallet database

changePassphrase(new_pwd)

Change the passphrase for the wallet database

create(pwd)

Alias for newWallet()

created()

Do we have a wallet database already?

getAccountFromPrivateKey(wif)

Obtain account name from private key

getAccountFromPublicKey(pub)

Obtain the first account name from public key

getAccounts()

Return all accounts installed in the wallet database

getAccountsFromPublicKey(pub)

Obtain all accounts associated with a public key

getActiveKeyForAccount(name)

Obtain owner Active Key for an account from the wallet database

getAllAccounts(pub)

Get the account data for a public key (all accounts found for this public key)

getKeyType(account, pub)

Get key type

getMemoKeyForAccount(name)

Obtain owner Memo Key for an account from the wallet database

getOwnerKeyForAccount(name)

Obtain owner Private Key for an account from the wallet database

getPrivateKeyForPublicKey(pub)

Obtain the private key for a given public key

Parameters:pub (str) – Public Key
getPublicKeys(current=False)

Return all installed public keys

Parameters:current (bool) – If true, returns only keys for currently connected blockchain
is_encrypted()

Is the key store encrypted?

lock()

Lock the wallet database

locked()

Is the wallet database locked?

newWallet(pwd)

Create a new wallet database

prefix
privatekey(key)
publickey_from_wif(wif)
removeAccount(account)

Remove all keys associated with a given account

removePrivateKeyFromPublicKey(pub)

Remove a key from the wallet database

rpc
setKeys(loadkeys)

This method is strictly only for in memory keys that are passed to Wallet with the keys argument

unlock(pwd)

Unlock the wallet database

unlocked()

Is the wallet database unlocked?

wipe(sure=False)
graphenecommon.witness module
class graphenecommon.witness.Witness(*args, **kwargs)

Bases: graphenecommon.blockchainobject.BlockchainObject, graphenecommon.instance.AbstractBlockchainInstanceProvider

Read data about a witness in the chain

Parameters:
  • account_name (str) – Name of the witness
  • blockchain_instance (instance) – instance to use when accesing a RPC
account
is_active
refresh()
weight
class graphenecommon.witness.Witnesses(*args, only_active=False, lazy=False, **kwargs)

Bases: graphenecommon.blockchainobject.BlockchainObjects, graphenecommon.instance.AbstractBlockchainInstanceProvider

Obtain a list of active witnesses and the current schedule

Parameters:
  • only_active (bool) – (False) Only return witnesses that are actively producing blocks
  • blockchain_instance (instance) – instance to use when accesing a RPC
refresh(*args, **kwargs)

Interface that needs to be implemented. This method is called when an object is requested that has not yet been fetched/stored

graphenecommon.worker module
class graphenecommon.worker.Worker(*args, **kwargs)

Bases: graphenecommon.blockchainobject.BlockchainObject, graphenecommon.instance.AbstractBlockchainInstanceProvider

Read data about a worker in the chain

Parameters:
  • id (str) – id of the worker
  • blockchain_instance (instance) – instance to use when accesing a RPC
account
post_format()
refresh()
class graphenecommon.worker.Workers(*args, account_name=None, lazy=False, **kwargs)

Bases: graphenecommon.blockchainobject.BlockchainObjects, graphenecommon.instance.AbstractBlockchainInstanceProvider

Obtain a list of workers for an account

Parameters:
  • account_name/id (str) – Name/id of the account (optional)
  • blockchain_instance (instance) – instance to use when accesing a RPC
refresh(*args, **kwargs)

Interface that needs to be implemented. This method is called when an object is requested that has not yet been fetched/stored

Module contents

graphenestorage package

Submodules
graphenestorage.base module
class graphenestorage.base.InRamConfigurationStore(*args, **kwargs)

Bases: graphenestorage.ram.InRamStore, graphenestorage.interfaces.ConfigInterface

A simple example that stores configuration in RAM.

Internally, this works by simply inheriting graphenestorage.ram.InRamStore. The interface is defined in graphenestorage.interfaces.ConfigInterface.

class graphenestorage.base.InRamEncryptedKeyStore(*args, **kwargs)

Bases: graphenestorage.ram.InRamStore, graphenestorage.base.KeyEncryption

An in-RAM Store that stores keys encrypted in RAM.

Internally, this works by simply inheriting graphenestorage.ram.InRamStore. The interface is defined in graphenestorage.interfaces.KeyInterface.

Note

This module also inherits graphenestorage.masterpassword.MasterPassword which offers additional methods and deals with encrypting the keys.

class graphenestorage.base.InRamPlainKeyStore(*args, **kwargs)

Bases: graphenestorage.ram.InRamStore, graphenestorage.interfaces.KeyInterface

A simple in-RAM Store that stores keys unencrypted in RAM

Internally, this works by simply inheriting graphenestorage.ram.InRamStore. The interface is defined in graphenestorage.interfaces.KeyInterface.

add(wif, pub)
Add a new public/private key pair (correspondence has to be
checked elsewhere!)
Parameters:
  • pub (str) – Public key
  • wif (str) – Private key
delete(pub)

Delete a key from the store

getPrivateKeyForPublicKey(pub)
Returns the (possibly encrypted) private key that
corresponds to a public key
Parameters:pub (str) – Public key

The encryption scheme is BIP38

getPublicKeys()

Returns the public keys stored in the database

class graphenestorage.base.KeyEncryption(*args, **kwargs)

Bases: graphenestorage.masterpassword.MasterPassword, graphenestorage.interfaces.EncryptedKeyInterface

This is an interface class that provides the methods required for EncryptedKeyInterface and links them to the MasterPassword-provided functionatlity, accordingly.

add(wif, pub)
Add a new public/private key pair (correspondence has to be
checked elsewhere!)
Parameters:
  • pub (str) – Public key
  • wif (str) – Private key
getPrivateKeyForPublicKey(pub)
Returns the (possibly encrypted) private key that
corresponds to a public key
Parameters:pub (str) – Public key

The encryption scheme is BIP38

getPublicKeys()

Returns the public keys stored in the database

is_encrypted()

Returns True/False to indicate required use of unlock

class graphenestorage.base.SqliteConfigurationStore(*args, **kwargs)

Bases: graphenestorage.sqlite.SQLiteStore, graphenestorage.interfaces.ConfigInterface

This is the configuration storage that stores key/value pairs in the config table of the SQLite3 database.

Internally, this works by simply inheriting graphenestorage.sqlite.SQLiteStore. The interface is defined in graphenestorage.interfaces.ConfigInterface.

class graphenestorage.base.SqliteEncryptedKeyStore(*args, **kwargs)

Bases: graphenestorage.sqlite.SQLiteStore, graphenestorage.base.KeyEncryption

This is the key storage that stores the public key and the encrypted private key in the keys table in the SQLite3 database.

Internally, this works by simply inheriting graphenestorage.ram.InRamStore. The interface is defined in graphenestorage.interfaces.KeyInterface.

Note

This module also inherits graphenestorage.masterpassword.MasterPassword which offers additional methods and deals with encrypting the keys.

class graphenestorage.base.SqlitePlainKeyStore(*args, **kwargs)

Bases: graphenestorage.sqlite.SQLiteStore, graphenestorage.interfaces.KeyInterface

This is the key storage that stores the public key and the unencrypted private key in the keys table in the SQLite3 database.

Internally, this works by simply inheriting graphenestorage.ram.InRamStore. The interface is defined in graphenestorage.interfaces.KeyInterface.

add(wif, pub)
Add a new public/private key pair (correspondence has to be
checked elsewhere!)
Parameters:
  • pub (str) – Public key
  • wif (str) – Private key
delete(pub)

Delete a key from the store

Parameters:value (str) – Value
getPrivateKeyForPublicKey(pub)
Returns the (possibly encrypted) private key that
corresponds to a public key
Parameters:pub (str) – Public key

The encryption scheme is BIP38

getPublicKeys()

Returns the public keys stored in the database

is_encrypted()

Returns False, as we are not encrypted here

graphenestorage.exceptions module
exception graphenestorage.exceptions.KeyAlreadyInStoreException

Bases: Exception

The key of a key/value pair is already in the store

exception graphenestorage.exceptions.WalletLocked

Bases: Exception

exception graphenestorage.exceptions.WrongMasterPasswordException

Bases: Exception

The password provided could not properly unlock the wallet

graphenestorage.interfaces module
class graphenestorage.interfaces.ConfigInterface(*args, **kwargs)

Bases: graphenestorage.interfaces.StoreInterface

The BaseKeyStore defines the interface for key storage

Note

This class inherits graphenestorage.interfaces.StoreInterface and defines no additional configuration-specific methods.

class graphenestorage.interfaces.EncryptedKeyInterface(*args, **kwargs)

Bases: graphenestorage.interfaces.KeyInterface

The EncryptedKeyInterface extends KeyInterface to work with encrypted keys

is_encrypted()

Returns True/False to indicate required use of unlock

lock()

Lock the wallet again

locked()

is the wallet locked?

unlock(password)

Tries to unlock the wallet if required

Parameters:password (str) – Plain password
class graphenestorage.interfaces.KeyInterface(*args, **kwargs)

Bases: graphenestorage.interfaces.StoreInterface

The KeyInterface defines the interface for key storage.

Note

This class inherits graphenestorage.interfaces.StoreInterface and defines additional key-specific methods.

add(wif, pub=None)
Add a new public/private key pair (correspondence has to be
checked elsewhere!)
Parameters:
  • pub (str) – Public key
  • wif (str) – Private key
delete(pub)

Delete a pubkey/privatekey pair from the store

Parameters:pub (str) – Public key
getPrivateKeyForPublicKey(pub)
Returns the (possibly encrypted) private key that
corresponds to a public key
Parameters:pub (str) – Public key

The encryption scheme is BIP38

getPublicKeys()

Returns the public keys stored in the database

is_encrypted()

Returns True/False to indicate required use of unlock

class graphenestorage.interfaces.StoreInterface(*args, **kwargs)

Bases: dict

The store interface is the most general store that we can have.

It inherits dict and thus behaves like a dictionary. As such any key/value store can be used as store with or even without an adaptor.

Note

This class defines defaults that are used to return reasonable defaults for the library.

Warning

If you are trying to obtain a value for a key that does not exist in the store, the library will NOT raise but return a None value. This represents the biggest difference to a regular dict class.

Methods that need to be implemented:

  • def setdefault(cls, key, value)
  • def __init__(self, *args, **kwargs)
  • def __setitem__(self, key, value)
  • def __getitem__(self, key)
  • def __iter__(self)
  • def __len__(self)
  • def __contains__(self, key)

Note

Configuration and Key classes are subclasses of this to allow storing keys separate from configuration.

defaults = {}
delete(key)

Delete a key from the store

get(key, default=None)

Return the key if exists or a default value

items()

Returns all items off the store as tuples

classmethod setdefault(key, value)

Allows to define default values

wipe()

Wipe the store

graphenestorage.masterpassword module
class graphenestorage.masterpassword.MasterPassword(config=None, **kwargs)

Bases: object

The keys are encrypted with a Masterpassword that is stored in the configurationStore. It has a checksum to verify correctness of the password The encrypted private keys in keys are encrypted with a random masterkey/masterpassword that is stored in the configuration encrypted by the user-provided password.

Parameters:config (ConfigStore) – Configuration store to get access to the encrypted master password
changePassword(newpassword)
change_password(newpassword)

Change the password that allows to decrypt the master key

decrypt(wif)

Decrypt the content according to BIP38

Parameters:wif (str) – Encrypted key
encrypt(wif)

Encrypt the content according to BIP38

Parameters:wif (str) – Unencrypted key
has_masterpassword()

Tells us if the config store knows an encrypted masterpassword

lock()

Lock the store so that we can no longer decrypt the content of the store

locked()

Is the store locked. E.g. Is a valid password known that can be used to decrypt the master key?

masterkey

Contains the decrypted master key

unlock(password)

The password is used to encrypt this masterpassword. To decrypt the keys stored in the keys database, one must use BIP38, decrypt the masterpassword from the configuration store with the user password, and use the decrypted masterpassword to decrypt the BIP38 encrypted private keys from the keys storage!

Parameters:password (str) – Password to use for en-/de-cryption
unlocked()

Is the store unlocked so that I can decrypt the content?

graphenestorage.ram module
class graphenestorage.ram.InRamStore(*args, **kwargs)

Bases: graphenestorage.interfaces.StoreInterface

The InRamStore inherits graphenestore.interfaces.StoreInterface and extends it by two further calls for wipe and delete.

The store is syntactically equivalent to a regular dictionary.

Warning

If you are trying to obtain a value for a key that does not exist in the store, the library will NOT raise but return a None value. This represents the biggest difference to a regular dict class.

delete(key)

Delete a key from the store

wipe()

Wipe the store

graphenestorage.sqlite module
class graphenestorage.sqlite.SQLiteCommon

Bases: object

This class abstracts away common sqlite3 operations.

This class should not be used directly.

When inheriting from this class, the following instance members must be defined:

  • sqlite_file: Path to the SQLite Database file
sql_execute(query, lastid=False)
sql_fetchall(query)
sql_fetchone(query)
class graphenestorage.sqlite.SQLiteFile(*args, **kwargs)

Bases: object

This class ensures that the user’s data is stored in its OS preotected user directory:

OSX:

  • ~/Library/Application Support/<AppName>

Windows:

  • C:Documents and Settings<User>Application DataLocal Settings<AppAuthor><AppName>
  • C:Documents and Settings<User>Application Data<AppAuthor><AppName>

Linux:

  • ~/.local/share/<AppName>

Furthermore, it offers an interface to generated backups in the backups/ directory every now and then.

Note

The file name can be overwritten when providing a keyword argument profile.

sqlite_file = None

Ensure that the directory in which the data is stored exists

class graphenestorage.sqlite.SQLiteStore(*args, **kwargs)

Bases: graphenestorage.sqlite.SQLiteFile, graphenestorage.sqlite.SQLiteCommon, graphenestorage.interfaces.StoreInterface

The SQLiteStore deals with the sqlite3 part of storing data into a database file.

Note

This module is limited to two columns and merely stores key/value pairs into the sqlite database

On first launch, the database file as well as the tables are created automatically.

When inheriting from this class, the following three class members must be defined:

  • __tablename__: Name of the table
  • __key__: Name of the key column
  • __value__: Name of the value column
create()

Create the new table in the SQLite database

delete(key)

Delete a key from the store

Parameters:value (str) – Value
exists()

Check if the database table exists

get(key, default=None)

Return the key if exists or a default value

Parameters:
  • value (str) – Value
  • default (str) – Default value if key not present
items()

returns all items off the store as tuples

keys() → a set-like object providing a view on D's keys
wipe()

Wipe the store

Module contents

Indices and tables