6 |
7 |
--------------------------------------------------------------------------------
/code/truffle/Faucet/truffle-config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | networks: {
3 | localnode: { // Whatever network our local node connects to
4 | network_id: "*", // Match any network id
5 | host: "localhost",
6 | port: 8545,
7 | gas: 4700000,
8 | gasPrice: 100000000000,
9 | }
10 | }
11 | };
12 |
--------------------------------------------------------------------------------
/code/auction_dapp/frontend/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": [
3 | ["env", {
4 | "modules": false,
5 | "targets": {
6 | "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
7 | }
8 | }],
9 | "stage-2"
10 | ],
11 | "plugins": ["transform-vue-jsx", "transform-runtime"]
12 | }
13 |
--------------------------------------------------------------------------------
/code/truffle/FaucetEvents/truffle-config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | networks: {
3 | localnode: { // Whatever network our local node connects to
4 | network_id: "*", // Match any network id
5 | host: "localhost",
6 | port: 8545,
7 | gas: 4700000,
8 | gasPrice: 100000000000,
9 | }
10 | }
11 | };
12 |
--------------------------------------------------------------------------------
/code/OpenZeppelin/contracts/SampleToken.sol:
--------------------------------------------------------------------------------
1 | pragma solidity 0.4.23;
2 |
3 | import 'openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol';
4 |
5 | contract SampleToken is MintableToken {
6 | string public name = "SAMPLE TOKEN";
7 | string public symbol = "SAM";
8 | uint8 public decimals = 18;
9 | }
10 |
--------------------------------------------------------------------------------
/code/auction_dapp/backend/contracts/ERC721/ERC721Holder.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.5.16;
2 |
3 | import "./ERC721Receiver.sol";
4 |
5 |
6 | contract ERC721Holder is ERC721Receiver {
7 | function onERC721Received(address, uint256, bytes memory) public returns(bytes4) {
8 | return ERC721_RECEIVED;
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/code/auction_dapp/frontend/.postcssrc.js:
--------------------------------------------------------------------------------
1 | // https://github.com/michael-ciniawsky/postcss-load-config
2 |
3 | module.exports = {
4 | "plugins": {
5 | "postcss-import": {},
6 | "postcss-url": {},
7 | // to edit target browsers: use "browserslist" field in package.json
8 | "autoprefixer": {}
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/code/web3js/raw_tx/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "raw_tx",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "raw_tx_demo.js",
6 | "scripts": {
7 | "test": "raw_tx_demo.js"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "dependencies": {
12 | "ethereumjs-tx": "^2.0.0",
13 | "ethereumjs-util": "^5.1.5",
14 | "rlp": "^2.0.0"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/code/auction_dapp/backend/migrations/2_deploy_contracts.js:
--------------------------------------------------------------------------------
1 | var AuctionRepository = artifacts.require("./AuctionRepository.sol");
2 | var DeedRepository = artifacts.require("./DeedRepository.sol");
3 | // DeedRepository => 0xbb55adc67f64d1e6f08ba7523ecd2eca2ee434a3
4 | module.exports = function(deployer) {
5 | deployer.deploy(AuctionRepository);
6 | deployer.deploy(DeedRepository, "Ultra Auction NFT", "UANFT");
7 | };
8 |
--------------------------------------------------------------------------------
/code/jsonrpc/http/js/README.md:
--------------------------------------------------------------------------------
1 | # Ethereum HTTP Client
2 |
3 | Connect to a node using HTTP(POST) and call the following rpc:
4 | - Get accounts associated with a node(Only you should be able to access these endpoint)
5 | - Get the current block number
6 |
7 |
8 | ## Build Setup
9 |
10 | ``` bash
11 | # install dependencies
12 | npm install
13 |
14 | # run the node script
15 | npm run http
16 |
17 | ```
18 |
--------------------------------------------------------------------------------
/code/jsonrpc/websockets/README.md:
--------------------------------------------------------------------------------
1 | # Ethereum WS Client
2 |
3 | Connect to a node using Websockets and call the following rpc:
4 | - Get accounts associated with a node(Only you should be able to access these endpoint)
5 | - Get the current block number
6 |
7 |
8 | ## Build Setup
9 |
10 | ``` bash
11 | # install dependencies
12 | npm install
13 |
14 | # run the node script
15 | npm run rpc
16 |
17 | ```
18 |
--------------------------------------------------------------------------------
/code/auction_dapp/frontend/README.md:
--------------------------------------------------------------------------------
1 | # Auction Platform Fronten
2 |
3 | > Decentralized Auction Platform
4 |
5 | ## Build Setup
6 |
7 | ``` bash
8 | # install dependencies
9 | npm install
10 |
11 | # serve with hot reload at localhost:8080
12 | npm run dev
13 |
14 | # build for production with minification
15 | npm run build
16 |
17 | # build for production and view the bundle analyzer report
18 | npm run build --report
19 | ```
20 |
21 |
--------------------------------------------------------------------------------
/code/truffle/CallExamples/migrations/2_deploy_contracts.js:
--------------------------------------------------------------------------------
1 | var caller = artifacts.require("caller");
2 | var calledContract = artifacts.require("calledContract");
3 | var calledLibrary = artifacts.require("calledLibrary");
4 |
5 | module.exports = function(deployer) {
6 |
7 | deployer.deploy(calledContract);
8 | deployer.deploy(calledLibrary);
9 |
10 | deployer.link(calledLibrary, [caller]);
11 |
12 | deployer.deploy(caller);
13 | };
14 |
--------------------------------------------------------------------------------
/tools/evm-opcodes-generator/appdx-evm-opcodes-gas-header.asciidoc:
--------------------------------------------------------------------------------
1 | [[me-evm-opcodes-gas-header]]
2 | [appendix]
3 |
4 | == Ethereum EVM Opcodes and gas consumption
5 |
6 | This appendix is based on the consolidation work done by the people of https://github.com/trailofbits/evm-opcodes as a Reference for Ethereum VM (EVM) Opcodes and Instruction information with the following LICENSE https://github.com/trailofbits/evm-opcodes/blob/master/LICENSE.
7 |
8 |
--------------------------------------------------------------------------------
/code/truffle/console/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "web3_console",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "nonce.js",
6 | "directories": {
7 | "test": "test"
8 | },
9 | "scripts": {
10 | "test": "echo \"Error: no test specified\" && exit 1"
11 | },
12 | "author": "",
13 | "license": "ISC",
14 | "dependencies": {
15 | "dotenv": "^5.0.1",
16 | "ethereumjs-wallet": "^0.6.0",
17 | "truffle-wallet-provider": "0.0.5"
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/code/truffle/Faucet/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "faucet",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "truffle-config.js",
6 | "directories": {
7 | "test": "test"
8 | },
9 | "scripts": {
10 | "test": "echo \"Error: no test specified\" && exit 1"
11 | },
12 | "author": "",
13 | "license": "ISC",
14 | "dependencies": {
15 | "dotenv": "^5.0.0",
16 | "ethereumjs-wallet": "^0.6.0",
17 | "truffle-wallet-provider": "0.0.5"
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/code/truffle/FaucetEvents/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "faucet",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "truffle-config.js",
6 | "directories": {
7 | "test": "test"
8 | },
9 | "scripts": {
10 | "test": "echo \"Error: no test specified\" && exit 1"
11 | },
12 | "author": "",
13 | "license": "ISC",
14 | "dependencies": {
15 | "dotenv": "^5.0.0",
16 | "ethereumjs-wallet": "^0.6.0",
17 | "truffle-wallet-provider": "0.0.5"
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/code/truffle/CallExamples/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "contractcalls",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "truffle-config.js",
6 | "directories": {
7 | "test": "test"
8 | },
9 | "scripts": {
10 | "test": "echo \"Error: no test specified\" && exit 1"
11 | },
12 | "author": "",
13 | "license": "ISC",
14 | "devDependencies": {
15 | "dotenv": "^5.0.1",
16 | "ethereumjs-wallet": "^0.6.0",
17 | "truffle-wallet-provider": "0.0.5"
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/code/truffle/METoken/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "metoken",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "truffle.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "dependencies": {
12 | "zeppelin-solidity": "^1.6.0"
13 | },
14 | "devDependencies": {
15 | "dotenv": "^5.0.0",
16 | "ethereumjs-wallet": "^0.6.0",
17 | "truffle-wallet-provider": "0.0.5"
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/code/truffle/METoken_Faucet/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "metoken",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "truffle.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "dependencies": {
12 | "zeppelin-solidity": "^1.6.0"
13 | },
14 | "devDependencies": {
15 | "dotenv": "^5.0.0",
16 | "ethereumjs-wallet": "^0.6.0",
17 | "truffle-wallet-provider": "0.0.5"
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/code/truffle/METoken_METFaucet/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "metoken",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "truffle.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "dependencies": {
12 | "openzeppelin-solidity": "^1.6.0"
13 | },
14 | "devDependencies": {
15 | "dotenv": "^5.0.0",
16 | "ethereumjs-wallet": "^0.6.0",
17 | "truffle-wallet-provider": "0.0.5"
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/code/truffle/FaucetReentryAttack/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "faucet",
3 | "version": "1.0.0",
4 | "main": "truffle-config.js",
5 | "directories": {
6 | "test": "test"
7 | },
8 | "scripts": {
9 | "test": "echo \"Error: no test specified\" && exit 1"
10 | },
11 | "author": "",
12 | "license": "ISC",
13 | "dependencies": {},
14 | "devDependencies": {
15 | "dotenv": "^5.0.1",
16 | "ethereumjs-wallet": "^0.6.0",
17 | "truffle-wallet-provider": "0.0.5"
18 | },
19 | "description": ""
20 | }
21 |
--------------------------------------------------------------------------------
/code/aws/genesis.json:
--------------------------------------------------------------------------------
1 | {
2 | "config": {
3 | "chainId": 15,
4 | "homesteadBlock": 0,
5 | "eip155Block": 0,
6 | "eip158Block": 0
7 | },
8 | "nonce": "0x0000000000000042",
9 | "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
10 | "difficulty": "0x4000",
11 | "alloc": {},
12 | "coinbase": "0x0000000000000000000000000000000000000000",
13 | "timestamp": "0x00",
14 | "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
15 | "gasLimit": "0xffffffff"
16 | }
--------------------------------------------------------------------------------
/code/truffle/METoken_METFaucet/migrations/2_deploy_contracts.js:
--------------------------------------------------------------------------------
1 | var METoken = artifacts.require("METoken");
2 | var METFaucet = artifacts.require("METFaucet");
3 | var owner = web3.eth.accounts[0];
4 |
5 | module.exports = function(deployer) {
6 |
7 | // Deploy the METoken contract first
8 | deployer.deploy(METoken, {from: owner}).then(function() {
9 | // then deploy METFaucet and pass the address of METoken
10 | // and the address of the owner of all the MET who will approve METFaucet
11 | return deployer.deploy(METFaucet, METoken.address, owner);
12 | });
13 | }
14 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | before_install:
2 | - sudo apt-get -qq update
3 | - sudo apt-get install -y pandoc
4 |
5 | install: true
6 |
7 | script:
8 | - echo "OPCODES and Gas appendix auto generation started"
9 | - ls -l ./tools/evm-opcodes-generator
10 | - cd ./tools/evm-opcodes-generator
11 | - ./appdx-evm-opcodes-gas-generator.sh
12 | - ls -l
13 | - cat appdx-evm-opcodes-gas.asciidoc
14 | - echo "OPCODES and Gas appendix auto generation finished"
15 | - echo "Marker for testing travis"
16 |
17 | notifications:
18 | email: false
19 |
20 | branches:
21 | only:
22 | - evm-opcodes-appendix
23 |
--------------------------------------------------------------------------------
/code/auction_dapp/frontend/src/router/index.js:
--------------------------------------------------------------------------------
1 | import Vue from 'vue'
2 | import Router from 'vue-router'
3 | import Home from '@/components/Home'
4 | import Auction from '@/components/Auction'
5 |
6 | Vue.use(Router)
7 |
8 | export default new Router({
9 | routes: [
10 | {
11 | path: '/',
12 | name: 'Home',
13 | component: Home
14 | },
15 | {
16 | path: '/auctions/:id',
17 | name: 'Auction',
18 | component: Auction
19 | }
20 | ],
21 | mode: 'history',
22 | scrollBehavior (to, from, savedPosition) {
23 | return { x: 0, y: 0 }
24 | }
25 | })
26 |
--------------------------------------------------------------------------------
/code/truffle/Faucet/contracts/Faucet.sol:
--------------------------------------------------------------------------------
1 | // Version of Solidity compiler this program was written for
2 | pragma solidity ^0.4.19;
3 |
4 | // Our first contract is a faucet!
5 | contract Faucet {
6 |
7 | // Give out ether to anyone who asks
8 | function withdraw(uint withdraw_amount) public {
9 |
10 | // Limit withdrawal amount
11 | require(withdraw_amount <= 100000000000000000);
12 |
13 | // Send the amount to the address that requested it
14 | msg.sender.transfer(withdraw_amount);
15 | }
16 |
17 | // Accept any incoming amount
18 | function () external payable {}
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/code/truffle/METoken_Faucet/contracts/Faucet.sol:
--------------------------------------------------------------------------------
1 | // Version of Solidity compiler this program was written for
2 | pragma solidity ^0.4.19;
3 |
4 | // Our first contract is a faucet!
5 | contract Faucet {
6 |
7 | // Give out ether to anyone who asks
8 | function withdraw(uint withdraw_amount) public {
9 |
10 | // Limit withdrawal amount
11 | require(withdraw_amount <= 100000000000000000);
12 |
13 | // Send the amount to the address that requested it
14 | msg.sender.transfer(withdraw_amount);
15 | }
16 |
17 | // Accept any incoming amount
18 | function () external payable {}
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/code/truffle/METoken/contracts/METoken.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.21;
2 |
3 | import 'openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol';
4 |
5 | contract METoken is StandardToken {
6 | string public constant name = 'Mastering Ethereum Token';
7 | string public constant symbol = 'MET';
8 | uint8 public constant decimals = 2;
9 | uint constant _initial_supply = 2100000000;
10 |
11 | function METoken() public {
12 | totalSupply_ = _initial_supply;
13 | balances[msg.sender] = _initial_supply;
14 | emit Transfer(address(0), msg.sender, _initial_supply);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/code/truffle/METoken_Faucet/contracts/METoken.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.18;
2 |
3 | import 'openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol';
4 |
5 | contract METoken is StandardToken {
6 | string public constant name = 'Mastering Ethereum Token';
7 | string public constant symbol = 'MET';
8 | uint8 public constant decimals = 2;
9 | uint constant _initial_supply = 2100000000;
10 |
11 | function METoken() public {
12 | totalSupply_ = _initial_supply;
13 | balances[msg.sender] = _initial_supply;
14 | Transfer(address(0), msg.sender, _initial_supply);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/code/truffle/METoken_METFaucet/contracts/METoken.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.18;
2 |
3 | import 'openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol';
4 |
5 | contract METoken is StandardToken {
6 | string public constant name = 'Mastering Ethereum Token';
7 | string public constant symbol = 'MET';
8 | uint8 public constant decimals = 2;
9 | uint constant _initial_supply = 2100000000;
10 |
11 | function METoken() public {
12 | totalSupply_ = _initial_supply;
13 | balances[msg.sender] = _initial_supply;
14 | Transfer(address(0), msg.sender, _initial_supply);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/code/Solidity/Faucet.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: CC-BY-SA-4.0
2 |
3 | // Version of Solidity compiler this program was written for
4 | pragma solidity 0.6.4;
5 |
6 | // Our first contract is a faucet!
7 | contract Faucet {
8 | // Accept any incoming amount
9 | receive() external payable {}
10 |
11 | // Give out ether to anyone who asks
12 | function withdraw(uint withdraw_amount) public {
13 | // Limit withdrawal amount
14 | require(withdraw_amount <= 100000000000000000);
15 |
16 | // Send the amount to the address that requested it
17 | msg.sender.transfer(withdraw_amount);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/code/Solidity/Faucet2.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: CC-BY-SA-4.0
2 |
3 | // Version of Solidity compiler this program was written for
4 | pragma solidity ^0.6.4;
5 |
6 | // Our first contract is a faucet!
7 | contract Faucet {
8 | // Accept any incoming amount
9 | receive() external payable {}
10 |
11 | // Give out ether to anyone who asks
12 | function withdraw(uint withdraw_amount) public {
13 | // Limit withdrawal amount
14 | require(withdraw_amount <= 100000000000000000);
15 |
16 | // Send the amount to the address that requested it
17 | msg.sender.transfer(withdraw_amount);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/code/truffle/Faucet/contracts/Migrations.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.17;
2 |
3 | contract Migrations {
4 | address public owner;
5 | uint public last_completed_migration;
6 |
7 | modifier restricted() {
8 | if (msg.sender == owner) _;
9 | }
10 |
11 | function Migrations() public {
12 | owner = msg.sender;
13 | }
14 |
15 | function setCompleted(uint completed) public restricted {
16 | last_completed_migration = completed;
17 | }
18 |
19 | function upgrade(address new_address) public restricted {
20 | Migrations upgraded = Migrations(new_address);
21 | upgraded.setCompleted(last_completed_migration);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/code/truffle/METoken/contracts/Migrations.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.17;
2 |
3 | contract Migrations {
4 | address public owner;
5 | uint public last_completed_migration;
6 |
7 | modifier restricted() {
8 | if (msg.sender == owner) _;
9 | }
10 |
11 | function Migrations() public {
12 | owner = msg.sender;
13 | }
14 |
15 | function setCompleted(uint completed) public restricted {
16 | last_completed_migration = completed;
17 | }
18 |
19 | function upgrade(address new_address) public restricted {
20 | Migrations upgraded = Migrations(new_address);
21 | upgraded.setCompleted(last_completed_migration);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/code/truffle/console/contracts/Migrations.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.17;
2 |
3 | contract Migrations {
4 | address public owner;
5 | uint public last_completed_migration;
6 |
7 | modifier restricted() {
8 | if (msg.sender == owner) _;
9 | }
10 |
11 | function Migrations() public {
12 | owner = msg.sender;
13 | }
14 |
15 | function setCompleted(uint completed) public restricted {
16 | last_completed_migration = completed;
17 | }
18 |
19 | function upgrade(address new_address) public restricted {
20 | Migrations upgraded = Migrations(new_address);
21 | upgraded.setCompleted(last_completed_migration);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/code/truffle/CallExamples/contracts/Migrations.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.17;
2 |
3 | contract Migrations {
4 | address public owner;
5 | uint public last_completed_migration;
6 |
7 | modifier restricted() {
8 | if (msg.sender == owner) _;
9 | }
10 |
11 | function Migrations() public {
12 | owner = msg.sender;
13 | }
14 |
15 | function setCompleted(uint completed) public restricted {
16 | last_completed_migration = completed;
17 | }
18 |
19 | function upgrade(address new_address) public restricted {
20 | Migrations upgraded = Migrations(new_address);
21 | upgraded.setCompleted(last_completed_migration);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/code/truffle/FaucetEvents/contracts/Migrations.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.17;
2 |
3 | contract Migrations {
4 | address public owner;
5 | uint public last_completed_migration;
6 |
7 | modifier restricted() {
8 | if (msg.sender == owner) _;
9 | }
10 |
11 | function Migrations() public {
12 | owner = msg.sender;
13 | }
14 |
15 | function setCompleted(uint completed) public restricted {
16 | last_completed_migration = completed;
17 | }
18 |
19 | function upgrade(address new_address) public restricted {
20 | Migrations upgraded = Migrations(new_address);
21 | upgraded.setCompleted(last_completed_migration);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/code/truffle/METoken_Faucet/contracts/Migrations.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.17;
2 |
3 | contract Migrations {
4 | address public owner;
5 | uint public last_completed_migration;
6 |
7 | modifier restricted() {
8 | if (msg.sender == owner) _;
9 | }
10 |
11 | function Migrations() public {
12 | owner = msg.sender;
13 | }
14 |
15 | function setCompleted(uint completed) public restricted {
16 | last_completed_migration = completed;
17 | }
18 |
19 | function upgrade(address new_address) public restricted {
20 | Migrations upgraded = Migrations(new_address);
21 | upgraded.setCompleted(last_completed_migration);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/code/truffle/METoken_METFaucet/contracts/Migrations.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.17;
2 |
3 | contract Migrations {
4 | address public owner;
5 | uint public last_completed_migration;
6 |
7 | modifier restricted() {
8 | if (msg.sender == owner) _;
9 | }
10 |
11 | function Migrations() public {
12 | owner = msg.sender;
13 | }
14 |
15 | function setCompleted(uint completed) public restricted {
16 | last_completed_migration = completed;
17 | }
18 |
19 | function upgrade(address new_address) public restricted {
20 | Migrations upgraded = Migrations(new_address);
21 | upgraded.setCompleted(last_completed_migration);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/code/auction_dapp/backend/contracts/utils/math/Math.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.5.16;
2 |
3 |
4 | /**
5 | * @title Math
6 | * @dev Assorted math operations
7 | */
8 | library Math {
9 | function max64(uint64 a, uint64 b) internal pure returns (uint64) {
10 | return a >= b ? a : b;
11 | }
12 |
13 | function min64(uint64 a, uint64 b) internal pure returns (uint64) {
14 | return a < b ? a : b;
15 | }
16 |
17 | function max256(uint256 a, uint256 b) internal pure returns (uint256) {
18 | return a >= b ? a : b;
19 | }
20 |
21 | function min256(uint256 a, uint256 b) internal pure returns (uint256) {
22 | return a < b ? a : b;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/code/auction_dapp/backend/contracts/ERC721/DeprecatedERC721.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.5.16;
2 |
3 | import "./ERC721.sol";
4 |
5 |
6 | /**
7 | * @title ERC-721 methods shipped in OpenZeppelin v1.7.0, removed in the latest version of the standard
8 | * @dev Only use this interface for compatibility with previously deployed contracts
9 | * @dev Use ERC721 for interacting with new contracts which are standard-compliant
10 | */
11 | contract DeprecatedERC721 is ERC721 {
12 | function takeOwnership(uint256 _tokenId) public;
13 | function transfer(address _to, uint256 _tokenId) public;
14 | function tokensOf(address _owner) public view returns (uint256[] memory);
15 | }
16 |
--------------------------------------------------------------------------------
/code/OpenZeppelin/contracts/SampleCrowdsale.sol:
--------------------------------------------------------------------------------
1 | pragma solidity 0.4.23;
2 |
3 | import './SampleToken.sol';
4 | import 'openzeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol';
5 | import 'openzeppelin-solidity/contracts/crowdsale/ \
6 | distribution/PostDeliveryCrowdsale.sol';
7 |
8 | contract SampleCrowdsale is PostDeliveryCrowdsale, MintedCrowdsale {
9 |
10 | constructor(
11 | uint256 _openingTime,
12 | uint256 _closingTime
13 | uint256 _rate,
14 | address _wallet,
15 | MintableToken _token
16 | )
17 | public
18 | Crowdsale(_rate, _wallet, _token)
19 | PostDeliveryCrowdsale(_openingTime, _closingTime)
20 | {
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/code/auction_dapp/backend/contracts/Migrations.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.5.16;
2 |
3 | contract Migrations {
4 | address public owner;
5 | uint public last_completed_migration;
6 |
7 | modifier restricted() {
8 | if (msg.sender == owner) _;
9 | }
10 |
11 | constructor() public {
12 | owner = msg.sender;
13 | }
14 |
15 | function setCompleted(uint completed) public restricted {
16 | last_completed_migration = completed;
17 | }
18 |
19 | function upgrade(address new_address) public restricted {
20 | Migrations upgraded = Migrations(new_address);
21 | upgraded.setCompleted(last_completed_migration);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/code/auction_dapp/frontend/build/vue-loader.conf.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 | const utils = require('./utils')
3 | const config = require('../config')
4 | const isProduction = process.env.NODE_ENV === 'production'
5 | const sourceMapEnabled = isProduction
6 | ? config.build.productionSourceMap
7 | : config.dev.cssSourceMap
8 |
9 | module.exports = {
10 | loaders: utils.cssLoaders({
11 | sourceMap: sourceMapEnabled,
12 | extract: isProduction
13 | }),
14 | cssSourceMap: sourceMapEnabled,
15 | cacheBusting: config.dev.cacheBusting,
16 | transformToRequire: {
17 | video: ['src', 'poster'],
18 | source: 'src',
19 | img: 'src',
20 | image: 'xlink:href'
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/contrib/example.asciidoc:
--------------------------------------------------------------------------------
1 | ////
2 | Source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
3 | License: CC0
4 | Added By: @aantonop
5 | ////
6 |
7 |
8 | = The ERC20 Token Standard
9 |
10 | The ERC20 standard allows for the implementation of a standard API for tokens within smart contracts. This standard provides basic functionality to transfer tokens, as well as allow tokens to be approved so they can be spent by another on-chain third party. It is documented in https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md[EIP-20 Token Standard]
11 |
12 | == What Are Tokens?
13 |
14 | Tokens are abstractions that represent ownership, access or value...
15 |
16 | == Known Problems with ERC20 Tokens
17 |
18 | == Additional Standards (ERC223)
19 |
20 | === Rationale
21 |
--------------------------------------------------------------------------------
/code/OpenZeppelin/migrations/2_deploy_contracts.js:
--------------------------------------------------------------------------------
1 | const SampleCrowdsale = artifacts.require('./SampleCrowdsale.sol');
2 | const SampleToken = artifacts.require('./SampleToken.sol');
3 |
4 | module.exports = function(deployer, network, accounts) {
5 | const openingTime = web3.eth.getBlock('latest').timestamp + 2; // 2s in future
6 | const closingTime = openingTime + 86400 * 20; // 20 days
7 | const rate = new web3.BigNumber(1000);
8 | const wallet = accounts[1];
9 |
10 | return deployer
11 | .then(() => {
12 | return deployer.deploy(SampleToken);
13 | })
14 | .then(() => {
15 | return deployer.deploy(
16 | SampleCrowdsale,
17 | openingTime,
18 | closingTime,
19 | rate,
20 | wallet,
21 | SampleToken.address
22 | );
23 | });
24 | };
25 |
--------------------------------------------------------------------------------
/code/truffle/METoken_METFaucet/test/test_approve_transferFrom.js:
--------------------------------------------------------------------------------
1 | var METoken = artifacts.require("METoken");
2 | var METFaucet = artifacts.require("METFaucet");
3 |
4 | contract('METoken', function(accounts) {
5 | var Alice = accounts[0];
6 | var Bob = accounts[1];
7 |
8 |
9 | it("should approve METFaucet for up to 1000 MET ", function() {
10 | return METoken.deployed().then(instance => {
11 | instance.approve(METFaucet.address, 100000).then(function(result) {
12 | assert(result.logs[0].event, "Approval", "Expected approval event")
13 | });
14 | });
15 | });
16 | it("should allow Bob to withdraw 10 MET from METFaucet", function() {
17 | return METFaucet.deployed().then(instance => {
18 | instance.withdraw(1000, {from: Bob}).then(function(result) {
19 | console.log(result.logs);
20 | });
21 | });
22 | });
23 | });
24 |
--------------------------------------------------------------------------------
/code/auction_dapp/frontend/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Auction Dapp
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
22 |
--------------------------------------------------------------------------------
/code/jsonrpc/websockets/app.js:
--------------------------------------------------------------------------------
1 | const WebSocket = require('ws');
2 | const wsEndpoint = "ws://172.16.163.129:8546"
3 | const ws = new WebSocket(wsEndpoint);
4 |
5 | const requests = [
6 | {
7 | // Get the current block number
8 | jsonrpc: "2.0",
9 | method: "eth_blockNumber",
10 | params: [],
11 | id: 1234
12 | },
13 | {
14 | // Get accounts on this node
15 | jsonrpc: "2.0",
16 | method: "eth_accounts",
17 | params: [],
18 | id: 12345
19 | }
20 | ]
21 |
22 | // Connection is established
23 | ws.on('open', function open() {
24 | requests.map((req) => {
25 | console.log("Call procedure: ", req.method)
26 | ws.send(JSON.stringify(req))
27 | })
28 | });
29 |
30 | // Listen for incoming messages
31 | ws.on('message', function incoming(data) {
32 | console.log("Ethereum node response: ", JSON.parse(data));
33 | });
34 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | # CC-BY-SA
2 |
3 | ## Creative Commons Attribution-ShareAlike 4.0
4 |
5 | Mastering Ethereum by Andreas M. Antonopoulos, Gavin Wood is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License. Based on a work at https://github.com/ethereumbook/ethereumbook.
6 |
--------------------------------------------------------------------------------
/code/jsonrpc/http/js/index.js:
--------------------------------------------------------------------------------
1 | const axios = require("axios")
2 | const url = "http://172.16.163.129:8545"
3 |
4 | const requests = [
5 | {
6 | // Get the current block number
7 | jsonrpc: "2.0",
8 | method: "eth_blockNumber",
9 | params: [],
10 | id: 1234
11 | },
12 | {
13 | // Get accounts on this node
14 | jsonrpc: "2.0",
15 | method: "eth_accounts",
16 | params: [],
17 | id: 12345
18 | }
19 | ]
20 |
21 | requests.map(async (request) => {
22 | try {
23 | // send the request
24 | console.log("Call procedure: ", request.method)
25 | const result = await axios.post(url, request)
26 |
27 | // check for errors
28 | if(result.data.error)
29 | console.log("Error: ", result.data.error.message)
30 | else
31 | console.log("Ethereum node response: ", result.data)
32 | } catch (e) {
33 | console.log("Error while connecting to the remote server", e)
34 | }
35 |
36 | })
--------------------------------------------------------------------------------
/code/Solidity/Faucet3.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: CC-BY-SA-4.0
2 |
3 | // Version of Solidity compiler this program was written for
4 | pragma solidity ^0.6.4;
5 |
6 | // Our first contract is a faucet!
7 | contract Faucet {
8 | address payable owner;
9 |
10 | // Contract constructor: set owner
11 | constructor() public {
12 | owner = msg.sender;
13 | }
14 |
15 | // Accept any incoming amount
16 | receive() external payable {}
17 |
18 | // Contract destructor
19 | function destroy() public {
20 | require(msg.sender == owner);
21 | selfdestruct(owner);
22 | }
23 |
24 | // Give out ether to anyone who asks
25 | function withdraw(uint withdraw_amount) public {
26 | // Limit withdrawal amount
27 | require(withdraw_amount <= 0.1 ether);
28 |
29 | // Send the amount to the address that requested it
30 | msg.sender.transfer(withdraw_amount);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/theme/epub/layout.html:
--------------------------------------------------------------------------------
1 | {{ doctype }}
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | {{ title }}
11 |
12 |
13 | {{ content }}
14 |
15 |
16 |
--------------------------------------------------------------------------------
/theme/mobi/layout.html:
--------------------------------------------------------------------------------
1 | {{ doctype }}
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | {{ title }}
11 |
12 |
13 | {{ content }}
14 |
15 |
16 |
--------------------------------------------------------------------------------
/code/truffle/METoken/test/METoken.test.js:
--------------------------------------------------------------------------------
1 | const METoken = artifacts.require("METoken");
2 |
3 | contract('METoken', accounts => {
4 |
5 | beforeEach(async function () {
6 | InstanceMEToken = await METoken.new();
7 | });
8 |
9 | it('has a name', async function () {
10 | const name = await InstanceMEToken.name();
11 | assert.notEqual(name, "", "token name shouldn't be empty");
12 | });
13 |
14 | it('has a symbol', async function () {
15 | const symbol = await InstanceMEToken.symbol();
16 | assert.notEqual(symbol, "", "token symbol shouldn't be empty");
17 | });
18 |
19 | it('has decimals', async function () {
20 | const decimals = await InstanceMEToken.decimals();
21 | assert.notEqual(decimals, "", "token decimals shouldn't be empty");
22 | });
23 |
24 | it('owner has 2100000000 tokens', async function () {
25 | const balance = await InstanceMEToken.balanceOf(accounts[0]);
26 | assert.equal(balance, 2100000000, "owner doesn't have 2100000000 tokens");
27 | });
28 | });
--------------------------------------------------------------------------------
/misc/readme_wordcount.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function
2 | import glob
3 | import re
4 |
5 | markup_files = glob.glob('*.asciidoc')
6 |
7 | wordcount = {}
8 | wordcount_sum = 0
9 |
10 | for markup_file in markup_files:
11 | markup_f = open(markup_file, 'r')
12 | markup_contents = markup_f.read()
13 | markup_f.close()
14 | wc = len(markup_contents.strip().split())
15 | wordcount_sum += wc
16 | wordcount[markup_file] = wc
17 | print(wc, "\t", markup_file)
18 | print(wordcount_sum)
19 |
20 | readme_f = open('README.md','r')
21 | readme = readme_f.read()
22 | readme_f.close()
23 |
24 | wc_tag_re = re.compile("\| +(\[.*\])\((.*asciidoc)\) +\| +[\#]+ +\|(.*)$")
25 |
26 | readme_f = open('README.md','w')
27 | for line in readme.splitlines():
28 | match_re = wc_tag_re.match(line)
29 | if match_re:
30 | wordcount_bar = "#" * ((wordcount[match_re.group(2)]//500) + 1)
31 | line = match_re.expand("| \g<1>(\g<2>) | " + wordcount_bar + " |\g<3>")
32 | readme_f.write(line+"\n")
33 | readme_f.close()
34 |
--------------------------------------------------------------------------------
/code/web3js/raw_tx/raw_tx_demo.js:
--------------------------------------------------------------------------------
1 | // Load requirements first:
2 | //
3 | // npm init
4 | // npm install ethereumjs-tx
5 | //
6 | // Run with: $ node raw_tx_demo.js
7 | const ethTx = require('ethereumjs-tx').Transaction;
8 |
9 | const txData = {
10 | nonce: '0x0',
11 | gasPrice: '0x09184e72a000',
12 | gasLimit: '0x30000',
13 | to: '0xb0920c523d582040f2bcb1bd7fb1c7c1ecebdb34',
14 | value: '0x00',
15 | data: '',
16 | v: "0x1c", // Ethereum mainnet chainID
17 | r: 0,
18 | s: 0
19 | };
20 |
21 | tx = new ethTx(txData);
22 | console.log('RLP-Encoded Tx: 0x' + tx.serialize().toString('hex'))
23 |
24 | txHash = tx.hash(); // This step encodes into RLP and calculates the hash
25 | console.log('Tx Hash: 0x' + txHash.toString('hex'))
26 |
27 | // Sign transaction
28 | const privKey = Buffer.from(
29 | '91c8360c4cb4b5fac45513a7213f31d4e4a7bfcb4630e9fbf074f42a203ac0b9', 'hex');
30 | tx.sign(privKey);
31 |
32 | serializedTx = tx.serialize();
33 | rawTx = 'Signed Raw Transaction: 0x' + serializedTx.toString('hex');
34 | console.log(rawTx)
35 |
--------------------------------------------------------------------------------
/code/Solidity/Faucet4.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: CC-BY-SA-4.0
2 |
3 | // Version of Solidity compiler this program was written for
4 | pragma solidity ^0.6.4;
5 |
6 | // Our first contract is a faucet!
7 | contract Faucet {
8 | address payable owner;
9 |
10 | // Contract constructor: set owner
11 | constructor() public {
12 | owner = msg.sender;
13 | }
14 |
15 | // Access control modifier
16 | modifier onlyOwner {
17 | require(msg.sender == owner);
18 | _;
19 | }
20 |
21 | // Accept any incoming amount
22 | receive() external payable {}
23 |
24 | // Contract destructor
25 | function destroy() public onlyOwner {
26 | selfdestruct(owner);
27 | }
28 |
29 | // Give out ether to anyone who asks
30 | function withdraw(uint withdraw_amount) public {
31 | // Limit withdrawal amount
32 | require(withdraw_amount <= 0.1 ether);
33 |
34 | // Send the amount to the address that requested it
35 | msg.sender.transfer(withdraw_amount);
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/code/truffle/FaucetEvents/gas_estimates.js:
--------------------------------------------------------------------------------
1 | var FaucetContract = artifacts.require("Faucet.sol");
2 |
3 | FaucetContract.web3.eth.getGasPrice(function(error, result) {
4 | var gasPrice = Number(result);
5 | console.log("Gas Price is " + gasPrice + " wei"); // "10000000000000"
6 |
7 | // Get the contract instance
8 | FaucetContract.deployed().then(function(FaucetContractInstance) {
9 |
10 | // Use the keyword 'estimateGas' after the function name to get the gas estimation for this particular function (aprove)
11 | FaucetContractInstance.send(web3.utils.toWei(1, "ether"));
12 | return FaucetContractInstance.withdraw.estimateGas(web3.utils.toWei(0.1, "ether"));
13 |
14 | }).then(function(result) {
15 | var gas = Number(result);
16 |
17 | console.log("gas estimation = " + gas + " units");
18 | console.log("gas cost estimation = " + (gas * gasPrice) + " wei");
19 | console.log("gas cost estimation = " + FaucetContract.web3.utils.fromWei((gas * gasPrice), 'ether') + " ether");
20 | });
21 | });
22 |
--------------------------------------------------------------------------------
/code/auction_dapp/frontend/src/config.js:
--------------------------------------------------------------------------------
1 | var DeedRepository = require('./contracts/DeedRepository')
2 | var AuctionRepository = require('./contracts/AuctionRepository')
3 |
4 | module.exports = {
5 | JSONRPC_ENDPOINT: 'http://52.59.238.144:8545',
6 | JSONRPC_WS_ENDPOINT: 'ws://52.59.238.144:8546', //'ws://52.59.238.144:8546',
7 | BZZ_ENDPOINT: 'http://52.59.238.144:8500',
8 | SHH_ENDPOINT: 'ws://52.59.238.144:8546',
9 |
10 | DEEDREPOSITORY_ADDRESS: '0xfc35c45cd57661197d0bb19399c9d3ede1c50dcc',
11 | AUCTIONREPOSITORY_ADDRESS: '0xefbebbf64a570f7b94f168430f45ecbb87546f06',
12 |
13 | DEEDREPOSITORY_ABI: DeedRepository.abi,
14 | AUCTIONREPOSITORY_ABI: AuctionRepository.abi,
15 |
16 | GAS_AMOUNT: 500000,
17 |
18 | //whisper settings
19 | WHISPER_SHARED_KEY: '0x8bda3abeb454847b515fa9b404cede50b1cc63cfdeddd4999d074284b4c21e15'
20 |
21 | }
22 |
23 | // web3.eth.sendTransaction({from: web3.eth.accounts[0], to: "0x6f0023D1CFe5A7A56F96e61E0169B775Ac97f90E" , value: web3.utils.toWei(1, 'ether'), gasLimit: 21000, gasPrice: 20000000000})
24 |
--------------------------------------------------------------------------------
/code/truffle/CallExamples/contracts/CallExamples.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.22;
2 |
3 | contract calledContract {
4 | event callEvent(address sender, address origin, address from);
5 | function calledFunction() public {
6 | emit callEvent(msg.sender, tx.origin, this);
7 | }
8 | }
9 |
10 | library calledLibrary {
11 | event callEvent(address sender, address origin, address from);
12 | function calledFunction() public {
13 | emit callEvent(msg.sender, tx.origin, this);
14 | }
15 | }
16 |
17 | contract caller {
18 |
19 | function make_calls(calledContract _calledContract) public {
20 |
21 | // Calling calledContract and calledLibrary directly
22 | _calledContract.calledFunction();
23 | calledLibrary.calledFunction();
24 |
25 | // Low-level calls using the address object for calledContract
26 | require(address(_calledContract).
27 | call(bytes4(keccak256("calledFunction()"))));
28 | require(address(_calledContract).
29 | delegatecall(bytes4(keccak256("calledFunction()"))));
30 |
31 |
32 |
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/code/Solidity/Faucet5.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: CC-BY-SA-4.0
2 |
3 | // Version of Solidity compiler this program was written for
4 | pragma solidity ^0.6.4;
5 |
6 | contract Owned {
7 | address payable owner;
8 |
9 | // Contract constructor: set owner
10 | constructor() public {
11 | owner = msg.sender;
12 | }
13 |
14 | // Access control modifier
15 | modifier onlyOwner {
16 | require(msg.sender == owner);
17 | _;
18 | }
19 | }
20 |
21 | contract Mortal is Owned {
22 | // Contract destructor
23 | function destroy() public onlyOwner {
24 | selfdestruct(owner);
25 | }
26 | }
27 |
28 | contract Faucet is Mortal {
29 | // Accept any incoming amount
30 | receive() external payable {}
31 |
32 | // Give out ether to anyone who asks
33 | function withdraw(uint withdraw_amount) public {
34 | // Limit withdrawal amount
35 | require(withdraw_amount <= 0.1 ether);
36 |
37 | // Send the amount to the address that requested it
38 | msg.sender.transfer(withdraw_amount);
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/code/truffle/METoken_METFaucet/contracts/METFaucet.sol:
--------------------------------------------------------------------------------
1 | // Version of Solidity compiler this program was written for
2 | pragma solidity ^0.4.19;
3 |
4 | import 'openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol';
5 |
6 |
7 | // A faucet for ERC20 token MET
8 | contract METFaucet {
9 |
10 | StandardToken public METoken;
11 | address public METOwner;
12 |
13 | // METFaucet constructor, provide the address of METoken contract and
14 | // the owner address we will be approved to transferFrom
15 | function METFaucet(address _METoken, address _METOwner) public {
16 |
17 | // Initialize the METoken from the address provided
18 | METoken = StandardToken(_METoken);
19 | METOwner = _METOwner;
20 | }
21 |
22 | function withdraw(uint withdraw_amount) public {
23 |
24 | // Limit withdrawal amount to 10 MET
25 | require(withdraw_amount <= 1000);
26 |
27 | // Use the transferFrom function of METoken
28 | METoken.transferFrom(METOwner, msg.sender, withdraw_amount);
29 | }
30 |
31 | // REJECT any incoming ether
32 | function () external payable { revert(); }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/code/Solidity/Faucet6.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: CC-BY-SA-4.0
2 |
3 | // Version of Solidity compiler this program was written for
4 | pragma solidity ^0.6.4;
5 |
6 | contract Owned {
7 | address payable owner;
8 |
9 | // Contract constructor: set owner
10 | constructor() public {
11 | owner = msg.sender;
12 | }
13 |
14 | // Access control modifier
15 | modifier onlyOwner {
16 | require(msg.sender == owner, "Only the contract owner can call this function");
17 | _;
18 | }
19 | }
20 |
21 | contract Mortal is Owned {
22 | // Contract destructor
23 | function destroy() public onlyOwner {
24 | selfdestruct(owner);
25 | }
26 | }
27 |
28 | contract Faucet is Mortal {
29 | // Accept any incoming amount
30 | receive() external payable {}
31 |
32 | // Give out ether to anyone who asks
33 | function withdraw(uint withdraw_amount) public {
34 | // Limit withdrawal amount
35 | require(withdraw_amount <= 0.1 ether);
36 |
37 | // Send the amount to the address that requested it
38 | msg.sender.transfer(withdraw_amount);
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/code/auction_dapp/backend/contracts/utils/AddressUtils.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.5.16;
2 |
3 |
4 | /**
5 | * Utility library of inline functions on addresses
6 | */
7 | library AddressUtils {
8 |
9 | /**
10 | * Returns whether the target address is a contract
11 | * @dev This function will return false if invoked during the constructor of a contract,
12 | * as the code is not actually created until after the constructor finishes.
13 | * @param addr address to check
14 | * @return whether the target address is a contract
15 | */
16 | function isContract(address addr) internal view returns (bool) {
17 | uint256 size;
18 | // XXX Currently there is no better way to check if there is a contract in an address
19 | // than to check the size of the code at that address.
20 | // See https://ethereum.stackexchange.com/a/14016/36603
21 | // for more details about how this works.
22 | // TODO Check this again before the Serenity release, because all addresses will be
23 | // contracts then.
24 | assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly
25 | return size > 0;
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/misc/theme.yml:
--------------------------------------------------------------------------------
1 | font:
2 | catalog:
3 | Noto Serif:
4 | normal: notoserif-regular-subset.ttf
5 | bold: notoserif-bold-subset.ttf
6 | italic: notoserif-italic-subset.ttf
7 | bold_italic: notoserif-bold_italic-subset.ttf
8 | # M+ 1mn supports ASCII and the circled numbers used for conums
9 | M+ 1mn:
10 | normal: mplus1mn-regular-ascii-conums.ttf
11 | bold: mplus1mn-bold-ascii.ttf
12 | italic: mplus1mn-italic-ascii.ttf
13 | bold_italic: mplus1mn-bold_italic-ascii.ttf
14 | # M+ 1p supports Latin, Latin-1 Supplement, Latin Extended, Greek, Cyrillic, Vietnamese, Japanese & an assortment of symbols
15 | # It also provides arrows for ->, <-, => and <= replacements in case these glyphs are missing from font
16 | M+ 1p Fallback:
17 | normal: mplus1p-regular-fallback.ttf
18 | bold: mplus1p-regular-fallback.ttf
19 | italic: mplus1p-regular-fallback.ttf
20 | bold_italic: mplus1p-regular-fallback.ttf
21 | fallbacks:
22 | - M+ 1p Fallback
23 |
24 | base_font_family: Noto Serif
25 | base_font_size: 10.5
26 | base_font_size_small: 8.5
27 |
28 | toc_font_size: 9
29 | toc_dot_leader_content: ". "
30 |
--------------------------------------------------------------------------------
/misc/link_short_unshort_table.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function
2 | import glob
3 | import re
4 | import requests
5 |
6 | markup_files = glob.glob('*.asciidoc')
7 | short_link = re.compile("http[s]*://bit.ly/([0-9a-zA-Z]+)")
8 | heading = re.compile("^== (.*)$")
9 | resolved = {}
10 |
11 | for markup_file in markup_files:
12 | markup_f = open(markup_file, 'r')
13 | markup_contents = markup_f.read()
14 | markup_f.close()
15 | short_links = []
16 | for line in markup_contents.splitlines():
17 | heading_match = heading.match(line)
18 | if heading_match:
19 | print("\n=== "+heading_match.group(1)+"\n|===\n| Short Link | Expanded Link")
20 | short_link_match = short_link.match(line)
21 | if short_link_match:
22 | if short_link_match.group(1) not in short_links:
23 | short_links.append(short_link_match.group(1))
24 | session = requests.Session()
25 | if len(short_links):
26 | for link in short_links:
27 | try:
28 | resp = session.head("https://bit.ly/{link}".format(link=link), allow_redirects=True, timeout=5)
29 | resolved[link] = resp.url
30 | except:
31 | resolved[link] = "manual"
32 |
33 | print("| {link} | {resolved} ".format(link=link, resolved=resolved[link]))
34 | print("|===")
35 |
--------------------------------------------------------------------------------
/contrib/aws-setup.asciidoc:
--------------------------------------------------------------------------------
1 | [[_anchor_introduction_aws_setup]]
2 | == Introduction
3 |
4 | This section describes in detail the set-up of a private Ethereum network and deployment of *Mastering Ethereum Token (MET)* on Amazon Web Services (AWS) cloud.
5 |
6 | Broadly, there are two categories of steps to work with a private Ethereum network as shown below. Each category calls out the high level steps to be followed.
7 |
8 | 1. *Network set-up*
9 | . Set up nodes for launch
10 | . Configuring genesis for nodes
11 | . Peering
12 |
13 | 2. *Network operation*
14 | . Account set-up
15 | . Mining
16 | . RPC end-point
17 | . Contract deployment and execution
18 |
19 | [[_anchor_pre_requisites]]
20 | == Pre-requisites
21 |
22 | The following pre-requisites apply:
23 |
24 | - An AWS account. If you do not have one, create here https://aws.amazon.com/account/
25 | - General command line knowledge on Linux (ideally, Ubuntu) operating system.
26 |
27 | [[_anchor_network_launch]]
28 | == Launch
29 | To launch a private Ethereum network and deploy contracts, follow the links below:
30 |
31 | * link:aws-network-setup.asciidoc[Setting up a private Ethereum network on AWS]
32 | * link:aws-network-operation.asciidoc[Operating a private Ethereum network on AWS]
--------------------------------------------------------------------------------
/misc/reconcile_references.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function
2 | import glob
3 | import re
4 |
5 | markup_files = glob.glob('*.asciidoc')
6 | anchor_re = re.compile("\[\[(.*)\]\]")
7 | ref_re = re.compile(".*\<\<([^\>]*)\>\>.")
8 |
9 | refs = []
10 | anchors = []
11 | dup_anchors = []
12 |
13 | for markup_file in markup_files:
14 | markup_f = open(markup_file, 'r')
15 | markup_contents = markup_f.read()
16 | markup_f.close()
17 | for line in markup_contents.splitlines():
18 | ref_match = ref_re.match(line)
19 | if ref_match:
20 | if ref_match.group(1) not in refs:
21 | refs.append(ref_match.group(1))
22 | anchor_match = anchor_re.match(line)
23 | if anchor_match:
24 | if anchor_match.group(1) not in anchors:
25 | anchors.append(anchor_match.group(1))
26 | else:
27 | dup_anchors.append(anchor_match.group(1))
28 |
29 | print("\nAnchors: ", len(anchors))
30 | print("\nDuplicated Anchors: ", len(dup_anchors))
31 | print(dup_anchors)
32 | print("\nReferences: ", len(refs))
33 | print(refs)
34 | broken_refs = list(set(refs) - set(anchors))
35 | print("\nBroken references: ", len(broken_refs), broken_refs)
36 | missing_refs = list(set(anchors) - set(refs))
37 | print("\nUn-referenced Anchors: ", len(missing_refs), missing_refs)
38 |
--------------------------------------------------------------------------------
/tools/evm-opcodes-generator/appdx-evm-opcodes-gas-generator.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # This script generate automatically an up to date OPCODES and Gas appendix based on
4 | # https://raw.githubusercontent.com/trailofbits/evm-opcodes/master/README.md
5 | # from https://github.com/trailofbits/evm-opcodes
6 |
7 | # ^[^|]*(\|[^|]*){3}$
8 |
9 | ORIGIN_FILE=https://raw.githubusercontent.com/trailofbits/evm-opcodes/master/README.md
10 |
11 | # OPCODES MARKER in the converted asciidoc file
12 | OPCODES_BEGIN_MARKER=Table
13 | echo "The OPCODES_BEGIN_MARKER is $OPCODES_BEGIN_MARKER."
14 |
15 | OPCODES_END_MARKER=instruction-details
16 | echo "The OPCODES_END_MARKER is $OPCODES_END_MARKER."
17 |
18 | echo "Getting the origin file, converting it and spliting it ..."
19 | wget -q -O - $ORIGIN_FILE | pandoc --columns=200 -t asciidoc | csplit - -q --prefix=appdx-evm-opcodes-gas- -b "%02d.asciidoc" /$OPCODES_BEGIN_MARKER/ /$OPCODES_END_MARKER/
20 |
21 | echo "Concatenating header OPCODES and footer ..."
22 | cat appdx-evm-opcodes-gas-header.asciidoc appdx-evm-opcodes-gas-01.asciidoc appdx-evm-opcodes-gas-footer.asciidoc > appdx-evm-opcodes-gas.asciidoc
23 |
24 | echo "Removing temp files ..."
25 | rm appdx-evm-opcodes-gas-0*
26 |
27 | echo "The new appendix for OPCODES and Gas was autogenerated succesfully!"
--------------------------------------------------------------------------------
/code/auction_dapp/backend/contracts/ERC721/ERC721.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.5.16;
2 |
3 | import "./ERC721Basic.sol";
4 |
5 |
6 | /**
7 | * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
8 | * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
9 | */
10 | contract ERC721Enumerable is ERC721Basic {
11 | function totalSupply() public view returns (uint256);
12 | function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId);
13 | function tokenByIndex(uint256 _index) public view returns (uint256);
14 | }
15 |
16 |
17 | /**
18 | * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
19 | * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
20 | */
21 | contract ERC721Metadata is ERC721Basic {
22 | function name() public view returns (string memory _name);
23 | function symbol() public view returns (string memory _symbol);
24 | function tokenURI(uint256 _tokenId) public view returns (string memory);
25 | }
26 |
27 |
28 | /**
29 | * @title ERC-721 Non-Fungible Token Standard, full implementation interface
30 | * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
31 | */
32 | contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
33 | }
34 |
--------------------------------------------------------------------------------
/code/Solidity/Faucet7.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: CC-BY-SA-4.0
2 |
3 | // Version of Solidity compiler this program was written for
4 | pragma solidity ^0.6.4;
5 |
6 | contract Owned {
7 | address payable owner;
8 |
9 | // Contract constructor: set owner
10 | constructor() public {
11 | owner = msg.sender;
12 | }
13 |
14 | // Access control modifier
15 | modifier onlyOwner {
16 | require(msg.sender == owner, "Only the contract owner can call this function");
17 | _;
18 | }
19 | }
20 |
21 | contract Mortal is Owned {
22 | // Contract destructor
23 | function destroy() public onlyOwner {
24 | selfdestruct(owner);
25 | }
26 | }
27 |
28 | contract Faucet is Mortal {
29 | // Accept any incoming amount
30 | receive() external payable {}
31 |
32 | // Give out ether to anyone who asks
33 | function withdraw(uint withdraw_amount) public {
34 | // Limit withdrawal amount
35 | require(withdraw_amount <= 0.1 ether);
36 |
37 | require(
38 | address(this).balance >= withdraw_amount,
39 | "Insufficient balance in faucet for withdrawal request"
40 | );
41 |
42 | // Send the amount to the address that requested it
43 | msg.sender.transfer(withdraw_amount);
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/code/truffle/FaucetEvents/contracts/Faucet.sol:
--------------------------------------------------------------------------------
1 | // Version of Solidity compiler this program was written for
2 | pragma solidity ^0.4.22;
3 |
4 | contract owned {
5 | address owner;
6 | // Contract constructor: set owner
7 | constructor() {
8 | owner = msg.sender;
9 | }
10 | // Access control modifier
11 | modifier onlyOwner {
12 | require(msg.sender == owner, "Only the contract owner can call this function");
13 | _;
14 | }
15 | }
16 |
17 | contract mortal is owned {
18 | // Contract destructor
19 | function destroy() public onlyOwner {
20 | selfdestruct(owner);
21 | }
22 | }
23 |
24 | contract Faucet is mortal {
25 | event Withdrawal(address indexed to, uint amount);
26 | event Deposit(address indexed from, uint amount);
27 |
28 | // Give out ether to anyone who asks
29 | function withdraw(uint withdraw_amount) public {
30 | // Limit withdrawal amount
31 | require(withdraw_amount <= 0.1 ether);
32 | require(this.balance >= withdraw_amount,
33 | "Insufficient balance in faucet for withdrawal request");
34 | // Send the amount to the address that requested it
35 | msg.sender.transfer(withdraw_amount);
36 | emit Withdrawal(msg.sender, withdraw_amount);
37 | }
38 | // Accept any incoming amount
39 | function () external payable {
40 | emit Deposit(msg.sender, msg.value);
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/code/auction_dapp/backend/contracts/utils/math/SafeMath.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.5.16;
2 |
3 |
4 | /**
5 | * @title SafeMath
6 | * @dev Math operations with safety checks that throw on error
7 | */
8 | library SafeMath {
9 |
10 | /**
11 | * @dev Multiplies two numbers, throws on overflow.
12 | */
13 | function mul(uint256 a, uint256 b) internal pure returns (uint256) {
14 | if (a == 0) {
15 | return 0;
16 | }
17 | uint256 c = a * b;
18 | assert(c / a == b);
19 | return c;
20 | }
21 |
22 | /**
23 | * @dev Integer division of two numbers, truncating the quotient.
24 | */
25 | function div(uint256 a, uint256 b) internal pure returns (uint256) {
26 | // assert(b > 0); // Solidity automatically throws when dividing by 0
27 | // uint256 c = a / b;
28 | // assert(a == b * c + a % b); // There is no case in which this doesn't hold
29 | return a / b;
30 | }
31 |
32 | /**
33 | * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
34 | */
35 | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
36 | assert(b <= a);
37 | return a - b;
38 | }
39 |
40 | /**
41 | * @dev Adds two numbers, throws on overflow.
42 | */
43 | function add(uint256 a, uint256 b) internal pure returns (uint256) {
44 | uint256 c = a + b;
45 | assert(c >= a);
46 | return c;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/code/auction_dapp/frontend/build/build.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 | require('./check-versions')()
3 |
4 | process.env.NODE_ENV = 'production'
5 |
6 | const ora = require('ora')
7 | const rm = require('rimraf')
8 | const path = require('path')
9 | const chalk = require('chalk')
10 | const webpack = require('webpack')
11 | const config = require('../config')
12 | const webpackConfig = require('./webpack.prod.conf')
13 |
14 | const spinner = ora('building for production...')
15 | spinner.start()
16 |
17 | rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
18 | if (err) throw err
19 | webpack(webpackConfig, (err, stats) => {
20 | spinner.stop()
21 | if (err) throw err
22 | process.stdout.write(stats.toString({
23 | colors: true,
24 | modules: false,
25 | children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
26 | chunks: false,
27 | chunkModules: false
28 | }) + '\n\n')
29 |
30 | if (stats.hasErrors()) {
31 | console.log(chalk.red(' Build failed with errors.\n'))
32 | process.exit(1)
33 | }
34 |
35 | console.log(chalk.cyan(' Build complete.\n'))
36 | console.log(chalk.yellow(
37 | ' Tip: built files are meant to be served over an HTTP server.\n' +
38 | ' Opening index.html over file:// won\'t work.\n'
39 | ))
40 | })
41 | })
42 |
--------------------------------------------------------------------------------
/code/auction_dapp/backend/contracts/ERC721/ERC721Receiver.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.5.16;
2 |
3 |
4 | /**
5 | * @title ERC721 token receiver interface
6 | * @dev Interface for any contract that wants to support safeTransfers
7 | * from ERC721 asset contracts.
8 | */
9 | contract ERC721Receiver {
10 | /**
11 | * @dev Magic value to be returned upon successful reception of an NFT
12 | * Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
13 | * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
14 | */
15 | bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
16 |
17 | /**
18 | * @notice Handle the receipt of an NFT
19 | * @dev The ERC721 smart contract calls this function on the recipient
20 | * after a `safetransfer`. This function MAY throw to revert and reject the
21 | * transfer. This function MUST use 50,000 gas or less. Return of other
22 | * than the magic value MUST result in the transaction being reverted.
23 | * Note: the contract address is always the message sender.
24 | * @param _from The sending address
25 | * @param _tokenId The NFT identifier which is being transfered
26 | * @param _data Additional data with no specified format
27 | * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
28 | */
29 | function onERC721Received(address _from, uint256 _tokenId, bytes memory _data) public returns(bytes4);
30 | }
31 |
--------------------------------------------------------------------------------
/code/auction_dapp/backend/contracts/ERC721/ERC721Basic.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.5.16;
2 |
3 |
4 | /**
5 | * @title ERC721 Non-Fungible Token Standard basic interface
6 | * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
7 | */
8 | contract ERC721Basic {
9 | event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
10 | event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
11 | event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
12 |
13 | function balanceOf(address _owner) public view returns (uint256 _balance);
14 | function ownerOf(uint256 _tokenId) public view returns (address _owner);
15 | function exists(uint256 _tokenId) public view returns (bool _exists);
16 |
17 | function approve(address _to, uint256 _tokenId) public;
18 | function getApproved(uint256 _tokenId) public view returns (address _operator);
19 |
20 | function setApprovalForAll(address _operator, bool _approved) public;
21 | function isApprovedForAll(address _owner, address _operator) public view returns (bool);
22 |
23 | function transferFrom(address _from, address _to, uint256 _tokenId) public;
24 | function safeTransferFrom(address _from, address _to, uint256 _tokenId) public;
25 | function safeTransferFrom(
26 | address _from,
27 | address _to,
28 | uint256 _tokenId,
29 | bytes memory _data
30 | )
31 | public;
32 | }
33 |
--------------------------------------------------------------------------------
/code/auction_dapp/DEV_README.md:
--------------------------------------------------------------------------------
1 | # Configuring truffle
2 | Guide to properly configure truffle to build and deploy contracts to the network
3 |
4 |
5 | ## Add local testnet
6 |
7 | Edit `truffle.js` :
8 |
9 | ```
10 | networks: {
11 | development: {
12 | host: "",
13 | port: 8545,
14 | network_id: "*",
15 | gas: 2900000
16 | }
17 | }
18 | ```
19 |
20 | ## Commands
21 |
22 | ```
23 | $ truffle init #initialize truffle project
24 | $ truffle console
25 | $ truffle deploy
26 | $ truffle migrate --reset --compile-all #redeploy the smat contracts
27 |
28 | ```
29 |
30 | ## Errors
31 | Here is a list of possible errors:
32 |
33 | ## ParserError: Expected token Semicolon got 'LParen'
34 |
35 | Emitting events gives compilation error if solc-js not 0.4.21
36 | Update truffle using:
37 |
38 | ```
39 | $ cd /usr/lib/node_modules/truffle
40 | $ npm install solc@0.4.21 --save
41 | ```
42 |
43 | ### Account is locked/Auth needed
44 |
45 | ```
46 | $ truffle console
47 | truffle(development)> var acc = web3.eth.accounts[0]
48 | truffle(development)> web3.personal.unlockAccount(acc, 'pass', 36000)
49 | ```
50 |
51 | Then deploy. Repeat the step when needed
52 |
53 | ### Intrinsic gas too low
54 |
55 | ```
56 | $ truffle console
57 | truffle(development)> web3.eth.getBlock("pending").gasLimit
58 | xxxxxxx
59 | ```
60 |
61 | edit truffle.js
62 |
63 | ```
64 | development: {
65 | ...
66 | gas: xxxxxxxxx,
67 | network_id: "*"
68 | }
69 | ```
70 |
--------------------------------------------------------------------------------
/code/Solidity/Faucet8.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: CC-BY-SA-4.0
2 |
3 | // Version of Solidity compiler this program was written for
4 | pragma solidity ^0.6.4;
5 |
6 | contract Owned {
7 | address payable owner;
8 |
9 | // Contract constructor: set owner
10 | constructor() public {
11 | owner = msg.sender;
12 | }
13 |
14 | // Access control modifier
15 | modifier onlyOwner {
16 | require(msg.sender == owner, "Only the contract owner can call this function");
17 | _;
18 | }
19 | }
20 |
21 | contract Mortal is Owned {
22 | // Contract destructor
23 | function destroy() public onlyOwner {
24 | selfdestruct(owner);
25 | }
26 | }
27 |
28 | contract Faucet is Mortal {
29 | event Withdrawal(address indexed to, uint amount);
30 | event Deposit(address indexed from, uint amount);
31 |
32 | // Accept any incoming amount
33 | receive() external payable {
34 | emit Deposit(msg.sender, msg.value);
35 | }
36 |
37 | // Give out ether to anyone who asks
38 | function withdraw(uint withdraw_amount) public {
39 | // Limit withdrawal amount
40 | require(withdraw_amount <= 0.1 ether);
41 |
42 | require(
43 | address(this).balance >= withdraw_amount,
44 | "Insufficient balance in faucet for withdrawal request"
45 | );
46 |
47 | // Send the amount to the address that requested it
48 | msg.sender.transfer(withdraw_amount);
49 |
50 | emit Withdrawal(msg.sender, withdraw_amount);
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/code/auction_dapp/frontend/build/check-versions.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 | const chalk = require('chalk')
3 | const semver = require('semver')
4 | const packageConfig = require('../package.json')
5 | const shell = require('shelljs')
6 |
7 | function exec (cmd) {
8 | return require('child_process').execSync(cmd).toString().trim()
9 | }
10 |
11 | const versionRequirements = [
12 | {
13 | name: 'node',
14 | currentVersion: semver.clean(process.version),
15 | versionRequirement: packageConfig.engines.node
16 | }
17 | ]
18 |
19 | if (shell.which('npm')) {
20 | versionRequirements.push({
21 | name: 'npm',
22 | currentVersion: exec('npm --version'),
23 | versionRequirement: packageConfig.engines.npm
24 | })
25 | }
26 |
27 | module.exports = function () {
28 | const warnings = []
29 |
30 | for (let i = 0; i < versionRequirements.length; i++) {
31 | const mod = versionRequirements[i]
32 |
33 | if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
34 | warnings.push(mod.name + ': ' +
35 | chalk.red(mod.currentVersion) + ' should be ' +
36 | chalk.green(mod.versionRequirement)
37 | )
38 | }
39 | }
40 |
41 | if (warnings.length) {
42 | console.log('')
43 | console.log(chalk.yellow('To use this template, you must update following to modules:'))
44 | console.log()
45 |
46 | for (let i = 0; i < warnings.length; i++) {
47 | const warning = warnings[i]
48 | console.log(' ' + warning)
49 | }
50 |
51 | console.log()
52 | process.exit(1)
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/code/auction_dapp/backend/scripts/prepare.js:
--------------------------------------------------------------------------------
1 | var deedabi = require("./build/contracts/DeedRepository.json").abi;
2 | var deedaddress = "0x454e7bd1e743ec2517a104758895bec40d9ffb9d";
3 | var auctionabi = require("./build/contracts/AuctionRepository.json").abi;
4 | var auctionaddress = "0x14fba6349fe2f9187d08391b8dc2ca0c3742e285";
5 |
6 | var deedinstance = web3.eth.contract(deedabi).at(deedaddress);
7 | var auctioninstance = web3.eth.contract(auctionabi).at(auctionaddress);
8 | var acc = web3.eth.accounts[0];
9 | var ops = { from: acc, gas: 300000 };
10 | //register a deed and transfer to auctionrepository address
11 |
12 | deedinstance.registerDeed(acc, 123456789, ops);
13 | deedinstance.approve(auctionaddress, 123456789, ops);
14 | deedinstance.transferFrom( acc ,auctionaddress, 123456789, ops );
15 |
16 | // create auction
17 | var startprice = new web3.BigNumber(1000000000000000000)
18 | auctioninstance.createAuction(deedaddress, 123456789, "My title", "meta://", startprice, 1527811200 , ops );
19 |
20 | auctioninstance.getAuctionsCount(ops); // should be 1
21 |
22 | auctioninstance.getAuctionById(0, ops);
23 |
24 | auctioninstance.bidOnAuction(0, { from: web3.eth.accounts[1], gas: 300000, value: new web3.BigNumber(2000000000000000000) }); // should be 1
25 | // error..cant bid on auction that is owned
26 | auctioninstance.getBidsCount(0, ops)
27 |
28 | // balance of account 2 should be 9899xxxxxx
29 | web3.eth.getBalance(web3.eth.accounts[1]).toNumber()
30 |
31 | auctioninstance.cancelAuction(0, ops);
32 |
33 | // balance back to where it was minus some gas costs
34 | web3.eth.getBalance(web3.eth.accounts[1]).toNumber()
35 |
36 |
--------------------------------------------------------------------------------
/code/jsonrpc/ipc/client.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "io"
7 | "log"
8 | "net"
9 | "sync"
10 | )
11 |
12 | // Request represents the jsonrpc2 request
13 | type Request struct {
14 | Jsonrpc string `json:"jsonrpc"`
15 | Method string `json:"method"`
16 | Params interface{} `json:"params"`
17 | ID uint64 `json:"id"`
18 | }
19 |
20 | // ReadIPC reads from a socket
21 | func ReadIPC(r io.Reader, wg *sync.WaitGroup) {
22 | //20KB buffer
23 | buf := make([]byte, 20*1024)
24 | n, err := r.Read(buf[:])
25 | if err != nil {
26 | log.Fatal("Unable to read from socket", err)
27 | }
28 | fmt.Println("Ethereum node response: ", string(buf[0:n]))
29 | wg.Done()
30 | }
31 |
32 | func main() {
33 | var wg sync.WaitGroup
34 | socketfile := "/home/younix/testnet/chaindata/geth.ipc"
35 |
36 | // create a request
37 | params := make([]int, 0)
38 | request := &Request{
39 | Jsonrpc: "2.0",
40 | Method: "eth_blockNumber",
41 | Params: params,
42 | ID: 12345,
43 | }
44 |
45 | // marshal the struct to json string
46 | strRequest, err := json.Marshal(&request)
47 | if err != nil {
48 | log.Fatal("Unable to encode request", err)
49 | }
50 |
51 | // dial the socket
52 | ipc, err := net.Dial("unix", socketfile)
53 | if err != nil {
54 | log.Fatal("Unable to connect to the unix socket", err)
55 | }
56 | defer ipc.Close()
57 |
58 | // listen for incoming messages
59 | wg.Add(1)
60 | go ReadIPC(ipc, &wg)
61 |
62 | // write to the unix socket
63 | fmt.Println("Call procedure: ", request.Method)
64 | _, err = ipc.Write(strRequest)
65 | if err != nil {
66 | log.Fatal("Unable to write to the unix socket", err)
67 | }
68 |
69 | // wait for response
70 | wg.Wait()
71 | }
72 |
--------------------------------------------------------------------------------
/colo.html:
--------------------------------------------------------------------------------
1 |
2 |
Colophon
3 |
4 |
The animal on the cover of Mastering Ethereum is a group of Eastern honey bees (Apis cerana), a species found throughout southeastern Asian countries. This insect exhibits highly complex behavior that, ultimately, benefits its hive. Each individual bee operates freely under a set of simple rules and communicates findings of importance by pheromones and the so-called “waggle dance.” This dance carries valuable information like the position of the sun and relative geographical coordinates from the hive to the target in question. By interpreting this dance, the bees can relay this information or act on it, thus carrying out the decentralized will of swarm intelligence.
5 |
6 |
Although bees form a caste-based society and have a queen for producing offspring, there is no central authority or leader in a beehive. The highly intelligent and sophisticated behavior exhibited by a multi-thousand-member colony is an emergent property that arises from the interaction of the individuals in a social network.
7 |
8 |
Nature demonstrates that decentralized systems can be resilient and can produce emergent complexity and incredible sophistication without the need for a central authority, hierarchy, or complex parts.
9 |
10 |
Many of the animals on O'Reilly covers are endangered; all of them are important to the world. To learn more about how you can help, go to animals.oreilly.com.
11 |
12 |
The cover image is from Animal Life In the Sea and On the Land. The cover fonts are URW Typewriter and Guardian Sans. The text font is Adobe Minion Pro; the heading font is Adobe Myriad Condensed; and the code font is Dalton Maag's Ubuntu Mono.
13 |
14 |
--------------------------------------------------------------------------------
/code/truffle/METoken/truffle-config.js:
--------------------------------------------------------------------------------
1 | // Install dependencies:
2 | // npm init
3 | // npm install --save-dev dotenv truffle-wallet-provider ethereumjs-wallet
4 |
5 | // Create .env in project root, with keys:
6 | // ROPSTEN_PRIVATE_KEY="123abc"
7 | // MAINNET_PRIVATE_KEY="123abc"
8 |
9 | require('dotenv').config();
10 | const Web3 = require("web3");
11 | const web3 = new Web3();
12 | const WalletProvider = require("truffle-wallet-provider");
13 | const Wallet = require('ethereumjs-wallet');
14 |
15 | var mainNetPrivateKey = new Buffer(process.env["MAINNET_PRIVATE_KEY"], "hex")
16 | var mainNetWallet = Wallet.fromPrivateKey(mainNetPrivateKey);
17 | var mainNetProvider = new WalletProvider(mainNetWallet, "https://mainnet.infura.io/");
18 |
19 | var ropstenPrivateKey = new Buffer(process.env["ROPSTEN_PRIVATE_KEY"], "hex")
20 | var ropstenWallet = Wallet.fromPrivateKey(ropstenPrivateKey);
21 | var ropstenProvider = new WalletProvider(ropstenWallet, "https://ropsten.infura.io/");
22 |
23 | module.exports = {
24 | networks: {
25 | dev: { // Whatever network our local node connects to
26 | network_id: "*", // Match any network id
27 | host: "localhost",
28 | port: 8545,
29 | },
30 | mainnet: { // Provided by Infura, load keys in .env file
31 | network_id: "1",
32 | provider: mainNetProvider,
33 | gas: 4600000,
34 | gasPrice: web3.utils.toWei("20", "gwei"),
35 | },
36 | ropsten: { // Provided by Infura, load keys in .env file
37 | network_id: "3",
38 | provider: ropstenProvider,
39 | gas: 4600000,
40 | gasPrice: web3.utils.toWei("20", "gwei"),
41 | },
42 | kovan: {
43 | network_id: 42,
44 | host: "localhost", // parity --chain=kovan
45 | port: 8545,
46 | gas: 5000000
47 | },
48 | ganache: { // Ganache local test RPC blockchain
49 | network_id: "5777",
50 | host: "localhost",
51 | port: 7545,
52 | gas: 6721975,
53 | }
54 | }
55 | };
56 |
--------------------------------------------------------------------------------
/code/truffle/console/truffle-config.js:
--------------------------------------------------------------------------------
1 | // Install dependencies:
2 | // npm init
3 | // npm install --save-dev dotenv truffle-wallet-provider ethereumjs-wallet
4 |
5 | // Create .env in project root, with keys:
6 | // ROPSTEN_PRIVATE_KEY="123abc"
7 | // MAINNET_PRIVATE_KEY="123abc"
8 |
9 | require('dotenv').config();
10 | const Web3 = require("web3");
11 | const web3 = new Web3();
12 | const WalletProvider = require("truffle-wallet-provider");
13 | const Wallet = require('ethereumjs-wallet');
14 |
15 | var mainNetPrivateKey = new Buffer(process.env["MAINNET_PRIVATE_KEY"], "hex")
16 | var mainNetWallet = Wallet.fromPrivateKey(mainNetPrivateKey);
17 | var mainNetProvider = new WalletProvider(mainNetWallet, "https://mainnet.infura.io/");
18 |
19 | var ropstenPrivateKey = new Buffer(process.env["ROPSTEN_PRIVATE_KEY"], "hex")
20 | var ropstenWallet = Wallet.fromPrivateKey(ropstenPrivateKey);
21 | var ropstenProvider = new WalletProvider(ropstenWallet, "https://ropsten.infura.io/");
22 |
23 | module.exports = {
24 | networks: {
25 | dev: { // Whatever network our local node connects to
26 | network_id: "*", // Match any network id
27 | host: "localhost",
28 | port: 8545,
29 | },
30 | mainnet: { // Provided by Infura, load keys in .env file
31 | network_id: "1",
32 | provider: mainNetProvider,
33 | gas: 4600000,
34 | gasPrice: web3.utils.toWei("20", "gwei"),
35 | },
36 | ropsten: { // Provided by Infura, load keys in .env file
37 | network_id: "3",
38 | provider: ropstenProvider,
39 | gas: 4600000,
40 | gasPrice: web3.utils.toWei("20", "gwei"),
41 | },
42 | kovan: {
43 | network_id: 42,
44 | host: "localhost", // parity --chain=kovan
45 | port: 8545,
46 | gas: 5000000
47 | },
48 | ganache: { // Ganache local test RPC blockchain
49 | network_id: "5777",
50 | host: "localhost",
51 | port: 7545,
52 | gas: 6721975,
53 | }
54 | }
55 | };
56 |
--------------------------------------------------------------------------------
/code/truffle/CallExamples/truffle-config.js:
--------------------------------------------------------------------------------
1 | // Install dependencies:
2 | // npm init
3 | // npm install --save-dev dotenv truffle-wallet-provider ethereumjs-wallet
4 |
5 | // Create .env in project root, with keys:
6 | // ROPSTEN_PRIVATE_KEY="123abc"
7 | // MAINNET_PRIVATE_KEY="123abc"
8 |
9 | require('dotenv').config();
10 | const Web3 = require("web3");
11 | const web3 = new Web3();
12 | const WalletProvider = require("truffle-wallet-provider");
13 | const Wallet = require('ethereumjs-wallet');
14 |
15 | var mainNetPrivateKey = new Buffer(process.env["MAINNET_PRIVATE_KEY"], "hex")
16 | var mainNetWallet = Wallet.fromPrivateKey(mainNetPrivateKey);
17 | var mainNetProvider = new WalletProvider(mainNetWallet, "https://mainnet.infura.io/");
18 |
19 | var ropstenPrivateKey = new Buffer(process.env["ROPSTEN_PRIVATE_KEY"], "hex")
20 | var ropstenWallet = Wallet.fromPrivateKey(ropstenPrivateKey);
21 | var ropstenProvider = new WalletProvider(ropstenWallet, "https://ropsten.infura.io/");
22 |
23 | module.exports = {
24 | networks: {
25 | dev: { // Whatever network our local node connects to
26 | network_id: "*", // Match any network id
27 | host: "localhost",
28 | port: 8545,
29 | },
30 | mainnet: { // Provided by Infura, load keys in .env file
31 | network_id: "1",
32 | provider: mainNetProvider,
33 | gas: 4600000,
34 | gasPrice: web3.utils.toWei("20", "gwei"),
35 | },
36 | ropsten: { // Provided by Infura, load keys in .env file
37 | network_id: "3",
38 | provider: ropstenProvider,
39 | gas: 4600000,
40 | gasPrice: web3.utils.toWei("20", "gwei"),
41 | },
42 | kovan: {
43 | network_id: 42,
44 | host: "localhost", // parity --chain=kovan
45 | port: 8545,
46 | gas: 5000000
47 | },
48 | ganache: { // Ganache local test RPC blockchain
49 | network_id: "5777",
50 | host: "localhost",
51 | port: 7545,
52 | gas: 6721975,
53 | }
54 | }
55 | };
56 |
--------------------------------------------------------------------------------
/code/truffle/METoken_Faucet/truffle-config.js:
--------------------------------------------------------------------------------
1 | // Install dependencies:
2 | // npm init
3 | // npm install --save-dev dotenv truffle-wallet-provider ethereumjs-wallet
4 |
5 | // Create .env in project root, with keys:
6 | // ROPSTEN_PRIVATE_KEY="123abc"
7 | // MAINNET_PRIVATE_KEY="123abc"
8 |
9 | require('dotenv').config();
10 | const Web3 = require("web3");
11 | const web3 = new Web3();
12 | const WalletProvider = require("truffle-wallet-provider");
13 | const Wallet = require('ethereumjs-wallet');
14 |
15 | var mainNetPrivateKey = new Buffer(process.env["MAINNET_PRIVATE_KEY"], "hex")
16 | var mainNetWallet = Wallet.fromPrivateKey(mainNetPrivateKey);
17 | var mainNetProvider = new WalletProvider(mainNetWallet, "https://mainnet.infura.io/");
18 |
19 | var ropstenPrivateKey = new Buffer(process.env["ROPSTEN_PRIVATE_KEY"], "hex")
20 | var ropstenWallet = Wallet.fromPrivateKey(ropstenPrivateKey);
21 | var ropstenProvider = new WalletProvider(ropstenWallet, "https://ropsten.infura.io/");
22 |
23 | module.exports = {
24 | networks: {
25 | dev: { // Whatever network our local node connects to
26 | network_id: "*", // Match any network id
27 | host: "localhost",
28 | port: 8545,
29 | },
30 | mainnet: { // Provided by Infura, load keys in .env file
31 | network_id: "1",
32 | provider: mainNetProvider,
33 | gas: 4600000,
34 | gasPrice: web3.utils.toWei("20", "gwei"),
35 | },
36 | ropsten: { // Provided by Infura, load keys in .env file
37 | network_id: "3",
38 | provider: ropstenProvider,
39 | gas: 4600000,
40 | gasPrice: web3.utils.toWei("20", "gwei"),
41 | },
42 | kovan: {
43 | network_id: 42,
44 | host: "localhost", // parity --chain=kovan
45 | port: 8545,
46 | gas: 5000000
47 | },
48 | ganache: { // Ganache local test RPC blockchain
49 | network_id: "5777",
50 | host: "localhost",
51 | port: 7545,
52 | gas: 6721975,
53 | }
54 | }
55 | };
56 |
--------------------------------------------------------------------------------
/code/truffle/METoken_METFaucet/truffle-config.js:
--------------------------------------------------------------------------------
1 | // Install dependencies:
2 | // npm init
3 | // npm install --save-dev dotenv truffle-wallet-provider ethereumjs-wallet
4 |
5 | // Create .env in project root, with keys:
6 | // ROPSTEN_PRIVATE_KEY="123abc"
7 | // MAINNET_PRIVATE_KEY="123abc"
8 |
9 | require('dotenv').config();
10 | const Web3 = require("web3");
11 | const web3 = new Web3();
12 | const WalletProvider = require("truffle-wallet-provider");
13 | const Wallet = require('ethereumjs-wallet');
14 |
15 | var mainNetPrivateKey = new Buffer(process.env["MAINNET_PRIVATE_KEY"], "hex")
16 | var mainNetWallet = Wallet.fromPrivateKey(mainNetPrivateKey);
17 | var mainNetProvider = new WalletProvider(mainNetWallet, "https://mainnet.infura.io/");
18 |
19 | var ropstenPrivateKey = new Buffer(process.env["ROPSTEN_PRIVATE_KEY"], "hex")
20 | var ropstenWallet = Wallet.fromPrivateKey(ropstenPrivateKey);
21 | var ropstenProvider = new WalletProvider(ropstenWallet, "https://ropsten.infura.io/");
22 |
23 | module.exports = {
24 | networks: {
25 | dev: { // Whatever network our local node connects to
26 | network_id: "*", // Match any network id
27 | host: "localhost",
28 | port: 8545,
29 | },
30 | mainnet: { // Provided by Infura, load keys in .env file
31 | network_id: "1",
32 | provider: mainNetProvider,
33 | gas: 4600000,
34 | gasPrice: web3.utils.toWei("20", "gwei"),
35 | },
36 | ropsten: { // Provided by Infura, load keys in .env file
37 | network_id: "3",
38 | provider: ropstenProvider,
39 | gas: 4600000,
40 | gasPrice: web3.utils.toWei("20", "gwei"),
41 | },
42 | kovan: {
43 | network_id: 42,
44 | host: "localhost", // parity --chain=kovan
45 | port: 8545,
46 | gas: 5000000
47 | },
48 | ganache: { // Ganache local test RPC blockchain
49 | network_id: "5777",
50 | host: "localhost",
51 | port: 7545,
52 | gas: 6721975,
53 | }
54 | }
55 | };
56 |
--------------------------------------------------------------------------------
/code/auction_dapp/backend/contracts/DeedRepository.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.5.16;
2 | import "./ERC721/ERC721Token.sol";
3 |
4 | /**
5 | * @title Repository of ERC721 Deeds
6 | * This contract contains the list of deeds registered by users.
7 | * This is a demo to show how tokens (deeds) can be minted and added
8 | * to the repository.
9 | */
10 | contract DeedRepository is ERC721Token {
11 |
12 |
13 | /**
14 | * @dev Created a DeedRepository with a name and symbol
15 | * @param _name string represents the name of the repository
16 | * @param _symbol string represents the symbol of the repository
17 | */
18 | constructor(string memory _name, string memory _symbol)
19 | public ERC721Token(_name, _symbol) {}
20 |
21 | /**
22 | * @dev Public function to register a new deed
23 | * @dev Call the ERC721Token minter
24 | * @param _tokenId uint256 represents a specific deed
25 | * @param _uri string containing metadata/uri
26 | */
27 | function registerDeed(uint256 _tokenId, string memory _uri) public {
28 | _mint(msg.sender, _tokenId);
29 | addDeedMetadata(_tokenId, _uri);
30 | emit DeedRegistered(msg.sender, _tokenId);
31 | }
32 |
33 | /**
34 | * @dev Public function to add metadata to a deed
35 | * @param _tokenId represents a specific deed
36 | * @param _uri text which describes the characteristics of a given deed
37 | * @return whether the deed metadata was added to the repository
38 | */
39 | function addDeedMetadata(uint256 _tokenId, string memory _uri) public returns(bool){
40 | _setTokenURI(_tokenId, _uri);
41 | return true;
42 | }
43 |
44 | /**
45 | * @dev Event is triggered if deed/token is registered
46 | * @param _by address of the registrar
47 | * @param _tokenId uint256 represents a specific deed
48 | */
49 | event DeedRegistered(address _by, uint256 _tokenId);
50 | }
51 |
--------------------------------------------------------------------------------
/code/aws/truffle-config.js:
--------------------------------------------------------------------------------
1 | // Install dependencies:
2 | // npm init
3 | // npm install --save-dev dotenv truffle-wallet-provider ethereumjs-wallet
4 |
5 | // Create .env in project root, with keys:
6 | // ROPSTEN_PRIVATE_KEY="123abc"
7 | // MAINNET_PRIVATE_KEY="123abc"
8 |
9 | require('dotenv').config();
10 | const Web3 = require("web3");
11 | const web3 = new Web3();
12 | const WalletProvider = require("truffle-wallet-provider");
13 | const Wallet = require('ethereumjs-wallet');
14 |
15 | var mainNetPrivateKey = new Buffer(process.env["MAINNET_PRIVATE_KEY"], "hex")
16 | var mainNetWallet = Wallet.fromPrivateKey(mainNetPrivateKey);
17 | var mainNetProvider = new WalletProvider(mainNetWallet, "https://mainnet.infura.io/");
18 |
19 | var ropstenPrivateKey = new Buffer(process.env["ROPSTEN_PRIVATE_KEY"], "hex")
20 | var ropstenWallet = Wallet.fromPrivateKey(ropstenPrivateKey);
21 | var ropstenProvider = new WalletProvider(ropstenWallet, "https://ropsten.infura.io/");
22 |
23 | module.exports = {
24 | networks: {
25 | dev: { // Whatever network our local node connects to
26 | network_id: "*", // Match any network id
27 | host: "localhost",
28 | port: 8545
29 | },
30 | mainnet: { // Provided by Infura, load keys in .env file
31 | network_id: "1",
32 | provider: mainNetProvider,
33 | gas: 4600000,
34 | gasPrice: web3.utils.toWei("20", "gwei")
35 | },
36 | ropsten: { // Provided by Infura, load keys in .env file
37 | network_id: "3",
38 | provider: ropstenProvider,
39 | gas: 4600000,
40 | gasPrice: web3.utils.toWei("20", "gwei")
41 | },
42 | kovan: {
43 | network_id: 42,
44 | host: "localhost", // parity --chain=kovan
45 | port: 8545,
46 | gas: 5000000
47 | },
48 | ganache: { // Ganache local test RPC blockchain
49 | network_id: "5777",
50 | host: "localhost",
51 | port: 7545,
52 | gas: 6721975
53 | },
54 | aws: { // Private network on AWS
55 | network_id: "15",
56 | host: "public-ip-address",
57 | port: 8545,
58 | gas: 6721975
59 | }
60 | }
61 | };
--------------------------------------------------------------------------------
/code/truffle/console/nonce.js:
--------------------------------------------------------------------------------
1 | console.log("getTransactionCount (confirmed)");
2 | console.log(web3.eth.getTransactionCount("0x9e713963a92c02317a681b9bb3065a8249de124f"));
3 |
4 | console.log("getTransactionCount (pending)");
5 | console.log(web3.eth.getTransactionCount("0x9e713963a92c02317a681b9bb3065a8249de124f", "pending"));
6 |
7 | console.log("sendTransaction");
8 | console.log(web3.eth.sendTransaction({from: web3.eth.accounts[0], to: "0xB0920c523d582040f2BCB1bD7FB1c7C1ECEbdB34", value: web3.utils.toWei(0.01, "ether")}));
9 |
10 | console.log("getTransactionCount (confirmed)");
11 | console.log(web3.eth.getTransactionCount("0x9e713963a92c02317a681b9bb3065a8249de124f"));
12 |
13 | console.log("getTransactionCount (pending)");
14 | console.log(web3.eth.getTransactionCount("0x9e713963a92c02317a681b9bb3065a8249de124f", "pending"));
15 |
16 | console.log("sendTransaction");
17 | console.log(web3.eth.sendTransaction({from: web3.eth.accounts[0], to: "0xB0920c523d582040f2BCB1bD7FB1c7C1ECEbdB34", value: web3.utils.toWei(0.01, "ether")}));
18 |
19 | console.log("getTransactionCount (confirmed)");
20 | console.log(web3.eth.getTransactionCount("0x9e713963a92c02317a681b9bb3065a8249de124f"));
21 |
22 | console.log("getTransactionCount (pending)");
23 | console.log(web3.eth.getTransactionCount("0x9e713963a92c02317a681b9bb3065a8249de124f", "pending"));
24 |
25 | console.log("sendTransaction");
26 | console.log(web3.eth.sendTransaction({from: web3.eth.accounts[0], to: "0xB0920c523d582040f2BCB1bD7FB1c7C1ECEbdB34", value: web3.utils.toWei(0.01, "ether")}));
27 |
28 | console.log("getTransactionCount (confirmed)");
29 | console.log(web3.eth.getTransactionCount("0x9e713963a92c02317a681b9bb3065a8249de124f"));
30 |
31 | console.log("getTransactionCount (pending)");
32 | console.log(web3.eth.getTransactionCount("0x9e713963a92c02317a681b9bb3065a8249de124f", "pending"));
33 |
34 | console.log("sendTransaction");
35 | console.log(web3.eth.sendTransaction({from: web3.eth.accounts[0], to: "0xB0920c523d582040f2BCB1bD7FB1c7C1ECEbdB34", value: web3.utils.toWei(0.01, "ether")}));
36 |
--------------------------------------------------------------------------------
/code/auction_dapp/frontend/src/models/ChatRoom.js:
--------------------------------------------------------------------------------
1 | import Config from '../config'
2 |
3 | export class ChatRoom {
4 | web3 = null
5 | keyID = ''
6 | privateKey = ''
7 | publicKey = ''
8 | conn = null
9 | room = ''
10 | identity = ''
11 |
12 | constructor(){
13 | this.privateKey = Config.WHISPER_SHARED_KEY
14 | }
15 |
16 | async setWeb3(web3){
17 | this.web3 = web3
18 | this.keyID = await this.web3.shh.addPrivateKey(this.privateKey)
19 | this.publicKey = await this.web3.shh.getPublicKey(this.keyID)
20 | }
21 |
22 | getWeb3(){
23 | return this.web3
24 | }
25 |
26 | async getWeb3ConnStatusAction() {
27 | return await this.web3.shh.net.isListening()
28 | }
29 |
30 | async subscribeToTopic(topic, fn) {
31 | this.conn = this.web3.shh.subscribe("messages", {
32 | privateKeyID: this.keyID,
33 | //topics: [this.web3.utils.stringToHex(topic)]
34 | topics: [topic]
35 | }).on('data', fn)
36 | }
37 |
38 | async sendJoinEvent(identity, room, data) {
39 | const messageRaw = {
40 | identity: identity,
41 | type: "join",
42 | data: data
43 | }
44 | return await this.sendRawWhisperMessage(messageRaw, room )
45 | }
46 |
47 | async sendMessageEvent(identity, room, data) {
48 | const messageRaw = {
49 | identity: identity,
50 | type: "msg",
51 | data: data
52 | }
53 | return await this.sendRawWhisperMessage(messageRaw, room )
54 | }
55 |
56 | async sendRawWhisperMessage(msg, topic){
57 | return await this.web3.shh.post({
58 | pubKey: this.publicKey, // encrypts using the sym key ID
59 | ttl: 10,
60 | //topic: this.web3.utils.stringToHex(topic),
61 | topic: topic,
62 | payload: this.web3.utils.stringToHex(JSON.stringify(msg)),
63 | powTime: 60,
64 | powTarget: 0.2
65 | })
66 | }
67 |
68 | }
--------------------------------------------------------------------------------
/atlas.json:
--------------------------------------------------------------------------------
1 | {
2 | "branch": "master",
3 | "files": [
4 | "cover.html",
5 | "praise.html",
6 | "titlepage.html",
7 | "copyright.html",
8 | "toc.html",
9 | "preface.asciidoc",
10 | "glossary.asciidoc",
11 | "01what-is.asciidoc",
12 | "02intro.asciidoc",
13 | "03clients.asciidoc",
14 | "04keys-addresses.asciidoc",
15 | "05wallets.asciidoc",
16 | "06transactions.asciidoc",
17 | "07smart-contracts-solidity.asciidoc",
18 | "08smart-contracts-vyper.asciidoc",
19 | "09smart-contracts-security.asciidoc",
20 | "10tokens.asciidoc",
21 | "11oracles.asciidoc",
22 | "12dapps.asciidoc",
23 | "13evm.asciidoc",
24 | "14consensus.asciidoc",
25 | "appdx-forks-history.asciidoc",
26 | "appdx-standards-eip-erc.asciidoc",
27 | "appdx-evm-opcodes-gas.asciidoc",
28 | "appdx-dev-tools.asciidoc",
29 | "appdx-web3js-tutorial.asciidoc",
30 | "appdx-shortlinks.asciidoc",
31 | "ix.html",
32 | "author_bio.html",
33 | "colo.html"
34 | ],
35 | "formats": {
36 | "pdf": {
37 | "version": "web",
38 | "toc": true,
39 | "index": true,
40 | "syntaxhighlighting": true,
41 | "show_comments": false,
42 | "antennahouse_version": "AHFormatterV62_64-MR4",
43 | "color_count": "1",
44 | "trim_size": "7inx9.1875in"
45 | },
46 | "epub": {
47 | "toc": true,
48 | "index": true,
49 | "syntaxhighlighting": true,
50 | "epubcheck": true,
51 | "show_comments": false,
52 | "downsample_images": true,
53 | "mathmlreplacement": false
54 | },
55 | "mobi": {
56 | "toc": true,
57 | "index": true,
58 | "syntaxhighlighting": true,
59 | "show_comments": false,
60 | "downsample_images": false
61 | },
62 | "html": {
63 | "toc": true,
64 | "index": true,
65 | "syntaxhighlighting": true,
66 | "show_comments": false,
67 | "consolidated": true
68 | }
69 | },
70 | "theme": "oreillymedia/animal_theme_sass",
71 | "title": "Mastering Ethereum",
72 | "templating": true,
73 | "print_isbn13": "9781491971949",
74 | "lang": "en",
75 | "accent_color": "cmyk(12%, 100%, 92%, 3%)"
76 | }
--------------------------------------------------------------------------------
/theme/pdf/pdf.css:
--------------------------------------------------------------------------------
1 | @charset "UTF-8";
2 |
3 | /*--------Put Your Custom CSS Rules Below--------*/
4 |
5 | /* Font fallback for character not represented in
6 | standard monospace font */
7 | pre, code { font-family: UbuntuMono, monospace, ArialUnicodeMS; }
8 |
9 | pre.codewrap {
10 | white-space: pre-wrap;
11 | word-wrap: break-word;
12 | }
13 |
14 | /* Appendix C custom table column widths (STYL-1104) */
15 | table#evm_opcodes_table { width: 100%; }
16 | table#evm_opcodes_table p > * { word-wrap: break-word; }
17 | table#evm_opcodes_table td:nth-child(3) { width: 34%; }
18 | table#evm_opcodes_table td:nth-child(4) { width: 24%; }
19 | table#evm_opcodes_table td:nth-child(5) { width: 7%; }
20 |
21 | /*----Uncomment to temporarily turn on code-eyballer highlighting (make sure to recomment after you build)
22 | pre {
23 | background-color: yellow;
24 | }
25 | ---*/
26 |
27 | /*----Uncomment to turn on automatic code wrapping
28 | pre {
29 | white-space: pre-wrap;
30 | word-wrap: break-word;
31 | }
32 | ----*/
33 |
34 | /*----Uncomment to change the TOC start page (set
35 | the number to one page _after_ the one you want;
36 | so 6 to start on v, 8 to start on vii, etc.)
37 | @page toc:first {
38 | counter-reset: page 6;
39 | }
40 | ----*/
41 |
42 | /*----Uncomment to fix a bad break in the title
43 | (increase padding value to push down, decrease
44 | value to pull up)
45 | section[data-type="titlepage"] h1 {
46 | padding-left: 1.5in;
47 | }
48 | ----*/
49 |
50 | /*----Uncomment to fix a bad break in the subtitle
51 | (increase padding value to push down, decrease
52 | value to pull up)
53 | section[data-type="titlepage"] h2 {
54 | padding-left: 1in;
55 | }
56 | ----*/
57 |
58 | /*----Uncomment to fix a bad break in the author names
59 | (increase padding value to push down, decrease
60 | value to pull up)
61 | section[data-type="titlepage"] p.author {
62 | padding-left: 3in;
63 | }
64 | ----*/
65 |
66 | /* ----Uncomment to suppress duplicate page numbers in index entries
67 | WARNING: MAY CAUSE PDF BUILDS TO SEGFAULT
68 | div[data-type="index"] {
69 | -ah-suppress-duplicate-page-number: true;
70 | }
71 | ----*/
72 |
--------------------------------------------------------------------------------
/code/auction_dapp/frontend/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "frontend",
3 | "version": "1.0.0",
4 | "description": "Auction Dapp powered by Ethereum",
5 | "author": "iNDicat0r ",
6 | "private": true,
7 | "scripts": {
8 | "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
9 | "start": "npm run dev",
10 | "build": "node build/build.js"
11 | },
12 | "dependencies": {
13 | "ethereumjs-util": "^5.1.5",
14 | "moment": "^2.22.0",
15 | "vue": "^2.5.2",
16 | "vue-resource": "^1.5.0",
17 | "vue-router": "^3.0.1",
18 | "vuetify": "^0.17.6",
19 | "web3": "^1.0.0-beta.31",
20 | "web3-shh": "^1.0.0-beta.31"
21 | },
22 | "devDependencies": {
23 | "autoprefixer": "^7.1.2",
24 | "babel-core": "^6.22.1",
25 | "babel-helper-vue-jsx-merge-props": "^2.0.3",
26 | "babel-loader": "^7.1.1",
27 | "babel-plugin-syntax-jsx": "^6.18.0",
28 | "babel-plugin-transform-runtime": "^6.22.0",
29 | "babel-plugin-transform-vue-jsx": "^3.5.0",
30 | "babel-preset-env": "^1.3.2",
31 | "babel-preset-stage-2": "^6.22.0",
32 | "chalk": "^2.0.1",
33 | "copy-webpack-plugin": "^4.0.1",
34 | "css-loader": "^0.28.0",
35 | "extract-text-webpack-plugin": "^3.0.0",
36 | "file-loader": "^1.1.4",
37 | "friendly-errors-webpack-plugin": "^1.6.1",
38 | "html-webpack-plugin": "^2.30.1",
39 | "node-notifier": "^5.1.2",
40 | "optimize-css-assets-webpack-plugin": "^3.2.0",
41 | "ora": "^1.2.0",
42 | "portfinder": "^1.0.13",
43 | "postcss-import": "^11.0.0",
44 | "postcss-loader": "^2.0.8",
45 | "postcss-url": "^7.2.1",
46 | "rimraf": "^2.6.0",
47 | "semver": "^5.3.0",
48 | "shelljs": "^0.7.6",
49 | "uglifyjs-webpack-plugin": "^1.1.1",
50 | "url-loader": "^0.5.8",
51 | "vue-loader": "^13.3.0",
52 | "vue-style-loader": "^3.0.1",
53 | "vue-template-compiler": "^2.5.2",
54 | "webpack": "^3.6.0",
55 | "webpack-bundle-analyzer": "^2.9.0",
56 | "webpack-dev-server": "^2.9.1",
57 | "webpack-merge": "^4.1.0"
58 | },
59 | "engines": {
60 | "node": ">= 6.0.0",
61 | "npm": ">= 3.0.0"
62 | },
63 | "browserslist": [
64 | "> 1%",
65 | "last 2 versions",
66 | "not ie <= 8"
67 | ]
68 | }
69 |
--------------------------------------------------------------------------------
/code/auction_dapp/frontend/config/index.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 | // Template version: 1.2.8
3 | // see http://vuejs-templates.github.io/webpack for documentation.
4 |
5 | const path = require('path')
6 |
7 | module.exports = {
8 | dev: {
9 |
10 | // Paths
11 | assetsSubDirectory: 'static',
12 | assetsPublicPath: '/',
13 | proxyTable: {},
14 |
15 | // Various Dev Server settings
16 | host: 'localhost', // can be overwritten by process.env.HOST
17 | port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
18 | autoOpenBrowser: false,
19 | errorOverlay: true,
20 | notifyOnErrors: true,
21 | poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
22 |
23 |
24 | /**
25 | * Source Maps
26 | */
27 |
28 | // https://webpack.js.org/configuration/devtool/#development
29 | devtool: 'cheap-module-eval-source-map',
30 |
31 | // If you have problems debugging vue-files in devtools,
32 | // set this to false - it *may* help
33 | // https://vue-loader.vuejs.org/en/options.html#cachebusting
34 | cacheBusting: true,
35 |
36 | cssSourceMap: true,
37 | },
38 |
39 | build: {
40 | // Template for index.html
41 | index: path.resolve(__dirname, '../dist/index.html'),
42 |
43 | // Paths
44 | assetsRoot: path.resolve(__dirname, '../dist'),
45 | assetsSubDirectory: 'static',
46 | assetsPublicPath: '/',
47 |
48 | /**
49 | * Source Maps
50 | */
51 |
52 | productionSourceMap: true,
53 | // https://webpack.js.org/configuration/devtool/#production
54 | devtool: '#source-map',
55 |
56 | // Gzip off by default as many popular static hosts such as
57 | // Surge or Netlify already gzip all static assets for you.
58 | // Before setting to `true`, make sure to:
59 | // npm install --save-dev compression-webpack-plugin
60 | productionGzip: false,
61 | productionGzipExtensions: ['js', 'css'],
62 |
63 | // Run the build command with an extra argument to
64 | // View the bundle analyzer report after build finishes:
65 | // `npm run build --report`
66 | // Set to `true` or `false` to always turn it on or off
67 | bundleAnalyzerReport: process.env.npm_config_report
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/code/auction_dapp/frontend/build/webpack.base.conf.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 | const path = require('path')
3 | const utils = require('./utils')
4 | const config = require('../config')
5 | const vueLoaderConfig = require('./vue-loader.conf')
6 |
7 | function resolve (dir) {
8 | return path.join(__dirname, '..', dir)
9 | }
10 |
11 |
12 |
13 | module.exports = {
14 | context: path.resolve(__dirname, '../'),
15 | entry: {
16 | app: './src/main.js'
17 | },
18 | output: {
19 | path: config.build.assetsRoot,
20 | filename: '[name].js',
21 | publicPath: process.env.NODE_ENV === 'production'
22 | ? config.build.assetsPublicPath
23 | : config.dev.assetsPublicPath
24 | },
25 | resolve: {
26 | extensions: ['.js', '.vue', '.json'],
27 | alias: {
28 | 'vue$': 'vue/dist/vue.esm.js',
29 | '@': resolve('src'),
30 | }
31 | },
32 | module: {
33 | rules: [
34 | {
35 | test: /\.vue$/,
36 | loader: 'vue-loader',
37 | options: vueLoaderConfig
38 | },
39 | {
40 | test: /\.js$/,
41 | loader: 'babel-loader',
42 | include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
43 | },
44 | {
45 | test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
46 | loader: 'url-loader',
47 | options: {
48 | limit: 10000,
49 | name: utils.assetsPath('img/[name].[hash:7].[ext]')
50 | }
51 | },
52 | {
53 | test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
54 | loader: 'url-loader',
55 | options: {
56 | limit: 10000,
57 | name: utils.assetsPath('media/[name].[hash:7].[ext]')
58 | }
59 | },
60 | {
61 | test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
62 | loader: 'url-loader',
63 | options: {
64 | limit: 10000,
65 | name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
66 | }
67 | }
68 | ]
69 | },
70 | node: {
71 | // prevent webpack from injecting useless setImmediate polyfill because Vue
72 | // source contains it (although only uses it if it's native).
73 | setImmediate: false,
74 | // prevent webpack from injecting mocks to Node native modules
75 | // that does not make sense for the client
76 | dgram: 'empty',
77 | fs: 'empty',
78 | net: 'empty',
79 | tls: 'empty',
80 | child_process: 'empty'
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/book.asciidoc:
--------------------------------------------------------------------------------
1 | = Mastering Ethereum
2 | :author: Andreas M. Antonopoulos, Gavin Wood
3 | :doctype: book
4 | :toc:
5 | :toclevels: 6
6 | :media: prepress
7 | :icons: font
8 | :pdf-page-size: 8in x 9in
9 | :pdf-style: misc/theme.yml
10 |
11 | == LICENSE
12 |
13 | This copy is for PERSONAL USE ONLY. You may read it for free. You may NOT distribute this book. _Mastering Ethereum_ is licensed CC-BY-NC-ND. The "NC-ND" part of the license means no commercial use and NO DERIVATIVES. Derivatives include: HTML, PDF, ebook, mobi, Kindle or other "typeset" versions. You cannot create derivatives.
14 |
15 | You are not allowed to publish a PDF "for convenience". That is a gross violation of the (already generous) open license. You are not allowed to translate and publish a derivative. Translation licensing rights must be negotiated with the publisher O'Reilly Media.
16 |
17 | _Mastering Ethereum_ will be released under an open license (CC-BY-SA) in January 2020, one year after initial publication. Until then, please respect the work of the publisher, the authors and their licensing terms. Just because you can produce a PDF and just because this book is available for free online does not mean you can violate the rights of the publisher and authors.
18 |
19 | Violating this license does more than rob the authors and publishers of the ability to benefit financially from their hard work. It also discourages them and other authors and publishers from releasing books in an open, free-to-read format like this and deprives our creative commons.
20 |
21 |
22 | include::preface.asciidoc[]
23 |
24 | include::glossary.asciidoc[]
25 |
26 | include::01what-is.asciidoc[]
27 |
28 | include::02intro.asciidoc[]
29 |
30 | include::03clients.asciidoc[]
31 |
32 | include::04keys-addresses.asciidoc[]
33 |
34 | include::05wallets.asciidoc[]
35 |
36 | include::06transactions.asciidoc[]
37 |
38 | include::07smart-contracts-solidity.asciidoc[]
39 |
40 | include::08smart-contracts-vyper.asciidoc[]
41 |
42 | include::09smart-contracts-security.asciidoc[]
43 |
44 | include::10tokens.asciidoc[]
45 |
46 | include::11oracles.asciidoc[]
47 |
48 | include::12dapps.asciidoc[]
49 |
50 | include::13evm.asciidoc[]
51 |
52 | include::14consensus.asciidoc[]
53 |
54 | [appendix]
55 | include::appdx-forks-history.asciidoc[]
56 |
57 | [appendix]
58 | include::appdx-standards-eip-erc.asciidoc[]
59 |
60 | [appendix]
61 | include::appdx-evm-opcodes-gas.asciidoc[]
62 |
63 | [appendix]
64 | include::appdx-dev-tools.asciidoc[]
65 |
66 | [appendix]
67 | include::appdx-web3js-tutorial.asciidoc[]
68 |
69 | [index]
70 | == Index
71 |
--------------------------------------------------------------------------------
/code/auction_dapp/backend/test/2_deedrepository.js:
--------------------------------------------------------------------------------
1 | var DeedRepository = artifacts.require("./DeedRepository.sol");
2 | const fs = require('fs');
3 |
4 | contract('DeedRepository', async (accounts) => {
5 |
6 | let instance;
7 | let auctionContractAddress = "";
8 |
9 | beforeEach('setup contract for each test', async function () {
10 | instance = await DeedRepository.deployed();
11 | auctionContractAddress = fs.readFileSync("./test/output.address").toString()
12 | })
13 |
14 | it("It should create an deed repository with UANFT as symbol", async () => {
15 | let symbol = await instance.symbol();
16 | assert.equal(symbol.valueOf(), 'UANFT' , `Deedrepository symbol should be UANFT`);
17 | });
18 |
19 | it("It should register a deed with id: 123456789", async () => {
20 | await instance.registerDeed(accounts[0], 123456789);
21 | let ownerOfDeed = await instance.exists(123456789);
22 | assert.equal(ownerOfDeed.valueOf(), true , `Result should be true`);
23 | });
24 |
25 | it(`It should check owner of 123456789 who is ${accounts[0]}`, async () => {
26 | let ownerOfDeed = await instance.ownerOf(123456789);
27 | assert.equal(ownerOfDeed.valueOf(), accounts[0] , `Owner should be ${accounts[0]}`);
28 | });
29 |
30 | it(`It should check balance of ${accounts[0]}`, async () => {
31 | let balance = await instance.balanceOf(accounts[0]);
32 | assert.equal(balance.valueOf(), 1 , `balance ${balance} should be 1`);
33 | });
34 |
35 | it(`It should check total supply of the repository`, async () => {
36 | let supply = await instance.totalSupply();
37 | assert.equal(supply.valueOf(), 1 , `total supply: ${supply} should be 1`);
38 | });
39 |
40 | it(`It should approve transfer the ownership of 123456789 to the auctionRepository address`, async () => {
41 | await instance.approve(auctionContractAddress, 123456789);
42 | // console.log('this auction address:', auctionAddress, ' deedrepo instance addr', instance.address);
43 | let address = await instance.getApproved(123456789);
44 | assert.equal(address.valueOf(), auctionContractAddress, `${address} should be equal to ${auctionContractAddress}`);
45 | });
46 |
47 | it("It should transfer ownership of deed 123456789 to this contract", async () => {
48 | await instance.transferFrom( accounts[0] ,auctionContractAddress, 123456789, { from: accounts[0]});
49 | let newOwnerAddress = await instance.ownerOf(123456789);
50 | //let success = await instance.isApprovedOrOwner(auctionAddress, 123456789)
51 | assert.equal(newOwnerAddress.valueOf(), auctionContractAddress, `${newOwnerAddress} should be ${auctionContractAddress}`);
52 | });
53 |
54 |
55 | });
--------------------------------------------------------------------------------
/code/auction_dapp/frontend/src/models/DeedRepository.js:
--------------------------------------------------------------------------------
1 | import Config from '../config'
2 |
3 | export class DeedRepository {
4 |
5 | web3 = null
6 | account = ''
7 | contractInstance = null
8 | gas = 4476768
9 |
10 | constructor(){
11 | this.gas = Config.GAS_AMOUNT
12 | }
13 | setWeb3(web3) {
14 | this.web3 = web3
15 | this.contractInstance = this.web3.eth.contract(Config.DEEDREPOSITORY_ABI).at(Config.DEEDREPOSITORY_ADDRESS)
16 | }
17 |
18 | getWeb3() {
19 | return this.web3
20 | }
21 |
22 | setAccount(account){
23 | this.account = account
24 | }
25 |
26 | getCurrentBlock() {
27 | return new Promise((resolve, reject ) => {
28 | this.web3.eth.getBlockNumber((err, blocknumber) => {
29 | if(!err) resolve(blocknumber)
30 | reject(err)
31 | })
32 | })
33 | }
34 |
35 | // getAccounts() {
36 | // return new Promise((resolve, reject ) => {
37 | // this.web3.eth.getAccounts((err, accounts) => {
38 | // if(!err) resolve(accounts)
39 | // reject(err)
40 | // })
41 | // })
42 | // }
43 |
44 | async watchIfCreated(cb) {
45 | const currentBlock = await this.getCurrentBlock()
46 | const eventWatcher = this.contractInstance.DeedRegistered({}, {fromBlock: currentBlock - 1, toBlock: 'latest'})
47 | eventWatcher.watch(cb)
48 | }
49 |
50 | async watchIfDeedTransfered(cb) {
51 | const currentBlock = await this.getCurrentBlock()
52 | const eventWatcher = this.contractInstance.Transfer({}, {fromBlock: currentBlock - 1, toBlock: 'latest'})
53 | eventWatcher.watch(cb)
54 | }
55 |
56 | exists(deedId) {
57 | return new Promise(async (resolve, reject) => {
58 | this.contractInstance.exists(deedId, {from: this.account, gas: this.gas }, (err, transaction) => {
59 | if(!err) resolve(transaction)
60 | reject(err)
61 | })
62 | })
63 | }
64 |
65 | transferTo(to, deedId) {
66 | return new Promise(async (resolve, reject) => {
67 | this.contractInstance.transferFrom(this.account, to, deedId, {from: this.account, gas: this.gas }, (err, transaction) => {
68 | if(!err) resolve(transaction)
69 | reject(err)
70 | })
71 | })
72 |
73 | }
74 |
75 | create(deedId, deedURI) {
76 | console.log('contractinsatnce', this.contractInstance )
77 | return new Promise(async (resolve, reject) => {
78 | this.contractInstance.registerDeed(deedId, deedURI, {from: this.account, gas: this.gas }, (err, transaction) => {
79 | if(!err)
80 | resolve(transaction)
81 | else
82 | reject(err)
83 | })
84 | })
85 | }
86 | }
--------------------------------------------------------------------------------
/author_bio.html:
--------------------------------------------------------------------------------
1 |
2 |
About the Authors
3 |
4 |
Andreas M. Antonopoulos is a critically acclaimed bestselling author, speaker, and educator, and one of the world’s foremost Bitcoin and open blockchain experts. Andreas makes complex subjects accessible and easy to understand. He is known for delivering electric talks that combine economics, psychology, technology, and game theory with current events, personal anecdotes, and historical precedent—effortlessly transliterating the complex issues of blockchain technology out of the abstract and into the real world.
5 |
6 |
In 2014, Andreas authored the groundbreaking book Mastering Bitcoin (O’Reilly Media), widely considered to be the best technical guide ever written about the technology. His second book, The Internet of Money (Merkle Bloom LLC)—which explains the technology’s potential impacts on human civilization—is a bestseller on Amazon. The much-anticipated second volume of The Internet of Money was released in fall 2017 and sold thousands of copies in the first month alone. Mastering Ethereum is his fourth book.
7 |
8 |
9 |
Dr. Gavin Wood has a lifelong interest in the intersection of game theory, society, and technology. He began programming at the age of 9 and became an award winning developer during the Commodore Amiga while at the Royal Grammar School in Lancaster, UK. At the University of York he gained a PhD in computer science and cemented his reputation as a prolific open source coder, leading and contributing to many projects (the most prominent being KDE). His professional career includes time at a premier games house (creating a cross-platform high-performance audio engine) and Microsoft Research (writing embedded C++ domain-specific languages). Outside professional work he has taught maths, art and English to school children, and designed board games (including “Milton Keynes”), voting systems, and advanced programming tools (culminating in the first C++ language workbench). Two startups later, a mutual friend made the introduction to Vitalik Buterin, and within a few weeks he finished coding the first functional implementation of Ethereum. He quickly became Ethereum’s CTO and effective platform architect. He coined the terms “EVM,” “PoA,” and “Web 3.0,” with the latter being his forward-looking idea for the decentralized web platform. He devised the Solidity contract language and wrote the Yellow Paper, the first formal specification of any blockchain protocol and one of the key ways Ethereum distinguishes itself from other blockchains.
10 |
11 |
In the months after Ethereum launched, Gavin left his position as CTO of the Ethereum Foundation with several others and founded Parity Technologies, a venture-backed firm set up to continue building out his original Ethereum vision. He now also serves as the founder and president of the Web3 Foundation and is currently focused on Polkadot, a next-generation blockchain intended to provide a platform for future innovations in the space.
12 |
13 |
14 |
--------------------------------------------------------------------------------
/code/auction_dapp/frontend/build/utils.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 | const path = require('path')
3 | const config = require('../config')
4 | const ExtractTextPlugin = require('extract-text-webpack-plugin')
5 | const packageConfig = require('../package.json')
6 |
7 | exports.assetsPath = function (_path) {
8 | const assetsSubDirectory = process.env.NODE_ENV === 'production'
9 | ? config.build.assetsSubDirectory
10 | : config.dev.assetsSubDirectory
11 |
12 | return path.posix.join(assetsSubDirectory, _path)
13 | }
14 |
15 | exports.cssLoaders = function (options) {
16 | options = options || {}
17 |
18 | const cssLoader = {
19 | loader: 'css-loader',
20 | options: {
21 | sourceMap: options.sourceMap
22 | }
23 | }
24 |
25 | const postcssLoader = {
26 | loader: 'postcss-loader',
27 | options: {
28 | sourceMap: options.sourceMap
29 | }
30 | }
31 |
32 | // generate loader string to be used with extract text plugin
33 | function generateLoaders (loader, loaderOptions) {
34 | const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]
35 |
36 | if (loader) {
37 | loaders.push({
38 | loader: loader + '-loader',
39 | options: Object.assign({}, loaderOptions, {
40 | sourceMap: options.sourceMap
41 | })
42 | })
43 | }
44 |
45 | // Extract CSS when that option is specified
46 | // (which is the case during production build)
47 | if (options.extract) {
48 | return ExtractTextPlugin.extract({
49 | use: loaders,
50 | fallback: 'vue-style-loader'
51 | })
52 | } else {
53 | return ['vue-style-loader'].concat(loaders)
54 | }
55 | }
56 |
57 | // https://vue-loader.vuejs.org/en/configurations/extract-css.html
58 | return {
59 | css: generateLoaders(),
60 | postcss: generateLoaders(),
61 | less: generateLoaders('less'),
62 | sass: generateLoaders('sass', { indentedSyntax: true }),
63 | scss: generateLoaders('sass'),
64 | stylus: generateLoaders('stylus'),
65 | styl: generateLoaders('stylus')
66 | }
67 | }
68 |
69 | // Generate loaders for standalone style files (outside of .vue)
70 | exports.styleLoaders = function (options) {
71 | const output = []
72 | const loaders = exports.cssLoaders(options)
73 |
74 | for (const extension in loaders) {
75 | const loader = loaders[extension]
76 | output.push({
77 | test: new RegExp('\\.' + extension + '$'),
78 | use: loader
79 | })
80 | }
81 |
82 | return output
83 | }
84 |
85 | exports.createNotifierCallback = () => {
86 | const notifier = require('node-notifier')
87 |
88 | return (severity, errors) => {
89 | if (severity !== 'error') return
90 |
91 | const error = errors[0]
92 | const filename = error.file && error.file.split('!').pop()
93 |
94 | notifier.notify({
95 | title: packageConfig.name,
96 | message: severity + ': ' + error.name,
97 | subtitle: filename || '',
98 | icon: path.join(__dirname, 'logo.png')
99 | })
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/code/auction_dapp/README.md:
--------------------------------------------------------------------------------
1 | # Decentralized Auction Application on Ethereum
2 |
3 | This project aims to implement basic functionalities of an auction platform using Ethereum.
4 |
5 | ## Requirements
6 |
7 | 
8 |
9 | The application should be decentralized and utilize Ethereum's stack:
10 |
11 | 1. Smart contracts for business logic(auctions, bids, refund and transfer of ownership)
12 | 2. Swarm for data storage(image and metadata)
13 | 3. Whisper for a peer-to-peer messaging(chatrooms)
14 |
15 | ### Deed Repository
16 | Manage non-fungible tokens by implementing an asset/token/deed repository which holds unique asset/token/deed.
17 |
18 | #### ERC: Non-fungible Token Standard #721 (NFT)
19 | See following link:
20 | https://github.com/ethereum/eips/issues/721
21 |
22 | ### Auction Repository
23 |
24 | Auction repository MUST act as an auction house which does the following:
25 |
26 | - Holds asset/token/deed that is to be auctioned(ERC721 Ownership by smart contract)
27 | - Allows users bid on auctions
28 | - Keeps track of auctions/bids/ownership
29 | - Transfers ownership of asset/token/deed to winder
30 | - Transfers Funds to auction creator if auction is ended and there is at least one winner
31 | - Cancels auction and deal with refunds
32 | - UI to interact with the above functionality
33 |
34 | ### Front-end: Vuejs2.x + Vuetify
35 |
36 | The front-end is developed using a reactive UI framework with integration of Vuetify, a Google's Material Design implementation.
37 |
38 | ## Implementation/Data flow
39 |
40 | #### 1. Register an ERC721 Non-Fungible Token with the AuctionDaap Deed Repository
41 |
42 | The idea of a Deed Repository is used across this project to hold any NFT with metadata attached to. A token/deed is registered by giving a unique ID and attaching metadata(TokenURI). The metadata is what makes each token important or valuable.
43 |
44 | #### 2. Transfer Ownership of the NFT to AuctionRepository(Auction house)
45 |
46 | The Auction house needs to verify that a NFT is owned by the auction creator, therefore before the auction is created, the owner should transfer the ownership of the NFT to the AuctionRepository smart contract address.
47 |
48 | #### 3. Create Auction for NFT
49 |
50 | Creating the auction is a simple process of entering auction details such as name, starting price, expiry date etc. The important part is to have the reference between the deed and the auction.
51 |
52 | #### 4. Bid on Auction
53 |
54 | Anyone can bid on an auction except the owner of the auction. Biding means that previous bidders are refunded and new bid is placed. Bid requirements are as follow:
55 | 1. Auction not expired
56 | 2. Bidder is not auction owner
57 | 3. Bid amount is greator than current bid or starting price(if no bid)
58 |
59 | #### 5. Refunds
60 |
61 | If an auction is canceled, the Auction Repository MUST return the ownership of the asset/token/deed back to the auction creator and refund bidders if any.
62 |
63 | #### 6. Bidder Win Auction
64 |
65 | If there is an auction winner, the asset/token/deed is transferred to the bidder and the bid amount is sent to the auction creator.
66 |
67 |
--------------------------------------------------------------------------------
/praise.html:
--------------------------------------------------------------------------------
1 |
2 |
Praise for Mastering Ethereum
3 |
4 |
5 |
“Mastering Ethereum is a fantastically thorough guide, from basics to state-of-the-art practices in smart contract programming, by two of the most eloquent blockchain educators."
6 |
Manuel Araoz, CTO, Zeppelin
7 |
8 |
9 |
10 |
Mastering Bitcoin is the canonical reference that made Bitcoin and blockchain technology accessible to a broad audience, and Mastering Ethereum does the same for the Ethereum world computer.
11 |
Lane Rettig, Ethereum core developer
12 |
13 |
14 |
15 |
“Mastering Ethereum is the absolute best book to read if you’re ready to build your own DApp! Andreas and Gavin have put together a comprehensive guide for anyone interested in the decentralized web and how to build decentralized applications.”
16 |
Taylor Gerring, Executive Director, Blockchain Institute
17 |
18 |
19 |
20 |
“I had the privilege of having access to Andreas’ and Gav’s book Mastering Ethereum, and I have to say I’m amazed at its breadth, scope, and accessibility. It has it all: a deep history of Ethereum, explanations of elliptical curve mathematics, solidity tutorials, and legal debates on utility tokens and ICOs. It’s deep enough that it can be used as a whole syllabus of reference material, yet it’s accessible enough that anyone who is merely math-curious can understand. After reading a few chapters on the topic, I feel I have a much more solid understanding of many of the underlying cryptographic primitives. If you’re a researcher, a developer, a manager, a lawyer, a student, or anyone curious about where the future of tech is going, I highly recommend having Mastering Ethereum on your shelf.”
21 |
Alex Van de Sande, designer, Ethereum Foundation
22 |
23 |
24 |
25 |
“Mastering Ethereum will become a must-read in the future, as Ethereum is going to be as ubiquitous as TCP/IP. It will become a necessary layer under which decentralized, trustless technologies live and thrive.”
26 |
Hudson Jameson, Community Organizer, Ethereum Foundation
27 |
28 |
29 |
30 |
“Mastering Ethereum is the perfect book for anyone who wants to learn more about Ethereum, whether you're looking to test the waters or dive straight into the deep end. Between Gavin Wood's technical knowledge of Ethereum's inner workings and Andreas Antonopoulos' ability to make complex subjects approachable, you get the best of both worlds with this book. I only wish it had been around when I first started diving into Ethereum.”
Published by O'Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
11 |
12 |
O'Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com/safari). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com.
13 |
14 |
15 |
Acquisitions Editor: Rachel Roumeliotis
16 |
Developmental Editor: Michele Cronin
17 |
GitHub Editor: Will Binns
18 |
Production Editors: Nicholas Adams and Kristen Brown
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Mastering Ethereum, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc.
44 |
45 |
The views expressed in this work are those of the authors, and do not represent the publisher's views. While the publisher and the authors have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the authors disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.
49 |
50 |
Mastering Ethereum is available under the Creative Commons Attribution-
51 | Noncommercial-No Derivative Works 4.0 International License (CC BY-NC-ND
52 | 4.0). The author maintains an online version at https://github.com/ethereumbook/ethereumbook.
53 |
54 |
55 |
56 |
978-1-491-97194-9
57 |
58 |
[LSI]
59 |
60 |
61 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Mastering Ethereum
2 |
3 | 
4 |
5 | Mastering Ethereum is a book for developers, offering a guide to the operation and use of the Ethereum, Ethereum Classic, RootStock (RSK) and other compatible EVM-based open blockchains.
6 |
7 | ## Reading this book
8 |
9 | To read this book, see [book.asciidoc](https://github.com/ethereumbook/ethereumbook/blob/develop/book.asciidoc). Click on each of the chapters to read in your browser. Other parties may choose to release PDFs of the book online.
10 |
11 | ## Chapters
12 | + Preface: '[Preface](https://github.com/ethereumbook/ethereumbook/blob/develop/preface.asciidoc)'
13 | + Chapter 1: '[What Is Ethereum](https://github.com/ethereumbook/ethereumbook/blob/develop/01what-is.asciidoc)'
14 | + Chapter 2: '[Ethereum Basics](https://github.com/ethereumbook/ethereumbook/blob/develop/02intro.asciidoc)'
15 | + Chapter 3: '[Ethereum Clients](https://github.com/ethereumbook/ethereumbook/blob/develop/03clients.asciidoc)'
16 | + Chapter 4: '[Cryptography](https://github.com/ethereumbook/ethereumbook/blob/develop/04keys-addresses.asciidoc)'
17 | + Chapter 5: '[Wallets](https://github.com/ethereumbook/ethereumbook/blob/develop/05wallets.asciidoc)'
18 | + Chapter 6: '[Transactions](https://github.com/ethereumbook/ethereumbook/blob/develop/06transactions.asciidoc)'
19 | + Chapter 7: '[Smart Contracts and Solidity](https://github.com/ethereumbook/ethereumbook/blob/develop/07smart-contracts-solidity.asciidoc)'
20 | + Chapter 8: '[Smart Contracts and Vyper](https://github.com/ethereumbook/ethereumbook/blob/develop/08smart-contracts-vyper.asciidoc)'
21 | + Chapter 9: '[Smart Contract Security](https://github.com/ethereumbook/ethereumbook/blob/develop/09smart-contracts-security.asciidoc)'
22 | + Chapter 10: '[Tokens](https://github.com/ethereumbook/ethereumbook/blob/develop/10tokens.asciidoc)'
23 | + Chapter 11: '[Oracles](https://github.com/ethereumbook/ethereumbook/blob/develop/11oracles.asciidoc)'
24 | + Chapter 12: '[Decentralized Applications (DApps)](https://github.com/ethereumbook/ethereumbook/blob/develop/12dapps.asciidoc)'
25 | + Chapter 13: '[The Ethereum Virtual Machine](https://github.com/ethereumbook/ethereumbook/blob/develop/13evm.asciidoc)'
26 | + Chapter 14: '[Consensus](https://github.com/ethereumbook/ethereumbook/blob/develop/14consensus.asciidoc)'
27 |
28 | ## Content
29 |
30 | The content status is "COMPLETE". The first edition of this book was published on December 1st, 2018. That edition is available in print and ebook format at many popular bookstores. It is tagged ["first_edition_first_print"](https://github.com/ethereumbook/ethereumbook/tree/first_edition_first_print) in the develop branch of this repository.
31 |
32 | At this time, **only bug fix requests are accepted**. If you find a bug, start an issue or better yet, fix the problem with a pull request. We will start work on the second edition in late 2019.
33 |
34 | ## Source and license
35 |
36 | The [first edition](https://github.com/ethereumbook/ethereumbook/tree/first_edition_first_print) of this book, as printed and sold by O'Reilly Media, is available in this repository.
37 |
38 | Mastering Ethereum is released under the *Creative Commons CC-BY-SA license*.
39 |
40 | This "Free Culture" compliant license was approved by our publisher O'Reilly Media (http://oreilly.com), who understands the value of open source. O'Reilly Media is not just the world's best publisher of technical books, but is also a strong supporter of this open culture and the sharing of knowledge.
41 |
42 | Mastering Ethereum by Andreas M. Antonopoulos, Gavin Wood is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License. Based on a work at https://github.com/ethereumbook/ethereumbook.
43 |
44 | # Translate This Book!
45 |
46 | If you are interested in translating this book, please join our team of volunteers at: https://www.transifex.com/aantonop/ethereumbook
47 |
--------------------------------------------------------------------------------
/appdx-shortlinks.asciidoc:
--------------------------------------------------------------------------------
1 | [appendix]
2 | [[short_links]]
3 | == Short Links Reference
4 |
5 | Throughout this book we have used short links. These short links take up less space on the page and make it easier for readers of the print edition to transcribe them into a browser. However, short links can break and the companies providing these services may cease to exist or block certain links. The complete links are shown here in the order they are found in the text.
6 |
7 |
8 | === Smart Contract Security
9 |
10 | [options="header"]
11 | |===
12 | | Short Link | Expanded Link
13 | | 2Ogvnng | https://solidity.readthedocs.io/en/latest/units-and-global-variables.html#address-related
14 | | 2EVo70v | https://solidity.readthedocs.io/en/latest/security-considerations.html#use-the-checks-effects-interactions-pattern
15 | | 2EQaLCI | http://hackingdistributed.com/2016/06/18/analysis-of-the-dao-exploit/
16 | | 2MOfBPv | https://consensys.github.io/smart-contract-best-practices/known_attacks/#integer-overflow-and-underflow
17 | | 2xvbx1M | https://randomoracle.wordpress.com/2018/04/27/ethereum-solidity-and-integer-overflows-programming-blockchains-like-1970/
18 | | 2CUf7WG | https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
19 | | 2RovrDf | https://solidity.readthedocs.io/en/latest/introduction-to-smart-contracts.html
20 | | 2AAElb8 | https://ethereum.stackexchange.com/questions/3667/difference-between-call-callcode-and-delegatecall
21 | | 2Oi7UlH | https://solidity.readthedocs.io/en/latest/introduction-to-smart-contracts.html#delegatecall-callcode-and-libraries
22 | | 2RmueMP | https://solidity.readthedocs.io/en/latest/abi-spec.html#function-selector
23 | | 2Dg7GtW | https://medium.com/chain-cloud-company-blog/parity-multisig-hack-again-b46771eaa838
24 | | 2CUh2KS | https://ethereum.stackexchange.com/questions/191/how-can-i-securely-generate-a-random-number-in-my-smart-contract
25 | | 2Q589lx | https://blog.positive.com/predicting-random-numbers-in-ethereum-smart-contracts-e5358c6b8620
26 | | 2JtdqRi | https://etherscan.io/address/0x95d34980095380851902ccd9a1fb4c813c2cb639#code
27 | | 2Q58VyX | https://www.reddit.com/r/ethdev/comments/7x5rwr/tricked_by_a_honeypot_contract_or_beaten_by/
28 | | 2yKme14 | https://vessenes.com/the-erc20-short-address-attack-explained/
29 | | 2yFOGRQ | https://medium.com/huzzle/ico-smart-contract-vulnerability-short-address-attack-31ac9177eb6b
30 | | 2CQjBhc | https://www.reddit.com/r/ethereum/comments/6r9nhj/cant_understand_the_erc20_short_address_attack/
31 | | 2Q5VIG9 | https://solidity.readthedocs.io/en/latest/abi-spec.html
32 | | 2Q1ybpQ | https://vessenes.com/the-erc20-short-address-attack-explained/
33 | | 2RnS1vA | http://hackingdistributed.com/2016/06/16/scanning-live-ethereum-contracts-for-bugs/
34 | | 2CSdF7y | https://solidity.readthedocs.io/en/latest/common-patterns.html
35 | | 2OfHalK | https://github.com/etherpot/contract/blob/master/app/contracts/lotto.sol
36 | | 2Jpzf4x | http://aakilfernandes.github.io/blockhashes-are-only-good-for-256-blocks
37 | | 2ACsfi1 | https://www.kingoftheether.com/thrones/kingoftheether/index.html
38 | | 2ESoaub | https://www.kingoftheether.com/postmortem.html
39 | | 2Q6E4lP | https://consensys.github.io/smart-contract-best-practices/known_attacks/#race-conditions
40 | | 2yI5Dv7 | https://github.com/ethereum/wiki/wiki/Ethash
41 | | 2SygqQx | http://hackingdistributed.com/2017/08/28/submarine-sends/
42 | | 2EUlLzb | https://hackernoon.com/front-running-bancor-in-150-lines-of-python-with-ethereum-api-d5e2bfd0d798
43 | | 2Oh8j7R | https://etherscan.io/address/0xf45717552f12ef7cb65e95476f217ea008167ae3
44 | | 2OdUC9C | https://solidity.readthedocs.io/en/latest/units-and-global-variables.html
45 | | 2AAebFr | https://etherscan.io/address/0x0d8775f648430679a709e98d2b0cb6250d2887ef#code
46 | | 2Q1AMA6 | https://applicature.com/blog/history-of-ethereum-security-vulnerabilities-hacks-and-their-fixes
47 | | 2ESWG7t | https://etherscan.io/address/0xe82719202e5965Cf5D9B6673B7503a3b92DE20be#code
48 | | 2ERI0pb | https://medium.com/cryptronics/storage-allocation-exploits-in-ethereum-smart-contracts-16c2aa312743
49 | | 2OgxPtG | https://www.reddit.com/r/ethdev/comments/7wp363/how_does_this_honeypot_work_it_seems_like_a/
50 | | 2OVkSL4 | https://medium.com/coinmonks/an-analysis-of-a-couple-ethereum-honeypot-contracts-5c07c95b0a8d
51 | | 2Ogp2Ia | https://github.com/ethereum/wiki/wiki/Safety#beware-rounding-with-integer-division
52 | | 2SwDnE0 | https://vessenes.com/ethereum-contracts-are-going-to-be-candy-for-hackers/
53 | | 2qm7ocJ | https://vessenes.com/tx-origin-and-ethereum-oh-my/
54 | | 2P3KVA4 | https://medium.com/coinmonks/solidity-tx-origin-attacks-58211ad95514
55 | |===
56 |
57 | === Tokens
58 |
59 | [options="header"]
60 | |===
61 | | Short Link | Expanded Link
62 | | 2CUf7WG | https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
63 | | 2EUYCMR | https://github.com/ConsenSys/Tokens/blob/master/contracts/eip20/EIP20.sol
64 | | 2xPYck6 | https://github.com/OpenZeppelin/openzeppelin-solidity/blob/v1.12.0/contracts/token/ERC20/StandardToken.sol
65 | |===
66 |
--------------------------------------------------------------------------------
/misc/example_keys.txt:
--------------------------------------------------------------------------------
1 | $ echo -n "Mastering Ethereum" | keccak-256sum
2 | F8F8A2F43C8376CCB0871305060D7B27B0554D2CC72BCCF41B2705608452F315 -
3 |
4 | Private Key
5 | f8f8a2f43c8376ccb0871305060d7b27b0554d2cc72bccf41b2705608452f315
6 |
7 | Public Key
8 | 046e145ccef1033dea239875dd00dfb4fee6e3348b84985c92f103444683bae07b83b5c38e5e2b0c8529d7fa3f64d46daa1ece2d9ac14cab9477d042c84c32ccd0
9 |
10 | Prefix: 04
11 | X:
12 | 6e145ccef1033dea239875dd00dfb4fee6e3348b84985c92f103444683bae07b
13 | Y:
14 | 83b5c38e5e2b0c8529d7fa3f64d46daa1ece2d9ac14cab9477d042c84c32ccd0
15 |
16 | ETH Address (mixed cap)
17 | 0x001d3F1ef827552Ae1114027BD3ECF1f086bA0F9
18 |
19 | -------
20 |
21 | MetaMask seed
22 | piano tower spell inhale drama inside else quarter quality velvet small fit
23 |
24 | Available Accounts
25 | ==================
26 | (0) 0x9e713963a92c02317a681b9bb3065a8249de124f
27 | (1) 0xb0920c523d582040f2bcb1bd7fb1c7c1ecebdb34
28 | (2) 0xa49b21493176e73d5d24368cde4c1e6e5380e83a
29 | (3) 0xadb5191bc45ee6b6992a05a7cab778727700d469
30 | (4) 0x47121eacb0b0a61ff2699d702f7773b521ff8bea
31 | (5) 0x3a6e24b67bf25f5c1b988f068300e390ff398e0d
32 | (6) 0x64030e9b656b1fbdc568547dce3a8e7a6d75e4f6
33 | (7) 0x97656373117b650900d3732d8a3e7248afd10d63
34 | (8) 0x6e135145a1ea7cd97fb50cb2cc209766afde5f6b
35 | (9) 0xda9f13c519e5f34ebcae3d81c23660267861f7c0
36 |
37 | Private Keys
38 | ==================
39 | (0) 91c8360c4cb4b5fac45513a7213f31d4e4a7bfcb4630e9fbf074f42a203ac0b9
40 | (1) 7e06428bb2ad698b277cd77607505abb00faed5a99a9bf8064c40787e1e7b745
41 | (2) 3719fd869bc9d310b3334ee69530fdae03106adef47dd8c584a1d14a29b41d84
42 | (3) 6fb3a3070d2c0b32a8a181d3a33ca5cc3d4dd958b95fa0a28a1c6c4df698f919
43 | (4) 7cf6be18e131638a83675805294017a81d7b7a40271df17f83071845678eaa96
44 | (5) 5b758a7b39afc142c3293d17b5af401afd80835e5708654188545eda45d52d95
45 | (6) 32b5b6b830a5fa5cd6796bde303ce89ee645a6952b1d4251d048ea68dde8c702
46 | (7) 03e64537cef8909d54645c980c4d805be86930a095637fb7f7b22a9d2fb58e42
47 | (8) e6edb1ee507a967780f63d03e88135708d67d62a56611a9cff6144a596edceab
48 | (9) 0cc66101e2efe5bb72776925c878dfc2a934bb87787f3fe6f56ed6eecc70589e
49 |
50 | -------
51 |
52 | Ganache Seed
53 | candy maple cake sugar pudding cream honey rich smooth crumble sweet treat
54 |
55 | Available Accounts
56 | ==================
57 | (0) 0x627306090abab3a6e1400e9345bc60c78a8bef57
58 | (1) 0xf17f52151ebef6c7334fad080c5704d77216b732
59 | (2) 0xc5fdf4076b8f3a5357c5e395ab970b5b54098fef
60 | (3) 0x821aea9a577a9b44299b9c15c88cf3087f3b5544
61 | (4) 0x0d1d4e623d10f9fba5db95830f7d3839406c6af2
62 | (5) 0x2932b7a2355d6fecc4b5c0b6bd44cc31df247a2e
63 | (6) 0x2191ef87e392377ec08e7c08eb105ef5448eced5
64 | (7) 0x0f4f2ac550a1b4e2280d04c21cea7ebd822934b5
65 | (8) 0x6330a553fc93768f612722bb8c2ec78ac90b3bbc
66 | (9) 0x5aeda56215b167893e80b4fe645ba6d5bab767de
67 |
68 | Private Keys
69 | ==================
70 | (0) c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3
71 | (1) ae6ae8e5ccbfb04590405997ee2d52d2b330726137b875053c36d94e974d162f
72 | (2) 0dbbe8e4ae425a6d2687f1a7e3ba17bc98c673636790f1b8ad91193c05875ef1
73 | (3) c88b703fb08cbea894b6aeff5a544fb92e78a18e19814cd85da83b71f772aa6c
74 | (4) 388c684f0ba1ef5017716adb5d21a053ea8e90277d0868337519f97bede61418
75 | (5) 659cbb0e2411a44db63778987b1e22153c086a95eb6b18bdf89de078917abc63
76 | (6) 82d052c865f5763aad42add438569276c00d3d88a2d062d36b2bae914d58b8c8
77 | (7) aa3680d5d48a8283413f7a108367c7299ca73f553735860a87b08f39395618b7
78 | (8) 0f62d96d6675f32685bbdb8ac13cda7c23436f63efbb9d07700d8669ff12b7c4
79 | (9) 8d5366123cb560bb606379f90a0bfd4769eecc0557f1b362dcae9012b548b1e5
80 |
81 | -------
82 |
83 | BIP39 example seed
84 | wolf juice proud gown wool unfair wall cliff insect more detail hub
85 |
86 | BIP32 root
87 | xprv9s21ZrQH143K2Q5FjzwmUXKS9adFPhHhKSGiWhvxoXBwBA5FzXEe3oF3RdzWKUEjuFH1MAHsvZpfBHmcZxHRLf6bR1GBzJLrmc5uGso6rNE
88 |
89 | Available Accounts
90 | ==================
91 | (0) 0x6adca879124a3e9a87b4b55a9ada0119e4468941
92 | (1) 0xe1544a42ae1e21de1dc2e8f689dd3ae5fd64d507
93 | (2) 0x9c1f74baf574a4fd56ac4d73dfbdb10559734a14
94 | (3) 0x1745ec0c503d3c88f0af096eb7e0407ef934f153
95 | (4) 0x11e27593a8ee5a98f9b2e752fabb159c7837d49f
96 | (5) 0xf5484b9e3928576915d275e82e6af1539f3a9597
97 | (6) 0x7e0da4dc380249ea4919910b3ca8dc9d023fe7be
98 | (7) 0x15fb650736bace2f76f527307cf6c1639642e066
99 | (8) 0xd5326ba2c5924912a5c773835ad521c925af0d00
100 | (9) 0xe518bf0ebf9da4ba0342ea5d3213cc9279002d8a
101 |
102 | Private Keys
103 | ==================
104 | (0) 9d147484b814e14c7c6d546325e493e962825045ba5f6407c199ffabf226b28d
105 | (1) ae343294259b84aaaa12ffa4b91a1dbea46d2760c5506e62e2e698582398752f
106 | (2) 55d226c0e62029b20a3e6239268d159a555da0097618102133b6bb9b9c4ef968
107 | (3) aa2fffcbf8c3cf4508c71925f8bf87d9e9b7240fe868a6ac4d846ef4e66e75cf
108 | (4) de61c4d9645f3ac9d9e93d1f05eee866179e4f4b0605bf52d4797f0df750d70f
109 | (5) f52301c634da761d51848448d6a22f49161e0f5f22cc83d393cf5a44698f2c44
110 | (6) a8005637219801f87ddd7e248c2e8d0c3013c0ebb450b35ee64caf55e221f900
111 | (7) b132c35e45e79bbd371b9d3a1a46f580667a64293b88d74831a59a9eac4bf4e0
112 | (8) a6b09fb86fd6682abb1cad43b8aa53897bf10696f8b6934f0b1e4fa11a69cfce
113 | (9) 8a0037949e186f8810dfeb5b38ee657fcf43d12bbdd58dacd7684de3a98c87a2
114 |
--------------------------------------------------------------------------------
/tools/intakereport.txt:
--------------------------------------------------------------------------------
1 | Title: Mastering Ethereum
2 | ISBN: 9781491971949
3 | JIRA #: DCPSPROD-2740
4 |
5 |
6 | Stylesheet: animal_theme_sass
7 | Toolchain: Atlas 2
8 |
9 | Atlas URL: https://atlas.oreilly.com/oreillymedia/mastering-ethereum
10 |
11 | Incoming format: AsciiDoc
12 | Outgoing format: AsciiDoc
13 |
14 | Preliminary pagecount: 424 (with draft figures)
15 |
16 | Is this project in Early Release? Yes
17 |
18 | Resources
19 | =========
20 |
21 | ** Figs: Illustrations is still working on the figs.
22 | 62 total. (0 are informal; 0 are inline.)
23 |
24 | Once the figs are processed on /work, you'll need to add them to the book's repo.
25 |
26 | Per a Slack conversation with Mel, I didn't rename the figure files.
27 |
28 | ** Intake Report:
29 | (Git repo) tools/intakereport.txt
30 |
31 | ** MS Snapshot:
32 | To view the submitted files, you'll need to checkout the git tag named 'manuscript_to_prod'
33 | by running the following command in your checkout:
34 |
35 | $ git checkout manuscript_to_prod
36 |
37 | This will temporarily switch the files in your repo to the state they were in when the manuscript_to_prod tag
38 | was created.
39 | To switch the files back to the current state, run:
40 |
41 | $ git checkout master
42 |
43 |
44 | Notes from Tools:
45 | =================
46 |
47 | ** PROD: Add any authors to project that need to be added.
48 | ** Syntax highlighting: applied to 85 out of 337 code listings.
49 | ** The 'assembly' lexer called at line 98 of smart-contracts-vyper.asciidoc does not exist. I've left it in place so you can ask the author what real lexer he/she would prefer.
50 | ** The external link at line 1235 of smart-contracts-security.asciidoc points to the URL of a page that does not exist. It could probably be fixed by replacing the URL with "https://en.wikipedia.org/wiki/ROT13", but I'm leaving that to the production editor.
51 | ** The URL at line 174 of preface.asciidoc has a URL that epubcheck doesn't like. The colon in the URL doesn't seem to meet epubcheck's specifications for a URL. I think we need a URL without a colon.
52 | ** LaTeX equations will need to be replaced with the MathML in passthroughs in order to resolve the 'attribute "mode"' epubcheck errors.
53 | ** If warnings about Atlas's inability to parse figures for downsampling isn't resolved when Rebecca delivers the processed figure files, I'll need to look into it more.
54 | ** There are a couple errors concerning xrefs to missing target IDs that remain in the build log.
55 | ** Please let Tools know ASAP if there are any other global problems for which we can help automate a fix.
56 |
57 |
58 | Notes at arrival in production:
59 | ==================
60 |
61 | Techbook
62 |
63 | ISBN: 9781491971949
64 | Page count: 415
65 | Source Files: https://atlas.oreilly.com/aantonop/masteringethereum
66 | Editor name: Michele Cronin
67 | Acquisitions Editor: Rachel Roumeliotis
68 | Interior design: 7x9; animal_theme_sass
69 | Prod ed: Nick Adams
70 | Is this sponsored? No
71 |
72 | *Notes for Production*
73 | * Notes for CE:
74 | ** Author just added in-text references to figures; watch for punctuation errors around those.
75 | ** Keep an eye on the heading levels. There were several that I marked to become H2s etc, but it looks like the author missed some
76 | ** Noticed a few broken references in the final
77 | ** Reference sections need citation formatting added to them
78 | * Figures:
79 | ** Figure list located here: https://docs.google.com/spreadsheets/d/10VeJGSVY9WvFIkSmxh_6FBV7dBqnn5hBoiL9up6o0lY/edit?usp=sharing
80 | ** There are a few sketches and illustrations marked for redraw
81 | ** *IMPORTANT* author had issues with figures being renumbered in his other book (mastering bitcoin). The book is under CC license, and there will be a version available on Github. When the figures were renumbered, it was done incorrectly, and the result was mislabeled images and several images being deleted - which caused a version control issue for the author. He has asked we either do not renumber the figures, OR that we RETAIN the descriptive text in the figure names so that he can also track the figures on his end.
82 | * Some figures are very large and could probably be sized down
83 | * There is a list of GitHub contributors in the preface that is very long, work with the authors to make this a table or something
84 | * Some weird formatting in the preface containing {nbsp}
85 | * So many long code lines
86 | * The CE is going to be pretty heavy, so I extended the dates a bit in the schedule (since the release date isn't until 12/2018)
87 |
88 | *Notes for Tools*
89 | Incoming format: AsciiDoc
90 |
91 | *Notes*
92 | * The author doesn't want the figure filenames changed, so please just add me_0101 to the beginning of the figure filenames rather than replacing them. Let me know if that won't work.
93 | * There are some errors in the build log: 2018-09-05 19:25:01,962 ERROR Unable to highlight code with language attr JavaScript: global name 'ClassNotFound' is not defined
94 | * Please add the chapter numbers to the existing chapter filenames (01, 02, should be fine).
95 |
96 | ==================
97 |
98 | Please let me know about any other issues.
99 |
100 | Thanks,
101 | Matt
102 |
103 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Guide to contributing
2 |
3 | [](https://gitter.im/ethereumbook/Lobby)
4 |
5 | This book is developed collaboratively and openly, here on GitHub. We accept comments, contributions and corrections from all.
6 |
7 | ## Current Project STATUS
8 | **CONTENT FREEZE - FIRST EDITION IN PRODUCTION**
9 |
10 | ## Contributing with a Pull Request
11 |
12 | Before contributing with a Pull Request, please read the current **PROJECT STATUS**.
13 |
14 | If the current **PROJECT STATUS** is **CONTENT FREEZE**, please keep these points in mind;
15 |
16 | * Please submit only PRs for errors that a non-domain-expert copy editor might miss. Do not submit PRs for typos, grammar and syntax, as those are part of the copy editors job.
17 | * Please don't merge code. Any changes will have to be applied manually (by the Author) after copy edit and before final proof, if the copy editor doesn't catch the same errors.
18 |
19 |
20 | ## Chat with the authors
21 |
22 | You can chat with the authors and editors on [Gitter chat](https://gitter.im/ethereumbook/Lobby).
23 |
24 | ## License and attribution
25 |
26 | All contributions must be properly licensed and attributed. If you are contributing your own original work, then you are offering it under a CC-BY license (Creative Commons Attribution). You are responsible for adding your own name or pseudonym in the Acknowledgments section in the [Preface](preface.asciidoc), as attribution for your contribution.
27 |
28 | If you are sourcing a contribution from somewhere else, it must carry a compatible license. The book will initially be released under a CC-BY-NC-ND license which means that contributions must be licensed under open licenses such as MIT, CC0, CC-BY, etc. You need to indicate the original source and original license, by including an asciidoc markup comment above your contribution, like this:
29 |
30 | ```asciidoc
31 | ////
32 | Source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
33 | License: CC0
34 | Added by: @aantonop
35 | ////
36 | ```
37 |
38 | The best way to contribute to this book is by making a pull request:
39 |
40 | 1. Login with your GitHub account or create one now
41 | 2. [Fork](https://github.com/ethereumbook/ethereumbook#fork-destination-box) the `ethereumbook` repository. Work on your fork.
42 | 3. Create a new branch on which to make your change, e.g. `git checkout -b my_code_contribution`, or make the change on the `develop` branch.
43 | 4. Please do one pull request PER asciidoc file, to avoid large merges. Edit the asciidoc file where you want to make a change or create a new asciidoc file in the `contrib` directory if you're not sure where your contribution might fit.
44 | 5. Edit `preface.asciidoc` and add your own name to the list of contributors under the Acknowledgment section. Use your name, or a GitHub username, or a pseudonym.
45 | 6. Commit your change. Include a commit message describing the correction.
46 | 7. Submit a pull request against the ethereumbook repository.
47 |
48 | Here's a video tutorial to help you make your first pull request:
49 |
50 | [](https://www.youtube.com/watch?v=IBYHohWm_5w)
51 |
52 | ## Contributing with an issue
53 |
54 | If you find a mistake and you're not sure how to fix it, or you don't know how to do a pull request, then you can file an Issue. Filing an Issue will help us see the problem and fix it.
55 |
56 | Create a [new Issue](https://github.com/ethereumbook/ethereumbook/issues/new) now!
57 |
58 | ## Heading styles normalization across the book
59 |
60 | Adjust heading style in each section as follows:
61 |
62 | 1. Only the chapter/section should be level 2, everything else should be level 3 and below (level 1 is the book title itself). Each asciidoc file should start with a "==" heading.
63 | 2. All lower case, except for first letter, proper nouns and acronyms. "What is this thing?", "What is the Ethereum sprocket?" "Who created the Ethereum Name Service (ENS)"
64 | 3. Acronyms are spelled out, capitalized, with the acronym in parentheses. Once you have spelled out an acronym in one heading, we can keep it as an acronym in subsequent headings.
65 | 4. No period at the end. Question mark if it is a question (generally avoid question headings, unless really appropriate)
66 | 5. Should include a unique anchor (see #279), all lower case, underscore separated.
67 | 6. Headings should be followed by a blank line.
68 | 7. Heading should be followed by a paragraph of text, not a lower-level heading without any text. If you find one like this, add a TODO comment (line of 4 slashes "////", line with "TODO: add paragraph", line of 4 slashes)
69 |
70 | ## Line endings
71 |
72 | All submission should use Unix-like line endings: LF (not CR, not CR/LF). All the postprocessing is done on Unix-like systems. Incorrect line endings, or changes to line endings cause confusion for the diff tools and make the whole file look like it has changed.
73 |
74 | If you are unsure or your OS makes things difficult, consider using a developer's text editor such as Atom.
75 |
76 | ## Thanks
77 |
78 | We are very grateful for the support of the entire Ethereum community. With your help, this will be a great book that can help thousands of developers get started and eventually "master" Ethereum. Thank you!
79 |
--------------------------------------------------------------------------------
/code/web3js/web3js_demo/web3-contract-basic-interaction-async-await.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 |
3 | /**
4 | * @author Francisco Javier Rojas García
5 | */
6 |
7 | console.log('Mastering Ethereum - web3.js basic interactions using async/await')
8 | console.log('Author: Francisco Javier Rojas García - fjrojasgarcia@gmail.com')
9 |
10 |
11 | const optionDefinitions = [
12 | { name: 'localRPC', alias: 'l', type: Boolean },
13 | { name: 'infuraFileToken', type: String },
14 | { name: 'alchemyFileToken', type: String }
15 | ]
16 |
17 | const commandLineArgs = require('command-line-args')
18 | const options = commandLineArgs(optionDefinitions)
19 |
20 | var Web3 = require('web3');
21 | var fs = require('fs')
22 |
23 | if (options.infuraFileToken && !options.localRPC) {
24 | console.log(options.infuraFileToken);
25 |
26 | // Loading an Infura Token from a file
27 | var infura_token = fs.readFileSync(options.infuraFileToken, 'utf8');
28 |
29 | // Show your Infura token
30 | console.log(infura_token);
31 |
32 | // Prepare your Infura host url
33 | var node_host = `https://kovan.infura.io/${infura_token}`
34 |
35 | } else if (options.alchemyFileToken && !options.localRPC) {
36 | console.log(options.alchemyFileToken);
37 |
38 | // Loading an Alchemy Token from a file
39 | var alchemy_token = fs.readFileSync(options.alchemyFileToken, 'utf8');
40 |
41 | // Show your Alchemy token
42 | console.log(alchemy_token);
43 |
44 | // Prepare your Alchemy host url
45 | var node_host = `https://eth-kovan.alchemyapi.io/v2/${alchemy_token}`
46 |
47 | } else {
48 | console.log('No argument found for node provider token');
49 |
50 | // Prepare your Node host url
51 | var node_host = "https://kovan.infura.io"
52 | }
53 |
54 | // Instantiate web3 provider
55 | var web3 = new Web3(node_host);
56 |
57 | // Let's do some basic interactions at web3 level
58 | async function basicInterations() {
59 | // Let's see the Protocol Version
60 | var protocolVersion = await web3.eth.getProtocolVersion();
61 | console.log(`Protocol Version: ${protocolVersion}`);
62 |
63 | // Now I'm curious about the current gas price
64 | var gasPrice = await web3.eth.getGasPrice();
65 | console.log(`Gas Price: ${gasPrice}`);
66 |
67 | // And, Whats the last mined block in my chain?
68 | var blockNumber = await web3.eth.getBlockNumber();
69 | console.log(`Block Number: ${blockNumber}`);
70 |
71 | // Now let's dive into some basics actions with a contract
72 | // We will use the contract at;
73 | // https://kovan.etherscan.io/address/0xd0a1e359811322d97991e03f863a0c30c2cf029c#code
74 |
75 | // First things first, let's initialize our contract address
76 | var our_contract_address = "0xd0A1E359811322d97991E03f863a0C30C2cF029C";
77 |
78 | // Let's see its balance
79 | var balance = await web3.eth.getBalance(our_contract_address);
80 | console.log(`Balance of ${our_contract_address}: ${balance}`);
81 |
82 | // Now let's see its byte code
83 | var code = await web3.eth.getCode(our_contract_address);
84 | console.log("Contract code: ----------------------------------------------\n");
85 | console.log(code);
86 | console.log("-------------------------------------------------------------\n");
87 |
88 | // Let's initialize our contract url in Etherescan for Kovan chain
89 | var etherescan_url = `http://kovan.etherscan.io/api?module=contract&action=getabi&address=${our_contract_address}`
90 | console.log(etherescan_url);
91 |
92 | var client = require('node-rest-client-promise').Client();
93 |
94 | var etherescan_response = await client.getPromise(etherescan_url)
95 |
96 | // Leave this two lines for future object analysis
97 | //const util = require('util')
98 | //console.log(util.inspect(etherescan_response, false, null))
99 |
100 | // We get here our contract ABI
101 | our_contract_abi = JSON.parse(etherescan_response.data.result);
102 |
103 | // Let's instantiate our contract object
104 | var our_contract = await new web3.eth.Contract(our_contract_abi, our_contract_address);
105 |
106 | // Let's see our contract address
107 | console.log(`Our Contract address: ${our_contract._address}`);
108 |
109 | // or in this other way
110 | console.log(`Our Contract address in other way: ${our_contract.options.address}`);
111 |
112 | // Now our contract abi
113 | console.log("Our contract abi: " + JSON.stringify(our_contract.options.jsonInterface));
114 |
115 | // This is turning more interesting, let's see what's going with our contract methods
116 | // Now let's see our contract total supply
117 | var totalSupply = await our_contract.methods.totalSupply().call();
118 | console.log(`Total Supply of Our Contract address ${our_contract._address}: ${totalSupply}`);
119 |
120 | // Now let's see our contract public variable name
121 | var name = await our_contract.methods.name().call();
122 | console.log(`Public variable name of our Contract address ${our_contract._address}: ${name}`);
123 |
124 | // Now let's see our contract public variable symbol
125 | var symbol = await our_contract.methods.symbol().call();
126 | console.log(`Public variable symbol of our Contract address ${our_contract._address}: ${symbol}`);
127 | }
128 |
129 | // Let's interact with a node
130 | basicInterations();
131 |
--------------------------------------------------------------------------------
/contrib/scaling.asciidoc:
--------------------------------------------------------------------------------
1 | == Scaling
2 |
3 | One the most notable problems public blockchains face is scaling. According to Wikipedia, the definition of scaling in general can be "a computer's or network's ability to function as the number of users increases.". When talking about a blockchain, usage of the system is expressed in transactions. Based on that, we can define scalability in a blockchain as the ability of the network to function as the number of transactions increases. A popular way to measure scalability of a blockchain is measuring how much transactions per second (TPS) it can process.
4 |
5 | ////
6 | Source: https://ethereum.stackexchange.com/a/49600/31518
7 | License: CC-BY
8 | Added by: @meshugah
9 | ////
10 |
11 | Ethereum itself can support around 25 state updates (aka. transactions) per second, compared to around 500 transactions per second PayPal can support
12 | or the millions state updates (tweets, comment, likes etc.) Twitter supports we can clearly see the problem, Ethereum can not support a massive adoption of users
13 | without solving this problem. A great example of this would be the infamous Crypto Kitties flu of December 2017, it showed us exactly what a
14 | small pick in the usage of Ethereum can do to the network, transactions were taking hours to days and the fees were about 40 Gwei -
15 | more than 10 times higher than the typical fee.
16 |
17 | === "The Blockchain Trillema"
18 |
19 | The reason for these scalability issues can be explained using what's called "The Blockchain Trillema".
20 | This is a trillema where (without a decent solution) a blockchain can support only 2 edges of the triangle and needs to compromise on the on third one.
21 | The three edges are:
22 |
23 | * Scalability
24 | * Decentralization
25 | * Security
26 |
27 | We can look at what each combination of 2 out of the 3 may look like.
28 |
29 | Scalability combined with Security - This could be a private blockchain, since the consensus needs to be achieved is only between a small cluster of trusted nodes (or maybe only one)
30 | there is no need for many security features such as distributed consensus that public blockchains need and the communication between a few nodes is much faster than between a big decentralized network.
31 |
32 | Scalability combined with Decentralization - A great example for this could be a public blockchain such as Bitcoin or Ethereum, but with with 0 block confirmations
33 | this may allow instant transactions with the additional benefit of no fees but it is extremely insecure to the point that it is just not very applicable.
34 |
35 | Decentralization and Security - this is certainly where most public blockchains including Bitcoin and Ethereum are at, they are decentralized and secure
36 | but as said before, they do not support strong scaling solutions at the time of writing this.
37 |
38 | The problem with this Trillema is you can't completely win it, you just can't support very high TPS, a huge open network of nodes and be secure all at once.
39 |
40 | With that in mind, we can start exploring the different approaches of scaling the public blockchain without decreasing decentralization or security
41 | it is important to understand, since it is not possible to completely satisfy all 3 at the same time most solutions aim to get to some point in the middle
42 | where they have decent security, decentralization and scalability.
43 |
44 | == Attempts at scaling
45 |
46 | === Casper - Proof of Stake for Ethereum
47 | Proof of Stake is a form of consensus that aims to improve/ replace the current Proof of Work consensus. The idea of Proof of Work consensus algoritm, in its simplest form, is to allow reaching consensus based on a '1 CPU is 1 vote'. Proof of Stake introduces a new voting power distribution idea in a '1 Coin is 1 vote' basis, effectively moving the power of a vote from computational power to a participant's stake in the system.
48 |
49 | Proof of Stake grants the ability to provide a blockchain with "economic finality", thus strengthening it's economical security, reducing centralization risks by making it less rewardable to collude on a majority attack. A benefit to the change Proof-of-Stake is that it makes the protocol easier on the environment by replacing the Proof-of-Work's energy expenditure ,as a result of the struggle for power in the network, with the desire to hold stake in the security of the network.
50 |
51 | Ethereum has officially decided to shift its consensus algorithm from Proof of Work to Proof of stake. The new Proof of Stake algorithm for Ethereum is called Casper - The Friendly GHOST, a playful monicker refering to Casper the Friendly Ghost, where GHOST stands for Greedy Heaviest Observed Sub-Tree. It was decided that the transition to Proof of Stake will be done in 2 phases.
52 | The motivation behind this was to give room to handle unforseen transient effects and to allow for current users of the system to have a smoother transition.
53 |
54 | The first part of the roll-out is a hybrid Proof of Work - Proof of Stake algorithm called Casper the Friendly Finality Gadget (FFG) which aims to provide finality and implicitly reduce energy waste. The second and target update is called Casper, Correct By Construction (CBC), this is a pure Proof of Stake algorithm and will complete Ethereum's transition to Proof of Stake.
55 |
56 | Casper the Friendly Finality Gadget (FFG)
57 |
58 |
59 | Casper Correct by Construction (CBC)
60 |
61 |
62 | Sharding
63 |
64 | Plasma
65 |
66 | Raiden
67 |
68 | Counterfactual State Channels
69 |
70 | Truebit
71 |
72 | Loom Network
73 |
--------------------------------------------------------------------------------
/code/auction_dapp/frontend/build/webpack.prod.conf.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 | const path = require('path')
3 | const utils = require('./utils')
4 | const webpack = require('webpack')
5 | const config = require('../config')
6 | const merge = require('webpack-merge')
7 | const baseWebpackConfig = require('./webpack.base.conf')
8 | const CopyWebpackPlugin = require('copy-webpack-plugin')
9 | const HtmlWebpackPlugin = require('html-webpack-plugin')
10 | const ExtractTextPlugin = require('extract-text-webpack-plugin')
11 | const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
12 | const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
13 |
14 | const env = require('../config/prod.env')
15 |
16 | const webpackConfig = merge(baseWebpackConfig, {
17 | module: {
18 | rules: utils.styleLoaders({
19 | sourceMap: config.build.productionSourceMap,
20 | extract: true,
21 | usePostCSS: true
22 | })
23 | },
24 | devtool: config.build.productionSourceMap ? config.build.devtool : false,
25 | output: {
26 | path: config.build.assetsRoot,
27 | filename: utils.assetsPath('js/[name].[chunkhash].js'),
28 | chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
29 | },
30 | plugins: [
31 | // http://vuejs.github.io/vue-loader/en/workflow/production.html
32 | new webpack.DefinePlugin({
33 | 'process.env': env
34 | }),
35 | new UglifyJsPlugin({
36 | uglifyOptions: {
37 | compress: {
38 | warnings: false
39 | }
40 | },
41 | sourceMap: config.build.productionSourceMap,
42 | parallel: true
43 | }),
44 | // extract css into its own file
45 | new ExtractTextPlugin({
46 | filename: utils.assetsPath('css/[name].[contenthash].css'),
47 | // Setting the following option to `false` will not extract CSS from codesplit chunks.
48 | // Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
49 | // It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
50 | // increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
51 | allChunks: true,
52 | }),
53 | // Compress extracted CSS. We are using this plugin so that possible
54 | // duplicated CSS from different components can be deduped.
55 | new OptimizeCSSPlugin({
56 | cssProcessorOptions: config.build.productionSourceMap
57 | ? { safe: true, map: { inline: false } }
58 | : { safe: true }
59 | }),
60 | // generate dist index.html with correct asset hash for caching.
61 | // you can customize output by editing /index.html
62 | // see https://github.com/ampedandwired/html-webpack-plugin
63 | new HtmlWebpackPlugin({
64 | filename: config.build.index,
65 | template: 'index.html',
66 | inject: true,
67 | minify: {
68 | removeComments: true,
69 | collapseWhitespace: true,
70 | removeAttributeQuotes: true
71 | // more options:
72 | // https://github.com/kangax/html-minifier#options-quick-reference
73 | },
74 | // necessary to consistently work with multiple chunks via CommonsChunkPlugin
75 | chunksSortMode: 'dependency'
76 | }),
77 | // keep module.id stable when vendor modules does not change
78 | new webpack.HashedModuleIdsPlugin(),
79 | // enable scope hoisting
80 | new webpack.optimize.ModuleConcatenationPlugin(),
81 | // split vendor js into its own file
82 | new webpack.optimize.CommonsChunkPlugin({
83 | name: 'vendor',
84 | minChunks (module) {
85 | // any required modules inside node_modules are extracted to vendor
86 | return (
87 | module.resource &&
88 | /\.js$/.test(module.resource) &&
89 | module.resource.indexOf(
90 | path.join(__dirname, '../node_modules')
91 | ) === 0
92 | )
93 | }
94 | }),
95 | // extract webpack runtime and module manifest to its own file in order to
96 | // prevent vendor hash from being updated whenever app bundle is updated
97 | new webpack.optimize.CommonsChunkPlugin({
98 | name: 'manifest',
99 | minChunks: Infinity
100 | }),
101 | // This instance extracts shared chunks from code splitted chunks and bundles them
102 | // in a separate chunk, similar to the vendor chunk
103 | // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
104 | new webpack.optimize.CommonsChunkPlugin({
105 | name: 'app',
106 | async: 'vendor-async',
107 | children: true,
108 | minChunks: 3
109 | }),
110 |
111 | // copy custom static assets
112 | new CopyWebpackPlugin([
113 | {
114 | from: path.resolve(__dirname, '../static'),
115 | to: config.build.assetsSubDirectory,
116 | ignore: ['.*']
117 | }
118 | ])
119 | ]
120 | })
121 |
122 | if (config.build.productionGzip) {
123 | const CompressionWebpackPlugin = require('compression-webpack-plugin')
124 |
125 | webpackConfig.plugins.push(
126 | new CompressionWebpackPlugin({
127 | asset: '[path].gz[query]',
128 | algorithm: 'gzip',
129 | test: new RegExp(
130 | '\\.(' +
131 | config.build.productionGzipExtensions.join('|') +
132 | ')$'
133 | ),
134 | threshold: 10240,
135 | minRatio: 0.8
136 | })
137 | )
138 | }
139 |
140 | if (config.build.bundleAnalyzerReport) {
141 | const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
142 | webpackConfig.plugins.push(new BundleAnalyzerPlugin())
143 | }
144 |
145 | module.exports = webpackConfig
146 |
--------------------------------------------------------------------------------
/code/web3js/web3js_demo/web3-contract-basic-interaction.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 |
3 | /**
4 | * @author Francisco Javier Rojas García
5 | */
6 |
7 | // Take a closer look at the web3 1.0 documentation for calling methods (it's very different from the 0.2x API).
8 | // https://stackoverflow.com/questions/48547268/smart-contract-method-is-not-a-function-in-web3
9 |
10 | console.log('Mastering Ethereum - web3.js basic interactions')
11 | console.log('Author: Francisco Javier Rojas García - fjrojasgarcia@gmail.com')
12 |
13 | const optionDefinitions = [
14 | { name: 'localRPC', alias: 'l', type: Boolean },
15 | { name: 'infuraFileToken', type: String},
16 | { name: 'alchemyFileToken', type: String}
17 | ]
18 |
19 | const commandLineArgs = require('command-line-args')
20 | const options = commandLineArgs(optionDefinitions)
21 |
22 | var Web3 = require('web3');
23 | var fs = require('fs')
24 |
25 | if (options.infuraFileToken && !options.localRPC) {
26 | console.log(options.infuraFileToken);
27 |
28 | // Loading an Infura Token from a file
29 | var infura_token = fs.readFileSync(options.infuraFileToken, 'utf8');
30 |
31 | // Show your Infura token
32 | console.log(infura_token);
33 |
34 | // Prepare your Infura host url
35 | var node_host = `https://kovan.infura.io/${infura_token}`
36 |
37 | } else if (options.alchemyFileToken && !options.localRPC) {
38 | console.log(options.alchemyFileToken);
39 |
40 | // Loading an Alchemy Token from a file
41 | var alchemy_token = fs.readFileSync(options.alchemyFileToken, 'utf8');
42 |
43 | // Show your Alchemy token
44 | console.log(alchemy_token);
45 |
46 | // Prepare your Alchemy host url
47 | var node_host = `https://eth-kovan.alchemyapi.io/v2/${alchemy_token}`
48 |
49 | } else {
50 | console.log('No argument found for node provider token');
51 |
52 | // Prepare your Node host url
53 | var node_host = "https://kovan.infura.io"
54 | }
55 |
56 | // Show your Node host url for your web3 connection
57 | console.log(node_host);
58 |
59 | // Instantiate web3 provider
60 | var web3 = new Web3(node_host);
61 |
62 | // Let's do some basic interactions at web3 level
63 | // Let's see the Protocol Version
64 | web3.eth.getProtocolVersion().then(function(protocolVersion) {
65 | console.log(`Protocol Version: ${protocolVersion}`);
66 | })
67 |
68 | // Now I'm curious about the current gas price
69 | web3.eth.getGasPrice().then(function(gasPrice) {
70 | console.log(`Gas Price: ${gasPrice}`);
71 | })
72 |
73 | // And, Whats the last mined block in my chain?
74 | web3.eth.getBlockNumber().then(function(blockNumber) {
75 | console.log(`Block Number: ${blockNumber}`);
76 | })
77 |
78 | // Now let's dive into some basics actions with a contract
79 | // We will use the contract at;
80 | // https://kovan.etherscan.io/address/0xd0a1e359811322d97991e03f863a0c30c2cf029c#code
81 |
82 | // First things first, let's initialize our contract address
83 | var our_contract_address = "0xd0A1E359811322d97991E03f863a0C30C2cF029C";
84 |
85 | // Let's see its balance
86 | web3.eth.getBalance(our_contract_address).then(function(balance) {
87 | console.log(`Balance of ${our_contract_address}: ${balance}`);
88 | })
89 |
90 | // Now let's see its byte code
91 | web3.eth.getCode(our_contract_address).then(function(code) {
92 | console.log("Contract code: ----------------------------------------------\n");
93 | console.log(code);
94 | console.log("-------------------------------------------------------------\n");
95 | })
96 |
97 | // Let's initialize our contract url in Etherescan for Kovan chain
98 | var etherescan_url = `http://kovan.etherscan.io/api?module=contract&action=getabi&address=${our_contract_address}`
99 | console.log(etherescan_url);
100 |
101 | var client = require('node-rest-client-promise').Client();
102 |
103 | // Now we are going to deal with the contract from web3.js in a non-block fashion (async mode)
104 | client.getPromise(etherescan_url)
105 | .then((client_promise) => {
106 | // Leave this two lines for fure object analisys
107 | //const util = require('util')
108 | //console.log(util.inspect(client_promise, false, null))
109 |
110 | // We get here our contract ABI
111 | our_contract_abi = JSON.parse(client_promise.data.result);
112 |
113 | // And now we create a promise to consume later
114 | return new Promise((resolve, reject) => {
115 | var our_contract = new web3.eth.Contract(our_contract_abi, our_contract_address);
116 | try {
117 | // If all goes well
118 | resolve(our_contract);
119 | } catch (ex) {
120 | // If something goes wrong
121 | reject(ex);
122 | }
123 | });
124 |
125 | })
126 | .then((our_contract) => {
127 | // Let's see our contract address
128 | console.log(`Our Contract address: ${our_contract._address}`);
129 |
130 | // or in this other way
131 | console.log(`Our Contract address in other way: ${our_contract.options.address}`);
132 |
133 | // Now our contract abi
134 | console.log("Our contract abi: " + JSON.stringify(our_contract.options.jsonInterface));
135 |
136 | // This is turning more interesting, let's see what's going with our contract methods
137 | // Now let's see our contract total supply in a callback fashion
138 | our_contract.methods.totalSupply().call(function(err, totalSupply) {
139 | if (!err) {
140 | console.log(`Total Supply with a callback: ${totalSupply}`);
141 | } else {
142 | console.log(err);
143 | }
144 | });
145 |
146 | // Or you can use the returned Promise instead of passing in the callback:
147 | our_contract.methods.totalSupply().call().then(function(totalSupply){
148 | console.log(`Total Supply with a promise: ${totalSupply}`);
149 | }).catch(function(err) {
150 | console.log(err);
151 | });
152 |
153 | })
154 |
--------------------------------------------------------------------------------