python-blockchain.png

Python packages for Blockchain

BlockChain Expert 24/October/2017
The Blockchain is an emerging technology which provides a platform for managing digital assets. Blockchain also serves as a distributed ledger where all the transactions are stored publically. The high-level language Python can be used to develop Blockchain applications. Python can interact with the public ledger API of Blockchain ‘blockchain.info’ and execute our codes. ‘blockchain.info’ package is available in ‘github’, you can download it from there. Installation method is described below.
 
Installation using pip:
        $ pip install blockchain
Installation from Github:
   $ git clone https://github.com/blockchain/api-v1-client-python
   $ cd api-v1-client-python
   $ python setup.py install

This ‘blockchain.info’ package supports python 2 and python 3. The package consists of 7 modules, they are:-

1. blockexplorer
2. create wallet
3. exchange rates
4. pushtx
5. v2.receive
6. Statistics
7. Wallet

Block, Address, and Transaction are the major objects used in Blockchain. Python package provides you many built-in functions to perform operations and transactions on these objects.

1. blockexplorer Module
‘blockexplorer’ is the most important module in blockchain package which has Ten inbuilt functions to perform Blockchain manipulation operations. To import the package to our Python code we can use the following code.
  from blockchain import blockexplorer
 
1) get_block()
 
get_block is used to access a block from blockchain using the blocks hash value. The function will return the accessed block.
 
Parameters
block_id : str - block hash
example:-
Block =blockexplorer. get_block('g2d9e6257899a5a7994ca3c81315af180273de34c75f9d8933')

2) get_tx()
You can get a transaction object from a blockchain using ‘get_tx’ function. Pass the transaction hash as a parameter to specify the object.

Parameters:
tx_id : str - transaction hash
Example:-
from blockchain import blockexplorer
transaction =blockexplorer. get_tx('726962b93d0f233d144dc9c8ada3a49251df804a135e43df5e8ac8e33182f98')

3) get_address()
This method is used to return a single address and all its transactions.by specifying a block address.
Parameters:
address:       str -             address(base58 or hash160).
filter:        FilterType -    The filter for transactions selection (not mandatory)
limit:         int -             The number of transactions to display (not mandatory)
offset:        int -             The number of transactions to skip (not mandatory)```
example:-
Address1 =blockexplorer.get_address('k47ghd5kqwrui4984yfny4vbi3yevf')

4) get_block_height()
This function will return an array of block objects at the specified height.
You can get an array of block object with ‘get_block_height()’ method. Pass the number of blocks as a parameter.
Parameters:
height:      int - block height
Example:-
height1=blockexplorer .get_block_height('20158')

5) get_xpub()
Get an extended public key object and all its transactions using ‘get_xpub()’ method. The method takes one mandatory and three optional parameters as below.
Parameters:
xpu:          str           xpub to look up
filter :       FilterType - The filter for transactions selection (Not mandatory)
limit :        int -        Number of transactions to display (Not mandatory)
offset :      int -         The number of transactions to skip (Not mandatory)
example:-
xpubs=blockexplorer.get_xpub('p37fhfkg82hb7rw6eb1dnd983bvyd1yu227cb3ve8f93nnu7tvbs3nh
a5srt7dds9fu8f')

6) get_multi_address()
You can use ‘get_multi_address()’ method to get a multi-address object containing the summary of multiple addresses. The object also returns overall balance, per address balance etc.
Parameters:
addresses :    tuple - addresses(base58 or xpub) to look up
filter :       FilterType -    The filter for transactions selection (not mandatory)
limit :        int -  The number of transactions to display (not mandatory)
offset :       int - number of transactions to skip (not mandatory)
example:-
addresses=blockexplorer.get_multi_address('7rw6eb1dnd983bvyd1yu227c’,’p37fhfkg82hbb3ve8f’,’93nnu7tvbs3nha5srt7’,r5thja3bf0j18gfjhgds9fu8f')

7) get_unspent_outputs()
You can get the details of all ‘UnspentOutput’ objects using this method.
Parameters:
addresses:            tuple addresses - addresses in the base58 format or in ‘xpub’ format
confirmations:    int - minimum number confirmations to include (optional)
limit :   int - number of unspent outputs to fetch (optional)
example:-
unspent=blockexplorer.get_unspent_outputs('7rw6eb1dnd983bvyd1yu227cmdu73hfjfiterhendt34’)

8) get_latest_block()
Get the details of the latest block added in Blockchain using ‘get_latest_block()’ method.
example:-
latest=blockexplorer.get_latest_block()

9) get_unconfirmed_tx()
You can access the details of all unconfirmed transaction objects using ‘get_unconfirmed_tx()’ method.
example:-
latest=blockexplorer.get_unconfirmed_tx()

10) get_blocks()
This function will return an array of ‘SimpleBlock’ objects for a specified day or for a specified mining tool.
Parameters:
time : int - unix time in ms (optional)
pool_name : str - pool name (optional)
example:-
blocks=blockexplorer.get_blocks(1324213)

2.createwallet module
All the basic operations related to a digital wallet is managed with this module. The digital wallet is an important organ of Blockchain based financial transactions. It is similar to a bank account, all your digital assets are stored inside it. 
You have to run an instance of service-my-wallet-v3 to use ‘Createwallet’ and ‘Wallet’ modules. Moreover, to create a wallet you need an ‘api_code’ also. You can obtain the ‘api_code’ from https://api.blockchain.info/customer/signup
The one and only function available in createwallet module is ‘create_wallet()’. To import the package into our Python code we can use the following code.
  from blockchain import createwallet

1)create_wallet()
This function is used to create a new Blockchain.info wallet. The new wallet can be created with a pre-generated private key or the method can generate a new private key. It will return a CreateWalletResponse instance.
Parameters
password :       str        password for the new wallet. At least 10 characters.
api_code :       str       API code with the create wallets permission
service_url:     str      URL to an instance of service-my-wallet-v3 (with trailing slash)
priv :           str       private key to add to the wallet (optional)
label :          str      label for the first address in the wallet (optional)
email :          str      email to associate with the new wallet (optional)
example:-
wallet = createwallet.create_wallet('675password', '32ts91klsop', 'http://localhost:3002/', label = 'demo wallet')
3.exchangerates module
This module supports managing the digital currency exchanges. The module provides 2 built-in methods to facilitate the exchange process.
To import the package into our Python code we can use the following code.
  from blockchain import  exchangerates

1)get_ticker
get_ticker() method will return a dictionary of ‘Currency’ objects. Values in the dictionary represent the ‘currency’ object and the keys represent the currency symbols. 
example:-
    ticker = exchangerates.get_ticker()

2)to_btc
The function can convert any currency to its equivalent bitcoin value.
Parameters:
ccy :        str   currency code
value :     float
example:-
btc_amount = exchangerates.to_btc('INR', 400000)
4.pushtx module
This module will provide support for the transaction broadcasting. It contains only one function which is used for the broadcasting of transactions.
To import the package into our Python code we can use the following code.
    from blockchain import  pushtx

1)pushtx
This function is used to broadcast an encoded transaction to the blockchain. The method will return an exception if the transaction is a distorted one. 
Parameters:
tx :              str     (hex encoded)
api_code :   str      (optional)
example:-
pushtx.pushtx(‘10sdh47eb239rh39sk4jdudg534kfk565msdfu89fgfhtu67856y47efbhdfn4u3487hcb’)
5.v2.receive module
Blockchain Receive Payments API V2 is the fastest way to receive automated bitcoin payments. Use this module to implement the same.
To import the package into our Python code we can use the following code.
  from blockchain.v2 import receive

1)receive
The method receives is used to generate a forwarding address. A ‘ReceiveResponse’ object returned by it.
Parameters:
xpub :               str          the xpub address
callback :          str          call back address
api_code :         str          your api key
example:-
resp = receive.receive('1sdyh35sdgsdf6fgrt535gtrfg423gbcd2A', 'http://my.demo.com?invoice=634125', 'your api key')

2)callback_log
Get the list of call-backs performed for particular callback URL. The method will return a list of ‘LogEntry’ objects.
Parameters:
callback : str
api_code : str
example:-
logs = receive.callback_log('http://my.demo.com?invoice_id=634125', 'your api key')

6.statistics module
The module can be used to obtain the complete blockchain statistics like the total number of blocks, a number of transactions, mined blocks, total bitcoins send, etc. The module implements only one function that is ‘get’ 
     To import the package into our Python code we can use the following code.
  from blockchain import statistics

1)get
Get network statistics. Returns a Stats object.
Parameters:
api_code : str (optional)
example:-
    stats= statistics.get()
7.wallet module
While the create wallet module used only for creating a digital wallet, this module completes the rest of the operations in the wallet. The module contains 7 built-in functions to perform different operations in a wallet.  The methods in Wallet class are accessed through an initialized instance of Wallet class. See the below example.
Constructor parameters:
identifier :               str
password :               str
service_url :             str      URL to an instance of service-my-wallet-v3 (with trailing slash)
second_password :  str       (optional)
api_code :                str       (optional)
constructor example;
wallet = Wallet('7i2gh5dv-5t1n-54j1-nges-947243m4zx12', 'password987', 'http://localhost:3001/')
     To import the package into our Python code we can use the following code.   
 from blockchain import wallet

1)send
You can use send() method to send the bitcoin from your wallet to a single address. ‘PaymentResponse’ object is returned to success.
Parameters:
to :                         str            receiving address
amount :                int            amount to send (in satoshi)
from_address :      str            specific address to send from (optional)
fee :                       int            transaction fee in satoshi. Must be greater than default (optional)
note :                     str             public note to include with the transaction if amount >= 0.005 BTC 
example:-
payment = wallet.send('9ght53sdvmi98r6dxcvnjjtd45hmmi75erdcbj876', 5000000, from_address='5jkhd378kjhtd57nh55cvmo73svl98gce4090mnv')

2)send_many
You can use send_many() method to send bitcoin from your wallet to multiple addresses. ‘PaymentResponse’ object is returned to success.
Parameters:
recipients:               dictionary                    dictionary with the structure of 'address':amount
from_address :         str                                specific address to send from (optional)
fee:                          int                        transaction fee in satoshi. Must be greater than default 
 (optional)
note:                       str -              public note to include with the transaction if amount >= 0.005 BTC 
Example:-
payment = wallet.send_many({‘jeygy4237846fd8mfsdkjd’:50000,’po9674yrhn872784io9yhgs83’:100000})

3)get_balance
This function is used to fetch the wallet balance. 
example:-
print wallet.get_balance()

4)list_addresses
List_addresses() method is used to list all active addresses in the wallet. An array of ‘Address’ objects are returned by this method.
Parameters:
confirmations:    int      minimum number of confirmations transactions must have before being included in balance of addresses (optional)
Example:-
       addresses = wallet.list_addresses()
5)get_address  
get_address () method is used to Retrieve an address from the wallet. An array of ‘Address’ objects are returned by this method
Parameters:
confirmations:        int                minimum number of confirmations transactions must have before being included in the balance (optional)
Example:-
addr = wallet.get_address('86hbtd5436gvhaiai6e765reg', confirmations = 2)

6)new_address
new_address () method is used to Generate a new address and add it to the wallet. An ‘Address’ object is returned by this method
Parameters:
label :      str        label to attach to the address (optional)
Example:-
newaddress = wallet.new_address('test_label')

7)archive_address
archive_address () method is used to Archive an address. A string representation of the archived address is returned by this method
Parameters:
address :          str            address to archive
Example:-
wallet.archive_address('7ysdBvb5fdbDduNy56ghd5syRdcgbs8btb’)

8)unarchive_address
unarchive_address () method is used to un-archive an address. A string representation of the un-archived address is returned by this method
Parameters:
address:                   str           address to un-archive
Example:-
wallet.unarchive_address('7ysdBvb5fdbDduNy56ghd5syRdcgbs8btb')