Category Archives: smart contracts

Ethereum Commonwealth development update (11 Jan, 2018)

1. Callisto network project.

Rationale:

  • The main goal of Callisto network is to research and provide a reference implementation of an experimental protocol changes that aim to establish a smart-contract based on-chain governance system, completely financially transparent built-in development funding mechanism and balance the interest in the network between the miners and coin holders (ordinary network users).
  • It is possible to improve the scalability of both ETC and Callisto networks by using one as a sidechain.
  • Create a field for crosschain services improvements. It is also possible to establish a core of any crosschain service at the Callisto network and use Callisto smart-contracts state on ETC chain and visa versa which allows to facilitate the bandwidth of ETC chain. (Currently, DexNS, Address-To-Address message system, Token swap channels and ECNS are crosschain services that are deployed on ETC chain simultaneously)

Here you can track the progress:

Summary:

Callisto is a separate blockchain that is based on Ethereum protocol with its own cryptocurrency (CLO). Callisto has a fixed cap monetary policy similar to ETC. Unlike ETH, ETC is posing itself as a value storage. It should be noted that the ETC does not have any incentives for coin holders. The whole emission is completely controlled by miners and their influence grows with the growth of the network. Callisto introduces a Cold staking protocol that rewards coin holders for being a network participants.

Cold staking is a smart-contract based process that allows CLO holders to earn interest in a total CLO emission when they hold CLO coins at their balances for long enough preiod of staking time (1 month by default).

Cold stakers are not required to run a node to participate in cold staking process. Cold stakers are not validating transactions and the whole system can remain fully POW which is important since ETC adheres to POW consensys. It is only necessary to call the “Staking contract” to become a cold staker.

Cold staking is a step towards the goal of turning the desired cryptocurrency into a value storage currency because this significantly increases a total demand to hold for stake holders. Further protocol improvements would be described at this open document. It may take years to propose any changes to ETC protocol and achieve a consensys on whether we need to implement it or not. As the result it was decided to launch a separate network to implement the protocol. If the reference implementation will succeed then we can implement the protocol changes on ETC as well.

Cold staking protocol could be an intermediate step of automated on-chain governance system implementation.

Callisto whitepaper will be released soon.

Callisto initial distribution

It was decided to distribute the initial stake of CLO between current ETC holders. We will make a snapshot of ETC blockchain at block 5500000 (approximately 5 March, 2018. This depends on ETC block time and ETC hashrate changes). Then we implement the initial balance of each ETC holder in the Callisto network genesis block, so each ETC owner will receive CLO coins automatically in a 1:1 ratio to the amount of ETC that he had at block 5500000.

2. Cold staking protocol.

Problem that is solved by this project:

  • There is no incentive for coin holders to continue to own coins which is important for “store of value” currencies.
  • Interest and influence in the network are not balanced. The balance is strongly biased towards the miners.
  • Lack of governance system. Cold staking protocol could serve as an intermediate step for governance system implementation.

Here you can track the progress:

Update summary:

Reference implementation of the cold staking protocol is developed and tested. The 1.0 version of the protocol has some issues that can hurt the network bandwidth in some circumstances. The 2.0 version of the protocol is intended to resolve bandwidth issues but it is still in development.

3. Callisto testnet.

Problem that is solved by this project:

  • Lack of a specialized testnet for Callisto and ETC chains. If Ethereum will introduce any breaking changes then there will be no viable testnet for ETC chain. Morden testnet is very old and require syncing and mining a test block to start testing contracts on it which is not suitable in most cases.

Here you can track the progress:

Update summary:

Callisto-TEST is ETC-compatible implementation of Callisto protocol that allows to run smart-contracts with the same version of EVM that ETC is currently relying on. Unfortunately, there is no blockchain explorers that support Callisto-TEST now. We are working on our own blockchain explorer that will support multiple networks but it is still in development.

Callisto-TEST is now supported at ClassicEtherWallet.This means that any developer can successfully deploy, run, test and debug contracts on Callisto-TEST network.

We have a manual faucet for Callisto at the moment. You should join the ETC discord and type your address at the special #callisto-faucet channel in tech topic. We will distribute test-CLO manually (analogue to how Ropsten testnet works).

Advantages of Callisto-TEST network:

  • Proof of Authority consensys. High DDOS resistance.
  • Zero install requirements to test your contracts at this testnet.
  • No need to sync your node to test contracts at this testnet.
  • Reduced block time for testing reasons which allows to execute contract calls and normal transactions faster.

4. DexNS revenue.

Here you can track the progress:

Update summary:

A final version of DexNS is launched. 56 names are currently registered at DexNS which brings 5,6 ETC to the revenue distribution address. The amount is too small to launch a distribution between DEX token holders now.

The amount of revenue that is generated by DexNS will be distributed between DEX token holders according to announcement#24: revenue distribution process of Ethereum Commonwealth as soon as the amount of revenue will be sufficient to cover gas fees for transfers to the smallest DEX holders.

5. Address to Address message system.

Problem that is solved by this project:

  • This contract solves the problem of impossibility to contact the address owner without knowing anything other than his address.
  • Ethereum lacks a central messaging system that will allow to contact an address owner directly. As the result there is no viable way to deliver a message to address owner without knowing his real identity.

Here you can track the progress:

Update summary:

A2A Message smart-contract is successfully deployed. The next step is UI implementation and integration with ClassicEtherWallet.

For more information read this: https://www.reddit.com/r/EthereumClassic/comments/7n2a83/addresstoaddress_message_system_based_on/

6. ClassicEtherWallet maintenance.

Rationale:

  • Maintain and improve the efficiency of the main web-wallet of Ethereum CLassic.

Here you can track the progress:

Update summary:

  • Callisto-TEST network integration.
  • Specialized GAS options for Callisto-TEST network.
  • Minor UI fixes and upgrades.
  • UBQ RPC endpoint fix.

Ethereum Commonwealth

Ethereum Commonwealth is a completely financially transparent development team that aims to solve a number of Ethereum Classic infrastructure problems and improve the whole Ethereum Classic ecosystem.

You can find a complete Ethereum Commonwealth roadmap here.

Ethereum Commonwealth official address: 0x52823e725a34d42e14a1b66fb67299c30c4d8edf

If you have something to say, feel free to reply to this post or contact via e-mail: dexaran@ethereumclassic.org

當性交同意書/自願做愛證明書都上blockchain (認真post)

以下呢兩張form你可能都會見過?

Kian Lee

呢兩張嘢都係為咗證明雙方都係出於同意先會發生性關系嘅文件,網上流傳多時,有幾多人用,係咪有用,效果成疑。

不過有間startup公司https://legalfling.io就非常認真咁做咗隻app俾大家喺隻app度簽名證明,保證唔會有手尾跟。原來外國都有呢個問題,唔係淨係港女偷食完俾正印發現先會告強姦㗎!

呢種類型嘅同意app,並唔係新發明,之前都有其他例如http://sasie.date/http://we-consent.org/做過。不過blockchain年代,咩鬼都可以ICO,咩鬼都可以加個blockchain buzzword就成件事潮晒。所以LegalFling就大膽採用blockchain技術去處理呢d雙方同意嘅record啦。

blockchain技術除咗可以用來做bitcoin之類嘅cryptocurrency之外,其實仲可以用嚟做smart contract,即係將code同record都儲存落去blockchain上嘅一個block度,由smart contract決定數據應該點樣寫,如果牽涉金錢交易,又點樣先放行個transfer咁。而家ethereum係最多人用嚟deploy smart contract嘅架構,但ethereum有個問題,就係一般情況下account嘅address都唔會改變,即係只要你有果個人嘅address,上去個etherscan度睇睇,你就知道邊個最多錢,個address嘅主人做咗幾多個transaction之類。(當然你唔會知呢個係邊個嘅)

換言之,如果冇特別去跟進呢個address privacy嘅問題的話,你只要攞咗佢address check一check,睇吓呢個account同smart contract account嘅交易紀錄,隨時睇到佢之前同幾多不同嘅人玩過,邊個係雞係公廁真係無所遁形。喺系統設計時要特別周全哋去諗點樣可以令個user同人交易緊,但又唔知道對方嘅address,諗起都覺得頭痛。不過咁可能都係一種對雙方健康嘅保障?

如果上述有錯,請指正!

Ethereum Development Guide — Part 1

Developing an Ethereum Document Certification Application

Introduction

Document certification, also known as timestamping or proof of existence, is one of the most obvious use cases for blockchain technology beyond digital currencies. Document certification consists in saving a tamper-proof timestamped fingerprint of a document (or binary file) on the blockchain. This basically serves as proof that the document existed in a certain version at a certain time and can be used to prove integrity of the file. That is, you can prove that a document has not been modified since its certification. Use cases cover registering private contracts, protecting copyright, sealing log files and any other case where file integrity is important.

In this tutorial we will look at how to create an Ethereum contract that allows to store data on the blockchain and read it, by using document certification as an example. To do so, we will create a simple smart contract that saves an SHA-256 hash of a file on the blockchain, together with a timestamp. SHA-256 hashes uniquely identify sets of data by means of a cryptographic hash function. We will not go into detail on hash functions and cryptography here, but you should know that a SHA-256 hash is a 32-byte fingerprint derived from the input data. The reverse operation, i.e. calculating the data from the hash value, is not feasible, so data protection is a welcome side-effect.

Document certification is fairly easy to implement, which means it is ideal for explaining certain concepts and techniques without unnecessary complexity, whilst still being more useful than typical “Hello World” examples.

Prerequisites and Learning outcomes

To follow this tutorial you need some basic understanding of the command line, text editing and a basic understanding of how blockchains work. You should have Node.js installed on your system and know some Javascript. After following this tutorial you will know how to:

  • Write a simple smart contract for the Ethereum blockchain
  • Store and retrieve data on the blockchain
  • Understand the difference between a transaction and a call
  • Deploy and test a smart contract in a local test environment
  • Use basic functionality of a professional Ethereum development framework

Developing the smart contract

We will use the Solidity programming language to write our contract and the Truffle framework to ease development.

Install Truffle with the following command (the -g option may require root privileges on your system):

npm install -g truffle

Now, we are ready to initialize our smart contract development project. In a new directory type the following:

truffle init

This creates various directories and files. For now we will create a Solidity source file in the contracts directory. We can use truffle to create the file with some scaffolding code for us:

truffle create contract Notary

This creates a file called Notary.sol in the contracts directory. In the same directory there is also a Migrations.sol file. This is a contract used by truffle to aid blockchain deployment. You should leave this file untouched. Let’s edit Notary.sol to contain the following code:

pragma solidity ^0.4.4;
contract Notary {
struct Record {
uint mineTime;
uint blockNumber;
}
mapping (bytes32 => Record) private docHashes;
function Notary() public {
// constructor
}
function addDocHash (bytes32 hash) public {
Record memory newRecord = Record(now, block.number);
docHashes[hash] = newRecord;
}
function findDocHash (bytes32 hash) public constant returns(uint, uint) {
return (docHashes[hash].mineTime, docHashes[hash].blockNumber);
}
}

This is all the Solidity code we require for this application. First of all, we use a pragma expression to specify a minimum compiler version (0.4.4) for this code. The code should compile with anything below version 0.5.0.

Next we use declare the Notary contract. Inside the contract we declare a struct datatype, instances of which will be used to store records of the documents we wish to fingerprint. The struct has two entries of type uint, which is an unsigned 256-bit integer. The fields are a timestamp and the block number at which the transaction supplying the hash value of our files is mined.

In the next line we create the following state variable:

mapping (bytes32 => Record) private docHashes;

This will actually be stored on the blockchain and maps 32-byte values, our SHA-256 hashes, to an instance of our previously declared Record struct. A mapping is essentially a hash table, which you may know from other programming languages. The SHA-256 hash will actually be used as the key to find the corresponding record.

The next piece of code is the constructor of our contract. Constructors are called at contract deployment and serve for initialisation tasks. As our contract is very simple we do not need to do anything special here, so we just leave the constructor empty.

Next, we declare the function that is used to store records on the blockchain:

function addDocHash (bytes32 hash) public {
Record memory newRecord = Record(now, block.number);
docHashes[hash] = newRecord;
}

Note that the function takes a hash value as an argument. We could send the actual file content to the contract and calculate the hash value in the contract code, but this would be a poorer design decision for a number of reasons: First of all, contract execution has an associated cost in gas, which is translated to Ether via the gas price, and is charged to the caller of the transaction. The more work to be done, the costlier the transaction will be. Secondly, users should not have to send their files across the network. There is no reason for user data to leave the owner’s machine, as SHA-256 hashes can be calculated locally. Finally, independent of transaction fees, sending large files over the network is just much more inefficient than sending the SHA-256 hash. As can be seen above, the addDocHash function is declared public, so that it can be accessed externally. The memory keyword used in the local Record declaration means that it won’t be saved to storage. Storing it is eventually achieved by saving the data to the docHashes mapping, which is an in-storage state variable.

When the addDocHash function is called in a transaction, the same transaction is executed by all nodes trying to include the transaction in a new block. The winning miner node that eventually seals the block sets the correct block number and mine time. Note, that whilst the timestamp can be manipulated by the miner in theory, it still needs to be larger than the previous block’s and lower than the next block’s timestamp. Therefore, any discrepancies will be minimal.

Having provided a way to save a hash, we now need a way to verify wether a hash exists on the blockchain and retrieve the corresponding record:

function findDocHash (bytes32 hash) public constant returns(uint, uint) {
return (docHashes[hash].mineTime, docHashes[hash].blockNumber);
}

This function simply returns the corresponding mine time and block number for a given hash as a tuple (Solidity can have multiple return values). If a hash is not in the mapping the code will return (0,0). We could in fact add a test wether the hash exists and throw an exception, but as (0,0) is a pretty clear indicator for failure to find a hash, we can deal with this off-chain in the client code. A good rule of thumb is to only include code that benefits from the blockchain’s properties in your contract. The rest is better off in client side code.

One important fact to notice is the constant keyword in the findDocHash function declaration. This indicates that the function does not alter state and can therefore be executed in a call, rather than a transaction. Calls may read state of a local Ethereum node and do not have to be propagated through the network and mined. They therefore do not require any gas and are free to use.

To compile this code with truffle type:

truffle compile

This creates a JSON files in the build directory of our contracts. Feel free to look at Notary.json. We will discuss the content of the file further on this series of articles. For now, we let Truffle handle the file.

Testing the contract

To test our contract we will deploy it onto an in-memory Ethereum blockchain simulator. It would be unwise to directly deploy our contract onto the real network without prior testing. We will use the Ganache tool for testing. Installation of the tool is straightforward. Once executed, Ganache presents the following graphical user interface:

As you can see there are a number of accounts created automatically, each of of which hold plenty of test Ether. You can also see details on the chain’s blocks and transactions, which is useful for testing.

Now we will deploy our contract onto the test blockchain. To do so, we use truffle to first create a migration file for our Notary contract:

truffle create migration Notary

This will create a new Javascript file in the migrations directory with some scaffolding code. Edit this file to contain the following code:

var NotaryContract = artifacts.require("Notary");
module.exports = function(deployer) {
deployer.deploy(NotaryContract);
};

The code tells Truffle to obtain a reference to the Notary contract and deploy it. However, before we can execute this code and proceed with the actual deployment, we have to configure Truffle to use our local test blockchain for deployment.

To do so we need to edit the file truffle.js which is the main configuration file, and add the following content:

module.exports = {
networks: {
development: {
host: "localhost",
port: 7545,
network_id: "*"
}
}
};

This code tells truffle to look for an Ethereum node’s RPC interface on port 7545 on localhost and deploy onto the network we find there, whatever the network id (Ethereum networks are identified by ids, with 1 being the oficial Ethereum main network). Ganache is listening on this port by default. We have also named this deployment configuration development, so that we can add further networks with different names later on.

Now we can deploy the contract by typing:

truffle migrate --network development

It is not actually necessary to explicitly specify the network, as truffle will deploy to the first network on the list. However, it is good practice to do so, in order to avoid mistakes later on. During development we might fix some bugs and redeploy. To do a re-deploy we have to add a reset option:

truffle migrate --network development --reset

Note, that we have automatically deployed the truffle supplied Migrations contract as well. This is used by Truffle for migration tasks and we will leave it alone. You should see the address each contract is assigned.

We now have version of our contract on our local blockchain simulator and can interact with it. There are various ways to test a contract and Truffle actually ships with a sophisticated test framework, but for now we connect to our blockchain using Truffle’s console mode, which provides a Javascript console with the Web3 library and some further Truffle extensions. The Web3 library provides a standard Javascript interface to allow applications to communicate with the blockchain. Type the following to enter console mode and receive a Javascript command prompt:

truffle console

Truffle makes life easy by injecting a Notary object with some important fields, such as the contracts Application Binary Interface (ABI) and it’s a address. These are two details you need to know of any contact you wish to interact with on the blockchain. We can use the injected object to create a reference to our deployed contract:

var notary = Notary.at(Notary.address);

We can now send a hash value of a file to the blockchain. As we have not implemented a client which calculates hash values yet, we can either send any integer number for testing purposes or use openssl or any other tool you have installed locally to generate a SHA-256 hash of a file. Alternatively you can just use the value I use in my example below. To send a hash value to the blockchain we can use the following code in the Truffle console:

notary.addDocHash("0x5abf61c361e5ef91582e70634dfbf2214fbdb6f29c949160b69f27ae947d919d");

Note that we are passing a string datatype as an argument. As long as we format the string correctly with a leading (0x) to indicate a hexadecimal value, the web3 library translates this correctly to our contract’s ABI.

On return, you should be presented with a receipt of your transaction, including a transaction id, some information on the block the transaction has been mined in and the gas used. Note, that in our testing environment the transaction is mined instantly. Using a real Ethereum network things would be considerably slower and testing would be cumbersome.

Let’s now use the findDocHash function to check wether our hash value exists on the blockchain:

notary.findDocHash("0x5abf61c361e5ef91582e70634dfbf2214fbdb6f29c949160b69f27ae947d919d");

The result is an array with two objects of type BigNumber. Web3 uses the BigNumber library, as Javascript is notoriously bad at dealing with large numbers. We could use the library to decode these values properly, but it is easy to see that the first element of the array corresponds to our first return value, the timestamp, and the second element to the block number.

You may try repeating the call with a hash value which we have not saved onto the blockchain to get two zero values as return values.

We have thus shown that our contract works correctly.

Next Steps

Once we have a working contract our next steps could be as follows:

  1. Develop a client application that calculates hash values for provided files and sends them to the blockchain and also allows checking if hashes exist.
  2. Test our client with our test environment.
  3. Deploy the contract on the Ethereum test network, a real blockchain that works with worthless test Ether to allow inexpensive real world testing.
  4. Test our client against the contract deployed on the test network
  5. Deploy our contract on the Ethereum main network.

We will look at these steps in part 2 of this tutorial series.

The source code for this tutorial can be found on GitHub:

stbeyer/docCertTutorial

If you find this tutorial useful, you may consider donating a modest amount:

Ethereum: 0xd9fa3fb148154ca0c70ecb89009df54ae9f9924b

Bitcoin: 1Jk13X9BTcQ2huMy1RS6Dx71oFtMMUmfXc

Litecoin: LcfTyh7xbLgi1gFStEG3xBNpGhmVAXg2Yj

Ethereum Development Guide — Part 1

Developing an Ethereum Document Certification Application

Introduction

Document certification, also known as timestamping or proof of existence, is one of the most obvious use cases for blockchain technology beyond digital currencies. Document certification consists in saving a tamper-proof timestamped fingerprint of a document (or binary file) on the blockchain. This basically serves as proof that the document existed in a certain version at a certain time and can be used to prove integrity of the file. That is, you can prove that a document has not been modified since its certification. Use cases cover registering private contracts, protecting copyright, sealing log files and any other case where file integrity is important.

In this tutorial we will look at how to create an Ethereum contract that allows to store data on the blockchain and read it, by using document certification as an example. To do so, we will create a simple smart contract that saves an SHA-256 hash of a file on the blockchain, together with a timestamp. SHA-256 hashes uniquely identify sets of data by means of a cryptographic hash function. We will not go into detail on hash functions and cryptography here, but you should know that a SHA-256 hash is a 32-byte fingerprint derived from the input data. The reverse operation, i.e. calculating the data from the hash value, is not feasible, so data protection is a welcome side-effect.

Document certification is fairly easy to implement, which means it is ideal for explaining certain concepts and techniques without unnecessary complexity, whilst still being more useful than typical “Hello World” examples.

Prerequisites and Learning outcomes

To follow this tutorial you need some basic understanding of the command line, text editing and a basic understanding of how blockchains work. You should have Node.js installed on your system and know some Javascript. After following this tutorial you will know how to:

  • Write a simple smart contract for the Ethereum blockchain
  • Store and retrieve data on the blockchain
  • Understand the difference between a transaction and a call
  • Deploy and test a smart contract in a local test environment
  • Use basic functionality of a professional Ethereum development framework

Developing the smart contract

We will use the Solidity programming language to write our contract and the Truffle framework to ease development.

Install Truffle with the following command (the -g option may require root privileges on your system):

npm install -g truffle

Now, we are ready to initialize our smart contract development project. In a new directory type the following:

truffle init

This creates various directories and files. For now we will create a Solidity source file in the contracts directory. We can use truffle to create the file with some scaffolding code for us:

truffle create contract Notary

This creates a file called Notary.sol in the contracts directory. In the same directory there is also a Migrations.sol file. This is a contract used by truffle to aid blockchain deployment. You should leave this file untouched. Let’s edit Notary.sol to contain the following code:

pragma solidity ^0.4.4;
contract Notary {
struct Record {
uint mineTime;
uint blockNumber;
}
mapping (bytes32 => Record) private docHashes;
function Notary() public {
// constructor
}
function addDocHash (bytes32 hash) public {
Record memory newRecord = Record(now, block.number);
docHashes[hash] = newRecord;
}
function findDocHash (bytes32 hash) public constant returns(uint, uint) {
return (docHashes[hash].mineTime, docHashes[hash].blockNumber);
}
}

This is all the Solidity code we require for this application. First of all, we use a pragma expression to specify a minimum compiler version (0.4.4) for this code. The code should compile with anything below version 0.5.0.

Next we use declare the Notary contract. Inside the contract we declare a struct datatype, instances of which will be used to store records of the documents we wish to fingerprint. The struct has two entries of type uint, which is an unsigned 256-bit integer. The fields are a timestamp and the block number at which the transaction supplying the hash value of our files is mined.

In the next line we create the following state variable:

mapping (bytes32 => Record) private docHashes;

This will actually be stored on the blockchain and maps 32-byte values, our SHA-256 hashes, to an instance of our previously declared Record struct. A mapping is essentially a hash table, which you may know from other programming languages. The SHA-256 hash will actually be used as the key to find the corresponding record.

The next piece of code is the constructor of our contract. Constructors are called at contract deployment and serve for initialisation tasks. As our contract is very simple we do not need to do anything special here, so we just leave the constructor empty.

Next, we declare the function that is used to store records on the blockchain:

function addDocHash (bytes32 hash) public {
Record memory newRecord = Record(now, block.number);
docHashes[hash] = newRecord;
}

Note that the function takes a hash value as an argument. We could send the actual file content to the contract and calculate the hash value in the contract code, but this would be a poorer design decision for a number of reasons: First of all, contract execution has an associated cost in gas, which is translated to Ether via the gas price, and is charged to the caller of the transaction. The more work to be done, the costlier the transaction will be. Secondly, users should not have to send their files across the network. There is no reason for user data to leave the owner’s machine, as SHA-256 hashes can be calculated locally. Finally, independent of transaction fees, sending large files over the network is just much more inefficient than sending the SHA-256 hash. As can be seen above, the addDocHash function is declared public, so that it can be accessed externally. The memory keyword used in the local Record declaration means that it won’t be saved to storage. Storing it is eventually achieved by saving the data to the docHashes mapping, which is an in-storage state variable.

When the addDocHash function is called in a transaction, the same transaction is executed by all nodes trying to include the transaction in a new block. The winning miner node that eventually seals the block sets the correct block number and mine time. Note, that whilst the timestamp can be manipulated by the miner in theory, it still needs to be larger than the previous block’s and lower than the next block’s timestamp. Therefore, any discrepancies will be minimal.

Having provided a way to save a hash, we now need a way to verify wether a hash exists on the blockchain and retrieve the corresponding record:

function findDocHash (bytes32 hash) public constant returns(uint, uint) {
return (docHashes[hash].mineTime, docHashes[hash].blockNumber);
}

This function simply returns the corresponding mine time and block number for a given hash as a tuple (Solidity can have multiple return values). If a hash is not in the mapping the code will return (0,0). We could in fact add a test wether the hash exists and throw an exception, but as (0,0) is a pretty clear indicator for failure to find a hash, we can deal with this off-chain in the client code. A good rule of thumb is to only include code that benefits from the blockchain’s properties in your contract. The rest is better off in client side code.

One important fact to notice is the constant keyword in the findDocHash function declaration. This indicates that the function does not alter state and can therefore be executed in a call, rather than a transaction. Calls may read state of a local Ethereum node and do not have to be propagated through the network and mined. They therefore do not require any gas and are free to use.

To compile this code with truffle type:

truffle compile

This creates a JSON files in the build directory of our contracts. Feel free to look at Notary.json. We will discuss the content of the file further on this series of articles. For now, we let Truffle handle the file.

Testing the contract

To test our contract we will deploy it onto an in-memory Ethereum blockchain simulator. It would be unwise to directly deploy our contract onto the real network without prior testing. We will use the Ganache tool for testing. Installation of the tool is straightforward. Once executed, Ganache presents the following graphical user interface:

As you can see there are a number of accounts created automatically, each of of which hold plenty of test Ether. You can also see details on the chain’s blocks and transactions, which is useful for testing.

Now we will deploy our contract onto the test blockchain. To do so, we use truffle to first create a migration file for our Notary contract:

truffle create migration Notary

This will create a new Javascript file in the migrations directory with some scaffolding code. Edit this file to contain the following code:

var NotaryContract = artifacts.require("Notary");
module.exports = function(deployer) {
deployer.deploy(NotaryContract);
};

The code tells Truffle to obtain a reference to the Notary contract and deploy it. However, before we can execute this code and proceed with the actual deployment, we have to configure Truffle to use our local test blockchain for deployment.

To do so we need to edit the file truffle.js which is the main configuration file, and add the following content:

module.exports = {
networks: {
development: {
host: "localhost",
port: 7545,
network_id: "*"
}
}
};

This code tells truffle to look for an Ethereum node’s RPC interface on port 7545 on localhost and deploy onto the network we find there, whatever the network id (Ethereum networks are identified by ids, with 1 being the oficial Ethereum main network). Ganache is listening on this port by default. We have also named this deployment configuration development, so that we can add further networks with different names later on.

Now we can deploy the contract by typing:

truffle migrate --network development

It is not actually necessary to explicitly specify the network, as truffle will deploy to the first network on the list. However, it is good practice to do so, in order to avoid mistakes later on. During development we might fix some bugs and redeploy. To do a re-deploy we have to add a reset option:

truffle migrate --network development --reset

Note, that we have automatically deployed the truffle supplied Migrations contract as well. This is used by Truffle for migration tasks and we will leave it alone. You should see the address each contract is assigned.

We now have version of our contract on our local blockchain simulator and can interact with it. There are various ways to test a contract and Truffle actually ships with a sophisticated test framework, but for now we connect to our blockchain using Truffle’s console mode, which provides a Javascript console with the Web3 library and some further Truffle extensions. The Web3 library provides a standard Javascript interface to allow applications to communicate with the blockchain. Type the following to enter console mode and receive a Javascript command prompt:

truffle console

Truffle makes life easy by injecting a Notary object with some important fields, such as the contracts Application Binary Interface (ABI) and it’s a address. These are two details you need to know of any contact you wish to interact with on the blockchain. We can use the injected object to create a reference to our deployed contract:

var notary = Notary.at(Notary.address);

We can now send a hash value of a file to the blockchain. As we have not implemented a client which calculates hash values yet, we can either send any integer number for testing purposes or use openssl or any other tool you have installed locally to generate a SHA-256 hash of a file. Alternatively you can just use the value I use in my example below. To send a hash value to the blockchain we can use the following code in the Truffle console:

notary.addDocHash("0x5abf61c361e5ef91582e70634dfbf2214fbdb6f29c949160b69f27ae947d919d");

Note that we are passing a string datatype as an argument. As long as we format the string correctly with a leading (0x) to indicate a hexadecimal value, the web3 library translates this correctly to our contract’s ABI.

On return, you should be presented with a receipt of your transaction, including a transaction id, some information on the block the transaction has been mined in and the gas used. Note, that in our testing environment the transaction is mined instantly. Using a real Ethereum network things would be considerably slower and testing would be cumbersome.

Let’s now use the findDocHash function to check wether our hash value exists on the blockchain:

notary.findDocHash("0x5abf61c361e5ef91582e70634dfbf2214fbdb6f29c949160b69f27ae947d919d");

The result is an array with two objects of type BigNumber. Web3 uses the BigNumber library, as Javascript is notoriously bad at dealing with large numbers. We could use the library to decode these values properly, but it is easy to see that the first element of the array corresponds to our first return value, the timestamp, and the second element to the block number.

You may try repeating the call with a hash value which we have not saved onto the blockchain to get two zero values as return values.

We have thus shown that our contract works correctly.

Next Steps

Once we have a working contract our next steps could be as follows:

  1. Develop a client application that calculates hash values for provided files and sends them to the blockchain and also allows checking if hashes exist.
  2. Test our client with our test environment.
  3. Deploy the contract on the Ethereum test network, a real blockchain that works with worthless test Ether to allow inexpensive real world testing.
  4. Test our client against the contract deployed on the test network
  5. Deploy our contract on the Ethereum main network.

We will look at these steps in part 2 of this tutorial series.

The source code for this tutorial can be found on GitHub:

stbeyer/docCertTutorial

If you find this tutorial useful, you may consider donating a modest amount:

Ethereum: 0xd9fa3fb148154ca0c70ecb89009df54ae9f9924b

Bitcoin: 1Jk13X9BTcQ2huMy1RS6Dx71oFtMMUmfXc

Litecoin: LcfTyh7xbLgi1gFStEG3xBNpGhmVAXg2Yj

Fixing Smart Contracts: Here comes Blockchain Contracts

Among many innovations spurred by Bitcoins which includes distributed ledgers, the idea of decentralized trust, first practical implementation of virtually unhackable datastores, demonstration of assets with non-tangible interactive valuations, seeding the notions of Initial Coin Offers, introducing first mass scale system with completely transparent transactions, the one innovation that stands out for me in ability to do human mediated and enforced contracts purely on blockchains. I will use the term Blockchain Contracts for them.

Blockchain Contracts are different from Smart Contracts. Smart contracts are purely algorithm driven. They are machines. But machines have no brains. They are hackable. As Kurt Godel postulated in 1931 with his two incompleteness theorem, in a formal system of purely logical rules, there will always be provable mistakes. If the logical rules are rigidly enforced, some wrong ones will be deemed compliant to rules when they are not. If the rules are loosely enforced, then some genuine cases will classified non-compliant to rules. In other words, if a purely logical system of rules were created to identify whether someone is guilty or innocent, the necessary price of finding everyone guilty is some innocent people will be classified as guilty. And if the rule system were loose enough to ensure that no innocent is classified as guilty, then the price is some guilty will necessarily go scot free. You can only have one of those, but not both.

The implication of Godel’s incompleteness theorem in the world of smart contract is a pure machine based financial algorithm will never be 100% accurate. It will either dole out financial benefits to those who do not deserve. Or it will deny financial benefit to some of those who do deserve. In other words, a pure machine based system will definitely have fraud cases. If all frauds were to be eliminated, then some genuine beneficiaries will have to be denied service, which is an unacceptable condition. So accepting frauds is the only possible compromise, and frauds cannot be eliminated in pure smart contract based financial system.

Satoshi Nakamoto, the creator of Bitcoins realized it. He defined the parameters of the system such that the bar to insert a fraud transaction in Bitcoin ledger system is extremely high. To be able to insert a fraud transaction in Bitcoin Blockchain, the fraudster needs to have computing power higher than all supercomputers of world put together. And he altered the incentive system in Bitcoin in such a way the a fraudster will find it more profitable to co-operate with Bitcoin system. If he that that amount of computing power, and gain more by simply mining those Bitcoins. He also ensured that Bitcoin programming language, its scripting system is not Turing complete. A Turing complete programming language gives all logical powers to the programmer such that the programmer can do anything a logical system of rules can achieve. Ethereum, the most popular smart contracts platform on the other hand, permitted the programmers to have a Turing complete programming language. Not without surprise, smart contract writers are up against the wall of Godel postulates, and as a result Ethereum world is replete with hacking incidents at blockchain level itself.

So are we chasing an impossible dream here ? Can we never have a secure system that also services all its beneficiaries accurately.

The answer is breaking the confines of a pure rules based logical system. If we were to inject a little bit of illogical behaviour where the output is different for same input cases at different times, then we can cut down the losses compared to a pure logical system. And the best source of illogical behaviour is human judgement. If a smart contract were to be dependent on some human judgement for some actions, then at a price of little lower efficiency, we can have a system that rejects false cases much better than a pure machine based system. Of course, the system is now vulnerable to errors of human judgement, but as evidence from algorithmic trading in financial systems have demonstrated, human trading systems have performed much better than pure machine based trading systems in general. The best investors in the world are all human, with human instincts and human judgements. No machine has come close to beat Warren Buffet investment track record over long consistent period of times.

Thats what a Blockchain Contract is. Its a smart contract with human judgement baked in. If the contract designer is smart, he will insert human elements at most critical points so that the contract gets the full benefits of machine speeds as well as fraud resistance of human judgement. If the contract designer is sloppy by overdoing human factor, then the contract will be slow, loose the benefits of automatic execution, and will also have more frauds.

A well designed Blockchain Contract will perform much better than a well designed smart contract. It will create more trust. It will create more wealth.

What do you need for successful ICO?

Initial Coin Offering (ICO) is a hot subject right now, but what do you need to run one successfully?

  1. Idea.
    Without idea there is no business and no ICO. You need to have realistic business idea for your ICO start-up.
  2. Team.
    You can’t do everything yourself, so you need motivated people to help you around. Ideally there will be a person to take care of every aspect of your business, so that all that would be left for you is to manage them.
  3. Smart Contract.
    This is very obvious, but yes, to run an ICO you need a Smart Contract.
  4. White Paper.
    White Paper is a presentation about your company and idea, and it’s crucial for the project. Based on the white paper potential investors will decide if they want to invest in you or not.
  5. Money.
    It is clear that you need money, this is why you are having an ICO fundraising in the first place, but in order to succeed at your fundraising you need to have some money of your own that you will spend on developing smart contract and promoting your ICO.
  6. Advisors.
    While you may have a team of experts, it’s always nice and wise to have few advisors on boards. These experts will help you issues you may run into when diving in the Blockchain world.

Good luck with your ICO and if you need any help feel free to contact me!

What do you need for successful ICO?

Initial Coin Offering (ICO) is a hot subject right now, but what do you need to run one successfully?

  1. Idea.
    Without idea there is no business and no ICO. You need to have realistic business idea for your ICO start-up.
  2. Team.
    You can’t do everything yourself, so you need motivated people to help you around. Ideally there will be a person to take care of every aspect of your business, so that all that would be left for you is to manage them.
  3. Smart Contract.
    This is very obvious, but yes, to run an ICO you need a Smart Contract.
  4. White Paper.
    White Paper is a presentation about your company and idea, and it’s crucial for the project. Based on the white paper potential investors will decide if they want to invest in you or not.
  5. Money.
    It is clear that you need money, this is why you are having an ICO fundraising in the first place, but in order to succeed at your fundraising you need to have some money of your own that you will spend on developing smart contract and promoting your ICO.
  6. Advisors.
    While you may have a team of experts, it’s always nice and wise to have few advisors on boards. These experts will help you issues you may run into when diving in the Blockchain world.

Good luck with your ICO and if you need any help feel free to contact me!

I think you missed a few things in this post… I think it is important to understand a few things…

I think you missed a few things in this post… I think it is important to understand a few things about BlockChains;

The Proof of Work model might not be sustainable as a concept (due to energy consumption for compute), Proof of Stake models might be much more viable for this purpose.

Biggest drawback with the BitCoin blockchain is that it only has one application; BitCoins. It is also inheritable unusable for payments, it is not and never was a currency. It is a digital commodity.

The core concept of a Blockchain (cryptographically sealed sequential blocks of transactions) is not new actually. If you use the Internet you use SSL/TLS (HTTPS) which relies on a fairly old and well established model for securing trust in a chain of cryptographicly secured identities — where I do not need to know or have direct trust with the intermediate actors. This requires trust with a root authority, the Etheruem and Bitcoin blockchain requirest trust of the [root] of the chain (although not specifically). Not 100 % the same, and there are additional opportunities to expand use cases with the distributed trust/consensus model of what we call “Blockhain” right now. But conceptually these are similair and what we call Blockchains today are derived from this PKI model.

There are also Blockhain models that are widely used to secure authority and attribution in netwokring infrastructure etc such as GuardTime. They did not even call what they do a Blockchain initially (it was not on everybody’s lips a few years ago — but it is nothing but a commercial Blockchain with massive applications).



I think you missed a few things in this post… I think it is important to understand a few things… was originally published in nicolaiwadstrom on Medium, where people are continuing the conversation by highlighting and responding to this story.

I think you missed a few things in this post… I think it is important to understand a few things…

I think you missed a few things in this post… I think it is important to understand a few things about BlockChains;

The Proof of Work model might not be sustainable as a concept (due to energy consumption for compute), Proof of Stake models might be much more viable for this purpose.

Biggest drawback with the BitCoin blockchain is that it only has one application; BitCoins. It is also inheritable unusable for payments, it is not and never was a currency. It is a digital commodity.

The core concept of a Blockchain (cryptographically sealed sequential blocks of transactions) is not new actually. If you use the Internet you use SSL/TLS (HTTPS) which relies on a fairly old and well established model for securing trust in a chain of cryptographicly secured identities — where I do not need to know or have direct trust with the intermediate actors. This requires trust with a root authority, the Etheruem and Bitcoin blockchain requirest trust of the [root] of the chain (although not specifically). Not 100 % the same, and there are additional opportunities to expand use cases with the distributed trust/consensus model of what we call “Blockhain” right now. But conceptually these are similair and what we call Blockchains today are derived from this PKI model.

There are also Blockhain models that are widely used to secure authority and attribution in netwokring infrastructure etc such as GuardTime. They did not even call what they do a Blockchain initially (it was not on everybody’s lips a few years ago — but it is nothing but a commercial Blockchain with massive applications).



I think you missed a few things in this post… I think it is important to understand a few things… was originally published in nicolaiwadstrom on Medium, where people are continuing the conversation by highlighting and responding to this story.

The savedroid Smart Contract

Miguel and Sebastian are our smart contract professionals.
They will give you an overview what they do and how the savedroid smart contract will look like.

💪Give power to the people and join the revolution now! 🚀

____________________________

⚡️⚡️⚡️ Revolution is coming — JOIN IT : Don’t miss out to SIGN UP for our #ICO newsletter!
👉 https://ico.savedroid.com/
We will keep you updated with exciting #cryptocurrency #news ⚡️⚡️⚡️#savedroidICO #TokenSale #ethereum #bitcoin

►MORE INFORMATION: https://ico.savedroid.com
►BECOME A FACEBOOK FAN: https://www.facebook.com/savedroid/
►TWITTER: https://twitter.com/savedroidAG
►INSTAGRAM: https://www.instagram.com/savedroid
►REDDIT: https://www.reddit.com/r/savedroid_ico/
►TELEGRAM: https://t.me/savedroidico
►BITCOINTALK: https://bitcointalk.org/index.php?topic=2578161.new#new

____________________________

Produced by: Lydia Witzmann

Zap Tech Development Update — December 2017

Updates on the ZAP CLI, Chrome Extension, and Mobile App

The Zap Project team has been hard at work developing the tech and interfaces that will build the Zap Store smart contract oracle market. In this update, which will likely be the last one before the new year, we will outline our progress on the Zap CLI npm package and the upcoming Zap Chrome extension and Mobile apps.

ZAP CLI

The Zap CLI (command line interface) is being developed as a package for npm (node package manager). Soon, smart contract developers will be able to get started with creating Zap oracles by simply typing “npm install zapcli” into their terminal.

The CLI will allow developers and data providers to register their oracles and Websocket-based streaming data feeds on the Zap Store. This functionality also operates as the backend commands for the Chrome extension and mobile app interfaces for the Zap Store.

A functional npm package for the Zap CLI is expected to be released Q1 2018. You can monitor progress on the Zap CLI on our GitHub page in the public FeedArbitration repository. As we progress further, we’ll have a more specific date.

Zap Chrome Extension

Even though the Zap Store will be web-based, we are developing a Google Chrome extension that will enable users to easily monitor their data feed subscriptions and the oracles they have bonded ZAP tokens to.

If you recall, the Zap platform has its own economic-incentive-based oracle curation system. The Chrome extension, pictured to the left, will be an “always available” one-click-away summary of how the Zap tokens that you have bonded are doing.

Although the Chrome extension is currently in a private repository on our GitHub, as it progresses further we will make it public and its release is also scheduled for Q1 2018.

Zap Mobile App

We are also working on a mobile application for the Zap Store. The first version will be released on Android but an iOS version will follow in its footsteps.

The Zap mobile app will allow users to browse available data feeds/oracles. The app will also have a built-in Ethereum/Zap Token wallet, and if the wallet is funded, users will also be able to subscribe to data feeds and bond Zap tokens to oracles right inside the app. We are very excited about this one!

Just like the Chrome extension, the Android app is currently living inside a private repository on our GitHub, but we will be making all of the code public as soon as it’s ready for release. Expect to be Zapping on the go in Q1 2018. We are very excited for the mobile app & wallet!

We have a lot in store for Zap coming in Q1 2018. This post serves as an overview of what’s in the pipeline. The next update, which will be in January, will provide specific details about the features and release dates for everything we have been working on. Our mission to make it simple and easy to connect smart contracts with external data is well on its way!

Happy Holidays, Zappers!



Zap Tech Development Update — December 2017 was originally published in ZapProject on Medium, where people are continuing the conversation by highlighting and responding to this story.

Zap Tech Development Update — December 2017

Updates on the ZAP CLI, Chrome Extension, and Mobile App

The Zap Project team has been hard at work developing the tech and interfaces that will build the Zap Store smart contract oracle market. In this update, which will likely be the last one before the new year, we will outline our progress on the Zap CLI npm package and the upcoming Zap Chrome extension and Mobile apps.

ZAP CLI

The Zap CLI (command line interface) is being developed as a package for npm (node package manager). Soon, smart contract developers will be able to get started with creating Zap oracles by simply typing “npm install zapcli” into their terminal.

The CLI will allow developers and data providers to register their oracles and Websocket-based streaming data feeds on the Zap Store. This functionality also operates as the backend commands for the Chrome extension and mobile app interfaces for the Zap Store.

A functional npm package for the Zap CLI is expected to be released Q1 2018. You can monitor progress on the Zap CLI on our GitHub page in the public FeedArbitration repository. As we progress further, we’ll have a more specific date.

Zap Chrome Extension

Even though the Zap Store will be web-based, we are developing a Google Chrome extension that will enable users to easily monitor their data feed subscriptions and the oracles they have bonded ZAP tokens to.

If you recall, the Zap platform has its own economic-incentive-based oracle curation system. The Chrome extension, pictured to the left, will be an “always available” one-click-away summary of how the Zap tokens that you have bonded are doing.

Although the Chrome extension is currently in a private repository on our GitHub, as it progresses further we will make it public and its release is also scheduled for Q1 2018.

Zap Mobile App

We are also working on a mobile application for the Zap Store. The first version will be released on Android but an iOS version will follow in its footsteps.

The Zap mobile app will allow users to browse available data feeds/oracles. The app will also have a built-in Ethereum/Zap Token wallet, and if the wallet is funded, users will also be able to subscribe to data feeds and bond Zap tokens to oracles right inside the app. We are very excited about this one!

Just like the Chrome extension, the Android app is currently living inside a private repository on our GitHub, but we will be making all of the code public as soon as it’s ready for release. Expect to be Zapping on the go in Q1 2018. We are very excited for the mobile app & wallet!

We have a lot in store for Zap coming in Q1 2018. This post serves as an overview of what’s in the pipeline. The next update, which will be in January, will provide specific details about the features and release dates for everything we have been working on. Our mission to make it simple and easy to connect smart contracts with external data is well on its way!

Happy Holidays, Zappers!



Zap Tech Development Update — December 2017 was originally published in ZapProject on Medium, where people are continuing the conversation by highlighting and responding to this story.

Writing Smart Contracts in IULIA

People keep asking about the status of our new low-level language IULIA and are often surprised when I tell them that it is already used in the Solidity compiler. Perhaps you have even used IULIA in the past without noticing. The reason is that IULIA shares a lot of code and structure with what was previously called “inline assembly”. For the compiler, the distinction between the two is often not even noticeable.

Since people sometimes like writing smart contracts very close to the metal (or rather close to the ether), I would like to explain how you can use IULIA to write smart contracts directly. Or perhaps almost directly. One component is missing for writing smart contracts in IULIA and that is the ability to reference code from within code. This is needed for the deployment (“constructor”) part of a smart contract. We already have a specification about that, but it is not yet implemented in the Solidity compiler.

Because of that, I will use the inline assembly tools for Solidity so that the compiler will create the necessary wrappers for us. Using IULIA inside of Solidity instead of stand-alone also has the benefit that we can use existing Solidity tools like the remix IDE and debugger.

Since IULIA is designed to compile to different backends including the EVM but also Ethereum-flavoured WebAssembly, it comes with a certain set of built-in functions which are not exactly the EVM opcodes. While these built-in functions are not yet implemented, there is a flavour of IULIA which uses EVM opcodes instead of the built-in functions and is currently used as inline assembly for Solidity and also inside the compiler. Translating these opcodes to fully-fledged IULIA built-ins will be trivial, though.

So what we are doing here is that we are using the syntactic elements of IULIA, remove types and replace the built-in functions by the EVM opcodes (in functional notation).

As an example, we will implement a simple ERC20 token contract. Let us start with the surrounding Solidity code:

interface ERC20 {
function totalSupply() constant returns (uint totalSupply);
function balanceOf(address _owner) constant
returns (uint balance);
function mint(address _addr, uint _value);
function transfer(address _to, uint _value);
}
contract MyToken {
function MyToken() {
assembly {
// init code comes here
}
}
function() payable {
assembly {
// runtime code comes here
}
}
}

This snippet defines the ERC20 token interface (we will use that later to interface with the contract) and a skeleton for our own token. This is the only code we will write in Solidity.

If you want to try it out, paste it into https://remix.ethereum.org, switch to the “run” tab, select MyToken and click “create”. This creates a contract without any interface. We will later implement the ERC20 interface as specified above, although that will not be visible to the compiler. Because of that, we have to nudge remix a little: Click the “clipboard” symbol next to the MyToken contract just created to copy its address into the clipboard. Then paste the address into the input field next to “At address”. Next, select the “ERC20” interface in the drop-down element just above it and click “At address”. Now you should have a new ERC20 instance with buttons for all the functions that are part of the interface. If you click one of these buttons now, the relevant function on MyToken will be called (just that it is not implemented yet).

OK, now on to implementing those functions. First, we have to come up with how we want to use storage.

  • Slot 0: owner / creator
  • Slot 1: total balance (we have to update this all the time)
  • Slot 0x1000 + address: account balances

After having verified that there will be no overlap in storage, we can start with the creation code:

contract MyToken {
function MyToken() {
assembly {
// Store the creator at storage slot zero
sstore(0, caller())
}
}
// ...
}

The IULIA snippet will result in the following stream of opcodes:

CALLER PUSH1 0 SSTORE

This stores the caller/sender/creator in the first storage slot. The functional notation is probably much easier to read, but essentially, all components in such an expression are turned into EVM opcodes by just reading from right to left, ignoring any parenthesis structure. The main thing the compiler does for you is checking that the number of arguments (and later their types) matches the parameters.

The next this we will do is implement an accidental Ether transfer to our token:

contract MyToken {
function MyToken() {
// ...
}
function () payable {
assembly {
// Protection against sending Ether
if gt(callvalue(), 0) { revert(0, 0) }
      // ...
}
}
}

If-statements take a single expression as condition and if it evaluates to non-zero (with introduction of types, it will check against true/false), the body is executed and skipped otherwise. This snippet reverts the call if it contains a nonzero Ether transfer.

After that, we have to read the calldata and decide which function is to be called. This is called a function dispatcher. IULIA has a convenient switch statement for that purpose (I will omit the Solidity code surrounding the IULIA code from now on):

// Protection against sending Ether
if gt(callvalue(), 0) { revert(0, 0) }
// Dispatcher
switch selector()
case 0x70a08231 /* "balanceOf(address)" */ {
returnUint(balanceOf(decodeAsAddress(0)))
}
case 0x18160ddd /* "totalSupply()" */ {
returnUint(totalSupply())
}
case 0xa9059cbb /* "transfer(address,uint256)" */ {
transfer(decodeAsAddress(0), decodeAsUint(1))
}
case 0x40c10f19 /* "mint(address,uint256)" */ {
mint(decodeAsAddress(0), decodeAsUint(1))
}
default {
revert(0, 0)
}

So far, so boring. But actually not: What you might have noticed is that this code uses identifiers which are not EVM opcodes, but their syntax is exactly the same. This is also why we can talk about IULIA and Solidity inline assembly more or less interchangeably: The core language allows the user to define functions (more on that below), but there is not a single built-in language, not even the EVM opcodes. Then there is the actual IULIA flavour that defines some built-in functions and the Solidity inline assembly that uses EVM opcodes as built-in functions. From a semantics standpoint, it does not matter where and how the function is defined, only its semantics matter. Because of that you can have the same code compiling to different backends, have the same optimizer routines, the same simulator and only the way these built-in functions are in the end defined in the target machine is different.

You might have noticed the functions called decodeAsAddress, decodeAsUint and returnUint. These handle how calldata is decoded and encodde and we will take a look at them next. By the way, it does not matter whether you first define a function and use it later or define it after it is used, it only needs to be in scope (i.e. not inside a pair of curly braces in a deeper nesting layer).

function selector() -> s {
s := div(calldataload(0),
0x100000000000000000000000000000000000000000000000000000000)
}
function decodeAsAddress(offset) -> v {
v := decodeAsUint(offset)
if iszero(iszero(and(v,
not(0xffffffffffffffffffffffffffffffffffffffff)))) {
revert(0, 0)
}
}
function decodeAsUint(offset) -> v {
v := calldataload(add(4, mul(offset, 0x20)))
}

This snippet shows the first real difference between LLL and IULIA: It is possible to define functions and (stack) variables. LLL only knows macros and it is possible to use these macros to define memory variables and things that look similar to functions. Another difference between LLL and IULIA is where the parentheses are placed, but that is just a matter of taste.

The function selector() returns the first four bytes of the calldata, properly right-aligned to ease comparisons. The other two decode values of type address and uint256, respectively where the correct value range is checked for the former. In both cases, the argument is the index of the parameter in the ABI starting with zero. For both functions, the return variable is called v and assigned in the first line.

Function definitions and calls are an abstract thing in IULIA and they will be mapped to proper functions for WebAssembly. Since the EVM does not have functions, they have to be emulated with jumps, where the return PC and the arguments and return values are placed on the stack. But don’t worry, the compiler will do that behind the scenes and the translation is actually very simple.

Note that (internal) function calls in the EVM are rather cheap. The only reason they might be avoided is because they are called with certain arguments where further optimization might be possible for these specific arguments. If you take a look at how decodeAsAddress is used in the balanceOf part of the dispatcher above, you notice an opportunity of optimisation:

case 0x70a08231 /* "balanceOf(address)" */ {
returnUint(balanceOf(decodeAsAddress(0)))
}

Since it is called with 0 as argument, which is forwarded to decodeAsUint, which in turn performs

v := calldataload(add(4, mul(offset, 0x20))

we see that a mere

calldataload(4)

would do the whole trick.

Exactly because of this reason, we are currently working on an optimizing compiler for IULIA that can reduce such cases to much better performing code. Every single stage of the optimizer is easy to understand and can also emit intermediate IULIA code in readable text representation. This makes it possible to even verify the optimized code after the compiler did its job.

The other benefit of such an optimizing compiler is that you can write modular code. We could have just used

returnUint(balanceOf(calldataload(4))

but this would have removed the value range check and would also be much more error-prone and harder to maintain. What happens if we want to add another parameter, for example? We would have to re-calculate the proper position in the calldata ourselves all the time.

Ok, let us continue with other helper functions. We still need the value encoder:

function returnUint(v) {
mstore(0, v)
return(0, 0x20)
}

This is where we first use this magical thing called “memory”: It is a semi-volatile, byte-addressed storage. The IULIA compiler will not use it for internals, but knows how to handle it, meaning that concurrent reads and writes will work correctly even after the optimizer changed the code.

Now let us add some functions to handle the internal logic of the token:

function mint(account, amount) {
if iszero(calledByOwner()) { revert(0, 0) }
mintTokens(amount)
addToBalance(account, amount)
}
function transfer(to, amount) {
deductFromBalance(caller(), amount)
addToBalance(to, amount)
}

This basically only calls helper functions. The mint function reverts the call if it is not called by the owner and the transfer function removes an amount from one account and adds it to another account.

function owner() -> o {
o := sload(0)
}
function totalSupply() -> supply {
supply := sload(1)
}

Remember that we said that we store the owner in the first slot and the total supply in the second? This is where this convention is used. These two functions are of course also candidates for inlining.

function mintTokens(amount) {
sstore(1, safeAdd(totalSupply(), amount))
}
function accountToStorageOffset(account) -> offset {
offset := add(0x1000, account)
}
function balanceOf(account) -> bal {
bal := sload(accountToStorageOffset(account))
}
function addToBalance(account, amount) {
let offset := accountToStorageOffset(account)
sstore(offset, safeAdd(sload(offset), amount))
}
function deductFromBalance(account, amount) {
let offset := accountToStorageOffset(account)
let bal := sload(offset)
if lt(bal, amount) { revert(0, 0) }
sstore(offset, sub(bal, amount))
}

The only two functions that are missing now are safeAdd and calledByOwner which are defined as follows:

function safeAdd(a, b) -> r {
r := add(a, b)
if or(lt(r, a), lt(r, b)) { revert(0, 0) }
}
function calledByOwner() -> cbo {
cbo := eq(owner(), caller())
}

The safeAdd function reverts in case of an overflow as a side-effect of its evaluation.

The full contract can be found below, please try it out in remix with the method explained in the beginning.

I hope you enjoyed this tour of IULIA and I also hope that you find it simple and flexible enough at the same time, perhaps not for implementing full smart contract but at least for nice and readable helper functions. I am open for any suggestions, comments and ideas.

By the way, there is a single syntactical element we did not cover, and this is the for-loop. In total, there are only the following 9 elements:

  • literal
  • function call (including built-ins and opcodes)
  • function definition
  • variable declaration (can have multiple variables)
  • variable assignment (can have multiple variables)
  • if statement
  • switch statement
  • for statement
  • statement block

Of these, only the first two can make up expressions.

We are developing an open public permissioned blockchain platform for managing IP rights in music…

We are developing an open public permissioned blockchain platform for managing IP rights in music and ICO platform for musicians and authors

It allows artists to tokenize their tracks, sell music tokens to fans and investors, grant commercial licenses for their music via integrated licensing marketplace and automatically receive royalties, distributed among all holders of track tokens via smart-contracts.

Users of the platform can invest in music and become co-owners of tracks by purchasing track tokens, thus being entitled to receive a share of all royalties from track licensing and to participate in track governance by voting with their track tokens.

All of the transactions in the system are made in Musereum tokens — ETM — that will be available for purchasing at selected exchanges, via fiat gateway from our website or directly from us during the token sale.

Artists and other platform users will be able to get necessary services from third-party providers (rights-clearing, promotion, video production, etc.) that can be paid for with ETM.

In order to gain public recognition, as well as to attract artists to our platform, a streaming solution — Soundchain — will enable private users to stream music from the platform free of charge, while every time the music is listened to, holders of track tokens will receive remuneration in ETM from the platform.
Our project will operate on a five-sided market, uniting artists, investors, service providers, business users and listeners in one ecosystem.

Why are we doing this?

We can help music industry overcome several major problems.

It is difficult to find information on who owns what — and that makes it harder to use music without infringing someone?s copyright.

Our blockchain being a unified database with the immutable history of all transactions will provide automatically updated information on the attribution of rights.

Transactions of all kinds (money, rights, licenses, etc.) within the industry are rarely transparent — and that creates incentive for fraudulent behaviour.

A blockchain solution makes it possible to make all of the transactions transparent and verifiable — and that makes fraudulent behaviour unreasonable.

Lots of interconnected intermediaries with complex relations between them makes it hard for rights holders to manage and control their IP.

Use of smart-contracts and automation eliminates some of the links in the value while providing a unified and versatile tool for rights holders to

Since the structure is complex and obscure, a lot of value is lost — undistributed royalties end up in black boxes, uncleared rights can be neither assigned not licensed.

With the databases of the granted licenses and of the rights holders entitled to royalties from these licenses, distributing royalties and clearing rights will become a routine task.

Complicated value chains make monetizing music hard, because distribution of royalties can take years — so those who are able to pay advances obtain power over artists.

Smart-contracts automatically and instantly distributes royalties among all the token holders, eliminating the monetization lag inherent in the current system.

Furthermore, the crowdinvesting option enables artists to raise funds by sharing their rights with fans and investors — similar to record label deals, but on artist?s conditions.

The market power of the majors make for an oligopolic market, where individual artists are forced to enter into highly restraining deals in order to get paid and be promoted.

By creating a marketplace for service providers accepting ETM tokens, we enable artists to directly request only the services they need — be it promotion, video production or managerial advice — and stay independent from majors until they make a free and informed choice to ask for a specific service.

Most of the players in the industry utilize ancient approaches to every aspect of the business — endless approvals and tons of paperwork make negotiations lengthy and expensive.

Although the structure of relations may remain as complex as participants choose it to be, traceable transactions and unified voting mechanics facilitate negotiations among network participants and provides for easier governance experience.

Thus we believe that our project can greatly increase efficiency for most music industry participants, re-enabling competition in the music market and, as a side effect, creating secondary market for IP rights.

How does the system operate?

On the technical side we have a separate blockchain based on Ethereum that utilize a Proof-of-Authority consensus mechanism similar to that implemented by Oracles.org. We use technology developed by Parity and by Oracles Network, as well as our own developments.

Two types of tokens exist within the system — the main token, ETM, that is used as an internal currency for all of the transactions within the system, and track tokens that represent shares in IP rights for a specific track.

Track tokens will be generated for each track uploaded to the platform and will be distributed among rights holders according to the metadata provided by the uploader. These tokens can be further distributed by the rights holders, who will thereby assign a proportional share of the IP rights belonging to them to the new token holder.

A token holder or a group of token holders that own 100% of tokens for a specific track constitute a DAL — a decentralized autonomous label. All of the royalties paid through the system are automatically distributed among DAL members according to the number of track tokens they hold at the time the royalty is being paid. If a member of a DAL license the music through traditional channels and the royalties are paid in fiat money, he is legally obliged to transmit a share of the royalty proportional to a share of the track tokens held by the other members of the DAL to the bank account of the Musereum operating company, that will use this money to buy ETM tokens and will distribute them among all of the other holders of track tokens. Members of the DAL can vote for specific use of the track and possible licensing terms via the Voting Dapp with the number of votes proportional to the number of tokens they hold.

ETM token will be used as the main internal currency — to buy music tokens and invest in music ICOs, to pay for licenses at the licensing marketplace and to pay industry professionals for the services they render.

A fixed amount of 250,000,000 ETM tokens is generated with the launch of the platform, and additional 25,000,000 ETM will be generated every year. ETM tokens will be initially sold to the public during the token sale, and will be traded at selected cryptocurrency exchanges after that. A fiat gateway will be introduced later for the network participants (corporations mainly) who are unwilling to deal with the crypto stuff.

How to find out more about the project?

If you are interested in the Musereum project, please visit our website, join our Telegram community and Q&A chat, subscribe to our Twitter and Facebook.

Feel free to read our White Paper and FAQ and stay tuned for the further news!

We are developing an open public permissioned blockchain platform for managing IP rights in music…

We are developing an open public permissioned blockchain platform for managing IP rights in music and ICO platform for musicians and authors

It allows artists to tokenize their tracks, sell music tokens to fans and investors, grant commercial licenses for their music via integrated licensing marketplace and automatically receive royalties, distributed among all holders of track tokens via smart-contracts.

Users of the platform can invest in music and become co-owners of tracks by purchasing track tokens, thus being entitled to receive a share of all royalties from track licensing and to participate in track governance by voting with their track tokens.

All of the transactions in the system are made in Musereum tokens — ETM — that will be available for purchasing at selected exchanges, via fiat gateway from our website or directly from us during the token sale.

Artists and other platform users will be able to get necessary services from third-party providers (rights-clearing, promotion, video production, etc.) that can be paid for with ETM.

In order to gain public recognition, as well as to attract artists to our platform, a streaming solution — Soundchain — will enable private users to stream music from the platform free of charge, while every time the music is listened to, holders of track tokens will receive remuneration in ETM from the platform.
Our project will operate on a five-sided market, uniting artists, investors, service providers, business users and listeners in one ecosystem.

Why are we doing this?

We can help music industry overcome several major problems.

It is difficult to find information on who owns what — and that makes it harder to use music without infringing someone?s copyright.

Our blockchain being a unified database with the immutable history of all transactions will provide automatically updated information on the attribution of rights.

Transactions of all kinds (money, rights, licenses, etc.) within the industry are rarely transparent — and that creates incentive for fraudulent behaviour.

A blockchain solution makes it possible to make all of the transactions transparent and verifiable — and that makes fraudulent behaviour unreasonable.

Lots of interconnected intermediaries with complex relations between them makes it hard for rights holders to manage and control their IP.

Use of smart-contracts and automation eliminates some of the links in the value while providing a unified and versatile tool for rights holders to

Since the structure is complex and obscure, a lot of value is lost — undistributed royalties end up in black boxes, uncleared rights can be neither assigned not licensed.

With the databases of the granted licenses and of the rights holders entitled to royalties from these licenses, distributing royalties and clearing rights will become a routine task.

Complicated value chains make monetizing music hard, because distribution of royalties can take years — so those who are able to pay advances obtain power over artists.

Smart-contracts automatically and instantly distributes royalties among all the token holders, eliminating the monetization lag inherent in the current system.

Furthermore, the crowdinvesting option enables artists to raise funds by sharing their rights with fans and investors — similar to record label deals, but on artist?s conditions.

The market power of the majors make for an oligopolic market, where individual artists are forced to enter into highly restraining deals in order to get paid and be promoted.

By creating a marketplace for service providers accepting ETM tokens, we enable artists to directly request only the services they need — be it promotion, video production or managerial advice — and stay independent from majors until they make a free and informed choice to ask for a specific service.

Most of the players in the industry utilize ancient approaches to every aspect of the business — endless approvals and tons of paperwork make negotiations lengthy and expensive.

Although the structure of relations may remain as complex as participants choose it to be, traceable transactions and unified voting mechanics facilitate negotiations among network participants and provides for easier governance experience.

Thus we believe that our project can greatly increase efficiency for most music industry participants, re-enabling competition in the music market and, as a side effect, creating secondary market for IP rights.

How does the system operate?

On the technical side we have a separate blockchain based on Ethereum that utilize a Proof-of-Authority consensus mechanism similar to that implemented by Oracles.org. We use technology developed by Parity and by Oracles Network, as well as our own developments.

Two types of tokens exist within the system — the main token, ETM, that is used as an internal currency for all of the transactions within the system, and track tokens that represent shares in IP rights for a specific track.

Track tokens will be generated for each track uploaded to the platform and will be distributed among rights holders according to the metadata provided by the uploader. These tokens can be further distributed by the rights holders, who will thereby assign a proportional share of the IP rights belonging to them to the new token holder.

A token holder or a group of token holders that own 100% of tokens for a specific track constitute a DAL — a decentralized autonomous label. All of the royalties paid through the system are automatically distributed among DAL members according to the number of track tokens they hold at the time the royalty is being paid. If a member of a DAL license the music through traditional channels and the royalties are paid in fiat money, he is legally obliged to transmit a share of the royalty proportional to a share of the track tokens held by the other members of the DAL to the bank account of the Musereum operating company, that will use this money to buy ETM tokens and will distribute them among all of the other holders of track tokens. Members of the DAL can vote for specific use of the track and possible licensing terms via the Voting Dapp with the number of votes proportional to the number of tokens they hold.

ETM token will be used as the main internal currency — to buy music tokens and invest in music ICOs, to pay for licenses at the licensing marketplace and to pay industry professionals for the services they render.

A fixed amount of 250,000,000 ETM tokens is generated with the launch of the platform, and additional 25,000,000 ETM will be generated every year. ETM tokens will be initially sold to the public during the token sale, and will be traded at selected cryptocurrency exchanges after that. A fiat gateway will be introduced later for the network participants (corporations mainly) who are unwilling to deal with the crypto stuff.

How to find out more about the project?

If you are interested in the Musereum project, please visit our website, join our Telegram community and Q&A chat, subscribe to our Twitter and Facebook.

Feel free to read our White Paper and FAQ and stay tuned for the further news!

INVEST IN RAZOOM! 50% off of ALL RZM TOKENS UNTIL DECEMBER 24 2017

Join the presale @ https://razoom.org/token

The arrival of smart contracts has made our lives a lot easier. Smart contracts help you create legal agreements around the exchange of money, property, shares, goods and services, or anything of value in a transparent, conflict-free way — while avoiding the services of a middleman.

Enter RaZOOM, the latest software to greatly simplify communication between a person and various devices. With a few simple clicks, you can create smart contracts on a convenient and simple graphical interface. The automatic execution of contracts does not require any programming skills from the user and eliminates the probability of human error at the same time.

All transactions are based on blockchain technology that is secure and decentralized.

The smart contract is going to change the traditional way to sign and execute contracts, for every need.

Business transactions and government regulations all work with contracts, and the creation of these often fill our days with long meetings and negotiations.

RaZOOM software is here to facilitate these processes in a novel and engaging way.

Investors receive significant discounts.

● You can exchange RZMP tokens at the TOKEN SALE stage for RZM 1 to 2 tokens. The total growth before TOKEN SALE is 200%.

● Discount for the participant of the first stages of TOKEN SALE

● The start of the sale of tokens on the exchange — 1 2 months

ABOUT US

Company RAZOOM Pte Ltd incorporated in Singapore and is part of the holding: RAZOOM Corp Ltd (Hong Kong), RAZOOM Pte Ltd (Singapore), and Razum Rus (Russia).

The company develops platform for writing, executing, arbitrating, and guaranteeing the standardization of smart contracts with the application of artificial intelligence, usable and simple graphical interface on all types of OS, helper (question-answer system) in natural language, with its own “ecosystem” and messenger.

We use a visual algorithmic programming and modeling language. Powered by distributing device and own blockchain. It has gateways for interacting with other databases. The platform is the operating system and interface for writing smart contracts for any business process (contract) by ordinary Internet users and holders of crypto-currencies.

The platform is used in making automated transactions (wagers, contracts), using encryption based on blocking technology. Automation of smart contracts is based on the operation of predicates of first-order logic that serves to categorize information in the RaZOOM database and is used as the basis for managing the interface for drawing up contracts.

Our platform unites the world of real data, the world of crypto currency and the world of ordinary money (fiat). Smart contracts on our platform can be executed in the environments of digital currencies and fiat money.

TECHNICAL INFORMATION

RAZOOM creates a RAZOOM GUI based on the ETHEREUM fork, which is the next-generation crypto-currency platform.

Smart contracts in Ethereum are presented in the form of classes that can be implemented in different languages, including visual programming and compiled into the bytecode for the Ethereum Virtual Machine (EVM) before being sent to the blockchain. Changing the state of a virtual machine can be written in a full Turing scripting language.

Unlike the scripting language in the bitcoin protocol, EVM supports loops, so the platform uses a mechanism called gas to limit contracts that can take a long time to complete.

Unlike Ethereum Virtual Machine, RAZOOM Core operates with a specialized language of logical predicates connected in RAZOOM GRAF with a complex architecture of linguistic dependence.

While forging the ETHEREUM but retaining the architecture, we restrict the use of the SOLIDITY language. The ban on the use of language is dictated not by security, complexity for ordinary users, not by friendliness. In doing so, we create our visual translator to the language based on the visual interface RAZOOM. The translator is based on a multitude of workflows based on the logic of the DRACON language. It will relieve the user of the difficulties associated with using the language SOLIDITY.

50% off of ALL RZM TOKENS UNTIL DECEMBER 24 2017

Join the presale @ https://razoom.org/token/ and get 50% off RZM tokens!

TOKEN PRESALE (RZMP SALE) October 16 — December 24, 2017

● 10 000 000 RZMP is issued for sale.

● FIX PRICE FOR 1 RZMP = 0.00035 Eth.

● The fee is limited by the total amount of 3500 Eth.

Ethereum contract adress: 0xa0A57FE3E3C5887d35242F4Be93688A2C20C0695 or razoomtoken.eth

**A total of 300,000,000 RZM and 10,000,000 RZMP tokens have been created**

RZMP tokens are changed to RZM 1: 2 tokens (one to two) after the end of TOKEN SALE.

Distribution:

● 75% of RZM tokens — is allocated for TOKEN SALE

● 25% of RZM tokens — remains in the reserve fund of the company and can be used only after the release of the product.

TOKEN SALE. January 15 — March 15 2017

300 000 000 RZM is issued for sale (25% — remains in the reserve fund of the company).

The price of 1 RZM for TOKEN SALE:

● 1 step = 0.00105 Eth. (15.01.2018–21.01.2018)

● 2 step = 0.00118 Eth. (22.01.2018–28.01.2018)

● 3 step = 0.00135 Eth. (29.01.2018–04.02.2018)

● 4 step = 0.00152 Eth. (05.02.2018–11.02.2018)

● 5 step = 0.00169 Eth. (12.02.2018–18.02.2018)

● 6 step = 0.00187 Eth. (19.02.2018–25.02.2018)

● 7 step = 0.00204 Eth. (26.02.2018–04.03.2018)

● 8 step = 0.00221 Eth. (05.03.2018–15.03.2018)

After the end of TOKEN SALE, all unsold tokens will be burnt.

FOR MORE INFORMATION PLEASE VISIT:

WEBSITE (smart contract) — www.razoom.org
WHITE PAPER http://www.razoom.org/docs/RAZOOM_WHITEPAPER_EN.pdf
PRESENTATION — https://youtu.be/vANaIt-VWZ0
About TOKENSALE — http://razoom.org/en/token/

INVEST IN RAZOOM! 50% off of ALL RZM TOKENS UNTIL DECEMBER 24 2017

Join the presale @ https://razoom.org/token

The arrival of smart contracts has made our lives a lot easier. Smart contracts help you create legal agreements around the exchange of money, property, shares, goods and services, or anything of value in a transparent, conflict-free way — while avoiding the services of a middleman.

Enter RaZOOM, the latest software to greatly simplify communication between a person and various devices. With a few simple clicks, you can create smart contracts on a convenient and simple graphical interface. The automatic execution of contracts does not require any programming skills from the user and eliminates the probability of human error at the same time.

All transactions are based on blockchain technology that is secure and decentralized.

The smart contract is going to change the traditional way to sign and execute contracts, for every need.

Business transactions and government regulations all work with contracts, and the creation of these often fill our days with long meetings and negotiations.

RaZOOM software is here to facilitate these processes in a novel and engaging way.

Investors receive significant discounts.

● You can exchange RZMP tokens at the TOKEN SALE stage for RZM 1 to 2 tokens. The total growth before TOKEN SALE is 200%.

● Discount for the participant of the first stages of TOKEN SALE

● The start of the sale of tokens on the exchange — 1 2 months

ABOUT US

Company RAZOOM Pte Ltd incorporated in Singapore and is part of the holding: RAZOOM Corp Ltd (Hong Kong), RAZOOM Pte Ltd (Singapore), and Razum Rus (Russia).

The company develops platform for writing, executing, arbitrating, and guaranteeing the standardization of smart contracts with the application of artificial intelligence, usable and simple graphical interface on all types of OS, helper (question-answer system) in natural language, with its own “ecosystem” and messenger.

We use a visual algorithmic programming and modeling language. Powered by distributing device and own blockchain. It has gateways for interacting with other databases. The platform is the operating system and interface for writing smart contracts for any business process (contract) by ordinary Internet users and holders of crypto-currencies.

The platform is used in making automated transactions (wagers, contracts), using encryption based on blocking technology. Automation of smart contracts is based on the operation of predicates of first-order logic that serves to categorize information in the RaZOOM database and is used as the basis for managing the interface for drawing up contracts.

Our platform unites the world of real data, the world of crypto currency and the world of ordinary money (fiat). Smart contracts on our platform can be executed in the environments of digital currencies and fiat money.

TECHNICAL INFORMATION

RAZOOM creates a RAZOOM GUI based on the ETHEREUM fork, which is the next-generation crypto-currency platform.

Smart contracts in Ethereum are presented in the form of classes that can be implemented in different languages, including visual programming and compiled into the bytecode for the Ethereum Virtual Machine (EVM) before being sent to the blockchain. Changing the state of a virtual machine can be written in a full Turing scripting language.

Unlike the scripting language in the bitcoin protocol, EVM supports loops, so the platform uses a mechanism called gas to limit contracts that can take a long time to complete.

Unlike Ethereum Virtual Machine, RAZOOM Core operates with a specialized language of logical predicates connected in RAZOOM GRAF with a complex architecture of linguistic dependence.

While forging the ETHEREUM but retaining the architecture, we restrict the use of the SOLIDITY language. The ban on the use of language is dictated not by security, complexity for ordinary users, not by friendliness. In doing so, we create our visual translator to the language based on the visual interface RAZOOM. The translator is based on a multitude of workflows based on the logic of the DRACON language. It will relieve the user of the difficulties associated with using the language SOLIDITY.

50% off of ALL RZM TOKENS UNTIL DECEMBER 24 2017

Join the presale @ https://razoom.org/token/ and get 50% off RZM tokens!

TOKEN PRESALE (RZMP SALE) October 16 — December 24, 2017

● 10 000 000 RZMP is issued for sale.

● FIX PRICE FOR 1 RZMP = 0.00035 Eth.

● The fee is limited by the total amount of 3500 Eth.

Ethereum contract adress: 0xa0A57FE3E3C5887d35242F4Be93688A2C20C0695 or razoomtoken.eth

**A total of 300,000,000 RZM and 10,000,000 RZMP tokens have been created**

RZMP tokens are changed to RZM 1: 2 tokens (one to two) after the end of TOKEN SALE.

Distribution:

● 75% of RZM tokens — is allocated for TOKEN SALE

● 25% of RZM tokens — remains in the reserve fund of the company and can be used only after the release of the product.

TOKEN SALE. January 15 — March 15 2017

300 000 000 RZM is issued for sale (25% — remains in the reserve fund of the company).

The price of 1 RZM for TOKEN SALE:

● 1 step = 0.00105 Eth. (15.01.2018–21.01.2018)

● 2 step = 0.00118 Eth. (22.01.2018–28.01.2018)

● 3 step = 0.00135 Eth. (29.01.2018–04.02.2018)

● 4 step = 0.00152 Eth. (05.02.2018–11.02.2018)

● 5 step = 0.00169 Eth. (12.02.2018–18.02.2018)

● 6 step = 0.00187 Eth. (19.02.2018–25.02.2018)

● 7 step = 0.00204 Eth. (26.02.2018–04.03.2018)

● 8 step = 0.00221 Eth. (05.03.2018–15.03.2018)

After the end of TOKEN SALE, all unsold tokens will be burnt.

FOR MORE INFORMATION PLEASE VISIT:

WEBSITE (smart contract) — www.razoom.org
WHITE PAPER http://www.razoom.org/docs/RAZOOM_WHITEPAPER_EN.pdf
PRESENTATION — https://youtu.be/vANaIt-VWZ0
About TOKENSALE — http://razoom.org/en/token/

预测性智能合约

由A.I主导的奖励机制时代

Read the english version here

机器能引导我们做个好人吗?

趋利是人的天性。将人的固有的自利转化为有利于社会的行动是极具挑战性的,若能成功,这将颠覆整个时代。试想,如果为社会做贡献是对自己最有益的,它自然会成为人们的生活习惯。然而,如何设计出可持续并且诱人的双赢奖励机制则面临着诸多挑战:

  • 如何给社会事业评估其价值,并确保我们的奖励能够最大限度地促进这一事业?
  • 如何设计出足够灵活的奖励措施,以适应不断变化的情况?
  • 如何确定这些奖励措施是可靠的?

在这篇文章中,我们并非要领域专家亲自设计这些奖励措施,而是要介绍以人工智能代为设计奖励机制的技术。我们认为,人工智能驱动的方法不仅能使我们克服许多上述障碍,更能帮助我们设计更高效,可扩展和数据驱动的策略。

GainForest — 一个(非常)机智的打击亚马逊森林砍伐的合同


森林砍伐和森林退化所导致的碳排放量约占全球碳排放的17%,超过全球交通运输领域,仅次于能源领域

我们从一个激励型的例子开始:热带森林的砍伐和退化占全球温室气体(GHG)年排放量的17%左右,要避免危害全人类的气候变化,减少森林砍伐是必要的。在亚马逊地区,超过80%的森林砍伐的原因当地农民需要为种植和牧畜腾出空间。对护林员的小额经济激励措施可使森林砍伐减少一半。但是,认证谁来照顾亚马逊是一项非常耗费人力的任务。

在hack4climate中,我们团队意识到,可以利用经济利益激励人们成为护林员,因此,我们建立了GainForest。这是一个透明,可扩展的平台,允许任何人通过区块链式智能合约成为热带雨林地区的利益相关者。

护林员的安置制度


可从中获益者受利益所激励,自愿成为护林员。全球化的投资系统允许任何人成为护林员。

这个想法很简单:护林员负责确保亚马逊的某一片森林区域免受砍伐 。他们先选择一块区域并且投入一笔资金,在保护期结束后(1/3/6个月),如果他们选择的森林未受破坏,他们将获得最初的投注并且获得奖励。森林若遭破坏,他们的投注将用来支付给以后的护林员。奖励根据保护的难易水平,该区域中有多少利益相关者,以及其他因素来计算。有经济利益的人会受激励来看护他们在本地或全球投资的地区。当地农民可以简单地投资自身所在的区域,在当地亲自看护森林,而全球企业家或社区可以投资,并帮助制定政策,并支付当地的护林员,以打击当地的森林砍伐行为。

此外,捐助者可以通过金钱捐赠系统将资金重新分配给护林员。由于透明的智能合约再分配系统,他们可以即时地看到他们的援助在何时何地取得何等成效。

基于区块链的智能合约,交易将是安全透明的


人工智能机器激励系统概况

智能合同是一种计算机协议,在签署协议后,如果所有条件都得到满足,它保证会被精确地遵守与履行。重要的是,智能合约是自动生效和自动执行的。它们被部署在一个分散的区块链上,消除了对可信赖的第三方(人)的需求。所有交易也透明地记录在区块链中,使捐赠者能够掌握捐赠对环境的影响。

更进一步,通过将人类排除在重新分配的循环过程外,我们可以将其扩展成为一个更加透明的数据驱动系统。

利用机器智能进行数据驱动的投注分配

如前所述,护林员的认证及其在亚马逊的影响是一项非常耗费人力的任务。我们提出了一个基于机器学习的oracle,可以自动评估Amazon的每块区域单元。例如,遥感算法可以轻易从卫星图像(如GLAD,DETER,SAD或FORMA)中检测森林砍伐。


GLAD是一个每周砍伐森林警报系统。它从卫星图像中提取信息,并能够在30m分辨率内检测树木覆盖的减少量(粉色)。这个数字显示了从2015年1月1日到2017年11月1日的树木减少情况。

除此之外,我们还可以进一步利用机器智能。投标制度有以下弱点:一个狡猾的投资者可以把所有的钱投入到亚马逊的一个偏远地区,因为他知道森林被砍伐的可能性非常低。因此,我们需要找到一种将利率与森林砍伐的实际风险联系起来的方法。总之:我们需要预测驱动的奖励。在黑客马拉松(Hackathon)期间,我们从GLAD收集了可取得的图像和森林砍伐数据,并训练了一个卷积神经网络来预测未来森林被砍伐的几率。令我们惊讶的是(考虑到24小时的时间限制),我们能够得到合理的预期结果。我们认为如果有更多的数据和更长的时间,该系统可以计算出更精确的结果。


尽管深度神经网络并不能精准预测森林砍伐,但我们可以看到它学习到了有效的模式。也许它只是预测了一个更长远的未来? (左:地表实况,右:森林砍伐的预测)

我们制作了:GainForest.org,一个区块链激励预测智能合同。我们赢得了hack4climate的一等奖,并在2017年联合国气候变化大会(COP23)上发表。欢迎访问我们的网站,并查看我们的代码。

预测智能合约的更多应用

可持续发展

我们的卫星图像方法可以灵活地应用于更多的环境情景,如河流污染,油棕榈种植和海洋保护。

交通部门

交通拥堵和高峰时间的预测是现代智能城市中非常普遍的任务。若能将它们与智能合同结合起来,可以动态调整公共交通系统的票价,以激励人们乘坐公车而不是私家车。

犯罪侦查

一个激动人心的应用可能是找出潜在的奖励措施来防止犯罪率上升。基于政策的历史数据及其对某些市区的影响,利用人工智能可以设计新的政策和激励措施,以减少犯罪率。

小额信贷

验证小额信贷的影响较为困难。通过将现有的基础设施和经济数据与某些领域的小额信贷奖励措施联系起来,或有可能确定具有最高增长潜力的地区,允许这些地区进行低风险贷款。

下一步是什么?从数据中学习战略激励

区块链和人工智能本不相关。但是,从GainForest的例子中,我们看到人工智能可以帮助我们通过预测自动评估风险,使我们拥有动态的智能合约。另一方面,智能合约帮助我们定义一个自我执行和约束的系统,同时它也是将神经网络用于预测的完美尝试 。我们认为,随着人工智能和区块链技术的进步,预测性智能合约将在未来的区块链交易系统中起到巨大的作用。在GainForest的情况下,在一定程度上,我们甚至可以用有限的数据预测世界不同地区的森林砍伐模式。那是因为像神经网络这样的人工智能算法,能够将学到的知识从一个数据集转移到另一个数据集。转移学习因此使我们能够在亚马逊热带雨林(数据量大的地区)进行训练,然后可将预测应用到世界其他数据缺乏的地区。

更有意思的是,我们的神经网络正在发出自败预言。当我们的学习算法预测森林砍伐到一定程度的时候,它会因为自己也被包含在预测系统中中而阻止预测状况的发生。那么为什么我们不是仅优化神经网络的森林砍伐预测的准确度,同时也要直接预测整体的森林砍伐呢?设想这是两个玩家之间的对抗性游戏,一个神经网络可以激励护林员和采伐方试图将利益最大化。基本上,神经网络想要扩大热带雨林的保护区,而采伐方则试图最小化它。有了这个博弈论的目标,也许神经网络能够学习预测激励策略,对人类行为产生正面的引导。在深度学习,区块链技术和博弈论的交汇处,肯定有一个令人兴奋的研究领域,正在等待被探索!

Acknowledgements

Many thanks to Shan for the chinese translation and Yunyan and Shaoduo for proofreading it!

Links

GainForest

Pitch Slides

2017-11-18-GainForest_distribution

Code

domwoe/gainforest

Live Contracts — What’s all the fuss about?

LegalThings One plans to change the way law is practiced. And yes, it is using the blockchain

Picture this. A contract or law visualized in such a way that it is understandable for humans and computers. Not only the rules that you are agreeing upon in the contract, but also the consequences behind those rules. With our solution Live Contracts, we enable equality of rights for all parties involved.

So, what’s the big deal? For those of you that haven’t been in a legal conflict before, let me explain to you how this works. For starters, law isn’t fair. On paper it is, because the rules apply to everyone. However, in practice the law is on the side of those with the deepest pockets and with friends in the highest places.

Millions of deals are closed every day. Most of them are formalized in contracts. You won’t notice it, but when you don’t get paid or are not happy with how things are going you take a look at the contract. Even for a pretty simple deal, you would have a 3 pager contract with ‘legal lingo’ that is not really easy to read and you would definitely need a lawyer to explain you what the consequences are of breaching a certain clause. Lawyers are doing this for a reason. A natural language contract is prone to ambiguity. This is not per se a bad thing, but lawyers that are drafting the contracts use this ambiguity to their benefit. Ambiguity allows lawyers to build in escape routes within the clauses of the contract. Because when the shit hits the fan, they want parachutes to escape from the breached clause or even the entire contract.

Just a quick example of a contract exploit that cost a Canadian company a million bucks.

In this case a comma was misplaced, corrupting an entire sentence and the meaning behind it. The regulator judged that the Canadian Telco could escape a 5 year contract after as little as one year, although it was clear to everyone that parties only allowed for that possibility after 5 years. With Live Contracts we are getting rid of linguistic chicaneries such as these.

Isn’t this already solved with Smart Contracts?

Smart contracts are written in a programming language, which is intended as instructions for computers. This means that a Smart Contract is even less readable for humans than a paper contract and just as vulnerable for intentional or unintentional exploits.

Additionally, Smart Contracts are intended to self-executing and self-enforcing agreements. The do not operate within a legal framework and are not enforceable by a judicial system. This severely limits the types of contracts you can create as Smart Contract.

Live Contracts are easy to understand for humans as well as computers. They can be used as replacement for any paper contract or agreement, even for laws.

This might be interesting for big corporations, but why should I care?

We want everyone to be able to participate in our economic system without being dependent on others. This is especially important for individuals because they currently only have the choice between relying on a lawyer or blindly trusting organizations and governments.

To make Live Contracts easily understandable for both computers and humans, we split up a contract or law in small and understandable rules. Parts that are considered simple and safe, can be executed by computers. Other parts can, and should, be left to human interpretation.

A paper contract gets signed and put into a drawer only to be forgotten. A Live Contract is something that you continue to interact with. Each event related to the contract is logged in an immutable way, using decentralized storage and the blockchain.

Consider a single large database, managed by the government, to which all other systems are connected. This database would be the single source of truth. This would be highly efficient, unfortunately this very easy to manipulate. Especially by the people in power.

To prevent this we invented bureaucracy. Most people think this is a bad thing, but in fact bureaucracy is our best defence against fraud and favoritism. Having a large number of people jumping to hoops and making sure everything is documented, provides a long paper trail and proof of work. This makes it difficult to exploit the system.

Our solution makes it possible for anyone to participate, without having to rely on others. This is especially important for individuals, as currently they only have the choice between depending on a lawyer or blindly trusting organizations and the government.

Conclusion

Live Contracts can replace any contract or law making them easier to understand. This makes them accessible for everyone involved. Unlike smart contracts, they allow automation without giving full control to the machines. By storing events and information in an immutable way we mitigate fraud while reducing bureaucracy.

Live Contracts will make the legal system fair for everybody.



Live Contracts — What’s all the fuss about? was originally published in legalthingsone on Medium, where people are continuing the conversation by highlighting and responding to this story.

A Platform for the on-demand economy

HireBits is a platform for the gig economy, where everything and everyone will be available at the speed of thought and tap of a button. In other words, the uberisation of services will continue and we are here to help workers embrace it.

McKinsey categorizes independent workers into 4 groups.


HireBits: 4 types of independent workers

Today, very few large companies use independent workers in any significant manner. An important reason is the absence of the right platforms that can broaden worker participation, enable availability matching, assure on-demand services and skills, and automate contract enforcement.

HireBits wants to be the preferred platform for casual earners and reluctants to embrace gigs as a way of life and become free agents.

Incidentally, only a fraction of people who are part of the on-demand, independent workforce actually connect through digital platforms. HireBits will change that, particularly in some of the largest job markets in the world. We want HireBits to be seen as a trusted platform for talent sourcing. HireBits will disrupt the gigs marketplace, by being a trustless decentralized platform that enforces contracts on the blockchain, combined with institutional relationships and evangelism.

HireBits will be a global marketplace for gigs and jobs, transcending borders, guaranteeing trust, and promoting on-demand services across a wide variety of sectors. We invite you to be a part of the journey.

Do read our platform whitepaper to learn more about how HireBits will transform talent sourcing in the on-demand world.

A Platform for the on-demand economy

HireBits is a platform for the gig economy, where everything and everyone will be available at the speed of thought and tap of a button. In other words, the uberisation of services will continue and we are here to help workers embrace it.

McKinsey categorizes independent workers into 4 groups.


HireBits: 4 types of independent workers

Today, very few large companies use independent workers in any significant manner. An important reason is the absence of the right platforms that can broaden worker participation, enable availability matching, assure on-demand services and skills, and automate contract enforcement.

HireBits wants to be the preferred platform for casual earners and reluctants to embrace gigs as a way of life and become free agents.

Incidentally, only a fraction of people who are part of the on-demand, independent workforce actually connect through digital platforms. HireBits will change that, particularly in some of the largest job markets in the world. We want HireBits to be seen as a trusted platform for talent sourcing. HireBits will disrupt the gigs marketplace, by being a trustless decentralized platform that enforces contracts on the blockchain, combined with institutional relationships and evangelism.

HireBits will be a global marketplace for gigs and jobs, transcending borders, guaranteeing trust, and promoting on-demand services across a wide variety of sectors. We invite you to be a part of the journey.

Do read our platform whitepaper to learn more about how HireBits will transform talent sourcing in the on-demand world.

Predictive Smart Contracts

The Age of A.I. Powered Incentives

Can a machine guide us to be good humans?

Self-interest is an integral part of human nature. Being able to re-channel self-interest into actions that would benefit all of the society is challenging but possibly transformative. Imagine, to enable people to do social good just because it is simply the most profitable way to live. We would naturally consolidate a more sustainable lifestyle without even thinking about it. However, the design of sustainable incentives faces a plethora of challenges:

  • How can we link a value to a social cause and ensure that it maximizes this cause?
  • How can we design incentives that are flexible enough to adapt and react to changing scenarios?
  • How can we make sure, that these incentives are trustable?

In this blog post, instead of designing these incentives by hand, we want to introduce a technology stack, that allows us to design incentives by machines. We argue that this machine-powered approach not only allows us to overcome many of the aforementioned obstacles but moreover help us design more efficient, scalable, and data-driven strategies.

I tweet new blog posts @dwddao on Twitter and my code is always available @daviddao in GitHub. Follow me for random thoughts about artificial intelligence.

GainForest — A (very) smart contract to fight deforestation in the Amazon


Deforestation and forest degradation account for approximately 17 percent of carbon emissions, more than the entire global transportation sector and second only to the energy sector

Let’s start with a motivating example: Tropical deforestation and degradation contributes about 17% of annual global greenhouse gas (GHG) emissions and reducing it will be necessary to avoid dangerous climate change. More than 80% of deforestation in the Amazon happens due to local farmers making room for crops and cattle. Small financial incentives to caretakers have been shown to cut deforestation in half. However, verifying who takes care of what in the Amazon is a hugely labor-intensive task.

During hack4climate, our team realized that people with financial stakes are incentivized to act as caretakers. As a result, we built GainForest, a transparent, scalable platform that allows anyone to become a stakeholder in rainforest regions via blockchain-powered smart contracts.

A staking system for caretakers


People with financial stakes are incentivized to act as caretakers. A global staking system would allow everyone to become a caretaker

The idea is simple: caretakers take responsibility for ensuring a certain patch of the Amazon is protected against deforestation. They select their patch and stake a voluntary amount of money. After the conservation period is over (1/3/6 months), if their forest still stands, they get their initial stake back plus a reward. If not, their stake is used to support future caretakers. Rewards are calculated based on the level of difficulty of the conservation, how many stakeholders there are in that patch, and other factors. People with financial stakes are incentivized to take care of the regions they invested in — locally or globally. Local farmers can simply invest in their own regions and take care on site while global entrepreneurs or communities can invest and help shape policies and pay local caretakers to fight local deforestation.

Additionally, donors can make monetary donations that the system can redistribute to caretakers. They can see where and when their support impacts conservation efforts in real-time thanks to a transparent smart contract redistribution system.

Safe and transparent transactions with blockchain-based smart contracts


An overview of the machine-powered incentive system

Smart contracts are computer protocols that guarantee that an agreement, once signed, is precisely followed and paid out if all conditions are fulfilled. The important thing is that smart contracts are self-executing and self-enforcing. They are deployed on a decentralized blockchain, removing the need for a trusted third (human) party. All transactions are also transparently recorded within the blockchain, allowing the donators to follow the environmental impact of their donations.

Furthermore, by taking the human out of the loop during the full redistribution process, we can scale into a more transparent and data-driven system.

Data-driven stake distribution using machine intelligence

As mentioned before, verification of caretakers and their impact in the Amazon is a hugely labor-intensive task. We propose a machine learning based oracle that automatically evaluates patches of the Amazon. For example, it is straightforward for remote sensing algorithms to detect deforestation from satellite images such as GLAD, DETER, SAD or FORMA.


GLAD is a weekly deforestation alert system. It extracts its information from satellite images and can detect tree cover loss (pink) within 30m resolution. This figure displays tree cover loss from 1 Jan 2015 to 1 Nov 2017

But we can even go further using machine intelligence. The staking system has following weakness: A clever investor could just put all his money into a remote region of the Amazon, knowing that the probability of deforestation happening is very low. Thus, we need to find a way to link interest rates with the actual risk of deforestation happening. In short: We need prediction-driven incentives. During the hackathon, we collected available image and deforestation data from GLAD and trained a convolution neural network to predict future deforestation. To our own surprise (considering the 24h time frame), we were able to get reasonable looking results. We hypothesize that with more data and time, we can get even more accurate results.


Although the deep neural network doesn’t predict the deforestation exactly, we can see that it learned useful patterns. Maybe it just predicted a more radical future? (Left: Ground Truth, Right: Predicted Deforestation)

And there we have it: GainForest.org, a blockchain-powered predictive smart contract. We won the first prize at hack4climate and were able to pitch our ideas at the UN Climate Change Conference 2017 (COP23). Feel free to visit our website and check out our code.

More applications of predictive smart contracts

Sustainability

Our satellite image approach can be easily adapted to more environmental scenarios such as river pollution, oil palm plantations, and ocean protection.

Transportation sector

The prediction of traffic congestion and rush hours are very common tasks in modern smart cities. Being able to combine them with smart contracts would allow us to dynamically adjust ticket fares of public transportation systems to incentivize people to rather take the bus than their private car.

Crime detection

One exciting use case might be to find possible incentives against a rising crime rate. Using historic data from policies and its impact on certain city districts, a machine might be able to design new policies and incentives with the goal to minimize crime rates.

Microfinance

Verifying the impact of microcredits is difficult. By linking available infrastructural and economic data with microcredit incentives in certain areas, it might be possible to determine regions with highest growth potential, allowing these regions to take credits with lower risks.

What’s next? Learning strategic incentives from data


Maybe include game theory into our predictive smart contracts to guide humans with strategic incentives?

Blockchain and A.I. are orthogonal technologies. However, from the GainForest example, we see that intelligent machines can help us automatically evaluate risk through predictions, allowing us to have dynamic smart contracts. While on the other hand, smart contracts help us define a self-enforcing and constrained system. A perfect testing ground for neural networks. We think that these predictive smart contracts will play a huge role in future blockchain-powered transaction systems as A.I. and blockchain technology gets better every day. In case of GainForest, to a certain degree, we could even make predictions of deforestation patterns in different areas of the world, with limited data. That is due to the fact that A.I. algorithms such as neural networks have the ability to transfer their knowledge from one dataset to the other. Transfer learning thus allows us to train on the Amazon rainforest (where we have a lot of data) and apply predictions also on other parts of the world.

Interestingly, our neural network is giving our self-defeating prophecies. The moment our learning algorithm predicts deforestation, to a certain point, it prevents what it predicts from happening due to the underlying staking system. So why don’t we just optimise the neural network not on just how well it predicts deforestation, but also to directly minimize the overall deforestation. Imagine it to be an adversarial game between two players, a neural network which can give out incentives for caretakers and logging parties trying to maximize profit. Basically, a neural network now wants to optimize the conservation area of the rainforest, while logging parties try to minimize it. With this game-theoretic objective, maybe the network is able to learn to predict strategic incentives, teaching us how to be better human beings? There is definitely an exciting area of research at the intersection of deep learning, blockchain technology, and game theory, waiting to be explored!

If you are interested in this research topic, please don’t hesitate to contact me and the DS3Lab at ETH Zurich.

If you want to support us in starting a pilot project with GainForest.org, send us a mail at hello@gainforest.org.

Resources

GainForest

Pitch Slides

https://docs.google.com/presentation/d/1nH5LeSwfTUaCHqUrkyubR4fpvvTKeKO4QJGuvWEJ4ns/edit?usp=sharing

Code

https://github.com/domwoe/gainforest

Why can’t I withdraw my tokens from the HACK VC Token Dashboard!?

We would love for our contributors be able to hold HACK tokens in their ERC20 wallets from the moment they buy in, but we can’t make that happen.

Why is this?

We want HACK tokens to hold their value during the token sale.

We want contributor’s tokens to all be released at once. This ensures that there will be no secondary market trading throughout the entire duration of our token sale.

It prevents malicious users from doing a “Pump and Dump”(probably my favorite term ever).

Imagine if someone were to buy in early at the highest possible discount and then, a month later, sell their HACK tokens on a secondary market while we were still in the middle of the token sale. That person could undersell us and still make a tidy profit. This happens often in the ICO/Token Sale space and people do this without even knowing about the product.

Releasing our tokens to users all at once, after the token sale ends, solves this large problem.

Why can’t I withdraw my tokens from the HACK VC Token Dashboard!?

We would love for our contributors be able to hold HACK tokens in their ERC20 wallets from the moment they buy in, but we can’t make that happen.

Why is this?

We want HACK tokens to hold their value during the token sale.

We want contributor’s tokens to all be released at once. This ensures that there will be no secondary market trading throughout the entire duration of our token sale.

It prevents malicious users from doing a “Pump and Dump”(probably my favorite term ever).

Imagine if someone were to buy in early at the highest possible discount and then, a month later, sell their HACK tokens on a secondary market while we were still in the middle of the token sale. That person could undersell us and still make a tidy profit. This happens often in the ICO/Token Sale space and people do this without even knowing about the product.

Releasing our tokens to users all at once, after the token sale ends, solves this large problem.

Hi Sam, thanks for your reading!

Hi Sam, thanks for your reading! After debugging over 3 hours, I finally figured out the issue. My tutorial is outdated since truffle upgrade to version 4 couple days ago. Thanks for you reporting and feedback, I already entirely rewrite the tutorial and sample code on github to make it work with truffle 4. If you want, you can “redownload” my repo or git pull the repo again and start reading the whole tutorial again.(I change many places and it’s better now)

There is also another way to fix the “ Exceeds block gas limit” in my old code, update the truffle.js under ~/02-Testing/finish/truffle.js to be what I pasted in this gist(https://gist.github.com/amazingandyyy/b2d3411720d7b946d0d6ea5ad4b6f244)

The change to this gist is actually just add an explicit gas limit as 4700000.

Please feel free to reply me if it works and if you encounter further bugs :)

Thanks for your report!

LiveEdu-The Next Generation Decentralized Online Learning Platform

About Is LiveEdu ?

LiveEdu is The Next-generation learning platform to teaching college students and professionals practical skills. It has resulted in new methods for teaching worldwide

LiveEdu is building the world’s largest project-based learning (PBL) library on any topic starting with the seven topics programming, game development, data analytics, design, augmented and virtual reality, artificial intelligence and cryptocurrencies. The aim is to develop a decentralized online learning ecosystem that is not reliant on learning theory but practical useful career skills

The LiveEdu peer-to-peer marketplace will connect streamers (content creators) and viewers (learners) from all over the world. The idea being that streamers will create educational premium projects and are paid a monthly lifelong royalty fee if their projects are watched by viewers.

LiveEdu also seeks to bring cryptocurrency to the masses by educating college students and professionals using real practical cryptocurrency tutorial projects covering cryptocurrency basics, blockchain mining, Bitcoin, Ethereum, security and ICOs

Key Features

LiveEdu Platform and API Ecosystem

  1. List of Topics and Categories
    LiveEdu covers seven topics; programming, game development, design, data science, virtual and augmented reality, artificial intelligence and cryptocurrencies.
    Each of these seven topics contains its own sub-categories.
    The six other new topics were launched in August 2017 and LiveEdu does not yet have significant content for them. Currently, there is no premium project content on LiveEdu except for programming.
    Our plan is to use part of the funds from the ICO to incentivize streamers to create premium projects.
  2. Main Product Features: Live Streams, Videos, Chat
    Content on LiveEdu is organized around projects. Each project contains a live streaming channel, video project playlist and live chat window. ​Each live stream is archived automatically as a video. LiveEdu gives content creators the ability to deliver their projects via live stream or offline recording.
    There are two main types of projects on LiveEdu; premium tutorial projects and non-premium projects.
    The interactive live chat is the main mode of Q & A communication between a content creator and viewers. Learners ask questions, give suggestions for improvement and also socialize with other learners. When a learner opens a live stream he can see the live channel, chat window, project description, curriculum and downloadable resources. Content 10 creators use the streaming software client Open Broadcaster Software (OBS) to stream their desktop, audio and camera to one of the LiveEdu streaming origin servers.
  3. Premium Tutorial Projects
    Premium tutorial projects are projects created with the sole intention of teaching learners. They are fully narrative, structured, contain well drafted project descriptions, streamed at same weekly schedule and have downloadable project resources.
    The creation of premium tutorial projects undergoes a strict content moderation process to ensure the highest quality standard. Creating a premium tutorial project requires the content creator to spend time preparing the content. The content creators selected for premium tutorial projects have vast real industry experience, with at least four years in their field.
    Below are examples of premium tutorial projects from the fields of data science and programming that explain how LiveEdu teaches learners how to build real products:
    – Project Title: Python Data Analytics and Visualization
    – Project Title: How to Create a Dating Web App in Node.js
    – Project Title: Machine Learning Model: Python Sklearn & Kera
  4. LiveEdu API Ecosystem and Third-party Apps As
    LiveEdu seeks to position itself as the major tutorial learning platform in the world, an API will help to make this into a reality. Authentication and access controls are performed using standard and widely supported OAuth2 protocol.
    The API is available over HTTPS and follows RESTful conventions. Third-party developers can build their own complete applications on top of the LiveEdu API. This can be bots, mobile apps, websites, widget or plugins. One of such example is the LiveEdu streamer Iamvalerio who is using the API to build a LiveEdu Android app.

LiveEdu EDU Token Model

Use-Cases for EDU Smart Tokens
Each positive activity a learner, content creator, site moderator or ecosystem participant completes on LiveEdu represents the minting of EDU tokens.
EDU tokens are going to be fully integrated into all core modules and transactions on LiveEdu; a paymentmethod for all financial transactions; rewarding premium project tutorial creators,positive learner behavior, site moderators, and API ecosystem developers.
When the EDU tokens are fully rolled out and integrated into LiveEdu, this is how they will be used on our website and in mobile apps:

  1. Payment Method for all Financial Transactions
  2. Paying Premium Project Content Creators
  3. LiveEdu Token Utility Activities for Learners
  4. LiveEdu Token Rewards for Quality Assurance and Site Moderation
  5. LiveEdu Token Rewards for LiveEdu API Ecosystem Developers

Technical Implementation of EDU Tokens

  1. Smart Contract Implementation
    The EDU smart contract is fully implemented and set-up by the experienced blockchain and ICO experts from New Alchemy.
    The token is based on the ERC-20 standard with minimal deviations. This was designed with inspiration from other ERC-20 tokens such as Bancor, Filecoin and Civic.
    The smart contract accepts only ether. investments made with other coins and fiat will be converted to ether.
  2. Token Model
    investors can buy EDU tokens directly with Ethereum (ETH), Bitcoin (BTC), Litecoin (LTC), fiat (USD/EUR) and with other coins indirectly via Shapeshift.
    An EDU token can have maximum eight decimal points. There is a soft cap of $1M and hard cap of $8M for ETH investments (non- ETH investments do not count toward the hard cap).
    The total number of EDU tokens to be minted for the LiveEdu ICO will be determined after the ICO closes.
    The total token supply is limited by the hard cap. As soon as the hard cap is reached the ICO closes.
    For both the pre-ico and main crowdsale, minimum investment amount per transaction is $3.
    If you send less than $3 per transaction, you will lose that.
    The token is denominated in US $:
    1 USD = 10 EDU tokens
    1 ETH = $ ETH value x 10
    1 BTC = $ BTC value x 10
    1 LTC = $ LTC value x 10
    1 EUR = $ EUR value x 10
    Pre-sale bonus:
    The company is pre-selling EDU tokens prior to the public sale at a discount on a wholesale basis for large volume purchases. Minimum amount for bonus: $50
    <= $10,000 USD + receives a 25% bonus
    >= $10,000 USD + receives a 30% bonus
    >= $30,000 USD + receives a 35% bonus
    >= $50,000 USD + receives a 40% bonus
    > $100,000 USD + receives a 50% bonus

Token Allocation

5% Pre-Sale
45% Main Crowdsale
10% Subscription pool (user token purchases)
13% Content Creators (streamers)
13% Team
6% ICO Legal and Technical Advisory, Bounty Program, ICO Marketing
3% API Ecosystem Developers
3% Supporters (Quality Assurance and Site Moderation)
2% Learners (viewers)

Use Funds

15% Building Premium Projects
Each quarter approximately 300 premium projects will be created by streamers.
35% Team Member Expansion
Hiring of new team members: engineers, product manager, chief marketing officer, head of curriculum, and head of sales.
25% Platform Development and Server Costs
Integration of EDU token into LiveEdu. Expanding streaming cluster and improving stream quality. Native Android and iOS app development.
15% Marketing
10% Overhead

Bounty Program

Bounty participants will be split into bounty pools based on their method of contribution with each pool having its own distribution of EDU Tokens.

The total number of EDU tokens to be minted for the LiveEdu ICO will be determined after the ICO closes. 10 EDU tokens equals $1

2.5% of tokens is to be distributed to bounty hunters. The fairest way to share the 2.5% of all EDU tokens issued (Over $500k ) is by using the stakes system.

The total bounty is divided into
15% Bitcointalk Signature and Avatar
10% Social Media Twitter
10% Country Specific Marketing
25% Blog Posts
15% Translation, Moderation & Community Management
10% Reddit
10% Telegram
5% Other [Social media influencers or newsletter owners.
Contact us on content@liveedu.tv to discuss remuneration.]
The Bounty Program Detail Here

More Info

Website
Whitepaper
Ann Thread
Facebook
Twiter
Telegram
Medium
Reddit

Author
StreakW
https://bitcointalk.org/index.php?action=profile;u=1192619
0x73BCEb6C37F42e72caB4747783275E1585eaa097

ChainLink White Paper — Section 2 — Architectural Overview

The Architectural Overview gives the detailed view for how ChainLink fits between the blockchain and the internet. It also provides the technical outlook for how the network will operate. ChainLink is going to be developed on Ethereum initially, with support for other blockchains and cross-chains at a later date. There is also a focus keeping the system separated so that any piece may be easily upgraded. The architectural overview is comprised of only two (but both very important) sub-sections: On-Chain Architecture and Off-Chain Architecture.

On-Chain Architecture is the initial implementation for the ChainLink network. In this method, the majority of the work is done within smart contracts and the retrieving of the data is done within the node. The user-created smart contract is what supplies the query supplied by the smart contract creator for the nodes to individually carry out.

The ChainLink smart contract’s on-chain components are comprised of a reputation contract, and order-matching contract, and an aggregating contract. The reputation contract is what keeps track of the metrics discussed in Section 5. The order-matching contract takes the parameters set by the smart contract creator and accepts bids from individual nodes according to the SLA. Finally, the aggregating contract is what collects each node’s answer and provides a final result to the user’s query (as well as provide metrics to the reputation contract). On-chain aggregation is broken into three steps: oracle selection, data reporting, and result aggregation.

In oracle selection, the smart contract creator (or end-user) specifies the criteria needed by the smart contract, like what information they would like to gather and the number of and reputation of the nodes to be used in the assignment (assignment is another word used for the work required of the nodes). A listing service will be provided to make the oracle selection process easier on the smart contract creator. This will allow the smart contract creator to submit the assignment through the listing service (off-chain), but the final SLA will be met on-chain. Additionally, it may be possible to automatically determine which nodes would be best suited for the assignment with an order-matching contract. This would be possible with the use of rules configured on each node to determine whether they would automatically bid on the assignment or not. If an assignment matches the node’s own criteria, it will bid by paying the configured penalty amount (an amount that would be lost if the node returns unacceptable data). Nodes which were not accepted by the assignment will immediately be able to withdraw their penalty payment bid, and those that were selected will start the assignment.

In data reporting, the nodes simply carry out the assignment as defined by the SLA. This means the node would connect to their API endpoints, process the data through their adapters, digitally sign their responses, and return their answers on-chain.

In result aggregation, nodes reveal their results to the aggregating contract, which calculates an answer for the contract creator’s query. The aggregation contract uses each oracle’s response to report to the reputation contract its validity and timeliness. An additional property of the aggregation contract is that it is entirely configurable by the smart contract creator. In order to deal with varying answers, the smart contract creator my wish to configure the aggregation contract to ignore outlying answers before calculating an average, for example.

The off-chain architecture is made up of the nodes which make up the ChainLink network. Each node must individually connect to other off-chain resources via API calls in order to gather responses for assignments. External adapters may be employed in order to extend the available connections for 3rd party API endpoints.

The ChainLink core software is what translates off-chain data (data which was gathered via an API endpoint) into a way that can be read on-chain. It also handles the details of an assignment, including carrying out an assignment’s sub-tasks as they are configured and scheduled by the smart contract creator.

External adapters are needed for connecting to 3rd party API endpoints. They can be written in any language as long as they conform to the schema defined by ChainLink. External adapters may also chain off one another, accepting the response of one adapter in order to produce another result.

That’s all for this section of the ChainLink white paper. Let me know what you think and feel free to leave any feedback.

Decentralized Applications and Lending on the Blockchain

ETHLend is a ”fully decentralised P2P lending platform build on top of the Ethereum Blockchain using Smart Contracts”. So what does this actually mean? That is a great question, so lets break it down.

Decentralization refers to the degree of which power is taken from a central entity and, in case of blockchains, how this power is distributed into a network. In theory this means that there is no single entity that has decision making power, instead the whole network is responsible for the development of the project. This is a completely new paradigm shift, which is going to disrupt many industries and create completely new eco-systems with their own economics.

ETHLend will aim to be as decentralized as possible. This means that we are focused on building our community and not making all the decision by ourselves. Our goal in the long term is to shift our governance from the ETHLend Foundation to the community. In the blockchain space this is known as a DAO, Decentralized Autonomous Organization. This means that we will build in a governance model into the platform that will give our users the possibility to vote on new developments.

P2P, peer to peer, means that all exchanges of value happens directly between two people. In a normal environment, when we exchange value we want to have a 3rd party as a middleman to ensure ”safety and security”. With the blockchain this model becomes obsolete. We call this a trust-less environment, where any two people can transact with each other without trusting each other. The reason for this is that the blockchain will take care of the ”trust” part. We can always trust that the code works the same way and this way we do not need to trust the other party, just the fact that the blockchain will work.

ETHLend is a lending platform. We offer a platform that is accessible through you internet browser (Google Chrome + Metamask plug-in) and where you can request a loan in digital currencies. There are many use cases for this platform. One would be a speculative use case where traders want to increase their liquidity or swap in between tokens e.g. if your getting short squeezed.

But the bigger vision for our platform is to offer a financial service for the 2 billion unbanked people in the world. Especially in places where the government is oppressing people, corruption is present in the governing bodies, using unsuccessful monetary and fiscal policies and creating huge inflation. The list goes on and on… With the help of cryptocurrencies we can transact directly with each other in a democratic and decentralized manner. There’s no need for people to trust their banks and in some countries you most definitely shouldn’t. If we look at the interest rates between developed and developing countries, the differences are huge. Our goal is to offer a global and fair marketplace that gives everyone access to capital. Democratizing lending markets with the help of the blockchain.

The Ethereum blockchain. We’re building on top of the Ethereum blockchain. But we should probably start of by giving some kind of definition of what a blockchain is.

” A blockchain is a digitized, decentralized, public ledger of all cryptocurrency transactions. Constantly growing as ‘completed’ blocks (the most recent transactions) are recorded and added to it in chronological order, it allows market participants to keep track of digital currency transactions without central record keeping. Each node (a computer connected to the network) gets a copy of the blockchain, which is downloaded automatically.”

This pretty much summarizes what a blockchain is, but this description is more fitting for Bitcoin. What makes Ethereum different is that we can do Smart Contracts. This is a computer protocol that is specifically designed to facilitate, verify and enforce contracts. Negotiations and performance indicators will be specified in the code and the contract will execute when certain parameters are met.

In our use case we want to put the loan data on these smart contracts and this way ensure a secure and safe lending environment. There’s no involvement from third parties and there’s no way for anyone to ”hack” this system. Our loans are safe and secure by design and also democratic by nature.

This pretty much summarizes what ETHLend is. Stay tuned for updates or check out our social media for more details on the project. Doing lending in a decentralized environment and creating a credit rating or history is a big challenge. Our solution is already working, but this is only the beginning.

Br,
Martin Wichmann, Head of Token Sale, ETHLend

As usual, all insights and exclusive content on Telegram.

To keep track of news and updates, make sure to follow us on our social channels:

Subscribe to ETHLend Token Sale: https://about.ethlend.io/token-sale/

Telegram: https://t.me/ETHLend

White Paper: https://github.com/ETHLend/Documentation/blob/master/ETHLendWhitePaper.md

Follow us & participate …
Discord (Latest news and voice chats): https://discord.gg/nKjsStv
DAPP Thread: https://bitcointalk.org/index.php?topic=2013399
Telegram General: https://t.me/ETHLend
Telegram Sprechen Sie Deutsch https://t.me/ETHLend_DE
Telegram ¿Hablas español https://t.me/ETHLend_ES
Telegram Parli italiano https://t.me/ETHLend_ITA
Telegram Говорите по-русски https://t.me/ETHLend_RU
Reddit: https://www.reddit.com/r/ETHLend/
Facebook: https://www.facebook.com/ETHLend/
YouTube: https://www.youtube.com/channel/UCZUFYgrvO7xpxzMjijgqWyQ
Twitter: https://twitter.com/ethlend1
Medium https://medium.com/@ethlend1
DTube: http://dtube.video/#!/c/ethlend
Steemit: https://steemit.com/@ethlend
BTCTalk ICO Thread: http://bitcointalk.org/index.php?topic=2090735.0;all
WeChat: @ethlend
KakaoTalk: http://open.kakao.com/o/gBzFr5y
Vkontakte: http://vk.com/ethlend



Decentralized Applications and Lending on the Blockchain was originally published in ETHLend Blog on Medium, where people are continuing the conversation by highlighting and responding to this story.

Decentralized Applications and Lending on the Blockchain

ETHLend is a ”fully decentralised P2P lending platform build on top of the Ethereum Blockchain using Smart Contracts”. So what does this actually mean? That is a great question, so lets break it down.

Decentralization refers to the degree of which power is taken from a central entity and, in case of blockchains, how this power is distributed into a network. In theory this means that there is no single entity that has decision making power, instead the whole network is responsible for the development of the project. This is a completely new paradigm shift, which is going to disrupt many industries and create completely new eco-systems with their own economics.

ETHLend will aim to be as decentralized as possible. This means that we are focused on building our community and not making all the decision by ourselves. Our goal in the long term is to shift our governance from the ETHLend Foundation to the community. In the blockchain space this is known as a DAO, Decentralized Autonomous Organization. This means that we will build in a governance model into the platform that will give our users the possibility to vote on new developments.

P2P, peer to peer, means that all exchanges of value happens directly between two people. In a normal environment, when we exchange value we want to have a 3rd party as a middleman to ensure ”safety and security”. With the blockchain this model becomes obsolete. We call this a trust-less environment, where any two people can transact with each other without trusting each other. The reason for this is that the blockchain will take care of the ”trust” part. We can always trust that the code works the same way and this way we do not need to trust the other party, just the fact that the blockchain will work.

ETHLend is a lending platform. We offer a platform that is accessible through you internet browser (Google Chrome + Metamask plug-in) and where you can request a loan in digital currencies. There are many use cases for this platform. One would be a speculative use case where traders want to increase their liquidity or swap in between tokens e.g. if your getting short squeezed.

But the bigger vision for our platform is to offer a financial service for the 2 billion unbanked people in the world. Especially in places where the government is oppressing people, corruption is present in the governing bodies, using unsuccessful monetary and fiscal policies and creating huge inflation. The list goes on and on… With the help of cryptocurrencies we can transact directly with each other in a democratic and decentralized manner. There’s no need for people to trust their banks and in some countries you most definitely shouldn’t. If we look at the interest rates between developed and developing countries, the differences are huge. Our goal is to offer a global and fair marketplace that gives everyone access to capital. Democratizing lending markets with the help of the blockchain.

The Ethereum blockchain. We’re building on top of the Ethereum blockchain. But we should probably start of by giving some kind of definition of what a blockchain is.

” A blockchain is a digitized, decentralized, public ledger of all cryptocurrency transactions. Constantly growing as ‘completed’ blocks (the most recent transactions) are recorded and added to it in chronological order, it allows market participants to keep track of digital currency transactions without central record keeping. Each node (a computer connected to the network) gets a copy of the blockchain, which is downloaded automatically.”

This pretty much summarizes what a blockchain is, but this description is more fitting for Bitcoin. What makes Ethereum different is that we can do Smart Contracts. This is a computer protocol that is specifically designed to facilitate, verify and enforce contracts. Negotiations and performance indicators will be specified in the code and the contract will execute when certain parameters are met.

In our use case we want to put the loan data on these smart contracts and this way ensure a secure and safe lending environment. There’s no involvement from third parties and there’s no way for anyone to ”hack” this system. Our loans are safe and secure by design and also democratic by nature.

This pretty much summarizes what ETHLend is. Stay tuned for updates or check out our social media for more details on the project. Doing lending in a decentralized environment and creating a credit rating or history is a big challenge. Our solution is already working, but this is only the beginning.

Br,
Martin Wichmann, Head of Token Sale, ETHLend

As usual, all insights and exclusive content on Telegram.

To keep track of news and updates, make sure to follow us on our social channels:

Subscribe to ETHLend Token Sale: https://about.ethlend.io/token-sale/

Telegram: https://t.me/ETHLend

White Paper: https://github.com/ETHLend/Documentation/blob/master/ETHLendWhitePaper.md

Follow us & participate …
Discord (Latest news and voice chats): https://discord.gg/nKjsStv
DAPP Thread: https://bitcointalk.org/index.php?topic=2013399
Telegram General: https://t.me/ETHLend
Telegram Sprechen Sie Deutsch https://t.me/ETHLend_DE
Telegram ¿Hablas español https://t.me/ETHLend_ES
Telegram Parli italiano https://t.me/ETHLend_ITA
Telegram Говорите по-русски https://t.me/ETHLend_RU
Reddit: https://www.reddit.com/r/ETHLend/
Facebook: https://www.facebook.com/ETHLend/
YouTube: https://www.youtube.com/channel/UCZUFYgrvO7xpxzMjijgqWyQ
Twitter: https://twitter.com/ethlend1
Medium https://medium.com/@ethlend1
DTube: http://dtube.video/#!/c/ethlend
Steemit: https://steemit.com/@ethlend
BTCTalk ICO Thread: http://bitcointalk.org/index.php?topic=2090735.0;all
WeChat: @ethlend
KakaoTalk: http://open.kakao.com/o/gBzFr5y
Vkontakte: http://vk.com/ethlend



Decentralized Applications and Lending on the Blockchain was originally published in ETHLend Blog on Medium, where people are continuing the conversation by highlighting and responding to this story.

Parity 多签名钱包里的资金为什么被冻结了???

Let’s explain what happened

北京时间昨天夜里又发生了一起针对Parity MultiSig 合约的攻击。这也是继7月份之后的又一起严重的安全事件。本次事故造成的损失在50万ETH左右,价值不菲,其中包括了Web3基金会的Polkadot的30万ETH的开发资金。

回顾

Github 用户devops199 在parity仓库上提出了一个 issue #6995 — “anyone can kill your contract”. 他声称自己不小心“杀死”了以下合约:0x863df6bfa4469f3ead0be8f9f2aae51c91a907b4. (合约代码链接: here)

由上图可见一个用户触发了kill函数。他首先调用了initWallet 函数,这样就成为了该合约的拥有者,然后接着执行力kill函数。他之所以能这么做是因为该合约从未被初始化过,所加的修饰符 only_uninitialized并没有阻止他的call。

当一个新版本的multi-sig钱包被部署了,它都是以合约的形式出现,其代码会作为其他智能合约的模版。以上合约被多次作为multi-sig钱包的重要逻辑实现方式,通过 delegateCall调用。所以当它被“杀死”后,multi-sig钱包也就不能再使用了。也就是说,所有存在于这些multi-sig钱包里的资金都不能被转移。

Parity已经发出了严重的安全警告, 之前在Github 上提交的issue也被标记为 P0-dropeverything

当事人反应

用户devops199在后来的采访中表示自己并不懂写代码,刚刚接触以太坊的东西,只是在学习此文章中有关7月份攻击的内容,然后就发送了一些交易尝试kill合约。

这让人哭笑不得。

损失情况

根据非官方统计,这次主要受害者是polkadot,iconomi和musiconomi。

以太坊社区的反应

  • Polkadot表示不是所有的ICO资金都被锁住,将继续开发工作。
  • Parity钱包为什么会采用这样的设计?

根据reddit上的讨论,由于Parity在钱包的设计上考虑了减少gas的成本,所以导致了此次单点故障。在最初的设计中,若钱包合约需要使用library内的内容,则每一个钱包合约在部署时需要花费大量gas在调用library合约函数上。parity将library合约设计成stub的形式,有效减少钱包的交易成本。当然,此次事故也离不开7月份攻击后的修复,这就和delegateCall有关。具体可参见openzeepline的博客

  • Hard fork??

目前,所有丢失的资金只能通过硬分叉找回。但是,以太坊的信誉是否经得起再一次硬分叉呢?一些reddit用于表示

Reputation is everything

社区在发展的过程中会经历各种事件。parity的安全事故一次次在考验以太坊社区的团结。

附录:

合约代码

//sol Wallet
// Multi-sig, daily-limited account proxy/wallet.
// @authors:
// Gav Wood <g@ethdev.com>
// inheritable “property” contract that enables methods to be protected by requiring the acquiescence of either a
// single, or, crucially, each of a number of, designated owners.
// usage:
// use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by
// some number (specified in constructor) of the set of owners (specified in the constructor, modifiable) before the
// interior is executed.
pragma solidity ^0.4.9;
contract WalletEvents {
// EVENTS
// this contract only has six types of events: it can accept a confirmation, in which case
// we record owner and operation (hash) alongside it.
event Confirmation(address owner, bytes32 operation);
event Revoke(address owner, bytes32 operation);
// some others are in the case of an owner changing.
event OwnerChanged(address oldOwner, address newOwner);
event OwnerAdded(address newOwner);
event OwnerRemoved(address oldOwner);
// the last one is emitted if the required signatures change
event RequirementChanged(uint newRequirement);
// Funds has arrived into the wallet (record how much).
event Deposit(address _from, uint value);
// Single transaction going out of the wallet (record who signed for it, how much, and to whom it’s going).
event SingleTransact(address owner, uint value, address to, bytes data, address created);
// Multi-sig transaction going out of the wallet (record who signed for it last, the operation hash, how much, and to whom it’s going).
event MultiTransact(address owner, bytes32 operation, uint value, address to, bytes data, address created);
// Confirmation still needed for a transaction.
event ConfirmationNeeded(bytes32 operation, address initiator, uint value, address to, bytes data);
}
contract WalletAbi {
// Revokes a prior confirmation of the given operation
function revoke(bytes32 _operation) external;
// Replaces an owner `_from` with another `_to`.
function changeOwner(address _from, address _to) external;
function addOwner(address _owner) external;
function removeOwner(address _owner) external;
function changeRequirement(uint _newRequired) external;
function isOwner(address _addr) constant returns (bool);
function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool);
// (re)sets the daily limit. needs many of the owners to confirm. doesn’t alter the amount already spent today.
function setDailyLimit(uint _newLimit) external;
function execute(address _to, uint _value, bytes _data) external returns (bytes32 o_hash);
function confirm(bytes32 _h) returns (bool o_success);
}
contract WalletLibrary is WalletEvents {
// TYPES
// struct for the status of a pending operation.
struct PendingState {
uint yetNeeded;
uint ownersDone;
uint index;
}
// Transaction structure to remember details of transaction lest it need be saved for a later call.
struct Transaction {
address to;
uint value;
bytes data;
}
// MODIFIERS
// simple single-sig function modifier.
modifier onlyowner {
if (isOwner(msg.sender))
_;
}
// multi-sig function modifier: the operation must have an intrinsic hash in order
// that later attempts can be realised as the same underlying operation and
// thus count as confirmations.
modifier onlymanyowners(bytes32 _operation) {
if (confirmAndCheck(_operation))
_;
}
// METHODS
// gets called when no other function matches
function() payable {
// just being sent some cash?
if (msg.value > 0)
Deposit(msg.sender, msg.value);
}
// constructor is given number of sigs required to do protected “onlymanyowners” transactions
// as well as the selection of addresses capable of confirming them.
function initMultiowned(address[] _owners, uint _required) only_uninitialized {
m_numOwners = _owners.length + 1;
m_owners[1] = uint(msg.sender);
m_ownerIndex[uint(msg.sender)] = 1;
for (uint i = 0; i < _owners.length; ++i)
{
m_owners[2 + i] = uint(_owners[i]);
m_ownerIndex[uint(_owners[i])] = 2 + i;
}
m_required = _required;
}
// Revokes a prior confirmation of the given operation
function revoke(bytes32 _operation) external {
uint ownerIndex = m_ownerIndex[uint(msg.sender)];
// make sure they’re an owner
if (ownerIndex == 0) return;
uint ownerIndexBit = 2**ownerIndex;
var pending = m_pending[_operation];
if (pending.ownersDone & ownerIndexBit > 0) {
pending.yetNeeded++;
pending.ownersDone -= ownerIndexBit;
Revoke(msg.sender, _operation);
}
}
// Replaces an owner `_from` with another `_to`.
function changeOwner(address _from, address _to) onlymanyowners(sha3(msg.data)) external {
if (isOwner(_to)) return;
uint ownerIndex = m_ownerIndex[uint(_from)];
if (ownerIndex == 0) return;
clearPending();
m_owners[ownerIndex] = uint(_to);
m_ownerIndex[uint(_from)] = 0;
m_ownerIndex[uint(_to)] = ownerIndex;
OwnerChanged(_from, _to);
}
function addOwner(address _owner) onlymanyowners(sha3(msg.data)) external {
if (isOwner(_owner)) return;
clearPending();
if (m_numOwners >= c_maxOwners)
reorganizeOwners();
if (m_numOwners >= c_maxOwners)
return;
m_numOwners++;
m_owners[m_numOwners] = uint(_owner);
m_ownerIndex[uint(_owner)] = m_numOwners;
OwnerAdded(_owner);
}
function removeOwner(address _owner) onlymanyowners(sha3(msg.data)) external {
uint ownerIndex = m_ownerIndex[uint(_owner)];
if (ownerIndex == 0) return;
if (m_required > m_numOwners — 1) return;
m_owners[ownerIndex] = 0;
m_ownerIndex[uint(_owner)] = 0;
clearPending();
reorganizeOwners(); //make sure m_numOwner is equal to the number of owners and always points to the optimal free slot
OwnerRemoved(_owner);
}
function changeRequirement(uint _newRequired) onlymanyowners(sha3(msg.data)) external {
if (_newRequired > m_numOwners) return;
m_required = _newRequired;
clearPending();
RequirementChanged(_newRequired);
}
// Gets an owner by 0-indexed position (using numOwners as the count)
function getOwner(uint ownerIndex) external constant returns (address) {
return address(m_owners[ownerIndex + 1]);
}
function isOwner(address _addr) constant returns (bool) {
return m_ownerIndex[uint(_addr)] > 0;
}
function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool) {
var pending = m_pending[_operation];
uint ownerIndex = m_ownerIndex[uint(_owner)];
// make sure they’re an owner
if (ownerIndex == 0) return false;
// determine the bit to set for this owner.
uint ownerIndexBit = 2**ownerIndex;
return !(pending.ownersDone & ownerIndexBit == 0);
}
// constructor — stores initial daily limit and records the present day’s index.
function initDaylimit(uint _limit) only_uninitialized {
m_dailyLimit = _limit;
m_lastDay = today();
}
// (re)sets the daily limit. needs many of the owners to confirm. doesn’t alter the amount already spent today.
function setDailyLimit(uint _newLimit) onlymanyowners(sha3(msg.data)) external {
m_dailyLimit = _newLimit;
}
// resets the amount already spent today. needs many of the owners to confirm.
function resetSpentToday() onlymanyowners(sha3(msg.data)) external {
m_spentToday = 0;
}
// throw unless the contract is not yet initialized.
modifier only_uninitialized { if (m_numOwners > 0) throw; _; }
// constructor — just pass on the owner array to the multiowned and
// the limit to daylimit
function initWallet(address[] _owners, uint _required, uint _daylimit) only_uninitialized {
initDaylimit(_daylimit);
initMultiowned(_owners, _required);
}
// kills the contract sending everything to `_to`.
function kill(address _to) onlymanyowners(sha3(msg.data)) external {
suicide(_to);
}
// Outside-visible transact entry point. Executes transaction immediately if below daily spend limit.
// If not, goes into multisig process. We provide a hash on return to allow the sender to provide
// shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value
// and _data arguments). They still get the option of using them if they want, anyways.
function execute(address _to, uint _value, bytes _data) external onlyowner returns (bytes32 o_hash) {
// first, take the opportunity to check that we’re under the daily limit.
if ((_data.length == 0 && underLimit(_value)) || m_required == 1) {
// yes — just execute the call.
address created;
if (_to == 0) {
created = create(_value, _data);
} else {
if (!_to.call.value(_value)(_data))
throw;
}
SingleTransact(msg.sender, _value, _to, _data, created);
} else {
// determine our operation hash.
o_hash = sha3(msg.data, block.number);
// store if it’s new
if (m_txs[o_hash].to == 0 && m_txs[o_hash].value == 0 && m_txs[o_hash].data.length == 0) {
m_txs[o_hash].to = _to;
m_txs[o_hash].value = _value;
m_txs[o_hash].data = _data;
}
if (!confirm(o_hash)) {
ConfirmationNeeded(o_hash, msg.sender, _value, _to, _data);
}
}
}
function create(uint _value, bytes _code) internal returns (address o_addr) {
assembly {
o_addr := create(_value, add(_code, 0x20), mload(_code))
jumpi(invalidJumpLabel, iszero(extcodesize(o_addr)))
}
}
// confirm a transaction through just the hash. we use the previous transactions map, m_txs, in order
// to determine the body of the transaction from the hash provided.
function confirm(bytes32 _h) onlymanyowners(_h) returns (bool o_success) {
if (m_txs[_h].to != 0 || m_txs[_h].value != 0 || m_txs[_h].data.length != 0) {
address created;
if (m_txs[_h].to == 0) {
created = create(m_txs[_h].value, m_txs[_h].data);
} else {
if (!m_txs[_h].to.call.value(m_txs[_h].value)(m_txs[_h].data))
throw;
}
MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to, m_txs[_h].data, created);
delete m_txs[_h];
return true;
}
}
// INTERNAL METHODS
function confirmAndCheck(bytes32 _operation) internal returns (bool) {
// determine what index the present sender is:
uint ownerIndex = m_ownerIndex[uint(msg.sender)];
// make sure they’re an owner
if (ownerIndex == 0) return;
var pending = m_pending[_operation];
// if we’re not yet working on this operation, switch over and reset the confirmation status.
if (pending.yetNeeded == 0) {
// reset count of confirmations needed.
pending.yetNeeded = m_required;
// reset which owners have confirmed (none) — set our bitmap to 0.
pending.ownersDone = 0;
pending.index = m_pendingIndex.length++;
m_pendingIndex[pending.index] = _operation;
}
// determine the bit to set for this owner.
uint ownerIndexBit = 2**ownerIndex;
// make sure we (the message sender) haven’t confirmed this operation previously.
if (pending.ownersDone & ownerIndexBit == 0) {
Confirmation(msg.sender, _operation);
// ok — check if count is enough to go ahead.
if (pending.yetNeeded <= 1) {
// enough confirmations: reset and run interior.
delete m_pendingIndex[m_pending[_operation].index];
delete m_pending[_operation];
return true;
}
else
{
// not enough: record that this owner in particular confirmed.
pending.yetNeeded — ;
pending.ownersDone |= ownerIndexBit;
}
}
}
function reorganizeOwners() private {
uint free = 1;
while (free < m_numOwners)
{
while (free < m_numOwners && m_owners[free] != 0) free++;
while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners — ;
if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0)
{
m_owners[free] = m_owners[m_numOwners];
m_ownerIndex[m_owners[free]] = free;
m_owners[m_numOwners] = 0;
}
}
}
// checks to see if there is at least `_value` left from the daily limit today. if there is, subtracts it and
// returns true. otherwise just returns false.
function underLimit(uint _value) internal onlyowner returns (bool) {
// reset the spend limit if we’re on a different day to last time.
if (today() > m_lastDay) {
m_spentToday = 0;
m_lastDay = today();
}
// check to see if there’s enough left — if so, subtract and return true.
// overflow protection // dailyLimit check
if (m_spentToday + _value >= m_spentToday && m_spentToday + _value <= m_dailyLimit) {
m_spentToday += _value;
return true;
}
return false;
}
// determines today’s index.
function today() private constant returns (uint) { return now / 1 days; }
function clearPending() internal {
uint length = m_pendingIndex.length;
for (uint i = 0; i < length; ++i) {
delete m_txs[m_pendingIndex[i]];
if (m_pendingIndex[i] != 0)
delete m_pending[m_pendingIndex[i]];
}
delete m_pendingIndex;
}
// FIELDS
address constant _walletLibrary = 0xcafecafecafecafecafecafecafecafecafecafe;
// the number of owners that must confirm the same operation before it is run.
uint public m_required;
// pointer used to find a free slot in m_owners
uint public m_numOwners;
uint public m_dailyLimit;
uint public m_spentToday;
uint public m_lastDay;
// list of owners
uint[256] m_owners;
uint constant c_maxOwners = 250;
// index on the list of owners to allow reverse lookup
mapping(uint => uint) m_ownerIndex;
// the ongoing operations.
mapping(bytes32 => PendingState) m_pending;
bytes32[] m_pendingIndex;
// pending transactions we have at present.
mapping (bytes32 => Transaction) m_txs;
}
contract Wallet is WalletEvents {
// WALLET CONSTRUCTOR
// calls the `initWallet` method of the Library in this context
function Wallet(address[] _owners, uint _required, uint _daylimit) {
// Signature of the Wallet Library’s init function
bytes4 sig = bytes4(sha3(“initWallet(address[],uint256,uint256)”));
address target = _walletLibrary;
// Compute the size of the call data : arrays has 2
// 32bytes for offset and length, plus 32bytes per element ;
// plus 2 32bytes for each uint
uint argarraysize = (2 + _owners.length);
uint argsize = (2 + argarraysize) * 32;
assembly {
// Add the signature first to memory
mstore(0x0, sig)
// Add the call data, which is at the end of the
// code
codecopy(0x4, sub(codesize, argsize), argsize)
// Delegate call to the library
delegatecall(sub(gas, 10000), target, 0x0, add(argsize, 0x4), 0x0, 0x0)
}
}
// METHODS
// gets called when no other function matches
function() payable {
// just being sent some cash?
if (msg.value > 0)
Deposit(msg.sender, msg.value);
else if (msg.data.length > 0)
_walletLibrary.delegatecall(msg.data);
}
// Gets an owner by 0-indexed position (using numOwners as the count)
function getOwner(uint ownerIndex) constant returns (address) {
return address(m_owners[ownerIndex + 1]);
}
// As return statement unavailable in fallback, explicit the method here
function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool) {
return _walletLibrary.delegatecall(msg.data);
}
function isOwner(address _addr) constant returns (bool) {
return _walletLibrary.delegatecall(msg.data);
}
// FIELDS
address constant _walletLibrary = 0xcafecafecafecafecafecafecafecafecafecafe;
// the number of owners that must confirm the same operation before it is run.
uint public m_required;
// pointer used to find a free slot in m_owners
uint public m_numOwners;
uint public m_dailyLimit;
uint public m_spentToday;
uint public m_lastDay;
// list of owners
uint[256] m_owners;
}