Skip to content
Eslam Ali edited this page Jun 21, 2018 · 8 revisions

Introduction

This documentation explains koyn library public methods and literals. It also explains how you can change your preferences from Config.h file inside the library, and if you would like to make use of more functionalities like the serial debugger option.

User Preferences

The following are some preferences which can be altered according to each and every hardware platform interfaced with the library (In terms of performance and memory capabilities). You can find them under the "User Preference" section inside Config.h file.

Disclaimer

Changing preferences is critical to your hardware performance, so make sure to study your hardware capabilities and that it can support such changes.

MAX_CONNECTED_SERVERS

Defines the maximum number of Bitcoin client/server connections your hardware can establish. For example with ESP8266, the optimum number of connected bitcoin servers are 5, but since we are dealing with Bitcoin testnet we adjusted the max connected servers to 3 according to the available number of servers.

MAX_PARALLEL_REQUESTS

Defines the maximum number of requests koyn library can handle using the client/server connections. Default value "20".

SD_CARD_CHIP_SELECT

Defines a digital pin as a chip select trigger for the SD card shield, so please make sure to use the proper pin number with your hardware. Default for ESP8266 "pin15".

MAX_TRANSACTION_COUNT

Defines the maximum number of transactions koyn library can save in a session. This preference is also related to others explained bellow. By default koyn library can handle maximum 10 transactions per session.

MAX_TRANSACTION_SIZE

Defines the max size per transaction to be saved in the hardware memory, For ESP8266 modules by default a transaction can have 1000 bytes max, otherwise it will be discarded by the library. This is a critical key for your hardware performance, changing the size of transaction will affect the memory and may lead to undefined behavior.

REMOVE_CONFIRMED_TRANSACTION_AFTER

Defines the number of blocks a confirmed transaction (included in block) could stay in memory then automatically removed by the library.

REMOVE_UNCONFIRMED_TRANSACTION_AFTER

Defines the number of blocks an unconfirmed transaction (not included in block) could stay in memory then automatically removed by the library.

MAX_TRACKED_ADDRESSES_COUNT

Defines maximum number of addresses (accounts) to be tracked in a single session.

USE_TEST_NET

Defines the use of Bitcoin test network. Activated by default.

USE_MAIN_NET

Defines the use of Bitcoin main network. Currently commented as the library is under development and is not ready to be used with the main network. Disclaimer: Using this option will be under your responsibility.

ENABLE_DEBUG_MESSAGES

Enables debugging messages.

Koyn:

void begin()

Starts the library by checking on:

  • SD card was mounted.
  • koyn directory folder exists along with blkhdrs file.
  • Connected to servers.
  • Updating the device by subscribing to headers and peers.

Return

Void.

Parameters

Void.

 

void run();

The magical function where everything happens from syncing, verifying, checking connectivity and managing data.

Return

Void.

Parameters

Void.

 

uint8_t trackAddress(BitcoinAddress * address);

Tracks a bitcoin address over the Bitcoin network and checks its status and creates a folder with the last 8 char from the address. This folder contains:

  • History of address.
  • Status of address.
  • Unspent transactions history "UTXO".

Return

States according the address provided:

  • (MAIN_NET_NOT_SUPPORTED)If address provided from main net.(temporary until main net is supported)
  • (MAX_ADDRESSES_TRACKED_REACHED) If max number of addresses tracked reached.
  • (TRACKING_ADDRESS) If tracking was successful.
  • (TRACKING_ADDRESS_ERROR) If something went wrong and network couldn't track the address, for example miss typed address.

Parameters

A pointer to your BitcoinAddress (address).

 

void unTrackAddress(BitcoinAddress * address);

unTrack a bitcoin address and permanently removes the corresponding address folder from the SD card.

Return

Void.

Parameters

A pointer to your BitcoinAddress (address).

 

unTrack all tracked bitcoin addresses and permanently removes the corresponding addresses folders from the SD card.

Return

Void.

Parameters

Void.

 

bool isAddressTracked(BitcoinAddress * address);

Check if address was tracked by the network.

Return

A Yes '1' or No '0'.

Parameters

A pointer to your BitcoinAddress (address).

 

bool isSynced();

Check if the library is up to date with the network and that it got all verified missing blockchain headers.

Return

A Yes '1' or No '0'.

Parameters

Void.

 

void onNewTransaction(void (*userFunction)(BitcoinTransaction));

A callback method to be called once a new transaction occurred in the network including one of the tracked addresses.

Return

Void.

Parameters

A pointer to a function that takes a BitcoinTransaction object as a parameter to fetch the addresses from the returned transaction and check the amount received/spent by such addresses.

Example

Koyn.onNewTransaction(&paymentCallback);
/* Callback function to take a physical action when a transaction is received. */
void paymentCallback(BitcoinTransaction tx){
  /* Loop over Inputs and check my friends address. */
  for(int i=0;i<tx.getInputsCount();i++)
  {
    /* Creating an empty address object. */
    BitcoinAddress from;
    /* Retrieving address from transaction. */
    tx.getInput(i, &from);
    if(from == myFriendAddress){
      /* Loop over my address and check the payment value. */
      for(int j=0;j<tx.getOutputsCount();j++)
      {
        /* Create an empty address object. */
        BitcoinAddress to;
        /* Retrieving address from transaction. */
        tx.getOutput(j, &to);
        if(to == myAddress){
          /* Check payment value and get amount using address index. */
          if(tx.getOutputAmount(j) >= PAYMENT_VALUE){
              /* Turn on the light bulb. */
              digitalWrite(LIGHT_BULB, HIGH);
              /* Delay for a second. */
              Koyn.delay(1000);
              /* Turn off the light bulb. */
              digitalWrite(LIGHT_BULB, LOW); 
          }
        break;          
        }
      }
      break;
    }
  }
}

 

void onNewBlockHeader(void (*userFunction)(uint32_t));

A callback method to be called once a new blockchain header received by the network.

Return

Void.

Parameters

A pointer to a function that takes a 32 bit integer holding the height of the new blockchain header.

Example

Koyn.onNewBlockHeader(&newBlockCallback);
/* Callback function to take a physical action when a new blockheader received. */
void newBlockCallback(uint32_t blockNumber){
    Serial.println("New Block Received");
}

 

void delay(unsigned long time);

A delay method.

Return

Void.

Parameters

A 64 bit integer representing the number of seconds (time) to be delayed.

 

uint8_t spend(BitcoinAddress * fromAddress, BitcoinAddress * toAddress, uint64_t amount, uint64_t fees, BitcoinAddress * changeAddress);

A 1to1 spending method to spend bitcoins from an address to other address and a change returned to a certain address.

Transaction is passed but under certain conditions:

  • Spending address should be a valid address.(Testnet addresses P2PKH currently supported)
  • Spending address balance should cover both the amount to be spent plus the fees otherwise the transaction will be discarded.
  • Spending address private key must be provided when created otherwise the signing method won't be completed and transaction will be discarded.
  • Spending address should be tracked by the library.
  • Receiving address should be a valid address.
  • Amount provided in transaction should be a valid value and not 0.
  • Fees should meet the network expected value otherwise the network will refuse the transaction.
  • Amount and fees are represented in satoshis and not bitcoins.

Return

Zero if parameters given passed the conditions explained earlier, but still the network has the higher authority to refuse or accept the transaction, otherwise a value is returned according to an error met with one of the conditions. States according the address provided:

  • (TRANSACTION_PASSED) If all the conditions were met by the koyn library.
  • (INVALID_AMOUNT) If amount provided is 0.
  • (ADDRESS_NOT_TRACKED) If fromAddress was not tracked.
  • (ADDRESS_NO_FUNDS) If fromAddress's confirmed balance can't cover the amount given.
  • (ADDRESS_INSUFFICIENT_BALANCE) If totalAmount (amount+fees) not covered by fromAddress's confirmed balance.
  • (ADDRESS_NO_PRIVATE_KEY) If fromAddress provided doesn't have the private key.
  • (ADDRESS_INVALID) If any of the addresses (fromAddress, toAddress, changeAddress) are invalid.

Parameters

  • Spending address (fromAddress).
  • Receiving address (toAddress).
  • Amount to be spent in satoshis (amount).
  • Fees of transaction (fees).
  • Change address (changeAddress).

 

uint8_t spend(BitcoinAddress * fromAddress, BitcoinAddress * toAddress, uint64_t amount, uint64_t fees);

A 1to1 spending method to spend bitcoins from an address to other address and automatically return the change (if there's any) to fromAddress.

Transaction is passed but under certain conditions:

  • Spending address should be a valid address.(Testnet addresses P2PKH currently supported)
  • Spending address balance should cover both the amount to be spent plus the fees otherwise the transaction will be discarded.
  • Spending address private key must be provided when created otherwise the signing method won't be completed and transaction will be discarded.
  • Spending address should be tracked by the library.
  • Receiving address should be a valid address.
  • Amount provided in transaction should be a valid value and not 0.
  • Fees should meet the network expected value otherwise the network will refuse the transaction.
  • Amount and fees are represented in satoshis and not bitcoins.

Return

Zero if parameters given passed the conditions explained earlier, but still the network has the higher authority to refuse or accept the transaction, otherwise a value is returned according to an error met with one of the conditions.

States according the address provided:

  • (TRANSACTION_PASSED) If all the conditions were met by the koyn library.
  • (INVALID_AMOUNT) If amount provided is 0.
  • (ADDRESS_NOT_TRACKED) If fromAddress was not tracked.
  • (ADDRESS_NO_FUNDS) If fromAddress's confirmed balance can't cover the amount given.
  • (ADDRESS_INSUFFICIENT_BALANCE) If totalAmount (amount+fees) not covered by fromAddress's confirmed balance.
  • (ADDRESS_NO_PRIVATE_KEY) If fromAddress provided doesn't have the private key.
  • (ADDRESS_INVALID) If any of the addresses (fromAddress, toAddress, changeAddress) are invalid.

Parameters

  • Spending address (fromAddress).
  • Receiving address (toAddress).
  • Amount to be spent in satoshis (amount).
  • Fees of transaction (fees).

 

BitcoinAddress:

BitcoinAddress(const char * key, uint8_t key_type);

Constructor to create an address given a (encoded/Wif/private/compressed pubic/uncompressed public) key and the key_type.

Keys types:

  • ADDRESS_ENCODED
  • KEY_WIF
  • KEY_PRIVATE
  • KEY_COMPRESSED_PUBLIC
  • KEY_PUBLIC

Return

Void.

Parameters

  • A const char key string to create your address (key).
  • The key type defined above according to the provided key (key_type).

Usage

BitcoinAddress myAddress("mqBPVCaTaJdDVGruNzkTD3CKTVqYqamVow6R",ADDRESS_ENCODED);
BitcoinAddress myAddress("cTSpGS6pTZBZ9yFDS4tmuJDM1oCziFHP9p26AnQidhccYqPJHf9T",KEY_WIF);
BitcoinAddress myAddress("f5fdccaf76152ddfaa27f1a61cb3aadd45e41aad8aaa35f7b577fc3ea3c66cd3",KEY_PRIVATE);
BitcoinAddress myAddress("0230e93d3ac36aaab880bc3209e20328d724f12645218dab523a016cf7a87c9738",KEY_COMPRESSED_PUBLIC);
BitcoinAddress myAddress("0430e93d3ac36aaab880bc3209e20328d724f12645218dab523a016cf7a87c973830e93d3ac36aaab880bc3209e20328d724f12645218dab523a016cf7a87c9738",KEY_PUBLIC);

 

BitcoinAddress(uint8_t * key, uint8_t key_type);

Constructor to create an address given a (private/compressed pubic/uncompressed public) key and the key_type.

Keys types:

  • KEY_PRIVATE
  • KEY_COMPRESSED_PUBLIC
  • KEY_PUBLIC

Return

Void.

Parameters

  • A byte array key to create your address (key).
  • The key type defined above according to the provided key (key_type).

Usage

uint8_t privateKey[]={0xf5,0xfd,0xcc,0xaf,0x76,0x15,0x2d,0xdf,0xaa,0x27,0xf1,0xa6,0x1c,0xb3,0xaa,0xdd,0x45,0xe4,0x1a,0xad,0x8a,0xaa,0x35,0xf7,0xb5,0x77,0xfc,0x3e,0xa3,0xc6,0x6c,0xd3}
BitcoinAddress myAddress(privateKey,KEY_PRIVATE);

 

BitcoinAddress(bool generateKeys);

Constructor to create an empty shell address to be filled by user (if set false), Or generating a brand new address with new private and public keys using the embedded UECC library included in koyn library (if set true).

Return

Void.

Parameters

  • True to create a new address with new private and public keys or false to just create a shell address to be filled by the user when a transaction is returned from the network.

Usage

BitcoinAddress myAddress; /* A shell address */
BitcoinAddress myAddress(true); /* A brand new address to be tracked or spend bitcoins from*/

 

uint8_t getPrivateKey(uint8_t * privateKeyArray);

A getter takes a byte array to be filled with the address's private key.

Note: make sure to reserve the proper byte array size (32 byte for private key) to be filled with the private key.

Return

32 as filled.

Parameters

  • A 32 byte array to be filled with the private key.

Usage

uint8_t privateKey[32];
BitcoinAddress myAddress(true);
myAddress.getPrivateKey(privateKey);

 

uint8_t getPrivateKey(char * privateKeyArray);

A getter takes a char array to be filled with the address's private key.

Note: make sure to reserve the proper char array size + an extra char to be trailed with the null character (65 byte for private key).

Return

64 as filled.

Parameters

  • A 65 char array to be filled with the private key.

Usage

char privateKey[65];
BitcoinAddress myAddress(true);
myAddress.getPrivateKey(privateKey);

 

uint8_t getPublicKey(uint8_t * publicKeyArray);

A getter takes a byte array to be filled with the address's compressed public key.

Note: make sure to reserve the proper byte array size (33 byte for private key) to be filled with the compressed public key.

Return

33 as filled.

Parameters

  • A 33 byte array to be filled with the compressed public key.

Usage

uint8_t publicKey[33];
BitcoinAddress myAddress(true);
myAddress.getPublicKey(publicKey);

 

uint8_t getPublicKey(char * publicKeyArray);

A getter takes a char array to be filled with the address's compressed public key.

Note: make sure to reserve the proper char array size + an extra char to be trailed with the null character (67 byte for private key).

Return

66 as filled.

Parameters

  • A 67 char array to be filled with the compressed public key.

Usage

uint8_t publicKey[67];
BitcoinAddress myAddress(true);
myAddress.getPublicKey(publicKey);

 

uint8_t getWif(char * wifKeyArray);

A getter takes a char array to be filled with the address's WIF type private key.

Note: make sure to reserve the proper char array size + an extra char to be trailed with the null character (53 char for Wif private key).

Return

52 as filled.

Parameters

  • A 53 char array to be filled with the wif private key.

Usage

uint8_t wifPrivateKey[53];
BitcoinAddress myAddress(true);
myAddress.getWif(wifPrivateKey);

 

uint8_t getEncoded(char * encodedArray);

A getter takes a char array to be filled with the encoded address.

Note: make sure to reserve the proper char array size + an extra char to be trailed with the null character (35 char for P2PKH address).

Return

34 as filled.

Parameters

  • A 35 char array to be filled with the encoded address.

Usage

uint8_t encodedAddress[35];
BitcoinAddress myAddress(true);
myAddress.getEncoded(encodedAddress);

 

bool isTracked();

Check if the address is being tracked by the network.

Return

A Yes '1' or No '0'.

Parameters

Void.

 

uint64_t getBalance();

Get the whole balance address holds (confirmed+unconfirmed).

Return

A 64 bit integer holding the whole balance.

Parameters

Void.

 

uint64_t getConfirmedBalance();

Get confirmed balance address holds.

Return

A 64 bit integer holding the confirmed balance.

Parameters

Void.

 

uint64_t getUnconfirmedBalance();

Get unconfirmed balance address holds.

Return

A 64 bit integer holding the unconfirmed balance.

Parameters

Void.

 

BitcoinTransaction:

uint8_t getInput(uint8_t inputIndex,BitcoinAddress * shellAddress);

A getter to retrieve an address from the inputs included in a transaction returned by the callback.

Return

A state declaring the address condition:

  • (ADDRESS_RETRIEVED) If address was copied successfully from the transaction to the declared shell address.
  • (INDEX_ERROR) If the index given exceeds the number of inputs in transaction.
  • (ADDRESS_TYPE_ERROR) If the provided address is not a shell type address and already has an address/private/public keys.

Parameters

  • A byte holding the index of the input (inputIndex).
  • A BitcoinAddress pointer to a shell address (shellAddress).

 

uint8_t getOutput(uint8_t outputIndex,BitcoinAddress * shellAddress);

A getter to retrieve an address from the outputs included in a transaction returned by the callback.

Return

A state declaring the address condition:

  • (ADDRESS_RETRIEVED) If address was copied successfully from the transaction to the declared shell address.
  • (INDEX_ERROR) If the index given exceeds the number of outputs in transaction.
  • (ADDRESS_TYPE_ERROR) If the provided address is not a shell type address and already has an address/private/public keys.

Parameters

  • A byte holding the index of the output (outputIndex).
  • A BitcoinAddress pointer to a shell address (shellAddress).

 

uint64_t getOutputAmount(uint8_t outputIndex);

A getter to retrieve the amount received by the tracked address.

Return

A 64 bit integer holding the amount received.

Parameters

  • A byte holding the index of the output (outputIndex).

 

uint8_t getInputsCount();

A getter to retrieve the number of inputs (addresses) included in transaction.

Return

A 8 bit integer holding the count.

Parameters

Void.

 

uint8_t getOutputsCount();

A getter to retrieve the number of outputs (addresses) included in transaction.

Return

A 8 bit integer holding the count.

Parameters

Void.

 

uint8_t getHash(uint8_t * hashByteArray);

A getter takes a byte array to retrieve the hash of the transaction.

Note: make sure to reserve the proper byte array size (32 byte for transaction hash) to be filled with the hash.

Return

32 as filled.

Parameters

  • A 32 byte array to be filled with the transaction hash.

 

uint8_t getHash(char * hashByteArray);

A getter takes a char array to retrieve the hash of the transaction.

Note: make sure to reserve the proper char array size + an extra char to be trailed with the null character (65 char for transaction hash).

Return

64 as filled.

Parameters

  • A 65 char array to be filled with the transaction hash.

 

uint32_t getBlockNumber();

A getter that returns the block height the transaction was included in.

Return

A 32 bit integer holding the height of block.

Parameters

Void.

 

uint32_t getConfirmations();

A getter that returns the number of block confirmation the transaction went through.

Return

A 32 bit integer holding the number of block confirmations.

Parameters

Void.

 

Clone this wiki locally