Lawrence  Lesch

Lawrence Lesch

1673682660

Monorepo for the Ethereum VM TypeScript Implementation

EthereumJS Monorepo

This repository holds various protocol building blocks of the Ethereum blockchain execution layer and is managed by the Ethereum Foundation JavaScript team. There is a TypeScript implementation of the Ethereum Virtual Machine (EVM) ready to be used in Node.js or a browser environment, implementations of core structural blockchain building blocks like an Ethereum Tx, Block or Blockchain as well as a Trie (Merkle Patricia Tree) and devp2p (execution networking layer) implementation.

All libraries are bound together by the core Common library keeping track of chain specifics and hardfork changes. They are complemented by helper packages like RLP for data encoding/decoding or Util, providing helper functionalities like (byte) conversion, signatures, types and others.

Finally, the EthereumJS Execution Client (EthereumJS) has been in active development for some time now. It already serves a variety of purposes like testing, research (e.g. EIPs) and developer tooling to engage with the protocol.

Also to note: on the Ethereum Consensus side, the ChainSafe Lodestar repository complements this repository with an Ethereum Consensus Client implementation as well as various protocol implementations (like an SSZ library) developed in the context of Ethereum Consensus layer evolution.

Packages

Below you can find a list of the packages included in this repository.

packagenpmissuestestscoverage
@ethereumjs/blockNPM PackageBlock IssuesActions StatusCode Coverage
@ethereumjs/blockchainNPM PackageBlockchain IssuesActions StatusCode Coverage
@ethereumjs/clientNPM PackageClient IssuesActions StatusCode Coverage
@ethereumjs/commonNPM PackageCommon IssuesActions StatusCode Coverage
@ethereumjs/devp2pNPM PackageDevp2p IssuesActions StatusCode Coverage
@ethereumjs/ethashNPM PackageEthash IssuesActions StatusCode Coverage
@ethereumjs/evmNPM PackageEVM IssuesActions StatusCode Coverage
@ethereumjs/rlpNPM Packagerlp IssuesActions StatusCode Coverage
@ethereumjs/statemanagerNPM PackageStateManager IssuesActions StatusCode Coverage
@ethereumjs/trieNPM PackageTrie IssuesActions StatusCode Coverage
@ethereumjs/txNPM PackageTx IssuesActions StatusCode Coverage
@ethereumjs/utilNPM PackageUtil IssuesActions StatusCode Coverage
@ethereumjs/vmNPM PackageVM IssuesActions StatusCode Coverage

Branches

The following are our currently active branches:

BranchRelease SeriesStatus Description
masterv6Beta Main working branch, current v6 work merged in (2022-06-08)
v5-maintenancev5ActiveMaintenance for v5 releases

Breaking releases are in sync for all libraries, and release cycles are named after the @ethereumjs/vm version. In most cases PRs should be opened towards the current working branch.

To inspect code related to a specific package version, refer to the tags.

Coverage report

Detailed version can be seen on Codecov.io

Code Coverage

Package dependency relationship


 

To update the diagram above edit the README file and open a new PR with the changes.

Getting Started

See our monorepo documentation to get started on setting up the repository and installing dependencies. The config folder gives an overview on shared configuration and scripts between packages.

EthereumJS

See our organizational documentation for an introduction to EthereumJS as well as information on current standards and best practices. If you want to join for work or carry out improvements on the libraries, please review our contribution guidelines first.

Download Details:

Author: Ethereumjs
Source Code: https://github.com/ethereumjs/ethereumjs-monorepo 
License: MPL-2.0

#typescript #javascript #ethereum #monorepo #evm 

Monorepo for the Ethereum VM TypeScript Implementation
Ben Taylor

Ben Taylor

1664270340

Top EVM (Ethereum Virtual Machine) compatible networks

Ethereum’s vision is clear from the day one. That is to become a “world computer” or an “internet computer”. It’s the worlds first programmable blockchain. So how does it accomplish this? The answer lies in the EVM.

EVM also known as Ethereum Virtual Machine. EVM is a computation machine which works like a decentralized computer. It is a powerful, sandboxed, virtual machine that is embedded within each node. Every full Ethereum node runs on the EVM to maintain consensus across the blockchain.

The role of EVM is to execute and deploy smart contract. It is basically responsible for facilitating smart contract functionality where the contracts are usually written in higher level programming languages like Solidity.

Ethereum Virtual Machine is a runtime environment for every smart contract – A Turing complete virtual machine that executes code exactly as intended. EVM has millions of executable projects. It can deploy number of extra functionalities to the blockchain and it is the core of the Ethereum’s entire operating structure.

In this article you will see Top 20 EVM compatible networks

Name/Coin/TokenDescribePrice overviewWebsite
BNB Smart Chain - BNB

BNB Smart Chain (formerly Binance Smart Chain) is a blockchain developed by Binance, one of the leading cryptocurrency exchanges, using Proof of Staked Authority (PoSA).

BSC supports smart contracts and is EVM-compatible, allowing developers to deploy smart contracts and build DApps on BSC conveniently. Compared with Ethereum, the transaction fees are lower and confirmation time is faster.

BSC adopts Proof of Staked Authority (PoSA), which allows holders of its native token, BNB, to vote for 41 validators. 21 validators of them are responsible for on-chain transaction validation and block production, while the other 20 serve as candidate block producers.

BSC produces 1 block every 3 seconds, and when a validator produces a valid block, he will be rewarded with the miner's fee for all transactions in the block, but unlike Ethereum and Bitcoin, BSC validators do not have block rewards.

Buy BNB 
Link
Polygon - MATIC

Polygon

  • Polygon, formerly known as the Matic Network, is a scaling solution that seeks to give several methods to boost the speed of transactions on blockchain networks while also lowering their cost and complexity.
  • Polygon describes itself as a layer-2 network, which means it is an add-on layer to Ethereum that does not attempt to alter the original blockchain layer.
  • Like its geometric namesake, it has numerous sides, shapes, and applications, and it promises to be a more straightforward framework for creating interconnected networks.

Matic

  • After the rebranding, Polygon retained its MATIC cryptocurrency, the digital coin underpinning the network. 
  • MATIC is the payment and settlement unit for participants who engage within the network and is also utilized to keep tokens safe on the Polygon network.
  • The MATIC cryptocurrency is available on several well-known decentralized and centralized trading platforms, including Binance, 1inch Exchange, and Coinbase Pro.
  • The crypto community is gathering together to make it easier to buy Polygon (MATIC) tokens by making them available in both fiat and crypto.

Features of Matic

  • It provides blockchain performance enhancement technologies like sidechain, which was one of the first things they offered to improve its performance. Transactions are processed faster, and the fee is significantly lower.
  • Its primary goal is to create a foundation for blockchain networks. Instead of being completely disconnected, users would be able to establish blockchain networks that interconnect.
  •  It is Ethereum Virtual Machine (EVM) compatible. Because Polygon is EVM compatible, developers can easily port their apps to it. Aave and SushiSwap are two of the popular Ethereum apps that have already been deployed on Polygon.
  • Other blockchain networks, such as Ethereum 2.0, may pose certain difficulties. Polygon is one of the blockchain network projects under development to avoid these challenges. Polkadot and Avalanche also provide interconnected blockchains. 
  • Fees, governance, and staking are all handled through the Polygon token.
Buy MATIC
Link
Avalanche - AVAX

Avalanche is a layer one blockchain that functions as a platform for decentralized applications and custom blockchain networks. It is one of Ethereum’s rivals, aiming to unseat Ethereum as the most popular blockchain for smart contracts. It aims to do so by having a higher transaction output of up to 6,500 transactions per second while not compromising scalability.

This is made possible by Avalanche’s unique architecture. The Avalanche network consists of three individual blockchains: the X-Chain, C-Chain and P-Chain. Each chain has a distinct purpose, which is radically different from the approach Bitcoin and Ethereum use, namely having all nodes validate all transactions. Avalanche blockchains even use different consensus mechanisms based on their use cases.

Buy AVAX
Link
Cronos - CRO

Powered by Ethermint, Cronos allows rapid porting of apps and smart contracts from Ethereum and EVM-compatible chains.

Cronos (CRO) is the native cryptocurrency token of Cronos Chain — a decentralized, open-source blockchain developed by the Crypto.com payment, trading and financial services company.

Cronos Chain is one of the products in Crypto.com’s lineup of solutions designed to accelerate the global adoption of cryptocurrencies as a means of increasing personal control over money, safeguarding user data and protecting users’ identities. The CRO blockchain serves primarily as a vehicle that powers the Crypto.com Pay mobile payments app.

Buy CRO 
Link
OKB - OKB

OKC has recently launched support for Ethereum Virtual Machine and can now support developers wanting to migrate their Ethereum decentralized applications without having to write entirely new code. For instance, developers can now migrate their Ethereum DApps to OKC, such as trading and lending protocols as well as nonfungible tokens and stablecoins.

In order to facilitate user participation in this new ecosystem of Ethereum DApps on OKC, the team has also introduced EVM-compatible wallet addresses. Now, each OKC user will have two wallet addresses: a native OKC wallet address and an EVM-compatible wallet address. As seen in the image below, EVM addresses start with “0x” and OKC’s native wallet addresses start with “ex.”

Buy OKB
Link
Fantom - FTM

Fantom is an open-source decentralized smart contract platform for DApps and digital assets that was created as an alternative to Ethereum. Fantom has the goal of overcoming the limitations of previous generation blockchains and balancing three components: scalability, security and decentralization. The project offers a set of tools to simplify the process of integrating existing DApps, as well as a detailed staking reward system and built-in DeFi instruments.

Fantom is a Layer-1 blockchain that uses a scratch-built consensus mechanism and independent consensus layer, Lachesis, to facilitate DeFi and related services on the basis of smart contracts. Lachesis provides security for other layers as well, including Opera, Fantom's EVM-compatible smart contract chain. The long-playing mission of the project is to “grant compatibility between all transaction bodies around the world.”
 

Buy FTM
Link
IoTeX - IOTX

The IoTeX blockchain is decentralized, EVM-compatible, and lightning-fast, making it the perfect foundation for decentralized applications and products. Powered by our in-house Roll-DPoS consensus mechanism, the IoTeX blockchain is governed and maintained by 60+ Delegates for true decentralization. As the "root of trust" for the entire IoTeX Network, our blockchain is fully open-source and built-from-scratch to the highest technical standards. It is also one of the fastest blockchains in the industry (5-second blocks w/ instant finality) and has been running error-free since 2019.

The IoTeX blockchain is compatible with the Ethereum Virtual Machine (EVM), which allows developers to build/convert any Solidity-based smart contract on IoTeX.

The IoTeX blockchain utilizes Roll-DPoS consensus, a variant of Delegated Proof of Stake (DPoS) designed in-house to support the high scalability required for IoT use cases. Unlike traditional DPoS that utilizes a fixed number of Delegates (e.g., EOS has 21 block producers), Roll-DPoS randomly selects 24 of the top 36 community-voted Delegates to mine every hour, which greatly improves the decentralization and security of the IoTeX Network without sacrificing performance.

Buy IOTX
Link
Harmony - ONE

Harmony is a powerful blockchain that is EVM compatible with sharding and staking features. Developing on Harmony should feel very familiar for Ethereum developers, as Harmony is fully Ethereum compatible and inherits almost all the tools and libraries from Ethereum, like truffle, remix, web3js, etc.

Harmony is a blockchain platform designed to facilitate the creation and use of decentralized applications (DApps). The network aims to innovate the way decentralized applications work by focusing on random state sharding, which allows creating blocks in seconds.

Buy ONE
Link
Optimism - OPOptimism is a fast, stable, and scalable L2 blockchain built by Ethereum developers, for Ethereum developers. Built as a minimal extension to existing Ethereum software, Optimism’s EVM-equivalent architecture scales your Ethereum apps without surprises. If it works on Ethereum, it works on Optimism at a fraction of the cost.
 
Buy OP
Link
Reef - REEF

Reef is a Reliable Extensible Efficient Fast Layer-1 Blockchain for DeFi, NFT & Gaming. Built using Substrate Framework, it provides high scalability, enabling almost instant low-cost transactions, and supports Solidity and EVM, allowing developers to seamlessly migrate their DApps from Ethereum without any change in the codebase.

Reef Chain is the most advanced EVM-compatible blockchain. It's self-upgradable and has on-chain governance. Its infrastructure also allows for EVM extensions which allows for native token bridge, scheduled calls (ie. recurring payments), and smart contract in-place code upgrades. In the near future, it will support additional VMs which will allow developers to write code in multiple programming languages. The network runs on a Nominated Proof-of-Stake (NPoS) consensus mechanism, which offers scalability and low fees.
 

Buy REEF
Link
Moonbeam - GLMR

Moonbeam is an Ethereum-compatible smart contract parachain on Polkadot. Moonbeam makes it easy to use popular Ethereum developer tools to build or redeploy Solidity projects in a Substrate-based environment.

Moonbeam is much more than just an EVM implementation: it’s a highly specialized parachain that mirrors Ethereum’s Web3 RPC, accounts, keys, subscriptions, logs, and more. The Moonbeam platform extends the base Ethereum feature set with additional features such as on-chain governance, staking, and cross-chain integrations.

Buy GLMR
Link
Velas - VLX

Velas is the world's fastest EVM Blockchain enabling up to 75 000 tx/s, processed instantly, with highest security out there, at almost for free. Velas Ecosystem consists of decentralised products built on top of its chain to present the ease of user experience of decentralised, open-source products.

Velas blockchain is based on high-performance protocol, which implements an innovative time architecture, transaction processing mechanism, and more efficient consensus model compared to other blockchains. Velas is the full hybrid EVM/eBPF chain of Solana and Ethereum, that inherited the best from both: security, scalability, high performance, 1.2 sec finality, extremely low fees and EVM/Solidity support.

Buy VLX
Link
Aurora - AURORA

Aurora is an Ethereum Virtual Machine created by the team at the NEAR Protocol, delivering a turn-key solution for developers to operate their apps on an Ethereum-compatible, high-throughput, scalable and future-safe platform, with low transaction costs for their users.

Aurora is a product that helps Ethereum users and dApps to easily move to the NEAR blockchain. It allows users to do two distinct things: upload and interact with Solidity smart contracts on NEAR blockchain and move assets (including ERC-20 tokens) between Ethereum, NEAR and Aurora via the Rainbow Bridge..

Aurora’s base token is ETH to deliver the best user experience and familiar tooling for developers.

AURORA token is a governance token to ensure proper upgrades to the protocol. Aurora is governed by AuroraDAO which includes representatives from different ecosystems and sectors of the blockchain industry.

Buy AURORA
Link
Moonriver - MOVR

Moonriver is an Ethereum-compatible, smart-contract parachain on Kusama. It is intended to be a companion network to Moonbeam, where it will provide a permanently incentivized canary network. New code will ship to Moonriver first, where it can be tested and verified under real economic conditions. Once proven, the same code will ship to Moonbeam on Polkadot.

It does this by providing a full EVM implementation, a Web3-compatible API, and bridges that connect Moonriver to existing Ethereum networks.

This allows developers to deploy existing Solidity smart contracts and DApp frontends to Moonriver with minimal changes.

Buy MOVR
Link
Telos - TLOS

Telos is a high performance L1 and the home to the fastest EVM

Telos is built for speed and scalability making it the ideal network for mainstream adoption – Telos based Tokens NFT’s and Smart Contracts are already used for DeFi, Gaming, Social Media apps and many more use cases. Telos is home to over 100 distinct applications (dApps) including Taikai, Qudo, Qubicles, Appics, Wordproof, Seeds, Zeptagram, and NewLife. These applications enjoy the networks speed (0.5s block times) and scale (10,000+ TPS) but also the robust on-chain services that Telos provides for voting, sentiment, decentralized file storage, location and much more.

The network is home to the most performant version of the Ethereum Virtual Machine available. Telos is the the only blockchain to support the two leading standards EVM and EOSIO for smart contract development. These two technologies together make up the majority of the top dApps on popular tracking websites such as dapp radar.

Buy TLOS
Link
Boba Network - BOBA

Boba is a next-generation Ethereum Layer 2 Optimistic Rollup scaling solution that reduces gas fees, improves transaction throughput, and extends the capabilities of smart contracts. Boba offers fast exits backed by community-driven liquidity pools, shrinking the Optimistic Rollup exit period from seven days to only a few minutes, while giving LPs incentivized yield farming opportunities.

Boba’s extensible smart contracts will enable developers across the Ethereum ecosystem to build dApps that invoke code executed on web-scale infrastructure such as AWS Lambda, making it possible to use algorithms that are either too expensive or impossible to execute on-chain.

Buy BOBA
Link
TomoChain - TOMO

TomoChain is a scalable public blockchain built on a performance layer that achieves high transaction speeds without compromising decentralization. TomoChain uses an innovative consensus method called PoSV (Proof of Stake Voting) which gives an incentive to all TomoChain token-holders to play an active part in staking across a network of 150 high-quality Masternodes, and to monitor their performance and governance actively.

The TomoChain blockchain and its product ecosystem allow entrepreneurs, enterprises, and institutions to build high-performance, feature-rich blockchain projects on an enhanced EVM-compatible platform. An array of original features and protocols is designed to support users’ speed, privacy, usability, and liquidity needs all in one platform.

Buy TOMO
Link
Evmos - EVMOS

Evmos is an Inter-Blockchain Communication protocol, a.k.a. IBC; the IP layer for blockchains. IBC is currently the safest and most secure and decentralized way to move assets across different blockchains, unlocking interoperability across multiple chains.

Evmos leverages the Cosmos SDK serves as the first IBC-compatible EVM-based chain, bringing composability, interoperability, and fast finality to Ethereum.

Buy EVMOS
Link

Source image: Coinmarketcap


How and Where to Buy token/coin?

You will have to first buy one of the major cryptocurrencies, usually either Bitcoin (BTC), Ethereum (ETH), Tether (USDT), Binance (BNB)…

We will use Binance Exchange here as it is one of the largest crypto exchanges that accept fiat deposits.

Once you finished the KYC process. You will be asked to add a payment method. Here you can either choose to provide a credit/debit card or use a bank transfer, and buy one of the major cryptocurrencies, usually either Bitcoin (BTC), Ethereum (ETH), Tether (USDT), Binance (BNB)…

☞ SIGN UP ON BINANCE

Once finished you will then need to make a BTC/ETH/USDT/BNB deposit to the exchange from Binance depending on the available market pairs. After the deposit is confirmed you may then purchase Coin/Token from the Binance exchange.

Read more: DEX projects on Ethereum Network

Thank you for reading !

#blockchain #bitcoin #cryptocurrency #evm #ethereum 

Top EVM (Ethereum Virtual Machine) compatible networks
Best of Crypto

Best of Crypto

1660958821

BlockScout: Blockchain Explorer for inspecting and analyzing EVM Chain

BlockScout

Blockchain Explorer for inspecting and analyzing EVM Chains.

BlockScout provides a comprehensive, easy-to-use interface for users to view, confirm, and inspect transactions on EVM (Ethereum Virtual Machine) blockchains. This includes the POA Network, xDai Chain, Ethereum Classic and other Ethereum testnets, private networks and sidechains.

See our project documentation for detailed information and setup instructions.

Visit the POA BlockScout forum for FAQs, troubleshooting, and other BlockScout related items. You can also post and answer questions here.

You can also access the dev chatroom on our Gitter Channel.

About BlockScout

BlockScout is an Elixir application that allows users to search transactions, view accounts and balances, and verify smart contracts on the Ethereum network including all forks and sidechains.

Currently available full-featured block explorers (Etherscan, Etherchain, Blockchair) are closed systems which are not independently verifiable. As Ethereum sidechains continue to proliferate in both private and public settings, transparent, open-source tools are needed to analyze and validate transactions.

Supported Projects

BlockScout supports a number of projects. Hosted instances include POA Network, xDai Chain, Ethereum Classic, Sokol & Kovan testnets, and other EVM chains.

Getting Started

See the project documentation for instructions:

Acknowledgements

We would like to thank the EthPrize foundation for their funding support.

Contributing

See CONTRIBUTING.md for contribution and pull request protocol. We expect contributors to follow our code of conduct when submitting code or comments.

Download details:

Author: dogechain-lab
Source code: https://github.com/dogechain-lab/blockscout
License: GPL-3.0 license

#dogchain #blockchain #evm #ethereum

BlockScout: Blockchain Explorer for inspecting and analyzing EVM Chain

The Helper Smart Contract to Use Opcode EVM `CREATE2`

CREATE2 Deployer

Helper smart contract to make easier and safer usage of the CREATE2 Ethereum Virtual Machine (EVM) opcode. CREATE2 can be used to compute in advance the address where a smart contract will be deployed, which allows for interesting new mechanisms known as counterfactual interactions.

Unit Tests

Since Hardhat implements great features for Solidity debugging like Solidity stack traces, console.log, and explicit error messages when transactions fail, we leverage Hardhat for testing:

npm run test

Test Coverage

This project repository implements a test coverage plugin. Simply run:

npm run coverage

The written tests available in the file Create2.test.ts achieve a test coverage of 100%:

----------------------|----------|----------|----------|----------|----------------|
File                  |  % Stmts | % Branch |  % Funcs |  % Lines |Uncovered Lines |
----------------------|----------|----------|----------|----------|----------------|
 contracts\           |      100 |      100 |      100 |      100 |                |
  Create2Deployer.sol |      100 |      100 |      100 |      100 |                |
----------------------|----------|----------|----------|----------|----------------|
All files             |      100 |      100 |      100 |      100 |                |
----------------------|----------|----------|----------|----------|----------------|

Important: A test coverage of 100% does not mean that there are no vulnerabilities. What really counts is the quality and spectrum of the tests themselves. This project is in beta, use at your own risk!

Deployments Create2Deployer.sol

Download details:

Author: pcaversaccio
Source code: https://github.com/pcaversaccio/create2deployer
License: MIT license

#solidity #smartcontract #blockchain #web3 #ethereum #dapp #evm

The Helper Smart Contract to Use Opcode EVM `CREATE2`
Best of Crypto

Best of Crypto

1660165200

EVM Rs: A New EVM Implementation in Rust & Solidity

evm-rs

EVM implementation in Rust. Stack-based.

This contains our Ethereum Virtual Machine. Any valid Solidity bytecode should run on the EVM.

Developer guide

Install the latest version of Rust. We tend to use nightly versions. CLI tool for installing Rust.

We use rust-clippy linters to improve code quality.

There are plenty of IDEs and other Rust development tools to consider.

CLI instructions

# Install Rust (nightly)
$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- --default-toolchain nightly
# Install cargo-make (cross-platform feature-rich reimplementation of Make)
$ cargo install --force cargo-make
# Install rustfmt (Rust formatter)
$ rustup component add rustfmt
# Install clippy (Rust linter)
$ rustup component add clippy
# Clone this repo
$ git clone https://github.com/Fantom-foundation/evm-rs && cd evm-rs
# Run tests
$ cargo test
# Format, build and test
$ cargo make

RFCs

https://github.com/Fantom-foundation/fantom-rfcs

Download details:

Author: Fantom-foundation
Source code: https://github.com/Fantom-foundation/evm-rs
License: MIT license

#fantom #blockchain #evm #rust

EVM Rs: A New EVM Implementation in Rust & Solidity
Elian  Harber

Elian Harber

1659883260

Opera blockchain protocol secured by the Lachesis consensus algorithm

Opera

EVM-compatible chain secured by the Lachesis consensus algorithm.

Building the source

Building opera requires both a Go (version 1.14 or later) and a C compiler. You can install them using your favourite package manager. Once the dependencies are installed, run

make opera

The build output is build/opera executable.

Running opera

Going through all the possible command line flags is out of scope here, but we've enumerated a few common parameter combos to get you up to speed quickly on how you can run your own opera instance.

Launching a network

You will need a genesis file to join a network, which may be found in https://github.com/Fantom-foundation/lachesis_launch

Launching opera readonly (non-validator) node for network specified by the genesis file:

$ opera --genesis file.g

Configuration

As an alternative to passing the numerous flags to the opera binary, you can also pass a configuration file via:

$ opera --config /path/to/your_config.toml

To get an idea how the file should look like you can use the dumpconfig subcommand to export your existing configuration:

$ opera --your-favourite-flags dumpconfig

Validator

New validator private key may be created with opera validator new command.

To launch a validator, you have to use --validator.id and --validator.pubkey flags to enable events emitter.

$ opera --nousb --validator.id YOUR_ID --validator.pubkey 0xYOUR_PUBKEY

opera will prompt you for a password to decrypt your validator private key. Optionally, you can specify password with a file using --validator.password flag.

Participation in discovery

Optionally you can specify your public IP to straighten connectivity of the network. Ensure your TCP/UDP p2p port (5050 by default) isn't blocked by your firewall.

$ opera --nat extip:1.2.3.4

Dev

Running testnet

The network is specified only by its genesis file, so running a testnet node is equivalent to using a testnet genesis file instead of a mainnet genesis file:

$ opera --genesis /path/to/testnet.g # launch node

It may be convenient to use a separate datadir for your testnet node to avoid collisions with other networks:

$ opera --genesis /path/to/testnet.g --datadir /path/to/datadir # launch node
$ opera --datadir /path/to/datadir account new # create new account
$ opera --datadir /path/to/datadir attach # attach to IPC

Testing

Lachesis has extensive unit-testing. Use the Go tool to run tests:

go test ./...

If everything goes well, it should output something along these lines:

ok      github.com/Fantom-foundation/go-opera/app    0.033s
?       github.com/Fantom-foundation/go-opera/cmd/cmdtest    [no test files]
ok      github.com/Fantom-foundation/go-opera/cmd/opera    13.890s
?       github.com/Fantom-foundation/go-opera/cmd/opera/metrics    [no test files]
?       github.com/Fantom-foundation/go-opera/cmd/opera/tracing    [no test files]
?       github.com/Fantom-foundation/go-opera/crypto    [no test files]
?       github.com/Fantom-foundation/go-opera/debug    [no test files]
?       github.com/Fantom-foundation/go-opera/ethapi    [no test files]
?       github.com/Fantom-foundation/go-opera/eventcheck    [no test files]
?       github.com/Fantom-foundation/go-opera/eventcheck/basiccheck    [no test files]
?       github.com/Fantom-foundation/go-opera/eventcheck/gaspowercheck    [no test files]
?       github.com/Fantom-foundation/go-opera/eventcheck/heavycheck    [no test files]
?       github.com/Fantom-foundation/go-opera/eventcheck/parentscheck    [no test files]
ok      github.com/Fantom-foundation/go-opera/evmcore    6.322s
?       github.com/Fantom-foundation/go-opera/gossip    [no test files]
?       github.com/Fantom-foundation/go-opera/gossip/emitter    [no test files]
ok      github.com/Fantom-foundation/go-opera/gossip/filters    1.250s
?       github.com/Fantom-foundation/go-opera/gossip/gasprice    [no test files]
?       github.com/Fantom-foundation/go-opera/gossip/occuredtxs    [no test files]
?       github.com/Fantom-foundation/go-opera/gossip/piecefunc    [no test files]
ok      github.com/Fantom-foundation/go-opera/integration    21.640s

Also it is tested with fuzzing.

Operating a private network (fakenet)

Fakenet is a private network optimized for your private testing. It'll generate a genesis containing N validators with equal stakes. To launch a validator in this network, all you need to do is specify a validator ID you're willing to launch.

Pay attention that validator's private keys are deterministically generated in this network, so you must use it only for private testing.

Maintaining your own private network is more involved as a lot of configurations taken for granted in the official networks need to be manually set up.

To run the fakenet with just one validator (which will work practically as a PoA blockchain), use:

$ opera --fakenet 1/1

To run the fakenet with 5 validators, run the command for each validator:

$ opera --fakenet 1/5 # first node, use 2/5 for second node

If you have to launch a non-validator node in fakenet, use 0 as ID:

$ opera --fakenet 0/5

After that, you have to connect your nodes. Either connect them statically or specify a bootnode:

$ opera --fakenet 1/5 --bootnodes "enode://verylonghex@1.2.3.4:5050"

Running the demo

For the testing purposes, the full demo may be launched using:

cd demo/
./start.sh # start the Opera processes
./stop.sh # stop the demo
./clean.sh # erase the chain data

Check README.md in the demo directory for more information.

Author: Fantom-foundation
Source Code: https://github.com/Fantom-foundation/go-opera 
License: MIT license

#go #golang #evm #blockchain 

Opera blockchain protocol secured by the Lachesis consensus algorithm

Society Kit: Low-code Semantic Fractals for EVM

The Society Kit

Using the magic of decentralized cryptography to create a highe-level DeSoc building blocks out of composible smart contracts and NFTs.

Overview

This platform allows you to

  • Mint characters
  • Create games
  • Set up roles and incentives
  • Manage reputation
  • Design an interaction flow

Technical info

Getting Started

Environment

Clone .env.example to .env and fill in your environment parameters

Commands

  • Install environemnt: npm install
  • Run tests: npx hardhat test
  • Check contract size: npx hardhat size-contracts
  • Deploy protocol (Rinkeby): npx hardhat run scripts/deploy.ts --network rinkeby
  • Deploy foundation (Mumbai): npx hardhat run scripts/foundation.ts --network mumbai
  • Deploy protocol (Mumbai): npx hardhat run scripts/deploy.ts --network mumbai
  • Compile contracts: npx hardhat compile
  • Cleanup: npx hardhat clean

Etherscan verification

Enter your Etherscan API key into the .env file and run the following command (replace DEPLOYED_CONTRACT_ADDRESS with the contract's address and "Hello, Hardhat!" with the parameters you sent the contract upon deployment:

npx hardhat verify --network ropsten DEPLOYED_CONTRACT_ADDRESS "Hello, Hardhat!"

Download details:

Author: toledoroy
Source code: https://github.com/toledoroy/Society-Kit
License: MIT license

#solidity #smartcontract #ethereum #blockchain #evm

Society Kit: Low-code Semantic Fractals for EVM

Core Smart Contracts Of Unipeer Built on Solidity & Rust

Foundry Rust Monorepo Template

Template for quickly getting started with developing Rust applications that leverage Foundry for EVM smart contract development.

Continuous Integration is already set up to test both your Rust and Solidity code, as well as ensure formatting and that your Rust bindings match the Solidity build artifacts.

Directory Structure

The project is structured as a mixed Rust workspace with a Foundry project under contracts/ and typesafe auto-generated bindings to the contracts under bindings/.

├── Cargo.toml
├── app // <-- Your Rust application logic
├── contracts // <- The smart contracts + tests using Foundry
├── bindings // <-- Generated bindings to the smart contracts' abis (like Typechain)

Testing

Given the repository contains both Solidity and Rust code, there's 2 different workflows.

Solidity

If you are in the root directory of the project, run:

forge test --root ./contracts

If you are in in contracts/:

forge test

Rust

cargo test

Generating Rust bindings to the contracts

Rust bindings to the contracts can be generated via forge bind, which requires first building your contracts:

forge build --root ./contracts
forge bind --bindings-path ./bindings --root ./contracts --crate-name bindings

Any follow-on calls to forge bind will check that the generated bindings match the ones under the build files. If you want to re-generate your bindings, pass the --overwrite flag to your forge bind command.

Installing Foundry

First run the command below to get foundryup, the Foundry toolchain installer:

curl -L https://foundry.paradigm.xyz | bash

Then, in a new terminal session or after reloading your PATH, run it to get the latest forge and cast binaries:

foundryup

For more, see the official docs.

Download details:

Author: unipeer
Source code: https://github.com/unipeer/unipeer

#solidity #smartcontract #ethereum #blockchain #rust #evm

Core Smart Contracts Of Unipeer Built on Solidity & Rust

Huff RS: A Low-level Assembly Language for EVM Built in Rust

huff-rs • 

huff-rs is a Huff compiler built in rust.

What is a Huff?

Huff is a low-level programming language designed for developing highly optimized smart contracts that run on the Ethereum Virtual Machine (EVM). Huff does not hide the inner workings of the EVM. Instead, Huff exposes its programming stack to the developer for manual manipulation.

Rather than having functions, Huff has macros - individual blocks of bytecode that can be rigorously tested and evaluated using the Huff runtime testing suite.

Huff was originally developed by the Aztec Protocol team to write Weierstrudel. Weierstrudel is an on-chain elliptical curve arithmetic library that requires incredibly optimized code that neither Solidity nor Yul could provide.

While EVM experts can use Huff to write highly-efficient smart contracts for use in production, it can also serve as a way for beginners to learn more about the EVM.

To dive deeper into Huff, visit the Official Huff Docs(also available on github).

Installation

Something not working? Send a message in discord.

First run the command below to get huffup, the Huff installer:

curl -L get.huff.sh | bash

To avoid redirecting the script directly into bash, download and run the huffup installation script.

To install the Huff compiler, simply run huffup.

If you have the old huffc (TypeScript version) npm package installed globally, you can remove it with:

sudo yarn global remove huffc

To make sure you are running the rust version, you can run huffc --version and it should respond with huff_cli <version>. If it responds with 2.0.0 that means you are running the Typescript version.

$ huffc --version
huff_cli 0.1.0

Alternatively

Install from source by running:

git clone https://raw.githubusercontent.com/huff-language/huff-rs
cd huff-rs
cargo install --path ./huff_cli --bins --locked --force

OR

cargo install --git https://raw.githubusercontent.com/huff-language/huff-rs --locked huff_cli

How Fast?

Compilation Benchmarks

CompilerCold (No Cache)Light CacheDeep CacheFull Cache
[huff-language/huff-rs][huff-rs]XXXmsXXXmsXXXmsXXXms
[huff-language/huffc][huffc]XXXmsXXXmsXXXmsXXXms

Note: Compilation benchmarks were performed on huff-examples erc20.

Architecture

Huff Compiler Architecture

Modules

  • huff_core: The core module to huff-rs. Resolves source file paths, executes compilation, and exports artifacts.
  • huff_cli: The command line interface for the Huff compiler.
  • huff_lexer: Takes in the source of a .huff file and generates a vector of Tokens.
  • huff_parser: Crafts a Contract AST from the the vector of Tokens generated by huff_lexer.
  • huff_codegen: EVM Bytecode generation module that accepts an AST generated by huff_parser.
  • huff_utils: Various utilities and types used by all modules.
  • huffup: Update or revert to a specific huff-rs branch with ease. (Forked from foundry)

Contributing

All contributions are welcome! We want to make contributing to this project as easy and transparent as possible, whether it's:

  • Reporting a bug
  • Discussing the current state of the code
  • Submitting a fix
  • Proposing new features
  • Becoming a maintainer

We use GitHub issues to track public bugs. Report a bug by opening a new issue; it's that easy!

To run examples, make sure you update git submodules to pull down the huff-examples submodule by running git submodule update.

The branching convention used by huff-rs is a stage branch that is meant to be merged off of and is periodically merged into main. So, when creating a feature, branch off of the stage branch and create a pr from your branch into the stage branch!

i.e: Branching Conventions

To pass github actions, please run:

cargo check --all
cargo test --all --all-features
cargo +nightly fmt -- --check
cargo +nightly clippy --all --all-features -- -D warnings

In order to fix any formatting issues, run:

cargo +nightly fmt --all

Recommended PR Template

Here is an example PR template - not strictly required, but will greatly improve the speed at which your PR is reviewed & merged!

## Overview

<Provide a general overview of what your pr accomplishes, why, and how (including links)>

## Checklist

- [x] <Ex: Added a `new` method to the Huff Lexer [here](./huff_lexer/src/lib.rs#50)>
- [x] <Ex: Fully tested the `new` method [here](./huff_lexer/tests/new.rs)>
- [ ] <Ex: Wrote documentation for the `new` method [here](./huff_lexer/README.md#20)>

When the PR checklist isn't complete, it is highly recommended to make it a draft PR. NOTE: if your PR is not complete, it will likely be changed to a draft by one of the repository admins.

For breaking changes: make sure to edit the excalidraw asset and export the file to ./assets/huffc.excalidraw along with an image to ./assets/huffc.png.

Safety

Warning

This is experimental software and is provided on an "as is" and "as available" basis. Expect rapid iteration and use at your own risk.

This code is not designed for safety.

  • There are untested invariants in the code that may break.
  • You can easily shoot yourself in the foot if you're not careful.
  • You should thoroughly read the documentation and examples.

We do not give any warranties and will not be liable for any loss incurred through any use of this codebase.

Acknowledgements

The original Huff Language compiler: huffc.

An exemplary, minimal rust compiler: ripc.

Foundry, for the many scripts, documentation, devops, and code on which huff-rs is based on.

All huff-rs contributors, users, advocates, and enthusiasts!

Download details:

Author: huff-language
Source code: https://github.com/huff-language/huff-rs
License: Apache-2.0 license

#solidity #smartcontract #ethereum #blockchain #rust #evm

Huff RS: A Low-level Assembly Language for EVM Built in Rust
Best of Crypto

Best of Crypto

1659496200

How to Retrieve Asset Price From any EVM Chain using Golang

Getting an asset price from EVM chain

About The Project

The project shows how to retrieve asset price from any EVM chain. The price data feed contract addresses can be found here.

📘 Note on Go bindings aggregator_v3_interface.go

Follow these steps to learn how to generate this file:

  1. Generate the Contract ABI from a solidity source file using solc. In this case, we are going to download the AggregatorV3Interface and generate an ABI called AggregatorV3Interface.abi:
wget https://raw.githubusercontent.com/smartcontractkit/chainlink/develop/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol
solc --abi AggregatorV3Interface.sol -o .

2.  From AggregatorV3Interface.abi, generate the Go bindings aggregator_v3_interface.go required to programmatically interact with a smart contract > using generated, typesafe Gocode. Ensure that Geth is installed so you can use > > > abigen.

abigen --abi=AggregatorV3Interface.abi --pkg=aggregator_v3_interface --out=aggregator_v3_interface.go

Prerequisites

Installation

  1. Get a RPC API Key from a node provider such as Alchemy, Infura, Moralis, or QuickNode. This example uses the Rinkeby testnet.
  2. Clone the repo
git clone https://github.com/smartcontractkit/smart-contract-examples.git

3.   Enter the direcory

cd pricefeed-golang

4.   Copy the example environment file .env.example to create .env file

cp .env.example .env

5.   In .env file , replace REPLACE_BY_YOUR_RPC_URL by the RPC_URL of the EVM chain you want to connect to.

6.   In .env file , replace REPLACE_BY_PRICE_FEED_PROXY_ADDR by the price feed address. For instance, 0x8A753747A1Fa494EC906cE90E9f37563A8AF630e if you want the ETH/USD price feed on the Rinkeby testnet.

Usage

After the installation step, run the example

go run main.go

2022/05/18 18:48:26 ETH / USD Price feed address is 0x8A753747A1Fa494EC906cE90E9f37563A8AF630e
2022/05/18 18:48:26 Round id is 36893488147419115714
2022/05/18 18:48:26 Answer is 195086228530
2022/05/18 18:48:26 Formatted answer is 1950.8622853
2022/05/18 18:48:26 Started at 2022-05-18 18:10:36 +0200 CEST
2022/05/18 18:48:26 Updated at 2022-05-18 18:10:36 +0200 CEST
2022/05/18 18:48:26 Answered in round 36893488147419115714

Note that you can also override the price feed address on the command line. For instance:

go run main.go 0x78F9e60608bF48a1155b4B2A5e31F32318a1d85F

2022/05/18 18:48:46 EUR / USD Price feed address is 0x78F9e60608bF48a1155b4B2A5e31F32318a1d85F
2022/05/18 18:48:46 Round id is 73786976294838233703
2022/05/18 18:48:46 Answer is 104976000
2022/05/18 18:48:46 Formatted answer is 1.04976
2022/05/18 18:48:46 Started at 2022-05-18 18:45:36 +0200 CEST
2022/05/18 18:48:46 Updated at 2022-05-18 18:45:36 +0200 CEST
2022/05/18 18:48:46 Answered in round 73786976294838233703

Link: https://github.com/smartcontractkit/smart-contract-examples/tree/main/pricefeed-golang

#smartcontract #blockchain #oracle #chainlink #go #golang #evm

How to Retrieve Asset Price From any EVM Chain using Golang

Mana Ethereum: An EVM Implementation in Elixir

Mana-Ethereum

Mana-Ethereum is an open-source Ethereum blockchain client built using Elixir. Elixir runs on the Erlang Virtual Machine, which is used for distributed systems and offers massive scalability and high visibility. These properties make Elixir a perfect candidate for blockchain network development.

In the current Ethereum ecosystem, a majority of active nodes on the network are Geth or Parity nodes. Mana-Ethereum provides an additional open-source alternative. Our aim is to create an open, well-documented implementation that closely matches the protocols described in the Ethereum yellow paper.

Mana-Ethereum is currently in development. See the Project Status and Project FAQs for more information.

Dependencies

  • Elixir ~> 1.8.0

Installation

git clone --recurse-submodules https://github.com/mana-ethereum/mana.git
  • Go to the mana subdirectory cd mana
  • Run bin/setup

Running a node

Peer-to-peer communication is currently in development. A command-line interface is available for chain syncing.

Sync From RPC Client

To sync a chain from an RPC Client (e.g. Infura) or a local client, run the following command:

mix sync --chain ropsten

You can sign up for an Infura API key here. This will ensure your requests are not throttled.

mix sync --chain ropsten --provider-url https://ropsten.infura.io/v3/<api_key>

Alternatively, you can sync via IPC to a local node (like Parity or Geth running locally):

mix sync --chain ropsten --provider-url ipc://~/Library/Application\ Support/io.parity.ethereum/jsonrpc.ipc

Once syncing begins you will see a timestamp and a running list of verified blocks.

Releases

To build a release, run: mix release, which will build a release in _build/dev/rel/mana/bin/mana.

Then you can run:

_build/dev/rel/mana/bin/mana run --no-discovery --bootnodes enode://...

which will start a DevP2P sync with a local peer.

Known Sync Issues

Updated Dec-5-2018

  • We've restarted mainnet syncing and are at block ~ 2,470,630. We are currently investigating performance and storage issues #622, #623, and #624.
  • Ropsten sync is in progress as we've reached the Constantinople fork. Current block is ~ 4,253,000 - Oct-18-2018

Helpful debugging tools

When debugging block verification failures, we have found etherscan tools extrememly helpful. Take block 177610 for example:

We can look at the block information, and dive into the transaction information. From that page, the "Tools & Utilities" dropdown provides useful debugging tools. Two of the most valuable are Geth DebugTrace and Remix Debugger.

Geth DebugTrace allows us to compare each operation and its gas consumption against our implementation.

Remix Debugger allows us to compare the stack against our implementation's stack for each cycle of the virtual machine.

NOTE: for the Remix Debugger, you may want to add the block number at the top before pressing the play button.

To log the operation, gas consumption, and stack in our application, please see the EVM README example setup.

Testing

Run:

mix test --exclude network

Tests tagged with network integrate with other nodes and cannot run unless another node is running in parallel. Use the --exclude network flag to exclude these tests.

If you want to only run Ethereum common tests, we currently have:

# Ethereum Virtual Machine tests
cd apps/evm && mix test test/evm_test.exs

# Ethereum Blockchain tests
cd apps/blockchain && mix test test/blockchain_test.exs

# Ethereum General State tests
cd apps/blockchain && mix test test/blockchain/state_test.exs

# Ethereum Transaction tests
cd apps/blockchain && mix test test/blockchain/transaction_test.exs

Test Status

Ethereum common tests are created for all clients to test against. See the common test documentation for more information.

VMTests = 100% passing

Hardfork[BlockchainTests] passing[GeneralStateTests] passingComplete?
Frontier100% (1328/1328)100% (1041/1041)
Homestead100% (2211/2211)100% (2069/2069)
HomesteadToDaoAt5100% (4/4)N/A
TangerineWhistle100% (1270/1270)100% (1120/1120)
SpuriousDragon100% (1201/1201)100% (1193/1193)
Byzantium100% (4954/4954)100% (4813/4813)
Constantinople100% (10627/10627)100% (10588/10588)

View the community Constantinople Project Tracker.

Updating Common Tests

The Ethereum common tests are in a submodule. To update:

% cd ethereum_common_tests
% git checkout develop
% git pull

Project Status

FunctionalityStatus
Encoding and HashingThe [RLP] encoding protocol and the [Merkle Patricia Tree] data structure are fully implemented.
[Ethereum Virtual Machine]Our EVM currently passes 100% of the common [VM tests]. We are refining our implementation to address subtle differences between our EVM and other implementations.
Peer to Peer NetworkingCurrently we can connect to one of the Ethereum bootnodes, get a list of peers, and add them to a list of known peers. We have fully implemented the modified [kademlia DHT]. 

We can also successfully perform the encrypted handshake with peer nodes and derive secrets to frame the rest of the messages. We are currently configuring ExWire to work against a local Geth/Parity node.
DEVp2p Protocol and Ethereum Wire ProtocolWe are in the process of addressing networking layer issues. Progress is being tracked in Issue [#407].

Documentation

To view module and reference documentation:

Generate documentation. mix docs

View the generated docs. open doc/index.html

Download details:
Author: mana-ethereum
Source code: https://github.com/mana-ethereum/mana
License: Apache-2.0, MIT licenses found

#solidity #smartcontract #blockchain #ethereum #evm

Mana Ethereum: An EVM Implementation in Elixir

Solevm: An EVM Runtime Implementation in Solidity

Solidity EVM and Runtime (PoC)

This is a simple Ethereum runtime written in Solidity. The runtime contract allows you to execute evm bytecode with calldata and various other parameters. It is meant to be used for one-off execution, like is done with the "evm" executables that comes with the ethereum clients.

This is still very early in development. There is no support for gas metering, and the limit to contract code-size could make it impossible to add. See the roadmap section for the plans ahead.

NOTE: This is only an experiment in it's early PoC stages. Do not rely on this library to test or verify EVM bytecode.

Update 2018-06-05: There is no way to add all gas metering without exceeding the maximum codesize

Building and Testing

The runtime is a regular Solidity contract that can be compiled by solc, and can therefore be used with libraries such as web3js or just executed by the various different stand-alone evm implementations. The limitations is that a lot of gas is required in order to run the code, and that web3js does not have support for Solidity structs (ABI tuples).

In order to build and test the code you need go-ethereum's evm as well as solc on your path. The code is tested using the solidity 0.4.24 release version and the evm 1.8.7 version - both with constantinople settings.

bin/compile.js can be executed to create bin, bin-runtime, abi and signatures files for the runtime contract. The files are put in the bin_output folder.

npm run test can be run to test the runtime contract. It will automatically compile all the involved contracts.

bin/test.js can be used to test some of the supporting contracts and libraries.

bin/perf.js can be used to compute gas cost estimates for the runtime and supporting libraries.

Runtime

First of all, the EthereumRuntime code is designed to run on a constantinople net, with all constantinople features. The genesis.json file in the root folder can be used to configure the geth EVM (through the --prestate option).

The executable contract is EthereumRuntime.sol. The contract has an execute method which is used to run code. It has many overloaded versions, but the simplest version takes two arguments - code and data.

code is the bytecode to run.

data is the calldata.

The solidity type for both of them is bytes memory.

// Execute the given code and call-data.
    function execute(bytes memory code, bytes memory data) public pure returns (Result memory state);

    // Execute the given transaction.
    function execute(TxInput memory input) public pure returns (Result memory result);

    // Execute the given transaction in the given context.
    function execute(TxInput memory input, Context memory context) public pure returns (Result memory result);

The other alternatives have two objects, TxInput and Context:

    struct TxInput {
        uint64 gas;
        uint gasPrice;
        address caller;
        uint callerBalance;
        uint value;
        address target;
        uint targetBalance;
        bytes targetCode;
        bytes data;
        bool staticExec;
    }

The gas and gasPrice fields are reserved but never used, since gas is not yet supported. All the other params are obvious except for staticExec which should be set to true if the call should be executed as a STATICCALL, i.e. what used to be called a read-only call (as opposed to a transaction).

struct Context {
    address origin;
    uint gasPrice;
    uint gasLimit;
    uint coinBase;
    uint blockNumber;
    uint time;
    uint difficulty;
}

These fields all speak for themselves.

NOTE: There is no actual CREATE operation taking place for the contract account in which the code is run, i.e. the code to execute would normally be runtime code; however, the code being run can create new contracts.

The return value from the execute functions is a struct on the form:

struct Result {
    uint errno;
    uint errpc;
    bytes returnData;
    uint[] stack;
    bytes mem;
    uint[] accounts;
    bytes accountsCode;
    uint[] logs;
    bytes logsData;
}

errno - an error code. If execution was normal, this is set to 0.

errpc - the program counter at the time when execution stopped.

returnData - the return data. It will be empty if no data was returned.

stack - The stack when execution stopped.

mem - The memory when execution stopped.

accounts - Account data packed into an uint-array, omitting the account code.

accountsCode - The combined code for all accounts.

logs - Logs packed into an uint-array, omitting the log data.

logsData - The combined data for all logs.

Note that errpc is only meant to be used when the error is non-zero, in which case it will be the program counter at the time when the error was thrown.

There is a javascript (typescript) adapter at script/adapter.ts which allow you to run the execute function from within this library, and automatically format input and output parameters. The return data is formatted as such:

{
    errno: number,
    errpc: number,
    returnData: string (hex),
    stack: [BigNumber],
    mem: string (hex),
    accounts: [{
        address: string (hex),
        balance: BigNumber,
        nonce: BigNumber,
        destroyed: boolean
        storage: [{
            address: BigNumber,
            value: BigNumber
        }]
    }]
    logs: [{
        account: string (hex)
        topics: [BigNumber] (size 4)
        data: string (hex)
    }]
}

There is a pretty-print function in the adapter as well.

Accounts

Accounts are on the following format:

account : {
    addr: address,
    balance: uint,
    nonce: uint8,
    destroyed: bool
    code: bytes
    storage: [{
        addr: uint,
        val: uint
    }]
}

nonce is restricted to uint8 (max 255) to make new account creation easier, since it will get a simpler RLP encoding.

The destroyed flag is used to indicate whether or not a (contract) account has been destroyed during execution. This can only happen if SELFDESTRUCT is called in that contract.

When executing code, two accounts will always be created - the caller account, and the contract account used to run the provided code. In the simple "code + data" call, the caller and contract account are assigned default addresses.

In contract code, accounts and account storage are both arrays instead of maps. Technically they are implemented as (singly) linked lists. This will be improved later.

The "raw" int arrays in the return object has an account packed in the following way:

0: account address

1: account balance

2: account nonce

3: account destroyed (true or false)

4: code starting index (in combined 'accountsCode' array).

5: code size

6: number of entries in storage

7+ : pairs of (address, value) storage entries

The size of an account is thus: 7 + storageEntries*2.

The accounts array is a series of accounts: [account0, account1, ... ]

Logs

Logs are on the following format:

log: {
     account: address
     topics: uint[4]
     data: bytes
 }

account - The address of the account that generated the log entry.

topics - The topics.

data - The data.

The "raw" int arrays in the return object has a log packed in the following way:

0: account address

1 - 4: topics

5: data starting index (in combined 'logsData' array).

6: data size.

Blockchain

There are no blocks, so BLOCKHASH will always return 0. The only blockchain related parameters that can be set are those in the context object.

Javascript

In addition to the contracts, the library also comes with some rudimentary javascript (typescript) for compiling the contract, and for executing unit tests through the geth evm. In order for this to work, both solc and the geth evm must be on the path.

The script/adapter.ts file can be used to call the runtime contract with code and data provided as hex-strings. Currently, only the code + data version and the TxInput overload is supported, but the one using both TxInput and Context will soon be supported as well.

The supporting script will be improved over time.

Current status

The initial version only lets you run code. There is no gas metering system in place.

Calls are currently being tested, and is not yet verified to work well in all cases. CALLCODE has not yet been added (and may not be).

Of the precompiled contracts, only ecrecover, sha256, ripemd160 and identity has been implemented. Neither of them are properly tested.

CREATE2 has not been added.

Roadmap

The plan for 0.2.0, is to support all instructions, and to have a full test suite done.

The plan for 0.3.0 is that the runtime should be properly checked against the yellow paper specification - or at least the parts of the protocol that is supported (gas may never be).

The plan for 0.4.0 is to extend the capacities of the runtime and add some performance optimization. Gas may or may not be added here.

The long-term plan is to add gas metering, and also add a way to add block data, chain settings, and other things. Whether any of that will be possible depends on many things, including the limitations of the EVM and Solidity (such as the maximum allowed code-size for contracts, and Solidity's stack limitations).

Download details:
Author: 
Source code: 
License:

#solidity #smartcontract #blockchain #ethereum #evm

Solevm: An EVM Runtime Implementation in Solidity

Rattle: An EVM Binary Static Analysis Framework to Work Smartcontracts

rattle

Rattle is an EVM binary static analysis framework designed to work on deployed smart contracts. Rattle takes EVM byte strings, uses a flow-sensitive analysis to recover the original control flow graph, lifts the control flow graph into an SSA/infinite register form, and optimizes the SSA – removing DUPs, SWAPs, PUSHs, and POPs. The conversion from a stack machine to SSA form removes 60%+ of all EVM instructions and presents a much friendlier interface to those who wish to read the smart contracts they’re interacting with.

Example

$ python3 rattle-cli.py --input inputs/kingofether/KingOfTheEtherThrone.bin -O

Would produce a register machine output like this:

King of Ether numberOfMonarchs

Functions are recovered and split off. Additionally function arguments, memory locations, and storage locations are recovered.

Usage

Rattle runs on the runtime contract hex string.

If you're running rattle on a contract you can compile with solidity, use the --bin-runtime option and strip off the header:

$ solc --bin-runtime KingOfTheEtherThrone.sol 2>/dev/null | tail -n1 > contract.bin

Dependencies

  • python3
  • graphviz
  • cbor2
  • pyevmasm

To install the python dependencies, run these commands:

$ python3 -m venv venv
$ source venv/bin/activate
$ pip install -r requirements.txt

Troubleshooting

If you get a syntax error like this:

  File "rattle-cli.py", line 16
    def main() -> None:
               ^
SyntaxError: invalid syntax

You likely ran rattle with python2 instead of python3.

Presentation

For more details on the Rattle design and features, see my reCON Montreal presentation, which is annotated here.

Download details:
Author: crytic
Source code: https://github.com/crytic/rattle
License:

#solidity #smartcontract #blockchain #ethereum #python #evm

Rattle: An EVM Binary Static Analysis Framework to Work Smartcontracts

Pyevmasm: Ethereum Virtual Machine (EVM) Disassembler and Assembler

pyevmasm

pyevmasm is an assembler and disassembler library for the Ethereum Virtual Machine (EVM). It includes a commandline utility and a Python API.

CLI Examples with evmasm

evmasm is a commandline utility that uses pyevmasm to assemble or disassemble EVM:

usage: evmasm [-h] (-a | -d | -t) [-bi] [-bo] [-i [INPUT]] [-o [OUTPUT]] [-f FORK]

pyevmasm the EVM assembler and disassembler

optional arguments:
  -h, --help            show this help message and exit
  -a, --assemble        Assemble EVM instructions to opcodes
  -d, --disassemble     Disassemble EVM to opcodes
  -t, --print-opcode-table
                        List supported EVM opcodes
  -bi, --binary-input   Binary input mode (-d only)
  -bo, --binary-output  Binary output mode (-a only)
  -i [INPUT], --input [INPUT]
                        Input file, default=stdin
  -o [OUTPUT], --output [OUTPUT]
                        Output file, default=stdout
  -f FORK, --fork FORK  Fork, default: byzantium. Possible: frontier,
                        homestead, tangerine_whistle, spurious_dragon,
                        byzantium, constantinople, serenity. Also an unsigned
                        block number is accepted to select the fork.

Disassembling the preamble of compiled contract:

$ echo -n "608060405260043610603f57600035" | evmasm -d
00000000: PUSH1 0x80
00000002: PUSH1 0x40
00000004: MSTORE
00000005: PUSH1 0x4
00000007: CALLDATASIZE
00000008: LT
00000009: PUSH1 0x3f
0000000b: JUMPI
0000000c: PUSH1 0x0
0000000e: CALLDATALOAD

Python API Examples

>>> from pyevmasm import instruction_tables, disassemble_hex, disassemble_all, assemble_hex
>>> instruction_table = instruction_tables['byzantium']
>>> instruction_table[20]
Instruction(0x14, 'EQ', 0, 2, 1, 3, 'Equality comparision.', None, 0)
>>> instruction_table['EQ']
Instruction(0x14, 'EQ', 0, 2, 1, 3, 'Equality comparision.', None, 0)
>>> instrs = list(disassemble_all(binascii.unhexlify('608060405260043610603f57600035')))
>>> instrs.insert(1, instruction_table['JUMPI'])
>>> a = assemble_hex(instrs)
>>> a
'0x60805760405260043610603f57600035'
>>> print(disassemble_hex(a))
PUSH1 0x80
JUMPI
PUSH1 0x40
MSTORE
...
>>> assemble_hex('PUSH1 0x40\nMSTORE\n')
'0x604052'

Installation

Python >=2.7 or Python >=3.3 is required.

Install the latest stable version using pip:

pip install pyevmasm

Or, install the library from source:

git clone https://github.com/trailofbits/pyevmasm
cd pyevmasm
python setup.py install --user

Documentation

https://pyevmasm.readthedocs.io

New issues, feature requests, and contributions are welcome. Join us in #ethereum channel on the Empire Hacking Slack to discuss Ethereum security tool development.

Download details:
Author: crytic
Source code: https://github.com/crytic/pyevmasm
License: Apache-2.0 license

#solidity #smartcontract #blockchain #ethereum #evm #python

Pyevmasm: Ethereum Virtual Machine (EVM) Disassembler and Assembler

EVM Lab: Utilities for interacting with The Ethereum Virtual Machine

EVM lab utilities

This package contains various tools to interact with the Ethereum virtual machine.

Please refer to the Wiki for more information and howto's.

screenshot

Installation

From source:

Consider creating a virtualenv.

#> virtualenv -p python3 .env3
#> . .env3/bin/activate
#> python3 -m pip install -r requirements.txt
#> python3 setup.py install
#> python3 -m evmlab  # verify installation

From PIP:

#> python3 -m pip install evmlab[consolegui,abidecoder,docker]
#> python3 -m evmlab  # verify installation

EVMLab comes with a commandline utility that can be invoked by calling python3 -m evmlab <subcommand> <args>

Running it

The easiest way to get it working is to use a docker image.

docker build . -t evmlab && docker run -it evmlab

The docker image should also be available at hub.docker.com, as an automated build:

docker pull holiman/evmlab && docker run -it holiman/evmlab

Download details:
Author: ethereum
Source code: https://github.com/ethereum/evmlab
License: GPL-3.0 license

#solidity #smartcontract #blockchain #ethereum #evm #python

EVM Lab: Utilities for interacting with The Ethereum Virtual Machine