Repository: ajlopez/SoliditySamples Branch: master Commit: d1b8f294f52b Files: 424 Total size: 1.3 MB Directory structure: gitextract_u2aez7lv/ ├── .gitignore ├── CryptoKitties/ │ └── cryptokitties.sol ├── README.md ├── exeth/ │ ├── bet/ │ │ ├── bet.eth │ │ └── contracts/ │ │ └── bet.sol │ ├── blockchain/ │ │ ├── blockchain.eth │ │ └── contracts/ │ │ └── blockchain.sol │ ├── events/ │ │ ├── build/ │ │ │ └── contracts/ │ │ │ └── Emitter.json │ │ ├── contracts/ │ │ │ └── Emitter.sol │ │ └── truffle-config.js │ ├── federation/ │ │ ├── contracts/ │ │ │ └── federation.sol │ │ └── federation.eth │ └── simple/ │ ├── .gitignore │ ├── accounts.eth │ ├── balances.eth │ ├── blocks.eth │ ├── compile.eth │ ├── contracts/ │ │ ├── Methods.sol │ │ ├── counter.asm │ │ ├── counter.sol │ │ ├── creator.sol │ │ ├── empty.asm │ │ ├── empty.sol │ │ ├── foobar.sol │ │ ├── greeter.sol │ │ ├── message.sol │ │ ├── selector.sol │ │ ├── throw.sol │ │ ├── token.asm │ │ ├── token.sol │ │ └── types.sol │ ├── counter.eth │ ├── creator.eth │ ├── deploy.eth │ ├── dump.eth │ ├── empty.eth │ ├── greeter.eth │ ├── hello.eth │ ├── message.eth │ ├── rsksend.eth │ ├── rsktransfer.eth │ ├── throw.eth │ ├── token.eth │ └── transfer.eth ├── old/ │ └── simple/ │ ├── .gitignore │ ├── README.md │ ├── accounts.eth │ ├── balance.eth │ ├── balances10.eth │ ├── balances20.eth │ ├── balances30.eth │ ├── balances4.eth │ ├── compile.eth │ ├── config.json │ ├── contracts/ │ │ ├── counter.sol │ │ ├── creator.sol │ │ ├── empty.sol │ │ ├── foobar.sol │ │ ├── greeter.sol │ │ ├── message.sol │ │ ├── selector.sol │ │ ├── throw.sol │ │ ├── token.asm │ │ ├── token.sol │ │ └── types.sol │ ├── counter.asm │ ├── counter.eth │ ├── creator.eth │ ├── deploy.eth │ ├── do.js │ ├── dump.eth │ ├── empty.eth │ ├── greeter.eth │ ├── hello.eth │ ├── lib/ │ │ ├── commands.js │ │ ├── contexts.js │ │ ├── executors.js │ │ └── utils.js │ ├── message.eth │ ├── package.json │ ├── rsksend.eth │ ├── rsktransfer.eth │ ├── run.js │ ├── test/ │ │ ├── assert.js │ │ ├── compile.js │ │ ├── contexts.js │ │ ├── evaluate.js │ │ ├── executors.js │ │ └── utils.js │ ├── throw.eth │ ├── token.eth │ └── transfer.eth ├── openzeppelin/ │ └── first/ │ ├── .gitignore │ ├── contracts/ │ │ ├── ConvertLib.sol │ │ ├── MetaCoin.sol │ │ └── Migrations.sol │ ├── migrations/ │ │ ├── 1_initial_migration.js │ │ └── 2_deploy_contracts.js │ ├── package.json │ ├── test/ │ │ ├── TestMetacoin.sol │ │ └── metacoin.js │ └── truffle.js ├── rskapi/ │ ├── .gitignore │ ├── package.json │ └── transfer.js ├── truffle/ │ ├── .gitignore │ ├── bac1/ │ │ ├── contracts/ │ │ │ ├── Counter.sol │ │ │ └── Migrations.sol │ │ ├── migrations/ │ │ │ ├── 1_initial_migration.js │ │ │ └── 2_deploy_contracts.js │ │ ├── test/ │ │ │ └── CounterTest.js │ │ └── truffle-config.js │ ├── bytes/ │ │ ├── .gitignore │ │ ├── contracts/ │ │ │ ├── Bytes.asm │ │ │ ├── Bytes.sol │ │ │ └── Migrations.sol │ │ ├── migrations/ │ │ │ └── 1_initial_migration.js │ │ ├── scripts/ │ │ │ ├── .gitignore │ │ │ ├── README.md │ │ │ ├── config.js │ │ │ ├── deploy.js │ │ │ └── package.json │ │ ├── test/ │ │ │ └── Bytes_test.js │ │ └── truffle-config.js │ ├── first/ │ │ ├── contracts/ │ │ │ ├── ConvertLib.sol │ │ │ ├── MetaCoin.sol │ │ │ └── Migrations.sol │ │ ├── migrations/ │ │ │ ├── 1_initial_migration.js │ │ │ └── 2_deploy_contracts.js │ │ ├── test/ │ │ │ ├── TestMetacoin.sol │ │ │ └── metacoin.js │ │ └── truffle.js │ ├── kc1/ │ │ ├── Ballot.txt │ │ ├── contracts/ │ │ │ ├── Ballot.sol │ │ │ ├── Counter.sol │ │ │ ├── Empty.sol │ │ │ └── Migrations.sol │ │ ├── migrations/ │ │ │ ├── 1_initial_migration.js │ │ │ └── 2_deploy_contracts.js │ │ ├── test/ │ │ │ ├── Ballot_test.js │ │ │ └── Counter_test.js │ │ └── truffle-config.js │ ├── mug1/ │ │ ├── contracts/ │ │ │ ├── Counter.sol │ │ │ ├── Empty.sol │ │ │ └── Migrations.sol │ │ ├── migrations/ │ │ │ ├── 1_initial_migration.js │ │ │ └── 2_deploy_contracts.js │ │ ├── test/ │ │ │ └── counter_test.js │ │ └── truffle-config.js │ ├── mug2/ │ │ ├── contracts/ │ │ │ ├── Counter.sol │ │ │ ├── Migrations.sol │ │ │ └── Token.sol │ │ ├── migrations/ │ │ │ ├── 1_initial_migration.js │ │ │ └── 2_deploy_contracts.js │ │ ├── test/ │ │ │ ├── Counter_test.js │ │ │ └── Token_test.js │ │ └── truffle-config.js │ ├── oz/ │ │ ├── contracts/ │ │ │ ├── Bounty.sol │ │ │ ├── ConvertLib.sol │ │ │ ├── DayLimit.sol │ │ │ ├── ECRecovery.sol │ │ │ ├── LimitBalance.sol │ │ │ ├── MerkleProof.sol │ │ │ ├── MetaCoin.sol │ │ │ ├── Migrations.sol │ │ │ ├── ReentrancyGuard.sol │ │ │ ├── crowdsale/ │ │ │ │ ├── CappedCrowdsale.sol │ │ │ │ ├── Crowdsale.sol │ │ │ │ ├── FinalizableCrowdsale.sol │ │ │ │ ├── RefundVault.sol │ │ │ │ └── RefundableCrowdsale.sol │ │ │ ├── examples/ │ │ │ │ ├── SampleCrowdsale.sol │ │ │ │ └── SimpleToken.sol │ │ │ ├── helpers/ │ │ │ │ ├── BasicTokenMock.sol │ │ │ │ ├── BurnableTokenMock.sol │ │ │ │ ├── CappedCrowdsaleImpl.sol │ │ │ │ ├── DayLimitMock.sol │ │ │ │ ├── DetailedERC20Mock.sol │ │ │ │ ├── ERC23TokenMock.sol │ │ │ │ ├── EVMRevert.js │ │ │ │ ├── EVMThrow.js │ │ │ │ ├── FinalizableCrowdsaleImpl.sol │ │ │ │ ├── ForceEther.sol │ │ │ │ ├── HasNoEtherTest.sol │ │ │ │ ├── InsecureTargetBounty.sol │ │ │ │ ├── LimitBalanceMock.sol │ │ │ │ ├── PausableMock.sol │ │ │ │ ├── PausableTokenMock.sol │ │ │ │ ├── PullPaymentMock.sol │ │ │ │ ├── ReentrancyAttack.sol │ │ │ │ ├── ReentrancyMock.sol │ │ │ │ ├── RefundableCrowdsaleImpl.sol │ │ │ │ ├── SafeERC20Helper.sol │ │ │ │ ├── SafeMathMock.sol │ │ │ │ ├── SecureTargetBounty.sol │ │ │ │ ├── SplitPaymentMock.sol │ │ │ │ ├── StandardTokenMock.sol │ │ │ │ ├── advanceToBlock.js │ │ │ │ ├── assertJump.js │ │ │ │ ├── assertRevert.js │ │ │ │ ├── ether.js │ │ │ │ ├── expectThrow.js │ │ │ │ ├── hashMessage.js │ │ │ │ ├── increaseTime.js │ │ │ │ ├── latestTime.js │ │ │ │ ├── merkleTree.js │ │ │ │ ├── toPromise.js │ │ │ │ └── transactionMined.js │ │ │ ├── lifecycle/ │ │ │ │ ├── Destructible.sol │ │ │ │ ├── Migrations.sol │ │ │ │ ├── Pausable.sol │ │ │ │ └── TokenDestructible.sol │ │ │ ├── math/ │ │ │ │ ├── Math.sol │ │ │ │ └── SafeMath.sol │ │ │ ├── ownership/ │ │ │ │ ├── CanReclaimToken.sol │ │ │ │ ├── Claimable.sol │ │ │ │ ├── Contactable.sol │ │ │ │ ├── DelayedClaimable.sol │ │ │ │ ├── HasNoContracts.sol │ │ │ │ ├── HasNoEther.sol │ │ │ │ ├── HasNoTokens.sol │ │ │ │ ├── NoOwner.sol │ │ │ │ └── Ownable.sol │ │ │ ├── payment/ │ │ │ │ ├── PullPayment.sol │ │ │ │ └── SplitPayment.sol │ │ │ └── token/ │ │ │ ├── BasicToken.sol │ │ │ ├── BurnableToken.sol │ │ │ ├── CappedToken.sol │ │ │ ├── DetailedERC20.sol │ │ │ ├── ERC20.sol │ │ │ ├── ERC20Basic.sol │ │ │ ├── MintableToken.sol │ │ │ ├── PausableToken.sol │ │ │ ├── SafeERC20.sol │ │ │ ├── StandardToken.sol │ │ │ ├── TokenTimelock.sol │ │ │ └── TokenVesting.sol │ │ ├── migrations/ │ │ │ ├── 1_initial_migration.js │ │ │ └── 2_deploy_contracts.js │ │ ├── package.json │ │ ├── test/ │ │ │ ├── BasicToken.js │ │ │ ├── Bounty.js │ │ │ ├── BurnableToken.js │ │ │ ├── CanReclaimToken.js │ │ │ ├── CappedCrowdsale.js │ │ │ ├── CappedToken.js │ │ │ ├── Claimable.js │ │ │ ├── Contactable.js │ │ │ ├── Crowdsale.js │ │ │ ├── DayLimit.js │ │ │ ├── DelayedClaimble.js │ │ │ ├── Destructible.js │ │ │ ├── DetailedERC20.js │ │ │ ├── ECRecovery.js │ │ │ ├── FinalizableCrowdsale.js │ │ │ ├── HasNoContracts.js │ │ │ ├── HasNoEther.js │ │ │ ├── HasNoTokens.js │ │ │ ├── LimitBalance.js │ │ │ ├── MerkleProof.js │ │ │ ├── MintableToken.js │ │ │ ├── Ownable.js │ │ │ ├── Pausable.js │ │ │ ├── PausableToken.js │ │ │ ├── PullPayment.js │ │ │ ├── ReentrancyGuard.js │ │ │ ├── RefundVault.js │ │ │ ├── RefundableCrowdsale.js │ │ │ ├── SafeERC20.js │ │ │ ├── SafeMath.js │ │ │ ├── SampleCrowdsale.js │ │ │ ├── SplitPayment.js │ │ │ ├── StandardToken.js │ │ │ ├── TestMetacoin.sol │ │ │ ├── TokenDestructible.js │ │ │ ├── TokenTimelock.js │ │ │ ├── TokenVesting.js │ │ │ ├── helpers/ │ │ │ │ ├── BasicTokenMock.sol │ │ │ │ ├── BurnableTokenMock.sol │ │ │ │ ├── CappedCrowdsaleImpl.sol │ │ │ │ ├── DayLimitMock.sol │ │ │ │ ├── DetailedERC20Mock.sol │ │ │ │ ├── ERC23TokenMock.sol │ │ │ │ ├── EVMRevert.js │ │ │ │ ├── EVMThrow.js │ │ │ │ ├── FinalizableCrowdsaleImpl.sol │ │ │ │ ├── ForceEther.sol │ │ │ │ ├── HasNoEtherTest.sol │ │ │ │ ├── InsecureTargetBounty.sol │ │ │ │ ├── LimitBalanceMock.sol │ │ │ │ ├── PausableMock.sol │ │ │ │ ├── PausableTokenMock.sol │ │ │ │ ├── PullPaymentMock.sol │ │ │ │ ├── ReentrancyAttack.sol │ │ │ │ ├── ReentrancyMock.sol │ │ │ │ ├── RefundableCrowdsaleImpl.sol │ │ │ │ ├── SafeERC20Helper.sol │ │ │ │ ├── SafeMathMock.sol │ │ │ │ ├── SecureTargetBounty.sol │ │ │ │ ├── SplitPaymentMock.sol │ │ │ │ ├── StandardTokenMock.sol │ │ │ │ ├── advanceToBlock.js │ │ │ │ ├── assertJump.js │ │ │ │ ├── assertRevert.js │ │ │ │ ├── ether.js │ │ │ │ ├── expectThrow.js │ │ │ │ ├── hashMessage.js │ │ │ │ ├── increaseTime.js │ │ │ │ ├── latestTime.js │ │ │ │ ├── merkleTree.js │ │ │ │ ├── toPromise.js │ │ │ │ └── transactionMined.js │ │ │ └── metacoin.js │ │ └── truffle.js │ ├── ozex/ │ │ ├── README.md │ │ ├── contracts/ │ │ │ ├── ExampleToken.sol │ │ │ └── Migrations.sol │ │ ├── migrations/ │ │ │ ├── 1_initial_migration.js │ │ │ └── 2_deploy_contracts.js │ │ ├── test/ │ │ │ └── exampletoken.js │ │ ├── truffle-config.js │ │ └── truffle.js │ ├── ozws/ │ │ ├── bs-config.json │ │ ├── contracts/ │ │ │ ├── Migrations.sol │ │ │ └── TutorialToken.sol │ │ ├── migrations/ │ │ │ ├── 1_initial_migration.js │ │ │ └── 2_deploy_contracts.js │ │ ├── package.json │ │ ├── src/ │ │ │ ├── index.html │ │ │ └── js/ │ │ │ ├── app.js │ │ │ └── truffle-contract.js │ │ ├── test/ │ │ │ └── .placeholder │ │ └── truffle.js │ ├── prueba/ │ │ ├── contracts/ │ │ │ └── Migrations.sol │ │ ├── migrations/ │ │ │ └── 1_initial_migration.js │ │ └── truffle-config.js │ ├── sf1/ │ │ ├── contracts/ │ │ │ ├── Ballot.sol │ │ │ ├── Counter.sol │ │ │ ├── Migrations.sol │ │ │ └── Token.sol │ │ ├── migrations/ │ │ │ ├── 1_initial_migration.js │ │ │ └── 2_deploy_contracts.js │ │ ├── test/ │ │ │ ├── Ballot_test.js │ │ │ ├── Counter_tests.js │ │ │ └── Token_test.js │ │ └── truffle-config.js │ ├── sj/ │ │ ├── contracts/ │ │ │ ├── Ballot.sol │ │ │ ├── Counter.sol │ │ │ ├── Empty.sol │ │ │ └── Migrations.sol │ │ ├── migrations/ │ │ │ ├── 1_initial_migration.js │ │ │ └── 2_deploy_contracts.js │ │ ├── test/ │ │ │ ├── Ballot_tests.js │ │ │ └── Counter_tests.js │ │ └── truffle-config.js │ ├── tokentutorial/ │ │ ├── bs-config.json │ │ ├── contracts/ │ │ │ └── Migrations.sol │ │ ├── migrations/ │ │ │ └── 1_initial_migration.js │ │ ├── package.json │ │ ├── src/ │ │ │ ├── index.html │ │ │ └── js/ │ │ │ ├── app.js │ │ │ └── truffle-contract.js │ │ ├── test/ │ │ │ └── .placeholder │ │ └── truffle.js │ ├── tpetshop/ │ │ ├── README.md │ │ ├── bs-config.json │ │ ├── contracts/ │ │ │ ├── .gitkeep │ │ │ ├── Adoption.sol │ │ │ ├── Migrations.sol │ │ │ └── MyContract.sol │ │ ├── migrations/ │ │ │ ├── 1_initial_migration.js │ │ │ └── 2_deploy_contracts.js │ │ ├── package.json │ │ ├── src/ │ │ │ ├── index.html │ │ │ ├── js/ │ │ │ │ ├── app.js │ │ │ │ └── truffle-contract.js │ │ │ └── pets.json │ │ ├── test/ │ │ │ ├── .gitkeep │ │ │ └── TestAdoption.sol │ │ └── truffle-config.js │ ├── webapp/ │ │ ├── .babelrc │ │ ├── .eslintignore │ │ ├── .eslintrc │ │ ├── .gitignore │ │ ├── ORIGINALREADME.md │ │ ├── README.md │ │ ├── app/ │ │ │ ├── index.html │ │ │ ├── javascripts/ │ │ │ │ └── app.js │ │ │ └── stylesheets/ │ │ │ └── app.css │ │ ├── contracts/ │ │ │ ├── ConvertLib.sol │ │ │ ├── MetaCoin.sol │ │ │ └── Migrations.sol │ │ ├── migrations/ │ │ │ ├── 1_initial_migration.js │ │ │ └── 2_deploy_contracts.js │ │ ├── package.json │ │ ├── test/ │ │ │ ├── TestMetacoin.sol │ │ │ └── metacoin.js │ │ ├── truffle-box.json │ │ ├── truffle.js │ │ └── webpack.config.js │ └── zero/ │ ├── contracts/ │ │ ├── ConvertLib.sol │ │ ├── MetaCoin.sol │ │ └── Migrations.sol │ ├── migrations/ │ │ ├── 1_initial_migration.js │ │ └── 2_deploy_contracts.js │ └── test/ │ ├── TestMetacoin.sol │ └── metacoin.js └── web31/ ├── abiencoding.js ├── accounts.js ├── accounts2.js ├── ballot.sol ├── compile.js ├── config.json ├── counter.js ├── counter.json ├── counter.sol ├── counter1.js ├── deploy.js ├── deploy1.js ├── deploy2.js ├── greeter.sol ├── message.json ├── message.sol └── package.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ node_modules ================================================ FILE: CryptoKitties/cryptokitties.sol ================================================ // CryptoKitties Source code // Copied from: https://etherscan.io/address/0x06012c8cf97bead5deae237070f9587f8e7a266d#code pragma solidity ^0.4.11; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley (https://github.com/dete) contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } // // Auction wrapper functions // Auction wrapper functions /// @title SEKRETOOOO contract GeneScienceInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isGeneScience() public pure returns (bool); /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor /// @param genes1 genes of mom /// @param genes2 genes of sire /// @return the genes that are supposed to be passed down the child function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public returns (uint256); } /// @title A facet of KittyCore that manages special access privileges. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. contract KittyAccessControl { // This facet controls access control for CryptoKitties. There are four roles managed here: // // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. It is initially // set to the address that created the smart contract in the KittyCore constructor. // // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. // // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. // // It should be noted that these roles are distinct without overlap in their access abilities, the // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any // address to any role, the CEO address itself doesn't have the ability to act in those roles. This // restriction is intentional so that we aren't tempted to use the CEO address frequently out of // convenience. The less we use an address, the less likely it is that we somehow compromise the // account. /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } /// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. contract KittyBase is KittyAccessControl { /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously /// includes any time a cat is created through the giveBirth method, but it is also called /// when a new gen0 cat is created. event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** DATA TYPES ***/ /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy /// of this structure, so great care was taken to ensure that it fits neatly into /// exactly two 256-bit words. Note that the order of the members in this structure /// is important because of the byte-packing rules used by Ethereum. /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Kitty { // The Kitty's genetic code is packed into these 256-bits, the format is // sooper-sekret! A cat's genes never change. uint256 genes; // The timestamp from the block when this cat came into existence. uint64 birthTime; // The minimum timestamp after which this cat can engage in breeding // activities again. This same timestamp is used for the pregnancy // timer (for matrons) as well as the siring cooldown. uint64 cooldownEndBlock; // The ID of the parents of this kitty, set to 0 for gen0 cats. // Note that using 32-bit unsigned integers limits us to a "mere" // 4 billion cats. This number might seem small until you realize // that Ethereum currently has a limit of about 500 million // transactions per year! So, this definitely won't be a problem // for several years (even as Ethereum learns to scale). uint32 matronId; uint32 sireId; // Set to the ID of the sire cat for matrons that are pregnant, // zero otherwise. A non-zero value here is how we know a cat // is pregnant. Used to retrieve the genetic material for the new // kitten when the birth transpires. uint32 siringWithId; // Set to the index in the cooldown array (see below) that represents // the current cooldown duration for this Kitty. This starts at zero // for gen0 cats, and is initialized to floor(generation/2) for others. // Incremented by one for each successful breeding action, regardless // of whether this cat is acting as matron or sire. uint16 cooldownIndex; // The "generation number" of this cat. Cats minted by the CK contract // for sale are called "gen0" and have a generation number of 0. The // generation number of all other cats is the larger of the two generation // numbers of their parents, plus one. // (i.e. max(matron.generation, sire.generation) + 1) uint16 generation; } /*** CONSTANTS ***/ /// @dev A lookup table indicating the cooldown duration after any successful /// breeding action, called "pregnancy time" for matrons and "siring cooldown" /// for sires. Designed such that the cooldown roughly doubles each time a cat /// is bred, encouraging owners not to just keep breeding the same cat over /// and over again. Caps out at one week (a cat can breed an unbounded number /// of times, and the maximum cooldown is always seven days). uint32[14] public cooldowns = [ uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(10 minutes), uint32(30 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /// @dev An array containing the Kitty struct for all Kitties in existence. The ID /// of each cat is actually an index into this array. Note that ID 0 is a negacat, /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre /// creature that is both matron and sire... to itself! Has an invalid genetic code. /// In other words, cat ID 0 is invalid... ;-) Kitty[] kitties; /// @dev A mapping from cat IDs to the address that owns them. All cats have /// some valid owner address, even gen0 cats are created with a non-zero owner. mapping (uint256 => address) public kittyIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; /// @dev A mapping from KittyIDs to an address that has been approved to call /// transferFrom(). Each Kitty can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public kittyIndexToApproved; /// @dev A mapping from KittyIDs to an address that has been approved to use /// this Kitty for siring via breedWith(). Each Kitty can only have one approved /// address for siring at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public sireAllowedToAddress; /// @dev The address of the ClockAuction contract that handles sales of Kitties. This /// same contract handles both peer-to-peer sales as well as the gen0 sales which are /// initiated every 15 minutes. SaleClockAuction public saleAuction; /// @dev The address of a custom ClockAuction subclassed contract that handles siring /// auctions. Needs to be separate from saleAuction because the actions taken on success /// after a sales and siring auction are quite different. SiringClockAuction public siringAuction; /// @dev Assigns ownership of a specific Kitty to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // Since the number of kittens is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; // transfer ownership kittyIndexToOwner[_tokenId] = _to; // When creating new kittens _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // once the kitten is transferred also clear sire allowances delete sireAllowedToAddress[_tokenId]; // clear any previously approved ownership exchange delete kittyIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } /// @dev An internal method that creates a new kitty and stores it. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate both a Birth event /// and a Transfer event. /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) /// @param _generation The generation number of this cat, must be computed by caller. /// @param _genes The kitty's genetic code. /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) function _createKitty( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _genes, address _owner ) internal returns (uint) { // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. However! _createKitty() is already // an expensive call (for storage), and it doesn't hurt to be especially careful // to ensure our data structures are always valid. require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint16(_generation))); // New kitty starts with the same cooldown as parent gen/2 uint16 cooldownIndex = uint16(_generation / 2); if (cooldownIndex > 13) { cooldownIndex = 13; } Kitty memory _kitty = Kitty({ genes: _genes, birthTime: uint64(now), cooldownEndBlock: 0, matronId: uint32(_matronId), sireId: uint32(_sireId), siringWithId: 0, cooldownIndex: cooldownIndex, generation: uint16(_generation) }); uint256 newKittenId = kitties.push(_kitty) - 1; // It's probably never going to happen, 4 billion cats is A LOT, but // let's just be 100% sure we never let this happen. require(newKittenId == uint256(uint32(newKittenId))); // emit the birth event Birth( _owner, newKittenId, uint256(_kitty.matronId), uint256(_kitty.sireId), _kitty.genes ); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, _owner, newKittenId); return newKittenId; } // Any C-level can fix how many seconds per blocks are currently observed. function setSecondsPerBlock(uint256 secs) external onlyCLevel { require(secs < cooldowns[0]); secondsPerBlock = secs; } } /// @title The external contract that is responsible for generating metadata for the kitties, /// it has one function that will return the data as bytes. contract ERC721Metadata { /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) { if (_tokenId == 1) { buffer[0] = "Hello World! :D"; count = 15; } else if (_tokenId == 2) { buffer[0] = "I would definitely choose a medi"; buffer[1] = "um length string."; count = 49; } else if (_tokenId == 3) { buffer[0] = "Lorem ipsum dolor sit amet, mi e"; buffer[1] = "st accumsan dapibus augue lorem,"; buffer[2] = " tristique vestibulum id, libero"; buffer[3] = " suscipit varius sapien aliquam."; count = 128; } } } /// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 /// See the KittyCore contract documentation to understand how the various contract facets are arranged. contract KittyOwnership is KittyBase, ERC721 { /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant name = "CryptoKitties"; string public constant symbol = "CK"; // The contract that will return kitty metadata ERC721Metadata public erc721Metadata; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } /// @dev Set the address of the sibling contract that tracks metadata. /// CEO only. function setMetadataAddress(address _contractAddress) public onlyCEO { erc721Metadata = ERC721Metadata(_contractAddress); } // Internal utility functions: These functions all assume that their input arguments // are valid. We leave it to public methods to sanitize their inputs and follow // the required logic. /// @dev Checks if a given address is the current owner of a particular Kitty. /// @param _claimant the address we are validating against. /// @param _tokenId kitten id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return kittyIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular Kitty. /// @param _claimant the address we are confirming kitten is approved for. /// @param _tokenId kitten id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return kittyIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Kitties on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { kittyIndexToApproved[_tokenId] = _approved; } /// @notice Returns the number of Kitties owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a Kitty to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Kitty to transfer. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any kitties (except very briefly // after a gen0 cat is created and before it goes on auction). require(_to != address(this)); // Disallow transfers to the auction contracts to prevent accidental // misuse. Auction contracts should only take ownership of kitties // through the allow + transferFrom flow. require(_to != address(saleAuction)); require(_to != address(siringAuction)); // You can only send your own cat. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific Kitty via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Kitty owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Kitty to be transfered. /// @param _to The address that should take ownership of the Kitty. Can be any address, /// including the caller. /// @param _tokenId The ID of the Kitty to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any kitties (except very briefly // after a gen0 cat is created and before it goes on auction). require(_to != address(this)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @notice Returns the total number of Kitties currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint) { return kitties.length - 1; } /// @notice Returns the address currently assigned ownership of a given Kitty. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = kittyIndexToOwner[_tokenId]; require(owner != address(0)); } /// @notice Returns a list of all Kitty IDs assigned to an address. /// @param _owner The owner whose Kitties we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Kitty array looking for cats belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalCats = totalSupply(); uint256 resultIndex = 0; // We count on the fact that all cats have IDs starting at 1 and increasing // sequentially up to the totalCat count. uint256 catId; for (catId = 1; catId <= totalCats; catId++) { if (kittyIndexToOwner[catId] == _owner) { result[resultIndex] = catId; resultIndex++; } } return result; } } /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _memcpy(uint _dest, uint _src, uint _len) private view { // Copy word-length chunks while possible for(; _len >= 32; _len -= 32) { assembly { mstore(_dest, mload(_src)) } _dest += 32; _src += 32; } // Copy remaining bytes uint256 mask = 256 ** (32 - _len) - 1; assembly { let srcpart := and(mload(_src), not(mask)) let destpart := and(mload(_dest), mask) mstore(_dest, or(destpart, srcpart)) } } /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) { var outputString = new string(_stringLength); uint256 outputPtr; uint256 bytesPtr; assembly { outputPtr := add(outputString, 32) bytesPtr := _rawBytes } _memcpy(outputPtr, bytesPtr, _stringLength); return outputString; } /// @notice Returns a URI pointing to a metadata package for this token conforming to /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) /// @param _tokenId The ID number of the Kitty whose metadata should be returned. function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) { require(erc721Metadata != address(0)); bytes32[4] memory buffer; uint256 count; (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); return _toString(buffer, count); } } /// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. contract KittyBreeding is KittyOwnership { /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy /// timer begins for the matron. event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by /// the COO role as the gas price changes. uint256 public autoBirthFee = 2 finney; // Keeps track of number of pregnant kitties. uint256 public pregnantKitties; /// @dev The address of the sibling contract that is used to implement the sooper-sekret /// genetic combination algorithm. GeneScienceInterface public geneScience; /// @dev Update the address of the genetic contract, can only be called by the CEO. /// @param _address An address of a GeneScience contract instance to be used from this point forward. function setGeneScienceAddress(address _address) external onlyCEO { GeneScienceInterface candidateContract = GeneScienceInterface(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isGeneScience()); // Set the new contract address geneScience = candidateContract; } /// @dev Checks that a given kitten is able to breed. Requires that the /// current cooldown is finished (for sires) and also checks that there is /// no pending pregnancy. function _isReadyToBreed(Kitty _kit) internal view returns (bool) { // In addition to checking the cooldownEndBlock, we also need to check to see if // the cat has a pending birth; there can be some period of time between the end // of the pregnacy timer and the birth event. return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); } /// @dev Check if a sire has authorized breeding with this matron. True if both sire /// and matron have the same owner, or if the sire has given siring permission to /// the matron's owner (via approveSiring()). function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { address matronOwner = kittyIndexToOwner[_matronId]; address sireOwner = kittyIndexToOwner[_sireId]; // Siring is okay if they have same owner, or if the matron's owner was given // permission to breed with this sire. return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); } /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. /// Also increments the cooldownIndex (unless it has hit the cap). /// @param _kitten A reference to the Kitty in storage which needs its timer started. function _triggerCooldown(Kitty storage _kitten) internal { // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); // Increment the breeding count, clamping it at 13, which is the length of the // cooldowns array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. Yay, Solidity! if (_kitten.cooldownIndex < 13) { _kitten.cooldownIndex += 1; } } /// @notice Grants approval to another user to sire with one of your Kitties. /// @param _addr The address that will be able to sire with your Kitty. Set to /// address(0) to clear all siring approvals for this Kitty. /// @param _sireId A Kitty that you own that _addr will now be able to sire with. function approveSiring(address _addr, uint256 _sireId) external whenNotPaused { require(_owns(msg.sender, _sireId)); sireAllowedToAddress[_sireId] = _addr; } /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only /// be called by the COO address. (This fee is used to offset the gas cost incurred /// by the autobirth daemon). function setAutoBirthFee(uint256 val) external onlyCOO { autoBirthFee = val; } /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation /// period has passed. function _isReadyToGiveBirth(Kitty _matron) private view returns (bool) { return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); } /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or /// in the middle of a siring cooldown). /// @param _kittyId reference the id of the kitten, any user can inquire about it function isReadyToBreed(uint256 _kittyId) public view returns (bool) { require(_kittyId > 0); Kitty storage kit = kitties[_kittyId]; return _isReadyToBreed(kit); } /// @dev Checks whether a kitty is currently pregnant. /// @param _kittyId reference the id of the kitten, any user can inquire about it function isPregnant(uint256 _kittyId) public view returns (bool) { require(_kittyId > 0); // A kitty is pregnant if and only if this field is set return kitties[_kittyId].siringWithId != 0; } /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT /// check ownership permissions (that is up to the caller). /// @param _matron A reference to the Kitty struct of the potential matron. /// @param _matronId The matron's ID. /// @param _sire A reference to the Kitty struct of the potential sire. /// @param _sireId The sire's ID function _isValidMatingPair( Kitty storage _matron, uint256 _matronId, Kitty storage _sire, uint256 _sireId ) private view returns(bool) { // A Kitty can't breed with itself! if (_matronId == _sireId) { return false; } // Kitties can't breed with their parents. if (_matron.matronId == _sireId || _matron.sireId == _sireId) { return false; } if (_sire.matronId == _matronId || _sire.sireId == _matronId) { return false; } // We can short circuit the sibling check (below) if either cat is // gen zero (has a matron ID of zero). if (_sire.matronId == 0 || _matron.matronId == 0) { return true; } // Kitties can't breed with full or half siblings. if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { return false; } if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { return false; } // Everything seems cool! Let's get DTF. return true; } /// @dev Internal check to see if a given sire and matron are a valid mating pair for /// breeding via auction (i.e. skips ownership and siring approval checks). function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) internal view returns (bool) { Kitty storage matron = kitties[_matronId]; Kitty storage sire = kitties[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId); } /// @notice Checks to see if two cats can breed together, including checks for /// ownership and siring approvals. Does NOT check that both cats are ready for /// breeding (i.e. breedWith could still fail until the cooldowns are finished). /// TODO: Shouldn't this check pregnancy and cooldowns?!? /// @param _matronId The ID of the proposed matron. /// @param _sireId The ID of the proposed sire. function canBreedWith(uint256 _matronId, uint256 _sireId) external view returns(bool) { require(_matronId > 0); require(_sireId > 0); Kitty storage matron = kitties[_matronId]; Kitty storage sire = kitties[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId) && _isSiringPermitted(_sireId, _matronId); } /// @dev Internal utility function to initiate breeding, assumes that all breeding /// requirements have been checked. function _breedWith(uint256 _matronId, uint256 _sireId) internal { // Grab a reference to the Kitties from storage. Kitty storage sire = kitties[_sireId]; Kitty storage matron = kitties[_matronId]; // Mark the matron as pregnant, keeping track of who the sire is. matron.siringWithId = uint32(_sireId); // Trigger the cooldown for both parents. _triggerCooldown(sire); _triggerCooldown(matron); // Clear siring permission for both parents. This may not be strictly necessary // but it's likely to avoid confusion! delete sireAllowedToAddress[_matronId]; delete sireAllowedToAddress[_sireId]; // Every time a kitty gets pregnant, counter is incremented. pregnantKitties++; // Emit the pregnancy event. Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); } /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you /// have previously been given Siring approval. Will either make your cat pregnant, or will /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) function breedWithAuto(uint256 _matronId, uint256 _sireId) external payable whenNotPaused { // Checks for payment. require(msg.value >= autoBirthFee); // Caller must own the matron. require(_owns(msg.sender, _matronId)); // Neither sire nor matron are allowed to be on auction during a normal // breeding operation, but we don't need to check that explicitly. // For matron: The caller of this function can't be the owner of the matron // because the owner of a Kitty on auction is the auction house, and the // auction house will never call breedWith(). // For sire: Similarly, a sire on auction will be owned by the auction house // and the act of transferring ownership will have cleared any oustanding // siring approval. // Thus we don't need to spend gas explicitly checking to see if either cat // is on auction. // Check that matron and sire are both owned by caller, or that the sire // has given siring permission to caller (i.e. matron's owner). // Will fail for _sireId = 0 require(_isSiringPermitted(_sireId, _matronId)); // Grab a reference to the potential matron Kitty storage matron = kitties[_matronId]; // Make sure matron isn't pregnant, or in the middle of a siring cooldown require(_isReadyToBreed(matron)); // Grab a reference to the potential sire Kitty storage sire = kitties[_sireId]; // Make sure sire isn't pregnant, or in the middle of a siring cooldown require(_isReadyToBreed(sire)); // Test that these cats are a valid mating pair. require(_isValidMatingPair( matron, _matronId, sire, _sireId )); // All checks passed, kitty gets pregnant! _breedWith(_matronId, _sireId); } /// @notice Have a pregnant Kitty give birth! /// @param _matronId A Kitty ready to give birth. /// @return The Kitty ID of the new kitten. /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned /// to the current owner of the matron. Upon successful completion, both the matron and the /// new kitten will be ready to breed again. Note that anyone can call this function (if they /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. function giveBirth(uint256 _matronId) external whenNotPaused returns(uint256) { // Grab a reference to the matron in storage. Kitty storage matron = kitties[_matronId]; // Check that the matron is a valid cat. require(matron.birthTime != 0); // Check that the matron is pregnant, and that its time has come! require(_isReadyToGiveBirth(matron)); // Grab a reference to the sire in storage. uint256 sireId = matron.siringWithId; Kitty storage sire = kitties[sireId]; // Determine the higher generation number of the two parents uint16 parentGen = matron.generation; if (sire.generation > matron.generation) { parentGen = sire.generation; } // Call the sooper-sekret gene mixing operation. uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); // Make the new kitten! address owner = kittyIndexToOwner[_matronId]; uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); // Clear the reference to sire from the matron (REQUIRED! Having siringWithId // set is what marks a matron as being pregnant.) delete matron.siringWithId; // Every time a kitty gives birth counter is decremented. pregnantKitties--; // Send the balance fee to the person who made birth happen. msg.sender.send(autoBirthFee); // return the new kitten's ID return kittenId; } } /// @title Auction Core /// @dev Contains models, variables, and internal methods for the auction. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuctionBase { // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; // Price (in wei) at beginning of auction uint128 startingPrice; // Price (in wei) at end of auction uint128 endingPrice; // Duration (in seconds) of auction uint64 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; } // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; // Map from token ID to their corresponding auction. mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint256 _tokenId, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); AuctionCancelled(_tokenId); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the bid is greater than or equal to the current price uint256 price = _currentPrice(auction); require(_bidAmount >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) seller.transfer(sellerProceeds); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 bidExcess = _bidAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. msg.sender.transfer(bidExcess); // Tell the world! AuctionSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Returns true if the NFT is on auction. /// @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /// @dev Returns current price of an NFT on auction. Broken into two /// functions (this one, that computes the duration from the auction /// structure, and the other that does the price computation) so we /// can easily test that the price computation works correctly. function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; // A bit of insurance against negative values (or wraparound). // Probably not necessary (since Ethereum guarnatees that the // now variable doesn't ever go backwards). if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } /// @dev Computes the current price of an auction. Factored out /// from _currentPrice so we can run extensive unit tests. /// When testing, make this function public and turn on /// `Current price computation` test suite. function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our public functions carefully cap the maximum values for // time (at 64-bits) and currency (at 128-bits). _duration is // also known to be non-zero (see the require() statement in // _addAuction()) if (_secondsPassed >= _duration) { // We've reached the end of the dynamic pricing portion // of the auction, just return the end price. return _endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multiplication can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that _startingPrice. Thus, this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } /// @title Clock auction for non-fungible tokens. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuction is Pausable, ClockAuctionBase { /// @dev The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _nftAddress - address of a deployed contract implementing /// the Nonfungible Interface. /// @param _cut - percent cut the owner takes on each auction, must be /// between 0-10,000. function ClockAuction(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); nonFungibleContract = candidateContract; } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == owner || msg.sender == nftAddress ); // We are using this boolean method to make sure that even if one fails it will still work bool res = nftAddress.send(this.balance); } /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of time to move between starting /// price and ending price (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external whenNotPaused { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(_owns(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Bids on an open auction, completing the auction and transferring /// ownership of the NFT if enough Ether is supplied. /// @param _tokenId - ID of token to bid on. function bid(uint256 _tokenId) external payable whenNotPaused { // _bid will throw if the bid or funds transfer fails _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); } /// @dev Cancels an auction that hasn't been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } /// @dev Cancels an auction when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyOwner external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } /// @dev Returns the current price of an auction. /// @param _tokenId - ID of the token price we are checking. function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } } /// @title Reverse auction modified for siring /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SiringClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSiringAuctionAddress() call. bool public isSiringClockAuction = true; // Delegate constructor function SiringClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be KittyCore contract. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Places a bid for siring. Requires the sender /// is the KittyCore contract because all bid methods /// should be wrapped. Also returns the kitty to the /// seller rather than the winner. function bid(uint256 _tokenId) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; // _bid checks that token ID is valid and will throw if bid fails _bid(_tokenId, msg.value); // We transfer the kitty back to the seller, the winner will get // the offspring _transfer(seller, _tokenId); } } /// @title Clock auction modified for sale of kitties /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SaleClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSaleAuctionAddress() call. bool public isSaleClockAuction = true; // Tracks last 5 sale price of gen0 kitty sales uint256 public gen0SaleCount; uint256[5] public lastGen0SalePrices; // Delegate constructor function SaleClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Updates lastSalePrice if seller is the nft contract /// Otherwise, works the same as default bid method. function bid(uint256 _tokenId) external payable { // _bid verifies token ID size address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); // If not a gen0 auction, exit if (seller == address(nonFungibleContract)) { // Track gen0 sale prices lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } } function averageGen0SalePrice() external view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastGen0SalePrices[i]; } return sum / 5; } } /// @title Handles creating auctions for sale and siring of kitties. /// This wrapper of ReverseAuction exists only so that users can create /// auctions with only one transaction. contract KittyAuction is KittyBreeding { // @notice The auction contract variables are defined in KittyBase to allow // us to refer to them in KittyOwnership to prevent accidental transfers. // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. // `siringAuction` refers to the auction for siring rights of kitties. /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionAddress(address _address) external onlyCEO { SaleClockAuction candidateContract = SaleClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSaleClockAuction()); // Set the new contract address saleAuction = candidateContract; } /// @dev Sets the reference to the siring auction. /// @param _address - Address of siring contract. function setSiringAuctionAddress(address _address) external onlyCEO { SiringClockAuction candidateContract = SiringClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSiringClockAuction()); // Set the new contract address siringAuction = candidateContract; } /// @dev Put a kitty up for auction. /// Does some ownership trickery to create auctions in one tx. function createSaleAuction( uint256 _kittyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If kitty is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _kittyId)); // Ensure the kitty is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the kitty IS allowed to be in a cooldown. require(!isPregnant(_kittyId)); _approve(_kittyId, saleAuction); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the kitty. saleAuction.createAuction( _kittyId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Put a kitty up for auction to be sire. /// Performs checks to ensure the kitty can be sired, then /// delegates to reverse auction. function createSiringAuction( uint256 _kittyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If kitty is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _kittyId)); require(isReadyToBreed(_kittyId)); _approve(_kittyId, siringAuction); // Siring auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the kitty. siringAuction.createAuction( _kittyId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Completes a siring auction by bidding. /// Immediately breeds the winning matron with the sire on auction. /// @param _sireId - ID of the sire on auction. /// @param _matronId - ID of the matron owned by the bidder. function bidOnSiringAuction( uint256 _sireId, uint256 _matronId ) external payable whenNotPaused { // Auction contract checks input sizes require(_owns(msg.sender, _matronId)); require(isReadyToBreed(_matronId)); require(_canBreedWithViaAuction(_matronId, _sireId)); // Define the current price of the auction. uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); require(msg.value >= currentPrice + autoBirthFee); // Siring auction will throw if the bid fails. siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); _breedWith(uint32(_matronId), uint32(_sireId)); } /// @dev Transfers the balance of the sale auction contract /// to the KittyCore contract. We use two-step withdrawal to /// prevent two transfer calls in the auction bid function. function withdrawAuctionBalances() external onlyCLevel { saleAuction.withdrawBalance(); siringAuction.withdrawBalance(); } } /// @title all functions related to creating kittens contract KittyMinting is KittyAuction { // Limits the number of cats the contract owner can ever create. uint256 public constant PROMO_CREATION_LIMIT = 5000; uint256 public constant GEN0_CREATION_LIMIT = 45000; // Constants for gen0 auctions. uint256 public constant GEN0_STARTING_PRICE = 10 finney; uint256 public constant GEN0_AUCTION_DURATION = 1 days; // Counts the number of cats the contract owner has created. uint256 public promoCreatedCount; uint256 public gen0CreatedCount; /// @dev we can create promo kittens, up to a limit. Only callable by COO /// @param _genes the encoded genes of the kitten to be created, any value is accepted /// @param _owner the future owner of the created kittens. Default to contract COO function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { address kittyOwner = _owner; if (kittyOwner == address(0)) { kittyOwner = cooAddress; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; _createKitty(0, 0, 0, _genes, kittyOwner); } /// @dev Creates a new gen0 kitty with the given genes and /// creates an auction for it. function createGen0Auction(uint256 _genes) external onlyCOO { require(gen0CreatedCount < GEN0_CREATION_LIMIT); uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); _approve(kittyId, saleAuction); saleAuction.createAuction( kittyId, _computeNextGen0Price(), 0, GEN0_AUCTION_DURATION, address(this) ); gen0CreatedCount++; } /// @dev Computes the next gen0 auction starting price, given /// the average of the past 5 prices + 50%. function _computeNextGen0Price() internal view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); // Sanity check to ensure we don't overflow arithmetic require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; } return nextPrice; } } /// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. contract KittyCore is KittyMinting { // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping // them in their own contracts, we can upgrade them without disrupting the main contract that tracks // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. // Don't worry, I'm sure someone will reverse engineer it soon enough! // // Secondly, we break the core contract into multiple files using inheritence, one for each major // facet of functionality of CK. This allows us to keep related code bundled together while still // avoiding a single giant file with everything in it. The breakdown is as follows: // // - KittyBase: This is where we define the most fundamental code shared throughout the core // functionality. This includes our main data storage, constants and data types, plus // internal functions for managing these items. // // - KittyAccessControl: This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO, CFO and COO. // // - KittyOwnership: This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // // - KittyBreeding: This file contains the methods necessary to breed cats together, including // keeping track of siring offers, and relies on an external genetic combination contract. // // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring // services. The actual auction functionality is handled in two sibling contracts (one // for sales and one for siring), while auction creation and bidding is mostly mediated // through this facet of the core contract. // // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. // We can make up to 5000 "promo" cats that can be given away (especially important when // the community is new), and all others can only be created and then immediately put up // for auction via an algorithmically determined starting price. Regardless of how they // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the // community to breed, breed, breed! // Set in case the core contract is broken and an upgrade is required address public newContractAddress; /// @notice Creates the main CryptoKitties smart contract instance. function KittyCore() public { // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is also the initial COO cooAddress = msg.sender; // start with the mythical kitten 0 - so we don't have generation-0 parent issues _createKitty(0, 0, 0, uint256(-1), address(0)); } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; ContractUpgrade(_v2Address); } /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) function() external payable { require( msg.sender == address(saleAuction) || msg.sender == address(siringAuction) ); } /// @notice Returns all the relevant information about a specific kitty. /// @param _id The ID of the kitty of interest. function getKitty(uint256 _id) external view returns ( bool isGestating, bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint256 siringWithId, uint256 birthTime, uint256 matronId, uint256 sireId, uint256 generation, uint256 genes ) { Kitty storage kit = kitties[_id]; // if this variable is 0 then it's not gestating isGestating = (kit.siringWithId != 0); isReady = (kit.cooldownEndBlock <= block.number); cooldownIndex = uint256(kit.cooldownIndex); nextActionAt = uint256(kit.cooldownEndBlock); siringWithId = uint256(kit.siringWithId); birthTime = uint256(kit.birthTime); matronId = uint256(kit.matronId); sireId = uint256(kit.sireId); generation = uint256(kit.generation); genes = kit.genes; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyCEO whenPaused { require(saleAuction != address(0)); require(siringAuction != address(0)); require(geneScience != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } // @dev Allows the CFO to capture the balance available to the contract. function withdrawBalance() external onlyCFO { uint256 balance = this.balance; // Subtract all the currently pregnant kittens we have, plus 1 of margin. uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; if (balance > subtractFees) { cfoAddress.send(balance - subtractFees); } } } ================================================ FILE: README.md ================================================ # Solidity Samples Solidity programming language samples, smart contracts for Ethereum. ## Related Repositories - [Aprendiendo Solidity (Spanish)](https://github.com/ajlopez/AprendiendoSolidity) - [Solidity Compiler](https://github.com/ajlopez/SolidityCompiler) - [Solidity Decompiler](https://github.com/ajlopez/yasold) ## References - [The Ethereum Project](https://ethereum.org/) - [Solidity Documentation](http://solidity.readthedocs.io/en/develop/) - [Truffle Framework](http://truffleframework.com/) - [OpenZeppelin](https://openzeppelin.org/) ## Ethereum - [The Complete Tutorial On Getting Started With Smart Contracts On Ethereum](https://medium.com/@ricochenx/the-complete-tutorial-on-getting-started-with-smart-contracts-on-ethereum-3ee6c54e84db) - [What is Ethereum?](https://medium.com/on-the-block/what-is-ethereum-fb6b7c33e21d) - [Learn Ethereum](https://ethereum.network/learn) - [The Hitchhikers Guide to Smart Contracts in Ethereum](https://blog.zeppelin.solutions/the-hitchhikers-guide-to-smart-contracts-in-ethereum-848f08001f05) - [Programming Ethereum smart contract transactions in JavaScript](https://tokenmarket.net/blog/creating-ethereum-smart-contract-transactions-in-client-side-javascript/) - [Ethereum Virtual Machine Awesome List](https://github.com/pirapira/awesome-ethereum-virtual-machine) - [A curated list of awesome Ethereum Resources](http://awesome-ethereum.com/) - [A Gentle Introduction to Ethereum Programming, Part 1](https://blog.zeppelin.solutions/a-gentle-introduction-to-ethereum-programming-part-1-783cc7796094) - [A Gentle Introduction to Ethereum Programming, Part 2](https://blog.zeppelin.solutions/a-gentle-introduction-to-ethereum-programming-part-2-7bbf15e1a953) - [A Gentle Introduction to Ethereum Programming, Part 3](https://blog.zeppelin.solutions/a-gentle-introduction-to-ethereum-programming-part-3-abdd9644d0c2) - [Ethereum Dev Cheatsheet](https://github.com/beether/ethereum-dev-cheatsheet) - [CryptoZombies is a free, interactive code school that teaches you to build games on Ethereum](https://cryptozombies.io/) - [Beether](http://www.beether.net/) - [Getting started with Ethereum as a developer](https://medium.com/bcgdv-engineering/getting-started-with-ethereum-as-a-developer-af20d78c49f) - [Getting Started as an Ethereum Web Developer](https://hackernoon.com/getting-started-as-an-ethereum-web-developer-9a2a4ab47baf) - [A Guide to Gas](https://media.consensys.net/a-guide-to-gas-12b40d03605d) - [Understanding the ethereum trie](https://easythereentropy.wordpress.com/2014/06/04/understanding-the-ethereum-trie/) - [Data structure in Ethereum | Episode 1: Recursive Length Prefix (RLP) Encoding/Decoding](https://medium.com/coinmonks/data-structure-in-ethereum-episode-1-recursive-length-prefix-rlp-encoding-decoding-d1016832f919) - [Data structure in Ethereum | Episode 1+: Compact (Hex-prefix) encoding](https://medium.com/coinmonks/data-structure-in-ethereum-episode-1-compact-hex-prefix-encoding-12558ae02791) - [Data structure in Ethereum | Episode 2: Radix trie and Merkle trie](https://medium.com/coinmonks/data-structure-in-ethereum-episode-2-radix-trie-and-merkle-trie-d941d0bfd69a) - [Data structure in Ethereum | Episode 3: Patricia trie](https://medium.com/coinmonks/data-structure-in-ethereum-episode-3-patricia-trie-b7b0ccddd32f) - [Data structure in Ethereum | Episode 4: Diving into examples](https://medium.com/coinmonks/data-structure-in-ethereum-episode-4-diving-by-examples-f6a4cbd8c329) - [Skewed Merkle Trees](https://medium.com/codechain/skewed-merkle-tree-259b984acc0c) - [Ethereum 69: how to set up a fully synced blockchain node in 10 mins](https://medium.freecodecamp.org/ethereum-69-how-to-set-up-a-fully-synced-blockchain-node-in-10-mins-f6318d7aad40) - [State Channels for Dummies: Part 5](https://medium.com/blockchannel/state-channels-for-dummies-part-5-6238f83f8da3) - [Ethereum Explained: Merkle Trees, World State, Transactions, and More](https://pegasys.tech/ethereum-explained-merkle-trees-world-state-transactions-and-more/) - [The 11 Best Sources for Ethereum News and Learning](https://media.consensys.net/the-11-best-sources-for-ethereum-news-and-learning-783ef4803ab0) - [Improving Smart Contract development with Tenderly and human readable stack traces](https://medium.com/tenderly/improving-smart-contract-development-with-tenderly-and-human-readable-stack-traces-16abfad5dd15) - [Ethereum Under the Hood: Part-1 (ver 0.1)](https://medium.com/coinmonks/ethereum-under-the-hood-part-i-ver-0-1-4f2fb24b3d68) - [Ethereum Under the Hood- Part 2 (RLP Encoding)](https://medium.com/coinmonks/ethereum-under-the-hood-part-ii-i-933411deebe1) - [Ethereum Under The Hood Part 3 (RLP Decoding)](https://medium.com/coinmonks/ethereum-under-the-hood-part-3-rlp-decoding-c0c07f5c0714) - [A Guide to Gas](https://media.consensys.net/a-guide-to-gas-12b40d03605d) - [A Definitive List of Ethereum Developer Tools](https://media.consensys.net/an-definitive-list-of-ethereum-developer-tools-2159ce865974) - [Ethereums EIP 2/4: 15 Second Block Target](https://blog.cotten.io/ethereums-eip-2-4-15-second-block-target-98d4c11017e1) - [The business of sending transactions on Ethereum](https://medium.com/coinmonks/the-business-of-sending-transactions-on-ethereum-e79fd9a2b88) - [EVM Evolution Roadmap](https://medium.com/spadebuilders/evm-evolution-roadmap-f8b8e3a73882) - [Ethereum Yellow Paper Walkthrough: Merkle Trees](https://dzone.com/articles/ethereum-yellow-paper-walkthrough-27) - [Role Based Access Control for the Ethereum Blockchain](https://hackernoon.com/role-based-access-control-for-the-ethereum-blockchain-bcc9dfbcfe5c) - [How does Ethereum work, anyway?](https://medium.com/@preethikasireddy/how-does-ethereum-work-anyway-22d1df506369) - [A guide to Ethereums ERC standards](https://news.yahoo.com/guide-ethereum-erc-standards-150024381.html) - [Diving into Ethereums world state](https://medium.com/cybermiles/diving-into-ethereums-world-state-c893102030ed) - [The Ethereum Virtual Machine (EVM) Runtime Environment](https://medium.com/0xcode/the-ethereum-virtual-machine-evm-runtime-environment-d7969544d3dd) - [How does Ethereum work, anyway?](https://medium.com/@preethikasireddy/how-does-ethereum-work-anyway-22d1df506369) - [Mastering The Fundamentals of Ethereum (For New Blockchain Devs) Part III Wallets, Keys, And Accounts](https://medium.com/@markmuskardin/mastering-the-fundamentals-of-ethereum-for-new-blockchain-devs-part-iii-wallets-keys-and-4cd3175b535b) - [Ethereum Development Crash Course Part One](https://medium.com/bitfwd/ethereum-development-crash-course-part-one-327dee16878b) - [Data Convergence Blockchain Blockchain Developer Tools](https://medium.com/data-convergence/data-convergence-blockchain-blockchain-developer-tools-8c9e98852251) ## Solidity - [Documentation](http://solidity.readthedocs.io/en/develop/index.html) - [Learning Solidity (videos)](https://www.youtube.com/watch?v=v_hU0jPtLto&list=PL16WqdAj66SCOdL6XIFbke-XQg2GW_Avg&index=1) - [Solidity Contracts](http://solidity.readthedocs.io/en/develop/contracts.html) - [Application Binary Interface Specification](http://solidity.readthedocs.io/en/develop/abi-spec.html#abi) - [Solidity Baby Steps](https://github.com/fivedogit/solidity-baby-steps) - [How to initialize an empty array and push items into it?](https://ethereum.stackexchange.com/questions/11533/how-to-initialize-an-empty-array-and-push-items-into-it) - [What is the memory keyword? What does it do?](https://solidity.readthedocs.io/en/latest/frequently-asked-questions.html#what-is-the-memory-keyword-what-does-it-do) - [A curated list of awesome Solidity resources, libraries, tools and more](https://github.com/bkrem/awesome-solidity) - [Solidity REPL](https://github.com/raineorshine/solidity-repl) - [Remix](https://remix.ethereum.org/#version=soljson-v0.4.18+commit.9cf6e910.js) - [Interaction between Contracts](https://dappsforbeginners.wordpress.com/tutorials/interactions-between-contracts/) - [How can I debug a smart contract?](https://ethereum.stackexchange.com/questions/184/how-can-i-debug-a-smart-contract) - [What is the difference between an internal/external and public/private function in solidity?](https://ethereum.stackexchange.com/questions/32353/what-is-the-difference-between-an-internal-external-and-public-private-function) - [external vs public best practices](https://ethereum.stackexchange.com/questions/19380/external-vs-public-best-practices) - [internal keyword in a function definition in Solidity](https://ethereum.stackexchange.com/questions/631/internal-keyword-in-a-function-definition-in-solidity) - [Doxity Documentation Generator for Solidity](https://github.com/DigixGlobal/doxity) - [Solidity doc generator](https://github.com/vitiko/solidity-doc) - [Markdown documentation generator for Solidity](https://github.com/dpilch/solmd) - [Solidity Common Patterns](http://solidity.readthedocs.io/en/develop/common-patterns.html) - [Thinking in Solidity](https://blog.cotten.io/thinking-in-solidity-6670c06390a9) - [Solidity tips and tricks to save gas and reduce bytecode size](https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6) - [Solidity CRUD- Epilogue](https://medium.com/robhitchens/solidity-crud-epilogue-e563e794fde) - [Getting Loopy with Solidity](https://blog.b9lab.com/getting-loopy-with-solidity-1d51794622ad) - [Solidity Collections](https://github.com/ethereum/wiki/wiki/Solidity-Collections) - [Testing and Code Coverage of Solidity Smart Contracts](https://medium.com/edgefund/testing-and-code-coverage-of-solidity-smart-contracts-660cb6291701 - [Which custom data structures do you use in Solidity?](https://forum.zeppelin.solutions/t/which-custom-data-structures-do-you-use-in-solidity/510) - [Ethernaut Lvl 0 Walkthrough: ABIs, Web3, and how to abuse them](https://hackernoon.com/ethernaut-lvl-0-walkthrough-abis-web3-and-how-to-abuse-them-d92a8842d71b) - [Deconstructing a Solidity Contract Part II: Creation vs. Runtime](https://forum.zeppelin.solutions/t/deconstructing-a-solidity-contract-part-ii-creation-vs-runtime/679) - [Solidity for Beginners](https://medium.com/swlh/solidity-for-beginners-9b8cb5cb4620) - [Stack Too Deep- Error in Solidity](https://medium.com/coinmonks/stack-too-deep-error-in-solidity-608d1bd6a1ea) - [Better Solidity debugging: stack traces are finally here](https://medium.com/nomic-labs-blog/better-solidity-debugging-stack-traces-are-finally-here-dd80a56f92bb) - [Fixed point math in Solidity](https://medium.com/cementdao/fixed-point-math-in-solidity-616f4508c6e8) - [Solidity Library for Array of Type Address](https://medium.com/51nodes/solidity-library-for-array-of-type-address-e40c36784ab2) - [`external` vs `public` best practices](https://ethereum.stackexchange.com/questions/19380/external-vs-public-best-practices) - [Solidity 0.6: You Might Be Sending Ether Incorrectly](https://medium.com/better-programming/solidity-0-6-you-might-be-sending-ether-all-wrong-1e119e1ffc27) - [Introduction into Mutation Testing](https://medium.com/swlh/introduction-into-mutation-testing-d6512dc702b0) - [Math in Solidity (Part 5: Exponent and Logarithm)](https://medium.com/coinmonks/math-in-solidity-part-5-exponent-and-logarithm-9aef8515136e) - [A brief analysis of the new try/catch functionality in Solidity 0.6](https://forum.openzeppelin.com/t/a-brief-analysis-of-the-new-try-catch-functionality-in-solidity-0-6/2564) ## Contracts - [How to Code Your Own CryptoKitties-Style Game on Ethereum](https://medium.com/loom-network/how-to-code-your-own-cryptokitties-style-game-on-ethereum-7c8ac86a4eb3) - [How to call a contract method using the eth_call JSON-RPC API](https://ethereum.stackexchange.com/questions/3514/how-to-call-a-contract-method-using-the-eth-call-json-rpc-api) - [Smart Contract Patterns](https://github.com/cjgdev/smart-contract-patterns) - [Writing upgradable contracts in Solidity](https://blog.colony.io/writing-upgradeable-contracts-in-solidity-6743f0eecc88) - [Legal Design Patterns in Smart Contracts](https://medium.com/@billgleim/legal-design-patterns-in-smart-contracts-60916cd9ebd7) - [Mad blockchain science: A 100% upgradeable contract](https://www.reddit.com/r/ethereum/comments/4kt1zp/mad_blockchain_science_a_100_upgradeable_contract/) - [EVM Assembly Tricks](http://www.swende.se/blog/EVM-Assembly-trick.html) - [Lottery as a Smart Contract: The Business Logic](https://medium.com/coinmonks/lottery-as-a-smart-contract-the-business-logic-3bd22d3a6c4e) - [Creating Smart Contracts with Smart Contract](https://medium.com/coinmonks/creating-smart-contracts-with-smart-contract-d54e21d26e00) - [How to Write Upgradeable Smart Contracts with Truffle 5.0 and ZeppelinOS 2.0](https://paulrberg.com/post/2018/12/30/upgradeable-smart-contracts/) - [zepcon0 - ZeppelinOS - Upgradeability by Elena Nadolinski](https://www.youtube.com/watch?v=FzmzUHLiutg) - [Smart Contracts: A Simple Guide Part 1](https://medium.com/@ShapeShift.io/smart-contracts-a-simple-guide-part-1-fa16a6c201c1) - [Writing Smart Contracts with Solidity > 0.5](https://medium.com/@rossbulat/writing-solidity-0-5-smart-contracts-101-5efd1ee9f53e) - [Dapp](https://dapp.tools/dapp/) - [Compiling and deploying Ethereum Smart Contracts with pure JavaScript](https://medium.com/coinmonks/compiling-and-deploying-ethereum-smart-contracts-with-pure-javascript-4bee3bfe99bb) - [Crypto Wars](https://github.com/e11-io/crypto-wars-solidity) - [Paritys Checklist for Secure Smart Contract Development](https://www.parity.io/paritys-checklist-for-secure-smart-contract-development/) - [A simple blockchain application for data verification](https://hackernoon.com/a-simple-blockchain-application-for-data-verification-c288a64e0d24) - [Smart contract vs token-based systems](https://medium.com/symbiont-io/smart-contract-vs-token-based-systems-ccdd99af41e3) - [Smart Contract Explained by Demonstration](https://medium.com/coinmonks/smart-contract-explained-by-demonstration-93b06e938474) - [How to write a simple token contract in Solidity](https://medium.com/datadriveninvestor/writing-a-simple-token-contract-in-solidity-1c457ab25b1a) ## Geth - [An Introduction to Geth and Running Ethereum Nodes](https://www.sitepoint.com/an-introduction-to-geth-and-running-ethereum-nodes/) - [Set up an Ethereum development network in two minutes](https://gist.github.com/evertonfraga/9d65a9f3ea399ac138b3e40641accf23) - [Ethereum : How to setup a local test node with initial ether balance using geth](https://medium.com/@chim/ethereum-how-to-setup-a-local-test-node-with-initial-ether-balance-using-geth-974511ce712) ## Web3JS - [Web3JS 1.x Documentation](http://web3js.readthedocs.io/en/1.0/) - [New Contract](https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#new-contract) - [Calling your first Smart Contract function with Web3 and Angular5](https://blog.fundrequest.io/calling-your-first-smart-contract-function-with-web3-and-angular5-aa1bde26a55c) - [Web3JS 0.2x Documentation](https://github.com/ethereum/wiki/wiki/JavaScript-API) - [03. Web3.js Tutorial - Attach a GUI to your Ethereum Smart Contract](https://www.youtube.com/watch?v=hcTPjpPvas8) - [04. Capturing Smart Contract Events in our User Interface (Solidity)](https://www.youtube.com/watch?v=L5Au5DY8eL4) ## Truffle - [Truffle Framework](http://truffleframework.com) - [Truffle Tutorials](http://truffleframework.com/tutorials) - [PetShop Tutorial](http://truffleframework.com/tutorials/pet-shop) - [Building Robust Smart Contracts with OpenZeppelin](http://truffleframework.com/tutorials/robust-smart-contracts-with-openzeppelin) - [Truffle Boxes](http://truffleframework.com/boxes) - [How Truffle Works Under the Hood](https://medium.com/heartbankacademy/how-truffle-works-under-the-hood-f1ff6add416c) - [Debugging Smart Contracts with Truffle Debugger: A Practical Approach](https://medium.com/coinmonks/debugging-smart-contracts-with-truffle-debugger-a-practical-approach-3410e9d20837) - [Unit Testing: Build a Decentralized Domain Name System on Top of Ethereum](https://hack.bg/blog/tutorials/part-two-unit-testing-build-a-decentralized-domain-name-system-ddns-on-top-of-ethereum/) - [Introduction to the Truffle Suite and Dapp Development Pipeline](https://medium.com/@rossbulat/introduction-to-the-truffle-suite-and-dapp-development-pipeline-1b33bb8228d4) - [Test Driven Solidity with Truffle](https://medium.com/@yahya_gis/test-driven-solidity-with-truffle-e4beaa2bd194) - [Solidity and TDD - How to build a smart contract](https://ilanolkies.com/post/Solidity-and-TDD) - [Managing Ethereum Smart Contract Events with Drizzle](https://medium.com/truffle-suite/managing-ethereum-smart-contract-events-with-drizzle-58f3f9afbdad) - [Getting Started with Drizzle and React](https://www.trufflesuite.com/tutorials/getting-started-with-drizzle-and-react) - [Handy helper functions for Solidity Development with Truffle](https://medium.com/@contacttomnash/handy-helper-functions-for-solidity-development-with-truffle-39d14a371c12) - [How to Write Complex Truffle Migrations](https://medium.com/better-programming/how-to-write-complex-truffle-migrations-86d4b85d7783) ## Dapps - [Dapps for Beginners](https://dappsforbeginners.wordpress.com) - [Tips and Tricks for Adding Metamask to Your UI](https://hackernoon.com/tips-and-tricks-for-adding-metamask-to-your-ui-32728b437194) - [Dip Dapp Doe??Anatomy of an Ethereum distributed fair game (part 1)](https://hackernoon.com/dip-dapp-doe-anatomy-of-an-ethereum-distributed-fair-game-part-1-5ee78980e360) - [Introducing ZepKit: the easiest way to start your decentralized application](https://blog.zeppelinos.org/introducing-zepkit/) - [Designing the architecture for your Ethereum application](https://forum.zeppelin.solutions/t/designing-the-architecture-for-your-ethereum-application/534/1) - [DApp Development for Python Programmers](https://levelup.gitconnected.com/dapps-development-for-python-developers-f52b32b54f28) ## Explorers - [Etherparty Explorer](https://github.com/etherparty/explorer) ## Tokens - [What is An Ethereum Token: The Ultimate Beginners Guide](https://blockgeeks.com/guides/ethereum-token/) - [ERC20 Token Standard](https://theethereum.wiki/w/index.php/ERC20_Token_Standard) - [ERC20 Token Standard: A Beginners Guide](https://medium.com/cryptoxtech/erc20-token-standard-a-beginners-guide-5b5f0c87e11f) - [ERC20](https://en.wikipedia.org/wiki/ERC20) - [Ethereum's ERC-20 Token Standard Has Been Formalized](https://www.coindesk.com/ethereums-erc-20-token-standard-formalized/) - [ERC20 Standard Token Explorer](https://etherscan.io/token-search) - [ERC: Non-fungible Token Standard #721](https://github.com/ethereum/EIPs/issues/721) - [Ethereum Based Tokens](https://theethereum.wiki/w/index.php/Ethereum_Based_Tokens) - [Ethereum smart service payment with tokens](https://medium.com/@jgm.orinoco/ethereum-smart-service-payment-with-tokens-60894a79f75c) - [How To Write A Smart-Contract For Your ICO? An Ultimate guide](https://howtotoken.com/ico/how-to-write-a-smart-contract-for-your-ico-an-ultimate-guide/) - [The Innards of an ERC20 Token](https://hackernoon.com/the-innards-of-an-erc20-token-587c29e9b8a1) ## CryptoKitties - [CriptoKitties](https://www.cryptokitties.co/) - [CriptoKitties White Paper](https://www.dropbox.com/s/a5h3zso545wuqkm/CryptoKitties_WhitePapurr_V2.pdf?dl=0) - [How to Code Your Own CryptoKitties-Style Game on Ethereum](https://medium.com/loom-network/how-to-code-your-own-cryptokitties-style-game-on-ethereum-7c8ac86a4eb3) - [CryptoKitties](https://www.cryptokitties.co) - [CryptoKitties: Collectible and Breedable Cats Empowered by Blockchain Technology](https://www.dropbox.com/s/a5h3zso545wuqkm/CryptoKitties_WhitePapurr_V2.pdf?dl=0) - [Source Code](https://ethfiddle.com/09YbyJRfiI) - [Code From EtherScan](https://etherscan.io/address/0x06012c8cf97bead5deae237070f9587f8e7a266d#code) - [The Inside Story of the CryptoKitties Congestion Crisis](https://media.consensys.net/the-inside-story-of-the-cryptokitties-congestion-crisis-499b35d119cc) - [Hacking the CryptoKitties Genome](https://hackernoon.com/hacking-the-cryptokitties-genome-1cb3e7dddab3) - [CryptoKitties, Explained Mostly](https://medium.com/the-new-york-times/cryptokitties-explained-mostly-d56d70024f36) ## Zeppelin - [How to implement ERC20 supply mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226) ================================================ FILE: exeth/bet/bet.eth ================================================ # retrieve accounts message "retrieving accounts..." accounts # compile contract # (contracts variable has the compiled contract data) message "compiling contract..." compile "./contracts/bet.sol" message "contract function hashes" dump contracts.Bet.evm.methodIdentifiers deploy Bet bet dump instances.bet message "unknown match amount..." call bet getMatchAmount(string) "foo" assert result == 0 message "OK" message "first bet..." set value 1000 invoke bet bet(string,string) "foo" "bar" set value 0 call bet getMatchAmount(string) "foo" assert result == 1000 message "OK" message "second bet..." set value 2000 invoke bet bet(string,string) "foo" "bar" set value 0 call bet getMatchAmount(string) "foo" assert result == 3000 message "OK" message "third bet with second player..." set value 4000 set from accounts[1] invoke bet bet(string,string) "foo" "baz" set value 0 set from accounts[0] call bet getMatchAmount(string) "foo" assert result == 7000 message "OK" message "amount of first player..." call bet getAddressAmount(address,string) accounts[0] "foo" assert result == 3000 message "OK" message "amount of second player..." call bet getAddressAmount(address,string) accounts[1] "foo" assert result == 4000 message "OK" message "amount of third player..." call bet getAddressAmount(address,string) accounts[2] "foo" assert result == 0 message "OK" message "amount of first player in unknown match..." call bet getAddressAmount(address,string) accounts[0] "unknown" assert result == 0 message "OK" message "amount of match and first result" call bet getMatchAmount(string,string) "foo" "bar" assert result == 3000 message "OK" message "amount of match and second result" call bet getMatchAmount(string,string) "foo" "baz" assert result == 4000 message "OK" message "resolve match" balance accounts[0] message "balance first player before resolve" result balance accounts[1] message "balance second player before resolve" result invoke bet resolve(string,string) "foo" "bar" balance accounts[0] message "balance first player after resolve" result balance accounts[1] message "balance second player after resolve" result message "OK" message "done" ================================================ FILE: exeth/bet/contracts/bet.sol ================================================ contract Bet { struct Bet { address payable account; string name; string result; uint amount; } mapping (string => Bet[]) betsByMatch; mapping (address => Bet[]) betsByAddress; function bet(string memory name, string memory result) public payable { Bet memory b = Bet(msg.sender, name, result, msg.value); betsByAddress[msg.sender].push(b); betsByMatch[name].push(b); } function getMatchAmount(string memory name) public view returns (uint) { uint result; Bet[] storage bets = betsByMatch[name]; uint nbets = bets.length; for (uint k = 0; k < nbets; k++) { Bet storage b = bets[k]; result += b.amount; } return result; } function getMatchAmount(string memory name, string memory result) public view returns (uint) { uint amount; Bet[] storage bets = betsByMatch[name]; uint nbets = bets.length; bytes32 kresult = keccak256(abi.encodePacked(result)); for (uint k = 0; k < nbets; k++) { Bet storage b = bets[k]; if (keccak256(abi.encodePacked(b.result)) != kresult) continue; amount += b.amount; } return amount; } function resolve(string memory name, string memory result) public { uint total = getMatchAmount(name); uint winners = getMatchAmount(name, result); bytes32 kresult = keccak256(abi.encodePacked(result)); if (winners > 0) { uint factor = total / winners; Bet[] storage bets = betsByMatch[name]; uint nbets = bets.length; for (uint k = 0; k < nbets; k++) { Bet storage b = bets[k]; if (keccak256(abi.encodePacked(b.result)) != kresult) continue; b.account.transfer(factor * b.amount); } } betsByMatch[name].length = 0; return; } function getAddressAmount(address from, string memory name) public view returns (uint) { uint result; Bet[] storage bs = betsByAddress[from]; uint nbs = bs.length; bytes32 kname = keccak256(abi.encodePacked(name)); for (uint k = 0; k < nbs; k++) { Bet storage b = bs[k]; if (keccak256(abi.encodePacked(b.name)) != kname) continue; result += b.amount; } return result; } } ================================================ FILE: exeth/blockchain/blockchain.eth ================================================ # retrieve accounts message "retrieving accounts..." accounts # compile contract # (contracts variable has the compiled contract data) message "compiling contract..." compile "./contracts/blockchain.sol" message "contract function hashes" dump contracts.Blockchain.functionHashes # deploy instances, using default sender: accounts[0], message default value: 0 # first argument: contract name # second argument: new instance name message "deploy instance..." deploy Blockchain blockchain # show instance address # (instances variable has the instances data) message "new instance" instances.blockchain.address # the block with hash 0 is not in the blockchain message "check block with hash" 0 call blockchain blockInfos(uint256) 0 assert result.length === 3 assert result[0] == 0 assert result[1] == 0 assert result[2] == 0 # add a block message "adding block with hash 0x0100..." invoke blockchain addBlock(uint32,uint256,uint256) 1 0x0100 0 message "check block with hash" 0x0100 call blockchain blockInfos(uint256) 0x0100 assert result.length === 3 assert result[0] == 1 assert result[1] == 0x100 assert result[2] == 0 message "block info" result # add orphan block message "adding orphan block..." invoke blockchain addBlock(uint32,uint256,uint256) 3 0x0300 0x0200 message "check block with hash" 0x0300 call blockchain blockInfos(uint256) 0x0300 assert result.length === 3 assert result[0] == 0 assert result[1] == 0 assert result[2] == 0 message "block does not exist" message "done" ================================================ FILE: exeth/blockchain/contracts/blockchain.sol ================================================ contract Blockchain { struct BlockInfo { uint32 number; uint hash; uint parentHash; } mapping(uint => BlockInfo) public blockInfos; function addBlock(uint32 number, uint hash, uint parentHash) public returns (bool) { if (blockInfos[hash].hash != 0) return false; if (number > 1 && blockInfos[parentHash].hash == 0) return false; BlockInfo memory binfo = BlockInfo(number, hash, parentHash); blockInfos[hash] = binfo; return true; } } ================================================ FILE: exeth/events/build/contracts/Emitter.json ================================================ { "contractName": "Emitter", "abi": [ { "anonymous": false, "inputs": [], "name": "BeginEvents", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "receiver", "type": "address" }, { "indexed": true, "name": "token", "type": "address" }, { "indexed": false, "name": "amount", "type": "uint256" } ], "name": "Transfer", "type": "event" }, { "anonymous": false, "inputs": [], "name": "EndEvents", "type": "event" }, { "constant": false, "inputs": [ { "name": "receivers", "type": "address[]" }, { "name": "tokens", "type": "address[]" }, { "name": "amounts", "type": "uint256[]" } ], "name": "emitEvents", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" } ], "metadata": "{\"compiler\":{\"version\":\"0.5.0+commit.1d4f565a\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"constant\":false,\"inputs\":[{\"name\":\"receivers\",\"type\":\"address[]\"},{\"name\":\"tokens\",\"type\":\"address[]\"},{\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"name\":\"emitEvents\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[],\"name\":\"BeginEvents\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"receiver\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"token\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[],\"name\":\"EndEvents\",\"type\":\"event\"}],\"devdoc\":{\"methods\":{}},\"userdoc\":{\"methods\":{}}},\"settings\":{\"compilationTarget\":{\"/C/git/SoliditySamples/exeth/events/contracts/Emitter.sol\":\"Emitter\"},\"evmVersion\":\"byzantium\",\"libraries\":{},\"optimizer\":{\"enabled\":false,\"runs\":200},\"remappings\":[]},\"sources\":{\"/C/git/SoliditySamples/exeth/events/contracts/Emitter.sol\":{\"keccak256\":\"0x5a7d8d2327771f416c2fef21b20b7aad388b7026f17a5bc061528e7ae45f888c\",\"urls\":[\"bzzr://d1ab698196751e58ae4b0f7b35590fcdc964cc14b4e47b96e9c3c36a78278090\"]}},\"version\":1}", "bytecode": "0x608060405234801561001057600080fd5b50610389806100206000396000f3fe608060405260043610610041576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680637da2938a14610046575b600080fd5b34801561005257600080fd5b506102316004803603606081101561006957600080fd5b810190808035906020019064010000000081111561008657600080fd5b82018360208201111561009857600080fd5b803590602001918460208302840111640100000000831117156100ba57600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600081840152601f19601f8201169050808301925050505050505091929192908035906020019064010000000081111561011a57600080fd5b82018360208201111561012c57600080fd5b8035906020019184602083028401116401000000008311171561014e57600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600081840152601f19601f820116905080830192505050505050509192919290803590602001906401000000008111156101ae57600080fd5b8201836020820111156101c057600080fd5b803590602001918460208302840111640100000000831117156101e257600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600081840152601f19601f820116905080830192505050505050509192919290505050610233565b005b6000835190507f875d966eda6487c7c1a52ef9d6ec077de2fe63a903c4ed02db0d11f4528a001160405160405180910390a160008090505b8181101561032a57838181518110151561028157fe5b9060200190602002015173ffffffffffffffffffffffffffffffffffffffff1685828151811015156102af57fe5b9060200190602002015173ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef85848151811015156102fe57fe5b906020019060200201516040518082815260200191505060405180910390a3808060010191505061026b565b507f30beee9487f19272cea486f3940e1f4a5ce5d4f4fecb20dbf6979d63e695e5d760405160405180910390a15050505056fea165627a7a72305820650f25b8abd4b8e7f9b4428413d06590d1a55ca48f362990346605239464787c0029", "deployedBytecode": "0x608060405260043610610041576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680637da2938a14610046575b600080fd5b34801561005257600080fd5b506102316004803603606081101561006957600080fd5b810190808035906020019064010000000081111561008657600080fd5b82018360208201111561009857600080fd5b803590602001918460208302840111640100000000831117156100ba57600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600081840152601f19601f8201169050808301925050505050505091929192908035906020019064010000000081111561011a57600080fd5b82018360208201111561012c57600080fd5b8035906020019184602083028401116401000000008311171561014e57600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600081840152601f19601f820116905080830192505050505050509192919290803590602001906401000000008111156101ae57600080fd5b8201836020820111156101c057600080fd5b803590602001918460208302840111640100000000831117156101e257600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600081840152601f19601f820116905080830192505050505050509192919290505050610233565b005b6000835190507f875d966eda6487c7c1a52ef9d6ec077de2fe63a903c4ed02db0d11f4528a001160405160405180910390a160008090505b8181101561032a57838181518110151561028157fe5b9060200190602002015173ffffffffffffffffffffffffffffffffffffffff1685828151811015156102af57fe5b9060200190602002015173ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef85848151811015156102fe57fe5b906020019060200201516040518082815260200191505060405180910390a3808060010191505061026b565b507f30beee9487f19272cea486f3940e1f4a5ce5d4f4fecb20dbf6979d63e695e5d760405160405180910390a15050505056fea165627a7a72305820650f25b8abd4b8e7f9b4428413d06590d1a55ca48f362990346605239464787c0029", "sourceMap": "2:524:0:-;;;;8:9:-1;5:2;;;30:1;27;20:12;5:2;2:524:0;;;;;;;", "deployedSourceMap": "2:524:0:-;;;;;;;;;;;;;;;;;;;;;;;;168:355;;8:9:-1;5:2;;;30:1;27;20:12;5:2;168:355:0;;;;;;13:2:-1;8:3;5:11;2:2;;;29:1;26;19:12;2:2;168:355:0;;;;;;;;;;21:11:-1;8;5:28;2:2;;;46:1;43;36:12;2:2;168:355:0;;35:9:-1;28:4;12:14;8:25;5:40;2:2;;;58:1;55;48:12;2:2;168:355:0;;;;;;101:9:-1;95:2;81:12;77:21;67:8;63:36;60:51;39:11;25:12;22:29;11:108;8:2;;;132:1;129;122:12;8:2;168:355:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;30:3:-1;22:6;14;1:33;99:1;93:3;85:6;81:16;74:27;137:4;133:9;126:4;121:3;117:14;113:30;106:37;;169:3;161:6;157:16;147:26;;168:355:0;;;;;;;;;;;;;;;;;21:11:-1;8;5:28;2:2;;;46:1;43;36:12;2:2;168:355:0;;35:9:-1;28:4;12:14;8:25;5:40;2:2;;;58:1;55;48:12;2:2;168:355:0;;;;;;101:9:-1;95:2;81:12;77:21;67:8;63:36;60:51;39:11;25:12;22:29;11:108;8:2;;;132:1;129;122:12;8:2;168:355:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;30:3:-1;22:6;14;1:33;99:1;93:3;85:6;81:16;74:27;137:4;133:9;126:4;121:3;117:14;113:30;106:37;;169:3;161:6;157:16;147:26;;168:355:0;;;;;;;;;;;;;;;;;21:11:-1;8;5:28;2:2;;;46:1;43;36:12;2:2;168:355:0;;35:9:-1;28:4;12:14;8:25;5:40;2:2;;;58:1;55;48:12;2:2;168:355:0;;;;;;101:9:-1;95:2;81:12;77:21;67:8;63:36;60:51;39:11;25:12;22:29;11:108;8:2;;;132:1;129;122:12;8:2;168:355:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;30:3:-1;22:6;14;1:33;99:1;93:3;85:6;81:16;74:27;137:4;133:9;126:4;121:3;117:14;113:30;106:37;;169:3;161:6;157:16;147:26;;168:355:0;;;;;;;;;;;;;;;;;;;285:12;300:9;:16;285:31;;342:13;;;;;;;;;;381:6;390:1;381:10;;376:98;397:7;393:1;:11;376:98;;;452:6;459:1;452:9;;;;;;;;;;;;;;;;;;429:45;;438:9;448:1;438:12;;;;;;;;;;;;;;;;;;429:45;;;463:7;471:1;463:10;;;;;;;;;;;;;;;;;;429:45;;;;;;;;;;;;;;;;;;406:3;;;;;;;376:98;;;;504:11;;;;;;;;;;168:355;;;;:::o", "source": "\r\ncontract Emitter {\r\n event BeginEvents();\r\n event Transfer(address indexed receiver, address indexed token, uint256 amount);\r\n event EndEvents();\r\n \r\n function emitEvents(address[] memory receivers, address[] memory tokens, uint256[] memory amounts) public {\r\n uint nevents = receivers.length;\r\n \r\n emit BeginEvents();\r\n \r\n for (uint k = 0; k < nevents; k++)\r\n emit Transfer(receivers[k], tokens[k], amounts[k]);\r\n \r\n emit EndEvents();\r\n }\r\n}", "sourcePath": "C:/git/SoliditySamples/exeth/events/contracts/Emitter.sol", "ast": { "absolutePath": "/C/git/SoliditySamples/exeth/events/contracts/Emitter.sol", "exportedSymbols": { "Emitter": [ 60 ] }, "id": 61, "nodeType": "SourceUnit", "nodes": [ { "baseContracts": [], "contractDependencies": [], "contractKind": "contract", "documentation": null, "fullyImplemented": true, "id": 60, "linearizedBaseContracts": [ 60 ], "name": "Emitter", "nodeType": "ContractDefinition", "nodes": [ { "anonymous": false, "documentation": null, "id": 2, "name": "BeginEvents", "nodeType": "EventDefinition", "parameters": { "id": 1, "nodeType": "ParameterList", "parameters": [], "src": "43:2:0" }, "src": "26:20:0" }, { "anonymous": false, "documentation": null, "id": 10, "name": "Transfer", "nodeType": "EventDefinition", "parameters": { "id": 9, "nodeType": "ParameterList", "parameters": [ { "constant": false, "id": 4, "indexed": true, "name": "receiver", "nodeType": "VariableDeclaration", "scope": 10, "src": "67:24:0", "stateVariable": false, "storageLocation": "default", "typeDescriptions": { "typeIdentifier": "t_address", "typeString": "address" }, "typeName": { "id": 3, "name": "address", "nodeType": "ElementaryTypeName", "src": "67:7:0", "stateMutability": "nonpayable", "typeDescriptions": { "typeIdentifier": "t_address", "typeString": "address" } }, "value": null, "visibility": "internal" }, { "constant": false, "id": 6, "indexed": true, "name": "token", "nodeType": "VariableDeclaration", "scope": 10, "src": "93:21:0", "stateVariable": false, "storageLocation": "default", "typeDescriptions": { "typeIdentifier": "t_address", "typeString": "address" }, "typeName": { "id": 5, "name": "address", "nodeType": "ElementaryTypeName", "src": "93:7:0", "stateMutability": "nonpayable", "typeDescriptions": { "typeIdentifier": "t_address", "typeString": "address" } }, "value": null, "visibility": "internal" }, { "constant": false, "id": 8, "indexed": false, "name": "amount", "nodeType": "VariableDeclaration", "scope": 10, "src": "116:14:0", "stateVariable": false, "storageLocation": "default", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" }, "typeName": { "id": 7, "name": "uint256", "nodeType": "ElementaryTypeName", "src": "116:7:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "value": null, "visibility": "internal" } ], "src": "66:65:0" }, "src": "52:80:0" }, { "anonymous": false, "documentation": null, "id": 12, "name": "EndEvents", "nodeType": "EventDefinition", "parameters": { "id": 11, "nodeType": "ParameterList", "parameters": [], "src": "153:2:0" }, "src": "138:18:0" }, { "body": { "id": 58, "nodeType": "Block", "src": "274:249:0", "statements": [ { "assignments": [ 25 ], "declarations": [ { "constant": false, "id": 25, "name": "nevents", "nodeType": "VariableDeclaration", "scope": 58, "src": "285:12:0", "stateVariable": false, "storageLocation": "default", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" }, "typeName": { "id": 24, "name": "uint", "nodeType": "ElementaryTypeName", "src": "285:4:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "value": null, "visibility": "internal" } ], "id": 28, "initialValue": { "argumentTypes": null, "expression": { "argumentTypes": null, "id": 26, "name": "receivers", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 15, "src": "300:9:0", "typeDescriptions": { "typeIdentifier": "t_array$_t_address_$dyn_memory_ptr", "typeString": "address[] memory" } }, "id": 27, "isConstant": false, "isLValue": false, "isPure": false, "lValueRequested": false, "memberName": "length", "nodeType": "MemberAccess", "referencedDeclaration": null, "src": "300:16:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "nodeType": "VariableDeclarationStatement", "src": "285:31:0" }, { "eventCall": { "argumentTypes": null, "arguments": [], "expression": { "argumentTypes": [], "id": 29, "name": "BeginEvents", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 2, "src": "342:11:0", "typeDescriptions": { "typeIdentifier": "t_function_event_nonpayable$__$returns$__$", "typeString": "function ()" } }, "id": 30, "isConstant": false, "isLValue": false, "isPure": false, "kind": "functionCall", "lValueRequested": false, "names": [], "nodeType": "FunctionCall", "src": "342:13:0", "typeDescriptions": { "typeIdentifier": "t_tuple$__$", "typeString": "tuple()" } }, "id": 31, "nodeType": "EmitStatement", "src": "337:18:0" }, { "body": { "eventCall": { "argumentTypes": null, "arguments": [ { "argumentTypes": null, "baseExpression": { "argumentTypes": null, "id": 43, "name": "receivers", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 15, "src": "438:9:0", "typeDescriptions": { "typeIdentifier": "t_array$_t_address_$dyn_memory_ptr", "typeString": "address[] memory" } }, "id": 45, "indexExpression": { "argumentTypes": null, "id": 44, "name": "k", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 33, "src": "448:1:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "isConstant": false, "isLValue": true, "isPure": false, "lValueRequested": false, "nodeType": "IndexAccess", "src": "438:12:0", "typeDescriptions": { "typeIdentifier": "t_address", "typeString": "address" } }, { "argumentTypes": null, "baseExpression": { "argumentTypes": null, "id": 46, "name": "tokens", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 18, "src": "452:6:0", "typeDescriptions": { "typeIdentifier": "t_array$_t_address_$dyn_memory_ptr", "typeString": "address[] memory" } }, "id": 48, "indexExpression": { "argumentTypes": null, "id": 47, "name": "k", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 33, "src": "459:1:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "isConstant": false, "isLValue": true, "isPure": false, "lValueRequested": false, "nodeType": "IndexAccess", "src": "452:9:0", "typeDescriptions": { "typeIdentifier": "t_address", "typeString": "address" } }, { "argumentTypes": null, "baseExpression": { "argumentTypes": null, "id": 49, "name": "amounts", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 21, "src": "463:7:0", "typeDescriptions": { "typeIdentifier": "t_array$_t_uint256_$dyn_memory_ptr", "typeString": "uint256[] memory" } }, "id": 51, "indexExpression": { "argumentTypes": null, "id": 50, "name": "k", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 33, "src": "471:1:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "isConstant": false, "isLValue": true, "isPure": false, "lValueRequested": false, "nodeType": "IndexAccess", "src": "463:10:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } } ], "expression": { "argumentTypes": [ { "typeIdentifier": "t_address", "typeString": "address" }, { "typeIdentifier": "t_address", "typeString": "address" }, { "typeIdentifier": "t_uint256", "typeString": "uint256" } ], "id": 42, "name": "Transfer", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 10, "src": "429:8:0", "typeDescriptions": { "typeIdentifier": "t_function_event_nonpayable$_t_address_$_t_address_$_t_uint256_$returns$__$", "typeString": "function (address,address,uint256)" } }, "id": 52, "isConstant": false, "isLValue": false, "isPure": false, "kind": "functionCall", "lValueRequested": false, "names": [], "nodeType": "FunctionCall", "src": "429:45:0", "typeDescriptions": { "typeIdentifier": "t_tuple$__$", "typeString": "tuple()" } }, "id": 53, "nodeType": "EmitStatement", "src": "424:50:0" }, "condition": { "argumentTypes": null, "commonType": { "typeIdentifier": "t_uint256", "typeString": "uint256" }, "id": 38, "isConstant": false, "isLValue": false, "isPure": false, "lValueRequested": false, "leftExpression": { "argumentTypes": null, "id": 36, "name": "k", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 33, "src": "393:1:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "nodeType": "BinaryOperation", "operator": "<", "rightExpression": { "argumentTypes": null, "id": 37, "name": "nevents", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 25, "src": "397:7:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "src": "393:11:0", "typeDescriptions": { "typeIdentifier": "t_bool", "typeString": "bool" } }, "id": 54, "initializationExpression": { "assignments": [ 33 ], "declarations": [ { "constant": false, "id": 33, "name": "k", "nodeType": "VariableDeclaration", "scope": 54, "src": "381:6:0", "stateVariable": false, "storageLocation": "default", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" }, "typeName": { "id": 32, "name": "uint", "nodeType": "ElementaryTypeName", "src": "381:4:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "value": null, "visibility": "internal" } ], "id": 35, "initialValue": { "argumentTypes": null, "hexValue": "30", "id": 34, "isConstant": false, "isLValue": false, "isPure": true, "kind": "number", "lValueRequested": false, "nodeType": "Literal", "src": "390:1:0", "subdenomination": null, "typeDescriptions": { "typeIdentifier": "t_rational_0_by_1", "typeString": "int_const 0" }, "value": "0" }, "nodeType": "VariableDeclarationStatement", "src": "381:10:0" }, "loopExpression": { "expression": { "argumentTypes": null, "id": 40, "isConstant": false, "isLValue": false, "isPure": false, "lValueRequested": false, "nodeType": "UnaryOperation", "operator": "++", "prefix": false, "src": "406:3:0", "subExpression": { "argumentTypes": null, "id": 39, "name": "k", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 33, "src": "406:1:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "id": 41, "nodeType": "ExpressionStatement", "src": "406:3:0" }, "nodeType": "ForStatement", "src": "376:98:0" }, { "eventCall": { "argumentTypes": null, "arguments": [], "expression": { "argumentTypes": [], "id": 55, "name": "EndEvents", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 12, "src": "504:9:0", "typeDescriptions": { "typeIdentifier": "t_function_event_nonpayable$__$returns$__$", "typeString": "function ()" } }, "id": 56, "isConstant": false, "isLValue": false, "isPure": false, "kind": "functionCall", "lValueRequested": false, "names": [], "nodeType": "FunctionCall", "src": "504:11:0", "typeDescriptions": { "typeIdentifier": "t_tuple$__$", "typeString": "tuple()" } }, "id": 57, "nodeType": "EmitStatement", "src": "499:16:0" } ] }, "documentation": null, "id": 59, "implemented": true, "kind": "function", "modifiers": [], "name": "emitEvents", "nodeType": "FunctionDefinition", "parameters": { "id": 22, "nodeType": "ParameterList", "parameters": [ { "constant": false, "id": 15, "name": "receivers", "nodeType": "VariableDeclaration", "scope": 59, "src": "188:26:0", "stateVariable": false, "storageLocation": "memory", "typeDescriptions": { "typeIdentifier": "t_array$_t_address_$dyn_memory_ptr", "typeString": "address[]" }, "typeName": { "baseType": { "id": 13, "name": "address", "nodeType": "ElementaryTypeName", "src": "188:7:0", "stateMutability": "nonpayable", "typeDescriptions": { "typeIdentifier": "t_address", "typeString": "address" } }, "id": 14, "length": null, "nodeType": "ArrayTypeName", "src": "188:9:0", "typeDescriptions": { "typeIdentifier": "t_array$_t_address_$dyn_storage_ptr", "typeString": "address[]" } }, "value": null, "visibility": "internal" }, { "constant": false, "id": 18, "name": "tokens", "nodeType": "VariableDeclaration", "scope": 59, "src": "216:23:0", "stateVariable": false, "storageLocation": "memory", "typeDescriptions": { "typeIdentifier": "t_array$_t_address_$dyn_memory_ptr", "typeString": "address[]" }, "typeName": { "baseType": { "id": 16, "name": "address", "nodeType": "ElementaryTypeName", "src": "216:7:0", "stateMutability": "nonpayable", "typeDescriptions": { "typeIdentifier": "t_address", "typeString": "address" } }, "id": 17, "length": null, "nodeType": "ArrayTypeName", "src": "216:9:0", "typeDescriptions": { "typeIdentifier": "t_array$_t_address_$dyn_storage_ptr", "typeString": "address[]" } }, "value": null, "visibility": "internal" }, { "constant": false, "id": 21, "name": "amounts", "nodeType": "VariableDeclaration", "scope": 59, "src": "241:24:0", "stateVariable": false, "storageLocation": "memory", "typeDescriptions": { "typeIdentifier": "t_array$_t_uint256_$dyn_memory_ptr", "typeString": "uint256[]" }, "typeName": { "baseType": { "id": 19, "name": "uint256", "nodeType": "ElementaryTypeName", "src": "241:7:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "id": 20, "length": null, "nodeType": "ArrayTypeName", "src": "241:9:0", "typeDescriptions": { "typeIdentifier": "t_array$_t_uint256_$dyn_storage_ptr", "typeString": "uint256[]" } }, "value": null, "visibility": "internal" } ], "src": "187:79:0" }, "returnParameters": { "id": 23, "nodeType": "ParameterList", "parameters": [], "src": "274:0:0" }, "scope": 60, "src": "168:355:0", "stateMutability": "nonpayable", "superFunction": null, "visibility": "public" } ], "scope": 61, "src": "2:524:0" } ], "src": "2:524:0" }, "legacyAST": { "absolutePath": "/C/git/SoliditySamples/exeth/events/contracts/Emitter.sol", "exportedSymbols": { "Emitter": [ 60 ] }, "id": 61, "nodeType": "SourceUnit", "nodes": [ { "baseContracts": [], "contractDependencies": [], "contractKind": "contract", "documentation": null, "fullyImplemented": true, "id": 60, "linearizedBaseContracts": [ 60 ], "name": "Emitter", "nodeType": "ContractDefinition", "nodes": [ { "anonymous": false, "documentation": null, "id": 2, "name": "BeginEvents", "nodeType": "EventDefinition", "parameters": { "id": 1, "nodeType": "ParameterList", "parameters": [], "src": "43:2:0" }, "src": "26:20:0" }, { "anonymous": false, "documentation": null, "id": 10, "name": "Transfer", "nodeType": "EventDefinition", "parameters": { "id": 9, "nodeType": "ParameterList", "parameters": [ { "constant": false, "id": 4, "indexed": true, "name": "receiver", "nodeType": "VariableDeclaration", "scope": 10, "src": "67:24:0", "stateVariable": false, "storageLocation": "default", "typeDescriptions": { "typeIdentifier": "t_address", "typeString": "address" }, "typeName": { "id": 3, "name": "address", "nodeType": "ElementaryTypeName", "src": "67:7:0", "stateMutability": "nonpayable", "typeDescriptions": { "typeIdentifier": "t_address", "typeString": "address" } }, "value": null, "visibility": "internal" }, { "constant": false, "id": 6, "indexed": true, "name": "token", "nodeType": "VariableDeclaration", "scope": 10, "src": "93:21:0", "stateVariable": false, "storageLocation": "default", "typeDescriptions": { "typeIdentifier": "t_address", "typeString": "address" }, "typeName": { "id": 5, "name": "address", "nodeType": "ElementaryTypeName", "src": "93:7:0", "stateMutability": "nonpayable", "typeDescriptions": { "typeIdentifier": "t_address", "typeString": "address" } }, "value": null, "visibility": "internal" }, { "constant": false, "id": 8, "indexed": false, "name": "amount", "nodeType": "VariableDeclaration", "scope": 10, "src": "116:14:0", "stateVariable": false, "storageLocation": "default", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" }, "typeName": { "id": 7, "name": "uint256", "nodeType": "ElementaryTypeName", "src": "116:7:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "value": null, "visibility": "internal" } ], "src": "66:65:0" }, "src": "52:80:0" }, { "anonymous": false, "documentation": null, "id": 12, "name": "EndEvents", "nodeType": "EventDefinition", "parameters": { "id": 11, "nodeType": "ParameterList", "parameters": [], "src": "153:2:0" }, "src": "138:18:0" }, { "body": { "id": 58, "nodeType": "Block", "src": "274:249:0", "statements": [ { "assignments": [ 25 ], "declarations": [ { "constant": false, "id": 25, "name": "nevents", "nodeType": "VariableDeclaration", "scope": 58, "src": "285:12:0", "stateVariable": false, "storageLocation": "default", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" }, "typeName": { "id": 24, "name": "uint", "nodeType": "ElementaryTypeName", "src": "285:4:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "value": null, "visibility": "internal" } ], "id": 28, "initialValue": { "argumentTypes": null, "expression": { "argumentTypes": null, "id": 26, "name": "receivers", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 15, "src": "300:9:0", "typeDescriptions": { "typeIdentifier": "t_array$_t_address_$dyn_memory_ptr", "typeString": "address[] memory" } }, "id": 27, "isConstant": false, "isLValue": false, "isPure": false, "lValueRequested": false, "memberName": "length", "nodeType": "MemberAccess", "referencedDeclaration": null, "src": "300:16:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "nodeType": "VariableDeclarationStatement", "src": "285:31:0" }, { "eventCall": { "argumentTypes": null, "arguments": [], "expression": { "argumentTypes": [], "id": 29, "name": "BeginEvents", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 2, "src": "342:11:0", "typeDescriptions": { "typeIdentifier": "t_function_event_nonpayable$__$returns$__$", "typeString": "function ()" } }, "id": 30, "isConstant": false, "isLValue": false, "isPure": false, "kind": "functionCall", "lValueRequested": false, "names": [], "nodeType": "FunctionCall", "src": "342:13:0", "typeDescriptions": { "typeIdentifier": "t_tuple$__$", "typeString": "tuple()" } }, "id": 31, "nodeType": "EmitStatement", "src": "337:18:0" }, { "body": { "eventCall": { "argumentTypes": null, "arguments": [ { "argumentTypes": null, "baseExpression": { "argumentTypes": null, "id": 43, "name": "receivers", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 15, "src": "438:9:0", "typeDescriptions": { "typeIdentifier": "t_array$_t_address_$dyn_memory_ptr", "typeString": "address[] memory" } }, "id": 45, "indexExpression": { "argumentTypes": null, "id": 44, "name": "k", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 33, "src": "448:1:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "isConstant": false, "isLValue": true, "isPure": false, "lValueRequested": false, "nodeType": "IndexAccess", "src": "438:12:0", "typeDescriptions": { "typeIdentifier": "t_address", "typeString": "address" } }, { "argumentTypes": null, "baseExpression": { "argumentTypes": null, "id": 46, "name": "tokens", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 18, "src": "452:6:0", "typeDescriptions": { "typeIdentifier": "t_array$_t_address_$dyn_memory_ptr", "typeString": "address[] memory" } }, "id": 48, "indexExpression": { "argumentTypes": null, "id": 47, "name": "k", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 33, "src": "459:1:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "isConstant": false, "isLValue": true, "isPure": false, "lValueRequested": false, "nodeType": "IndexAccess", "src": "452:9:0", "typeDescriptions": { "typeIdentifier": "t_address", "typeString": "address" } }, { "argumentTypes": null, "baseExpression": { "argumentTypes": null, "id": 49, "name": "amounts", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 21, "src": "463:7:0", "typeDescriptions": { "typeIdentifier": "t_array$_t_uint256_$dyn_memory_ptr", "typeString": "uint256[] memory" } }, "id": 51, "indexExpression": { "argumentTypes": null, "id": 50, "name": "k", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 33, "src": "471:1:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "isConstant": false, "isLValue": true, "isPure": false, "lValueRequested": false, "nodeType": "IndexAccess", "src": "463:10:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } } ], "expression": { "argumentTypes": [ { "typeIdentifier": "t_address", "typeString": "address" }, { "typeIdentifier": "t_address", "typeString": "address" }, { "typeIdentifier": "t_uint256", "typeString": "uint256" } ], "id": 42, "name": "Transfer", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 10, "src": "429:8:0", "typeDescriptions": { "typeIdentifier": "t_function_event_nonpayable$_t_address_$_t_address_$_t_uint256_$returns$__$", "typeString": "function (address,address,uint256)" } }, "id": 52, "isConstant": false, "isLValue": false, "isPure": false, "kind": "functionCall", "lValueRequested": false, "names": [], "nodeType": "FunctionCall", "src": "429:45:0", "typeDescriptions": { "typeIdentifier": "t_tuple$__$", "typeString": "tuple()" } }, "id": 53, "nodeType": "EmitStatement", "src": "424:50:0" }, "condition": { "argumentTypes": null, "commonType": { "typeIdentifier": "t_uint256", "typeString": "uint256" }, "id": 38, "isConstant": false, "isLValue": false, "isPure": false, "lValueRequested": false, "leftExpression": { "argumentTypes": null, "id": 36, "name": "k", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 33, "src": "393:1:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "nodeType": "BinaryOperation", "operator": "<", "rightExpression": { "argumentTypes": null, "id": 37, "name": "nevents", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 25, "src": "397:7:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "src": "393:11:0", "typeDescriptions": { "typeIdentifier": "t_bool", "typeString": "bool" } }, "id": 54, "initializationExpression": { "assignments": [ 33 ], "declarations": [ { "constant": false, "id": 33, "name": "k", "nodeType": "VariableDeclaration", "scope": 54, "src": "381:6:0", "stateVariable": false, "storageLocation": "default", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" }, "typeName": { "id": 32, "name": "uint", "nodeType": "ElementaryTypeName", "src": "381:4:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "value": null, "visibility": "internal" } ], "id": 35, "initialValue": { "argumentTypes": null, "hexValue": "30", "id": 34, "isConstant": false, "isLValue": false, "isPure": true, "kind": "number", "lValueRequested": false, "nodeType": "Literal", "src": "390:1:0", "subdenomination": null, "typeDescriptions": { "typeIdentifier": "t_rational_0_by_1", "typeString": "int_const 0" }, "value": "0" }, "nodeType": "VariableDeclarationStatement", "src": "381:10:0" }, "loopExpression": { "expression": { "argumentTypes": null, "id": 40, "isConstant": false, "isLValue": false, "isPure": false, "lValueRequested": false, "nodeType": "UnaryOperation", "operator": "++", "prefix": false, "src": "406:3:0", "subExpression": { "argumentTypes": null, "id": 39, "name": "k", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 33, "src": "406:1:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "id": 41, "nodeType": "ExpressionStatement", "src": "406:3:0" }, "nodeType": "ForStatement", "src": "376:98:0" }, { "eventCall": { "argumentTypes": null, "arguments": [], "expression": { "argumentTypes": [], "id": 55, "name": "EndEvents", "nodeType": "Identifier", "overloadedDeclarations": [], "referencedDeclaration": 12, "src": "504:9:0", "typeDescriptions": { "typeIdentifier": "t_function_event_nonpayable$__$returns$__$", "typeString": "function ()" } }, "id": 56, "isConstant": false, "isLValue": false, "isPure": false, "kind": "functionCall", "lValueRequested": false, "names": [], "nodeType": "FunctionCall", "src": "504:11:0", "typeDescriptions": { "typeIdentifier": "t_tuple$__$", "typeString": "tuple()" } }, "id": 57, "nodeType": "EmitStatement", "src": "499:16:0" } ] }, "documentation": null, "id": 59, "implemented": true, "kind": "function", "modifiers": [], "name": "emitEvents", "nodeType": "FunctionDefinition", "parameters": { "id": 22, "nodeType": "ParameterList", "parameters": [ { "constant": false, "id": 15, "name": "receivers", "nodeType": "VariableDeclaration", "scope": 59, "src": "188:26:0", "stateVariable": false, "storageLocation": "memory", "typeDescriptions": { "typeIdentifier": "t_array$_t_address_$dyn_memory_ptr", "typeString": "address[]" }, "typeName": { "baseType": { "id": 13, "name": "address", "nodeType": "ElementaryTypeName", "src": "188:7:0", "stateMutability": "nonpayable", "typeDescriptions": { "typeIdentifier": "t_address", "typeString": "address" } }, "id": 14, "length": null, "nodeType": "ArrayTypeName", "src": "188:9:0", "typeDescriptions": { "typeIdentifier": "t_array$_t_address_$dyn_storage_ptr", "typeString": "address[]" } }, "value": null, "visibility": "internal" }, { "constant": false, "id": 18, "name": "tokens", "nodeType": "VariableDeclaration", "scope": 59, "src": "216:23:0", "stateVariable": false, "storageLocation": "memory", "typeDescriptions": { "typeIdentifier": "t_array$_t_address_$dyn_memory_ptr", "typeString": "address[]" }, "typeName": { "baseType": { "id": 16, "name": "address", "nodeType": "ElementaryTypeName", "src": "216:7:0", "stateMutability": "nonpayable", "typeDescriptions": { "typeIdentifier": "t_address", "typeString": "address" } }, "id": 17, "length": null, "nodeType": "ArrayTypeName", "src": "216:9:0", "typeDescriptions": { "typeIdentifier": "t_array$_t_address_$dyn_storage_ptr", "typeString": "address[]" } }, "value": null, "visibility": "internal" }, { "constant": false, "id": 21, "name": "amounts", "nodeType": "VariableDeclaration", "scope": 59, "src": "241:24:0", "stateVariable": false, "storageLocation": "memory", "typeDescriptions": { "typeIdentifier": "t_array$_t_uint256_$dyn_memory_ptr", "typeString": "uint256[]" }, "typeName": { "baseType": { "id": 19, "name": "uint256", "nodeType": "ElementaryTypeName", "src": "241:7:0", "typeDescriptions": { "typeIdentifier": "t_uint256", "typeString": "uint256" } }, "id": 20, "length": null, "nodeType": "ArrayTypeName", "src": "241:9:0", "typeDescriptions": { "typeIdentifier": "t_array$_t_uint256_$dyn_storage_ptr", "typeString": "uint256[]" } }, "value": null, "visibility": "internal" } ], "src": "187:79:0" }, "returnParameters": { "id": 23, "nodeType": "ParameterList", "parameters": [], "src": "274:0:0" }, "scope": 60, "src": "168:355:0", "stateMutability": "nonpayable", "superFunction": null, "visibility": "public" } ], "scope": 61, "src": "2:524:0" } ], "src": "2:524:0" }, "compiler": { "name": "solc", "version": "0.5.0+commit.1d4f565a.Emscripten.clang" }, "networks": {}, "schemaVersion": "3.0.8", "updatedAt": "2019-08-29T15:25:05.458Z", "devdoc": { "methods": {} }, "userdoc": { "methods": {} } } ================================================ FILE: exeth/events/contracts/Emitter.sol ================================================ contract Emitter { event BeginEvents(); event Cross(address indexed token, address indexed receiver, uint256 amount); event EndEvents(); function emitEvents(address[] memory receivers, address[] memory tokens, uint256[] memory amounts) public { uint nevents = receivers.length; emit BeginEvents(); for (uint k = 0; k < nevents; k++) emit Transfer(receivers[k], tokens[k], amounts[k]); emit EndEvents(); } } ================================================ FILE: exeth/events/truffle-config.js ================================================ /* * NB: since truffle-hdwallet-provider 0.0.5 you must wrap HDWallet providers in a * function when declaring them. Failure to do so will cause commands to hang. ex: * ``` * mainnet: { * provider: function() { * return new HDWalletProvider(mnemonic, 'https://mainnet.infura.io/') * }, * network_id: '1', * gas: 4500000, * gasPrice: 10000000000, * }, */ module.exports = { // See // to customize your Truffle configuration! networks: { development: { host: "127.0.0.1", port: 8545, gasPrice: 0, gas: 50000000, network_id: "*" // Match any network id } } }; ================================================ FILE: exeth/federation/contracts/federation.sol ================================================ contract Federation { address[] federators; event NewFederator(address federator); constructor(address[] memory feds) public { federators = feds; } function federationSize() public view returns (uint) { return federators.length; } function isFederator(address addr) public view returns(bool) { for (uint16 k; k < federators.length; k++) if (addr == federators[k]) return true; return false; } function addFederator(address addr) public returns (bool) { if (isFederator(addr)) return false; federators.push(addr); emit NewFederator(addr); return true; } } ================================================ FILE: exeth/federation/federation.eth ================================================ # retrieve accounts message "retrieving accounts..." accounts # compile contract # (contracts variable has the compiled contract data) message "compiling contract..." compile "./contracts/federation.sol" message "contract function hashes" dump contracts.Federation.evm.methodIdentifiers # deploy contract with three accounts message "deploy contract with three federators" deploy Federation federation [accounts[0],accounts[1],accounts[2]] # federation size call federation federationSize() assert result == 3 message "federation size" result # check federators set n 0 while n < accounts.length call federation isFederator(address) accounts[n] assert result === (n < 3) set negation result == 0 ? " not " : " " message accounts[n] ("is" + negation + "a federator") set n n + 1 end # add an account that is a federator message "adding an existing federator" invoke federation addFederator(address) accounts[0] call federation federationSize() assert result == 3 # add a new federator message "adding a new federator" invoke federation addFederator(address) accounts[3] call federation federationSize() assert result == 4 message "done" ================================================ FILE: exeth/simple/.gitignore ================================================ ================================================ FILE: exeth/simple/accounts.eth ================================================ # retrieve accounts from default host (http://localhost:8545) accounts # dump the accounts addresses dump accounts assert accounts assert accounts.length ================================================ FILE: exeth/simple/balances.eth ================================================ # retrieve accounts from host accounts # retrieve balances set n 0 while n < accounts.length message "account" accounts[n] balance accounts[n] message "balance" parseInt(result) set n n + 1 end ================================================ FILE: exeth/simple/blocks.eth ================================================ # get the best block number blocknumber set bbnumber result message "best block number" bbnumber # retrieve genesis block block 0 dump result # retrieve best block block bbnumber dump result ================================================ FILE: exeth/simple/compile.eth ================================================ message "compiling counter.sol" compile "./contracts/counter.sol" message "counter.sol compiled" dump Object.keys(contracts.Counter) dump contracts.Counter.evm.assembly dump contracts.Counter.evm.methodIdentifiers ================================================ FILE: exeth/simple/contracts/Methods.sol ================================================ contract Methods { uint counter; function add(uint x) public { addToCounter(x); counter++; } function addToCounter(uint x) private { x++; counter += x; } } ================================================ FILE: exeth/simple/contracts/counter.asm ================================================ ======= counter.sol:Counter ======= EVM assembly: /* "counter.sol":63:399 contract Counter { ... */ mstore(0x40, 0x60) /* "counter.sol":109:165 function Counter() public { ... */ jumpi(tag_1, iszero(callvalue)) 0x0 dup1 revert tag_1: tag_2: /* "counter.sol":156:157 1 */ 0x1 /* "counter.sol":146:153 counter */ 0x0 /* "counter.sol":146:157 counter = 1 */ dup2 swap1 sstore pop /* "counter.sol":109:165 function Counter() public { ... */ tag_3: /* "counter.sol":63:399 contract Counter { ... */ tag_4: dataSize(sub_0) dup1 dataOffset(sub_0) 0x0 codecopy 0x0 return stop sub_0: assembly { /* "counter.sol":63:399 contract Counter { ... */ mstore(0x40, 0x60) calldataload(0x0) 0x100000000000000000000000000000000000000000000000000000000 swap1 div 0xffffffff and dup1 0x1003e2d2 eq tag_2 jumpi dup1 0x8ada066e eq tag_3 jumpi dup1 0xd09de08a eq tag_4 jumpi tag_1: 0x0 dup1 revert /* "counter.sol":242:301 function add(uint v) public { ... */ tag_2: jumpi(tag_5, iszero(callvalue)) 0x0 dup1 revert tag_5: tag_6 0x4 dup1 dup1 calldataload swap1 0x20 add swap1 swap2 swap1 pop pop jump(tag_7) tag_6: stop /* "counter.sol":310:396 function getCounter() public constant returns (uint) { ... */ tag_3: jumpi(tag_8, iszero(callvalue)) 0x0 dup1 revert tag_8: tag_9 jump(tag_10) tag_9: mload(0x40) dup1 dup3 dup2 mstore 0x20 add swap2 pop pop mload(0x40) dup1 swap2 sub swap1 return /* "counter.sol":177:233 function increment() public { ... */ tag_4: jumpi(tag_11, iszero(callvalue)) 0x0 dup1 revert tag_11: tag_12 jump(tag_13) tag_12: stop /* "counter.sol":242:301 function add(uint v) public { ... */ tag_7: /* "counter.sol":292:293 v */ dup1 /* "counter.sol":281:288 counter */ 0x0 dup1 /* "counter.sol":281:293 counter += v */ dup3 dup3 sload add swap3 pop pop dup2 swap1 sstore pop /* "counter.sol":242:301 function add(uint v) public { ... */ tag_14: pop jump // out /* "counter.sol":310:396 function getCounter() public constant returns (uint) { ... */ tag_10: /* "counter.sol":357:361 uint */ 0x0 /* "counter.sol":381:388 counter */ dup1 sload /* "counter.sol":374:388 return counter */ swap1 pop /* "counter.sol":310:396 function getCounter() public constant returns (uint) { ... */ tag_15: swap1 jump // out /* "counter.sol":177:233 function increment() public { ... */ tag_13: /* "counter.sol":216:223 counter */ 0x0 dup1 /* "counter.sol":216:225 counter++ */ dup2 sload dup1 swap3 swap2 swap1 0x1 add swap2 swap1 pop sstore pop /* "counter.sol":177:233 function increment() public { ... */ tag_16: jump // out auxdata: 0xa165627a7a723058209c14b0491dc15ac395ea1519522f3b1b4162ad8e2a8a0f4e9b43e8b2963c528e0029 } ================================================ FILE: exeth/simple/contracts/counter.sol ================================================ pragma solidity >=0.4.21 <0.6.0; // Simple counter contract contract Counter { uint counter; // function Counter() public { constructor() public { counter = 1; } function increment() public { counter++; } function add(uint v) public { counter += v; } function getCounter() public view returns (uint) { return counter; } } ================================================ FILE: exeth/simple/contracts/creator.sol ================================================ contract Counter { uint x; event Incremented(bool indexed odd, uint x); event Created(uint x); event Valued(uint x); constructor() public { x = 70; emit Created(x); } function increment() public { ++x; emit Incremented(x % 2 == 1, x); } function getValue() public view returns (uint) { // emit Valued(x); return x; } } contract Creator { Counter public counter; event CounterCreated(uint); constructor() public { counter = new Counter(); emit CounterCreated(counter.getValue()); } } ================================================ FILE: exeth/simple/contracts/empty.asm ================================================ ======= empty.sol:Empty ======= EVM assembly: /* "empty.sol":59:78 contract Empty { ... */ mstore(0x40, 0x60) jumpi(tag_1, iszero(callvalue)) 0x0 dup1 revert tag_1: tag_2: dataSize(sub_0) dup1 dataOffset(sub_0) 0x0 codecopy 0x0 return stop sub_0: assembly { /* "empty.sol":59:78 contract Empty { ... */ mstore(0x40, 0x60) tag_1: 0x0 dup1 revert auxdata: 0xa165627a7a7230582046b5464930e5eb5db6027b5aaae7f9140430cdd322d5eb42de2e546521573bd90029 } ================================================ FILE: exeth/simple/contracts/empty.sol ================================================ // pragma solidity ^0.4.18; // Simple empty contract contract Empty { } ================================================ FILE: exeth/simple/contracts/foobar.sol ================================================ // Simple inheritance contract Foo { } contract Bar is Foo { } ================================================ FILE: exeth/simple/contracts/greeter.sol ================================================ contract Greeter { string public message; constructor() public { message = "Hello, Contract"; } function setMessage(string memory msg) public { message = msg; } } ================================================ FILE: exeth/simple/contracts/message.sol ================================================ contract Message { string public message; constructor(string memory _message) public { message = _message; } function setMessage(string memory _message) public { message = _message; } } ================================================ FILE: exeth/simple/contracts/selector.sol ================================================ contract Selector { function f() returns (bytes4) { return this.f.selector; } } ================================================ FILE: exeth/simple/contracts/throw.sol ================================================ contract Throw { modifier sentValue() { require(msg.value > 0); _; } constructor() public payable sentValue { // require(msg.value > 0); //if (msg.value == 0) // throw; } function otherFunction() public payable sentValue { // require(msg.value > 0); } } ================================================ FILE: exeth/simple/contracts/token.asm ================================================ ======= token.sol:Token ======= EVM assembly: /* "token.sol":31:697 contract Token { ... */ mstore(0x40, 0x60) /* "token.sol":262:333 function Token() public { ... */ jumpi(tag_1, iszero(callvalue)) 0x0 dup1 revert tag_1: tag_2: /* "token.sol":320:325 10000 */ 0x2710 /* "token.sol":297:305 balances */ 0x0 /* "token.sol":297:317 balances[msg.sender] */ dup1 /* "token.sol":306:316 msg.sender */ caller /* "token.sol":297:317 balances[msg.sender] */ 0xffffffffffffffffffffffffffffffffffffffff and 0xffffffffffffffffffffffffffffffffffffffff and dup2 mstore 0x20 add swap1 dup2 mstore 0x20 add 0x0 keccak256 /* "token.sol":297:325 balances[msg.sender] = 10000 */ dup2 swap1 sstore pop /* "token.sol":262:333 function Token() public { ... */ tag_3: /* "token.sol":31:697 contract Token { ... */ tag_4: dataSize(sub_0) dup1 dataOffset(sub_0) 0x0 codecopy 0x0 return stop sub_0: assembly { /* "token.sol":31:697 contract Token { ... */ mstore(0x40, 0x60) calldataload(0x0) 0x100000000000000000000000000000000000000000000000000000000 swap1 div 0xffffffff and dup1 0x27e235e3 eq tag_2 jumpi dup1 0xa9059cbb eq tag_3 jumpi tag_1: 0x0 dup1 revert /* "token.sol":54:95 mapping (address => uint) public balances */ tag_2: jumpi(tag_4, iszero(callvalue)) 0x0 dup1 revert tag_4: tag_5 0x4 dup1 dup1 calldataload 0xffffffffffffffffffffffffffffffffffffffff and swap1 0x20 add swap1 swap2 swap1 pop pop jump(tag_6) tag_5: mload(0x40) dup1 dup3 dup2 mstore 0x20 add swap2 pop pop mload(0x40) dup1 swap2 sub swap1 return /* "token.sol":379:694 function transfer(address receiver, uint amount) public returns(bool sufficient) { ... */ tag_3: jumpi(tag_7, iszero(callvalue)) 0x0 dup1 revert tag_7: tag_8 0x4 dup1 dup1 calldataload 0xffffffffffffffffffffffffffffffffffffffff and swap1 0x20 add swap1 swap2 swap1 dup1 calldataload swap1 0x20 add swap1 swap2 swap1 pop pop jump(tag_9) tag_8: mload(0x40) dup1 dup3 iszero iszero iszero iszero dup2 mstore 0x20 add swap2 pop pop mload(0x40) dup1 swap2 sub swap1 return /* "token.sol":54:95 mapping (address => uint) public balances */ tag_6: mstore(0x20, 0x0) dup1 0x0 mstore keccak256(0x0, 0x40) 0x0 swap2 pop swap1 pop sload dup2 jump // out /* "token.sol":379:694 function transfer(address receiver, uint amount) public returns(bool sufficient) { ... */ tag_9: /* "token.sol":443:458 bool sufficient */ 0x0 /* "token.sol":498:504 amount */ dup2 /* "token.sol":475:483 balances */ 0x0 /* "token.sol":475:495 balances[msg.sender] */ dup1 /* "token.sol":484:494 msg.sender */ caller /* "token.sol":475:495 balances[msg.sender] */ 0xffffffffffffffffffffffffffffffffffffffff and 0xffffffffffffffffffffffffffffffffffffffff and dup2 mstore 0x20 add swap1 dup2 mstore 0x20 add 0x0 keccak256 sload /* "token.sol":475:504 balances[msg.sender] < amount */ lt /* "token.sol":471:523 if (balances[msg.sender] < amount) ... */ iszero tag_11 jumpi /* "token.sol":518:523 false */ 0x0 /* "token.sol":511:523 return false */ swap1 pop jump(tag_10) /* "token.sol":471:523 if (balances[msg.sender] < amount) ... */ tag_11: /* "token.sol":562:568 amount */ dup2 /* "token.sol":538:546 balances */ 0x0 /* "token.sol":538:558 balances[msg.sender] */ dup1 /* "token.sol":547:557 msg.sender */ caller /* "token.sol":538:558 balances[msg.sender] */ 0xffffffffffffffffffffffffffffffffffffffff and 0xffffffffffffffffffffffffffffffffffffffff and dup2 mstore 0x20 add swap1 dup2 mstore 0x20 add 0x0 keccak256 0x0 /* "token.sol":538:568 balances[msg.sender] -= amount */ dup3 dup3 sload sub swap3 pop pop dup2 swap1 sstore pop /* "token.sol":601:607 amount */ dup2 /* "token.sol":579:587 balances */ 0x0 /* "token.sol":579:597 balances[receiver] */ dup1 /* "token.sol":588:596 receiver */ dup6 /* "token.sol":579:597 balances[receiver] */ 0xffffffffffffffffffffffffffffffffffffffff and 0xffffffffffffffffffffffffffffffffffffffff and dup2 mstore 0x20 add swap1 dup2 mstore 0x20 add 0x0 keccak256 0x0 /* "token.sol":579:607 balances[receiver] += amount */ dup3 dup3 sload add swap3 pop pop dup2 swap1 sstore pop /* "token.sol":622:660 Transfer(msg.sender, receiver, amount) */ 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef /* "token.sol":631:641 msg.sender */ caller /* "token.sol":643:651 receiver */ dup5 /* "token.sol":653:659 amount */ dup5 /* "token.sol":622:660 Transfer(msg.sender, receiver, amount) */ mload(0x40) dup1 dup5 0xffffffffffffffffffffffffffffffffffffffff and 0xffffffffffffffffffffffffffffffffffffffff and dup2 mstore 0x20 add dup4 0xffffffffffffffffffffffffffffffffffffffff and 0xffffffffffffffffffffffffffffffffffffffff and dup2 mstore 0x20 add dup3 dup2 mstore 0x20 add swap4 pop pop pop pop mload(0x40) dup1 swap2 sub swap1 log1 /* "token.sol":682:686 true */ 0x1 /* "token.sol":675:686 return true */ swap1 pop /* "token.sol":379:694 function transfer(address receiver, uint amount) public returns(bool sufficient) { ... */ tag_10: swap3 swap2 pop pop jump // out auxdata: 0xa165627a7a723058206eeb5ce99ecaedf1e1d69e2be9f2b6aff6498dc1892a8884a484b4dff65ce9730029 } ================================================ FILE: exeth/simple/contracts/token.sol ================================================ // pragma solidity ^0.4.18; contract Token { mapping (address => uint) public balances; event Transfer(address sender, address receiver, uint amount); /* Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { balances[msg.sender] = 10000; } /* Very simple transfer function */ function transfer(address receiver, uint amount) public returns(bool sufficient) { // require(balances[msg.sender] >= amount); if (balances[msg.sender] <= amount) return false; balances[msg.sender] -= amount; balances[receiver] += amount; emit Transfer(msg.sender, receiver, amount); return true; } } ================================================ FILE: exeth/simple/contracts/types.sol ================================================ contract Types { // signed integer (32 bytes) int signed; // unsigned integer (32 bytes) uint unsigned; // integer with bit size uint16 short; // boolean bool flag; // string string name; // address address wallet; // members: wallet.balance, // wallet.transfer(uint256) throws on failure // wallet.send(uint256) returns(bool) // returns false on failure // visible state variable int public visible; // fixed size byte arrays bytes1 onebyte; bytes20 twentybytes; bytes32 thirtytwobytes; int[10] tenintegers; string[5] fivemessages; // dynamically-sized arrays bytes data; string message; // enums enum Actions { GoLeft, GoRight, GoStraight, SitStill } // dynamic array initialization function f(uint len) { uint[] memory a = new uint[](7); bytes memory b = new bytes(len); // Here we have a.length == 7 and b.length == len a[6] = 8; } struct Voter { address delegate; bool voted; } struct Proposal { bytes32 name; uint voteCount; } } ================================================ FILE: exeth/simple/counter.eth ================================================ # retrieve accounts message "retrieving accounts..." accounts # compile contract # (contracts variable has the compiled contract data) message "compiling contract..." compile "./contracts/counter.sol" message "counter.sol compiled" message "functions" dump contracts.Counter.evm.methodIdentifiers # deploy instances, using default sender: accounts[0], message default result: 0 # first argument: contract name # second argument: new instance name message "deploy instance..." deploy Counter counter # show instance address # (instances variable has the instances data) message "new instance" instances.counter.address # get counter call counter getCounter() set counter result message "counter" counter assert counter == 1 # invoke increment (default sender: accounts[0]) message "increment..." invoke counter increment() # get counter call counter getCounter() set counter result message "counter" counter assert counter == 2 # invoke add (default sender: accounts[0]) message "add 40..." invoke counter add(uint256) 40 # get counter call counter getCounter() set counter result message "counter" counter assert counter == 42 message "done" ================================================ FILE: exeth/simple/creator.eth ================================================ accounts message "compiling creator.sol" compile "./contracts/creator.sol" message "creator.sol compiled" deploy Creator creator1 message "contract deployed to address" result call creator1 counter() set counteraddr result message "counter contract" counteraddr ================================================ FILE: exeth/simple/deploy.eth ================================================ # uncomment to enable logging # logging true # retrieve accounts to use accounts[0] as default sender accounts message "compiling counter.sol" compile "./contracts/counter.sol" message "counter.sol compiled" deploy Counter counter1 message "contract deployed to address" value message "instance counter1 data" dump instances.counter1 ================================================ FILE: exeth/simple/dump.eth ================================================ message "compiling empty.sol" compile "./contracts/empty.sol" message "empty.sol compiled" message "Empty functions" dump contracts.Empty.evm.methodIdentifiers message message "compiling counter.sol" compile "./contracts/counter.sol" message "counter.sol compiled" # assertions assert contracts.Counter assert contracts.Counter.abi assert contracts.Counter.evm.bytecode assert contracts.Counter.evm.deployedBytecode message "Counter functions" dump contracts.Counter.evm.methodIdentifiers message "Counter interface" dump contracts.Counter.abi message "Counter bytecodes" dump contracts.Counter.evm.bytecode.object ================================================ FILE: exeth/simple/empty.eth ================================================ # uncomment to enable logging # logging true # retrieve accounts to use accounts[0] as default sender accounts message "compiling empty.sol" compile "./contracts/empty.sol" message "empty.sol compiled" deploy Empty empty1 message "contract deployed to address" result message "instance empty1 data" dump instances.empty1 ================================================ FILE: exeth/simple/greeter.eth ================================================ # uncomment to enable logging # logging true # retrieve accounts to use accounts[0] as default sender accounts message "compiling greeter.sol" compile "./contracts/greeter.sol" message "greeter.sol compiled" dump contracts.Greeter.evm.methodIdentifiers dump contracts.Greeter.abi deploy Greeter greeter1 message "contract deployed to address" result message "retrieving message" call greeter1 message() message "message" result assert result === "Hello, Contract" message "changing message" invoke greeter1 setMessage(string) "Hello, World" message "retrieving message" call greeter1 message() message "message" result assert result === "Hello, World" ================================================ FILE: exeth/simple/hello.eth ================================================ # a message message "hello world" ================================================ FILE: exeth/simple/message.eth ================================================ # retrieve accounts to use accounts[0] as default sender accounts message "compiling message.sol" compile "./contracts/message.sol" message "message.sol compiled" dump Object.keys(contracts); #dump contracts.Message.evm.methodInterfaces #dump contracts.Message.abi deploy Message message1 "hello" message "contract deployed to address" result message "retrieving message" call message1 message() message "message" result assert result === "hello" message "changing message" invoke message1 setMessage(string) "Hello, World" message "retrieving message" call message1 message() message "message" result assert result === "Hello, World" ================================================ FILE: exeth/simple/rsksend.eth ================================================ # uncomment to enable logging # logging true # set RSK host host "http://localhost:4444" # retrieve accounts from host accounts assert accounts assert accounts.length message "Second account is" accounts[1] balance accounts[1] message "Its balance is" parseInt(value) message "Sending transaction..." send accounts[1] accounts[3] 1000000 message "Third account is" accounts[2] balance accounts[2] message "Its balance is" parseInt(value) message "Sending transaction..." send accounts[2] accounts[0] 1000000 ================================================ FILE: exeth/simple/rsktransfer.eth ================================================ # uncomment to enable logging # logging true # set RSK host host "http://localhost:4444" # retrieve accounts from host accounts assert accounts assert accounts.length message "Fourth account is" accounts[3] balance accounts[4] message "Its balance is" parseInt(value) message "First account is" accounts[1] balance accounts[0] message "Its balance is" parseInt(value) message "Transfering..." transfer accounts[4] accounts[0] 10000000000000 message "Second account is" accounts[1] balance accounts[1] message "Its balance is" parseInt(value) message "Transfering..." transfer accounts[4] accounts[1] 10000000000000 message "Third account is" accounts[2] balance accounts[2] message "Its balance is" parseInt(value) message "Transfering..." transfer accounts[4] accounts[2] 10000000000000 message "Fourth account is" accounts[3] balance accounts[3] message "Its balance is" parseInt(value) message "Transfering..." transfer accounts[4] accounts[3] 10000000000000 ================================================ FILE: exeth/simple/throw.eth ================================================ # retrieve accounts to use accounts[0] as default sender accounts message "compiling throw.sol" compile "./contracts/throw.sol" message "throw.sol compiled" deploy Throw throw1 message "contract deployed to address" value message "instance throw1 data" dump instances.throw1 ================================================ FILE: exeth/simple/token.eth ================================================ # uncomment to enable logging # logging true # retrieve accounts to use accounts[0] as default sender accounts message "compiling token.sol" compile "./contracts/token.sol" message "token.sol compiled" dump contracts.Token.evm.methodIdentifiers deploy Token token1 message "contract deployed to address" result call token1 balances(address) accounts[0] message "owner balance" result assert result == 10000 invoke token1 transfer(address,uint256) accounts[1] 100 call token1 balances(address) accounts[0] message "owner balance" result assert result == 10000 - 100 call token1 balances(address) accounts[1] message "receiver balance" result assert result == 100 message "done" ================================================ FILE: exeth/simple/transfer.eth ================================================ # uncomment to enable logging # logging true # retrieve accounts from default host (http://localhost:8545) accounts assert accounts assert accounts.length message "First account is" accounts[0] balance accounts[0] message "Its balance is" parseInt(result) message "Second account is" accounts[1] balance accounts[1] message "Its balance is" parseInt(result) message "Transfering..." transfer accounts[0] accounts[1] 1000000 message "First account is" accounts[0] balance accounts[0] message "Its balance is" parseInt(result) message "Second account is" accounts[1] balance accounts[1] message "Its balance is" parseInt(result) ================================================ FILE: old/simple/.gitignore ================================================ context.json ================================================ FILE: old/simple/README.md ================================================ # Simple Contract Samples ## Install Install (NodeJS)[https://nodejs.org/en/] Run ``` npm install ``` ## Running a DSL file There is a defined DSL (Domain Specific Language) to compile contracts and to send Ethereum commands to a node. Example, to show accounts the `accounts.eth` text file contains: ``` # retrieve accounts from default host (http://localhost:8545) accounts # dump the accounts addresses dump accounts ``` To execute the DSL file, run: ``` node run accounts ``` ================================================ FILE: old/simple/accounts.eth ================================================ # retrieve accounts from default host (http://localhost:8545) accounts # dump the accounts addresses dump accounts assert accounts assert accounts.length ================================================ FILE: old/simple/balance.eth ================================================ # retrieve accounts from default host (http://localhost:8545) accounts assert accounts assert accounts.length message "First account is" accounts[0] balance accounts[0] message "Its balance is" value ================================================ FILE: old/simple/balances10.eth ================================================ accounts balance accounts[0] message "account" accounts[0] "balance is" value balance accounts[1] message "account" accounts[1] "balance is" value balance accounts[2] message "account" accounts[2] "balance is" value balance accounts[3] message "account" accounts[3] "balance is" value balance accounts[4] message "account" accounts[4] "balance is" value balance accounts[5] message "account" accounts[5] "balance is" value balance accounts[6] message "account" accounts[6] "balance is" value balance accounts[7] message "account" accounts[7] "balance is" value balance accounts[8] message "account" accounts[8] "balance is" value balance accounts[9] message "account" accounts[9] "balance is" value ================================================ FILE: old/simple/balances20.eth ================================================ accounts balance accounts[0] message "account" accounts[0] "balance is" value balance accounts[1] message "account" accounts[1] "balance is" value balance accounts[2] message "account" accounts[2] "balance is" value balance accounts[3] message "account" accounts[3] "balance is" value balance accounts[4] message "account" accounts[4] "balance is" value balance accounts[5] message "account" accounts[5] "balance is" value balance accounts[6] message "account" accounts[6] "balance is" value balance accounts[7] message "account" accounts[7] "balance is" value balance accounts[8] message "account" accounts[8] "balance is" value balance accounts[9] message "account" accounts[9] "balance is" value balance accounts[10] message "account" accounts[10] "balance is" value balance accounts[11] message "account" accounts[11] "balance is" value balance accounts[12] message "account" accounts[12] "balance is" value balance accounts[13] message "account" accounts[13] "balance is" value balance accounts[14] message "account" accounts[14] "balance is" value balance accounts[15] message "account" accounts[15] "balance is" value balance accounts[16] message "account" accounts[16] "balance is" value balance accounts[17] message "account" accounts[17] "balance is" value balance accounts[18] message "account" accounts[18] "balance is" value balance accounts[19] message "account" accounts[19] "balance is" value ================================================ FILE: old/simple/balances30.eth ================================================ accounts balance accounts[0] message "account" accounts[0] "balance is" value balance accounts[1] message "account" accounts[1] "balance is" value balance accounts[2] message "account" accounts[2] "balance is" value balance accounts[3] message "account" accounts[3] "balance is" value balance accounts[4] message "account" accounts[4] "balance is" value balance accounts[5] message "account" accounts[5] "balance is" value balance accounts[6] message "account" accounts[6] "balance is" value balance accounts[7] message "account" accounts[7] "balance is" value balance accounts[8] message "account" accounts[8] "balance is" value balance accounts[9] message "account" accounts[9] "balance is" value balance accounts[10] message "account" accounts[10] "balance is" value balance accounts[11] message "account" accounts[11] "balance is" value balance accounts[12] message "account" accounts[12] "balance is" value balance accounts[13] message "account" accounts[13] "balance is" value balance accounts[14] message "account" accounts[14] "balance is" value balance accounts[15] message "account" accounts[15] "balance is" value balance accounts[16] message "account" accounts[16] "balance is" value balance accounts[17] message "account" accounts[17] "balance is" value balance accounts[18] message "account" accounts[18] "balance is" value balance accounts[19] message "account" accounts[19] "balance is" value balance accounts[20] message "account" accounts[20] "balance is" value balance accounts[21] message "account" accounts[21] "balance is" value balance accounts[22] message "account" accounts[22] "balance is" value balance accounts[23] message "account" accounts[23] "balance is" value balance accounts[24] message "account" accounts[24] "balance is" value balance accounts[25] message "account" accounts[25] "balance is" value balance accounts[26] message "account" accounts[26] "balance is" value balance accounts[27] message "account" accounts[27] "balance is" value balance accounts[28] message "account" accounts[28] "balance is" value balance accounts[29] message "account" accounts[29] "balance is" value ================================================ FILE: old/simple/balances4.eth ================================================ accounts balance accounts[0] message "account" accounts[0] "balance is" value balance accounts[1] message "account" accounts[1] "balance is" value balance accounts[2] message "account" accounts[2] "balance is" value balance accounts[3] message "account" accounts[3] "balance is" value ================================================ FILE: old/simple/compile.eth ================================================ message "compiling counter.sol" compile "./contracts/counter.sol" message "counter.sol compiled" # dump contracts.Counter.interface # dump contracts.Counter.opcodes dump Object.keys(contracts.Counter) dump contracts.Counter.assembly dump contracts.Counter.functionHashes ================================================ FILE: old/simple/config.json ================================================ { "host": "http://localhost:8545" } ================================================ FILE: old/simple/contracts/counter.sol ================================================ // pragma solidity ^0.4.18; // Simple counter contract contract Counter { uint counter; function Counter() public { counter = 1; } function increment() public { counter++; } function add(uint v) public { counter += v; } function getCounter() public constant returns (uint) { return counter; } } ================================================ FILE: old/simple/contracts/creator.sol ================================================ contract Counter { event Incremented(bool indexed odd, uint x); event Created(uint x); event Valued(uint x); function Counter() { x = 70; Created(x); } function increment() { ++x; Incremented(x % 2 == 1, x); } function getValue() constant returns (uint) { Valued(x); return x; } uint x; } contract Creator { Counter counter; event CounterCreated(uint); function Creator() { counter = new Counter(); CounterCreated(counter.getValue()); } } ================================================ FILE: old/simple/contracts/empty.sol ================================================ // pragma solidity ^0.4.18; // Simple empty contract contract Empty { } ================================================ FILE: old/simple/contracts/foobar.sol ================================================ // Simple inheritance contract Foo { } contract Bar is Foo { } ================================================ FILE: old/simple/contracts/greeter.sol ================================================ contract Greeter { string public message; function Greeter() { message = "Hello, Contract"; } function setMessage(string msg) { message = msg; } } ================================================ FILE: old/simple/contracts/message.sol ================================================ contract Message { string public message; function Message(string msg) { message = msg; } function setMessage(string msg) { message = msg; } } ================================================ FILE: old/simple/contracts/selector.sol ================================================ contract Selector { function f() returns (bytes4) { return this.f.selector; } } ================================================ FILE: old/simple/contracts/throw.sol ================================================ contract Throw { function Throw() { require(msg.value > 0); } } ================================================ FILE: old/simple/contracts/token.asm ================================================ ======= token.sol:Token ======= EVM assembly: /* "token.sol":31:697 contract Token { ... */ mstore(0x40, 0x60) /* "token.sol":262:333 function Token() public { ... */ jumpi(tag_1, iszero(callvalue)) 0x0 dup1 revert tag_1: tag_2: /* "token.sol":320:325 10000 */ 0x2710 /* "token.sol":297:305 balances */ 0x0 /* "token.sol":297:317 balances[msg.sender] */ dup1 /* "token.sol":306:316 msg.sender */ caller /* "token.sol":297:317 balances[msg.sender] */ 0xffffffffffffffffffffffffffffffffffffffff and 0xffffffffffffffffffffffffffffffffffffffff and dup2 mstore 0x20 add swap1 dup2 mstore 0x20 add 0x0 keccak256 /* "token.sol":297:325 balances[msg.sender] = 10000 */ dup2 swap1 sstore pop /* "token.sol":262:333 function Token() public { ... */ tag_3: /* "token.sol":31:697 contract Token { ... */ tag_4: dataSize(sub_0) dup1 dataOffset(sub_0) 0x0 codecopy 0x0 return stop sub_0: assembly { /* "token.sol":31:697 contract Token { ... */ mstore(0x40, 0x60) calldataload(0x0) 0x100000000000000000000000000000000000000000000000000000000 swap1 div 0xffffffff and dup1 0x27e235e3 eq tag_2 jumpi dup1 0xa9059cbb eq tag_3 jumpi tag_1: 0x0 dup1 revert /* "token.sol":54:95 mapping (address => uint) public balances */ tag_2: jumpi(tag_4, iszero(callvalue)) 0x0 dup1 revert tag_4: tag_5 0x4 dup1 dup1 calldataload 0xffffffffffffffffffffffffffffffffffffffff and swap1 0x20 add swap1 swap2 swap1 pop pop jump(tag_6) tag_5: mload(0x40) dup1 dup3 dup2 mstore 0x20 add swap2 pop pop mload(0x40) dup1 swap2 sub swap1 return /* "token.sol":379:694 function transfer(address receiver, uint amount) public returns(bool sufficient) { ... */ tag_3: jumpi(tag_7, iszero(callvalue)) 0x0 dup1 revert tag_7: tag_8 0x4 dup1 dup1 calldataload 0xffffffffffffffffffffffffffffffffffffffff and swap1 0x20 add swap1 swap2 swap1 dup1 calldataload swap1 0x20 add swap1 swap2 swap1 pop pop jump(tag_9) tag_8: mload(0x40) dup1 dup3 iszero iszero iszero iszero dup2 mstore 0x20 add swap2 pop pop mload(0x40) dup1 swap2 sub swap1 return /* "token.sol":54:95 mapping (address => uint) public balances */ tag_6: mstore(0x20, 0x0) dup1 0x0 mstore keccak256(0x0, 0x40) 0x0 swap2 pop swap1 pop sload dup2 jump // out /* "token.sol":379:694 function transfer(address receiver, uint amount) public returns(bool sufficient) { ... */ tag_9: /* "token.sol":443:458 bool sufficient */ 0x0 /* "token.sol":498:504 amount */ dup2 /* "token.sol":475:483 balances */ 0x0 /* "token.sol":475:495 balances[msg.sender] */ dup1 /* "token.sol":484:494 msg.sender */ caller /* "token.sol":475:495 balances[msg.sender] */ 0xffffffffffffffffffffffffffffffffffffffff and 0xffffffffffffffffffffffffffffffffffffffff and dup2 mstore 0x20 add swap1 dup2 mstore 0x20 add 0x0 keccak256 sload /* "token.sol":475:504 balances[msg.sender] < amount */ lt /* "token.sol":471:523 if (balances[msg.sender] < amount) ... */ iszero tag_11 jumpi /* "token.sol":518:523 false */ 0x0 /* "token.sol":511:523 return false */ swap1 pop jump(tag_10) /* "token.sol":471:523 if (balances[msg.sender] < amount) ... */ tag_11: /* "token.sol":562:568 amount */ dup2 /* "token.sol":538:546 balances */ 0x0 /* "token.sol":538:558 balances[msg.sender] */ dup1 /* "token.sol":547:557 msg.sender */ caller /* "token.sol":538:558 balances[msg.sender] */ 0xffffffffffffffffffffffffffffffffffffffff and 0xffffffffffffffffffffffffffffffffffffffff and dup2 mstore 0x20 add swap1 dup2 mstore 0x20 add 0x0 keccak256 0x0 /* "token.sol":538:568 balances[msg.sender] -= amount */ dup3 dup3 sload sub swap3 pop pop dup2 swap1 sstore pop /* "token.sol":601:607 amount */ dup2 /* "token.sol":579:587 balances */ 0x0 /* "token.sol":579:597 balances[receiver] */ dup1 /* "token.sol":588:596 receiver */ dup6 /* "token.sol":579:597 balances[receiver] */ 0xffffffffffffffffffffffffffffffffffffffff and 0xffffffffffffffffffffffffffffffffffffffff and dup2 mstore 0x20 add swap1 dup2 mstore 0x20 add 0x0 keccak256 0x0 /* "token.sol":579:607 balances[receiver] += amount */ dup3 dup3 sload add swap3 pop pop dup2 swap1 sstore pop /* "token.sol":622:660 Transfer(msg.sender, receiver, amount) */ 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef /* "token.sol":631:641 msg.sender */ caller /* "token.sol":643:651 receiver */ dup5 /* "token.sol":653:659 amount */ dup5 /* "token.sol":622:660 Transfer(msg.sender, receiver, amount) */ mload(0x40) dup1 dup5 0xffffffffffffffffffffffffffffffffffffffff and 0xffffffffffffffffffffffffffffffffffffffff and dup2 mstore 0x20 add dup4 0xffffffffffffffffffffffffffffffffffffffff and 0xffffffffffffffffffffffffffffffffffffffff and dup2 mstore 0x20 add dup3 dup2 mstore 0x20 add swap4 pop pop pop pop mload(0x40) dup1 swap2 sub swap1 log1 /* "token.sol":682:686 true */ 0x1 /* "token.sol":675:686 return true */ swap1 pop /* "token.sol":379:694 function transfer(address receiver, uint amount) public returns(bool sufficient) { ... */ tag_10: swap3 swap2 pop pop jump // out auxdata: 0xa165627a7a723058206eeb5ce99ecaedf1e1d69e2be9f2b6aff6498dc1892a8884a484b4dff65ce9730029 } ================================================ FILE: old/simple/contracts/token.sol ================================================ // pragma solidity ^0.4.18; contract Token { mapping (address => uint) public balances; event Transfer(address sender, address receiver, uint amount); /* Initializes contract with initial supply tokens to the creator of the contract */ function Token() public { balances[msg.sender] = 10000; } /* Very simple transfer function */ function transfer(address receiver, uint amount) public returns(bool sufficient) { if (balances[msg.sender] < amount) return false; balances[msg.sender] -= amount; balances[receiver] += amount; Transfer(msg.sender, receiver, amount); return true; } } ================================================ FILE: old/simple/contracts/types.sol ================================================ contract Types { // signed integer (32 bytes) int signed; // unsigned integer (32 bytes) uint unsigned; // integer with bit size uint16 short; // boolean bool flag; // string string name; // address address wallet; // members: wallet.balance, // wallet.transfer(uint256) throws on failure // wallet.send(uint256) returns(bool) // returns false on failure // visible state variable int public visible; // fixed size byte arrays bytes1 onebyte; bytes20 twentybytes; bytes32 thirtytwobytes; int[10] tenintegers; string[5] fivemessages; // dynamically-sized arrays bytes data; string message; // enums enum Actions { GoLeft, GoRight, GoStraight, SitStill } // dynamic array initialization function f(uint len) { uint[] memory a = new uint[](7); bytes memory b = new bytes(len); // Here we have a.length == 7 and b.length == len a[6] = 8; } struct Voter { address delegate; bool voted; } struct Proposal { bytes32 name; uint voteCount; } } ================================================ FILE: old/simple/counter.asm ================================================ ======= contracts\counter.sol:Counter ======= EVM assembly: /* "contracts\counter.sol":63:399 contract Counter { ... */ mstore(0x40, 0x60) /* "contracts\counter.sol":109:165 function Counter() public { ... */ jumpi(tag_1, iszero(callvalue)) 0x0 dup1 revert tag_1: tag_2: /* "contracts\counter.sol":156:157 1 */ 0x1 /* "contracts\counter.sol":146:153 counter */ 0x0 /* "contracts\counter.sol":146:157 counter = 1 */ dup2 swap1 sstore pop /* "contracts\counter.sol":109:165 function Counter() public { ... */ tag_3: /* "contracts\counter.sol":63:399 contract Counter { ... */ tag_4: dataSize(sub_0) dup1 dataOffset(sub_0) 0x0 codecopy 0x0 return stop sub_0: assembly { /* "contracts\counter.sol":63:399 contract Counter { ... */ mstore(0x40, 0x60) calldataload(0x0) 0x100000000000000000000000000000000000000000000000000000000 swap1 div 0xffffffff and dup1 0x1003e2d2 eq tag_2 jumpi dup1 0x8ada066e eq tag_3 jumpi dup1 0xd09de08a eq tag_4 jumpi tag_1: 0x0 dup1 revert /* "contracts\counter.sol":242:301 function add(uint v) public { ... */ tag_2: jumpi(tag_5, iszero(callvalue)) 0x0 dup1 revert tag_5: tag_6 0x4 dup1 dup1 calldataload swap1 0x20 add swap1 swap2 swap1 pop pop jump(tag_7) tag_6: stop /* "contracts\counter.sol":310:396 function getCounter() public constant returns (uint) { ... */ tag_3: jumpi(tag_8, iszero(callvalue)) 0x0 dup1 revert tag_8: tag_9 jump(tag_10) tag_9: mload(0x40) dup1 dup3 dup2 mstore 0x20 add swap2 pop pop mload(0x40) dup1 swap2 sub swap1 return /* "contracts\counter.sol":177:233 function increment() public { ... */ tag_4: jumpi(tag_11, iszero(callvalue)) 0x0 dup1 revert tag_11: tag_12 jump(tag_13) tag_12: stop /* "contracts\counter.sol":242:301 function add(uint v) public { ... */ tag_7: /* "contracts\counter.sol":292:293 v */ dup1 /* "contracts\counter.sol":281:288 counter */ 0x0 dup1 /* "contracts\counter.sol":281:293 counter += v */ dup3 dup3 sload add swap3 pop pop dup2 swap1 sstore pop /* "contracts\counter.sol":242:301 function add(uint v) public { ... */ tag_14: pop jump // out /* "contracts\counter.sol":310:396 function getCounter() public constant returns (uint) { ... */ tag_10: /* "contracts\counter.sol":357:361 uint */ 0x0 /* "contracts\counter.sol":381:388 counter */ dup1 sload /* "contracts\counter.sol":374:388 return counter */ swap1 pop /* "contracts\counter.sol":310:396 function getCounter() public constant returns (uint) { ... */ tag_15: swap1 jump // out /* "contracts\counter.sol":177:233 function increment() public { ... */ tag_13: /* "contracts\counter.sol":216:223 counter */ 0x0 dup1 /* "contracts\counter.sol":216:225 counter++ */ dup2 sload dup1 swap3 swap2 swap1 0x1 add swap2 swap1 pop sstore pop /* "contracts\counter.sol":177:233 function increment() public { ... */ tag_16: jump // out auxdata: 0xa165627a7a72305820ce1256d578d3a616ce794b4e657934308050c723323cd4054e711e36e22d652d0029 } ================================================ FILE: old/simple/counter.eth ================================================ # uncomment to enable logging # logging true # retrieve accounts to use accounts[0] as default sender accounts message "compiling counter.sol" compile "./contracts/counter.sol" message "counter.sol compiled" dump contracts.Counter.functionHashes deploy Counter counter1 message "contract deployed to address" value call counter1 getCounter message "counter is" value assert value == 1 invoke counter1 increment call counter1 getCounter message "counter is" value assert value == 2 invoke counter1 add(uint256) 40 call counter1 getCounter message "counter is" value assert value == 42 ================================================ FILE: old/simple/creator.eth ================================================ accounts message "compiling creator.sol" compile "./contracts/creator.sol" message "creator.sol compiled" deploy Creator creator1 message "contract deployed to address" value ================================================ FILE: old/simple/deploy.eth ================================================ # uncomment to enable logging # logging true # retrieve accounts to use accounts[0] as default sender accounts message "compiling counter.sol" compile "./contracts/counter.sol" message "counter.sol compiled" deploy Counter counter1 message "contract deployed to address" value message "instance counter1 data" dump instances.counter1 ================================================ FILE: old/simple/do.js ================================================ var commands = require('./lib/commands'); var config = require('./config.json'); var sargs = require('simpleargs'); sargs .define('h', 'host', config.host, 'Host JSON RPC entry point') .define('n', 'name', config.name, 'Name of the new entity') .define('g', 'gas', config.name, 'Gas limit to consume'); var options = sargs(process.argv.slice(3)); var args = options._ || []; var cmdname = process.argv[2]; commands[cmdname](args, options, function (err, data) { if (err) console.error('error', err); else console.log(data); }); ================================================ FILE: old/simple/dump.eth ================================================ message "compiling empty.sol" compile "./contracts/empty.sol" message "empty.sol compiled" message "Empty functions" dump contracts.Empty.functionHashes message message "compiling counter.sol" compile "./contracts/counter.sol" message "counter.sol compiled" # assertions assert contracts.Counter assert contracts.Counter.interface assert contracts.Counter.bytecode assert contracts.Counter.runtimeBytecode message "Counter functions" dump contracts.Counter.functionHashes message "Counter interface" dump contracts.Counter.interface message "Counter bytecodes" dump contracts.Counter.bytecode ================================================ FILE: old/simple/empty.eth ================================================ # uncomment to enable logging # logging true # retrieve accounts to use accounts[0] as default sender accounts message "compiling empty.sol" compile "./contracts/empty.sol" message "empty.sol compiled" #unlock from "passphrase" 10000 deploy Empty empty1 message "contract deployed to address" value message "instance empty1 data" dump instances.empty1 ================================================ FILE: old/simple/greeter.eth ================================================ # uncomment to enable logging # logging true # retrieve accounts to use accounts[0] as default sender accounts message "compiling greeter.sol" compile "./contracts/greeter.sol" message "greeter.sol compiled" # dump contracts.Greeter.functionHashes # dump contracts.Greeter.interface deploy Greeter greeter1 message "contract deployed to address" value message "retrieving message" call greeter1 message message "message" value assert value === "Hello, Contract" message "changing message" invoke greeter1 setMessage "Hello, World" message "retrieving message" call greeter1 message message "message" value assert value === "Hello, World" ================================================ FILE: old/simple/hello.eth ================================================ # a message message "hello world" ================================================ FILE: old/simple/lib/commands.js ================================================ var rskapi = require('rskapi'); var async = require('simpleasync'); var solc = require('solc'); var utils = require('./utils'); var fs = require('fs'); var path = require('path'); var host = rskapi.host('http://localhost:4444'); var ctxfilename = 'context.json'; var context = loadContext(ctxfilename); function switchToHost(h) { host = h; flushHostContext(ctxfilename, context); } function setHost(url) { if (!url) { if (!host) switchToHost(rskapi.host('http://localhost:4444')); } else switchToHost(rskapi.host(url)); } function loadContext(filename) { if (!fs.existsSync(filename)) return {}; return JSON.parse(fs.readFileSync(filename).toString()); } function saveContext(filename, ctx) { var text = JSON.stringify(ctx); fs.writeFileSync(filename, text); } function flushHostContext(filename, ctx) { if (!ctx.addresses) return; delete ctx.addresses; saveContext(filename, ctx); } function toNumber(obj) { if (obj == null) return null; if (typeof obj === 'number') return obj; if (typeof obj === 'string' && obj.length < 16) return parseInt(obj); return obj; } function asNumber(obj) { if (typeof obj === 'number') return obj; if (typeof obj === 'string' && obj.length <= 10) return parseInt(obj); return null; } function getAccountAddress(acc, cb) { if (acc == null) return cb(null, null); host.getAccounts(function (err, accounts) { if (err) return cb(err); cb(null, getAccount(accounts)); }); function getAccount(accounts) { var n = asNumber(acc); if (n == null) return acc; return accounts[n]; } } function saveContract(name, value) { if (!context.contracts) context.contracts = {}; context.contracts[name] = value; } function saveInstance(name, contractname, txhash, address) { if (!context.instances) context.instances = {}; context.instances[name] = { contract: contractname, tx: txhash, address: address } } function getInstance(instancename) { if (!instancename) return null; if (!context.instances) return null; if (!context.instances[instancename]) return null; return context.instances[instancename]; } function getContract(contractname) { if (!contractname) return null; if (!context.contracts) return null; if (!context.contracts[contractname]) return null; return context.contracts[contractname]; } function getInstanceContract(instancename) { var instance = getInstance(instancename); if (!instance) return null; var contract = getContract(instance.contract); if (!contract) return null; return contract; } function getInstanceAddress(instancename) { var instance = getInstance(instancename); if (!instance) return null; if (!instance.address) return null; return instance.address; } function getInstance(name) { if (!context.instances) return null; return context.instances[name]; } function toData(contract, fnname, fnargs) { return contract.functionHashes[fnname] + utils.encodeArguments(fnargs); } function unlockAccount(addr, cb) { host.unlockPersonalAccount(addr, 'passphrase', 1000, cb); } function sendTransaction(from, to, value, options, cb) { options = options || {}; var fromaddr; var toaddr; async() .exec(function (next) { getAccountAddress(from, next); }) .then(function (addr, next) { fromaddr = addr; getAccountAddress(to, next); }) .then(function (addr, next) { toaddr = addr; unlockAccount(fromaddr, function (err, data) { next(); }); }) .then(function (data, next) { var txdata = { from: fromaddr, to: toaddr, value: value, gas: options.gas || 21000, gasPrice: options.gasPrice || 1 }; if (options.data) txdata.data = options.data; host.sendTransaction(txdata, cb); }) .error(function (err) { cb(err); }); } function sendRawCall(from, to, value, data, options, cb) { options = options || {}; var txdata = { from: from, to: to, value: value, gas: options.gas || 21000, gasPrice: options.gasPrice || 1, data: data }; host.callTransaction(txdata, cb); } function sendCallOrInvoke(instancename, from, fnname, fnargs, value, options, cb, iscall) { var toaddr = getInstanceAddress(instancename); if (!toaddr) return cb(new Error('unknown instance: ' + instancename)); var data = toData(getInstanceContract(instancename), fnname, fnargs); var tx; if (!data) if (fnname && fnname.startsWith('0x') && fnname.length === 10) data = fnname; else return cb(new Error('unknown function: ' + fnname)); async() .exec(function (next) { getAccountAddress(from, next); }) .then(function (addr, next) { if (iscall) return sendRawCall(addr, toaddr, value, data, options, cb); options.data = data; if (!options.gas) options.gas = 3000000; if (iscall) return sendRawCall(addr, toaddr, value, data, options, cb); sendTransaction(addr, toaddr, value, options, next); }) .then(function (txhash, next) { tx = txhash; getTransactionReceipt(txhash, 60, next); }) .then(function (txr, next) { cb(null, tx); }) .error(cb); } function sendCall(instancename, from, fnname, fnargs, value, options, cb) { sendCallOrInvoke(instancename, from, fnname, fnargs, value, options, cb, true) } function sendInvoke(instancename, from, fnname, fnargs, value, options, cb) { sendCallOrInvoke(instancename, from, fnname, fnargs, value, options, cb, false) } function getTransactionReceipt(hash, ntry, cb) { if (ntry <= 0) return cb('transaction ' + hash + 'not mined'); host.getTransactionReceiptByHash(hash, function (err, data) { if (err) return cb(err, null); if (data) return cb(null, data); setTimeout(function () { getTransactionReceipt(hash, ntry - 1, cb); }, 1000); }); } function createContract(contractname, owner, value, options, cb) { var opts = {}; opts.gas = options.gas || 3000000; opts.data = context.contracts[contractname].bytecode; var name = options.name || contractname; var txhash; async() .exec(function (next) { sendTransaction(owner, null, value, opts, next); }) .then(function (tx, next) { txhash = tx; getTransactionReceipt(txhash, 60, next); }) .then(function (txr, next) { saveInstance(name, contractname, txhash, txr.contractAddress); saveContext(ctxfilename, context); cb(null, name); }) .error(function (err) { cb(err); }); } function findImports(path) { return { contents: fs.readFileSync('./' + path).toString() }; // return { error: 'File not found' } } function compileContract(filename, name) { var input = fs.readFileSync(filename).toString(); var sources = {}; sources[filename] = input; var output = solc.compile({ sources: sources }, 1, findImports); // 1 activates the optimiser if (!name) { var fullname = Object.keys(output.contracts)[0]; var p = fullname.lastIndexOf(':'); if (p >= 0) name = fullname.substring(p + 1); else name = fullname; } for (var n in output.contracts) if (n.endsWith(':' + name)) { var contract = output.contracts[n]; saveContract(name, contract); saveContext(ctxfilename, context); return { name: name, contract: contract }; } } function compile(args, options, cb) { var filename = path.join('.', 'contracts', args[0]); var name = args[1]; setHost(options.host); try { var result = compileContract(filename, name); cb(null, result.name); } catch (err) { cb(err); } } function account(args, options, cb) { setHost(options.host); getAccountAddress(args[0], cb); } function accounts(args, options, cb) { setHost(options.host); host.getAccounts(cb); } function number(args, options, cb) { setHost(options.host); host.getBlockNumber(cb); }; function block(args, options, cb) { setHost(options.host); var id = args[0]; if (typeof id === 'number' || id.length <= 10) host.getBlockByNumber(parseInt(id), cb); else host.getBlockByHash(id, cb); }; function blocks(args, options, cb) { setHost(options.host); var id = args[0]; host.getBlocksByNumber(parseInt(id), cb); }; function balance(args, options, cb) { setHost(options.host); var address = args[0]; async() .exec(function (next) { getAccountAddress(address, next); }) .then(function (addr, next) { host.getBalance(addr, next); }) .then(function (balance, next) { cb(null, toNumber(balance)); }) .error(function (err) { cb(err); }); } function balances(args, options, cb) { setHost(options.host); async() .exec(function (next) { host.getAccounts(next); }).map(function (data, next) { host.getBalance(data, function (err, balance) { cb(err, { account: data, balance: balance }); }); }).then(function (data, next) { cb(null, data); }).error(function (err) { cb(err); }); } function deploy(args, options, cb) { setHost(options.host); createContract(args[0], args[1], args[2], options, cb); } function fns(args, options, cb) { var name = args[0]; if (!context.contracts[name]) return cb('unknown contract: ' + name); cb(null, Object.keys(context.contracts[name].functionHashes)); } function transfer(args, options, cb) { setHost(options.host); var from = args[0]; var to = args[1]; var value = args[2]; var tx; async() .exec(function (next) { sendTransaction(from, to, value, options, next); }) .then(function (txhash, next) { tx = txhash; getTransactionReceipt(txhash, 60, next); }) .then(function (txr, next) { cb(null, tx); }) .error(function (err) { cb(err); }); } function instance(args, options, cb) { var name = args[0]; cb(null, getInstance(name)); } function call(args, options, cb) { setHost(options.host); var name = args[0]; var from = args[1]; var fnname = args[2]; var fnargs = args[3] ? args[3].split(';') : []; var value = args[4] ? toNumber(args[4]) : 0; sendCall(name, from, fnname, fnargs, value, options, cb); } function invoke(args, options, cb) { setHost(options.host); var name = args[0]; var from = args[1]; var fnname = args[2]; var fnargs = args[3] ? args[3].toString().split(';') : []; var value = args[4] ? toNumber(args[4]) : 0; sendInvoke(name, from, fnname, fnargs, value, options, cb); } module.exports = { compile: compile, deploy: deploy, instance: instance, fns: fns, call: call, invoke: invoke, transfer: transfer, account: account, accounts: accounts, balance: balance, balances: balances, number: number, block: block, blocks: blocks }; ================================================ FILE: old/simple/lib/contexts.js ================================================ function Context() { var data = { contracts: {} }; this.contract = function (name, value) { if (value !== undefined) data.contracts[name] = value; else return data.contracts[name]; }; } function createContext() { return new Context(); } module.exports = { context: createContext }; ================================================ FILE: old/simple/lib/executors.js ================================================ var fs = require('fs'); var rskapi = require('rskapi'); var simpledsl = require('simpledsl'); var solc = require('solc'); var chalk = require('chalk'); var utils = require('./utils'); var DEFAULT_HOST = "http://localhost:8545"; function findImports(path) { return { contents: fs.readFileSync('./' + path).toString() }; // return { error: 'File not found' } } function compileContract(filename) { var input = fs.readFileSync(filename).toString(); var sources = {}; sources[filename] = input; var output = solc.compile({ sources: sources }, 1, findImports); // 1 activates the optimiser return output.contracts; } function toNumber(value) { if (typeof value === 'string' && value.startsWith('0x')) return value; return parseInt(value); } function Executor () { var self = this; var logger = console; var dsl = simpledsl.dsl({ comment: '#' }); var value; var host; var contracts = {}; var instances = {}; var accounts = []; var logging = false; var from; register('logging', function (cmd, next) { logging = evaluate(cmd.args); next(null, null); }); register('message', function (cmd, next) { logger.log.apply(logger, expand(cmd.args)); next(null, null); }); register('dump', function (cmd, next) { logger.log(evaluate(cmd.args)); next(null, null); }); register('evaluate', function (cmd, next) { var result = evaluate(cmd.args); self.value(result); next(null, result); }); register('assert', function (cmd, next) { var result = evaluate(cmd.args); if (!result) throw new Error('failed assertion: ' + cmd.args.join(' ')); else next(null, result); }); register('compile', function (cmd, next) { var result = compileContract(expand(cmd.args)[0]); for (var n in result) { self.contract(n, result[n]); var p = n.lastIndexOf(':'); if (p >= 0) self.contract(n.substring(p + 1), result[n]); } next(null, null); }); register('accounts', function (cmd, next) { self.host().getAccounts(function (err, data) { if (err) next(err, null); else { accounts = data; log('accounts', data); next(null, data); } }); }); register('balance', function (cmd, next) { self.host().getBalance(expand(cmd.args)[0], function (err, data) { if (err) next(err, null); else { value = data; next(null, data); } }); }); register('unlock', function (cmd, next) { var args = expand(cmd.args); log('unlock account', args[0]); self.host().unlockPersonalAccount(args[0], args[1], args[2], function (err, data) { if (err) next(err, null); else { value = data; next(null, data); } }); }); register('host', function (cmd, next) { host = rskapi.host(expand(cmd.args)[0]); next(null, null); }); register('transfer', function (cmd, next) { var host = self.host(); var args = expand(cmd.args); var from = args[0]; var to = args[1]; var value = args[2]; var tx; var txdata = { from: from, to: to, value: toNumber(value), gas: 3000000, gasPrice: 0 }; log('transaction data', txdata); host.sendTransaction(txdata, function (err, txhash) { if (err) return next(err, null); log('transaction hash', txhash); getTransactionReceipt(txhash, 60, function (err, txreceipt) { if (err) return next(err, null); log('transaction receipt', txreceipt); value = txhash; next(null, txhash); }) }); }); register('from', function (cmd, next) { from = expand(cmd.args)[0]; next(null, null); }); register('deploy', function (cmd, next) { var host = self.host(); var args = cmd.args; var contractname = args[0]; var instancename = args[1] || contractname; var contract = contracts[contractname]; var from = self.from(); var to = '0x00'; var bytecode = contract.bytecode; var fnargs = expand(args.slice(2)); var data = bytecode + toData(contract, null, fnargs); var tx; var txdata = { from: from, // to: to, value: 0, data: data, gas: 2000000, gasPrice: 0 }; log('transaction data', txdata); host.sendTransaction(txdata, function (err, txhash) { if (err) return next(err, null); log('transaction hash', txhash); getTransactionReceipt(txhash, 60, function (err, txreceipt) { if (err) return next(err, null); log('transaction receipt', txreceipt); instances[instancename] = { transactionHash: txhash, contractAddress: txreceipt.contractAddress, blockHash: txreceipt.blockHash, blockNumber: parseInt(txreceipt.blockNumber), contractName: args[0] }; value = txreceipt.contractAddress; next(null, txreceipt.contractAddress); }) }); }); register('call', function (cmd, next) { var host = self.host(); var args = cmd.args; var instancename = args[0]; var instance = instances[instancename]; var contractname = instance.contractName; var contract = contracts[contractname]; var fnname = args[1]; var fnargs = expand(args.slice(2)); var from = self.from(); var to = instance.contractAddress; var data = toData(contract, fnname, fnargs); var tx; var txdata = { from: from, to: to, value: 0, data: data, gas: 3000000, gasPrice: 0 }; log('transaction data', txdata); host.callTransaction(txdata, function (err, result) { if (err) return next(err, null); log('call result', result); result = utils.decodeValue(result); value = result; next(null, result); }); }); register('invoke', function (cmd, next) { var host = self.host(); var args = cmd.args; var instancename = args[0]; var instance = instances[instancename]; var contractname = instance.contractName; var contract = contracts[contractname]; var fnname = args[1]; var fnargs = expand(args.slice(2)); var from = self.from(); var to = instance.contractAddress; var data = toData(contract, fnname, fnargs); var tx; var txdata = { from: from, to: to, value: 0, data: data, gas: 3000000, gasPrice: 0 }; log('transaction data', txdata); host.sendTransaction(txdata, function (err, txhash) { if (err) return next(err, null); log('transaction hash', txhash); getTransactionReceipt(txhash, 60, function (err, txreceipt) { if (err) return next(err, null); log('transaction receipt', txreceipt); value = txhash; next(null, txhash); }) }); }); this.from = function (value) { if (value != null) return from = value; if (from && accounts && accounts[from]) return accounts[from]; if (from) return from; if (accounts) return accounts[0]; throw new Error('unknown sender'); } this.logging = function (value) { logging = value; } this.contract = function (name, value) { if (value === undefined) return contracts[name]; else contracts[name] = value; } this.value = function (newvalue) { if (newvalue === undefined) return value; else value = newvalue; } this.use = function (name, value) { if (name === 'logger') logger = value; }; this.execute = function (txt, cb) { dsl.execute(txt, cb); }; this.executeFile = function (filename, cb) { dsl.executeFile(filename, cb); }; this.evaluate = function (expr) { return evaluate(expr); } this.host = function (value) { if (value) host = rskapi.host(value); if (host) return host; host = rskapi.host(DEFAULT_HOST); return host; } function register(name, fn) { dsl.register(name, function (cmd, next) { try { fn(cmd, next); } catch (ex) { next(ex, null); } }); } function evaluate(args) { var expr; if (Array.isArray(args)) expr = args.join(' '); else expr = args; return eval(expr); } function expand(args) { if (Array.isArray(args)) return normalize(args).map(arg => expand(arg)); return evaluate(args); } function normalize(items) { var result = []; var ni = items.length; var instring = false; for (var k = 0; k < ni; k++) { var item = items[k]; if (instring) result[result.length - 1] += ' ' + item; else result.push(item); if (item.startsWith('"')) instring = true; if (item.endsWith('"')) instring = false; } return result; } function log(message, value) { if (!logging) return; if (value === undefined) return console.log(chalk.green(message)); if (typeof value !== 'object') return console.log(chalk.green(message), chalk.green(value)); console.log(chalk.green(message)); console.log(chalk.green(JSON.stringify(value, null, 4))); } function toData(contract, fnname, fnargs) { if (!fnname) return utils.encodeArguments(fnargs); return toFunctionHash(contract, fnname) + utils.encodeArguments(fnargs); } function toFunctionHash(contract, fnname) { if (contract.functionHashes[fnname]) return contract.functionHashes[fnname]; for (var n in contract.functionHashes) if (n.startsWith(fnname + '(')) return contract.functionHashes[n]; } function getTransactionReceipt(hash, ntry, cb) { var host = self.host(); if (ntry <= 0) return cb(new Error('transaction ' + hash + ' not mined')); host.getTransactionReceiptByHash(hash, function (err, data) { if (err) return cb(err, null); if (data) return cb(null, data); setTimeout(function () { getTransactionReceipt(hash, ntry - 1, cb); }, 1000); }); } } function createExecutor() { return new Executor(); } module.exports = { executor: createExecutor }; ================================================ FILE: old/simple/lib/utils.js ================================================ function repeatFunction(fn, ntimes, cb) { if (ntimes <= 0) return cb(null, null); fn(function (err, data) { if (err) return cb(err); setTimeout(function () { repeatFunction(fn, ntimes - 1, cb); }, 0); }); } function fillTo64(str) { if (str.length % 1) str += '0'; while (str.length % 64) str += '00'; return str; } function stringToHex(str) { var hex = Buffer.from(str).toString('hex'); if (hex.length % 1) hex = '0' + hex; return hex; } function encodeHexaValue(arg) { if (arg.startsWith('0x')) arg = arg.substring(2); while (arg.length < 64) arg = '0' + arg; return arg; } function encodeStringArgument(arg, ending) { var result = []; result.push(encodeIntegerArgument(ending)); var encoded = encodeIntegerArgument(arg.length) + fillTo64(stringToHex(arg)); result.push(encoded); return result; } function encodeStringValue(arg) { return encodeIntegerArgument(arg.length) + fillTo64(stringToHex(arg)); return result; } function encodeValue(arg) { if (typeof arg === 'string') if (arg.startsWith('0x')) return encodeHexaValue(arg); else return encodeStringValue(arg); else return encodeIntegerArgument(arg); } function encodeArguments(args) { var result = ''; var varresult = ''; args.forEach(function (arg) { if (typeof arg === 'string') { if (arg.startsWith('0x')) result += encodeHexaValue(arg); else { var encoded = encodeStringArgument(arg, args.length * 32 + varresult.length / 2); result += encoded[0]; varresult += encoded[1]; } } else result += encodeIntegerArgument(arg); }); return result + varresult; } function hexToString(hex) { var str = ''; for (var k = 0; k < hex.length; k += 2) str += String.fromCharCode(parseInt(hex.substring(k, k + 2), 16)); return str; } function decodeValue(encoded) { if (encoded.substring(0,2) === '0x') encoded = encoded.substring(2); if (encoded.length > 64) { var position = decodeValue(encoded.substring(0, 64)) * 2; var length = decodeValue(encoded.substring(position, position + 64)) * 2; return hexToString(encoded.substring(position + 64, position + 64 + length)); } return parseInt(encoded, 16); } function decodeValues(encoded) { if (encoded.substring(0,2) === '0x') encoded = encoded.substring(2); var values = []; while (encoded.length >= 64) { values.push(decodeValue(encoded.substring(0, 64))); encoded = encoded.substring(64); } return values; } function encodeIntegerArgument(arg) { var encoded = arg.toString(16); if (arg < 0) while (encoded.length < 64) encoded = 'f' + encoded; else while (encoded.length < 64) encoded = '0' + encoded; return encoded; } module.exports = { repeat: repeatFunction, encodeArguments: encodeArguments, encodeValue: encodeValue, decodeValue: decodeValue, decodeValues: decodeValues } ================================================ FILE: old/simple/message.eth ================================================ # retrieve accounts to use accounts[0] as default sender accounts message "compiling message.sol" compile "./contracts/message.sol" message "message.sol compiled" # dump contracts.Message.functionHashes dump contracts.Message.interface deploy Message message1 "hello" message "contract deployed to address" value message "retrieving message" call message1 message message "message" value assert value === "hello" message "changing message" invoke message1 setMessage "Hello, World" message "retrieving message" call message1 message message "message" value assert value === "Hello, World" ================================================ FILE: old/simple/package.json ================================================ { "name": "simple-solidity-contracts", "private": true, "version": "0.0.1", "description": "Simple Solidity Contracts", "main": "console.js", "scripts": { "test": "simpleunit test -r" }, "author": "", "license": "MIT", "dependencies": { "chalk": "^2.3.0", "rskapi": "0.0.6", "simpleargs": "0.0.3", "simpleasync": "0.0.8", "simpledsl": "0.0.3", "solc": "0.4.18" }, "engines": { "node": ">= 6.0.0" }, "devDependencies": { "solc": "0.4.18", "simpleunit": "0.0.7" } } ================================================ FILE: old/simple/rsksend.eth ================================================ # uncomment to enable logging # logging true # set RSK host host "http://localhost:4444" # retrieve accounts from host accounts assert accounts assert accounts.length message "Second account is" accounts[1] balance accounts[1] message "Its balance is" parseInt(value) message "Sending transaction..." send accounts[1] accounts[3] 1000000 message "Third account is" accounts[2] balance accounts[2] message "Its balance is" parseInt(value) message "Sending transaction..." send accounts[2] accounts[0] 1000000 ================================================ FILE: old/simple/rsktransfer.eth ================================================ # uncomment to enable logging # logging true # set RSK host host "http://localhost:4444" # retrieve accounts from host accounts assert accounts assert accounts.length message "Fourth account is" accounts[3] balance accounts[4] message "Its balance is" parseInt(value) message "First account is" accounts[1] balance accounts[0] message "Its balance is" parseInt(value) message "Transfering..." transfer accounts[4] accounts[0] 10000000000000 message "Second account is" accounts[1] balance accounts[1] message "Its balance is" parseInt(value) message "Transfering..." transfer accounts[4] accounts[1] 10000000000000 message "Third account is" accounts[2] balance accounts[2] message "Its balance is" parseInt(value) message "Transfering..." transfer accounts[4] accounts[2] 10000000000000 message "Fourth account is" accounts[3] balance accounts[3] message "Its balance is" parseInt(value) message "Transfering..." transfer accounts[4] accounts[3] 10000000000000 ================================================ FILE: old/simple/run.js ================================================ var executor = require('./lib/executors').executor(); var path = require('path'); var config = require('./config.json'); var sargs = require('simpleargs'); sargs .define('h', 'host', config.host, 'Host JSON RPC entry point') .define('f', 'from', config.from, 'From account address or number') .define('l', 'logging', false, 'Enable logging', { flag: true }) var options = sargs(process.argv.slice(2)); var args = options._; if (options.host) executor.host(options.host); if (options.from != null) executor.from(options.from); if (options.logging) executor.logging(options.logging); function normalize(filename) { var ext = path.extname(filename); if (!ext || ext.length == 0) return filename + '.eth'; return filename; } var cmdfile = normalize(process.argv[2]); executor.executeFile(cmdfile, function (err, data) { if (err) console.error(err); }); ================================================ FILE: old/simple/test/assert.js ================================================ var executors = require('../lib/executors'); exports['assert true'] = function (test) { var executor = executors.executor(); test.async(); executor.execute('assert true', function (err, data) { test.ok(!err); test.equal(data, true); test.done(); }); } exports['assert false'] = function (test) { var executor = executors.executor(); test.async(); executor.execute('assert false', function (err, data) { test.ok(err); test.equal(err.toString(), 'Error: failed assertion: false'); test.ok(!data); test.done(); }); } ================================================ FILE: old/simple/test/compile.js ================================================ var executors = require('../lib/executors'); exports['compile empty contract'] = function (test) { var executor = executors.executor(); test.async(); executor.execute('compile "./contracts/empty.sol"', function (err, data) { if (err) console.error(err); test.ok(!err); test.ok(executor.contract('./contracts/empty.sol:Empty')); test.ok(executor.contract('Empty')); test.done(); }); } exports['compile two contracts'] = function (test) { var executor = executors.executor(); test.async(); executor.execute('compile "./contracts/foobar.sol"', function (err, data) { test.ok(!err); test.ok(executor.contract('./contracts/foobar.sol:Foo')); test.ok(executor.contract('Foo')); test.ok(executor.contract('./contracts/foobar.sol:Bar')); test.ok(executor.contract('Bar')); test.done(); }); } ================================================ FILE: old/simple/test/contexts.js ================================================ var contexts = require('../lib/contexts'); exports['unknown contract'] = function (test) { var context = contexts.context(); test.equal(context.contract('foo'), null); }; exports['set and get contract'] = function (test) { var context = contexts.context(); var contract = { name: 'foo' }; context.contract('foo', contract); test.deepEqual(context.contract('foo'), contract); }; ================================================ FILE: old/simple/test/evaluate.js ================================================ var executors = require('../lib/executors'); exports['evaluate true'] = function (test) { var executor = executors.executor(); test.async(); executor.execute('evaluate true', function (err, data) { test.ok(!err); test.ok(data === true); test.ok(executor.value() === true); test.done(); }); } exports['evaluate false'] = function (test) { var executor = executors.executor(); test.async(); executor.execute('evaluate false', function (err, data) { test.ok(!err); test.ok(data === false); test.ok(executor.value() === false); test.done(); }); } exports['evaluate comparison'] = function (test) { var executor = executors.executor(); test.async(); executor.execute('evaluate 1 > 0', function (err, data) { test.ok(!err); test.ok(data === true); test.ok(executor.value() === true); test.done(); }); } exports['evaluate false comparison'] = function (test) { var executor = executors.executor(); test.async(); executor.execute('evaluate 1 > 2', function (err, data) { test.ok(!err); test.ok(data === false); test.ok(executor.value() === false); test.done(); }); } exports['evaluate comparison without spaces'] = function (test) { var executor = executors.executor(); test.async(); executor.execute('evaluate 1>0', function (err, data) { test.ok(!err); test.ok(data === true); test.ok(executor.value() === true); test.done(); }); } exports['evaluate value'] = function (test) { var executor = executors.executor(); test.async(); executor.execute(['evaluate 1 + 2', 'evaluate value'], function (err, data) { test.ok(!err); test.ok(data === 3); test.ok(executor.value() === 3); test.done(); }); } ================================================ FILE: old/simple/test/executors.js ================================================ var executors = require('../lib/executors'); exports['executor as object'] = function (test) { var executor = executors.executor(); test.ok(executor); test.equal(typeof executor, 'object'); }; exports['execute message'] = function (test) { var executor = executors.executor(); test.async(); executor.use('logger', { log: function () { test.ok(arguments); test.equal(arguments[0], "hello"); test.equal(arguments[1], "world"); } }); executor.execute('message "hello" "world"', function (err, data) { if (err) console.error(err); test.ok(!err); test.ok(!data); test.done(); }); }; exports['execute message with evaluated argument'] = function (test) { var executor = executors.executor(); test.async(); executor.use('logger', { log: function () { test.ok(arguments); test.equal(arguments[0], 3); } }); executor.execute('message 1+2', function (err, data) { if (err) console.error(err); test.ok(!err); test.ok(!data); test.done(); }); }; exports['execute message with string argument'] = function (test) { var executor = executors.executor(); test.async(); executor.use('logger', { log: function () { test.ok(arguments); test.equal(arguments[0], "hello"); } }); executor.execute('message "hello"', function (err, data) { if (err) console.error(err); test.ok(!err); test.ok(!data); test.done(); }); }; exports['execute dump'] = function (test) { var executor = executors.executor(); test.async(); executor.use('logger', { log: function () { test.ok(arguments); test.deepEqual(arguments[0], { name: 'Adam', age: 800 }); } }); executor.execute(['evaluate new Object({ name: "Adam", age: 800 })', 'dump value'], function (err, data) { if (err) console.error(err); test.ok(!err); test.ok(!data); test.done(); }); }; exports['execute file with message'] = function (test) { var executor = executors.executor(); test.async(); executor.use('logger', { log: function () { test.ok(arguments); test.equal(arguments[0], "hello world"); } }); executor.executeFile('./message.eth', function (err, data) { if (err) console.error(err); test.ok(!err); test.ok(!data); test.done(); }); }; exports['get host'] = function (test) { var executor = executors.executor(); var host = executor.host(); test.ok(host); test.equal(typeof host, 'object'); } exports['evaluate text'] = function (test) { var executor = executors.executor(); test.equal(executor.evaluate('1 + 41'), 42); } ================================================ FILE: old/simple/test/utils.js ================================================ var utils = require('../lib/utils'); exports['encode decode integer value'] = function (test) { var encoded = utils.encodeValue(42); var result = utils.decodeValue(encoded); test.equal(result, 42); } exports['encode hexa value'] = function (test) { var encoded = utils.encodeValue('0x1'); test.ok(encoded); test.equal(encoded.length, 64); test.equal(encoded, '0000000000000000000000000000000000000000000000000000000000000001'); } exports['encode hexa arguments'] = function (test) { var encoded = utils.encodeArguments(['0x1', '0x10']); test.ok(encoded); test.equal(encoded.length, 128); test.equal(encoded, '00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000010'); } exports['encode hexa arguments'] = function (test) { var encoded = utils.encodeArguments(['0x1', '0x10']); test.ok(encoded); test.equal(encoded.length, 128); test.equal(encoded, '00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000010'); } ================================================ FILE: old/simple/throw.eth ================================================ # retrieve accounts to use accounts[0] as default sender accounts message "compiling throw.sol" compile "./contracts/throw.sol" message "throw.sol compiled" deploy Throw throw1 message "contract deployed to address" value message "instance throw1 data" dump instances.throw1 ================================================ FILE: old/simple/token.eth ================================================ # uncomment to enable logging # logging true # retrieve accounts to use accounts[0] as default sender accounts message "compiling token.sol" compile "./contracts/token.sol" message "token.sol compiled" dump contracts.Token.functionHashes deploy Token token1 message "contract deployed to address" value call token1 balances(address) accounts[0] message "owner balance" value assert value == 10000 invoke token1 transfer(address,uint256) accounts[1] 100 call token1 balances(address) accounts[0] message "owner balance" value assert value == 10000-100 call token1 balances(address) accounts[1] message "receiver balance" value assert value == 100 ================================================ FILE: old/simple/transfer.eth ================================================ # uncomment to enable logging # logging true # retrieve accounts from default host (http://localhost:8545) accounts assert accounts assert accounts.length message "First account is" accounts[0] balance accounts[0] message "Its balance is" parseInt(value) message "Second account is" accounts[1] balance accounts[1] message "Its balance is" parseInt(value) message "Transfering..." transfer accounts[0] accounts[1] 1000000 message "First account is" accounts[0] balance accounts[0] message "Its balance is" parseInt(value) message "Second account is" accounts[1] balance accounts[1] message "Its balance is" parseInt(value) ================================================ FILE: openzeppelin/first/.gitignore ================================================ node_modules build ================================================ FILE: openzeppelin/first/contracts/ConvertLib.sol ================================================ pragma solidity ^0.4.4; library ConvertLib{ function convert(uint amount,uint conversionRate) returns (uint convertedAmount) { return amount * conversionRate; } } ================================================ FILE: openzeppelin/first/contracts/MetaCoin.sol ================================================ pragma solidity ^0.4.4; import "./ConvertLib.sol"; // This is just a simple example of a coin-like contract. // It is not standards compatible and cannot be expected to talk to other // coin/token contracts. If you want to create a standards-compliant // token, see: https://github.com/ConsenSys/Tokens. Cheers! contract MetaCoin { mapping (address => uint) balances; event Transfer(address indexed _from, address indexed _to, uint256 _value); function MetaCoin() { balances[tx.origin] = 10000; } function sendCoin(address receiver, uint amount) returns(bool sufficient) { if (balances[msg.sender] < amount) return false; balances[msg.sender] -= amount; balances[receiver] += amount; Transfer(msg.sender, receiver, amount); return true; } function getBalanceInEth(address addr) returns(uint){ return ConvertLib.convert(getBalance(addr),2); } function getBalance(address addr) returns(uint) { return balances[addr]; } } ================================================ FILE: openzeppelin/first/contracts/Migrations.sol ================================================ pragma solidity ^0.4.4; contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } function Migrations() { owner = msg.sender; } function setCompleted(uint completed) restricted { last_completed_migration = completed; } function upgrade(address new_address) restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } ================================================ FILE: openzeppelin/first/migrations/1_initial_migration.js ================================================ var Migrations = artifacts.require("./Migrations.sol"); module.exports = function(deployer) { deployer.deploy(Migrations); }; ================================================ FILE: openzeppelin/first/migrations/2_deploy_contracts.js ================================================ var ConvertLib = artifacts.require("./ConvertLib.sol"); var MetaCoin = artifacts.require("./MetaCoin.sol"); module.exports = function(deployer) { deployer.deploy(ConvertLib); deployer.link(ConvertLib, MetaCoin); deployer.deploy(MetaCoin); }; ================================================ FILE: openzeppelin/first/package.json ================================================ { "name": "openzeppelinfirst", "private": true, "version": "1.0.0", "description": "OpenZeppelin sample", "main": "truffle.js", "directories": { "test": "test" }, "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "zeppelin-solidity": "^1.3.0" } } ================================================ FILE: openzeppelin/first/test/TestMetacoin.sol ================================================ pragma solidity ^0.4.2; import "truffle/Assert.sol"; import "truffle/DeployedAddresses.sol"; import "../contracts/MetaCoin.sol"; contract TestMetacoin { function testInitialBalanceUsingDeployedContract() { MetaCoin meta = MetaCoin(DeployedAddresses.MetaCoin()); uint expected = 10000; Assert.equal(meta.getBalance(tx.origin), expected, "Owner should have 10000 MetaCoin initially"); } function testInitialBalanceWithNewMetaCoin() { MetaCoin meta = new MetaCoin(); uint expected = 10000; Assert.equal(meta.getBalance(tx.origin), expected, "Owner should have 10000 MetaCoin initially"); } } ================================================ FILE: openzeppelin/first/test/metacoin.js ================================================ var MetaCoin = artifacts.require("./MetaCoin.sol"); contract('MetaCoin', function(accounts) { it("should put 10000 MetaCoin in the first account", function() { return MetaCoin.deployed().then(function(instance) { return instance.getBalance.call(accounts[0]); }).then(function(balance) { assert.equal(balance.valueOf(), 10000, "10000 wasn't in the first account"); }); }); it("should call a function that depends on a linked library", function() { var meta; var metaCoinBalance; var metaCoinEthBalance; return MetaCoin.deployed().then(function(instance) { meta = instance; return meta.getBalance.call(accounts[0]); }).then(function(outCoinBalance) { metaCoinBalance = outCoinBalance.toNumber(); return meta.getBalanceInEth.call(accounts[0]); }).then(function(outCoinBalanceEth) { metaCoinEthBalance = outCoinBalanceEth.toNumber(); }).then(function() { assert.equal(metaCoinEthBalance, 2 * metaCoinBalance, "Library function returned unexpected function, linkage may be broken"); }); }); it("should send coin correctly", function() { var meta; // Get initial balances of first and second account. var account_one = accounts[0]; var account_two = accounts[1]; var account_one_starting_balance; var account_two_starting_balance; var account_one_ending_balance; var account_two_ending_balance; var amount = 10; return MetaCoin.deployed().then(function(instance) { meta = instance; return meta.getBalance.call(account_one); }).then(function(balance) { account_one_starting_balance = balance.toNumber(); return meta.getBalance.call(account_two); }).then(function(balance) { account_two_starting_balance = balance.toNumber(); return meta.sendCoin(account_two, amount, {from: account_one}); }).then(function() { return meta.getBalance.call(account_one); }).then(function(balance) { account_one_ending_balance = balance.toNumber(); return meta.getBalance.call(account_two); }).then(function(balance) { account_two_ending_balance = balance.toNumber(); assert.equal(account_one_ending_balance, account_one_starting_balance - amount, "Amount wasn't correctly taken from the sender"); assert.equal(account_two_ending_balance, account_two_starting_balance + amount, "Amount wasn't correctly sent to the receiver"); }); }); }); ================================================ FILE: openzeppelin/first/truffle.js ================================================ module.exports = { networks: { development: { host: "localhost", port: 8545, network_id: "*" // Match any network id } } }; ================================================ FILE: rskapi/.gitignore ================================================ config.json ================================================ FILE: rskapi/package.json ================================================ { "name": "rskapi_samples", "private": true, "version": "1.0.0", "description": "", "main": "test.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "ethereumjs-tx": "^1.3.7", "rskapi": "0.0.10" } } ================================================ FILE: rskapi/transfer.js ================================================ const rskapi = require('rskapi'); var Tx = require('ethereumjs-tx'); const config = require('./config.json'); const value = parseInt(process.argv[2]); let targetAccount = process.argv[3]; const host = rskapi.host(config.host); const privateKey = new Buffer(config.account.privateKey.substring(2), 'hex'); const tx = { to: targetAccount, value: value, gas: 22000, gasPrice: 0 }; (async function () { const nonce = await host.getTransactionCount(config.account.address); tx.nonce = nonce; var xtx = new Tx(tx); xtx.sign(privateKey); var serializedTx = xtx.serialize(); host.sendRawTransaction('0x' + serializedTx.toString('hex')); })(); ================================================ FILE: truffle/.gitignore ================================================ build ================================================ FILE: truffle/bac1/contracts/Counter.sol ================================================ contract Counter { uint public counter; function increment() public { counter++; } function add(uint v) public { counter += v; } } ================================================ FILE: truffle/bac1/contracts/Migrations.sol ================================================ pragma solidity ^0.4.23; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } ================================================ FILE: truffle/bac1/migrations/1_initial_migration.js ================================================ var Migrations = artifacts.require("./Migrations.sol"); module.exports = function(deployer) { deployer.deploy(Migrations); }; ================================================ FILE: truffle/bac1/migrations/2_deploy_contracts.js ================================================ var Counter = artifacts.require("./Counter.sol"); module.exports = function(deployer) { deployer.deploy(Counter); }; ================================================ FILE: truffle/bac1/test/CounterTest.js ================================================ var assert = require('assert'); var Counter = artifacts.require("./Counter.sol"); contract("Counter", function (accounts) { var counter; beforeEach(async function () { counter = await Counter.new(); }); describe("Increment", function () { it("Create counter", async function () { const c = await counter.counter(); assert.equal(c, 0); }); it("Increment counter", async function () { await counter.increment(); const c = await counter.counter(); assert.equal(c, 1); }); }); it("Add value to counter", async function () { await counter.add(1); await counter.add(41); const c = await counter.counter(); assert.equal(c, 42); }); }); ================================================ FILE: truffle/bac1/truffle-config.js ================================================ /* * NB: since truffle-hdwallet-provider 0.0.5 you must wrap HDWallet providers in a * function when declaring them. Failure to do so will cause commands to hang. ex: * ``` * mainnet: { * provider: function() { * return new HDWalletProvider(mnemonic, 'https://mainnet.infura.io/') * }, * network_id: '1', * gas: 4500000, * gasPrice: 10000000000, * }, */ module.exports = { networks: { development: { host: "127.0.0.1", port: 8545, network_id: "*" // Match any network id } } // See // to customize your Truffle configuration! }; ================================================ FILE: truffle/bytes/.gitignore ================================================ node_modules build ================================================ FILE: truffle/bytes/contracts/Bytes.asm ================================================ ======= contracts\Bytes.sol:Bytes ======= EVM assembly: /* "contracts\Bytes.sol":65:502 contract Bytes { ... */ mstore(0x40, 0x80) callvalue /* "--CODEGEN--":8:17 */ dup1 /* "--CODEGEN--":5:7 */ iszero tag_1 jumpi /* "--CODEGEN--":30:31 */ 0x0 /* "--CODEGEN--":27:28 */ dup1 /* "--CODEGEN--":20:32 */ revert /* "--CODEGEN--":5:7 */ tag_1: /* "contracts\Bytes.sol":65:502 contract Bytes { ... */ pop dataSize(sub_0) dup1 dataOffset(sub_0) 0x0 codecopy 0x0 return stop sub_0: assembly { /* "contracts\Bytes.sol":65:502 contract Bytes { ... */ mstore(0x40, 0x80) jumpi(tag_1, lt(calldatasize, 0x4)) calldataload(0x0) 0x100000000000000000000000000000000000000000000000000000000 swap1 div 0xffffffff and dup1 0x87de500d eq tag_2 jumpi dup1 0x9d5ef15e eq tag_3 jumpi dup1 0xa62af6a2 eq tag_4 jumpi dup1 0xc8f43d16 eq tag_5 jumpi dup1 0xd8d798f2 eq tag_6 jumpi dup1 0xf0ba8440 eq tag_7 jumpi tag_1: 0x0 dup1 revert /* "contracts\Bytes.sol":308:383 function setData2(string[] _data2) public { ... */ tag_2: callvalue /* "--CODEGEN--":8:17 */ dup1 /* "--CODEGEN--":5:7 */ iszero tag_8 jumpi /* "--CODEGEN--":30:31 */ 0x0 /* "--CODEGEN--":27:28 */ dup1 /* "--CODEGEN--":20:32 */ revert /* "--CODEGEN--":5:7 */ tag_8: /* "contracts\Bytes.sol":308:383 function setData2(string[] _data2) public { ... */ pop tag_9 0x4 dup1 calldatasize sub tag_10 swap2 swap1 dup2 add swap1 jump(tag_11) tag_10: jump(tag_12) tag_9: stop /* "contracts\Bytes.sol":171:296 function setData(bytes[] _data) public { ... */ tag_3: callvalue /* "--CODEGEN--":8:17 */ dup1 /* "--CODEGEN--":5:7 */ iszero tag_13 jumpi /* "--CODEGEN--":30:31 */ 0x0 /* "--CODEGEN--":27:28 */ dup1 /* "--CODEGEN--":20:32 */ revert /* "--CODEGEN--":5:7 */ tag_13: /* "contracts\Bytes.sol":171:296 function setData(bytes[] _data) public { ... */ pop tag_14 0x4 dup1 calldatasize sub tag_15 swap2 swap1 dup2 add swap1 jump(tag_16) tag_15: jump(tag_17) tag_14: stop /* "contracts\Bytes.sol":395:499 function getDataItem(uint position) public view returns (bytes) { ... */ tag_4: callvalue /* "--CODEGEN--":8:17 */ dup1 /* "--CODEGEN--":5:7 */ iszero tag_18 jumpi /* "--CODEGEN--":30:31 */ 0x0 /* "--CODEGEN--":27:28 */ dup1 /* "--CODEGEN--":20:32 */ revert /* "--CODEGEN--":5:7 */ tag_18: /* "contracts\Bytes.sol":395:499 function getDataItem(uint position) public view returns (bytes) { ... */ pop tag_19 0x4 dup1 calldatasize sub tag_20 swap2 swap1 dup2 add swap1 jump(tag_21) tag_20: jump(tag_22) tag_19: mload(0x40) tag_23 swap2 swap1 jump(tag_24) tag_23: mload(0x40) dup1 swap2 sub swap1 return /* "contracts\Bytes.sol":137:158 string[] public data2 */ tag_5: callvalue /* "--CODEGEN--":8:17 */ dup1 /* "--CODEGEN--":5:7 */ iszero tag_25 jumpi /* "--CODEGEN--":30:31 */ 0x0 /* "--CODEGEN--":27:28 */ dup1 /* "--CODEGEN--":20:32 */ revert /* "--CODEGEN--":5:7 */ tag_25: /* "contracts\Bytes.sol":137:158 string[] public data2 */ pop tag_26 0x4 dup1 calldatasize sub tag_27 swap2 swap1 dup2 add swap1 jump(tag_21) tag_27: jump(tag_28) tag_26: mload(0x40) tag_29 swap2 swap1 jump(tag_30) tag_29: mload(0x40) dup1 swap2 sub swap1 return /* "contracts\Bytes.sol":113:130 uint public ldata */ tag_6: callvalue /* "--CODEGEN--":8:17 */ dup1 /* "--CODEGEN--":5:7 */ iszero tag_31 jumpi /* "--CODEGEN--":30:31 */ 0x0 /* "--CODEGEN--":27:28 */ dup1 /* "--CODEGEN--":20:32 */ revert /* "--CODEGEN--":5:7 */ tag_31: /* "contracts\Bytes.sol":113:130 uint public ldata */ pop tag_32 jump(tag_33) tag_32: mload(0x40) tag_34 swap2 swap1 jump(tag_35) tag_34: mload(0x40) dup1 swap2 sub swap1 return /* "contracts\Bytes.sol":87:106 bytes[] public data */ tag_7: callvalue /* "--CODEGEN--":8:17 */ dup1 /* "--CODEGEN--":5:7 */ iszero tag_36 jumpi /* "--CODEGEN--":30:31 */ 0x0 /* "--CODEGEN--":27:28 */ dup1 /* "--CODEGEN--":20:32 */ revert /* "--CODEGEN--":5:7 */ tag_36: /* "contracts\Bytes.sol":87:106 bytes[] public data */ pop tag_37 0x4 dup1 calldatasize sub tag_38 swap2 swap1 dup2 add swap1 jump(tag_21) tag_38: jump(tag_39) tag_37: mload(0x40) tag_40 swap2 swap1 jump(tag_41) tag_40: mload(0x40) dup1 swap2 sub swap1 return /* "contracts\Bytes.sol":308:383 function setData2(string[] _data2) public { ... */ tag_12: /* "contracts\Bytes.sol":369:375 _data2 */ dup1 /* "contracts\Bytes.sol":361:366 data2 */ 0x2 /* "contracts\Bytes.sol":361:375 data2 = _data2 */ swap1 dup1 mload swap1 0x20 add swap1 tag_43 swap3 swap2 swap1 jump // in(tag_44) tag_43: pop /* "contracts\Bytes.sol":308:383 function setData2(string[] _data2) public { ... */ pop jump // out /* "contracts\Bytes.sol":171:296 function setData(bytes[] _data) public { ... */ tag_17: /* "contracts\Bytes.sol":287:288 1 */ 0x1 /* "contracts\Bytes.sol":279:284 ldata */ dup1 /* "contracts\Bytes.sol":279:288 ldata = 1 */ dup2 swap1 sstore pop /* "contracts\Bytes.sol":171:296 function setData(bytes[] _data) public { ... */ pop jump // out /* "contracts\Bytes.sol":395:499 function getDataItem(uint position) public view returns (bytes) { ... */ tag_22: /* "contracts\Bytes.sol":452:457 bytes */ 0x60 /* "contracts\Bytes.sol":477:481 data */ 0x0 /* "contracts\Bytes.sol":482:490 position */ dup3 /* "contracts\Bytes.sol":477:491 data[position] */ dup2 sload dup2 lt iszero iszero tag_47 jumpi invalid tag_47: swap1 0x0 mstore keccak256(0x0, 0x20) add /* "contracts\Bytes.sol":470:491 return data[position] */ dup1 sload 0x1 dup2 0x1 and iszero 0x100 mul sub and 0x2 swap1 div dup1 0x1f add 0x20 dup1 swap2 div mul 0x20 add mload(0x40) swap1 dup2 add 0x40 mstore dup1 swap3 swap2 swap1 dup2 dup2 mstore 0x20 add dup3 dup1 sload 0x1 dup2 0x1 and iszero 0x100 mul sub and 0x2 swap1 div dup1 iszero tag_49 jumpi dup1 0x1f lt tag_50 jumpi 0x100 dup1 dup4 sload div mul dup4 mstore swap2 0x20 add swap2 jump(tag_49) tag_50: dup3 add swap2 swap1 0x0 mstore keccak256(0x0, 0x20) swap1 tag_51: dup2 sload dup2 mstore swap1 0x1 add swap1 0x20 add dup1 dup4 gt tag_51 jumpi dup3 swap1 sub 0x1f and dup3 add swap2 tag_49: pop pop pop pop pop swap1 pop /* "contracts\Bytes.sol":395:499 function getDataItem(uint position) public view returns (bytes) { ... */ swap2 swap1 pop jump // out /* "contracts\Bytes.sol":137:158 string[] public data2 */ tag_28: 0x2 dup2 dup2 sload dup2 lt iszero iszero tag_52 jumpi invalid tag_52: swap1 0x0 mstore keccak256(0x0, 0x20) add 0x0 swap2 pop swap1 pop dup1 sload 0x1 dup2 0x1 and iszero 0x100 mul sub and 0x2 swap1 div dup1 0x1f add 0x20 dup1 swap2 div mul 0x20 add mload(0x40) swap1 dup2 add 0x40 mstore dup1 swap3 swap2 swap1 dup2 dup2 mstore 0x20 add dup3 dup1 sload 0x1 dup2 0x1 and iszero 0x100 mul sub and 0x2 swap1 div dup1 iszero tag_54 jumpi dup1 0x1f lt tag_55 jumpi 0x100 dup1 dup4 sload div mul dup4 mstore swap2 0x20 add swap2 jump(tag_54) tag_55: dup3 add swap2 swap1 0x0 mstore keccak256(0x0, 0x20) swap1 tag_56: dup2 sload dup2 mstore swap1 0x1 add swap1 0x20 add dup1 dup4 gt tag_56 jumpi dup3 swap1 sub 0x1f and dup3 add swap2 tag_54: pop pop pop pop pop dup2 jump // out /* "contracts\Bytes.sol":113:130 uint public ldata */ tag_33: sload(0x1) dup2 jump // out /* "contracts\Bytes.sol":87:106 bytes[] public data */ tag_39: 0x0 dup2 dup2 sload dup2 lt iszero iszero tag_57 jumpi invalid tag_57: swap1 0x0 mstore keccak256(0x0, 0x20) add 0x0 swap2 pop swap1 pop dup1 sload 0x1 dup2 0x1 and iszero 0x100 mul sub and 0x2 swap1 div dup1 0x1f add 0x20 dup1 swap2 div mul 0x20 add mload(0x40) swap1 dup2 add 0x40 mstore dup1 swap3 swap2 swap1 dup2 dup2 mstore 0x20 add dup3 dup1 sload 0x1 dup2 0x1 and iszero 0x100 mul sub and 0x2 swap1 div dup1 iszero tag_59 jumpi dup1 0x1f lt tag_60 jumpi 0x100 dup1 dup4 sload div mul dup4 mstore swap2 0x20 add swap2 jump(tag_59) tag_60: dup3 add swap2 swap1 0x0 mstore keccak256(0x0, 0x20) swap1 tag_61: dup2 sload dup2 mstore swap1 0x1 add swap1 0x20 add dup1 dup4 gt tag_61 jumpi dup3 swap1 sub 0x1f and dup3 add swap2 tag_59: pop pop pop pop pop dup2 jump // out /* "contracts\Bytes.sol":65:502 contract Bytes { ... */ tag_44: dup3 dup1 sload dup3 dup3 sstore swap1 0x0 mstore keccak256(0x0, 0x20) swap1 dup2 add swap3 dup3 iszero tag_62 jumpi swap2 0x20 mul dup3 add tag_63: dup3 dup2 gt iszero tag_64 jumpi dup3 mload dup3 swap1 dup1 mload swap1 0x20 add swap1 tag_65 swap3 swap2 swap1 jump // in(tag_66) tag_65: pop swap2 0x20 add swap2 swap1 0x1 add swap1 jump(tag_63) tag_64: tag_62: pop swap1 pop tag_67 swap2 swap1 jump // in(tag_68) tag_67: pop swap1 jump // out tag_66: dup3 dup1 sload 0x1 dup2 0x1 and iszero 0x100 mul sub and 0x2 swap1 div swap1 0x0 mstore keccak256(0x0, 0x20) swap1 0x1f add 0x20 swap1 div dup2 add swap3 dup3 0x1f lt tag_70 jumpi dup1 mload not(0xff) and dup4 dup1 add or dup6 sstore jump(tag_69) tag_70: dup3 dup1 add 0x1 add dup6 sstore dup3 iszero tag_69 jumpi swap2 dup3 add tag_71: dup3 dup2 gt iszero tag_72 jumpi dup3 mload dup3 sstore swap2 0x20 add swap2 swap1 0x1 add swap1 jump(tag_71) tag_72: tag_69: pop swap1 pop tag_73 swap2 swap1 jump // in(tag_74) tag_73: pop swap1 jump // out tag_68: tag_75 swap2 swap1 tag_76: dup1 dup3 gt iszero tag_77 jumpi 0x0 dup2 dup2 tag_78 swap2 swap1 jump // in(tag_79) tag_78: pop 0x1 add jump(tag_76) tag_77: pop swap1 jump tag_75: swap1 jump // out tag_74: tag_80 swap2 swap1 tag_81: dup1 dup3 gt iszero tag_82 jumpi 0x0 dup2 0x0 swap1 sstore pop 0x1 add jump(tag_81) tag_82: pop swap1 jump tag_80: swap1 jump // out tag_79: pop dup1 sload 0x1 dup2 0x1 and iszero 0x100 mul sub and 0x2 swap1 div 0x0 dup3 sstore dup1 0x1f lt tag_84 jumpi pop jump(tag_83) tag_84: 0x1f add 0x20 swap1 div swap1 0x0 mstore keccak256(0x0, 0x20) swap1 dup2 add swap1 tag_85 swap2 swap1 jump // in(tag_74) tag_85: tag_83: pop jump // out /* "--CODEGEN--":21:714 */ tag_87: 0x0 /* "--CODEGEN--":143:146 */ dup3 /* "--CODEGEN--":136:140 */ 0x1f /* "--CODEGEN--":128:134 */ dup4 /* "--CODEGEN--":124:141 */ add /* "--CODEGEN--":120:147 */ slt /* "--CODEGEN--":113:148 */ iszero /* "--CODEGEN--":110:112 */ iszero tag_88 jumpi /* "--CODEGEN--":161:162 */ 0x0 /* "--CODEGEN--":158:159 */ dup1 /* "--CODEGEN--":151:163 */ revert /* "--CODEGEN--":110:112 */ tag_88: /* "--CODEGEN--":198:204 */ dup2 /* "--CODEGEN--":185:205 */ calldataload /* "--CODEGEN--":220:305 */ tag_89 /* "--CODEGEN--":235:304 */ tag_90 /* "--CODEGEN--":297:303 */ dup3 /* "--CODEGEN--":235:304 */ jump(tag_91) tag_90: /* "--CODEGEN--":220:305 */ jump(tag_92) tag_89: /* "--CODEGEN--":211:305 */ swap2 pop /* "--CODEGEN--":322:327 */ dup2 /* "--CODEGEN--":347:353 */ dup2 /* "--CODEGEN--":340:345 */ dup4 /* "--CODEGEN--":333:354 */ mstore /* "--CODEGEN--":377:381 */ 0x20 /* "--CODEGEN--":369:375 */ dup5 /* "--CODEGEN--":365:382 */ add /* "--CODEGEN--":355:382 */ swap4 pop /* "--CODEGEN--":399:403 */ 0x20 /* "--CODEGEN--":394:397 */ dup2 /* "--CODEGEN--":390:404 */ add /* "--CODEGEN--":383:404 */ swap1 pop /* "--CODEGEN--":452:458 */ dup4 /* "--CODEGEN--":485:486 */ 0x0 /* "--CODEGEN--":470:708 */ tag_93: /* "--CODEGEN--":495:501 */ dup4 /* "--CODEGEN--":492:493 */ dup2 /* "--CODEGEN--":489:502 */ lt /* "--CODEGEN--":470:708 */ iszero tag_94 jumpi /* "--CODEGEN--":578:581 */ dup2 /* "--CODEGEN--":565:582 */ calldataload /* "--CODEGEN--":557:563 */ dup7 /* "--CODEGEN--":553:583 */ add /* "--CODEGEN--":602:644 */ tag_96 /* "--CODEGEN--":640:643 */ dup9 /* "--CODEGEN--":628:638 */ dup3 /* "--CODEGEN--":602:644 */ jump(tag_97) tag_96: /* "--CODEGEN--":597:600 */ dup5 /* "--CODEGEN--":590:645 */ mstore /* "--CODEGEN--":668:672 */ 0x20 /* "--CODEGEN--":663:666 */ dup5 /* "--CODEGEN--":659:673 */ add /* "--CODEGEN--":652:673 */ swap4 pop /* "--CODEGEN--":696:700 */ 0x20 /* "--CODEGEN--":691:694 */ dup4 /* "--CODEGEN--":687:701 */ add /* "--CODEGEN--":680:701 */ swap3 pop /* "--CODEGEN--":527:708 */ pop /* "--CODEGEN--":517:518 */ 0x1 /* "--CODEGEN--":514:515 */ dup2 /* "--CODEGEN--":510:519 */ add /* "--CODEGEN--":505:519 */ swap1 pop /* "--CODEGEN--":470:708 */ jump(tag_93) tag_94: /* "--CODEGEN--":474:488 */ pop /* "--CODEGEN--":103:714 */ pop pop pop swap3 swap2 pop pop jump /* "--CODEGEN--":739:1435 */ tag_99: 0x0 /* "--CODEGEN--":862:865 */ dup3 /* "--CODEGEN--":855:859 */ 0x1f /* "--CODEGEN--":847:853 */ dup4 /* "--CODEGEN--":843:860 */ add /* "--CODEGEN--":839:866 */ slt /* "--CODEGEN--":832:867 */ iszero /* "--CODEGEN--":829:831 */ iszero tag_100 jumpi /* "--CODEGEN--":880:881 */ 0x0 /* "--CODEGEN--":877:878 */ dup1 /* "--CODEGEN--":870:882 */ revert /* "--CODEGEN--":829:831 */ tag_100: /* "--CODEGEN--":917:923 */ dup2 /* "--CODEGEN--":904:924 */ calldataload /* "--CODEGEN--":939:1025 */ tag_101 /* "--CODEGEN--":954:1024 */ tag_102 /* "--CODEGEN--":1017:1023 */ dup3 /* "--CODEGEN--":954:1024 */ jump(tag_103) tag_102: /* "--CODEGEN--":939:1025 */ jump(tag_92) tag_101: /* "--CODEGEN--":930:1025 */ swap2 pop /* "--CODEGEN--":1042:1047 */ dup2 /* "--CODEGEN--":1067:1073 */ dup2 /* "--CODEGEN--":1060:1065 */ dup4 /* "--CODEGEN--":1053:1074 */ mstore /* "--CODEGEN--":1097:1101 */ 0x20 /* "--CODEGEN--":1089:1095 */ dup5 /* "--CODEGEN--":1085:1102 */ add /* "--CODEGEN--":1075:1102 */ swap4 pop /* "--CODEGEN--":1119:1123 */ 0x20 /* "--CODEGEN--":1114:1117 */ dup2 /* "--CODEGEN--":1110:1124 */ add /* "--CODEGEN--":1103:1124 */ swap1 pop /* "--CODEGEN--":1172:1178 */ dup4 /* "--CODEGEN--":1205:1206 */ 0x0 /* "--CODEGEN--":1190:1429 */ tag_104: /* "--CODEGEN--":1215:1221 */ dup4 /* "--CODEGEN--":1212:1213 */ dup2 /* "--CODEGEN--":1209:1222 */ lt /* "--CODEGEN--":1190:1429 */ iszero tag_105 jumpi /* "--CODEGEN--":1298:1301 */ dup2 /* "--CODEGEN--":1285:1302 */ calldataload /* "--CODEGEN--":1277:1283 */ dup7 /* "--CODEGEN--":1273:1303 */ add /* "--CODEGEN--":1322:1365 */ tag_107 /* "--CODEGEN--":1361:1364 */ dup9 /* "--CODEGEN--":1349:1359 */ dup3 /* "--CODEGEN--":1322:1365 */ jump(tag_108) tag_107: /* "--CODEGEN--":1317:1320 */ dup5 /* "--CODEGEN--":1310:1366 */ mstore /* "--CODEGEN--":1389:1393 */ 0x20 /* "--CODEGEN--":1384:1387 */ dup5 /* "--CODEGEN--":1380:1394 */ add /* "--CODEGEN--":1373:1394 */ swap4 pop /* "--CODEGEN--":1417:1421 */ 0x20 /* "--CODEGEN--":1412:1415 */ dup4 /* "--CODEGEN--":1408:1422 */ add /* "--CODEGEN--":1401:1422 */ swap3 pop /* "--CODEGEN--":1247:1429 */ pop /* "--CODEGEN--":1237:1238 */ 0x1 /* "--CODEGEN--":1234:1235 */ dup2 /* "--CODEGEN--":1230:1239 */ add /* "--CODEGEN--":1225:1239 */ swap1 pop /* "--CODEGEN--":1190:1429 */ jump(tag_104) tag_105: /* "--CODEGEN--":1194:1208 */ pop /* "--CODEGEN--":822:1435 */ pop pop pop swap3 swap2 pop pop jump /* "--CODEGEN--":1444:1876 */ tag_97: 0x0 /* "--CODEGEN--":1541:1544 */ dup3 /* "--CODEGEN--":1534:1538 */ 0x1f /* "--CODEGEN--":1526:1532 */ dup4 /* "--CODEGEN--":1522:1539 */ add /* "--CODEGEN--":1518:1545 */ slt /* "--CODEGEN--":1511:1546 */ iszero /* "--CODEGEN--":1508:1510 */ iszero tag_110 jumpi /* "--CODEGEN--":1559:1560 */ 0x0 /* "--CODEGEN--":1556:1557 */ dup1 /* "--CODEGEN--":1549:1561 */ revert /* "--CODEGEN--":1508:1510 */ tag_110: /* "--CODEGEN--":1596:1602 */ dup2 /* "--CODEGEN--":1583:1603 */ calldataload /* "--CODEGEN--":1618:1678 */ tag_111 /* "--CODEGEN--":1633:1677 */ tag_112 /* "--CODEGEN--":1670:1676 */ dup3 /* "--CODEGEN--":1633:1677 */ jump(tag_113) tag_112: /* "--CODEGEN--":1618:1678 */ jump(tag_92) tag_111: /* "--CODEGEN--":1609:1678 */ swap2 pop /* "--CODEGEN--":1698:1704 */ dup1 /* "--CODEGEN--":1691:1696 */ dup3 /* "--CODEGEN--":1684:1705 */ mstore /* "--CODEGEN--":1734:1738 */ 0x20 /* "--CODEGEN--":1726:1732 */ dup4 /* "--CODEGEN--":1722:1739 */ add /* "--CODEGEN--":1767:1771 */ 0x20 /* "--CODEGEN--":1760:1765 */ dup4 /* "--CODEGEN--":1756:1772 */ add /* "--CODEGEN--":1802:1805 */ dup6 /* "--CODEGEN--":1793:1799 */ dup4 /* "--CODEGEN--":1788:1791 */ dup4 /* "--CODEGEN--":1784:1800 */ add /* "--CODEGEN--":1781:1806 */ gt /* "--CODEGEN--":1778:1780 */ iszero tag_114 jumpi /* "--CODEGEN--":1819:1820 */ 0x0 /* "--CODEGEN--":1816:1817 */ dup1 /* "--CODEGEN--":1809:1821 */ revert /* "--CODEGEN--":1778:1780 */ tag_114: /* "--CODEGEN--":1829:1870 */ tag_115 /* "--CODEGEN--":1863:1869 */ dup4 /* "--CODEGEN--":1858:1861 */ dup3 /* "--CODEGEN--":1853:1856 */ dup5 /* "--CODEGEN--":1829:1870 */ jump(tag_116) tag_115: /* "--CODEGEN--":1501:1876 */ pop pop pop swap3 swap2 pop pop jump /* "--CODEGEN--":1885:2319 */ tag_108: 0x0 /* "--CODEGEN--":1983:1986 */ dup3 /* "--CODEGEN--":1976:1980 */ 0x1f /* "--CODEGEN--":1968:1974 */ dup4 /* "--CODEGEN--":1964:1981 */ add /* "--CODEGEN--":1960:1987 */ slt /* "--CODEGEN--":1953:1988 */ iszero /* "--CODEGEN--":1950:1952 */ iszero tag_118 jumpi /* "--CODEGEN--":2001:2002 */ 0x0 /* "--CODEGEN--":1998:1999 */ dup1 /* "--CODEGEN--":1991:2003 */ revert /* "--CODEGEN--":1950:1952 */ tag_118: /* "--CODEGEN--":2038:2044 */ dup2 /* "--CODEGEN--":2025:2045 */ calldataload /* "--CODEGEN--":2060:2121 */ tag_119 /* "--CODEGEN--":2075:2120 */ tag_120 /* "--CODEGEN--":2113:2119 */ dup3 /* "--CODEGEN--":2075:2120 */ jump(tag_121) tag_120: /* "--CODEGEN--":2060:2121 */ jump(tag_92) tag_119: /* "--CODEGEN--":2051:2121 */ swap2 pop /* "--CODEGEN--":2141:2147 */ dup1 /* "--CODEGEN--":2134:2139 */ dup3 /* "--CODEGEN--":2127:2148 */ mstore /* "--CODEGEN--":2177:2181 */ 0x20 /* "--CODEGEN--":2169:2175 */ dup4 /* "--CODEGEN--":2165:2182 */ add /* "--CODEGEN--":2210:2214 */ 0x20 /* "--CODEGEN--":2203:2208 */ dup4 /* "--CODEGEN--":2199:2215 */ add /* "--CODEGEN--":2245:2248 */ dup6 /* "--CODEGEN--":2236:2242 */ dup4 /* "--CODEGEN--":2231:2234 */ dup4 /* "--CODEGEN--":2227:2243 */ add /* "--CODEGEN--":2224:2249 */ gt /* "--CODEGEN--":2221:2223 */ iszero tag_122 jumpi /* "--CODEGEN--":2262:2263 */ 0x0 /* "--CODEGEN--":2259:2260 */ dup1 /* "--CODEGEN--":2252:2264 */ revert /* "--CODEGEN--":2221:2223 */ tag_122: /* "--CODEGEN--":2272:2313 */ tag_123 /* "--CODEGEN--":2306:2312 */ dup4 /* "--CODEGEN--":2301:2304 */ dup3 /* "--CODEGEN--":2296:2299 */ dup5 /* "--CODEGEN--":2272:2313 */ jump(tag_116) tag_123: /* "--CODEGEN--":1943:2319 */ pop pop pop swap3 swap2 pop pop jump /* "--CODEGEN--":2327:2445 */ tag_125: 0x0 /* "--CODEGEN--":2394:2440 */ tag_126 /* "--CODEGEN--":2432:2438 */ dup3 /* "--CODEGEN--":2419:2439 */ calldataload /* "--CODEGEN--":2394:2440 */ jump(tag_127) tag_126: /* "--CODEGEN--":2385:2440 */ swap1 pop /* "--CODEGEN--":2379:2445 */ swap3 swap2 pop pop jump /* "--CODEGEN--":2452:2839 */ tag_16: 0x0 /* "--CODEGEN--":2586:2588 */ 0x20 /* "--CODEGEN--":2574:2583 */ dup3 /* "--CODEGEN--":2565:2572 */ dup5 /* "--CODEGEN--":2561:2584 */ sub /* "--CODEGEN--":2557:2589 */ slt /* "--CODEGEN--":2554:2556 */ iszero tag_129 jumpi /* "--CODEGEN--":2602:2603 */ 0x0 /* "--CODEGEN--":2599:2600 */ dup1 /* "--CODEGEN--":2592:2604 */ revert /* "--CODEGEN--":2554:2556 */ tag_129: /* "--CODEGEN--":2665:2666 */ 0x0 /* "--CODEGEN--":2654:2663 */ dup3 /* "--CODEGEN--":2650:2667 */ add /* "--CODEGEN--":2637:2668 */ calldataload /* "--CODEGEN--":2688:2706 */ 0xffffffffffffffff /* "--CODEGEN--":2680:2686 */ dup2 /* "--CODEGEN--":2677:2707 */ gt /* "--CODEGEN--":2674:2676 */ iszero tag_130 jumpi /* "--CODEGEN--":2720:2721 */ 0x0 /* "--CODEGEN--":2717:2718 */ dup1 /* "--CODEGEN--":2710:2722 */ revert /* "--CODEGEN--":2674:2676 */ tag_130: /* "--CODEGEN--":2740:2823 */ tag_131 /* "--CODEGEN--":2815:2822 */ dup5 /* "--CODEGEN--":2806:2812 */ dup3 /* "--CODEGEN--":2795:2804 */ dup6 /* "--CODEGEN--":2791:2813 */ add /* "--CODEGEN--":2740:2823 */ jump(tag_87) tag_131: /* "--CODEGEN--":2730:2823 */ swap2 pop /* "--CODEGEN--":2616:2829 */ pop /* "--CODEGEN--":2548:2839 */ swap3 swap2 pop pop jump /* "--CODEGEN--":2846:3235 */ tag_11: 0x0 /* "--CODEGEN--":2981:2983 */ 0x20 /* "--CODEGEN--":2969:2978 */ dup3 /* "--CODEGEN--":2960:2967 */ dup5 /* "--CODEGEN--":2956:2979 */ sub /* "--CODEGEN--":2952:2984 */ slt /* "--CODEGEN--":2949:2951 */ iszero tag_133 jumpi /* "--CODEGEN--":2997:2998 */ 0x0 /* "--CODEGEN--":2994:2995 */ dup1 /* "--CODEGEN--":2987:2999 */ revert /* "--CODEGEN--":2949:2951 */ tag_133: /* "--CODEGEN--":3060:3061 */ 0x0 /* "--CODEGEN--":3049:3058 */ dup3 /* "--CODEGEN--":3045:3062 */ add /* "--CODEGEN--":3032:3063 */ calldataload /* "--CODEGEN--":3083:3101 */ 0xffffffffffffffff /* "--CODEGEN--":3075:3081 */ dup2 /* "--CODEGEN--":3072:3102 */ gt /* "--CODEGEN--":3069:3071 */ iszero tag_134 jumpi /* "--CODEGEN--":3115:3116 */ 0x0 /* "--CODEGEN--":3112:3113 */ dup1 /* "--CODEGEN--":3105:3117 */ revert /* "--CODEGEN--":3069:3071 */ tag_134: /* "--CODEGEN--":3135:3219 */ tag_135 /* "--CODEGEN--":3211:3218 */ dup5 /* "--CODEGEN--":3202:3208 */ dup3 /* "--CODEGEN--":3191:3200 */ dup6 /* "--CODEGEN--":3187:3209 */ add /* "--CODEGEN--":3135:3219 */ jump(tag_99) tag_135: /* "--CODEGEN--":3125:3219 */ swap2 pop /* "--CODEGEN--":3011:3225 */ pop /* "--CODEGEN--":2943:3235 */ swap3 swap2 pop pop jump /* "--CODEGEN--":3242:3483 */ tag_21: 0x0 /* "--CODEGEN--":3346:3348 */ 0x20 /* "--CODEGEN--":3334:3343 */ dup3 /* "--CODEGEN--":3325:3332 */ dup5 /* "--CODEGEN--":3321:3344 */ sub /* "--CODEGEN--":3317:3349 */ slt /* "--CODEGEN--":3314:3316 */ iszero tag_137 jumpi /* "--CODEGEN--":3362:3363 */ 0x0 /* "--CODEGEN--":3359:3360 */ dup1 /* "--CODEGEN--":3352:3364 */ revert /* "--CODEGEN--":3314:3316 */ tag_137: /* "--CODEGEN--":3397:3398 */ 0x0 /* "--CODEGEN--":3414:3467 */ tag_138 /* "--CODEGEN--":3459:3466 */ dup5 /* "--CODEGEN--":3450:3456 */ dup3 /* "--CODEGEN--":3439:3448 */ dup6 /* "--CODEGEN--":3435:3457 */ add /* "--CODEGEN--":3414:3467 */ jump(tag_125) tag_138: /* "--CODEGEN--":3404:3467 */ swap2 pop /* "--CODEGEN--":3376:3473 */ pop /* "--CODEGEN--":3308:3483 */ swap3 swap2 pop pop jump /* "--CODEGEN--":3490:3787 */ tag_140: 0x0 /* "--CODEGEN--":3590:3628 */ tag_141 /* "--CODEGEN--":3622:3627 */ dup3 /* "--CODEGEN--":3590:3628 */ jump(tag_142) tag_141: /* "--CODEGEN--":3645:3651 */ dup1 /* "--CODEGEN--":3640:3643 */ dup5 /* "--CODEGEN--":3633:3652 */ mstore /* "--CODEGEN--":3657:3720 */ tag_143 /* "--CODEGEN--":3713:3719 */ dup2 /* "--CODEGEN--":3706:3710 */ 0x20 /* "--CODEGEN--":3701:3704 */ dup7 /* "--CODEGEN--":3697:3711 */ add /* "--CODEGEN--":3690:3694 */ 0x20 /* "--CODEGEN--":3683:3688 */ dup7 /* "--CODEGEN--":3679:3695 */ add /* "--CODEGEN--":3657:3720 */ jump(tag_144) tag_143: /* "--CODEGEN--":3752:3781 */ tag_145 /* "--CODEGEN--":3774:3780 */ dup2 /* "--CODEGEN--":3752:3781 */ jump(tag_146) tag_145: /* "--CODEGEN--":3745:3749 */ 0x20 /* "--CODEGEN--":3740:3743 */ dup6 /* "--CODEGEN--":3736:3750 */ add /* "--CODEGEN--":3732:3782 */ add /* "--CODEGEN--":3725:3782 */ swap2 pop /* "--CODEGEN--":3570:3787 */ pop swap3 swap2 pop pop jump /* "--CODEGEN--":3794:4083 */ tag_148: 0x0 /* "--CODEGEN--":3890:3924 */ tag_149 /* "--CODEGEN--":3918:3923 */ dup3 /* "--CODEGEN--":3890:3924 */ jump(tag_150) tag_149: /* "--CODEGEN--":3941:3947 */ dup1 /* "--CODEGEN--":3936:3939 */ dup5 /* "--CODEGEN--":3929:3948 */ mstore /* "--CODEGEN--":3953:4016 */ tag_151 /* "--CODEGEN--":4009:4015 */ dup2 /* "--CODEGEN--":4002:4006 */ 0x20 /* "--CODEGEN--":3997:4000 */ dup7 /* "--CODEGEN--":3993:4007 */ add /* "--CODEGEN--":3986:3990 */ 0x20 /* "--CODEGEN--":3979:3984 */ dup7 /* "--CODEGEN--":3975:3991 */ add /* "--CODEGEN--":3953:4016 */ jump(tag_144) tag_151: /* "--CODEGEN--":4048:4077 */ tag_152 /* "--CODEGEN--":4070:4076 */ dup2 /* "--CODEGEN--":4048:4077 */ jump(tag_146) tag_152: /* "--CODEGEN--":4041:4045 */ 0x20 /* "--CODEGEN--":4036:4039 */ dup6 /* "--CODEGEN--":4032:4046 */ add /* "--CODEGEN--":4028:4078 */ add /* "--CODEGEN--":4021:4078 */ swap2 pop /* "--CODEGEN--":3870:4083 */ pop swap3 swap2 pop pop jump /* "--CODEGEN--":4090:4382 */ tag_154: 0x0 /* "--CODEGEN--":4188:4223 */ tag_155 /* "--CODEGEN--":4217:4222 */ dup3 /* "--CODEGEN--":4188:4223 */ jump(tag_156) tag_155: /* "--CODEGEN--":4240:4246 */ dup1 /* "--CODEGEN--":4235:4238 */ dup5 /* "--CODEGEN--":4228:4247 */ mstore /* "--CODEGEN--":4252:4315 */ tag_157 /* "--CODEGEN--":4308:4314 */ dup2 /* "--CODEGEN--":4301:4305 */ 0x20 /* "--CODEGEN--":4296:4299 */ dup7 /* "--CODEGEN--":4292:4306 */ add /* "--CODEGEN--":4285:4289 */ 0x20 /* "--CODEGEN--":4278:4283 */ dup7 /* "--CODEGEN--":4274:4290 */ add /* "--CODEGEN--":4252:4315 */ jump(tag_144) tag_157: /* "--CODEGEN--":4347:4376 */ tag_158 /* "--CODEGEN--":4369:4375 */ dup2 /* "--CODEGEN--":4347:4376 */ jump(tag_146) tag_158: /* "--CODEGEN--":4340:4344 */ 0x20 /* "--CODEGEN--":4335:4338 */ dup6 /* "--CODEGEN--":4331:4345 */ add /* "--CODEGEN--":4327:4377 */ add /* "--CODEGEN--":4320:4377 */ swap2 pop /* "--CODEGEN--":4168:4382 */ pop swap3 swap2 pop pop jump /* "--CODEGEN--":4389:4499 */ tag_160: /* "--CODEGEN--":4462:4493 */ tag_161 /* "--CODEGEN--":4487:4492 */ dup2 /* "--CODEGEN--":4462:4493 */ jump(tag_162) tag_161: /* "--CODEGEN--":4457:4460 */ dup3 /* "--CODEGEN--":4450:4494 */ mstore /* "--CODEGEN--":4444:4499 */ pop pop jump /* "--CODEGEN--":4506:4775 */ tag_41: 0x0 /* "--CODEGEN--":4628:4630 */ 0x20 /* "--CODEGEN--":4617:4626 */ dup3 /* "--CODEGEN--":4613:4631 */ add /* "--CODEGEN--":4605:4631 */ swap1 pop /* "--CODEGEN--":4678:4687 */ dup2 /* "--CODEGEN--":4672:4676 */ dup2 /* "--CODEGEN--":4668:4688 */ sub /* "--CODEGEN--":4664:4665 */ 0x0 /* "--CODEGEN--":4653:4662 */ dup4 /* "--CODEGEN--":4649:4666 */ add /* "--CODEGEN--":4642:4689 */ mstore /* "--CODEGEN--":4703:4765 */ tag_164 /* "--CODEGEN--":4760:4764 */ dup2 /* "--CODEGEN--":4751:4757 */ dup5 /* "--CODEGEN--":4703:4765 */ jump(tag_148) tag_164: /* "--CODEGEN--":4695:4765 */ swap1 pop /* "--CODEGEN--":4599:4775 */ swap3 swap2 pop pop jump /* "--CODEGEN--":4782:5059 */ tag_24: 0x0 /* "--CODEGEN--":4908:4910 */ 0x20 /* "--CODEGEN--":4897:4906 */ dup3 /* "--CODEGEN--":4893:4911 */ add /* "--CODEGEN--":4885:4911 */ swap1 pop /* "--CODEGEN--":4958:4967 */ dup2 /* "--CODEGEN--":4952:4956 */ dup2 /* "--CODEGEN--":4948:4968 */ sub /* "--CODEGEN--":4944:4945 */ 0x0 /* "--CODEGEN--":4933:4942 */ dup4 /* "--CODEGEN--":4929:4946 */ add /* "--CODEGEN--":4922:4969 */ mstore /* "--CODEGEN--":4983:5049 */ tag_166 /* "--CODEGEN--":5044:5048 */ dup2 /* "--CODEGEN--":5035:5041 */ dup5 /* "--CODEGEN--":4983:5049 */ jump(tag_140) tag_166: /* "--CODEGEN--":4975:5049 */ swap1 pop /* "--CODEGEN--":4879:5059 */ swap3 swap2 pop pop jump /* "--CODEGEN--":5066:5339 */ tag_30: 0x0 /* "--CODEGEN--":5190:5192 */ 0x20 /* "--CODEGEN--":5179:5188 */ dup3 /* "--CODEGEN--":5175:5193 */ add /* "--CODEGEN--":5167:5193 */ swap1 pop /* "--CODEGEN--":5240:5249 */ dup2 /* "--CODEGEN--":5234:5238 */ dup2 /* "--CODEGEN--":5230:5250 */ sub /* "--CODEGEN--":5226:5227 */ 0x0 /* "--CODEGEN--":5215:5224 */ dup4 /* "--CODEGEN--":5211:5228 */ add /* "--CODEGEN--":5204:5251 */ mstore /* "--CODEGEN--":5265:5329 */ tag_168 /* "--CODEGEN--":5324:5328 */ dup2 /* "--CODEGEN--":5315:5321 */ dup5 /* "--CODEGEN--":5265:5329 */ jump(tag_154) tag_168: /* "--CODEGEN--":5257:5329 */ swap1 pop /* "--CODEGEN--":5161:5339 */ swap3 swap2 pop pop jump /* "--CODEGEN--":5346:5539 */ tag_35: 0x0 /* "--CODEGEN--":5454:5456 */ 0x20 /* "--CODEGEN--":5443:5452 */ dup3 /* "--CODEGEN--":5439:5457 */ add /* "--CODEGEN--":5431:5457 */ swap1 pop /* "--CODEGEN--":5468:5529 */ tag_170 /* "--CODEGEN--":5526:5527 */ 0x0 /* "--CODEGEN--":5515:5524 */ dup4 /* "--CODEGEN--":5511:5528 */ add /* "--CODEGEN--":5502:5508 */ dup5 /* "--CODEGEN--":5468:5529 */ jump(tag_160) tag_170: /* "--CODEGEN--":5425:5539 */ swap3 swap2 pop pop jump /* "--CODEGEN--":5546:5802 */ tag_92: 0x0 /* "--CODEGEN--":5608:5610 */ 0x40 /* "--CODEGEN--":5602:5611 */ mload /* "--CODEGEN--":5592:5611 */ swap1 pop /* "--CODEGEN--":5646:5650 */ dup2 /* "--CODEGEN--":5638:5644 */ dup2 /* "--CODEGEN--":5634:5651 */ add /* "--CODEGEN--":5745:5751 */ dup2 /* "--CODEGEN--":5733:5743 */ dup2 /* "--CODEGEN--":5730:5752 */ lt /* "--CODEGEN--":5709:5727 */ 0xffffffffffffffff /* "--CODEGEN--":5697:5707 */ dup3 /* "--CODEGEN--":5694:5728 */ gt /* "--CODEGEN--":5691:5753 */ or /* "--CODEGEN--":5688:5690 */ iszero tag_172 jumpi /* "--CODEGEN--":5766:5767 */ 0x0 /* "--CODEGEN--":5763:5764 */ dup1 /* "--CODEGEN--":5756:5768 */ revert /* "--CODEGEN--":5688:5690 */ tag_172: /* "--CODEGEN--":5786:5796 */ dup1 /* "--CODEGEN--":5782:5784 */ 0x40 /* "--CODEGEN--":5775:5797 */ mstore /* "--CODEGEN--":5586:5802 */ pop swap2 swap1 pop jump /* "--CODEGEN--":5809:6072 */ tag_91: 0x0 /* "--CODEGEN--":5973:5991 */ 0xffffffffffffffff /* "--CODEGEN--":5965:5971 */ dup3 /* "--CODEGEN--":5962:5992 */ gt /* "--CODEGEN--":5959:5961 */ iszero tag_174 jumpi /* "--CODEGEN--":6005:6006 */ 0x0 /* "--CODEGEN--":6002:6003 */ dup1 /* "--CODEGEN--":5995:6007 */ revert /* "--CODEGEN--":5959:5961 */ tag_174: /* "--CODEGEN--":6034:6038 */ 0x20 /* "--CODEGEN--":6026:6032 */ dup3 /* "--CODEGEN--":6022:6039 */ mul /* "--CODEGEN--":6014:6039 */ swap1 pop /* "--CODEGEN--":6062:6066 */ 0x20 /* "--CODEGEN--":6056:6060 */ dup2 /* "--CODEGEN--":6052:6067 */ add /* "--CODEGEN--":6044:6067 */ swap1 pop /* "--CODEGEN--":5896:6072 */ swap2 swap1 pop jump /* "--CODEGEN--":6079:6343 */ tag_103: 0x0 /* "--CODEGEN--":6244:6262 */ 0xffffffffffffffff /* "--CODEGEN--":6236:6242 */ dup3 /* "--CODEGEN--":6233:6263 */ gt /* "--CODEGEN--":6230:6232 */ iszero tag_176 jumpi /* "--CODEGEN--":6276:6277 */ 0x0 /* "--CODEGEN--":6273:6274 */ dup1 /* "--CODEGEN--":6266:6278 */ revert /* "--CODEGEN--":6230:6232 */ tag_176: /* "--CODEGEN--":6305:6309 */ 0x20 /* "--CODEGEN--":6297:6303 */ dup3 /* "--CODEGEN--":6293:6310 */ mul /* "--CODEGEN--":6285:6310 */ swap1 pop /* "--CODEGEN--":6333:6337 */ 0x20 /* "--CODEGEN--":6327:6331 */ dup2 /* "--CODEGEN--":6323:6338 */ add /* "--CODEGEN--":6315:6338 */ swap1 pop /* "--CODEGEN--":6167:6343 */ swap2 swap1 pop jump /* "--CODEGEN--":6350:6604 */ tag_113: 0x0 /* "--CODEGEN--":6489:6507 */ 0xffffffffffffffff /* "--CODEGEN--":6481:6487 */ dup3 /* "--CODEGEN--":6478:6508 */ gt /* "--CODEGEN--":6475:6477 */ iszero tag_178 jumpi /* "--CODEGEN--":6521:6522 */ 0x0 /* "--CODEGEN--":6518:6519 */ dup1 /* "--CODEGEN--":6511:6523 */ revert /* "--CODEGEN--":6475:6477 */ tag_178: /* "--CODEGEN--":6565:6569 */ 0x1f /* "--CODEGEN--":6561:6570 */ not /* "--CODEGEN--":6554:6558 */ 0x1f /* "--CODEGEN--":6546:6552 */ dup4 /* "--CODEGEN--":6542:6559 */ add /* "--CODEGEN--":6538:6571 */ and /* "--CODEGEN--":6530:6571 */ swap1 pop /* "--CODEGEN--":6594:6598 */ 0x20 /* "--CODEGEN--":6588:6592 */ dup2 /* "--CODEGEN--":6584:6599 */ add /* "--CODEGEN--":6576:6599 */ swap1 pop /* "--CODEGEN--":6412:6604 */ swap2 swap1 pop jump /* "--CODEGEN--":6611:6866 */ tag_121: 0x0 /* "--CODEGEN--":6751:6769 */ 0xffffffffffffffff /* "--CODEGEN--":6743:6749 */ dup3 /* "--CODEGEN--":6740:6770 */ gt /* "--CODEGEN--":6737:6739 */ iszero tag_180 jumpi /* "--CODEGEN--":6783:6784 */ 0x0 /* "--CODEGEN--":6780:6781 */ dup1 /* "--CODEGEN--":6773:6785 */ revert /* "--CODEGEN--":6737:6739 */ tag_180: /* "--CODEGEN--":6827:6831 */ 0x1f /* "--CODEGEN--":6823:6832 */ not /* "--CODEGEN--":6816:6820 */ 0x1f /* "--CODEGEN--":6808:6814 */ dup4 /* "--CODEGEN--":6804:6821 */ add /* "--CODEGEN--":6800:6833 */ and /* "--CODEGEN--":6792:6833 */ swap1 pop /* "--CODEGEN--":6856:6860 */ 0x20 /* "--CODEGEN--":6850:6854 */ dup2 /* "--CODEGEN--":6846:6861 */ add /* "--CODEGEN--":6838:6861 */ swap1 pop /* "--CODEGEN--":6674:6866 */ swap2 swap1 pop jump /* "--CODEGEN--":6873:6960 */ tag_150: 0x0 /* "--CODEGEN--":6949:6954 */ dup2 /* "--CODEGEN--":6943:6955 */ mload /* "--CODEGEN--":6933:6955 */ swap1 pop /* "--CODEGEN--":6927:6960 */ swap2 swap1 pop jump /* "--CODEGEN--":6967:7058 */ tag_142: 0x0 /* "--CODEGEN--":7047:7052 */ dup2 /* "--CODEGEN--":7041:7053 */ mload /* "--CODEGEN--":7031:7053 */ swap1 pop /* "--CODEGEN--":7025:7058 */ swap2 swap1 pop jump /* "--CODEGEN--":7065:7153 */ tag_156: 0x0 /* "--CODEGEN--":7142:7147 */ dup2 /* "--CODEGEN--":7136:7148 */ mload /* "--CODEGEN--":7126:7148 */ swap1 pop /* "--CODEGEN--":7120:7153 */ swap2 swap1 pop jump /* "--CODEGEN--":7160:7239 */ tag_162: 0x0 /* "--CODEGEN--":7229:7234 */ dup2 /* "--CODEGEN--":7218:7234 */ swap1 pop /* "--CODEGEN--":7212:7239 */ swap2 swap1 pop jump /* "--CODEGEN--":7246:7325 */ tag_127: 0x0 /* "--CODEGEN--":7315:7320 */ dup2 /* "--CODEGEN--":7304:7320 */ swap1 pop /* "--CODEGEN--":7298:7325 */ swap2 swap1 pop jump /* "--CODEGEN--":7333:7478 */ tag_116: /* "--CODEGEN--":7414:7420 */ dup3 /* "--CODEGEN--":7409:7412 */ dup2 /* "--CODEGEN--":7404:7407 */ dup4 /* "--CODEGEN--":7391:7421 */ calldatacopy /* "--CODEGEN--":7470:7471 */ 0x0 /* "--CODEGEN--":7461:7467 */ dup4 /* "--CODEGEN--":7456:7459 */ dup4 /* "--CODEGEN--":7452:7468 */ add /* "--CODEGEN--":7445:7472 */ mstore /* "--CODEGEN--":7384:7478 */ pop pop pop jump /* "--CODEGEN--":7487:7755 */ tag_144: /* "--CODEGEN--":7552:7553 */ 0x0 /* "--CODEGEN--":7559:7660 */ tag_188: /* "--CODEGEN--":7573:7579 */ dup4 /* "--CODEGEN--":7570:7571 */ dup2 /* "--CODEGEN--":7567:7580 */ lt /* "--CODEGEN--":7559:7660 */ iszero tag_189 jumpi /* "--CODEGEN--":7649:7650 */ dup1 /* "--CODEGEN--":7644:7647 */ dup3 /* "--CODEGEN--":7640:7651 */ add /* "--CODEGEN--":7634:7652 */ mload /* "--CODEGEN--":7630:7631 */ dup2 /* "--CODEGEN--":7625:7628 */ dup5 /* "--CODEGEN--":7621:7632 */ add /* "--CODEGEN--":7614:7653 */ mstore /* "--CODEGEN--":7595:7597 */ 0x20 /* "--CODEGEN--":7592:7593 */ dup2 /* "--CODEGEN--":7588:7598 */ add /* "--CODEGEN--":7583:7598 */ swap1 pop /* "--CODEGEN--":7559:7660 */ jump(tag_188) tag_189: /* "--CODEGEN--":7675:7681 */ dup4 /* "--CODEGEN--":7672:7673 */ dup2 /* "--CODEGEN--":7669:7682 */ gt /* "--CODEGEN--":7666:7668 */ iszero tag_191 jumpi /* "--CODEGEN--":7740:7741 */ 0x0 /* "--CODEGEN--":7731:7737 */ dup5 /* "--CODEGEN--":7726:7729 */ dup5 /* "--CODEGEN--":7722:7738 */ add /* "--CODEGEN--":7715:7742 */ mstore /* "--CODEGEN--":7666:7668 */ tag_191: /* "--CODEGEN--":7536:7755 */ pop pop pop pop jump /* "--CODEGEN--":7763:7860 */ tag_146: 0x0 /* "--CODEGEN--":7851:7853 */ 0x1f /* "--CODEGEN--":7847:7854 */ not /* "--CODEGEN--":7842:7844 */ 0x1f /* "--CODEGEN--":7835:7840 */ dup4 /* "--CODEGEN--":7831:7845 */ add /* "--CODEGEN--":7827:7855 */ and /* "--CODEGEN--":7817:7855 */ swap1 pop /* "--CODEGEN--":7811:7860 */ swap2 swap1 pop jump auxdata: 0xa265627a7a72305820c13ebadd7c63100dbfb8b23f4cd71e360ee77691a607b09383d8fbbf4d478d3a6c6578706572696d656e74616cf50037 } ================================================ FILE: truffle/bytes/contracts/Bytes.sol ================================================ pragma solidity ^0.4.24; pragma experimental ABIEncoderV2; contract Bytes { bytes[] public data; string[] public data2; function setData(bytes[] _data) public { data = _data; } function setData2(string[] _data2) public { data2 = _data2; } function getDataItem(uint position) public view returns (bytes) { return data[position]; } } ================================================ FILE: truffle/bytes/contracts/Migrations.sol ================================================ pragma solidity ^0.4.23; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } ================================================ FILE: truffle/bytes/migrations/1_initial_migration.js ================================================ var Migrations = artifacts.require("./Migrations.sol"); module.exports = function(deployer) { deployer.deploy(Migrations); }; ================================================ FILE: truffle/bytes/scripts/.gitignore ================================================ data.json ================================================ FILE: truffle/bytes/scripts/README.md ================================================ # Scripts ## Installation ## Configuration ## Commands ### Deploy contract ### List owners ### List prices ### Item information ### Sell item ### Buy item ================================================ FILE: truffle/bytes/scripts/config.js ================================================ module.exports = { networks: { development: { provider: "http://localhost:8545" }, rsk: { provider: "http://localhost:4444" } } }; ================================================ FILE: truffle/bytes/scripts/deploy.js ================================================ const fs = require('fs'); const rskapi = require('rskapi'); const simpleabi = require('simpleabi'); const config = require('./config'); var data; try { data = require('./data.json'); } catch (err) { data = {}; } const Collectible = require('../build/contracts/Collectible.json'); const network = 'development'; const provider = config.networks[network].provider; const host = rskapi.host(provider); const bytecodes = Collectible.bytecode; const params = simpleabi.encodeValues(1000, 100); async function run() { const accounts = await host.getAccounts(); const account = accounts[0]; const tx = { from: account, data: bytecodes + params, value: 0, gas: 2000000, gasPrice: 0 } const txhash = await host.sendTransaction(tx); console.log("tx", txhash); var counter = 0; var txr = null while (counter++ < 50 && !txr) txr = await host.getTransactionReceiptByHash(txhash); console.log('contract address', txr.contractAddress); console.log('gas used', parseInt(txr.gasUsed)); if (!data.networks) data.networks = {}; if (!data.networks[network]) data.networks[network] = {}; data.networks[network].contractAddress = txr.contractAddress; const datajson = JSON.stringify(data, null, 4); fs.writeFileSync('data.json', datajson); } run(); ================================================ FILE: truffle/bytes/scripts/package.json ================================================ { "name": "scripts", "private": true, "version": "1.0.0", "description": "Game scripts", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "MIT", "dependencies": { "ethereumjs-tx": "^1.3.7", "rskapi": "0.0.10", "simpleabi": "0.0.3" } } ================================================ FILE: truffle/bytes/test/Bytes_test.js ================================================ const Bytes = artifacts.require('./Bytes.sol'); contract('Bytes', function (accounts) { /* it('set data and get item', async function () { const bytes = await Bytes.new(); await bytes.setData([ '0x01', '0x0102', '0x01022a' ]); }); it('set data2 and get item', async function () { const bytes = await Bytes.new(); await bytes.setData2([ 'adam', 'eve' ]); }); */ it('transaction', async function () { const bytes = await Bytes.new(); const txdata = { from: accounts[0], to: bytes.address, gas: "0x6691b7", gasPrice: "0x100", data: "0x9d5ef15e00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000e00000000000000000000000000000000000000000000000000000000000000001010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020102000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000301022a0000000000000000000000000000000000000000000000000000000000" }; await web3.eth.sendTransaction(txdata); const item0 = await bytes.getDataItem(0); assert.equal(item0, '0x01'); const item1 = await bytes.getDataItem(1); assert.equal(item1, '0x0102'); const item2 = await bytes.getDataItem(2); assert.equal(item2, '0x01022a'); }); }); ================================================ FILE: truffle/bytes/truffle-config.js ================================================ /* * NB: since truffle-hdwallet-provider 0.0.5 you must wrap HDWallet providers in a * function when declaring them. Failure to do so will cause commands to hang. ex: * ``` * mainnet: { * provider: function() { * return new HDWalletProvider(mnemonic, 'https://mainnet.infura.io/') * }, * network_id: '1', * gas: 4500000, * gasPrice: 10000000000, * }, */ module.exports = { // See // to customize your Truffle configuration! /* networks: { development: { host: "127.0.0.1", port: 8545, network_id: "*" // Match any network id }, regtest: { host: "127.0.0.1", port: 4444, network_id: "*" // Match any network id } } */ }; ================================================ FILE: truffle/first/contracts/ConvertLib.sol ================================================ pragma solidity ^0.4.4; library ConvertLib{ function convert(uint amount,uint conversionRate) returns (uint convertedAmount) { return amount * conversionRate; } } ================================================ FILE: truffle/first/contracts/MetaCoin.sol ================================================ pragma solidity ^0.4.4; import "./ConvertLib.sol"; // This is just a simple example of a coin-like contract. // It is not standards compatible and cannot be expected to talk to other // coin/token contracts. If you want to create a standards-compliant // token, see: https://github.com/ConsenSys/Tokens. Cheers! contract MetaCoin { mapping (address => uint) balances; event Transfer(address indexed _from, address indexed _to, uint256 _value); function MetaCoin() { balances[tx.origin] = 10000; } function sendCoin(address receiver, uint amount) returns(bool sufficient) { if (balances[msg.sender] < amount) return false; balances[msg.sender] -= amount; balances[receiver] += amount; Transfer(msg.sender, receiver, amount); return true; } function getBalanceInEth(address addr) returns(uint){ return ConvertLib.convert(getBalance(addr),2); } function getBalance(address addr) returns(uint) { return balances[addr]; } } ================================================ FILE: truffle/first/contracts/Migrations.sol ================================================ pragma solidity ^0.4.4; contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } function Migrations() { owner = msg.sender; } function setCompleted(uint completed) restricted { last_completed_migration = completed; } function upgrade(address new_address) restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } ================================================ FILE: truffle/first/migrations/1_initial_migration.js ================================================ var Migrations = artifacts.require("./Migrations.sol"); module.exports = function(deployer) { deployer.deploy(Migrations); }; ================================================ FILE: truffle/first/migrations/2_deploy_contracts.js ================================================ var ConvertLib = artifacts.require("./ConvertLib.sol"); var MetaCoin = artifacts.require("./MetaCoin.sol"); module.exports = function(deployer) { deployer.deploy(ConvertLib); deployer.link(ConvertLib, MetaCoin); deployer.deploy(MetaCoin); }; ================================================ FILE: truffle/first/test/TestMetacoin.sol ================================================ pragma solidity ^0.4.2; import "truffle/Assert.sol"; import "truffle/DeployedAddresses.sol"; import "../contracts/MetaCoin.sol"; contract TestMetacoin { function testInitialBalanceUsingDeployedContract() { MetaCoin meta = MetaCoin(DeployedAddresses.MetaCoin()); uint expected = 10000; Assert.equal(meta.getBalance(tx.origin), expected, "Owner should have 10000 MetaCoin initially"); } function testInitialBalanceWithNewMetaCoin() { MetaCoin meta = new MetaCoin(); uint expected = 10000; Assert.equal(meta.getBalance(tx.origin), expected, "Owner should have 10000 MetaCoin initially"); } } ================================================ FILE: truffle/first/test/metacoin.js ================================================ var MetaCoin = artifacts.require("./MetaCoin.sol"); contract('MetaCoin', function(accounts) { it("should put 10000 MetaCoin in the first account", function() { return MetaCoin.deployed().then(function(instance) { return instance.getBalance.call(accounts[0]); }).then(function(balance) { assert.equal(balance.valueOf(), 10000, "10000 wasn't in the first account"); }); }); it("should call a function that depends on a linked library", function() { var meta; var metaCoinBalance; var metaCoinEthBalance; return MetaCoin.deployed().then(function(instance) { meta = instance; return meta.getBalance.call(accounts[0]); }).then(function(outCoinBalance) { metaCoinBalance = outCoinBalance.toNumber(); return meta.getBalanceInEth.call(accounts[0]); }).then(function(outCoinBalanceEth) { metaCoinEthBalance = outCoinBalanceEth.toNumber(); }).then(function() { assert.equal(metaCoinEthBalance, 2 * metaCoinBalance, "Library function returned unexpected function, linkage may be broken"); }); }); it("should send coin correctly", function() { var meta; // Get initial balances of first and second account. var account_one = accounts[0]; var account_two = accounts[1]; var account_one_starting_balance; var account_two_starting_balance; var account_one_ending_balance; var account_two_ending_balance; var amount = 10; return MetaCoin.deployed().then(function(instance) { meta = instance; return meta.getBalance.call(account_one); }).then(function(balance) { account_one_starting_balance = balance.toNumber(); return meta.getBalance.call(account_two); }).then(function(balance) { account_two_starting_balance = balance.toNumber(); return meta.sendCoin(account_two, amount, {from: account_one}); }).then(function() { return meta.getBalance.call(account_one); }).then(function(balance) { account_one_ending_balance = balance.toNumber(); return meta.getBalance.call(account_two); }).then(function(balance) { account_two_ending_balance = balance.toNumber(); assert.equal(account_one_ending_balance, account_one_starting_balance - amount, "Amount wasn't correctly taken from the sender"); assert.equal(account_two_ending_balance, account_two_starting_balance + amount, "Amount wasn't correctly sent to the receiver"); }); }); }); ================================================ FILE: truffle/first/truffle.js ================================================ module.exports = { networks: { development: { host: "localhost", port: 8545, network_id: "*" // Match any network id } } }; ================================================ FILE: truffle/kc1/Ballot.txt ================================================ - Votar por si una propuesta - Evitar voto doble - Saber cuantos votos si tiene una propuesta - Solo un grupo de cuentas pueda votar ================================================ FILE: truffle/kc1/contracts/Ballot.sol ================================================ pragma solidity ^0.4.24; contract Ballot { mapping (uint => address[]) public votes; address[] public members; constructor(address[] _members) public { members = _members; } function isMember(address user) private view returns (bool) { for (uint k = 0; k < members.length; k++) if (user == members[k]) return true; return false; } modifier onlyMember() { require(isMember(msg.sender)); _; } function vote(uint id) public onlyMember() { address[] storage vts = votes[id]; for (uint k = 0; k < vts.length; k++) if (vts[k] == msg.sender) return; vts.push(msg.sender); } function noVotes(uint id) public view returns (uint) { return votes[id].length; } } ================================================ FILE: truffle/kc1/contracts/Counter.sol ================================================ pragma solidity ^0.4.24; contract Counter { uint public counter; constructor() public { counter = 1; } function increment() public { counter++; } function add(uint value) public { counter += value; } } ================================================ FILE: truffle/kc1/contracts/Empty.sol ================================================ pragma solidity >=0.4.21 <0.6.0; contract Empty { } ================================================ FILE: truffle/kc1/contracts/Migrations.sol ================================================ pragma solidity ^0.4.23; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } ================================================ FILE: truffle/kc1/migrations/1_initial_migration.js ================================================ var Migrations = artifacts.require("./Migrations.sol"); module.exports = function(deployer) { deployer.deploy(Migrations); }; ================================================ FILE: truffle/kc1/migrations/2_deploy_contracts.js ================================================ var Empty = artifacts.require("Empty"); var Counter = artifacts.require("Counter"); //var Ballot = artifacts.require("Ballot"); module.exports = function(deployer) { deployer.deploy(Empty); deployer.deploy(Counter); //deployer.deploy(Ballot); }; ================================================ FILE: truffle/kc1/test/Ballot_test.js ================================================ const Ballot = artifacts.require('Ballot'); async function expectThrow (promise) { try { await promise; } catch (error) { return; } assert.fail('Expected throw not received'); } contract('Ballot', function (accounts) { const members = [ accounts[0], accounts[1], accounts[2] ]; beforeEach(async function () { this.ballot = await Ballot.new(members); }); it('no vote for new proposal', async function () { const novotes = await this.ballot.noVotes(1); assert.equal(novotes, 0); }); it('vote proposal', async function () { await this.ballot.vote(1); const novotes = await this.ballot.noVotes(1); assert.equal(novotes, 1); }); it('vote proposal twice', async function () { await this.ballot.vote(1, { from: accounts[0] }); await this.ballot.vote(1, { from: accounts[1] }); const novotes = await this.ballot.noVotes(1); assert.equal(novotes, 2); }); it('cannot vote twice with the same account', async function () { await this.ballot.vote(1); await this.ballot.vote(1); const novotes = await this.ballot.noVotes(1); assert.equal(novotes, 1); }); it('non member cannot vote', async function () { await expectThrow(this.ballot.vote(1, { from: accounts[4] })); }); }); ================================================ FILE: truffle/kc1/test/Counter_test.js ================================================ const Counter = artifacts.require("Counter"); contract('Counter', function (accounts) { //console.log(accounts); beforeEach(async function () { this.counter = await Counter.new(); }); it('counter is one', async function () { //console.log(counter.address); const c = await this.counter.counter(); //console.log(c.toNumber()); assert.equal(c, 1); }); it('increment', async function () { await this.counter.increment(); const c = await this.counter.counter(); assert.equal(c, 2); }); it('add', async function () { await this.counter.increment(); await this.counter.add(40); const c = await this.counter.counter(); assert.equal(c, 42); }); }); ================================================ FILE: truffle/kc1/truffle-config.js ================================================ /* * NB: since truffle-hdwallet-provider 0.0.5 you must wrap HDWallet providers in a * function when declaring them. Failure to do so will cause commands to hang. ex: * ``` * mainnet: { * provider: function() { * return new HDWalletProvider(mnemonic, 'https://mainnet.infura.io/') * }, * network_id: '1', * gas: 4500000, * gasPrice: 10000000000, * }, */ module.exports = { // See // to customize your Truffle configuration! networks: { development: { host: "127.0.0.1", port: 8545, network_id: "*" // Match any network id } } }; ================================================ FILE: truffle/mug1/contracts/Counter.sol ================================================ contract Counter { uint public counter; function increment() public { counter++; } function add(uint value) public { counter += value; } function process(bytes data) public { } function add(uint value, uint value2) public { counter += value + value2; } } ================================================ FILE: truffle/mug1/contracts/Empty.sol ================================================ contract Empty { } ================================================ FILE: truffle/mug1/contracts/Migrations.sol ================================================ pragma solidity ^0.4.23; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } ================================================ FILE: truffle/mug1/migrations/1_initial_migration.js ================================================ var Migrations = artifacts.require("./Migrations.sol"); module.exports = function(deployer) { deployer.deploy(Migrations); }; ================================================ FILE: truffle/mug1/migrations/2_deploy_contracts.js ================================================ var Empty = artifacts.require("./Empty.sol"); module.exports = function(deployer) { deployer.deploy(Empty); }; ================================================ FILE: truffle/mug1/test/counter_test.js ================================================ var Counter = artifacts.require('./Counter.sol'); contract('Counter', function (accounts) { console.log(accounts); var contract; beforeEach(async function() { contract = await Counter.new(); console.log('contract deployed', contract.address); }); it('create contract', async function () { assert.equal(await contract.counter(), 0); }); it('increment counter', async function () { await contract.increment(); assert.equal(await contract.counter(), 1); }); it('add counter', async function () { await contract.increment(); await contract.increment(); await contract.add(40, { from: accounts[1], gasPrice: 1, gas: 3000000 }); // web3.eth.getAccounts(); assert.equal(await contract.counter(), 42); }); it('add counter with two arguments', async function () { await contract.increment(); await contract.increment(); // await contract.add(20, 20, { from: accounts[1], gasPrice: 1, gas: 3000000 }); // assert.equal(await contract.counter(), 42); // await contract.process("0x01020304"); }); }); ================================================ FILE: truffle/mug1/truffle-config.js ================================================ module.exports = { networks: { development: { host: "127.0.0.1", port: 8545, network_id: "*" // Match any network id } } }; ================================================ FILE: truffle/mug2/contracts/Counter.sol ================================================ pragma solidity ^0.4.24; contract Counter { uint public counter; constructor() public { counter = 1; } function increment() public { counter++; } function add(uint val) public { counter += val; } } ================================================ FILE: truffle/mug2/contracts/Migrations.sol ================================================ pragma solidity ^0.4.23; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } ================================================ FILE: truffle/mug2/contracts/Token.sol ================================================ pragma solidity ^0.4.24; contract Token { mapping (address => uint) balances; address owner; constructor(uint initial) public { balances[msg.sender] = initial; owner = msg.sender; } function balanceOf(address account) public view returns (uint) { return balances[account]; } function transfer(address receiver, uint amount) public { require(balances[msg.sender] >= amount); balances[msg.sender] -= amount; balances[receiver] += amount; } modifier onlyOwner() { require(msg.sender == owner); _; } function emit(uint amount) onlyOwner public { balances[msg.sender] += amount; } } ================================================ FILE: truffle/mug2/migrations/1_initial_migration.js ================================================ var Migrations = artifacts.require("./Migrations.sol"); module.exports = function(deployer) { deployer.deploy(Migrations); }; ================================================ FILE: truffle/mug2/migrations/2_deploy_contracts.js ================================================ var Counter = artifacts.require("./Counter.sol"); module.exports = function (deployer) { deployer.deploy(Counter); }; ================================================ FILE: truffle/mug2/test/Counter_test.js ================================================ const Counter = artifacts.require('./Counter.sol'); contract('Counter', function (accounts) { // console.dir(accounts); var counter; beforeEach(async function() { counter = await Counter.new(); }); describe('first tests', function () { it('initial counter', async function () { const c1 = await counter.counter(); assert.equal(c1, 1); }); it('increment', async function () { await counter.increment(); const c1 = await counter.counter(); assert.equal(c1, 2); }); it('add', async function () { await counter.increment(); await counter.add(40); const c1 = await counter.counter(); assert.equal(c1, 42); }); }); }); ================================================ FILE: truffle/mug2/test/Token_test.js ================================================ const Token = artifacts.require('./Token.sol'); async function expectThrow (promise) { try { await promise; } catch (error) { return; } assert.fail('Expected throw not received'); } contract('Token', function (accounts) { it('create token with initial balance', async function () { var token = await Token.new(10000); const balance = await token.balanceOf(accounts[0]); assert.equal(balance, 10000); }); it('transfer tokens', async function () { var token = await Token.new(10000); await token.transfer(accounts[1], 1000); const balance = await token.balanceOf(accounts[0]); assert.equal(balance, 9000); const balance2 = await token.balanceOf(accounts[1]); assert.equal(balance2, 1000); }); it('cannot transfer tokens if not enough balance', async function () { var token = await Token.new(10000); expectThrow(token.transfer(accounts[1], 1000, { from: accounts[2] })); const balance = await token.balanceOf(accounts[0]); assert.equal(balance, 10000); const balance2 = await token.balanceOf(accounts[1]); assert.equal(balance2, 0); const balance3 = await token.balanceOf(accounts[2]); assert.equal(balance3, 0); }); it('owner emits new tokens', async function () { var token = await Token.new(10000); await token.emit(1000); const balance = await token.balanceOf(accounts[0]); assert.equal(balance, 11000); }); it('not owner cannot emit new tokens', async function () { var token = await Token.new(10000); expectThrow(token.emit(1000, { from: accounts[1] })); const balance = await token.balanceOf(accounts[0]); assert.equal(balance, 10000); const balance2 = await token.balanceOf(accounts[1]); assert.equal(balance2, 0); }); }); ================================================ FILE: truffle/mug2/truffle-config.js ================================================ /* * NB: since truffle-hdwallet-provider 0.0.5 you must wrap HDWallet providers in a * function when declaring them. Failure to do so will cause commands to hang. ex: * ``` * mainnet: { * provider: function() { * return new HDWalletProvider(mnemonic, 'https://mainnet.infura.io/') * }, * network_id: '1', * gas: 4500000, * gasPrice: 10000000000, * }, */ module.exports = { networks: { development: { host: "127.0.0.1", port: 8545, network_id: "*" // Match any network id }, testnet: { host: "127.0.0.1", port: 8545, network_id: "*" // Match any network id }, mainnet: { host: "127.0.0.1", port: 8545, network_id: "*" // Match any network id } } }; ================================================ FILE: truffle/oz/contracts/Bounty.sol ================================================ pragma solidity ^0.4.18; import './payment/PullPayment.sol'; import './lifecycle/Destructible.sol'; /** * @title Bounty * @dev This bounty will pay out to a researcher if they break invariant logic of the contract. */ contract Bounty is PullPayment, Destructible { bool public claimed; mapping(address => address) public researchers; event TargetCreated(address createdAddress); /** * @dev Fallback function allowing the contract to receive funds, if they haven't already been claimed. */ function() external payable { require(!claimed); } /** * @dev Create and deploy the target contract (extension of Target contract), and sets the * msg.sender as a researcher * @return A target contract */ function createTarget() public returns(Target) { Target target = Target(deployContract()); researchers[target] = msg.sender; TargetCreated(target); return target; } /** * @dev Internal function to deploy the target contract. * @return A target contract address */ function deployContract() internal returns(address); /** * @dev Sends the contract funds to the researcher that proved the contract is broken. * @param target contract */ function claim(Target target) public { address researcher = researchers[target]; require(researcher != 0); // Check Target contract invariants require(!target.checkInvariant()); asyncSend(researcher, this.balance); claimed = true; } } /** * @title Target * @dev Your main contract should inherit from this class and implement the checkInvariant method. */ contract Target { /** * @dev Checks all values a contract assumes to be true all the time. If this function returns * false, the contract is broken in some way and is in an inconsistent state. * In order to win the bounty, security researchers will try to cause this broken state. * @return True if all invariant values are correct, false otherwise. */ function checkInvariant() public returns(bool); } ================================================ FILE: truffle/oz/contracts/ConvertLib.sol ================================================ pragma solidity ^0.4.4; library ConvertLib{ function convert(uint amount,uint conversionRate) returns (uint convertedAmount) { return amount * conversionRate; } } ================================================ FILE: truffle/oz/contracts/DayLimit.sol ================================================ pragma solidity ^0.4.18; /** * @title DayLimit * @dev Base contract that enables methods to be protected by placing a linear limit (specifiable) * on a particular resource per calendar day. Is multiowned to allow the limit to be altered. */ contract DayLimit { uint256 public dailyLimit; uint256 public spentToday; uint256 public lastDay; /** * @dev Constructor that sets the passed value as a dailyLimit. * @param _limit uint256 to represent the daily limit. */ function DayLimit(uint256 _limit) public { dailyLimit = _limit; lastDay = today(); } /** * @dev sets the daily limit. Does not alter the amount already spent today. * @param _newLimit uint256 to represent the new limit. */ function _setDailyLimit(uint256 _newLimit) internal { dailyLimit = _newLimit; } /** * @dev Resets the amount already spent today. */ function _resetSpentToday() internal { spentToday = 0; } /** * @dev Checks to see if there is enough resource to spend today. If true, the resource may be expended. * @param _value uint256 representing the amount of resource to spend. * @return A boolean that is True if the resource was spent and false otherwise. */ function underLimit(uint256 _value) internal returns (bool) { // reset the spend limit if we're on a different day to last time. if (today() > lastDay) { spentToday = 0; lastDay = today(); } // check to see if there's enough left - if so, subtract and return true. // overflow protection // dailyLimit check if (spentToday + _value >= spentToday && spentToday + _value <= dailyLimit) { spentToday += _value; return true; } return false; } /** * @dev Private function to determine today's index * @return uint256 of today's index. */ function today() private view returns (uint256) { return now / 1 days; } /** * @dev Simple modifier for daily limit. */ modifier limitedDaily(uint256 _value) { require(underLimit(_value)); _; } } ================================================ FILE: truffle/oz/contracts/ECRecovery.sol ================================================ pragma solidity ^0.4.18; /** * @title Eliptic curve signature operations * * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d */ library ECRecovery { /** * @dev Recover signer address from a message by using his signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param sig bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes sig) public pure returns (address) { bytes32 r; bytes32 s; uint8 v; //Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } } } ================================================ FILE: truffle/oz/contracts/LimitBalance.sol ================================================ pragma solidity ^0.4.18; /** * @title LimitBalance * @dev Simple contract to limit the balance of child contract. * @dev Note this doesn't prevent other contracts to send funds by using selfdestruct(address); * @dev See: https://github.com/ConsenSys/smart-contract-best-practices#remember-that-ether-can-be-forcibly-sent-to-an-account */ contract LimitBalance { uint256 public limit; /** * @dev Constructor that sets the passed value as a limit. * @param _limit uint256 to represent the limit. */ function LimitBalance(uint256 _limit) public { limit = _limit; } /** * @dev Checks if limit was reached. Case true, it throws. */ modifier limitedPayable() { require(this.balance <= limit); _; } } ================================================ FILE: truffle/oz/contracts/MerkleProof.sol ================================================ pragma solidity ^0.4.18; /* * @title MerkleProof * @dev Merkle proof verification * @note Based on https://github.com/ameensol/merkle-tree-solidity/blob/master/src/MerkleProof.sol */ library MerkleProof { /* * @dev Verifies a Merkle proof proving the existence of a leaf in a Merkle tree. Assumes that each pair of leaves * and each pair of pre-images is sorted. * @param _proof Merkle proof containing sibling hashes on the branch from the leaf to the root of the Merkle tree * @param _root Merkle root * @param _leaf Leaf of Merkle tree */ function verifyProof(bytes _proof, bytes32 _root, bytes32 _leaf) public pure returns (bool) { // Check if proof length is a multiple of 32 if (_proof.length % 32 != 0) return false; bytes32 proofElement; bytes32 computedHash = _leaf; for (uint256 i = 32; i <= _proof.length; i += 32) { assembly { // Load the current element of the proof proofElement := mload(add(_proof, i)) } if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(proofElement, computedHash); } } // Check if the computed hash (root) is equal to the provided root return computedHash == _root; } } ================================================ FILE: truffle/oz/contracts/MetaCoin.sol ================================================ pragma solidity ^0.4.4; import "./ConvertLib.sol"; // This is just a simple example of a coin-like contract. // It is not standards compatible and cannot be expected to talk to other // coin/token contracts. If you want to create a standards-compliant // token, see: https://github.com/ConsenSys/Tokens. Cheers! contract MetaCoin { mapping (address => uint) balances; event Transfer(address indexed _from, address indexed _to, uint256 _value); function MetaCoin() { balances[tx.origin] = 10000; } function sendCoin(address receiver, uint amount) returns(bool sufficient) { if (balances[msg.sender] < amount) return false; balances[msg.sender] -= amount; balances[receiver] += amount; Transfer(msg.sender, receiver, amount); return true; } function getBalanceInEth(address addr) returns(uint){ return ConvertLib.convert(getBalance(addr),2); } function getBalance(address addr) returns(uint) { return balances[addr]; } } ================================================ FILE: truffle/oz/contracts/Migrations.sol ================================================ pragma solidity ^0.4.4; contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } function Migrations() { owner = msg.sender; } function setCompleted(uint completed) restricted { last_completed_migration = completed; } function upgrade(address new_address) restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } ================================================ FILE: truffle/oz/contracts/ReentrancyGuard.sol ================================================ pragma solidity ^0.4.18; /** * @title Helps contracts guard agains rentrancy attacks. * @author Remco Bloemen * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /** * @dev We use a single lock for the whole contract. */ bool private rentrancy_lock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one nonReentrant function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and a `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!rentrancy_lock); rentrancy_lock = true; _; rentrancy_lock = false; } } ================================================ FILE: truffle/oz/contracts/crowdsale/CappedCrowdsale.sol ================================================ pragma solidity ^0.4.18; import '../math/SafeMath.sol'; import './Crowdsale.sol'; /** * @title CappedCrowdsale * @dev Extension of Crowdsale with a max amount of funds raised */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; function CappedCrowdsale(uint256 _cap) public { require(_cap > 0); cap = _cap; } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal view returns (bool) { bool withinCap = weiRaised.add(msg.value) <= cap; return super.validPurchase() && withinCap; } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { bool capReached = weiRaised >= cap; return super.hasEnded() || capReached; } } ================================================ FILE: truffle/oz/contracts/crowdsale/Crowdsale.sol ================================================ pragma solidity ^0.4.18; import '../token/MintableToken.sol'; import '../math/SafeMath.sol'; /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint256; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); token = createTokenContract(); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } } ================================================ FILE: truffle/oz/contracts/crowdsale/FinalizableCrowdsale.sol ================================================ pragma solidity ^0.4.18; import '../math/SafeMath.sol'; import '../ownership/Ownable.sol'; import './Crowdsale.sol'; /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } ================================================ FILE: truffle/oz/contracts/crowdsale/RefundVault.sol ================================================ pragma solidity ^0.4.18; import '../math/SafeMath.sol'; import '../ownership/Ownable.sol'; /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } ================================================ FILE: truffle/oz/contracts/crowdsale/RefundableCrowdsale.sol ================================================ pragma solidity ^0.4.18; import '../math/SafeMath.sol'; import './FinalizableCrowdsale.sol'; import './RefundVault.sol'; /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * Uses a RefundVault as the crowdsale's vault. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; function RefundableCrowdsale(uint256 _goal) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } // We're overriding the fund forwarding from Crowdsale. // In addition to sending the funds, we want to call // the RefundVault deposit function function forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } // if crowdsale is unsuccessful, investors can claim refunds here function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } // vault finalization task, called when owner calls finalize() function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } function goalReached() public view returns (bool) { return weiRaised >= goal; } } ================================================ FILE: truffle/oz/contracts/examples/SampleCrowdsale.sol ================================================ pragma solidity ^0.4.18; import "../crowdsale/CappedCrowdsale.sol"; import "../crowdsale/RefundableCrowdsale.sol"; import "../token/MintableToken.sol"; /** * @title SampleCrowdsaleToken * @dev Very simple ERC20 Token that can be minted. * It is meant to be used in a crowdsale contract. */ contract SampleCrowdsaleToken is MintableToken { string public constant name = "Sample Crowdsale Token"; string public constant symbol = "SCT"; uint8 public constant decimals = 18; } /** * @title SampleCrowdsale * @dev This is an example of a fully fledged crowdsale. * The way to add new features to a base crowdsale is by multiple inheritance. * In this example we are providing following extensions: * CappedCrowdsale - sets a max boundary for raised funds * RefundableCrowdsale - set a min goal to be reached and returns funds if it's not met * * After adding multiple features it's good practice to run integration tests * to ensure that subcontracts works together as intended. */ contract SampleCrowdsale is CappedCrowdsale, RefundableCrowdsale { function SampleCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _goal, uint256 _cap, address _wallet) public CappedCrowdsale(_cap) FinalizableCrowdsale() RefundableCrowdsale(_goal) Crowdsale(_startTime, _endTime, _rate, _wallet) { //As goal needs to be met for a successful crowdsale //the value needs to less or equal than a cap which is limit for accepted funds require(_goal <= _cap); } function createTokenContract() internal returns (MintableToken) { return new SampleCrowdsaleToken(); } } ================================================ FILE: truffle/oz/contracts/examples/SimpleToken.sol ================================================ pragma solidity ^0.4.18; import "../token/StandardToken.sol"; /** * @title SimpleToken * @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator. * Note they can later distribute these tokens as they wish using `transfer` and other * `StandardToken` functions. */ contract SimpleToken is StandardToken { string public constant name = "SimpleToken"; string public constant symbol = "SIM"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 10000 * (10 ** uint256(decimals)); /** * @dev Constructor that gives msg.sender all of existing tokens. */ function SimpleToken() public { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } } ================================================ FILE: truffle/oz/contracts/helpers/BasicTokenMock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/token/BasicToken.sol'; // mock class using BasicToken contract BasicTokenMock is BasicToken { function BasicTokenMock(address initialAccount, uint256 initialBalance) public { balances[initialAccount] = initialBalance; totalSupply = initialBalance; } } ================================================ FILE: truffle/oz/contracts/helpers/BurnableTokenMock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/token/BurnableToken.sol'; contract BurnableTokenMock is BurnableToken { function BurnableTokenMock(address initialAccount, uint initialBalance) public { balances[initialAccount] = initialBalance; totalSupply = initialBalance; } } ================================================ FILE: truffle/oz/contracts/helpers/CappedCrowdsaleImpl.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/crowdsale/CappedCrowdsale.sol'; contract CappedCrowdsaleImpl is CappedCrowdsale { function CappedCrowdsaleImpl ( uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _cap ) public Crowdsale(_startTime, _endTime, _rate, _wallet) CappedCrowdsale(_cap) { } } ================================================ FILE: truffle/oz/contracts/helpers/DayLimitMock.sol ================================================ pragma solidity ^0.4.18; import "../../contracts/DayLimit.sol"; contract DayLimitMock is DayLimit { uint256 public totalSpending; function DayLimitMock(uint256 _value) public DayLimit(_value) { totalSpending = 0; } function attemptSpend(uint256 _value) external limitedDaily(_value) { totalSpending += _value; } function setDailyLimit(uint256 _newLimit) external { _setDailyLimit(_newLimit); } function resetSpentToday() external { _resetSpentToday(); } } ================================================ FILE: truffle/oz/contracts/helpers/DetailedERC20Mock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/token/StandardToken.sol'; import '../../contracts/token/DetailedERC20.sol'; contract DetailedERC20Mock is StandardToken, DetailedERC20 { function DetailedERC20Mock(string _name, string _symbol, uint8 _decimals) DetailedERC20(_name, _symbol, _decimals) public {} } ================================================ FILE: truffle/oz/contracts/helpers/ERC23TokenMock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/token/BasicToken.sol'; contract ERC23ContractInterface { function tokenFallback(address _from, uint256 _value, bytes _data) external; } contract ERC23TokenMock is BasicToken { function ERC23TokenMock(address initialAccount, uint256 initialBalance) public { balances[initialAccount] = initialBalance; totalSupply = initialBalance; } // ERC23 compatible transfer function (except the name) function transferERC23(address _to, uint256 _value, bytes _data) public returns (bool success) { transfer(_to, _value); bool is_contract = false; assembly { is_contract := not(iszero(extcodesize(_to))) } if(is_contract) { ERC23ContractInterface receiver = ERC23ContractInterface(_to); receiver.tokenFallback(msg.sender, _value, _data); } return true; } } ================================================ FILE: truffle/oz/contracts/helpers/EVMRevert.js ================================================ export default 'revert' ================================================ FILE: truffle/oz/contracts/helpers/EVMThrow.js ================================================ export default 'invalid opcode' ================================================ FILE: truffle/oz/contracts/helpers/FinalizableCrowdsaleImpl.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/crowdsale/FinalizableCrowdsale.sol'; contract FinalizableCrowdsaleImpl is FinalizableCrowdsale { function FinalizableCrowdsaleImpl ( uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet ) public Crowdsale(_startTime, _endTime, _rate, _wallet) FinalizableCrowdsale() { } } ================================================ FILE: truffle/oz/contracts/helpers/ForceEther.sol ================================================ pragma solidity ^0.4.18; // @title Force Ether into a contract. // @notice even // if the contract is not payable. // @notice To use, construct the contract with the target as argument. // @author Remco Bloemen contract ForceEther { function ForceEther() public payable { } function destroyAndSend(address _recipient) public { selfdestruct(_recipient); } } ================================================ FILE: truffle/oz/contracts/helpers/HasNoEtherTest.sol ================================================ pragma solidity ^0.4.18; import "../../contracts/ownership/HasNoEther.sol"; contract HasNoEtherTest is HasNoEther { // Constructor with explicit payable — should still fail function HasNoEtherTest() public payable { } } ================================================ FILE: truffle/oz/contracts/helpers/InsecureTargetBounty.sol ================================================ pragma solidity ^0.4.18; import {Bounty, Target} from "../../contracts/Bounty.sol"; contract InsecureTargetMock is Target { function checkInvariant() public returns(bool){ return false; } } contract InsecureTargetBounty is Bounty { function deployContract() internal returns (address) { return new InsecureTargetMock(); } } ================================================ FILE: truffle/oz/contracts/helpers/LimitBalanceMock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/LimitBalance.sol'; // mock class using LimitBalance contract LimitBalanceMock is LimitBalance(1000) { function limitedDeposit() public payable limitedPayable { } } ================================================ FILE: truffle/oz/contracts/helpers/PausableMock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/lifecycle/Pausable.sol'; // mock class using Pausable contract PausableMock is Pausable { bool public drasticMeasureTaken; uint256 public count; function PausableMock() public { drasticMeasureTaken = false; count = 0; } function normalProcess() external whenNotPaused { count++; } function drasticMeasure() external whenPaused { drasticMeasureTaken = true; } } ================================================ FILE: truffle/oz/contracts/helpers/PausableTokenMock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/token/PausableToken.sol'; // mock class using PausableToken contract PausableTokenMock is PausableToken { function PausableTokenMock(address initialAccount, uint initialBalance) public { balances[initialAccount] = initialBalance; } } ================================================ FILE: truffle/oz/contracts/helpers/PullPaymentMock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/payment/PullPayment.sol'; // mock class using PullPayment contract PullPaymentMock is PullPayment { function PullPaymentMock() public payable { } // test helper function to call asyncSend function callSend(address dest, uint256 amount) public { asyncSend(dest, amount); } } ================================================ FILE: truffle/oz/contracts/helpers/ReentrancyAttack.sol ================================================ pragma solidity ^0.4.18; contract ReentrancyAttack { function callSender(bytes4 data) public { require(msg.sender.call(data)); } } ================================================ FILE: truffle/oz/contracts/helpers/ReentrancyMock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/ReentrancyGuard.sol'; import './ReentrancyAttack.sol'; contract ReentrancyMock is ReentrancyGuard { uint256 public counter; function ReentrancyMock() public { counter = 0; } function count() private { counter += 1; } function countLocalRecursive(uint256 n) public nonReentrant { if(n > 0) { count(); countLocalRecursive(n - 1); } } function countThisRecursive(uint256 n) public nonReentrant { bytes4 func = bytes4(keccak256("countThisRecursive(uint256)")); if(n > 0) { count(); bool result = this.call(func, n - 1); require(result == true); } } function countAndCall(ReentrancyAttack attacker) public nonReentrant { count(); bytes4 func = bytes4(keccak256("callback()")); attacker.callSender(func); } function callback() external nonReentrant { count(); } } ================================================ FILE: truffle/oz/contracts/helpers/RefundableCrowdsaleImpl.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/crowdsale/RefundableCrowdsale.sol'; contract RefundableCrowdsaleImpl is RefundableCrowdsale { function RefundableCrowdsaleImpl ( uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _goal ) public Crowdsale(_startTime, _endTime, _rate, _wallet) RefundableCrowdsale(_goal) { } } ================================================ FILE: truffle/oz/contracts/helpers/SafeERC20Helper.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/token/ERC20.sol'; import '../../contracts/token/SafeERC20.sol'; contract ERC20FailingMock is ERC20 { function transfer(address, uint256) public returns (bool) { return false; } function transferFrom(address, address, uint256) public returns (bool) { return false; } function approve(address, uint256) public returns (bool) { return false; } function balanceOf(address) public constant returns (uint256) { return 0; } function allowance(address, address) public constant returns (uint256) { return 0; } } contract ERC20SucceedingMock is ERC20 { function transfer(address, uint256) public returns (bool) { return true; } function transferFrom(address, address, uint256) public returns (bool) { return true; } function approve(address, uint256) public returns (bool) { return true; } function balanceOf(address) public constant returns (uint256) { return 0; } function allowance(address, address) public constant returns (uint256) { return 0; } } contract SafeERC20Helper { using SafeERC20 for ERC20; ERC20 failing; ERC20 succeeding; function SafeERC20Helper() public { failing = new ERC20FailingMock(); succeeding = new ERC20SucceedingMock(); } function doFailingTransfer() public { failing.safeTransfer(0, 0); } function doFailingTransferFrom() public { failing.safeTransferFrom(0, 0, 0); } function doFailingApprove() public { failing.safeApprove(0, 0); } function doSucceedingTransfer() public { succeeding.safeTransfer(0, 0); } function doSucceedingTransferFrom() public { succeeding.safeTransferFrom(0, 0, 0); } function doSucceedingApprove() public { succeeding.safeApprove(0, 0); } } ================================================ FILE: truffle/oz/contracts/helpers/SafeMathMock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/math/SafeMath.sol'; contract SafeMathMock { uint256 public result; function multiply(uint256 a, uint256 b) public { result = SafeMath.mul(a, b); } function subtract(uint256 a, uint256 b) public { result = SafeMath.sub(a, b); } function add(uint256 a, uint256 b) public { result = SafeMath.add(a, b); } } ================================================ FILE: truffle/oz/contracts/helpers/SecureTargetBounty.sol ================================================ pragma solidity ^0.4.18; import {Bounty, Target} from "../../contracts/Bounty.sol"; contract SecureTargetMock is Target { function checkInvariant() public returns(bool) { return true; } } contract SecureTargetBounty is Bounty { function deployContract() internal returns (address) { return new SecureTargetMock(); } } ================================================ FILE: truffle/oz/contracts/helpers/SplitPaymentMock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/payment/SplitPayment.sol'; // mock class using SplitPayment contract SplitPaymentMock is SplitPayment { function SplitPaymentMock(address[] _payees, uint256[] _shares) public SplitPayment(_payees, _shares) payable {} function () external payable {} } ================================================ FILE: truffle/oz/contracts/helpers/StandardTokenMock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/token/StandardToken.sol'; // mock class using StandardToken contract StandardTokenMock is StandardToken { function StandardTokenMock(address initialAccount, uint256 initialBalance) public { balances[initialAccount] = initialBalance; totalSupply = initialBalance; } } ================================================ FILE: truffle/oz/contracts/helpers/advanceToBlock.js ================================================ export function advanceBlock() { return new Promise((resolve, reject) => { web3.currentProvider.sendAsync({ jsonrpc: '2.0', method: 'evm_mine', id: Date.now(), }, (err, res) => { return err ? reject(err) : resolve(res) }) }) } // Advances the block number so that the last mined block is `number`. export default async function advanceToBlock(number) { if (web3.eth.blockNumber > number) { throw Error(`block number ${number} is in the past (current is ${web3.eth.blockNumber})`) } while (web3.eth.blockNumber < number) { await advanceBlock() } } ================================================ FILE: truffle/oz/contracts/helpers/assertJump.js ================================================ module.exports = function(error) { assert.isAbove(error.message.search('invalid opcode'), -1, 'Invalid opcode error must be returned'); } ================================================ FILE: truffle/oz/contracts/helpers/assertRevert.js ================================================ module.exports = function(error) { assert.isAbove(error.message.search('revert'), -1, 'Error containing "revert" must be returned'); } ================================================ FILE: truffle/oz/contracts/helpers/ether.js ================================================ export default function ether(n) { return new web3.BigNumber(web3.toWei(n, 'ether')) } ================================================ FILE: truffle/oz/contracts/helpers/expectThrow.js ================================================ export default async promise => { try { await promise; } catch (error) { // TODO: Check jump destination to destinguish between a throw // and an actual invalid jump. const invalidOpcode = error.message.search('invalid opcode') >= 0; // TODO: When we contract A calls contract B, and B throws, instead // of an 'invalid jump', we get an 'out of gas' error. How do // we distinguish this from an actual out of gas event? (The // testrpc log actually show an 'invalid jump' event.) const outOfGas = error.message.search('out of gas') >= 0; const revert = error.message.search('revert') >= 0; assert( invalidOpcode || outOfGas || revert, "Expected throw, got '" + error + "' instead", ); return; } assert.fail('Expected throw not received'); }; ================================================ FILE: truffle/oz/contracts/helpers/hashMessage.js ================================================ import utils from 'ethereumjs-util'; // Hash and add same prefix to the hash that testrpc use. module.exports = function(message) { const messageHex = new Buffer(utils.sha3(message).toString('hex'), 'hex'); const prefix = utils.toBuffer('\u0019Ethereum Signed Message:\n' + messageHex.length.toString()); return utils.bufferToHex( utils.sha3(Buffer.concat([prefix, messageHex])) ); }; ================================================ FILE: truffle/oz/contracts/helpers/increaseTime.js ================================================ import latestTime from './latestTime' // Increases testrpc time by the passed duration in seconds export default function increaseTime(duration) { const id = Date.now() return new Promise((resolve, reject) => { web3.currentProvider.sendAsync({ jsonrpc: '2.0', method: 'evm_increaseTime', params: [duration], id: id, }, err1 => { if (err1) return reject(err1) web3.currentProvider.sendAsync({ jsonrpc: '2.0', method: 'evm_mine', id: id+1, }, (err2, res) => { return err2 ? reject(err2) : resolve(res) }) }) }) } /** * Beware that due to the need of calling two separate testrpc methods and rpc calls overhead * it's hard to increase time precisely to a target point so design your test to tolerate * small fluctuations from time to time. * * @param target time in seconds */ export function increaseTimeTo(target) { let now = latestTime(); if (target < now) throw Error(`Cannot increase current time(${now}) to a moment in the past(${target})`); let diff = target - now; return increaseTime(diff); } export const duration = { seconds: function(val) { return val}, minutes: function(val) { return val * this.seconds(60) }, hours: function(val) { return val * this.minutes(60) }, days: function(val) { return val * this.hours(24) }, weeks: function(val) { return val * this.days(7) }, years: function(val) { return val * this.days(365)} }; ================================================ FILE: truffle/oz/contracts/helpers/latestTime.js ================================================ // Returns the time of the last mined block in seconds export default function latestTime() { return web3.eth.getBlock('latest').timestamp; } ================================================ FILE: truffle/oz/contracts/helpers/merkleTree.js ================================================ import { sha3, bufferToHex } from "ethereumjs-util"; export default class MerkleTree { constructor(elements) { // Filter empty strings and hash elements this.elements = elements.filter(el => el).map(el => sha3(el)); // Deduplicate elements this.elements = this.bufDedup(this.elements); // Sort elements this.elements.sort(Buffer.compare); // Create layers this.layers = this.getLayers(this.elements); } getLayers(elements) { if (elements.length == 0) { return [[""]]; } const layers = []; layers.push(elements); // Get next layer until we reach the root while (layers[layers.length - 1].length > 1) { layers.push(this.getNextLayer(layers[layers.length - 1])); } return layers; } getNextLayer(elements) { return elements.reduce((layer, el, idx, arr) => { if (idx % 2 === 0) { // Hash the current element with its pair element layer.push(this.combinedHash(el, arr[idx + 1])); } return layer; }, []); } combinedHash(first, second) { if (!first) { return second; } if (!second) { return first; } return sha3(this.sortAndConcat(first, second)); } getRoot() { return this.layers[this.layers.length - 1][0]; } getHexRoot() { return bufferToHex(this.getRoot()); } getProof(el) { let idx = this.bufIndexOf(el, this.elements); if (idx === -1) { throw new Error("Element does not exist in Merkle tree"); } return this.layers.reduce((proof, layer) => { const pairElement = this.getPairElement(idx, layer); if (pairElement) { proof.push(pairElement); } idx = Math.floor(idx / 2); return proof; }, []); } getHexProof(el) { const proof = this.getProof(el); return this.bufArrToHex(proof); } getPairElement(idx, layer) { const pairIdx = idx % 2 === 0 ? idx + 1 : idx - 1; if (pairIdx < layer.length) { return layer[pairIdx]; } else { return null; } } bufIndexOf(el, arr) { let hash; // Convert element to 32 byte hash if it is not one already if (el.length !== 32 || !Buffer.isBuffer(el)) { hash = sha3(el); } else { hash = el; } for (let i = 0; i < arr.length; i++) { if (hash.equals(arr[i])) { return i; } } return -1; } bufDedup(elements) { return elements.filter((el, idx) => { return this.bufIndexOf(el, elements) === idx; }); } bufArrToHex(arr) { if (arr.some(el => !Buffer.isBuffer(el))) { throw new Error("Array is not an array of buffers"); } return "0x" + arr.map(el => el.toString("hex")).join(""); } sortAndConcat(...args) { return Buffer.concat([...args].sort(Buffer.compare)); } } ================================================ FILE: truffle/oz/contracts/helpers/toPromise.js ================================================ export default func => (...args) => new Promise((accept, reject) => func(...args, (error, data) => error ? reject(error) : accept(data))); ================================================ FILE: truffle/oz/contracts/helpers/transactionMined.js ================================================ 'use strict'; //from https://gist.github.com/xavierlepretre/88682e871f4ad07be4534ae560692ee6 module.export = web3.eth.transactionMined = function (txnHash, interval) { var transactionReceiptAsync; interval = interval ? interval : 500; transactionReceiptAsync = function(txnHash, resolve, reject) { try { var receipt = web3.eth.getTransactionReceipt(txnHash); if (receipt === null) { setTimeout(function () { transactionReceiptAsync(txnHash, resolve, reject); }, interval); } else { resolve(receipt); } } catch(e) { reject(e); } }; if (Array.isArray(txnHash)) { var promises = []; txnHash.forEach(function (oneTxHash) { promises.push( web3.eth.getTransactionReceiptMined(oneTxHash, interval)); }); return Promise.all(promises); } else { return new Promise(function (resolve, reject) { transactionReceiptAsync(txnHash, resolve, reject); }); } }; ================================================ FILE: truffle/oz/contracts/lifecycle/Destructible.sol ================================================ pragma solidity ^0.4.18; import "../ownership/Ownable.sol"; /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } ================================================ FILE: truffle/oz/contracts/lifecycle/Migrations.sol ================================================ pragma solidity ^0.4.18; import '../ownership/Ownable.sol'; /** * @title Migrations * @dev This is a truffle contract, needed for truffle integration, not meant for use by Zeppelin users. */ contract Migrations is Ownable { uint256 public lastCompletedMigration; function setCompleted(uint256 completed) onlyOwner public { lastCompletedMigration = completed; } function upgrade(address newAddress) onlyOwner public { Migrations upgraded = Migrations(newAddress); upgraded.setCompleted(lastCompletedMigration); } } ================================================ FILE: truffle/oz/contracts/lifecycle/Pausable.sol ================================================ pragma solidity ^0.4.18; import "../ownership/Ownable.sol"; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } ================================================ FILE: truffle/oz/contracts/lifecycle/TokenDestructible.sol ================================================ pragma solidity ^0.4.18; import "../ownership/Ownable.sol"; import "../token/ERC20Basic.sol"; /** * @title TokenDestructible: * @author Remco Bloemen * @dev Base contract that can be destroyed by owner. All funds in contract including * listed tokens will be sent to the owner. */ contract TokenDestructible is Ownable { function TokenDestructible() public payable { } /** * @notice Terminate contract and refund to owner * @param tokens List of addresses of ERC20 or ERC20Basic token contracts to refund. * @notice The called token contracts could try to re-enter this contract. Only supply token contracts you trust. */ function destroy(address[] tokens) onlyOwner public { // Transfer tokens to owner for(uint256 i = 0; i < tokens.length; i++) { ERC20Basic token = ERC20Basic(tokens[i]); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); } // Transfer Eth to owner and terminate contract selfdestruct(owner); } } ================================================ FILE: truffle/oz/contracts/math/Math.sol ================================================ pragma solidity ^0.4.18; /** * @title Math * @dev Assorted math operations */ library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } ================================================ FILE: truffle/oz/contracts/math/SafeMath.sol ================================================ pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } ================================================ FILE: truffle/oz/contracts/ownership/CanReclaimToken.sol ================================================ pragma solidity ^0.4.18; import "./Ownable.sol"; import "../token/ERC20Basic.sol"; import "../token/SafeERC20.sol"; /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic token) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(owner, balance); } } ================================================ FILE: truffle/oz/contracts/ownership/Claimable.sol ================================================ pragma solidity ^0.4.18; import './Ownable.sol'; /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } ================================================ FILE: truffle/oz/contracts/ownership/Contactable.sol ================================================ pragma solidity ^0.4.18; import './Ownable.sol'; /** * @title Contactable token * @dev Basic version of a contactable contract, allowing the owner to provide a string with their * contact information. */ contract Contactable is Ownable{ string public contactInformation; /** * @dev Allows the owner to set a string with their contact information. * @param info The contact information to attach to the contract. */ function setContactInformation(string info) onlyOwner public { contactInformation = info; } } ================================================ FILE: truffle/oz/contracts/ownership/DelayedClaimable.sol ================================================ pragma solidity ^0.4.18; import './Claimable.sol'; /** * @title DelayedClaimable * @dev Extension for the Claimable contract, where the ownership needs to be claimed before/after * a certain block number. */ contract DelayedClaimable is Claimable { uint256 public end; uint256 public start; /** * @dev Used to specify the time period during which a pending * owner can claim ownership. * @param _start The earliest time ownership can be claimed. * @param _end The latest time ownership can be claimed. */ function setLimits(uint256 _start, uint256 _end) onlyOwner public { require(_start <= _end); end = _end; start = _start; } /** * @dev Allows the pendingOwner address to finalize the transfer, as long as it is called within * the specified start and end time. */ function claimOwnership() onlyPendingOwner public { require((block.number <= end) && (block.number >= start)); OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); end = 0; } } ================================================ FILE: truffle/oz/contracts/ownership/HasNoContracts.sol ================================================ pragma solidity ^0.4.18; import "./Ownable.sol"; /** * @title Contracts that should not own Contracts * @author Remco Bloemen * @dev Should contracts (anything Ownable) end up being owned by this contract, it allows the owner * of this contract to reclaim ownership of the contracts. */ contract HasNoContracts is Ownable { /** * @dev Reclaim ownership of Ownable contracts * @param contractAddr The address of the Ownable to be reclaimed. */ function reclaimContract(address contractAddr) external onlyOwner { Ownable contractInst = Ownable(contractAddr); contractInst.transferOwnership(owner); } } ================================================ FILE: truffle/oz/contracts/ownership/HasNoEther.sol ================================================ pragma solidity ^0.4.18; import "./Ownable.sol"; /** * @title Contracts that should not own Ether * @author Remco Bloemen * @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up * in the contract, it will allow the owner to reclaim this ether. * @notice Ether can still be send to this contract by: * calling functions labeled `payable` * `selfdestruct(contract_address)` * mining directly to the contract address */ contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ function HasNoEther() public payable { require(msg.value == 0); } /** * @dev Disallows direct send by settings a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { assert(owner.send(this.balance)); } } ================================================ FILE: truffle/oz/contracts/ownership/HasNoTokens.sol ================================================ pragma solidity ^0.4.18; import "./CanReclaimToken.sol"; /** * @title Contracts that should not own Tokens * @author Remco Bloemen * @dev This blocks incoming ERC23 tokens to prevent accidental loss of tokens. * Should tokens (any ERC20Basic compatible) end up in the contract, it allows the * owner to reclaim the tokens. */ contract HasNoTokens is CanReclaimToken { /** * @dev Reject all ERC23 compatible tokens * @param from_ address The address that is transferring the tokens * @param value_ uint256 the amount of the specified token * @param data_ Bytes The data passed from the caller. */ function tokenFallback(address from_, uint256 value_, bytes data_) external { from_; value_; data_; revert(); } } ================================================ FILE: truffle/oz/contracts/ownership/NoOwner.sol ================================================ pragma solidity ^0.4.18; import "./HasNoEther.sol"; import "./HasNoTokens.sol"; import "./HasNoContracts.sol"; /** * @title Base contract for contracts that should not own things. * @author Remco Bloemen * @dev Solves a class of errors where a contract accidentally becomes owner of Ether, Tokens or * Owned contracts. See respective base contracts for details. */ contract NoOwner is HasNoEther, HasNoTokens, HasNoContracts { } ================================================ FILE: truffle/oz/contracts/ownership/Ownable.sol ================================================ pragma solidity ^0.4.18; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } ================================================ FILE: truffle/oz/contracts/payment/PullPayment.sol ================================================ pragma solidity ^0.4.18; import '../math/SafeMath.sol'; /** * @title PullPayment * @dev Base contract supporting async send for pull payments. Inherit from this * contract and use asyncSend instead of send. */ contract PullPayment { using SafeMath for uint256; mapping(address => uint256) public payments; uint256 public totalPayments; /** * @dev Called by the payer to store the sent amount as credit to be pulled. * @param dest The destination address of the funds. * @param amount The amount to transfer. */ function asyncSend(address dest, uint256 amount) internal { payments[dest] = payments[dest].add(amount); totalPayments = totalPayments.add(amount); } /** * @dev withdraw accumulated balance, called by payee. */ function withdrawPayments() public { address payee = msg.sender; uint256 payment = payments[payee]; require(payment != 0); require(this.balance >= payment); totalPayments = totalPayments.sub(payment); payments[payee] = 0; assert(payee.send(payment)); } } ================================================ FILE: truffle/oz/contracts/payment/SplitPayment.sol ================================================ pragma solidity ^0.4.18; import '../math/SafeMath.sol'; /** * @title SplitPayment * @dev Base contract that supports multiple payees claiming funds sent to this contract * according to the proportion they own. */ contract SplitPayment { using SafeMath for uint256; uint256 public totalShares = 0; uint256 public totalReleased = 0; mapping(address => uint256) public shares; mapping(address => uint256) public released; address[] public payees; /** * @dev Constructor */ function SplitPayment(address[] _payees, uint256[] _shares) public { require(_payees.length == _shares.length); for (uint256 i = 0; i < _payees.length; i++) { addPayee(_payees[i], _shares[i]); } } /** * @dev Add a new payee to the contract. * @param _payee The address of the payee to add. * @param _shares The number of shares owned by the payee. */ function addPayee(address _payee, uint256 _shares) internal { require(_payee != address(0)); require(_shares > 0); require(shares[_payee] == 0); payees.push(_payee); shares[_payee] = _shares; totalShares = totalShares.add(_shares); } /** * @dev Claim your share of the balance. */ function claim() public { address payee = msg.sender; require(shares[payee] > 0); uint256 totalReceived = this.balance.add(totalReleased); uint256 payment = totalReceived.mul(shares[payee]).div(totalShares).sub(released[payee]); require(payment != 0); require(this.balance >= payment); released[payee] = released[payee].add(payment); totalReleased = totalReleased.add(payment); payee.transfer(payment); } } ================================================ FILE: truffle/oz/contracts/token/BasicToken.sol ================================================ pragma solidity ^0.4.18; import './ERC20Basic.sol'; import '../math/SafeMath.sol'; /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } ================================================ FILE: truffle/oz/contracts/token/BurnableToken.sol ================================================ pragma solidity ^0.4.18; import './StandardToken.sol'; /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value > 0); require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } ================================================ FILE: truffle/oz/contracts/token/CappedToken.sol ================================================ pragma solidity ^0.4.11; import './MintableToken.sol'; /** * @title Capped token * @dev Mintable token with a token cap. */ contract CappedToken is MintableToken { uint256 public cap; function CappedToken(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { require(totalSupply.add(_amount) <= cap); return super.mint(_to, _amount); } } ================================================ FILE: truffle/oz/contracts/token/DetailedERC20.sol ================================================ pragma solidity ^0.4.18; import './ERC20.sol'; contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; function DetailedERC20(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } ================================================ FILE: truffle/oz/contracts/token/ERC20.sol ================================================ pragma solidity ^0.4.18; import './ERC20Basic.sol'; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } ================================================ FILE: truffle/oz/contracts/token/ERC20Basic.sol ================================================ pragma solidity ^0.4.18; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } ================================================ FILE: truffle/oz/contracts/token/MintableToken.sol ================================================ pragma solidity ^0.4.18; import './StandardToken.sol'; import '../ownership/Ownable.sol'; /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } ================================================ FILE: truffle/oz/contracts/token/PausableToken.sol ================================================ pragma solidity ^0.4.18; import './StandardToken.sol'; import '../lifecycle/Pausable.sol'; /** * @title Pausable token * * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } ================================================ FILE: truffle/oz/contracts/token/SafeERC20.sol ================================================ pragma solidity ^0.4.18; import './ERC20Basic.sol'; import './ERC20.sol'; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } ================================================ FILE: truffle/oz/contracts/token/StandardToken.sol ================================================ pragma solidity ^0.4.18; import './BasicToken.sol'; import './ERC20.sol'; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } ================================================ FILE: truffle/oz/contracts/token/TokenTimelock.sol ================================================ pragma solidity ^0.4.18; import './ERC20Basic.sol'; import "../token/SafeERC20.sol"; /** * @title TokenTimelock * @dev TokenTimelock is a token holder contract that will allow a * beneficiary to extract the tokens after a given release time */ contract TokenTimelock { using SafeERC20 for ERC20Basic; // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint64 public releaseTime; function TokenTimelock(ERC20Basic _token, address _beneficiary, uint64 _releaseTime) public { require(_releaseTime > now); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { require(now >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); token.safeTransfer(beneficiary, amount); } } ================================================ FILE: truffle/oz/contracts/token/TokenVesting.sol ================================================ pragma solidity ^0.4.18; import './ERC20Basic.sol'; import './SafeERC20.sol'; import '../ownership/Ownable.sol'; import '../math/SafeMath.sol'; /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(now.sub(start)).div(duration); } } } ================================================ FILE: truffle/oz/migrations/1_initial_migration.js ================================================ var Migrations = artifacts.require("./Migrations.sol"); module.exports = function(deployer) { deployer.deploy(Migrations); }; ================================================ FILE: truffle/oz/migrations/2_deploy_contracts.js ================================================ var Ownable = artifacts.require("ownership/Ownable.sol"); var BasicToken = artifacts.require("token/BasicToken.sol"); module.exports = function(deployer) { deployer.deploy(Ownable); deployer.deploy(BasicToken); }; ================================================ FILE: truffle/oz/package.json ================================================ { "name": "open-zeppelin-samples", "private": true, "version": "1.0.0", "description": "Open Zeppelin Samples", "main": "truffle.js", "directories": { "test": "test" }, "dependencies": { "truffle": "^4.0.1", "zeppelin-solidity": "^1.4.0" }, "devDependencies": {}, "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC" } ================================================ FILE: truffle/oz/test/BasicToken.js ================================================ const assertRevert = require('./helpers/assertRevert'); var BasicTokenMock = artifacts.require("./helpers/BasicTokenMock.sol"); contract('BasicToken', function(accounts) { it("should return the correct totalSupply after construction", async function() { let token = await BasicTokenMock.new(accounts[0], 100); let totalSupply = await token.totalSupply(); assert.equal(totalSupply, 100); }) it("should return correct balances after transfer", async function(){ let token = await BasicTokenMock.new(accounts[0], 100); let transfer = await token.transfer(accounts[1], 100); let firstAccountBalance = await token.balanceOf(accounts[0]); assert.equal(firstAccountBalance, 0); let secondAccountBalance = await token.balanceOf(accounts[1]); assert.equal(secondAccountBalance, 100); }); it('should throw an error when trying to transfer more than balance', async function() { let token = await BasicTokenMock.new(accounts[0], 100); try { let transfer = await token.transfer(accounts[1], 101); assert.fail('should have thrown before'); } catch(error) { assertRevert(error); } }); it('should throw an error when trying to transfer to 0x0', async function() { let token = await BasicTokenMock.new(accounts[0], 100); try { let transfer = await token.transfer(0x0, 100); assert.fail('should have thrown before'); } catch(error) { assertRevert(error); } }); }); ================================================ FILE: truffle/oz/test/Bounty.js ================================================ 'use strict'; let sendReward = function(sender, receiver, value){ web3.eth.sendTransaction({ from:sender, to:receiver, value: value }); }; var SecureTargetBounty = artifacts.require('helpers/SecureTargetBounty.sol'); var InsecureTargetBounty = artifacts.require('helpers/InsecureTargetBounty.sol'); function awaitEvent(event, handler) { return new Promise((resolve, reject) => { function wrappedHandler(...args) { Promise.resolve(handler(...args)).then(resolve).catch(reject); } event.watch(wrappedHandler); }); } contract('Bounty', function(accounts) { it('sets reward', async function() { let owner = accounts[0]; let reward = web3.toWei(1, 'ether'); let bounty = await SecureTargetBounty.new(); sendReward(owner, bounty.address, reward); assert.equal(reward, web3.eth.getBalance(bounty.address).toNumber()); }); it('empties itself when destroyed', async function(){ let owner = accounts[0]; let reward = web3.toWei(1, 'ether'); let bounty = await SecureTargetBounty.new(); sendReward(owner, bounty.address, reward); assert.equal(reward, web3.eth.getBalance(bounty.address).toNumber()); await bounty.destroy(); assert.equal(0, web3.eth.getBalance(bounty.address).toNumber()); }); describe('Against secure contract', function(){ it('cannot claim reward', async function(){ let owner = accounts[0]; let researcher = accounts[1]; let reward = web3.toWei(1, 'ether'); let bounty = await SecureTargetBounty.new(); let event = bounty.TargetCreated({}); let watcher = async function(err, result) { event.stopWatching(); if (err) { throw err; } var targetAddress = result.args.createdAddress; sendReward(owner, bounty.address, reward); assert.equal(reward, web3.eth.getBalance(bounty.address).toNumber()); try { await bounty.claim(targetAddress, {from:researcher}); assert.isTrue(false); // should never reach here } catch(error) { let reClaimedBounty = await bounty.claimed.call(); assert.isFalse(reClaimedBounty); } try { await bounty.withdrawPayments({from:researcher}); assert.isTrue(false); // should never reach here } catch (err) { assert.equal(reward, web3.eth.getBalance(bounty.address).toNumber()); } }; bounty.createTarget({from:researcher}); await awaitEvent(event, watcher); }); }); describe('Against broken contract', function(){ it('claims reward', async function() { let owner = accounts[0]; let researcher = accounts[1]; let reward = web3.toWei(1, 'ether'); let bounty = await InsecureTargetBounty.new(); let event = bounty.TargetCreated({}); let watcher = async function(err, result) { event.stopWatching(); if (err) { throw err; } let targetAddress = result.args.createdAddress; sendReward(owner, bounty.address, reward); assert.equal(reward, web3.eth.getBalance(bounty.address).toNumber()); await bounty.claim(targetAddress, {from:researcher}); let claim = await bounty.claimed.call(); assert.isTrue(claim); await bounty.withdrawPayments({from:researcher}); assert.equal(0, web3.eth.getBalance(bounty.address).toNumber()); }; bounty.createTarget({from:researcher}); await awaitEvent(event, watcher); }); }); }); ================================================ FILE: truffle/oz/test/BurnableToken.js ================================================ 'use strict' const EVMRevert = require('./helpers/EVMRevert.js') const BurnableTokenMock = artifacts.require("./helpers/BurnableTokenMock.sol") const BigNumber = web3.BigNumber require('chai') .use(require('chai-as-promised')) .use(require('chai-bignumber')(BigNumber)) .should() const expect = require('chai').expect contract('BurnableToken', function (accounts) { let token let expectedTokenSupply = new BigNumber(999) beforeEach(async function () { token = await BurnableTokenMock.new(accounts[0], 1000) }) it('owner should be able to burn tokens', async function () { const { logs } = await token.burn(1, { from: accounts[0] }) const balance = await token.balanceOf(accounts[0]) balance.should.be.bignumber.equal(expectedTokenSupply) const totalSupply = await token.totalSupply() totalSupply.should.be.bignumber.equal(expectedTokenSupply) const event = logs.find(e => e.event === 'Burn') expect(event).to.exist }) it('cannot burn more tokens than your balance', async function () { await token.burn(2000, { from: accounts[0] }) .should.be.rejectedWith(EVMRevert) }) }) ================================================ FILE: truffle/oz/test/CanReclaimToken.js ================================================ 'use strict'; import expectThrow from './helpers/expectThrow'; import toPromise from './helpers/toPromise'; const CanReclaimToken = artifacts.require('../contracts/ownership/CanReclaimToken.sol'); const BasicTokenMock = artifacts.require("./helpers/BasicTokenMock.sol"); contract('CanReclaimToken', function(accounts) { let token = null; let canReclaimToken = null; beforeEach(async function() { // Create contract and token token = await BasicTokenMock.new(accounts[0], 100); canReclaimToken = await CanReclaimToken.new(); // Force token into contract await token.transfer(canReclaimToken.address, 10); const startBalance = await token.balanceOf(canReclaimToken.address); assert.equal(startBalance, 10); }); it('should allow owner to reclaim tokens', async function() { const ownerStartBalance = await token.balanceOf(accounts[0]); await canReclaimToken.reclaimToken(token.address); const ownerFinalBalance = await token.balanceOf(accounts[0]); const finalBalance = await token.balanceOf(canReclaimToken.address); assert.equal(finalBalance, 0); assert.equal(ownerFinalBalance - ownerStartBalance, 10); }); it('should allow only owner to reclaim tokens', async function() { await expectThrow( canReclaimToken.reclaimToken(token.address, {from: accounts[1]}), ); }); }); ================================================ FILE: truffle/oz/test/CappedCrowdsale.js ================================================ import ether from './helpers/ether' import {advanceBlock} from './helpers/advanceToBlock' import {increaseTimeTo, duration} from './helpers/increaseTime' import latestTime from './helpers/latestTime' import EVMRevert from './helpers/EVMRevert' const BigNumber = web3.BigNumber require('chai') .use(require('chai-as-promised')) .use(require('chai-bignumber')(BigNumber)) .should() const CappedCrowdsale = artifacts.require('./helpers/CappedCrowdsaleImpl.sol') const MintableToken = artifacts.require('MintableToken') contract('CappedCrowdsale', function ([_, wallet]) { const rate = new BigNumber(1000) const cap = ether(300) const lessThanCap = ether(60) before(async function() { //Advance to the next block to correctly read time in the solidity "now" function interpreted by testrpc await advanceBlock() }) beforeEach(async function () { this.startTime = latestTime() + duration.weeks(1); this.endTime = this.startTime + duration.weeks(1); this.crowdsale = await CappedCrowdsale.new(this.startTime, this.endTime, rate, wallet, cap) this.token = MintableToken.at(await this.crowdsale.token()) }) describe('creating a valid crowdsale', function () { it('should fail with zero cap', async function () { await CappedCrowdsale.new(this.startTime, this.endTime, rate, wallet, 0).should.be.rejectedWith(EVMRevert); }) }); describe('accepting payments', function () { beforeEach(async function () { await increaseTimeTo(this.startTime) }) it('should accept payments within cap', async function () { await this.crowdsale.send(cap.minus(lessThanCap)).should.be.fulfilled await this.crowdsale.send(lessThanCap).should.be.fulfilled }) it('should reject payments outside cap', async function () { await this.crowdsale.send(cap) await this.crowdsale.send(1).should.be.rejectedWith(EVMRevert) }) it('should reject payments that exceed cap', async function () { await this.crowdsale.send(cap.plus(1)).should.be.rejectedWith(EVMRevert) }) }) describe('ending', function () { beforeEach(async function () { await increaseTimeTo(this.startTime) }) it('should not be ended if under cap', async function () { let hasEnded = await this.crowdsale.hasEnded() hasEnded.should.equal(false) await this.crowdsale.send(lessThanCap) hasEnded = await this.crowdsale.hasEnded() hasEnded.should.equal(false) }) it('should not be ended if just under cap', async function () { await this.crowdsale.send(cap.minus(1)) let hasEnded = await this.crowdsale.hasEnded() hasEnded.should.equal(false) }) it('should be ended if cap reached', async function () { await this.crowdsale.send(cap) let hasEnded = await this.crowdsale.hasEnded() hasEnded.should.equal(true) }) }) }) ================================================ FILE: truffle/oz/test/CappedToken.js ================================================ 'use strict'; import expectThrow from './helpers/expectThrow'; import ether from './helpers/ether'; var CappedToken = artifacts.require('../contracts/Tokens/CappedToken.sol'); const BigNumber = web3.BigNumber contract('Capped', function(accounts) { const cap = ether(1000); let token; beforeEach(async function() { token = await CappedToken.new(cap); }) it('should start with the correct cap', async function() { let _cap = await token.cap(); assert(cap.eq(_cap)); }) it('should mint when amount is less than cap', async function() { const result = await token.mint(accounts[0], 100); assert.equal(result.logs[0].event, 'Mint'); }) it('should fail to mint if the ammount exceeds the cap', async function() { await token.mint(accounts[0], cap.sub(1)); await expectThrow(token.mint(accounts[0], 100)); }) it('should fail to mint after cap is reached', async function() { await token.mint(accounts[0], cap); await expectThrow(token.mint(accounts[0], 1)); }) }); ================================================ FILE: truffle/oz/test/Claimable.js ================================================ 'use strict'; const assertRevert = require('./helpers/assertRevert'); var Claimable = artifacts.require('../contracts/ownership/Claimable.sol'); contract('Claimable', function(accounts) { let claimable; beforeEach(async function() { claimable = await Claimable.new(); }); it('should have an owner', async function() { let owner = await claimable.owner(); assert.isTrue(owner !== 0); }); it('changes pendingOwner after transfer', async function() { let newOwner = accounts[1]; await claimable.transferOwnership(newOwner); let pendingOwner = await claimable.pendingOwner(); assert.isTrue(pendingOwner === newOwner); }); it('should prevent to claimOwnership from no pendingOwner', async function() { try { await claimable.claimOwnership({from: accounts[2]}); assert.fail('should have thrown before'); } catch(error) { assertRevert(error); } }); it('should prevent non-owners from transfering', async function() { const other = accounts[2]; const owner = await claimable.owner.call(); assert.isTrue(owner !== other); try { await claimable.transferOwnership(other, {from: other}); assert.fail('should have thrown before'); } catch(error) { assertRevert(error); } }); describe('after initiating a transfer', function () { let newOwner; beforeEach(async function () { newOwner = accounts[1]; await claimable.transferOwnership(newOwner); }); it('changes allow pending owner to claim ownership', async function() { await claimable.claimOwnership({from: newOwner}); let owner = await claimable.owner(); assert.isTrue(owner === newOwner); }); }); }); ================================================ FILE: truffle/oz/test/Contactable.js ================================================ 'use strict'; const assertRevert = require('./helpers/assertRevert'); var Contactable = artifacts.require('../contracts/ownership/Contactable.sol'); contract('Contactable', function(accounts) { let contactable; beforeEach(async function() { contactable = await Contactable.new(); }); it('should have an empty contact info', async function() { let info = await contactable.contactInformation(); assert.isTrue(info == ""); }); describe('after setting the contact information', function () { let contactInfo = "contact information" beforeEach(async function () { await contactable.setContactInformation(contactInfo); }); it('should return the setted contact information', async function() { let info = await contactable.contactInformation(); assert.isTrue(info === contactInfo); }); }); }); ================================================ FILE: truffle/oz/test/Crowdsale.js ================================================ import ether from './helpers/ether' import {advanceBlock} from './helpers/advanceToBlock' import {increaseTimeTo, duration} from './helpers/increaseTime' import latestTime from './helpers/latestTime' import EVMRevert from './helpers/EVMRevert' const BigNumber = web3.BigNumber const should = require('chai') .use(require('chai-as-promised')) .use(require('chai-bignumber')(BigNumber)) .should() const Crowdsale = artifacts.require('Crowdsale') const MintableToken = artifacts.require('MintableToken') contract('Crowdsale', function ([_, investor, wallet, purchaser]) { const rate = new BigNumber(1000) const value = ether(42) const expectedTokenAmount = rate.mul(value) before(async function() { //Advance to the next block to correctly read time in the solidity "now" function interpreted by testrpc await advanceBlock() }) beforeEach(async function () { this.startTime = latestTime() + duration.weeks(1); this.endTime = this.startTime + duration.weeks(1); this.afterEndTime = this.endTime + duration.seconds(1) this.crowdsale = await Crowdsale.new(this.startTime, this.endTime, rate, wallet) this.token = MintableToken.at(await this.crowdsale.token()) }) it('should be token owner', async function () { const owner = await this.token.owner() owner.should.equal(this.crowdsale.address) }) it('should be ended only after end', async function () { let ended = await this.crowdsale.hasEnded() ended.should.equal(false) await increaseTimeTo(this.afterEndTime) ended = await this.crowdsale.hasEnded() ended.should.equal(true) }) describe('accepting payments', function () { it('should reject payments before start', async function () { await this.crowdsale.send(value).should.be.rejectedWith(EVMRevert) await this.crowdsale.buyTokens(investor, {from: purchaser, value: value}).should.be.rejectedWith(EVMRevert) }) it('should accept payments after start', async function () { await increaseTimeTo(this.startTime) await this.crowdsale.send(value).should.be.fulfilled await this.crowdsale.buyTokens(investor, {value: value, from: purchaser}).should.be.fulfilled }) it('should reject payments after end', async function () { await increaseTimeTo(this.afterEndTime) await this.crowdsale.send(value).should.be.rejectedWith(EVMRevert) await this.crowdsale.buyTokens(investor, {value: value, from: purchaser}).should.be.rejectedWith(EVMRevert) }) }) describe('high-level purchase', function () { beforeEach(async function() { await increaseTimeTo(this.startTime) }) it('should log purchase', async function () { const {logs} = await this.crowdsale.sendTransaction({value: value, from: investor}) const event = logs.find(e => e.event === 'TokenPurchase') should.exist(event) event.args.purchaser.should.equal(investor) event.args.beneficiary.should.equal(investor) event.args.value.should.be.bignumber.equal(value) event.args.amount.should.be.bignumber.equal(expectedTokenAmount) }) it('should increase totalSupply', async function () { await this.crowdsale.send(value) const totalSupply = await this.token.totalSupply() totalSupply.should.be.bignumber.equal(expectedTokenAmount) }) it('should assign tokens to sender', async function () { await this.crowdsale.sendTransaction({value: value, from: investor}) let balance = await this.token.balanceOf(investor); balance.should.be.bignumber.equal(expectedTokenAmount) }) it('should forward funds to wallet', async function () { const pre = web3.eth.getBalance(wallet) await this.crowdsale.sendTransaction({value, from: investor}) const post = web3.eth.getBalance(wallet) post.minus(pre).should.be.bignumber.equal(value) }) }) describe('low-level purchase', function () { beforeEach(async function() { await increaseTimeTo(this.startTime) }) it('should log purchase', async function () { const {logs} = await this.crowdsale.buyTokens(investor, {value: value, from: purchaser}) const event = logs.find(e => e.event === 'TokenPurchase') should.exist(event) event.args.purchaser.should.equal(purchaser) event.args.beneficiary.should.equal(investor) event.args.value.should.be.bignumber.equal(value) event.args.amount.should.be.bignumber.equal(expectedTokenAmount) }) it('should increase totalSupply', async function () { await this.crowdsale.buyTokens(investor, {value, from: purchaser}) const totalSupply = await this.token.totalSupply() totalSupply.should.be.bignumber.equal(expectedTokenAmount) }) it('should assign tokens to beneficiary', async function () { await this.crowdsale.buyTokens(investor, {value, from: purchaser}) const balance = await this.token.balanceOf(investor) balance.should.be.bignumber.equal(expectedTokenAmount) }) it('should forward funds to wallet', async function () { const pre = web3.eth.getBalance(wallet) await this.crowdsale.buyTokens(investor, {value, from: purchaser}) const post = web3.eth.getBalance(wallet) post.minus(pre).should.be.bignumber.equal(value) }) }) }) ================================================ FILE: truffle/oz/test/DayLimit.js ================================================ 'use strict'; const assertRevert = require('./helpers/assertRevert'); import latestTime from './helpers/latestTime' import {increaseTimeTo, duration} from './helpers/increaseTime' var DayLimitMock = artifacts.require('./helpers/DayLimitMock.sol'); contract('DayLimit', function(accounts) { let dayLimit; let initLimit = 10; beforeEach( async function() { this.startTime = latestTime(); dayLimit = await DayLimitMock.new(initLimit); }); it('should construct with the passed daily limit', async function() { let dailyLimit = await dayLimit.dailyLimit(); assert.equal(initLimit, dailyLimit); }); it('should be able to spend if daily limit is not reached', async function() { await dayLimit.attemptSpend(8); let spentToday = await dayLimit.spentToday(); assert.equal(spentToday, 8); await dayLimit.attemptSpend(2); spentToday = await dayLimit.spentToday(); assert.equal(spentToday, 10); }); it('should prevent spending if daily limit is reached', async function() { await dayLimit.attemptSpend(8); let spentToday = await dayLimit.spentToday(); assert.equal(spentToday, 8); try { await dayLimit.attemptSpend(3); assert.fail('should have thrown before'); } catch(error) { assertRevert(error); } }); it('should allow spending if daily limit is reached and then set higher', async function() { await dayLimit.attemptSpend(8); let spentToday = await dayLimit.spentToday(); assert.equal(spentToday, 8); try { await dayLimit.attemptSpend(3); assert.fail('should have thrown before'); } catch(error) { assertRevert(error); } spentToday = await dayLimit.spentToday(); assert.equal(spentToday, 8); await dayLimit.setDailyLimit(15); await dayLimit.attemptSpend(3); spentToday = await dayLimit.spentToday(); assert.equal(spentToday, 11); }); it('should allow spending if daily limit is reached and then amount spent is reset', async function() { await dayLimit.attemptSpend(8); let spentToday = await dayLimit.spentToday(); assert.equal(spentToday, 8); try { await dayLimit.attemptSpend(3); assert.fail('should have thrown before'); } catch(error) { assertRevert(error); } spentToday = await dayLimit.spentToday(); assert.equal(spentToday, 8); await dayLimit.resetSpentToday(); await dayLimit.attemptSpend(3); spentToday = await dayLimit.spentToday(); assert.equal(spentToday, 3); }); it('should allow spending if daily limit is reached and then the next has come', async function() { let limit = 10; let dayLimit = await DayLimitMock.new(limit); await dayLimit.attemptSpend(8); let spentToday = await dayLimit.spentToday(); assert.equal(spentToday, 8); try { await dayLimit.attemptSpend(3); assert.fail('should have thrown before'); } catch(error) { assertRevert(error); } spentToday = await dayLimit.spentToday(); assert.equal(spentToday, 8); await increaseTimeTo(this.startTime + duration.days(1)); await dayLimit.attemptSpend(3); spentToday = await dayLimit.spentToday(); assert.equal(spentToday, 3); }); }); ================================================ FILE: truffle/oz/test/DelayedClaimble.js ================================================ 'use strict'; var DelayedClaimable = artifacts.require('../contracts/ownership/DelayedClaimable.sol'); contract('DelayedClaimable', function(accounts) { var delayedClaimable; beforeEach(function() { return DelayedClaimable.new().then(function(deployed) { delayedClaimable = deployed; }); }); it('can set claim blocks', async function() { await delayedClaimable.transferOwnership(accounts[2]); await delayedClaimable.setLimits(0, 1000); let end = await delayedClaimable.end(); assert.equal(end, 1000); let start = await delayedClaimable.start(); assert.equal(start, 0); }); it('changes pendingOwner after transfer successful', async function() { await delayedClaimable.transferOwnership(accounts[2]); await delayedClaimable.setLimits(0, 1000); let end = await delayedClaimable.end(); assert.equal(end, 1000); let start = await delayedClaimable.start(); assert.equal(start, 0); let pendingOwner = await delayedClaimable.pendingOwner(); assert.equal(pendingOwner, accounts[2]); await delayedClaimable.claimOwnership({from: accounts[2]}); let owner = await delayedClaimable.owner(); assert.equal(owner, accounts[2]); }); it('changes pendingOwner after transfer fails', async function() { await delayedClaimable.transferOwnership(accounts[1]); await delayedClaimable.setLimits(100, 110); let end = await delayedClaimable.end(); assert.equal(end, 110); let start = await delayedClaimable.start(); assert.equal(start, 100); let pendingOwner = await delayedClaimable.pendingOwner(); assert.equal(pendingOwner, accounts[1]); var err = null; try { await delayedClaimable.claimOwnership({from: accounts[1]}); } catch (error) { err = error; } assert.isFalse(err.message.search('revert') === -1); let owner = await delayedClaimable.owner(); assert.isTrue(owner !== accounts[1]); }); it('set end and start invalid values fail', async function() { await delayedClaimable.transferOwnership(accounts[1]); var err = null; try { await delayedClaimable.setLimits(1001, 1000); } catch (error) { err = error; } assert.isFalse(err.message.search('revert') === -1); }); }); ================================================ FILE: truffle/oz/test/Destructible.js ================================================ 'use strict'; var Destructible = artifacts.require('../contracts/lifecycle/Destructible.sol'); require('./helpers/transactionMined.js'); contract('Destructible', function(accounts) { it('should send balance to owner after destruction', async function() { let destructible = await Destructible.new({from: accounts[0], value: web3.toWei('10','ether')}); let owner = await destructible.owner(); let initBalance = web3.eth.getBalance(owner); await destructible.destroy({from: owner}); let newBalance = web3.eth.getBalance(owner); assert.isTrue(newBalance > initBalance); }); it('should send balance to recepient after destruction', async function() { let destructible = await Destructible.new({from: accounts[0], value: web3.toWei('10','ether')}); let owner = await destructible.owner(); let initBalance = web3.eth.getBalance(accounts[1]); await destructible.destroyAndSend(accounts[1], {from: owner} ); let newBalance = web3.eth.getBalance(accounts[1]); assert.isTrue(newBalance.greaterThan(initBalance)); }); }); ================================================ FILE: truffle/oz/test/DetailedERC20.js ================================================ const BigNumber = web3.BigNumber; require('chai') .use(require('chai-as-promised')) .use(require('chai-bignumber')(BigNumber)) .should(); const DetailedERC20Mock = artifacts.require('./helpers/DetailedERC20Mock.sol'); contract('DetailedERC20', accounts => { let detailedERC20 = null; const _name = "My Detailed ERC20"; const _symbol = "MDT"; const _decimals = 18; beforeEach(async function() { detailedERC20 = await DetailedERC20Mock.new(_name, _symbol, _decimals); }); it('has a name', async function () { const name = await detailedERC20.name(); name.should.be.equal(_name); }); it('has a symbol', async function () { const symbol = await detailedERC20.symbol(); symbol.should.be.equal(_symbol); }); it('has an amount of decimals', async function () { const decimals = await detailedERC20.decimals(); decimals.should.be.bignumber.equal(_decimals) }); }); ================================================ FILE: truffle/oz/test/ECRecovery.js ================================================ var ECRecovery = artifacts.require("../contracts/ECRecovery.sol"); var utils = require('ethereumjs-util'); var hashMessage = require('./helpers/hashMessage.js'); contract('ECRecovery', function(accounts) { let ecrecovery; before(async function() { ecrecovery = await ECRecovery.new(); }); it("recover v0", async function() { // Signature generated outside testrpc with method web3.eth.sign(signer, message) let signer = '0x2cc1166f6212628a0deef2b33befb2187d35b86c'; let message = '0x7dbaf558b0a1a5dc7a67202117ab143c1d8605a983e4a743bc06fcc03162dc0d'; // web3.sha3('OpenZeppelin') let signature = '0x5d99b6f7f6d1f73d1a26497f2b1c89b24c0993913f86e9a2d02cd69887d9c94f3c880358579d811b21dd1b7fd9bb01c1d81d10e69f0384e675c32b39643be89200'; assert.equal(signer, await ecrecovery.recover(message, signature)); }); it("recover v1", async function() { // Signature generated outside testrpc with method web3.eth.sign(signer, message) let signer = '0x1e318623ab09fe6de3c9b8672098464aeda9100e'; let message = '0x7dbaf558b0a1a5dc7a67202117ab143c1d8605a983e4a743bc06fcc03162dc0d'; // web3.sha3('OpenZeppelin') let signature = '0x331fe75a821c982f9127538858900d87d3ec1f9f737338ad67cad133fa48feff48e6fa0c18abc62e42820f05943e47af3e9fbe306ce74d64094bdf1691ee53e001'; assert.equal(signer, await ecrecovery.recover(message, signature)); }); it("recover using web3.eth.sign()", async function() { // Create the signature using account[0] const signature = web3.eth.sign(web3.eth.accounts[0], web3.sha3('OpenZeppelin')); // Recover the signer address form the generated message and signature. assert.equal(web3.eth.accounts[0], await ecrecovery.recover(hashMessage('OpenZeppelin'), signature)); }); it("recover using web3.eth.sign() should return wrong signer", async function() { // Create the signature using account[0] const signature = web3.eth.sign(web3.eth.accounts[0], web3.sha3('OpenZeppelin')); // Recover the signer address form the generated message and wrong signature. assert.notEqual(web3.eth.accounts[0], await ecrecovery.recover(hashMessage('Test'), signature)); }); it("recover should fail when a wrong hash is sent", async function() { // Create the signature using account[0] let signature = web3.eth.sign(web3.eth.accounts[0], web3.sha3('OpenZeppelin')); // Recover the signer address form the generated message and wrong signature. assert.equal('0x0000000000000000000000000000000000000000', await ecrecovery.recover(hashMessage('OpenZeppelin').substring(2), signature) ); }); }); ================================================ FILE: truffle/oz/test/FinalizableCrowdsale.js ================================================ import {advanceBlock} from './helpers/advanceToBlock' import {increaseTimeTo, duration} from './helpers/increaseTime' import latestTime from './helpers/latestTime' import EVMRevert from './helpers/EVMRevert' const BigNumber = web3.BigNumber const should = require('chai') .use(require('chai-as-promised')) .use(require('chai-bignumber')(BigNumber)) .should() const FinalizableCrowdsale = artifacts.require('./helpers/FinalizableCrowdsaleImpl.sol') const MintableToken = artifacts.require('MintableToken') contract('FinalizableCrowdsale', function ([_, owner, wallet, thirdparty]) { const rate = new BigNumber(1000) before(async function() { //Advance to the next block to correctly read time in the solidity "now" function interpreted by testrpc await advanceBlock() }) beforeEach(async function () { this.startTime = latestTime() + duration.weeks(1) this.endTime = this.startTime + duration.weeks(1) this.afterEndTime = this.endTime + duration.seconds(1) this.crowdsale = await FinalizableCrowdsale.new(this.startTime, this.endTime, rate, wallet, {from: owner}) this.token = MintableToken.at(await this.crowdsale.token()) }) it('cannot be finalized before ending', async function () { await this.crowdsale.finalize({from: owner}).should.be.rejectedWith(EVMRevert) }) it('cannot be finalized by third party after ending', async function () { await increaseTimeTo(this.afterEndTime) await this.crowdsale.finalize({from: thirdparty}).should.be.rejectedWith(EVMRevert) }) it('can be finalized by owner after ending', async function () { await increaseTimeTo(this.afterEndTime) await this.crowdsale.finalize({from: owner}).should.be.fulfilled }) it('cannot be finalized twice', async function () { await increaseTimeTo(this.afterEndTime) await this.crowdsale.finalize({from: owner}) await this.crowdsale.finalize({from: owner}).should.be.rejectedWith(EVMRevert) }) it('logs finalized', async function () { await increaseTimeTo(this.afterEndTime) const {logs} = await this.crowdsale.finalize({from: owner}) const event = logs.find(e => e.event === 'Finalized') should.exist(event) }) }) ================================================ FILE: truffle/oz/test/HasNoContracts.js ================================================ 'use strict'; import expectThrow from './helpers/expectThrow'; import toPromise from './helpers/toPromise'; const Ownable = artifacts.require('../contracts/ownership/Ownable.sol'); const HasNoContracts = artifacts.require( '../contracts/ownership/HasNoContracts.sol', ); contract('HasNoContracts', function(accounts) { let hasNoContracts = null; let ownable = null; beforeEach(async () => { // Create contract and token hasNoContracts = await HasNoContracts.new(); ownable = await Ownable.new(); // Force ownership into contract await ownable.transferOwnership(hasNoContracts.address); const owner = await ownable.owner(); assert.equal(owner, hasNoContracts.address); }); it('should allow owner to reclaim contracts', async function() { await hasNoContracts.reclaimContract(ownable.address); const owner = await ownable.owner(); assert.equal(owner, accounts[0]); }); it('should allow only owner to reclaim contracts', async function() { await expectThrow( hasNoContracts.reclaimContract(ownable.address, {from: accounts[1]}), ); }); }); ================================================ FILE: truffle/oz/test/HasNoEther.js ================================================ 'use strict'; import expectThrow from './helpers/expectThrow'; import toPromise from './helpers/toPromise'; const HasNoEther = artifacts.require('../contracts/lifecycle/HasNoEther.sol'); const HasNoEtherTest = artifacts.require('../helpers/HasNoEtherTest.sol'); const ForceEther = artifacts.require('../helpers/ForceEther.sol'); contract('HasNoEther', function(accounts) { const amount = web3.toWei('1', 'ether'); it('should be constructorable', async function() { let hasNoEther = await HasNoEtherTest.new(); }); it('should not accept ether in constructor', async function() { await expectThrow(HasNoEtherTest.new({value: amount})); }); it('should not accept ether', async function() { let hasNoEther = await HasNoEtherTest.new(); await expectThrow( toPromise(web3.eth.sendTransaction)({ from: accounts[1], to: hasNoEther.address, value: amount, }), ); }); it('should allow owner to reclaim ether', async function() { // Create contract let hasNoEther = await HasNoEtherTest.new(); const startBalance = await web3.eth.getBalance(hasNoEther.address); assert.equal(startBalance, 0); // Force ether into it let forceEther = await ForceEther.new({value: amount}); await forceEther.destroyAndSend(hasNoEther.address); const forcedBalance = await web3.eth.getBalance(hasNoEther.address); assert.equal(forcedBalance, amount); // Reclaim const ownerStartBalance = await web3.eth.getBalance(accounts[0]); await hasNoEther.reclaimEther(); const ownerFinalBalance = await web3.eth.getBalance(accounts[0]); const finalBalance = await web3.eth.getBalance(hasNoEther.address); assert.equal(finalBalance, 0); assert.isAbove(ownerFinalBalance, ownerStartBalance); }); it('should allow only owner to reclaim ether', async function() { // Create contract let hasNoEther = await HasNoEtherTest.new({from: accounts[0]}); // Force ether into it let forceEther = await ForceEther.new({value: amount}); await forceEther.destroyAndSend(hasNoEther.address); const forcedBalance = await web3.eth.getBalance(hasNoEther.address); assert.equal(forcedBalance, amount); // Reclaim await expectThrow(hasNoEther.reclaimEther({from: accounts[1]})); }); }); ================================================ FILE: truffle/oz/test/HasNoTokens.js ================================================ 'use strict'; import expectThrow from './helpers/expectThrow'; import toPromise from './helpers/toPromise'; const HasNoTokens = artifacts.require('../contracts/lifecycle/HasNoTokens.sol'); const ERC23TokenMock = artifacts.require('./helpers/ERC23TokenMock.sol'); contract('HasNoTokens', function(accounts) { let hasNoTokens = null; let token = null; beforeEach(async () => { // Create contract and token hasNoTokens = await HasNoTokens.new(); token = await ERC23TokenMock.new(accounts[0], 100); // Force token into contract await token.transfer(hasNoTokens.address, 10); const startBalance = await token.balanceOf(hasNoTokens.address); assert.equal(startBalance, 10); }); it('should not accept ERC23 tokens', async function() { await expectThrow(token.transferERC23(hasNoTokens.address, 10, '')); }); it('should allow owner to reclaim tokens', async function() { const ownerStartBalance = await token.balanceOf(accounts[0]); await hasNoTokens.reclaimToken(token.address); const ownerFinalBalance = await token.balanceOf(accounts[0]); const finalBalance = await token.balanceOf(hasNoTokens.address); assert.equal(finalBalance, 0); assert.equal(ownerFinalBalance - ownerStartBalance, 10); }); it('should allow only owner to reclaim tokens', async function() { await expectThrow( hasNoTokens.reclaimToken(token.address, {from: accounts[1]}), ); }); }); ================================================ FILE: truffle/oz/test/LimitBalance.js ================================================ 'use strict'; var LimitBalanceMock = artifacts.require('helpers/LimitBalanceMock.sol'); const assertRevert = require('./helpers/assertRevert'); contract('LimitBalance', function(accounts) { let lb; beforeEach(async function() { lb = await LimitBalanceMock.new(); }); let LIMIT = 1000; it('should expose limit', async function() { let limit = await lb.limit(); assert.equal(limit, LIMIT); }); it('should allow sending below limit', async function() { let amount = 1; await lb.limitedDeposit({value: amount}); assert.equal(web3.eth.getBalance(lb.address), amount); }); it('shouldnt allow sending above limit', async function() { let amount = 1110; try { await lb.limitedDeposit({value: amount}); assert.fail('should have thrown before'); } catch(error) { assertRevert(error); } }); it('should allow multiple sends below limit', async function() { let amount = 500; await lb.limitedDeposit({value: amount}); assert.equal(web3.eth.getBalance(lb.address), amount); await lb.limitedDeposit({value: amount}); assert.equal(web3.eth.getBalance(lb.address), amount*2); }); it('shouldnt allow multiple sends above limit', async function() { let amount = 500; await lb.limitedDeposit({value: amount}); assert.equal(web3.eth.getBalance(lb.address), amount); try { await lb.limitedDeposit({value: amount+1}); assert.fail('should have thrown before'); } catch(error) { assertRevert(error); } }); }); ================================================ FILE: truffle/oz/test/MerkleProof.js ================================================ var MerkleProof = artifacts.require("./MerkleProof.sol"); import MerkleTree from "./helpers/merkleTree.js"; import { sha3, bufferToHex } from "ethereumjs-util"; contract('MerkleProof', function(accounts) { let merkleProof; before(async function() { merkleProof = await MerkleProof.new(); }); describe("verifyProof", function() { it("should return true for a valid Merkle proof", async function() { const elements = ["a", "b", "c", "d"]; const merkleTree = new MerkleTree(elements); const root = merkleTree.getHexRoot(); const proof = merkleTree.getHexProof(elements[0]); const leaf = bufferToHex(sha3(elements[0])); const result = await merkleProof.verifyProof(proof, root, leaf); assert.isOk(result, "verifyProof did not return true for a valid proof"); }); it("should return false for an invalid Merkle proof", async function() { const correctElements = ["a", "b", "c"] const correctMerkleTree = new MerkleTree(correctElements); const correctRoot = correctMerkleTree.getHexRoot(); const correctLeaf = bufferToHex(sha3(correctElements[0])); const badElements = ["d", "e", "f"] const badMerkleTree = new MerkleTree(badElements) const badProof = badMerkleTree.getHexProof(badElements[0]) const result = await merkleProof.verifyProof(badProof, correctRoot, correctLeaf); assert.isNotOk(result, "verifyProof did not return false for an invalid proof"); }); it("should return false for a Merkle proof of invalid length", async function() { const elements = ["a", "b", "c"] const merkleTree = new MerkleTree(elements); const root = merkleTree.getHexRoot(); const proof = merkleTree.getHexProof(elements[0]); const badProof = proof.slice(0, proof.length - 5); const leaf = bufferToHex(sha3(elements[0])); const result = await merkleProof.verifyProof(badProof, root, leaf); assert.isNotOk(result, "verifyProof did not return false for proof of invalid length"); }) }); }); ================================================ FILE: truffle/oz/test/MintableToken.js ================================================ 'use strict'; import expectThrow from './helpers/expectThrow'; var MintableToken = artifacts.require('../contracts/Tokens/MintableToken.sol'); contract('Mintable', function(accounts) { let token; beforeEach(async function() { token = await MintableToken.new(); }); it('should start with a totalSupply of 0', async function() { let totalSupply = await token.totalSupply(); assert.equal(totalSupply, 0); }); it('should return mintingFinished false after construction', async function() { let mintingFinished = await token.mintingFinished(); assert.equal(mintingFinished, false); }); it('should mint a given amount of tokens to a given address', async function() { const result = await token.mint(accounts[0], 100); assert.equal(result.logs[0].event, 'Mint'); assert.equal(result.logs[0].args.to.valueOf(), accounts[0]); assert.equal(result.logs[0].args.amount.valueOf(), 100); assert.equal(result.logs[1].event, 'Transfer'); assert.equal(result.logs[1].args.from.valueOf(), 0x0); let balance0 = await token.balanceOf(accounts[0]); assert(balance0, 100); let totalSupply = await token.totalSupply(); assert(totalSupply, 100); }) it('should fail to mint after call to finishMinting', async function () { await token.finishMinting(); assert.equal(await token.mintingFinished(), true); await expectThrow(token.mint(accounts[0], 100)); }) }); ================================================ FILE: truffle/oz/test/Ownable.js ================================================ 'use strict'; const assertRevert = require('./helpers/assertRevert'); var Ownable = artifacts.require('../contracts/ownership/Ownable.sol'); contract('Ownable', function(accounts) { let ownable; beforeEach(async function() { ownable = await Ownable.new(); }); it('should have an owner', async function() { let owner = await ownable.owner(); assert.isTrue(owner !== 0); }); it('changes owner after transfer', async function() { let other = accounts[1]; await ownable.transferOwnership(other); let owner = await ownable.owner(); assert.isTrue(owner === other); }); it('should prevent non-owners from transfering', async function() { const other = accounts[2]; const owner = await ownable.owner.call(); assert.isTrue(owner !== other); try { await ownable.transferOwnership(other, {from: other}); assert.fail('should have thrown before'); } catch(error) { assertRevert(error); } }); it('should guard ownership against stuck state', async function() { let originalOwner = await ownable.owner(); try { await ownable.transferOwnership(null, {from: originalOwner}); assert.fail(); } catch(error) { assertRevert(error); } }); }); ================================================ FILE: truffle/oz/test/Pausable.js ================================================ 'use strict'; const assertRevert = require('./helpers/assertRevert'); const PausableMock = artifacts.require('helpers/PausableMock.sol'); contract('Pausable', function(accounts) { it('can perform normal process in non-pause', async function() { let Pausable = await PausableMock.new(); let count0 = await Pausable.count(); assert.equal(count0, 0); await Pausable.normalProcess(); let count1 = await Pausable.count(); assert.equal(count1, 1); }); it('can not perform normal process in pause', async function() { let Pausable = await PausableMock.new(); await Pausable.pause(); let count0 = await Pausable.count(); assert.equal(count0, 0); try { await Pausable.normalProcess(); assert.fail('should have thrown before'); } catch(error) { assertRevert(error); } let count1 = await Pausable.count(); assert.equal(count1, 0); }); it('can not take drastic measure in non-pause', async function() { let Pausable = await PausableMock.new(); try { await Pausable.drasticMeasure(); assert.fail('should have thrown before'); } catch(error) { assertRevert(error); } const drasticMeasureTaken = await Pausable.drasticMeasureTaken(); assert.isFalse(drasticMeasureTaken); }); it('can take a drastic measure in a pause', async function() { let Pausable = await PausableMock.new(); await Pausable.pause(); await Pausable.drasticMeasure(); let drasticMeasureTaken = await Pausable.drasticMeasureTaken(); assert.isTrue(drasticMeasureTaken); }); it('should resume allowing normal process after pause is over', async function() { let Pausable = await PausableMock.new(); await Pausable.pause(); await Pausable.unpause(); await Pausable.normalProcess(); let count0 = await Pausable.count(); assert.equal(count0, 1); }); it('should prevent drastic measure after pause is over', async function() { let Pausable = await PausableMock.new(); await Pausable.pause(); await Pausable.unpause(); try { await Pausable.drasticMeasure(); assert.fail('should have thrown before'); } catch(error) { assertRevert(error); } const drasticMeasureTaken = await Pausable.drasticMeasureTaken(); assert.isFalse(drasticMeasureTaken); }); }); ================================================ FILE: truffle/oz/test/PausableToken.js ================================================ 'user strict'; const assertRevert = require('./helpers/assertRevert'); var PausableTokenMock = artifacts.require('./helpers/PausableTokenMock.sol'); contract('PausableToken', function(accounts) { let token; beforeEach(async function() { token = await PausableTokenMock.new(accounts[0], 100); }); it('should return paused false after construction', async function() { let paused = await token.paused(); assert.equal(paused, false); }); it('should return paused true after pause', async function() { await token.pause(); let paused = await token.paused(); assert.equal(paused, true); }); it('should return paused false after pause and unpause', async function() { await token.pause(); await token.unpause(); let paused = await token.paused(); assert.equal(paused, false); }); it('should be able to transfer if transfers are unpaused', async function() { await token.transfer(accounts[1], 100); let balance0 = await token.balanceOf(accounts[0]); assert.equal(balance0, 0); let balance1 = await token.balanceOf(accounts[1]); assert.equal(balance1, 100); }); it('should be able to transfer after transfers are paused and unpaused', async function() { await token.pause(); await token.unpause(); await token.transfer(accounts[1], 100); let balance0 = await token.balanceOf(accounts[0]); assert.equal(balance0, 0); let balance1 = await token.balanceOf(accounts[1]); assert.equal(balance1, 100); }); it('should throw an error trying to transfer while transactions are paused', async function() { await token.pause(); try { await token.transfer(accounts[1], 100); assert.fail('should have thrown before'); } catch (error) { assertRevert(error); } }); it('should throw an error trying to transfer from another account while transactions are paused', async function() { await token.pause(); try { await token.transferFrom(accounts[0], accounts[1], 100); assert.fail('should have thrown before'); } catch (error) { assertRevert(error); } }); }) ================================================ FILE: truffle/oz/test/PullPayment.js ================================================ var PullPaymentMock = artifacts.require("./helpers/PullPaymentMock.sol"); contract('PullPayment', function(accounts) { let ppce; let amount = 17*1e18; beforeEach(async function() { ppce = await PullPaymentMock.new({value: amount}); }); it("can't call asyncSend externally", async function() { assert.isUndefined(ppce.asyncSend); }); it("can record an async payment correctly", async function() { let AMOUNT = 100; let callSend = await ppce.callSend(accounts[0], AMOUNT); let paymentsToAccount0 = await ppce.payments(accounts[0]); let totalPayments = await ppce.totalPayments(); assert.equal(totalPayments, AMOUNT); assert.equal(paymentsToAccount0, AMOUNT); }); it("can add multiple balances on one account", async function() { let call1 = await ppce.callSend(accounts[0], 200); let call2 = await ppce.callSend(accounts[0], 300); let paymentsToAccount0 = await ppce.payments(accounts[0]); let totalPayments = await ppce.totalPayments(); assert.equal(totalPayments, 500); assert.equal(paymentsToAccount0, 500); }); it("can add balances on multiple accounts", async function() { let call1 = await ppce.callSend(accounts[0], 200); let call2 = await ppce.callSend(accounts[1], 300); let paymentsToAccount0 = await ppce.payments(accounts[0]); assert.equal(paymentsToAccount0, 200); let paymentsToAccount1 = await ppce.payments(accounts[1]); assert.equal(paymentsToAccount1, 300); let totalPayments = await ppce.totalPayments(); assert.equal(totalPayments, 500); }); it("can withdraw payment", async function() { let payee = accounts[1]; let initialBalance = web3.eth.getBalance(payee); let call1 = await ppce.callSend(payee, amount); let payment1 = await ppce.payments(payee); assert.equal(payment1, amount); let totalPayments = await ppce.totalPayments(); assert.equal(totalPayments, amount); let withdraw = await ppce.withdrawPayments({from: payee}); let payment2 = await ppce.payments(payee); assert.equal(payment2, 0); totalPayments = await ppce.totalPayments(); assert.equal(totalPayments, 0); let balance = web3.eth.getBalance(payee); assert(Math.abs(balance-initialBalance-amount) < 1e16); }); }); ================================================ FILE: truffle/oz/test/ReentrancyGuard.js ================================================ 'use strict'; import expectThrow from './helpers/expectThrow'; const ReentrancyMock = artifacts.require('./helper/ReentrancyMock.sol'); const ReentrancyAttack = artifacts.require('./helper/ReentrancyAttack.sol'); contract('ReentrancyGuard', function(accounts) { let reentrancyMock; beforeEach(async function() { reentrancyMock = await ReentrancyMock.new(); let initialCounter = await reentrancyMock.counter(); assert.equal(initialCounter, 0); }); it('should not allow remote callback', async function() { let attacker = await ReentrancyAttack.new(); await expectThrow(reentrancyMock.countAndCall(attacker.address)); }); // The following are more side-effects that intended behaviour: // I put them here as documentation, and to monitor any changes // in the side-effects. it('should not allow local recursion', async function() { await expectThrow(reentrancyMock.countLocalRecursive(10)); }); it('should not allow indirect local recursion', async function() { await expectThrow(reentrancyMock.countThisRecursive(10)); }); }); ================================================ FILE: truffle/oz/test/RefundVault.js ================================================ const BigNumber = web3.BigNumber require('chai') .use(require('chai-as-promised')) .use(require('chai-bignumber')(BigNumber)) .should() import ether from './helpers/ether' import EVMRevert from './helpers/EVMRevert' const RefundVault = artifacts.require('RefundVault') contract('RefundVault', function ([_, owner, wallet, investor]) { const value = ether(42) beforeEach(async function () { this.vault = await RefundVault.new(wallet, {from: owner}) }) it('should accept contributions', async function () { await this.vault.deposit(investor, {value, from: owner}).should.be.fulfilled }) it('should not refund contribution during active state', async function () { await this.vault.deposit(investor, {value, from: owner}) await this.vault.refund(investor).should.be.rejectedWith(EVMRevert) }) it('only owner can enter refund mode', async function () { await this.vault.enableRefunds({from: _}).should.be.rejectedWith(EVMRevert) await this.vault.enableRefunds({from: owner}).should.be.fulfilled }) it('should refund contribution after entering refund mode', async function () { await this.vault.deposit(investor, {value, from: owner}) await this.vault.enableRefunds({from: owner}) const pre = web3.eth.getBalance(investor) await this.vault.refund(investor) const post = web3.eth.getBalance(investor) post.minus(pre).should.be.bignumber.equal(value) }) it('only owner can close', async function () { await this.vault.close({from: _}).should.be.rejectedWith(EVMRevert) await this.vault.close({from: owner}).should.be.fulfilled }) it('should forward funds to wallet after closing', async function () { await this.vault.deposit(investor, {value, from: owner}) const pre = web3.eth.getBalance(wallet) await this.vault.close({from: owner}) const post = web3.eth.getBalance(wallet) post.minus(pre).should.be.bignumber.equal(value) }) }) ================================================ FILE: truffle/oz/test/RefundableCrowdsale.js ================================================ import ether from './helpers/ether' import {advanceBlock} from './helpers/advanceToBlock' import {increaseTimeTo, duration} from './helpers/increaseTime' import latestTime from './helpers/latestTime' import EVMRevert from './helpers/EVMRevert' const BigNumber = web3.BigNumber require('chai') .use(require('chai-as-promised')) .use(require('chai-bignumber')(BigNumber)) .should() const RefundableCrowdsale = artifacts.require('./helpers/RefundableCrowdsaleImpl.sol') contract('RefundableCrowdsale', function ([_, owner, wallet, investor]) { const rate = new BigNumber(1000) const goal = ether(800) const lessThanGoal = ether(750) before(async function() { //Advance to the next block to correctly read time in the solidity "now" function interpreted by testrpc await advanceBlock() }) beforeEach(async function () { this.startTime = latestTime() + duration.weeks(1) this.endTime = this.startTime + duration.weeks(1) this.afterEndTime = this.endTime + duration.seconds(1) this.crowdsale = await RefundableCrowdsale.new(this.startTime, this.endTime, rate, wallet, goal, {from: owner}) }) describe('creating a valid crowdsale', function () { it('should fail with zero goal', async function () { await RefundableCrowdsale.new(this.startTime, this.endTime, rate, wallet, 0, {from: owner}).should.be.rejectedWith(EVMRevert); }) }); it('should deny refunds before end', async function () { await this.crowdsale.claimRefund({from: investor}).should.be.rejectedWith(EVMRevert) await increaseTimeTo(this.startTime) await this.crowdsale.claimRefund({from: investor}).should.be.rejectedWith(EVMRevert) }) it('should deny refunds after end if goal was reached', async function () { await increaseTimeTo(this.startTime) await this.crowdsale.sendTransaction({value: goal, from: investor}) await increaseTimeTo(this.afterEndTime) await this.crowdsale.claimRefund({from: investor}).should.be.rejectedWith(EVMRevert) }) it('should allow refunds after end if goal was not reached', async function () { await increaseTimeTo(this.startTime) await this.crowdsale.sendTransaction({value: lessThanGoal, from: investor}) await increaseTimeTo(this.afterEndTime) await this.crowdsale.finalize({from: owner}) const pre = web3.eth.getBalance(investor) await this.crowdsale.claimRefund({from: investor, gasPrice: 0}) .should.be.fulfilled const post = web3.eth.getBalance(investor) post.minus(pre).should.be.bignumber.equal(lessThanGoal) }) it('should forward funds to wallet after end if goal was reached', async function () { await increaseTimeTo(this.startTime) await this.crowdsale.sendTransaction({value: goal, from: investor}) await increaseTimeTo(this.afterEndTime) const pre = web3.eth.getBalance(wallet) await this.crowdsale.finalize({from: owner}) const post = web3.eth.getBalance(wallet) post.minus(pre).should.be.bignumber.equal(goal) }) }) ================================================ FILE: truffle/oz/test/SafeERC20.js ================================================ import EVMThrow from './helpers/EVMThrow'; require('chai') .use(require('chai-as-promised')) .should(); const SafeERC20Helper = artifacts.require('./helpers/SafeERC20Helper.sol'); contract('SafeERC20', function () { beforeEach(async function () { this.helper = await SafeERC20Helper.new(); }); it('should throw on failed transfer', async function () { await this.helper.doFailingTransfer().should.be.rejectedWith(EVMThrow); }); it('should throw on failed transferFrom', async function () { await this.helper.doFailingTransferFrom().should.be.rejectedWith(EVMThrow); }); it('should throw on failed approve', async function () { await this.helper.doFailingApprove().should.be.rejectedWith(EVMThrow); }); it('should not throw on succeeding transfer', async function () { await this.helper.doSucceedingTransfer().should.be.fulfilled; }); it('should not throw on succeeding transferFrom', async function () { await this.helper.doSucceedingTransferFrom().should.be.fulfilled; }); it('should not throw on succeeding approve', async function () { await this.helper.doSucceedingApprove().should.be.fulfilled; }); }); ================================================ FILE: truffle/oz/test/SafeMath.js ================================================ const assertRevert = require('./helpers/assertRevert'); const assertJump = require('./helpers/assertJump'); var SafeMathMock = artifacts.require("./helpers/SafeMathMock.sol"); contract('SafeMath', function(accounts) { let safeMath; before(async function() { safeMath = await SafeMathMock.new(); }); it("multiplies correctly", async function() { let a = 5678; let b = 1234; let mult = await safeMath.multiply(a, b); let result = await safeMath.result(); assert.equal(result, a*b); }); it("adds correctly", async function() { let a = 5678; let b = 1234; let add = await safeMath.add(a, b); let result = await safeMath.result(); assert.equal(result, a+b); }); it("subtracts correctly", async function() { let a = 5678; let b = 1234; let subtract = await safeMath.subtract(a, b); let result = await safeMath.result(); assert.equal(result, a-b); }); it("should throw an error if subtraction result would be negative", async function () { let a = 1234; let b = 5678; try { let subtract = await safeMath.subtract(a, b); assert.fail('should have thrown before'); } catch(error) { assertJump(error); } }); it("should throw an error on addition overflow", async function() { let a = 115792089237316195423570985008687907853269984665640564039457584007913129639935; let b = 1; try { let add = await safeMath.add(a, b); assert.fail('should have thrown before'); } catch(error) { assertRevert(error); } }); it("should throw an error on multiplication overflow", async function() { let a = 115792089237316195423570985008687907853269984665640564039457584007913129639933; let b = 2; try { let multiply = await safeMath.multiply(a, b); assert.fail('should have thrown before'); } catch(error) { assertRevert(error); } }); }); ================================================ FILE: truffle/oz/test/SampleCrowdsale.js ================================================ import ether from './helpers/ether' import {advanceBlock} from './helpers/advanceToBlock' import {increaseTimeTo, duration} from './helpers/increaseTime' import latestTime from './helpers/latestTime' import EVMRevert from './helpers/EVMRevert' const BigNumber = web3.BigNumber; const should = require('chai') .use(require('chai-as-promised')) .use(require('chai-bignumber')(BigNumber)) .should(); const SampleCrowdsale = artifacts.require('SampleCrowdsale'); const SampleCrowdsaleToken = artifacts.require('SampleCrowdsaleToken'); contract('Crowdsale', function ([owner, wallet, investor]) { const RATE = new BigNumber(10); const GOAL = ether(10); const CAP = ether(20); before(async function() { //Advance to the next block to correctly read time in the solidity "now" function interpreted by testrpc await advanceBlock() }) beforeEach(async function () { this.startTime = latestTime() + duration.weeks(1); this.endTime = this.startTime + duration.weeks(1); this.afterEndTime = this.endTime + duration.seconds(1); this.crowdsale = await SampleCrowdsale.new(this.startTime, this.endTime, RATE, GOAL, CAP, wallet); this.token = SampleCrowdsaleToken.at(await this.crowdsale.token()); }); it('should create crowdsale with correct parameters', async function () { this.crowdsale.should.exist; this.token.should.exist; (await this.crowdsale.startTime()).should.be.bignumber.equal(this.startTime); (await this.crowdsale.endTime()).should.be.bignumber.equal(this.endTime); (await this.crowdsale.rate()).should.be.bignumber.equal(RATE); (await this.crowdsale.wallet()).should.be.equal(wallet); (await this.crowdsale.goal()).should.be.bignumber.equal(GOAL); (await this.crowdsale.cap()).should.be.bignumber.equal(CAP); }); it('should not accept payments before start', async function () { await this.crowdsale.send(ether(1)).should.be.rejectedWith(EVMRevert); await this.crowdsale.buyTokens(investor, {from: investor, value: ether(1)}).should.be.rejectedWith(EVMRevert); }); it('should accept payments during the sale', async function () { const investmentAmount = ether(1); const expectedTokenAmount = RATE.mul(investmentAmount); await increaseTimeTo(this.startTime); await this.crowdsale.buyTokens(investor, {value: investmentAmount, from: investor}).should.be.fulfilled; (await this.token.balanceOf(investor)).should.be.bignumber.equal(expectedTokenAmount); (await this.token.totalSupply()).should.be.bignumber.equal(expectedTokenAmount); }); it('should reject payments after end', async function () { await increaseTimeTo(this.afterEnd); await this.crowdsale.send(ether(1)).should.be.rejectedWith(EVMRevert); await this.crowdsale.buyTokens(investor, {value: ether(1), from: investor}).should.be.rejectedWith(EVMRevert); }); it('should reject payments over cap', async function () { await increaseTimeTo(this.startTime); await this.crowdsale.send(CAP); await this.crowdsale.send(1).should.be.rejectedWith(EVMRevert); }); it('should allow finalization and transfer funds to wallet if the goal is reached', async function () { await increaseTimeTo(this.startTime); await this.crowdsale.send(GOAL); const beforeFinalization = web3.eth.getBalance(wallet); await increaseTimeTo(this.afterEndTime); await this.crowdsale.finalize({from: owner}); const afterFinalization = web3.eth.getBalance(wallet); afterFinalization.minus(beforeFinalization).should.be.bignumber.equal(GOAL); }); it('should allow refunds if the goal is not reached', async function () { const balanceBeforeInvestment = web3.eth.getBalance(investor); await increaseTimeTo(this.startTime); await this.crowdsale.sendTransaction({value: ether(1), from: investor, gasPrice: 0}); await increaseTimeTo(this.afterEndTime); await this.crowdsale.finalize({from: owner}); await this.crowdsale.claimRefund({from: investor, gasPrice: 0}).should.be.fulfilled; const balanceAfterRefund = web3.eth.getBalance(investor); balanceBeforeInvestment.should.be.bignumber.equal(balanceAfterRefund); }); }); ================================================ FILE: truffle/oz/test/SplitPayment.js ================================================ const BigNumber = web3.BigNumber const should = require('chai') .use(require('chai-as-promised')) .use(require('chai-bignumber')(BigNumber)) .should() const EVMThrow = require('./helpers/EVMThrow.js') const SplitPaymentMock = artifacts.require('./helpers/SplitPaymentMock.sol') contract('SplitPayment', function ([owner, payee1, payee2, payee3, nonpayee1, payer1]) { const amount = web3.toWei(1.0, 'ether') beforeEach(async function () { this.payees = [payee1, payee2, payee3] this.shares = [20, 10, 70] this.contract = await SplitPaymentMock.new(this.payees, this.shares) }) it('should accept payments', async function () { await web3.eth.sendTransaction({ from: owner, to: this.contract.address, value: amount }) const balance = web3.eth.getBalance(this.contract.address) balance.should.be.bignumber.equal(amount) }) it('should store shares if address is payee', async function () { const shares = await this.contract.shares.call(payee1) shares.should.be.bignumber.not.equal(0) }) it('should not store shares if address is not payee', async function () { const shares = await this.contract.shares.call(nonpayee1) shares.should.be.bignumber.equal(0) }) it('should throw if no funds to claim', async function () { await this.contract.claim({from: payee1}).should.be.rejectedWith(EVMThrow) }) it('should throw if non-payee want to claim', async function () { await web3.eth.sendTransaction({from: payer1, to: this.contract.address, value: amount}) await this.contract.claim({from: nonpayee1}).should.be.rejectedWith(EVMThrow) }) it('should distribute funds to payees', async function () { await web3.eth.sendTransaction({from: payer1, to: this.contract.address, value: amount}) // receive funds const initBalance = web3.eth.getBalance(this.contract.address) initBalance.should.be.bignumber.equal(amount) // distribute to payees const initAmount1 = web3.eth.getBalance(payee1) await this.contract.claim({from: payee1}) const profit1 = web3.eth.getBalance(payee1) - initAmount1 assert(Math.abs(profit1 - web3.toWei(0.20, 'ether')) < 1e16) const initAmount2 = web3.eth.getBalance(payee2) await this.contract.claim({from: payee2}) const profit2 = web3.eth.getBalance(payee2) - initAmount2 assert(Math.abs(profit2 - web3.toWei(0.10, 'ether')) < 1e16) const initAmount3 = web3.eth.getBalance(payee3) await this.contract.claim({from: payee3}) const profit3 = web3.eth.getBalance(payee3) - initAmount3 assert(Math.abs(profit3 - web3.toWei(0.70, 'ether')) < 1e16) // end balance should be zero const endBalance = web3.eth.getBalance(this.contract.address) endBalance.should.be.bignumber.equal(0) // check correct funds released accounting const totalReleased = await this.contract.totalReleased.call() totalReleased.should.be.bignumber.equal(initBalance) }) }) ================================================ FILE: truffle/oz/test/StandardToken.js ================================================ 'use strict'; const assertRevert = require('./helpers/assertRevert'); const expectThrow = require('./helpers/expectThrow'); var StandardTokenMock = artifacts.require('./helpers/StandardTokenMock.sol'); contract('StandardToken', function(accounts) { let token; beforeEach(async function() { token = await StandardTokenMock.new(accounts[0], 100); }); it('should return the correct totalSupply after construction', async function() { let totalSupply = await token.totalSupply(); assert.equal(totalSupply, 100); }); it('should return the correct allowance amount after approval', async function() { let token = await StandardTokenMock.new(); await token.approve(accounts[1], 100); let allowance = await token.allowance(accounts[0], accounts[1]); assert.equal(allowance, 100); }); it('should return correct balances after transfer', async function() { let token = await StandardTokenMock.new(accounts[0], 100); await token.transfer(accounts[1], 100); let balance0 = await token.balanceOf(accounts[0]); assert.equal(balance0, 0); let balance1 = await token.balanceOf(accounts[1]); assert.equal(balance1, 100); }); it('should throw an error when trying to transfer more than balance', async function() { let token = await StandardTokenMock.new(accounts[0], 100); try { await token.transfer(accounts[1], 101); assert.fail('should have thrown before'); } catch(error) { assertRevert(error); } }); it('should return correct balances after transfering from another account', async function() { let token = await StandardTokenMock.new(accounts[0], 100); await token.approve(accounts[1], 100); await token.transferFrom(accounts[0], accounts[2], 100, {from: accounts[1]}); let balance0 = await token.balanceOf(accounts[0]); assert.equal(balance0, 0); let balance1 = await token.balanceOf(accounts[2]); assert.equal(balance1, 100); let balance2 = await token.balanceOf(accounts[1]); assert.equal(balance2, 0); }); it('should throw an error when trying to transfer more than allowed', async function() { await token.approve(accounts[1], 99); try { await token.transferFrom(accounts[0], accounts[2], 100, {from: accounts[1]}); assert.fail('should have thrown before'); } catch (error) { assertRevert(error); } }); it('should throw an error when trying to transferFrom more than _from has', async function() { let balance0 = await token.balanceOf(accounts[0]); await token.approve(accounts[1], 99); try { await token.transferFrom(accounts[0], accounts[2], balance0+1, {from: accounts[1]}); assert.fail('should have thrown before'); } catch (error) { assertRevert(error); } }); describe('validating allowance updates to spender', function() { let preApproved; it('should start with zero', async function() { preApproved = await token.allowance(accounts[0], accounts[1]); assert.equal(preApproved, 0); }) it('should increase by 50 then decrease by 10', async function() { await token.increaseApproval(accounts[1], 50); let postIncrease = await token.allowance(accounts[0], accounts[1]); preApproved.plus(50).should.be.bignumber.equal(postIncrease); await token.decreaseApproval(accounts[1], 10); let postDecrease = await token.allowance(accounts[0], accounts[1]); postIncrease.minus(10).should.be.bignumber.equal(postDecrease); }) }); it('should increase by 50 then set to 0 when decreasing by more than 50', async function() { await token.approve(accounts[1], 50); await token.decreaseApproval(accounts[1], 60); let postDecrease = await token.allowance(accounts[0], accounts[1]); postDecrease.should.be.bignumber.equal(0); }); it('should throw an error when trying to transfer to 0x0', async function() { let token = await StandardTokenMock.new(accounts[0], 100); try { let transfer = await token.transfer(0x0, 100); assert.fail('should have thrown before'); } catch(error) { assertRevert(error); } }); it('should throw an error when trying to transferFrom to 0x0', async function() { let token = await StandardTokenMock.new(accounts[0], 100); await token.approve(accounts[1], 100); try { let transfer = await token.transferFrom(accounts[0], 0x0, 100, {from: accounts[1]}); assert.fail('should have thrown before'); } catch(error) { assertRevert(error); } }); }); ================================================ FILE: truffle/oz/test/TestMetacoin.sol ================================================ pragma solidity ^0.4.2; import "truffle/Assert.sol"; import "truffle/DeployedAddresses.sol"; import "../contracts/MetaCoin.sol"; contract TestMetacoin { function testInitialBalanceUsingDeployedContract() { MetaCoin meta = MetaCoin(DeployedAddresses.MetaCoin()); uint expected = 10000; Assert.equal(meta.getBalance(tx.origin), expected, "Owner should have 10000 MetaCoin initially"); } function testInitialBalanceWithNewMetaCoin() { MetaCoin meta = new MetaCoin(); uint expected = 10000; Assert.equal(meta.getBalance(tx.origin), expected, "Owner should have 10000 MetaCoin initially"); } } ================================================ FILE: truffle/oz/test/TokenDestructible.js ================================================ 'use strict'; var TokenDestructible = artifacts.require('../contracts/lifecycle/TokenDestructible.sol'); var StandardTokenMock = artifacts.require("./helpers/StandardTokenMock.sol"); require('./helpers/transactionMined.js'); contract('TokenDestructible', function(accounts) { let destructible; beforeEach(async function() { destructible = await TokenDestructible.new({fron: accounts[0], value: web3.toWei('10', 'ether')}); }); it('should send balance to owner after destruction', async function() { let owner = await destructible.owner(); let initBalance = web3.eth.getBalance(owner); await destructible.destroy([], {from: owner}); let newBalance = web3.eth.getBalance(owner); assert.isTrue(newBalance > initBalance); }); it('should send tokens to owner after destruction', async function() { let owner = await destructible.owner(); let token = await StandardTokenMock.new(destructible.address, 100); let initContractBalance = await token.balanceOf(destructible.address); let initOwnerBalance = await token.balanceOf(owner); assert.equal(initContractBalance, 100); assert.equal(initOwnerBalance, 0); await destructible.destroy([token.address], {from: owner}); let newContractBalance = await token.balanceOf(destructible.address); let newOwnerBalance = await token.balanceOf(owner); assert.equal(newContractBalance, 0); assert.equal(newOwnerBalance, 100); }); }); ================================================ FILE: truffle/oz/test/TokenTimelock.js ================================================ const BigNumber = web3.BigNumber require('chai') .use(require('chai-as-promised')) .use(require('chai-bignumber')(BigNumber)) .should() import latestTime from './helpers/latestTime' import {increaseTimeTo, duration} from './helpers/increaseTime' const MintableToken = artifacts.require('MintableToken') const TokenTimelock = artifacts.require('TokenTimelock') contract('TokenTimelock', function ([_, owner, beneficiary]) { const amount = new BigNumber(100) beforeEach(async function () { this.token = await MintableToken.new({from: owner}) this.releaseTime = latestTime() + duration.years(1) this.timelock = await TokenTimelock.new(this.token.address, beneficiary, this.releaseTime) await this.token.mint(this.timelock.address, amount, {from: owner}) }) it('cannot be released before time limit', async function () { await this.timelock.release().should.be.rejected }) it('cannot be released just before time limit', async function () { await increaseTimeTo(this.releaseTime - duration.seconds(3)) await this.timelock.release().should.be.rejected }) it('can be released just after limit', async function () { await increaseTimeTo(this.releaseTime + duration.seconds(1)) await this.timelock.release().should.be.fulfilled const balance = await this.token.balanceOf(beneficiary) balance.should.be.bignumber.equal(amount) }) it('can be released after time limit', async function () { await increaseTimeTo(this.releaseTime + duration.years(1)) await this.timelock.release().should.be.fulfilled const balance = await this.token.balanceOf(beneficiary) balance.should.be.bignumber.equal(amount) }) it('cannot be released twice', async function () { await increaseTimeTo(this.releaseTime + duration.years(1)) await this.timelock.release().should.be.fulfilled await this.timelock.release().should.be.rejected const balance = await this.token.balanceOf(beneficiary) balance.should.be.bignumber.equal(amount) }) }) ================================================ FILE: truffle/oz/test/TokenVesting.js ================================================ const BigNumber = web3.BigNumber require('chai') .use(require('chai-as-promised')) .use(require('chai-bignumber')(BigNumber)) .should(); import EVMRevert from './helpers/EVMRevert' import latestTime from './helpers/latestTime'; import {increaseTimeTo, duration} from './helpers/increaseTime'; const MintableToken = artifacts.require('MintableToken'); const TokenVesting = artifacts.require('TokenVesting'); contract('TokenVesting', function ([_, owner, beneficiary]) { const amount = new BigNumber(1000); beforeEach(async function () { this.token = await MintableToken.new({ from: owner }); this.start = latestTime() + duration.minutes(1); // +1 minute so it starts after contract instantiation this.cliff = duration.years(1); this.duration = duration.years(2); this.vesting = await TokenVesting.new(beneficiary, this.start, this.cliff, this.duration, true, { from: owner }); await this.token.mint(this.vesting.address, amount, { from: owner }); }); it('cannot be released before cliff', async function () { await this.vesting.release(this.token.address).should.be.rejectedWith(EVMRevert); }); it('can be released after cliff', async function () { await increaseTimeTo(this.start + this.cliff + duration.weeks(1)); await this.vesting.release(this.token.address).should.be.fulfilled; }); it('should release proper amount after cliff', async function () { await increaseTimeTo(this.start + this.cliff); const { receipt } = await this.vesting.release(this.token.address); const releaseTime = web3.eth.getBlock(receipt.blockNumber).timestamp; const balance = await this.token.balanceOf(beneficiary); balance.should.bignumber.equal(amount.mul(releaseTime - this.start).div(this.duration).floor()); }); it('should linearly release tokens during vesting period', async function () { const vestingPeriod = this.duration - this.cliff; const checkpoints = 4; for (let i = 1; i <= checkpoints; i++) { const now = this.start + this.cliff + i * (vestingPeriod / checkpoints); await increaseTimeTo(now); await this.vesting.release(this.token.address); const balance = await this.token.balanceOf(beneficiary); const expectedVesting = amount.mul(now - this.start).div(this.duration).floor(); balance.should.bignumber.equal(expectedVesting); } }); it('should have released all after end', async function () { await increaseTimeTo(this.start + this.duration); await this.vesting.release(this.token.address); const balance = await this.token.balanceOf(beneficiary); balance.should.bignumber.equal(amount); }); it('should be revoked by owner if revocable is set', async function () { await this.vesting.revoke(this.token.address, { from: owner }).should.be.fulfilled; }); it('should fail to be revoked by owner if revocable not set', async function () { const vesting = await TokenVesting.new(beneficiary, this.start, this.cliff, this.duration, false, { from: owner } ); await vesting.revoke(this.token.address, { from: owner }).should.be.rejectedWith(EVMRevert); }); it('should return the non-vested tokens when revoked by owner', async function () { await increaseTimeTo(this.start + this.cliff + duration.weeks(12)); const vested = await this.vesting.vestedAmount(this.token.address); await this.vesting.revoke(this.token.address, { from: owner }); const ownerBalance = await this.token.balanceOf(owner); ownerBalance.should.bignumber.equal(amount.sub(vested)); }); it('should keep the vested tokens when revoked by owner', async function () { await increaseTimeTo(this.start + this.cliff + duration.weeks(12)); const vestedPre = await this.vesting.vestedAmount(this.token.address); await this.vesting.revoke(this.token.address, { from: owner }); const vestedPost = await this.vesting.vestedAmount(this.token.address); vestedPre.should.bignumber.equal(vestedPost); }); it('should fail to be revoked a second time', async function () { await increaseTimeTo(this.start + this.cliff + duration.weeks(12)); const vested = await this.vesting.vestedAmount(this.token.address); await this.vesting.revoke(this.token.address, { from: owner }); await this.vesting.revoke(this.token.address, { from: owner }).should.be.rejectedWith(EVMRevert); }); }); ================================================ FILE: truffle/oz/test/helpers/BasicTokenMock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/token/BasicToken.sol'; // mock class using BasicToken contract BasicTokenMock is BasicToken { function BasicTokenMock(address initialAccount, uint256 initialBalance) public { balances[initialAccount] = initialBalance; totalSupply = initialBalance; } } ================================================ FILE: truffle/oz/test/helpers/BurnableTokenMock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/token/BurnableToken.sol'; contract BurnableTokenMock is BurnableToken { function BurnableTokenMock(address initialAccount, uint initialBalance) public { balances[initialAccount] = initialBalance; totalSupply = initialBalance; } } ================================================ FILE: truffle/oz/test/helpers/CappedCrowdsaleImpl.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/crowdsale/CappedCrowdsale.sol'; contract CappedCrowdsaleImpl is CappedCrowdsale { function CappedCrowdsaleImpl ( uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _cap ) public Crowdsale(_startTime, _endTime, _rate, _wallet) CappedCrowdsale(_cap) { } } ================================================ FILE: truffle/oz/test/helpers/DayLimitMock.sol ================================================ pragma solidity ^0.4.18; import "../../contracts/DayLimit.sol"; contract DayLimitMock is DayLimit { uint256 public totalSpending; function DayLimitMock(uint256 _value) public DayLimit(_value) { totalSpending = 0; } function attemptSpend(uint256 _value) external limitedDaily(_value) { totalSpending += _value; } function setDailyLimit(uint256 _newLimit) external { _setDailyLimit(_newLimit); } function resetSpentToday() external { _resetSpentToday(); } } ================================================ FILE: truffle/oz/test/helpers/DetailedERC20Mock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/token/StandardToken.sol'; import '../../contracts/token/DetailedERC20.sol'; contract DetailedERC20Mock is StandardToken, DetailedERC20 { function DetailedERC20Mock(string _name, string _symbol, uint8 _decimals) DetailedERC20(_name, _symbol, _decimals) public {} } ================================================ FILE: truffle/oz/test/helpers/ERC23TokenMock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/token/BasicToken.sol'; contract ERC23ContractInterface { function tokenFallback(address _from, uint256 _value, bytes _data) external; } contract ERC23TokenMock is BasicToken { function ERC23TokenMock(address initialAccount, uint256 initialBalance) public { balances[initialAccount] = initialBalance; totalSupply = initialBalance; } // ERC23 compatible transfer function (except the name) function transferERC23(address _to, uint256 _value, bytes _data) public returns (bool success) { transfer(_to, _value); bool is_contract = false; assembly { is_contract := not(iszero(extcodesize(_to))) } if(is_contract) { ERC23ContractInterface receiver = ERC23ContractInterface(_to); receiver.tokenFallback(msg.sender, _value, _data); } return true; } } ================================================ FILE: truffle/oz/test/helpers/EVMRevert.js ================================================ export default 'revert' ================================================ FILE: truffle/oz/test/helpers/EVMThrow.js ================================================ export default 'invalid opcode' ================================================ FILE: truffle/oz/test/helpers/FinalizableCrowdsaleImpl.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/crowdsale/FinalizableCrowdsale.sol'; contract FinalizableCrowdsaleImpl is FinalizableCrowdsale { function FinalizableCrowdsaleImpl ( uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet ) public Crowdsale(_startTime, _endTime, _rate, _wallet) FinalizableCrowdsale() { } } ================================================ FILE: truffle/oz/test/helpers/ForceEther.sol ================================================ pragma solidity ^0.4.18; // @title Force Ether into a contract. // @notice even // if the contract is not payable. // @notice To use, construct the contract with the target as argument. // @author Remco Bloemen contract ForceEther { function ForceEther() public payable { } function destroyAndSend(address _recipient) public { selfdestruct(_recipient); } } ================================================ FILE: truffle/oz/test/helpers/HasNoEtherTest.sol ================================================ pragma solidity ^0.4.18; import "../../contracts/ownership/HasNoEther.sol"; contract HasNoEtherTest is HasNoEther { // Constructor with explicit payable — should still fail function HasNoEtherTest() public payable { } } ================================================ FILE: truffle/oz/test/helpers/InsecureTargetBounty.sol ================================================ pragma solidity ^0.4.18; import {Bounty, Target} from "../../contracts/Bounty.sol"; contract InsecureTargetMock is Target { function checkInvariant() public returns(bool){ return false; } } contract InsecureTargetBounty is Bounty { function deployContract() internal returns (address) { return new InsecureTargetMock(); } } ================================================ FILE: truffle/oz/test/helpers/LimitBalanceMock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/LimitBalance.sol'; // mock class using LimitBalance contract LimitBalanceMock is LimitBalance(1000) { function limitedDeposit() public payable limitedPayable { } } ================================================ FILE: truffle/oz/test/helpers/PausableMock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/lifecycle/Pausable.sol'; // mock class using Pausable contract PausableMock is Pausable { bool public drasticMeasureTaken; uint256 public count; function PausableMock() public { drasticMeasureTaken = false; count = 0; } function normalProcess() external whenNotPaused { count++; } function drasticMeasure() external whenPaused { drasticMeasureTaken = true; } } ================================================ FILE: truffle/oz/test/helpers/PausableTokenMock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/token/PausableToken.sol'; // mock class using PausableToken contract PausableTokenMock is PausableToken { function PausableTokenMock(address initialAccount, uint initialBalance) public { balances[initialAccount] = initialBalance; } } ================================================ FILE: truffle/oz/test/helpers/PullPaymentMock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/payment/PullPayment.sol'; // mock class using PullPayment contract PullPaymentMock is PullPayment { function PullPaymentMock() public payable { } // test helper function to call asyncSend function callSend(address dest, uint256 amount) public { asyncSend(dest, amount); } } ================================================ FILE: truffle/oz/test/helpers/ReentrancyAttack.sol ================================================ pragma solidity ^0.4.18; contract ReentrancyAttack { function callSender(bytes4 data) public { require(msg.sender.call(data)); } } ================================================ FILE: truffle/oz/test/helpers/ReentrancyMock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/ReentrancyGuard.sol'; import './ReentrancyAttack.sol'; contract ReentrancyMock is ReentrancyGuard { uint256 public counter; function ReentrancyMock() public { counter = 0; } function count() private { counter += 1; } function countLocalRecursive(uint256 n) public nonReentrant { if(n > 0) { count(); countLocalRecursive(n - 1); } } function countThisRecursive(uint256 n) public nonReentrant { bytes4 func = bytes4(keccak256("countThisRecursive(uint256)")); if(n > 0) { count(); bool result = this.call(func, n - 1); require(result == true); } } function countAndCall(ReentrancyAttack attacker) public nonReentrant { count(); bytes4 func = bytes4(keccak256("callback()")); attacker.callSender(func); } function callback() external nonReentrant { count(); } } ================================================ FILE: truffle/oz/test/helpers/RefundableCrowdsaleImpl.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/crowdsale/RefundableCrowdsale.sol'; contract RefundableCrowdsaleImpl is RefundableCrowdsale { function RefundableCrowdsaleImpl ( uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _goal ) public Crowdsale(_startTime, _endTime, _rate, _wallet) RefundableCrowdsale(_goal) { } } ================================================ FILE: truffle/oz/test/helpers/SafeERC20Helper.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/token/ERC20.sol'; import '../../contracts/token/SafeERC20.sol'; contract ERC20FailingMock is ERC20 { function transfer(address, uint256) public returns (bool) { return false; } function transferFrom(address, address, uint256) public returns (bool) { return false; } function approve(address, uint256) public returns (bool) { return false; } function balanceOf(address) public constant returns (uint256) { return 0; } function allowance(address, address) public constant returns (uint256) { return 0; } } contract ERC20SucceedingMock is ERC20 { function transfer(address, uint256) public returns (bool) { return true; } function transferFrom(address, address, uint256) public returns (bool) { return true; } function approve(address, uint256) public returns (bool) { return true; } function balanceOf(address) public constant returns (uint256) { return 0; } function allowance(address, address) public constant returns (uint256) { return 0; } } contract SafeERC20Helper { using SafeERC20 for ERC20; ERC20 failing; ERC20 succeeding; function SafeERC20Helper() public { failing = new ERC20FailingMock(); succeeding = new ERC20SucceedingMock(); } function doFailingTransfer() public { failing.safeTransfer(0, 0); } function doFailingTransferFrom() public { failing.safeTransferFrom(0, 0, 0); } function doFailingApprove() public { failing.safeApprove(0, 0); } function doSucceedingTransfer() public { succeeding.safeTransfer(0, 0); } function doSucceedingTransferFrom() public { succeeding.safeTransferFrom(0, 0, 0); } function doSucceedingApprove() public { succeeding.safeApprove(0, 0); } } ================================================ FILE: truffle/oz/test/helpers/SafeMathMock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/math/SafeMath.sol'; contract SafeMathMock { uint256 public result; function multiply(uint256 a, uint256 b) public { result = SafeMath.mul(a, b); } function subtract(uint256 a, uint256 b) public { result = SafeMath.sub(a, b); } function add(uint256 a, uint256 b) public { result = SafeMath.add(a, b); } } ================================================ FILE: truffle/oz/test/helpers/SecureTargetBounty.sol ================================================ pragma solidity ^0.4.18; import {Bounty, Target} from "../../contracts/Bounty.sol"; contract SecureTargetMock is Target { function checkInvariant() public returns(bool) { return true; } } contract SecureTargetBounty is Bounty { function deployContract() internal returns (address) { return new SecureTargetMock(); } } ================================================ FILE: truffle/oz/test/helpers/SplitPaymentMock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/payment/SplitPayment.sol'; // mock class using SplitPayment contract SplitPaymentMock is SplitPayment { function SplitPaymentMock(address[] _payees, uint256[] _shares) public SplitPayment(_payees, _shares) payable {} function () external payable {} } ================================================ FILE: truffle/oz/test/helpers/StandardTokenMock.sol ================================================ pragma solidity ^0.4.18; import '../../contracts/token/StandardToken.sol'; // mock class using StandardToken contract StandardTokenMock is StandardToken { function StandardTokenMock(address initialAccount, uint256 initialBalance) public { balances[initialAccount] = initialBalance; totalSupply = initialBalance; } } ================================================ FILE: truffle/oz/test/helpers/advanceToBlock.js ================================================ export function advanceBlock() { return new Promise((resolve, reject) => { web3.currentProvider.sendAsync({ jsonrpc: '2.0', method: 'evm_mine', id: Date.now(), }, (err, res) => { return err ? reject(err) : resolve(res) }) }) } // Advances the block number so that the last mined block is `number`. export default async function advanceToBlock(number) { if (web3.eth.blockNumber > number) { throw Error(`block number ${number} is in the past (current is ${web3.eth.blockNumber})`) } while (web3.eth.blockNumber < number) { await advanceBlock() } } ================================================ FILE: truffle/oz/test/helpers/assertJump.js ================================================ module.exports = function(error) { assert.isAbove(error.message.search('invalid opcode'), -1, 'Invalid opcode error must be returned'); } ================================================ FILE: truffle/oz/test/helpers/assertRevert.js ================================================ module.exports = function(error) { assert.isAbove(error.message.search('revert'), -1, 'Error containing "revert" must be returned'); } ================================================ FILE: truffle/oz/test/helpers/ether.js ================================================ export default function ether(n) { return new web3.BigNumber(web3.toWei(n, 'ether')) } ================================================ FILE: truffle/oz/test/helpers/expectThrow.js ================================================ export default async promise => { try { await promise; } catch (error) { // TODO: Check jump destination to destinguish between a throw // and an actual invalid jump. const invalidOpcode = error.message.search('invalid opcode') >= 0; // TODO: When we contract A calls contract B, and B throws, instead // of an 'invalid jump', we get an 'out of gas' error. How do // we distinguish this from an actual out of gas event? (The // testrpc log actually show an 'invalid jump' event.) const outOfGas = error.message.search('out of gas') >= 0; const revert = error.message.search('revert') >= 0; assert( invalidOpcode || outOfGas || revert, "Expected throw, got '" + error + "' instead", ); return; } assert.fail('Expected throw not received'); }; ================================================ FILE: truffle/oz/test/helpers/hashMessage.js ================================================ import utils from 'ethereumjs-util'; // Hash and add same prefix to the hash that testrpc use. module.exports = function(message) { const messageHex = new Buffer(utils.sha3(message).toString('hex'), 'hex'); const prefix = utils.toBuffer('\u0019Ethereum Signed Message:\n' + messageHex.length.toString()); return utils.bufferToHex( utils.sha3(Buffer.concat([prefix, messageHex])) ); }; ================================================ FILE: truffle/oz/test/helpers/increaseTime.js ================================================ import latestTime from './latestTime' // Increases testrpc time by the passed duration in seconds export default function increaseTime(duration) { const id = Date.now() return new Promise((resolve, reject) => { web3.currentProvider.sendAsync({ jsonrpc: '2.0', method: 'evm_increaseTime', params: [duration], id: id, }, err1 => { if (err1) return reject(err1) web3.currentProvider.sendAsync({ jsonrpc: '2.0', method: 'evm_mine', id: id+1, }, (err2, res) => { return err2 ? reject(err2) : resolve(res) }) }) }) } /** * Beware that due to the need of calling two separate testrpc methods and rpc calls overhead * it's hard to increase time precisely to a target point so design your test to tolerate * small fluctuations from time to time. * * @param target time in seconds */ export function increaseTimeTo(target) { let now = latestTime(); if (target < now) throw Error(`Cannot increase current time(${now}) to a moment in the past(${target})`); let diff = target - now; return increaseTime(diff); } export const duration = { seconds: function(val) { return val}, minutes: function(val) { return val * this.seconds(60) }, hours: function(val) { return val * this.minutes(60) }, days: function(val) { return val * this.hours(24) }, weeks: function(val) { return val * this.days(7) }, years: function(val) { return val * this.days(365)} }; ================================================ FILE: truffle/oz/test/helpers/latestTime.js ================================================ // Returns the time of the last mined block in seconds export default function latestTime() { return web3.eth.getBlock('latest').timestamp; } ================================================ FILE: truffle/oz/test/helpers/merkleTree.js ================================================ import { sha3, bufferToHex } from "ethereumjs-util"; export default class MerkleTree { constructor(elements) { // Filter empty strings and hash elements this.elements = elements.filter(el => el).map(el => sha3(el)); // Deduplicate elements this.elements = this.bufDedup(this.elements); // Sort elements this.elements.sort(Buffer.compare); // Create layers this.layers = this.getLayers(this.elements); } getLayers(elements) { if (elements.length == 0) { return [[""]]; } const layers = []; layers.push(elements); // Get next layer until we reach the root while (layers[layers.length - 1].length > 1) { layers.push(this.getNextLayer(layers[layers.length - 1])); } return layers; } getNextLayer(elements) { return elements.reduce((layer, el, idx, arr) => { if (idx % 2 === 0) { // Hash the current element with its pair element layer.push(this.combinedHash(el, arr[idx + 1])); } return layer; }, []); } combinedHash(first, second) { if (!first) { return second; } if (!second) { return first; } return sha3(this.sortAndConcat(first, second)); } getRoot() { return this.layers[this.layers.length - 1][0]; } getHexRoot() { return bufferToHex(this.getRoot()); } getProof(el) { let idx = this.bufIndexOf(el, this.elements); if (idx === -1) { throw new Error("Element does not exist in Merkle tree"); } return this.layers.reduce((proof, layer) => { const pairElement = this.getPairElement(idx, layer); if (pairElement) { proof.push(pairElement); } idx = Math.floor(idx / 2); return proof; }, []); } getHexProof(el) { const proof = this.getProof(el); return this.bufArrToHex(proof); } getPairElement(idx, layer) { const pairIdx = idx % 2 === 0 ? idx + 1 : idx - 1; if (pairIdx < layer.length) { return layer[pairIdx]; } else { return null; } } bufIndexOf(el, arr) { let hash; // Convert element to 32 byte hash if it is not one already if (el.length !== 32 || !Buffer.isBuffer(el)) { hash = sha3(el); } else { hash = el; } for (let i = 0; i < arr.length; i++) { if (hash.equals(arr[i])) { return i; } } return -1; } bufDedup(elements) { return elements.filter((el, idx) => { return this.bufIndexOf(el, elements) === idx; }); } bufArrToHex(arr) { if (arr.some(el => !Buffer.isBuffer(el))) { throw new Error("Array is not an array of buffers"); } return "0x" + arr.map(el => el.toString("hex")).join(""); } sortAndConcat(...args) { return Buffer.concat([...args].sort(Buffer.compare)); } } ================================================ FILE: truffle/oz/test/helpers/toPromise.js ================================================ export default func => (...args) => new Promise((accept, reject) => func(...args, (error, data) => error ? reject(error) : accept(data))); ================================================ FILE: truffle/oz/test/helpers/transactionMined.js ================================================ 'use strict'; //from https://gist.github.com/xavierlepretre/88682e871f4ad07be4534ae560692ee6 module.export = web3.eth.transactionMined = function (txnHash, interval) { var transactionReceiptAsync; interval = interval ? interval : 500; transactionReceiptAsync = function(txnHash, resolve, reject) { try { var receipt = web3.eth.getTransactionReceipt(txnHash); if (receipt === null) { setTimeout(function () { transactionReceiptAsync(txnHash, resolve, reject); }, interval); } else { resolve(receipt); } } catch(e) { reject(e); } }; if (Array.isArray(txnHash)) { var promises = []; txnHash.forEach(function (oneTxHash) { promises.push( web3.eth.getTransactionReceiptMined(oneTxHash, interval)); }); return Promise.all(promises); } else { return new Promise(function (resolve, reject) { transactionReceiptAsync(txnHash, resolve, reject); }); } }; ================================================ FILE: truffle/oz/test/metacoin.js ================================================ var MetaCoin = artifacts.require("./MetaCoin.sol"); contract('MetaCoin', function(accounts) { it("should put 10000 MetaCoin in the first account", function() { return MetaCoin.deployed().then(function(instance) { return instance.getBalance.call(accounts[0]); }).then(function(balance) { assert.equal(balance.valueOf(), 10000, "10000 wasn't in the first account"); }); }); it("should call a function that depends on a linked library", function() { var meta; var metaCoinBalance; var metaCoinEthBalance; return MetaCoin.deployed().then(function(instance) { meta = instance; return meta.getBalance.call(accounts[0]); }).then(function(outCoinBalance) { metaCoinBalance = outCoinBalance.toNumber(); return meta.getBalanceInEth.call(accounts[0]); }).then(function(outCoinBalanceEth) { metaCoinEthBalance = outCoinBalanceEth.toNumber(); }).then(function() { assert.equal(metaCoinEthBalance, 2 * metaCoinBalance, "Library function returned unexpected function, linkage may be broken"); }); }); it("should send coin correctly", function() { var meta; // Get initial balances of first and second account. var account_one = accounts[0]; var account_two = accounts[1]; var account_one_starting_balance; var account_two_starting_balance; var account_one_ending_balance; var account_two_ending_balance; var amount = 10; return MetaCoin.deployed().then(function(instance) { meta = instance; return meta.getBalance.call(account_one); }).then(function(balance) { account_one_starting_balance = balance.toNumber(); return meta.getBalance.call(account_two); }).then(function(balance) { account_two_starting_balance = balance.toNumber(); return meta.sendCoin(account_two, amount, {from: account_one}); }).then(function() { return meta.getBalance.call(account_one); }).then(function(balance) { account_one_ending_balance = balance.toNumber(); return meta.getBalance.call(account_two); }).then(function(balance) { account_two_ending_balance = balance.toNumber(); assert.equal(account_one_ending_balance, account_one_starting_balance - amount, "Amount wasn't correctly taken from the sender"); assert.equal(account_two_ending_balance, account_two_starting_balance + amount, "Amount wasn't correctly sent to the receiver"); }); }); }); ================================================ FILE: truffle/oz/truffle.js ================================================ module.exports = { networks: { development: { host: "localhost", port: 8545, gas: 3000000, network_id: "*" // Match any network id } } }; ================================================ FILE: truffle/ozex/README.md ================================================ ## OpenZeppelin sample Run ``` npm install zeppelin-solidity truffle test ``` ================================================ FILE: truffle/ozex/contracts/ExampleToken.sol ================================================ pragma solidity ^0.4.11; import "zeppelin-solidity/contracts/token/StandardToken.sol"; contract ExampleToken is StandardToken { string public name = "ExampleToken"; string public symbol = "EGT"; uint public decimals = 18; uint public INITIAL_SUPPLY = 10000; function ExampleToken() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } } ================================================ FILE: truffle/ozex/contracts/Migrations.sol ================================================ pragma solidity ^0.4.17; contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } function Migrations() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } ================================================ FILE: truffle/ozex/migrations/1_initial_migration.js ================================================ var Migrations = artifacts.require("./Migrations.sol"); module.exports = function(deployer) { deployer.deploy(Migrations); }; ================================================ FILE: truffle/ozex/migrations/2_deploy_contracts.js ================================================ var ExampleToken = artifacts.require("./ExampleToken.sol"); module.exports = function(deployer) { deployer.deploy(ExampleToken); }; ================================================ FILE: truffle/ozex/test/exampletoken.js ================================================ var ExampleToken = artifacts.require("ExampleToken.sol"); contract('ExampleToken', function(accounts) { it("should return the correct totalSupply after construction", async function() { let token = await ExampleToken.new(accounts[0], 100); let totalSupply = await token.totalSupply(); console.log('total supply', totalSupply); assert.equal(totalSupply, 10000); }) }); ================================================ FILE: truffle/ozex/truffle-config.js ================================================ module.exports = { // See // to customize your Truffle configuration! }; ================================================ FILE: truffle/ozex/truffle.js ================================================ module.exports = { // See // to customize your Truffle configuration! }; ================================================ FILE: truffle/ozws/bs-config.json ================================================ { "server": { "baseDir": ["./src", "./build/contracts"] } } ================================================ FILE: truffle/ozws/contracts/Migrations.sol ================================================ pragma solidity ^0.4.2; contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } function Migrations() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } ================================================ FILE: truffle/ozws/contracts/TutorialToken.sol ================================================ import 'zeppelin-solidity/contracts/token/StandardToken.sol'; contract TutorialToken is StandardToken { string public name = 'TutorialToken'; string public symbol = 'TT'; uint public decimals = 2; uint public INITIAL_SUPPLY = 12000; function TutorialToken() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } } ================================================ FILE: truffle/ozws/migrations/1_initial_migration.js ================================================ var Migrations = artifacts.require("./Migrations.sol"); module.exports = function(deployer) { deployer.deploy(Migrations); }; ================================================ FILE: truffle/ozws/migrations/2_deploy_contracts.js ================================================ var TutorialToken = artifacts.require("TutorialToken"); module.exports = function(deployer) { deployer.deploy(TutorialToken); }; ================================================ FILE: truffle/ozws/package.json ================================================ { "name": "tutorialtoken", "version": "1.0.0", "description": "", "main": "truffle.js", "directories": { "test": "test" }, "scripts": { "dev": "lite-server", "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "devDependencies": { "lite-server": "^2.3.0" } } ================================================ FILE: truffle/ozws/src/index.html ================================================ TutorialToken - Wallet

TutorialToken



My Wallet

Balance

Balance: TT

Transfer

================================================ FILE: truffle/ozws/src/js/app.js ================================================ App = { web3Provider: null, contracts: {}, init: function() { return App.initWeb3(); }, initWeb3: function() { // Initialize web3 and set the provider to the testRPC. if (typeof web3 !== 'undefined') { App.web3Provider = web3.currentProvider; web3 = new Web3(web3.currentProvider); } else { // set the provider you want from Web3.providers App.web3Provider = new Web3.providers.HttpProvider('http://127.0.0.1:8545'); web3 = new Web3(App.web3Provider); } return App.initContract(); }, initContract: function() { $.getJSON('TutorialToken.json', function(data) { // Get the necessary contract artifact file and instantiate it with truffle-contract. var TutorialTokenArtifact = data; App.contracts.TutorialToken = TruffleContract(TutorialTokenArtifact); // Set the provider for our contract. App.contracts.TutorialToken.setProvider(App.web3Provider); // Use our contract to retieve and mark the adopted pets. return App.getBalances(); }); return App.bindEvents(); }, bindEvents: function() { $(document).on('click', '#transferButton', App.handleTransfer); }, handleTransfer: function(event) { event.preventDefault(); var amount = parseInt($('#TTTransferAmount').val()); var toAddress = $('#TTTransferAddress').val(); console.log('Transfer ' + amount + ' TT to ' + toAddress); var tutorialTokenInstance; web3.eth.getAccounts(function(error, accounts) { if (error) { console.log(error); } var account = accounts[0]; App.contracts.TutorialToken.deployed().then(function(instance) { tutorialTokenInstance = instance; return tutorialTokenInstance.transfer(toAddress, amount, {from: account}); }).then(function(result) { alert('Transfer Successful!'); return App.getBalances(); }).catch(function(err) { console.log(err.message); }); }); }, getBalances: function(adopters, account) { console.log('Getting balances...'); var tutorialTokenInstance; web3.eth.getAccounts(function(error, accounts) { if (error) { console.log(error); } var account = accounts[0]; App.contracts.TutorialToken.deployed().then(function(instance) { tutorialTokenInstance = instance; return tutorialTokenInstance.balanceOf(account); }).then(function(result) { balance = result.c[0]; $('#TTBalance').text(balance); }).catch(function(err) { console.log(err.message); }); }); } }; $(function() { $(window).load(function() { App.init(); }); }); ================================================ FILE: truffle/ozws/src/js/truffle-contract.js ================================================ (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0 && new Date().getTime() - start > timeout) { return reject(new Error("Transaction " + tx + " wasn't processed in " + (timeout / 1000) + " seconds!")); } setTimeout(make_attempt, 1000); }); }; make_attempt(); }; args.push(tx_params, callback); fn.apply(self, args); }); }); }; }, merge: function() { var merged = {}; var args = Array.prototype.slice.call(arguments); for (var i = 0; i < args.length; i++) { var object = args[i]; var keys = Object.keys(object); for (var j = 0; j < keys.length; j++) { var key = keys[j]; var value = object[key]; merged[key] = value; } } return merged; }, parallel: function (arr, callback) { callback = callback || function () {}; if (!arr.length) { return callback(null, []); } var index = 0; var results = new Array(arr.length); arr.forEach(function (fn, position) { fn(function (err, result) { if (err) { callback(err); callback = function () {}; } else { index++; results[position] = result; if (index >= arr.length) { callback(null, results); } } }); }); }, bootstrap: function(fn) { // Add our static methods Object.keys(fn._static_methods).forEach(function(key) { fn[key] = fn._static_methods[key].bind(fn); }); // Add our properties. Object.keys(fn._properties).forEach(function(key) { fn.addProp(key, fn._properties[key]); }); return fn; } }; // Accepts a contract object created with web3.eth.contract. // Optionally, if called without `new`, accepts a network_id and will // create a new version of the contract abstraction with that network_id set. function Contract(contract) { var self = this; var constructor = this.constructor; this.abi = constructor.abi; if (typeof contract == "string") { var address = contract; var contract_class = constructor.web3.eth.contract(this.abi); contract = contract_class.at(address); } this.contract = contract; // Provision our functions. for (var i = 0; i < this.abi.length; i++) { var item = this.abi[i]; if (item.type == "function") { if (item.constant == true) { this[item.name] = Utils.promisifyFunction(contract[item.name], constructor); } else { this[item.name] = Utils.synchronizeFunction(contract[item.name], this, constructor); } this[item.name].call = Utils.promisifyFunction(contract[item.name].call, constructor); this[item.name].sendTransaction = Utils.promisifyFunction(contract[item.name].sendTransaction, constructor); this[item.name].request = contract[item.name].request; this[item.name].estimateGas = Utils.promisifyFunction(contract[item.name].estimateGas, constructor); } if (item.type == "event") { this[item.name] = contract[item.name]; } } this.sendTransaction = Utils.synchronizeFunction(function(tx_params, callback) { if (typeof tx_params == "function") { callback = tx_params; tx_params = {}; } tx_params.to = self.address; constructor.web3.eth.sendTransaction.apply(constructor.web3.eth, [tx_params, callback]); }, this, constructor); this.send = function(value) { return self.sendTransaction({value: value}); }; this.allEvents = contract.allEvents; this.address = contract.address; this.transactionHash = contract.transactionHash; }; Contract._static_methods = { setProvider: function(provider) { if (!provider) { throw new Error("Invalid provider passed to setProvider(); provider is " + provider); } var wrapped = new Provider(provider); this.web3.setProvider(wrapped); this.currentProvider = provider; }, new: function() { var self = this; if (this.currentProvider == null) { throw new Error(this.contract_name + " error: Please call setProvider() first before calling new()."); } var args = Array.prototype.slice.call(arguments); if (!this.unlinked_binary) { throw new Error(this._json.contract_name + " error: contract binary not set. Can't deploy new instance."); } return self.detectNetwork().then(function(network_id) { // After the network is set, check to make sure everything's ship shape. var regex = /__[^_]+_+/g; var unlinked_libraries = self.binary.match(regex); if (unlinked_libraries != null) { unlinked_libraries = unlinked_libraries.map(function(name) { // Remove underscores return name.replace(/_/g, ""); }).sort().filter(function(name, index, arr) { // Remove duplicates if (index + 1 >= arr.length) { return true; } return name != arr[index + 1]; }).join(", "); throw new Error(self.contract_name + " contains unresolved libraries. You must deploy and link the following libraries before you can deploy a new version of " + self._json.contract_name + ": " + unlinked_libraries); } }).then(function() { return new Promise(function(accept, reject) { var contract_class = self.web3.eth.contract(self.abi); var tx_params = {}; var last_arg = args[args.length - 1]; // It's only tx_params if it's an object and not a BigNumber. if (Utils.is_object(last_arg) && !Utils.is_big_number(last_arg)) { tx_params = args.pop(); } tx_params = Utils.merge(self.class_defaults, tx_params); if (tx_params.data == null) { tx_params.data = self.binary; } // web3 0.9.0 and above calls new this callback twice. // Why, I have no idea... var intermediary = function(err, web3_instance) { if (err != null) { reject(err); return; } if (err == null && web3_instance != null && web3_instance.address != null) { accept(new self(web3_instance)); } }; args.push(tx_params, intermediary); contract_class.new.apply(contract_class, args); }); }); }, at: function(address) { var self = this; if (address == null || typeof address != "string" || address.length != 42) { throw new Error("Invalid address passed to " + this._json.contract_name + ".at(): " + address); } var contract = new this(address); // Add thennable to allow people opt into new recommended usage. contract.then = function(fn) { return self.detectNetwork().then(function(network_id) { var instance = new self(address); return new Promise(function(accept, reject) { self.web3.eth.getCode(address, function(err, code) { if (err) return reject(err); if (!code || new BigNumber(code).eq(0)) { return reject(new Error("Cannot create instance of " + self.contract_name + "; no code at address " + address)); } accept(instance); }); }); }).then(fn); }; return contract; }, deployed: function() { var self = this; var val = {}; //this.at(this.address); // Add thennable to allow people to opt into new recommended usage. val.then = function(fn) { return self.detectNetwork().then(function() { // We don't have a network config for the one we found if (self._json.networks[self.network_id] == null) { throw new Error(self.contract_name + " has not been deployed to detected network (network/artifact mismatch)"); } // If we found the network but it's not deployed if (!self.isDeployed()) { throw new Error(self.contract_name + " has not been deployed to detected network (" + self.network_id + ")"); } return new self(self.address); }).then(fn); }; return val; }, defaults: function(class_defaults) { if (this.class_defaults == null) { this.class_defaults = {}; } if (class_defaults == null) { class_defaults = {}; } var self = this; Object.keys(class_defaults).forEach(function(key) { var value = class_defaults[key]; self.class_defaults[key] = value; }); return this.class_defaults; }, hasNetwork: function(network_id) { return this._json.networks[network_id + ""] != null; }, isDeployed: function() { if (this.network_id == null) { return false; } if (this._json.networks[this.network_id] == null) { return false; } return !!this.network.address; }, detectNetwork: function() { var self = this; return new Promise(function(accept, reject) { // Try to detect the network we have artifacts for. if (self.network_id) { // We have a network id and a configuration, let's go with it. if (self.networks[self.network_id] != null) { return accept(self.network_id); } } self.web3.version.getNetwork(function(err, result) { if (err) return reject(err); var network_id = result.toString(); // If we found the network via a number, let's use that. if (self.hasNetwork(network_id)) { self.setNetwork(network_id); return accept(); } // Otherwise, go through all the networks that are listed as // blockchain uris and see if they match. var uris = Object.keys(self._json.networks).filter(function(network) { return network.indexOf("blockchain://") == 0; }); var matches = uris.map(function(uri) { return BlockchainUtils.matches.bind(BlockchainUtils, uri, self.web3.currentProvider); }); Utils.parallel(matches, function(err, results) { if (err) return reject(err); for (var i = 0; i < results.length; i++) { if (results[i]) { self.setNetwork(uris[i]); return accept(); } } // We found nothing. Set the network id to whatever the provider states. self.setNetwork(network_id); accept(); }); }); }); }, setNetwork: function(network_id) { if (!network_id) return; this.network_id = network_id + ""; }, // Overrides the deployed address to null. // You must call this explicitly so you don't inadvertently do this otherwise. resetAddress: function() { delete this.network.address; }, link: function(name, address) { var self = this; if (typeof name == "function") { var contract = name; if (contract.isDeployed() == false) { throw new Error("Cannot link contract without an address."); } this.link(contract.contract_name, contract.address); // Merge events so this contract knows about library's events Object.keys(contract.events).forEach(function(topic) { self.network.events[topic] = contract.events[topic]; }); return; } if (typeof name == "object") { var obj = name; Object.keys(obj).forEach(function(name) { var a = obj[name]; self.link(name, a); }); return; } if (this._json.networks[this.network_id] == null) { this._json.networks[this.network_id] = { events: {}, links: {} }; } this.network.links[name] = address; }, clone: function(options) { var self = this; var temp = function TruffleContract() { this.constructor = temp; return Contract.apply(this, arguments); }; var json = options; var network_id; if (typeof options != "object") { json = self._json; network_id = options; options = {}; } temp.prototype = Object.create(self.prototype); temp._static_methods = this._static_methods; temp._properties = this._properties; temp._property_values = {}; temp._json = json || {}; Utils.bootstrap(temp); temp.web3 = new Web3(); temp.class_defaults = temp.prototype.defaults || {}; if (network_id) { temp.setNetwork(network_id); } // Copy over custom options Object.keys(options).forEach(function(key) { if (key.indexOf("x-") != 0) return; temp[key] = options[key]; }); return temp; }, addProp: function(key, fn) { var self = this; var getter = function() { if (fn.get != null) { return fn.get.call(self); } return self._property_values[key] || fn.call(self); } var setter = function(val) { if (fn.set != null) { fn.set.call(self, val); return; } // If there's not a setter, then the property is immutable. throw new Error(key + " property is immutable"); }; var definition = {}; definition.enumerable = false; definition.configurable = false; definition.get = getter; definition.set = setter; Object.defineProperty(this, key, definition); }, toJSON: function() { return this._json; } }; // Getter functions are scoped to Contract object. Contract._properties = { contract_name: { get: function() { return this._json.contract_name; }, set: function(val) { this._json.contract_name = val; } }, abi: { get: function() { return this._json.abi; }, set: function(val) { this._json.abi = val; } }, network: function() { var network_id = this.network_id; if (network_id == null) { throw new Error(this.contract_name + " has no network id set, cannot lookup artifact data. Either set the network manually using " + this.contract_name + ".setNetwork(), run " + this.contract_name + ".detectNetwork(), or use new(), at() or deployed() as a thenable which will detect the network automatically."); } // TODO: this might be bad; setting a value on a get. if (this._json.networks[network_id] == null) { throw new Error(this.contract_name + " has no network configuration for its current network id (" + network_id + ")."); } return this._json.networks[network_id]; }, networks: function() { return this._json.networks; }, address: { get: function() { var address = this.network.address; if (address == null) { throw new Error("Cannot find deployed address: " + this.contract_name + " not deployed or address not set."); } return address; }, set: function(val) { if (val == null) { throw new Error("Cannot set deployed address; malformed value: " + val); } var network_id = this.network_id; if (network_id == null) { throw new Error(this.contract_name + " has no network id set, cannot lookup artifact data. Either set the network manually using " + this.contract_name + ".setNetwork(), run " + this.contract_name + ".detectNetwork(), or use new(), at() or deployed() as a thenable which will detect the network automatically."); } // Create a network if we don't have one. if (this._json.networks[network_id] == null) { this._json.networks[network_id] = { events: {}, links: {} }; } // Finally, set the address. this.network.address = val; } }, links: function() { if (this._json.networks[this.network_id] == null) { return {}; } return this.network.links || {}; }, events: function() { // helper web3; not used for provider var web3 = new Web3(); var events; if (this._json.networks[this.network_id] == null) { events = {}; } else { events = this.network.events || {}; } // Merge abi events with whatever's returned. var abi = this.abi; abi.forEach(function(item) { if (item.type != "event") return; var signature = item.name + "("; item.inputs.forEach(function(input, index) { signature += input.type; if (index < item.inputs.length - 1) { signature += ","; } }); signature += ")"; var topic = web3.sha3(signature); events[topic] = item; }); return events; }, binary: function() { var self = this; var binary = this.unlinked_binary; Object.keys(this.links).forEach(function(library_name) { var library_address = self.links[library_name]; var regex = new RegExp("__" + library_name + "_*", "g"); binary = binary.replace(regex, library_address.replace("0x", "")); }); return binary; }, unlinked_binary: { get: function() { return this._json.unlinked_binary; }, set: function(val) { // TODO: Ensure 0x prefix. this._json.unlinked_binary = val; } }, schema_version: function() { return this._json.schema_version; }, updated_at: function() { try { return this.network.updated_at || this._json.updated_at; } catch (e) { return this._json.updated_at; } } }; Utils.bootstrap(Contract); module.exports = Contract; return Contract; })(module || {}); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"ethjs-abi":7,"truffle-blockchain-utils":15,"web3":5}],2:[function(require,module,exports){ var Schema = require("truffle-contract-schema"); var Contract = require("./contract.js"); var contract = function(options) { options = Schema.normalizeOptions(options); var binary = Schema.generateBinary(options, {}, {dirty: false}); // Note we don't use `new` here at all. This will cause the class to // "mutate" instead of instantiate an instance. return Contract.clone(binary); }; // To be used to upgrade old .sol.js abstractions contract.fromSolJS = function(soljs_abstraction, ignore_default_network) { if (ignore_default_network == null) { ignore_default_network = false; } // Find the latest binary var latest_network = null; var latest_network_updated_at = 0; var networks = {}; Object.keys(soljs_abstraction.all_networks).forEach(function(network_name) { if (network_name == "default") { if (ignore_default_network == true ) { return; } else { throw new Error(soljs_abstraction.contract_name + " has legacy 'default' network artifacts stored within it. Generally these artifacts were a result of running Truffle on a development environment -- in order to store contracts with truffle-contract, all networks must have an identified id. If you're sure this default network represents your development environment, you can ignore processing of the default network by passing `true` as the second argument to this function. However, if you think this network represents artifacts you'd like to keep (i.e., addresses deployed to the main network), you'll need to edit your .sol.js file yourself and change the default network id to be the id of your desired network. For most people, ignoring the default network is the correct option."); } } if (soljs_abstraction.all_networks[network_name].updated_at > latest_network_updated_at) { latest_network = network_name; latest_network_updated_at = soljs_abstraction.all_networks[network_name].updated_at; } networks[network_name] = {}; ["address", "events", "links", "updated_at"].forEach(function(key) { networks[network_name][key] = soljs_abstraction.all_networks[network_name][key]; }) }); latest_network = soljs_abstraction.all_networks[latest_network] || {}; var json = { contract_name: soljs_abstraction.contract_name, unlinked_binary: latest_network.unlinked_binary, abi: latest_network.abi, networks: networks, updated_at: latest_network_updated_at == 0 ? undefined : latest_network_updated_at }; return contract(json); }; module.exports = contract; if (typeof window !== "undefined") { window.TruffleContract = contract; } },{"./contract.js":1,"truffle-contract-schema":16}],3:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i] revLookup[code.charCodeAt(i)] = i } revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 function placeHoldersCount (b64) { var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 } function byteLength (b64) { // base64 is 4/3 + up to two characters of the original data return b64.length * 3 / 4 - placeHoldersCount(b64) } function toByteArray (b64) { var i, j, l, tmp, placeHolders, arr var len = b64.length placeHolders = placeHoldersCount(b64) arr = new Arr(len * 3 / 4 - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? len - 4 : len var L = 0 for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[L++] = (tmp >> 16) & 0xFF arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } if (placeHolders === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[L++] = tmp & 0xFF } else if (placeHolders === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } return arr } function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } function encodeChunk (uint8, start, end) { var tmp var output = [] for (var i = start; i < end; i += 3) { tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output.push(tripletToBase64(tmp)) } return output.join('') } function fromByteArray (uint8) { var tmp var len = uint8.length var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes var output = '' var parts = [] var maxChunkLength = 16383 // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1] output += lookup[tmp >> 2] output += lookup[(tmp << 4) & 0x3F] output += '==' } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) output += lookup[tmp >> 10] output += lookup[(tmp >> 4) & 0x3F] output += lookup[(tmp << 2) & 0x3F] output += '=' } parts.push(output) return parts.join('') } },{}],4:[function(require,module,exports){ (function (module, exports) { 'use strict'; // Utils function assert (val, msg) { if (!val) throw new Error(msg || 'Assertion failed'); } // Could use `inherits` module, but don't want to move from single file // architecture yet. function inherits (ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } // BN function BN (number, base, endian) { if (BN.isBN(number)) { return number; } this.negative = 0; this.words = null; this.length = 0; // Reduction context this.red = null; if (number !== null) { if (base === 'le' || base === 'be') { endian = base; base = 10; } this._init(number || 0, base || 10, endian || 'be'); } } if (typeof module === 'object') { module.exports = BN; } else { exports.BN = BN; } BN.BN = BN; BN.wordSize = 26; var Buffer; try { Buffer = require('buf' + 'fer').Buffer; } catch (e) { } BN.isBN = function isBN (num) { if (num instanceof BN) { return true; } return num !== null && typeof num === 'object' && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); }; BN.max = function max (left, right) { if (left.cmp(right) > 0) return left; return right; }; BN.min = function min (left, right) { if (left.cmp(right) < 0) return left; return right; }; BN.prototype._init = function init (number, base, endian) { if (typeof number === 'number') { return this._initNumber(number, base, endian); } if (typeof number === 'object') { return this._initArray(number, base, endian); } if (base === 'hex') { base = 16; } assert(base === (base | 0) && base >= 2 && base <= 36); number = number.toString().replace(/\s+/g, ''); var start = 0; if (number[0] === '-') { start++; } if (base === 16) { this._parseHex(number, start); } else { this._parseBase(number, base, start); } if (number[0] === '-') { this.negative = 1; } this.strip(); if (endian !== 'le') return; this._initArray(this.toArray(), base, endian); }; BN.prototype._initNumber = function _initNumber (number, base, endian) { if (number < 0) { this.negative = 1; number = -number; } if (number < 0x4000000) { this.words = [ number & 0x3ffffff ]; this.length = 1; } else if (number < 0x10000000000000) { this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff ]; this.length = 2; } else { assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff, 1 ]; this.length = 3; } if (endian !== 'le') return; // Reverse the bytes this._initArray(this.toArray(), base, endian); }; BN.prototype._initArray = function _initArray (number, base, endian) { // Perhaps a Uint8Array assert(typeof number.length === 'number'); if (number.length <= 0) { this.words = [ 0 ]; this.length = 1; return this; } this.length = Math.ceil(number.length / 3); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } var j, w; var off = 0; if (endian === 'be') { for (i = number.length - 1, j = 0; i >= 0; i -= 3) { w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } else if (endian === 'le') { for (i = 0, j = 0; i < number.length; i += 3) { w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } return this.strip(); }; function parseHex (str, start, end) { var r = 0; var len = Math.min(str.length, end); for (var i = start; i < len; i++) { var c = str.charCodeAt(i) - 48; r <<= 4; // 'a' - 'f' if (c >= 49 && c <= 54) { r |= c - 49 + 0xa; // 'A' - 'F' } else if (c >= 17 && c <= 22) { r |= c - 17 + 0xa; // '0' - '9' } else { r |= c & 0xf; } } return r; } BN.prototype._parseHex = function _parseHex (number, start) { // Create possibly bigger array to ensure that it fits the number this.length = Math.ceil((number.length - start) / 6); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } var j, w; // Scan 24-bit chunks and add them to the number var off = 0; for (i = number.length - 6, j = 0; i >= start; i -= 6) { w = parseHex(number, i, i + 6); this.words[j] |= (w << off) & 0x3ffffff; // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; off += 24; if (off >= 26) { off -= 26; j++; } } if (i + 6 !== start) { w = parseHex(number, start, i + 6); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; } this.strip(); }; function parseBase (str, start, end, mul) { var r = 0; var len = Math.min(str.length, end); for (var i = start; i < len; i++) { var c = str.charCodeAt(i) - 48; r *= mul; // 'a' if (c >= 49) { r += c - 49 + 0xa; // 'A' } else if (c >= 17) { r += c - 17 + 0xa; // '0' - '9' } else { r += c; } } return r; } BN.prototype._parseBase = function _parseBase (number, base, start) { // Initialize as zero this.words = [ 0 ]; this.length = 1; // Find length of limb in base for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { limbLen++; } limbLen--; limbPow = (limbPow / base) | 0; var total = number.length - start; var mod = total % limbLen; var end = Math.min(total, total - mod) + start; var word = 0; for (var i = start; i < end; i += limbLen) { word = parseBase(number, i, i + limbLen, base); this.imuln(limbPow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } if (mod !== 0) { var pow = 1; word = parseBase(number, i, number.length, base); for (i = 0; i < mod; i++) { pow *= base; } this.imuln(pow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } }; BN.prototype.copy = function copy (dest) { dest.words = new Array(this.length); for (var i = 0; i < this.length; i++) { dest.words[i] = this.words[i]; } dest.length = this.length; dest.negative = this.negative; dest.red = this.red; }; BN.prototype.clone = function clone () { var r = new BN(null); this.copy(r); return r; }; BN.prototype._expand = function _expand (size) { while (this.length < size) { this.words[this.length++] = 0; } return this; }; // Remove leading `0` from `this` BN.prototype.strip = function strip () { while (this.length > 1 && this.words[this.length - 1] === 0) { this.length--; } return this._normSign(); }; BN.prototype._normSign = function _normSign () { // -0 = 0 if (this.length === 1 && this.words[0] === 0) { this.negative = 0; } return this; }; BN.prototype.inspect = function inspect () { return (this.red ? ''; }; /* var zeros = []; var groupSizes = []; var groupBases = []; var s = ''; var i = -1; while (++i < BN.wordSize) { zeros[i] = s; s += '0'; } groupSizes[0] = 0; groupSizes[1] = 0; groupBases[0] = 0; groupBases[1] = 0; var base = 2 - 1; while (++base < 36 + 1) { var groupSize = 0; var groupBase = 1; while (groupBase < (1 << BN.wordSize) / base) { groupBase *= base; groupSize += 1; } groupSizes[base] = groupSize; groupBases[base] = groupBase; } */ var zeros = [ '', '0', '00', '000', '0000', '00000', '000000', '0000000', '00000000', '000000000', '0000000000', '00000000000', '000000000000', '0000000000000', '00000000000000', '000000000000000', '0000000000000000', '00000000000000000', '000000000000000000', '0000000000000000000', '00000000000000000000', '000000000000000000000', '0000000000000000000000', '00000000000000000000000', '000000000000000000000000', '0000000000000000000000000' ]; var groupSizes = [ 0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 ]; var groupBases = [ 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 ]; BN.prototype.toString = function toString (base, padding) { base = base || 10; padding = padding | 0 || 1; var out; if (base === 16 || base === 'hex') { out = ''; var off = 0; var carry = 0; for (var i = 0; i < this.length; i++) { var w = this.words[i]; var word = (((w << off) | carry) & 0xffffff).toString(16); carry = (w >>> (24 - off)) & 0xffffff; if (carry !== 0 || i !== this.length - 1) { out = zeros[6 - word.length] + word + out; } else { out = word + out; } off += 2; if (off >= 26) { off -= 26; i--; } } if (carry !== 0) { out = carry.toString(16) + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } if (base === (base | 0) && base >= 2 && base <= 36) { // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); var groupSize = groupSizes[base]; // var groupBase = Math.pow(base, groupSize); var groupBase = groupBases[base]; out = ''; var c = this.clone(); c.negative = 0; while (!c.isZero()) { var r = c.modn(groupBase).toString(base); c = c.idivn(groupBase); if (!c.isZero()) { out = zeros[groupSize - r.length] + r + out; } else { out = r + out; } } if (this.isZero()) { out = '0' + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } assert(false, 'Base should be between 2 and 36'); }; BN.prototype.toNumber = function toNumber () { var ret = this.words[0]; if (this.length === 2) { ret += this.words[1] * 0x4000000; } else if (this.length === 3 && this.words[2] === 0x01) { // NOTE: at this stage it is known that the top bit is set ret += 0x10000000000000 + (this.words[1] * 0x4000000); } else if (this.length > 2) { assert(false, 'Number can only safely store up to 53 bits'); } return (this.negative !== 0) ? -ret : ret; }; BN.prototype.toJSON = function toJSON () { return this.toString(16); }; BN.prototype.toBuffer = function toBuffer (endian, length) { assert(typeof Buffer !== 'undefined'); return this.toArrayLike(Buffer, endian, length); }; BN.prototype.toArray = function toArray (endian, length) { return this.toArrayLike(Array, endian, length); }; BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { var byteLength = this.byteLength(); var reqLength = length || Math.max(1, byteLength); assert(byteLength <= reqLength, 'byte array longer than desired length'); assert(reqLength > 0, 'Requested array length <= 0'); this.strip(); var littleEndian = endian === 'le'; var res = new ArrayType(reqLength); var b, i; var q = this.clone(); if (!littleEndian) { // Assume big-endian for (i = 0; i < reqLength - byteLength; i++) { res[i] = 0; } for (i = 0; !q.isZero(); i++) { b = q.andln(0xff); q.iushrn(8); res[reqLength - i - 1] = b; } } else { for (i = 0; !q.isZero(); i++) { b = q.andln(0xff); q.iushrn(8); res[i] = b; } for (; i < reqLength; i++) { res[i] = 0; } } return res; }; if (Math.clz32) { BN.prototype._countBits = function _countBits (w) { return 32 - Math.clz32(w); }; } else { BN.prototype._countBits = function _countBits (w) { var t = w; var r = 0; if (t >= 0x1000) { r += 13; t >>>= 13; } if (t >= 0x40) { r += 7; t >>>= 7; } if (t >= 0x8) { r += 4; t >>>= 4; } if (t >= 0x02) { r += 2; t >>>= 2; } return r + t; }; } BN.prototype._zeroBits = function _zeroBits (w) { // Short-cut if (w === 0) return 26; var t = w; var r = 0; if ((t & 0x1fff) === 0) { r += 13; t >>>= 13; } if ((t & 0x7f) === 0) { r += 7; t >>>= 7; } if ((t & 0xf) === 0) { r += 4; t >>>= 4; } if ((t & 0x3) === 0) { r += 2; t >>>= 2; } if ((t & 0x1) === 0) { r++; } return r; }; // Return number of used bits in a BN BN.prototype.bitLength = function bitLength () { var w = this.words[this.length - 1]; var hi = this._countBits(w); return (this.length - 1) * 26 + hi; }; function toBitArray (num) { var w = new Array(num.bitLength()); for (var bit = 0; bit < w.length; bit++) { var off = (bit / 26) | 0; var wbit = bit % 26; w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; } return w; } // Number of trailing zero bits BN.prototype.zeroBits = function zeroBits () { if (this.isZero()) return 0; var r = 0; for (var i = 0; i < this.length; i++) { var b = this._zeroBits(this.words[i]); r += b; if (b !== 26) break; } return r; }; BN.prototype.byteLength = function byteLength () { return Math.ceil(this.bitLength() / 8); }; BN.prototype.toTwos = function toTwos (width) { if (this.negative !== 0) { return this.abs().inotn(width).iaddn(1); } return this.clone(); }; BN.prototype.fromTwos = function fromTwos (width) { if (this.testn(width - 1)) { return this.notn(width).iaddn(1).ineg(); } return this.clone(); }; BN.prototype.isNeg = function isNeg () { return this.negative !== 0; }; // Return negative clone of `this` BN.prototype.neg = function neg () { return this.clone().ineg(); }; BN.prototype.ineg = function ineg () { if (!this.isZero()) { this.negative ^= 1; } return this; }; // Or `num` with `this` in-place BN.prototype.iuor = function iuor (num) { while (this.length < num.length) { this.words[this.length++] = 0; } for (var i = 0; i < num.length; i++) { this.words[i] = this.words[i] | num.words[i]; } return this.strip(); }; BN.prototype.ior = function ior (num) { assert((this.negative | num.negative) === 0); return this.iuor(num); }; // Or `num` with `this` BN.prototype.or = function or (num) { if (this.length > num.length) return this.clone().ior(num); return num.clone().ior(this); }; BN.prototype.uor = function uor (num) { if (this.length > num.length) return this.clone().iuor(num); return num.clone().iuor(this); }; // And `num` with `this` in-place BN.prototype.iuand = function iuand (num) { // b = min-length(num, this) var b; if (this.length > num.length) { b = num; } else { b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = this.words[i] & num.words[i]; } this.length = b.length; return this.strip(); }; BN.prototype.iand = function iand (num) { assert((this.negative | num.negative) === 0); return this.iuand(num); }; // And `num` with `this` BN.prototype.and = function and (num) { if (this.length > num.length) return this.clone().iand(num); return num.clone().iand(this); }; BN.prototype.uand = function uand (num) { if (this.length > num.length) return this.clone().iuand(num); return num.clone().iuand(this); }; // Xor `num` with `this` in-place BN.prototype.iuxor = function iuxor (num) { // a.length > b.length var a; var b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = a.words[i] ^ b.words[i]; } if (this !== a) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = a.length; return this.strip(); }; BN.prototype.ixor = function ixor (num) { assert((this.negative | num.negative) === 0); return this.iuxor(num); }; // Xor `num` with `this` BN.prototype.xor = function xor (num) { if (this.length > num.length) return this.clone().ixor(num); return num.clone().ixor(this); }; BN.prototype.uxor = function uxor (num) { if (this.length > num.length) return this.clone().iuxor(num); return num.clone().iuxor(this); }; // Not ``this`` with ``width`` bitwidth BN.prototype.inotn = function inotn (width) { assert(typeof width === 'number' && width >= 0); var bytesNeeded = Math.ceil(width / 26) | 0; var bitsLeft = width % 26; // Extend the buffer with leading zeroes this._expand(bytesNeeded); if (bitsLeft > 0) { bytesNeeded--; } // Handle complete words for (var i = 0; i < bytesNeeded; i++) { this.words[i] = ~this.words[i] & 0x3ffffff; } // Handle the residue if (bitsLeft > 0) { this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); } // And remove leading zeroes return this.strip(); }; BN.prototype.notn = function notn (width) { return this.clone().inotn(width); }; // Set `bit` of `this` BN.prototype.setn = function setn (bit, val) { assert(typeof bit === 'number' && bit >= 0); var off = (bit / 26) | 0; var wbit = bit % 26; this._expand(off + 1); if (val) { this.words[off] = this.words[off] | (1 << wbit); } else { this.words[off] = this.words[off] & ~(1 << wbit); } return this.strip(); }; // Add `num` to `this` in-place BN.prototype.iadd = function iadd (num) { var r; // negative + positive if (this.negative !== 0 && num.negative === 0) { this.negative = 0; r = this.isub(num); this.negative ^= 1; return this._normSign(); // positive + negative } else if (this.negative === 0 && num.negative !== 0) { num.negative = 0; r = this.isub(num); num.negative = 1; return r._normSign(); } // a.length > b.length var a, b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) + (b.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } this.length = a.length; if (carry !== 0) { this.words[this.length] = carry; this.length++; // Copy the rest of the words } else if (a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } return this; }; // Add `num` to `this` BN.prototype.add = function add (num) { var res; if (num.negative !== 0 && this.negative === 0) { num.negative = 0; res = this.sub(num); num.negative ^= 1; return res; } else if (num.negative === 0 && this.negative !== 0) { this.negative = 0; res = num.sub(this); this.negative = 1; return res; } if (this.length > num.length) return this.clone().iadd(num); return num.clone().iadd(this); }; // Subtract `num` from `this` in-place BN.prototype.isub = function isub (num) { // this - (-num) = this + num if (num.negative !== 0) { num.negative = 0; var r = this.iadd(num); num.negative = 1; return r._normSign(); // -this - num = -(this + num) } else if (this.negative !== 0) { this.negative = 0; this.iadd(num); this.negative = 1; return this._normSign(); } // At this point both numbers are positive var cmp = this.cmp(num); // Optimization - zeroify if (cmp === 0) { this.negative = 0; this.length = 1; this.words[0] = 0; return this; } // a > b var a, b; if (cmp > 0) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) - (b.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } // Copy rest of the words if (carry === 0 && i < a.length && a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = Math.max(this.length, i); if (a !== this) { this.negative = 1; } return this.strip(); }; // Subtract `num` from `this` BN.prototype.sub = function sub (num) { return this.clone().isub(num); }; function smallMulTo (self, num, out) { out.negative = num.negative ^ self.negative; var len = (self.length + num.length) | 0; out.length = len; len = (len - 1) | 0; // Peel one iteration (compiler can't do it, because of code complexity) var a = self.words[0] | 0; var b = num.words[0] | 0; var r = a * b; var lo = r & 0x3ffffff; var carry = (r / 0x4000000) | 0; out.words[0] = lo; for (var k = 1; k < len; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff var ncarry = carry >>> 26; var rword = carry & 0x3ffffff; var maxJ = Math.min(k, num.length - 1); for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { var i = (k - j) | 0; a = self.words[i] | 0; b = num.words[j] | 0; r = a * b + rword; ncarry += (r / 0x4000000) | 0; rword = r & 0x3ffffff; } out.words[k] = rword | 0; carry = ncarry | 0; } if (carry !== 0) { out.words[k] = carry | 0; } else { out.length--; } return out.strip(); } // TODO(indutny): it may be reasonable to omit it for users who don't need // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit // multiplication (like elliptic secp256k1). var comb10MulTo = function comb10MulTo (self, num, out) { var a = self.words; var b = num.words; var o = out.words; var c = 0; var lo; var mid; var hi; var a0 = a[0] | 0; var al0 = a0 & 0x1fff; var ah0 = a0 >>> 13; var a1 = a[1] | 0; var al1 = a1 & 0x1fff; var ah1 = a1 >>> 13; var a2 = a[2] | 0; var al2 = a2 & 0x1fff; var ah2 = a2 >>> 13; var a3 = a[3] | 0; var al3 = a3 & 0x1fff; var ah3 = a3 >>> 13; var a4 = a[4] | 0; var al4 = a4 & 0x1fff; var ah4 = a4 >>> 13; var a5 = a[5] | 0; var al5 = a5 & 0x1fff; var ah5 = a5 >>> 13; var a6 = a[6] | 0; var al6 = a6 & 0x1fff; var ah6 = a6 >>> 13; var a7 = a[7] | 0; var al7 = a7 & 0x1fff; var ah7 = a7 >>> 13; var a8 = a[8] | 0; var al8 = a8 & 0x1fff; var ah8 = a8 >>> 13; var a9 = a[9] | 0; var al9 = a9 & 0x1fff; var ah9 = a9 >>> 13; var b0 = b[0] | 0; var bl0 = b0 & 0x1fff; var bh0 = b0 >>> 13; var b1 = b[1] | 0; var bl1 = b1 & 0x1fff; var bh1 = b1 >>> 13; var b2 = b[2] | 0; var bl2 = b2 & 0x1fff; var bh2 = b2 >>> 13; var b3 = b[3] | 0; var bl3 = b3 & 0x1fff; var bh3 = b3 >>> 13; var b4 = b[4] | 0; var bl4 = b4 & 0x1fff; var bh4 = b4 >>> 13; var b5 = b[5] | 0; var bl5 = b5 & 0x1fff; var bh5 = b5 >>> 13; var b6 = b[6] | 0; var bl6 = b6 & 0x1fff; var bh6 = b6 >>> 13; var b7 = b[7] | 0; var bl7 = b7 & 0x1fff; var bh7 = b7 >>> 13; var b8 = b[8] | 0; var bl8 = b8 & 0x1fff; var bh8 = b8 >>> 13; var b9 = b[9] | 0; var bl9 = b9 & 0x1fff; var bh9 = b9 >>> 13; out.negative = self.negative ^ num.negative; out.length = 19; /* k = 0 */ lo = Math.imul(al0, bl0); mid = Math.imul(al0, bh0); mid = (mid + Math.imul(ah0, bl0)) | 0; hi = Math.imul(ah0, bh0); var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; w0 &= 0x3ffffff; /* k = 1 */ lo = Math.imul(al1, bl0); mid = Math.imul(al1, bh0); mid = (mid + Math.imul(ah1, bl0)) | 0; hi = Math.imul(ah1, bh0); lo = (lo + Math.imul(al0, bl1)) | 0; mid = (mid + Math.imul(al0, bh1)) | 0; mid = (mid + Math.imul(ah0, bl1)) | 0; hi = (hi + Math.imul(ah0, bh1)) | 0; var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; w1 &= 0x3ffffff; /* k = 2 */ lo = Math.imul(al2, bl0); mid = Math.imul(al2, bh0); mid = (mid + Math.imul(ah2, bl0)) | 0; hi = Math.imul(ah2, bh0); lo = (lo + Math.imul(al1, bl1)) | 0; mid = (mid + Math.imul(al1, bh1)) | 0; mid = (mid + Math.imul(ah1, bl1)) | 0; hi = (hi + Math.imul(ah1, bh1)) | 0; lo = (lo + Math.imul(al0, bl2)) | 0; mid = (mid + Math.imul(al0, bh2)) | 0; mid = (mid + Math.imul(ah0, bl2)) | 0; hi = (hi + Math.imul(ah0, bh2)) | 0; var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; w2 &= 0x3ffffff; /* k = 3 */ lo = Math.imul(al3, bl0); mid = Math.imul(al3, bh0); mid = (mid + Math.imul(ah3, bl0)) | 0; hi = Math.imul(ah3, bh0); lo = (lo + Math.imul(al2, bl1)) | 0; mid = (mid + Math.imul(al2, bh1)) | 0; mid = (mid + Math.imul(ah2, bl1)) | 0; hi = (hi + Math.imul(ah2, bh1)) | 0; lo = (lo + Math.imul(al1, bl2)) | 0; mid = (mid + Math.imul(al1, bh2)) | 0; mid = (mid + Math.imul(ah1, bl2)) | 0; hi = (hi + Math.imul(ah1, bh2)) | 0; lo = (lo + Math.imul(al0, bl3)) | 0; mid = (mid + Math.imul(al0, bh3)) | 0; mid = (mid + Math.imul(ah0, bl3)) | 0; hi = (hi + Math.imul(ah0, bh3)) | 0; var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; w3 &= 0x3ffffff; /* k = 4 */ lo = Math.imul(al4, bl0); mid = Math.imul(al4, bh0); mid = (mid + Math.imul(ah4, bl0)) | 0; hi = Math.imul(ah4, bh0); lo = (lo + Math.imul(al3, bl1)) | 0; mid = (mid + Math.imul(al3, bh1)) | 0; mid = (mid + Math.imul(ah3, bl1)) | 0; hi = (hi + Math.imul(ah3, bh1)) | 0; lo = (lo + Math.imul(al2, bl2)) | 0; mid = (mid + Math.imul(al2, bh2)) | 0; mid = (mid + Math.imul(ah2, bl2)) | 0; hi = (hi + Math.imul(ah2, bh2)) | 0; lo = (lo + Math.imul(al1, bl3)) | 0; mid = (mid + Math.imul(al1, bh3)) | 0; mid = (mid + Math.imul(ah1, bl3)) | 0; hi = (hi + Math.imul(ah1, bh3)) | 0; lo = (lo + Math.imul(al0, bl4)) | 0; mid = (mid + Math.imul(al0, bh4)) | 0; mid = (mid + Math.imul(ah0, bl4)) | 0; hi = (hi + Math.imul(ah0, bh4)) | 0; var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; w4 &= 0x3ffffff; /* k = 5 */ lo = Math.imul(al5, bl0); mid = Math.imul(al5, bh0); mid = (mid + Math.imul(ah5, bl0)) | 0; hi = Math.imul(ah5, bh0); lo = (lo + Math.imul(al4, bl1)) | 0; mid = (mid + Math.imul(al4, bh1)) | 0; mid = (mid + Math.imul(ah4, bl1)) | 0; hi = (hi + Math.imul(ah4, bh1)) | 0; lo = (lo + Math.imul(al3, bl2)) | 0; mid = (mid + Math.imul(al3, bh2)) | 0; mid = (mid + Math.imul(ah3, bl2)) | 0; hi = (hi + Math.imul(ah3, bh2)) | 0; lo = (lo + Math.imul(al2, bl3)) | 0; mid = (mid + Math.imul(al2, bh3)) | 0; mid = (mid + Math.imul(ah2, bl3)) | 0; hi = (hi + Math.imul(ah2, bh3)) | 0; lo = (lo + Math.imul(al1, bl4)) | 0; mid = (mid + Math.imul(al1, bh4)) | 0; mid = (mid + Math.imul(ah1, bl4)) | 0; hi = (hi + Math.imul(ah1, bh4)) | 0; lo = (lo + Math.imul(al0, bl5)) | 0; mid = (mid + Math.imul(al0, bh5)) | 0; mid = (mid + Math.imul(ah0, bl5)) | 0; hi = (hi + Math.imul(ah0, bh5)) | 0; var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; w5 &= 0x3ffffff; /* k = 6 */ lo = Math.imul(al6, bl0); mid = Math.imul(al6, bh0); mid = (mid + Math.imul(ah6, bl0)) | 0; hi = Math.imul(ah6, bh0); lo = (lo + Math.imul(al5, bl1)) | 0; mid = (mid + Math.imul(al5, bh1)) | 0; mid = (mid + Math.imul(ah5, bl1)) | 0; hi = (hi + Math.imul(ah5, bh1)) | 0; lo = (lo + Math.imul(al4, bl2)) | 0; mid = (mid + Math.imul(al4, bh2)) | 0; mid = (mid + Math.imul(ah4, bl2)) | 0; hi = (hi + Math.imul(ah4, bh2)) | 0; lo = (lo + Math.imul(al3, bl3)) | 0; mid = (mid + Math.imul(al3, bh3)) | 0; mid = (mid + Math.imul(ah3, bl3)) | 0; hi = (hi + Math.imul(ah3, bh3)) | 0; lo = (lo + Math.imul(al2, bl4)) | 0; mid = (mid + Math.imul(al2, bh4)) | 0; mid = (mid + Math.imul(ah2, bl4)) | 0; hi = (hi + Math.imul(ah2, bh4)) | 0; lo = (lo + Math.imul(al1, bl5)) | 0; mid = (mid + Math.imul(al1, bh5)) | 0; mid = (mid + Math.imul(ah1, bl5)) | 0; hi = (hi + Math.imul(ah1, bh5)) | 0; lo = (lo + Math.imul(al0, bl6)) | 0; mid = (mid + Math.imul(al0, bh6)) | 0; mid = (mid + Math.imul(ah0, bl6)) | 0; hi = (hi + Math.imul(ah0, bh6)) | 0; var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; w6 &= 0x3ffffff; /* k = 7 */ lo = Math.imul(al7, bl0); mid = Math.imul(al7, bh0); mid = (mid + Math.imul(ah7, bl0)) | 0; hi = Math.imul(ah7, bh0); lo = (lo + Math.imul(al6, bl1)) | 0; mid = (mid + Math.imul(al6, bh1)) | 0; mid = (mid + Math.imul(ah6, bl1)) | 0; hi = (hi + Math.imul(ah6, bh1)) | 0; lo = (lo + Math.imul(al5, bl2)) | 0; mid = (mid + Math.imul(al5, bh2)) | 0; mid = (mid + Math.imul(ah5, bl2)) | 0; hi = (hi + Math.imul(ah5, bh2)) | 0; lo = (lo + Math.imul(al4, bl3)) | 0; mid = (mid + Math.imul(al4, bh3)) | 0; mid = (mid + Math.imul(ah4, bl3)) | 0; hi = (hi + Math.imul(ah4, bh3)) | 0; lo = (lo + Math.imul(al3, bl4)) | 0; mid = (mid + Math.imul(al3, bh4)) | 0; mid = (mid + Math.imul(ah3, bl4)) | 0; hi = (hi + Math.imul(ah3, bh4)) | 0; lo = (lo + Math.imul(al2, bl5)) | 0; mid = (mid + Math.imul(al2, bh5)) | 0; mid = (mid + Math.imul(ah2, bl5)) | 0; hi = (hi + Math.imul(ah2, bh5)) | 0; lo = (lo + Math.imul(al1, bl6)) | 0; mid = (mid + Math.imul(al1, bh6)) | 0; mid = (mid + Math.imul(ah1, bl6)) | 0; hi = (hi + Math.imul(ah1, bh6)) | 0; lo = (lo + Math.imul(al0, bl7)) | 0; mid = (mid + Math.imul(al0, bh7)) | 0; mid = (mid + Math.imul(ah0, bl7)) | 0; hi = (hi + Math.imul(ah0, bh7)) | 0; var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; w7 &= 0x3ffffff; /* k = 8 */ lo = Math.imul(al8, bl0); mid = Math.imul(al8, bh0); mid = (mid + Math.imul(ah8, bl0)) | 0; hi = Math.imul(ah8, bh0); lo = (lo + Math.imul(al7, bl1)) | 0; mid = (mid + Math.imul(al7, bh1)) | 0; mid = (mid + Math.imul(ah7, bl1)) | 0; hi = (hi + Math.imul(ah7, bh1)) | 0; lo = (lo + Math.imul(al6, bl2)) | 0; mid = (mid + Math.imul(al6, bh2)) | 0; mid = (mid + Math.imul(ah6, bl2)) | 0; hi = (hi + Math.imul(ah6, bh2)) | 0; lo = (lo + Math.imul(al5, bl3)) | 0; mid = (mid + Math.imul(al5, bh3)) | 0; mid = (mid + Math.imul(ah5, bl3)) | 0; hi = (hi + Math.imul(ah5, bh3)) | 0; lo = (lo + Math.imul(al4, bl4)) | 0; mid = (mid + Math.imul(al4, bh4)) | 0; mid = (mid + Math.imul(ah4, bl4)) | 0; hi = (hi + Math.imul(ah4, bh4)) | 0; lo = (lo + Math.imul(al3, bl5)) | 0; mid = (mid + Math.imul(al3, bh5)) | 0; mid = (mid + Math.imul(ah3, bl5)) | 0; hi = (hi + Math.imul(ah3, bh5)) | 0; lo = (lo + Math.imul(al2, bl6)) | 0; mid = (mid + Math.imul(al2, bh6)) | 0; mid = (mid + Math.imul(ah2, bl6)) | 0; hi = (hi + Math.imul(ah2, bh6)) | 0; lo = (lo + Math.imul(al1, bl7)) | 0; mid = (mid + Math.imul(al1, bh7)) | 0; mid = (mid + Math.imul(ah1, bl7)) | 0; hi = (hi + Math.imul(ah1, bh7)) | 0; lo = (lo + Math.imul(al0, bl8)) | 0; mid = (mid + Math.imul(al0, bh8)) | 0; mid = (mid + Math.imul(ah0, bl8)) | 0; hi = (hi + Math.imul(ah0, bh8)) | 0; var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; w8 &= 0x3ffffff; /* k = 9 */ lo = Math.imul(al9, bl0); mid = Math.imul(al9, bh0); mid = (mid + Math.imul(ah9, bl0)) | 0; hi = Math.imul(ah9, bh0); lo = (lo + Math.imul(al8, bl1)) | 0; mid = (mid + Math.imul(al8, bh1)) | 0; mid = (mid + Math.imul(ah8, bl1)) | 0; hi = (hi + Math.imul(ah8, bh1)) | 0; lo = (lo + Math.imul(al7, bl2)) | 0; mid = (mid + Math.imul(al7, bh2)) | 0; mid = (mid + Math.imul(ah7, bl2)) | 0; hi = (hi + Math.imul(ah7, bh2)) | 0; lo = (lo + Math.imul(al6, bl3)) | 0; mid = (mid + Math.imul(al6, bh3)) | 0; mid = (mid + Math.imul(ah6, bl3)) | 0; hi = (hi + Math.imul(ah6, bh3)) | 0; lo = (lo + Math.imul(al5, bl4)) | 0; mid = (mid + Math.imul(al5, bh4)) | 0; mid = (mid + Math.imul(ah5, bl4)) | 0; hi = (hi + Math.imul(ah5, bh4)) | 0; lo = (lo + Math.imul(al4, bl5)) | 0; mid = (mid + Math.imul(al4, bh5)) | 0; mid = (mid + Math.imul(ah4, bl5)) | 0; hi = (hi + Math.imul(ah4, bh5)) | 0; lo = (lo + Math.imul(al3, bl6)) | 0; mid = (mid + Math.imul(al3, bh6)) | 0; mid = (mid + Math.imul(ah3, bl6)) | 0; hi = (hi + Math.imul(ah3, bh6)) | 0; lo = (lo + Math.imul(al2, bl7)) | 0; mid = (mid + Math.imul(al2, bh7)) | 0; mid = (mid + Math.imul(ah2, bl7)) | 0; hi = (hi + Math.imul(ah2, bh7)) | 0; lo = (lo + Math.imul(al1, bl8)) | 0; mid = (mid + Math.imul(al1, bh8)) | 0; mid = (mid + Math.imul(ah1, bl8)) | 0; hi = (hi + Math.imul(ah1, bh8)) | 0; lo = (lo + Math.imul(al0, bl9)) | 0; mid = (mid + Math.imul(al0, bh9)) | 0; mid = (mid + Math.imul(ah0, bl9)) | 0; hi = (hi + Math.imul(ah0, bh9)) | 0; var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; w9 &= 0x3ffffff; /* k = 10 */ lo = Math.imul(al9, bl1); mid = Math.imul(al9, bh1); mid = (mid + Math.imul(ah9, bl1)) | 0; hi = Math.imul(ah9, bh1); lo = (lo + Math.imul(al8, bl2)) | 0; mid = (mid + Math.imul(al8, bh2)) | 0; mid = (mid + Math.imul(ah8, bl2)) | 0; hi = (hi + Math.imul(ah8, bh2)) | 0; lo = (lo + Math.imul(al7, bl3)) | 0; mid = (mid + Math.imul(al7, bh3)) | 0; mid = (mid + Math.imul(ah7, bl3)) | 0; hi = (hi + Math.imul(ah7, bh3)) | 0; lo = (lo + Math.imul(al6, bl4)) | 0; mid = (mid + Math.imul(al6, bh4)) | 0; mid = (mid + Math.imul(ah6, bl4)) | 0; hi = (hi + Math.imul(ah6, bh4)) | 0; lo = (lo + Math.imul(al5, bl5)) | 0; mid = (mid + Math.imul(al5, bh5)) | 0; mid = (mid + Math.imul(ah5, bl5)) | 0; hi = (hi + Math.imul(ah5, bh5)) | 0; lo = (lo + Math.imul(al4, bl6)) | 0; mid = (mid + Math.imul(al4, bh6)) | 0; mid = (mid + Math.imul(ah4, bl6)) | 0; hi = (hi + Math.imul(ah4, bh6)) | 0; lo = (lo + Math.imul(al3, bl7)) | 0; mid = (mid + Math.imul(al3, bh7)) | 0; mid = (mid + Math.imul(ah3, bl7)) | 0; hi = (hi + Math.imul(ah3, bh7)) | 0; lo = (lo + Math.imul(al2, bl8)) | 0; mid = (mid + Math.imul(al2, bh8)) | 0; mid = (mid + Math.imul(ah2, bl8)) | 0; hi = (hi + Math.imul(ah2, bh8)) | 0; lo = (lo + Math.imul(al1, bl9)) | 0; mid = (mid + Math.imul(al1, bh9)) | 0; mid = (mid + Math.imul(ah1, bl9)) | 0; hi = (hi + Math.imul(ah1, bh9)) | 0; var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; w10 &= 0x3ffffff; /* k = 11 */ lo = Math.imul(al9, bl2); mid = Math.imul(al9, bh2); mid = (mid + Math.imul(ah9, bl2)) | 0; hi = Math.imul(ah9, bh2); lo = (lo + Math.imul(al8, bl3)) | 0; mid = (mid + Math.imul(al8, bh3)) | 0; mid = (mid + Math.imul(ah8, bl3)) | 0; hi = (hi + Math.imul(ah8, bh3)) | 0; lo = (lo + Math.imul(al7, bl4)) | 0; mid = (mid + Math.imul(al7, bh4)) | 0; mid = (mid + Math.imul(ah7, bl4)) | 0; hi = (hi + Math.imul(ah7, bh4)) | 0; lo = (lo + Math.imul(al6, bl5)) | 0; mid = (mid + Math.imul(al6, bh5)) | 0; mid = (mid + Math.imul(ah6, bl5)) | 0; hi = (hi + Math.imul(ah6, bh5)) | 0; lo = (lo + Math.imul(al5, bl6)) | 0; mid = (mid + Math.imul(al5, bh6)) | 0; mid = (mid + Math.imul(ah5, bl6)) | 0; hi = (hi + Math.imul(ah5, bh6)) | 0; lo = (lo + Math.imul(al4, bl7)) | 0; mid = (mid + Math.imul(al4, bh7)) | 0; mid = (mid + Math.imul(ah4, bl7)) | 0; hi = (hi + Math.imul(ah4, bh7)) | 0; lo = (lo + Math.imul(al3, bl8)) | 0; mid = (mid + Math.imul(al3, bh8)) | 0; mid = (mid + Math.imul(ah3, bl8)) | 0; hi = (hi + Math.imul(ah3, bh8)) | 0; lo = (lo + Math.imul(al2, bl9)) | 0; mid = (mid + Math.imul(al2, bh9)) | 0; mid = (mid + Math.imul(ah2, bl9)) | 0; hi = (hi + Math.imul(ah2, bh9)) | 0; var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; w11 &= 0x3ffffff; /* k = 12 */ lo = Math.imul(al9, bl3); mid = Math.imul(al9, bh3); mid = (mid + Math.imul(ah9, bl3)) | 0; hi = Math.imul(ah9, bh3); lo = (lo + Math.imul(al8, bl4)) | 0; mid = (mid + Math.imul(al8, bh4)) | 0; mid = (mid + Math.imul(ah8, bl4)) | 0; hi = (hi + Math.imul(ah8, bh4)) | 0; lo = (lo + Math.imul(al7, bl5)) | 0; mid = (mid + Math.imul(al7, bh5)) | 0; mid = (mid + Math.imul(ah7, bl5)) | 0; hi = (hi + Math.imul(ah7, bh5)) | 0; lo = (lo + Math.imul(al6, bl6)) | 0; mid = (mid + Math.imul(al6, bh6)) | 0; mid = (mid + Math.imul(ah6, bl6)) | 0; hi = (hi + Math.imul(ah6, bh6)) | 0; lo = (lo + Math.imul(al5, bl7)) | 0; mid = (mid + Math.imul(al5, bh7)) | 0; mid = (mid + Math.imul(ah5, bl7)) | 0; hi = (hi + Math.imul(ah5, bh7)) | 0; lo = (lo + Math.imul(al4, bl8)) | 0; mid = (mid + Math.imul(al4, bh8)) | 0; mid = (mid + Math.imul(ah4, bl8)) | 0; hi = (hi + Math.imul(ah4, bh8)) | 0; lo = (lo + Math.imul(al3, bl9)) | 0; mid = (mid + Math.imul(al3, bh9)) | 0; mid = (mid + Math.imul(ah3, bl9)) | 0; hi = (hi + Math.imul(ah3, bh9)) | 0; var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; w12 &= 0x3ffffff; /* k = 13 */ lo = Math.imul(al9, bl4); mid = Math.imul(al9, bh4); mid = (mid + Math.imul(ah9, bl4)) | 0; hi = Math.imul(ah9, bh4); lo = (lo + Math.imul(al8, bl5)) | 0; mid = (mid + Math.imul(al8, bh5)) | 0; mid = (mid + Math.imul(ah8, bl5)) | 0; hi = (hi + Math.imul(ah8, bh5)) | 0; lo = (lo + Math.imul(al7, bl6)) | 0; mid = (mid + Math.imul(al7, bh6)) | 0; mid = (mid + Math.imul(ah7, bl6)) | 0; hi = (hi + Math.imul(ah7, bh6)) | 0; lo = (lo + Math.imul(al6, bl7)) | 0; mid = (mid + Math.imul(al6, bh7)) | 0; mid = (mid + Math.imul(ah6, bl7)) | 0; hi = (hi + Math.imul(ah6, bh7)) | 0; lo = (lo + Math.imul(al5, bl8)) | 0; mid = (mid + Math.imul(al5, bh8)) | 0; mid = (mid + Math.imul(ah5, bl8)) | 0; hi = (hi + Math.imul(ah5, bh8)) | 0; lo = (lo + Math.imul(al4, bl9)) | 0; mid = (mid + Math.imul(al4, bh9)) | 0; mid = (mid + Math.imul(ah4, bl9)) | 0; hi = (hi + Math.imul(ah4, bh9)) | 0; var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; w13 &= 0x3ffffff; /* k = 14 */ lo = Math.imul(al9, bl5); mid = Math.imul(al9, bh5); mid = (mid + Math.imul(ah9, bl5)) | 0; hi = Math.imul(ah9, bh5); lo = (lo + Math.imul(al8, bl6)) | 0; mid = (mid + Math.imul(al8, bh6)) | 0; mid = (mid + Math.imul(ah8, bl6)) | 0; hi = (hi + Math.imul(ah8, bh6)) | 0; lo = (lo + Math.imul(al7, bl7)) | 0; mid = (mid + Math.imul(al7, bh7)) | 0; mid = (mid + Math.imul(ah7, bl7)) | 0; hi = (hi + Math.imul(ah7, bh7)) | 0; lo = (lo + Math.imul(al6, bl8)) | 0; mid = (mid + Math.imul(al6, bh8)) | 0; mid = (mid + Math.imul(ah6, bl8)) | 0; hi = (hi + Math.imul(ah6, bh8)) | 0; lo = (lo + Math.imul(al5, bl9)) | 0; mid = (mid + Math.imul(al5, bh9)) | 0; mid = (mid + Math.imul(ah5, bl9)) | 0; hi = (hi + Math.imul(ah5, bh9)) | 0; var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; w14 &= 0x3ffffff; /* k = 15 */ lo = Math.imul(al9, bl6); mid = Math.imul(al9, bh6); mid = (mid + Math.imul(ah9, bl6)) | 0; hi = Math.imul(ah9, bh6); lo = (lo + Math.imul(al8, bl7)) | 0; mid = (mid + Math.imul(al8, bh7)) | 0; mid = (mid + Math.imul(ah8, bl7)) | 0; hi = (hi + Math.imul(ah8, bh7)) | 0; lo = (lo + Math.imul(al7, bl8)) | 0; mid = (mid + Math.imul(al7, bh8)) | 0; mid = (mid + Math.imul(ah7, bl8)) | 0; hi = (hi + Math.imul(ah7, bh8)) | 0; lo = (lo + Math.imul(al6, bl9)) | 0; mid = (mid + Math.imul(al6, bh9)) | 0; mid = (mid + Math.imul(ah6, bl9)) | 0; hi = (hi + Math.imul(ah6, bh9)) | 0; var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; w15 &= 0x3ffffff; /* k = 16 */ lo = Math.imul(al9, bl7); mid = Math.imul(al9, bh7); mid = (mid + Math.imul(ah9, bl7)) | 0; hi = Math.imul(ah9, bh7); lo = (lo + Math.imul(al8, bl8)) | 0; mid = (mid + Math.imul(al8, bh8)) | 0; mid = (mid + Math.imul(ah8, bl8)) | 0; hi = (hi + Math.imul(ah8, bh8)) | 0; lo = (lo + Math.imul(al7, bl9)) | 0; mid = (mid + Math.imul(al7, bh9)) | 0; mid = (mid + Math.imul(ah7, bl9)) | 0; hi = (hi + Math.imul(ah7, bh9)) | 0; var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; w16 &= 0x3ffffff; /* k = 17 */ lo = Math.imul(al9, bl8); mid = Math.imul(al9, bh8); mid = (mid + Math.imul(ah9, bl8)) | 0; hi = Math.imul(ah9, bh8); lo = (lo + Math.imul(al8, bl9)) | 0; mid = (mid + Math.imul(al8, bh9)) | 0; mid = (mid + Math.imul(ah8, bl9)) | 0; hi = (hi + Math.imul(ah8, bh9)) | 0; var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; w17 &= 0x3ffffff; /* k = 18 */ lo = Math.imul(al9, bl9); mid = Math.imul(al9, bh9); mid = (mid + Math.imul(ah9, bl9)) | 0; hi = Math.imul(ah9, bh9); var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; w18 &= 0x3ffffff; o[0] = w0; o[1] = w1; o[2] = w2; o[3] = w3; o[4] = w4; o[5] = w5; o[6] = w6; o[7] = w7; o[8] = w8; o[9] = w9; o[10] = w10; o[11] = w11; o[12] = w12; o[13] = w13; o[14] = w14; o[15] = w15; o[16] = w16; o[17] = w17; o[18] = w18; if (c !== 0) { o[19] = c; out.length++; } return out; }; // Polyfill comb if (!Math.imul) { comb10MulTo = smallMulTo; } function bigMulTo (self, num, out) { out.negative = num.negative ^ self.negative; out.length = self.length + num.length; var carry = 0; var hncarry = 0; for (var k = 0; k < out.length - 1; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff var ncarry = hncarry; hncarry = 0; var rword = carry & 0x3ffffff; var maxJ = Math.min(k, num.length - 1); for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { var i = k - j; var a = self.words[i] | 0; var b = num.words[j] | 0; var r = a * b; var lo = r & 0x3ffffff; ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; lo = (lo + rword) | 0; rword = lo & 0x3ffffff; ncarry = (ncarry + (lo >>> 26)) | 0; hncarry += ncarry >>> 26; ncarry &= 0x3ffffff; } out.words[k] = rword; carry = ncarry; ncarry = hncarry; } if (carry !== 0) { out.words[k] = carry; } else { out.length--; } return out.strip(); } function jumboMulTo (self, num, out) { var fftm = new FFTM(); return fftm.mulp(self, num, out); } BN.prototype.mulTo = function mulTo (num, out) { var res; var len = this.length + num.length; if (this.length === 10 && num.length === 10) { res = comb10MulTo(this, num, out); } else if (len < 63) { res = smallMulTo(this, num, out); } else if (len < 1024) { res = bigMulTo(this, num, out); } else { res = jumboMulTo(this, num, out); } return res; }; // Cooley-Tukey algorithm for FFT // slightly revisited to rely on looping instead of recursion function FFTM (x, y) { this.x = x; this.y = y; } FFTM.prototype.makeRBT = function makeRBT (N) { var t = new Array(N); var l = BN.prototype._countBits(N) - 1; for (var i = 0; i < N; i++) { t[i] = this.revBin(i, l, N); } return t; }; // Returns binary-reversed representation of `x` FFTM.prototype.revBin = function revBin (x, l, N) { if (x === 0 || x === N - 1) return x; var rb = 0; for (var i = 0; i < l; i++) { rb |= (x & 1) << (l - i - 1); x >>= 1; } return rb; }; // Performs "tweedling" phase, therefore 'emulating' // behaviour of the recursive algorithm FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { for (var i = 0; i < N; i++) { rtws[i] = rws[rbt[i]]; itws[i] = iws[rbt[i]]; } }; FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { this.permute(rbt, rws, iws, rtws, itws, N); for (var s = 1; s < N; s <<= 1) { var l = s << 1; var rtwdf = Math.cos(2 * Math.PI / l); var itwdf = Math.sin(2 * Math.PI / l); for (var p = 0; p < N; p += l) { var rtwdf_ = rtwdf; var itwdf_ = itwdf; for (var j = 0; j < s; j++) { var re = rtws[p + j]; var ie = itws[p + j]; var ro = rtws[p + j + s]; var io = itws[p + j + s]; var rx = rtwdf_ * ro - itwdf_ * io; io = rtwdf_ * io + itwdf_ * ro; ro = rx; rtws[p + j] = re + ro; itws[p + j] = ie + io; rtws[p + j + s] = re - ro; itws[p + j + s] = ie - io; /* jshint maxdepth : false */ if (j !== l) { rx = rtwdf * rtwdf_ - itwdf * itwdf_; itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; rtwdf_ = rx; } } } } }; FFTM.prototype.guessLen13b = function guessLen13b (n, m) { var N = Math.max(m, n) | 1; var odd = N & 1; var i = 0; for (N = N / 2 | 0; N; N = N >>> 1) { i++; } return 1 << i + 1 + odd; }; FFTM.prototype.conjugate = function conjugate (rws, iws, N) { if (N <= 1) return; for (var i = 0; i < N / 2; i++) { var t = rws[i]; rws[i] = rws[N - i - 1]; rws[N - i - 1] = t; t = iws[i]; iws[i] = -iws[N - i - 1]; iws[N - i - 1] = -t; } }; FFTM.prototype.normalize13b = function normalize13b (ws, N) { var carry = 0; for (var i = 0; i < N / 2; i++) { var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + Math.round(ws[2 * i] / N) + carry; ws[i] = w & 0x3ffffff; if (w < 0x4000000) { carry = 0; } else { carry = w / 0x4000000 | 0; } } return ws; }; FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { var carry = 0; for (var i = 0; i < len; i++) { carry = carry + (ws[i] | 0); rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; } // Pad with zeroes for (i = 2 * len; i < N; ++i) { rws[i] = 0; } assert(carry === 0); assert((carry & ~0x1fff) === 0); }; FFTM.prototype.stub = function stub (N) { var ph = new Array(N); for (var i = 0; i < N; i++) { ph[i] = 0; } return ph; }; FFTM.prototype.mulp = function mulp (x, y, out) { var N = 2 * this.guessLen13b(x.length, y.length); var rbt = this.makeRBT(N); var _ = this.stub(N); var rws = new Array(N); var rwst = new Array(N); var iwst = new Array(N); var nrws = new Array(N); var nrwst = new Array(N); var niwst = new Array(N); var rmws = out.words; rmws.length = N; this.convert13b(x.words, x.length, rws, N); this.convert13b(y.words, y.length, nrws, N); this.transform(rws, _, rwst, iwst, N, rbt); this.transform(nrws, _, nrwst, niwst, N, rbt); for (var i = 0; i < N; i++) { var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; rwst[i] = rx; } this.conjugate(rwst, iwst, N); this.transform(rwst, iwst, rmws, _, N, rbt); this.conjugate(rmws, _, N); this.normalize13b(rmws, N); out.negative = x.negative ^ y.negative; out.length = x.length + y.length; return out.strip(); }; // Multiply `this` by `num` BN.prototype.mul = function mul (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return this.mulTo(num, out); }; // Multiply employing FFT BN.prototype.mulf = function mulf (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return jumboMulTo(this, num, out); }; // In-place Multiplication BN.prototype.imul = function imul (num) { return this.clone().mulTo(num, this); }; BN.prototype.imuln = function imuln (num) { assert(typeof num === 'number'); assert(num < 0x4000000); // Carry var carry = 0; for (var i = 0; i < this.length; i++) { var w = (this.words[i] | 0) * num; var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); carry >>= 26; carry += (w / 0x4000000) | 0; // NOTE: lo is 27bit maximum carry += lo >>> 26; this.words[i] = lo & 0x3ffffff; } if (carry !== 0) { this.words[i] = carry; this.length++; } return this; }; BN.prototype.muln = function muln (num) { return this.clone().imuln(num); }; // `this` * `this` BN.prototype.sqr = function sqr () { return this.mul(this); }; // `this` * `this` in-place BN.prototype.isqr = function isqr () { return this.imul(this.clone()); }; // Math.pow(`this`, `num`) BN.prototype.pow = function pow (num) { var w = toBitArray(num); if (w.length === 0) return new BN(1); // Skip leading zeroes var res = this; for (var i = 0; i < w.length; i++, res = res.sqr()) { if (w[i] !== 0) break; } if (++i < w.length) { for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { if (w[i] === 0) continue; res = res.mul(q); } } return res; }; // Shift-left in-place BN.prototype.iushln = function iushln (bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); var i; if (r !== 0) { var carry = 0; for (i = 0; i < this.length; i++) { var newCarry = this.words[i] & carryMask; var c = ((this.words[i] | 0) - newCarry) << r; this.words[i] = c | carry; carry = newCarry >>> (26 - r); } if (carry) { this.words[i] = carry; this.length++; } } if (s !== 0) { for (i = this.length - 1; i >= 0; i--) { this.words[i + s] = this.words[i]; } for (i = 0; i < s; i++) { this.words[i] = 0; } this.length += s; } return this.strip(); }; BN.prototype.ishln = function ishln (bits) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushln(bits); }; // Shift-right in-place // NOTE: `hint` is a lowest bit before trailing zeroes // NOTE: if `extended` is present - it will be filled with destroyed bits BN.prototype.iushrn = function iushrn (bits, hint, extended) { assert(typeof bits === 'number' && bits >= 0); var h; if (hint) { h = (hint - (hint % 26)) / 26; } else { h = 0; } var r = bits % 26; var s = Math.min((bits - r) / 26, this.length); var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); var maskedWords = extended; h -= s; h = Math.max(0, h); // Extended mode, copy masked part if (maskedWords) { for (var i = 0; i < s; i++) { maskedWords.words[i] = this.words[i]; } maskedWords.length = s; } if (s === 0) { // No-op, we should not move anything at all } else if (this.length > s) { this.length -= s; for (i = 0; i < this.length; i++) { this.words[i] = this.words[i + s]; } } else { this.words[0] = 0; this.length = 1; } var carry = 0; for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { var word = this.words[i] | 0; this.words[i] = (carry << (26 - r)) | (word >>> r); carry = word & mask; } // Push carried bits as a mask if (maskedWords && carry !== 0) { maskedWords.words[maskedWords.length++] = carry; } if (this.length === 0) { this.words[0] = 0; this.length = 1; } return this.strip(); }; BN.prototype.ishrn = function ishrn (bits, hint, extended) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushrn(bits, hint, extended); }; // Shift-left BN.prototype.shln = function shln (bits) { return this.clone().ishln(bits); }; BN.prototype.ushln = function ushln (bits) { return this.clone().iushln(bits); }; // Shift-right BN.prototype.shrn = function shrn (bits) { return this.clone().ishrn(bits); }; BN.prototype.ushrn = function ushrn (bits) { return this.clone().iushrn(bits); }; // Test if n bit is set BN.prototype.testn = function testn (bit) { assert(typeof bit === 'number' && bit >= 0); var r = bit % 26; var s = (bit - r) / 26; var q = 1 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) return false; // Check bit and return var w = this.words[s]; return !!(w & q); }; // Return only lowers bits of number (in-place) BN.prototype.imaskn = function imaskn (bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; assert(this.negative === 0, 'imaskn works only with positive numbers'); if (this.length <= s) { return this; } if (r !== 0) { s++; } this.length = Math.min(s, this.length); if (r !== 0) { var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); this.words[this.length - 1] &= mask; } return this.strip(); }; // Return only lowers bits of number BN.prototype.maskn = function maskn (bits) { return this.clone().imaskn(bits); }; // Add plain number `num` to `this` BN.prototype.iaddn = function iaddn (num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.isubn(-num); // Possible sign change if (this.negative !== 0) { if (this.length === 1 && (this.words[0] | 0) < num) { this.words[0] = num - (this.words[0] | 0); this.negative = 0; return this; } this.negative = 0; this.isubn(num); this.negative = 1; return this; } // Add without checks return this._iaddn(num); }; BN.prototype._iaddn = function _iaddn (num) { this.words[0] += num; // Carry for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { this.words[i] -= 0x4000000; if (i === this.length - 1) { this.words[i + 1] = 1; } else { this.words[i + 1]++; } } this.length = Math.max(this.length, i + 1); return this; }; // Subtract plain number `num` from `this` BN.prototype.isubn = function isubn (num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.iaddn(-num); if (this.negative !== 0) { this.negative = 0; this.iaddn(num); this.negative = 1; return this; } this.words[0] -= num; if (this.length === 1 && this.words[0] < 0) { this.words[0] = -this.words[0]; this.negative = 1; } else { // Carry for (var i = 0; i < this.length && this.words[i] < 0; i++) { this.words[i] += 0x4000000; this.words[i + 1] -= 1; } } return this.strip(); }; BN.prototype.addn = function addn (num) { return this.clone().iaddn(num); }; BN.prototype.subn = function subn (num) { return this.clone().isubn(num); }; BN.prototype.iabs = function iabs () { this.negative = 0; return this; }; BN.prototype.abs = function abs () { return this.clone().iabs(); }; BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { var len = num.length + shift; var i; this._expand(len); var w; var carry = 0; for (i = 0; i < num.length; i++) { w = (this.words[i + shift] | 0) + carry; var right = (num.words[i] | 0) * mul; w -= right & 0x3ffffff; carry = (w >> 26) - ((right / 0x4000000) | 0); this.words[i + shift] = w & 0x3ffffff; } for (; i < this.length - shift; i++) { w = (this.words[i + shift] | 0) + carry; carry = w >> 26; this.words[i + shift] = w & 0x3ffffff; } if (carry === 0) return this.strip(); // Subtraction overflow assert(carry === -1); carry = 0; for (i = 0; i < this.length; i++) { w = -(this.words[i] | 0) + carry; carry = w >> 26; this.words[i] = w & 0x3ffffff; } this.negative = 1; return this.strip(); }; BN.prototype._wordDiv = function _wordDiv (num, mode) { var shift = this.length - num.length; var a = this.clone(); var b = num; // Normalize var bhi = b.words[b.length - 1] | 0; var bhiBits = this._countBits(bhi); shift = 26 - bhiBits; if (shift !== 0) { b = b.ushln(shift); a.iushln(shift); bhi = b.words[b.length - 1] | 0; } // Initialize quotient var m = a.length - b.length; var q; if (mode !== 'mod') { q = new BN(null); q.length = m + 1; q.words = new Array(q.length); for (var i = 0; i < q.length; i++) { q.words[i] = 0; } } var diff = a.clone()._ishlnsubmul(b, 1, m); if (diff.negative === 0) { a = diff; if (q) { q.words[m] = 1; } } for (var j = m - 1; j >= 0; j--) { var qj = (a.words[b.length + j] | 0) * 0x4000000 + (a.words[b.length + j - 1] | 0); // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max // (0x7ffffff) qj = Math.min((qj / bhi) | 0, 0x3ffffff); a._ishlnsubmul(b, qj, j); while (a.negative !== 0) { qj--; a.negative = 0; a._ishlnsubmul(b, 1, j); if (!a.isZero()) { a.negative ^= 1; } } if (q) { q.words[j] = qj; } } if (q) { q.strip(); } a.strip(); // Denormalize if (mode !== 'div' && shift !== 0) { a.iushrn(shift); } return { div: q || null, mod: a }; }; // NOTE: 1) `mode` can be set to `mod` to request mod only, // to `div` to request div only, or be absent to // request both div & mod // 2) `positive` is true if unsigned mod is requested BN.prototype.divmod = function divmod (num, mode, positive) { assert(!num.isZero()); if (this.isZero()) { return { div: new BN(0), mod: new BN(0) }; } var div, mod, res; if (this.negative !== 0 && num.negative === 0) { res = this.neg().divmod(num, mode); if (mode !== 'mod') { div = res.div.neg(); } if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.iadd(num); } } return { div: div, mod: mod }; } if (this.negative === 0 && num.negative !== 0) { res = this.divmod(num.neg(), mode); if (mode !== 'mod') { div = res.div.neg(); } return { div: div, mod: res.mod }; } if ((this.negative & num.negative) !== 0) { res = this.neg().divmod(num.neg(), mode); if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.isub(num); } } return { div: res.div, mod: mod }; } // Both numbers are positive at this point // Strip both numbers to approximate shift value if (num.length > this.length || this.cmp(num) < 0) { return { div: new BN(0), mod: this }; } // Very short reduction if (num.length === 1) { if (mode === 'div') { return { div: this.divn(num.words[0]), mod: null }; } if (mode === 'mod') { return { div: null, mod: new BN(this.modn(num.words[0])) }; } return { div: this.divn(num.words[0]), mod: new BN(this.modn(num.words[0])) }; } return this._wordDiv(num, mode); }; // Find `this` / `num` BN.prototype.div = function div (num) { return this.divmod(num, 'div', false).div; }; // Find `this` % `num` BN.prototype.mod = function mod (num) { return this.divmod(num, 'mod', false).mod; }; BN.prototype.umod = function umod (num) { return this.divmod(num, 'mod', true).mod; }; // Find Round(`this` / `num`) BN.prototype.divRound = function divRound (num) { var dm = this.divmod(num); // Fast case - exact division if (dm.mod.isZero()) return dm.div; var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; var half = num.ushrn(1); var r2 = num.andln(1); var cmp = mod.cmp(half); // Round down if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; // Round up return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); }; BN.prototype.modn = function modn (num) { assert(num <= 0x3ffffff); var p = (1 << 26) % num; var acc = 0; for (var i = this.length - 1; i >= 0; i--) { acc = (p * acc + (this.words[i] | 0)) % num; } return acc; }; // In-place division by number BN.prototype.idivn = function idivn (num) { assert(num <= 0x3ffffff); var carry = 0; for (var i = this.length - 1; i >= 0; i--) { var w = (this.words[i] | 0) + carry * 0x4000000; this.words[i] = (w / num) | 0; carry = w % num; } return this.strip(); }; BN.prototype.divn = function divn (num) { return this.clone().idivn(num); }; BN.prototype.egcd = function egcd (p) { assert(p.negative === 0); assert(!p.isZero()); var x = this; var y = p.clone(); if (x.negative !== 0) { x = x.umod(p); } else { x = x.clone(); } // A * x + B * y = x var A = new BN(1); var B = new BN(0); // C * x + D * y = y var C = new BN(0); var D = new BN(1); var g = 0; while (x.isEven() && y.isEven()) { x.iushrn(1); y.iushrn(1); ++g; } var yp = y.clone(); var xp = x.clone(); while (!x.isZero()) { for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); if (i > 0) { x.iushrn(i); while (i-- > 0) { if (A.isOdd() || B.isOdd()) { A.iadd(yp); B.isub(xp); } A.iushrn(1); B.iushrn(1); } } for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); if (j > 0) { y.iushrn(j); while (j-- > 0) { if (C.isOdd() || D.isOdd()) { C.iadd(yp); D.isub(xp); } C.iushrn(1); D.iushrn(1); } } if (x.cmp(y) >= 0) { x.isub(y); A.isub(C); B.isub(D); } else { y.isub(x); C.isub(A); D.isub(B); } } return { a: C, b: D, gcd: y.iushln(g) }; }; // This is reduced incarnation of the binary EEA // above, designated to invert members of the // _prime_ fields F(p) at a maximal speed BN.prototype._invmp = function _invmp (p) { assert(p.negative === 0); assert(!p.isZero()); var a = this; var b = p.clone(); if (a.negative !== 0) { a = a.umod(p); } else { a = a.clone(); } var x1 = new BN(1); var x2 = new BN(0); var delta = b.clone(); while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); if (i > 0) { a.iushrn(i); while (i-- > 0) { if (x1.isOdd()) { x1.iadd(delta); } x1.iushrn(1); } } for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); if (j > 0) { b.iushrn(j); while (j-- > 0) { if (x2.isOdd()) { x2.iadd(delta); } x2.iushrn(1); } } if (a.cmp(b) >= 0) { a.isub(b); x1.isub(x2); } else { b.isub(a); x2.isub(x1); } } var res; if (a.cmpn(1) === 0) { res = x1; } else { res = x2; } if (res.cmpn(0) < 0) { res.iadd(p); } return res; }; BN.prototype.gcd = function gcd (num) { if (this.isZero()) return num.abs(); if (num.isZero()) return this.abs(); var a = this.clone(); var b = num.clone(); a.negative = 0; b.negative = 0; // Remove common factor of two for (var shift = 0; a.isEven() && b.isEven(); shift++) { a.iushrn(1); b.iushrn(1); } do { while (a.isEven()) { a.iushrn(1); } while (b.isEven()) { b.iushrn(1); } var r = a.cmp(b); if (r < 0) { // Swap `a` and `b` to make `a` always bigger than `b` var t = a; a = b; b = t; } else if (r === 0 || b.cmpn(1) === 0) { break; } a.isub(b); } while (true); return b.iushln(shift); }; // Invert number in the field F(num) BN.prototype.invm = function invm (num) { return this.egcd(num).a.umod(num); }; BN.prototype.isEven = function isEven () { return (this.words[0] & 1) === 0; }; BN.prototype.isOdd = function isOdd () { return (this.words[0] & 1) === 1; }; // And first word and num BN.prototype.andln = function andln (num) { return this.words[0] & num; }; // Increment at the bit position in-line BN.prototype.bincn = function bincn (bit) { assert(typeof bit === 'number'); var r = bit % 26; var s = (bit - r) / 26; var q = 1 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) { this._expand(s + 1); this.words[s] |= q; return this; } // Add bit and propagate, if needed var carry = q; for (var i = s; carry !== 0 && i < this.length; i++) { var w = this.words[i] | 0; w += carry; carry = w >>> 26; w &= 0x3ffffff; this.words[i] = w; } if (carry !== 0) { this.words[i] = carry; this.length++; } return this; }; BN.prototype.isZero = function isZero () { return this.length === 1 && this.words[0] === 0; }; BN.prototype.cmpn = function cmpn (num) { var negative = num < 0; if (this.negative !== 0 && !negative) return -1; if (this.negative === 0 && negative) return 1; this.strip(); var res; if (this.length > 1) { res = 1; } else { if (negative) { num = -num; } assert(num <= 0x3ffffff, 'Number is too big'); var w = this.words[0] | 0; res = w === num ? 0 : w < num ? -1 : 1; } if (this.negative !== 0) return -res | 0; return res; }; // Compare two numbers and return: // 1 - if `this` > `num` // 0 - if `this` == `num` // -1 - if `this` < `num` BN.prototype.cmp = function cmp (num) { if (this.negative !== 0 && num.negative === 0) return -1; if (this.negative === 0 && num.negative !== 0) return 1; var res = this.ucmp(num); if (this.negative !== 0) return -res | 0; return res; }; // Unsigned comparison BN.prototype.ucmp = function ucmp (num) { // At this point both numbers have the same sign if (this.length > num.length) return 1; if (this.length < num.length) return -1; var res = 0; for (var i = this.length - 1; i >= 0; i--) { var a = this.words[i] | 0; var b = num.words[i] | 0; if (a === b) continue; if (a < b) { res = -1; } else if (a > b) { res = 1; } break; } return res; }; BN.prototype.gtn = function gtn (num) { return this.cmpn(num) === 1; }; BN.prototype.gt = function gt (num) { return this.cmp(num) === 1; }; BN.prototype.gten = function gten (num) { return this.cmpn(num) >= 0; }; BN.prototype.gte = function gte (num) { return this.cmp(num) >= 0; }; BN.prototype.ltn = function ltn (num) { return this.cmpn(num) === -1; }; BN.prototype.lt = function lt (num) { return this.cmp(num) === -1; }; BN.prototype.lten = function lten (num) { return this.cmpn(num) <= 0; }; BN.prototype.lte = function lte (num) { return this.cmp(num) <= 0; }; BN.prototype.eqn = function eqn (num) { return this.cmpn(num) === 0; }; BN.prototype.eq = function eq (num) { return this.cmp(num) === 0; }; // // A reduce context, could be using montgomery or something better, depending // on the `m` itself. // BN.red = function red (num) { return new Red(num); }; BN.prototype.toRed = function toRed (ctx) { assert(!this.red, 'Already a number in reduction context'); assert(this.negative === 0, 'red works only with positives'); return ctx.convertTo(this)._forceRed(ctx); }; BN.prototype.fromRed = function fromRed () { assert(this.red, 'fromRed works only with numbers in reduction context'); return this.red.convertFrom(this); }; BN.prototype._forceRed = function _forceRed (ctx) { this.red = ctx; return this; }; BN.prototype.forceRed = function forceRed (ctx) { assert(!this.red, 'Already a number in reduction context'); return this._forceRed(ctx); }; BN.prototype.redAdd = function redAdd (num) { assert(this.red, 'redAdd works only with red numbers'); return this.red.add(this, num); }; BN.prototype.redIAdd = function redIAdd (num) { assert(this.red, 'redIAdd works only with red numbers'); return this.red.iadd(this, num); }; BN.prototype.redSub = function redSub (num) { assert(this.red, 'redSub works only with red numbers'); return this.red.sub(this, num); }; BN.prototype.redISub = function redISub (num) { assert(this.red, 'redISub works only with red numbers'); return this.red.isub(this, num); }; BN.prototype.redShl = function redShl (num) { assert(this.red, 'redShl works only with red numbers'); return this.red.shl(this, num); }; BN.prototype.redMul = function redMul (num) { assert(this.red, 'redMul works only with red numbers'); this.red._verify2(this, num); return this.red.mul(this, num); }; BN.prototype.redIMul = function redIMul (num) { assert(this.red, 'redMul works only with red numbers'); this.red._verify2(this, num); return this.red.imul(this, num); }; BN.prototype.redSqr = function redSqr () { assert(this.red, 'redSqr works only with red numbers'); this.red._verify1(this); return this.red.sqr(this); }; BN.prototype.redISqr = function redISqr () { assert(this.red, 'redISqr works only with red numbers'); this.red._verify1(this); return this.red.isqr(this); }; // Square root over p BN.prototype.redSqrt = function redSqrt () { assert(this.red, 'redSqrt works only with red numbers'); this.red._verify1(this); return this.red.sqrt(this); }; BN.prototype.redInvm = function redInvm () { assert(this.red, 'redInvm works only with red numbers'); this.red._verify1(this); return this.red.invm(this); }; // Return negative clone of `this` % `red modulo` BN.prototype.redNeg = function redNeg () { assert(this.red, 'redNeg works only with red numbers'); this.red._verify1(this); return this.red.neg(this); }; BN.prototype.redPow = function redPow (num) { assert(this.red && !num.red, 'redPow(normalNum)'); this.red._verify1(this); return this.red.pow(this, num); }; // Prime numbers with efficient reduction var primes = { k256: null, p224: null, p192: null, p25519: null }; // Pseudo-Mersenne prime function MPrime (name, p) { // P = 2 ^ N - K this.name = name; this.p = new BN(p, 16); this.n = this.p.bitLength(); this.k = new BN(1).iushln(this.n).isub(this.p); this.tmp = this._tmp(); } MPrime.prototype._tmp = function _tmp () { var tmp = new BN(null); tmp.words = new Array(Math.ceil(this.n / 13)); return tmp; }; MPrime.prototype.ireduce = function ireduce (num) { // Assumes that `num` is less than `P^2` // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) var r = num; var rlen; do { this.split(r, this.tmp); r = this.imulK(r); r = r.iadd(this.tmp); rlen = r.bitLength(); } while (rlen > this.n); var cmp = rlen < this.n ? -1 : r.ucmp(this.p); if (cmp === 0) { r.words[0] = 0; r.length = 1; } else if (cmp > 0) { r.isub(this.p); } else { r.strip(); } return r; }; MPrime.prototype.split = function split (input, out) { input.iushrn(this.n, 0, out); }; MPrime.prototype.imulK = function imulK (num) { return num.imul(this.k); }; function K256 () { MPrime.call( this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); } inherits(K256, MPrime); K256.prototype.split = function split (input, output) { // 256 = 9 * 26 + 22 var mask = 0x3fffff; var outLen = Math.min(input.length, 9); for (var i = 0; i < outLen; i++) { output.words[i] = input.words[i]; } output.length = outLen; if (input.length <= 9) { input.words[0] = 0; input.length = 1; return; } // Shift by 9 limbs var prev = input.words[9]; output.words[output.length++] = prev & mask; for (i = 10; i < input.length; i++) { var next = input.words[i] | 0; input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); prev = next; } prev >>>= 22; input.words[i - 10] = prev; if (prev === 0 && input.length > 10) { input.length -= 10; } else { input.length -= 9; } }; K256.prototype.imulK = function imulK (num) { // K = 0x1000003d1 = [ 0x40, 0x3d1 ] num.words[num.length] = 0; num.words[num.length + 1] = 0; num.length += 2; // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 var lo = 0; for (var i = 0; i < num.length; i++) { var w = num.words[i] | 0; lo += w * 0x3d1; num.words[i] = lo & 0x3ffffff; lo = w * 0x40 + ((lo / 0x4000000) | 0); } // Fast length reduction if (num.words[num.length - 1] === 0) { num.length--; if (num.words[num.length - 1] === 0) { num.length--; } } return num; }; function P224 () { MPrime.call( this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); } inherits(P224, MPrime); function P192 () { MPrime.call( this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); } inherits(P192, MPrime); function P25519 () { // 2 ^ 255 - 19 MPrime.call( this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); } inherits(P25519, MPrime); P25519.prototype.imulK = function imulK (num) { // K = 0x13 var carry = 0; for (var i = 0; i < num.length; i++) { var hi = (num.words[i] | 0) * 0x13 + carry; var lo = hi & 0x3ffffff; hi >>>= 26; num.words[i] = lo; carry = hi; } if (carry !== 0) { num.words[num.length++] = carry; } return num; }; // Exported mostly for testing purposes, use plain name instead BN._prime = function prime (name) { // Cached version of prime if (primes[name]) return primes[name]; var prime; if (name === 'k256') { prime = new K256(); } else if (name === 'p224') { prime = new P224(); } else if (name === 'p192') { prime = new P192(); } else if (name === 'p25519') { prime = new P25519(); } else { throw new Error('Unknown prime ' + name); } primes[name] = prime; return prime; }; // // Base reduction engine // function Red (m) { if (typeof m === 'string') { var prime = BN._prime(m); this.m = prime.p; this.prime = prime; } else { assert(m.gtn(1), 'modulus must be greater than 1'); this.m = m; this.prime = null; } } Red.prototype._verify1 = function _verify1 (a) { assert(a.negative === 0, 'red works only with positives'); assert(a.red, 'red works only with red numbers'); }; Red.prototype._verify2 = function _verify2 (a, b) { assert((a.negative | b.negative) === 0, 'red works only with positives'); assert(a.red && a.red === b.red, 'red works only with red numbers'); }; Red.prototype.imod = function imod (a) { if (this.prime) return this.prime.ireduce(a)._forceRed(this); return a.umod(this.m)._forceRed(this); }; Red.prototype.neg = function neg (a) { if (a.isZero()) { return a.clone(); } return this.m.sub(a)._forceRed(this); }; Red.prototype.add = function add (a, b) { this._verify2(a, b); var res = a.add(b); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res._forceRed(this); }; Red.prototype.iadd = function iadd (a, b) { this._verify2(a, b); var res = a.iadd(b); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res; }; Red.prototype.sub = function sub (a, b) { this._verify2(a, b); var res = a.sub(b); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res._forceRed(this); }; Red.prototype.isub = function isub (a, b) { this._verify2(a, b); var res = a.isub(b); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res; }; Red.prototype.shl = function shl (a, num) { this._verify1(a); return this.imod(a.ushln(num)); }; Red.prototype.imul = function imul (a, b) { this._verify2(a, b); return this.imod(a.imul(b)); }; Red.prototype.mul = function mul (a, b) { this._verify2(a, b); return this.imod(a.mul(b)); }; Red.prototype.isqr = function isqr (a) { return this.imul(a, a.clone()); }; Red.prototype.sqr = function sqr (a) { return this.mul(a, a); }; Red.prototype.sqrt = function sqrt (a) { if (a.isZero()) return a.clone(); var mod3 = this.m.andln(3); assert(mod3 % 2 === 1); // Fast case if (mod3 === 3) { var pow = this.m.add(new BN(1)).iushrn(2); return this.pow(a, pow); } // Tonelli-Shanks algorithm (Totally unoptimized and slow) // // Find Q and S, that Q * 2 ^ S = (P - 1) var q = this.m.subn(1); var s = 0; while (!q.isZero() && q.andln(1) === 0) { s++; q.iushrn(1); } assert(!q.isZero()); var one = new BN(1).toRed(this); var nOne = one.redNeg(); // Find quadratic non-residue // NOTE: Max is such because of generalized Riemann hypothesis. var lpow = this.m.subn(1).iushrn(1); var z = this.m.bitLength(); z = new BN(2 * z * z).toRed(this); while (this.pow(z, lpow).cmp(nOne) !== 0) { z.redIAdd(nOne); } var c = this.pow(z, q); var r = this.pow(a, q.addn(1).iushrn(1)); var t = this.pow(a, q); var m = s; while (t.cmp(one) !== 0) { var tmp = t; for (var i = 0; tmp.cmp(one) !== 0; i++) { tmp = tmp.redSqr(); } assert(i < m); var b = this.pow(c, new BN(1).iushln(m - i - 1)); r = r.redMul(b); c = b.redSqr(); t = t.redMul(c); m = i; } return r; }; Red.prototype.invm = function invm (a) { var inv = a._invmp(this.m); if (inv.negative !== 0) { inv.negative = 0; return this.imod(inv).redNeg(); } else { return this.imod(inv); } }; Red.prototype.pow = function pow (a, num) { if (num.isZero()) return new BN(1); if (num.cmpn(1) === 0) return a.clone(); var windowSize = 4; var wnd = new Array(1 << windowSize); wnd[0] = new BN(1).toRed(this); wnd[1] = a; for (var i = 2; i < wnd.length; i++) { wnd[i] = this.mul(wnd[i - 1], a); } var res = wnd[0]; var current = 0; var currentLen = 0; var start = num.bitLength() % 26; if (start === 0) { start = 26; } for (i = num.length - 1; i >= 0; i--) { var word = num.words[i]; for (var j = start - 1; j >= 0; j--) { var bit = (word >> j) & 1; if (res !== wnd[0]) { res = this.sqr(res); } if (bit === 0 && current === 0) { currentLen = 0; continue; } current <<= 1; current |= bit; currentLen++; if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; res = this.mul(res, wnd[current]); currentLen = 0; current = 0; } start = 26; } return res; }; Red.prototype.convertTo = function convertTo (num) { var r = num.umod(this.m); return r === num ? r.clone() : r; }; Red.prototype.convertFrom = function convertFrom (num) { var res = num.clone(); res.red = null; return res; }; // // Montgomery method engine // BN.mont = function mont (num) { return new Mont(num); }; function Mont (m) { Red.call(this, m); this.shift = this.m.bitLength(); if (this.shift % 26 !== 0) { this.shift += 26 - (this.shift % 26); } this.r = new BN(1).iushln(this.shift); this.r2 = this.imod(this.r.sqr()); this.rinv = this.r._invmp(this.m); this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); this.minv = this.minv.umod(this.r); this.minv = this.r.sub(this.minv); } inherits(Mont, Red); Mont.prototype.convertTo = function convertTo (num) { return this.imod(num.ushln(this.shift)); }; Mont.prototype.convertFrom = function convertFrom (num) { var r = this.imod(num.mul(this.rinv)); r.red = null; return r; }; Mont.prototype.imul = function imul (a, b) { if (a.isZero() || b.isZero()) { a.words[0] = 0; a.length = 1; return a; } var t = a.imul(b); var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u = t.isub(c).iushrn(this.shift); var res = u; if (u.cmp(this.m) >= 0) { res = u.isub(this.m); } else if (u.cmpn(0) < 0) { res = u.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.mul = function mul (a, b) { if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); var t = a.mul(b); var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u = t.isub(c).iushrn(this.shift); var res = u; if (u.cmp(this.m) >= 0) { res = u.isub(this.m); } else if (u.cmpn(0) < 0) { res = u.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.invm = function invm (a) { // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R var res = this.imod(a._invmp(this.m).mul(this.r2)); return res._forceRed(this); }; })(typeof module === 'undefined' || module, this); },{}],5:[function(require,module,exports){ },{}],6:[function(require,module,exports){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ /* eslint-disable no-proto */ 'use strict' var base64 = require('base64-js') var ieee754 = require('ieee754') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 var K_MAX_LENGTH = 0x7fffffff exports.kMaxLength = K_MAX_LENGTH /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Print warning and recommend using `buffer` v4.x which has an Object * implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * We report that the browser does not support typed arrays if the are not subclassable * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support * for __proto__ and has a buggy typed array implementation. */ Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() if (!Buffer.TYPED_ARRAY_SUPPORT) { console.error( 'This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.') } function typedArraySupport () { // Can typed array instances can be augmented? try { var arr = new Uint8Array(1) arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} return arr.foo() === 42 } catch (e) { return false } } function createBuffer (length) { if (length > K_MAX_LENGTH) { throw new RangeError('Invalid typed array length') } // Return an augmented `Uint8Array` instance var buf = new Uint8Array(length) buf.__proto__ = Buffer.prototype return buf } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer (arg, encodingOrOffset, length) { // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new Error( 'If encoding is specified then the first argument must be a string' ) } return allocUnsafe(arg) } return from(arg, encodingOrOffset, length) } // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 if (typeof Symbol !== 'undefined' && Symbol.species && Buffer[Symbol.species] === Buffer) { Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true, enumerable: false, writable: false }) } Buffer.poolSize = 8192 // not used by this implementation function from (value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { return fromArrayBuffer(value, encodingOrOffset, length) } if (typeof value === 'string') { return fromString(value, encodingOrOffset) } return fromObject(value) } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(value, encodingOrOffset, length) } // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: // https://github.com/feross/buffer/pull/148 Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be a number') } else if (size < 0) { throw new RangeError('"size" argument must not be negative') } } function alloc (size, fill, encoding) { assertSize(size) if (size <= 0) { return createBuffer(size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill) } return createBuffer(size) } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(size, fill, encoding) } function allocUnsafe (size) { assertSize(size) return createBuffer(size < 0 ? 0 : checked(size) | 0) } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(size) } /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(size) } function fromString (string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } var length = byteLength(string, encoding) | 0 var buf = createBuffer(length) var actual = buf.write(string, encoding) if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') buf = buf.slice(0, actual) } return buf } function fromArrayLike (array) { var length = array.length < 0 ? 0 : checked(array.length) | 0 var buf = createBuffer(length) for (var i = 0; i < length; i += 1) { buf[i] = array[i] & 255 } return buf } function fromArrayBuffer (array, byteOffset, length) { array.byteLength // this throws if `array` is not a valid ArrayBuffer if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('\'offset\' is out of bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('\'length\' is out of bounds') } var buf if (byteOffset === undefined && length === undefined) { buf = new Uint8Array(array) } else if (length === undefined) { buf = new Uint8Array(array, byteOffset) } else { buf = new Uint8Array(array, byteOffset, length) } // Return an augmented `Uint8Array` instance buf.__proto__ = Buffer.prototype return buf } function fromObject (obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0 var buf = createBuffer(len) if (buf.length === 0) { return buf } obj.copy(buf, 0, 0, len) return buf } if (obj) { if ((typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer) || 'length' in obj) { if (typeof obj.length !== 'number' || isnan(obj.length)) { return createBuffer(0) } return fromArrayLike(obj) } if (obj.type === 'Buffer' && Array.isArray(obj.data)) { return fromArrayLike(obj.data) } } throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } function checked (length) { // Note: cannot use `length < K_MAX_LENGTH` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= K_MAX_LENGTH) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') } return length | 0 } function SlowBuffer (length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0 } return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers') } if (a === b) return 0 var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i] y = b[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!Array.isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { return Buffer.alloc(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; ++i) { length += list[i].length } } var buffer = Buffer.allocUnsafe(length) var pos = 0 for (i = 0; i < list.length; ++i) { var buf = list[i] if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers') } buf.copy(buffer, pos) pos += buf.length } return buffer } function byteLength (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { string = '' + string } var len = string.length if (len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len case 'utf8': case 'utf-8': case undefined: return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) return utf8ToBytes(string).length // assume utf8 encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0 } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return '' } if (end === undefined || end > this.length) { end = this.length } if (end <= 0) { return '' } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0 start >>>= 0 if (end <= start) { return '' } if (!encoding) encoding = 'utf8' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'latin1': case 'binary': return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. Buffer.prototype._isBuffer = true function swap (b, n, m) { var i = b[n] b[n] = b[m] b[m] = i } Buffer.prototype.swap16 = function swap16 () { var len = this.length if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1) } return this } Buffer.prototype.swap32 = function swap32 () { var len = this.length if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3) swap(this, i + 1, i + 2) } return this } Buffer.prototype.swap64 = function swap64 () { var len = this.length if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7) swap(this, i + 1, i + 6) swap(this, i + 2, i + 5) swap(this, i + 3, i + 4) } return this } Buffer.prototype.toString = function toString () { var length = this.length if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '' } Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!Buffer.isBuffer(target)) { throw new TypeError('Argument must be a Buffer') } if (start === undefined) { start = 0 } if (end === undefined) { end = target ? target.length : 0 } if (thisStart === undefined) { thisStart = 0 } if (thisEnd === undefined) { thisEnd = this.length } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index') } if (thisStart >= thisEnd && start >= end) { return 0 } if (thisStart >= thisEnd) { return -1 } if (start >= end) { return 1 } start >>>= 0 end >>>= 0 thisStart >>>= 0 thisEnd >>>= 0 if (this === target) return 0 var x = thisEnd - thisStart var y = end - start var len = Math.min(x, y) var thisCopy = this.slice(thisStart, thisEnd) var targetCopy = target.slice(start, end) for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i] y = targetCopy[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1 // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset byteOffset = 0 } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000 } byteOffset = +byteOffset // Coerce to Number. if (isNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : (buffer.length - 1) } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset if (byteOffset >= buffer.length) { if (dir) return -1 else byteOffset = buffer.length - 1 } else if (byteOffset < 0) { if (dir) byteOffset = 0 else return -1 } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding) } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1 } return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF // Search for a byte value [0-255] if (typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } } return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } throw new TypeError('val must be string, number or Buffer') } function arrayIndexOf (arr, val, byteOffset, encoding, dir) { var indexSize = 1 var arrLength = arr.length var valLength = val.length if (encoding !== undefined) { encoding = String(encoding).toLowerCase() if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2 arrLength /= 2 valLength /= 2 byteOffset /= 2 } } function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } var i if (dir) { var foundIndex = -1 for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1 } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength for (i = byteOffset; i >= 0; i--) { var found = true for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false break } } if (found) return i } } return -1 } Buffer.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 } Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) } Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (isNaN(parsed)) return i buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset >>> 0 if (isFinite(length)) { length = length >>> 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': return latin1Write(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function latin1Slice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; ++i) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf = this.subarray(start, end) // Return an augmented `Uint8Array` instance newBuf.__proto__ = Buffer.prototype return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 var sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 var sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range') if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start var i if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } } else if (len < 1000) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start] } } else { Uint8Array.prototype.set.call( target, this.subarray(start, start + len), targetStart ) } return len } // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start start = 0 end = this.length } else if (typeof end === 'string') { encoding = end end = this.length } if (val.length === 1) { var code = val.charCodeAt(0) if (code < 256) { val = code } } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { val = val & 255 } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index') } if (end <= start) { return this } start = start >>> 0 end = end === undefined ? this.length : end >>> 0 if (!val) val = 0 var i if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val } } else { var bytes = Buffer.isBuffer(val) ? val : new Buffer(val, encoding) var len = bytes.length for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len] } } return this } // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } // valid lead leadSurrogate = codePoint continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; ++i) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } function isnan (val) { return val !== val // eslint-disable-line no-self-compare } },{"base64-js":3,"ieee754":9}],7:[function(require,module,exports){ (function (Buffer){ 'use strict'; /* eslint-disable */ var utils = require('./utils/index.js'); var uint256Coder = utils.uint256Coder; var coderBoolean = utils.coderBoolean; var coderFixedBytes = utils.coderFixedBytes; var coderAddress = utils.coderAddress; var coderDynamicBytes = utils.coderDynamicBytes; var coderString = utils.coderString; var coderArray = utils.coderArray; var paramTypePart = utils.paramTypePart; var getParamCoder = utils.getParamCoder; function Result() {} function encodeParams(types, values) { if (types.length !== values.length) { throw new Error('[ethjs-abi] while encoding params, types/values mismatch, types length ' + types.length + ' should be ' + values.length); } var parts = []; types.forEach(function (type, index) { var coder = getParamCoder(type); parts.push({ dynamic: coder.dynamic, value: coder.encode(values[index]) }); }); function alignSize(size) { return parseInt(32 * Math.ceil(size / 32)); } var staticSize = 0, dynamicSize = 0; parts.forEach(function (part) { if (part.dynamic) { staticSize += 32; dynamicSize += alignSize(part.value.length); } else { staticSize += alignSize(part.value.length); } }); var offset = 0, dynamicOffset = staticSize; var data = new Buffer(staticSize + dynamicSize); parts.forEach(function (part, index) { if (part.dynamic) { uint256Coder.encode(dynamicOffset).copy(data, offset); offset += 32; part.value.copy(data, dynamicOffset); dynamicOffset += alignSize(part.value.length); } else { part.value.copy(data, offset); offset += alignSize(part.value.length); } }); return '0x' + data.toString('hex'); } // decode bytecode data from output names and types function decodeParams(names, types, data) { // Names is optional, so shift over all the parameters if not provided if (arguments.length < 3) { data = types; types = names; names = []; } data = utils.hexOrBuffer(data); var values = new Result(); var offset = 0; types.forEach(function (type, index) { var coder = getParamCoder(type); if (coder.dynamic) { var dynamicOffset = uint256Coder.decode(data, offset); var result = coder.decode(data, dynamicOffset.value.toNumber()); offset += dynamicOffset.consumed; } else { var result = coder.decode(data, offset); offset += result.consumed; } values[index] = result.value; if (names[index]) { values[names[index]] = result.value; } }); return values; } // encode method ABI object with values in an array, output bytecode function encodeMethod(method, values) { var signature = method.name + '(' + utils.getKeys(method.inputs, 'type').join(',') + ')'; var signatureEncoded = '0x' + new Buffer(utils.keccak256(signature), 'hex').slice(0, 4).toString('hex'); var paramsEncoded = encodeParams(utils.getKeys(method.inputs, 'type'), values).substring(2); return '' + signatureEncoded + paramsEncoded; } // decode method data bytecode, from method ABI object function decodeMethod(method, data) { var outputNames = utils.getKeys(method.outputs, 'name', true); var outputTypes = utils.getKeys(method.outputs, 'type'); return decodeParams(outputNames, outputTypes, utils.hexOrBuffer(data)); } // decode method data bytecode, from method ABI object function encodeEvent(eventObject, values) { return encodeMethod(eventObject, values); } // decode method data bytecode, from method ABI object function decodeEvent(eventObject, data) { var inputNames = utils.getKeys(eventObject.inputs, 'name', true); var inputTypes = utils.getKeys(eventObject.inputs, 'type'); return decodeParams(inputNames, inputTypes, utils.hexOrBuffer(data)); } module.exports = { encodeParams: encodeParams, decodeParams: decodeParams, encodeMethod: encodeMethod, decodeMethod: decodeMethod, encodeEvent: encodeEvent, decodeEvent: decodeEvent }; }).call(this,require("buffer").Buffer) },{"./utils/index.js":8,"buffer":6}],8:[function(require,module,exports){ (function (Buffer){ 'use strict'; var BN = require('bn.js'); var numberToBN = require('number-to-bn'); var keccak256 = require('js-sha3').keccak_256; // from ethereumjs-util function stripZeros(aInput) { var a = aInput; // eslint-disable-line var first = a[0]; // eslint-disable-line while (a.length > 0 && first.toString() === '0') { a = a.slice(1); first = a[0]; } return a; } function bnToBuffer(bnInput) { var bn = bnInput; // eslint-disable-line var hex = bn.toString(16); // eslint-disable-line if (hex.length % 2) { hex = '0' + hex; } return stripZeros(new Buffer(hex, 'hex')); } function isHexString(value, length) { if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) { return false; } if (length && value.length !== 2 + 2 * length) { return false; } return true; } function hexOrBuffer(valueInput, name) { var value = valueInput; // eslint-disable-line if (!Buffer.isBuffer(value)) { if (!isHexString(value)) { var error = new Error(name ? '[ethjs-abi] invalid ' + name : '[ethjs-abi] invalid hex or buffer, must be a prefixed alphanumeric even length hex string'); error.reason = '[ethjs-abi] invalid hex string, hex must be prefixed and alphanumeric (e.g. 0x023..)'; error.value = value; throw error; } value = value.substring(2); if (value.length % 2) { value = '0' + value; } value = new Buffer(value, 'hex'); } return value; } function hexlify(value) { if (typeof value === 'number') { return '0x' + bnToBuffer(new BN(value)).toString('hex'); } else if (value.mod || value.modulo) { return '0x' + bnToBuffer(value).toString('hex'); } else { // eslint-disable-line return '0x' + hexOrBuffer(value).toString('hex'); } } // getKeys([{a: 1, b: 2}, {a: 3, b: 4}], 'a') => [1, 3] function getKeys(params, key, allowEmpty) { var result = []; // eslint-disable-line if (!Array.isArray(params)) { throw new Error('[ethjs-abi] while getting keys, invalid params value ' + JSON.stringify(params)); } for (var i = 0; i < params.length; i++) { // eslint-disable-line var value = params[i][key]; // eslint-disable-line if (allowEmpty && !value) { value = ''; } else if (typeof value !== 'string') { throw new Error('[ethjs-abi] while getKeys found invalid ABI data structure, type value not string'); } result.push(value); } return result; } function coderNumber(size, signed) { return { encode: function encodeNumber(valueInput) { var value = valueInput; // eslint-disable-line if (typeof value === 'object' && value.toString && (value.toTwos || value.dividedToIntegerBy)) { value = value.toString(10).split('.')[0]; } if (typeof value === 'string' || typeof value === 'number') { value = String(value).split('.')[0]; } value = numberToBN(value); value = value.toTwos(size * 8).maskn(size * 8); if (signed) { value = value.fromTwos(size * 8).toTwos(256); } return value.toArrayLike(Buffer, 'be', 32); }, decode: function decodeNumber(data, offset) { var junkLength = 32 - size; // eslint-disable-line var value = new BN(data.slice(offset + junkLength, offset + 32)); // eslint-disable-line if (signed) { value = value.fromTwos(size * 8); } else { value = value.maskn(size * 8); } return { consumed: 32, value: new BN(value.toString(10)) }; } }; } var uint256Coder = coderNumber(32, false); var coderBoolean = { encode: function encodeBoolean(value) { return uint256Coder.encode(value ? 1 : 0); }, decode: function decodeBoolean(data, offset) { var result = uint256Coder.decode(data, offset); // eslint-disable-line return { consumed: result.consumed, value: !result.value.isZero() }; } }; function coderFixedBytes(length) { return { encode: function encodeFixedBytes(valueInput) { var value = valueInput; // eslint-disable-line value = hexOrBuffer(value); if (value.length === 32) { return value; } var result = new Buffer(32); // eslint-disable-line result.fill(0); value.copy(result); return result; }, decode: function decodeFixedBytes(data, offset) { if (data.length < offset + 32) { throw new Error('[ethjs-abi] while decoding fixed bytes, invalid bytes data length: ' + length); } return { consumed: 32, value: '0x' + data.slice(offset, offset + length).toString('hex') }; } }; } var coderAddress = { encode: function encodeAddress(valueInput) { var value = valueInput; // eslint-disable-line var result = new Buffer(32); // eslint-disable-line if (!isHexString(value, 20)) { throw new Error('[ethjs-abi] while encoding address, invalid address value, not alphanumeric 20 byte hex string'); } value = hexOrBuffer(value); result.fill(0); value.copy(result, 12); return result; }, decode: function decodeAddress(data, offset) { if (data.length === 0) { return { consumed: 32, value: '0x' }; } if (data.length < offset + 32) { throw new Error('[ethjs-abi] while decoding address data, invalid address data, invalid byte length ' + data.length); } return { consumed: 32, value: '0x' + data.slice(offset + 12, offset + 32).toString('hex') }; } }; function encodeDynamicBytesHelper(value) { var dataLength = parseInt(32 * Math.ceil(value.length / 32)); // eslint-disable-line var padding = new Buffer(dataLength - value.length); // eslint-disable-line padding.fill(0); return Buffer.concat([uint256Coder.encode(value.length), value, padding]); } function decodeDynamicBytesHelper(data, offset) { if (data.length < offset + 32) { throw new Error('[ethjs-abi] while decoding dynamic bytes data, invalid bytes length: ' + data.length + ' should be less than ' + (offset + 32)); } var length = uint256Coder.decode(data, offset).value; // eslint-disable-line length = length.toNumber(); if (data.length < offset + 32 + length) { throw new Error('[ethjs-abi] while decoding dynamic bytes data, invalid bytes length: ' + data.length + ' should be less than ' + (offset + 32 + length)); } return { consumed: parseInt(32 + 32 * Math.ceil(length / 32), 10), value: data.slice(offset + 32, offset + 32 + length) }; } var coderDynamicBytes = { encode: function encodeDynamicBytes(value) { return encodeDynamicBytesHelper(hexOrBuffer(value)); }, decode: function decodeDynamicBytes(data, offset) { var result = decodeDynamicBytesHelper(data, offset); // eslint-disable-line result.value = '0x' + result.value.toString('hex'); return result; }, dynamic: true }; var coderString = { encode: function encodeString(value) { return encodeDynamicBytesHelper(new Buffer(value, 'utf8')); }, decode: function decodeString(data, offset) { var result = decodeDynamicBytesHelper(data, offset); // eslint-disable-line result.value = result.value.toString('utf8'); return result; }, dynamic: true }; function coderArray(coder, lengthInput) { return { encode: function encodeArray(value) { var result = new Buffer(0); // eslint-disable-line var length = lengthInput; // eslint-disable-line if (!Array.isArray(value)) { throw new Error('[ethjs-abi] while encoding array, invalid array data, not type Object (Array)'); } if (length === -1) { length = value.length; result = uint256Coder.encode(length); } if (length !== value.length) { throw new Error('[ethjs-abi] while encoding array, size mismatch array length ' + length + ' does not equal ' + value.length); } value.forEach(function (resultValue) { result = Buffer.concat([result, coder.encode(resultValue)]); }); return result; }, decode: function decodeArray(data, offsetInput) { var length = lengthInput; // eslint-disable-line var offset = offsetInput; // eslint-disable-line // @TODO: // if (data.length < offset + length * 32) { throw new Error('invalid array'); } var consumed = 0; // eslint-disable-line var decodeResult; // eslint-disable-line if (length === -1) { decodeResult = uint256Coder.decode(data, offset); length = decodeResult.value.toNumber(); consumed += decodeResult.consumed; offset += decodeResult.consumed; } var value = []; // eslint-disable-line for (var i = 0; i < length; i++) { // eslint-disable-line var loopResult = coder.decode(data, offset); consumed += loopResult.consumed; offset += loopResult.consumed; value.push(loopResult.value); } return { consumed: consumed, value: value }; }, dynamic: lengthInput === -1 }; } // Break the type up into [staticType][staticArray]*[dynamicArray]? | [dynamicType] and // build the coder up from its parts var paramTypePart = new RegExp(/^((u?int|bytes)([0-9]*)|(address|bool|string)|(\[([0-9]*)\]))/); function getParamCoder(typeInput) { var type = typeInput; // eslint-disable-line var coder = null; // eslint-disable-line var invalidTypeErrorMessage = '[ethjs-abi] while getting param coder (getParamCoder) type value ' + JSON.stringify(type) + ' is either invalid or unsupported by ethjs-abi.'; while (type) { var part = type.match(paramTypePart); // eslint-disable-line if (!part) { throw new Error(invalidTypeErrorMessage); } type = type.substring(part[0].length); var prefix = part[2] || part[4] || part[5]; // eslint-disable-line switch (prefix) { case 'int':case 'uint': if (coder) { throw new Error(invalidTypeErrorMessage); } var intSize = parseInt(part[3] || 256); // eslint-disable-line if (intSize === 0 || intSize > 256 || intSize % 8 !== 0) { throw new Error('[ethjs-abi] while getting param coder for type ' + type + ', invalid ' + prefix + ' width: ' + type); } coder = coderNumber(intSize / 8, prefix === 'int'); break; case 'bool': if (coder) { throw new Error(invalidTypeErrorMessage); } coder = coderBoolean; break; case 'string': if (coder) { throw new Error(invalidTypeErrorMessage); } coder = coderString; break; case 'bytes': if (coder) { throw new Error(invalidTypeErrorMessage); } if (part[3]) { var size = parseInt(part[3]); // eslint-disable-line if (size === 0 || size > 32) { throw new Error('[ethjs-abi] while getting param coder for prefix bytes, invalid type ' + type + ', size ' + size + ' should be 0 or greater than 32'); } coder = coderFixedBytes(size); } else { coder = coderDynamicBytes; } break; case 'address': if (coder) { throw new Error(invalidTypeErrorMessage); } coder = coderAddress; break; case '[]': if (!coder || coder.dynamic) { throw new Error(invalidTypeErrorMessage); } coder = coderArray(coder, -1); break; // "[0-9+]" default: if (!coder || coder.dynamic) { throw new Error(invalidTypeErrorMessage); } var defaultSize = parseInt(part[6]); // eslint-disable-line coder = coderArray(coder, defaultSize); } } if (!coder) { throw new Error(invalidTypeErrorMessage); } return coder; } module.exports = { BN: BN, bnToBuffer: bnToBuffer, isHexString: isHexString, hexOrBuffer: hexOrBuffer, hexlify: hexlify, stripZeros: stripZeros, keccak256: keccak256, getKeys: getKeys, numberToBN: numberToBN, coderNumber: coderNumber, uint256Coder: uint256Coder, coderBoolean: coderBoolean, coderFixedBytes: coderFixedBytes, coderAddress: coderAddress, coderDynamicBytes: coderDynamicBytes, coderString: coderString, coderArray: coderArray, paramTypePart: paramTypePart, getParamCoder: getParamCoder }; }).call(this,require("buffer").Buffer) },{"bn.js":4,"buffer":6,"js-sha3":11,"number-to-bn":12}],9:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } },{}],10:[function(require,module,exports){ /** * Returns a `Boolean` on whether or not the a `String` starts with '0x' * @param {String} str the string input value * @return {Boolean} a boolean if it is or is not hex prefixed * @throws if the str input is not a string */ module.exports = function isHexPrefixed(str) { if (typeof str !== 'string') { throw new Error("[is-hex-prefixed] value must be type 'string', is currently type " + (typeof str) + ", while checking isHexPrefixed."); } return str.slice(0, 2) === '0x'; } },{}],11:[function(require,module,exports){ (function (process,global){ /** * [js-sha3]{@link https://github.com/emn178/js-sha3} * * @version 0.5.5 * @author Chen, Yi-Cyuan [emn178@gmail.com] * @copyright Chen, Yi-Cyuan 2015-2016 * @license MIT */ (function (root) { 'use strict'; var NODE_JS = typeof process == 'object' && process.versions && process.versions.node; if (NODE_JS) { root = global; } var COMMON_JS = !root.JS_SHA3_TEST && typeof module == 'object' && module.exports; var HEX_CHARS = '0123456789abcdef'.split(''); var SHAKE_PADDING = [31, 7936, 2031616, 520093696]; var KECCAK_PADDING = [1, 256, 65536, 16777216]; var PADDING = [6, 1536, 393216, 100663296]; var SHIFT = [0, 8, 16, 24]; var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]; var BITS = [224, 256, 384, 512]; var SHAKE_BITS = [128, 256]; var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array']; var createOutputMethod = function (bits, padding, outputType) { return function (message) { return new Keccak(bits, padding, bits).update(message)[outputType](); } }; var createShakeOutputMethod = function (bits, padding, outputType) { return function (message, outputBits) { return new Keccak(bits, padding, outputBits).update(message)[outputType](); } }; var createMethod = function (bits, padding) { var method = createOutputMethod(bits, padding, 'hex'); method.create = function () { return new Keccak(bits, padding, bits); }; method.update = function (message) { return method.create().update(message); }; for (var i = 0;i < OUTPUT_TYPES.length;++i) { var type = OUTPUT_TYPES[i]; method[type] = createOutputMethod(bits, padding, type); } return method; }; var createShakeMethod = function (bits, padding) { var method = createShakeOutputMethod(bits, padding, 'hex'); method.create = function (outputBits) { return new Keccak(bits, padding, outputBits); }; method.update = function (message, outputBits) { return method.create(outputBits).update(message); }; for (var i = 0;i < OUTPUT_TYPES.length;++i) { var type = OUTPUT_TYPES[i]; method[type] = createShakeOutputMethod(bits, padding, type); } return method; }; var algorithms = [ {name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod}, {name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod}, {name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod} ]; var methods = {}; for (var i = 0;i < algorithms.length;++i) { var algorithm = algorithms[i]; var bits = algorithm.bits; for (var j = 0;j < bits.length;++j) { methods[algorithm.name +'_' + bits[j]] = algorithm.createMethod(bits[j], algorithm.padding); } } function Keccak(bits, padding, outputBits) { this.blocks = []; this.s = []; this.padding = padding; this.outputBits = outputBits; this.reset = true; this.block = 0; this.start = 0; this.blockCount = (1600 - (bits << 1)) >> 5; this.byteCount = this.blockCount << 2; this.outputBlocks = outputBits >> 5; this.extraBytes = (outputBits & 31) >> 3; for (var i = 0;i < 50;++i) { this.s[i] = 0; } }; Keccak.prototype.update = function (message) { var notString = typeof message != 'string'; if (notString && message.constructor == root.ArrayBuffer) { message = new Uint8Array(message); } var length = message.length, blocks = this.blocks, byteCount = this.byteCount, blockCount = this.blockCount, index = 0, s = this.s, i, code; while (index < length) { if (this.reset) { this.reset = false; blocks[0] = this.block; for (i = 1;i < blockCount + 1;++i) { blocks[i] = 0; } } if (notString) { for (i = this.start;index < length && i < byteCount;++index) { blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; } } else { for (i = this.start;index < length && i < byteCount;++index) { code = message.charCodeAt(index); if (code < 0x80) { blocks[i >> 2] |= code << SHIFT[i++ & 3]; } else if (code < 0x800) { blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } else if (code < 0xd800 || code >= 0xe000) { blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } else { code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } } } this.lastByteIndex = i; if (i >= byteCount) { this.start = i - byteCount; this.block = blocks[blockCount]; for (i = 0;i < blockCount;++i) { s[i] ^= blocks[i]; } f(s); this.reset = true; } else { this.start = i; } } return this; }; Keccak.prototype.finalize = function () { var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s; blocks[i >> 2] |= this.padding[i & 3]; if (this.lastByteIndex == this.byteCount) { blocks[0] = blocks[blockCount]; for (i = 1;i < blockCount + 1;++i) { blocks[i] = 0; } } blocks[blockCount - 1] |= 0x80000000; for (i = 0;i < blockCount;++i) { s[i] ^= blocks[i]; } f(s); }; Keccak.prototype.toString = Keccak.prototype.hex = function () { this.finalize(); var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i = 0, j = 0; var hex = '', block; while (j < outputBlocks) { for (i = 0;i < blockCount && j < outputBlocks;++i, ++j) { block = s[i]; hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] + HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] + HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] + HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F]; } if (j % blockCount == 0) { f(s); i = 0; } } if (extraBytes) { block = s[i]; if (extraBytes > 0) { hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F]; } if (extraBytes > 1) { hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F]; } if (extraBytes > 2) { hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F]; } } return hex; }; Keccak.prototype.arrayBuffer = function () { this.finalize(); var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i = 0, j = 0; var bytes = this.outputBits >> 3; var buffer; if (extraBytes) { buffer = new ArrayBuffer((outputBlocks + 1) << 2); } else { buffer = new ArrayBuffer(bytes); } var array = new Uint32Array(buffer); while (j < outputBlocks) { for (i = 0;i < blockCount && j < outputBlocks;++i, ++j) { array[j] = s[i]; } if (j % blockCount == 0) { f(s); } } if (extraBytes) { array[i] = s[i]; buffer = buffer.slice(0, bytes); } return buffer; }; Keccak.prototype.buffer = Keccak.prototype.arrayBuffer; Keccak.prototype.digest = Keccak.prototype.array = function () { this.finalize(); var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i = 0, j = 0; var array = [], offset, block; while (j < outputBlocks) { for (i = 0;i < blockCount && j < outputBlocks;++i, ++j) { offset = j << 2; block = s[i]; array[offset] = block & 0xFF; array[offset + 1] = (block >> 8) & 0xFF; array[offset + 2] = (block >> 16) & 0xFF; array[offset + 3] = (block >> 24) & 0xFF; } if (j % blockCount == 0) { f(s); } } if (extraBytes) { offset = j << 2; block = s[i]; if (extraBytes > 0) { array[offset] = block & 0xFF; } if (extraBytes > 1) { array[offset + 1] = (block >> 8) & 0xFF; } if (extraBytes > 2) { array[offset + 2] = (block >> 16) & 0xFF; } } return array; }; var f = function (s) { var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49; for (n = 0;n < 48;n += 2) { c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]; c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]; c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]; c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]; c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]; c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]; c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]; c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]; c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]; c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]; h = c8 ^ ((c2 << 1) | (c3 >>> 31)); l = c9 ^ ((c3 << 1) | (c2 >>> 31)); s[0] ^= h; s[1] ^= l; s[10] ^= h; s[11] ^= l; s[20] ^= h; s[21] ^= l; s[30] ^= h; s[31] ^= l; s[40] ^= h; s[41] ^= l; h = c0 ^ ((c4 << 1) | (c5 >>> 31)); l = c1 ^ ((c5 << 1) | (c4 >>> 31)); s[2] ^= h; s[3] ^= l; s[12] ^= h; s[13] ^= l; s[22] ^= h; s[23] ^= l; s[32] ^= h; s[33] ^= l; s[42] ^= h; s[43] ^= l; h = c2 ^ ((c6 << 1) | (c7 >>> 31)); l = c3 ^ ((c7 << 1) | (c6 >>> 31)); s[4] ^= h; s[5] ^= l; s[14] ^= h; s[15] ^= l; s[24] ^= h; s[25] ^= l; s[34] ^= h; s[35] ^= l; s[44] ^= h; s[45] ^= l; h = c4 ^ ((c8 << 1) | (c9 >>> 31)); l = c5 ^ ((c9 << 1) | (c8 >>> 31)); s[6] ^= h; s[7] ^= l; s[16] ^= h; s[17] ^= l; s[26] ^= h; s[27] ^= l; s[36] ^= h; s[37] ^= l; s[46] ^= h; s[47] ^= l; h = c6 ^ ((c0 << 1) | (c1 >>> 31)); l = c7 ^ ((c1 << 1) | (c0 >>> 31)); s[8] ^= h; s[9] ^= l; s[18] ^= h; s[19] ^= l; s[28] ^= h; s[29] ^= l; s[38] ^= h; s[39] ^= l; s[48] ^= h; s[49] ^= l; b0 = s[0]; b1 = s[1]; b32 = (s[11] << 4) | (s[10] >>> 28); b33 = (s[10] << 4) | (s[11] >>> 28); b14 = (s[20] << 3) | (s[21] >>> 29); b15 = (s[21] << 3) | (s[20] >>> 29); b46 = (s[31] << 9) | (s[30] >>> 23); b47 = (s[30] << 9) | (s[31] >>> 23); b28 = (s[40] << 18) | (s[41] >>> 14); b29 = (s[41] << 18) | (s[40] >>> 14); b20 = (s[2] << 1) | (s[3] >>> 31); b21 = (s[3] << 1) | (s[2] >>> 31); b2 = (s[13] << 12) | (s[12] >>> 20); b3 = (s[12] << 12) | (s[13] >>> 20); b34 = (s[22] << 10) | (s[23] >>> 22); b35 = (s[23] << 10) | (s[22] >>> 22); b16 = (s[33] << 13) | (s[32] >>> 19); b17 = (s[32] << 13) | (s[33] >>> 19); b48 = (s[42] << 2) | (s[43] >>> 30); b49 = (s[43] << 2) | (s[42] >>> 30); b40 = (s[5] << 30) | (s[4] >>> 2); b41 = (s[4] << 30) | (s[5] >>> 2); b22 = (s[14] << 6) | (s[15] >>> 26); b23 = (s[15] << 6) | (s[14] >>> 26); b4 = (s[25] << 11) | (s[24] >>> 21); b5 = (s[24] << 11) | (s[25] >>> 21); b36 = (s[34] << 15) | (s[35] >>> 17); b37 = (s[35] << 15) | (s[34] >>> 17); b18 = (s[45] << 29) | (s[44] >>> 3); b19 = (s[44] << 29) | (s[45] >>> 3); b10 = (s[6] << 28) | (s[7] >>> 4); b11 = (s[7] << 28) | (s[6] >>> 4); b42 = (s[17] << 23) | (s[16] >>> 9); b43 = (s[16] << 23) | (s[17] >>> 9); b24 = (s[26] << 25) | (s[27] >>> 7); b25 = (s[27] << 25) | (s[26] >>> 7); b6 = (s[36] << 21) | (s[37] >>> 11); b7 = (s[37] << 21) | (s[36] >>> 11); b38 = (s[47] << 24) | (s[46] >>> 8); b39 = (s[46] << 24) | (s[47] >>> 8); b30 = (s[8] << 27) | (s[9] >>> 5); b31 = (s[9] << 27) | (s[8] >>> 5); b12 = (s[18] << 20) | (s[19] >>> 12); b13 = (s[19] << 20) | (s[18] >>> 12); b44 = (s[29] << 7) | (s[28] >>> 25); b45 = (s[28] << 7) | (s[29] >>> 25); b26 = (s[38] << 8) | (s[39] >>> 24); b27 = (s[39] << 8) | (s[38] >>> 24); b8 = (s[48] << 14) | (s[49] >>> 18); b9 = (s[49] << 14) | (s[48] >>> 18); s[0] = b0 ^ (~b2 & b4); s[1] = b1 ^ (~b3 & b5); s[10] = b10 ^ (~b12 & b14); s[11] = b11 ^ (~b13 & b15); s[20] = b20 ^ (~b22 & b24); s[21] = b21 ^ (~b23 & b25); s[30] = b30 ^ (~b32 & b34); s[31] = b31 ^ (~b33 & b35); s[40] = b40 ^ (~b42 & b44); s[41] = b41 ^ (~b43 & b45); s[2] = b2 ^ (~b4 & b6); s[3] = b3 ^ (~b5 & b7); s[12] = b12 ^ (~b14 & b16); s[13] = b13 ^ (~b15 & b17); s[22] = b22 ^ (~b24 & b26); s[23] = b23 ^ (~b25 & b27); s[32] = b32 ^ (~b34 & b36); s[33] = b33 ^ (~b35 & b37); s[42] = b42 ^ (~b44 & b46); s[43] = b43 ^ (~b45 & b47); s[4] = b4 ^ (~b6 & b8); s[5] = b5 ^ (~b7 & b9); s[14] = b14 ^ (~b16 & b18); s[15] = b15 ^ (~b17 & b19); s[24] = b24 ^ (~b26 & b28); s[25] = b25 ^ (~b27 & b29); s[34] = b34 ^ (~b36 & b38); s[35] = b35 ^ (~b37 & b39); s[44] = b44 ^ (~b46 & b48); s[45] = b45 ^ (~b47 & b49); s[6] = b6 ^ (~b8 & b0); s[7] = b7 ^ (~b9 & b1); s[16] = b16 ^ (~b18 & b10); s[17] = b17 ^ (~b19 & b11); s[26] = b26 ^ (~b28 & b20); s[27] = b27 ^ (~b29 & b21); s[36] = b36 ^ (~b38 & b30); s[37] = b37 ^ (~b39 & b31); s[46] = b46 ^ (~b48 & b40); s[47] = b47 ^ (~b49 & b41); s[8] = b8 ^ (~b0 & b2); s[9] = b9 ^ (~b1 & b3); s[18] = b18 ^ (~b10 & b12); s[19] = b19 ^ (~b11 & b13); s[28] = b28 ^ (~b20 & b22); s[29] = b29 ^ (~b21 & b23); s[38] = b38 ^ (~b30 & b32); s[39] = b39 ^ (~b31 & b33); s[48] = b48 ^ (~b40 & b42); s[49] = b49 ^ (~b41 & b43); s[0] ^= RC[n]; s[1] ^= RC[n + 1]; } } if (COMMON_JS) { module.exports = methods; } else if (root) { for (var key in methods) { root[key] = methods[key]; } } }(this)); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":13}],12:[function(require,module,exports){ var BN = require('bn.js'); var stripHexPrefix = require('strip-hex-prefix'); /** * Returns a BN object, converts a number value to a BN * @param {String|Number|Object} `arg` input a string number, hex string number, number, BigNumber or BN object * @return {Object} `output` BN object of the number * @throws if the argument is not an array, object that isn't a bignumber, not a string number or number */ module.exports = function numberToBN(arg) { if (typeof arg === 'string' || typeof arg === 'number') { var multiplier = new BN(1); // eslint-disable-line var formattedString = String(arg).toLowerCase().trim(); var isHexPrefixed = formattedString.substr(0, 2) === '0x' || formattedString.substr(0, 3) === '-0x'; var stringArg = stripHexPrefix(formattedString); // eslint-disable-line if (stringArg.substr(0, 1) === '-') { stringArg = stripHexPrefix(stringArg.slice(1)); multiplier = new BN(-1, 10); } stringArg = stringArg === '' ? '0' : stringArg; if ((!stringArg.match(/^-?[0-9]+$/) && stringArg.match(/^[0-9A-Fa-f]+$/)) || stringArg.match(/^[a-fA-F]+$/) || (isHexPrefixed === true && stringArg.match(/^[0-9A-Fa-f]+$/))) { return new BN(stringArg, 16).mul(multiplier); } if ((stringArg.match(/^-?[0-9]+$/) || stringArg === '') && isHexPrefixed === false) { return new BN(stringArg, 10).mul(multiplier); } } else if (typeof arg === 'object' && arg.toString && (!arg.pop && !arg.push)) { if (arg.toString(10).match(/^-?[0-9]+$/) && (arg.mul || arg.dividedToIntegerBy)) { return new BN(arg.toString(10), 10); } } throw new Error('[number-to-bn] while converting number ' + JSON.stringify(arg) + ' to BN.js instance, error: invalid number value. Value must be an integer, hex string, BN or BigNumber instance. Note, decimals are not supported.'); } },{"bn.js":4,"strip-hex-prefix":14}],13:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],14:[function(require,module,exports){ var isHexPrefixed = require('is-hex-prefixed'); /** * Removes '0x' from a given `String` is present * @param {String} str the string value * @return {String|Optional} a string by pass if necessary */ module.exports = function stripHexPrefix(str) { if (typeof str !== 'string') { return str; } return isHexPrefixed(str) ? str.slice(2) : str; } },{"is-hex-prefixed":10}],15:[function(require,module,exports){ // TODO: remove web3 requirement // Call functions directly on the provider. var Web3 = require("web3"); var Blockchain = { parse: function(uri) { var parsed = {}; if (uri.indexOf("blockchain://") != 0) return parsed; uri = uri.replace("blockchain://", ""); var pieces = uri.split("/block/"); parsed.genesis_hash = "0x" + pieces[0]; parsed.block_hash = "0x" + pieces[1]; return parsed; }, asURI: function(provider, callback) { var web3 = new Web3(provider); web3.eth.getBlock(0, function(err, genesis) { if (err) return callback(err); web3.eth.getBlock("latest", function(err, latest) { if (err) return callback(err); var url = "blockchain://" + genesis.hash.replace("0x", "") + "/block/" + latest.hash.replace("0x", ""); callback(null, url); }); }); }, matches: function(uri, provider, callback) { uri = this.parse(uri); var expected_genesis = uri.genesis_hash; var expected_block = uri.block_hash; var web3 = new Web3(provider); web3.eth.getBlock(0, function(err, block) { if (err) return callback(err); if (block.hash != expected_genesis) return callback(null, false); web3.eth.getBlock(expected_block, function(err, block) { // Treat an error as if the block didn't exist. This is because // some clients respond differently. if (err || block == null) { return callback(null, false); } callback(null, true); }); }); } }; module.exports = Blockchain; },{"web3":5}],16:[function(require,module,exports){ var sha3 = require("crypto-js/sha3"); var schema_version = require("./package.json").version; var TruffleSchema = { // Normalize options passed in to be the exact options required // for truffle-contract. // // options can be three things: // - normal object // - contract object // - solc output // // TODO: Is extra_options still necessary? normalizeOptions: function(options, extra_options) { extra_options = extra_options || {}; var normalized = {}; var expected_keys = [ "contract_name", "abi", "binary", "unlinked_binary", "address", "networks", "links", "events", "network_id", "default_network", "updated_at" ]; // Merge options/contract object first, then extra_options expected_keys.forEach(function(key) { var value; try { // Will throw an error if key == address and address doesn't exist. value = options[key]; if (value != undefined) { normalized[key] = value; } } catch (e) { // Do nothing. } try { // Will throw an error if key == address and address doesn't exist. value = extra_options[key]; if (value != undefined) { normalized[key] = value; } } catch (e) { // Do nothing. } }); // Now look for solc specific items. if (options.interface != null) { normalized.abi = JSON.parse(options.interface); } if (options.bytecode != null) { normalized.unlinked_binary = options.bytecode } // Assume any binary passed is the unlinked binary if (normalized.unlinked_binary == null && normalized.binary) { normalized.unlinked_binary = normalized.binary; } delete normalized.binary; this.copyCustomOptions(options, normalized); return normalized; }, // Generate a proper binary from normalized options, and optionally // merge it with an existing binary. generateBinary: function(options, existing_binary, extra_options) { extra_options = extra_options || {}; existing_binary = existing_binary || {}; if (options.overwrite == true) { existing_binary = {}; } existing_binary.contract_name = options.contract_name || existing_binary.contract_name || "Contract"; existing_binary.default_network = options.default_network || existing_binary.default_network; existing_binary.abi = options.abi || existing_binary.abi; existing_binary.unlinked_binary = options.unlinked_binary || existing_binary.unlinked_binary; // Ensure unlinked binary starts with a 0x if (existing_binary.unlinked_binary && existing_binary.unlinked_binary.indexOf("0x") < 0) { existing_binary.unlinked_binary = "0x" + existing_binary.unlinked_binary; } // Merge existing networks with any passed in networks. existing_binary.networks = existing_binary.networks || {}; options.networks = options.networks || {}; Object.keys(options.networks).forEach(function(network_id) { existing_binary.networks[network_id] = options.networks[network_id]; }); var updated_at = new Date().getTime(); if (options.network_id) { // Ensure an object exists for this network. existing_binary.networks[options.network_id] = existing_binary.networks[options.network_id] || {}; var network = existing_binary.networks[options.network_id]; // Override specific keys network.address = options.address || network.address; network.links = options.links; // merge events with any that previously existed network.events = network.events || {}; options.events = options.events || {}; Object.keys(options.events).forEach(function(event_id) { options.events[event_id] = options.events[event_id]; }); // Now overwrite any events with the most recent data from the ABI. existing_binary.abi.forEach(function(item) { if (item.type != "event") return; var signature = item.name + "(" + item.inputs.map(function(param) {return param.type;}).join(",") + ")"; network.events["0x" + sha3(signature, {outputLength: 256})] = item; }); if (extra_options.dirty !== false) { network.updated_at = updated_at; } } else { if (options.address) { throw new Error("Cannot set address without network id"); } } // Ensure all networks have a `links` object. Object.keys(existing_binary.networks).forEach(function(network_id) { var network = existing_binary.networks[network_id]; network.links = network.links || {}; }); existing_binary.schema_version = schema_version; if (extra_options.dirty !== false) { existing_binary.updated_at = updated_at; } else { existing_binary.updated_at = options.updated_at || existing_binary.updated_at || updated_at; } this.copyCustomOptions(options, existing_binary); return existing_binary; }, copyCustomOptions: function(from, to) { // Now let all x- options through. Object.keys(from).forEach(function(key) { if (key.indexOf("x-") != 0) return; try { value = from[key]; if (value != undefined) { to[key] = value; } } catch (e) { // Do nothing. } }); } }; module.exports = TruffleSchema; },{"./package.json":20,"crypto-js/sha3":18}],17:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(); } else if (typeof define === "function" && define.amd) { // AMD define([], factory); } else { // Global (browser) root.CryptoJS = factory(); } }(this, function () { /** * CryptoJS core components. */ var CryptoJS = CryptoJS || (function (Math, undefined) { /* * Local polyfil of Object.create */ var create = Object.create || (function () { function F() {}; return function (obj) { var subtype; F.prototype = obj; subtype = new F(); F.prototype = null; return subtype; }; }()) /** * CryptoJS namespace. */ var C = {}; /** * Library namespace. */ var C_lib = C.lib = {}; /** * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function (overrides) { // Spawn var subtype = create(this); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function () { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function () { return this.init.prototype.extend(this); } }; }()); /** * An array of 32-bit words. * * @property {Array} words The array of 32-bit words. * @property {number} sigBytes The number of significant bytes in this word array. */ var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function (encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function (wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else { // Copy one word at a time for (var i = 0; i < thatSigBytes; i += 4) { thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; } } this.sigBytes += thatSigBytes; // Chainable return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function () { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function (nBytes) { var words = []; var r = (function (m_w) { var m_w = m_w; var m_z = 0x3ade68b1; var mask = 0xffffffff; return function () { m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; var result = ((m_z << 0x10) + m_w) & mask; result /= 0x100000000; result += 0.5; return result * (Math.random() > .5 ? 1 : -1); } }); for (var i = 0, rcache; i < nBytes; i += 4) { var _r = r((rcache || Math.random()) * 0x100000000); rcache = _r() * 0x3ade67b7; words.push((_r() * 0x100000000) | 0); } return new WordArray.init(words, nBytes); } }); /** * Encoder namespace. */ var C_enc = C.enc = {}; /** * Hex encoding strategy. */ var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function (hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); } }; /** * Latin1 encoding strategy. */ var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function (latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); } }; /** * UTF-8 encoding strategy. */ var Utf8 = C_enc.Utf8 = { /** * Converts a word array to a UTF-8 string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-8 string. * * @static * * @example * * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); */ stringify: function (wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error('Malformed UTF-8 data'); } }, /** * Converts a UTF-8 string to a word array. * * @param {string} utf8Str The UTF-8 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ parse: function (utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); } }; /** * Abstract buffered block algorithm template. * * The property blockSize must be implemented in a concrete subtype. * * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 */ var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** * Resets this block algorithm's data buffer to its initial state. * * @example * * bufferedBlockAlgorithm.reset(); */ reset: function () { // Initial values this._data = new WordArray.init(); this._nDataBytes = 0; }, /** * Adds new data to this block algorithm's buffer. * * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. * * @example * * bufferedBlockAlgorithm._append('data'); * bufferedBlockAlgorithm._append(wordArray); */ _append: function (data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; }, /** * Processes available data blocks. * * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. * * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. * * @return {WordArray} The processed data. * * @example * * var processedData = bufferedBlockAlgorithm._process(); * var processedData = bufferedBlockAlgorithm._process(!!'flush'); */ _process: function (doFlush) { // Shortcuts var data = this._data; var dataWords = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; // Count blocks ready var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { // Round up to include partial blocks nBlocksReady = Math.ceil(nBlocksReady); } else { // Round down to include only full blocks, // less the number of blocks that must remain in the buffer nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); } // Count words ready var nWordsReady = nBlocksReady * blockSize; // Count bytes ready var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { // Perform concrete-algorithm logic this._doProcessBlock(dataWords, offset); } // Remove processed words var processedWords = dataWords.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } // Return processed words return new WordArray.init(processedWords, nBytesReady); }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = bufferedBlockAlgorithm.clone(); */ clone: function () { var clone = Base.clone.call(this); clone._data = this._data.clone(); return clone; }, _minBufferSize: 0 }); /** * Abstract hasher template. * * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) */ var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ /** * Configuration options. */ cfg: Base.extend(), /** * Initializes a newly created hasher. * * @param {Object} cfg (Optional) The configuration options to use for this hash computation. * * @example * * var hasher = CryptoJS.algo.SHA256.create(); */ init: function (cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Set initial values this.reset(); }, /** * Resets this hasher to its initial state. * * @example * * hasher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic this._doReset(); }, /** * Updates this hasher with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {Hasher} This hasher. * * @example * * hasher.update('message'); * hasher.update(wordArray); */ update: function (messageUpdate) { // Append this._append(messageUpdate); // Update the hash this._process(); // Chainable return this; }, /** * Finalizes the hash computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The hash. * * @example * * var hash = hasher.finalize(); * var hash = hasher.finalize('message'); * var hash = hasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Final message update if (messageUpdate) { this._append(messageUpdate); } // Perform concrete-hasher logic var hash = this._doFinalize(); return hash; }, blockSize: 512/32, /** * Creates a shortcut function to a hasher's object interface. * * @param {Hasher} hasher The hasher to create a helper for. * * @return {Function} The shortcut function. * * @static * * @example * * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ _createHelper: function (hasher) { return function (message, cfg) { return new hasher.init(cfg).finalize(message); }; }, /** * Creates a shortcut function to the HMAC's object interface. * * @param {Hasher} hasher The hasher to use in this HMAC helper. * * @return {Function} The shortcut function. * * @static * * @example * * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ _createHmacHelper: function (hasher) { return function (message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; } }); /** * Algorithm namespace. */ var C_algo = C.algo = {}; return C; }(Math)); return CryptoJS; })); },{}],18:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var C_algo = C.algo; // Constants tables var RHO_OFFSETS = []; var PI_INDEXES = []; var ROUND_CONSTANTS = []; // Compute Constants (function () { // Compute rho offset constants var x = 1, y = 0; for (var t = 0; t < 24; t++) { RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; var newX = y % 5; var newY = (2 * x + 3 * y) % 5; x = newX; y = newY; } // Compute pi index constants for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; } } // Compute round constants var LFSR = 0x01; for (var i = 0; i < 24; i++) { var roundConstantMsw = 0; var roundConstantLsw = 0; for (var j = 0; j < 7; j++) { if (LFSR & 0x01) { var bitPosition = (1 << j) - 1; if (bitPosition < 32) { roundConstantLsw ^= 1 << bitPosition; } else /* if (bitPosition >= 32) */ { roundConstantMsw ^= 1 << (bitPosition - 32); } } // Compute next LFSR if (LFSR & 0x80) { // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 LFSR = (LFSR << 1) ^ 0x71; } else { LFSR <<= 1; } } ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); } }()); // Reusable objects for temporary values var T = []; (function () { for (var i = 0; i < 25; i++) { T[i] = X64Word.create(); } }()); /** * SHA-3 hash algorithm. */ var SHA3 = C_algo.SHA3 = Hasher.extend({ /** * Configuration options. * * @property {number} outputLength * The desired number of bits in the output hash. * Only values permitted are: 224, 256, 384, 512. * Default: 512 */ cfg: Hasher.cfg.extend({ outputLength: 512 }), _doReset: function () { var state = this._state = [] for (var i = 0; i < 25; i++) { state[i] = new X64Word.init(); } this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; }, _doProcessBlock: function (M, offset) { // Shortcuts var state = this._state; var nBlockSizeLanes = this.blockSize / 2; // Absorb for (var i = 0; i < nBlockSizeLanes; i++) { // Shortcuts var M2i = M[offset + 2 * i]; var M2i1 = M[offset + 2 * i + 1]; // Swap endian M2i = ( (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) ); M2i1 = ( (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) ); // Absorb message into state var lane = state[i]; lane.high ^= M2i1; lane.low ^= M2i; } // Rounds for (var round = 0; round < 24; round++) { // Theta for (var x = 0; x < 5; x++) { // Mix column lanes var tMsw = 0, tLsw = 0; for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; tMsw ^= lane.high; tLsw ^= lane.low; } // Temporary values var Tx = T[x]; Tx.high = tMsw; Tx.low = tLsw; } for (var x = 0; x < 5; x++) { // Shortcuts var Tx4 = T[(x + 4) % 5]; var Tx1 = T[(x + 1) % 5]; var Tx1Msw = Tx1.high; var Tx1Lsw = Tx1.low; // Mix surrounding columns var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; lane.high ^= tMsw; lane.low ^= tLsw; } } // Rho Pi for (var laneIndex = 1; laneIndex < 25; laneIndex++) { // Shortcuts var lane = state[laneIndex]; var laneMsw = lane.high; var laneLsw = lane.low; var rhoOffset = RHO_OFFSETS[laneIndex]; // Rotate lanes if (rhoOffset < 32) { var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); } else /* if (rhoOffset >= 32) */ { var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); } // Transpose lanes var TPiLane = T[PI_INDEXES[laneIndex]]; TPiLane.high = tMsw; TPiLane.low = tLsw; } // Rho pi at x = y = 0 var T0 = T[0]; var state0 = state[0]; T0.high = state0.high; T0.low = state0.low; // Chi for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { // Shortcuts var laneIndex = x + 5 * y; var lane = state[laneIndex]; var TLane = T[laneIndex]; var Tx1Lane = T[((x + 1) % 5) + 5 * y]; var Tx2Lane = T[((x + 2) % 5) + 5 * y]; // Mix rows lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); } } // Iota var lane = state[0]; var roundConstant = ROUND_CONSTANTS[round]; lane.high ^= roundConstant.high; lane.low ^= roundConstant.low;; } }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; var blockSizeBits = this.blockSize * 32; // Add padding dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Shortcuts var state = this._state; var outputLengthBytes = this.cfg.outputLength / 8; var outputLengthLanes = outputLengthBytes / 8; // Squeeze var hashWords = []; for (var i = 0; i < outputLengthLanes; i++) { // Shortcuts var lane = state[i]; var laneMsw = lane.high; var laneLsw = lane.low; // Swap endian laneMsw = ( (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) ); laneLsw = ( (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) ); // Squeeze state to retrieve hash hashWords.push(laneLsw); hashWords.push(laneMsw); } // Return final computed hash return new WordArray.init(hashWords, outputLengthBytes); }, clone: function () { var clone = Hasher.clone.call(this); var state = clone._state = this._state.slice(0); for (var i = 0; i < 25; i++) { state[i] = state[i].clone(); } return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA3('message'); * var hash = CryptoJS.SHA3(wordArray); */ C.SHA3 = Hasher._createHelper(SHA3); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA3(message, key); */ C.HmacSHA3 = Hasher._createHmacHelper(SHA3); }(Math)); return CryptoJS.SHA3; })); },{"./core":17,"./x64-core":19}],19:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var X32WordArray = C_lib.WordArray; /** * x64 namespace. */ var C_x64 = C.x64 = {}; /** * A 64-bit word. */ var X64Word = C_x64.Word = Base.extend({ /** * Initializes a newly created 64-bit word. * * @param {number} high The high 32 bits. * @param {number} low The low 32 bits. * * @example * * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); */ init: function (high, low) { this.high = high; this.low = low; } /** * Bitwise NOTs this word. * * @return {X64Word} A new x64-Word object after negating. * * @example * * var negated = x64Word.not(); */ // not: function () { // var high = ~this.high; // var low = ~this.low; // return X64Word.create(high, low); // }, /** * Bitwise ANDs this word with the passed word. * * @param {X64Word} word The x64-Word to AND with this word. * * @return {X64Word} A new x64-Word object after ANDing. * * @example * * var anded = x64Word.and(anotherX64Word); */ // and: function (word) { // var high = this.high & word.high; // var low = this.low & word.low; // return X64Word.create(high, low); // }, /** * Bitwise ORs this word with the passed word. * * @param {X64Word} word The x64-Word to OR with this word. * * @return {X64Word} A new x64-Word object after ORing. * * @example * * var ored = x64Word.or(anotherX64Word); */ // or: function (word) { // var high = this.high | word.high; // var low = this.low | word.low; // return X64Word.create(high, low); // }, /** * Bitwise XORs this word with the passed word. * * @param {X64Word} word The x64-Word to XOR with this word. * * @return {X64Word} A new x64-Word object after XORing. * * @example * * var xored = x64Word.xor(anotherX64Word); */ // xor: function (word) { // var high = this.high ^ word.high; // var low = this.low ^ word.low; // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the left. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftL(25); */ // shiftL: function (n) { // if (n < 32) { // var high = (this.high << n) | (this.low >>> (32 - n)); // var low = this.low << n; // } else { // var high = this.low << (n - 32); // var low = 0; // } // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the right. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftR(7); */ // shiftR: function (n) { // if (n < 32) { // var low = (this.low >>> n) | (this.high << (32 - n)); // var high = this.high >>> n; // } else { // var low = this.high >>> (n - 32); // var high = 0; // } // return X64Word.create(high, low); // }, /** * Rotates this word n bits to the left. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotL(25); */ // rotL: function (n) { // return this.shiftL(n).or(this.shiftR(64 - n)); // }, /** * Rotates this word n bits to the right. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotR(7); */ // rotR: function (n) { // return this.shiftR(n).or(this.shiftL(64 - n)); // }, /** * Adds this word with the passed word. * * @param {X64Word} word The x64-Word to add with this word. * * @return {X64Word} A new x64-Word object after adding. * * @example * * var added = x64Word.add(anotherX64Word); */ // add: function (word) { // var low = (this.low + word.low) | 0; // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; // var high = (this.high + word.high + carry) | 0; // return X64Word.create(high, low); // } }); /** * An array of 64-bit words. * * @property {Array} words The array of CryptoJS.x64.Word objects. * @property {number} sigBytes The number of significant bytes in this word array. */ var X64WordArray = C_x64.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.x64.WordArray.create(); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ]); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ], 10); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 8; } }, /** * Converts this 64-bit word array to a 32-bit word array. * * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. * * @example * * var x32WordArray = x64WordArray.toX32(); */ toX32: function () { // Shortcuts var x64Words = this.words; var x64WordsLength = x64Words.length; // Convert var x32Words = []; for (var i = 0; i < x64WordsLength; i++) { var x64Word = x64Words[i]; x32Words.push(x64Word.high); x32Words.push(x64Word.low); } return X32WordArray.create(x32Words, this.sigBytes); }, /** * Creates a copy of this word array. * * @return {X64WordArray} The clone. * * @example * * var clone = x64WordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); // Clone "words" array var words = clone.words = this.words.slice(0); // Clone each X64Word object var wordsLength = words.length; for (var i = 0; i < wordsLength; i++) { words[i] = words[i].clone(); } return clone; } }); }()); return CryptoJS; })); },{"./core":17}],20:[function(require,module,exports){ module.exports={ "_args": [ [ { "raw": "truffle-contract-schema@0.0.5", "scope": null, "escapedName": "truffle-contract-schema", "name": "truffle-contract-schema", "rawSpec": "0.0.5", "spec": "0.0.5", "type": "version" }, "/Users/tim/Documents/workspace/Consensys/truffle-contract" ] ], "_from": "truffle-contract-schema@0.0.5", "_id": "truffle-contract-schema@0.0.5", "_inCache": true, "_location": "/truffle-contract-schema", "_nodeVersion": "6.9.1", "_npmOperationalInternal": { "host": "packages-12-west.internal.npmjs.com", "tmp": "tmp/truffle-contract-schema-0.0.5.tgz_1485557985137_0.46875762194395065" }, "_npmUser": { "name": "tcoulter", "email": "tim@timothyjcoulter.com" }, "_npmVersion": "3.10.8", "_phantomChildren": {}, "_requested": { "raw": "truffle-contract-schema@0.0.5", "scope": null, "escapedName": "truffle-contract-schema", "name": "truffle-contract-schema", "rawSpec": "0.0.5", "spec": "0.0.5", "type": "version" }, "_requiredBy": [ "/" ], "_resolved": "https://registry.npmjs.org/truffle-contract-schema/-/truffle-contract-schema-0.0.5.tgz", "_shasum": "5e9d20bd0bf2a27fe94310748249d484eee49961", "_shrinkwrap": null, "_spec": "truffle-contract-schema@0.0.5", "_where": "/Users/tim/Documents/workspace/Consensys/truffle-contract", "author": { "name": "Tim Coulter", "email": "tim.coulter@consensys.net" }, "bugs": { "url": "https://github.com/trufflesuite/truffle-schema/issues" }, "dependencies": { "crypto-js": "^3.1.9-1" }, "description": "JSON schema for contract artifacts", "devDependencies": { "mocha": "^3.2.0" }, "directories": {}, "dist": { "shasum": "5e9d20bd0bf2a27fe94310748249d484eee49961", "tarball": "https://registry.npmjs.org/truffle-contract-schema/-/truffle-contract-schema-0.0.5.tgz" }, "gitHead": "cfa4313bd4bb95bf5b94f85185203ead418f9ee6", "homepage": "https://github.com/trufflesuite/truffle-schema#readme", "keywords": [ "ethereum", "json", "schema", "contract", "artifacts" ], "license": "MIT", "main": "index.js", "maintainers": [ { "name": "tcoulter", "email": "tim@timothyjcoulter.com" } ], "name": "truffle-contract-schema", "optionalDependencies": {}, "readme": "ERROR: No README data found!", "repository": { "type": "git", "url": "git+https://github.com/trufflesuite/truffle-schema.git" }, "scripts": { "test": "mocha" }, "version": "0.0.5" } },{}]},{},[2]); ================================================ FILE: truffle/ozws/test/.placeholder ================================================ This is a placeholder file to ensure the parent directory in the git repository. Feel free to remove. ================================================ FILE: truffle/ozws/truffle.js ================================================ module.exports = { networks: { development: { host: "localhost", port: 8545, network_id: "*" // Match any network id } } }; ================================================ FILE: truffle/prueba/contracts/Migrations.sol ================================================ pragma solidity >=0.4.21 <0.6.0; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } ================================================ FILE: truffle/prueba/migrations/1_initial_migration.js ================================================ const Migrations = artifacts.require("Migrations"); module.exports = function(deployer) { deployer.deploy(Migrations); }; ================================================ FILE: truffle/prueba/truffle-config.js ================================================ /** * Use this file to configure your truffle project. It's seeded with some * common settings for different networks and features like migrations, * compilation and testing. Uncomment the ones you need or modify * them to suit your project as necessary. * * More information about configuration can be found at: * * truffleframework.com/docs/advanced/configuration * * To deploy via Infura you'll need a wallet provider (like truffle-hdwallet-provider) * to sign your transactions before they're sent to a remote public node. Infura API * keys are available for free at: infura.io/register * * You'll also need a mnemonic - the twelve word phrase the wallet uses to generate * public/private key pairs. If you're publishing your code to GitHub make sure you load this * phrase from a file you've .gitignored so it doesn't accidentally become public. * */ // const HDWalletProvider = require('truffle-hdwallet-provider'); // const infuraKey = "fj4jll3k....."; // // const fs = require('fs'); // const mnemonic = fs.readFileSync(".secret").toString().trim(); module.exports = { /** * Networks define how you connect to your ethereum client and let you set the * defaults web3 uses to send transactions. If you don't specify one truffle * will spin up a development blockchain for you on port 9545 when you * run `develop` or `test`. You can ask a truffle command to use a specific * network from the command line, e.g * * $ truffle test --network */ networks: { // Useful for testing. The `development` name is special - truffle uses it by default // if it's defined here and no other network is specified at the command line. // You should run a client (like ganache-cli, geth or parity) in a separate terminal // tab if you use this network and you must also set the `host`, `port` and `network_id` // options below to some value. // // development: { // host: "127.0.0.1", // Localhost (default: none) // port: 8545, // Standard Ethereum port (default: none) // network_id: "*", // Any network (default: none) // }, // Another network with more advanced options... // advanced: { // port: 8777, // Custom port // network_id: 1342, // Custom network // gas: 8500000, // Gas sent with each transaction (default: ~6700000) // gasPrice: 20000000000, // 20 gwei (in wei) (default: 100 gwei) // from:
, // Account to send txs from (default: accounts[0]) // websockets: true // Enable EventEmitter interface for web3 (default: false) // }, // Useful for deploying to a public network. // NB: It's important to wrap the provider as a function. // ropsten: { // provider: () => new HDWalletProvider(mnemonic, `https://ropsten.infura.io/${infuraKey}`), // network_id: 3, // Ropsten's id // gas: 5500000, // Ropsten has a lower block limit than mainnet // confirmations: 2, // # of confs to wait between deployments. (default: 0) // timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50) // skipDryRun: true // Skip dry run before migrations? (default: false for public nets ) // }, // Useful for private networks // private: { // provider: () => new HDWalletProvider(mnemonic, `https://network.io`), // network_id: 2111, // This network is yours, in the cloud. // production: true // Treats this network as if it was a public net. (default: false) // } }, // Set default mocha options here, use special reporters etc. mocha: { // timeout: 100000 }, // Configure your compilers compilers: { solc: { // version: "0.5.1", // Fetch exact version from solc-bin (default: truffle's version) // docker: true, // Use "0.5.1" you've installed locally with docker (default: false) // settings: { // See the solidity docs for advice about optimization and evmVersion // optimizer: { // enabled: false, // runs: 200 // }, // evmVersion: "byzantium" // } } } } ================================================ FILE: truffle/sf1/contracts/Ballot.sol ================================================ pragma solidity ^0.4.24; contract Ballot { mapping (bytes32 => address[]) public votes; address[] voters; constructor(address[] _voters) public { voters = _voters; } modifier onlyVoters() { for (uint k = 0; k < voters.length; k++) if (msg.sender == voters[k]) { _; return; } revert(); } function vote(bytes32 id) public onlyVoters { for (uint k = 0; k < votes[id].length; k++) if (votes[id][k] == msg.sender) revert(); votes[id].push(msg.sender); } function noVotes(bytes32 id) public view returns (uint) { return votes[id].length; } function getVoters(bytes32 id) public view returns (address[]) { return votes[id]; } } ================================================ FILE: truffle/sf1/contracts/Counter.sol ================================================ pragma solidity ^0.4.24; contract Counter { uint public counter; constructor() public { counter = 1; } function increment() public { counter++; } function add(uint value) public { counter += value; } } ================================================ FILE: truffle/sf1/contracts/Migrations.sol ================================================ pragma solidity ^0.4.23; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } ================================================ FILE: truffle/sf1/contracts/Token.sol ================================================ pragma solidity ^0.4.24; contract Token { mapping(address => uint) balances; constructor() public { balances[msg.sender] = 1000000; } function balanceOf(address account) view public returns (uint) { return balances[account]; } function transfer(address receiver, uint amount) public { require(balances[msg.sender] >= amount); /* if (balances[msg.sender] < amount) return false; */ balances[msg.sender] -= amount; balances[receiver] += amount; } } ================================================ FILE: truffle/sf1/migrations/1_initial_migration.js ================================================ var Migrations = artifacts.require("./Migrations.sol"); module.exports = function(deployer) { deployer.deploy(Migrations); }; ================================================ FILE: truffle/sf1/migrations/2_deploy_contracts.js ================================================ var Counter = artifacts.require("./Counter.sol"); module.exports = function(deployer) { deployer.deploy(Counter); }; ================================================ FILE: truffle/sf1/test/Ballot_test.js ================================================ const Ballot = artifacts.require('./Ballot.sol'); async function expectThrow (promise) { try { await promise; } catch (error) { return; } assert.fail('Expected throw not received'); } contract('Ballot', function (accounts) { beforeEach(async function () { this.ballot = await Ballot.new([ accounts[0], accounts[1] ]); }); it('no votes in unknown proposal', async function () { // bytes32 identificar propuesta por hash const novotes = await this.ballot.noVotes(1); assert.equal(novotes, 0); }); it('vote proposal', async function () { await this.ballot.vote(1); const novotes = await this.ballot.noVotes(1); assert.equal(novotes, 1); }); it('vote proposal and get voter', async function () { await this.ballot.vote(1); const voters = await this.ballot.getVoters(1); assert.ok(voters); assert.equal(voters.length, 1); assert.equal(voters[0], accounts[0]); }); it('vote proposal twice and get voters', async function () { await this.ballot.vote(1); await this.ballot.vote(1, { from: accounts[1] }); const voters = await this.ballot.getVoters(1); assert.ok(voters); assert.equal(voters.length, 2); assert.equal(voters[0], accounts[0]); assert.equal(voters[1], accounts[1]); }); it('avoid double vote', async function () { await this.ballot.vote(1); expectThrow(this.ballot.vote(1)); const voters = await this.ballot.getVoters(1); assert.ok(voters); assert.equal(voters.length, 1); assert.equal(voters[0], accounts[0]); }); it('only voter can vote', async function () { expectThrow(this.ballot.vote(1, { from: accounts[2] })); const novotes = await this.ballot.noVotes(1); assert.equal(novotes, 0); }); }); ================================================ FILE: truffle/sf1/test/Counter_tests.js ================================================ const Counter = artifacts.require('./Counter.sol'); contract('Counter', function (accounts) { // console.dir(accounts); describe('first tests', function () { beforeEach(async function () { this.counter = await Counter.new(); }); it('create contract', async function () { assert.equal(await this.counter.counter(), 1); }); it('increment', async function () { await this.counter.increment(); assert.equal(await this.counter.counter(), 2); }); it('increment and add', async function () { await this.counter.increment(); await this.counter.add(40); assert.equal(await this.counter.counter(), 42); }); }); }); ================================================ FILE: truffle/sf1/test/Token_test.js ================================================ const Token = artifacts.require('./Token.sol'); contract('Token', function (accounts) { it('create token', async function () { const token = await Token.new(); const balance = await token.balanceOf(accounts[0]); assert.equal(balance, 1000000); }); it('create token with another account', async function () { const token = await Token.new({ from: accounts[1] }); const balance = await token.balanceOf(accounts[1]); assert.equal(balance, 1000000); const balance0 = await token.balanceOf(accounts[0]); assert.equal(balance0, 0); }); it('transfer', async function () { const token = await Token.new(); await token.transfer(accounts[1], 1000, { from: accounts[0] }); const balance = await token.balanceOf(accounts[1]); assert.equal(balance, 1000); const balance0 = await token.balanceOf(accounts[0]); assert.equal(balance0, 1000000 - 1000); }); }); ================================================ FILE: truffle/sf1/truffle-config.js ================================================ /* * NB: since truffle-hdwallet-provider 0.0.5 you must wrap HDWallet providers in a * function when declaring them. Failure to do so will cause commands to hang. ex: * ``` * mainnet: { * provider: function() { * return new HDWalletProvider(mnemonic, 'https://mainnet.infura.io/') * }, * network_id: '1', * gas: 4500000, * gasPrice: 10000000000, * }, */ module.exports = { // See // to customize your Truffle configuration! networks: { development: { host: "127.0.0.1", port: 8545, network_id: "*" // Match any network id } } }; ================================================ FILE: truffle/sj/contracts/Ballot.sol ================================================ pragma solidity ^0.4.24; contract Ballot { mapping (address => bool) canVote; mapping (uint => address[]) votes; modifier onlyVoter() { if (canVote[msg.sender]) _; } constructor(address[] _voters) public { for (uint k = 0; k < _voters.length; k++) canVote[_voters[k]] = true; } function vote(uint nproposal) public onlyVoter returns(bool) { address[] storage pvotes = votes[nproposal]; for (uint k = 0; k < pvotes.length; k++) if (pvotes[k] == msg.sender) return false; pvotes.push(msg.sender); return true; } function noVotes(uint nproposal) public view returns (uint) { return votes[nproposal].length; } function getVotes(uint nproposal) public view returns (address[]) { return votes[nproposal]; } } ================================================ FILE: truffle/sj/contracts/Counter.sol ================================================ pragma solidity ^0.4.24; contract Counter { uint public counter; constructor(uint value) public { counter = value; } function increment() public { counter++; } function add(uint v) public { counter += v; } } ================================================ FILE: truffle/sj/contracts/Empty.sol ================================================ pragma solidity ^0.4.24; contract Empty { } ================================================ FILE: truffle/sj/contracts/Migrations.sol ================================================ pragma solidity ^0.4.23; contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } ================================================ FILE: truffle/sj/migrations/1_initial_migration.js ================================================ var Migrations = artifacts.require("./Migrations.sol"); module.exports = function(deployer) { deployer.deploy(Migrations); }; ================================================ FILE: truffle/sj/migrations/2_deploy_contracts.js ================================================ var Empty = artifacts.require("./Empty.sol"); var Counter = artifacts.require("./Counter.sol"); module.exports = function(deployer) { deployer.deploy(Empty); deployer.deploy(Counter, 1); }; ================================================ FILE: truffle/sj/test/Ballot_tests.js ================================================ const Ballot = artifacts.require('./Ballot'); contract('Ballot', function (accounts) { const voters = [ accounts[0], accounts[1], accounts[2] ]; beforeEach(async function() { this.ballot = await Ballot.new(voters); }); it('no votes for proposal', async function () { const nvotes = await this.ballot.noVotes(1); assert.equal(nvotes, 0); }); it('vote proposal', async function () { await this.ballot.vote(1); const nvotes = await this.ballot.noVotes(1); assert.equal(nvotes, 1); }); it('only voter could vote proposal', async function () { await this.ballot.vote(1, { from: accounts[3] }); const nvotes = await this.ballot.noVotes(1); assert.equal(nvotes, 0); }); it('repeated vote proposal', async function () { await this.ballot.vote(1, { from: accounts[0] }); await this.ballot.vote(1, { from: accounts[0] }); const nvotes = await this.ballot.noVotes(1); assert.equal(nvotes, 1); const votes = await this.ballot.getVotes(1); assert.equal(votes.length, 1); assert.equal(votes[0], accounts[0]); }); it('two votes for proposal', async function () { await this.ballot.vote(1, { from: accounts[0] }); await this.ballot.vote(1, { from: accounts[1] }); const nvotes = await this.ballot.noVotes(1); assert.equal(nvotes, 2); const votes = await this.ballot.getVotes(1); assert.equal(votes.length, 2); assert.equal(votes[0], accounts[0]); assert.equal(votes[1], accounts[1]); }); }); ================================================ FILE: truffle/sj/test/Counter_tests.js ================================================ const Counter = artifacts.require('./Counter'); contract('Counter', function (accounts) { beforeEach(async function() { this.counter = await Counter.new(1); }); it('my first test', async function () { const value = await this.counter.counter(); assert.equal(value.toNumber(), 1); }); it('one increment', async function () { await this.counter.increment(); const value = await this.counter.counter(); assert.equal(value.toNumber(), 2); }); it('two increments', async function () { await this.counter.increment(); await this.counter.increment(); const value = await this.counter.counter(); assert.equal(value.toNumber(), 3); }); it('two increments and add', async function () { await this.counter.increment(); await this.counter.increment(); await this.counter.add(39); const value = await this.counter.counter(); assert.equal(value.toNumber(), 42); }); }); ================================================ FILE: truffle/sj/truffle-config.js ================================================ /* * NB: since truffle-hdwallet-provider 0.0.5 you must wrap HDWallet providers in a * function when declaring them. Failure to do so will cause commands to hang. ex: * ``` * mainnet: { * provider: function() { * return new HDWalletProvider(mnemonic, 'https://mainnet.infura.io/') * }, * network_id: '1', * gas: 4500000, * gasPrice: 10000000000, * }, */ module.exports = { // See // to customize your Truffle configuration! networks: { development: { host: "127.0.0.1", port: 8545, network_id: "*" // Match any network id } } }; ================================================ FILE: truffle/tokentutorial/bs-config.json ================================================ { "server": { "baseDir": ["./src", "./build/contracts"] } } ================================================ FILE: truffle/tokentutorial/contracts/Migrations.sol ================================================ pragma solidity ^0.4.24; contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } ================================================ FILE: truffle/tokentutorial/migrations/1_initial_migration.js ================================================ var Migrations = artifacts.require("./Migrations.sol"); module.exports = function(deployer) { deployer.deploy(Migrations); }; ================================================ FILE: truffle/tokentutorial/package.json ================================================ { "name": "tutorialtoken", "version": "1.0.0", "description": "", "main": "truffle.js", "directories": { "test": "test" }, "scripts": { "dev": "lite-server", "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "devDependencies": { "lite-server": "^2.3.0" } } ================================================ FILE: truffle/tokentutorial/src/index.html ================================================ TutorialToken - Wallet

TutorialToken



My Wallet

Balance

Balance: TT

Transfer

================================================ FILE: truffle/tokentutorial/src/js/app.js ================================================ App = { web3Provider: null, contracts: {}, init: function() { return App.initWeb3(); }, initWeb3: function() { // Initialize web3 and set the provider to the testRPC. if (typeof web3 !== 'undefined') { App.web3Provider = web3.currentProvider; web3 = new Web3(web3.currentProvider); } else { // set the provider you want from Web3.providers App.web3Provider = new Web3.providers.HttpProvider('http://127.0.0.1:9545'); web3 = new Web3(App.web3Provider); } return App.initContract(); }, initContract: function() { $.getJSON('TutorialToken.json', function(data) { // Get the necessary contract artifact file and instantiate it with truffle-contract. var TutorialTokenArtifact = data; App.contracts.TutorialToken = TruffleContract(TutorialTokenArtifact); // Set the provider for our contract. App.contracts.TutorialToken.setProvider(App.web3Provider); // Use our contract to retieve and mark the adopted pets. return App.getBalances(); }); return App.bindEvents(); }, bindEvents: function() { $(document).on('click', '#transferButton', App.handleTransfer); }, handleTransfer: function(event) { event.preventDefault(); var amount = parseInt($('#TTTransferAmount').val()); var toAddress = $('#TTTransferAddress').val(); console.log('Transfer ' + amount + ' TT to ' + toAddress); var tutorialTokenInstance; web3.eth.getAccounts(function(error, accounts) { if (error) { console.log(error); } var account = accounts[0]; App.contracts.TutorialToken.deployed().then(function(instance) { tutorialTokenInstance = instance; return tutorialTokenInstance.transfer(toAddress, amount, {from: account, gas: 100000}); }).then(function(result) { alert('Transfer Successful!'); return App.getBalances(); }).catch(function(err) { console.log(err.message); }); }); }, getBalances: function() { console.log('Getting balances...'); var tutorialTokenInstance; web3.eth.getAccounts(function(error, accounts) { if (error) { console.log(error); } var account = accounts[0]; App.contracts.TutorialToken.deployed().then(function(instance) { tutorialTokenInstance = instance; return tutorialTokenInstance.balanceOf(account); }).then(function(result) { balance = result.c[0]; $('#TTBalance').text(balance); }).catch(function(err) { console.log(err.message); }); }); } }; $(function() { $(window).load(function() { App.init(); }); }); ================================================ FILE: truffle/tokentutorial/src/js/truffle-contract.js ================================================ (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0 && new Date().getTime() - start > timeout) { return reject(new Error("Transaction " + tx + " wasn't processed in " + (timeout / 1000) + " seconds!")); } setTimeout(make_attempt, 1000); }); }; make_attempt(); }; args.push(tx_params, callback); fn.apply(self, args); }); }); }; }, merge: function() { var merged = {}; var args = Array.prototype.slice.call(arguments); for (var i = 0; i < args.length; i++) { var object = args[i]; var keys = Object.keys(object); for (var j = 0; j < keys.length; j++) { var key = keys[j]; var value = object[key]; merged[key] = value; } } return merged; }, parallel: function (arr, callback) { callback = callback || function () {}; if (!arr.length) { return callback(null, []); } var index = 0; var results = new Array(arr.length); arr.forEach(function (fn, position) { fn(function (err, result) { if (err) { callback(err); callback = function () {}; } else { index++; results[position] = result; if (index >= arr.length) { callback(null, results); } } }); }); }, bootstrap: function(fn) { // Add our static methods Object.keys(fn._static_methods).forEach(function(key) { fn[key] = fn._static_methods[key].bind(fn); }); // Add our properties. Object.keys(fn._properties).forEach(function(key) { fn.addProp(key, fn._properties[key]); }); return fn; } }; // Accepts a contract object created with web3.eth.contract. // Optionally, if called without `new`, accepts a network_id and will // create a new version of the contract abstraction with that network_id set. function Contract(contract) { var self = this; var constructor = this.constructor; this.abi = constructor.abi; if (typeof contract == "string") { var address = contract; var contract_class = constructor.web3.eth.contract(this.abi); contract = contract_class.at(address); } this.contract = contract; // Provision our functions. for (var i = 0; i < this.abi.length; i++) { var item = this.abi[i]; if (item.type == "function") { if (item.constant == true) { this[item.name] = Utils.promisifyFunction(contract[item.name], constructor); } else { this[item.name] = Utils.synchronizeFunction(contract[item.name], this, constructor); } this[item.name].call = Utils.promisifyFunction(contract[item.name].call, constructor); this[item.name].sendTransaction = Utils.promisifyFunction(contract[item.name].sendTransaction, constructor); this[item.name].request = contract[item.name].request; this[item.name].estimateGas = Utils.promisifyFunction(contract[item.name].estimateGas, constructor); } if (item.type == "event") { this[item.name] = contract[item.name]; } } this.sendTransaction = Utils.synchronizeFunction(function(tx_params, callback) { if (typeof tx_params == "function") { callback = tx_params; tx_params = {}; } tx_params.to = self.address; constructor.web3.eth.sendTransaction.apply(constructor.web3.eth, [tx_params, callback]); }, this, constructor); this.send = function(value) { return self.sendTransaction({value: value}); }; this.allEvents = contract.allEvents; this.address = contract.address; this.transactionHash = contract.transactionHash; }; Contract._static_methods = { setProvider: function(provider) { if (!provider) { throw new Error("Invalid provider passed to setProvider(); provider is " + provider); } var wrapped = new Provider(provider); this.web3.setProvider(wrapped); this.currentProvider = provider; }, new: function() { var self = this; if (this.currentProvider == null) { throw new Error(this.contract_name + " error: Please call setProvider() first before calling new()."); } var args = Array.prototype.slice.call(arguments); if (!this.unlinked_binary) { throw new Error(this._json.contract_name + " error: contract binary not set. Can't deploy new instance."); } return self.detectNetwork().then(function(network_id) { // After the network is set, check to make sure everything's ship shape. var regex = /__[^_]+_+/g; var unlinked_libraries = self.binary.match(regex); if (unlinked_libraries != null) { unlinked_libraries = unlinked_libraries.map(function(name) { // Remove underscores return name.replace(/_/g, ""); }).sort().filter(function(name, index, arr) { // Remove duplicates if (index + 1 >= arr.length) { return true; } return name != arr[index + 1]; }).join(", "); throw new Error(self.contract_name + " contains unresolved libraries. You must deploy and link the following libraries before you can deploy a new version of " + self._json.contract_name + ": " + unlinked_libraries); } }).then(function() { return new Promise(function(accept, reject) { var contract_class = self.web3.eth.contract(self.abi); var tx_params = {}; var last_arg = args[args.length - 1]; // It's only tx_params if it's an object and not a BigNumber. if (Utils.is_object(last_arg) && !Utils.is_big_number(last_arg)) { tx_params = args.pop(); } tx_params = Utils.merge(self.class_defaults, tx_params); if (tx_params.data == null) { tx_params.data = self.binary; } // web3 0.9.0 and above calls new this callback twice. // Why, I have no idea... var intermediary = function(err, web3_instance) { if (err != null) { reject(err); return; } if (err == null && web3_instance != null && web3_instance.address != null) { accept(new self(web3_instance)); } }; args.push(tx_params, intermediary); contract_class.new.apply(contract_class, args); }); }); }, at: function(address) { var self = this; if (address == null || typeof address != "string" || address.length != 42) { throw new Error("Invalid address passed to " + this._json.contract_name + ".at(): " + address); } var contract = new this(address); // Add thennable to allow people opt into new recommended usage. contract.then = function(fn) { return self.detectNetwork().then(function(network_id) { var instance = new self(address); return new Promise(function(accept, reject) { self.web3.eth.getCode(address, function(err, code) { if (err) return reject(err); if (!code || new BigNumber(code).eq(0)) { return reject(new Error("Cannot create instance of " + self.contract_name + "; no code at address " + address)); } accept(instance); }); }); }).then(fn); }; return contract; }, deployed: function() { var self = this; var val = {}; //this.at(this.address); // Add thennable to allow people to opt into new recommended usage. val.then = function(fn) { return self.detectNetwork().then(function() { // We don't have a network config for the one we found if (self._json.networks[self.network_id] == null) { throw new Error(self.contract_name + " has not been deployed to detected network (network/artifact mismatch)"); } // If we found the network but it's not deployed if (!self.isDeployed()) { throw new Error(self.contract_name + " has not been deployed to detected network (" + self.network_id + ")"); } return new self(self.address); }).then(fn); }; return val; }, defaults: function(class_defaults) { if (this.class_defaults == null) { this.class_defaults = {}; } if (class_defaults == null) { class_defaults = {}; } var self = this; Object.keys(class_defaults).forEach(function(key) { var value = class_defaults[key]; self.class_defaults[key] = value; }); return this.class_defaults; }, hasNetwork: function(network_id) { return this._json.networks[network_id + ""] != null; }, isDeployed: function() { if (this.network_id == null) { return false; } if (this._json.networks[this.network_id] == null) { return false; } return !!this.network.address; }, detectNetwork: function() { var self = this; return new Promise(function(accept, reject) { // Try to detect the network we have artifacts for. if (self.network_id) { // We have a network id and a configuration, let's go with it. if (self.networks[self.network_id] != null) { return accept(self.network_id); } } self.web3.version.getNetwork(function(err, result) { if (err) return reject(err); var network_id = result.toString(); // If we found the network via a number, let's use that. if (self.hasNetwork(network_id)) { self.setNetwork(network_id); return accept(); } // Otherwise, go through all the networks that are listed as // blockchain uris and see if they match. var uris = Object.keys(self._json.networks).filter(function(network) { return network.indexOf("blockchain://") == 0; }); var matches = uris.map(function(uri) { return BlockchainUtils.matches.bind(BlockchainUtils, uri, self.web3.currentProvider); }); Utils.parallel(matches, function(err, results) { if (err) return reject(err); for (var i = 0; i < results.length; i++) { if (results[i]) { self.setNetwork(uris[i]); return accept(); } } // We found nothing. Set the network id to whatever the provider states. self.setNetwork(network_id); accept(); }); }); }); }, setNetwork: function(network_id) { if (!network_id) return; this.network_id = network_id + ""; }, // Overrides the deployed address to null. // You must call this explicitly so you don't inadvertently do this otherwise. resetAddress: function() { delete this.network.address; }, link: function(name, address) { var self = this; if (typeof name == "function") { var contract = name; if (contract.isDeployed() == false) { throw new Error("Cannot link contract without an address."); } this.link(contract.contract_name, contract.address); // Merge events so this contract knows about library's events Object.keys(contract.events).forEach(function(topic) { self.network.events[topic] = contract.events[topic]; }); return; } if (typeof name == "object") { var obj = name; Object.keys(obj).forEach(function(name) { var a = obj[name]; self.link(name, a); }); return; } if (this._json.networks[this.network_id] == null) { this._json.networks[this.network_id] = { events: {}, links: {} }; } this.network.links[name] = address; }, clone: function(options) { var self = this; var temp = function TruffleContract() { this.constructor = temp; return Contract.apply(this, arguments); }; var json = options; var network_id; if (typeof options != "object") { json = self._json; network_id = options; options = {}; } temp.prototype = Object.create(self.prototype); temp._static_methods = this._static_methods; temp._properties = this._properties; temp._property_values = {}; temp._json = json || {}; Utils.bootstrap(temp); temp.web3 = new Web3(); temp.class_defaults = temp.prototype.defaults || {}; if (network_id) { temp.setNetwork(network_id); } // Copy over custom options Object.keys(options).forEach(function(key) { if (key.indexOf("x-") != 0) return; temp[key] = options[key]; }); return temp; }, addProp: function(key, fn) { var self = this; var getter = function() { if (fn.get != null) { return fn.get.call(self); } return self._property_values[key] || fn.call(self); } var setter = function(val) { if (fn.set != null) { fn.set.call(self, val); return; } // If there's not a setter, then the property is immutable. throw new Error(key + " property is immutable"); }; var definition = {}; definition.enumerable = false; definition.configurable = false; definition.get = getter; definition.set = setter; Object.defineProperty(this, key, definition); }, toJSON: function() { return this._json; } }; // Getter functions are scoped to Contract object. Contract._properties = { contract_name: { get: function() { return this._json.contract_name; }, set: function(val) { this._json.contract_name = val; } }, abi: { get: function() { return this._json.abi; }, set: function(val) { this._json.abi = val; } }, network: function() { var network_id = this.network_id; if (network_id == null) { throw new Error(this.contract_name + " has no network id set, cannot lookup artifact data. Either set the network manually using " + this.contract_name + ".setNetwork(), run " + this.contract_name + ".detectNetwork(), or use new(), at() or deployed() as a thenable which will detect the network automatically."); } // TODO: this might be bad; setting a value on a get. if (this._json.networks[network_id] == null) { throw new Error(this.contract_name + " has no network configuration for its current network id (" + network_id + ")."); } return this._json.networks[network_id]; }, networks: function() { return this._json.networks; }, address: { get: function() { var address = this.network.address; if (address == null) { throw new Error("Cannot find deployed address: " + this.contract_name + " not deployed or address not set."); } return address; }, set: function(val) { if (val == null) { throw new Error("Cannot set deployed address; malformed value: " + val); } var network_id = this.network_id; if (network_id == null) { throw new Error(this.contract_name + " has no network id set, cannot lookup artifact data. Either set the network manually using " + this.contract_name + ".setNetwork(), run " + this.contract_name + ".detectNetwork(), or use new(), at() or deployed() as a thenable which will detect the network automatically."); } // Create a network if we don't have one. if (this._json.networks[network_id] == null) { this._json.networks[network_id] = { events: {}, links: {} }; } // Finally, set the address. this.network.address = val; } }, links: function() { if (this._json.networks[this.network_id] == null) { return {}; } return this.network.links || {}; }, events: function() { // helper web3; not used for provider var web3 = new Web3(); var events; if (this._json.networks[this.network_id] == null) { events = {}; } else { events = this.network.events || {}; } // Merge abi events with whatever's returned. var abi = this.abi; abi.forEach(function(item) { if (item.type != "event") return; var signature = item.name + "("; item.inputs.forEach(function(input, index) { signature += input.type; if (index < item.inputs.length - 1) { signature += ","; } }); signature += ")"; var topic = web3.sha3(signature); events[topic] = item; }); return events; }, binary: function() { var self = this; var binary = this.unlinked_binary; Object.keys(this.links).forEach(function(library_name) { var library_address = self.links[library_name]; var regex = new RegExp("__" + library_name + "_*", "g"); binary = binary.replace(regex, library_address.replace("0x", "")); }); return binary; }, unlinked_binary: { get: function() { return this._json.unlinked_binary; }, set: function(val) { // TODO: Ensure 0x prefix. this._json.unlinked_binary = val; } }, schema_version: function() { return this._json.schema_version; }, updated_at: function() { try { return this.network.updated_at || this._json.updated_at; } catch (e) { return this._json.updated_at; } } }; Utils.bootstrap(Contract); module.exports = Contract; return Contract; })(module || {}); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"ethjs-abi":7,"truffle-blockchain-utils":15,"web3":5}],2:[function(require,module,exports){ var Schema = require("truffle-contract-schema"); var Contract = require("./contract.js"); var contract = function(options) { options = Schema.normalizeOptions(options); var binary = Schema.generateBinary(options, {}, {dirty: false}); // Note we don't use `new` here at all. This will cause the class to // "mutate" instead of instantiate an instance. return Contract.clone(binary); }; // To be used to upgrade old .sol.js abstractions contract.fromSolJS = function(soljs_abstraction, ignore_default_network) { if (ignore_default_network == null) { ignore_default_network = false; } // Find the latest binary var latest_network = null; var latest_network_updated_at = 0; var networks = {}; Object.keys(soljs_abstraction.all_networks).forEach(function(network_name) { if (network_name == "default") { if (ignore_default_network == true ) { return; } else { throw new Error(soljs_abstraction.contract_name + " has legacy 'default' network artifacts stored within it. Generally these artifacts were a result of running Truffle on a development environment -- in order to store contracts with truffle-contract, all networks must have an identified id. If you're sure this default network represents your development environment, you can ignore processing of the default network by passing `true` as the second argument to this function. However, if you think this network represents artifacts you'd like to keep (i.e., addresses deployed to the main network), you'll need to edit your .sol.js file yourself and change the default network id to be the id of your desired network. For most people, ignoring the default network is the correct option."); } } if (soljs_abstraction.all_networks[network_name].updated_at > latest_network_updated_at) { latest_network = network_name; latest_network_updated_at = soljs_abstraction.all_networks[network_name].updated_at; } networks[network_name] = {}; ["address", "events", "links", "updated_at"].forEach(function(key) { networks[network_name][key] = soljs_abstraction.all_networks[network_name][key]; }) }); latest_network = soljs_abstraction.all_networks[latest_network] || {}; var json = { contract_name: soljs_abstraction.contract_name, unlinked_binary: latest_network.unlinked_binary, abi: latest_network.abi, networks: networks, updated_at: latest_network_updated_at == 0 ? undefined : latest_network_updated_at }; return contract(json); }; module.exports = contract; if (typeof window !== "undefined") { window.TruffleContract = contract; } },{"./contract.js":1,"truffle-contract-schema":16}],3:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i] revLookup[code.charCodeAt(i)] = i } revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 function placeHoldersCount (b64) { var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 } function byteLength (b64) { // base64 is 4/3 + up to two characters of the original data return b64.length * 3 / 4 - placeHoldersCount(b64) } function toByteArray (b64) { var i, j, l, tmp, placeHolders, arr var len = b64.length placeHolders = placeHoldersCount(b64) arr = new Arr(len * 3 / 4 - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? len - 4 : len var L = 0 for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[L++] = (tmp >> 16) & 0xFF arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } if (placeHolders === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[L++] = tmp & 0xFF } else if (placeHolders === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } return arr } function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } function encodeChunk (uint8, start, end) { var tmp var output = [] for (var i = start; i < end; i += 3) { tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output.push(tripletToBase64(tmp)) } return output.join('') } function fromByteArray (uint8) { var tmp var len = uint8.length var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes var output = '' var parts = [] var maxChunkLength = 16383 // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1] output += lookup[tmp >> 2] output += lookup[(tmp << 4) & 0x3F] output += '==' } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) output += lookup[tmp >> 10] output += lookup[(tmp >> 4) & 0x3F] output += lookup[(tmp << 2) & 0x3F] output += '=' } parts.push(output) return parts.join('') } },{}],4:[function(require,module,exports){ (function (module, exports) { 'use strict'; // Utils function assert (val, msg) { if (!val) throw new Error(msg || 'Assertion failed'); } // Could use `inherits` module, but don't want to move from single file // architecture yet. function inherits (ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } // BN function BN (number, base, endian) { if (BN.isBN(number)) { return number; } this.negative = 0; this.words = null; this.length = 0; // Reduction context this.red = null; if (number !== null) { if (base === 'le' || base === 'be') { endian = base; base = 10; } this._init(number || 0, base || 10, endian || 'be'); } } if (typeof module === 'object') { module.exports = BN; } else { exports.BN = BN; } BN.BN = BN; BN.wordSize = 26; var Buffer; try { Buffer = require('buf' + 'fer').Buffer; } catch (e) { } BN.isBN = function isBN (num) { if (num instanceof BN) { return true; } return num !== null && typeof num === 'object' && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); }; BN.max = function max (left, right) { if (left.cmp(right) > 0) return left; return right; }; BN.min = function min (left, right) { if (left.cmp(right) < 0) return left; return right; }; BN.prototype._init = function init (number, base, endian) { if (typeof number === 'number') { return this._initNumber(number, base, endian); } if (typeof number === 'object') { return this._initArray(number, base, endian); } if (base === 'hex') { base = 16; } assert(base === (base | 0) && base >= 2 && base <= 36); number = number.toString().replace(/\s+/g, ''); var start = 0; if (number[0] === '-') { start++; } if (base === 16) { this._parseHex(number, start); } else { this._parseBase(number, base, start); } if (number[0] === '-') { this.negative = 1; } this.strip(); if (endian !== 'le') return; this._initArray(this.toArray(), base, endian); }; BN.prototype._initNumber = function _initNumber (number, base, endian) { if (number < 0) { this.negative = 1; number = -number; } if (number < 0x4000000) { this.words = [ number & 0x3ffffff ]; this.length = 1; } else if (number < 0x10000000000000) { this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff ]; this.length = 2; } else { assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff, 1 ]; this.length = 3; } if (endian !== 'le') return; // Reverse the bytes this._initArray(this.toArray(), base, endian); }; BN.prototype._initArray = function _initArray (number, base, endian) { // Perhaps a Uint8Array assert(typeof number.length === 'number'); if (number.length <= 0) { this.words = [ 0 ]; this.length = 1; return this; } this.length = Math.ceil(number.length / 3); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } var j, w; var off = 0; if (endian === 'be') { for (i = number.length - 1, j = 0; i >= 0; i -= 3) { w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } else if (endian === 'le') { for (i = 0, j = 0; i < number.length; i += 3) { w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } return this.strip(); }; function parseHex (str, start, end) { var r = 0; var len = Math.min(str.length, end); for (var i = start; i < len; i++) { var c = str.charCodeAt(i) - 48; r <<= 4; // 'a' - 'f' if (c >= 49 && c <= 54) { r |= c - 49 + 0xa; // 'A' - 'F' } else if (c >= 17 && c <= 22) { r |= c - 17 + 0xa; // '0' - '9' } else { r |= c & 0xf; } } return r; } BN.prototype._parseHex = function _parseHex (number, start) { // Create possibly bigger array to ensure that it fits the number this.length = Math.ceil((number.length - start) / 6); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } var j, w; // Scan 24-bit chunks and add them to the number var off = 0; for (i = number.length - 6, j = 0; i >= start; i -= 6) { w = parseHex(number, i, i + 6); this.words[j] |= (w << off) & 0x3ffffff; // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; off += 24; if (off >= 26) { off -= 26; j++; } } if (i + 6 !== start) { w = parseHex(number, start, i + 6); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; } this.strip(); }; function parseBase (str, start, end, mul) { var r = 0; var len = Math.min(str.length, end); for (var i = start; i < len; i++) { var c = str.charCodeAt(i) - 48; r *= mul; // 'a' if (c >= 49) { r += c - 49 + 0xa; // 'A' } else if (c >= 17) { r += c - 17 + 0xa; // '0' - '9' } else { r += c; } } return r; } BN.prototype._parseBase = function _parseBase (number, base, start) { // Initialize as zero this.words = [ 0 ]; this.length = 1; // Find length of limb in base for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { limbLen++; } limbLen--; limbPow = (limbPow / base) | 0; var total = number.length - start; var mod = total % limbLen; var end = Math.min(total, total - mod) + start; var word = 0; for (var i = start; i < end; i += limbLen) { word = parseBase(number, i, i + limbLen, base); this.imuln(limbPow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } if (mod !== 0) { var pow = 1; word = parseBase(number, i, number.length, base); for (i = 0; i < mod; i++) { pow *= base; } this.imuln(pow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } }; BN.prototype.copy = function copy (dest) { dest.words = new Array(this.length); for (var i = 0; i < this.length; i++) { dest.words[i] = this.words[i]; } dest.length = this.length; dest.negative = this.negative; dest.red = this.red; }; BN.prototype.clone = function clone () { var r = new BN(null); this.copy(r); return r; }; BN.prototype._expand = function _expand (size) { while (this.length < size) { this.words[this.length++] = 0; } return this; }; // Remove leading `0` from `this` BN.prototype.strip = function strip () { while (this.length > 1 && this.words[this.length - 1] === 0) { this.length--; } return this._normSign(); }; BN.prototype._normSign = function _normSign () { // -0 = 0 if (this.length === 1 && this.words[0] === 0) { this.negative = 0; } return this; }; BN.prototype.inspect = function inspect () { return (this.red ? ''; }; /* var zeros = []; var groupSizes = []; var groupBases = []; var s = ''; var i = -1; while (++i < BN.wordSize) { zeros[i] = s; s += '0'; } groupSizes[0] = 0; groupSizes[1] = 0; groupBases[0] = 0; groupBases[1] = 0; var base = 2 - 1; while (++base < 36 + 1) { var groupSize = 0; var groupBase = 1; while (groupBase < (1 << BN.wordSize) / base) { groupBase *= base; groupSize += 1; } groupSizes[base] = groupSize; groupBases[base] = groupBase; } */ var zeros = [ '', '0', '00', '000', '0000', '00000', '000000', '0000000', '00000000', '000000000', '0000000000', '00000000000', '000000000000', '0000000000000', '00000000000000', '000000000000000', '0000000000000000', '00000000000000000', '000000000000000000', '0000000000000000000', '00000000000000000000', '000000000000000000000', '0000000000000000000000', '00000000000000000000000', '000000000000000000000000', '0000000000000000000000000' ]; var groupSizes = [ 0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 ]; var groupBases = [ 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 ]; BN.prototype.toString = function toString (base, padding) { base = base || 10; padding = padding | 0 || 1; var out; if (base === 16 || base === 'hex') { out = ''; var off = 0; var carry = 0; for (var i = 0; i < this.length; i++) { var w = this.words[i]; var word = (((w << off) | carry) & 0xffffff).toString(16); carry = (w >>> (24 - off)) & 0xffffff; if (carry !== 0 || i !== this.length - 1) { out = zeros[6 - word.length] + word + out; } else { out = word + out; } off += 2; if (off >= 26) { off -= 26; i--; } } if (carry !== 0) { out = carry.toString(16) + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } if (base === (base | 0) && base >= 2 && base <= 36) { // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); var groupSize = groupSizes[base]; // var groupBase = Math.pow(base, groupSize); var groupBase = groupBases[base]; out = ''; var c = this.clone(); c.negative = 0; while (!c.isZero()) { var r = c.modn(groupBase).toString(base); c = c.idivn(groupBase); if (!c.isZero()) { out = zeros[groupSize - r.length] + r + out; } else { out = r + out; } } if (this.isZero()) { out = '0' + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } assert(false, 'Base should be between 2 and 36'); }; BN.prototype.toNumber = function toNumber () { var ret = this.words[0]; if (this.length === 2) { ret += this.words[1] * 0x4000000; } else if (this.length === 3 && this.words[2] === 0x01) { // NOTE: at this stage it is known that the top bit is set ret += 0x10000000000000 + (this.words[1] * 0x4000000); } else if (this.length > 2) { assert(false, 'Number can only safely store up to 53 bits'); } return (this.negative !== 0) ? -ret : ret; }; BN.prototype.toJSON = function toJSON () { return this.toString(16); }; BN.prototype.toBuffer = function toBuffer (endian, length) { assert(typeof Buffer !== 'undefined'); return this.toArrayLike(Buffer, endian, length); }; BN.prototype.toArray = function toArray (endian, length) { return this.toArrayLike(Array, endian, length); }; BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { var byteLength = this.byteLength(); var reqLength = length || Math.max(1, byteLength); assert(byteLength <= reqLength, 'byte array longer than desired length'); assert(reqLength > 0, 'Requested array length <= 0'); this.strip(); var littleEndian = endian === 'le'; var res = new ArrayType(reqLength); var b, i; var q = this.clone(); if (!littleEndian) { // Assume big-endian for (i = 0; i < reqLength - byteLength; i++) { res[i] = 0; } for (i = 0; !q.isZero(); i++) { b = q.andln(0xff); q.iushrn(8); res[reqLength - i - 1] = b; } } else { for (i = 0; !q.isZero(); i++) { b = q.andln(0xff); q.iushrn(8); res[i] = b; } for (; i < reqLength; i++) { res[i] = 0; } } return res; }; if (Math.clz32) { BN.prototype._countBits = function _countBits (w) { return 32 - Math.clz32(w); }; } else { BN.prototype._countBits = function _countBits (w) { var t = w; var r = 0; if (t >= 0x1000) { r += 13; t >>>= 13; } if (t >= 0x40) { r += 7; t >>>= 7; } if (t >= 0x8) { r += 4; t >>>= 4; } if (t >= 0x02) { r += 2; t >>>= 2; } return r + t; }; } BN.prototype._zeroBits = function _zeroBits (w) { // Short-cut if (w === 0) return 26; var t = w; var r = 0; if ((t & 0x1fff) === 0) { r += 13; t >>>= 13; } if ((t & 0x7f) === 0) { r += 7; t >>>= 7; } if ((t & 0xf) === 0) { r += 4; t >>>= 4; } if ((t & 0x3) === 0) { r += 2; t >>>= 2; } if ((t & 0x1) === 0) { r++; } return r; }; // Return number of used bits in a BN BN.prototype.bitLength = function bitLength () { var w = this.words[this.length - 1]; var hi = this._countBits(w); return (this.length - 1) * 26 + hi; }; function toBitArray (num) { var w = new Array(num.bitLength()); for (var bit = 0; bit < w.length; bit++) { var off = (bit / 26) | 0; var wbit = bit % 26; w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; } return w; } // Number of trailing zero bits BN.prototype.zeroBits = function zeroBits () { if (this.isZero()) return 0; var r = 0; for (var i = 0; i < this.length; i++) { var b = this._zeroBits(this.words[i]); r += b; if (b !== 26) break; } return r; }; BN.prototype.byteLength = function byteLength () { return Math.ceil(this.bitLength() / 8); }; BN.prototype.toTwos = function toTwos (width) { if (this.negative !== 0) { return this.abs().inotn(width).iaddn(1); } return this.clone(); }; BN.prototype.fromTwos = function fromTwos (width) { if (this.testn(width - 1)) { return this.notn(width).iaddn(1).ineg(); } return this.clone(); }; BN.prototype.isNeg = function isNeg () { return this.negative !== 0; }; // Return negative clone of `this` BN.prototype.neg = function neg () { return this.clone().ineg(); }; BN.prototype.ineg = function ineg () { if (!this.isZero()) { this.negative ^= 1; } return this; }; // Or `num` with `this` in-place BN.prototype.iuor = function iuor (num) { while (this.length < num.length) { this.words[this.length++] = 0; } for (var i = 0; i < num.length; i++) { this.words[i] = this.words[i] | num.words[i]; } return this.strip(); }; BN.prototype.ior = function ior (num) { assert((this.negative | num.negative) === 0); return this.iuor(num); }; // Or `num` with `this` BN.prototype.or = function or (num) { if (this.length > num.length) return this.clone().ior(num); return num.clone().ior(this); }; BN.prototype.uor = function uor (num) { if (this.length > num.length) return this.clone().iuor(num); return num.clone().iuor(this); }; // And `num` with `this` in-place BN.prototype.iuand = function iuand (num) { // b = min-length(num, this) var b; if (this.length > num.length) { b = num; } else { b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = this.words[i] & num.words[i]; } this.length = b.length; return this.strip(); }; BN.prototype.iand = function iand (num) { assert((this.negative | num.negative) === 0); return this.iuand(num); }; // And `num` with `this` BN.prototype.and = function and (num) { if (this.length > num.length) return this.clone().iand(num); return num.clone().iand(this); }; BN.prototype.uand = function uand (num) { if (this.length > num.length) return this.clone().iuand(num); return num.clone().iuand(this); }; // Xor `num` with `this` in-place BN.prototype.iuxor = function iuxor (num) { // a.length > b.length var a; var b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = a.words[i] ^ b.words[i]; } if (this !== a) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = a.length; return this.strip(); }; BN.prototype.ixor = function ixor (num) { assert((this.negative | num.negative) === 0); return this.iuxor(num); }; // Xor `num` with `this` BN.prototype.xor = function xor (num) { if (this.length > num.length) return this.clone().ixor(num); return num.clone().ixor(this); }; BN.prototype.uxor = function uxor (num) { if (this.length > num.length) return this.clone().iuxor(num); return num.clone().iuxor(this); }; // Not ``this`` with ``width`` bitwidth BN.prototype.inotn = function inotn (width) { assert(typeof width === 'number' && width >= 0); var bytesNeeded = Math.ceil(width / 26) | 0; var bitsLeft = width % 26; // Extend the buffer with leading zeroes this._expand(bytesNeeded); if (bitsLeft > 0) { bytesNeeded--; } // Handle complete words for (var i = 0; i < bytesNeeded; i++) { this.words[i] = ~this.words[i] & 0x3ffffff; } // Handle the residue if (bitsLeft > 0) { this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); } // And remove leading zeroes return this.strip(); }; BN.prototype.notn = function notn (width) { return this.clone().inotn(width); }; // Set `bit` of `this` BN.prototype.setn = function setn (bit, val) { assert(typeof bit === 'number' && bit >= 0); var off = (bit / 26) | 0; var wbit = bit % 26; this._expand(off + 1); if (val) { this.words[off] = this.words[off] | (1 << wbit); } else { this.words[off] = this.words[off] & ~(1 << wbit); } return this.strip(); }; // Add `num` to `this` in-place BN.prototype.iadd = function iadd (num) { var r; // negative + positive if (this.negative !== 0 && num.negative === 0) { this.negative = 0; r = this.isub(num); this.negative ^= 1; return this._normSign(); // positive + negative } else if (this.negative === 0 && num.negative !== 0) { num.negative = 0; r = this.isub(num); num.negative = 1; return r._normSign(); } // a.length > b.length var a, b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) + (b.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } this.length = a.length; if (carry !== 0) { this.words[this.length] = carry; this.length++; // Copy the rest of the words } else if (a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } return this; }; // Add `num` to `this` BN.prototype.add = function add (num) { var res; if (num.negative !== 0 && this.negative === 0) { num.negative = 0; res = this.sub(num); num.negative ^= 1; return res; } else if (num.negative === 0 && this.negative !== 0) { this.negative = 0; res = num.sub(this); this.negative = 1; return res; } if (this.length > num.length) return this.clone().iadd(num); return num.clone().iadd(this); }; // Subtract `num` from `this` in-place BN.prototype.isub = function isub (num) { // this - (-num) = this + num if (num.negative !== 0) { num.negative = 0; var r = this.iadd(num); num.negative = 1; return r._normSign(); // -this - num = -(this + num) } else if (this.negative !== 0) { this.negative = 0; this.iadd(num); this.negative = 1; return this._normSign(); } // At this point both numbers are positive var cmp = this.cmp(num); // Optimization - zeroify if (cmp === 0) { this.negative = 0; this.length = 1; this.words[0] = 0; return this; } // a > b var a, b; if (cmp > 0) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) - (b.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } // Copy rest of the words if (carry === 0 && i < a.length && a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = Math.max(this.length, i); if (a !== this) { this.negative = 1; } return this.strip(); }; // Subtract `num` from `this` BN.prototype.sub = function sub (num) { return this.clone().isub(num); }; function smallMulTo (self, num, out) { out.negative = num.negative ^ self.negative; var len = (self.length + num.length) | 0; out.length = len; len = (len - 1) | 0; // Peel one iteration (compiler can't do it, because of code complexity) var a = self.words[0] | 0; var b = num.words[0] | 0; var r = a * b; var lo = r & 0x3ffffff; var carry = (r / 0x4000000) | 0; out.words[0] = lo; for (var k = 1; k < len; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff var ncarry = carry >>> 26; var rword = carry & 0x3ffffff; var maxJ = Math.min(k, num.length - 1); for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { var i = (k - j) | 0; a = self.words[i] | 0; b = num.words[j] | 0; r = a * b + rword; ncarry += (r / 0x4000000) | 0; rword = r & 0x3ffffff; } out.words[k] = rword | 0; carry = ncarry | 0; } if (carry !== 0) { out.words[k] = carry | 0; } else { out.length--; } return out.strip(); } // TODO(indutny): it may be reasonable to omit it for users who don't need // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit // multiplication (like elliptic secp256k1). var comb10MulTo = function comb10MulTo (self, num, out) { var a = self.words; var b = num.words; var o = out.words; var c = 0; var lo; var mid; var hi; var a0 = a[0] | 0; var al0 = a0 & 0x1fff; var ah0 = a0 >>> 13; var a1 = a[1] | 0; var al1 = a1 & 0x1fff; var ah1 = a1 >>> 13; var a2 = a[2] | 0; var al2 = a2 & 0x1fff; var ah2 = a2 >>> 13; var a3 = a[3] | 0; var al3 = a3 & 0x1fff; var ah3 = a3 >>> 13; var a4 = a[4] | 0; var al4 = a4 & 0x1fff; var ah4 = a4 >>> 13; var a5 = a[5] | 0; var al5 = a5 & 0x1fff; var ah5 = a5 >>> 13; var a6 = a[6] | 0; var al6 = a6 & 0x1fff; var ah6 = a6 >>> 13; var a7 = a[7] | 0; var al7 = a7 & 0x1fff; var ah7 = a7 >>> 13; var a8 = a[8] | 0; var al8 = a8 & 0x1fff; var ah8 = a8 >>> 13; var a9 = a[9] | 0; var al9 = a9 & 0x1fff; var ah9 = a9 >>> 13; var b0 = b[0] | 0; var bl0 = b0 & 0x1fff; var bh0 = b0 >>> 13; var b1 = b[1] | 0; var bl1 = b1 & 0x1fff; var bh1 = b1 >>> 13; var b2 = b[2] | 0; var bl2 = b2 & 0x1fff; var bh2 = b2 >>> 13; var b3 = b[3] | 0; var bl3 = b3 & 0x1fff; var bh3 = b3 >>> 13; var b4 = b[4] | 0; var bl4 = b4 & 0x1fff; var bh4 = b4 >>> 13; var b5 = b[5] | 0; var bl5 = b5 & 0x1fff; var bh5 = b5 >>> 13; var b6 = b[6] | 0; var bl6 = b6 & 0x1fff; var bh6 = b6 >>> 13; var b7 = b[7] | 0; var bl7 = b7 & 0x1fff; var bh7 = b7 >>> 13; var b8 = b[8] | 0; var bl8 = b8 & 0x1fff; var bh8 = b8 >>> 13; var b9 = b[9] | 0; var bl9 = b9 & 0x1fff; var bh9 = b9 >>> 13; out.negative = self.negative ^ num.negative; out.length = 19; /* k = 0 */ lo = Math.imul(al0, bl0); mid = Math.imul(al0, bh0); mid = (mid + Math.imul(ah0, bl0)) | 0; hi = Math.imul(ah0, bh0); var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; w0 &= 0x3ffffff; /* k = 1 */ lo = Math.imul(al1, bl0); mid = Math.imul(al1, bh0); mid = (mid + Math.imul(ah1, bl0)) | 0; hi = Math.imul(ah1, bh0); lo = (lo + Math.imul(al0, bl1)) | 0; mid = (mid + Math.imul(al0, bh1)) | 0; mid = (mid + Math.imul(ah0, bl1)) | 0; hi = (hi + Math.imul(ah0, bh1)) | 0; var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; w1 &= 0x3ffffff; /* k = 2 */ lo = Math.imul(al2, bl0); mid = Math.imul(al2, bh0); mid = (mid + Math.imul(ah2, bl0)) | 0; hi = Math.imul(ah2, bh0); lo = (lo + Math.imul(al1, bl1)) | 0; mid = (mid + Math.imul(al1, bh1)) | 0; mid = (mid + Math.imul(ah1, bl1)) | 0; hi = (hi + Math.imul(ah1, bh1)) | 0; lo = (lo + Math.imul(al0, bl2)) | 0; mid = (mid + Math.imul(al0, bh2)) | 0; mid = (mid + Math.imul(ah0, bl2)) | 0; hi = (hi + Math.imul(ah0, bh2)) | 0; var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; w2 &= 0x3ffffff; /* k = 3 */ lo = Math.imul(al3, bl0); mid = Math.imul(al3, bh0); mid = (mid + Math.imul(ah3, bl0)) | 0; hi = Math.imul(ah3, bh0); lo = (lo + Math.imul(al2, bl1)) | 0; mid = (mid + Math.imul(al2, bh1)) | 0; mid = (mid + Math.imul(ah2, bl1)) | 0; hi = (hi + Math.imul(ah2, bh1)) | 0; lo = (lo + Math.imul(al1, bl2)) | 0; mid = (mid + Math.imul(al1, bh2)) | 0; mid = (mid + Math.imul(ah1, bl2)) | 0; hi = (hi + Math.imul(ah1, bh2)) | 0; lo = (lo + Math.imul(al0, bl3)) | 0; mid = (mid + Math.imul(al0, bh3)) | 0; mid = (mid + Math.imul(ah0, bl3)) | 0; hi = (hi + Math.imul(ah0, bh3)) | 0; var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; w3 &= 0x3ffffff; /* k = 4 */ lo = Math.imul(al4, bl0); mid = Math.imul(al4, bh0); mid = (mid + Math.imul(ah4, bl0)) | 0; hi = Math.imul(ah4, bh0); lo = (lo + Math.imul(al3, bl1)) | 0; mid = (mid + Math.imul(al3, bh1)) | 0; mid = (mid + Math.imul(ah3, bl1)) | 0; hi = (hi + Math.imul(ah3, bh1)) | 0; lo = (lo + Math.imul(al2, bl2)) | 0; mid = (mid + Math.imul(al2, bh2)) | 0; mid = (mid + Math.imul(ah2, bl2)) | 0; hi = (hi + Math.imul(ah2, bh2)) | 0; lo = (lo + Math.imul(al1, bl3)) | 0; mid = (mid + Math.imul(al1, bh3)) | 0; mid = (mid + Math.imul(ah1, bl3)) | 0; hi = (hi + Math.imul(ah1, bh3)) | 0; lo = (lo + Math.imul(al0, bl4)) | 0; mid = (mid + Math.imul(al0, bh4)) | 0; mid = (mid + Math.imul(ah0, bl4)) | 0; hi = (hi + Math.imul(ah0, bh4)) | 0; var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; w4 &= 0x3ffffff; /* k = 5 */ lo = Math.imul(al5, bl0); mid = Math.imul(al5, bh0); mid = (mid + Math.imul(ah5, bl0)) | 0; hi = Math.imul(ah5, bh0); lo = (lo + Math.imul(al4, bl1)) | 0; mid = (mid + Math.imul(al4, bh1)) | 0; mid = (mid + Math.imul(ah4, bl1)) | 0; hi = (hi + Math.imul(ah4, bh1)) | 0; lo = (lo + Math.imul(al3, bl2)) | 0; mid = (mid + Math.imul(al3, bh2)) | 0; mid = (mid + Math.imul(ah3, bl2)) | 0; hi = (hi + Math.imul(ah3, bh2)) | 0; lo = (lo + Math.imul(al2, bl3)) | 0; mid = (mid + Math.imul(al2, bh3)) | 0; mid = (mid + Math.imul(ah2, bl3)) | 0; hi = (hi + Math.imul(ah2, bh3)) | 0; lo = (lo + Math.imul(al1, bl4)) | 0; mid = (mid + Math.imul(al1, bh4)) | 0; mid = (mid + Math.imul(ah1, bl4)) | 0; hi = (hi + Math.imul(ah1, bh4)) | 0; lo = (lo + Math.imul(al0, bl5)) | 0; mid = (mid + Math.imul(al0, bh5)) | 0; mid = (mid + Math.imul(ah0, bl5)) | 0; hi = (hi + Math.imul(ah0, bh5)) | 0; var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; w5 &= 0x3ffffff; /* k = 6 */ lo = Math.imul(al6, bl0); mid = Math.imul(al6, bh0); mid = (mid + Math.imul(ah6, bl0)) | 0; hi = Math.imul(ah6, bh0); lo = (lo + Math.imul(al5, bl1)) | 0; mid = (mid + Math.imul(al5, bh1)) | 0; mid = (mid + Math.imul(ah5, bl1)) | 0; hi = (hi + Math.imul(ah5, bh1)) | 0; lo = (lo + Math.imul(al4, bl2)) | 0; mid = (mid + Math.imul(al4, bh2)) | 0; mid = (mid + Math.imul(ah4, bl2)) | 0; hi = (hi + Math.imul(ah4, bh2)) | 0; lo = (lo + Math.imul(al3, bl3)) | 0; mid = (mid + Math.imul(al3, bh3)) | 0; mid = (mid + Math.imul(ah3, bl3)) | 0; hi = (hi + Math.imul(ah3, bh3)) | 0; lo = (lo + Math.imul(al2, bl4)) | 0; mid = (mid + Math.imul(al2, bh4)) | 0; mid = (mid + Math.imul(ah2, bl4)) | 0; hi = (hi + Math.imul(ah2, bh4)) | 0; lo = (lo + Math.imul(al1, bl5)) | 0; mid = (mid + Math.imul(al1, bh5)) | 0; mid = (mid + Math.imul(ah1, bl5)) | 0; hi = (hi + Math.imul(ah1, bh5)) | 0; lo = (lo + Math.imul(al0, bl6)) | 0; mid = (mid + Math.imul(al0, bh6)) | 0; mid = (mid + Math.imul(ah0, bl6)) | 0; hi = (hi + Math.imul(ah0, bh6)) | 0; var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; w6 &= 0x3ffffff; /* k = 7 */ lo = Math.imul(al7, bl0); mid = Math.imul(al7, bh0); mid = (mid + Math.imul(ah7, bl0)) | 0; hi = Math.imul(ah7, bh0); lo = (lo + Math.imul(al6, bl1)) | 0; mid = (mid + Math.imul(al6, bh1)) | 0; mid = (mid + Math.imul(ah6, bl1)) | 0; hi = (hi + Math.imul(ah6, bh1)) | 0; lo = (lo + Math.imul(al5, bl2)) | 0; mid = (mid + Math.imul(al5, bh2)) | 0; mid = (mid + Math.imul(ah5, bl2)) | 0; hi = (hi + Math.imul(ah5, bh2)) | 0; lo = (lo + Math.imul(al4, bl3)) | 0; mid = (mid + Math.imul(al4, bh3)) | 0; mid = (mid + Math.imul(ah4, bl3)) | 0; hi = (hi + Math.imul(ah4, bh3)) | 0; lo = (lo + Math.imul(al3, bl4)) | 0; mid = (mid + Math.imul(al3, bh4)) | 0; mid = (mid + Math.imul(ah3, bl4)) | 0; hi = (hi + Math.imul(ah3, bh4)) | 0; lo = (lo + Math.imul(al2, bl5)) | 0; mid = (mid + Math.imul(al2, bh5)) | 0; mid = (mid + Math.imul(ah2, bl5)) | 0; hi = (hi + Math.imul(ah2, bh5)) | 0; lo = (lo + Math.imul(al1, bl6)) | 0; mid = (mid + Math.imul(al1, bh6)) | 0; mid = (mid + Math.imul(ah1, bl6)) | 0; hi = (hi + Math.imul(ah1, bh6)) | 0; lo = (lo + Math.imul(al0, bl7)) | 0; mid = (mid + Math.imul(al0, bh7)) | 0; mid = (mid + Math.imul(ah0, bl7)) | 0; hi = (hi + Math.imul(ah0, bh7)) | 0; var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; w7 &= 0x3ffffff; /* k = 8 */ lo = Math.imul(al8, bl0); mid = Math.imul(al8, bh0); mid = (mid + Math.imul(ah8, bl0)) | 0; hi = Math.imul(ah8, bh0); lo = (lo + Math.imul(al7, bl1)) | 0; mid = (mid + Math.imul(al7, bh1)) | 0; mid = (mid + Math.imul(ah7, bl1)) | 0; hi = (hi + Math.imul(ah7, bh1)) | 0; lo = (lo + Math.imul(al6, bl2)) | 0; mid = (mid + Math.imul(al6, bh2)) | 0; mid = (mid + Math.imul(ah6, bl2)) | 0; hi = (hi + Math.imul(ah6, bh2)) | 0; lo = (lo + Math.imul(al5, bl3)) | 0; mid = (mid + Math.imul(al5, bh3)) | 0; mid = (mid + Math.imul(ah5, bl3)) | 0; hi = (hi + Math.imul(ah5, bh3)) | 0; lo = (lo + Math.imul(al4, bl4)) | 0; mid = (mid + Math.imul(al4, bh4)) | 0; mid = (mid + Math.imul(ah4, bl4)) | 0; hi = (hi + Math.imul(ah4, bh4)) | 0; lo = (lo + Math.imul(al3, bl5)) | 0; mid = (mid + Math.imul(al3, bh5)) | 0; mid = (mid + Math.imul(ah3, bl5)) | 0; hi = (hi + Math.imul(ah3, bh5)) | 0; lo = (lo + Math.imul(al2, bl6)) | 0; mid = (mid + Math.imul(al2, bh6)) | 0; mid = (mid + Math.imul(ah2, bl6)) | 0; hi = (hi + Math.imul(ah2, bh6)) | 0; lo = (lo + Math.imul(al1, bl7)) | 0; mid = (mid + Math.imul(al1, bh7)) | 0; mid = (mid + Math.imul(ah1, bl7)) | 0; hi = (hi + Math.imul(ah1, bh7)) | 0; lo = (lo + Math.imul(al0, bl8)) | 0; mid = (mid + Math.imul(al0, bh8)) | 0; mid = (mid + Math.imul(ah0, bl8)) | 0; hi = (hi + Math.imul(ah0, bh8)) | 0; var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; w8 &= 0x3ffffff; /* k = 9 */ lo = Math.imul(al9, bl0); mid = Math.imul(al9, bh0); mid = (mid + Math.imul(ah9, bl0)) | 0; hi = Math.imul(ah9, bh0); lo = (lo + Math.imul(al8, bl1)) | 0; mid = (mid + Math.imul(al8, bh1)) | 0; mid = (mid + Math.imul(ah8, bl1)) | 0; hi = (hi + Math.imul(ah8, bh1)) | 0; lo = (lo + Math.imul(al7, bl2)) | 0; mid = (mid + Math.imul(al7, bh2)) | 0; mid = (mid + Math.imul(ah7, bl2)) | 0; hi = (hi + Math.imul(ah7, bh2)) | 0; lo = (lo + Math.imul(al6, bl3)) | 0; mid = (mid + Math.imul(al6, bh3)) | 0; mid = (mid + Math.imul(ah6, bl3)) | 0; hi = (hi + Math.imul(ah6, bh3)) | 0; lo = (lo + Math.imul(al5, bl4)) | 0; mid = (mid + Math.imul(al5, bh4)) | 0; mid = (mid + Math.imul(ah5, bl4)) | 0; hi = (hi + Math.imul(ah5, bh4)) | 0; lo = (lo + Math.imul(al4, bl5)) | 0; mid = (mid + Math.imul(al4, bh5)) | 0; mid = (mid + Math.imul(ah4, bl5)) | 0; hi = (hi + Math.imul(ah4, bh5)) | 0; lo = (lo + Math.imul(al3, bl6)) | 0; mid = (mid + Math.imul(al3, bh6)) | 0; mid = (mid + Math.imul(ah3, bl6)) | 0; hi = (hi + Math.imul(ah3, bh6)) | 0; lo = (lo + Math.imul(al2, bl7)) | 0; mid = (mid + Math.imul(al2, bh7)) | 0; mid = (mid + Math.imul(ah2, bl7)) | 0; hi = (hi + Math.imul(ah2, bh7)) | 0; lo = (lo + Math.imul(al1, bl8)) | 0; mid = (mid + Math.imul(al1, bh8)) | 0; mid = (mid + Math.imul(ah1, bl8)) | 0; hi = (hi + Math.imul(ah1, bh8)) | 0; lo = (lo + Math.imul(al0, bl9)) | 0; mid = (mid + Math.imul(al0, bh9)) | 0; mid = (mid + Math.imul(ah0, bl9)) | 0; hi = (hi + Math.imul(ah0, bh9)) | 0; var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; w9 &= 0x3ffffff; /* k = 10 */ lo = Math.imul(al9, bl1); mid = Math.imul(al9, bh1); mid = (mid + Math.imul(ah9, bl1)) | 0; hi = Math.imul(ah9, bh1); lo = (lo + Math.imul(al8, bl2)) | 0; mid = (mid + Math.imul(al8, bh2)) | 0; mid = (mid + Math.imul(ah8, bl2)) | 0; hi = (hi + Math.imul(ah8, bh2)) | 0; lo = (lo + Math.imul(al7, bl3)) | 0; mid = (mid + Math.imul(al7, bh3)) | 0; mid = (mid + Math.imul(ah7, bl3)) | 0; hi = (hi + Math.imul(ah7, bh3)) | 0; lo = (lo + Math.imul(al6, bl4)) | 0; mid = (mid + Math.imul(al6, bh4)) | 0; mid = (mid + Math.imul(ah6, bl4)) | 0; hi = (hi + Math.imul(ah6, bh4)) | 0; lo = (lo + Math.imul(al5, bl5)) | 0; mid = (mid + Math.imul(al5, bh5)) | 0; mid = (mid + Math.imul(ah5, bl5)) | 0; hi = (hi + Math.imul(ah5, bh5)) | 0; lo = (lo + Math.imul(al4, bl6)) | 0; mid = (mid + Math.imul(al4, bh6)) | 0; mid = (mid + Math.imul(ah4, bl6)) | 0; hi = (hi + Math.imul(ah4, bh6)) | 0; lo = (lo + Math.imul(al3, bl7)) | 0; mid = (mid + Math.imul(al3, bh7)) | 0; mid = (mid + Math.imul(ah3, bl7)) | 0; hi = (hi + Math.imul(ah3, bh7)) | 0; lo = (lo + Math.imul(al2, bl8)) | 0; mid = (mid + Math.imul(al2, bh8)) | 0; mid = (mid + Math.imul(ah2, bl8)) | 0; hi = (hi + Math.imul(ah2, bh8)) | 0; lo = (lo + Math.imul(al1, bl9)) | 0; mid = (mid + Math.imul(al1, bh9)) | 0; mid = (mid + Math.imul(ah1, bl9)) | 0; hi = (hi + Math.imul(ah1, bh9)) | 0; var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; w10 &= 0x3ffffff; /* k = 11 */ lo = Math.imul(al9, bl2); mid = Math.imul(al9, bh2); mid = (mid + Math.imul(ah9, bl2)) | 0; hi = Math.imul(ah9, bh2); lo = (lo + Math.imul(al8, bl3)) | 0; mid = (mid + Math.imul(al8, bh3)) | 0; mid = (mid + Math.imul(ah8, bl3)) | 0; hi = (hi + Math.imul(ah8, bh3)) | 0; lo = (lo + Math.imul(al7, bl4)) | 0; mid = (mid + Math.imul(al7, bh4)) | 0; mid = (mid + Math.imul(ah7, bl4)) | 0; hi = (hi + Math.imul(ah7, bh4)) | 0; lo = (lo + Math.imul(al6, bl5)) | 0; mid = (mid + Math.imul(al6, bh5)) | 0; mid = (mid + Math.imul(ah6, bl5)) | 0; hi = (hi + Math.imul(ah6, bh5)) | 0; lo = (lo + Math.imul(al5, bl6)) | 0; mid = (mid + Math.imul(al5, bh6)) | 0; mid = (mid + Math.imul(ah5, bl6)) | 0; hi = (hi + Math.imul(ah5, bh6)) | 0; lo = (lo + Math.imul(al4, bl7)) | 0; mid = (mid + Math.imul(al4, bh7)) | 0; mid = (mid + Math.imul(ah4, bl7)) | 0; hi = (hi + Math.imul(ah4, bh7)) | 0; lo = (lo + Math.imul(al3, bl8)) | 0; mid = (mid + Math.imul(al3, bh8)) | 0; mid = (mid + Math.imul(ah3, bl8)) | 0; hi = (hi + Math.imul(ah3, bh8)) | 0; lo = (lo + Math.imul(al2, bl9)) | 0; mid = (mid + Math.imul(al2, bh9)) | 0; mid = (mid + Math.imul(ah2, bl9)) | 0; hi = (hi + Math.imul(ah2, bh9)) | 0; var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; w11 &= 0x3ffffff; /* k = 12 */ lo = Math.imul(al9, bl3); mid = Math.imul(al9, bh3); mid = (mid + Math.imul(ah9, bl3)) | 0; hi = Math.imul(ah9, bh3); lo = (lo + Math.imul(al8, bl4)) | 0; mid = (mid + Math.imul(al8, bh4)) | 0; mid = (mid + Math.imul(ah8, bl4)) | 0; hi = (hi + Math.imul(ah8, bh4)) | 0; lo = (lo + Math.imul(al7, bl5)) | 0; mid = (mid + Math.imul(al7, bh5)) | 0; mid = (mid + Math.imul(ah7, bl5)) | 0; hi = (hi + Math.imul(ah7, bh5)) | 0; lo = (lo + Math.imul(al6, bl6)) | 0; mid = (mid + Math.imul(al6, bh6)) | 0; mid = (mid + Math.imul(ah6, bl6)) | 0; hi = (hi + Math.imul(ah6, bh6)) | 0; lo = (lo + Math.imul(al5, bl7)) | 0; mid = (mid + Math.imul(al5, bh7)) | 0; mid = (mid + Math.imul(ah5, bl7)) | 0; hi = (hi + Math.imul(ah5, bh7)) | 0; lo = (lo + Math.imul(al4, bl8)) | 0; mid = (mid + Math.imul(al4, bh8)) | 0; mid = (mid + Math.imul(ah4, bl8)) | 0; hi = (hi + Math.imul(ah4, bh8)) | 0; lo = (lo + Math.imul(al3, bl9)) | 0; mid = (mid + Math.imul(al3, bh9)) | 0; mid = (mid + Math.imul(ah3, bl9)) | 0; hi = (hi + Math.imul(ah3, bh9)) | 0; var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; w12 &= 0x3ffffff; /* k = 13 */ lo = Math.imul(al9, bl4); mid = Math.imul(al9, bh4); mid = (mid + Math.imul(ah9, bl4)) | 0; hi = Math.imul(ah9, bh4); lo = (lo + Math.imul(al8, bl5)) | 0; mid = (mid + Math.imul(al8, bh5)) | 0; mid = (mid + Math.imul(ah8, bl5)) | 0; hi = (hi + Math.imul(ah8, bh5)) | 0; lo = (lo + Math.imul(al7, bl6)) | 0; mid = (mid + Math.imul(al7, bh6)) | 0; mid = (mid + Math.imul(ah7, bl6)) | 0; hi = (hi + Math.imul(ah7, bh6)) | 0; lo = (lo + Math.imul(al6, bl7)) | 0; mid = (mid + Math.imul(al6, bh7)) | 0; mid = (mid + Math.imul(ah6, bl7)) | 0; hi = (hi + Math.imul(ah6, bh7)) | 0; lo = (lo + Math.imul(al5, bl8)) | 0; mid = (mid + Math.imul(al5, bh8)) | 0; mid = (mid + Math.imul(ah5, bl8)) | 0; hi = (hi + Math.imul(ah5, bh8)) | 0; lo = (lo + Math.imul(al4, bl9)) | 0; mid = (mid + Math.imul(al4, bh9)) | 0; mid = (mid + Math.imul(ah4, bl9)) | 0; hi = (hi + Math.imul(ah4, bh9)) | 0; var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; w13 &= 0x3ffffff; /* k = 14 */ lo = Math.imul(al9, bl5); mid = Math.imul(al9, bh5); mid = (mid + Math.imul(ah9, bl5)) | 0; hi = Math.imul(ah9, bh5); lo = (lo + Math.imul(al8, bl6)) | 0; mid = (mid + Math.imul(al8, bh6)) | 0; mid = (mid + Math.imul(ah8, bl6)) | 0; hi = (hi + Math.imul(ah8, bh6)) | 0; lo = (lo + Math.imul(al7, bl7)) | 0; mid = (mid + Math.imul(al7, bh7)) | 0; mid = (mid + Math.imul(ah7, bl7)) | 0; hi = (hi + Math.imul(ah7, bh7)) | 0; lo = (lo + Math.imul(al6, bl8)) | 0; mid = (mid + Math.imul(al6, bh8)) | 0; mid = (mid + Math.imul(ah6, bl8)) | 0; hi = (hi + Math.imul(ah6, bh8)) | 0; lo = (lo + Math.imul(al5, bl9)) | 0; mid = (mid + Math.imul(al5, bh9)) | 0; mid = (mid + Math.imul(ah5, bl9)) | 0; hi = (hi + Math.imul(ah5, bh9)) | 0; var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; w14 &= 0x3ffffff; /* k = 15 */ lo = Math.imul(al9, bl6); mid = Math.imul(al9, bh6); mid = (mid + Math.imul(ah9, bl6)) | 0; hi = Math.imul(ah9, bh6); lo = (lo + Math.imul(al8, bl7)) | 0; mid = (mid + Math.imul(al8, bh7)) | 0; mid = (mid + Math.imul(ah8, bl7)) | 0; hi = (hi + Math.imul(ah8, bh7)) | 0; lo = (lo + Math.imul(al7, bl8)) | 0; mid = (mid + Math.imul(al7, bh8)) | 0; mid = (mid + Math.imul(ah7, bl8)) | 0; hi = (hi + Math.imul(ah7, bh8)) | 0; lo = (lo + Math.imul(al6, bl9)) | 0; mid = (mid + Math.imul(al6, bh9)) | 0; mid = (mid + Math.imul(ah6, bl9)) | 0; hi = (hi + Math.imul(ah6, bh9)) | 0; var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; w15 &= 0x3ffffff; /* k = 16 */ lo = Math.imul(al9, bl7); mid = Math.imul(al9, bh7); mid = (mid + Math.imul(ah9, bl7)) | 0; hi = Math.imul(ah9, bh7); lo = (lo + Math.imul(al8, bl8)) | 0; mid = (mid + Math.imul(al8, bh8)) | 0; mid = (mid + Math.imul(ah8, bl8)) | 0; hi = (hi + Math.imul(ah8, bh8)) | 0; lo = (lo + Math.imul(al7, bl9)) | 0; mid = (mid + Math.imul(al7, bh9)) | 0; mid = (mid + Math.imul(ah7, bl9)) | 0; hi = (hi + Math.imul(ah7, bh9)) | 0; var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; w16 &= 0x3ffffff; /* k = 17 */ lo = Math.imul(al9, bl8); mid = Math.imul(al9, bh8); mid = (mid + Math.imul(ah9, bl8)) | 0; hi = Math.imul(ah9, bh8); lo = (lo + Math.imul(al8, bl9)) | 0; mid = (mid + Math.imul(al8, bh9)) | 0; mid = (mid + Math.imul(ah8, bl9)) | 0; hi = (hi + Math.imul(ah8, bh9)) | 0; var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; w17 &= 0x3ffffff; /* k = 18 */ lo = Math.imul(al9, bl9); mid = Math.imul(al9, bh9); mid = (mid + Math.imul(ah9, bl9)) | 0; hi = Math.imul(ah9, bh9); var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; w18 &= 0x3ffffff; o[0] = w0; o[1] = w1; o[2] = w2; o[3] = w3; o[4] = w4; o[5] = w5; o[6] = w6; o[7] = w7; o[8] = w8; o[9] = w9; o[10] = w10; o[11] = w11; o[12] = w12; o[13] = w13; o[14] = w14; o[15] = w15; o[16] = w16; o[17] = w17; o[18] = w18; if (c !== 0) { o[19] = c; out.length++; } return out; }; // Polyfill comb if (!Math.imul) { comb10MulTo = smallMulTo; } function bigMulTo (self, num, out) { out.negative = num.negative ^ self.negative; out.length = self.length + num.length; var carry = 0; var hncarry = 0; for (var k = 0; k < out.length - 1; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff var ncarry = hncarry; hncarry = 0; var rword = carry & 0x3ffffff; var maxJ = Math.min(k, num.length - 1); for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { var i = k - j; var a = self.words[i] | 0; var b = num.words[j] | 0; var r = a * b; var lo = r & 0x3ffffff; ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; lo = (lo + rword) | 0; rword = lo & 0x3ffffff; ncarry = (ncarry + (lo >>> 26)) | 0; hncarry += ncarry >>> 26; ncarry &= 0x3ffffff; } out.words[k] = rword; carry = ncarry; ncarry = hncarry; } if (carry !== 0) { out.words[k] = carry; } else { out.length--; } return out.strip(); } function jumboMulTo (self, num, out) { var fftm = new FFTM(); return fftm.mulp(self, num, out); } BN.prototype.mulTo = function mulTo (num, out) { var res; var len = this.length + num.length; if (this.length === 10 && num.length === 10) { res = comb10MulTo(this, num, out); } else if (len < 63) { res = smallMulTo(this, num, out); } else if (len < 1024) { res = bigMulTo(this, num, out); } else { res = jumboMulTo(this, num, out); } return res; }; // Cooley-Tukey algorithm for FFT // slightly revisited to rely on looping instead of recursion function FFTM (x, y) { this.x = x; this.y = y; } FFTM.prototype.makeRBT = function makeRBT (N) { var t = new Array(N); var l = BN.prototype._countBits(N) - 1; for (var i = 0; i < N; i++) { t[i] = this.revBin(i, l, N); } return t; }; // Returns binary-reversed representation of `x` FFTM.prototype.revBin = function revBin (x, l, N) { if (x === 0 || x === N - 1) return x; var rb = 0; for (var i = 0; i < l; i++) { rb |= (x & 1) << (l - i - 1); x >>= 1; } return rb; }; // Performs "tweedling" phase, therefore 'emulating' // behaviour of the recursive algorithm FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { for (var i = 0; i < N; i++) { rtws[i] = rws[rbt[i]]; itws[i] = iws[rbt[i]]; } }; FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { this.permute(rbt, rws, iws, rtws, itws, N); for (var s = 1; s < N; s <<= 1) { var l = s << 1; var rtwdf = Math.cos(2 * Math.PI / l); var itwdf = Math.sin(2 * Math.PI / l); for (var p = 0; p < N; p += l) { var rtwdf_ = rtwdf; var itwdf_ = itwdf; for (var j = 0; j < s; j++) { var re = rtws[p + j]; var ie = itws[p + j]; var ro = rtws[p + j + s]; var io = itws[p + j + s]; var rx = rtwdf_ * ro - itwdf_ * io; io = rtwdf_ * io + itwdf_ * ro; ro = rx; rtws[p + j] = re + ro; itws[p + j] = ie + io; rtws[p + j + s] = re - ro; itws[p + j + s] = ie - io; /* jshint maxdepth : false */ if (j !== l) { rx = rtwdf * rtwdf_ - itwdf * itwdf_; itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; rtwdf_ = rx; } } } } }; FFTM.prototype.guessLen13b = function guessLen13b (n, m) { var N = Math.max(m, n) | 1; var odd = N & 1; var i = 0; for (N = N / 2 | 0; N; N = N >>> 1) { i++; } return 1 << i + 1 + odd; }; FFTM.prototype.conjugate = function conjugate (rws, iws, N) { if (N <= 1) return; for (var i = 0; i < N / 2; i++) { var t = rws[i]; rws[i] = rws[N - i - 1]; rws[N - i - 1] = t; t = iws[i]; iws[i] = -iws[N - i - 1]; iws[N - i - 1] = -t; } }; FFTM.prototype.normalize13b = function normalize13b (ws, N) { var carry = 0; for (var i = 0; i < N / 2; i++) { var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + Math.round(ws[2 * i] / N) + carry; ws[i] = w & 0x3ffffff; if (w < 0x4000000) { carry = 0; } else { carry = w / 0x4000000 | 0; } } return ws; }; FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { var carry = 0; for (var i = 0; i < len; i++) { carry = carry + (ws[i] | 0); rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; } // Pad with zeroes for (i = 2 * len; i < N; ++i) { rws[i] = 0; } assert(carry === 0); assert((carry & ~0x1fff) === 0); }; FFTM.prototype.stub = function stub (N) { var ph = new Array(N); for (var i = 0; i < N; i++) { ph[i] = 0; } return ph; }; FFTM.prototype.mulp = function mulp (x, y, out) { var N = 2 * this.guessLen13b(x.length, y.length); var rbt = this.makeRBT(N); var _ = this.stub(N); var rws = new Array(N); var rwst = new Array(N); var iwst = new Array(N); var nrws = new Array(N); var nrwst = new Array(N); var niwst = new Array(N); var rmws = out.words; rmws.length = N; this.convert13b(x.words, x.length, rws, N); this.convert13b(y.words, y.length, nrws, N); this.transform(rws, _, rwst, iwst, N, rbt); this.transform(nrws, _, nrwst, niwst, N, rbt); for (var i = 0; i < N; i++) { var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; rwst[i] = rx; } this.conjugate(rwst, iwst, N); this.transform(rwst, iwst, rmws, _, N, rbt); this.conjugate(rmws, _, N); this.normalize13b(rmws, N); out.negative = x.negative ^ y.negative; out.length = x.length + y.length; return out.strip(); }; // Multiply `this` by `num` BN.prototype.mul = function mul (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return this.mulTo(num, out); }; // Multiply employing FFT BN.prototype.mulf = function mulf (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return jumboMulTo(this, num, out); }; // In-place Multiplication BN.prototype.imul = function imul (num) { return this.clone().mulTo(num, this); }; BN.prototype.imuln = function imuln (num) { assert(typeof num === 'number'); assert(num < 0x4000000); // Carry var carry = 0; for (var i = 0; i < this.length; i++) { var w = (this.words[i] | 0) * num; var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); carry >>= 26; carry += (w / 0x4000000) | 0; // NOTE: lo is 27bit maximum carry += lo >>> 26; this.words[i] = lo & 0x3ffffff; } if (carry !== 0) { this.words[i] = carry; this.length++; } return this; }; BN.prototype.muln = function muln (num) { return this.clone().imuln(num); }; // `this` * `this` BN.prototype.sqr = function sqr () { return this.mul(this); }; // `this` * `this` in-place BN.prototype.isqr = function isqr () { return this.imul(this.clone()); }; // Math.pow(`this`, `num`) BN.prototype.pow = function pow (num) { var w = toBitArray(num); if (w.length === 0) return new BN(1); // Skip leading zeroes var res = this; for (var i = 0; i < w.length; i++, res = res.sqr()) { if (w[i] !== 0) break; } if (++i < w.length) { for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { if (w[i] === 0) continue; res = res.mul(q); } } return res; }; // Shift-left in-place BN.prototype.iushln = function iushln (bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); var i; if (r !== 0) { var carry = 0; for (i = 0; i < this.length; i++) { var newCarry = this.words[i] & carryMask; var c = ((this.words[i] | 0) - newCarry) << r; this.words[i] = c | carry; carry = newCarry >>> (26 - r); } if (carry) { this.words[i] = carry; this.length++; } } if (s !== 0) { for (i = this.length - 1; i >= 0; i--) { this.words[i + s] = this.words[i]; } for (i = 0; i < s; i++) { this.words[i] = 0; } this.length += s; } return this.strip(); }; BN.prototype.ishln = function ishln (bits) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushln(bits); }; // Shift-right in-place // NOTE: `hint` is a lowest bit before trailing zeroes // NOTE: if `extended` is present - it will be filled with destroyed bits BN.prototype.iushrn = function iushrn (bits, hint, extended) { assert(typeof bits === 'number' && bits >= 0); var h; if (hint) { h = (hint - (hint % 26)) / 26; } else { h = 0; } var r = bits % 26; var s = Math.min((bits - r) / 26, this.length); var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); var maskedWords = extended; h -= s; h = Math.max(0, h); // Extended mode, copy masked part if (maskedWords) { for (var i = 0; i < s; i++) { maskedWords.words[i] = this.words[i]; } maskedWords.length = s; } if (s === 0) { // No-op, we should not move anything at all } else if (this.length > s) { this.length -= s; for (i = 0; i < this.length; i++) { this.words[i] = this.words[i + s]; } } else { this.words[0] = 0; this.length = 1; } var carry = 0; for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { var word = this.words[i] | 0; this.words[i] = (carry << (26 - r)) | (word >>> r); carry = word & mask; } // Push carried bits as a mask if (maskedWords && carry !== 0) { maskedWords.words[maskedWords.length++] = carry; } if (this.length === 0) { this.words[0] = 0; this.length = 1; } return this.strip(); }; BN.prototype.ishrn = function ishrn (bits, hint, extended) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushrn(bits, hint, extended); }; // Shift-left BN.prototype.shln = function shln (bits) { return this.clone().ishln(bits); }; BN.prototype.ushln = function ushln (bits) { return this.clone().iushln(bits); }; // Shift-right BN.prototype.shrn = function shrn (bits) { return this.clone().ishrn(bits); }; BN.prototype.ushrn = function ushrn (bits) { return this.clone().iushrn(bits); }; // Test if n bit is set BN.prototype.testn = function testn (bit) { assert(typeof bit === 'number' && bit >= 0); var r = bit % 26; var s = (bit - r) / 26; var q = 1 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) return false; // Check bit and return var w = this.words[s]; return !!(w & q); }; // Return only lowers bits of number (in-place) BN.prototype.imaskn = function imaskn (bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; assert(this.negative === 0, 'imaskn works only with positive numbers'); if (this.length <= s) { return this; } if (r !== 0) { s++; } this.length = Math.min(s, this.length); if (r !== 0) { var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); this.words[this.length - 1] &= mask; } return this.strip(); }; // Return only lowers bits of number BN.prototype.maskn = function maskn (bits) { return this.clone().imaskn(bits); }; // Add plain number `num` to `this` BN.prototype.iaddn = function iaddn (num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.isubn(-num); // Possible sign change if (this.negative !== 0) { if (this.length === 1 && (this.words[0] | 0) < num) { this.words[0] = num - (this.words[0] | 0); this.negative = 0; return this; } this.negative = 0; this.isubn(num); this.negative = 1; return this; } // Add without checks return this._iaddn(num); }; BN.prototype._iaddn = function _iaddn (num) { this.words[0] += num; // Carry for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { this.words[i] -= 0x4000000; if (i === this.length - 1) { this.words[i + 1] = 1; } else { this.words[i + 1]++; } } this.length = Math.max(this.length, i + 1); return this; }; // Subtract plain number `num` from `this` BN.prototype.isubn = function isubn (num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.iaddn(-num); if (this.negative !== 0) { this.negative = 0; this.iaddn(num); this.negative = 1; return this; } this.words[0] -= num; if (this.length === 1 && this.words[0] < 0) { this.words[0] = -this.words[0]; this.negative = 1; } else { // Carry for (var i = 0; i < this.length && this.words[i] < 0; i++) { this.words[i] += 0x4000000; this.words[i + 1] -= 1; } } return this.strip(); }; BN.prototype.addn = function addn (num) { return this.clone().iaddn(num); }; BN.prototype.subn = function subn (num) { return this.clone().isubn(num); }; BN.prototype.iabs = function iabs () { this.negative = 0; return this; }; BN.prototype.abs = function abs () { return this.clone().iabs(); }; BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { var len = num.length + shift; var i; this._expand(len); var w; var carry = 0; for (i = 0; i < num.length; i++) { w = (this.words[i + shift] | 0) + carry; var right = (num.words[i] | 0) * mul; w -= right & 0x3ffffff; carry = (w >> 26) - ((right / 0x4000000) | 0); this.words[i + shift] = w & 0x3ffffff; } for (; i < this.length - shift; i++) { w = (this.words[i + shift] | 0) + carry; carry = w >> 26; this.words[i + shift] = w & 0x3ffffff; } if (carry === 0) return this.strip(); // Subtraction overflow assert(carry === -1); carry = 0; for (i = 0; i < this.length; i++) { w = -(this.words[i] | 0) + carry; carry = w >> 26; this.words[i] = w & 0x3ffffff; } this.negative = 1; return this.strip(); }; BN.prototype._wordDiv = function _wordDiv (num, mode) { var shift = this.length - num.length; var a = this.clone(); var b = num; // Normalize var bhi = b.words[b.length - 1] | 0; var bhiBits = this._countBits(bhi); shift = 26 - bhiBits; if (shift !== 0) { b = b.ushln(shift); a.iushln(shift); bhi = b.words[b.length - 1] | 0; } // Initialize quotient var m = a.length - b.length; var q; if (mode !== 'mod') { q = new BN(null); q.length = m + 1; q.words = new Array(q.length); for (var i = 0; i < q.length; i++) { q.words[i] = 0; } } var diff = a.clone()._ishlnsubmul(b, 1, m); if (diff.negative === 0) { a = diff; if (q) { q.words[m] = 1; } } for (var j = m - 1; j >= 0; j--) { var qj = (a.words[b.length + j] | 0) * 0x4000000 + (a.words[b.length + j - 1] | 0); // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max // (0x7ffffff) qj = Math.min((qj / bhi) | 0, 0x3ffffff); a._ishlnsubmul(b, qj, j); while (a.negative !== 0) { qj--; a.negative = 0; a._ishlnsubmul(b, 1, j); if (!a.isZero()) { a.negative ^= 1; } } if (q) { q.words[j] = qj; } } if (q) { q.strip(); } a.strip(); // Denormalize if (mode !== 'div' && shift !== 0) { a.iushrn(shift); } return { div: q || null, mod: a }; }; // NOTE: 1) `mode` can be set to `mod` to request mod only, // to `div` to request div only, or be absent to // request both div & mod // 2) `positive` is true if unsigned mod is requested BN.prototype.divmod = function divmod (num, mode, positive) { assert(!num.isZero()); if (this.isZero()) { return { div: new BN(0), mod: new BN(0) }; } var div, mod, res; if (this.negative !== 0 && num.negative === 0) { res = this.neg().divmod(num, mode); if (mode !== 'mod') { div = res.div.neg(); } if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.iadd(num); } } return { div: div, mod: mod }; } if (this.negative === 0 && num.negative !== 0) { res = this.divmod(num.neg(), mode); if (mode !== 'mod') { div = res.div.neg(); } return { div: div, mod: res.mod }; } if ((this.negative & num.negative) !== 0) { res = this.neg().divmod(num.neg(), mode); if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.isub(num); } } return { div: res.div, mod: mod }; } // Both numbers are positive at this point // Strip both numbers to approximate shift value if (num.length > this.length || this.cmp(num) < 0) { return { div: new BN(0), mod: this }; } // Very short reduction if (num.length === 1) { if (mode === 'div') { return { div: this.divn(num.words[0]), mod: null }; } if (mode === 'mod') { return { div: null, mod: new BN(this.modn(num.words[0])) }; } return { div: this.divn(num.words[0]), mod: new BN(this.modn(num.words[0])) }; } return this._wordDiv(num, mode); }; // Find `this` / `num` BN.prototype.div = function div (num) { return this.divmod(num, 'div', false).div; }; // Find `this` % `num` BN.prototype.mod = function mod (num) { return this.divmod(num, 'mod', false).mod; }; BN.prototype.umod = function umod (num) { return this.divmod(num, 'mod', true).mod; }; // Find Round(`this` / `num`) BN.prototype.divRound = function divRound (num) { var dm = this.divmod(num); // Fast case - exact division if (dm.mod.isZero()) return dm.div; var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; var half = num.ushrn(1); var r2 = num.andln(1); var cmp = mod.cmp(half); // Round down if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; // Round up return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); }; BN.prototype.modn = function modn (num) { assert(num <= 0x3ffffff); var p = (1 << 26) % num; var acc = 0; for (var i = this.length - 1; i >= 0; i--) { acc = (p * acc + (this.words[i] | 0)) % num; } return acc; }; // In-place division by number BN.prototype.idivn = function idivn (num) { assert(num <= 0x3ffffff); var carry = 0; for (var i = this.length - 1; i >= 0; i--) { var w = (this.words[i] | 0) + carry * 0x4000000; this.words[i] = (w / num) | 0; carry = w % num; } return this.strip(); }; BN.prototype.divn = function divn (num) { return this.clone().idivn(num); }; BN.prototype.egcd = function egcd (p) { assert(p.negative === 0); assert(!p.isZero()); var x = this; var y = p.clone(); if (x.negative !== 0) { x = x.umod(p); } else { x = x.clone(); } // A * x + B * y = x var A = new BN(1); var B = new BN(0); // C * x + D * y = y var C = new BN(0); var D = new BN(1); var g = 0; while (x.isEven() && y.isEven()) { x.iushrn(1); y.iushrn(1); ++g; } var yp = y.clone(); var xp = x.clone(); while (!x.isZero()) { for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); if (i > 0) { x.iushrn(i); while (i-- > 0) { if (A.isOdd() || B.isOdd()) { A.iadd(yp); B.isub(xp); } A.iushrn(1); B.iushrn(1); } } for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); if (j > 0) { y.iushrn(j); while (j-- > 0) { if (C.isOdd() || D.isOdd()) { C.iadd(yp); D.isub(xp); } C.iushrn(1); D.iushrn(1); } } if (x.cmp(y) >= 0) { x.isub(y); A.isub(C); B.isub(D); } else { y.isub(x); C.isub(A); D.isub(B); } } return { a: C, b: D, gcd: y.iushln(g) }; }; // This is reduced incarnation of the binary EEA // above, designated to invert members of the // _prime_ fields F(p) at a maximal speed BN.prototype._invmp = function _invmp (p) { assert(p.negative === 0); assert(!p.isZero()); var a = this; var b = p.clone(); if (a.negative !== 0) { a = a.umod(p); } else { a = a.clone(); } var x1 = new BN(1); var x2 = new BN(0); var delta = b.clone(); while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); if (i > 0) { a.iushrn(i); while (i-- > 0) { if (x1.isOdd()) { x1.iadd(delta); } x1.iushrn(1); } } for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); if (j > 0) { b.iushrn(j); while (j-- > 0) { if (x2.isOdd()) { x2.iadd(delta); } x2.iushrn(1); } } if (a.cmp(b) >= 0) { a.isub(b); x1.isub(x2); } else { b.isub(a); x2.isub(x1); } } var res; if (a.cmpn(1) === 0) { res = x1; } else { res = x2; } if (res.cmpn(0) < 0) { res.iadd(p); } return res; }; BN.prototype.gcd = function gcd (num) { if (this.isZero()) return num.abs(); if (num.isZero()) return this.abs(); var a = this.clone(); var b = num.clone(); a.negative = 0; b.negative = 0; // Remove common factor of two for (var shift = 0; a.isEven() && b.isEven(); shift++) { a.iushrn(1); b.iushrn(1); } do { while (a.isEven()) { a.iushrn(1); } while (b.isEven()) { b.iushrn(1); } var r = a.cmp(b); if (r < 0) { // Swap `a` and `b` to make `a` always bigger than `b` var t = a; a = b; b = t; } else if (r === 0 || b.cmpn(1) === 0) { break; } a.isub(b); } while (true); return b.iushln(shift); }; // Invert number in the field F(num) BN.prototype.invm = function invm (num) { return this.egcd(num).a.umod(num); }; BN.prototype.isEven = function isEven () { return (this.words[0] & 1) === 0; }; BN.prototype.isOdd = function isOdd () { return (this.words[0] & 1) === 1; }; // And first word and num BN.prototype.andln = function andln (num) { return this.words[0] & num; }; // Increment at the bit position in-line BN.prototype.bincn = function bincn (bit) { assert(typeof bit === 'number'); var r = bit % 26; var s = (bit - r) / 26; var q = 1 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) { this._expand(s + 1); this.words[s] |= q; return this; } // Add bit and propagate, if needed var carry = q; for (var i = s; carry !== 0 && i < this.length; i++) { var w = this.words[i] | 0; w += carry; carry = w >>> 26; w &= 0x3ffffff; this.words[i] = w; } if (carry !== 0) { this.words[i] = carry; this.length++; } return this; }; BN.prototype.isZero = function isZero () { return this.length === 1 && this.words[0] === 0; }; BN.prototype.cmpn = function cmpn (num) { var negative = num < 0; if (this.negative !== 0 && !negative) return -1; if (this.negative === 0 && negative) return 1; this.strip(); var res; if (this.length > 1) { res = 1; } else { if (negative) { num = -num; } assert(num <= 0x3ffffff, 'Number is too big'); var w = this.words[0] | 0; res = w === num ? 0 : w < num ? -1 : 1; } if (this.negative !== 0) return -res | 0; return res; }; // Compare two numbers and return: // 1 - if `this` > `num` // 0 - if `this` == `num` // -1 - if `this` < `num` BN.prototype.cmp = function cmp (num) { if (this.negative !== 0 && num.negative === 0) return -1; if (this.negative === 0 && num.negative !== 0) return 1; var res = this.ucmp(num); if (this.negative !== 0) return -res | 0; return res; }; // Unsigned comparison BN.prototype.ucmp = function ucmp (num) { // At this point both numbers have the same sign if (this.length > num.length) return 1; if (this.length < num.length) return -1; var res = 0; for (var i = this.length - 1; i >= 0; i--) { var a = this.words[i] | 0; var b = num.words[i] | 0; if (a === b) continue; if (a < b) { res = -1; } else if (a > b) { res = 1; } break; } return res; }; BN.prototype.gtn = function gtn (num) { return this.cmpn(num) === 1; }; BN.prototype.gt = function gt (num) { return this.cmp(num) === 1; }; BN.prototype.gten = function gten (num) { return this.cmpn(num) >= 0; }; BN.prototype.gte = function gte (num) { return this.cmp(num) >= 0; }; BN.prototype.ltn = function ltn (num) { return this.cmpn(num) === -1; }; BN.prototype.lt = function lt (num) { return this.cmp(num) === -1; }; BN.prototype.lten = function lten (num) { return this.cmpn(num) <= 0; }; BN.prototype.lte = function lte (num) { return this.cmp(num) <= 0; }; BN.prototype.eqn = function eqn (num) { return this.cmpn(num) === 0; }; BN.prototype.eq = function eq (num) { return this.cmp(num) === 0; }; // // A reduce context, could be using montgomery or something better, depending // on the `m` itself. // BN.red = function red (num) { return new Red(num); }; BN.prototype.toRed = function toRed (ctx) { assert(!this.red, 'Already a number in reduction context'); assert(this.negative === 0, 'red works only with positives'); return ctx.convertTo(this)._forceRed(ctx); }; BN.prototype.fromRed = function fromRed () { assert(this.red, 'fromRed works only with numbers in reduction context'); return this.red.convertFrom(this); }; BN.prototype._forceRed = function _forceRed (ctx) { this.red = ctx; return this; }; BN.prototype.forceRed = function forceRed (ctx) { assert(!this.red, 'Already a number in reduction context'); return this._forceRed(ctx); }; BN.prototype.redAdd = function redAdd (num) { assert(this.red, 'redAdd works only with red numbers'); return this.red.add(this, num); }; BN.prototype.redIAdd = function redIAdd (num) { assert(this.red, 'redIAdd works only with red numbers'); return this.red.iadd(this, num); }; BN.prototype.redSub = function redSub (num) { assert(this.red, 'redSub works only with red numbers'); return this.red.sub(this, num); }; BN.prototype.redISub = function redISub (num) { assert(this.red, 'redISub works only with red numbers'); return this.red.isub(this, num); }; BN.prototype.redShl = function redShl (num) { assert(this.red, 'redShl works only with red numbers'); return this.red.shl(this, num); }; BN.prototype.redMul = function redMul (num) { assert(this.red, 'redMul works only with red numbers'); this.red._verify2(this, num); return this.red.mul(this, num); }; BN.prototype.redIMul = function redIMul (num) { assert(this.red, 'redMul works only with red numbers'); this.red._verify2(this, num); return this.red.imul(this, num); }; BN.prototype.redSqr = function redSqr () { assert(this.red, 'redSqr works only with red numbers'); this.red._verify1(this); return this.red.sqr(this); }; BN.prototype.redISqr = function redISqr () { assert(this.red, 'redISqr works only with red numbers'); this.red._verify1(this); return this.red.isqr(this); }; // Square root over p BN.prototype.redSqrt = function redSqrt () { assert(this.red, 'redSqrt works only with red numbers'); this.red._verify1(this); return this.red.sqrt(this); }; BN.prototype.redInvm = function redInvm () { assert(this.red, 'redInvm works only with red numbers'); this.red._verify1(this); return this.red.invm(this); }; // Return negative clone of `this` % `red modulo` BN.prototype.redNeg = function redNeg () { assert(this.red, 'redNeg works only with red numbers'); this.red._verify1(this); return this.red.neg(this); }; BN.prototype.redPow = function redPow (num) { assert(this.red && !num.red, 'redPow(normalNum)'); this.red._verify1(this); return this.red.pow(this, num); }; // Prime numbers with efficient reduction var primes = { k256: null, p224: null, p192: null, p25519: null }; // Pseudo-Mersenne prime function MPrime (name, p) { // P = 2 ^ N - K this.name = name; this.p = new BN(p, 16); this.n = this.p.bitLength(); this.k = new BN(1).iushln(this.n).isub(this.p); this.tmp = this._tmp(); } MPrime.prototype._tmp = function _tmp () { var tmp = new BN(null); tmp.words = new Array(Math.ceil(this.n / 13)); return tmp; }; MPrime.prototype.ireduce = function ireduce (num) { // Assumes that `num` is less than `P^2` // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) var r = num; var rlen; do { this.split(r, this.tmp); r = this.imulK(r); r = r.iadd(this.tmp); rlen = r.bitLength(); } while (rlen > this.n); var cmp = rlen < this.n ? -1 : r.ucmp(this.p); if (cmp === 0) { r.words[0] = 0; r.length = 1; } else if (cmp > 0) { r.isub(this.p); } else { r.strip(); } return r; }; MPrime.prototype.split = function split (input, out) { input.iushrn(this.n, 0, out); }; MPrime.prototype.imulK = function imulK (num) { return num.imul(this.k); }; function K256 () { MPrime.call( this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); } inherits(K256, MPrime); K256.prototype.split = function split (input, output) { // 256 = 9 * 26 + 22 var mask = 0x3fffff; var outLen = Math.min(input.length, 9); for (var i = 0; i < outLen; i++) { output.words[i] = input.words[i]; } output.length = outLen; if (input.length <= 9) { input.words[0] = 0; input.length = 1; return; } // Shift by 9 limbs var prev = input.words[9]; output.words[output.length++] = prev & mask; for (i = 10; i < input.length; i++) { var next = input.words[i] | 0; input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); prev = next; } prev >>>= 22; input.words[i - 10] = prev; if (prev === 0 && input.length > 10) { input.length -= 10; } else { input.length -= 9; } }; K256.prototype.imulK = function imulK (num) { // K = 0x1000003d1 = [ 0x40, 0x3d1 ] num.words[num.length] = 0; num.words[num.length + 1] = 0; num.length += 2; // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 var lo = 0; for (var i = 0; i < num.length; i++) { var w = num.words[i] | 0; lo += w * 0x3d1; num.words[i] = lo & 0x3ffffff; lo = w * 0x40 + ((lo / 0x4000000) | 0); } // Fast length reduction if (num.words[num.length - 1] === 0) { num.length--; if (num.words[num.length - 1] === 0) { num.length--; } } return num; }; function P224 () { MPrime.call( this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); } inherits(P224, MPrime); function P192 () { MPrime.call( this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); } inherits(P192, MPrime); function P25519 () { // 2 ^ 255 - 19 MPrime.call( this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); } inherits(P25519, MPrime); P25519.prototype.imulK = function imulK (num) { // K = 0x13 var carry = 0; for (var i = 0; i < num.length; i++) { var hi = (num.words[i] | 0) * 0x13 + carry; var lo = hi & 0x3ffffff; hi >>>= 26; num.words[i] = lo; carry = hi; } if (carry !== 0) { num.words[num.length++] = carry; } return num; }; // Exported mostly for testing purposes, use plain name instead BN._prime = function prime (name) { // Cached version of prime if (primes[name]) return primes[name]; var prime; if (name === 'k256') { prime = new K256(); } else if (name === 'p224') { prime = new P224(); } else if (name === 'p192') { prime = new P192(); } else if (name === 'p25519') { prime = new P25519(); } else { throw new Error('Unknown prime ' + name); } primes[name] = prime; return prime; }; // // Base reduction engine // function Red (m) { if (typeof m === 'string') { var prime = BN._prime(m); this.m = prime.p; this.prime = prime; } else { assert(m.gtn(1), 'modulus must be greater than 1'); this.m = m; this.prime = null; } } Red.prototype._verify1 = function _verify1 (a) { assert(a.negative === 0, 'red works only with positives'); assert(a.red, 'red works only with red numbers'); }; Red.prototype._verify2 = function _verify2 (a, b) { assert((a.negative | b.negative) === 0, 'red works only with positives'); assert(a.red && a.red === b.red, 'red works only with red numbers'); }; Red.prototype.imod = function imod (a) { if (this.prime) return this.prime.ireduce(a)._forceRed(this); return a.umod(this.m)._forceRed(this); }; Red.prototype.neg = function neg (a) { if (a.isZero()) { return a.clone(); } return this.m.sub(a)._forceRed(this); }; Red.prototype.add = function add (a, b) { this._verify2(a, b); var res = a.add(b); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res._forceRed(this); }; Red.prototype.iadd = function iadd (a, b) { this._verify2(a, b); var res = a.iadd(b); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res; }; Red.prototype.sub = function sub (a, b) { this._verify2(a, b); var res = a.sub(b); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res._forceRed(this); }; Red.prototype.isub = function isub (a, b) { this._verify2(a, b); var res = a.isub(b); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res; }; Red.prototype.shl = function shl (a, num) { this._verify1(a); return this.imod(a.ushln(num)); }; Red.prototype.imul = function imul (a, b) { this._verify2(a, b); return this.imod(a.imul(b)); }; Red.prototype.mul = function mul (a, b) { this._verify2(a, b); return this.imod(a.mul(b)); }; Red.prototype.isqr = function isqr (a) { return this.imul(a, a.clone()); }; Red.prototype.sqr = function sqr (a) { return this.mul(a, a); }; Red.prototype.sqrt = function sqrt (a) { if (a.isZero()) return a.clone(); var mod3 = this.m.andln(3); assert(mod3 % 2 === 1); // Fast case if (mod3 === 3) { var pow = this.m.add(new BN(1)).iushrn(2); return this.pow(a, pow); } // Tonelli-Shanks algorithm (Totally unoptimized and slow) // // Find Q and S, that Q * 2 ^ S = (P - 1) var q = this.m.subn(1); var s = 0; while (!q.isZero() && q.andln(1) === 0) { s++; q.iushrn(1); } assert(!q.isZero()); var one = new BN(1).toRed(this); var nOne = one.redNeg(); // Find quadratic non-residue // NOTE: Max is such because of generalized Riemann hypothesis. var lpow = this.m.subn(1).iushrn(1); var z = this.m.bitLength(); z = new BN(2 * z * z).toRed(this); while (this.pow(z, lpow).cmp(nOne) !== 0) { z.redIAdd(nOne); } var c = this.pow(z, q); var r = this.pow(a, q.addn(1).iushrn(1)); var t = this.pow(a, q); var m = s; while (t.cmp(one) !== 0) { var tmp = t; for (var i = 0; tmp.cmp(one) !== 0; i++) { tmp = tmp.redSqr(); } assert(i < m); var b = this.pow(c, new BN(1).iushln(m - i - 1)); r = r.redMul(b); c = b.redSqr(); t = t.redMul(c); m = i; } return r; }; Red.prototype.invm = function invm (a) { var inv = a._invmp(this.m); if (inv.negative !== 0) { inv.negative = 0; return this.imod(inv).redNeg(); } else { return this.imod(inv); } }; Red.prototype.pow = function pow (a, num) { if (num.isZero()) return new BN(1); if (num.cmpn(1) === 0) return a.clone(); var windowSize = 4; var wnd = new Array(1 << windowSize); wnd[0] = new BN(1).toRed(this); wnd[1] = a; for (var i = 2; i < wnd.length; i++) { wnd[i] = this.mul(wnd[i - 1], a); } var res = wnd[0]; var current = 0; var currentLen = 0; var start = num.bitLength() % 26; if (start === 0) { start = 26; } for (i = num.length - 1; i >= 0; i--) { var word = num.words[i]; for (var j = start - 1; j >= 0; j--) { var bit = (word >> j) & 1; if (res !== wnd[0]) { res = this.sqr(res); } if (bit === 0 && current === 0) { currentLen = 0; continue; } current <<= 1; current |= bit; currentLen++; if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; res = this.mul(res, wnd[current]); currentLen = 0; current = 0; } start = 26; } return res; }; Red.prototype.convertTo = function convertTo (num) { var r = num.umod(this.m); return r === num ? r.clone() : r; }; Red.prototype.convertFrom = function convertFrom (num) { var res = num.clone(); res.red = null; return res; }; // // Montgomery method engine // BN.mont = function mont (num) { return new Mont(num); }; function Mont (m) { Red.call(this, m); this.shift = this.m.bitLength(); if (this.shift % 26 !== 0) { this.shift += 26 - (this.shift % 26); } this.r = new BN(1).iushln(this.shift); this.r2 = this.imod(this.r.sqr()); this.rinv = this.r._invmp(this.m); this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); this.minv = this.minv.umod(this.r); this.minv = this.r.sub(this.minv); } inherits(Mont, Red); Mont.prototype.convertTo = function convertTo (num) { return this.imod(num.ushln(this.shift)); }; Mont.prototype.convertFrom = function convertFrom (num) { var r = this.imod(num.mul(this.rinv)); r.red = null; return r; }; Mont.prototype.imul = function imul (a, b) { if (a.isZero() || b.isZero()) { a.words[0] = 0; a.length = 1; return a; } var t = a.imul(b); var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u = t.isub(c).iushrn(this.shift); var res = u; if (u.cmp(this.m) >= 0) { res = u.isub(this.m); } else if (u.cmpn(0) < 0) { res = u.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.mul = function mul (a, b) { if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); var t = a.mul(b); var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u = t.isub(c).iushrn(this.shift); var res = u; if (u.cmp(this.m) >= 0) { res = u.isub(this.m); } else if (u.cmpn(0) < 0) { res = u.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.invm = function invm (a) { // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R var res = this.imod(a._invmp(this.m).mul(this.r2)); return res._forceRed(this); }; })(typeof module === 'undefined' || module, this); },{}],5:[function(require,module,exports){ },{}],6:[function(require,module,exports){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ /* eslint-disable no-proto */ 'use strict' var base64 = require('base64-js') var ieee754 = require('ieee754') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 var K_MAX_LENGTH = 0x7fffffff exports.kMaxLength = K_MAX_LENGTH /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Print warning and recommend using `buffer` v4.x which has an Object * implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * We report that the browser does not support typed arrays if the are not subclassable * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support * for __proto__ and has a buggy typed array implementation. */ Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() if (!Buffer.TYPED_ARRAY_SUPPORT) { console.error( 'This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.') } function typedArraySupport () { // Can typed array instances can be augmented? try { var arr = new Uint8Array(1) arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} return arr.foo() === 42 } catch (e) { return false } } function createBuffer (length) { if (length > K_MAX_LENGTH) { throw new RangeError('Invalid typed array length') } // Return an augmented `Uint8Array` instance var buf = new Uint8Array(length) buf.__proto__ = Buffer.prototype return buf } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer (arg, encodingOrOffset, length) { // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new Error( 'If encoding is specified then the first argument must be a string' ) } return allocUnsafe(arg) } return from(arg, encodingOrOffset, length) } // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 if (typeof Symbol !== 'undefined' && Symbol.species && Buffer[Symbol.species] === Buffer) { Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true, enumerable: false, writable: false }) } Buffer.poolSize = 8192 // not used by this implementation function from (value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { return fromArrayBuffer(value, encodingOrOffset, length) } if (typeof value === 'string') { return fromString(value, encodingOrOffset) } return fromObject(value) } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(value, encodingOrOffset, length) } // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: // https://github.com/feross/buffer/pull/148 Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be a number') } else if (size < 0) { throw new RangeError('"size" argument must not be negative') } } function alloc (size, fill, encoding) { assertSize(size) if (size <= 0) { return createBuffer(size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill) } return createBuffer(size) } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(size, fill, encoding) } function allocUnsafe (size) { assertSize(size) return createBuffer(size < 0 ? 0 : checked(size) | 0) } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(size) } /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(size) } function fromString (string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } var length = byteLength(string, encoding) | 0 var buf = createBuffer(length) var actual = buf.write(string, encoding) if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') buf = buf.slice(0, actual) } return buf } function fromArrayLike (array) { var length = array.length < 0 ? 0 : checked(array.length) | 0 var buf = createBuffer(length) for (var i = 0; i < length; i += 1) { buf[i] = array[i] & 255 } return buf } function fromArrayBuffer (array, byteOffset, length) { array.byteLength // this throws if `array` is not a valid ArrayBuffer if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('\'offset\' is out of bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('\'length\' is out of bounds') } var buf if (byteOffset === undefined && length === undefined) { buf = new Uint8Array(array) } else if (length === undefined) { buf = new Uint8Array(array, byteOffset) } else { buf = new Uint8Array(array, byteOffset, length) } // Return an augmented `Uint8Array` instance buf.__proto__ = Buffer.prototype return buf } function fromObject (obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0 var buf = createBuffer(len) if (buf.length === 0) { return buf } obj.copy(buf, 0, 0, len) return buf } if (obj) { if ((typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer) || 'length' in obj) { if (typeof obj.length !== 'number' || isnan(obj.length)) { return createBuffer(0) } return fromArrayLike(obj) } if (obj.type === 'Buffer' && Array.isArray(obj.data)) { return fromArrayLike(obj.data) } } throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } function checked (length) { // Note: cannot use `length < K_MAX_LENGTH` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= K_MAX_LENGTH) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') } return length | 0 } function SlowBuffer (length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0 } return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers') } if (a === b) return 0 var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i] y = b[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!Array.isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { return Buffer.alloc(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; ++i) { length += list[i].length } } var buffer = Buffer.allocUnsafe(length) var pos = 0 for (i = 0; i < list.length; ++i) { var buf = list[i] if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers') } buf.copy(buffer, pos) pos += buf.length } return buffer } function byteLength (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { string = '' + string } var len = string.length if (len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len case 'utf8': case 'utf-8': case undefined: return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) return utf8ToBytes(string).length // assume utf8 encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0 } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return '' } if (end === undefined || end > this.length) { end = this.length } if (end <= 0) { return '' } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0 start >>>= 0 if (end <= start) { return '' } if (!encoding) encoding = 'utf8' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'latin1': case 'binary': return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. Buffer.prototype._isBuffer = true function swap (b, n, m) { var i = b[n] b[n] = b[m] b[m] = i } Buffer.prototype.swap16 = function swap16 () { var len = this.length if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1) } return this } Buffer.prototype.swap32 = function swap32 () { var len = this.length if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3) swap(this, i + 1, i + 2) } return this } Buffer.prototype.swap64 = function swap64 () { var len = this.length if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7) swap(this, i + 1, i + 6) swap(this, i + 2, i + 5) swap(this, i + 3, i + 4) } return this } Buffer.prototype.toString = function toString () { var length = this.length if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '' } Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!Buffer.isBuffer(target)) { throw new TypeError('Argument must be a Buffer') } if (start === undefined) { start = 0 } if (end === undefined) { end = target ? target.length : 0 } if (thisStart === undefined) { thisStart = 0 } if (thisEnd === undefined) { thisEnd = this.length } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index') } if (thisStart >= thisEnd && start >= end) { return 0 } if (thisStart >= thisEnd) { return -1 } if (start >= end) { return 1 } start >>>= 0 end >>>= 0 thisStart >>>= 0 thisEnd >>>= 0 if (this === target) return 0 var x = thisEnd - thisStart var y = end - start var len = Math.min(x, y) var thisCopy = this.slice(thisStart, thisEnd) var targetCopy = target.slice(start, end) for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i] y = targetCopy[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1 // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset byteOffset = 0 } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000 } byteOffset = +byteOffset // Coerce to Number. if (isNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : (buffer.length - 1) } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset if (byteOffset >= buffer.length) { if (dir) return -1 else byteOffset = buffer.length - 1 } else if (byteOffset < 0) { if (dir) byteOffset = 0 else return -1 } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding) } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1 } return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF // Search for a byte value [0-255] if (typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } } return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } throw new TypeError('val must be string, number or Buffer') } function arrayIndexOf (arr, val, byteOffset, encoding, dir) { var indexSize = 1 var arrLength = arr.length var valLength = val.length if (encoding !== undefined) { encoding = String(encoding).toLowerCase() if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2 arrLength /= 2 valLength /= 2 byteOffset /= 2 } } function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } var i if (dir) { var foundIndex = -1 for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1 } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength for (i = byteOffset; i >= 0; i--) { var found = true for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false break } } if (found) return i } } return -1 } Buffer.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 } Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) } Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (isNaN(parsed)) return i buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset >>> 0 if (isFinite(length)) { length = length >>> 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': return latin1Write(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function latin1Slice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; ++i) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf = this.subarray(start, end) // Return an augmented `Uint8Array` instance newBuf.__proto__ = Buffer.prototype return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 var sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 var sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range') if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start var i if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } } else if (len < 1000) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start] } } else { Uint8Array.prototype.set.call( target, this.subarray(start, start + len), targetStart ) } return len } // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start start = 0 end = this.length } else if (typeof end === 'string') { encoding = end end = this.length } if (val.length === 1) { var code = val.charCodeAt(0) if (code < 256) { val = code } } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { val = val & 255 } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index') } if (end <= start) { return this } start = start >>> 0 end = end === undefined ? this.length : end >>> 0 if (!val) val = 0 var i if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val } } else { var bytes = Buffer.isBuffer(val) ? val : new Buffer(val, encoding) var len = bytes.length for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len] } } return this } // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } // valid lead leadSurrogate = codePoint continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; ++i) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } function isnan (val) { return val !== val // eslint-disable-line no-self-compare } },{"base64-js":3,"ieee754":9}],7:[function(require,module,exports){ (function (Buffer){ 'use strict'; /* eslint-disable */ var utils = require('./utils/index.js'); var uint256Coder = utils.uint256Coder; var coderBoolean = utils.coderBoolean; var coderFixedBytes = utils.coderFixedBytes; var coderAddress = utils.coderAddress; var coderDynamicBytes = utils.coderDynamicBytes; var coderString = utils.coderString; var coderArray = utils.coderArray; var paramTypePart = utils.paramTypePart; var getParamCoder = utils.getParamCoder; function Result() {} function encodeParams(types, values) { if (types.length !== values.length) { throw new Error('[ethjs-abi] while encoding params, types/values mismatch, types length ' + types.length + ' should be ' + values.length); } var parts = []; types.forEach(function (type, index) { var coder = getParamCoder(type); parts.push({ dynamic: coder.dynamic, value: coder.encode(values[index]) }); }); function alignSize(size) { return parseInt(32 * Math.ceil(size / 32)); } var staticSize = 0, dynamicSize = 0; parts.forEach(function (part) { if (part.dynamic) { staticSize += 32; dynamicSize += alignSize(part.value.length); } else { staticSize += alignSize(part.value.length); } }); var offset = 0, dynamicOffset = staticSize; var data = new Buffer(staticSize + dynamicSize); parts.forEach(function (part, index) { if (part.dynamic) { uint256Coder.encode(dynamicOffset).copy(data, offset); offset += 32; part.value.copy(data, dynamicOffset); dynamicOffset += alignSize(part.value.length); } else { part.value.copy(data, offset); offset += alignSize(part.value.length); } }); return '0x' + data.toString('hex'); } // decode bytecode data from output names and types function decodeParams(names, types, data) { // Names is optional, so shift over all the parameters if not provided if (arguments.length < 3) { data = types; types = names; names = []; } data = utils.hexOrBuffer(data); var values = new Result(); var offset = 0; types.forEach(function (type, index) { var coder = getParamCoder(type); if (coder.dynamic) { var dynamicOffset = uint256Coder.decode(data, offset); var result = coder.decode(data, dynamicOffset.value.toNumber()); offset += dynamicOffset.consumed; } else { var result = coder.decode(data, offset); offset += result.consumed; } values[index] = result.value; if (names[index]) { values[names[index]] = result.value; } }); return values; } // encode method ABI object with values in an array, output bytecode function encodeMethod(method, values) { var signature = method.name + '(' + utils.getKeys(method.inputs, 'type').join(',') + ')'; var signatureEncoded = '0x' + new Buffer(utils.keccak256(signature), 'hex').slice(0, 4).toString('hex'); var paramsEncoded = encodeParams(utils.getKeys(method.inputs, 'type'), values).substring(2); return '' + signatureEncoded + paramsEncoded; } // decode method data bytecode, from method ABI object function decodeMethod(method, data) { var outputNames = utils.getKeys(method.outputs, 'name', true); var outputTypes = utils.getKeys(method.outputs, 'type'); return decodeParams(outputNames, outputTypes, utils.hexOrBuffer(data)); } // decode method data bytecode, from method ABI object function encodeEvent(eventObject, values) { return encodeMethod(eventObject, values); } // decode method data bytecode, from method ABI object function decodeEvent(eventObject, data) { var inputNames = utils.getKeys(eventObject.inputs, 'name', true); var inputTypes = utils.getKeys(eventObject.inputs, 'type'); return decodeParams(inputNames, inputTypes, utils.hexOrBuffer(data)); } module.exports = { encodeParams: encodeParams, decodeParams: decodeParams, encodeMethod: encodeMethod, decodeMethod: decodeMethod, encodeEvent: encodeEvent, decodeEvent: decodeEvent }; }).call(this,require("buffer").Buffer) },{"./utils/index.js":8,"buffer":6}],8:[function(require,module,exports){ (function (Buffer){ 'use strict'; var BN = require('bn.js'); var numberToBN = require('number-to-bn'); var keccak256 = require('js-sha3').keccak_256; // from ethereumjs-util function stripZeros(aInput) { var a = aInput; // eslint-disable-line var first = a[0]; // eslint-disable-line while (a.length > 0 && first.toString() === '0') { a = a.slice(1); first = a[0]; } return a; } function bnToBuffer(bnInput) { var bn = bnInput; // eslint-disable-line var hex = bn.toString(16); // eslint-disable-line if (hex.length % 2) { hex = '0' + hex; } return stripZeros(new Buffer(hex, 'hex')); } function isHexString(value, length) { if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) { return false; } if (length && value.length !== 2 + 2 * length) { return false; } return true; } function hexOrBuffer(valueInput, name) { var value = valueInput; // eslint-disable-line if (!Buffer.isBuffer(value)) { if (!isHexString(value)) { var error = new Error(name ? '[ethjs-abi] invalid ' + name : '[ethjs-abi] invalid hex or buffer, must be a prefixed alphanumeric even length hex string'); error.reason = '[ethjs-abi] invalid hex string, hex must be prefixed and alphanumeric (e.g. 0x023..)'; error.value = value; throw error; } value = value.substring(2); if (value.length % 2) { value = '0' + value; } value = new Buffer(value, 'hex'); } return value; } function hexlify(value) { if (typeof value === 'number') { return '0x' + bnToBuffer(new BN(value)).toString('hex'); } else if (value.mod || value.modulo) { return '0x' + bnToBuffer(value).toString('hex'); } else { // eslint-disable-line return '0x' + hexOrBuffer(value).toString('hex'); } } // getKeys([{a: 1, b: 2}, {a: 3, b: 4}], 'a') => [1, 3] function getKeys(params, key, allowEmpty) { var result = []; // eslint-disable-line if (!Array.isArray(params)) { throw new Error('[ethjs-abi] while getting keys, invalid params value ' + JSON.stringify(params)); } for (var i = 0; i < params.length; i++) { // eslint-disable-line var value = params[i][key]; // eslint-disable-line if (allowEmpty && !value) { value = ''; } else if (typeof value !== 'string') { throw new Error('[ethjs-abi] while getKeys found invalid ABI data structure, type value not string'); } result.push(value); } return result; } function coderNumber(size, signed) { return { encode: function encodeNumber(valueInput) { var value = valueInput; // eslint-disable-line if (typeof value === 'object' && value.toString && (value.toTwos || value.dividedToIntegerBy)) { value = value.toString(10).split('.')[0]; } if (typeof value === 'string' || typeof value === 'number') { value = String(value).split('.')[0]; } value = numberToBN(value); value = value.toTwos(size * 8).maskn(size * 8); if (signed) { value = value.fromTwos(size * 8).toTwos(256); } return value.toArrayLike(Buffer, 'be', 32); }, decode: function decodeNumber(data, offset) { var junkLength = 32 - size; // eslint-disable-line var value = new BN(data.slice(offset + junkLength, offset + 32)); // eslint-disable-line if (signed) { value = value.fromTwos(size * 8); } else { value = value.maskn(size * 8); } return { consumed: 32, value: new BN(value.toString(10)) }; } }; } var uint256Coder = coderNumber(32, false); var coderBoolean = { encode: function encodeBoolean(value) { return uint256Coder.encode(value ? 1 : 0); }, decode: function decodeBoolean(data, offset) { var result = uint256Coder.decode(data, offset); // eslint-disable-line return { consumed: result.consumed, value: !result.value.isZero() }; } }; function coderFixedBytes(length) { return { encode: function encodeFixedBytes(valueInput) { var value = valueInput; // eslint-disable-line value = hexOrBuffer(value); if (value.length === 32) { return value; } var result = new Buffer(32); // eslint-disable-line result.fill(0); value.copy(result); return result; }, decode: function decodeFixedBytes(data, offset) { if (data.length < offset + 32) { throw new Error('[ethjs-abi] while decoding fixed bytes, invalid bytes data length: ' + length); } return { consumed: 32, value: '0x' + data.slice(offset, offset + length).toString('hex') }; } }; } var coderAddress = { encode: function encodeAddress(valueInput) { var value = valueInput; // eslint-disable-line var result = new Buffer(32); // eslint-disable-line if (!isHexString(value, 20)) { throw new Error('[ethjs-abi] while encoding address, invalid address value, not alphanumeric 20 byte hex string'); } value = hexOrBuffer(value); result.fill(0); value.copy(result, 12); return result; }, decode: function decodeAddress(data, offset) { if (data.length === 0) { return { consumed: 32, value: '0x' }; } if (data.length < offset + 32) { throw new Error('[ethjs-abi] while decoding address data, invalid address data, invalid byte length ' + data.length); } return { consumed: 32, value: '0x' + data.slice(offset + 12, offset + 32).toString('hex') }; } }; function encodeDynamicBytesHelper(value) { var dataLength = parseInt(32 * Math.ceil(value.length / 32)); // eslint-disable-line var padding = new Buffer(dataLength - value.length); // eslint-disable-line padding.fill(0); return Buffer.concat([uint256Coder.encode(value.length), value, padding]); } function decodeDynamicBytesHelper(data, offset) { if (data.length < offset + 32) { throw new Error('[ethjs-abi] while decoding dynamic bytes data, invalid bytes length: ' + data.length + ' should be less than ' + (offset + 32)); } var length = uint256Coder.decode(data, offset).value; // eslint-disable-line length = length.toNumber(); if (data.length < offset + 32 + length) { throw new Error('[ethjs-abi] while decoding dynamic bytes data, invalid bytes length: ' + data.length + ' should be less than ' + (offset + 32 + length)); } return { consumed: parseInt(32 + 32 * Math.ceil(length / 32), 10), value: data.slice(offset + 32, offset + 32 + length) }; } var coderDynamicBytes = { encode: function encodeDynamicBytes(value) { return encodeDynamicBytesHelper(hexOrBuffer(value)); }, decode: function decodeDynamicBytes(data, offset) { var result = decodeDynamicBytesHelper(data, offset); // eslint-disable-line result.value = '0x' + result.value.toString('hex'); return result; }, dynamic: true }; var coderString = { encode: function encodeString(value) { return encodeDynamicBytesHelper(new Buffer(value, 'utf8')); }, decode: function decodeString(data, offset) { var result = decodeDynamicBytesHelper(data, offset); // eslint-disable-line result.value = result.value.toString('utf8'); return result; }, dynamic: true }; function coderArray(coder, lengthInput) { return { encode: function encodeArray(value) { var result = new Buffer(0); // eslint-disable-line var length = lengthInput; // eslint-disable-line if (!Array.isArray(value)) { throw new Error('[ethjs-abi] while encoding array, invalid array data, not type Object (Array)'); } if (length === -1) { length = value.length; result = uint256Coder.encode(length); } if (length !== value.length) { throw new Error('[ethjs-abi] while encoding array, size mismatch array length ' + length + ' does not equal ' + value.length); } value.forEach(function (resultValue) { result = Buffer.concat([result, coder.encode(resultValue)]); }); return result; }, decode: function decodeArray(data, offsetInput) { var length = lengthInput; // eslint-disable-line var offset = offsetInput; // eslint-disable-line // @TODO: // if (data.length < offset + length * 32) { throw new Error('invalid array'); } var consumed = 0; // eslint-disable-line var decodeResult; // eslint-disable-line if (length === -1) { decodeResult = uint256Coder.decode(data, offset); length = decodeResult.value.toNumber(); consumed += decodeResult.consumed; offset += decodeResult.consumed; } var value = []; // eslint-disable-line for (var i = 0; i < length; i++) { // eslint-disable-line var loopResult = coder.decode(data, offset); consumed += loopResult.consumed; offset += loopResult.consumed; value.push(loopResult.value); } return { consumed: consumed, value: value }; }, dynamic: lengthInput === -1 }; } // Break the type up into [staticType][staticArray]*[dynamicArray]? | [dynamicType] and // build the coder up from its parts var paramTypePart = new RegExp(/^((u?int|bytes)([0-9]*)|(address|bool|string)|(\[([0-9]*)\]))/); function getParamCoder(typeInput) { var type = typeInput; // eslint-disable-line var coder = null; // eslint-disable-line var invalidTypeErrorMessage = '[ethjs-abi] while getting param coder (getParamCoder) type value ' + JSON.stringify(type) + ' is either invalid or unsupported by ethjs-abi.'; while (type) { var part = type.match(paramTypePart); // eslint-disable-line if (!part) { throw new Error(invalidTypeErrorMessage); } type = type.substring(part[0].length); var prefix = part[2] || part[4] || part[5]; // eslint-disable-line switch (prefix) { case 'int':case 'uint': if (coder) { throw new Error(invalidTypeErrorMessage); } var intSize = parseInt(part[3] || 256); // eslint-disable-line if (intSize === 0 || intSize > 256 || intSize % 8 !== 0) { throw new Error('[ethjs-abi] while getting param coder for type ' + type + ', invalid ' + prefix + ' width: ' + type); } coder = coderNumber(intSize / 8, prefix === 'int'); break; case 'bool': if (coder) { throw new Error(invalidTypeErrorMessage); } coder = coderBoolean; break; case 'string': if (coder) { throw new Error(invalidTypeErrorMessage); } coder = coderString; break; case 'bytes': if (coder) { throw new Error(invalidTypeErrorMessage); } if (part[3]) { var size = parseInt(part[3]); // eslint-disable-line if (size === 0 || size > 32) { throw new Error('[ethjs-abi] while getting param coder for prefix bytes, invalid type ' + type + ', size ' + size + ' should be 0 or greater than 32'); } coder = coderFixedBytes(size); } else { coder = coderDynamicBytes; } break; case 'address': if (coder) { throw new Error(invalidTypeErrorMessage); } coder = coderAddress; break; case '[]': if (!coder || coder.dynamic) { throw new Error(invalidTypeErrorMessage); } coder = coderArray(coder, -1); break; // "[0-9+]" default: if (!coder || coder.dynamic) { throw new Error(invalidTypeErrorMessage); } var defaultSize = parseInt(part[6]); // eslint-disable-line coder = coderArray(coder, defaultSize); } } if (!coder) { throw new Error(invalidTypeErrorMessage); } return coder; } module.exports = { BN: BN, bnToBuffer: bnToBuffer, isHexString: isHexString, hexOrBuffer: hexOrBuffer, hexlify: hexlify, stripZeros: stripZeros, keccak256: keccak256, getKeys: getKeys, numberToBN: numberToBN, coderNumber: coderNumber, uint256Coder: uint256Coder, coderBoolean: coderBoolean, coderFixedBytes: coderFixedBytes, coderAddress: coderAddress, coderDynamicBytes: coderDynamicBytes, coderString: coderString, coderArray: coderArray, paramTypePart: paramTypePart, getParamCoder: getParamCoder }; }).call(this,require("buffer").Buffer) },{"bn.js":4,"buffer":6,"js-sha3":11,"number-to-bn":12}],9:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } },{}],10:[function(require,module,exports){ /** * Returns a `Boolean` on whether or not the a `String` starts with '0x' * @param {String} str the string input value * @return {Boolean} a boolean if it is or is not hex prefixed * @throws if the str input is not a string */ module.exports = function isHexPrefixed(str) { if (typeof str !== 'string') { throw new Error("[is-hex-prefixed] value must be type 'string', is currently type " + (typeof str) + ", while checking isHexPrefixed."); } return str.slice(0, 2) === '0x'; } },{}],11:[function(require,module,exports){ (function (process,global){ /** * [js-sha3]{@link https://github.com/emn178/js-sha3} * * @version 0.5.5 * @author Chen, Yi-Cyuan [emn178@gmail.com] * @copyright Chen, Yi-Cyuan 2015-2016 * @license MIT */ (function (root) { 'use strict'; var NODE_JS = typeof process == 'object' && process.versions && process.versions.node; if (NODE_JS) { root = global; } var COMMON_JS = !root.JS_SHA3_TEST && typeof module == 'object' && module.exports; var HEX_CHARS = '0123456789abcdef'.split(''); var SHAKE_PADDING = [31, 7936, 2031616, 520093696]; var KECCAK_PADDING = [1, 256, 65536, 16777216]; var PADDING = [6, 1536, 393216, 100663296]; var SHIFT = [0, 8, 16, 24]; var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]; var BITS = [224, 256, 384, 512]; var SHAKE_BITS = [128, 256]; var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array']; var createOutputMethod = function (bits, padding, outputType) { return function (message) { return new Keccak(bits, padding, bits).update(message)[outputType](); } }; var createShakeOutputMethod = function (bits, padding, outputType) { return function (message, outputBits) { return new Keccak(bits, padding, outputBits).update(message)[outputType](); } }; var createMethod = function (bits, padding) { var method = createOutputMethod(bits, padding, 'hex'); method.create = function () { return new Keccak(bits, padding, bits); }; method.update = function (message) { return method.create().update(message); }; for (var i = 0;i < OUTPUT_TYPES.length;++i) { var type = OUTPUT_TYPES[i]; method[type] = createOutputMethod(bits, padding, type); } return method; }; var createShakeMethod = function (bits, padding) { var method = createShakeOutputMethod(bits, padding, 'hex'); method.create = function (outputBits) { return new Keccak(bits, padding, outputBits); }; method.update = function (message, outputBits) { return method.create(outputBits).update(message); }; for (var i = 0;i < OUTPUT_TYPES.length;++i) { var type = OUTPUT_TYPES[i]; method[type] = createShakeOutputMethod(bits, padding, type); } return method; }; var algorithms = [ {name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod}, {name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod}, {name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod} ]; var methods = {}; for (var i = 0;i < algorithms.length;++i) { var algorithm = algorithms[i]; var bits = algorithm.bits; for (var j = 0;j < bits.length;++j) { methods[algorithm.name +'_' + bits[j]] = algorithm.createMethod(bits[j], algorithm.padding); } } function Keccak(bits, padding, outputBits) { this.blocks = []; this.s = []; this.padding = padding; this.outputBits = outputBits; this.reset = true; this.block = 0; this.start = 0; this.blockCount = (1600 - (bits << 1)) >> 5; this.byteCount = this.blockCount << 2; this.outputBlocks = outputBits >> 5; this.extraBytes = (outputBits & 31) >> 3; for (var i = 0;i < 50;++i) { this.s[i] = 0; } }; Keccak.prototype.update = function (message) { var notString = typeof message != 'string'; if (notString && message.constructor == root.ArrayBuffer) { message = new Uint8Array(message); } var length = message.length, blocks = this.blocks, byteCount = this.byteCount, blockCount = this.blockCount, index = 0, s = this.s, i, code; while (index < length) { if (this.reset) { this.reset = false; blocks[0] = this.block; for (i = 1;i < blockCount + 1;++i) { blocks[i] = 0; } } if (notString) { for (i = this.start;index < length && i < byteCount;++index) { blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; } } else { for (i = this.start;index < length && i < byteCount;++index) { code = message.charCodeAt(index); if (code < 0x80) { blocks[i >> 2] |= code << SHIFT[i++ & 3]; } else if (code < 0x800) { blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } else if (code < 0xd800 || code >= 0xe000) { blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } else { code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } } } this.lastByteIndex = i; if (i >= byteCount) { this.start = i - byteCount; this.block = blocks[blockCount]; for (i = 0;i < blockCount;++i) { s[i] ^= blocks[i]; } f(s); this.reset = true; } else { this.start = i; } } return this; }; Keccak.prototype.finalize = function () { var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s; blocks[i >> 2] |= this.padding[i & 3]; if (this.lastByteIndex == this.byteCount) { blocks[0] = blocks[blockCount]; for (i = 1;i < blockCount + 1;++i) { blocks[i] = 0; } } blocks[blockCount - 1] |= 0x80000000; for (i = 0;i < blockCount;++i) { s[i] ^= blocks[i]; } f(s); }; Keccak.prototype.toString = Keccak.prototype.hex = function () { this.finalize(); var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i = 0, j = 0; var hex = '', block; while (j < outputBlocks) { for (i = 0;i < blockCount && j < outputBlocks;++i, ++j) { block = s[i]; hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] + HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] + HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] + HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F]; } if (j % blockCount == 0) { f(s); i = 0; } } if (extraBytes) { block = s[i]; if (extraBytes > 0) { hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F]; } if (extraBytes > 1) { hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F]; } if (extraBytes > 2) { hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F]; } } return hex; }; Keccak.prototype.arrayBuffer = function () { this.finalize(); var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i = 0, j = 0; var bytes = this.outputBits >> 3; var buffer; if (extraBytes) { buffer = new ArrayBuffer((outputBlocks + 1) << 2); } else { buffer = new ArrayBuffer(bytes); } var array = new Uint32Array(buffer); while (j < outputBlocks) { for (i = 0;i < blockCount && j < outputBlocks;++i, ++j) { array[j] = s[i]; } if (j % blockCount == 0) { f(s); } } if (extraBytes) { array[i] = s[i]; buffer = buffer.slice(0, bytes); } return buffer; }; Keccak.prototype.buffer = Keccak.prototype.arrayBuffer; Keccak.prototype.digest = Keccak.prototype.array = function () { this.finalize(); var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i = 0, j = 0; var array = [], offset, block; while (j < outputBlocks) { for (i = 0;i < blockCount && j < outputBlocks;++i, ++j) { offset = j << 2; block = s[i]; array[offset] = block & 0xFF; array[offset + 1] = (block >> 8) & 0xFF; array[offset + 2] = (block >> 16) & 0xFF; array[offset + 3] = (block >> 24) & 0xFF; } if (j % blockCount == 0) { f(s); } } if (extraBytes) { offset = j << 2; block = s[i]; if (extraBytes > 0) { array[offset] = block & 0xFF; } if (extraBytes > 1) { array[offset + 1] = (block >> 8) & 0xFF; } if (extraBytes > 2) { array[offset + 2] = (block >> 16) & 0xFF; } } return array; }; var f = function (s) { var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49; for (n = 0;n < 48;n += 2) { c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]; c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]; c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]; c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]; c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]; c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]; c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]; c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]; c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]; c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]; h = c8 ^ ((c2 << 1) | (c3 >>> 31)); l = c9 ^ ((c3 << 1) | (c2 >>> 31)); s[0] ^= h; s[1] ^= l; s[10] ^= h; s[11] ^= l; s[20] ^= h; s[21] ^= l; s[30] ^= h; s[31] ^= l; s[40] ^= h; s[41] ^= l; h = c0 ^ ((c4 << 1) | (c5 >>> 31)); l = c1 ^ ((c5 << 1) | (c4 >>> 31)); s[2] ^= h; s[3] ^= l; s[12] ^= h; s[13] ^= l; s[22] ^= h; s[23] ^= l; s[32] ^= h; s[33] ^= l; s[42] ^= h; s[43] ^= l; h = c2 ^ ((c6 << 1) | (c7 >>> 31)); l = c3 ^ ((c7 << 1) | (c6 >>> 31)); s[4] ^= h; s[5] ^= l; s[14] ^= h; s[15] ^= l; s[24] ^= h; s[25] ^= l; s[34] ^= h; s[35] ^= l; s[44] ^= h; s[45] ^= l; h = c4 ^ ((c8 << 1) | (c9 >>> 31)); l = c5 ^ ((c9 << 1) | (c8 >>> 31)); s[6] ^= h; s[7] ^= l; s[16] ^= h; s[17] ^= l; s[26] ^= h; s[27] ^= l; s[36] ^= h; s[37] ^= l; s[46] ^= h; s[47] ^= l; h = c6 ^ ((c0 << 1) | (c1 >>> 31)); l = c7 ^ ((c1 << 1) | (c0 >>> 31)); s[8] ^= h; s[9] ^= l; s[18] ^= h; s[19] ^= l; s[28] ^= h; s[29] ^= l; s[38] ^= h; s[39] ^= l; s[48] ^= h; s[49] ^= l; b0 = s[0]; b1 = s[1]; b32 = (s[11] << 4) | (s[10] >>> 28); b33 = (s[10] << 4) | (s[11] >>> 28); b14 = (s[20] << 3) | (s[21] >>> 29); b15 = (s[21] << 3) | (s[20] >>> 29); b46 = (s[31] << 9) | (s[30] >>> 23); b47 = (s[30] << 9) | (s[31] >>> 23); b28 = (s[40] << 18) | (s[41] >>> 14); b29 = (s[41] << 18) | (s[40] >>> 14); b20 = (s[2] << 1) | (s[3] >>> 31); b21 = (s[3] << 1) | (s[2] >>> 31); b2 = (s[13] << 12) | (s[12] >>> 20); b3 = (s[12] << 12) | (s[13] >>> 20); b34 = (s[22] << 10) | (s[23] >>> 22); b35 = (s[23] << 10) | (s[22] >>> 22); b16 = (s[33] << 13) | (s[32] >>> 19); b17 = (s[32] << 13) | (s[33] >>> 19); b48 = (s[42] << 2) | (s[43] >>> 30); b49 = (s[43] << 2) | (s[42] >>> 30); b40 = (s[5] << 30) | (s[4] >>> 2); b41 = (s[4] << 30) | (s[5] >>> 2); b22 = (s[14] << 6) | (s[15] >>> 26); b23 = (s[15] << 6) | (s[14] >>> 26); b4 = (s[25] << 11) | (s[24] >>> 21); b5 = (s[24] << 11) | (s[25] >>> 21); b36 = (s[34] << 15) | (s[35] >>> 17); b37 = (s[35] << 15) | (s[34] >>> 17); b18 = (s[45] << 29) | (s[44] >>> 3); b19 = (s[44] << 29) | (s[45] >>> 3); b10 = (s[6] << 28) | (s[7] >>> 4); b11 = (s[7] << 28) | (s[6] >>> 4); b42 = (s[17] << 23) | (s[16] >>> 9); b43 = (s[16] << 23) | (s[17] >>> 9); b24 = (s[26] << 25) | (s[27] >>> 7); b25 = (s[27] << 25) | (s[26] >>> 7); b6 = (s[36] << 21) | (s[37] >>> 11); b7 = (s[37] << 21) | (s[36] >>> 11); b38 = (s[47] << 24) | (s[46] >>> 8); b39 = (s[46] << 24) | (s[47] >>> 8); b30 = (s[8] << 27) | (s[9] >>> 5); b31 = (s[9] << 27) | (s[8] >>> 5); b12 = (s[18] << 20) | (s[19] >>> 12); b13 = (s[19] << 20) | (s[18] >>> 12); b44 = (s[29] << 7) | (s[28] >>> 25); b45 = (s[28] << 7) | (s[29] >>> 25); b26 = (s[38] << 8) | (s[39] >>> 24); b27 = (s[39] << 8) | (s[38] >>> 24); b8 = (s[48] << 14) | (s[49] >>> 18); b9 = (s[49] << 14) | (s[48] >>> 18); s[0] = b0 ^ (~b2 & b4); s[1] = b1 ^ (~b3 & b5); s[10] = b10 ^ (~b12 & b14); s[11] = b11 ^ (~b13 & b15); s[20] = b20 ^ (~b22 & b24); s[21] = b21 ^ (~b23 & b25); s[30] = b30 ^ (~b32 & b34); s[31] = b31 ^ (~b33 & b35); s[40] = b40 ^ (~b42 & b44); s[41] = b41 ^ (~b43 & b45); s[2] = b2 ^ (~b4 & b6); s[3] = b3 ^ (~b5 & b7); s[12] = b12 ^ (~b14 & b16); s[13] = b13 ^ (~b15 & b17); s[22] = b22 ^ (~b24 & b26); s[23] = b23 ^ (~b25 & b27); s[32] = b32 ^ (~b34 & b36); s[33] = b33 ^ (~b35 & b37); s[42] = b42 ^ (~b44 & b46); s[43] = b43 ^ (~b45 & b47); s[4] = b4 ^ (~b6 & b8); s[5] = b5 ^ (~b7 & b9); s[14] = b14 ^ (~b16 & b18); s[15] = b15 ^ (~b17 & b19); s[24] = b24 ^ (~b26 & b28); s[25] = b25 ^ (~b27 & b29); s[34] = b34 ^ (~b36 & b38); s[35] = b35 ^ (~b37 & b39); s[44] = b44 ^ (~b46 & b48); s[45] = b45 ^ (~b47 & b49); s[6] = b6 ^ (~b8 & b0); s[7] = b7 ^ (~b9 & b1); s[16] = b16 ^ (~b18 & b10); s[17] = b17 ^ (~b19 & b11); s[26] = b26 ^ (~b28 & b20); s[27] = b27 ^ (~b29 & b21); s[36] = b36 ^ (~b38 & b30); s[37] = b37 ^ (~b39 & b31); s[46] = b46 ^ (~b48 & b40); s[47] = b47 ^ (~b49 & b41); s[8] = b8 ^ (~b0 & b2); s[9] = b9 ^ (~b1 & b3); s[18] = b18 ^ (~b10 & b12); s[19] = b19 ^ (~b11 & b13); s[28] = b28 ^ (~b20 & b22); s[29] = b29 ^ (~b21 & b23); s[38] = b38 ^ (~b30 & b32); s[39] = b39 ^ (~b31 & b33); s[48] = b48 ^ (~b40 & b42); s[49] = b49 ^ (~b41 & b43); s[0] ^= RC[n]; s[1] ^= RC[n + 1]; } } if (COMMON_JS) { module.exports = methods; } else if (root) { for (var key in methods) { root[key] = methods[key]; } } }(this)); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":13}],12:[function(require,module,exports){ var BN = require('bn.js'); var stripHexPrefix = require('strip-hex-prefix'); /** * Returns a BN object, converts a number value to a BN * @param {String|Number|Object} `arg` input a string number, hex string number, number, BigNumber or BN object * @return {Object} `output` BN object of the number * @throws if the argument is not an array, object that isn't a bignumber, not a string number or number */ module.exports = function numberToBN(arg) { if (typeof arg === 'string' || typeof arg === 'number') { var multiplier = new BN(1); // eslint-disable-line var formattedString = String(arg).toLowerCase().trim(); var isHexPrefixed = formattedString.substr(0, 2) === '0x' || formattedString.substr(0, 3) === '-0x'; var stringArg = stripHexPrefix(formattedString); // eslint-disable-line if (stringArg.substr(0, 1) === '-') { stringArg = stripHexPrefix(stringArg.slice(1)); multiplier = new BN(-1, 10); } stringArg = stringArg === '' ? '0' : stringArg; if ((!stringArg.match(/^-?[0-9]+$/) && stringArg.match(/^[0-9A-Fa-f]+$/)) || stringArg.match(/^[a-fA-F]+$/) || (isHexPrefixed === true && stringArg.match(/^[0-9A-Fa-f]+$/))) { return new BN(stringArg, 16).mul(multiplier); } if ((stringArg.match(/^-?[0-9]+$/) || stringArg === '') && isHexPrefixed === false) { return new BN(stringArg, 10).mul(multiplier); } } else if (typeof arg === 'object' && arg.toString && (!arg.pop && !arg.push)) { if (arg.toString(10).match(/^-?[0-9]+$/) && (arg.mul || arg.dividedToIntegerBy)) { return new BN(arg.toString(10), 10); } } throw new Error('[number-to-bn] while converting number ' + JSON.stringify(arg) + ' to BN.js instance, error: invalid number value. Value must be an integer, hex string, BN or BigNumber instance. Note, decimals are not supported.'); } },{"bn.js":4,"strip-hex-prefix":14}],13:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],14:[function(require,module,exports){ var isHexPrefixed = require('is-hex-prefixed'); /** * Removes '0x' from a given `String` is present * @param {String} str the string value * @return {String|Optional} a string by pass if necessary */ module.exports = function stripHexPrefix(str) { if (typeof str !== 'string') { return str; } return isHexPrefixed(str) ? str.slice(2) : str; } },{"is-hex-prefixed":10}],15:[function(require,module,exports){ // TODO: remove web3 requirement // Call functions directly on the provider. var Web3 = require("web3"); var Blockchain = { parse: function(uri) { var parsed = {}; if (uri.indexOf("blockchain://") != 0) return parsed; uri = uri.replace("blockchain://", ""); var pieces = uri.split("/block/"); parsed.genesis_hash = "0x" + pieces[0]; parsed.block_hash = "0x" + pieces[1]; return parsed; }, asURI: function(provider, callback) { var web3 = new Web3(provider); web3.eth.getBlock(0, function(err, genesis) { if (err) return callback(err); web3.eth.getBlock("latest", function(err, latest) { if (err) return callback(err); var url = "blockchain://" + genesis.hash.replace("0x", "") + "/block/" + latest.hash.replace("0x", ""); callback(null, url); }); }); }, matches: function(uri, provider, callback) { uri = this.parse(uri); var expected_genesis = uri.genesis_hash; var expected_block = uri.block_hash; var web3 = new Web3(provider); web3.eth.getBlock(0, function(err, block) { if (err) return callback(err); if (block.hash != expected_genesis) return callback(null, false); web3.eth.getBlock(expected_block, function(err, block) { // Treat an error as if the block didn't exist. This is because // some clients respond differently. if (err || block == null) { return callback(null, false); } callback(null, true); }); }); } }; module.exports = Blockchain; },{"web3":5}],16:[function(require,module,exports){ var sha3 = require("crypto-js/sha3"); var schema_version = require("./package.json").version; var TruffleSchema = { // Normalize options passed in to be the exact options required // for truffle-contract. // // options can be three things: // - normal object // - contract object // - solc output // // TODO: Is extra_options still necessary? normalizeOptions: function(options, extra_options) { extra_options = extra_options || {}; var normalized = {}; var expected_keys = [ "contract_name", "abi", "binary", "unlinked_binary", "address", "networks", "links", "events", "network_id", "default_network", "updated_at" ]; // Merge options/contract object first, then extra_options expected_keys.forEach(function(key) { var value; try { // Will throw an error if key == address and address doesn't exist. value = options[key]; if (value != undefined) { normalized[key] = value; } } catch (e) { // Do nothing. } try { // Will throw an error if key == address and address doesn't exist. value = extra_options[key]; if (value != undefined) { normalized[key] = value; } } catch (e) { // Do nothing. } }); // Now look for solc specific items. if (options.interface != null) { normalized.abi = JSON.parse(options.interface); } if (options.bytecode != null) { normalized.unlinked_binary = options.bytecode } // Assume any binary passed is the unlinked binary if (normalized.unlinked_binary == null && normalized.binary) { normalized.unlinked_binary = normalized.binary; } delete normalized.binary; this.copyCustomOptions(options, normalized); return normalized; }, // Generate a proper binary from normalized options, and optionally // merge it with an existing binary. generateBinary: function(options, existing_binary, extra_options) { extra_options = extra_options || {}; existing_binary = existing_binary || {}; if (options.overwrite == true) { existing_binary = {}; } existing_binary.contract_name = options.contract_name || existing_binary.contract_name || "Contract"; existing_binary.default_network = options.default_network || existing_binary.default_network; existing_binary.abi = options.abi || existing_binary.abi; existing_binary.unlinked_binary = options.unlinked_binary || existing_binary.unlinked_binary; // Ensure unlinked binary starts with a 0x if (existing_binary.unlinked_binary && existing_binary.unlinked_binary.indexOf("0x") < 0) { existing_binary.unlinked_binary = "0x" + existing_binary.unlinked_binary; } // Merge existing networks with any passed in networks. existing_binary.networks = existing_binary.networks || {}; options.networks = options.networks || {}; Object.keys(options.networks).forEach(function(network_id) { existing_binary.networks[network_id] = options.networks[network_id]; }); var updated_at = new Date().getTime(); if (options.network_id) { // Ensure an object exists for this network. existing_binary.networks[options.network_id] = existing_binary.networks[options.network_id] || {}; var network = existing_binary.networks[options.network_id]; // Override specific keys network.address = options.address || network.address; network.links = options.links; // merge events with any that previously existed network.events = network.events || {}; options.events = options.events || {}; Object.keys(options.events).forEach(function(event_id) { options.events[event_id] = options.events[event_id]; }); // Now overwrite any events with the most recent data from the ABI. existing_binary.abi.forEach(function(item) { if (item.type != "event") return; var signature = item.name + "(" + item.inputs.map(function(param) {return param.type;}).join(",") + ")"; network.events["0x" + sha3(signature, {outputLength: 256})] = item; }); if (extra_options.dirty !== false) { network.updated_at = updated_at; } } else { if (options.address) { throw new Error("Cannot set address without network id"); } } // Ensure all networks have a `links` object. Object.keys(existing_binary.networks).forEach(function(network_id) { var network = existing_binary.networks[network_id]; network.links = network.links || {}; }); existing_binary.schema_version = schema_version; if (extra_options.dirty !== false) { existing_binary.updated_at = updated_at; } else { existing_binary.updated_at = options.updated_at || existing_binary.updated_at || updated_at; } this.copyCustomOptions(options, existing_binary); return existing_binary; }, copyCustomOptions: function(from, to) { // Now let all x- options through. Object.keys(from).forEach(function(key) { if (key.indexOf("x-") != 0) return; try { value = from[key]; if (value != undefined) { to[key] = value; } } catch (e) { // Do nothing. } }); } }; module.exports = TruffleSchema; },{"./package.json":20,"crypto-js/sha3":18}],17:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(); } else if (typeof define === "function" && define.amd) { // AMD define([], factory); } else { // Global (browser) root.CryptoJS = factory(); } }(this, function () { /** * CryptoJS core components. */ var CryptoJS = CryptoJS || (function (Math, undefined) { /* * Local polyfil of Object.create */ var create = Object.create || (function () { function F() {}; return function (obj) { var subtype; F.prototype = obj; subtype = new F(); F.prototype = null; return subtype; }; }()) /** * CryptoJS namespace. */ var C = {}; /** * Library namespace. */ var C_lib = C.lib = {}; /** * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function (overrides) { // Spawn var subtype = create(this); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function () { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function () { return this.init.prototype.extend(this); } }; }()); /** * An array of 32-bit words. * * @property {Array} words The array of 32-bit words. * @property {number} sigBytes The number of significant bytes in this word array. */ var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function (encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function (wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else { // Copy one word at a time for (var i = 0; i < thatSigBytes; i += 4) { thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; } } this.sigBytes += thatSigBytes; // Chainable return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function () { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function (nBytes) { var words = []; var r = (function (m_w) { var m_w = m_w; var m_z = 0x3ade68b1; var mask = 0xffffffff; return function () { m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; var result = ((m_z << 0x10) + m_w) & mask; result /= 0x100000000; result += 0.5; return result * (Math.random() > .5 ? 1 : -1); } }); for (var i = 0, rcache; i < nBytes; i += 4) { var _r = r((rcache || Math.random()) * 0x100000000); rcache = _r() * 0x3ade67b7; words.push((_r() * 0x100000000) | 0); } return new WordArray.init(words, nBytes); } }); /** * Encoder namespace. */ var C_enc = C.enc = {}; /** * Hex encoding strategy. */ var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function (hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); } }; /** * Latin1 encoding strategy. */ var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function (latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); } }; /** * UTF-8 encoding strategy. */ var Utf8 = C_enc.Utf8 = { /** * Converts a word array to a UTF-8 string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-8 string. * * @static * * @example * * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); */ stringify: function (wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error('Malformed UTF-8 data'); } }, /** * Converts a UTF-8 string to a word array. * * @param {string} utf8Str The UTF-8 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ parse: function (utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); } }; /** * Abstract buffered block algorithm template. * * The property blockSize must be implemented in a concrete subtype. * * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 */ var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** * Resets this block algorithm's data buffer to its initial state. * * @example * * bufferedBlockAlgorithm.reset(); */ reset: function () { // Initial values this._data = new WordArray.init(); this._nDataBytes = 0; }, /** * Adds new data to this block algorithm's buffer. * * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. * * @example * * bufferedBlockAlgorithm._append('data'); * bufferedBlockAlgorithm._append(wordArray); */ _append: function (data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; }, /** * Processes available data blocks. * * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. * * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. * * @return {WordArray} The processed data. * * @example * * var processedData = bufferedBlockAlgorithm._process(); * var processedData = bufferedBlockAlgorithm._process(!!'flush'); */ _process: function (doFlush) { // Shortcuts var data = this._data; var dataWords = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; // Count blocks ready var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { // Round up to include partial blocks nBlocksReady = Math.ceil(nBlocksReady); } else { // Round down to include only full blocks, // less the number of blocks that must remain in the buffer nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); } // Count words ready var nWordsReady = nBlocksReady * blockSize; // Count bytes ready var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { // Perform concrete-algorithm logic this._doProcessBlock(dataWords, offset); } // Remove processed words var processedWords = dataWords.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } // Return processed words return new WordArray.init(processedWords, nBytesReady); }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = bufferedBlockAlgorithm.clone(); */ clone: function () { var clone = Base.clone.call(this); clone._data = this._data.clone(); return clone; }, _minBufferSize: 0 }); /** * Abstract hasher template. * * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) */ var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ /** * Configuration options. */ cfg: Base.extend(), /** * Initializes a newly created hasher. * * @param {Object} cfg (Optional) The configuration options to use for this hash computation. * * @example * * var hasher = CryptoJS.algo.SHA256.create(); */ init: function (cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Set initial values this.reset(); }, /** * Resets this hasher to its initial state. * * @example * * hasher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic this._doReset(); }, /** * Updates this hasher with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {Hasher} This hasher. * * @example * * hasher.update('message'); * hasher.update(wordArray); */ update: function (messageUpdate) { // Append this._append(messageUpdate); // Update the hash this._process(); // Chainable return this; }, /** * Finalizes the hash computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The hash. * * @example * * var hash = hasher.finalize(); * var hash = hasher.finalize('message'); * var hash = hasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Final message update if (messageUpdate) { this._append(messageUpdate); } // Perform concrete-hasher logic var hash = this._doFinalize(); return hash; }, blockSize: 512/32, /** * Creates a shortcut function to a hasher's object interface. * * @param {Hasher} hasher The hasher to create a helper for. * * @return {Function} The shortcut function. * * @static * * @example * * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ _createHelper: function (hasher) { return function (message, cfg) { return new hasher.init(cfg).finalize(message); }; }, /** * Creates a shortcut function to the HMAC's object interface. * * @param {Hasher} hasher The hasher to use in this HMAC helper. * * @return {Function} The shortcut function. * * @static * * @example * * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ _createHmacHelper: function (hasher) { return function (message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; } }); /** * Algorithm namespace. */ var C_algo = C.algo = {}; return C; }(Math)); return CryptoJS; })); },{}],18:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var C_algo = C.algo; // Constants tables var RHO_OFFSETS = []; var PI_INDEXES = []; var ROUND_CONSTANTS = []; // Compute Constants (function () { // Compute rho offset constants var x = 1, y = 0; for (var t = 0; t < 24; t++) { RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; var newX = y % 5; var newY = (2 * x + 3 * y) % 5; x = newX; y = newY; } // Compute pi index constants for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; } } // Compute round constants var LFSR = 0x01; for (var i = 0; i < 24; i++) { var roundConstantMsw = 0; var roundConstantLsw = 0; for (var j = 0; j < 7; j++) { if (LFSR & 0x01) { var bitPosition = (1 << j) - 1; if (bitPosition < 32) { roundConstantLsw ^= 1 << bitPosition; } else /* if (bitPosition >= 32) */ { roundConstantMsw ^= 1 << (bitPosition - 32); } } // Compute next LFSR if (LFSR & 0x80) { // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 LFSR = (LFSR << 1) ^ 0x71; } else { LFSR <<= 1; } } ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); } }()); // Reusable objects for temporary values var T = []; (function () { for (var i = 0; i < 25; i++) { T[i] = X64Word.create(); } }()); /** * SHA-3 hash algorithm. */ var SHA3 = C_algo.SHA3 = Hasher.extend({ /** * Configuration options. * * @property {number} outputLength * The desired number of bits in the output hash. * Only values permitted are: 224, 256, 384, 512. * Default: 512 */ cfg: Hasher.cfg.extend({ outputLength: 512 }), _doReset: function () { var state = this._state = [] for (var i = 0; i < 25; i++) { state[i] = new X64Word.init(); } this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; }, _doProcessBlock: function (M, offset) { // Shortcuts var state = this._state; var nBlockSizeLanes = this.blockSize / 2; // Absorb for (var i = 0; i < nBlockSizeLanes; i++) { // Shortcuts var M2i = M[offset + 2 * i]; var M2i1 = M[offset + 2 * i + 1]; // Swap endian M2i = ( (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) ); M2i1 = ( (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) ); // Absorb message into state var lane = state[i]; lane.high ^= M2i1; lane.low ^= M2i; } // Rounds for (var round = 0; round < 24; round++) { // Theta for (var x = 0; x < 5; x++) { // Mix column lanes var tMsw = 0, tLsw = 0; for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; tMsw ^= lane.high; tLsw ^= lane.low; } // Temporary values var Tx = T[x]; Tx.high = tMsw; Tx.low = tLsw; } for (var x = 0; x < 5; x++) { // Shortcuts var Tx4 = T[(x + 4) % 5]; var Tx1 = T[(x + 1) % 5]; var Tx1Msw = Tx1.high; var Tx1Lsw = Tx1.low; // Mix surrounding columns var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; lane.high ^= tMsw; lane.low ^= tLsw; } } // Rho Pi for (var laneIndex = 1; laneIndex < 25; laneIndex++) { // Shortcuts var lane = state[laneIndex]; var laneMsw = lane.high; var laneLsw = lane.low; var rhoOffset = RHO_OFFSETS[laneIndex]; // Rotate lanes if (rhoOffset < 32) { var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); } else /* if (rhoOffset >= 32) */ { var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); } // Transpose lanes var TPiLane = T[PI_INDEXES[laneIndex]]; TPiLane.high = tMsw; TPiLane.low = tLsw; } // Rho pi at x = y = 0 var T0 = T[0]; var state0 = state[0]; T0.high = state0.high; T0.low = state0.low; // Chi for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { // Shortcuts var laneIndex = x + 5 * y; var lane = state[laneIndex]; var TLane = T[laneIndex]; var Tx1Lane = T[((x + 1) % 5) + 5 * y]; var Tx2Lane = T[((x + 2) % 5) + 5 * y]; // Mix rows lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); } } // Iota var lane = state[0]; var roundConstant = ROUND_CONSTANTS[round]; lane.high ^= roundConstant.high; lane.low ^= roundConstant.low;; } }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; var blockSizeBits = this.blockSize * 32; // Add padding dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Shortcuts var state = this._state; var outputLengthBytes = this.cfg.outputLength / 8; var outputLengthLanes = outputLengthBytes / 8; // Squeeze var hashWords = []; for (var i = 0; i < outputLengthLanes; i++) { // Shortcuts var lane = state[i]; var laneMsw = lane.high; var laneLsw = lane.low; // Swap endian laneMsw = ( (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) ); laneLsw = ( (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) ); // Squeeze state to retrieve hash hashWords.push(laneLsw); hashWords.push(laneMsw); } // Return final computed hash return new WordArray.init(hashWords, outputLengthBytes); }, clone: function () { var clone = Hasher.clone.call(this); var state = clone._state = this._state.slice(0); for (var i = 0; i < 25; i++) { state[i] = state[i].clone(); } return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA3('message'); * var hash = CryptoJS.SHA3(wordArray); */ C.SHA3 = Hasher._createHelper(SHA3); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA3(message, key); */ C.HmacSHA3 = Hasher._createHmacHelper(SHA3); }(Math)); return CryptoJS.SHA3; })); },{"./core":17,"./x64-core":19}],19:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var X32WordArray = C_lib.WordArray; /** * x64 namespace. */ var C_x64 = C.x64 = {}; /** * A 64-bit word. */ var X64Word = C_x64.Word = Base.extend({ /** * Initializes a newly created 64-bit word. * * @param {number} high The high 32 bits. * @param {number} low The low 32 bits. * * @example * * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); */ init: function (high, low) { this.high = high; this.low = low; } /** * Bitwise NOTs this word. * * @return {X64Word} A new x64-Word object after negating. * * @example * * var negated = x64Word.not(); */ // not: function () { // var high = ~this.high; // var low = ~this.low; // return X64Word.create(high, low); // }, /** * Bitwise ANDs this word with the passed word. * * @param {X64Word} word The x64-Word to AND with this word. * * @return {X64Word} A new x64-Word object after ANDing. * * @example * * var anded = x64Word.and(anotherX64Word); */ // and: function (word) { // var high = this.high & word.high; // var low = this.low & word.low; // return X64Word.create(high, low); // }, /** * Bitwise ORs this word with the passed word. * * @param {X64Word} word The x64-Word to OR with this word. * * @return {X64Word} A new x64-Word object after ORing. * * @example * * var ored = x64Word.or(anotherX64Word); */ // or: function (word) { // var high = this.high | word.high; // var low = this.low | word.low; // return X64Word.create(high, low); // }, /** * Bitwise XORs this word with the passed word. * * @param {X64Word} word The x64-Word to XOR with this word. * * @return {X64Word} A new x64-Word object after XORing. * * @example * * var xored = x64Word.xor(anotherX64Word); */ // xor: function (word) { // var high = this.high ^ word.high; // var low = this.low ^ word.low; // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the left. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftL(25); */ // shiftL: function (n) { // if (n < 32) { // var high = (this.high << n) | (this.low >>> (32 - n)); // var low = this.low << n; // } else { // var high = this.low << (n - 32); // var low = 0; // } // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the right. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftR(7); */ // shiftR: function (n) { // if (n < 32) { // var low = (this.low >>> n) | (this.high << (32 - n)); // var high = this.high >>> n; // } else { // var low = this.high >>> (n - 32); // var high = 0; // } // return X64Word.create(high, low); // }, /** * Rotates this word n bits to the left. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotL(25); */ // rotL: function (n) { // return this.shiftL(n).or(this.shiftR(64 - n)); // }, /** * Rotates this word n bits to the right. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotR(7); */ // rotR: function (n) { // return this.shiftR(n).or(this.shiftL(64 - n)); // }, /** * Adds this word with the passed word. * * @param {X64Word} word The x64-Word to add with this word. * * @return {X64Word} A new x64-Word object after adding. * * @example * * var added = x64Word.add(anotherX64Word); */ // add: function (word) { // var low = (this.low + word.low) | 0; // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; // var high = (this.high + word.high + carry) | 0; // return X64Word.create(high, low); // } }); /** * An array of 64-bit words. * * @property {Array} words The array of CryptoJS.x64.Word objects. * @property {number} sigBytes The number of significant bytes in this word array. */ var X64WordArray = C_x64.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.x64.WordArray.create(); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ]); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ], 10); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 8; } }, /** * Converts this 64-bit word array to a 32-bit word array. * * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. * * @example * * var x32WordArray = x64WordArray.toX32(); */ toX32: function () { // Shortcuts var x64Words = this.words; var x64WordsLength = x64Words.length; // Convert var x32Words = []; for (var i = 0; i < x64WordsLength; i++) { var x64Word = x64Words[i]; x32Words.push(x64Word.high); x32Words.push(x64Word.low); } return X32WordArray.create(x32Words, this.sigBytes); }, /** * Creates a copy of this word array. * * @return {X64WordArray} The clone. * * @example * * var clone = x64WordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); // Clone "words" array var words = clone.words = this.words.slice(0); // Clone each X64Word object var wordsLength = words.length; for (var i = 0; i < wordsLength; i++) { words[i] = words[i].clone(); } return clone; } }); }()); return CryptoJS; })); },{"./core":17}],20:[function(require,module,exports){ module.exports={ "_args": [ [ { "raw": "truffle-contract-schema@0.0.5", "scope": null, "escapedName": "truffle-contract-schema", "name": "truffle-contract-schema", "rawSpec": "0.0.5", "spec": "0.0.5", "type": "version" }, "/Users/tim/Documents/workspace/Consensys/truffle-contract" ] ], "_from": "truffle-contract-schema@0.0.5", "_id": "truffle-contract-schema@0.0.5", "_inCache": true, "_location": "/truffle-contract-schema", "_nodeVersion": "6.9.1", "_npmOperationalInternal": { "host": "packages-12-west.internal.npmjs.com", "tmp": "tmp/truffle-contract-schema-0.0.5.tgz_1485557985137_0.46875762194395065" }, "_npmUser": { "name": "tcoulter", "email": "tim@timothyjcoulter.com" }, "_npmVersion": "3.10.8", "_phantomChildren": {}, "_requested": { "raw": "truffle-contract-schema@0.0.5", "scope": null, "escapedName": "truffle-contract-schema", "name": "truffle-contract-schema", "rawSpec": "0.0.5", "spec": "0.0.5", "type": "version" }, "_requiredBy": [ "/" ], "_resolved": "https://registry.npmjs.org/truffle-contract-schema/-/truffle-contract-schema-0.0.5.tgz", "_shasum": "5e9d20bd0bf2a27fe94310748249d484eee49961", "_shrinkwrap": null, "_spec": "truffle-contract-schema@0.0.5", "_where": "/Users/tim/Documents/workspace/Consensys/truffle-contract", "author": { "name": "Tim Coulter", "email": "tim.coulter@consensys.net" }, "bugs": { "url": "https://github.com/trufflesuite/truffle-schema/issues" }, "dependencies": { "crypto-js": "^3.1.9-1" }, "description": "JSON schema for contract artifacts", "devDependencies": { "mocha": "^3.2.0" }, "directories": {}, "dist": { "shasum": "5e9d20bd0bf2a27fe94310748249d484eee49961", "tarball": "https://registry.npmjs.org/truffle-contract-schema/-/truffle-contract-schema-0.0.5.tgz" }, "gitHead": "cfa4313bd4bb95bf5b94f85185203ead418f9ee6", "homepage": "https://github.com/trufflesuite/truffle-schema#readme", "keywords": [ "ethereum", "json", "schema", "contract", "artifacts" ], "license": "MIT", "main": "index.js", "maintainers": [ { "name": "tcoulter", "email": "tim@timothyjcoulter.com" } ], "name": "truffle-contract-schema", "optionalDependencies": {}, "readme": "ERROR: No README data found!", "repository": { "type": "git", "url": "git+https://github.com/trufflesuite/truffle-schema.git" }, "scripts": { "test": "mocha" }, "version": "0.0.5" } },{}]},{},[2]); ================================================ FILE: truffle/tokentutorial/test/.placeholder ================================================ This is a placeholder file to ensure the parent directory in the git repository. Feel free to remove. ================================================ FILE: truffle/tokentutorial/truffle.js ================================================ module.exports = { // See // for more about customizing your Truffle configuration! networks: { development: { host: "127.0.0.1", port: 7545, network_id: "*" // Match any network id } } }; ================================================ FILE: truffle/tpetshop/README.md ================================================ # Pet Shop Sample Creating using the tutorial http://truffleframework.com/tutorials/pet-shop Run ``` truffle compile truffle deploy npm install npm run dev ``` In Windows you must use `truffle.cmd` instead of `truffle` It was tested using Truffle v3.4.9, installed globally: ``` npm install -g truffle@3.4.9 ``` ================================================ FILE: truffle/tpetshop/bs-config.json ================================================ { "server": { "baseDir": ["./src", "./build/contracts"] } } ================================================ FILE: truffle/tpetshop/contracts/.gitkeep ================================================ ================================================ FILE: truffle/tpetshop/contracts/Adoption.sol ================================================ pragma solidity ^0.4.15; contract Adoption { address[16] public adopters; // Adopting a pet function adopt(uint petId) public returns (uint) { require(petId >= 0 && petId <= 15); require(adopters[petId] == 0); adopters[petId] = msg.sender; return petId; } // Retrieving the adopters function getAdopters() public returns (address[16]) { return adopters; } } ================================================ FILE: truffle/tpetshop/contracts/Migrations.sol ================================================ pragma solidity ^0.4.2; contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } function Migrations() { owner = msg.sender; } function setCompleted(uint completed) restricted { last_completed_migration = completed; } function upgrade(address new_address) restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } ================================================ FILE: truffle/tpetshop/contracts/MyContract.sol ================================================ pragma solidity ^0.4.4; contract MyContract { function MyContract() { // constructor } } ================================================ FILE: truffle/tpetshop/migrations/1_initial_migration.js ================================================ var Migrations = artifacts.require("./Migrations.sol"); module.exports = function(deployer) { deployer.deploy(Migrations); }; ================================================ FILE: truffle/tpetshop/migrations/2_deploy_contracts.js ================================================ var Adoption = artifacts.require("./Adoption.sol"); module.exports = function(deployer) { deployer.deploy(Adoption); }; ================================================ FILE: truffle/tpetshop/package.json ================================================ { "name": "pet-shop", "version": "1.0.0", "description": "", "main": "truffle.js", "directories": { "test": "test" }, "scripts": { "preinstall": "npx npm-force-resolutions", "dev": "lite-server", "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "devDependencies": { "minimist": "^1.2.5", "lite-server": "^2.3.0" }, "resolutions": { "minimist": "^1.2.5" } } ================================================ FILE: truffle/tpetshop/src/index.html ================================================ Pete's Pet Shop

Pete's Pet Shop



================================================ FILE: truffle/tpetshop/src/js/app.js ================================================ App = { web3Provider: null, contracts: {}, init: function() { // Load pets. $.getJSON('../pets.json', function(data) { var petsRow = $('#petsRow'); var petTemplate = $('#petTemplate'); for (i = 0; i < data.length; i ++) { petTemplate.find('.panel-title').text(data[i].name); petTemplate.find('img').attr('src', data[i].picture); petTemplate.find('.pet-breed').text(data[i].breed); petTemplate.find('.pet-age').text(data[i].age); petTemplate.find('.pet-location').text(data[i].location); petTemplate.find('.btn-adopt').attr('data-id', data[i].id); petsRow.append(petTemplate.html()); } }); return App.initWeb3(); }, initWeb3: function() { // Is there is an injected web3 instance? if (typeof web3 !== 'undefined') { App.web3Provider = web3.currentProvider; } else { // If no injected web3 instance is detected, fallback to the TestRPC App.web3Provider = new Web3.providers.HttpProvider('http://localhost:8545'); } web3 = new Web3(App.web3Provider); return App.initContract(); }, initContract: function() { $.getJSON('Adoption.json', function(data) { // Get the necessary contract artifact file and instantiate it with truffle-contract var AdoptionArtifact = data; App.contracts.Adoption = TruffleContract(AdoptionArtifact); // Set the provider for our contract App.contracts.Adoption.setProvider(App.web3Provider); // Use our contract to retrieve and mark the adopted pets return App.markAdopted(); }); return App.bindEvents(); }, bindEvents: function() { $(document).on('click', '.btn-adopt', App.handleAdopt); }, markAdopted: function(adopters, account) { var adoptionInstance; App.contracts.Adoption.deployed().then(function(instance) { adoptionInstance = instance; return adoptionInstance.getAdopters.call(); }).then(function(adopters) { for (i = 0; i < adopters.length; i++) { if (adopters[i] !== '0x0000000000000000000000000000000000000000') { $('.panel-pet').eq(i).find('button').text('Success').attr('disabled', true); } } }).catch(function(err) { console.log(err.message); }); }, handleAdopt: function() { event.preventDefault(); var petId = parseInt($(event.target).data('id')); var adoptionInstance; web3.eth.getAccounts(function(error, accounts) { if (error) { console.log(error); } var account = accounts[0]; App.contracts.Adoption.deployed().then(function(instance) { adoptionInstance = instance; // Execute adopt as a transaction by sending account return adoptionInstance.adopt(petId, {from: account}); }).then(function(result) { return App.markAdopted(); }).catch(function(err) { console.log(err.message); }); }); } }; $(function() { $(window).load(function() { App.init(); }); }); ================================================ FILE: truffle/tpetshop/src/js/truffle-contract.js ================================================ (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0 && new Date().getTime() - start > timeout) { return reject(new Error("Transaction " + tx + " wasn't processed in " + (timeout / 1000) + " seconds!")); } setTimeout(make_attempt, 1000); }); }; make_attempt(); }; args.push(tx_params, callback); fn.apply(self, args); }); }); }; }, merge: function() { var merged = {}; var args = Array.prototype.slice.call(arguments); for (var i = 0; i < args.length; i++) { var object = args[i]; var keys = Object.keys(object); for (var j = 0; j < keys.length; j++) { var key = keys[j]; var value = object[key]; merged[key] = value; } } return merged; }, parallel: function (arr, callback) { callback = callback || function () {}; if (!arr.length) { return callback(null, []); } var index = 0; var results = new Array(arr.length); arr.forEach(function (fn, position) { fn(function (err, result) { if (err) { callback(err); callback = function () {}; } else { index++; results[position] = result; if (index >= arr.length) { callback(null, results); } } }); }); }, bootstrap: function(fn) { // Add our static methods Object.keys(fn._static_methods).forEach(function(key) { fn[key] = fn._static_methods[key].bind(fn); }); // Add our properties. Object.keys(fn._properties).forEach(function(key) { fn.addProp(key, fn._properties[key]); }); return fn; } }; // Accepts a contract object created with web3.eth.contract. // Optionally, if called without `new`, accepts a network_id and will // create a new version of the contract abstraction with that network_id set. function Contract(contract) { var self = this; var constructor = this.constructor; this.abi = constructor.abi; if (typeof contract == "string") { var address = contract; var contract_class = constructor.web3.eth.contract(this.abi); contract = contract_class.at(address); } this.contract = contract; // Provision our functions. for (var i = 0; i < this.abi.length; i++) { var item = this.abi[i]; if (item.type == "function") { if (item.constant == true) { this[item.name] = Utils.promisifyFunction(contract[item.name], constructor); } else { this[item.name] = Utils.synchronizeFunction(contract[item.name], this, constructor); } this[item.name].call = Utils.promisifyFunction(contract[item.name].call, constructor); this[item.name].sendTransaction = Utils.promisifyFunction(contract[item.name].sendTransaction, constructor); this[item.name].request = contract[item.name].request; this[item.name].estimateGas = Utils.promisifyFunction(contract[item.name].estimateGas, constructor); } if (item.type == "event") { this[item.name] = contract[item.name]; } } this.sendTransaction = Utils.synchronizeFunction(function(tx_params, callback) { if (typeof tx_params == "function") { callback = tx_params; tx_params = {}; } tx_params.to = self.address; constructor.web3.eth.sendTransaction.apply(constructor.web3.eth, [tx_params, callback]); }, this, constructor); this.send = function(value) { return self.sendTransaction({value: value}); }; this.allEvents = contract.allEvents; this.address = contract.address; this.transactionHash = contract.transactionHash; }; Contract._static_methods = { setProvider: function(provider) { if (!provider) { throw new Error("Invalid provider passed to setProvider(); provider is " + provider); } var wrapped = new Provider(provider); this.web3.setProvider(wrapped); this.currentProvider = provider; }, new: function() { var self = this; if (this.currentProvider == null) { throw new Error(this.contract_name + " error: Please call setProvider() first before calling new()."); } var args = Array.prototype.slice.call(arguments); if (!this.unlinked_binary) { throw new Error(this._json.contract_name + " error: contract binary not set. Can't deploy new instance."); } return self.detectNetwork().then(function(network_id) { // After the network is set, check to make sure everything's ship shape. var regex = /__[^_]+_+/g; var unlinked_libraries = self.binary.match(regex); if (unlinked_libraries != null) { unlinked_libraries = unlinked_libraries.map(function(name) { // Remove underscores return name.replace(/_/g, ""); }).sort().filter(function(name, index, arr) { // Remove duplicates if (index + 1 >= arr.length) { return true; } return name != arr[index + 1]; }).join(", "); throw new Error(self.contract_name + " contains unresolved libraries. You must deploy and link the following libraries before you can deploy a new version of " + self._json.contract_name + ": " + unlinked_libraries); } }).then(function() { return new Promise(function(accept, reject) { var contract_class = self.web3.eth.contract(self.abi); var tx_params = {}; var last_arg = args[args.length - 1]; // It's only tx_params if it's an object and not a BigNumber. if (Utils.is_object(last_arg) && !Utils.is_big_number(last_arg)) { tx_params = args.pop(); } tx_params = Utils.merge(self.class_defaults, tx_params); if (tx_params.data == null) { tx_params.data = self.binary; } // web3 0.9.0 and above calls new this callback twice. // Why, I have no idea... var intermediary = function(err, web3_instance) { if (err != null) { reject(err); return; } if (err == null && web3_instance != null && web3_instance.address != null) { accept(new self(web3_instance)); } }; args.push(tx_params, intermediary); contract_class.new.apply(contract_class, args); }); }); }, at: function(address) { var self = this; if (address == null || typeof address != "string" || address.length != 42) { throw new Error("Invalid address passed to " + this._json.contract_name + ".at(): " + address); } var contract = new this(address); // Add thennable to allow people opt into new recommended usage. contract.then = function(fn) { return self.detectNetwork().then(function(network_id) { var instance = new self(address); return new Promise(function(accept, reject) { self.web3.eth.getCode(address, function(err, code) { if (err) return reject(err); if (!code || new BigNumber(code).eq(0)) { return reject(new Error("Cannot create instance of " + self.contract_name + "; no code at address " + address)); } accept(instance); }); }); }).then(fn); }; return contract; }, deployed: function() { var self = this; var val = {}; //this.at(this.address); // Add thennable to allow people to opt into new recommended usage. val.then = function(fn) { return self.detectNetwork().then(function() { // We don't have a network config for the one we found if (self._json.networks[self.network_id] == null) { throw new Error(self.contract_name + " has not been deployed to detected network (network/artifact mismatch)"); } // If we found the network but it's not deployed if (!self.isDeployed()) { throw new Error(self.contract_name + " has not been deployed to detected network (" + self.network_id + ")"); } return new self(self.address); }).then(fn); }; return val; }, defaults: function(class_defaults) { if (this.class_defaults == null) { this.class_defaults = {}; } if (class_defaults == null) { class_defaults = {}; } var self = this; Object.keys(class_defaults).forEach(function(key) { var value = class_defaults[key]; self.class_defaults[key] = value; }); return this.class_defaults; }, hasNetwork: function(network_id) { return this._json.networks[network_id + ""] != null; }, isDeployed: function() { if (this.network_id == null) { return false; } if (this._json.networks[this.network_id] == null) { return false; } return !!this.network.address; }, detectNetwork: function() { var self = this; return new Promise(function(accept, reject) { // Try to detect the network we have artifacts for. if (self.network_id) { // We have a network id and a configuration, let's go with it. if (self.networks[self.network_id] != null) { return accept(self.network_id); } } self.web3.version.getNetwork(function(err, result) { if (err) return reject(err); var network_id = result.toString(); // If we found the network via a number, let's use that. if (self.hasNetwork(network_id)) { self.setNetwork(network_id); return accept(); } // Otherwise, go through all the networks that are listed as // blockchain uris and see if they match. var uris = Object.keys(self._json.networks).filter(function(network) { return network.indexOf("blockchain://") == 0; }); var matches = uris.map(function(uri) { return BlockchainUtils.matches.bind(BlockchainUtils, uri, self.web3.currentProvider); }); Utils.parallel(matches, function(err, results) { if (err) return reject(err); for (var i = 0; i < results.length; i++) { if (results[i]) { self.setNetwork(uris[i]); return accept(); } } // We found nothing. Set the network id to whatever the provider states. self.setNetwork(network_id); accept(); }); }); }); }, setNetwork: function(network_id) { if (!network_id) return; this.network_id = network_id + ""; }, // Overrides the deployed address to null. // You must call this explicitly so you don't inadvertently do this otherwise. resetAddress: function() { delete this.network.address; }, link: function(name, address) { var self = this; if (typeof name == "function") { var contract = name; if (contract.isDeployed() == false) { throw new Error("Cannot link contract without an address."); } this.link(contract.contract_name, contract.address); // Merge events so this contract knows about library's events Object.keys(contract.events).forEach(function(topic) { self.network.events[topic] = contract.events[topic]; }); return; } if (typeof name == "object") { var obj = name; Object.keys(obj).forEach(function(name) { var a = obj[name]; self.link(name, a); }); return; } if (this._json.networks[this.network_id] == null) { this._json.networks[this.network_id] = { events: {}, links: {} }; } this.network.links[name] = address; }, clone: function(options) { var self = this; var temp = function TruffleContract() { this.constructor = temp; return Contract.apply(this, arguments); }; var json = options; var network_id; if (typeof options != "object") { json = self._json; network_id = options; options = {}; } temp.prototype = Object.create(self.prototype); temp._static_methods = this._static_methods; temp._properties = this._properties; temp._property_values = {}; temp._json = json || {}; Utils.bootstrap(temp); temp.web3 = new Web3(); temp.class_defaults = temp.prototype.defaults || {}; if (network_id) { temp.setNetwork(network_id); } // Copy over custom options Object.keys(options).forEach(function(key) { if (key.indexOf("x-") != 0) return; temp[key] = options[key]; }); return temp; }, addProp: function(key, fn) { var self = this; var getter = function() { if (fn.get != null) { return fn.get.call(self); } return self._property_values[key] || fn.call(self); } var setter = function(val) { if (fn.set != null) { fn.set.call(self, val); return; } // If there's not a setter, then the property is immutable. throw new Error(key + " property is immutable"); }; var definition = {}; definition.enumerable = false; definition.configurable = false; definition.get = getter; definition.set = setter; Object.defineProperty(this, key, definition); }, toJSON: function() { return this._json; } }; // Getter functions are scoped to Contract object. Contract._properties = { contract_name: { get: function() { return this._json.contract_name; }, set: function(val) { this._json.contract_name = val; } }, abi: { get: function() { return this._json.abi; }, set: function(val) { this._json.abi = val; } }, network: function() { var network_id = this.network_id; if (network_id == null) { throw new Error(this.contract_name + " has no network id set, cannot lookup artifact data. Either set the network manually using " + this.contract_name + ".setNetwork(), run " + this.contract_name + ".detectNetwork(), or use new(), at() or deployed() as a thenable which will detect the network automatically."); } // TODO: this might be bad; setting a value on a get. if (this._json.networks[network_id] == null) { throw new Error(this.contract_name + " has no network configuration for its current network id (" + network_id + ")."); } return this._json.networks[network_id]; }, networks: function() { return this._json.networks; }, address: { get: function() { var address = this.network.address; if (address == null) { throw new Error("Cannot find deployed address: " + this.contract_name + " not deployed or address not set."); } return address; }, set: function(val) { if (val == null) { throw new Error("Cannot set deployed address; malformed value: " + val); } var network_id = this.network_id; if (network_id == null) { throw new Error(this.contract_name + " has no network id set, cannot lookup artifact data. Either set the network manually using " + this.contract_name + ".setNetwork(), run " + this.contract_name + ".detectNetwork(), or use new(), at() or deployed() as a thenable which will detect the network automatically."); } // Create a network if we don't have one. if (this._json.networks[network_id] == null) { this._json.networks[network_id] = { events: {}, links: {} }; } // Finally, set the address. this.network.address = val; } }, links: function() { if (this._json.networks[this.network_id] == null) { return {}; } return this.network.links || {}; }, events: function() { // helper web3; not used for provider var web3 = new Web3(); var events; if (this._json.networks[this.network_id] == null) { events = {}; } else { events = this.network.events || {}; } // Merge abi events with whatever's returned. var abi = this.abi; abi.forEach(function(item) { if (item.type != "event") return; var signature = item.name + "("; item.inputs.forEach(function(input, index) { signature += input.type; if (index < item.inputs.length - 1) { signature += ","; } }); signature += ")"; var topic = web3.sha3(signature); events[topic] = item; }); return events; }, binary: function() { var self = this; var binary = this.unlinked_binary; Object.keys(this.links).forEach(function(library_name) { var library_address = self.links[library_name]; var regex = new RegExp("__" + library_name + "_*", "g"); binary = binary.replace(regex, library_address.replace("0x", "")); }); return binary; }, unlinked_binary: { get: function() { return this._json.unlinked_binary; }, set: function(val) { // TODO: Ensure 0x prefix. this._json.unlinked_binary = val; } }, schema_version: function() { return this._json.schema_version; }, updated_at: function() { try { return this.network.updated_at || this._json.updated_at; } catch (e) { return this._json.updated_at; } } }; Utils.bootstrap(Contract); module.exports = Contract; return Contract; })(module || {}); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"ethjs-abi":7,"truffle-blockchain-utils":15,"web3":5}],2:[function(require,module,exports){ var Schema = require("truffle-contract-schema"); var Contract = require("./contract.js"); var contract = function(options) { options = Schema.normalizeOptions(options); var binary = Schema.generateBinary(options, {}, {dirty: false}); // Note we don't use `new` here at all. This will cause the class to // "mutate" instead of instantiate an instance. return Contract.clone(binary); }; // To be used to upgrade old .sol.js abstractions contract.fromSolJS = function(soljs_abstraction, ignore_default_network) { if (ignore_default_network == null) { ignore_default_network = false; } // Find the latest binary var latest_network = null; var latest_network_updated_at = 0; var networks = {}; Object.keys(soljs_abstraction.all_networks).forEach(function(network_name) { if (network_name == "default") { if (ignore_default_network == true ) { return; } else { throw new Error(soljs_abstraction.contract_name + " has legacy 'default' network artifacts stored within it. Generally these artifacts were a result of running Truffle on a development environment -- in order to store contracts with truffle-contract, all networks must have an identified id. If you're sure this default network represents your development environment, you can ignore processing of the default network by passing `true` as the second argument to this function. However, if you think this network represents artifacts you'd like to keep (i.e., addresses deployed to the main network), you'll need to edit your .sol.js file yourself and change the default network id to be the id of your desired network. For most people, ignoring the default network is the correct option."); } } if (soljs_abstraction.all_networks[network_name].updated_at > latest_network_updated_at) { latest_network = network_name; latest_network_updated_at = soljs_abstraction.all_networks[network_name].updated_at; } networks[network_name] = {}; ["address", "events", "links", "updated_at"].forEach(function(key) { networks[network_name][key] = soljs_abstraction.all_networks[network_name][key]; }) }); latest_network = soljs_abstraction.all_networks[latest_network] || {}; var json = { contract_name: soljs_abstraction.contract_name, unlinked_binary: latest_network.unlinked_binary, abi: latest_network.abi, networks: networks, updated_at: latest_network_updated_at == 0 ? undefined : latest_network_updated_at }; return contract(json); }; module.exports = contract; if (typeof window !== "undefined") { window.TruffleContract = contract; } },{"./contract.js":1,"truffle-contract-schema":16}],3:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i] revLookup[code.charCodeAt(i)] = i } revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 function placeHoldersCount (b64) { var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 } function byteLength (b64) { // base64 is 4/3 + up to two characters of the original data return b64.length * 3 / 4 - placeHoldersCount(b64) } function toByteArray (b64) { var i, j, l, tmp, placeHolders, arr var len = b64.length placeHolders = placeHoldersCount(b64) arr = new Arr(len * 3 / 4 - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? len - 4 : len var L = 0 for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[L++] = (tmp >> 16) & 0xFF arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } if (placeHolders === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[L++] = tmp & 0xFF } else if (placeHolders === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } return arr } function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } function encodeChunk (uint8, start, end) { var tmp var output = [] for (var i = start; i < end; i += 3) { tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output.push(tripletToBase64(tmp)) } return output.join('') } function fromByteArray (uint8) { var tmp var len = uint8.length var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes var output = '' var parts = [] var maxChunkLength = 16383 // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1] output += lookup[tmp >> 2] output += lookup[(tmp << 4) & 0x3F] output += '==' } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) output += lookup[tmp >> 10] output += lookup[(tmp >> 4) & 0x3F] output += lookup[(tmp << 2) & 0x3F] output += '=' } parts.push(output) return parts.join('') } },{}],4:[function(require,module,exports){ (function (module, exports) { 'use strict'; // Utils function assert (val, msg) { if (!val) throw new Error(msg || 'Assertion failed'); } // Could use `inherits` module, but don't want to move from single file // architecture yet. function inherits (ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } // BN function BN (number, base, endian) { if (BN.isBN(number)) { return number; } this.negative = 0; this.words = null; this.length = 0; // Reduction context this.red = null; if (number !== null) { if (base === 'le' || base === 'be') { endian = base; base = 10; } this._init(number || 0, base || 10, endian || 'be'); } } if (typeof module === 'object') { module.exports = BN; } else { exports.BN = BN; } BN.BN = BN; BN.wordSize = 26; var Buffer; try { Buffer = require('buf' + 'fer').Buffer; } catch (e) { } BN.isBN = function isBN (num) { if (num instanceof BN) { return true; } return num !== null && typeof num === 'object' && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); }; BN.max = function max (left, right) { if (left.cmp(right) > 0) return left; return right; }; BN.min = function min (left, right) { if (left.cmp(right) < 0) return left; return right; }; BN.prototype._init = function init (number, base, endian) { if (typeof number === 'number') { return this._initNumber(number, base, endian); } if (typeof number === 'object') { return this._initArray(number, base, endian); } if (base === 'hex') { base = 16; } assert(base === (base | 0) && base >= 2 && base <= 36); number = number.toString().replace(/\s+/g, ''); var start = 0; if (number[0] === '-') { start++; } if (base === 16) { this._parseHex(number, start); } else { this._parseBase(number, base, start); } if (number[0] === '-') { this.negative = 1; } this.strip(); if (endian !== 'le') return; this._initArray(this.toArray(), base, endian); }; BN.prototype._initNumber = function _initNumber (number, base, endian) { if (number < 0) { this.negative = 1; number = -number; } if (number < 0x4000000) { this.words = [ number & 0x3ffffff ]; this.length = 1; } else if (number < 0x10000000000000) { this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff ]; this.length = 2; } else { assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff, 1 ]; this.length = 3; } if (endian !== 'le') return; // Reverse the bytes this._initArray(this.toArray(), base, endian); }; BN.prototype._initArray = function _initArray (number, base, endian) { // Perhaps a Uint8Array assert(typeof number.length === 'number'); if (number.length <= 0) { this.words = [ 0 ]; this.length = 1; return this; } this.length = Math.ceil(number.length / 3); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } var j, w; var off = 0; if (endian === 'be') { for (i = number.length - 1, j = 0; i >= 0; i -= 3) { w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } else if (endian === 'le') { for (i = 0, j = 0; i < number.length; i += 3) { w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } return this.strip(); }; function parseHex (str, start, end) { var r = 0; var len = Math.min(str.length, end); for (var i = start; i < len; i++) { var c = str.charCodeAt(i) - 48; r <<= 4; // 'a' - 'f' if (c >= 49 && c <= 54) { r |= c - 49 + 0xa; // 'A' - 'F' } else if (c >= 17 && c <= 22) { r |= c - 17 + 0xa; // '0' - '9' } else { r |= c & 0xf; } } return r; } BN.prototype._parseHex = function _parseHex (number, start) { // Create possibly bigger array to ensure that it fits the number this.length = Math.ceil((number.length - start) / 6); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } var j, w; // Scan 24-bit chunks and add them to the number var off = 0; for (i = number.length - 6, j = 0; i >= start; i -= 6) { w = parseHex(number, i, i + 6); this.words[j] |= (w << off) & 0x3ffffff; // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; off += 24; if (off >= 26) { off -= 26; j++; } } if (i + 6 !== start) { w = parseHex(number, start, i + 6); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; } this.strip(); }; function parseBase (str, start, end, mul) { var r = 0; var len = Math.min(str.length, end); for (var i = start; i < len; i++) { var c = str.charCodeAt(i) - 48; r *= mul; // 'a' if (c >= 49) { r += c - 49 + 0xa; // 'A' } else if (c >= 17) { r += c - 17 + 0xa; // '0' - '9' } else { r += c; } } return r; } BN.prototype._parseBase = function _parseBase (number, base, start) { // Initialize as zero this.words = [ 0 ]; this.length = 1; // Find length of limb in base for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { limbLen++; } limbLen--; limbPow = (limbPow / base) | 0; var total = number.length - start; var mod = total % limbLen; var end = Math.min(total, total - mod) + start; var word = 0; for (var i = start; i < end; i += limbLen) { word = parseBase(number, i, i + limbLen, base); this.imuln(limbPow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } if (mod !== 0) { var pow = 1; word = parseBase(number, i, number.length, base); for (i = 0; i < mod; i++) { pow *= base; } this.imuln(pow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } }; BN.prototype.copy = function copy (dest) { dest.words = new Array(this.length); for (var i = 0; i < this.length; i++) { dest.words[i] = this.words[i]; } dest.length = this.length; dest.negative = this.negative; dest.red = this.red; }; BN.prototype.clone = function clone () { var r = new BN(null); this.copy(r); return r; }; BN.prototype._expand = function _expand (size) { while (this.length < size) { this.words[this.length++] = 0; } return this; }; // Remove leading `0` from `this` BN.prototype.strip = function strip () { while (this.length > 1 && this.words[this.length - 1] === 0) { this.length--; } return this._normSign(); }; BN.prototype._normSign = function _normSign () { // -0 = 0 if (this.length === 1 && this.words[0] === 0) { this.negative = 0; } return this; }; BN.prototype.inspect = function inspect () { return (this.red ? ''; }; /* var zeros = []; var groupSizes = []; var groupBases = []; var s = ''; var i = -1; while (++i < BN.wordSize) { zeros[i] = s; s += '0'; } groupSizes[0] = 0; groupSizes[1] = 0; groupBases[0] = 0; groupBases[1] = 0; var base = 2 - 1; while (++base < 36 + 1) { var groupSize = 0; var groupBase = 1; while (groupBase < (1 << BN.wordSize) / base) { groupBase *= base; groupSize += 1; } groupSizes[base] = groupSize; groupBases[base] = groupBase; } */ var zeros = [ '', '0', '00', '000', '0000', '00000', '000000', '0000000', '00000000', '000000000', '0000000000', '00000000000', '000000000000', '0000000000000', '00000000000000', '000000000000000', '0000000000000000', '00000000000000000', '000000000000000000', '0000000000000000000', '00000000000000000000', '000000000000000000000', '0000000000000000000000', '00000000000000000000000', '000000000000000000000000', '0000000000000000000000000' ]; var groupSizes = [ 0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 ]; var groupBases = [ 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 ]; BN.prototype.toString = function toString (base, padding) { base = base || 10; padding = padding | 0 || 1; var out; if (base === 16 || base === 'hex') { out = ''; var off = 0; var carry = 0; for (var i = 0; i < this.length; i++) { var w = this.words[i]; var word = (((w << off) | carry) & 0xffffff).toString(16); carry = (w >>> (24 - off)) & 0xffffff; if (carry !== 0 || i !== this.length - 1) { out = zeros[6 - word.length] + word + out; } else { out = word + out; } off += 2; if (off >= 26) { off -= 26; i--; } } if (carry !== 0) { out = carry.toString(16) + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } if (base === (base | 0) && base >= 2 && base <= 36) { // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); var groupSize = groupSizes[base]; // var groupBase = Math.pow(base, groupSize); var groupBase = groupBases[base]; out = ''; var c = this.clone(); c.negative = 0; while (!c.isZero()) { var r = c.modn(groupBase).toString(base); c = c.idivn(groupBase); if (!c.isZero()) { out = zeros[groupSize - r.length] + r + out; } else { out = r + out; } } if (this.isZero()) { out = '0' + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } assert(false, 'Base should be between 2 and 36'); }; BN.prototype.toNumber = function toNumber () { var ret = this.words[0]; if (this.length === 2) { ret += this.words[1] * 0x4000000; } else if (this.length === 3 && this.words[2] === 0x01) { // NOTE: at this stage it is known that the top bit is set ret += 0x10000000000000 + (this.words[1] * 0x4000000); } else if (this.length > 2) { assert(false, 'Number can only safely store up to 53 bits'); } return (this.negative !== 0) ? -ret : ret; }; BN.prototype.toJSON = function toJSON () { return this.toString(16); }; BN.prototype.toBuffer = function toBuffer (endian, length) { assert(typeof Buffer !== 'undefined'); return this.toArrayLike(Buffer, endian, length); }; BN.prototype.toArray = function toArray (endian, length) { return this.toArrayLike(Array, endian, length); }; BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { var byteLength = this.byteLength(); var reqLength = length || Math.max(1, byteLength); assert(byteLength <= reqLength, 'byte array longer than desired length'); assert(reqLength > 0, 'Requested array length <= 0'); this.strip(); var littleEndian = endian === 'le'; var res = new ArrayType(reqLength); var b, i; var q = this.clone(); if (!littleEndian) { // Assume big-endian for (i = 0; i < reqLength - byteLength; i++) { res[i] = 0; } for (i = 0; !q.isZero(); i++) { b = q.andln(0xff); q.iushrn(8); res[reqLength - i - 1] = b; } } else { for (i = 0; !q.isZero(); i++) { b = q.andln(0xff); q.iushrn(8); res[i] = b; } for (; i < reqLength; i++) { res[i] = 0; } } return res; }; if (Math.clz32) { BN.prototype._countBits = function _countBits (w) { return 32 - Math.clz32(w); }; } else { BN.prototype._countBits = function _countBits (w) { var t = w; var r = 0; if (t >= 0x1000) { r += 13; t >>>= 13; } if (t >= 0x40) { r += 7; t >>>= 7; } if (t >= 0x8) { r += 4; t >>>= 4; } if (t >= 0x02) { r += 2; t >>>= 2; } return r + t; }; } BN.prototype._zeroBits = function _zeroBits (w) { // Short-cut if (w === 0) return 26; var t = w; var r = 0; if ((t & 0x1fff) === 0) { r += 13; t >>>= 13; } if ((t & 0x7f) === 0) { r += 7; t >>>= 7; } if ((t & 0xf) === 0) { r += 4; t >>>= 4; } if ((t & 0x3) === 0) { r += 2; t >>>= 2; } if ((t & 0x1) === 0) { r++; } return r; }; // Return number of used bits in a BN BN.prototype.bitLength = function bitLength () { var w = this.words[this.length - 1]; var hi = this._countBits(w); return (this.length - 1) * 26 + hi; }; function toBitArray (num) { var w = new Array(num.bitLength()); for (var bit = 0; bit < w.length; bit++) { var off = (bit / 26) | 0; var wbit = bit % 26; w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; } return w; } // Number of trailing zero bits BN.prototype.zeroBits = function zeroBits () { if (this.isZero()) return 0; var r = 0; for (var i = 0; i < this.length; i++) { var b = this._zeroBits(this.words[i]); r += b; if (b !== 26) break; } return r; }; BN.prototype.byteLength = function byteLength () { return Math.ceil(this.bitLength() / 8); }; BN.prototype.toTwos = function toTwos (width) { if (this.negative !== 0) { return this.abs().inotn(width).iaddn(1); } return this.clone(); }; BN.prototype.fromTwos = function fromTwos (width) { if (this.testn(width - 1)) { return this.notn(width).iaddn(1).ineg(); } return this.clone(); }; BN.prototype.isNeg = function isNeg () { return this.negative !== 0; }; // Return negative clone of `this` BN.prototype.neg = function neg () { return this.clone().ineg(); }; BN.prototype.ineg = function ineg () { if (!this.isZero()) { this.negative ^= 1; } return this; }; // Or `num` with `this` in-place BN.prototype.iuor = function iuor (num) { while (this.length < num.length) { this.words[this.length++] = 0; } for (var i = 0; i < num.length; i++) { this.words[i] = this.words[i] | num.words[i]; } return this.strip(); }; BN.prototype.ior = function ior (num) { assert((this.negative | num.negative) === 0); return this.iuor(num); }; // Or `num` with `this` BN.prototype.or = function or (num) { if (this.length > num.length) return this.clone().ior(num); return num.clone().ior(this); }; BN.prototype.uor = function uor (num) { if (this.length > num.length) return this.clone().iuor(num); return num.clone().iuor(this); }; // And `num` with `this` in-place BN.prototype.iuand = function iuand (num) { // b = min-length(num, this) var b; if (this.length > num.length) { b = num; } else { b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = this.words[i] & num.words[i]; } this.length = b.length; return this.strip(); }; BN.prototype.iand = function iand (num) { assert((this.negative | num.negative) === 0); return this.iuand(num); }; // And `num` with `this` BN.prototype.and = function and (num) { if (this.length > num.length) return this.clone().iand(num); return num.clone().iand(this); }; BN.prototype.uand = function uand (num) { if (this.length > num.length) return this.clone().iuand(num); return num.clone().iuand(this); }; // Xor `num` with `this` in-place BN.prototype.iuxor = function iuxor (num) { // a.length > b.length var a; var b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = a.words[i] ^ b.words[i]; } if (this !== a) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = a.length; return this.strip(); }; BN.prototype.ixor = function ixor (num) { assert((this.negative | num.negative) === 0); return this.iuxor(num); }; // Xor `num` with `this` BN.prototype.xor = function xor (num) { if (this.length > num.length) return this.clone().ixor(num); return num.clone().ixor(this); }; BN.prototype.uxor = function uxor (num) { if (this.length > num.length) return this.clone().iuxor(num); return num.clone().iuxor(this); }; // Not ``this`` with ``width`` bitwidth BN.prototype.inotn = function inotn (width) { assert(typeof width === 'number' && width >= 0); var bytesNeeded = Math.ceil(width / 26) | 0; var bitsLeft = width % 26; // Extend the buffer with leading zeroes this._expand(bytesNeeded); if (bitsLeft > 0) { bytesNeeded--; } // Handle complete words for (var i = 0; i < bytesNeeded; i++) { this.words[i] = ~this.words[i] & 0x3ffffff; } // Handle the residue if (bitsLeft > 0) { this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); } // And remove leading zeroes return this.strip(); }; BN.prototype.notn = function notn (width) { return this.clone().inotn(width); }; // Set `bit` of `this` BN.prototype.setn = function setn (bit, val) { assert(typeof bit === 'number' && bit >= 0); var off = (bit / 26) | 0; var wbit = bit % 26; this._expand(off + 1); if (val) { this.words[off] = this.words[off] | (1 << wbit); } else { this.words[off] = this.words[off] & ~(1 << wbit); } return this.strip(); }; // Add `num` to `this` in-place BN.prototype.iadd = function iadd (num) { var r; // negative + positive if (this.negative !== 0 && num.negative === 0) { this.negative = 0; r = this.isub(num); this.negative ^= 1; return this._normSign(); // positive + negative } else if (this.negative === 0 && num.negative !== 0) { num.negative = 0; r = this.isub(num); num.negative = 1; return r._normSign(); } // a.length > b.length var a, b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) + (b.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } this.length = a.length; if (carry !== 0) { this.words[this.length] = carry; this.length++; // Copy the rest of the words } else if (a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } return this; }; // Add `num` to `this` BN.prototype.add = function add (num) { var res; if (num.negative !== 0 && this.negative === 0) { num.negative = 0; res = this.sub(num); num.negative ^= 1; return res; } else if (num.negative === 0 && this.negative !== 0) { this.negative = 0; res = num.sub(this); this.negative = 1; return res; } if (this.length > num.length) return this.clone().iadd(num); return num.clone().iadd(this); }; // Subtract `num` from `this` in-place BN.prototype.isub = function isub (num) { // this - (-num) = this + num if (num.negative !== 0) { num.negative = 0; var r = this.iadd(num); num.negative = 1; return r._normSign(); // -this - num = -(this + num) } else if (this.negative !== 0) { this.negative = 0; this.iadd(num); this.negative = 1; return this._normSign(); } // At this point both numbers are positive var cmp = this.cmp(num); // Optimization - zeroify if (cmp === 0) { this.negative = 0; this.length = 1; this.words[0] = 0; return this; } // a > b var a, b; if (cmp > 0) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) - (b.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } // Copy rest of the words if (carry === 0 && i < a.length && a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = Math.max(this.length, i); if (a !== this) { this.negative = 1; } return this.strip(); }; // Subtract `num` from `this` BN.prototype.sub = function sub (num) { return this.clone().isub(num); }; function smallMulTo (self, num, out) { out.negative = num.negative ^ self.negative; var len = (self.length + num.length) | 0; out.length = len; len = (len - 1) | 0; // Peel one iteration (compiler can't do it, because of code complexity) var a = self.words[0] | 0; var b = num.words[0] | 0; var r = a * b; var lo = r & 0x3ffffff; var carry = (r / 0x4000000) | 0; out.words[0] = lo; for (var k = 1; k < len; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff var ncarry = carry >>> 26; var rword = carry & 0x3ffffff; var maxJ = Math.min(k, num.length - 1); for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { var i = (k - j) | 0; a = self.words[i] | 0; b = num.words[j] | 0; r = a * b + rword; ncarry += (r / 0x4000000) | 0; rword = r & 0x3ffffff; } out.words[k] = rword | 0; carry = ncarry | 0; } if (carry !== 0) { out.words[k] = carry | 0; } else { out.length--; } return out.strip(); } // TODO(indutny): it may be reasonable to omit it for users who don't need // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit // multiplication (like elliptic secp256k1). var comb10MulTo = function comb10MulTo (self, num, out) { var a = self.words; var b = num.words; var o = out.words; var c = 0; var lo; var mid; var hi; var a0 = a[0] | 0; var al0 = a0 & 0x1fff; var ah0 = a0 >>> 13; var a1 = a[1] | 0; var al1 = a1 & 0x1fff; var ah1 = a1 >>> 13; var a2 = a[2] | 0; var al2 = a2 & 0x1fff; var ah2 = a2 >>> 13; var a3 = a[3] | 0; var al3 = a3 & 0x1fff; var ah3 = a3 >>> 13; var a4 = a[4] | 0; var al4 = a4 & 0x1fff; var ah4 = a4 >>> 13; var a5 = a[5] | 0; var al5 = a5 & 0x1fff; var ah5 = a5 >>> 13; var a6 = a[6] | 0; var al6 = a6 & 0x1fff; var ah6 = a6 >>> 13; var a7 = a[7] | 0; var al7 = a7 & 0x1fff; var ah7 = a7 >>> 13; var a8 = a[8] | 0; var al8 = a8 & 0x1fff; var ah8 = a8 >>> 13; var a9 = a[9] | 0; var al9 = a9 & 0x1fff; var ah9 = a9 >>> 13; var b0 = b[0] | 0; var bl0 = b0 & 0x1fff; var bh0 = b0 >>> 13; var b1 = b[1] | 0; var bl1 = b1 & 0x1fff; var bh1 = b1 >>> 13; var b2 = b[2] | 0; var bl2 = b2 & 0x1fff; var bh2 = b2 >>> 13; var b3 = b[3] | 0; var bl3 = b3 & 0x1fff; var bh3 = b3 >>> 13; var b4 = b[4] | 0; var bl4 = b4 & 0x1fff; var bh4 = b4 >>> 13; var b5 = b[5] | 0; var bl5 = b5 & 0x1fff; var bh5 = b5 >>> 13; var b6 = b[6] | 0; var bl6 = b6 & 0x1fff; var bh6 = b6 >>> 13; var b7 = b[7] | 0; var bl7 = b7 & 0x1fff; var bh7 = b7 >>> 13; var b8 = b[8] | 0; var bl8 = b8 & 0x1fff; var bh8 = b8 >>> 13; var b9 = b[9] | 0; var bl9 = b9 & 0x1fff; var bh9 = b9 >>> 13; out.negative = self.negative ^ num.negative; out.length = 19; /* k = 0 */ lo = Math.imul(al0, bl0); mid = Math.imul(al0, bh0); mid = (mid + Math.imul(ah0, bl0)) | 0; hi = Math.imul(ah0, bh0); var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; w0 &= 0x3ffffff; /* k = 1 */ lo = Math.imul(al1, bl0); mid = Math.imul(al1, bh0); mid = (mid + Math.imul(ah1, bl0)) | 0; hi = Math.imul(ah1, bh0); lo = (lo + Math.imul(al0, bl1)) | 0; mid = (mid + Math.imul(al0, bh1)) | 0; mid = (mid + Math.imul(ah0, bl1)) | 0; hi = (hi + Math.imul(ah0, bh1)) | 0; var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; w1 &= 0x3ffffff; /* k = 2 */ lo = Math.imul(al2, bl0); mid = Math.imul(al2, bh0); mid = (mid + Math.imul(ah2, bl0)) | 0; hi = Math.imul(ah2, bh0); lo = (lo + Math.imul(al1, bl1)) | 0; mid = (mid + Math.imul(al1, bh1)) | 0; mid = (mid + Math.imul(ah1, bl1)) | 0; hi = (hi + Math.imul(ah1, bh1)) | 0; lo = (lo + Math.imul(al0, bl2)) | 0; mid = (mid + Math.imul(al0, bh2)) | 0; mid = (mid + Math.imul(ah0, bl2)) | 0; hi = (hi + Math.imul(ah0, bh2)) | 0; var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; w2 &= 0x3ffffff; /* k = 3 */ lo = Math.imul(al3, bl0); mid = Math.imul(al3, bh0); mid = (mid + Math.imul(ah3, bl0)) | 0; hi = Math.imul(ah3, bh0); lo = (lo + Math.imul(al2, bl1)) | 0; mid = (mid + Math.imul(al2, bh1)) | 0; mid = (mid + Math.imul(ah2, bl1)) | 0; hi = (hi + Math.imul(ah2, bh1)) | 0; lo = (lo + Math.imul(al1, bl2)) | 0; mid = (mid + Math.imul(al1, bh2)) | 0; mid = (mid + Math.imul(ah1, bl2)) | 0; hi = (hi + Math.imul(ah1, bh2)) | 0; lo = (lo + Math.imul(al0, bl3)) | 0; mid = (mid + Math.imul(al0, bh3)) | 0; mid = (mid + Math.imul(ah0, bl3)) | 0; hi = (hi + Math.imul(ah0, bh3)) | 0; var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; w3 &= 0x3ffffff; /* k = 4 */ lo = Math.imul(al4, bl0); mid = Math.imul(al4, bh0); mid = (mid + Math.imul(ah4, bl0)) | 0; hi = Math.imul(ah4, bh0); lo = (lo + Math.imul(al3, bl1)) | 0; mid = (mid + Math.imul(al3, bh1)) | 0; mid = (mid + Math.imul(ah3, bl1)) | 0; hi = (hi + Math.imul(ah3, bh1)) | 0; lo = (lo + Math.imul(al2, bl2)) | 0; mid = (mid + Math.imul(al2, bh2)) | 0; mid = (mid + Math.imul(ah2, bl2)) | 0; hi = (hi + Math.imul(ah2, bh2)) | 0; lo = (lo + Math.imul(al1, bl3)) | 0; mid = (mid + Math.imul(al1, bh3)) | 0; mid = (mid + Math.imul(ah1, bl3)) | 0; hi = (hi + Math.imul(ah1, bh3)) | 0; lo = (lo + Math.imul(al0, bl4)) | 0; mid = (mid + Math.imul(al0, bh4)) | 0; mid = (mid + Math.imul(ah0, bl4)) | 0; hi = (hi + Math.imul(ah0, bh4)) | 0; var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; w4 &= 0x3ffffff; /* k = 5 */ lo = Math.imul(al5, bl0); mid = Math.imul(al5, bh0); mid = (mid + Math.imul(ah5, bl0)) | 0; hi = Math.imul(ah5, bh0); lo = (lo + Math.imul(al4, bl1)) | 0; mid = (mid + Math.imul(al4, bh1)) | 0; mid = (mid + Math.imul(ah4, bl1)) | 0; hi = (hi + Math.imul(ah4, bh1)) | 0; lo = (lo + Math.imul(al3, bl2)) | 0; mid = (mid + Math.imul(al3, bh2)) | 0; mid = (mid + Math.imul(ah3, bl2)) | 0; hi = (hi + Math.imul(ah3, bh2)) | 0; lo = (lo + Math.imul(al2, bl3)) | 0; mid = (mid + Math.imul(al2, bh3)) | 0; mid = (mid + Math.imul(ah2, bl3)) | 0; hi = (hi + Math.imul(ah2, bh3)) | 0; lo = (lo + Math.imul(al1, bl4)) | 0; mid = (mid + Math.imul(al1, bh4)) | 0; mid = (mid + Math.imul(ah1, bl4)) | 0; hi = (hi + Math.imul(ah1, bh4)) | 0; lo = (lo + Math.imul(al0, bl5)) | 0; mid = (mid + Math.imul(al0, bh5)) | 0; mid = (mid + Math.imul(ah0, bl5)) | 0; hi = (hi + Math.imul(ah0, bh5)) | 0; var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; w5 &= 0x3ffffff; /* k = 6 */ lo = Math.imul(al6, bl0); mid = Math.imul(al6, bh0); mid = (mid + Math.imul(ah6, bl0)) | 0; hi = Math.imul(ah6, bh0); lo = (lo + Math.imul(al5, bl1)) | 0; mid = (mid + Math.imul(al5, bh1)) | 0; mid = (mid + Math.imul(ah5, bl1)) | 0; hi = (hi + Math.imul(ah5, bh1)) | 0; lo = (lo + Math.imul(al4, bl2)) | 0; mid = (mid + Math.imul(al4, bh2)) | 0; mid = (mid + Math.imul(ah4, bl2)) | 0; hi = (hi + Math.imul(ah4, bh2)) | 0; lo = (lo + Math.imul(al3, bl3)) | 0; mid = (mid + Math.imul(al3, bh3)) | 0; mid = (mid + Math.imul(ah3, bl3)) | 0; hi = (hi + Math.imul(ah3, bh3)) | 0; lo = (lo + Math.imul(al2, bl4)) | 0; mid = (mid + Math.imul(al2, bh4)) | 0; mid = (mid + Math.imul(ah2, bl4)) | 0; hi = (hi + Math.imul(ah2, bh4)) | 0; lo = (lo + Math.imul(al1, bl5)) | 0; mid = (mid + Math.imul(al1, bh5)) | 0; mid = (mid + Math.imul(ah1, bl5)) | 0; hi = (hi + Math.imul(ah1, bh5)) | 0; lo = (lo + Math.imul(al0, bl6)) | 0; mid = (mid + Math.imul(al0, bh6)) | 0; mid = (mid + Math.imul(ah0, bl6)) | 0; hi = (hi + Math.imul(ah0, bh6)) | 0; var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; w6 &= 0x3ffffff; /* k = 7 */ lo = Math.imul(al7, bl0); mid = Math.imul(al7, bh0); mid = (mid + Math.imul(ah7, bl0)) | 0; hi = Math.imul(ah7, bh0); lo = (lo + Math.imul(al6, bl1)) | 0; mid = (mid + Math.imul(al6, bh1)) | 0; mid = (mid + Math.imul(ah6, bl1)) | 0; hi = (hi + Math.imul(ah6, bh1)) | 0; lo = (lo + Math.imul(al5, bl2)) | 0; mid = (mid + Math.imul(al5, bh2)) | 0; mid = (mid + Math.imul(ah5, bl2)) | 0; hi = (hi + Math.imul(ah5, bh2)) | 0; lo = (lo + Math.imul(al4, bl3)) | 0; mid = (mid + Math.imul(al4, bh3)) | 0; mid = (mid + Math.imul(ah4, bl3)) | 0; hi = (hi + Math.imul(ah4, bh3)) | 0; lo = (lo + Math.imul(al3, bl4)) | 0; mid = (mid + Math.imul(al3, bh4)) | 0; mid = (mid + Math.imul(ah3, bl4)) | 0; hi = (hi + Math.imul(ah3, bh4)) | 0; lo = (lo + Math.imul(al2, bl5)) | 0; mid = (mid + Math.imul(al2, bh5)) | 0; mid = (mid + Math.imul(ah2, bl5)) | 0; hi = (hi + Math.imul(ah2, bh5)) | 0; lo = (lo + Math.imul(al1, bl6)) | 0; mid = (mid + Math.imul(al1, bh6)) | 0; mid = (mid + Math.imul(ah1, bl6)) | 0; hi = (hi + Math.imul(ah1, bh6)) | 0; lo = (lo + Math.imul(al0, bl7)) | 0; mid = (mid + Math.imul(al0, bh7)) | 0; mid = (mid + Math.imul(ah0, bl7)) | 0; hi = (hi + Math.imul(ah0, bh7)) | 0; var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; w7 &= 0x3ffffff; /* k = 8 */ lo = Math.imul(al8, bl0); mid = Math.imul(al8, bh0); mid = (mid + Math.imul(ah8, bl0)) | 0; hi = Math.imul(ah8, bh0); lo = (lo + Math.imul(al7, bl1)) | 0; mid = (mid + Math.imul(al7, bh1)) | 0; mid = (mid + Math.imul(ah7, bl1)) | 0; hi = (hi + Math.imul(ah7, bh1)) | 0; lo = (lo + Math.imul(al6, bl2)) | 0; mid = (mid + Math.imul(al6, bh2)) | 0; mid = (mid + Math.imul(ah6, bl2)) | 0; hi = (hi + Math.imul(ah6, bh2)) | 0; lo = (lo + Math.imul(al5, bl3)) | 0; mid = (mid + Math.imul(al5, bh3)) | 0; mid = (mid + Math.imul(ah5, bl3)) | 0; hi = (hi + Math.imul(ah5, bh3)) | 0; lo = (lo + Math.imul(al4, bl4)) | 0; mid = (mid + Math.imul(al4, bh4)) | 0; mid = (mid + Math.imul(ah4, bl4)) | 0; hi = (hi + Math.imul(ah4, bh4)) | 0; lo = (lo + Math.imul(al3, bl5)) | 0; mid = (mid + Math.imul(al3, bh5)) | 0; mid = (mid + Math.imul(ah3, bl5)) | 0; hi = (hi + Math.imul(ah3, bh5)) | 0; lo = (lo + Math.imul(al2, bl6)) | 0; mid = (mid + Math.imul(al2, bh6)) | 0; mid = (mid + Math.imul(ah2, bl6)) | 0; hi = (hi + Math.imul(ah2, bh6)) | 0; lo = (lo + Math.imul(al1, bl7)) | 0; mid = (mid + Math.imul(al1, bh7)) | 0; mid = (mid + Math.imul(ah1, bl7)) | 0; hi = (hi + Math.imul(ah1, bh7)) | 0; lo = (lo + Math.imul(al0, bl8)) | 0; mid = (mid + Math.imul(al0, bh8)) | 0; mid = (mid + Math.imul(ah0, bl8)) | 0; hi = (hi + Math.imul(ah0, bh8)) | 0; var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; w8 &= 0x3ffffff; /* k = 9 */ lo = Math.imul(al9, bl0); mid = Math.imul(al9, bh0); mid = (mid + Math.imul(ah9, bl0)) | 0; hi = Math.imul(ah9, bh0); lo = (lo + Math.imul(al8, bl1)) | 0; mid = (mid + Math.imul(al8, bh1)) | 0; mid = (mid + Math.imul(ah8, bl1)) | 0; hi = (hi + Math.imul(ah8, bh1)) | 0; lo = (lo + Math.imul(al7, bl2)) | 0; mid = (mid + Math.imul(al7, bh2)) | 0; mid = (mid + Math.imul(ah7, bl2)) | 0; hi = (hi + Math.imul(ah7, bh2)) | 0; lo = (lo + Math.imul(al6, bl3)) | 0; mid = (mid + Math.imul(al6, bh3)) | 0; mid = (mid + Math.imul(ah6, bl3)) | 0; hi = (hi + Math.imul(ah6, bh3)) | 0; lo = (lo + Math.imul(al5, bl4)) | 0; mid = (mid + Math.imul(al5, bh4)) | 0; mid = (mid + Math.imul(ah5, bl4)) | 0; hi = (hi + Math.imul(ah5, bh4)) | 0; lo = (lo + Math.imul(al4, bl5)) | 0; mid = (mid + Math.imul(al4, bh5)) | 0; mid = (mid + Math.imul(ah4, bl5)) | 0; hi = (hi + Math.imul(ah4, bh5)) | 0; lo = (lo + Math.imul(al3, bl6)) | 0; mid = (mid + Math.imul(al3, bh6)) | 0; mid = (mid + Math.imul(ah3, bl6)) | 0; hi = (hi + Math.imul(ah3, bh6)) | 0; lo = (lo + Math.imul(al2, bl7)) | 0; mid = (mid + Math.imul(al2, bh7)) | 0; mid = (mid + Math.imul(ah2, bl7)) | 0; hi = (hi + Math.imul(ah2, bh7)) | 0; lo = (lo + Math.imul(al1, bl8)) | 0; mid = (mid + Math.imul(al1, bh8)) | 0; mid = (mid + Math.imul(ah1, bl8)) | 0; hi = (hi + Math.imul(ah1, bh8)) | 0; lo = (lo + Math.imul(al0, bl9)) | 0; mid = (mid + Math.imul(al0, bh9)) | 0; mid = (mid + Math.imul(ah0, bl9)) | 0; hi = (hi + Math.imul(ah0, bh9)) | 0; var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; w9 &= 0x3ffffff; /* k = 10 */ lo = Math.imul(al9, bl1); mid = Math.imul(al9, bh1); mid = (mid + Math.imul(ah9, bl1)) | 0; hi = Math.imul(ah9, bh1); lo = (lo + Math.imul(al8, bl2)) | 0; mid = (mid + Math.imul(al8, bh2)) | 0; mid = (mid + Math.imul(ah8, bl2)) | 0; hi = (hi + Math.imul(ah8, bh2)) | 0; lo = (lo + Math.imul(al7, bl3)) | 0; mid = (mid + Math.imul(al7, bh3)) | 0; mid = (mid + Math.imul(ah7, bl3)) | 0; hi = (hi + Math.imul(ah7, bh3)) | 0; lo = (lo + Math.imul(al6, bl4)) | 0; mid = (mid + Math.imul(al6, bh4)) | 0; mid = (mid + Math.imul(ah6, bl4)) | 0; hi = (hi + Math.imul(ah6, bh4)) | 0; lo = (lo + Math.imul(al5, bl5)) | 0; mid = (mid + Math.imul(al5, bh5)) | 0; mid = (mid + Math.imul(ah5, bl5)) | 0; hi = (hi + Math.imul(ah5, bh5)) | 0; lo = (lo + Math.imul(al4, bl6)) | 0; mid = (mid + Math.imul(al4, bh6)) | 0; mid = (mid + Math.imul(ah4, bl6)) | 0; hi = (hi + Math.imul(ah4, bh6)) | 0; lo = (lo + Math.imul(al3, bl7)) | 0; mid = (mid + Math.imul(al3, bh7)) | 0; mid = (mid + Math.imul(ah3, bl7)) | 0; hi = (hi + Math.imul(ah3, bh7)) | 0; lo = (lo + Math.imul(al2, bl8)) | 0; mid = (mid + Math.imul(al2, bh8)) | 0; mid = (mid + Math.imul(ah2, bl8)) | 0; hi = (hi + Math.imul(ah2, bh8)) | 0; lo = (lo + Math.imul(al1, bl9)) | 0; mid = (mid + Math.imul(al1, bh9)) | 0; mid = (mid + Math.imul(ah1, bl9)) | 0; hi = (hi + Math.imul(ah1, bh9)) | 0; var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; w10 &= 0x3ffffff; /* k = 11 */ lo = Math.imul(al9, bl2); mid = Math.imul(al9, bh2); mid = (mid + Math.imul(ah9, bl2)) | 0; hi = Math.imul(ah9, bh2); lo = (lo + Math.imul(al8, bl3)) | 0; mid = (mid + Math.imul(al8, bh3)) | 0; mid = (mid + Math.imul(ah8, bl3)) | 0; hi = (hi + Math.imul(ah8, bh3)) | 0; lo = (lo + Math.imul(al7, bl4)) | 0; mid = (mid + Math.imul(al7, bh4)) | 0; mid = (mid + Math.imul(ah7, bl4)) | 0; hi = (hi + Math.imul(ah7, bh4)) | 0; lo = (lo + Math.imul(al6, bl5)) | 0; mid = (mid + Math.imul(al6, bh5)) | 0; mid = (mid + Math.imul(ah6, bl5)) | 0; hi = (hi + Math.imul(ah6, bh5)) | 0; lo = (lo + Math.imul(al5, bl6)) | 0; mid = (mid + Math.imul(al5, bh6)) | 0; mid = (mid + Math.imul(ah5, bl6)) | 0; hi = (hi + Math.imul(ah5, bh6)) | 0; lo = (lo + Math.imul(al4, bl7)) | 0; mid = (mid + Math.imul(al4, bh7)) | 0; mid = (mid + Math.imul(ah4, bl7)) | 0; hi = (hi + Math.imul(ah4, bh7)) | 0; lo = (lo + Math.imul(al3, bl8)) | 0; mid = (mid + Math.imul(al3, bh8)) | 0; mid = (mid + Math.imul(ah3, bl8)) | 0; hi = (hi + Math.imul(ah3, bh8)) | 0; lo = (lo + Math.imul(al2, bl9)) | 0; mid = (mid + Math.imul(al2, bh9)) | 0; mid = (mid + Math.imul(ah2, bl9)) | 0; hi = (hi + Math.imul(ah2, bh9)) | 0; var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; w11 &= 0x3ffffff; /* k = 12 */ lo = Math.imul(al9, bl3); mid = Math.imul(al9, bh3); mid = (mid + Math.imul(ah9, bl3)) | 0; hi = Math.imul(ah9, bh3); lo = (lo + Math.imul(al8, bl4)) | 0; mid = (mid + Math.imul(al8, bh4)) | 0; mid = (mid + Math.imul(ah8, bl4)) | 0; hi = (hi + Math.imul(ah8, bh4)) | 0; lo = (lo + Math.imul(al7, bl5)) | 0; mid = (mid + Math.imul(al7, bh5)) | 0; mid = (mid + Math.imul(ah7, bl5)) | 0; hi = (hi + Math.imul(ah7, bh5)) | 0; lo = (lo + Math.imul(al6, bl6)) | 0; mid = (mid + Math.imul(al6, bh6)) | 0; mid = (mid + Math.imul(ah6, bl6)) | 0; hi = (hi + Math.imul(ah6, bh6)) | 0; lo = (lo + Math.imul(al5, bl7)) | 0; mid = (mid + Math.imul(al5, bh7)) | 0; mid = (mid + Math.imul(ah5, bl7)) | 0; hi = (hi + Math.imul(ah5, bh7)) | 0; lo = (lo + Math.imul(al4, bl8)) | 0; mid = (mid + Math.imul(al4, bh8)) | 0; mid = (mid + Math.imul(ah4, bl8)) | 0; hi = (hi + Math.imul(ah4, bh8)) | 0; lo = (lo + Math.imul(al3, bl9)) | 0; mid = (mid + Math.imul(al3, bh9)) | 0; mid = (mid + Math.imul(ah3, bl9)) | 0; hi = (hi + Math.imul(ah3, bh9)) | 0; var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; w12 &= 0x3ffffff; /* k = 13 */ lo = Math.imul(al9, bl4); mid = Math.imul(al9, bh4); mid = (mid + Math.imul(ah9, bl4)) | 0; hi = Math.imul(ah9, bh4); lo = (lo + Math.imul(al8, bl5)) | 0; mid = (mid + Math.imul(al8, bh5)) | 0; mid = (mid + Math.imul(ah8, bl5)) | 0; hi = (hi + Math.imul(ah8, bh5)) | 0; lo = (lo + Math.imul(al7, bl6)) | 0; mid = (mid + Math.imul(al7, bh6)) | 0; mid = (mid + Math.imul(ah7, bl6)) | 0; hi = (hi + Math.imul(ah7, bh6)) | 0; lo = (lo + Math.imul(al6, bl7)) | 0; mid = (mid + Math.imul(al6, bh7)) | 0; mid = (mid + Math.imul(ah6, bl7)) | 0; hi = (hi + Math.imul(ah6, bh7)) | 0; lo = (lo + Math.imul(al5, bl8)) | 0; mid = (mid + Math.imul(al5, bh8)) | 0; mid = (mid + Math.imul(ah5, bl8)) | 0; hi = (hi + Math.imul(ah5, bh8)) | 0; lo = (lo + Math.imul(al4, bl9)) | 0; mid = (mid + Math.imul(al4, bh9)) | 0; mid = (mid + Math.imul(ah4, bl9)) | 0; hi = (hi + Math.imul(ah4, bh9)) | 0; var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; w13 &= 0x3ffffff; /* k = 14 */ lo = Math.imul(al9, bl5); mid = Math.imul(al9, bh5); mid = (mid + Math.imul(ah9, bl5)) | 0; hi = Math.imul(ah9, bh5); lo = (lo + Math.imul(al8, bl6)) | 0; mid = (mid + Math.imul(al8, bh6)) | 0; mid = (mid + Math.imul(ah8, bl6)) | 0; hi = (hi + Math.imul(ah8, bh6)) | 0; lo = (lo + Math.imul(al7, bl7)) | 0; mid = (mid + Math.imul(al7, bh7)) | 0; mid = (mid + Math.imul(ah7, bl7)) | 0; hi = (hi + Math.imul(ah7, bh7)) | 0; lo = (lo + Math.imul(al6, bl8)) | 0; mid = (mid + Math.imul(al6, bh8)) | 0; mid = (mid + Math.imul(ah6, bl8)) | 0; hi = (hi + Math.imul(ah6, bh8)) | 0; lo = (lo + Math.imul(al5, bl9)) | 0; mid = (mid + Math.imul(al5, bh9)) | 0; mid = (mid + Math.imul(ah5, bl9)) | 0; hi = (hi + Math.imul(ah5, bh9)) | 0; var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; w14 &= 0x3ffffff; /* k = 15 */ lo = Math.imul(al9, bl6); mid = Math.imul(al9, bh6); mid = (mid + Math.imul(ah9, bl6)) | 0; hi = Math.imul(ah9, bh6); lo = (lo + Math.imul(al8, bl7)) | 0; mid = (mid + Math.imul(al8, bh7)) | 0; mid = (mid + Math.imul(ah8, bl7)) | 0; hi = (hi + Math.imul(ah8, bh7)) | 0; lo = (lo + Math.imul(al7, bl8)) | 0; mid = (mid + Math.imul(al7, bh8)) | 0; mid = (mid + Math.imul(ah7, bl8)) | 0; hi = (hi + Math.imul(ah7, bh8)) | 0; lo = (lo + Math.imul(al6, bl9)) | 0; mid = (mid + Math.imul(al6, bh9)) | 0; mid = (mid + Math.imul(ah6, bl9)) | 0; hi = (hi + Math.imul(ah6, bh9)) | 0; var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; w15 &= 0x3ffffff; /* k = 16 */ lo = Math.imul(al9, bl7); mid = Math.imul(al9, bh7); mid = (mid + Math.imul(ah9, bl7)) | 0; hi = Math.imul(ah9, bh7); lo = (lo + Math.imul(al8, bl8)) | 0; mid = (mid + Math.imul(al8, bh8)) | 0; mid = (mid + Math.imul(ah8, bl8)) | 0; hi = (hi + Math.imul(ah8, bh8)) | 0; lo = (lo + Math.imul(al7, bl9)) | 0; mid = (mid + Math.imul(al7, bh9)) | 0; mid = (mid + Math.imul(ah7, bl9)) | 0; hi = (hi + Math.imul(ah7, bh9)) | 0; var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; w16 &= 0x3ffffff; /* k = 17 */ lo = Math.imul(al9, bl8); mid = Math.imul(al9, bh8); mid = (mid + Math.imul(ah9, bl8)) | 0; hi = Math.imul(ah9, bh8); lo = (lo + Math.imul(al8, bl9)) | 0; mid = (mid + Math.imul(al8, bh9)) | 0; mid = (mid + Math.imul(ah8, bl9)) | 0; hi = (hi + Math.imul(ah8, bh9)) | 0; var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; w17 &= 0x3ffffff; /* k = 18 */ lo = Math.imul(al9, bl9); mid = Math.imul(al9, bh9); mid = (mid + Math.imul(ah9, bl9)) | 0; hi = Math.imul(ah9, bh9); var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; w18 &= 0x3ffffff; o[0] = w0; o[1] = w1; o[2] = w2; o[3] = w3; o[4] = w4; o[5] = w5; o[6] = w6; o[7] = w7; o[8] = w8; o[9] = w9; o[10] = w10; o[11] = w11; o[12] = w12; o[13] = w13; o[14] = w14; o[15] = w15; o[16] = w16; o[17] = w17; o[18] = w18; if (c !== 0) { o[19] = c; out.length++; } return out; }; // Polyfill comb if (!Math.imul) { comb10MulTo = smallMulTo; } function bigMulTo (self, num, out) { out.negative = num.negative ^ self.negative; out.length = self.length + num.length; var carry = 0; var hncarry = 0; for (var k = 0; k < out.length - 1; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff var ncarry = hncarry; hncarry = 0; var rword = carry & 0x3ffffff; var maxJ = Math.min(k, num.length - 1); for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { var i = k - j; var a = self.words[i] | 0; var b = num.words[j] | 0; var r = a * b; var lo = r & 0x3ffffff; ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; lo = (lo + rword) | 0; rword = lo & 0x3ffffff; ncarry = (ncarry + (lo >>> 26)) | 0; hncarry += ncarry >>> 26; ncarry &= 0x3ffffff; } out.words[k] = rword; carry = ncarry; ncarry = hncarry; } if (carry !== 0) { out.words[k] = carry; } else { out.length--; } return out.strip(); } function jumboMulTo (self, num, out) { var fftm = new FFTM(); return fftm.mulp(self, num, out); } BN.prototype.mulTo = function mulTo (num, out) { var res; var len = this.length + num.length; if (this.length === 10 && num.length === 10) { res = comb10MulTo(this, num, out); } else if (len < 63) { res = smallMulTo(this, num, out); } else if (len < 1024) { res = bigMulTo(this, num, out); } else { res = jumboMulTo(this, num, out); } return res; }; // Cooley-Tukey algorithm for FFT // slightly revisited to rely on looping instead of recursion function FFTM (x, y) { this.x = x; this.y = y; } FFTM.prototype.makeRBT = function makeRBT (N) { var t = new Array(N); var l = BN.prototype._countBits(N) - 1; for (var i = 0; i < N; i++) { t[i] = this.revBin(i, l, N); } return t; }; // Returns binary-reversed representation of `x` FFTM.prototype.revBin = function revBin (x, l, N) { if (x === 0 || x === N - 1) return x; var rb = 0; for (var i = 0; i < l; i++) { rb |= (x & 1) << (l - i - 1); x >>= 1; } return rb; }; // Performs "tweedling" phase, therefore 'emulating' // behaviour of the recursive algorithm FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { for (var i = 0; i < N; i++) { rtws[i] = rws[rbt[i]]; itws[i] = iws[rbt[i]]; } }; FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { this.permute(rbt, rws, iws, rtws, itws, N); for (var s = 1; s < N; s <<= 1) { var l = s << 1; var rtwdf = Math.cos(2 * Math.PI / l); var itwdf = Math.sin(2 * Math.PI / l); for (var p = 0; p < N; p += l) { var rtwdf_ = rtwdf; var itwdf_ = itwdf; for (var j = 0; j < s; j++) { var re = rtws[p + j]; var ie = itws[p + j]; var ro = rtws[p + j + s]; var io = itws[p + j + s]; var rx = rtwdf_ * ro - itwdf_ * io; io = rtwdf_ * io + itwdf_ * ro; ro = rx; rtws[p + j] = re + ro; itws[p + j] = ie + io; rtws[p + j + s] = re - ro; itws[p + j + s] = ie - io; /* jshint maxdepth : false */ if (j !== l) { rx = rtwdf * rtwdf_ - itwdf * itwdf_; itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; rtwdf_ = rx; } } } } }; FFTM.prototype.guessLen13b = function guessLen13b (n, m) { var N = Math.max(m, n) | 1; var odd = N & 1; var i = 0; for (N = N / 2 | 0; N; N = N >>> 1) { i++; } return 1 << i + 1 + odd; }; FFTM.prototype.conjugate = function conjugate (rws, iws, N) { if (N <= 1) return; for (var i = 0; i < N / 2; i++) { var t = rws[i]; rws[i] = rws[N - i - 1]; rws[N - i - 1] = t; t = iws[i]; iws[i] = -iws[N - i - 1]; iws[N - i - 1] = -t; } }; FFTM.prototype.normalize13b = function normalize13b (ws, N) { var carry = 0; for (var i = 0; i < N / 2; i++) { var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + Math.round(ws[2 * i] / N) + carry; ws[i] = w & 0x3ffffff; if (w < 0x4000000) { carry = 0; } else { carry = w / 0x4000000 | 0; } } return ws; }; FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { var carry = 0; for (var i = 0; i < len; i++) { carry = carry + (ws[i] | 0); rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; } // Pad with zeroes for (i = 2 * len; i < N; ++i) { rws[i] = 0; } assert(carry === 0); assert((carry & ~0x1fff) === 0); }; FFTM.prototype.stub = function stub (N) { var ph = new Array(N); for (var i = 0; i < N; i++) { ph[i] = 0; } return ph; }; FFTM.prototype.mulp = function mulp (x, y, out) { var N = 2 * this.guessLen13b(x.length, y.length); var rbt = this.makeRBT(N); var _ = this.stub(N); var rws = new Array(N); var rwst = new Array(N); var iwst = new Array(N); var nrws = new Array(N); var nrwst = new Array(N); var niwst = new Array(N); var rmws = out.words; rmws.length = N; this.convert13b(x.words, x.length, rws, N); this.convert13b(y.words, y.length, nrws, N); this.transform(rws, _, rwst, iwst, N, rbt); this.transform(nrws, _, nrwst, niwst, N, rbt); for (var i = 0; i < N; i++) { var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; rwst[i] = rx; } this.conjugate(rwst, iwst, N); this.transform(rwst, iwst, rmws, _, N, rbt); this.conjugate(rmws, _, N); this.normalize13b(rmws, N); out.negative = x.negative ^ y.negative; out.length = x.length + y.length; return out.strip(); }; // Multiply `this` by `num` BN.prototype.mul = function mul (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return this.mulTo(num, out); }; // Multiply employing FFT BN.prototype.mulf = function mulf (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return jumboMulTo(this, num, out); }; // In-place Multiplication BN.prototype.imul = function imul (num) { return this.clone().mulTo(num, this); }; BN.prototype.imuln = function imuln (num) { assert(typeof num === 'number'); assert(num < 0x4000000); // Carry var carry = 0; for (var i = 0; i < this.length; i++) { var w = (this.words[i] | 0) * num; var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); carry >>= 26; carry += (w / 0x4000000) | 0; // NOTE: lo is 27bit maximum carry += lo >>> 26; this.words[i] = lo & 0x3ffffff; } if (carry !== 0) { this.words[i] = carry; this.length++; } return this; }; BN.prototype.muln = function muln (num) { return this.clone().imuln(num); }; // `this` * `this` BN.prototype.sqr = function sqr () { return this.mul(this); }; // `this` * `this` in-place BN.prototype.isqr = function isqr () { return this.imul(this.clone()); }; // Math.pow(`this`, `num`) BN.prototype.pow = function pow (num) { var w = toBitArray(num); if (w.length === 0) return new BN(1); // Skip leading zeroes var res = this; for (var i = 0; i < w.length; i++, res = res.sqr()) { if (w[i] !== 0) break; } if (++i < w.length) { for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { if (w[i] === 0) continue; res = res.mul(q); } } return res; }; // Shift-left in-place BN.prototype.iushln = function iushln (bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); var i; if (r !== 0) { var carry = 0; for (i = 0; i < this.length; i++) { var newCarry = this.words[i] & carryMask; var c = ((this.words[i] | 0) - newCarry) << r; this.words[i] = c | carry; carry = newCarry >>> (26 - r); } if (carry) { this.words[i] = carry; this.length++; } } if (s !== 0) { for (i = this.length - 1; i >= 0; i--) { this.words[i + s] = this.words[i]; } for (i = 0; i < s; i++) { this.words[i] = 0; } this.length += s; } return this.strip(); }; BN.prototype.ishln = function ishln (bits) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushln(bits); }; // Shift-right in-place // NOTE: `hint` is a lowest bit before trailing zeroes // NOTE: if `extended` is present - it will be filled with destroyed bits BN.prototype.iushrn = function iushrn (bits, hint, extended) { assert(typeof bits === 'number' && bits >= 0); var h; if (hint) { h = (hint - (hint % 26)) / 26; } else { h = 0; } var r = bits % 26; var s = Math.min((bits - r) / 26, this.length); var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); var maskedWords = extended; h -= s; h = Math.max(0, h); // Extended mode, copy masked part if (maskedWords) { for (var i = 0; i < s; i++) { maskedWords.words[i] = this.words[i]; } maskedWords.length = s; } if (s === 0) { // No-op, we should not move anything at all } else if (this.length > s) { this.length -= s; for (i = 0; i < this.length; i++) { this.words[i] = this.words[i + s]; } } else { this.words[0] = 0; this.length = 1; } var carry = 0; for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { var word = this.words[i] | 0; this.words[i] = (carry << (26 - r)) | (word >>> r); carry = word & mask; } // Push carried bits as a mask if (maskedWords && carry !== 0) { maskedWords.words[maskedWords.length++] = carry; } if (this.length === 0) { this.words[0] = 0; this.length = 1; } return this.strip(); }; BN.prototype.ishrn = function ishrn (bits, hint, extended) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushrn(bits, hint, extended); }; // Shift-left BN.prototype.shln = function shln (bits) { return this.clone().ishln(bits); }; BN.prototype.ushln = function ushln (bits) { return this.clone().iushln(bits); }; // Shift-right BN.prototype.shrn = function shrn (bits) { return this.clone().ishrn(bits); }; BN.prototype.ushrn = function ushrn (bits) { return this.clone().iushrn(bits); }; // Test if n bit is set BN.prototype.testn = function testn (bit) { assert(typeof bit === 'number' && bit >= 0); var r = bit % 26; var s = (bit - r) / 26; var q = 1 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) return false; // Check bit and return var w = this.words[s]; return !!(w & q); }; // Return only lowers bits of number (in-place) BN.prototype.imaskn = function imaskn (bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; assert(this.negative === 0, 'imaskn works only with positive numbers'); if (this.length <= s) { return this; } if (r !== 0) { s++; } this.length = Math.min(s, this.length); if (r !== 0) { var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); this.words[this.length - 1] &= mask; } return this.strip(); }; // Return only lowers bits of number BN.prototype.maskn = function maskn (bits) { return this.clone().imaskn(bits); }; // Add plain number `num` to `this` BN.prototype.iaddn = function iaddn (num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.isubn(-num); // Possible sign change if (this.negative !== 0) { if (this.length === 1 && (this.words[0] | 0) < num) { this.words[0] = num - (this.words[0] | 0); this.negative = 0; return this; } this.negative = 0; this.isubn(num); this.negative = 1; return this; } // Add without checks return this._iaddn(num); }; BN.prototype._iaddn = function _iaddn (num) { this.words[0] += num; // Carry for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { this.words[i] -= 0x4000000; if (i === this.length - 1) { this.words[i + 1] = 1; } else { this.words[i + 1]++; } } this.length = Math.max(this.length, i + 1); return this; }; // Subtract plain number `num` from `this` BN.prototype.isubn = function isubn (num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.iaddn(-num); if (this.negative !== 0) { this.negative = 0; this.iaddn(num); this.negative = 1; return this; } this.words[0] -= num; if (this.length === 1 && this.words[0] < 0) { this.words[0] = -this.words[0]; this.negative = 1; } else { // Carry for (var i = 0; i < this.length && this.words[i] < 0; i++) { this.words[i] += 0x4000000; this.words[i + 1] -= 1; } } return this.strip(); }; BN.prototype.addn = function addn (num) { return this.clone().iaddn(num); }; BN.prototype.subn = function subn (num) { return this.clone().isubn(num); }; BN.prototype.iabs = function iabs () { this.negative = 0; return this; }; BN.prototype.abs = function abs () { return this.clone().iabs(); }; BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { var len = num.length + shift; var i; this._expand(len); var w; var carry = 0; for (i = 0; i < num.length; i++) { w = (this.words[i + shift] | 0) + carry; var right = (num.words[i] | 0) * mul; w -= right & 0x3ffffff; carry = (w >> 26) - ((right / 0x4000000) | 0); this.words[i + shift] = w & 0x3ffffff; } for (; i < this.length - shift; i++) { w = (this.words[i + shift] | 0) + carry; carry = w >> 26; this.words[i + shift] = w & 0x3ffffff; } if (carry === 0) return this.strip(); // Subtraction overflow assert(carry === -1); carry = 0; for (i = 0; i < this.length; i++) { w = -(this.words[i] | 0) + carry; carry = w >> 26; this.words[i] = w & 0x3ffffff; } this.negative = 1; return this.strip(); }; BN.prototype._wordDiv = function _wordDiv (num, mode) { var shift = this.length - num.length; var a = this.clone(); var b = num; // Normalize var bhi = b.words[b.length - 1] | 0; var bhiBits = this._countBits(bhi); shift = 26 - bhiBits; if (shift !== 0) { b = b.ushln(shift); a.iushln(shift); bhi = b.words[b.length - 1] | 0; } // Initialize quotient var m = a.length - b.length; var q; if (mode !== 'mod') { q = new BN(null); q.length = m + 1; q.words = new Array(q.length); for (var i = 0; i < q.length; i++) { q.words[i] = 0; } } var diff = a.clone()._ishlnsubmul(b, 1, m); if (diff.negative === 0) { a = diff; if (q) { q.words[m] = 1; } } for (var j = m - 1; j >= 0; j--) { var qj = (a.words[b.length + j] | 0) * 0x4000000 + (a.words[b.length + j - 1] | 0); // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max // (0x7ffffff) qj = Math.min((qj / bhi) | 0, 0x3ffffff); a._ishlnsubmul(b, qj, j); while (a.negative !== 0) { qj--; a.negative = 0; a._ishlnsubmul(b, 1, j); if (!a.isZero()) { a.negative ^= 1; } } if (q) { q.words[j] = qj; } } if (q) { q.strip(); } a.strip(); // Denormalize if (mode !== 'div' && shift !== 0) { a.iushrn(shift); } return { div: q || null, mod: a }; }; // NOTE: 1) `mode` can be set to `mod` to request mod only, // to `div` to request div only, or be absent to // request both div & mod // 2) `positive` is true if unsigned mod is requested BN.prototype.divmod = function divmod (num, mode, positive) { assert(!num.isZero()); if (this.isZero()) { return { div: new BN(0), mod: new BN(0) }; } var div, mod, res; if (this.negative !== 0 && num.negative === 0) { res = this.neg().divmod(num, mode); if (mode !== 'mod') { div = res.div.neg(); } if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.iadd(num); } } return { div: div, mod: mod }; } if (this.negative === 0 && num.negative !== 0) { res = this.divmod(num.neg(), mode); if (mode !== 'mod') { div = res.div.neg(); } return { div: div, mod: res.mod }; } if ((this.negative & num.negative) !== 0) { res = this.neg().divmod(num.neg(), mode); if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.isub(num); } } return { div: res.div, mod: mod }; } // Both numbers are positive at this point // Strip both numbers to approximate shift value if (num.length > this.length || this.cmp(num) < 0) { return { div: new BN(0), mod: this }; } // Very short reduction if (num.length === 1) { if (mode === 'div') { return { div: this.divn(num.words[0]), mod: null }; } if (mode === 'mod') { return { div: null, mod: new BN(this.modn(num.words[0])) }; } return { div: this.divn(num.words[0]), mod: new BN(this.modn(num.words[0])) }; } return this._wordDiv(num, mode); }; // Find `this` / `num` BN.prototype.div = function div (num) { return this.divmod(num, 'div', false).div; }; // Find `this` % `num` BN.prototype.mod = function mod (num) { return this.divmod(num, 'mod', false).mod; }; BN.prototype.umod = function umod (num) { return this.divmod(num, 'mod', true).mod; }; // Find Round(`this` / `num`) BN.prototype.divRound = function divRound (num) { var dm = this.divmod(num); // Fast case - exact division if (dm.mod.isZero()) return dm.div; var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; var half = num.ushrn(1); var r2 = num.andln(1); var cmp = mod.cmp(half); // Round down if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; // Round up return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); }; BN.prototype.modn = function modn (num) { assert(num <= 0x3ffffff); var p = (1 << 26) % num; var acc = 0; for (var i = this.length - 1; i >= 0; i--) { acc = (p * acc + (this.words[i] | 0)) % num; } return acc; }; // In-place division by number BN.prototype.idivn = function idivn (num) { assert(num <= 0x3ffffff); var carry = 0; for (var i = this.length - 1; i >= 0; i--) { var w = (this.words[i] | 0) + carry * 0x4000000; this.words[i] = (w / num) | 0; carry = w % num; } return this.strip(); }; BN.prototype.divn = function divn (num) { return this.clone().idivn(num); }; BN.prototype.egcd = function egcd (p) { assert(p.negative === 0); assert(!p.isZero()); var x = this; var y = p.clone(); if (x.negative !== 0) { x = x.umod(p); } else { x = x.clone(); } // A * x + B * y = x var A = new BN(1); var B = new BN(0); // C * x + D * y = y var C = new BN(0); var D = new BN(1); var g = 0; while (x.isEven() && y.isEven()) { x.iushrn(1); y.iushrn(1); ++g; } var yp = y.clone(); var xp = x.clone(); while (!x.isZero()) { for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); if (i > 0) { x.iushrn(i); while (i-- > 0) { if (A.isOdd() || B.isOdd()) { A.iadd(yp); B.isub(xp); } A.iushrn(1); B.iushrn(1); } } for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); if (j > 0) { y.iushrn(j); while (j-- > 0) { if (C.isOdd() || D.isOdd()) { C.iadd(yp); D.isub(xp); } C.iushrn(1); D.iushrn(1); } } if (x.cmp(y) >= 0) { x.isub(y); A.isub(C); B.isub(D); } else { y.isub(x); C.isub(A); D.isub(B); } } return { a: C, b: D, gcd: y.iushln(g) }; }; // This is reduced incarnation of the binary EEA // above, designated to invert members of the // _prime_ fields F(p) at a maximal speed BN.prototype._invmp = function _invmp (p) { assert(p.negative === 0); assert(!p.isZero()); var a = this; var b = p.clone(); if (a.negative !== 0) { a = a.umod(p); } else { a = a.clone(); } var x1 = new BN(1); var x2 = new BN(0); var delta = b.clone(); while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); if (i > 0) { a.iushrn(i); while (i-- > 0) { if (x1.isOdd()) { x1.iadd(delta); } x1.iushrn(1); } } for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); if (j > 0) { b.iushrn(j); while (j-- > 0) { if (x2.isOdd()) { x2.iadd(delta); } x2.iushrn(1); } } if (a.cmp(b) >= 0) { a.isub(b); x1.isub(x2); } else { b.isub(a); x2.isub(x1); } } var res; if (a.cmpn(1) === 0) { res = x1; } else { res = x2; } if (res.cmpn(0) < 0) { res.iadd(p); } return res; }; BN.prototype.gcd = function gcd (num) { if (this.isZero()) return num.abs(); if (num.isZero()) return this.abs(); var a = this.clone(); var b = num.clone(); a.negative = 0; b.negative = 0; // Remove common factor of two for (var shift = 0; a.isEven() && b.isEven(); shift++) { a.iushrn(1); b.iushrn(1); } do { while (a.isEven()) { a.iushrn(1); } while (b.isEven()) { b.iushrn(1); } var r = a.cmp(b); if (r < 0) { // Swap `a` and `b` to make `a` always bigger than `b` var t = a; a = b; b = t; } else if (r === 0 || b.cmpn(1) === 0) { break; } a.isub(b); } while (true); return b.iushln(shift); }; // Invert number in the field F(num) BN.prototype.invm = function invm (num) { return this.egcd(num).a.umod(num); }; BN.prototype.isEven = function isEven () { return (this.words[0] & 1) === 0; }; BN.prototype.isOdd = function isOdd () { return (this.words[0] & 1) === 1; }; // And first word and num BN.prototype.andln = function andln (num) { return this.words[0] & num; }; // Increment at the bit position in-line BN.prototype.bincn = function bincn (bit) { assert(typeof bit === 'number'); var r = bit % 26; var s = (bit - r) / 26; var q = 1 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) { this._expand(s + 1); this.words[s] |= q; return this; } // Add bit and propagate, if needed var carry = q; for (var i = s; carry !== 0 && i < this.length; i++) { var w = this.words[i] | 0; w += carry; carry = w >>> 26; w &= 0x3ffffff; this.words[i] = w; } if (carry !== 0) { this.words[i] = carry; this.length++; } return this; }; BN.prototype.isZero = function isZero () { return this.length === 1 && this.words[0] === 0; }; BN.prototype.cmpn = function cmpn (num) { var negative = num < 0; if (this.negative !== 0 && !negative) return -1; if (this.negative === 0 && negative) return 1; this.strip(); var res; if (this.length > 1) { res = 1; } else { if (negative) { num = -num; } assert(num <= 0x3ffffff, 'Number is too big'); var w = this.words[0] | 0; res = w === num ? 0 : w < num ? -1 : 1; } if (this.negative !== 0) return -res | 0; return res; }; // Compare two numbers and return: // 1 - if `this` > `num` // 0 - if `this` == `num` // -1 - if `this` < `num` BN.prototype.cmp = function cmp (num) { if (this.negative !== 0 && num.negative === 0) return -1; if (this.negative === 0 && num.negative !== 0) return 1; var res = this.ucmp(num); if (this.negative !== 0) return -res | 0; return res; }; // Unsigned comparison BN.prototype.ucmp = function ucmp (num) { // At this point both numbers have the same sign if (this.length > num.length) return 1; if (this.length < num.length) return -1; var res = 0; for (var i = this.length - 1; i >= 0; i--) { var a = this.words[i] | 0; var b = num.words[i] | 0; if (a === b) continue; if (a < b) { res = -1; } else if (a > b) { res = 1; } break; } return res; }; BN.prototype.gtn = function gtn (num) { return this.cmpn(num) === 1; }; BN.prototype.gt = function gt (num) { return this.cmp(num) === 1; }; BN.prototype.gten = function gten (num) { return this.cmpn(num) >= 0; }; BN.prototype.gte = function gte (num) { return this.cmp(num) >= 0; }; BN.prototype.ltn = function ltn (num) { return this.cmpn(num) === -1; }; BN.prototype.lt = function lt (num) { return this.cmp(num) === -1; }; BN.prototype.lten = function lten (num) { return this.cmpn(num) <= 0; }; BN.prototype.lte = function lte (num) { return this.cmp(num) <= 0; }; BN.prototype.eqn = function eqn (num) { return this.cmpn(num) === 0; }; BN.prototype.eq = function eq (num) { return this.cmp(num) === 0; }; // // A reduce context, could be using montgomery or something better, depending // on the `m` itself. // BN.red = function red (num) { return new Red(num); }; BN.prototype.toRed = function toRed (ctx) { assert(!this.red, 'Already a number in reduction context'); assert(this.negative === 0, 'red works only with positives'); return ctx.convertTo(this)._forceRed(ctx); }; BN.prototype.fromRed = function fromRed () { assert(this.red, 'fromRed works only with numbers in reduction context'); return this.red.convertFrom(this); }; BN.prototype._forceRed = function _forceRed (ctx) { this.red = ctx; return this; }; BN.prototype.forceRed = function forceRed (ctx) { assert(!this.red, 'Already a number in reduction context'); return this._forceRed(ctx); }; BN.prototype.redAdd = function redAdd (num) { assert(this.red, 'redAdd works only with red numbers'); return this.red.add(this, num); }; BN.prototype.redIAdd = function redIAdd (num) { assert(this.red, 'redIAdd works only with red numbers'); return this.red.iadd(this, num); }; BN.prototype.redSub = function redSub (num) { assert(this.red, 'redSub works only with red numbers'); return this.red.sub(this, num); }; BN.prototype.redISub = function redISub (num) { assert(this.red, 'redISub works only with red numbers'); return this.red.isub(this, num); }; BN.prototype.redShl = function redShl (num) { assert(this.red, 'redShl works only with red numbers'); return this.red.shl(this, num); }; BN.prototype.redMul = function redMul (num) { assert(this.red, 'redMul works only with red numbers'); this.red._verify2(this, num); return this.red.mul(this, num); }; BN.prototype.redIMul = function redIMul (num) { assert(this.red, 'redMul works only with red numbers'); this.red._verify2(this, num); return this.red.imul(this, num); }; BN.prototype.redSqr = function redSqr () { assert(this.red, 'redSqr works only with red numbers'); this.red._verify1(this); return this.red.sqr(this); }; BN.prototype.redISqr = function redISqr () { assert(this.red, 'redISqr works only with red numbers'); this.red._verify1(this); return this.red.isqr(this); }; // Square root over p BN.prototype.redSqrt = function redSqrt () { assert(this.red, 'redSqrt works only with red numbers'); this.red._verify1(this); return this.red.sqrt(this); }; BN.prototype.redInvm = function redInvm () { assert(this.red, 'redInvm works only with red numbers'); this.red._verify1(this); return this.red.invm(this); }; // Return negative clone of `this` % `red modulo` BN.prototype.redNeg = function redNeg () { assert(this.red, 'redNeg works only with red numbers'); this.red._verify1(this); return this.red.neg(this); }; BN.prototype.redPow = function redPow (num) { assert(this.red && !num.red, 'redPow(normalNum)'); this.red._verify1(this); return this.red.pow(this, num); }; // Prime numbers with efficient reduction var primes = { k256: null, p224: null, p192: null, p25519: null }; // Pseudo-Mersenne prime function MPrime (name, p) { // P = 2 ^ N - K this.name = name; this.p = new BN(p, 16); this.n = this.p.bitLength(); this.k = new BN(1).iushln(this.n).isub(this.p); this.tmp = this._tmp(); } MPrime.prototype._tmp = function _tmp () { var tmp = new BN(null); tmp.words = new Array(Math.ceil(this.n / 13)); return tmp; }; MPrime.prototype.ireduce = function ireduce (num) { // Assumes that `num` is less than `P^2` // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) var r = num; var rlen; do { this.split(r, this.tmp); r = this.imulK(r); r = r.iadd(this.tmp); rlen = r.bitLength(); } while (rlen > this.n); var cmp = rlen < this.n ? -1 : r.ucmp(this.p); if (cmp === 0) { r.words[0] = 0; r.length = 1; } else if (cmp > 0) { r.isub(this.p); } else { r.strip(); } return r; }; MPrime.prototype.split = function split (input, out) { input.iushrn(this.n, 0, out); }; MPrime.prototype.imulK = function imulK (num) { return num.imul(this.k); }; function K256 () { MPrime.call( this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); } inherits(K256, MPrime); K256.prototype.split = function split (input, output) { // 256 = 9 * 26 + 22 var mask = 0x3fffff; var outLen = Math.min(input.length, 9); for (var i = 0; i < outLen; i++) { output.words[i] = input.words[i]; } output.length = outLen; if (input.length <= 9) { input.words[0] = 0; input.length = 1; return; } // Shift by 9 limbs var prev = input.words[9]; output.words[output.length++] = prev & mask; for (i = 10; i < input.length; i++) { var next = input.words[i] | 0; input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); prev = next; } prev >>>= 22; input.words[i - 10] = prev; if (prev === 0 && input.length > 10) { input.length -= 10; } else { input.length -= 9; } }; K256.prototype.imulK = function imulK (num) { // K = 0x1000003d1 = [ 0x40, 0x3d1 ] num.words[num.length] = 0; num.words[num.length + 1] = 0; num.length += 2; // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 var lo = 0; for (var i = 0; i < num.length; i++) { var w = num.words[i] | 0; lo += w * 0x3d1; num.words[i] = lo & 0x3ffffff; lo = w * 0x40 + ((lo / 0x4000000) | 0); } // Fast length reduction if (num.words[num.length - 1] === 0) { num.length--; if (num.words[num.length - 1] === 0) { num.length--; } } return num; }; function P224 () { MPrime.call( this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); } inherits(P224, MPrime); function P192 () { MPrime.call( this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); } inherits(P192, MPrime); function P25519 () { // 2 ^ 255 - 19 MPrime.call( this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); } inherits(P25519, MPrime); P25519.prototype.imulK = function imulK (num) { // K = 0x13 var carry = 0; for (var i = 0; i < num.length; i++) { var hi = (num.words[i] | 0) * 0x13 + carry; var lo = hi & 0x3ffffff; hi >>>= 26; num.words[i] = lo; carry = hi; } if (carry !== 0) { num.words[num.length++] = carry; } return num; }; // Exported mostly for testing purposes, use plain name instead BN._prime = function prime (name) { // Cached version of prime if (primes[name]) return primes[name]; var prime; if (name === 'k256') { prime = new K256(); } else if (name === 'p224') { prime = new P224(); } else if (name === 'p192') { prime = new P192(); } else if (name === 'p25519') { prime = new P25519(); } else { throw new Error('Unknown prime ' + name); } primes[name] = prime; return prime; }; // // Base reduction engine // function Red (m) { if (typeof m === 'string') { var prime = BN._prime(m); this.m = prime.p; this.prime = prime; } else { assert(m.gtn(1), 'modulus must be greater than 1'); this.m = m; this.prime = null; } } Red.prototype._verify1 = function _verify1 (a) { assert(a.negative === 0, 'red works only with positives'); assert(a.red, 'red works only with red numbers'); }; Red.prototype._verify2 = function _verify2 (a, b) { assert((a.negative | b.negative) === 0, 'red works only with positives'); assert(a.red && a.red === b.red, 'red works only with red numbers'); }; Red.prototype.imod = function imod (a) { if (this.prime) return this.prime.ireduce(a)._forceRed(this); return a.umod(this.m)._forceRed(this); }; Red.prototype.neg = function neg (a) { if (a.isZero()) { return a.clone(); } return this.m.sub(a)._forceRed(this); }; Red.prototype.add = function add (a, b) { this._verify2(a, b); var res = a.add(b); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res._forceRed(this); }; Red.prototype.iadd = function iadd (a, b) { this._verify2(a, b); var res = a.iadd(b); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res; }; Red.prototype.sub = function sub (a, b) { this._verify2(a, b); var res = a.sub(b); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res._forceRed(this); }; Red.prototype.isub = function isub (a, b) { this._verify2(a, b); var res = a.isub(b); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res; }; Red.prototype.shl = function shl (a, num) { this._verify1(a); return this.imod(a.ushln(num)); }; Red.prototype.imul = function imul (a, b) { this._verify2(a, b); return this.imod(a.imul(b)); }; Red.prototype.mul = function mul (a, b) { this._verify2(a, b); return this.imod(a.mul(b)); }; Red.prototype.isqr = function isqr (a) { return this.imul(a, a.clone()); }; Red.prototype.sqr = function sqr (a) { return this.mul(a, a); }; Red.prototype.sqrt = function sqrt (a) { if (a.isZero()) return a.clone(); var mod3 = this.m.andln(3); assert(mod3 % 2 === 1); // Fast case if (mod3 === 3) { var pow = this.m.add(new BN(1)).iushrn(2); return this.pow(a, pow); } // Tonelli-Shanks algorithm (Totally unoptimized and slow) // // Find Q and S, that Q * 2 ^ S = (P - 1) var q = this.m.subn(1); var s = 0; while (!q.isZero() && q.andln(1) === 0) { s++; q.iushrn(1); } assert(!q.isZero()); var one = new BN(1).toRed(this); var nOne = one.redNeg(); // Find quadratic non-residue // NOTE: Max is such because of generalized Riemann hypothesis. var lpow = this.m.subn(1).iushrn(1); var z = this.m.bitLength(); z = new BN(2 * z * z).toRed(this); while (this.pow(z, lpow).cmp(nOne) !== 0) { z.redIAdd(nOne); } var c = this.pow(z, q); var r = this.pow(a, q.addn(1).iushrn(1)); var t = this.pow(a, q); var m = s; while (t.cmp(one) !== 0) { var tmp = t; for (var i = 0; tmp.cmp(one) !== 0; i++) { tmp = tmp.redSqr(); } assert(i < m); var b = this.pow(c, new BN(1).iushln(m - i - 1)); r = r.redMul(b); c = b.redSqr(); t = t.redMul(c); m = i; } return r; }; Red.prototype.invm = function invm (a) { var inv = a._invmp(this.m); if (inv.negative !== 0) { inv.negative = 0; return this.imod(inv).redNeg(); } else { return this.imod(inv); } }; Red.prototype.pow = function pow (a, num) { if (num.isZero()) return new BN(1); if (num.cmpn(1) === 0) return a.clone(); var windowSize = 4; var wnd = new Array(1 << windowSize); wnd[0] = new BN(1).toRed(this); wnd[1] = a; for (var i = 2; i < wnd.length; i++) { wnd[i] = this.mul(wnd[i - 1], a); } var res = wnd[0]; var current = 0; var currentLen = 0; var start = num.bitLength() % 26; if (start === 0) { start = 26; } for (i = num.length - 1; i >= 0; i--) { var word = num.words[i]; for (var j = start - 1; j >= 0; j--) { var bit = (word >> j) & 1; if (res !== wnd[0]) { res = this.sqr(res); } if (bit === 0 && current === 0) { currentLen = 0; continue; } current <<= 1; current |= bit; currentLen++; if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; res = this.mul(res, wnd[current]); currentLen = 0; current = 0; } start = 26; } return res; }; Red.prototype.convertTo = function convertTo (num) { var r = num.umod(this.m); return r === num ? r.clone() : r; }; Red.prototype.convertFrom = function convertFrom (num) { var res = num.clone(); res.red = null; return res; }; // // Montgomery method engine // BN.mont = function mont (num) { return new Mont(num); }; function Mont (m) { Red.call(this, m); this.shift = this.m.bitLength(); if (this.shift % 26 !== 0) { this.shift += 26 - (this.shift % 26); } this.r = new BN(1).iushln(this.shift); this.r2 = this.imod(this.r.sqr()); this.rinv = this.r._invmp(this.m); this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); this.minv = this.minv.umod(this.r); this.minv = this.r.sub(this.minv); } inherits(Mont, Red); Mont.prototype.convertTo = function convertTo (num) { return this.imod(num.ushln(this.shift)); }; Mont.prototype.convertFrom = function convertFrom (num) { var r = this.imod(num.mul(this.rinv)); r.red = null; return r; }; Mont.prototype.imul = function imul (a, b) { if (a.isZero() || b.isZero()) { a.words[0] = 0; a.length = 1; return a; } var t = a.imul(b); var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u = t.isub(c).iushrn(this.shift); var res = u; if (u.cmp(this.m) >= 0) { res = u.isub(this.m); } else if (u.cmpn(0) < 0) { res = u.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.mul = function mul (a, b) { if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); var t = a.mul(b); var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u = t.isub(c).iushrn(this.shift); var res = u; if (u.cmp(this.m) >= 0) { res = u.isub(this.m); } else if (u.cmpn(0) < 0) { res = u.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.invm = function invm (a) { // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R var res = this.imod(a._invmp(this.m).mul(this.r2)); return res._forceRed(this); }; })(typeof module === 'undefined' || module, this); },{}],5:[function(require,module,exports){ },{}],6:[function(require,module,exports){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ /* eslint-disable no-proto */ 'use strict' var base64 = require('base64-js') var ieee754 = require('ieee754') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 var K_MAX_LENGTH = 0x7fffffff exports.kMaxLength = K_MAX_LENGTH /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Print warning and recommend using `buffer` v4.x which has an Object * implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * We report that the browser does not support typed arrays if the are not subclassable * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support * for __proto__ and has a buggy typed array implementation. */ Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() if (!Buffer.TYPED_ARRAY_SUPPORT) { console.error( 'This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.') } function typedArraySupport () { // Can typed array instances can be augmented? try { var arr = new Uint8Array(1) arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} return arr.foo() === 42 } catch (e) { return false } } function createBuffer (length) { if (length > K_MAX_LENGTH) { throw new RangeError('Invalid typed array length') } // Return an augmented `Uint8Array` instance var buf = new Uint8Array(length) buf.__proto__ = Buffer.prototype return buf } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer (arg, encodingOrOffset, length) { // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new Error( 'If encoding is specified then the first argument must be a string' ) } return allocUnsafe(arg) } return from(arg, encodingOrOffset, length) } // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 if (typeof Symbol !== 'undefined' && Symbol.species && Buffer[Symbol.species] === Buffer) { Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true, enumerable: false, writable: false }) } Buffer.poolSize = 8192 // not used by this implementation function from (value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { return fromArrayBuffer(value, encodingOrOffset, length) } if (typeof value === 'string') { return fromString(value, encodingOrOffset) } return fromObject(value) } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(value, encodingOrOffset, length) } // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: // https://github.com/feross/buffer/pull/148 Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be a number') } else if (size < 0) { throw new RangeError('"size" argument must not be negative') } } function alloc (size, fill, encoding) { assertSize(size) if (size <= 0) { return createBuffer(size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill) } return createBuffer(size) } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(size, fill, encoding) } function allocUnsafe (size) { assertSize(size) return createBuffer(size < 0 ? 0 : checked(size) | 0) } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(size) } /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(size) } function fromString (string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } var length = byteLength(string, encoding) | 0 var buf = createBuffer(length) var actual = buf.write(string, encoding) if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') buf = buf.slice(0, actual) } return buf } function fromArrayLike (array) { var length = array.length < 0 ? 0 : checked(array.length) | 0 var buf = createBuffer(length) for (var i = 0; i < length; i += 1) { buf[i] = array[i] & 255 } return buf } function fromArrayBuffer (array, byteOffset, length) { array.byteLength // this throws if `array` is not a valid ArrayBuffer if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('\'offset\' is out of bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('\'length\' is out of bounds') } var buf if (byteOffset === undefined && length === undefined) { buf = new Uint8Array(array) } else if (length === undefined) { buf = new Uint8Array(array, byteOffset) } else { buf = new Uint8Array(array, byteOffset, length) } // Return an augmented `Uint8Array` instance buf.__proto__ = Buffer.prototype return buf } function fromObject (obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0 var buf = createBuffer(len) if (buf.length === 0) { return buf } obj.copy(buf, 0, 0, len) return buf } if (obj) { if ((typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer) || 'length' in obj) { if (typeof obj.length !== 'number' || isnan(obj.length)) { return createBuffer(0) } return fromArrayLike(obj) } if (obj.type === 'Buffer' && Array.isArray(obj.data)) { return fromArrayLike(obj.data) } } throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } function checked (length) { // Note: cannot use `length < K_MAX_LENGTH` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= K_MAX_LENGTH) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') } return length | 0 } function SlowBuffer (length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0 } return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers') } if (a === b) return 0 var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i] y = b[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!Array.isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { return Buffer.alloc(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; ++i) { length += list[i].length } } var buffer = Buffer.allocUnsafe(length) var pos = 0 for (i = 0; i < list.length; ++i) { var buf = list[i] if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers') } buf.copy(buffer, pos) pos += buf.length } return buffer } function byteLength (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { string = '' + string } var len = string.length if (len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len case 'utf8': case 'utf-8': case undefined: return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) return utf8ToBytes(string).length // assume utf8 encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0 } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return '' } if (end === undefined || end > this.length) { end = this.length } if (end <= 0) { return '' } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0 start >>>= 0 if (end <= start) { return '' } if (!encoding) encoding = 'utf8' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'latin1': case 'binary': return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. Buffer.prototype._isBuffer = true function swap (b, n, m) { var i = b[n] b[n] = b[m] b[m] = i } Buffer.prototype.swap16 = function swap16 () { var len = this.length if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1) } return this } Buffer.prototype.swap32 = function swap32 () { var len = this.length if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3) swap(this, i + 1, i + 2) } return this } Buffer.prototype.swap64 = function swap64 () { var len = this.length if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7) swap(this, i + 1, i + 6) swap(this, i + 2, i + 5) swap(this, i + 3, i + 4) } return this } Buffer.prototype.toString = function toString () { var length = this.length if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '' } Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!Buffer.isBuffer(target)) { throw new TypeError('Argument must be a Buffer') } if (start === undefined) { start = 0 } if (end === undefined) { end = target ? target.length : 0 } if (thisStart === undefined) { thisStart = 0 } if (thisEnd === undefined) { thisEnd = this.length } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index') } if (thisStart >= thisEnd && start >= end) { return 0 } if (thisStart >= thisEnd) { return -1 } if (start >= end) { return 1 } start >>>= 0 end >>>= 0 thisStart >>>= 0 thisEnd >>>= 0 if (this === target) return 0 var x = thisEnd - thisStart var y = end - start var len = Math.min(x, y) var thisCopy = this.slice(thisStart, thisEnd) var targetCopy = target.slice(start, end) for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i] y = targetCopy[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1 // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset byteOffset = 0 } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000 } byteOffset = +byteOffset // Coerce to Number. if (isNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : (buffer.length - 1) } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset if (byteOffset >= buffer.length) { if (dir) return -1 else byteOffset = buffer.length - 1 } else if (byteOffset < 0) { if (dir) byteOffset = 0 else return -1 } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding) } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1 } return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF // Search for a byte value [0-255] if (typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } } return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } throw new TypeError('val must be string, number or Buffer') } function arrayIndexOf (arr, val, byteOffset, encoding, dir) { var indexSize = 1 var arrLength = arr.length var valLength = val.length if (encoding !== undefined) { encoding = String(encoding).toLowerCase() if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2 arrLength /= 2 valLength /= 2 byteOffset /= 2 } } function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } var i if (dir) { var foundIndex = -1 for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1 } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength for (i = byteOffset; i >= 0; i--) { var found = true for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false break } } if (found) return i } } return -1 } Buffer.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 } Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) } Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (isNaN(parsed)) return i buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset >>> 0 if (isFinite(length)) { length = length >>> 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': return latin1Write(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function latin1Slice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; ++i) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf = this.subarray(start, end) // Return an augmented `Uint8Array` instance newBuf.__proto__ = Buffer.prototype return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 var sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 var sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range') if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start var i if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } } else if (len < 1000) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start] } } else { Uint8Array.prototype.set.call( target, this.subarray(start, start + len), targetStart ) } return len } // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start start = 0 end = this.length } else if (typeof end === 'string') { encoding = end end = this.length } if (val.length === 1) { var code = val.charCodeAt(0) if (code < 256) { val = code } } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { val = val & 255 } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index') } if (end <= start) { return this } start = start >>> 0 end = end === undefined ? this.length : end >>> 0 if (!val) val = 0 var i if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val } } else { var bytes = Buffer.isBuffer(val) ? val : new Buffer(val, encoding) var len = bytes.length for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len] } } return this } // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } // valid lead leadSurrogate = codePoint continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; ++i) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } function isnan (val) { return val !== val // eslint-disable-line no-self-compare } },{"base64-js":3,"ieee754":9}],7:[function(require,module,exports){ (function (Buffer){ 'use strict'; /* eslint-disable */ var utils = require('./utils/index.js'); var uint256Coder = utils.uint256Coder; var coderBoolean = utils.coderBoolean; var coderFixedBytes = utils.coderFixedBytes; var coderAddress = utils.coderAddress; var coderDynamicBytes = utils.coderDynamicBytes; var coderString = utils.coderString; var coderArray = utils.coderArray; var paramTypePart = utils.paramTypePart; var getParamCoder = utils.getParamCoder; function Result() {} function encodeParams(types, values) { if (types.length !== values.length) { throw new Error('[ethjs-abi] while encoding params, types/values mismatch, types length ' + types.length + ' should be ' + values.length); } var parts = []; types.forEach(function (type, index) { var coder = getParamCoder(type); parts.push({ dynamic: coder.dynamic, value: coder.encode(values[index]) }); }); function alignSize(size) { return parseInt(32 * Math.ceil(size / 32)); } var staticSize = 0, dynamicSize = 0; parts.forEach(function (part) { if (part.dynamic) { staticSize += 32; dynamicSize += alignSize(part.value.length); } else { staticSize += alignSize(part.value.length); } }); var offset = 0, dynamicOffset = staticSize; var data = new Buffer(staticSize + dynamicSize); parts.forEach(function (part, index) { if (part.dynamic) { uint256Coder.encode(dynamicOffset).copy(data, offset); offset += 32; part.value.copy(data, dynamicOffset); dynamicOffset += alignSize(part.value.length); } else { part.value.copy(data, offset); offset += alignSize(part.value.length); } }); return '0x' + data.toString('hex'); } // decode bytecode data from output names and types function decodeParams(names, types, data) { // Names is optional, so shift over all the parameters if not provided if (arguments.length < 3) { data = types; types = names; names = []; } data = utils.hexOrBuffer(data); var values = new Result(); var offset = 0; types.forEach(function (type, index) { var coder = getParamCoder(type); if (coder.dynamic) { var dynamicOffset = uint256Coder.decode(data, offset); var result = coder.decode(data, dynamicOffset.value.toNumber()); offset += dynamicOffset.consumed; } else { var result = coder.decode(data, offset); offset += result.consumed; } values[index] = result.value; if (names[index]) { values[names[index]] = result.value; } }); return values; } // encode method ABI object with values in an array, output bytecode function encodeMethod(method, values) { var signature = method.name + '(' + utils.getKeys(method.inputs, 'type').join(',') + ')'; var signatureEncoded = '0x' + new Buffer(utils.keccak256(signature), 'hex').slice(0, 4).toString('hex'); var paramsEncoded = encodeParams(utils.getKeys(method.inputs, 'type'), values).substring(2); return '' + signatureEncoded + paramsEncoded; } // decode method data bytecode, from method ABI object function decodeMethod(method, data) { var outputNames = utils.getKeys(method.outputs, 'name', true); var outputTypes = utils.getKeys(method.outputs, 'type'); return decodeParams(outputNames, outputTypes, utils.hexOrBuffer(data)); } // decode method data bytecode, from method ABI object function encodeEvent(eventObject, values) { return encodeMethod(eventObject, values); } // decode method data bytecode, from method ABI object function decodeEvent(eventObject, data) { var inputNames = utils.getKeys(eventObject.inputs, 'name', true); var inputTypes = utils.getKeys(eventObject.inputs, 'type'); return decodeParams(inputNames, inputTypes, utils.hexOrBuffer(data)); } module.exports = { encodeParams: encodeParams, decodeParams: decodeParams, encodeMethod: encodeMethod, decodeMethod: decodeMethod, encodeEvent: encodeEvent, decodeEvent: decodeEvent }; }).call(this,require("buffer").Buffer) },{"./utils/index.js":8,"buffer":6}],8:[function(require,module,exports){ (function (Buffer){ 'use strict'; var BN = require('bn.js'); var numberToBN = require('number-to-bn'); var keccak256 = require('js-sha3').keccak_256; // from ethereumjs-util function stripZeros(aInput) { var a = aInput; // eslint-disable-line var first = a[0]; // eslint-disable-line while (a.length > 0 && first.toString() === '0') { a = a.slice(1); first = a[0]; } return a; } function bnToBuffer(bnInput) { var bn = bnInput; // eslint-disable-line var hex = bn.toString(16); // eslint-disable-line if (hex.length % 2) { hex = '0' + hex; } return stripZeros(new Buffer(hex, 'hex')); } function isHexString(value, length) { if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) { return false; } if (length && value.length !== 2 + 2 * length) { return false; } return true; } function hexOrBuffer(valueInput, name) { var value = valueInput; // eslint-disable-line if (!Buffer.isBuffer(value)) { if (!isHexString(value)) { var error = new Error(name ? '[ethjs-abi] invalid ' + name : '[ethjs-abi] invalid hex or buffer, must be a prefixed alphanumeric even length hex string'); error.reason = '[ethjs-abi] invalid hex string, hex must be prefixed and alphanumeric (e.g. 0x023..)'; error.value = value; throw error; } value = value.substring(2); if (value.length % 2) { value = '0' + value; } value = new Buffer(value, 'hex'); } return value; } function hexlify(value) { if (typeof value === 'number') { return '0x' + bnToBuffer(new BN(value)).toString('hex'); } else if (value.mod || value.modulo) { return '0x' + bnToBuffer(value).toString('hex'); } else { // eslint-disable-line return '0x' + hexOrBuffer(value).toString('hex'); } } // getKeys([{a: 1, b: 2}, {a: 3, b: 4}], 'a') => [1, 3] function getKeys(params, key, allowEmpty) { var result = []; // eslint-disable-line if (!Array.isArray(params)) { throw new Error('[ethjs-abi] while getting keys, invalid params value ' + JSON.stringify(params)); } for (var i = 0; i < params.length; i++) { // eslint-disable-line var value = params[i][key]; // eslint-disable-line if (allowEmpty && !value) { value = ''; } else if (typeof value !== 'string') { throw new Error('[ethjs-abi] while getKeys found invalid ABI data structure, type value not string'); } result.push(value); } return result; } function coderNumber(size, signed) { return { encode: function encodeNumber(valueInput) { var value = valueInput; // eslint-disable-line if (typeof value === 'object' && value.toString && (value.toTwos || value.dividedToIntegerBy)) { value = value.toString(10).split('.')[0]; } if (typeof value === 'string' || typeof value === 'number') { value = String(value).split('.')[0]; } value = numberToBN(value); value = value.toTwos(size * 8).maskn(size * 8); if (signed) { value = value.fromTwos(size * 8).toTwos(256); } return value.toArrayLike(Buffer, 'be', 32); }, decode: function decodeNumber(data, offset) { var junkLength = 32 - size; // eslint-disable-line var value = new BN(data.slice(offset + junkLength, offset + 32)); // eslint-disable-line if (signed) { value = value.fromTwos(size * 8); } else { value = value.maskn(size * 8); } return { consumed: 32, value: new BN(value.toString(10)) }; } }; } var uint256Coder = coderNumber(32, false); var coderBoolean = { encode: function encodeBoolean(value) { return uint256Coder.encode(value ? 1 : 0); }, decode: function decodeBoolean(data, offset) { var result = uint256Coder.decode(data, offset); // eslint-disable-line return { consumed: result.consumed, value: !result.value.isZero() }; } }; function coderFixedBytes(length) { return { encode: function encodeFixedBytes(valueInput) { var value = valueInput; // eslint-disable-line value = hexOrBuffer(value); if (value.length === 32) { return value; } var result = new Buffer(32); // eslint-disable-line result.fill(0); value.copy(result); return result; }, decode: function decodeFixedBytes(data, offset) { if (data.length < offset + 32) { throw new Error('[ethjs-abi] while decoding fixed bytes, invalid bytes data length: ' + length); } return { consumed: 32, value: '0x' + data.slice(offset, offset + length).toString('hex') }; } }; } var coderAddress = { encode: function encodeAddress(valueInput) { var value = valueInput; // eslint-disable-line var result = new Buffer(32); // eslint-disable-line if (!isHexString(value, 20)) { throw new Error('[ethjs-abi] while encoding address, invalid address value, not alphanumeric 20 byte hex string'); } value = hexOrBuffer(value); result.fill(0); value.copy(result, 12); return result; }, decode: function decodeAddress(data, offset) { if (data.length === 0) { return { consumed: 32, value: '0x' }; } if (data.length < offset + 32) { throw new Error('[ethjs-abi] while decoding address data, invalid address data, invalid byte length ' + data.length); } return { consumed: 32, value: '0x' + data.slice(offset + 12, offset + 32).toString('hex') }; } }; function encodeDynamicBytesHelper(value) { var dataLength = parseInt(32 * Math.ceil(value.length / 32)); // eslint-disable-line var padding = new Buffer(dataLength - value.length); // eslint-disable-line padding.fill(0); return Buffer.concat([uint256Coder.encode(value.length), value, padding]); } function decodeDynamicBytesHelper(data, offset) { if (data.length < offset + 32) { throw new Error('[ethjs-abi] while decoding dynamic bytes data, invalid bytes length: ' + data.length + ' should be less than ' + (offset + 32)); } var length = uint256Coder.decode(data, offset).value; // eslint-disable-line length = length.toNumber(); if (data.length < offset + 32 + length) { throw new Error('[ethjs-abi] while decoding dynamic bytes data, invalid bytes length: ' + data.length + ' should be less than ' + (offset + 32 + length)); } return { consumed: parseInt(32 + 32 * Math.ceil(length / 32), 10), value: data.slice(offset + 32, offset + 32 + length) }; } var coderDynamicBytes = { encode: function encodeDynamicBytes(value) { return encodeDynamicBytesHelper(hexOrBuffer(value)); }, decode: function decodeDynamicBytes(data, offset) { var result = decodeDynamicBytesHelper(data, offset); // eslint-disable-line result.value = '0x' + result.value.toString('hex'); return result; }, dynamic: true }; var coderString = { encode: function encodeString(value) { return encodeDynamicBytesHelper(new Buffer(value, 'utf8')); }, decode: function decodeString(data, offset) { var result = decodeDynamicBytesHelper(data, offset); // eslint-disable-line result.value = result.value.toString('utf8'); return result; }, dynamic: true }; function coderArray(coder, lengthInput) { return { encode: function encodeArray(value) { var result = new Buffer(0); // eslint-disable-line var length = lengthInput; // eslint-disable-line if (!Array.isArray(value)) { throw new Error('[ethjs-abi] while encoding array, invalid array data, not type Object (Array)'); } if (length === -1) { length = value.length; result = uint256Coder.encode(length); } if (length !== value.length) { throw new Error('[ethjs-abi] while encoding array, size mismatch array length ' + length + ' does not equal ' + value.length); } value.forEach(function (resultValue) { result = Buffer.concat([result, coder.encode(resultValue)]); }); return result; }, decode: function decodeArray(data, offsetInput) { var length = lengthInput; // eslint-disable-line var offset = offsetInput; // eslint-disable-line // @TODO: // if (data.length < offset + length * 32) { throw new Error('invalid array'); } var consumed = 0; // eslint-disable-line var decodeResult; // eslint-disable-line if (length === -1) { decodeResult = uint256Coder.decode(data, offset); length = decodeResult.value.toNumber(); consumed += decodeResult.consumed; offset += decodeResult.consumed; } var value = []; // eslint-disable-line for (var i = 0; i < length; i++) { // eslint-disable-line var loopResult = coder.decode(data, offset); consumed += loopResult.consumed; offset += loopResult.consumed; value.push(loopResult.value); } return { consumed: consumed, value: value }; }, dynamic: lengthInput === -1 }; } // Break the type up into [staticType][staticArray]*[dynamicArray]? | [dynamicType] and // build the coder up from its parts var paramTypePart = new RegExp(/^((u?int|bytes)([0-9]*)|(address|bool|string)|(\[([0-9]*)\]))/); function getParamCoder(typeInput) { var type = typeInput; // eslint-disable-line var coder = null; // eslint-disable-line var invalidTypeErrorMessage = '[ethjs-abi] while getting param coder (getParamCoder) type value ' + JSON.stringify(type) + ' is either invalid or unsupported by ethjs-abi.'; while (type) { var part = type.match(paramTypePart); // eslint-disable-line if (!part) { throw new Error(invalidTypeErrorMessage); } type = type.substring(part[0].length); var prefix = part[2] || part[4] || part[5]; // eslint-disable-line switch (prefix) { case 'int':case 'uint': if (coder) { throw new Error(invalidTypeErrorMessage); } var intSize = parseInt(part[3] || 256); // eslint-disable-line if (intSize === 0 || intSize > 256 || intSize % 8 !== 0) { throw new Error('[ethjs-abi] while getting param coder for type ' + type + ', invalid ' + prefix + ' width: ' + type); } coder = coderNumber(intSize / 8, prefix === 'int'); break; case 'bool': if (coder) { throw new Error(invalidTypeErrorMessage); } coder = coderBoolean; break; case 'string': if (coder) { throw new Error(invalidTypeErrorMessage); } coder = coderString; break; case 'bytes': if (coder) { throw new Error(invalidTypeErrorMessage); } if (part[3]) { var size = parseInt(part[3]); // eslint-disable-line if (size === 0 || size > 32) { throw new Error('[ethjs-abi] while getting param coder for prefix bytes, invalid type ' + type + ', size ' + size + ' should be 0 or greater than 32'); } coder = coderFixedBytes(size); } else { coder = coderDynamicBytes; } break; case 'address': if (coder) { throw new Error(invalidTypeErrorMessage); } coder = coderAddress; break; case '[]': if (!coder || coder.dynamic) { throw new Error(invalidTypeErrorMessage); } coder = coderArray(coder, -1); break; // "[0-9+]" default: if (!coder || coder.dynamic) { throw new Error(invalidTypeErrorMessage); } var defaultSize = parseInt(part[6]); // eslint-disable-line coder = coderArray(coder, defaultSize); } } if (!coder) { throw new Error(invalidTypeErrorMessage); } return coder; } module.exports = { BN: BN, bnToBuffer: bnToBuffer, isHexString: isHexString, hexOrBuffer: hexOrBuffer, hexlify: hexlify, stripZeros: stripZeros, keccak256: keccak256, getKeys: getKeys, numberToBN: numberToBN, coderNumber: coderNumber, uint256Coder: uint256Coder, coderBoolean: coderBoolean, coderFixedBytes: coderFixedBytes, coderAddress: coderAddress, coderDynamicBytes: coderDynamicBytes, coderString: coderString, coderArray: coderArray, paramTypePart: paramTypePart, getParamCoder: getParamCoder }; }).call(this,require("buffer").Buffer) },{"bn.js":4,"buffer":6,"js-sha3":11,"number-to-bn":12}],9:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } },{}],10:[function(require,module,exports){ /** * Returns a `Boolean` on whether or not the a `String` starts with '0x' * @param {String} str the string input value * @return {Boolean} a boolean if it is or is not hex prefixed * @throws if the str input is not a string */ module.exports = function isHexPrefixed(str) { if (typeof str !== 'string') { throw new Error("[is-hex-prefixed] value must be type 'string', is currently type " + (typeof str) + ", while checking isHexPrefixed."); } return str.slice(0, 2) === '0x'; } },{}],11:[function(require,module,exports){ (function (process,global){ /** * [js-sha3]{@link https://github.com/emn178/js-sha3} * * @version 0.5.5 * @author Chen, Yi-Cyuan [emn178@gmail.com] * @copyright Chen, Yi-Cyuan 2015-2016 * @license MIT */ (function (root) { 'use strict'; var NODE_JS = typeof process == 'object' && process.versions && process.versions.node; if (NODE_JS) { root = global; } var COMMON_JS = !root.JS_SHA3_TEST && typeof module == 'object' && module.exports; var HEX_CHARS = '0123456789abcdef'.split(''); var SHAKE_PADDING = [31, 7936, 2031616, 520093696]; var KECCAK_PADDING = [1, 256, 65536, 16777216]; var PADDING = [6, 1536, 393216, 100663296]; var SHIFT = [0, 8, 16, 24]; var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]; var BITS = [224, 256, 384, 512]; var SHAKE_BITS = [128, 256]; var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array']; var createOutputMethod = function (bits, padding, outputType) { return function (message) { return new Keccak(bits, padding, bits).update(message)[outputType](); } }; var createShakeOutputMethod = function (bits, padding, outputType) { return function (message, outputBits) { return new Keccak(bits, padding, outputBits).update(message)[outputType](); } }; var createMethod = function (bits, padding) { var method = createOutputMethod(bits, padding, 'hex'); method.create = function () { return new Keccak(bits, padding, bits); }; method.update = function (message) { return method.create().update(message); }; for (var i = 0;i < OUTPUT_TYPES.length;++i) { var type = OUTPUT_TYPES[i]; method[type] = createOutputMethod(bits, padding, type); } return method; }; var createShakeMethod = function (bits, padding) { var method = createShakeOutputMethod(bits, padding, 'hex'); method.create = function (outputBits) { return new Keccak(bits, padding, outputBits); }; method.update = function (message, outputBits) { return method.create(outputBits).update(message); }; for (var i = 0;i < OUTPUT_TYPES.length;++i) { var type = OUTPUT_TYPES[i]; method[type] = createShakeOutputMethod(bits, padding, type); } return method; }; var algorithms = [ {name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod}, {name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod}, {name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod} ]; var methods = {}; for (var i = 0;i < algorithms.length;++i) { var algorithm = algorithms[i]; var bits = algorithm.bits; for (var j = 0;j < bits.length;++j) { methods[algorithm.name +'_' + bits[j]] = algorithm.createMethod(bits[j], algorithm.padding); } } function Keccak(bits, padding, outputBits) { this.blocks = []; this.s = []; this.padding = padding; this.outputBits = outputBits; this.reset = true; this.block = 0; this.start = 0; this.blockCount = (1600 - (bits << 1)) >> 5; this.byteCount = this.blockCount << 2; this.outputBlocks = outputBits >> 5; this.extraBytes = (outputBits & 31) >> 3; for (var i = 0;i < 50;++i) { this.s[i] = 0; } }; Keccak.prototype.update = function (message) { var notString = typeof message != 'string'; if (notString && message.constructor == root.ArrayBuffer) { message = new Uint8Array(message); } var length = message.length, blocks = this.blocks, byteCount = this.byteCount, blockCount = this.blockCount, index = 0, s = this.s, i, code; while (index < length) { if (this.reset) { this.reset = false; blocks[0] = this.block; for (i = 1;i < blockCount + 1;++i) { blocks[i] = 0; } } if (notString) { for (i = this.start;index < length && i < byteCount;++index) { blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; } } else { for (i = this.start;index < length && i < byteCount;++index) { code = message.charCodeAt(index); if (code < 0x80) { blocks[i >> 2] |= code << SHIFT[i++ & 3]; } else if (code < 0x800) { blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } else if (code < 0xd800 || code >= 0xe000) { blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } else { code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } } } this.lastByteIndex = i; if (i >= byteCount) { this.start = i - byteCount; this.block = blocks[blockCount]; for (i = 0;i < blockCount;++i) { s[i] ^= blocks[i]; } f(s); this.reset = true; } else { this.start = i; } } return this; }; Keccak.prototype.finalize = function () { var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s; blocks[i >> 2] |= this.padding[i & 3]; if (this.lastByteIndex == this.byteCount) { blocks[0] = blocks[blockCount]; for (i = 1;i < blockCount + 1;++i) { blocks[i] = 0; } } blocks[blockCount - 1] |= 0x80000000; for (i = 0;i < blockCount;++i) { s[i] ^= blocks[i]; } f(s); }; Keccak.prototype.toString = Keccak.prototype.hex = function () { this.finalize(); var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i = 0, j = 0; var hex = '', block; while (j < outputBlocks) { for (i = 0;i < blockCount && j < outputBlocks;++i, ++j) { block = s[i]; hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] + HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] + HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] + HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F]; } if (j % blockCount == 0) { f(s); i = 0; } } if (extraBytes) { block = s[i]; if (extraBytes > 0) { hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F]; } if (extraBytes > 1) { hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F]; } if (extraBytes > 2) { hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F]; } } return hex; }; Keccak.prototype.arrayBuffer = function () { this.finalize(); var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i = 0, j = 0; var bytes = this.outputBits >> 3; var buffer; if (extraBytes) { buffer = new ArrayBuffer((outputBlocks + 1) << 2); } else { buffer = new ArrayBuffer(bytes); } var array = new Uint32Array(buffer); while (j < outputBlocks) { for (i = 0;i < blockCount && j < outputBlocks;++i, ++j) { array[j] = s[i]; } if (j % blockCount == 0) { f(s); } } if (extraBytes) { array[i] = s[i]; buffer = buffer.slice(0, bytes); } return buffer; }; Keccak.prototype.buffer = Keccak.prototype.arrayBuffer; Keccak.prototype.digest = Keccak.prototype.array = function () { this.finalize(); var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i = 0, j = 0; var array = [], offset, block; while (j < outputBlocks) { for (i = 0;i < blockCount && j < outputBlocks;++i, ++j) { offset = j << 2; block = s[i]; array[offset] = block & 0xFF; array[offset + 1] = (block >> 8) & 0xFF; array[offset + 2] = (block >> 16) & 0xFF; array[offset + 3] = (block >> 24) & 0xFF; } if (j % blockCount == 0) { f(s); } } if (extraBytes) { offset = j << 2; block = s[i]; if (extraBytes > 0) { array[offset] = block & 0xFF; } if (extraBytes > 1) { array[offset + 1] = (block >> 8) & 0xFF; } if (extraBytes > 2) { array[offset + 2] = (block >> 16) & 0xFF; } } return array; }; var f = function (s) { var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49; for (n = 0;n < 48;n += 2) { c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]; c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]; c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]; c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]; c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]; c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]; c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]; c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]; c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]; c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]; h = c8 ^ ((c2 << 1) | (c3 >>> 31)); l = c9 ^ ((c3 << 1) | (c2 >>> 31)); s[0] ^= h; s[1] ^= l; s[10] ^= h; s[11] ^= l; s[20] ^= h; s[21] ^= l; s[30] ^= h; s[31] ^= l; s[40] ^= h; s[41] ^= l; h = c0 ^ ((c4 << 1) | (c5 >>> 31)); l = c1 ^ ((c5 << 1) | (c4 >>> 31)); s[2] ^= h; s[3] ^= l; s[12] ^= h; s[13] ^= l; s[22] ^= h; s[23] ^= l; s[32] ^= h; s[33] ^= l; s[42] ^= h; s[43] ^= l; h = c2 ^ ((c6 << 1) | (c7 >>> 31)); l = c3 ^ ((c7 << 1) | (c6 >>> 31)); s[4] ^= h; s[5] ^= l; s[14] ^= h; s[15] ^= l; s[24] ^= h; s[25] ^= l; s[34] ^= h; s[35] ^= l; s[44] ^= h; s[45] ^= l; h = c4 ^ ((c8 << 1) | (c9 >>> 31)); l = c5 ^ ((c9 << 1) | (c8 >>> 31)); s[6] ^= h; s[7] ^= l; s[16] ^= h; s[17] ^= l; s[26] ^= h; s[27] ^= l; s[36] ^= h; s[37] ^= l; s[46] ^= h; s[47] ^= l; h = c6 ^ ((c0 << 1) | (c1 >>> 31)); l = c7 ^ ((c1 << 1) | (c0 >>> 31)); s[8] ^= h; s[9] ^= l; s[18] ^= h; s[19] ^= l; s[28] ^= h; s[29] ^= l; s[38] ^= h; s[39] ^= l; s[48] ^= h; s[49] ^= l; b0 = s[0]; b1 = s[1]; b32 = (s[11] << 4) | (s[10] >>> 28); b33 = (s[10] << 4) | (s[11] >>> 28); b14 = (s[20] << 3) | (s[21] >>> 29); b15 = (s[21] << 3) | (s[20] >>> 29); b46 = (s[31] << 9) | (s[30] >>> 23); b47 = (s[30] << 9) | (s[31] >>> 23); b28 = (s[40] << 18) | (s[41] >>> 14); b29 = (s[41] << 18) | (s[40] >>> 14); b20 = (s[2] << 1) | (s[3] >>> 31); b21 = (s[3] << 1) | (s[2] >>> 31); b2 = (s[13] << 12) | (s[12] >>> 20); b3 = (s[12] << 12) | (s[13] >>> 20); b34 = (s[22] << 10) | (s[23] >>> 22); b35 = (s[23] << 10) | (s[22] >>> 22); b16 = (s[33] << 13) | (s[32] >>> 19); b17 = (s[32] << 13) | (s[33] >>> 19); b48 = (s[42] << 2) | (s[43] >>> 30); b49 = (s[43] << 2) | (s[42] >>> 30); b40 = (s[5] << 30) | (s[4] >>> 2); b41 = (s[4] << 30) | (s[5] >>> 2); b22 = (s[14] << 6) | (s[15] >>> 26); b23 = (s[15] << 6) | (s[14] >>> 26); b4 = (s[25] << 11) | (s[24] >>> 21); b5 = (s[24] << 11) | (s[25] >>> 21); b36 = (s[34] << 15) | (s[35] >>> 17); b37 = (s[35] << 15) | (s[34] >>> 17); b18 = (s[45] << 29) | (s[44] >>> 3); b19 = (s[44] << 29) | (s[45] >>> 3); b10 = (s[6] << 28) | (s[7] >>> 4); b11 = (s[7] << 28) | (s[6] >>> 4); b42 = (s[17] << 23) | (s[16] >>> 9); b43 = (s[16] << 23) | (s[17] >>> 9); b24 = (s[26] << 25) | (s[27] >>> 7); b25 = (s[27] << 25) | (s[26] >>> 7); b6 = (s[36] << 21) | (s[37] >>> 11); b7 = (s[37] << 21) | (s[36] >>> 11); b38 = (s[47] << 24) | (s[46] >>> 8); b39 = (s[46] << 24) | (s[47] >>> 8); b30 = (s[8] << 27) | (s[9] >>> 5); b31 = (s[9] << 27) | (s[8] >>> 5); b12 = (s[18] << 20) | (s[19] >>> 12); b13 = (s[19] << 20) | (s[18] >>> 12); b44 = (s[29] << 7) | (s[28] >>> 25); b45 = (s[28] << 7) | (s[29] >>> 25); b26 = (s[38] << 8) | (s[39] >>> 24); b27 = (s[39] << 8) | (s[38] >>> 24); b8 = (s[48] << 14) | (s[49] >>> 18); b9 = (s[49] << 14) | (s[48] >>> 18); s[0] = b0 ^ (~b2 & b4); s[1] = b1 ^ (~b3 & b5); s[10] = b10 ^ (~b12 & b14); s[11] = b11 ^ (~b13 & b15); s[20] = b20 ^ (~b22 & b24); s[21] = b21 ^ (~b23 & b25); s[30] = b30 ^ (~b32 & b34); s[31] = b31 ^ (~b33 & b35); s[40] = b40 ^ (~b42 & b44); s[41] = b41 ^ (~b43 & b45); s[2] = b2 ^ (~b4 & b6); s[3] = b3 ^ (~b5 & b7); s[12] = b12 ^ (~b14 & b16); s[13] = b13 ^ (~b15 & b17); s[22] = b22 ^ (~b24 & b26); s[23] = b23 ^ (~b25 & b27); s[32] = b32 ^ (~b34 & b36); s[33] = b33 ^ (~b35 & b37); s[42] = b42 ^ (~b44 & b46); s[43] = b43 ^ (~b45 & b47); s[4] = b4 ^ (~b6 & b8); s[5] = b5 ^ (~b7 & b9); s[14] = b14 ^ (~b16 & b18); s[15] = b15 ^ (~b17 & b19); s[24] = b24 ^ (~b26 & b28); s[25] = b25 ^ (~b27 & b29); s[34] = b34 ^ (~b36 & b38); s[35] = b35 ^ (~b37 & b39); s[44] = b44 ^ (~b46 & b48); s[45] = b45 ^ (~b47 & b49); s[6] = b6 ^ (~b8 & b0); s[7] = b7 ^ (~b9 & b1); s[16] = b16 ^ (~b18 & b10); s[17] = b17 ^ (~b19 & b11); s[26] = b26 ^ (~b28 & b20); s[27] = b27 ^ (~b29 & b21); s[36] = b36 ^ (~b38 & b30); s[37] = b37 ^ (~b39 & b31); s[46] = b46 ^ (~b48 & b40); s[47] = b47 ^ (~b49 & b41); s[8] = b8 ^ (~b0 & b2); s[9] = b9 ^ (~b1 & b3); s[18] = b18 ^ (~b10 & b12); s[19] = b19 ^ (~b11 & b13); s[28] = b28 ^ (~b20 & b22); s[29] = b29 ^ (~b21 & b23); s[38] = b38 ^ (~b30 & b32); s[39] = b39 ^ (~b31 & b33); s[48] = b48 ^ (~b40 & b42); s[49] = b49 ^ (~b41 & b43); s[0] ^= RC[n]; s[1] ^= RC[n + 1]; } } if (COMMON_JS) { module.exports = methods; } else if (root) { for (var key in methods) { root[key] = methods[key]; } } }(this)); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":13}],12:[function(require,module,exports){ var BN = require('bn.js'); var stripHexPrefix = require('strip-hex-prefix'); /** * Returns a BN object, converts a number value to a BN * @param {String|Number|Object} `arg` input a string number, hex string number, number, BigNumber or BN object * @return {Object} `output` BN object of the number * @throws if the argument is not an array, object that isn't a bignumber, not a string number or number */ module.exports = function numberToBN(arg) { if (typeof arg === 'string' || typeof arg === 'number') { var multiplier = new BN(1); // eslint-disable-line var formattedString = String(arg).toLowerCase().trim(); var isHexPrefixed = formattedString.substr(0, 2) === '0x' || formattedString.substr(0, 3) === '-0x'; var stringArg = stripHexPrefix(formattedString); // eslint-disable-line if (stringArg.substr(0, 1) === '-') { stringArg = stripHexPrefix(stringArg.slice(1)); multiplier = new BN(-1, 10); } stringArg = stringArg === '' ? '0' : stringArg; if ((!stringArg.match(/^-?[0-9]+$/) && stringArg.match(/^[0-9A-Fa-f]+$/)) || stringArg.match(/^[a-fA-F]+$/) || (isHexPrefixed === true && stringArg.match(/^[0-9A-Fa-f]+$/))) { return new BN(stringArg, 16).mul(multiplier); } if ((stringArg.match(/^-?[0-9]+$/) || stringArg === '') && isHexPrefixed === false) { return new BN(stringArg, 10).mul(multiplier); } } else if (typeof arg === 'object' && arg.toString && (!arg.pop && !arg.push)) { if (arg.toString(10).match(/^-?[0-9]+$/) && (arg.mul || arg.dividedToIntegerBy)) { return new BN(arg.toString(10), 10); } } throw new Error('[number-to-bn] while converting number ' + JSON.stringify(arg) + ' to BN.js instance, error: invalid number value. Value must be an integer, hex string, BN or BigNumber instance. Note, decimals are not supported.'); } },{"bn.js":4,"strip-hex-prefix":14}],13:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],14:[function(require,module,exports){ var isHexPrefixed = require('is-hex-prefixed'); /** * Removes '0x' from a given `String` is present * @param {String} str the string value * @return {String|Optional} a string by pass if necessary */ module.exports = function stripHexPrefix(str) { if (typeof str !== 'string') { return str; } return isHexPrefixed(str) ? str.slice(2) : str; } },{"is-hex-prefixed":10}],15:[function(require,module,exports){ // TODO: remove web3 requirement // Call functions directly on the provider. var Web3 = require("web3"); var Blockchain = { parse: function(uri) { var parsed = {}; if (uri.indexOf("blockchain://") != 0) return parsed; uri = uri.replace("blockchain://", ""); var pieces = uri.split("/block/"); parsed.genesis_hash = "0x" + pieces[0]; parsed.block_hash = "0x" + pieces[1]; return parsed; }, asURI: function(provider, callback) { var web3 = new Web3(provider); web3.eth.getBlock(0, function(err, genesis) { if (err) return callback(err); web3.eth.getBlock("latest", function(err, latest) { if (err) return callback(err); var url = "blockchain://" + genesis.hash.replace("0x", "") + "/block/" + latest.hash.replace("0x", ""); callback(null, url); }); }); }, matches: function(uri, provider, callback) { uri = this.parse(uri); var expected_genesis = uri.genesis_hash; var expected_block = uri.block_hash; var web3 = new Web3(provider); web3.eth.getBlock(0, function(err, block) { if (err) return callback(err); if (block.hash != expected_genesis) return callback(null, false); web3.eth.getBlock(expected_block, function(err, block) { // Treat an error as if the block didn't exist. This is because // some clients respond differently. if (err || block == null) { return callback(null, false); } callback(null, true); }); }); } }; module.exports = Blockchain; },{"web3":5}],16:[function(require,module,exports){ var sha3 = require("crypto-js/sha3"); var schema_version = require("./package.json").version; var TruffleSchema = { // Normalize options passed in to be the exact options required // for truffle-contract. // // options can be three things: // - normal object // - contract object // - solc output // // TODO: Is extra_options still necessary? normalizeOptions: function(options, extra_options) { extra_options = extra_options || {}; var normalized = {}; var expected_keys = [ "contract_name", "abi", "binary", "unlinked_binary", "address", "networks", "links", "events", "network_id", "default_network", "updated_at" ]; // Merge options/contract object first, then extra_options expected_keys.forEach(function(key) { var value; try { // Will throw an error if key == address and address doesn't exist. value = options[key]; if (value != undefined) { normalized[key] = value; } } catch (e) { // Do nothing. } try { // Will throw an error if key == address and address doesn't exist. value = extra_options[key]; if (value != undefined) { normalized[key] = value; } } catch (e) { // Do nothing. } }); // Now look for solc specific items. if (options.interface != null) { normalized.abi = JSON.parse(options.interface); } if (options.bytecode != null) { normalized.unlinked_binary = options.bytecode } // Assume any binary passed is the unlinked binary if (normalized.unlinked_binary == null && normalized.binary) { normalized.unlinked_binary = normalized.binary; } delete normalized.binary; this.copyCustomOptions(options, normalized); return normalized; }, // Generate a proper binary from normalized options, and optionally // merge it with an existing binary. generateBinary: function(options, existing_binary, extra_options) { extra_options = extra_options || {}; existing_binary = existing_binary || {}; if (options.overwrite == true) { existing_binary = {}; } existing_binary.contract_name = options.contract_name || existing_binary.contract_name || "Contract"; existing_binary.default_network = options.default_network || existing_binary.default_network; existing_binary.abi = options.abi || existing_binary.abi; existing_binary.unlinked_binary = options.unlinked_binary || existing_binary.unlinked_binary; // Ensure unlinked binary starts with a 0x if (existing_binary.unlinked_binary && existing_binary.unlinked_binary.indexOf("0x") < 0) { existing_binary.unlinked_binary = "0x" + existing_binary.unlinked_binary; } // Merge existing networks with any passed in networks. existing_binary.networks = existing_binary.networks || {}; options.networks = options.networks || {}; Object.keys(options.networks).forEach(function(network_id) { existing_binary.networks[network_id] = options.networks[network_id]; }); var updated_at = new Date().getTime(); if (options.network_id) { // Ensure an object exists for this network. existing_binary.networks[options.network_id] = existing_binary.networks[options.network_id] || {}; var network = existing_binary.networks[options.network_id]; // Override specific keys network.address = options.address || network.address; network.links = options.links; // merge events with any that previously existed network.events = network.events || {}; options.events = options.events || {}; Object.keys(options.events).forEach(function(event_id) { options.events[event_id] = options.events[event_id]; }); // Now overwrite any events with the most recent data from the ABI. existing_binary.abi.forEach(function(item) { if (item.type != "event") return; var signature = item.name + "(" + item.inputs.map(function(param) {return param.type;}).join(",") + ")"; network.events["0x" + sha3(signature, {outputLength: 256})] = item; }); if (extra_options.dirty !== false) { network.updated_at = updated_at; } } else { if (options.address) { throw new Error("Cannot set address without network id"); } } // Ensure all networks have a `links` object. Object.keys(existing_binary.networks).forEach(function(network_id) { var network = existing_binary.networks[network_id]; network.links = network.links || {}; }); existing_binary.schema_version = schema_version; if (extra_options.dirty !== false) { existing_binary.updated_at = updated_at; } else { existing_binary.updated_at = options.updated_at || existing_binary.updated_at || updated_at; } this.copyCustomOptions(options, existing_binary); return existing_binary; }, copyCustomOptions: function(from, to) { // Now let all x- options through. Object.keys(from).forEach(function(key) { if (key.indexOf("x-") != 0) return; try { value = from[key]; if (value != undefined) { to[key] = value; } } catch (e) { // Do nothing. } }); } }; module.exports = TruffleSchema; },{"./package.json":20,"crypto-js/sha3":18}],17:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(); } else if (typeof define === "function" && define.amd) { // AMD define([], factory); } else { // Global (browser) root.CryptoJS = factory(); } }(this, function () { /** * CryptoJS core components. */ var CryptoJS = CryptoJS || (function (Math, undefined) { /* * Local polyfil of Object.create */ var create = Object.create || (function () { function F() {}; return function (obj) { var subtype; F.prototype = obj; subtype = new F(); F.prototype = null; return subtype; }; }()) /** * CryptoJS namespace. */ var C = {}; /** * Library namespace. */ var C_lib = C.lib = {}; /** * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function (overrides) { // Spawn var subtype = create(this); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function () { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function () { return this.init.prototype.extend(this); } }; }()); /** * An array of 32-bit words. * * @property {Array} words The array of 32-bit words. * @property {number} sigBytes The number of significant bytes in this word array. */ var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function (encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function (wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else { // Copy one word at a time for (var i = 0; i < thatSigBytes; i += 4) { thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; } } this.sigBytes += thatSigBytes; // Chainable return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function () { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function (nBytes) { var words = []; var r = (function (m_w) { var m_w = m_w; var m_z = 0x3ade68b1; var mask = 0xffffffff; return function () { m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; var result = ((m_z << 0x10) + m_w) & mask; result /= 0x100000000; result += 0.5; return result * (Math.random() > .5 ? 1 : -1); } }); for (var i = 0, rcache; i < nBytes; i += 4) { var _r = r((rcache || Math.random()) * 0x100000000); rcache = _r() * 0x3ade67b7; words.push((_r() * 0x100000000) | 0); } return new WordArray.init(words, nBytes); } }); /** * Encoder namespace. */ var C_enc = C.enc = {}; /** * Hex encoding strategy. */ var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function (hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); } }; /** * Latin1 encoding strategy. */ var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function (latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); } }; /** * UTF-8 encoding strategy. */ var Utf8 = C_enc.Utf8 = { /** * Converts a word array to a UTF-8 string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-8 string. * * @static * * @example * * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); */ stringify: function (wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error('Malformed UTF-8 data'); } }, /** * Converts a UTF-8 string to a word array. * * @param {string} utf8Str The UTF-8 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ parse: function (utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); } }; /** * Abstract buffered block algorithm template. * * The property blockSize must be implemented in a concrete subtype. * * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 */ var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** * Resets this block algorithm's data buffer to its initial state. * * @example * * bufferedBlockAlgorithm.reset(); */ reset: function () { // Initial values this._data = new WordArray.init(); this._nDataBytes = 0; }, /** * Adds new data to this block algorithm's buffer. * * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. * * @example * * bufferedBlockAlgorithm._append('data'); * bufferedBlockAlgorithm._append(wordArray); */ _append: function (data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; }, /** * Processes available data blocks. * * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. * * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. * * @return {WordArray} The processed data. * * @example * * var processedData = bufferedBlockAlgorithm._process(); * var processedData = bufferedBlockAlgorithm._process(!!'flush'); */ _process: function (doFlush) { // Shortcuts var data = this._data; var dataWords = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; // Count blocks ready var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { // Round up to include partial blocks nBlocksReady = Math.ceil(nBlocksReady); } else { // Round down to include only full blocks, // less the number of blocks that must remain in the buffer nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); } // Count words ready var nWordsReady = nBlocksReady * blockSize; // Count bytes ready var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { // Perform concrete-algorithm logic this._doProcessBlock(dataWords, offset); } // Remove processed words var processedWords = dataWords.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } // Return processed words return new WordArray.init(processedWords, nBytesReady); }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = bufferedBlockAlgorithm.clone(); */ clone: function () { var clone = Base.clone.call(this); clone._data = this._data.clone(); return clone; }, _minBufferSize: 0 }); /** * Abstract hasher template. * * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) */ var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ /** * Configuration options. */ cfg: Base.extend(), /** * Initializes a newly created hasher. * * @param {Object} cfg (Optional) The configuration options to use for this hash computation. * * @example * * var hasher = CryptoJS.algo.SHA256.create(); */ init: function (cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Set initial values this.reset(); }, /** * Resets this hasher to its initial state. * * @example * * hasher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic this._doReset(); }, /** * Updates this hasher with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {Hasher} This hasher. * * @example * * hasher.update('message'); * hasher.update(wordArray); */ update: function (messageUpdate) { // Append this._append(messageUpdate); // Update the hash this._process(); // Chainable return this; }, /** * Finalizes the hash computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The hash. * * @example * * var hash = hasher.finalize(); * var hash = hasher.finalize('message'); * var hash = hasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Final message update if (messageUpdate) { this._append(messageUpdate); } // Perform concrete-hasher logic var hash = this._doFinalize(); return hash; }, blockSize: 512/32, /** * Creates a shortcut function to a hasher's object interface. * * @param {Hasher} hasher The hasher to create a helper for. * * @return {Function} The shortcut function. * * @static * * @example * * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ _createHelper: function (hasher) { return function (message, cfg) { return new hasher.init(cfg).finalize(message); }; }, /** * Creates a shortcut function to the HMAC's object interface. * * @param {Hasher} hasher The hasher to use in this HMAC helper. * * @return {Function} The shortcut function. * * @static * * @example * * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ _createHmacHelper: function (hasher) { return function (message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; } }); /** * Algorithm namespace. */ var C_algo = C.algo = {}; return C; }(Math)); return CryptoJS; })); },{}],18:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var C_algo = C.algo; // Constants tables var RHO_OFFSETS = []; var PI_INDEXES = []; var ROUND_CONSTANTS = []; // Compute Constants (function () { // Compute rho offset constants var x = 1, y = 0; for (var t = 0; t < 24; t++) { RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; var newX = y % 5; var newY = (2 * x + 3 * y) % 5; x = newX; y = newY; } // Compute pi index constants for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; } } // Compute round constants var LFSR = 0x01; for (var i = 0; i < 24; i++) { var roundConstantMsw = 0; var roundConstantLsw = 0; for (var j = 0; j < 7; j++) { if (LFSR & 0x01) { var bitPosition = (1 << j) - 1; if (bitPosition < 32) { roundConstantLsw ^= 1 << bitPosition; } else /* if (bitPosition >= 32) */ { roundConstantMsw ^= 1 << (bitPosition - 32); } } // Compute next LFSR if (LFSR & 0x80) { // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 LFSR = (LFSR << 1) ^ 0x71; } else { LFSR <<= 1; } } ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); } }()); // Reusable objects for temporary values var T = []; (function () { for (var i = 0; i < 25; i++) { T[i] = X64Word.create(); } }()); /** * SHA-3 hash algorithm. */ var SHA3 = C_algo.SHA3 = Hasher.extend({ /** * Configuration options. * * @property {number} outputLength * The desired number of bits in the output hash. * Only values permitted are: 224, 256, 384, 512. * Default: 512 */ cfg: Hasher.cfg.extend({ outputLength: 512 }), _doReset: function () { var state = this._state = [] for (var i = 0; i < 25; i++) { state[i] = new X64Word.init(); } this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; }, _doProcessBlock: function (M, offset) { // Shortcuts var state = this._state; var nBlockSizeLanes = this.blockSize / 2; // Absorb for (var i = 0; i < nBlockSizeLanes; i++) { // Shortcuts var M2i = M[offset + 2 * i]; var M2i1 = M[offset + 2 * i + 1]; // Swap endian M2i = ( (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) ); M2i1 = ( (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) ); // Absorb message into state var lane = state[i]; lane.high ^= M2i1; lane.low ^= M2i; } // Rounds for (var round = 0; round < 24; round++) { // Theta for (var x = 0; x < 5; x++) { // Mix column lanes var tMsw = 0, tLsw = 0; for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; tMsw ^= lane.high; tLsw ^= lane.low; } // Temporary values var Tx = T[x]; Tx.high = tMsw; Tx.low = tLsw; } for (var x = 0; x < 5; x++) { // Shortcuts var Tx4 = T[(x + 4) % 5]; var Tx1 = T[(x + 1) % 5]; var Tx1Msw = Tx1.high; var Tx1Lsw = Tx1.low; // Mix surrounding columns var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; lane.high ^= tMsw; lane.low ^= tLsw; } } // Rho Pi for (var laneIndex = 1; laneIndex < 25; laneIndex++) { // Shortcuts var lane = state[laneIndex]; var laneMsw = lane.high; var laneLsw = lane.low; var rhoOffset = RHO_OFFSETS[laneIndex]; // Rotate lanes if (rhoOffset < 32) { var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); } else /* if (rhoOffset >= 32) */ { var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); } // Transpose lanes var TPiLane = T[PI_INDEXES[laneIndex]]; TPiLane.high = tMsw; TPiLane.low = tLsw; } // Rho pi at x = y = 0 var T0 = T[0]; var state0 = state[0]; T0.high = state0.high; T0.low = state0.low; // Chi for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { // Shortcuts var laneIndex = x + 5 * y; var lane = state[laneIndex]; var TLane = T[laneIndex]; var Tx1Lane = T[((x + 1) % 5) + 5 * y]; var Tx2Lane = T[((x + 2) % 5) + 5 * y]; // Mix rows lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); } } // Iota var lane = state[0]; var roundConstant = ROUND_CONSTANTS[round]; lane.high ^= roundConstant.high; lane.low ^= roundConstant.low;; } }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; var blockSizeBits = this.blockSize * 32; // Add padding dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Shortcuts var state = this._state; var outputLengthBytes = this.cfg.outputLength / 8; var outputLengthLanes = outputLengthBytes / 8; // Squeeze var hashWords = []; for (var i = 0; i < outputLengthLanes; i++) { // Shortcuts var lane = state[i]; var laneMsw = lane.high; var laneLsw = lane.low; // Swap endian laneMsw = ( (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) ); laneLsw = ( (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) ); // Squeeze state to retrieve hash hashWords.push(laneLsw); hashWords.push(laneMsw); } // Return final computed hash return new WordArray.init(hashWords, outputLengthBytes); }, clone: function () { var clone = Hasher.clone.call(this); var state = clone._state = this._state.slice(0); for (var i = 0; i < 25; i++) { state[i] = state[i].clone(); } return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA3('message'); * var hash = CryptoJS.SHA3(wordArray); */ C.SHA3 = Hasher._createHelper(SHA3); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA3(message, key); */ C.HmacSHA3 = Hasher._createHmacHelper(SHA3); }(Math)); return CryptoJS.SHA3; })); },{"./core":17,"./x64-core":19}],19:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var X32WordArray = C_lib.WordArray; /** * x64 namespace. */ var C_x64 = C.x64 = {}; /** * A 64-bit word. */ var X64Word = C_x64.Word = Base.extend({ /** * Initializes a newly created 64-bit word. * * @param {number} high The high 32 bits. * @param {number} low The low 32 bits. * * @example * * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); */ init: function (high, low) { this.high = high; this.low = low; } /** * Bitwise NOTs this word. * * @return {X64Word} A new x64-Word object after negating. * * @example * * var negated = x64Word.not(); */ // not: function () { // var high = ~this.high; // var low = ~this.low; // return X64Word.create(high, low); // }, /** * Bitwise ANDs this word with the passed word. * * @param {X64Word} word The x64-Word to AND with this word. * * @return {X64Word} A new x64-Word object after ANDing. * * @example * * var anded = x64Word.and(anotherX64Word); */ // and: function (word) { // var high = this.high & word.high; // var low = this.low & word.low; // return X64Word.create(high, low); // }, /** * Bitwise ORs this word with the passed word. * * @param {X64Word} word The x64-Word to OR with this word. * * @return {X64Word} A new x64-Word object after ORing. * * @example * * var ored = x64Word.or(anotherX64Word); */ // or: function (word) { // var high = this.high | word.high; // var low = this.low | word.low; // return X64Word.create(high, low); // }, /** * Bitwise XORs this word with the passed word. * * @param {X64Word} word The x64-Word to XOR with this word. * * @return {X64Word} A new x64-Word object after XORing. * * @example * * var xored = x64Word.xor(anotherX64Word); */ // xor: function (word) { // var high = this.high ^ word.high; // var low = this.low ^ word.low; // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the left. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftL(25); */ // shiftL: function (n) { // if (n < 32) { // var high = (this.high << n) | (this.low >>> (32 - n)); // var low = this.low << n; // } else { // var high = this.low << (n - 32); // var low = 0; // } // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the right. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftR(7); */ // shiftR: function (n) { // if (n < 32) { // var low = (this.low >>> n) | (this.high << (32 - n)); // var high = this.high >>> n; // } else { // var low = this.high >>> (n - 32); // var high = 0; // } // return X64Word.create(high, low); // }, /** * Rotates this word n bits to the left. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotL(25); */ // rotL: function (n) { // return this.shiftL(n).or(this.shiftR(64 - n)); // }, /** * Rotates this word n bits to the right. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotR(7); */ // rotR: function (n) { // return this.shiftR(n).or(this.shiftL(64 - n)); // }, /** * Adds this word with the passed word. * * @param {X64Word} word The x64-Word to add with this word. * * @return {X64Word} A new x64-Word object after adding. * * @example * * var added = x64Word.add(anotherX64Word); */ // add: function (word) { // var low = (this.low + word.low) | 0; // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; // var high = (this.high + word.high + carry) | 0; // return X64Word.create(high, low); // } }); /** * An array of 64-bit words. * * @property {Array} words The array of CryptoJS.x64.Word objects. * @property {number} sigBytes The number of significant bytes in this word array. */ var X64WordArray = C_x64.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.x64.WordArray.create(); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ]); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ], 10); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 8; } }, /** * Converts this 64-bit word array to a 32-bit word array. * * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. * * @example * * var x32WordArray = x64WordArray.toX32(); */ toX32: function () { // Shortcuts var x64Words = this.words; var x64WordsLength = x64Words.length; // Convert var x32Words = []; for (var i = 0; i < x64WordsLength; i++) { var x64Word = x64Words[i]; x32Words.push(x64Word.high); x32Words.push(x64Word.low); } return X32WordArray.create(x32Words, this.sigBytes); }, /** * Creates a copy of this word array. * * @return {X64WordArray} The clone. * * @example * * var clone = x64WordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); // Clone "words" array var words = clone.words = this.words.slice(0); // Clone each X64Word object var wordsLength = words.length; for (var i = 0; i < wordsLength; i++) { words[i] = words[i].clone(); } return clone; } }); }()); return CryptoJS; })); },{"./core":17}],20:[function(require,module,exports){ module.exports={ "_args": [ [ { "raw": "truffle-contract-schema@0.0.5", "scope": null, "escapedName": "truffle-contract-schema", "name": "truffle-contract-schema", "rawSpec": "0.0.5", "spec": "0.0.5", "type": "version" }, "/Users/tim/Documents/workspace/Consensys/truffle-contract" ] ], "_from": "truffle-contract-schema@0.0.5", "_id": "truffle-contract-schema@0.0.5", "_inCache": true, "_location": "/truffle-contract-schema", "_nodeVersion": "6.9.1", "_npmOperationalInternal": { "host": "packages-12-west.internal.npmjs.com", "tmp": "tmp/truffle-contract-schema-0.0.5.tgz_1485557985137_0.46875762194395065" }, "_npmUser": { "name": "tcoulter", "email": "tim@timothyjcoulter.com" }, "_npmVersion": "3.10.8", "_phantomChildren": {}, "_requested": { "raw": "truffle-contract-schema@0.0.5", "scope": null, "escapedName": "truffle-contract-schema", "name": "truffle-contract-schema", "rawSpec": "0.0.5", "spec": "0.0.5", "type": "version" }, "_requiredBy": [ "/" ], "_resolved": "https://registry.npmjs.org/truffle-contract-schema/-/truffle-contract-schema-0.0.5.tgz", "_shasum": "5e9d20bd0bf2a27fe94310748249d484eee49961", "_shrinkwrap": null, "_spec": "truffle-contract-schema@0.0.5", "_where": "/Users/tim/Documents/workspace/Consensys/truffle-contract", "author": { "name": "Tim Coulter", "email": "tim.coulter@consensys.net" }, "bugs": { "url": "https://github.com/trufflesuite/truffle-schema/issues" }, "dependencies": { "crypto-js": "^3.1.9-1" }, "description": "JSON schema for contract artifacts", "devDependencies": { "mocha": "^3.2.0" }, "directories": {}, "dist": { "shasum": "5e9d20bd0bf2a27fe94310748249d484eee49961", "tarball": "https://registry.npmjs.org/truffle-contract-schema/-/truffle-contract-schema-0.0.5.tgz" }, "gitHead": "cfa4313bd4bb95bf5b94f85185203ead418f9ee6", "homepage": "https://github.com/trufflesuite/truffle-schema#readme", "keywords": [ "ethereum", "json", "schema", "contract", "artifacts" ], "license": "MIT", "main": "index.js", "maintainers": [ { "name": "tcoulter", "email": "tim@timothyjcoulter.com" } ], "name": "truffle-contract-schema", "optionalDependencies": {}, "readme": "ERROR: No README data found!", "repository": { "type": "git", "url": "git+https://github.com/trufflesuite/truffle-schema.git" }, "scripts": { "test": "mocha" }, "version": "0.0.5" } },{}]},{},[2]); ================================================ FILE: truffle/tpetshop/src/pets.json ================================================ [ { "id": 0, "name": "Frieda", "picture": "images/scottish-terrier.jpeg", "age": 3, "breed": "Scottish Terrier", "location": "Lisco, Alabama" }, { "id": 1, "name": "Gina", "picture": "images/scottish-terrier.jpeg", "age": 3, "breed": "Scottish Terrier", "location": "Tooleville, West Virginia" }, { "id": 2, "name": "Collins", "picture": "images/french-bulldog.jpeg", "age": 2, "breed": "French Bulldog", "location": "Freeburn, Idaho" }, { "id": 3, "name": "Melissa", "picture": "images/boxer.jpeg", "age": 2, "breed": "Boxer", "location": "Camas, Pennsylvania" }, { "id": 4, "name": "Jeanine", "picture": "images/french-bulldog.jpeg", "age": 2, "breed": "French Bulldog", "location": "Gerber, South Dakota" }, { "id": 5, "name": "Elvia", "picture": "images/french-bulldog.jpeg", "age": 3, "breed": "French Bulldog", "location": "Innsbrook, Illinois" }, { "id": 6, "name": "Latisha", "picture": "images/golden-retriever.jpeg", "age": 3, "breed": "Golden Retriever", "location": "Soudan, Louisiana" }, { "id": 7, "name": "Coleman", "picture": "images/golden-retriever.jpeg", "age": 3, "breed": "Golden Retriever", "location": "Jacksonwald, Palau" }, { "id": 8, "name": "Nichole", "picture": "images/french-bulldog.jpeg", "age": 2, "breed": "French Bulldog", "location": "Honolulu, Hawaii" }, { "id": 9, "name": "Fran", "picture": "images/boxer.jpeg", "age": 3, "breed": "Boxer", "location": "Matheny, Utah" }, { "id": 10, "name": "Leonor", "picture": "images/boxer.jpeg", "age": 2, "breed": "Boxer", "location": "Tyhee, Indiana" }, { "id": 11, "name": "Dean", "picture": "images/scottish-terrier.jpeg", "age": 3, "breed": "Golden Retriever", "location": "Windsor, Montana" }, { "id": 12, "name": "Stevenson", "picture": "images/french-bulldog.jpeg", "age": 3, "breed": "French Bulldog", "location": "Kingstowne, Nevada" }, { "id": 13, "name": "Kristina", "picture": "images/golden-retriever.jpeg", "age": 4, "breed": "Golden Retriever", "location": "Sultana, Massachusetts" }, { "id": 14, "name": "Ethel", "picture": "images/golden-retriever.jpeg", "age": 2, "breed": "Golden Retriever", "location": "Broadlands, Oregon" }, { "id": 15, "name": "Terry", "picture": "images/golden-retriever.jpeg", "age": 2, "breed": "Golden Retriever", "location": "Dawn, Wisconsin" } ] ================================================ FILE: truffle/tpetshop/test/.gitkeep ================================================ ================================================ FILE: truffle/tpetshop/test/TestAdoption.sol ================================================ import "truffle/Assert.sol"; import "truffle/DeployedAddresses.sol"; import "../contracts/Adoption.sol"; contract TestAdoption { Adoption adoption = Adoption(DeployedAddresses.Adoption()); // Testing the adopt() function function testUserCanAdoptPet() { uint returnedId = adoption.adopt(8); uint expected = 8; Assert.equal(returnedId, expected, "Adoption of pet ID 8 should be recorded."); } // Testing retrieval of a single pet's owner function testGetAdopterAddressByPetId() { // Expected owner is this contract address expected = this; address adopter = adoption.adopters(8); Assert.equal(adopter, expected, "Owner of pet ID 8 should be recorded."); } // Testing retrieval of all pet owners function testGetAdopterAddressByPetIdInArray() { // Expected owner is this contract address expected = this; // Store adopters in memory rather than contract's storage address[16] memory adopters = adoption.getAdopters(); Assert.equal(adopters[8], expected, "Owner of pet ID 8 should be recorded."); } } ================================================ FILE: truffle/tpetshop/truffle-config.js ================================================ module.exports = { networks: { development: { host: "localhost", port: 8545, network_id: "*" // Match any network id } } }; ================================================ FILE: truffle/webapp/.babelrc ================================================ { "presets": ["env"] } ================================================ FILE: truffle/webapp/.eslintignore ================================================ tmp/** build/** node_modules/** contracts/** migrations/1_initial_migration.js migrations/2_deploy_contracts.js test/metacoin.js ================================================ FILE: truffle/webapp/.eslintrc ================================================ { "parser": "babel-eslint", "extends": [ "standard" ], "plugins": [ "babel" ], "rules": { "key-spacing" : 0, "jsx-quotes" : [2, "prefer-single"], "max-len" : [2, 120, 2], "object-curly-spacing" : [2, "always"] } } ================================================ FILE: truffle/webapp/.gitignore ================================================ build node_modules yarn-error.log ================================================ FILE: truffle/webapp/ORIGINALREADME.md ================================================ # Webpack Truffle Box This box it our most bare official implementation with Webpack. Includes contracts, migrations, tests, user interface and webpack build pipeline. ## Installation 1. Install Truffle globally. ```javascript npm install -g truffle ``` 2. Download the box. This also takes care of installing the necessary dependencies. ```javascript truffle unbox webpack ``` 3. Run the development console. ```javascript truffle develop ``` 4. Compile and migrate the smart contracts. Note inside the development console we don't preface commands with `truffle`. ```javascript compile migrate ``` 5. Run the webpack server for front-end hot reloading (outside the development console). Smart contract changes must be manually recompiled and migrated. ```javascript // Serves the front-end on http://localhost:8080 npm run dev ``` 6. Truffle can run tests written in Solidity or JavaScript against your smart contracts. Note the command varies slightly if you're in or outside of the development console. ```javascript // If inside the development console. test // If outside the development console.. truffle test ``` ## FAQ * __How do I use this with the EthereumJS TestRPC?__ It's as easy as modifying the config file! [Check out our documentation on adding network configurations](http://truffleframework.com/docs/advanced/configuration#networks). Depending on the port you're using, you'll also need to update lines 96 and 98 of `app/javascripts/app.js`. * __I'm encountering this error: Error: Can't resolve '../build/contracts/MetaCoin.json'__ This means you haven't compiled or migrated your contracts yet. Run `truffle develop`, `compile` and `migrate` first. Full error: ``` ERROR in ./app/main.js Module not found: Error: Can't resolve '../build/contracts/MetaCoin.json' in '/Users/tim/Documents/workspace/Consensys/test3/app' @ ./app/main.js 11:16-59 ``` ================================================ FILE: truffle/webapp/README.md ================================================ # Webpack Truffle Demo From http://truffleframework.com/tutorials/building-testing-frontend-app-truffle-3 Launch an Ethereum client, like TestRPC, RPC entry point at http://127.0.0.1:8545. If you need to change the address edit the file `app\javascripts\app.js`. Run ``` truffle compile truffle deploy npm run build npm run dev ``` In Windows you must use `truffle.cmd` instead of `truffle` It was tested using Truffle v3.4.9, installed globally: ``` npm install -g truffle@3.4.9 ``` ================================================ FILE: truffle/webapp/app/index.html ================================================ MetaCoin - Truffle Webpack Demo w/ Frontend

MetaCoin

Example Truffle Dapp

You have META


Send MetaCoin








Hint: open the browser developer console to view any errors and warnings. ================================================ FILE: truffle/webapp/app/javascripts/app.js ================================================ // Import the page's CSS. Webpack will know what to do with it. import "../stylesheets/app.css"; // Import libraries we need. import { default as Web3} from 'web3'; import { default as contract } from 'truffle-contract' // Import our contract artifacts and turn them into usable abstractions. import metacoin_artifacts from '../../build/contracts/MetaCoin.json' // MetaCoin is our usable abstraction, which we'll use through the code below. var MetaCoin = contract(metacoin_artifacts); // The following code is simple to show off interacting with your contracts. // As your needs grow you will likely need to change its form and structure. // For application bootstrapping, check out window.addEventListener below. var accounts; var account; window.App = { start: function() { var self = this; // Bootstrap the MetaCoin abstraction for Use. MetaCoin.setProvider(web3.currentProvider); // Get the initial account balance so it can be displayed. web3.eth.getAccounts(function(err, accs) { if (err != null) { alert("There was an error fetching your accounts."); return; } if (accs.length == 0) { alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly."); return; } accounts = accs; account = accounts[0]; self.refreshBalance(); }); }, setStatus: function(message) { var status = document.getElementById("status"); status.innerHTML = message; }, refreshBalance: function() { var self = this; var meta; MetaCoin.deployed().then(function(instance) { meta = instance; return meta.getBalance.call(account, {from: account}); }).then(function(value) { var balance_element = document.getElementById("balance"); balance_element.innerHTML = value.valueOf(); }).catch(function(e) { console.log(e); self.setStatus("Error getting balance; see log."); }); }, sendCoin: function() { var self = this; var amount = parseInt(document.getElementById("amount").value); var receiver = document.getElementById("receiver").value; this.setStatus("Initiating transaction... (please wait)"); var meta; MetaCoin.deployed().then(function(instance) { meta = instance; return meta.sendCoin(receiver, amount, {from: account}); }).then(function() { self.setStatus("Transaction complete!"); self.refreshBalance(); }).catch(function(e) { console.log(e); self.setStatus("Error sending coin; see log."); }); } }; window.addEventListener('load', function() { // Checking if Web3 has been injected by the browser (Mist/MetaMask) if (typeof web3 !== 'undefined') { console.warn("Using web3 detected from external source. If you find that your accounts don't appear or you have 0 MetaCoin, ensure you've configured that source properly. If using MetaMask, see the following link. Feel free to delete this warning. :) http://truffleframework.com/tutorials/truffle-and-metamask") // Use Mist/MetaMask's provider window.web3 = new Web3(web3.currentProvider); } else { console.warn("No web3 detected. Falling back to http://127.0.0.1:8545. You should remove this fallback when you deploy live, as it's inherently insecure. Consider switching to Metamask for development. More info here: http://truffleframework.com/tutorials/truffle-and-metamask"); // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail) window.web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:8545")); } App.start(); }); ================================================ FILE: truffle/webapp/app/stylesheets/app.css ================================================ body { margin-left: 25%; margin-right: 25%; margin-top: 10%; font-family: "Open Sans", sans-serif; } label { display: inline-block; width: 100px; } input { width: 500px; padding: 5px; font-size: 16px; } button { font-size: 16px; padding: 5px; } h1, h2 { display: inline-block; vertical-align: middle; margin-top: 0px; margin-bottom: 10px; } h2 { color: #AAA; font-size: 32px; } h3 { font-weight: normal; color: #AAA; font-size: 24px; } .black { color: black; } #balance { color: black; } .hint { color: #666; } ================================================ FILE: truffle/webapp/contracts/ConvertLib.sol ================================================ pragma solidity ^0.4.2; library ConvertLib{ function convert(uint amount,uint conversionRate) returns (uint convertedAmount) { return amount * conversionRate; } } ================================================ FILE: truffle/webapp/contracts/MetaCoin.sol ================================================ pragma solidity ^0.4.2; import "./ConvertLib.sol"; // This is just a simple example of a coin-like contract. // It is not standards compatible and cannot be expected to talk to other // coin/token contracts. If you want to create a standards-compliant // token, see: https://github.com/ConsenSys/Tokens. Cheers! contract MetaCoin { mapping (address => uint) balances; event Transfer(address indexed _from, address indexed _to, uint256 _value); function MetaCoin() { balances[tx.origin] = 10000; } function sendCoin(address receiver, uint amount) returns(bool sufficient) { if (balances[msg.sender] < amount) return false; balances[msg.sender] -= amount; balances[receiver] += amount; Transfer(msg.sender, receiver, amount); return true; } function getBalanceInEth(address addr) returns(uint){ return ConvertLib.convert(getBalance(addr),2); } function getBalance(address addr) returns(uint) { return balances[addr]; } } ================================================ FILE: truffle/webapp/contracts/Migrations.sol ================================================ pragma solidity ^0.4.2; contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } function Migrations() { owner = msg.sender; } function setCompleted(uint completed) restricted { last_completed_migration = completed; } function upgrade(address new_address) restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } ================================================ FILE: truffle/webapp/migrations/1_initial_migration.js ================================================ var Migrations = artifacts.require("./Migrations.sol"); module.exports = function(deployer) { deployer.deploy(Migrations); }; ================================================ FILE: truffle/webapp/migrations/2_deploy_contracts.js ================================================ var ConvertLib = artifacts.require("./ConvertLib.sol"); var MetaCoin = artifacts.require("./MetaCoin.sol"); module.exports = function(deployer) { deployer.deploy(ConvertLib); deployer.link(ConvertLib, MetaCoin); deployer.deploy(MetaCoin); }; ================================================ FILE: truffle/webapp/package.json ================================================ { "name": "truffle-init-webpack", "version": "0.0.2", "description": "Frontend example using truffle v3", "scripts": { "lint": "eslint ./", "build": "webpack", "dev": "webpack-dev-server" }, "author": "Douglas von Kohorn", "license": "MIT", "devDependencies": { "babel-cli": "^6.22.2", "babel-core": "^6.22.1", "babel-eslint": "^6.1.2", "babel-loader": "^6.2.10", "babel-plugin-transform-runtime": "^6.22.0", "babel-preset-env": "^1.1.8", "babel-preset-es2015": "^6.22.0", "babel-register": "^6.22.0", "copy-webpack-plugin": "^4.0.1", "css-loader": "^0.26.1", "eslint": "^3.14.0", "eslint-config-standard": "^6.0.0", "eslint-plugin-babel": "^4.0.0", "eslint-plugin-mocha": "^4.8.0", "eslint-plugin-promise": "^3.0.0", "eslint-plugin-standard": "^2.0.0", "html-webpack-plugin": "^2.28.0", "json-loader": "^0.5.4", "style-loader": "^0.13.1", "truffle-contract": "^1.1.11", "web3": "^0.20.0", "webpack": "^2.2.1", "webpack-dev-server": "^2.3.0" } } ================================================ FILE: truffle/webapp/test/TestMetacoin.sol ================================================ pragma solidity ^0.4.2; import "truffle/Assert.sol"; import "truffle/DeployedAddresses.sol"; import "../contracts/MetaCoin.sol"; contract TestMetacoin { function testInitialBalanceUsingDeployedContract() { MetaCoin meta = MetaCoin(DeployedAddresses.MetaCoin()); uint expected = 10000; Assert.equal(meta.getBalance(tx.origin), expected, "Owner should have 10000 MetaCoin initially"); } function testInitialBalanceWithNewMetaCoin() { MetaCoin meta = new MetaCoin(); uint expected = 10000; Assert.equal(meta.getBalance(tx.origin), expected, "Owner should have 10000 MetaCoin initially"); } } ================================================ FILE: truffle/webapp/test/metacoin.js ================================================ var MetaCoin = artifacts.require("./MetaCoin.sol"); contract('MetaCoin', function(accounts) { it("should put 10000 MetaCoin in the first account", function() { return MetaCoin.deployed().then(function(instance) { return instance.getBalance.call(accounts[0]); }).then(function(balance) { assert.equal(balance.valueOf(), 10000, "10000 wasn't in the first account"); }); }); it("should call a function that depends on a linked library", function() { var meta; var metaCoinBalance; var metaCoinEthBalance; return MetaCoin.deployed().then(function(instance) { meta = instance; return meta.getBalance.call(accounts[0]); }).then(function(outCoinBalance) { metaCoinBalance = outCoinBalance.toNumber(); return meta.getBalanceInEth.call(accounts[0]); }).then(function(outCoinBalanceEth) { metaCoinEthBalance = outCoinBalanceEth.toNumber(); }).then(function() { assert.equal(metaCoinEthBalance, 2 * metaCoinBalance, "Library function returned unexpeced function, linkage may be broken"); }); }); it("should send coin correctly", function() { var meta; // Get initial balances of first and second account. var account_one = accounts[0]; var account_two = accounts[1]; var account_one_starting_balance; var account_two_starting_balance; var account_one_ending_balance; var account_two_ending_balance; var amount = 10; return MetaCoin.deployed().then(function(instance) { meta = instance; return meta.getBalance.call(account_one); }).then(function(balance) { account_one_starting_balance = balance.toNumber(); return meta.getBalance.call(account_two); }).then(function(balance) { account_two_starting_balance = balance.toNumber(); return meta.sendCoin(account_two, amount, {from: account_one}); }).then(function() { return meta.getBalance.call(account_one); }).then(function(balance) { account_one_ending_balance = balance.toNumber(); return meta.getBalance.call(account_two); }).then(function(balance) { account_two_ending_balance = balance.toNumber(); assert.equal(account_one_ending_balance, account_one_starting_balance - amount, "Amount wasn't correctly taken from the sender"); assert.equal(account_two_ending_balance, account_two_starting_balance + amount, "Amount wasn't correctly sent to the receiver"); }); }); }); ================================================ FILE: truffle/webapp/truffle-box.json ================================================ { "ignore": [ "README.md", ".gitignore" ], "commands": { "Compile": "truffle compile", "Migrate": "truffle migrate", "Test contracts": "truffle test", "Run linter": "npm run lint", "Run dev server": "npm run dev", "Build for production": "npm run build" }, "hooks": { "post-unpack": "npm install" } } ================================================ FILE: truffle/webapp/truffle.js ================================================ // Allows us to use ES6 in our migrations and tests. require('babel-register') module.exports = { networks: { development: { host: 'localhost', port: 8545, network_id: '*' // Match any network id } } } ================================================ FILE: truffle/webapp/webpack.config.js ================================================ const path = require('path'); const CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { entry: './app/javascripts/app.js', output: { path: path.resolve(__dirname, 'build'), filename: 'app.js' }, plugins: [ // Copy our app's index.html to the build folder. new CopyWebpackPlugin([ { from: './app/index.html', to: "index.html" } ]) ], module: { rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] } ], loaders: [ { test: /\.json$/, use: 'json-loader' }, { test: /\.js$/, exclude: /(node_modules|bower_components)/, loader: 'babel-loader', query: { presets: ['es2015'], plugins: ['transform-runtime'] } } ] } } ================================================ FILE: truffle/zero/contracts/ConvertLib.sol ================================================ pragma solidity ^0.4.4; library ConvertLib{ function convert(uint amount,uint conversionRate) returns (uint convertedAmount) { return amount * conversionRate; } } ================================================ FILE: truffle/zero/contracts/MetaCoin.sol ================================================ pragma solidity ^0.4.4; import "./ConvertLib.sol"; // This is just a simple example of a coin-like contract. // It is not standards compatible and cannot be expected to talk to other // coin/token contracts. If you want to create a standards-compliant // token, see: https://github.com/ConsenSys/Tokens. Cheers! contract MetaCoin { mapping (address => uint) balances; event Transfer(address indexed _from, address indexed _to, uint256 _value); function MetaCoin() { balances[tx.origin] = 10000; } function sendCoin(address receiver, uint amount) returns(bool sufficient) { if (balances[msg.sender] < amount) return false; balances[msg.sender] -= amount; balances[receiver] += amount; Transfer(msg.sender, receiver, amount); return true; } function getBalanceInEth(address addr) returns(uint){ return ConvertLib.convert(getBalance(addr),2); } function getBalance(address addr) returns(uint) { return balances[addr]; } } ================================================ FILE: truffle/zero/contracts/Migrations.sol ================================================ pragma solidity ^0.4.4; contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } function Migrations() { owner = msg.sender; } function setCompleted(uint completed) restricted { last_completed_migration = completed; } function upgrade(address new_address) restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } ================================================ FILE: truffle/zero/migrations/1_initial_migration.js ================================================ var Migrations = artifacts.require("./Migrations.sol"); module.exports = function(deployer) { deployer.deploy(Migrations); }; ================================================ FILE: truffle/zero/migrations/2_deploy_contracts.js ================================================ var ConvertLib = artifacts.require("./ConvertLib.sol"); var MetaCoin = artifacts.require("./MetaCoin.sol"); module.exports = function(deployer) { deployer.deploy(ConvertLib); deployer.link(ConvertLib, MetaCoin); deployer.deploy(MetaCoin); }; ================================================ FILE: truffle/zero/test/TestMetacoin.sol ================================================ pragma solidity ^0.4.2; import "truffle/Assert.sol"; import "truffle/DeployedAddresses.sol"; import "../contracts/MetaCoin.sol"; contract TestMetacoin { function testInitialBalanceUsingDeployedContract() { MetaCoin meta = MetaCoin(DeployedAddresses.MetaCoin()); uint expected = 10000; Assert.equal(meta.getBalance(tx.origin), expected, "Owner should have 10000 MetaCoin initially"); } function testInitialBalanceWithNewMetaCoin() { MetaCoin meta = new MetaCoin(); uint expected = 10000; Assert.equal(meta.getBalance(tx.origin), expected, "Owner should have 10000 MetaCoin initially"); } } ================================================ FILE: truffle/zero/test/metacoin.js ================================================ var MetaCoin = artifacts.require("./MetaCoin.sol"); contract('MetaCoin', function(accounts) { it("should put 10000 MetaCoin in the first account", function() { return MetaCoin.deployed().then(function(instance) { return instance.getBalance.call(accounts[0]); }).then(function(balance) { assert.equal(balance.valueOf(), 10000, "10000 wasn't in the first account"); }); }); it("should call a function that depends on a linked library", function() { var meta; var metaCoinBalance; var metaCoinEthBalance; return MetaCoin.deployed().then(function(instance) { meta = instance; return meta.getBalance.call(accounts[0]); }).then(function(outCoinBalance) { metaCoinBalance = outCoinBalance.toNumber(); return meta.getBalanceInEth.call(accounts[0]); }).then(function(outCoinBalanceEth) { metaCoinEthBalance = outCoinBalanceEth.toNumber(); }).then(function() { assert.equal(metaCoinEthBalance, 2 * metaCoinBalance, "Library function returned unexpected function, linkage may be broken"); }); }); it("should send coin correctly", function() { var meta; // Get initial balances of first and second account. var account_one = accounts[0]; var account_two = accounts[1]; var account_one_starting_balance; var account_two_starting_balance; var account_one_ending_balance; var account_two_ending_balance; var amount = 10; return MetaCoin.deployed().then(function(instance) { meta = instance; return meta.getBalance.call(account_one); }).then(function(balance) { account_one_starting_balance = balance.toNumber(); return meta.getBalance.call(account_two); }).then(function(balance) { account_two_starting_balance = balance.toNumber(); return meta.sendCoin(account_two, amount, {from: account_one}); }).then(function() { return meta.getBalance.call(account_one); }).then(function(balance) { account_one_ending_balance = balance.toNumber(); return meta.getBalance.call(account_two); }).then(function(balance) { account_two_ending_balance = balance.toNumber(); assert.equal(account_one_ending_balance, account_one_starting_balance - amount, "Amount wasn't correctly taken from the sender"); assert.equal(account_two_ending_balance, account_two_starting_balance + amount, "Amount wasn't correctly sent to the receiver"); }); }); }); ================================================ FILE: web31/abiencoding.js ================================================ var Web3 = require('web3'); var web = new Web3(); console.log(web.eth.abi.encodeParameter('int[]', [1, 2, 3])); console.log(web.eth.abi.encodeParameter('string[]', ['hello adsad asdsa asdsa asdsa hello adsad asdsa asdsa asdsa hello adsad asdsa asdsa asdsa', 'world'])); web.eth.abi.decodeParameter('string[]', web.eth.abi.encodeParameter('string[]', ['hello', 'world'])); ================================================ FILE: web31/accounts.js ================================================ var Web3 = require('web3'); var web = new Web3('http://localhost:8545'); web.eth.getAccounts(function (err, accounts) { if (err) console.error(err); else console.dir(accounts); }); ================================================ FILE: web31/accounts2.js ================================================ var Web3 = require('web3'); var web = new Web3('http://localhost:8545'); async function run() { var accounts = await web.eth.getAccounts(); console.log(accounts); } run(); ================================================ FILE: web31/ballot.sol ================================================ pragma solidity ^0.4.11; /// @title Voting with delegation. contract Ballot { // This declares a new complex type which will // be used for variables later. // It will represent a single voter. struct Voter { uint weight; // weight is accumulated by delegation bool voted; // if true, that person already voted address delegate; // person delegated to uint vote; // index of the voted proposal } // This is a type for a single proposal. struct Proposal { bytes32 name; // short name (up to 32 bytes) uint voteCount; // number of accumulated votes } address public chairperson; // This declares a state variable that // stores a `Voter` struct for each possible address. mapping(address => Voter) public voters; // A dynamically-sized array of `Proposal` structs. Proposal[] public proposals; /// Create a new ballot to choose one of `proposalNames`. function Ballot(bytes32[] proposalNames) { chairperson = msg.sender; voters[chairperson].weight = 1; // For each of the provided proposal names, // create a new proposal object and add it // to the end of the array. for (uint i = 0; i < proposalNames.length; i++) { // `Proposal({...})` creates a temporary // Proposal object and `proposals.push(...)` // appends it to the end of `proposals`. proposals.push(Proposal({ name: proposalNames[i], voteCount: 0 })); } } // Give `voter` the right to vote on this ballot. // May only be called by `chairperson`. function giveRightToVote(address voter) { // If the argument of `require` evaluates to `false`, // it terminates and reverts all changes to // the state and to Ether balances. It is often // a good idea to use this if functions are // called incorrectly. But watch out, this // will currently also consume all provided gas // (this is planned to change in the future). require((msg.sender == chairperson) && !voters[voter].voted && (voters[voter].weight == 0)); voters[voter].weight = 1; } /// Delegate your vote to the voter `to`. function delegate(address to) { // assigns reference Voter storage sender = voters[msg.sender]; require(!sender.voted); // Self-delegation is not allowed. require(to != msg.sender); // Forward the delegation as long as // `to` also delegated. // In general, such loops are very dangerous, // because if they run too long, they might // need more gas than is available in a block. // In this case, the delegation will not be executed, // but in other situations, such loops might // cause a contract to get "stuck" completely. while (voters[to].delegate != address(0)) { to = voters[to].delegate; // We found a loop in the delegation, not allowed. require(to != msg.sender); } // Since `sender` is a reference, this // modifies `voters[msg.sender].voted` sender.voted = true; sender.delegate = to; Voter storage delegate = voters[to]; if (delegate.voted) { // If the delegate already voted, // directly add to the number of votes proposals[delegate.vote].voteCount += sender.weight; } else { // If the delegate did not vote yet, // add to her weight. delegate.weight += sender.weight; } } /// Give your vote (including votes delegated to you) /// to proposal `proposals[proposal].name`. function vote(uint proposal) { Voter storage sender = voters[msg.sender]; require(!sender.voted); sender.voted = true; sender.vote = proposal; // If `proposal` is out of the range of the array, // this will throw automatically and revert all // changes. proposals[proposal].voteCount += sender.weight; } /// @dev Computes the winning proposal taking all /// previous votes into account. function winningProposal() constant returns (uint winningProposal) { uint winningVoteCount = 0; for (uint p = 0; p < proposals.length; p++) { if (proposals[p].voteCount > winningVoteCount) { winningVoteCount = proposals[p].voteCount; winningProposal = p; } } } // Calls winningProposal() function to get the index // of the winner contained in the proposals array and then // returns the name of the winner function winnerName() constant returns (bytes32 winnerName) { winnerName = proposals[winningProposal()].name; } } ================================================ FILE: web31/compile.js ================================================ var fs = require('fs'); var solc = require('solc'); function findImports(path) { return { contents: fs.readFileSync('./' + path).toString() }; // return { error: 'File not found' } } function compileContract(filename) { var input = fs.readFileSync(filename).toString(); var sources = {}; sources[filename] = input; var output = solc.compile({ sources: sources }, 1, findImports); // 1 activates the optimiser return output.contracts; } var contracts = compileContract(process.argv[2]); console.dir(Object.keys(contracts)); for (var n in contracts) { console.log(Object.keys(contracts[n])); console.log(contracts[n].functionHashes); console.log(contracts[n].assembly); console.log(contracts[n].gasEstimates); console.log(contracts[n].opcodes); console.log(contracts[n].interface); console.log(contracts[n].bytecode); console.log(contracts[n].runtimeBytecode); } ================================================ FILE: web31/config.json ================================================ { "host": "http://localhost:8545" } ================================================ FILE: web31/counter.js ================================================ var solc = require('solc'); var Web3 = require('web3'); var fs = require('fs'); var config = require('./config.json'); var sargs = require('simpleargs'); sargs .define('h', 'host', config.host, 'Host JSON RPC entry point') .define('f', 'from', config.from, 'From account address or number') .define('l', 'logging', false, 'Enable logging', { flag: true }) var options = sargs(process.argv.slice(2)); var args = options._; var web3 = new Web3(options.host); function findImports(path) { return { contents: fs.readFileSync('./' + path).toString() }; // return { error: 'File not found' } } function compileContract(filename) { var input = fs.readFileSync(filename).toString(); var sources = {}; sources[filename] = input; var output = solc.compile({ sources: sources }, 1, findImports); // 1 activates the optimiser return output.contracts; } var contracts = compileContract('counter.sol'); var contractnames = Object.keys(contracts); var contractdef = contracts[contractnames[contractnames.length - 1]]; var contract = new web3.eth.Contract(JSON.parse(contractdef.interface)); var accounts; var run = async () => { const accounts = await web3.eth.getAccounts(); var tx = contract.deploy({ data: contractdef.bytecode }); console.log('transaction data'); console.log(tx.encodeABI()); var transactionHash = await tx.send({ from: options.from || accounts[0], gas: 3000000, gasPrice: 0 }).on('receipt', async function (receipt) { console.log('transaction receipt'); console.dir(receipt); console.log('contract address', receipt.contractAddress); var counter = new web3.eth.Contract(JSON.parse(contractdef.interface), receipt.contractAddress); console.log(Object.keys(counter.methods)); const c = await counter.methods.getCounter().call(); console.log('counter', c); await counter.methods.increment().send({ from: options.from || accounts[0], gas: 3000000, gasPrice: 0 }); const c2 = await counter.methods.getCounter().call(); console.log('counter', c2); await counter.methods.add(40).send({ from: options.from || accounts[0], gas: 3000000, gasPrice: 0 }); const c3 = await counter.methods.getCounter().call(); console.log('counter', c3); }) .on('confirmation', function (confirmationNumber, receipt) { console.log('confirmation number', confirmationNumber); console.log('transaction receipt'); console.dir(receipt); console.log('contract address', receipt.contractAddress); }); } run(); ================================================ FILE: web31/counter.json ================================================ [{"constant":false,"inputs":[{"name":"v","type":"uint256"}],"name":"add","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"getCounter","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"increment","outputs":[],"payable":false,"type":"function"},{"inputs":[],"type":"constructor"}] ================================================ FILE: web31/counter.sol ================================================ // Simple counter contract contract Counter { uint counter; function Counter() { counter = 1; } function increment() { counter++; } function add(uint v) { counter += v; } function getCounter() constant returns (uint) { return counter; } } ================================================ FILE: web31/counter1.js ================================================ var Web3 = require('web3'); var web = new Web3('http://localhost:8545'); var json = require('./counter.json'); var contract = new web.eth.Contract(json); console.dir(contract.methods); console.dir(contract.options); console.log(contract.methods.add(1).encodeABI()); ================================================ FILE: web31/deploy.js ================================================ var solc = require('solc'); var Web3 = require('web3'); var sasync = require('simpleasync'); var fs = require('fs'); var config = require('./config.json'); var sargs = require('simpleargs'); sargs .define('h', 'host', config.host, 'Host JSON RPC entry point') .define('f', 'from', config.from, 'From account address or number') .define('l', 'logging', false, 'Enable logging', { flag: true }) var options = sargs(process.argv.slice(2)); var args = options._; var web3 = new Web3(options.host); function findImports(path) { return { contents: fs.readFileSync('./' + path).toString() }; // return { error: 'File not found' } } function compileContract(filename) { var input = fs.readFileSync(filename).toString(); var sources = {}; sources[filename] = input; var output = solc.compile({ sources: sources }, 1, findImports); // 1 activates the optimiser return output.contracts; } var contracts = compileContract(args[0]); var contractnames = Object.keys(contracts); var contractdef = contracts[contractnames[contractnames.length -1]]; var contract = new web3.eth.Contract(JSON.parse(contractdef.interface)); var accounts; sasync() .exec(function (next) { web3.eth.getAccounts(next) }) .then(function (data, next) { accounts = data; var tx = contract.deploy({ data: contractdef.bytecode }); tx.send({ from: options.from || accounts[0], gas: 3000000, gasPrice: 0 }, function (err, transactionHash) { if (err) return console.error(err); console.log('transaction hash'); console.dir(transactionHash); }) .on('receipt', function (receipt) { console.log('transaction receipt'); console.dir(receipt); console.log('contract address', receipt.contractAddress); }) .on('confirmation', function (confirmationNumber, receipt) { console.log('confirmation number', confirmationNumber); console.log('transaction receipt'); console.dir(receipt); console.log('contract address', receipt.contractAddress); }); console.log('transaction data'); console.log(tx.encodeABI()); }); ================================================ FILE: web31/deploy1.js ================================================ var Web3 = require('web3'); var web = new Web3('http://localhost:8545'); var json = require('./counter.json'); var contract = new web.eth.Contract(json); console.dir(web.eth.getAccounts); var tx = contract.deploy({ data: '60606040525b60016000600050819055505b60db80601d6000396000f360606040526000357c0100000000000000000000000000000000000000000000000000000000900480631003e2d214604d5780638ada066e146067578063d09de08a14608c576049565b6002565b3460025760656004808035906020019091905050609d565b005b346002576076600480505060b3565b6040518082815260200191505060405180910390f35b34600257609b600480505060c4565b005b8060006000828282505401925050819055505b50565b6000600060005054905060c1565b90565b60006000818150548092919060010191905055505b56' }); tx.send({ from: '0xda5ac26b293ea206d31b1b8ec1f4250798a184d6', gas: 3000000, gasPrice: 0 }, function (err, transactionHash) { if (err) return console.error(err); console.log('transaction hash'); console.dir(transactionHash); }) .on('receipt', function (receipt) { console.log('transaction receipt'); console.dir(receipt); console.log('contract address', receipt.contractAddress); }) .on('confirmation', function (confirmationNumber, receipt) { console.log('confirmation number', confirmationNumber); console.log('transaction receipt'); console.dir(receipt); console.log('contract address', receipt.contractAddress); }); console.log('transaction data'); console.log(tx.encodeABI()); console.log('add method data'); console.log(contract.methods.add(42).encodeABI()); ================================================ FILE: web31/deploy2.js ================================================ var solc = require('solc'); var Web3 = require('web3'); var fs = require('fs'); var config = require('./config.json'); var sargs = require('simpleargs'); sargs .define('h', 'host', config.host, 'Host JSON RPC entry point') .define('f', 'from', config.from, 'From account address or number') .define('l', 'logging', false, 'Enable logging', { flag: true }) var options = sargs(process.argv.slice(2)); var args = options._; var web3 = new Web3(options.host); function findImports(path) { return { contents: fs.readFileSync('./' + path).toString() }; // return { error: 'File not found' } } function compileContract(filename) { var input = fs.readFileSync(filename).toString(); var sources = {}; sources[filename] = input; var output = solc.compile({ sources: sources }, 1, findImports); // 1 activates the optimiser return output.contracts; } var contracts = compileContract(args[0]); var contractnames = Object.keys(contracts); var contractdef = contracts[contractnames[contractnames.length -1]]; var contract = new web3.eth.Contract(JSON.parse(contractdef.interface)); var accounts; var run = async () => { const accounts = await web3.eth.getAccounts(); var tx = contract.deploy({ data: contractdef.bytecode }); console.log('transaction data'); console.log(tx.encodeABI()); var transactionHash = await tx.send({ from: options.from || accounts[0], gas: 3000000, gasPrice: 0 }).on('receipt', function (receipt) { console.log('transaction receipt'); console.dir(receipt); console.log('contract address', receipt.contractAddress); }) .on('confirmation', function (confirmationNumber, receipt) { console.log('confirmation number', confirmationNumber); console.log('transaction receipt'); console.dir(receipt); console.log('contract address', receipt.contractAddress); }); } run(); ================================================ FILE: web31/greeter.sol ================================================ contract Greeter { string public message; function Greeter() { message = "Hello, Contract"; } function setMessage(string msg) { message = msg; } } ================================================ FILE: web31/message.json ================================================ [{"constant":false,"inputs":[{"name":"msg","type":"string"}],"name":"setMessage","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"message","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"inputs":[{"name":"msg","type":"string"}],"type":"constructor"}] ================================================ FILE: web31/message.sol ================================================ contract Message { string public message; function Message(string msg) { message = msg; } function setMessage(string msg) { message = msg; } } ================================================ FILE: web31/package.json ================================================ { "name": "web31_samples", "private": true, "version": "1.0.0", "description": "", "main": "test.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "simpleargs": "0.0.3", "simpleasync": "0.0.8", "solc": "^0.4.18", "web3": "^1.0.0-beta.24" } }