Skip to content

Commit

Permalink
First code dump
Browse files Browse the repository at this point in the history
  • Loading branch information
Bernhard Scholz committed Aug 8, 2022
0 parents commit 874c55f
Show file tree
Hide file tree
Showing 46 changed files with 7,108 additions and 0 deletions.
45 changes: 45 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
## UNRELEASED

SECURITY:

FEATURES:

IMPROVEMENTS:

BUG FIXES:

## v0.4.0 (October 14, 2018)

SECURITY:

* keygen: write keys to files instead of tty.

FEATURES:

* proxy: Introduced in-memory proxy.
* cmd: Enable reading config from file (lachesis.toml, .json, or .yaml)

IMPROVEMENTS:

* node: major refactoring of configuration and initialization of Lachesis node.
* node: Node ID is calculated from public key rather than from sorting the
peers.json file.

## v0.3.0 (September 4, 2018)

FEATURES:

* poset: Replaced Leemon Baird's original "Fair" ordering method with
Lamport timestamps.
* poset: Introduced the concept of Frames and Roots to enable initializing a
poset from a "non-zero" state.
* node: Added FastSync protocol to enable nodes to catch up with other nodes
without downloading the entire poset.
* proxy: Introduce Snapshot/Restore functionality.

IMPROVEMENTS:

* poset: Refactored the consensus methods around the concept of Frames.
* poset: Removed special case for "initial" Events, and make use of Roots
instead.
* docs: Added sections on Lachesis and FastSync.
46 changes: 46 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [email protected]. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]

[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
674 changes: 674 additions & 0 deletions COPYING

Large diffs are not rendered by default.

18 changes: 18 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
.PHONY: all
all: substate-cli

GOPROXY ?= "https://proxy.golang.org,direct"
.PHONY: substate-clie

substate-cli:
GIT_COMMIT=`git rev-list -1 HEAD 2>/dev/null || echo ""` && \
GIT_DATE=`git log -1 --date=short --pretty=format:%ct 2>/dev/null || echo ""` && \
GOPROXY=$(GOPROXY) \
go build \
-ldflags "-s -w -X github.com/Fantom-foundation/go-opera/cmd/substate-cli/replay.gitCommit=$${GIT_COMMIT} -X github.com/Fantom-foundation/go-opera/cmd/substate-cli/replay.gitDate=$${GIT_DATE}" \
-o build/substate-cli \
./cmd/substate-cli

.PHONY: clean
clean:
rm -fr ./build/*
17 changes: 17 additions & 0 deletions PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
Please check if what you want to add to `go-opera` list meets [quality standards](https://github.com/Fantom-foundation/go-opera/blob/master/CONTRIBUTING.md#quality-standard) before sending pull request.

**Please provide package links to:**

- github.com repo:
- godoc.org:
- goreportcard.com:
- coverage service link ([cover.run](https://cover.run/), [gocover](http://gocover.io/), [coveralls](https://coveralls.io/) etc.), example: `[![cover.run](https://cover.run/go/github.com/user/repository.svg?style=flat&tag=golang-1.10)](https://cover.run/go?tag=golang-1.10&repo=github.com%2Fuser%2Frepository)`

**Make sure that you've checked the boxes below before you submit PR:**
- [ ] I have added my package in alphabetical order.
- [ ] I have an appropriate description with correct grammar.
- [ ] I know that this package was not listed before.
- [ ] I have added godoc link to the repo and to my pull request.
- [ ] I have added coverage service link to the repo and to my pull request.
- [ ] I have added goreportcard link to the repo and to my pull request.
- [ ] I have read [Contribution guidelines](https://github.com/Fantom-foundation/go-opera/blob/master/CONTRIBUTING.md#contribution-guidelines), [maintainers note](https://github.com/Fantom-foundation/go-opera/blob/master/CONTRIBUTING.md#maintainers) and [Quality standard](https://github.com/Fantom-foundation/go-opera/blob/master/CONTRIBUTING.md#quality-standard).
85 changes: 85 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# Substate-cli
In addition to functionality testing, the recorder/replayer is useful to obtain execution metrics for smart contracts such as EVM call runtime or opcode/instruction statistics. ```substate-cli``` is a command-line interface for the replayer and applications to obtain mentioned metrics.

```
NAME:
substate-cli - Fantom substate command line interface
USAGE:
substate-cli [global options] command [command options] [arguments...]
VERSION:
1.10.8-stable
COMMANDS:
replay executes full state transitions and checks output consistency
storage-size returns changes in storage size by transactions in the specified block range
code-size reports code size and nonce of smart contracts in the specified block range
dump returns content in substates in json format
db A set of commands on substate DB
help, h Shows a list of commands or help for one command
GLOBAL OPTIONS:
--help, -h show help
--version, -v print the version
```

### Substate Replayer
To execute substrate in a given block range,
```shell
substate-cli replay 0 41000000
```


### EVM Call Runtime
To measure EVM call runtime of transactions in a given block range,
```shell
substate-cli replay --profiling-call 0 41000000
```

Output format
```
call: <Block>, <Nonce>, <Account>, <runtime in ns>
```

### EVM Micro Profiling
To get micro-profiling statistics,
```shell
substate-cli replay --profiling-opcode 0 41000000
```
The returned statistics include

- **opcode frequency:** the total number of times an opcode is used.
- **opcode runtime:** the total runtime of an opcode in nanoseconds.
- **instruction frequency:** a distribution showing number of times an instruction is executed.
- **step length frequency:** a distribution showing number of steps per smart contract invocation.

Output format
```
opcode-freq: <opcode>, <execution count>
opcode-runtime: <opcode>, <total runtime in ns>
instruction-freq: <execution frequency>, <instruction count>
steplen-freq: <execution steps>, <number of contracts>
```

### Blockchain Storage
To profile storage update size after each transaction in a given block range,
```shell
substate-cli storage-size 0 41000000
```

Output format
```
metric: <Block>, <Transaction>, <Unix timestamp>, <Account>, <Storage size change> ,<Size in input substate>, <Size in output substate>
```

### Smart Contract Code Size
To profile smart contract code size and nonce in a given block range,
```shell
substate-cli code-size 0 41000000
```

Output format
```
metric: <Block>, <Transaction>, <Unix timestamp>, <Account>, <Code size> ,<Nonce>, <Transaction type>
```
Binary file added build/substate-cli
Binary file not shown.
74 changes: 74 additions & 0 deletions cmd/substate-cli/db/clone.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package db

import (
"fmt"
"strconv"

"github.com/ethereum/go-ethereum/core/rawdb"
"github.com/ethereum/go-ethereum/substate"
cli "gopkg.in/urfave/cli.v1"
)

var CloneCommand = cli.Command{
Action: clone,
Name: "clone",
Usage: "Create a clone DB of a given range of blocks",
ArgsUsage: "<srcPath> <dstPath> <blockNumFirst> <blockNumLast>",
Flags: []cli.Flag{
substate.WorkersFlag,
},
Description: `
The substate-cli db clone command requires four arguments:
<srcPath> <dstPath> <blockNumFirst> <blockNumLast>
<srcPath> is the original substate database to read the information.
<dstPath> is the target substate database to write the information
<blockNumFirst> and <blockNumLast> are the first and
last block of the inclusive range of blocks to clone.`,
}

func clone(ctx *cli.Context) error {
var err error

if len(ctx.Args()) != 4 {
return fmt.Errorf("substate-cli db clone command requires exactly 4 arguments")
}

srcPath := ctx.Args().Get(0)
dstPath := ctx.Args().Get(1)
first, ferr := strconv.ParseInt(ctx.Args().Get(2), 10, 64)
last, lerr := strconv.ParseInt(ctx.Args().Get(3), 10, 64)
if ferr != nil || lerr != nil {
return fmt.Errorf("substate-cli db clone: error in parsing parameters: block number not an integer")
}
if first < 0 || last < 0 {
return fmt.Errorf("substate-cli db clone: error: block number must be greater than 0")
}
if first > last {
return fmt.Errorf("substate-cli db clone: error: first block has larger number than last block")
}

srcBackend, err := rawdb.NewLevelDBDatabase(srcPath, 1024, 100, "srcDB", true)
if err != nil {
return fmt.Errorf("substate-cli db clone: error opening %s: %v", srcPath, err)
}
srcDB := substate.NewSubstateDB(srcBackend)
defer srcDB.Close()

// Create dst DB
dstBackend, err := rawdb.NewLevelDBDatabase(dstPath, 1024, 100, "srcDB", false)
if err != nil {
return fmt.Errorf("substate-cli db clone: error creating %s: %v", dstPath, err)
}
dstDB := substate.NewSubstateDB(dstBackend)
defer dstDB.Close()

cloneTask := func(block uint64, tx int, substate *substate.Substate, taskPool *substate.SubstateTaskPool) error {
dstDB.PutSubstate(block, tx, substate)
return nil
}

taskPool := substate.NewSubstateTaskPool("substate-cli db clone", cloneTask, uint64(first), uint64(last), ctx)
taskPool.DB = srcDB
err = taskPool.Execute()
return err
}
62 changes: 62 additions & 0 deletions cmd/substate-cli/db/compact.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package db

import (
"fmt"
"sync"
"time"

"github.com/syndtr/goleveldb/leveldb"
leveldb_opt "github.com/syndtr/goleveldb/leveldb/opt"
leveldb_util "github.com/syndtr/goleveldb/leveldb/util"
cli "gopkg.in/urfave/cli.v1"
)

var CompactCommand = cli.Command{
Action: compact,
Name: "compact",
Usage: "Compat LevelDB - discarding deleted and overwritten versions",
ArgsUsage: "<dbPath>",
Flags: []cli.Flag{},
Description: `
The substate-cli db compact command requires one argument:
<dbPath>
<dbPath> is the target LevelDB instance to compact.`,
}

func compact(ctx *cli.Context) error {
var err error
if len(ctx.Args()) != 1 {
return fmt.Errorf("substate-cli db compact: command requires exactly one arguments")
}

dbPath := ctx.Args().Get(0)
dbOpt := &leveldb_opt.Options{
BlockCacheCapacity: 1 * leveldb_opt.GiB,
OpenFilesCacheCapacity: 50,

ErrorIfMissing: true,
ReadOnly: false,
}
db, err := leveldb.OpenFile(dbPath, dbOpt)
if err != nil {
return fmt.Errorf("substate-cli db compact: error opening dbPath %s: %v", dbPath, err)
}

start := time.Now()
fmt.Printf("substate-cli db compact: compaction begin\n")
wg := &sync.WaitGroup{}
wg.Add(1)
go func() {
err = db.CompactRange(leveldb_util.Range{})
if err != nil {
panic(fmt.Errorf("substate-cli db compact: error compacting dbPath %s: %v", dbPath, err))
}
wg.Done()
}()
wg.Wait()
duration := time.Since(start)
fmt.Printf("substate-cli db compact: compaction completed\n")
fmt.Printf("substate-cli db compact: elapsed time: %v\n", duration.Round(1*time.Millisecond))

return nil
}
Loading

0 comments on commit 874c55f

Please sign in to comment.