Smart Contract info

Smart Contract info

  • Contracts
  • TodoList
  • Help
  • Github
  • Blog

›Recent Posts

Recent Posts

  • Fixing Build Pipeline
  • Introduction to Bchain
  • Sept Status Report
  • Travis CI Configured

Fixing Build Pipeline

November 12, 2018

David Li

David Li

Solidity-docgen travis CI issues

Since the solc package was updated to version 5.0, and ppa eliminate previous versions, I found myself needed to install an old version.

What I ended up doing is manually downloading the binary using wget and then linking it to path

Introduction to Bchain

September 9, 2018

David Li

David Li

Bchain

Three important attributes of blockchain are:

  • Trust: Blockchain helps in creating applications that are decentralized and collectively owned by multiple people. Nobody within this group has the power to change or delete previous transactions. Even if someone tries to do so, it will not be accepted by other stakeholders.

  • Autonomy There is no single owner for blockchain-based applications. No one controls the blockchain, but everyone participates in its activities. This helps in creating solutions that cannot be manipulated or induce corruption.

  • Intermediaries Blockchain-based applications can help remove the intermediaries from existing processes. Generally there is a central body, such as vehicle registration, license issuing, and so on, that acts as registrar for registering vehicles as well as issuing driver licenses. Without blockchain-based systems, there is no central body and if a license is issued or vehicle is registered after a blockchain mining process, that will remain a fact for an epoch time-period without the need of any central authority vouching for it.

There are the following two types of cryptography in computing: Symmetric and Asymmetric

Types of cryptography

Symmetric cryptography refers to the process of using a single key for both encryption and decryption.

Asymmetric cryptography refers to the process of using two keys for encryption and decryption. Any key can be used for encryption and decryption. Message encryption with a public key can be decrypted using a private key and messages encrypted by a private key can be decrypted using a public key.

Hashing is the process of transforming any input data into fixed length random character data, and it is not possible to regenerate or identify the original data from the resultant string data. Hashes are also known as fingerprint of input data.

What is Gas

This is also known as gas cost. There is also gas price that can be adjusted to a lower price when the price of Ether increases and a higher price when the price of Ether decreases.

Properties of Ethereum Transactions

A transaction has some of the following important properties related to it:

  • The from account property denotes the account that is originating the transaction and represents an account that is ready to send some gas or Ether. Both gas and Ether concepts were discussed earlier in this chapter. The from account can be externally owned or a contract account.

  • The to account property refers to an account that is receiving Ether or benefits in lieu of an exchange. For transactions related to deployment of contract, the to field is empty. It can be externally owned or a contract account.

  • The value account property refers to the amount of Ether that is transferred from one account to another.

  • The input account property refers to the compiled contract bytecode and is used during contract deployment in EVM. It is also used for storing data related to smart contract function calls along with its parameters. A typical transaction in Ethereum where a contract function is invoked is shown here. In the following screenshot, notice the input field containing the function call to contract along with its parameters:

    • The blockHash account property refers to the hash of block to which this transaction belongs.

    • The blockNumber account property is the block in which this transaction belongs.

    • The gas account property refers to the amount of gas supplied by the sender who is executing this transaction.

    • The gasPrice account property refers to the price per gas the sender was willing to pay

    • The hash account property refers to the hash of the transaction.

    • The nonce account property refers to the number of transactions made by the sender prior to the current transaction.

    • The nonce account property refers to the number of transactions made by the sender prior to the current transaction.

    • The value account property refers to the amount of Ether transferred in wei.

    • The v, r, and s account properties relate to digital signatures and the signing of the transaction.

Properties of Ethereum Blocks

  • The difficulty property determines the complexity of the puzzle/challenge given to miners for this block.

  • The gasLimit property determines the maximum gas allowed. This helps in determining how many transactions can be part of the block.

  • The gasUsed property refers to the actual gas used for this block for executing all transactions in it.

  • The hash property refers to the hash of the block.

  • The nonce property refers to the number that helps in solving the challenge.

  • The miner property is the account identifier of the miner, also known as coinbase or etherbase.

  • The number property is the sequential number of this block on the chain.

  • The parentHash property refers to the parent block’s hash.

  • The receiptsRoot, stateRoot, and transactionsRoot properties refer to Merkle trees discussed during the mining process.

  • The transactions property refers to an array of transactions that are part of this block.

  • The difficulty property determines the complexity of the puzzle/challenge given to miners for this block.

Mining Protocols

Proof of Work

(PoW) wherein a miner provides proof that it is has worked on computing the final answer that could satisfy as solution to the puzzle.

Proof of Stake (PoS)

concept states that a person can mine or validate block transactions
according to how many coins he or she holds. The creator of the next
block is chosen via various combinations of random selection and
wealth or age (i.e., the stake)

** Proof of Authority (PoA)**

transactions and blocks are validated by approved accounts, known as validators. Validators run software allowing them to put transactions in blocks. The process is automated and does not require validators to be constantly monitoring their computers. It, however, does require maintaining the computer (the authority node) uncompromised.

Proof of Space Time (PoST)

apparently able to run on any computer without expensive hardware. A PoST allows a prover to convince a verifier that she spent a “space-time” resource (storing data space over a period of time) [1]

Geth allows connectivity to JSON RPC using the following three different protocols:

  • Inter Process Communication (IPC): This protocol is used for inter process communication generally used within the same computer.

  • Remote Procedure Calls (RPC): This protocol is used for inter process communication across computers. This is generally based on TCP and HTTP protocol.

  • Web Sockets (WS): This protocol is used to connect to Geth using sockets.

Variable NameDescription
block.blockhash(uint blockNumber) returns (bytes32)hash of the given block - only works for 256 most recent, excluding current, blocks - deprecated in version 0.4.22 and replaced by blockhash(uint blockNumber).
block.coinbase (address)current block miner’s address
block.difficulty (uint):current block difficulty
block.gaslimit (uint)current block gaslimit
block.number (uint)current block number
block.timestamp (uint)current block timestamp as seconds since unix epoch
gasleft() returns (uint256)remaining gas
msg.data (bytes)complete calldata
msg.gas (uint) to be gasLeft()remaining gas - deprecated in version
msg.sender (address)sender of the message (current call)
msg.sig (bytes4)first four bytes of the calldata (i.e. function identifier)
msg.value (uint)number of wei sent with the message
now (uint)current block timestamp (alias for block.timestamp)
tx.gasprice (uint)gas price of the transaction
tx.origin (address)sender of the transaction (full call chain)

In solidity, there are a few ground rules for a library contract, which differentiates it from a normal contract. These are:

  • A library cannot have a state variable

  • A library cannot inherit or be inherited

  • A library cannot receive ether.

Solidity is a work-in-progress yet well-documented language, being gradually developed as users face various problems while implementing smart contracts on the blockchain.

Token vs Coin

In simple words, the following three points summarize the difference between coins and tokens:

  • Coins are separate currencies on their own blockchain, while tokens are mainly based on a single blockchain variant

  • Coins generally have a limited functionality, store-of-value, while tokens can store a complex, multi-faceted level of values.

  • Coins are mostly generated by mining a blockchain, while tokens are generated by executing smart contracts on the blockchain.

Ponzi Scheme

  • Array based pyramid scheme

    • An early adopter in this scheme can redeem their multiplied investement when enough money is gathered from the useres who alter on join the scheme.

    • The last user must wait until all the users before her have redeemed their share

  • Tree based pyramid scheme

    • Each user has a parent, called inviter, expect the root node, which is the contract owner

    • Whenever a user joins the scheme, their money is split among its ancestors

    • An user cannot foresee how much they will gain

  • Handover schemes

    • Store only the address of the last user.

    • If someone wants to join, she must repay the last user of her investment plus a fixed interest.

  • Waterfall schemes

    • Each new investment gets divided among the already-joined users, starting from the first one.

    • Each user receives a fixed percentage of what they have invested, as far as there is enough money.


  1. For PoST, see https://eprint.iacr.org/2016/035.pdf ↩

Sept Status Report

September 8, 2018

David Li

David Li

Solidity

Solidity Notes

Solidity receives many comparisons to JavaScript, but its closest relative is C. Solidity is a strongly typed language with minimal functionality that emphasizes limiting storage and CPU usage. It supports 256-bit data types for the EVM, unlike most languages, which support only 32- and 64-bit processors.

In general, Solidity development should be treated more like building a bridge than building a web site. The process is not iterative.

Whenever possible, proven legacy code should be used instead of new, untested code. Contracts should be thoroughly tested and vetted before being deployed to the mainnet.

pragma solidity ^0.4.15;
contract HelloWorld {
 address owner;
 string greeting = "Hello World";
 // Constructor function
 function HelloWorld () public {
 owner = msg.sender;
 }
 function greet () view public returns (string) {
 return greeting; 
 }
 function kill () public {
 require(owner == msg.sender);
 selfdestruct(owner);
 }
}

Visibility modifiers determine the contexts in which a function can be executed. There are four visibility modifiers in Solidity:

  • private: Only the current contract can use the function.

  • internal: Only the current contract and contracts inheriting from the current contract can execute the function.

  • external: The function can be triggered only by a transaction or external contract.

  • public: There are no restrictions on how the function can be called.

Only some functions are permitted to modify the state tree. Functions declared with one of the following three modifiers cannot modify state or send ether:

  • view: Can read information from the state tree but cannot modify state.

  • pure: Cannot read or modify the state tree. Th return value depends on only the function arguments.

  • constant: An alias for view. Deprecated to prevent confusion with constant variables.

The modifier payable is special, allowing functions to accept ether.

Fallback Functions

Every contract can have one unnamed function that acts as a default function to execute when no other functions can match the transaction call or when a transaction is sent to a contract without specifying a function.

The type mapping is Solidity’s version of a hashmap. It’s a key/value store in which both the key and the value must adhere to the specified data type. The value can be any data type, whereas the key type is restricted to address, bool, the integer types, fixed-size arrays, and the fixed-size byte types.

Data TypesZero Value
Integers Values0
boolfalse
address0x0
Bytes types0
Array[](length=0)
mappingno keys

Variables set or initialized to the zero value in Solidity are not included in the state tree. The delete keyword in Solidity resets a variable to its zero value and deletes the variable from the state tree.

Solidity stores locations in two places: in the state tree and in memory. Storage in the state tree persists on the blockchain, whereas the memory is cleared after every transaction. Storage on the state tree is expensive and should be used only when necessary. Memory is cheap and should be used whenever possible. Solidity refers to these two locations as storage for the state tree and memory for memory.

    uint a = 3;
    2 + 3; // addition
    a += 3; // shorthand for a = a + 3
    a++; // shorthand for a += 1
    3 - 2; // subtraction
    a -= 1; // shorthand for a = a -1
    a--; // shorthand for a -= 1
    3 * 2; // multiplication
    a *= 3; // shorthand for a = a * 3
    4 / 2; // integer division
    3 / 2; // = 1, no floating point arithmetic
    a /= 2; // shorthand for a = a / 2;
    10 % 2; // modulus
    2**3; // power operator, this is 23
    2e7; // scientific notation, this is 2 * 107
uint a = 10;
uint b = 3;
// multiply by 10**n to add n zeros
// if you add n zeros, the last n digits will
// be the decimal digits
uint c = (a * 10**6) / b; // 3333333
1 == 1 wei;
1 ether == 10**18 wei;
2 ether == 2e18 wei;
2 finney == .002 ether;
if (msg.value == 1 ether) buyLottoTicket();
msg.value; // 1000000000000000000 a.k.a. 1 ether

Improper use of the ether transfer functions are the number one source of Solidity bugs and hacks. There are three ways to send ether in Solidity:

  • address.transfer(value)
  • address.send(value)
  • address.call.value(value)()
// DO NOT USE: BAD CODE
contract TrustFund {
 address[3] children;
 function TrustFund (address[3] _children) {
 children = _children;
 }
 function updateAddress(uint child, address newAddress)
 {
 require(msg.sender == children[child]);
 children[child] = newAddress;
 }
 function disperse () {
 uint balance = address(this).balance;
 children[0].transfer(balance / 2);
 children[1].transfer(balance / 4);
 children[2].transfer(balance / 4);
 }
 function () payable {}
}

If I’m the second child and I’m upset that I’m not receiving my fair share, I can lock up the contract so that no one can access their funds by updating my address to an empty contract with no fallback function: contract SaltyChild {}

Safely Dispersing Ether to a Fixed Number of Addresses

function disperse () {
 uint balance = address(this).balance;
 children[0].send(balance / 2);
 children[1].send(balance / 4);
 children[2].send(balance / 4);
}

Race condition is the general term for the class of bugs that can occur when calling external contracts. A race condition can occur when any unknown state change occurs in an external function call. A re-entrancy attack is one form of race condition. Another form of race condition can occur if two contracts are both modifying the same variable in a third contract.

I love IPFS

IPFS

  • https://ipfs.github.io/public-gateway-checker/
  • https://medium.com/coinmonks/step-by-step-approach-to-create-dapp-using-ethereum-reactjs-ipfs-part-1-42ea4cf69488

Travis CI Configured

August 25, 2018

David Li

David Li

CI/CD

CircleCI

version: 2
jobs:
  build:
    working_directory: ~/smart-contracts
    # The primary container is an instance of the first image listed. The job's commands run in this container.
    docker:
      - image: circleci/node:8-browsers
    # The secondary container is an instance of the second listed image which is run in a common network where ports exposed on the primary container are available on localhost.
      - image: trufflesuite/ganache-cli
    steps:
      - checkout
      - run:
          name: Update npm
          command: 'sudo npm install -g npm@latest'
      - restore_cache:
          key: dependency-cache-{{ checksum "package.json" }}
      - run:
          name: Install npm wee
          command: npm install
      - run:
          name: Migrate Contracts
          command: ./node_modules/truffle/build/cli.bundled.js migrate --network development
      - run:
          name: Test Contracts
          command: ./node_modules/truffle/build/cli.bundled.js test --network development
      - save_cache:
          key: dependency-cache-{{ checksum "package.json" }}
          paths:
            - node_modules

Gitlab CI

image: node:8.1.1

cache:
  paths:
  - node_modules/

stages:
  - truffle-tests

smart_contracts:
  stage: truffle-tests
  services:
   - trufflesuite/ganache-cli
  script:
   - npm install truffle
   - ./node_modules/truffle/build/cli.bundled.js compile
   - ./node_modules/truffle/build/cli.bundled.js migrate --network gitlab
   - ./node_modules/truffle/build/cli.bundled.js test --network gitlab

travis.yml

sudo: required
language: node_js
node_js:
  - "8"
addons:
  apt:
    sources:
      - google-chrome
    packages:
      - google-chrome-stable
cache:
  directories:
  - node_modules
before_install:
  - export CHROME_BIN=chromium-browser
  - export DISPLAY=:99.0
  - sh -e /etc/init.d/xvfb start
install:
  - npm install -g truffle
  - npm install -g ganache-cli
  - npm install
script:
  #- npm run lint
  - stage: test
  - npm run ganache
  - sleep 5
  - truffle migrate --network development
  - npm run test/truffle 
  - npm run unit
  - npm run e2e
  - npm run stop
  - stage: solidity-docs
  - sudo add-apt-repository -y ppa:ethereum/ethereum
  - sudo apt-get update
  - sudo apt-get -y install solc
  - solidity-docgen . contracts docs
after_script:
  - npm run coverage && cat coverage/lcov.info | coveralls

Test-rpc

image: node:8.11.1

cache:
  paths:
  - node_modules/

stages:
  - test
  - deploy

truffle-tests:
  stage: test
  before_script:
   - npm i --save-dev run-with-testrpc
   - npm i truffle@4.1.4
   - npm install -g ganache-cli 
  script:
   - npm install
   -  ./node_modules/truffle/build/cli.bundled.js compile
   - ./node_modules/.bin/run-with-testrpc './node_modules/truffle/build/cli.bundled.js migrate && ./node_modules/truffle/build/cli.bundled.js test'
  allow_failure: true

frontEnd-tests:
  stage: test
  before_script:
   - npm i --save-dev run-with-testrpc 
   - npm i truffle jest
   - npm install -g ganache-cli
  script:
   - npm install
   - ./node_modules/truffle/build/cli.bundled.js compile
   #- npm run docs
   - ./node_modules/.bin/run-with-testrpc './node_modules/truffle/build/cli.bundled.js migrate && npm run test' 
Smart Contract info
Docs
Getting Started (or other categories)Guides (or other categories)API Reference (or other categories)
Community
User ShowcaseStack OverflowProject ChatTwitter
More
BlogGitHubStar
Copyright © 2019 David Li