3rdstage's Wiki
Tag: Source edit
Tag: Source edit
Line 1,757: Line 1,757:
 
! Category !! Variable/Function !! Description !! Remarks
 
! Category !! Variable/Function !! Description !! Remarks
 
|-
 
|-
| Block/Transaction || <tt>block.coinbase</tt> || current block miner’s address ||
+
| Block/Transaction || <tt>block.coinbase::address payable</tt> || current block miner’s address ||
 
|-
 
|-
| || <tt>block.number</tt> || current block number ||
+
| || <tt>block.number::uint</tt> || current block number ||
 
|-
 
|-
| || <tt>block.timestamp</tt> || current block timestamp as seconds since unix epoch ||
+
| || <tt>block.timestamp::uint</tt> || current block timestamp as seconds since unix epoch ||
 
|-
 
|-
| || <tt>msg.sender</tt> || sender of the message ||
+
| || <tt>msg.sender::address payable</tt> || sender of the message ||
  +
|-
  +
| || <tt>msg.data::bytes</tt> || complete calldata ||
  +
|-
  +
| || <tt>msg.sig::bytes4</tt> || first four bytes of the calldata || function identifier(selector)
  +
|-
  +
| || <tt>msg.value::uint</tt> || number of '''wei''' sent with the message ||
  +
|-
  +
| || <tt>tx.origin::address payable</tt> || sender of the transaction (full call chain) || tx = &sum;call
  +
 
|-
 
|-
 
|-
 
|-

Revision as of 01:53, 25 February 2021

General

Consensus Algorithm

Style Description Remarks
PoW Deters denial of service attacks and other service abuses such as spam on a network by requiring some work from the service requester, usually meaning processing time by a computer.
PoS
DPoS
PoS

PoW

BFT (Byzantine Fault Tolerance)

pBFT

ZKP

misc

  • Paxos : a family of protocols for solving consensus in a network of unreliable processors
Fault Type Cryptography Replica Requirement
Non Byzantine Failures Non Cryptographic 2F + 1
Non-malicious Byzantine Failures Non Cryptographic 2F + 1
Malicious Byzantine Failures Non Cryptographic 3F + 1
Malicious Byzantine Failures Cryptographic 2F + 1

Blockchian Networks

Network Symbol Consensus Style Description Remarks
BitCoin BTC PoW
Ethereum ETH PoW
EOS EOS DPoS

Smart Contract

Key and Wallet

  • Shamir's Secret Sharing
    • a form of secret sharing, where a secret is divided into parts, giving each participant its own unique part.

Financial Business

Concept Description Remark
Leverage any technique involving the use of debt (borrowed funds) rather than fresh equity in the purchase of an asset, with the expectation that the after-tax profit to equity holders from the transaction will exceed the borrowing cost, frequently by several multiples⁠.
Margin collateral that the holder of a financial instrument has to deposit with a counterparty (most often their broker or an exchange) to cover some or all of the credit risk the holder poses for the counterparty.
Fungibility the property of a good or a commodity whose individual units are essentially interchangeable, and each of its parts is indistinguishable from another part. company shares, bonds, precious metals, currencies
Entry Meaning Position Korean
Debit a transfer of value to that account right side 차변
Credit a transfer of value from the account left side 대변
  • What Is Margin Trading? (13.01.2020)
    • This ability to expand trading results makes margin trading especially popular in low-volatility markets, particularly the international Forex market. Still, margin trading is also used in stock, commodity, and cryptocurrency markets.
  • Margin (Jun 25, 2019)

Financial Instrument

  • Financial instrument
    • monetary contracts between parties which can be created, traded, modified and settled.
Instrument Description Remark
Bond an instrument of indebtedness of the bond issuer to the holders. debt security
Loan the lending of money by one or more individuals, organizations, or other entities to other individuals, organizations etc.
Deposit any other type of bank account that allows money to be deposited and withdrawn by the account holder.

Credit Card

Misc

Bitcoin

Concepts

BIP

BIP Title Description Type Status Remarks Related
BIP 32 Hierarchical Deterministic Wallets describes hierarchical deterministic wallets (or "HD Wallets") Informational Final
BIP 39 Mnemonic code for generating deterministic keys describes the implementation of a mnemonic code or mnemonic sentence -- a group of easy to remember words -- for the generation of deterministic wallets. Standards Track Proposed
BIP 43 Purpose Field for Deterministic Wallets introduces a "Purpose Field" for use in deterministic wallets based on algorithm described in BIP-0032 Informational Draft m/purpose'/* BIP 32
BIP 44 Multi-Account Hierarchy for Deterministic Wallets defines a logical hierarchy for deterministic wallets based on an algorithm described in BIP-0032 Standards Track Proposed m/44'/*'/*'/*/* BIP 32, BIP 43

HD Wallet

Format Purpose Description Remarks
m/0'/* Default Account
m/44'/coin_type'/*'/*/* Multi-Account m/44'/0': BTC, m/44'/60': ETH, m/44'/61': ETC

BIP 32

private parent key → private child key : possible
public parent key → public child key : possible
private parent key → public child key : possible
public parent key → private child key : impossible
  • Each leaf node in the tree corresponds to an actual key, while the internal nodes correspond to the collections of keys that descend from them.
  • The chain codes of the leaf nodes are ignored, and only their embedded private or public key is relevant.
  • Knowing an extended private key allows reconstruction of all descendant private keys and public keys.
  • Knowing an extended public keys allows reconstruction of all descendant non-hardened public keys.
256 bit entropy
private key
public key
extended private key
extended public key
private child key derivation(CKD) function
public child key derivation(CKD) function
computes extended public key
private key node m : master extended private key
public key node M : master extended public key
Serialization Format
Position Value Remarks
4 bytes version bytes
  • mainnet/public: 0x0488B21E
  • mainnet/private: 0x0488ADE4
  • testnet/public: 0x043587CF
  • testnet/private: 0x04358394
1 bytes depth
  • master node: 0x00
  • level-1 derived: 0x01
4 bytes the fingerprint of the parent's key master key: 0x00000000
4 bytes child number
32 bytes chain code 256 bit
33 bytes the public key or private key data

Ethereum

Specs

EIP

  • EIPs (Ethereum Improvement Proposals)
    • describe standards for the Ethereum platform, including core protocol specifications, client APIs, and contract standards.
  • EIP List
EIP/ERC Title Description Category Status Remarks Related
EIP 20 Token Standard A standard interface for tokens. ERC Final totalSupply, balanceOf, transfer, transferFrom, approve, ...
EIP 55 Mixed-case checksum address encoding ERC Final
EIP 100 Change difficulty adjustment to target mean block time including uncles the formula to compute the difficulty of a block Core Final
EIP 101 Serenity Currency and Crypto Abstraction Accounts now have only two fields in their RLP encoding: code and storage Core Draft Ethereum 2.0
EIP-155 Simple replay attack protection provide a way to send transactions that work on Ethereum without working on ETC or the Morden testnet. Core Final
EIP 165 Standard Interface Detection Creates a standard method to publish and detect what interfaces a smart contract implements. ERC Final ERC-1820
EIP 721 Non-Fungible Token Standard A standard interface for non-fungible tokens, also known as deeds. ERC Final supportsInterface(bytes4 _if)
EIP 725 Proxy Account A standard interface for a simple proxy account. ERC Draft
EIP 777 Token Standard standard interfaces and behaviors for token contracts. ERC Final operators, send/receive hooks ERC-1820
EIP 1066 Status Codes Broadly applicable status codes for smart contracts. ERC Draft
EIP 1102 Opt-in account exposure describes a communication protocol between dapps and Ethereum-enabled DOM environments that allows the Ethereum-enabled DOM environment to choose what information to supply the dapp with and when. Interface Draft eth_requestAccounts
EIP 1155 Multi Token Standard A standard interface for contracts that manage multiple token types. ERC Final
EIP 1193 Ethereum Provider JavaScript API A JavaScript Ethereum Provider API for consistency across clients and applications. Interface Last Call Provider.request()
EIP 1474 Remote procedure call specification defines a standard set of remote procedure call methods that an Ethereum node should implement. Interface Draft JSON-RPC, Error Codes, Methods
EIP 1820 Pseudo-introspection Registry Contract defines a universal registry smart contract where any address (contract or regular account) can register which interface it supports and which smart contract is responsible for its implementation. ERC Final ERC-820, ERC-165

ERC

  • ERC : Application-level standards and conventions
ERC Title Description Remarks
ERC 734 Key Manager A contract for key management of a blockchain proxy account. ERC 725
ERC 735 Claim Holder Describes standard functions for adding, removing and holding of claims. ERC 725, ERC 734
ERC 780 Ethereum Claims Registry Describes a proposal for an Ethereum Claims Registry (ECR) which allows persons, smart contracts, and machines to issue claims about each other, as well as self issued claims. ERC 735
ERC 1155 Multi Token Standard A standard interface for contracts that manage multiple token types.
ERC 1238 Non-transferrable tokens (badges) Defines a set of standard APIs allowing the identification of statements (called badges) attributed to a public key, such that different dapps and smart contract can use to filter users or to provide user with different badges different experiences.
ERC 1400 Security Token Standard Represents a library of standards for security tokens on Ethereum. EIPs/issues/1411
ERC 1404 Simple Restricted Token Standard An open source standard for security tokens
                               
                            +--- Transferrable ---------- EIP 20
                            |
       +--- Fungible -------+
       |                    |
       |                    +--- Non Transferrable ----- 
       |
   +---+
       |
       |                    +--- Transferable ---------- EIP 721
       |                    |
       +--- Non Fungible ---+
                            |
                            +--- Non Transferrable ----- ERC 1238, ERC 735
  • ERC-725 Alliance
    • The home of ERC 725, a proposed standard for blockchain-based identity authored by Fabian Vogelsteller, creator of the ERC 20 standard and Web3.js.

Concepts

  • Ether
    • 1 wei = 10-18 ether
    • 1 Gwei (shannon) = 109 wei = 10-9 ether
  • Account Types, Gas, and Transactions
    • Externally Owned Account, Contract Account, Transaction, Message, Gas
  • What is Gas?
  • Gas and Gas Price
    • transaction gas limit : max amount of gas your willing to use for your transaction, set by you
    • block gas limit : max amount of gas allowed in a block, set by the network
  • What is coinbase? (Apr 16 '16)
  • The address of that contract is not the zero address but an address derived from the sender and its number of transactions sent (the “nonce”).
  • The gas price is a value set by the creator of the transaction, who has to pay gas_price * gas up front from the sending account. If some gas is left after the execution, it is refunded to the creator in the same way.
  • The Ethereum Virtual Machine has three areas where it can store data- storage, memory and the stack
  • Mining
  • How to Mine Ethereum.
    • Once you’ve successfully mined a block, you are entitled to receive a three ETH reward. Along with the reward, miners receive fees associated with the transaction.

Keys and Address

Element Size Remarks
Bits Bytes Hex Characters
Private Key 256 32 64
Public Key 512 64 128
Address 160 20 40 the right most 160-bits of the Keccak hash of the corresponding ECDSA public key.

A(pr)=B96...256(KEC(ECDSAPUBKEY(pr)))

A : address
pr : private key
KEC : Keccak-256 hash function

Signing
Account State
Field Symbol Description Remarks
nonce σ[a]n A scalar value equal to the number of transactions sent from this address or, in the case of accounts with associated code, the number of contract-creations made by this account.
balance σ[a]b A scalar value equal to the number of Wei owned by this address.
storageRoot σ[a]s A 256-bit hash of the root node of a Merkle Patricia tree that encodes the storage contents of the account.
codeHash σ[a]c The hash of the EVM code of this account—this is the code that gets executed should this address receive a message call. immutable

Transaction

A transaction (formally, T) is a single cryptographically-signed instruction constructed by an actor externally to the scope of Ethereum.

Field Symbol Description Remarks
nonce Tn A scalar value equal to the number of transactions sent by the sender
gasPrice Tp A scalar value equal to the number of Wei to be paid per unit of gas for all computation costs incurred as a result of the execution of this transaction
gasLimit Tg A scalar value equal to the maximum amount of gas that should be used in executing this transaction. This is paid up-front, before any computation is done and may not be increased
to Tt The 160-bit address of the message call’s recipient or, for a contract creation transaction, ∅
value Tv A scalar value equal to the number of Wei to be transferred to the message call’s recipient or, in the case of contract creation, as an endowment to the newly created account.
v, r, s Tw, Tr, Ts Values corresponding to the signature of the transaction and used to determine the sender of the transaction.
init Ti An unlimited size byte array specifying the EVM-code for the account initialisation procedure. a contract creation transaction only
data Td An unlimited size byte array specifying the input data of the message call. a message call transaction only
  • Transaction signature

Signature = Fsig(Fkeccak256(m), k) = (r, s)

m : encoded transaction
k : signer's private key
Fkeccak256 : Keccak-256 hash function
Fsig : Signing algorithm

Transaction Receipt

Field Type Size Description Remarks
blockHash String 32 Bytes hash of the block where this transaction was in.
blockNumber Number block number where this transaction was in.
transactionHash String 32 Bytes hash of the transaction.
transactionIndex Number integer of the transactions index position in the block.
from String 20 Bytes address of the sender.
to String 20 Bytes address of the receiver. null : a contract creation transaction.
cumulativeGasUsed Number total amount of gas used when this transaction was executed in the block.
gasUsed Number the amount of gas used by this specific transaction alone.
contractAddress String the contract address created, if the transaction was a contract creation, otherwise null.
logs Array Array of log objects, which this transaction generated.
status String '0x0' indicates transaction failure , '0x1' indicates transaction succeeded.
Component Description Remark
address the address of the contract (intrinsically provided by Ethereum)
topics[0] keccak(event-signature) not generated for anonymous event
topics[n] abi_encode(event-args[indexed][n - 1]) indexed arguments
data abi_encode(join(event-args[non-indexed])) non-indexed arguments

Block

Ethereum Block Structure
Block Header
Field Symbol Description Remarks
parentHash Hp The Keccak 256-bit hash of the parent block’s header, in its entirety.
ommersHash Ho The Keccak 256-bit hash of the ommers list portion of this block.
beneficiary Hc The 160-bit address to which all fees collected from the successful mining of this block be transferred.
stateRoot Hr The Keccak 256-bit hash of the root node of the state trie, after all transactions are executed and finalisations applied;
transactionsRoot Ht The Keccak 256-bit hash of the root node of the trie structure populated with each transaction in the transactions list portion of the block.
receiptsRoot He The Keccak 256-bit hash of the root node of the trie structure populated with the receipts of each transaction in the transactions list portion of the block.
logsBloom Hb The Bloom filter composed from indexable information (logger address and log topics) contained in each log entry from the receipt of each transaction in the transactions list.
difficulty Hd A scalar value corresponding to the difficulty level of this block. This can be calculated from the previous block’s difficulty level and the timestamp.
number Hi A scalar value equal to the number of ancestor blocks. 0 for genesis block
gasLimit Hl A scalar value equal to the current limit of gas expenditure per block
gasUsed Hg A scalar value equal to the total gas used in transactions in this block.
timestamp Hs A scalar value equal to the reasonable output of Unix’s time() at this block’s inception.
extraData Hx An arbitrary byte array containing data relevant to this block. This must be 32 bytes or fewer.
mixHash Hm A 256-bit hash which, combined with the nonce, proves that a sufficient amount of computation has been carried out on this block.
nonce Hn A 64-bit value which, combined with the mixhash, proves that a sufficient amount of computation has been carried out on this block.

World State

  • Diving into Ethereum’s world state (Feb 11, 2018)
    • There is one, and one only, global state trie in Ethereum.
    • A storage trie is where all of the contract data lives.
    • Each Ethereum account has its own storage trie.
    • Transaction trie — one per block
    • Ethereum’s Rust client Parity uses rocksdb. Whereas Ethereum’s Go, C++ and Python clients all use leveldb.

Merkle Patricia Tree

  • Trie
    • an ordered tree data structure used to store a dynamic set or associative array where the keys are usually strings.
    • Unlike a binary search tree, no node in the tree stores the key associated with that node; instead, its position in the tree defines the key with which it is associated.
  • Radix Tree
    • a data structure that represents a space-optimized trie (prefix tree) in which each node that is the only child is merged with its parent.

Consensus

  • JavaScript code snippet to calculate target in hexa with given difficulty
    • > (2n**256n / 24091770185844n).toString(16).padStart(64, '0') // difficulty: 24091770185844

Misc

Call vs Send
Library API Description Remarks
JSON-RPC eth_call Executes a new message call immediately without creating a transaction on the block chain. No signing, 0 gas
eth_sendTransaction Creates new message call transaction or a contract creation, if the data field contains code.
eth_sendRawTransaction Creates new message call transaction or a contract creation for signed transactions. single parameter for the signed transaction data.
web3js 1.2 methods.myMethod.call Will call a “constant” method and execute its smart contract method in the EVM without sending any transaction. Note calling can not alter the smart contract state. constant function -> view function in Solidity 0.5
methods.myMethod.send Will send a transaction to the smart contract and execute its method. Note this can alter the smart contract state.

Hard Forks

Fork Date Block # Description Remarks
Olympic 2015-05-09 N/A The final PoC testnet
Frontier 2015-06-30 0 The 1st official public mainnet Block Reward, Gas
Homestead 2016-03-14 1,150,000 The 1st planned hard fork Solidity, Mist wallet
DAO Fork 2016-06-20 1,192,000 To restore $50M stolen in DAO hack Ethereum Classic
Spurious Dragon 2016-11-22 2,675,000 EIP 155, EIP 160, EIP 161, EIP 170
Metropolis: Byzantium 2017-10-16 4,370,000 Add REVERT and STATICCALL opcode
Metropolis: Constantinople 2019-02-28 7,280,000 Smart Contract Verification
State Channel
Block Reward Reduction(3ETH -> 2ETH)
Istanbul 2019-12-07 9,069,000 Zcash interoperability enhancement
SNARK and STARK performance enhancement
EIP 1344, EIP 152, EIP 1108, EIP 2028, EIP 2200
Muir Glacier 2020-01-02 9,200,000 Delays the “difficulty bomb” by 4M blocks.

EVM

Ethereum 2.0

Casper

Misc

JSON RPC APIs

Object Description Properties Remarks
transaction from, to, gas, gasPrice, value, data, nonce
transaction receipt
JSON-RPC Method Description JavaScript API Python API
web3_clientVersion the current client version web3.eth.getNodeInfo() web3.clientVersion
web3_sha3 Keccak-256 (not the standardized SHA3-256) of the given data. web3.utils.sha3() Web3.keccak()
eth_protocolVersion the current ethereum protocol version web3.eth.getProtocolVersion() web3.eth.protocolVersion
eth_chainId a single string result for an integer value in hexadecimal format, describing the currently configured CHAIN_ID value used for signing replay-protected transactions web3.eth.getChainId() web3.eth.chain_id
eth_syncing an object with data about the sync status or false web3.eth.isSyncing() web3.eth.syncing
eth_coinbase the coinbase address to which mining rewards will go web3.eth.getCoinbase() web3.eth.coinbase
eth_mining whether the node is mining or not web3.eth.isMining() web3.eth.mining
eth_hashrate the number of hashes per second that the node is mining with web3.eth.getHashrate() web3.eth.hashrate
eth_gasPrice the current price per gas in wei web3.eth.getGasPrice() web3.eth.gasPrice
eth_accounts a list of addresses owned by client web3.eth.getAccounts() web3.eth.accounts
eth_blockNumber the number of most recent block web3.eth.getBlockNumber() web3.eth.blockNumber
eth_getBalance the balance of the account of given address web3.eth.getBalance() web3.eth.get_balance()
eth_getTransactionCount the number of transactions sent from an address. (nonce) web3.eth.getTransactionCount() web3.eth.getTransactionCount()
eth_getStorageAt the value from a storage position at a given address. web3.eth.getStorageAt() web3.eth.get_storage_at()
eth_getCode code at a given address web3.eth.getCode() web3.eth.getCode()
eth_getBlockTransactionCountByNumber the number of transactions in a block matching the given block number. web3.eth.getBlockTransactionCount() web3.eth.get_block_transaction_count()
eth_sign calculates an Ethereum specific signature web3.eth.sign() web3.eth.sign()
eth_signTransaction signs a transaction that can be submitted to the network at a later time. web3.eth.signTransaction() web3.eth.signTransaction()
eth_sendTransaction creates new message call transaction or a contract creation web3.eth.sendTransaction() web3.eth.sendTransaction()
eth_sendRawTransaction creates new message call transaction or a contract creation for signed transactions. web3.eth.sendSignedTransaction() web3.eth.sendRawTransaction()
eth_call executes a new message call immediately without creating a transaction on the block chain. web3.eth.call() we3.eth.call()
eth_getBlockByNumber information about a block by block number. web3.eth.getBlock() web3.eth.get_block()
eth_getTransactionByBlockNumberAndIndex information about a transaction by block number and transaction index position. web3.eth.getTransactionByBlock()
net_version the current network id web3.eth.net.getId() web3.net.version
net_peerCount number of peers currently connected to the client. web3.eth.net.getPeerCount() web3.net.peer_count
net_listening whether or not client is actively listening for network connections. web3.eth.net.isListening() web3.net.listening
  • Looking around the local client using JSON RPC API
$ # Get the client coinbase address. (https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_coinbase)
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_coinbase","params":[],"id":11}' http://127.0.0.1:8545

$ # Get the client version. (https://github.com/ethereum/wiki/wiki/JSON-RPC#web3_clientversion)
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"web3_clientVersion","params":[],"id":21}' http://127.0.0.1:8545

$ # Get the Ethereum protocol version. (https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_protocolversion)
$ # For more on Ethereum protocol version, refer https://github.com/ethereum/devp2p/blob/master/caps/eth.md
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_protocolVersion","params":[],"id":31}' http://127.0.0.1:8545

$ # Get the number of peers currently connected to the client. (https://github.com/ethereum/wiki/wiki/JSON-RPC#net_peercount)
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"net_peerCount","params":[],"id":41}' http://127.0.0.1:8545

$ # Check whether the client is mining or not. (https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_mining)
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_mining","params":[],"id":51}' http://127.0.0.1:8545

$ # Get a list of addresses owned by client (https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_accounts)
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_accounts","params":[],"id":61}' http://127.0.0.1:8545

$ # Get the network ID. (https://github.com/ethereum/wiki/wiki/JSON-RPC#net_version)
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"net_version","params":[],"id":71}' http://127.0.0.1:8545

$ # Get the current price per gas in wei. (https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_gasprice)
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_gasPrice","params":[],"id":81}' http://127.0.0.1:8545

$ # Get the number of most recent block. (https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_blocknumber)
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":91}' http://127.0.0.1:8545

$ # Get the gas limit of the most recent block
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["latest", false],"id":92}' http://127.0.0.1:8545 | jq .result.gasLimit

$ # Get information about a block by block number. (https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getblockbynumber)
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":[0, false],"id":101}' http://127.0.0.1:8545 | jq .  # block 0
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["0x1", false],"id":102}' http://127.0.0.1:8545 | jq .  # block 1
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":[2, false],"id":103}' http://127.0.0.1:8545 | jq .  # block 1


#! /bin/bash

function print_help {
  echo "Executes some basic Ethereum JSON RPC method to check the specified Ethereum client."
  echo ""
  echo "Usage:"
  echo "  $ ${0##*/}  [-h | --help | rpc_addr]"
  echo ""
  echo "If '-h' or '--help' is given, only display this help and quit."
  echo "If rpc_addr is given, execute some basic Ethereum JSON RPC "
  echo "methods to the specified address."
  echo "If no argument is given, excute the same method to local RPC"
  echo "address of 'http://127.0.0.1:8545'."
}

if [ $# -gt 1 ]; then
  echo "Too many parameters. At the most, one parameter is possible"
  echo ""
  print_help
  exit 100
fi

declare rpc_addr='http://127.0.0.1:8545'

if [ $# -eq 1 ]; then
  if [ "$1" == "-h" -o "$1" == "--help" ]; then
    print_help
    exit 0
  fi
  rpc_addr=$1
fi

# check the specified RPC address
curl -sS $rpc_addr
if [ $? -ne 0 ]; then
  echo "Fail to connect to the specified RPC adderss '$rpc_addr'"
  exit 200
fi

echo "Executing some basic JSON RPC methods to '$rpc_addr'"
echo ""

declare -ar titles=(
'the client coinbase address'
'current client version'
'the current ethereum protocol version'
'number of peers currently connected to the client'
'whether or not client is actively mining new blocks'
'a list of addresses owned by client'
'current network ID'
'the current price per gas in wei'
'the number of most recent block'
'about the genesis block'
)

declare -ar data=(
'{"jsonrpc":"2.0","method":"eth_coinbase","params":[],"id":11}'
'{"jsonrpc":"2.0","method":"web3_clientVersion","params":[],"id":21}'
'{"jsonrpc":"2.0","method":"eth_protocolVersion","params":[],"id":31}'
'{"jsonrpc":"2.0","method":"net_peerCount","params":[],"id":41}'
'{"jsonrpc":"2.0","method":"eth_mining","params":[],"id":51}'
'{"jsonrpc":"2.0","method":"eth_accounts","params":[],"id":61}'
'{"jsonrpc":"2.0","method":"net_version","params":[],"id":71}'
'{"jsonrpc":"2.0","method":"eth_gasPrice","params":[],"id":81}'
'{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":91}'
'{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["0x0", false],"id":101}'
)

for (( i = 0; i < ${#titles[@]}; i++ )); do

  cmd="curl -sSX POST --data '${data[$i]}' $rpc_addr"

  echo "// ${titles[$i]}"
  echo $cmd
  eval $cmd
  echo -e "\n"
done
  • Verifying a confusing result or situation at the most fundamental level using eth_getTransactionByHash and eth_getTransactionReceipt APIs for each transaction concenred
$ # Get information for the specified transaction (result is not included) (https://eth.wiki/json-rpc/API#eth_gettransactionbyhash)
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_getTransactionReceipt","params":["0x10f612a42b04ace427b0057caf76d7c7446840f419d4b424f117ecb1bd2cb0e8"],"id":201}' http://127.0.0.1:8545

$ # Get the receipt for the specified transaction, which include the result status and logs (https://eth.wiki/json-rpc/API#eth_gettransactionreceipt)
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_getTransactionByHash","params":["0x10f612a42b04ace427b0057caf76d7c7446840f419d4b424f117ecb1bd2cb0e8"],"id":211}' http://127.0.0.1:8545

Smart Contract

ERC Reference Description Remarks
ERC-725 ERC 725 Alliance Reference Implementation
uPort Identity Contracts

Oracle

Programming

Clients

Test Network, Private Network

Network ID Consensus Avg. Block Time Faucet Explorer GitHub Remark
Ropsten 3 PoW 30 sec. https://faucet.ropsten.be/ https://ropsten.etherscan.io/ https://github.com/ethereum/ropsten
Rinkeby 4 PoA 15 sec. https://faucet.rinkeby.io/ https://www.rinkeby.io/#explorer
Kovan 42 PoA 4 sec. https://faucet.kovan.network/ https://kovan.etherscan.io/ https://github.com/kovan-testnet
Görli 5 PoA 15 sec. https://goerli.etherscan.io/ https://github.com/goerli/testnet

Services

Recommendations

Hackings

misc

Ethereum Network Statistics

Topic Charts and Tables Remarks
Time Average Block Time Chart
Mining Difficulty Etherscan / Ethereum Network Difficulty Chart
Ethereum Difficulty Chart
Data Size Full Node Data Size Chart
Archive Node Data Size Chart

Ethereum Blocks

Block # Hash Date Difficulty Block Reward Fee Reward Transactions
10,000,000 0xaa20f7bde5be60603f11a45fc4923aab7552be775403fc00c2e6b805e6297dbe 2020-05-04 2 0.07667 103
9,500,000 0xfd233684d9cbabc563ccc5c3b316ab1f3a22c46cb1495777264f191f5fb96115 2020-02-17 2,230,523,668,588,724 2 0.04033 33
9,000,000 0x388f34dd94b899f65bbd23006ee93d61434a2f2a57053c9870466d8e142960e3 2019-11-26 2,573,664,196,528,490 2 0.14161 95
8,000,000 0x4e454b49dc8a2e2a229e0ce911e9fd4d2aa647de4cf6e0df40cf71bff7283330 2019-06-21 2,037,888,242,889,388 2 0.09102 168
7,000,000 0x17aa411843cb100e57126e911f51f295f5ddb7e9a3bd25e708990534a828c4b7 2019-01-03 2,553,711,764,445,236 3 0.01631 38
6,000,000 0xbe847be2bceb74e660daf96b3f0669d58f59dc9101715689a00ef864a5408f43 2018-07-21 3,483,739,548,912,554 3 0.17281 101
3,000,000 0xee396a86beaade9d6057b72a92b7bf5b40be4997745b437857469557b562a7c3 2017-01-16 103,975,266,902,792 5 0.00851 6
2,000,000 0xc0f4906fea23cf6f3cce98cb44e8e1449e455b28d684dfa9ff65426495584de6 2016-08-03 49,824,742,724,615 5 0.00063 1
1 0x88e96d4537bea4d9c05d12549907b32561d3bf31f45aae734cdc119f13406cb6 2015-07-31 17,171,480,576 5 0 0

Tokens

Solidity

References

  • Solidity (on Wikipedia)
    • an object-oriented programming language for writing smart contracts.
Data types Address Array
Contracts Functions Structs
Inheritance Interfaces Libraries
Units / Global Variables Block / Transaction Time Units
Pragmas Cheatsheet
  • Solidity v0.6.0 Breaking Changes
    • Function overriding should be explicit. - virtual, override keywords
    • Array's length property become immutable.
    • Abstract contract should be explicit. - abstract keyword
    • State variable shadowing become disallowed.
Data types Address Array
Contracts Functions Structs
Inheritance Interfaces Libraries
Units / Global Variables Block / Transaction Time Units
Pragmas Cheatsheet
  • Solidity v0.5.0 Breaking Changes
    • Function visibility (external, public, internal, private) should be explicit.
    • Data location for reference types (struct, array, mapping) should be explicit.
    • Conversion from contract type to address should be explicit. - address(contract).balance
    • Explicit conversion between unrelated contract types are disallowed.
    • Split address type into address type and address payable type.
    • For a contract c, address(c) is address payable iff c has payable fallback function.

Breaking Changes

Version Category Change Remark
0.8 Arithmetic Operation Arithmetic operations revert on underflow and overflow.
ABI Coder v2 ABI coder v2 is activated by default. pragma abicoder
Opcode Failing assertions and other internal checks like division by zero or arithmetic overflow do not use the invalid opcode but instead the revert opcode.
Data-type The type byte has been removed. bytes1
Data-type Address literals have the type address instead of address payable. payable()
Function Function call options can only be given once.
Global Function The global functions log0, log1, log2, log3 and log4 have been removed. inline assembly
Global Variable The global variables tx.origin and msg.sender have the type address instead of address payable. payable(tx.origin), payable(msg.sender)
Type Conversion Explicit conversion into address type always returns a non-payable address type.
0.7 Function Ether and gas is now specified using a new syntax: x.f{gas: 10000, value: 2 ether}(arg1, arg2).
Global Variable The global variable now is deprecated. block.timestamp
Data-type String literals now can only contain printable ASCII characters and this also includes a variety of escape sequences, such as hexadecimal (\xff) and unicode escapes (\u20ac).
Data-type Unicode string literals are supported now. unicode"Hello 😃"
State Mutability The state mutability of functions can now be restricted during inheritance.
Mapping If a struct or array contains a mapping, it can only be used in storage.
Mapping Assignments to structs or arrays in storage does not work if they contain mappings.
Constructor Visibility (public / external) is not needed for constructors anymore. abstract contract
Function Disallow virtual for library functions since libraries cannot be inherited from.
Inheritance using A for B is NOT inherited.
Shift Operation Shifts by signed types are disallowed.
Variable The keyword var cannot be used anymore. (compile-time) parser error

Grammar

Contract = State Variable*, Function*, Function Modifier*, Event*, Struct Type*, Enum Type*

function (<parameter types>) {internal|external} [pure|view|payable] [returns (<return types>)]
  • Reference Types
    • Every reference type, i.e. arrays and structs, has an additional annotation, the “data location”, about where it is stored.
    • All complex types must now give an explicit data location.
  • Functions
    • Functions may also return an arbitrary number of values as output.
    • Data location must be memory for return parameter in function
  • Constructors
    • Before the constructor code is executed, state variables are initialised to their specified value if you initialise them inline, or zero if you do not.
    • After the constructor has run, the final code of the contract is deployed to the blockchain.
    • The constructors of all the base contracts will be called following the linearization rules explained below.
  • Contracts
    • State variables are accessed via their name and not via e.g. `this.owner`. Functions can be accessed directly or through `this.f`, but the latter provides an external view to the function. Especially in the constructor, you should not access functions externally, because the function does not exist yet.
  • Mappings can only have a data location of storage and thus are allowed for state variables, as storage reference types in functions, or as parameters for library functions. They cannot be used as parameters or return parameters of contract functions that are publicly visible.

Visibility

Visibility Description Remarks
external Part of the contract interface, which means they can be called from other contracts and via transactions but cannot be called internally f() does not work, but this.f() works
public Part of the contract interface and can be either called internally or via messages.
internal Can only be accessed internally (i.e. from within the current contract or contracts deriving from it)
private Only visible for the contract they are defined in and not in derived contracts.

Mutability

Mutability Description Remarks
pure Promise not to read from or modify the state.
view Promise not to modify the state.
nonpayable Does not accept Ether
payable Accepts Ether

Types

Category Types Remarks
Value Type Booleans, Integers, Fixed Point Number, Address, Fixed-size Byte Array, Enum
Reference Type Arrays, Structs, Mappings
Value Types
Type Description Remarks
int8, int16, int24, ... , int248, int256 signed integer in 8 ~ 256 bits 8 bits step
uint8, uint16, uint24, ... , uint248, uint256 unsigned integer in 8 ~ 256 bits 8 bits step
int alias for int256 2256 ~ 1077
uint alias for uint256 2256 ~ 1077
address Holds a 20 byte value (size of an Ethereum address)
address payable Same as address, but with the additional members transfer and send
byte1
byte32
enum
Literals
bool b1 = true;   // boolean literal 'true'
bool b2 = false;   // boolean literal 'false'

uint[] arr1 = [uint(1), 2, 3];   // array literal using square bracket
Address Type
Member Description Remarks
balance
transfer(uint256 amount)
send(uint256 amount) returns (bool)
call(bytes memory) returns (bool, bytes memory) issue low-level CALL with the given payload, returns success condition and return data, forwards all available gas, adjustable
delegatecall(bytes memory) returns (bool, bytes memory) issue low-level DELEGATECALL with the given payload, returns success condition and return data, forwards all available gas, adjustable.
staticcall(bytes memory) returns (bool, bytes memory) issue low-level STATICCALL with the given payload, returns success condition and return data, forwards all available gas, adjustable.
Reference Types
Type Description Remarks
Arrays
bytes
string
Struct
Mappings
Array Type
Category Variable/Function Type Description Remarks
Array length ...
push() not for string
pop() not for string
  • bytes
    • similar to but cheaper than bytes[]
    • packed tightly in calldata and memory.
    • should be used for arbitrary-length raw byte data
  • string
    • equal to bytes
    • not allow length or index access
    • should be used for for arbitrary-length UTF-8 data
    • no built-in manipulation function
    • comparing two strings  : keccak256(abi.encodePacked(s1)) == keccak256(abi.encodePacked(s2))
    • concatenating two strings : abi.encodePacked(s1, s2)
Mapping Types

You can think of mappings as hash tables, which are virtually initialised such that every possible key exists and is mapped to a value whose byte-representation is all zeros, a type’s default value.

... mappings do not have a length or a concept of a key or value being set, and therefore cannot be erased without extra information regarding the assigned keys.

Data Location

Data Location Features Lifetime
storage
memory non-persistent function call
calldata non-modifiable, non-persistent
  • Currently, reference types comprise structs, arrays and mappings.
  • All reference types(array, struct, mapping) must give an explicit data location when used in function parameter, local variable.
  • Data location for reference type state variable is always storage implicitly.
  • Data location for reference type local variable should be 'storage' or 'memory'.
  • Data location for reference type return parameter should be 'memory'.
  • Data location for reference type external function parameter should be 'calldata'.
  • If you can, try to use calldata as data location because it will avoid copies and also makes sure that the data cannot be modified. Arrays and structs with calldata data location can also be returned from functions, but it is not possible to allocate such types.
Case Data Location Remarks
state variable always storage implicitly
local variable storage or memory
external function parameter calldata
return parameter memory
  • Data location and assignment
Assignment Semantics Remarks
Assignments between storage and memory always create an independent copy
Assignments from memory to memory only create references
Assignments from storage to a local storage variable only assign a reference
Assignments to state variables always copy
Assignments to members of local variables of storage struct type always copy
  • Ethereum Solidity: Memory vs Storage & When to Use Them (Mar 18, 2018)
    • storage cannot be newly created in a function. Any storage referenced variable in a function always refers a piece of data pre-allocated on the contract storage (state variable). Any mutation persists after function call.
    • memory can only be newly created in a function. It can either be newly instantiated complex types like array/struct (e.g. via new int[...]) or copied from a storage referenced variable.
    • As references are passed internally through function parameters, remember they default to memory and if the variable was on storage it would create a copy and any modification would not persist.
Usage storage memory calldata Preferred Remarks
State variables O X X forced to storage
Parameters of external functions X X O forced to calldata
Parameters and returns of functions O O O memory
Local variables O O O

Literal

Type Literal Remarks
address 0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF Hexadecimal literals that are between 39 and 41 digits long

Default Values (Zero Values)

Type Default Value Remarks
bool false
uint, int 0
address address(0)
enum the first element of the enum
fixed sized array zero-valued array an array of the fixed size where all elements are set to initial values
dynamic sized array empty array []
string empty string ""
mapping empty mapping
struct empty struct a struct value where all members are set to initial values

Special Variables and Functions

Category Variable/Function Description Remarks
Block/Transaction block.coinbase::address payable current block miner’s address
block.number::uint current block number
block.timestamp::uint current block timestamp as seconds since unix epoch
msg.sender::address payable sender of the message
msg.data::bytes complete calldata
msg.sig::bytes4 first four bytes of the calldata function identifier(selector)
msg.value::uint number of wei sent with the message
tx.origin::address payable sender of the transaction (full call chain) tx = ∑call
Error Handling assert(bool condition) causes an invalid opcode and thus state change reversion if the condition is not met - to be used for internal errors.
require(bool condition) reverts if the condition is not met - to be used for errors in inputs or external components.
Contract this the current contract address(this)

Contract

  • A constructor is optional. Only one constructor is allowed.
  • If there is no constructor, the contract will assume the default constructor, which is equivalent to constructor() public {}.
  • Before the constructor code is executed, state variables are initialised to their specified value if you initialise them inline, or zero if you do not.
  • The deployment of the code costs additional gas linear to the length of the code.
  • Constructor functions can be either public or internal.
  • A constructor set as internal causes the contract to be marked as abstract.
  • If the base constructors have arguments, derived contracts need to specify all of them.
  • If a derived contract does not specify the arguments to all of its base contracts’ constructors, it will be abstract.
  • Contracts may be marked as abstract even though all functions are implemented.
  • Abstract contracts can not be instantiated directly.
  • Abstract contracts cannot override an implemented virtual function with an unimplemented one.
  • We perform an explicit type conversion from `address` to `TokenCreator` and assume that the type of the calling contract is `TokenCreator`, there is no real way to verify that. This does not create a new contract.
    • TokenCreator creator;
    • creator = TokenCreator(msg.sender);
  • Explicit conversions to and from address are allowed for integers, integer literals, bytes20 and contract types with the following caveat: The result of a conversion of the form address(x) has the type address payable, if x is of integer or fixed bytes type, a literal or a contract with a receive or payable fallback function. If x is a contract without a receive or payable fallback function, then address(x) will be of type address.
  • Functions with the private visibility cannot be virtual.

Library

If library functions are called, their code is executed in the context of the calling contract,... ...

As a library is an isolated piece of source code, it can only access state variables of the calling contract if they are explicitly supplied... ...

Furthermore, internal functions of libraries are visible in all contracts, just as if the library were a base contract.

Error Handling

Built-in Description Remarks
assert(bool) causes an invalid opcode and thus state change reversion if the condition is not met - to be used for internal errors. imply bug, revert operation(0xfd)
require(bool) reverts if the condition is not met - to be used for errors in inputs or return values from calls to external contracts. invalid operation (0xfe)
  • Solidity performs a revert operation (instruction 0xfd) for a require-style exception and executes an invalid operation (instruction 0xfe) to throw an assert-style exception. In both cases, this causes the EVM to revert all changes made to the state.
  • assert-style exceptions consume all gas available to the call, while require-style exceptions do not consume any gas starting from the Metropolis release.

Events

  • The Log and its event data is not accessible from within contracts (not even from the contract that created them)

Readings

Data-type

String
Structs

Contract

Call

Ether Transfer

Debugging

Security

Guidelines

Tools

Libraries

Patterns

Collections

  • awesome-solidity : A curated list of awesome Solidity resources, libraries, tools and more

misc

Best Practices

Category Title Description Remarks
ERC-1400 Security Token Standard Contracts
ERC-1400 ConsenSys Codefi Universal Token a hybrid token standard precisely designed for the use case of tokenized financial assets
DeFi MakerDao Multi Collateral Dai Contracts
Wallet Authereum Contracts
Oracle Chainlink's Solidity Contracts

Libraries

Fixidity

Ethereum Clients

Go Ethereum

References

Readings


Ethereumj


Parity Ethereum

Readings


Pantheon

Readings


Hyperledger Besu

Readings


Quorum

References

Readings


Ethereum Libraries and Tools

  • Wallets
Wallet Description Type Remarks
MetaMask A crypto wallet & gateway to blockchain apps Web, Mobile
WalletConnect an open protocol for connecting desktop Dapps to mobile Wallets using end-to-end encryption by scanning a QR code.
Fortmatic allows you to easily integrate your app with the Ethereum blockchain

solc-js


web3.js

Package Description Remarks
web3.eth Allows you to interact with an Ethereum blockchain and Ethereum smart contracts.
web3.eth.accounts Contains functions to generate Ethereum accounts and sign transactions and data.
web3.eth.Contract The object makes it easy to interact with smart contracts on the ethereum blockchain.
web3.utils Provides utility functions for Ethereum dapps and other web3.js packages.
web3.eth.abi Let you de- and encode parameters to ABI (Application Binary Interface) for function calls to the EVM.
API Parameters Description Remarks
web3.eth.blockNumber Returns the current block number.
web3.eth.getBlock Returns a block matching the block number or block hash
web3.eth.getAccounts Function callback Will return a list of the unlocked accounts in the Web3 wallet or it will return the accounts from the currently connected node
web3.eth.getBalance String address
String|Number defaultBlock
Function callback
Get the balance of an address at a given block
web3.eth.getTransactionReceipt Returns the receipt of a transaction by transaction hash.
web3.eth.call Executes a message call transaction, which is directly executed in the VM of the node, but never mined into the blockchain.
web3.eth.sendTransaction Sends a transaction to the network. transaction object (from, to, value, gas, gasPrice, data, nonce)
web3.eth.accounts.privateKeyToAccount String privateKey Creates an account object from a private key. create not an account but an account object
web3.utils.sha3 String string Calculate the sha3 of the input. Alias: keccak256
web3.utils.asciiToHex String string
Number length
Transform an ASCII string into a valid bytes4, bytes8 etc Alias: fromAscii
web3.eth.abi.encodeFunctionCall Object jsonInterfacer
Array parameters
Encodes a function call using its JSON interface object and given parameters.
web3.utils
  // safely convert any given value (including BigNumber.js instances) into a BN.js instance, 
  // for handling big numbers in JavaScript.
  web3.utils.toBN(String|Number|HEX);

  // calculate the sha3 of the input.
  web3.utils.sha3(String);
  web3.utils.keccack256(String);

  // returns the HEX representation of a given ASCII string.
  web3.utils.asciiToHex(String);
  web3.utils.fromAscii(String); // deprecated

Basic Usage

$ truffle console --network ropsten
Warning: Please rename truffle.js to truffle-config.js to ensure Windows compatibility.
truffle(ropsten)> web3.version
'1.2.1'
truffle(ropsten)> web3.eth.getCoinbase()
...
truffle(ropsten)> web3.eth.getCoinbase().then(web3.eth.getBalance).then(v => parseInt(v).toLocaleString())
...
truffle(ropsten)> web3.eth.getNodeInfo()
'Geth/v1.9.9-omnibus-e320ae4c-20191206/linux-amd64/go1.13.4'
truffle(ropsten)> web3.eth.getProtocolVersion()
'0x40'
truffle(ropsten)> web3.eth.net.getPeerCount()
100
truffle(ropsten)> web3.eth.isMining()
false
truffle(ropsten)> web3.eth.getAccounts()
[ ... ]
truffle(ropsten)> web3.eth.getAccounts().then(accts => accts.forEach(acct => web3.eth.getBalance(acct.toString()).then(console.log)))
...
truffle(ropsten)> web3.eth.net.getId()
3
truffle(ropsten)> web3.eth.getGasPrice().then(v => parseInt(v).toLocaleString())
'1,000,000,000'
truffle(ropsten)> web3.eth.getBlock("latest").then(b => parseInt(b.gasLimit).toLocaleString())
'8,000,029'
truffle(ropsten)> web3.eth.getBlockNumber().then(v => v.toLocaleString())
'7,553,661'
truffle(ropsten)> web3.eth.getBlock(0)
{ difficulty: '1048576',
  extraData:
   '0x3535353535353535353535353535353535353535353535353535353535353535',
  gasLimit: '0x1000000',
  gasUsed: '0x0',
  hash:
   '0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d',
  logsBloom:
   '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
  miner: '0x0000000000000000000000000000000000000000',
  mixHash:
   '0x0000000000000000000000000000000000000000000000000000000000000000',
  nonce: '0x0000000000000042',
  number: 0,
  parentHash:
   '0x0000000000000000000000000000000000000000000000000000000000000000',
  receiptsRoot:
   '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421',
  sha3Uncles:
   '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347',
  size: 540,
  stateRoot:
   '0x217b0bbcfb72e2d57e28f33cb361b9983513177755dc3f33ce3e7022ed62b77b',
  timestamp: 0,
  totalDifficulty: '1048576',
  transactions: [],
  transactionsRoot:
   '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421',
  uncles: [] }

Web3j

References

  • API Documentation
Version API
4.5.18 Web3j Core API
Web3j Crypto API
Web3j Utils API
  • Core APIs
                                               extends
                                            +------------ Ethereum
  JsonRpc2_0Web3j ---------------- Web3j ---|
                     implements             +------------ Web3jRx
                                               extends
Class Source API Remark
public class HttpService extends Service HttpService.java HTTP implementation of our services API
org.web3j.protocol.Service Service.java Base service implementation
public class JsonRpc2_0Web3j implements Web3j JsonRpc2_0Web3j.java JSON-RPC 2.0 factory implementation
interface org.web3j.protocol.Web3j Web3j.java extends Ethereum, Web3jRx
interface org.web3j.protocol.core.Ethereum Ethereum.java JSON-RPC methods
interface org.web3j.protocol.rx.Web3jRx Web3jRx.java
interface org.web3j.quorum.Quorum Quorum.java extends Web3j
org.web3j.tx.Contract Contract.java
org.web3j.protocol.core.RemoteCall<T> RemoteCall.java
org.web3j.protocol.core.methods.request.Transaction Transaction.java
abstract org.web3j.abi.TypeReference<T extends org.web3j.abi.datatypes.Type> TypeReference.java
org.web3j.abi.datatypes.Function Function.java
  • ABI Types
  Type<T> ---+--- NumericType implements Type<BigInteger> ---+--- IntType ---+--- Uint ---+--- Uint8
             |                                                |               |            |
             |                                                |               |            +--- Uint16
             |                                                |               |
             |                                                |               +--- Int  ---+--- Int8
             |                                                |                            |
             |                                                |                            +--- Int8
             |                                                |                                      
             |                                                +--- FixedPointType ---+--- Ufixed
             |                                                                       |
             |                                                                       +--- Fixed
             |
             +--- BytesType implements Type<bytes[]> ---+--- Bytes ---+--- Bytes1
             |                                          |             |
             |                                          |             +--- Bytes2
Crypto/Util APIs
Class Method Description Remarks
Keys static ECKeyPair createEcKeyPair(SecureRandom random) Generate Elliptic Curve key pair for a Ethereum account
static ECKeyPair createEcKeyPair() Generate Elliptic Curve key pair for a Ethereum account
static String getAddress(ECKeyPair pair) address in 40-bytes hexadecimal format. Without prefix
static String toChecksumAddress(String address) Checksum address encoding as per EIP-55. EIP-55, With '0x' prefix
RawTransaction static createTransaction createTransaction(...) create raw transaction object that is not signed transaction object
TransactionEncoder static byte[] signMessage(RawTransaction rawTx, Credentials cred) sign a raw transaction
Numeric static BigInteger toBigInt(String hexValue) Get integer representation from the hexadecimal representation for private key, public key, or so on
static String toHexStringNoPrefixZeroPadded(BigInteger value, int size) Get hexadecimal represenation with prefix `0x` and in the specified length from the integer repesentation for private key, public key, or so on
static String toHexString(byte[] input) Get hexadecimal representation of the specified byte array with prefix '0x'
static String toHexStringNoPrefix(byte[] input) Get hexadecimal representation fo the specified byte array without prefix
byte[] hexStringToByteArray(String input) Convert string in hexdecimal format into byte array after removing prefix `0x` if any
// create Elliptic Curved key pair
ECKeyPair pair = Keys.createEcKeyPair();

// get EIP-55(checksum) address with '0x' prefix from EC key-pair
String addr = Keys.toChecksumAddress(Keys.getAddress(pair));

// or get EIP-55 address with '0x' prefix from public key
add = Keys.toChecksumAddress(Keys.getAddress(pair.getPublicKey());

// get private key in hexadecimal string without any prefix - 64 characters with left zero padding
Numeric.toHexStringNoPrefixZeroPadded(pair.getPrivateKey(), Keys.PRIVATE_KEY_LENGTH_IN_HEX);

// get public key in hexadecimal string without any prefix - 128 characters with left zero padding
Numeric.toHexStringNoPrefixZeroPadded(pair.getPublicKey(), 2 * Keys.PRIVATE_KEY_LENGTH_IN_HEX);

// convert hexadecimal string to integer in 'BigInteger' type
final BigInteger gas = Numeric.toBigInt("0x12e140");

Readings


Web3.py

  • https://github.com/ethereum/web3.py
  • Desc. : A Python library for interacting with Ethereum, inspired by web3.js.
  • License : MPL-2.0 (Mozilla Public License 2.0)
  • Written in : Python

API

Category API Description Remarks
Web3 web3.api the current Web3 version
web3.clientVersion the current client version

Basic Usage

Using Brownie and Web3.py together.

>>> web3.eth.coinbase
'0xb009cd53957c0D991CAbE184e884258a1D7b77D9'
>>> web3.eth.getBalance(web3.eth.coinbase)
9995080120300000000000
>>> for acc in web3.eth.accounts[:10]: print(f'{acc}, {web3.eth.getBalance(acc):,}')
...
0xb009cd53957c0D991CAbE184e884258a1D7b77D9, 9,995,080,120,300,000,000,000
0x05f9301Be8F3C133fC474F8d538fD732CaCa274c, 10,000,000,000,000,000,000,000
0x3DC9b4063a130535913137E40Bed546Ff93b1131, 10,000,000,000,000,000,000,000
0x770b1A8d293d152B8Cc9fC01531B1baB3469AF05, 10,000,000,000,000,000,000,000
0xAB3ca295454D4A4de79aE32474d2C82f2D0836b1, 10,000,000,000,000,000,000,000
0x876e0cab3dfC5d2EA19f9A9e6029E8C1b90452Ed, 10,000,000,000,000,000,000,000
0xBb9Bb87EfE2Cf5E024f32c5943311FdA471848Ca, 9,999,898,673,800,000,000,000
0x950ea7798112705f487F657E93Fe5D64557CD138, 9,999,950,898,650,000,000,000
0xA797051B95915F31464440A590332e3360bfEDb9, 9,999,696,040,100,000,000,000
0x9Ebe0ec1f5f2c0f6BA7d9f7187d6f5c540F2b5fa, 10,000,000,000,000,000,000,000
>>> web3.eth.blockNumber
289
>>> web3.eth.getBlock('latest')
AttributeDict({'number': 289, 'hash': HexBytes('0x6e432624d1d6730962cab95e48bf67be818a589f038851d63af3b8c748992633'), 'parentHash': HexBytes('0x8187ad82fc911ffe4658e491dc561ff1526690f4380ea6ff4250b80b865f363e'), 'mixHash': HexBytes('0x0000000000000000000000000000000000000000000000000000000000000000'), 'nonce': HexBytes('0x0000000000000000'), 'sha3Uncles': HexBytes('0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347'), 'logsBloom': HexBytes('0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'), 'transactionsRoot': HexBytes('0x2ab22b1c6b26e27b38af339fa2680a78801de67d7caba46b8c7a01f9fdca9ec7'), 'stateRoot': HexBytes('0x395bc4b216dfcd92a25124d3233010e5c130dc3f07cfd75a0a4c7670346a3f62'), 'receiptsRoot': HexBytes('0xc216ea002b476d3fcf65c0e0d5412cb69831da68ded61246d306b6060c57d82f'), 'miner': '0x0000000000000000000000000000000000000000', 'difficulty': 0, 'totalDifficulty': 0, 'extraData': HexBytes('0x'), 'size': 1000, 'gasLimit': 400000000, 'gasUsed': 26697, 'timestamp': 1609224132, 'transactions': [HexBytes('0x4ef99b474888675edb0f3aa28c310eeb506fa00390f06723b58cc960c9b1ff48')], 'uncles': []})
>>> web3.eth.getBlock(0)
AttributeDict({'number': 0, 'hash': HexBytes('0x515ff4d96e5ab4131d4cd9443ba4dd51ba92b1402f2a79416372efa9945b5094'), 'parentHash': HexBytes('0x0000000000000000000000000000000000000000000000000000000000000000'), 'mixHash': HexBytes('0x0000000000000000000000000000000000000000000000000000000000000000'), 'nonce': HexBytes('0x0000000000000000'), 'sha3Uncles': HexBytes('0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347'), 'logsBloom': HexBytes('0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'), 'transactionsRoot': HexBytes('0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421'), 'stateRoot': HexBytes('0xb477958b9dd0e44345b14ca1dc539ee49098710340252b3ba9ecb289a93a4b89'), 'receiptsRoot': HexBytes('0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421'), 'miner': '0x0000000000000000000000000000000000000000', 'difficulty': 0, 'totalDifficulty': 0, 'extraData': HexBytes('0x'), 'size': 1000, 'gasLimit': 400000000, 'gasUsed': 0, 'timestamp': 1609222192, 'transactions': [], 'uncles': []})
>>>

ethereumjs-tx


OpenZeppelin

References

Contracts
Contract Source Description Remarks
Ownable Ownable.sol
Roles Roles.sol
ERC 20 ERC20 Sources the most widespread token standard for fungible assets
ERC 721 ERC721 Sources the de-facto solution for non-fungible tokens
ERC 777 ERC 777 a richer standard for fungible tokens
Test Helpers
  • Desc. : Assertion library for Ethereum smart contract testing
API Description Remarks
expectEvent
expectEvent.inTransaction
expectEvent.notEmitted
Test Environment
  • Desc. : Blazing fast smart contract testing.

MetaMask


LightWallet


Remix IDE

  • https://github.com/ethereum/remix-ide
  • Desc. : a browser-based compiler and IDE that enables users to build Ethereum contracts with Solidity language and to debug transactions
  • License : MIT License

Readings


Truffle

References

Commands
Command Description Options Remarks
init Initialize new and empty Ethereum project --force
compile Compile contract source files. --list, --all, --network, --quiet
migrate Run migrations to deploy contracts. --reset, --f, --to, --dry-run
test Runs some or all tests within the test/ directory as specified. --show-events

Readings

Test
  • How to use bignumbers in truffle tests? (Feb 14 '19)
    • Avoid using toNumber() on any value returned from a contract function
    • Keep the returned value in its original type (BigNumber on Truffle 4.x / web3 0.x, and BN on Truffle 5.x / web3 1.x)
    • For printout, you're best off using toFixed() (or toLocaleString() maybe)

Examples

  • example-truffle-library : Example project showing how to use Truffle to create javascript libraries
  • truffle-webpack-demo : A demo Webpack + React App using truffle-solidity-loader
  • truffle-typescript-example : Minimal example integration of Truffle + TypeScript + TestRPC run in docker, for writing smart contracts on Ethereum blockchain.
  • Truffle Box : A set of boilerplates to help developers quickly build distributed applications on the Ethereum blockchain with Truffle.

Tips and Tricks

Typical Truffle Configuration
/**
 * You'll also need a mnemonic - the twelve word phrase the wallet uses to generate
 * public/private key pairs. If you're publishing your code to GitHub make sure you load this
 * phrase from a file you've .gitignored so it doesn't accidentally become public.
 *
 */

const HDWalletProvider = require('@truffle/hdwallet-provider');
// const infuraKey = "fj4jll3k.....";
//
// const fs = require('fs');
// const mnemonic = fs.readFileSync(".secret").toString().trim();

// http://truffleframework.com/docs/advanced/configuration
module.exports = {

  networks: {
    
    development: {
      host: '127.0.0.1',
      port: 8545,
      network_id: '31',
      gas: 4E8,
      gasPrice: 2.5E10,
      websockets: true
    },

    //GitHub : https://github.com/ethereum/ropsten/
    //Explorer : https://ropsten.etherscan.io/
    //Faucet : https://faucet.ropsten.be/
    ropsten: {
      provider: () => new HDWalletProvider(process.env.BIP39_MNEMONIC,"https://ropsten.infura.io/v3/" + process.env.INFURA_PROJECT_ID),
      network_id: '3',
      gas: 7E6,
      gasPrice: 1E10
    },

    //Explorer : https://rinkeby.etherscan.io/
    //Faucet : https://faucet.rinkeby.io/
    rinkeby: {
      provider: () => new HDWalletProvider(process.env.BIP39_MNEMONIC, "https://rinkeby.infura.io/v3/" + process.env.INFURA_PROJECT_ID),
      network_id: '4',
    },

    //GitHub : https://github.com/kovan-testnet/
    //Explorer : https://kovan.etherscan.io/
    //Faucet : https://faucet.kovan.network/
    kovan: {
      provider: () => new HDWalletProvider(process.env.BIP39_MNEMONIC, "https://kovan.infura.io/v3/" + process.env.INFURA_PROJECT_ID),
      network_id: '42', //https://github.com/ethereum/wiki/wiki/JSON-RPC#net_version
      gas: 7E6,
      gasPrice: 5E10
    }
  },

  // https://github.com/mochajs/mocha/blob/v5.2.0/lib/mocha.js#L64
  // https://mochajs.org/#command-line-usage
  mocha: {
    useColors: true,
    enableTimeouts: true,
    timeout: 180000
  },

  // http://truffleframework.com/docs/advanced/configuration
  compilers: {
    solc: {
      version: "^0.5.0",
      // version: "^0.6.0",
      settings: {
        optimizer: {
          enabled: false,
          runs: 200
        },
        evmVersion: "petersburg"
      }
    },
  },
};
Typical Truffle Test-case
const Token = artifacts.require("TrustedToken");
const Chance = require('chance');
const toBN = web3.utils.toBN;
const { constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers');

//References
//Truffle test in JavaScript : https://www.trufflesuite.com/docs/truffle/testing/writing-tests-in-javascript
//Truffle Contract Guide : https://www.trufflesuite.com/docs/truffle/getting-started/interacting-with-your-contracts
//Truffle Contract Package : https://github.com/trufflesuite/truffle/tree/master/packages/contract
//Mocha Documentation : https://mochajs.org/#getting-started
//Chai Assert API : https://www.chaijs.com/api/assert/
//Chai Expect/Should API : https://www.chaijs.com/api/bdd/
//OpenZeppelin Test Helpers API : https://docs.openzeppelin.com/test-helpers/0.5/api
//web3 API : https://web3js.readthedocs.io/en/v1.2.11/
//chance.js : https://chancejs.com/
//bn.js : https://github.com/indutny/bn.js/
//JavaScript Reference (MDN) : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
//The Modern JavaScript Tutorial : http://javascript.info/

contract("TrustedToken Test Suite 1", async accounts => {
  'use strict';

  // avoid too many accounts
  if(accounts.length > 8) accounts = accounts.slice(0, 8);

  const EventNames = {
    Transfer: 'Transfer',
    Approval: 'Approval'
  };

  async function createFixtures(){
    const chance = new Chance();
    const admin = chance.pickone(accounts);
    const token = await Token.new('Color Token', 'RGB', {from: admin});
    console.debug(`New token contract deployed - address: ${token.address}`);

    return [chance, admin, token];
  }

  before(async() => {
    const table = [];
    let balance = 0;

    // Before test suite, unlock all accounts and display the balances
    for(const acct of accounts){
        await web3.eth.personal.unlockAccount(acct);
        balance = await web3.eth.getBalance(acct);
        await table.push([acct, balance]);
    }

    console.debug(`The number of accounts : ${accounts.length}`);
    console.table(table);
  });

  describe("Minting", () => {
    // mint(), totalSupply(), balanceOf()
    it("Minting tokens should increase the owners balance and total supply", async() =>{
      const [chance, admin, token] = await createFixtures();

      ...
    });

    // mint(), grantRole()
    it("Only minter can 'mint' a token.", async() => {
      const [chance, admin, token] = await createFixtures();

      ...
    });
  });

  describe("Transfer", () => {

    // transfer(), mint()
    it("Transfer should decrease sender's balance and increase recipient's balance as much", async() => {
      const [chance, admin, token] = await createFixtures();
      
      ...
    });

    // mint(), transfer(), totalSupply()
    it("Token transfer should not change total supply.", async() => {
      const [chance, admin, token] = await createFixtures();

      ....
    });

    // transfer(), mint()
    it("Transfer to ZERO address is illegal.", async() => {
      const [chance, admin, token] = await createFixtures();

      ....
    });
    

    ...
  });

  ...
});

truffle-assertions


Embark


Brownie

Readings

Command Description Remarks
brownie init Initialize a new brownie project
brownie compile Compile the contract source file
brownie test Run test cases in the tests/ folder
brownie run Run a script in the scripts/ folder
brownie console Load the console
brownie networks Manage network settings
brownie networks list [verbose=false] List existing networks

ZeppelinOS


Mist Browser


Ganache CLI

#! /bin/bash

# TODO
#   - Check the availability of the TCP port for Linux
#   - Setup 'logrotate' for Linux

readonly verbose=1  # 1: true, 0: false - Hard coded yet
readonly dryrun=0   # 1: true, 0: false - Not Used Yet
readonly uname=`uname -s`  # OS type
readonly script_dir=$(cd `dirname $0` && pwd)

declare data_dir
declare log_dir
case $uname in
Linux)  #Linux
  data_dir='/var/lib/ganache-cli'
  log_dir='/var/log'
  ;;
MINGW*)  #Git Bash on Windows
  readonly run_dir=$(mkdir -p "${script_dir}/../run/ganache" && cd "${script_dir}/../run/ganache" && pwd)
  data_dir=${run_dir}/data
  log_dir=${run_dir}
  ;;
Darwin*) #Bash on macOS
  readonly run_dir=$(mkdir -p "${script_dir}/../run/ganache" && cd "${script_dir}/../run/ganache" && pwd)
  data_dir=${run_dir}/data
  log_dir=${run_dir}
  ;;
*)
  echo "The current system is Unknown of which 'uname -s' shows '$uname'."
  exit 600
esac


# check whether GNU getopt is available or not
if [ `getopt --test; echo $?` -ne 4 ]; then
  echo "The avaiable 'getopt' is not GNU getopt which supports long options."
  echo "For MacOS, install 'gnu-getopt' refering 'https://formulae.brew.sh/formula/gnu-getopt'."
  exit 410
fi

options=$(getopt -o rb --long "refresh,background" --name 'ganache-cli-start-options' -- "$@");

if [ $? -ne 0 ]; then
  command=${0##*/}
  echo "Unable to parse command line, which expect '$command [-r|--refresh] [-b|--background]'."
  echo ""
  exit 400
fi

eval set -- "$options"

declare refreshes=0   #false
declare backgrounds=0   #false
while true; do
  case "$1" in
    -r | --refresh )
      echo "refresh specified"
      refreshes=1
      shift ;;
    -b | --background )
      backgrounds=1
      shift ;;
    -- ) shift; break ;;
  esac
done

if [ ! -d "${data_dir}" ]; then
  echo "Creating data directory on '${data_dir}'"
  if [ "$uname" == "Linux" ]; then
    sudo mkdir -p "${data_dir}"
  else
    mkdir -p "${data_dir}"
  fi
fi

if [ $refreshes -eq 1 ]; then
  echo "Removing all current data under '${data_dir}'"
  if [ "$uname" == "Linux" ]; then
    sudo rm -Rf "${data_dir}"
    sleep 3
    sudo mkdir -p "${data_dir}"
  else
    rm -Rf "${data_dir}"
    sleep 3
    mkdir -p "${data_dir}"
  fi
fi

cd "${script_dir}"

readonly eth_ver=`cat ganache-cli.properties | grep -E "^ethereum\.netVersion=" | sed -E 's/ethereum\.netVersion=//'`
readonly eth_host=`cat ganache-cli.properties | grep -E "^ethereum\.host=" | sed -E 's/ethereum\.host=//'`
readonly eth_port=`cat ganache-cli.properties | grep -E "^ethereum\.port=" | sed -E 's/ethereum\.port=//'`
readonly eth_gas_price=`cat ganache-cli.properties | grep -E "^ethereum\.gasPrice=" | sed -E 's/ethereum\.gasPrice=//'`
readonly eth_gas_limit=`cat ganache-cli.properties | grep -E "^ethereum\.gasLimit=" | sed -E 's/ethereum\.gasLimit=//'`
readonly eth_keys=`cat ganache-cli.properties | grep -E "^ethereum\.keys" | sed -E 's/ethereum\.keys\.[0-9]*=//'`

if [ $verbose -ne 0 ]; then
  echo "Ethereum Network ID : $eth_ver"
  echo "Ethereum Client Host Address: $eth_host"
  echo "Ethereum Client TCP Port: $eth_port"
  echo "Ethereum Gas Limit: $eth_gas_limit"
  echo "Ethereum Gas Price: $eth_gas_price"
  echo "Ethereum Private Keys for Accounts: "
  for key in $eth_keys; do echo "    $key"; done
  echo "uname: $uname"
fi

case $uname in
Linux)  #Linux
  echo "Current system is 'Linux'"
  ;;
MINGW*)  #Git Bash on Windows
  echo "Curreun system is 'Windows'"
  # check whether the address is alreasy in use or not
  if [ `netstat -anp tcp | awk '$4 == "LISTENING" {print $2}' | grep -E "^($eth_host|0.0.0.0):$eth_port$" | wc -l` -gt 0 ]; then
    readonly pid=`netstat -anop tcp | awk '$4 == "LISTENING" {print $2 " " $5}' | grep -E "^($eth_host|0.0.0.0):$eth_port\s" | head -n 1 | awk '{print $2}'`
    echo "The address '$eth_host:$eth_port' is already in use by the process of which PID is $pid."
    echo "Fail to start ganache-cli."
    exit 500
  fi
  ;;
Darwin*) #Bash on macOS
  echo "Current system is 'macOS'"
  ;;
*)
  echo "Current system is Unknown of which 'uname -s' shows '$uname'."
  exit 600
esac

# Ganache CLI : https://github.com/trufflesuite/ganache-cli#using-ganache-cli
# BIP 32 : https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
# BIP 39 : https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki
#
# Options
#   - gasLimit : The block gas limit (defaults to 0x6691b7)
#   - gasPrice: The price of gas in wei (defaults to 20000000000)

cmd="ganache-cli --networkId $eth_ver \
            --host '$eth_host' \
            --port $eth_port \
            --gasPrice $eth_gas_price \
            --gasLimit $eth_gas_limit"

if [ -n "$eth_keys" ]; then
  echo ""
  echo "Private keys for Ethereum accounts are explicitly specified. They will be used."
  for key in $eth_keys;
    do cmd="${cmd} --account=\"${key},10000000000000000000000\""
  done;
else
  if [ -z "$BIP39_MNEMONIC" ]; then
    echo "'BIP39_MNEMONIC' env. variable is not defined, so implicit default mnemonic will be used."
    echo "If you want to use user defined mnemonic, define it via 'BIP39_MNEMONIC' env. variable and restart this script."
    cmd="${cmd} --deterministic"
  else
    echo "'BIP39_MNEMONIC' env. variable is defined, so it will be used."
    cmd="${cmd} --mnemonic '$BIP39_MNEMONIC'"
  fi
  cmd="${cmd} --defaultBalanceEther 10000 --accounts 10 --secure"
fi

cmd="${cmd} --unlock 0 --unlock 1 --unlock 2 --unlock 3 --unlock 4 \
            --hardfork 'petersburg' \
            --blockTime 0 \
            --db '${data_dir}' >> '${log_dir}'/ganache.log 2>&1"

if [ "$uname" == "Linux" ]; then
  cmd="sudo sh -c \"$cmd\""
  # cmd="sudo sh -c -- $cmd"
fi

if [ $dryrun -ne 0 ]; then
  echo $cmd
  echo ""
  echo "This is 'DRY' run."
  echo "The right above command would be executed, if run again without 'dryrun' option."
  exit 700
fi

if [ $backgrounds -eq 0 ]; then
  echo ""
  echo $cmd
  eval $cmd
else
  cmd=$cmd' &'
  echo ""
  echo $cmd
  eval $cmd

  if [ $? -eq 0 ]; then
    sleep 3
    tail "${log_dir}"/ganache.log -n 50
    echo "The loacal Ganache has started."
    echo "The log file is located at '${log_dir}/ganache.log'."
  fi
fi

Oraclize

  • http://www.oraclize.it/
  • Desc. : the leading oracle service for smart contracts and blockchain applications, serving thousands of requests for day every day on Ethereum, Bitcoin and Rootstock.
  • License :

Aleth.io

Readings

Memento

Lity

  • Components
    • a dynamically extensible language : a superset of the Solidity language
    • a compiler
    • a virtual machine

Readings

Ethereum plugin for Vault

Readings

EthSigner

Readings

Slither

Readings

Solhint

Readings

Mythril

  • https://github.com/ConsenSys/mythril
  • Desc. : detects security vulnerabilities in smart contracts built for Ethereum, Hedera, Quorum, Vechain, Roostock, Tron and other EVM-compatible blockchains.
  • License : MIT

Certora

Securify

Manticore

SmartBugs

uPort Identity Contracts

Substrate

Ripple

References

rippled API

Category API Methods Description Remarks
Public subscribe WebSocket requests periodic notifications from the server when certain events happen Ledger Stream, Validations Stream, Transaction Streams, Peer Status Stream, Order Book Streams
Admin ledger_request WebSocket, Commandline tells server to fetch a specific ledger version from its connected peers

Consensus

   Round Start --------------- Close -------------------- Consensus -------------------- Round End
                 Open phase            Establish phase                  Accept phase
  • The XRP Ledger Consensus Process
  • Consensus
    • Concensus
      • Through the consensus process, validating nodes agree on a specific subset of the candidate transactions to be considered for the next ledger
      • Consensus is an iterative process in which nodes relay proposals, or sets of candidate transactions.
      • Nodes communicate and update proposals until a supermajority 5 of peers agree on the same set of candidate transactions.
    • Validation
      • The validating nodes calculate a new version of the ledger and relay their results to the network, each sending a signed hash of the ledger it calculated based on the candidate transactions proposed during consensus.
      • In cases where a node is in the minority, having computed a ledger that differs from its peers, the node disregards the ledger it computed 9. It recomputes the correct ledger, or retrieves the correct ledger as needed.
  • rippled Server States
                                                            +--> full
                                                            |
   disconnected ---> connected ---> syncing ---> tracking --| 
                                                            |
                                                            +--> validating <-----> proposing

Transaction

  • Reliable Transaction Submission
    • Best Practices
    • Your rippled server should automatically acquire the missing ledger versions when it has spare resources (CPU/RAM/disk IO) to do so, unless the ledgers are older than its configured amount of history to store. Depending on the size of the gap and the resource usage of your server, acquiring missing ledgers should take a few minutes. You can also manually request your server to acquire historical ledger versions using the ledger_request method.
    • Use the LastLedgerSequence parameter to prevent undesirable cases where a transaction is not confirmed promptly but could be included in a future ledger. You should specify the LastLedgerSequence parameter on every transaction. Automated processes should use a value of 4 greater than the last validated ledger index to make sure that a transaction is validated or rejected in a predictable and prompt way.

Ledger

  • Ledgers
    • Ledger = Header + Transaction Tree + State Tree (Ledger Objects)
    • At any given time, a rippled instance has an in-progress "current" open ledger, plus some number of closed ledgers that have not yet been approved by consensus, and any number of historical ledgers that have been validated by consensus.
    • Only the validated ledgers are certain to be correct and immutable.
  • Ledger Header
    • Two ledgers with the same hash are always the same.
    • For validated ledgers, hash values and sequence numbers are equally valid and correlate 1:1.
    • Two different rippled servers may have different contents for a current ledger with the same ledger index, due to latency in propagating transactions throughout the network.
    • There may be multiple closed ledger versions competing to be validated by consensus. These ledger versions have the same sequence number but different contents (and different hashes). Only one of these closed ledgers can become validated.
    • A current ledger's contents change over time, which would cause its hash to change, even though its ledger index number stays the same. The hash of a ledger is not calculated until the ledger is closed.

Amendments

Readings

Troubleshooting

Sources

Component Type Description Remarks
SHAMapStoreImp.h, SHAMapStoreImp.cpp class
Setup struct deleteInterval, advisoryDelete, ledgerHistory, databasePath, deleteBatch, backOff, ageThreshold
Config.h class

Stellar

Hyperledger

Hyperledger Fabric

Readings

  • Concepts
    • Channels
      • Channel = Organizations + Ordering Service + Anchor Peers + Chaincodes + Ledger
      • At least one anchor peer per organization

Examples

Demos

Sources

  • fabric/core/ledger/ledgerconfig/ledger_config.go

Issues

Docker Images

fabric-peer

Config which is printed by "docker inspect --format='{{json .Config}}' ..." is

   
 "Config": {
   "Hostname": "e7eddde82bec",
   "Domainname": "",
   "User": "",
   "AttachStdin": false,
   "AttachStdout": false,
   "AttachStderr": false,
   "Tty": false,
   "OpenStdin": false,
   "StdinOnce": false,
   "Env": [
     "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
     "PEER_CFG_PATH=/etc/hyperledger/fabric",
     "CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/fabric/msp/sampleconfig"
   ],
   "Cmd": [
     "peer",
     "node",
     "start"
   ],
   "ArgsEscaped": true,
   "Image": "sha256:793719e9dd193f580f32c5984ac47a8c0f986819e4795c039703b26bb6ad15ce",
   "Volumes": null,
   "WorkingDir": "",
   "Entrypoint": null,
   "OnBuild": [],
   "Labels": {
     "org.hyperledger.fabric.base.version": "0.3.0",
     "org.hyperledger.fabric.version": "1.0.0-alpha"
   }
 },

Fabric CA

Fabric SDK for Node.js

Performance Tuning

  • LVM (Logical Volume Manager)

Companions

PTE

R3 Corda

Concepts

Concept Description Remarks
State Object a digital document which records the existence, content and current state of an agreement between two or more parties
Ledger a set of immutable state objects
Consensus pure function whose responsibility is either to accept or reject a proposed transaction and which can be composed from simpler, reusable functions
Transaction Consume existing state objects and produce new state objects Transaction Validity, Transaction Uniqueness
Smart Contract
Uniqueness and Timestamping Services
Flow Framework
          State Object ----+----> Contract Code
                           +----> Legal Prose

Features

References

  • End-State Principles
Principle Description Remarks
Inclusion Parties are able to discover each other freely, and transact directly, in a single, open network
Assured identity Parties will have assurance over the identity of participants in the network
Privacy The only parties who have access to the details of a transaction are those who participate in the transaction and those who need to assure themselves of transaction provenance.
Shared logic The behavior of agreements managed by the system will be described in computer code that is shared to ensure onsistency and validity of agreements
Legal footing Deals recorded by the ledger are, by contract, accepted as admissible evidence and legally binding by all parties in any dispute
Authoritative Facts recorded by the ledger are regarded as authoritative rather than “shadows” of authoritative data held elsewhere
Immutability Facts recorded on the ledger are final and immutable; errors and unwinds must be processed through a subsequent transaction
Open The system is open: open source, participation, development, governance and standards to ensure the platform balances the needs of its diverse user-base in a transparent fashion

Readings

Eris

References

Readings

Tendermint Core

Readings

IPFS

  • https://ipfs.io/
  • Desc. : A peer-to-peer hypermedia protocol to make the web faster, safer, and more open

STO

AML

Polymath

CoFi OS

  • https://github.com/ConsenSys/ERC1400
  • Desc. : an advanced institutional technology platform for issuing and exchanging tokenized financial assets, powered by the Ethereum blockchain.

De-Fi

  • DeFi Pulse : a site where you can find the latest analytics and rankings of DeFi protocols.

MakerDAO

DAI

  • DAI
    • Decentralized Stable Coin
    • Backed by Ether

Compound

Synthetix

DID

Concept Description Remarks
Holder A role an entity might perform by possessing one or more verifiable credentials and generating verifiable presentations from them. students, employees, customers
Issuer A role an entity performs by asserting claims about one or more subjects, creating a verifiable credential from these claims, and transmitting the verifiable credential to a holder. corporations, trade associations, governments
Verifier A role an entity performs by receiving one or more verifiable credentials, optionally inside a verifiable presentation, for processing.
Subject An entity about which claims are made. In many cases the holder of a verifiable credential is the subject, but in certain cases it is not. human beings, animals, things
Claim An assertion made about a subject.
Credential A set of one or more claims made by an issuer.
Verifiable Credential a tamper-evident credential that has authorship that can be cryptographically verified.