update to work with go-ipfs fork that doesn't use go modules and so can play nice with our forked dependencies; update documentation and dockerfile
This commit is contained in:
parent
5356cd50bb
commit
230e782e6c
950
Gopkg.lock
generated
950
Gopkg.lock
generated
File diff suppressed because it is too large
Load Diff
@ -58,9 +58,10 @@
|
||||
name = "github.com/vulcanize/eth-block-extractor"
|
||||
branch = "pair_with_syncAndPublish"
|
||||
|
||||
[[override]]
|
||||
[[constraint]]
|
||||
name = "github.com/ipfs/go-ipfs"
|
||||
version = "0.4.20"
|
||||
source = "github.com/vulcanize/go-ipfs"
|
||||
branch = "postgres_update"
|
||||
|
||||
[[override]]
|
||||
name = "github.com/dgraph-io/badger"
|
||||
@ -77,3 +78,7 @@
|
||||
[[prune.project]]
|
||||
name = "github.com/karalabe/hid"
|
||||
unused-packages = false
|
||||
|
||||
[[prune.project]]
|
||||
name = "github.com/karalabe/usb"
|
||||
unused-packages = false
|
||||
|
@ -28,8 +28,8 @@ set +e
|
||||
./goose postgres "$CONNECT_STRING" up
|
||||
if [ $? -eq 0 ]; then
|
||||
# Fire up the services
|
||||
ipfs ipfs init --profile=postgresds
|
||||
geth --statediff --statediff.streamblock --ws --syncmode=full
|
||||
ipfs ipfs init --profile=postgresds &
|
||||
geth --statediff --statediff.streamblock --ws --syncmode=full &
|
||||
./vulcanizedb syncPublishScreenAndServe --config environments/seedNodeStaging.toml &
|
||||
else
|
||||
echo "Could not run migrations. Are the database details correct?"
|
||||
|
@ -16,81 +16,32 @@ To start, download and install [IPFS](https://github.com/vulcanize/go-ipfs)
|
||||
|
||||
`make install`
|
||||
|
||||
If we want to use Postgres as our backing datastore, the setup is currently considerably more complicated because the Postgres support
|
||||
exists on a fork.
|
||||
If we want to use Postgres as our backing datastore, we need to use the vulcanize fork of go-ipfs. This fork supports
|
||||
the Postgres datastore plugin and has been adjusted to use `dep` instead of Go modules since Go modules cannot work with
|
||||
un-versioned forks and we need to use an un-versioned fork of go-ipfs-config.
|
||||
|
||||
Begin by downloading and installing the normal IPFS as shown above.
|
||||
Once that is done we need to initialize and then startup an IPFS daemon,
|
||||
due to the employment of `gx` we need to first have a daemon running in order to publish the hashes that are needed to update it to work with Postgres.
|
||||
|
||||
`ipfs init`
|
||||
|
||||
`ipfs daemon`
|
||||
|
||||
Now we can go about updating our ipfs dependencies. Start by switching to the Postgres supporting fork:
|
||||
Start by adding the fork and switching over to it:
|
||||
|
||||
`git remote add vulcanize https://github.com/vulcanize/go-ipfs.git`
|
||||
|
||||
`git fetch vulcanize`
|
||||
|
||||
`git checkout -b postgres vulcanize/postgres`
|
||||
`git checkout -b postgres_update vulcanize/postgres_update`
|
||||
|
||||
Switch it's gx dep to use the fork of go-ipfs-config which supports Postgres.
|
||||
This go-ipfs-config fork is approved but awaiting merger. It will be gx-ed when it is merged but not before,
|
||||
so for now we need to do it ourselves locally:
|
||||
Now install this fork of ipfs, first be sure to remove any previous installation. It is important to use the below command
|
||||
instead of using `make install`, as `make install` will default to using Go modules and this will wreck our dependencies
|
||||
since Go modules cannot work with un-versioned forks.
|
||||
|
||||
`go get github.com/ipfs/go-ipfs-config`
|
||||
`go install ./cmd/ipfs`
|
||||
|
||||
`cd $GOPATH/src/github.com/ipfs/go-ipfs-config`
|
||||
Check that is installed properly by running
|
||||
|
||||
`git remote add vulcanize https://github.com/vulcanize/go-ipfs-config.git`
|
||||
`ipfs`
|
||||
|
||||
`git fetch vulcanize`
|
||||
You should see the CLI info/help output.
|
||||
|
||||
`gx release patch`
|
||||
|
||||
This outputs a hash, let's call it "go-ipfs-config-hash", this hash now needs to be gx imported into go-ipfs:
|
||||
|
||||
`cd $GOPATH/src/github.com/ipfs/go-ipfs`
|
||||
|
||||
`gx update go-ipfs-config-hash`
|
||||
|
||||
This should update the go-ipfs-config dependency, it should also notify that the iptb-plugins has a different,
|
||||
conflicting, go-ipfs-config dependency- so we need to patch a fix for that too:
|
||||
|
||||
`go get github.com/ipfs/iptb-plugins`
|
||||
|
||||
`cd $GOPATH/src/github.com/ipfs/iptb-plugins`
|
||||
|
||||
`gx update go-ipfs-config-hash`
|
||||
|
||||
`gx release patch`
|
||||
|
||||
This outputs a hash, let's call it "iptb-plugins-hash", this hash now needs to be gx imported into go-ipfs too:
|
||||
|
||||
`cd $GOPATH/src/github.com/ipfs/go-ipfs`
|
||||
|
||||
`gx update iptb-plugins-hash`
|
||||
|
||||
And now we should have resolved all of the `gx` dependency issues.
|
||||
We can close the ipfs daemon at this point.
|
||||
|
||||
Before installing this updated version of ipfs, we first need to edit the `GOPATH/src/github.com/ipfs/go-ipfs/plugin/loader/preload_list` so that
|
||||
the postgresds plugin is not commented out on the bottom line.
|
||||
|
||||
After that we need to delete the old, non-postgres, profile we initialized for the ipfs daemon.
|
||||
|
||||
`rm ~/.ipfs/config`
|
||||
|
||||
And get rid of the old executable
|
||||
|
||||
`rm $GOPATH/bin/ipfs`
|
||||
|
||||
And now we should be ready to install PG-IPFS.
|
||||
|
||||
`make install`
|
||||
|
||||
And this time we initialize with the `postgresds` profile.
|
||||
And now we initialize with the `postgresds` profile.
|
||||
If ipfs was previously initialized we will need to remove the old profile first.
|
||||
We also need to provide env variables for the postgres connection:
|
||||
|
||||
We can either set these manually, e.g.
|
||||
@ -113,10 +64,10 @@ which has usage:
|
||||
|
||||
and will ask us to enter the password, avoiding storing it to an ENV variable.
|
||||
|
||||
Once we have initialized IPFS, that is all we need to do with it- we do not need to run a daemon during the subsequent processes.
|
||||
Once we have initialized ipfs, that is all we need to do with it- we do not need to run a daemon during the subsequent processes.
|
||||
|
||||
### Geth
|
||||
For Geth, we currently *require* a special fork but the setup is considerably more straight forward than the forked ipfs setup:
|
||||
For Geth, we currently *require* a special fork, and we can set this up as follows:
|
||||
|
||||
Begin by downloading geth and switching to the vulcanize/rpc_statediffing branch
|
||||
|
||||
|
3
vendor/github.com/Stebalien/go-bitfield/go.mod
generated
vendored
Normal file
3
vendor/github.com/Stebalien/go-bitfield/go.mod
generated
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
module github.com/Stebalien/go-bitfield
|
||||
|
||||
go 1.12
|
10
vendor/github.com/allegro/bigcache/.gitignore
generated
vendored
Normal file
10
vendor/github.com/allegro/bigcache/.gitignore
generated
vendored
Normal file
@ -0,0 +1,10 @@
|
||||
.idea
|
||||
.DS_Store
|
||||
/server/server.exe
|
||||
/server/server
|
||||
/server/server_dar*
|
||||
/server/server_fre*
|
||||
/server/server_win*
|
||||
/server/server_net*
|
||||
/server/server_ope*
|
||||
CHANGELOG.md
|
31
vendor/github.com/allegro/bigcache/.travis.yml
generated
vendored
Normal file
31
vendor/github.com/allegro/bigcache/.travis.yml
generated
vendored
Normal file
@ -0,0 +1,31 @@
|
||||
language: go
|
||||
|
||||
go:
|
||||
- 1.x
|
||||
- tip
|
||||
|
||||
matrix:
|
||||
allow_failures:
|
||||
- go: tip
|
||||
fast_finish: true
|
||||
|
||||
before_install:
|
||||
- go get github.com/modocache/gover
|
||||
- go get github.com/mattn/goveralls
|
||||
- go get golang.org/x/tools/cmd/cover
|
||||
- go get golang.org/x/tools/cmd/goimports
|
||||
- go get golang.org/x/lint/golint
|
||||
- go get github.com/stretchr/testify/assert
|
||||
- go get github.com/gordonklaus/ineffassign
|
||||
|
||||
script:
|
||||
- gofiles=$(find ./ -name '*.go') && [ -z "$gofiles" ] || unformatted=$(goimports -l $gofiles) && [ -z "$unformatted" ] || (echo >&2 "Go files must be formatted with gofmt. Following files has problem:\n $unformatted" && false)
|
||||
- diff <(echo -n) <(gofmt -s -d .)
|
||||
- golint ./... # This won't break the build, just show warnings
|
||||
- ineffassign .
|
||||
- go vet ./...
|
||||
- go test -race -count=1 -coverprofile=queue.coverprofile ./queue
|
||||
- go test -race -count=1 -coverprofile=server.coverprofile ./server
|
||||
- go test -race -count=1 -coverprofile=main.coverprofile
|
||||
- $HOME/gopath/bin/gover
|
||||
- $HOME/gopath/bin/goveralls -coverprofile=gover.coverprofile -service travis-ci
|
150
vendor/github.com/allegro/bigcache/README.md
generated
vendored
Normal file
150
vendor/github.com/allegro/bigcache/README.md
generated
vendored
Normal file
@ -0,0 +1,150 @@
|
||||
# BigCache [](https://travis-ci.org/allegro/bigcache) [](https://coveralls.io/github/allegro/bigcache?branch=master) [](https://godoc.org/github.com/allegro/bigcache) [](https://goreportcard.com/report/github.com/allegro/bigcache)
|
||||
|
||||
Fast, concurrent, evicting in-memory cache written to keep big number of entries without impact on performance.
|
||||
BigCache keeps entries on heap but omits GC for them. To achieve that operations on bytes arrays take place,
|
||||
therefore entries (de)serialization in front of the cache will be needed in most use cases.
|
||||
|
||||
## Usage
|
||||
|
||||
### Simple initialization
|
||||
|
||||
```go
|
||||
import "github.com/allegro/bigcache"
|
||||
|
||||
cache, _ := bigcache.NewBigCache(bigcache.DefaultConfig(10 * time.Minute))
|
||||
|
||||
cache.Set("my-unique-key", []byte("value"))
|
||||
|
||||
entry, _ := cache.Get("my-unique-key")
|
||||
fmt.Println(string(entry))
|
||||
```
|
||||
|
||||
### Custom initialization
|
||||
|
||||
When cache load can be predicted in advance then it is better to use custom initialization because additional memory
|
||||
allocation can be avoided in that way.
|
||||
|
||||
```go
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/allegro/bigcache"
|
||||
)
|
||||
|
||||
config := bigcache.Config {
|
||||
// number of shards (must be a power of 2)
|
||||
Shards: 1024,
|
||||
// time after which entry can be evicted
|
||||
LifeWindow: 10 * time.Minute,
|
||||
// rps * lifeWindow, used only in initial memory allocation
|
||||
MaxEntriesInWindow: 1000 * 10 * 60,
|
||||
// max entry size in bytes, used only in initial memory allocation
|
||||
MaxEntrySize: 500,
|
||||
// prints information about additional memory allocation
|
||||
Verbose: true,
|
||||
// cache will not allocate more memory than this limit, value in MB
|
||||
// if value is reached then the oldest entries can be overridden for the new ones
|
||||
// 0 value means no size limit
|
||||
HardMaxCacheSize: 8192,
|
||||
// callback fired when the oldest entry is removed because of its expiration time or no space left
|
||||
// for the new entry, or because delete was called. A bitmask representing the reason will be returned.
|
||||
// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.
|
||||
OnRemove: nil,
|
||||
// OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left
|
||||
// for the new entry, or because delete was called. A constant representing the reason will be passed through.
|
||||
// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.
|
||||
// Ignored if OnRemove is specified.
|
||||
OnRemoveWithReason: nil,
|
||||
}
|
||||
|
||||
cache, initErr := bigcache.NewBigCache(config)
|
||||
if initErr != nil {
|
||||
log.Fatal(initErr)
|
||||
}
|
||||
|
||||
cache.Set("my-unique-key", []byte("value"))
|
||||
|
||||
if entry, err := cache.Get("my-unique-key"); err == nil {
|
||||
fmt.Println(string(entry))
|
||||
}
|
||||
```
|
||||
|
||||
## Benchmarks
|
||||
|
||||
Three caches were compared: bigcache, [freecache](https://github.com/coocood/freecache) and map.
|
||||
Benchmark tests were made using an i7-6700K with 32GB of RAM on Windows 10.
|
||||
|
||||
### Writes and reads
|
||||
|
||||
```bash
|
||||
cd caches_bench; go test -bench=. -benchtime=10s ./... -timeout 30m
|
||||
|
||||
BenchmarkMapSet-8 3000000 569 ns/op 202 B/op 3 allocs/op
|
||||
BenchmarkConcurrentMapSet-8 1000000 1592 ns/op 347 B/op 8 allocs/op
|
||||
BenchmarkFreeCacheSet-8 3000000 775 ns/op 355 B/op 2 allocs/op
|
||||
BenchmarkBigCacheSet-8 3000000 640 ns/op 303 B/op 2 allocs/op
|
||||
BenchmarkMapGet-8 5000000 407 ns/op 24 B/op 1 allocs/op
|
||||
BenchmarkConcurrentMapGet-8 3000000 558 ns/op 24 B/op 2 allocs/op
|
||||
BenchmarkFreeCacheGet-8 2000000 682 ns/op 136 B/op 2 allocs/op
|
||||
BenchmarkBigCacheGet-8 3000000 512 ns/op 152 B/op 4 allocs/op
|
||||
BenchmarkBigCacheSetParallel-8 10000000 225 ns/op 313 B/op 3 allocs/op
|
||||
BenchmarkFreeCacheSetParallel-8 10000000 218 ns/op 341 B/op 3 allocs/op
|
||||
BenchmarkConcurrentMapSetParallel-8 5000000 318 ns/op 200 B/op 6 allocs/op
|
||||
BenchmarkBigCacheGetParallel-8 20000000 178 ns/op 152 B/op 4 allocs/op
|
||||
BenchmarkFreeCacheGetParallel-8 20000000 295 ns/op 136 B/op 3 allocs/op
|
||||
BenchmarkConcurrentMapGetParallel-8 10000000 237 ns/op 24 B/op 2 allocs/op
|
||||
```
|
||||
|
||||
Writes and reads in bigcache are faster than in freecache.
|
||||
Writes to map are the slowest.
|
||||
|
||||
### GC pause time
|
||||
|
||||
```bash
|
||||
cd caches_bench; go run caches_gc_overhead_comparison.go
|
||||
|
||||
Number of entries: 20000000
|
||||
GC pause for bigcache: 5.8658ms
|
||||
GC pause for freecache: 32.4341ms
|
||||
GC pause for map: 52.9661ms
|
||||
```
|
||||
|
||||
Test shows how long are the GC pauses for caches filled with 20mln of entries.
|
||||
Bigcache and freecache have very similar GC pause time.
|
||||
It is clear that both reduce GC overhead in contrast to map
|
||||
which GC pause time took more than 10 seconds.
|
||||
|
||||
## How it works
|
||||
|
||||
BigCache relies on optimization presented in 1.5 version of Go ([issue-9477](https://github.com/golang/go/issues/9477)).
|
||||
This optimization states that if map without pointers in keys and values is used then GC will omit its content.
|
||||
Therefore BigCache uses `map[uint64]uint32` where keys are hashed and values are offsets of entries.
|
||||
|
||||
Entries are kept in bytes array, to omit GC again.
|
||||
Bytes array size can grow to gigabytes without impact on performance
|
||||
because GC will only see single pointer to it.
|
||||
|
||||
## Bigcache vs Freecache
|
||||
|
||||
Both caches provide the same core features but they reduce GC overhead in different ways.
|
||||
Bigcache relies on `map[uint64]uint32`, freecache implements its own mapping built on
|
||||
slices to reduce number of pointers.
|
||||
|
||||
Results from benchmark tests are presented above.
|
||||
One of the advantage of bigcache over freecache is that you don’t need to know
|
||||
the size of the cache in advance, because when bigcache is full,
|
||||
it can allocate additional memory for new entries instead of
|
||||
overwriting existing ones as freecache does currently.
|
||||
However hard max size in bigcache also can be set, check [HardMaxCacheSize](https://godoc.org/github.com/allegro/bigcache#Config).
|
||||
|
||||
## HTTP Server
|
||||
|
||||
This package also includes an easily deployable HTTP implementation of BigCache, which can be found in the [server](/server) package.
|
||||
|
||||
## More
|
||||
|
||||
Bigcache genesis is described in allegro.tech blog post: [writing a very fast cache service in Go](http://allegro.tech/2016/03/writing-fast-cache-service-in-go.html)
|
||||
|
||||
## License
|
||||
|
||||
BigCache is released under the Apache 2.0 license (see [LICENSE](LICENSE))
|
202
vendor/github.com/allegro/bigcache/bigcache.go
generated
vendored
Normal file
202
vendor/github.com/allegro/bigcache/bigcache.go
generated
vendored
Normal file
@ -0,0 +1,202 @@
|
||||
package bigcache
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
minimumEntriesInShard = 10 // Minimum number of entries in single shard
|
||||
)
|
||||
|
||||
// BigCache is fast, concurrent, evicting cache created to keep big number of entries without impact on performance.
|
||||
// It keeps entries on heap but omits GC for them. To achieve that, operations take place on byte arrays,
|
||||
// therefore entries (de)serialization in front of the cache will be needed in most use cases.
|
||||
type BigCache struct {
|
||||
shards []*cacheShard
|
||||
lifeWindow uint64
|
||||
clock clock
|
||||
hash Hasher
|
||||
config Config
|
||||
shardMask uint64
|
||||
maxShardSize uint32
|
||||
close chan struct{}
|
||||
}
|
||||
|
||||
// RemoveReason is a value used to signal to the user why a particular key was removed in the OnRemove callback.
|
||||
type RemoveReason uint32
|
||||
|
||||
const (
|
||||
// Expired means the key is past its LifeWindow.
|
||||
Expired RemoveReason = iota
|
||||
// NoSpace means the key is the oldest and the cache size was at its maximum when Set was called, or the
|
||||
// entry exceeded the maximum shard size.
|
||||
NoSpace
|
||||
// Deleted means Delete was called and this key was removed as a result.
|
||||
Deleted
|
||||
)
|
||||
|
||||
// NewBigCache initialize new instance of BigCache
|
||||
func NewBigCache(config Config) (*BigCache, error) {
|
||||
return newBigCache(config, &systemClock{})
|
||||
}
|
||||
|
||||
func newBigCache(config Config, clock clock) (*BigCache, error) {
|
||||
|
||||
if !isPowerOfTwo(config.Shards) {
|
||||
return nil, fmt.Errorf("Shards number must be power of two")
|
||||
}
|
||||
|
||||
if config.Hasher == nil {
|
||||
config.Hasher = newDefaultHasher()
|
||||
}
|
||||
|
||||
cache := &BigCache{
|
||||
shards: make([]*cacheShard, config.Shards),
|
||||
lifeWindow: uint64(config.LifeWindow.Seconds()),
|
||||
clock: clock,
|
||||
hash: config.Hasher,
|
||||
config: config,
|
||||
shardMask: uint64(config.Shards - 1),
|
||||
maxShardSize: uint32(config.maximumShardSize()),
|
||||
close: make(chan struct{}),
|
||||
}
|
||||
|
||||
var onRemove func(wrappedEntry []byte, reason RemoveReason)
|
||||
if config.OnRemove != nil {
|
||||
onRemove = cache.providedOnRemove
|
||||
} else if config.OnRemoveWithReason != nil {
|
||||
onRemove = cache.providedOnRemoveWithReason
|
||||
} else {
|
||||
onRemove = cache.notProvidedOnRemove
|
||||
}
|
||||
|
||||
for i := 0; i < config.Shards; i++ {
|
||||
cache.shards[i] = initNewShard(config, onRemove, clock)
|
||||
}
|
||||
|
||||
if config.CleanWindow > 0 {
|
||||
go func() {
|
||||
ticker := time.NewTicker(config.CleanWindow)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case t := <-ticker.C:
|
||||
cache.cleanUp(uint64(t.Unix()))
|
||||
case <-cache.close:
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
return cache, nil
|
||||
}
|
||||
|
||||
// Close is used to signal a shutdown of the cache when you are done with it.
|
||||
// This allows the cleaning goroutines to exit and ensures references are not
|
||||
// kept to the cache preventing GC of the entire cache.
|
||||
func (c *BigCache) Close() error {
|
||||
close(c.close)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get reads entry for the key.
|
||||
// It returns an ErrEntryNotFound when
|
||||
// no entry exists for the given key.
|
||||
func (c *BigCache) Get(key string) ([]byte, error) {
|
||||
hashedKey := c.hash.Sum64(key)
|
||||
shard := c.getShard(hashedKey)
|
||||
return shard.get(key, hashedKey)
|
||||
}
|
||||
|
||||
// Set saves entry under the key
|
||||
func (c *BigCache) Set(key string, entry []byte) error {
|
||||
hashedKey := c.hash.Sum64(key)
|
||||
shard := c.getShard(hashedKey)
|
||||
return shard.set(key, hashedKey, entry)
|
||||
}
|
||||
|
||||
// Delete removes the key
|
||||
func (c *BigCache) Delete(key string) error {
|
||||
hashedKey := c.hash.Sum64(key)
|
||||
shard := c.getShard(hashedKey)
|
||||
return shard.del(key, hashedKey)
|
||||
}
|
||||
|
||||
// Reset empties all cache shards
|
||||
func (c *BigCache) Reset() error {
|
||||
for _, shard := range c.shards {
|
||||
shard.reset(c.config)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Len computes number of entries in cache
|
||||
func (c *BigCache) Len() int {
|
||||
var len int
|
||||
for _, shard := range c.shards {
|
||||
len += shard.len()
|
||||
}
|
||||
return len
|
||||
}
|
||||
|
||||
// Capacity returns amount of bytes store in the cache.
|
||||
func (c *BigCache) Capacity() int {
|
||||
var len int
|
||||
for _, shard := range c.shards {
|
||||
len += shard.capacity()
|
||||
}
|
||||
return len
|
||||
}
|
||||
|
||||
// Stats returns cache's statistics
|
||||
func (c *BigCache) Stats() Stats {
|
||||
var s Stats
|
||||
for _, shard := range c.shards {
|
||||
tmp := shard.getStats()
|
||||
s.Hits += tmp.Hits
|
||||
s.Misses += tmp.Misses
|
||||
s.DelHits += tmp.DelHits
|
||||
s.DelMisses += tmp.DelMisses
|
||||
s.Collisions += tmp.Collisions
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Iterator returns iterator function to iterate over EntryInfo's from whole cache.
|
||||
func (c *BigCache) Iterator() *EntryInfoIterator {
|
||||
return newIterator(c)
|
||||
}
|
||||
|
||||
func (c *BigCache) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool {
|
||||
oldestTimestamp := readTimestampFromEntry(oldestEntry)
|
||||
if currentTimestamp-oldestTimestamp > c.lifeWindow {
|
||||
evict(Expired)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *BigCache) cleanUp(currentTimestamp uint64) {
|
||||
for _, shard := range c.shards {
|
||||
shard.cleanUp(currentTimestamp)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *BigCache) getShard(hashedKey uint64) (shard *cacheShard) {
|
||||
return c.shards[hashedKey&c.shardMask]
|
||||
}
|
||||
|
||||
func (c *BigCache) providedOnRemove(wrappedEntry []byte, reason RemoveReason) {
|
||||
c.config.OnRemove(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry))
|
||||
}
|
||||
|
||||
func (c *BigCache) providedOnRemoveWithReason(wrappedEntry []byte, reason RemoveReason) {
|
||||
if c.config.onRemoveFilter == 0 || (1<<uint(reason))&c.config.onRemoveFilter > 0 {
|
||||
c.config.OnRemoveWithReason(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry), reason)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *BigCache) notProvidedOnRemove(wrappedEntry []byte, reason RemoveReason) {
|
||||
}
|
14
vendor/github.com/allegro/bigcache/bytes.go
generated
vendored
Normal file
14
vendor/github.com/allegro/bigcache/bytes.go
generated
vendored
Normal file
@ -0,0 +1,14 @@
|
||||
// +build !appengine
|
||||
|
||||
package bigcache
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func bytesToString(b []byte) string {
|
||||
bytesHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b))
|
||||
strHeader := reflect.StringHeader{Data: bytesHeader.Data, Len: bytesHeader.Len}
|
||||
return *(*string)(unsafe.Pointer(&strHeader))
|
||||
}
|
7
vendor/github.com/allegro/bigcache/bytes_appengine.go
generated
vendored
Normal file
7
vendor/github.com/allegro/bigcache/bytes_appengine.go
generated
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
// +build appengine
|
||||
|
||||
package bigcache
|
||||
|
||||
func bytesToString(b []byte) string {
|
||||
return string(b)
|
||||
}
|
86
vendor/github.com/allegro/bigcache/config.go
generated
vendored
Normal file
86
vendor/github.com/allegro/bigcache/config.go
generated
vendored
Normal file
@ -0,0 +1,86 @@
|
||||
package bigcache
|
||||
|
||||
import "time"
|
||||
|
||||
// Config for BigCache
|
||||
type Config struct {
|
||||
// Number of cache shards, value must be a power of two
|
||||
Shards int
|
||||
// Time after which entry can be evicted
|
||||
LifeWindow time.Duration
|
||||
// Interval between removing expired entries (clean up).
|
||||
// If set to <= 0 then no action is performed. Setting to < 1 second is counterproductive — bigcache has a one second resolution.
|
||||
CleanWindow time.Duration
|
||||
// Max number of entries in life window. Used only to calculate initial size for cache shards.
|
||||
// When proper value is set then additional memory allocation does not occur.
|
||||
MaxEntriesInWindow int
|
||||
// Max size of entry in bytes. Used only to calculate initial size for cache shards.
|
||||
MaxEntrySize int
|
||||
// Verbose mode prints information about new memory allocation
|
||||
Verbose bool
|
||||
// Hasher used to map between string keys and unsigned 64bit integers, by default fnv64 hashing is used.
|
||||
Hasher Hasher
|
||||
// HardMaxCacheSize is a limit for cache size in MB. Cache will not allocate more memory than this limit.
|
||||
// It can protect application from consuming all available memory on machine, therefore from running OOM Killer.
|
||||
// Default value is 0 which means unlimited size. When the limit is higher than 0 and reached then
|
||||
// the oldest entries are overridden for the new ones.
|
||||
HardMaxCacheSize int
|
||||
// OnRemove is a callback fired when the oldest entry is removed because of its expiration time or no space left
|
||||
// for the new entry, or because delete was called.
|
||||
// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.
|
||||
OnRemove func(key string, entry []byte)
|
||||
// OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left
|
||||
// for the new entry, or because delete was called. A constant representing the reason will be passed through.
|
||||
// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.
|
||||
// Ignored if OnRemove is specified.
|
||||
OnRemoveWithReason func(key string, entry []byte, reason RemoveReason)
|
||||
|
||||
onRemoveFilter int
|
||||
|
||||
// Logger is a logging interface and used in combination with `Verbose`
|
||||
// Defaults to `DefaultLogger()`
|
||||
Logger Logger
|
||||
}
|
||||
|
||||
// DefaultConfig initializes config with default values.
|
||||
// When load for BigCache can be predicted in advance then it is better to use custom config.
|
||||
func DefaultConfig(eviction time.Duration) Config {
|
||||
return Config{
|
||||
Shards: 1024,
|
||||
LifeWindow: eviction,
|
||||
CleanWindow: 0,
|
||||
MaxEntriesInWindow: 1000 * 10 * 60,
|
||||
MaxEntrySize: 500,
|
||||
Verbose: true,
|
||||
Hasher: newDefaultHasher(),
|
||||
HardMaxCacheSize: 0,
|
||||
Logger: DefaultLogger(),
|
||||
}
|
||||
}
|
||||
|
||||
// initialShardSize computes initial shard size
|
||||
func (c Config) initialShardSize() int {
|
||||
return max(c.MaxEntriesInWindow/c.Shards, minimumEntriesInShard)
|
||||
}
|
||||
|
||||
// maximumShardSize computes maximum shard size
|
||||
func (c Config) maximumShardSize() int {
|
||||
maxShardSize := 0
|
||||
|
||||
if c.HardMaxCacheSize > 0 {
|
||||
maxShardSize = convertMBToBytes(c.HardMaxCacheSize) / c.Shards
|
||||
}
|
||||
|
||||
return maxShardSize
|
||||
}
|
||||
|
||||
// OnRemoveFilterSet sets which remove reasons will trigger a call to OnRemoveWithReason.
|
||||
// Filtering out reasons prevents bigcache from unwrapping them, which saves cpu.
|
||||
func (c Config) OnRemoveFilterSet(reasons ...RemoveReason) Config {
|
||||
c.onRemoveFilter = 0
|
||||
for i := range reasons {
|
||||
c.onRemoveFilter |= 1 << uint(reasons[i])
|
||||
}
|
||||
|
||||
return c
|
||||
}
|
62
vendor/github.com/allegro/bigcache/encoding.go
generated
vendored
Normal file
62
vendor/github.com/allegro/bigcache/encoding.go
generated
vendored
Normal file
@ -0,0 +1,62 @@
|
||||
package bigcache
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
)
|
||||
|
||||
const (
|
||||
timestampSizeInBytes = 8 // Number of bytes used for timestamp
|
||||
hashSizeInBytes = 8 // Number of bytes used for hash
|
||||
keySizeInBytes = 2 // Number of bytes used for size of entry key
|
||||
headersSizeInBytes = timestampSizeInBytes + hashSizeInBytes + keySizeInBytes // Number of bytes used for all headers
|
||||
)
|
||||
|
||||
func wrapEntry(timestamp uint64, hash uint64, key string, entry []byte, buffer *[]byte) []byte {
|
||||
keyLength := len(key)
|
||||
blobLength := len(entry) + headersSizeInBytes + keyLength
|
||||
|
||||
if blobLength > len(*buffer) {
|
||||
*buffer = make([]byte, blobLength)
|
||||
}
|
||||
blob := *buffer
|
||||
|
||||
binary.LittleEndian.PutUint64(blob, timestamp)
|
||||
binary.LittleEndian.PutUint64(blob[timestampSizeInBytes:], hash)
|
||||
binary.LittleEndian.PutUint16(blob[timestampSizeInBytes+hashSizeInBytes:], uint16(keyLength))
|
||||
copy(blob[headersSizeInBytes:], key)
|
||||
copy(blob[headersSizeInBytes+keyLength:], entry)
|
||||
|
||||
return blob[:blobLength]
|
||||
}
|
||||
|
||||
func readEntry(data []byte) []byte {
|
||||
length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:])
|
||||
|
||||
// copy on read
|
||||
dst := make([]byte, len(data)-int(headersSizeInBytes+length))
|
||||
copy(dst, data[headersSizeInBytes+length:])
|
||||
|
||||
return dst
|
||||
}
|
||||
|
||||
func readTimestampFromEntry(data []byte) uint64 {
|
||||
return binary.LittleEndian.Uint64(data)
|
||||
}
|
||||
|
||||
func readKeyFromEntry(data []byte) string {
|
||||
length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:])
|
||||
|
||||
// copy on read
|
||||
dst := make([]byte, length)
|
||||
copy(dst, data[headersSizeInBytes:headersSizeInBytes+length])
|
||||
|
||||
return bytesToString(dst)
|
||||
}
|
||||
|
||||
func readHashFromEntry(data []byte) uint64 {
|
||||
return binary.LittleEndian.Uint64(data[timestampSizeInBytes:])
|
||||
}
|
||||
|
||||
func resetKeyFromEntry(data []byte) {
|
||||
binary.LittleEndian.PutUint64(data[timestampSizeInBytes:], 0)
|
||||
}
|
6
vendor/github.com/allegro/bigcache/entry_not_found_error.go
generated
vendored
Normal file
6
vendor/github.com/allegro/bigcache/entry_not_found_error.go
generated
vendored
Normal file
@ -0,0 +1,6 @@
|
||||
package bigcache
|
||||
|
||||
import "errors"
|
||||
|
||||
// ErrEntryNotFound is an error type struct which is returned when entry was not found for provided key
|
||||
var ErrEntryNotFound = errors.New("Entry not found")
|
239
vendor/github.com/allegro/bigcache/shard.go
generated
vendored
Normal file
239
vendor/github.com/allegro/bigcache/shard.go
generated
vendored
Normal file
@ -0,0 +1,239 @@
|
||||
package bigcache
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/allegro/bigcache/queue"
|
||||
)
|
||||
|
||||
type onRemoveCallback func(wrappedEntry []byte, reason RemoveReason)
|
||||
|
||||
type cacheShard struct {
|
||||
hashmap map[uint64]uint32
|
||||
entries queue.BytesQueue
|
||||
lock sync.RWMutex
|
||||
entryBuffer []byte
|
||||
onRemove onRemoveCallback
|
||||
|
||||
isVerbose bool
|
||||
logger Logger
|
||||
clock clock
|
||||
lifeWindow uint64
|
||||
|
||||
stats Stats
|
||||
}
|
||||
|
||||
func (s *cacheShard) get(key string, hashedKey uint64) ([]byte, error) {
|
||||
s.lock.RLock()
|
||||
itemIndex := s.hashmap[hashedKey]
|
||||
|
||||
if itemIndex == 0 {
|
||||
s.lock.RUnlock()
|
||||
s.miss()
|
||||
return nil, ErrEntryNotFound
|
||||
}
|
||||
|
||||
wrappedEntry, err := s.entries.Get(int(itemIndex))
|
||||
if err != nil {
|
||||
s.lock.RUnlock()
|
||||
s.miss()
|
||||
return nil, err
|
||||
}
|
||||
if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey {
|
||||
if s.isVerbose {
|
||||
s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey)
|
||||
}
|
||||
s.lock.RUnlock()
|
||||
s.collision()
|
||||
return nil, ErrEntryNotFound
|
||||
}
|
||||
s.lock.RUnlock()
|
||||
s.hit()
|
||||
return readEntry(wrappedEntry), nil
|
||||
}
|
||||
|
||||
func (s *cacheShard) set(key string, hashedKey uint64, entry []byte) error {
|
||||
currentTimestamp := uint64(s.clock.epoch())
|
||||
|
||||
s.lock.Lock()
|
||||
|
||||
if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 {
|
||||
if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil {
|
||||
resetKeyFromEntry(previousEntry)
|
||||
}
|
||||
}
|
||||
|
||||
if oldestEntry, err := s.entries.Peek(); err == nil {
|
||||
s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry)
|
||||
}
|
||||
|
||||
w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer)
|
||||
|
||||
for {
|
||||
if index, err := s.entries.Push(w); err == nil {
|
||||
s.hashmap[hashedKey] = uint32(index)
|
||||
s.lock.Unlock()
|
||||
return nil
|
||||
}
|
||||
if s.removeOldestEntry(NoSpace) != nil {
|
||||
s.lock.Unlock()
|
||||
return fmt.Errorf("entry is bigger than max shard size")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *cacheShard) del(key string, hashedKey uint64) error {
|
||||
s.lock.RLock()
|
||||
itemIndex := s.hashmap[hashedKey]
|
||||
|
||||
if itemIndex == 0 {
|
||||
s.lock.RUnlock()
|
||||
s.delmiss()
|
||||
return ErrEntryNotFound
|
||||
}
|
||||
|
||||
wrappedEntry, err := s.entries.Get(int(itemIndex))
|
||||
if err != nil {
|
||||
s.lock.RUnlock()
|
||||
s.delmiss()
|
||||
return err
|
||||
}
|
||||
s.lock.RUnlock()
|
||||
|
||||
s.lock.Lock()
|
||||
{
|
||||
delete(s.hashmap, hashedKey)
|
||||
s.onRemove(wrappedEntry, Deleted)
|
||||
resetKeyFromEntry(wrappedEntry)
|
||||
}
|
||||
s.lock.Unlock()
|
||||
|
||||
s.delhit()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *cacheShard) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool {
|
||||
oldestTimestamp := readTimestampFromEntry(oldestEntry)
|
||||
if currentTimestamp-oldestTimestamp > s.lifeWindow {
|
||||
evict(Expired)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *cacheShard) cleanUp(currentTimestamp uint64) {
|
||||
s.lock.Lock()
|
||||
for {
|
||||
if oldestEntry, err := s.entries.Peek(); err != nil {
|
||||
break
|
||||
} else if evicted := s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry); !evicted {
|
||||
break
|
||||
}
|
||||
}
|
||||
s.lock.Unlock()
|
||||
}
|
||||
|
||||
func (s *cacheShard) getOldestEntry() ([]byte, error) {
|
||||
return s.entries.Peek()
|
||||
}
|
||||
|
||||
func (s *cacheShard) getEntry(index int) ([]byte, error) {
|
||||
s.lock.RLock()
|
||||
entry, err := s.entries.Get(index)
|
||||
s.lock.RUnlock()
|
||||
|
||||
return entry, err
|
||||
}
|
||||
|
||||
func (s *cacheShard) copyKeys() (keys []uint32, next int) {
|
||||
s.lock.RLock()
|
||||
keys = make([]uint32, len(s.hashmap))
|
||||
|
||||
for _, index := range s.hashmap {
|
||||
keys[next] = index
|
||||
next++
|
||||
}
|
||||
|
||||
s.lock.RUnlock()
|
||||
return keys, next
|
||||
}
|
||||
|
||||
func (s *cacheShard) removeOldestEntry(reason RemoveReason) error {
|
||||
oldest, err := s.entries.Pop()
|
||||
if err == nil {
|
||||
hash := readHashFromEntry(oldest)
|
||||
delete(s.hashmap, hash)
|
||||
s.onRemove(oldest, reason)
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *cacheShard) reset(config Config) {
|
||||
s.lock.Lock()
|
||||
s.hashmap = make(map[uint64]uint32, config.initialShardSize())
|
||||
s.entryBuffer = make([]byte, config.MaxEntrySize+headersSizeInBytes)
|
||||
s.entries.Reset()
|
||||
s.lock.Unlock()
|
||||
}
|
||||
|
||||
func (s *cacheShard) len() int {
|
||||
s.lock.RLock()
|
||||
res := len(s.hashmap)
|
||||
s.lock.RUnlock()
|
||||
return res
|
||||
}
|
||||
|
||||
func (s *cacheShard) capacity() int {
|
||||
s.lock.RLock()
|
||||
res := s.entries.Capacity()
|
||||
s.lock.RUnlock()
|
||||
return res
|
||||
}
|
||||
|
||||
func (s *cacheShard) getStats() Stats {
|
||||
var stats = Stats{
|
||||
Hits: atomic.LoadInt64(&s.stats.Hits),
|
||||
Misses: atomic.LoadInt64(&s.stats.Misses),
|
||||
DelHits: atomic.LoadInt64(&s.stats.DelHits),
|
||||
DelMisses: atomic.LoadInt64(&s.stats.DelMisses),
|
||||
Collisions: atomic.LoadInt64(&s.stats.Collisions),
|
||||
}
|
||||
return stats
|
||||
}
|
||||
|
||||
func (s *cacheShard) hit() {
|
||||
atomic.AddInt64(&s.stats.Hits, 1)
|
||||
}
|
||||
|
||||
func (s *cacheShard) miss() {
|
||||
atomic.AddInt64(&s.stats.Misses, 1)
|
||||
}
|
||||
|
||||
func (s *cacheShard) delhit() {
|
||||
atomic.AddInt64(&s.stats.DelHits, 1)
|
||||
}
|
||||
|
||||
func (s *cacheShard) delmiss() {
|
||||
atomic.AddInt64(&s.stats.DelMisses, 1)
|
||||
}
|
||||
|
||||
func (s *cacheShard) collision() {
|
||||
atomic.AddInt64(&s.stats.Collisions, 1)
|
||||
}
|
||||
|
||||
func initNewShard(config Config, callback onRemoveCallback, clock clock) *cacheShard {
|
||||
return &cacheShard{
|
||||
hashmap: make(map[uint64]uint32, config.initialShardSize()),
|
||||
entries: *queue.NewBytesQueue(config.initialShardSize()*config.MaxEntrySize, config.maximumShardSize(), config.Verbose),
|
||||
entryBuffer: make([]byte, config.MaxEntrySize+headersSizeInBytes),
|
||||
onRemove: callback,
|
||||
|
||||
isVerbose: config.Verbose,
|
||||
logger: newLogger(config.Logger),
|
||||
clock: clock,
|
||||
lifeWindow: uint64(config.LifeWindow.Seconds()),
|
||||
}
|
||||
}
|
540
vendor/github.com/btcsuite/btcd/btcec/signature.go
generated
vendored
Normal file
540
vendor/github.com/btcsuite/btcd/btcec/signature.go
generated
vendored
Normal file
@ -0,0 +1,540 @@
|
||||
// Copyright (c) 2013-2017 The btcsuite developers
|
||||
// Use of this source code is governed by an ISC
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package btcec
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash"
|
||||
"math/big"
|
||||
)
|
||||
|
||||
// Errors returned by canonicalPadding.
|
||||
var (
|
||||
errNegativeValue = errors.New("value may be interpreted as negative")
|
||||
errExcessivelyPaddedValue = errors.New("value is excessively padded")
|
||||
)
|
||||
|
||||
// Signature is a type representing an ecdsa signature.
|
||||
type Signature struct {
|
||||
R *big.Int
|
||||
S *big.Int
|
||||
}
|
||||
|
||||
var (
|
||||
// Used in RFC6979 implementation when testing the nonce for correctness
|
||||
one = big.NewInt(1)
|
||||
|
||||
// oneInitializer is used to fill a byte slice with byte 0x01. It is provided
|
||||
// here to avoid the need to create it multiple times.
|
||||
oneInitializer = []byte{0x01}
|
||||
)
|
||||
|
||||
// Serialize returns the ECDSA signature in the more strict DER format. Note
|
||||
// that the serialized bytes returned do not include the appended hash type
|
||||
// used in Bitcoin signature scripts.
|
||||
//
|
||||
// encoding/asn1 is broken so we hand roll this output:
|
||||
//
|
||||
// 0x30 <length> 0x02 <length r> r 0x02 <length s> s
|
||||
func (sig *Signature) Serialize() []byte {
|
||||
// low 'S' malleability breaker
|
||||
sigS := sig.S
|
||||
if sigS.Cmp(S256().halfOrder) == 1 {
|
||||
sigS = new(big.Int).Sub(S256().N, sigS)
|
||||
}
|
||||
// Ensure the encoded bytes for the r and s values are canonical and
|
||||
// thus suitable for DER encoding.
|
||||
rb := canonicalizeInt(sig.R)
|
||||
sb := canonicalizeInt(sigS)
|
||||
|
||||
// total length of returned signature is 1 byte for each magic and
|
||||
// length (6 total), plus lengths of r and s
|
||||
length := 6 + len(rb) + len(sb)
|
||||
b := make([]byte, length)
|
||||
|
||||
b[0] = 0x30
|
||||
b[1] = byte(length - 2)
|
||||
b[2] = 0x02
|
||||
b[3] = byte(len(rb))
|
||||
offset := copy(b[4:], rb) + 4
|
||||
b[offset] = 0x02
|
||||
b[offset+1] = byte(len(sb))
|
||||
copy(b[offset+2:], sb)
|
||||
return b
|
||||
}
|
||||
|
||||
// Verify calls ecdsa.Verify to verify the signature of hash using the public
|
||||
// key. It returns true if the signature is valid, false otherwise.
|
||||
func (sig *Signature) Verify(hash []byte, pubKey *PublicKey) bool {
|
||||
return ecdsa.Verify(pubKey.ToECDSA(), hash, sig.R, sig.S)
|
||||
}
|
||||
|
||||
// IsEqual compares this Signature instance to the one passed, returning true
|
||||
// if both Signatures are equivalent. A signature is equivalent to another, if
|
||||
// they both have the same scalar value for R and S.
|
||||
func (sig *Signature) IsEqual(otherSig *Signature) bool {
|
||||
return sig.R.Cmp(otherSig.R) == 0 &&
|
||||
sig.S.Cmp(otherSig.S) == 0
|
||||
}
|
||||
|
||||
// MinSigLen is the minimum length of a DER encoded signature and is when both R
|
||||
// and S are 1 byte each.
|
||||
// 0x30 + <1-byte> + 0x02 + 0x01 + <byte> + 0x2 + 0x01 + <byte>
|
||||
const MinSigLen = 8
|
||||
|
||||
func parseSig(sigStr []byte, curve elliptic.Curve, der bool) (*Signature, error) {
|
||||
// Originally this code used encoding/asn1 in order to parse the
|
||||
// signature, but a number of problems were found with this approach.
|
||||
// Despite the fact that signatures are stored as DER, the difference
|
||||
// between go's idea of a bignum (and that they have sign) doesn't agree
|
||||
// with the openssl one (where they do not). The above is true as of
|
||||
// Go 1.1. In the end it was simpler to rewrite the code to explicitly
|
||||
// understand the format which is this:
|
||||
// 0x30 <length of whole message> <0x02> <length of R> <R> 0x2
|
||||
// <length of S> <S>.
|
||||
|
||||
signature := &Signature{}
|
||||
|
||||
if len(sigStr) < MinSigLen {
|
||||
return nil, errors.New("malformed signature: too short")
|
||||
}
|
||||
// 0x30
|
||||
index := 0
|
||||
if sigStr[index] != 0x30 {
|
||||
return nil, errors.New("malformed signature: no header magic")
|
||||
}
|
||||
index++
|
||||
// length of remaining message
|
||||
siglen := sigStr[index]
|
||||
index++
|
||||
|
||||
// siglen should be less than the entire message and greater than
|
||||
// the minimal message size.
|
||||
if int(siglen+2) > len(sigStr) || int(siglen+2) < MinSigLen {
|
||||
return nil, errors.New("malformed signature: bad length")
|
||||
}
|
||||
// trim the slice we're working on so we only look at what matters.
|
||||
sigStr = sigStr[:siglen+2]
|
||||
|
||||
// 0x02
|
||||
if sigStr[index] != 0x02 {
|
||||
return nil,
|
||||
errors.New("malformed signature: no 1st int marker")
|
||||
}
|
||||
index++
|
||||
|
||||
// Length of signature R.
|
||||
rLen := int(sigStr[index])
|
||||
// must be positive, must be able to fit in another 0x2, <len> <s>
|
||||
// hence the -3. We assume that the length must be at least one byte.
|
||||
index++
|
||||
if rLen <= 0 || rLen > len(sigStr)-index-3 {
|
||||
return nil, errors.New("malformed signature: bogus R length")
|
||||
}
|
||||
|
||||
// Then R itself.
|
||||
rBytes := sigStr[index : index+rLen]
|
||||
if der {
|
||||
switch err := canonicalPadding(rBytes); err {
|
||||
case errNegativeValue:
|
||||
return nil, errors.New("signature R is negative")
|
||||
case errExcessivelyPaddedValue:
|
||||
return nil, errors.New("signature R is excessively padded")
|
||||
}
|
||||
}
|
||||
signature.R = new(big.Int).SetBytes(rBytes)
|
||||
index += rLen
|
||||
// 0x02. length already checked in previous if.
|
||||
if sigStr[index] != 0x02 {
|
||||
return nil, errors.New("malformed signature: no 2nd int marker")
|
||||
}
|
||||
index++
|
||||
|
||||
// Length of signature S.
|
||||
sLen := int(sigStr[index])
|
||||
index++
|
||||
// S should be the rest of the string.
|
||||
if sLen <= 0 || sLen > len(sigStr)-index {
|
||||
return nil, errors.New("malformed signature: bogus S length")
|
||||
}
|
||||
|
||||
// Then S itself.
|
||||
sBytes := sigStr[index : index+sLen]
|
||||
if der {
|
||||
switch err := canonicalPadding(sBytes); err {
|
||||
case errNegativeValue:
|
||||
return nil, errors.New("signature S is negative")
|
||||
case errExcessivelyPaddedValue:
|
||||
return nil, errors.New("signature S is excessively padded")
|
||||
}
|
||||
}
|
||||
signature.S = new(big.Int).SetBytes(sBytes)
|
||||
index += sLen
|
||||
|
||||
// sanity check length parsing
|
||||
if index != len(sigStr) {
|
||||
return nil, fmt.Errorf("malformed signature: bad final length %v != %v",
|
||||
index, len(sigStr))
|
||||
}
|
||||
|
||||
// Verify also checks this, but we can be more sure that we parsed
|
||||
// correctly if we verify here too.
|
||||
// FWIW the ecdsa spec states that R and S must be | 1, N - 1 |
|
||||
// but crypto/ecdsa only checks for Sign != 0. Mirror that.
|
||||
if signature.R.Sign() != 1 {
|
||||
return nil, errors.New("signature R isn't 1 or more")
|
||||
}
|
||||
if signature.S.Sign() != 1 {
|
||||
return nil, errors.New("signature S isn't 1 or more")
|
||||
}
|
||||
if signature.R.Cmp(curve.Params().N) >= 0 {
|
||||
return nil, errors.New("signature R is >= curve.N")
|
||||
}
|
||||
if signature.S.Cmp(curve.Params().N) >= 0 {
|
||||
return nil, errors.New("signature S is >= curve.N")
|
||||
}
|
||||
|
||||
return signature, nil
|
||||
}
|
||||
|
||||
// ParseSignature parses a signature in BER format for the curve type `curve'
|
||||
// into a Signature type, perfoming some basic sanity checks. If parsing
|
||||
// according to the more strict DER format is needed, use ParseDERSignature.
|
||||
func ParseSignature(sigStr []byte, curve elliptic.Curve) (*Signature, error) {
|
||||
return parseSig(sigStr, curve, false)
|
||||
}
|
||||
|
||||
// ParseDERSignature parses a signature in DER format for the curve type
|
||||
// `curve` into a Signature type. If parsing according to the less strict
|
||||
// BER format is needed, use ParseSignature.
|
||||
func ParseDERSignature(sigStr []byte, curve elliptic.Curve) (*Signature, error) {
|
||||
return parseSig(sigStr, curve, true)
|
||||
}
|
||||
|
||||
// canonicalizeInt returns the bytes for the passed big integer adjusted as
|
||||
// necessary to ensure that a big-endian encoded integer can't possibly be
|
||||
// misinterpreted as a negative number. This can happen when the most
|
||||
// significant bit is set, so it is padded by a leading zero byte in this case.
|
||||
// Also, the returned bytes will have at least a single byte when the passed
|
||||
// value is 0. This is required for DER encoding.
|
||||
func canonicalizeInt(val *big.Int) []byte {
|
||||
b := val.Bytes()
|
||||
if len(b) == 0 {
|
||||
b = []byte{0x00}
|
||||
}
|
||||
if b[0]&0x80 != 0 {
|
||||
paddedBytes := make([]byte, len(b)+1)
|
||||
copy(paddedBytes[1:], b)
|
||||
b = paddedBytes
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// canonicalPadding checks whether a big-endian encoded integer could
|
||||
// possibly be misinterpreted as a negative number (even though OpenSSL
|
||||
// treats all numbers as unsigned), or if there is any unnecessary
|
||||
// leading zero padding.
|
||||
func canonicalPadding(b []byte) error {
|
||||
switch {
|
||||
case b[0]&0x80 == 0x80:
|
||||
return errNegativeValue
|
||||
case len(b) > 1 && b[0] == 0x00 && b[1]&0x80 != 0x80:
|
||||
return errExcessivelyPaddedValue
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// hashToInt converts a hash value to an integer. There is some disagreement
|
||||
// about how this is done. [NSA] suggests that this is done in the obvious
|
||||
// manner, but [SECG] truncates the hash to the bit-length of the curve order
|
||||
// first. We follow [SECG] because that's what OpenSSL does. Additionally,
|
||||
// OpenSSL right shifts excess bits from the number if the hash is too large
|
||||
// and we mirror that too.
|
||||
// This is borrowed from crypto/ecdsa.
|
||||
func hashToInt(hash []byte, c elliptic.Curve) *big.Int {
|
||||
orderBits := c.Params().N.BitLen()
|
||||
orderBytes := (orderBits + 7) / 8
|
||||
if len(hash) > orderBytes {
|
||||
hash = hash[:orderBytes]
|
||||
}
|
||||
|
||||
ret := new(big.Int).SetBytes(hash)
|
||||
excess := len(hash)*8 - orderBits
|
||||
if excess > 0 {
|
||||
ret.Rsh(ret, uint(excess))
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
// recoverKeyFromSignature recovers a public key from the signature "sig" on the
|
||||
// given message hash "msg". Based on the algorithm found in section 5.1.5 of
|
||||
// SEC 1 Ver 2.0, page 47-48 (53 and 54 in the pdf). This performs the details
|
||||
// in the inner loop in Step 1. The counter provided is actually the j parameter
|
||||
// of the loop * 2 - on the first iteration of j we do the R case, else the -R
|
||||
// case in step 1.6. This counter is used in the bitcoin compressed signature
|
||||
// format and thus we match bitcoind's behaviour here.
|
||||
func recoverKeyFromSignature(curve *KoblitzCurve, sig *Signature, msg []byte,
|
||||
iter int, doChecks bool) (*PublicKey, error) {
|
||||
// 1.1 x = (n * i) + r
|
||||
Rx := new(big.Int).Mul(curve.Params().N,
|
||||
new(big.Int).SetInt64(int64(iter/2)))
|
||||
Rx.Add(Rx, sig.R)
|
||||
if Rx.Cmp(curve.Params().P) != -1 {
|
||||
return nil, errors.New("calculated Rx is larger than curve P")
|
||||
}
|
||||
|
||||
// convert 02<Rx> to point R. (step 1.2 and 1.3). If we are on an odd
|
||||
// iteration then 1.6 will be done with -R, so we calculate the other
|
||||
// term when uncompressing the point.
|
||||
Ry, err := decompressPoint(curve, Rx, iter%2 == 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 1.4 Check n*R is point at infinity
|
||||
if doChecks {
|
||||
nRx, nRy := curve.ScalarMult(Rx, Ry, curve.Params().N.Bytes())
|
||||
if nRx.Sign() != 0 || nRy.Sign() != 0 {
|
||||
return nil, errors.New("n*R does not equal the point at infinity")
|
||||
}
|
||||
}
|
||||
|
||||
// 1.5 calculate e from message using the same algorithm as ecdsa
|
||||
// signature calculation.
|
||||
e := hashToInt(msg, curve)
|
||||
|
||||
// Step 1.6.1:
|
||||
// We calculate the two terms sR and eG separately multiplied by the
|
||||
// inverse of r (from the signature). We then add them to calculate
|
||||
// Q = r^-1(sR-eG)
|
||||
invr := new(big.Int).ModInverse(sig.R, curve.Params().N)
|
||||
|
||||
// first term.
|
||||
invrS := new(big.Int).Mul(invr, sig.S)
|
||||
invrS.Mod(invrS, curve.Params().N)
|
||||
sRx, sRy := curve.ScalarMult(Rx, Ry, invrS.Bytes())
|
||||
|
||||
// second term.
|
||||
e.Neg(e)
|
||||
e.Mod(e, curve.Params().N)
|
||||
e.Mul(e, invr)
|
||||
e.Mod(e, curve.Params().N)
|
||||
minuseGx, minuseGy := curve.ScalarBaseMult(e.Bytes())
|
||||
|
||||
// TODO: this would be faster if we did a mult and add in one
|
||||
// step to prevent the jacobian conversion back and forth.
|
||||
Qx, Qy := curve.Add(sRx, sRy, minuseGx, minuseGy)
|
||||
|
||||
return &PublicKey{
|
||||
Curve: curve,
|
||||
X: Qx,
|
||||
Y: Qy,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// SignCompact produces a compact signature of the data in hash with the given
|
||||
// private key on the given koblitz curve. The isCompressed parameter should
|
||||
// be used to detail if the given signature should reference a compressed
|
||||
// public key or not. If successful the bytes of the compact signature will be
|
||||
// returned in the format:
|
||||
// <(byte of 27+public key solution)+4 if compressed >< padded bytes for signature R><padded bytes for signature S>
|
||||
// where the R and S parameters are padde up to the bitlengh of the curve.
|
||||
func SignCompact(curve *KoblitzCurve, key *PrivateKey,
|
||||
hash []byte, isCompressedKey bool) ([]byte, error) {
|
||||
sig, err := key.Sign(hash)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// bitcoind checks the bit length of R and S here. The ecdsa signature
|
||||
// algorithm returns R and S mod N therefore they will be the bitsize of
|
||||
// the curve, and thus correctly sized.
|
||||
for i := 0; i < (curve.H+1)*2; i++ {
|
||||
pk, err := recoverKeyFromSignature(curve, sig, hash, i, true)
|
||||
if err == nil && pk.X.Cmp(key.X) == 0 && pk.Y.Cmp(key.Y) == 0 {
|
||||
result := make([]byte, 1, 2*curve.byteSize+1)
|
||||
result[0] = 27 + byte(i)
|
||||
if isCompressedKey {
|
||||
result[0] += 4
|
||||
}
|
||||
// Not sure this needs rounding but safer to do so.
|
||||
curvelen := (curve.BitSize + 7) / 8
|
||||
|
||||
// Pad R and S to curvelen if needed.
|
||||
bytelen := (sig.R.BitLen() + 7) / 8
|
||||
if bytelen < curvelen {
|
||||
result = append(result,
|
||||
make([]byte, curvelen-bytelen)...)
|
||||
}
|
||||
result = append(result, sig.R.Bytes()...)
|
||||
|
||||
bytelen = (sig.S.BitLen() + 7) / 8
|
||||
if bytelen < curvelen {
|
||||
result = append(result,
|
||||
make([]byte, curvelen-bytelen)...)
|
||||
}
|
||||
result = append(result, sig.S.Bytes()...)
|
||||
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, errors.New("no valid solution for pubkey found")
|
||||
}
|
||||
|
||||
// RecoverCompact verifies the compact signature "signature" of "hash" for the
|
||||
// Koblitz curve in "curve". If the signature matches then the recovered public
|
||||
// key will be returned as well as a boolen if the original key was compressed
|
||||
// or not, else an error will be returned.
|
||||
func RecoverCompact(curve *KoblitzCurve, signature,
|
||||
hash []byte) (*PublicKey, bool, error) {
|
||||
bitlen := (curve.BitSize + 7) / 8
|
||||
if len(signature) != 1+bitlen*2 {
|
||||
return nil, false, errors.New("invalid compact signature size")
|
||||
}
|
||||
|
||||
iteration := int((signature[0] - 27) & ^byte(4))
|
||||
|
||||
// format is <header byte><bitlen R><bitlen S>
|
||||
sig := &Signature{
|
||||
R: new(big.Int).SetBytes(signature[1 : bitlen+1]),
|
||||
S: new(big.Int).SetBytes(signature[bitlen+1:]),
|
||||
}
|
||||
// The iteration used here was encoded
|
||||
key, err := recoverKeyFromSignature(curve, sig, hash, iteration, false)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
|
||||
return key, ((signature[0] - 27) & 4) == 4, nil
|
||||
}
|
||||
|
||||
// signRFC6979 generates a deterministic ECDSA signature according to RFC 6979 and BIP 62.
|
||||
func signRFC6979(privateKey *PrivateKey, hash []byte) (*Signature, error) {
|
||||
|
||||
privkey := privateKey.ToECDSA()
|
||||
N := S256().N
|
||||
halfOrder := S256().halfOrder
|
||||
k := nonceRFC6979(privkey.D, hash)
|
||||
inv := new(big.Int).ModInverse(k, N)
|
||||
r, _ := privkey.Curve.ScalarBaseMult(k.Bytes())
|
||||
r.Mod(r, N)
|
||||
|
||||
if r.Sign() == 0 {
|
||||
return nil, errors.New("calculated R is zero")
|
||||
}
|
||||
|
||||
e := hashToInt(hash, privkey.Curve)
|
||||
s := new(big.Int).Mul(privkey.D, r)
|
||||
s.Add(s, e)
|
||||
s.Mul(s, inv)
|
||||
s.Mod(s, N)
|
||||
|
||||
if s.Cmp(halfOrder) == 1 {
|
||||
s.Sub(N, s)
|
||||
}
|
||||
if s.Sign() == 0 {
|
||||
return nil, errors.New("calculated S is zero")
|
||||
}
|
||||
return &Signature{R: r, S: s}, nil
|
||||
}
|
||||
|
||||
// nonceRFC6979 generates an ECDSA nonce (`k`) deterministically according to RFC 6979.
|
||||
// It takes a 32-byte hash as an input and returns 32-byte nonce to be used in ECDSA algorithm.
|
||||
func nonceRFC6979(privkey *big.Int, hash []byte) *big.Int {
|
||||
|
||||
curve := S256()
|
||||
q := curve.Params().N
|
||||
x := privkey
|
||||
alg := sha256.New
|
||||
|
||||
qlen := q.BitLen()
|
||||
holen := alg().Size()
|
||||
rolen := (qlen + 7) >> 3
|
||||
bx := append(int2octets(x, rolen), bits2octets(hash, curve, rolen)...)
|
||||
|
||||
// Step B
|
||||
v := bytes.Repeat(oneInitializer, holen)
|
||||
|
||||
// Step C (Go zeroes the all allocated memory)
|
||||
k := make([]byte, holen)
|
||||
|
||||
// Step D
|
||||
k = mac(alg, k, append(append(v, 0x00), bx...))
|
||||
|
||||
// Step E
|
||||
v = mac(alg, k, v)
|
||||
|
||||
// Step F
|
||||
k = mac(alg, k, append(append(v, 0x01), bx...))
|
||||
|
||||
// Step G
|
||||
v = mac(alg, k, v)
|
||||
|
||||
// Step H
|
||||
for {
|
||||
// Step H1
|
||||
var t []byte
|
||||
|
||||
// Step H2
|
||||
for len(t)*8 < qlen {
|
||||
v = mac(alg, k, v)
|
||||
t = append(t, v...)
|
||||
}
|
||||
|
||||
// Step H3
|
||||
secret := hashToInt(t, curve)
|
||||
if secret.Cmp(one) >= 0 && secret.Cmp(q) < 0 {
|
||||
return secret
|
||||
}
|
||||
k = mac(alg, k, append(v, 0x00))
|
||||
v = mac(alg, k, v)
|
||||
}
|
||||
}
|
||||
|
||||
// mac returns an HMAC of the given key and message.
|
||||
func mac(alg func() hash.Hash, k, m []byte) []byte {
|
||||
h := hmac.New(alg, k)
|
||||
h.Write(m)
|
||||
return h.Sum(nil)
|
||||
}
|
||||
|
||||
// https://tools.ietf.org/html/rfc6979#section-2.3.3
|
||||
func int2octets(v *big.Int, rolen int) []byte {
|
||||
out := v.Bytes()
|
||||
|
||||
// left pad with zeros if it's too short
|
||||
if len(out) < rolen {
|
||||
out2 := make([]byte, rolen)
|
||||
copy(out2[rolen-len(out):], out)
|
||||
return out2
|
||||
}
|
||||
|
||||
// drop most significant bytes if it's too long
|
||||
if len(out) > rolen {
|
||||
out2 := make([]byte, rolen)
|
||||
copy(out2, out[len(out)-rolen:])
|
||||
return out2
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
// https://tools.ietf.org/html/rfc6979#section-2.3.4
|
||||
func bits2octets(in []byte, curve elliptic.Curve, rolen int) []byte {
|
||||
z1 := hashToInt(in, curve)
|
||||
z2 := new(big.Int).Sub(z1, curve.Params().N)
|
||||
if z2.Sign() < 0 {
|
||||
return int2octets(z1, rolen)
|
||||
}
|
||||
return int2octets(z2, rolen)
|
||||
}
|
2
vendor/github.com/cenkalti/backoff/.gitignore
generated
vendored
2
vendor/github.com/cenkalti/backoff/.gitignore
generated
vendored
@ -20,3 +20,5 @@ _cgo_export.*
|
||||
_testmain.go
|
||||
|
||||
*.exe
|
||||
*.bench
|
||||
go.sum
|
3
vendor/github.com/cenkalti/backoff/go.mod
generated
vendored
Normal file
3
vendor/github.com/cenkalti/backoff/go.mod
generated
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
module github.com/cenkalti/backoff/v3
|
||||
|
||||
go 1.12
|
84
vendor/github.com/elastic/gosigar/.appveyor.yml
generated
vendored
Normal file
84
vendor/github.com/elastic/gosigar/.appveyor.yml
generated
vendored
Normal file
@ -0,0 +1,84 @@
|
||||
# Version format
|
||||
version: "{build}"
|
||||
|
||||
# Operating system (build VM template)
|
||||
os: Windows Server 2012 R2
|
||||
|
||||
# Environment variables
|
||||
environment:
|
||||
GOPATH: c:\gopath
|
||||
GVM_GO_VERSION: 1.8.3
|
||||
GVM_DL: https://github.com/andrewkroh/gvm/releases/download/v0.0.1/gvm-windows-amd64.exe
|
||||
|
||||
# Custom clone folder (variables are not expanded here).
|
||||
clone_folder: c:\gopath\src\github.com\elastic\gosigar
|
||||
|
||||
# Cache mingw install until appveyor.yml is modified.
|
||||
cache:
|
||||
- C:\ProgramData\chocolatey\bin -> .appveyor.yml
|
||||
- C:\ProgramData\chocolatey\lib -> .appveyor.yml
|
||||
- C:\Users\appveyor\.gvm -> .appveyor.yml
|
||||
- C:\Windows\System32\gvm.exe -> .appveyor.yml
|
||||
- C:\tools\mingw64 -> .appveyor.yml
|
||||
|
||||
# Scripts that run after cloning repository
|
||||
install:
|
||||
- ps: >-
|
||||
if(!(Test-Path "C:\Windows\System32\gvm.exe")) {
|
||||
wget "$env:GVM_DL" -Outfile C:\Windows\System32\gvm.exe
|
||||
}
|
||||
- ps: gvm --format=powershell "$env:GVM_GO_VERSION" | Invoke-Expression
|
||||
# AppVeyor installed mingw is 32-bit only so install 64-bit version.
|
||||
- ps: >-
|
||||
if(!(Test-Path "C:\tools\mingw64\bin\gcc.exe")) {
|
||||
cinst mingw > mingw-install.txt
|
||||
Push-AppveyorArtifact mingw-install.txt
|
||||
}
|
||||
- set PATH=C:\tools\mingw64\bin;%GOROOT%\bin;%PATH%
|
||||
- set PATH=%GOPATH%\bin;%PATH%
|
||||
- go version
|
||||
- go env
|
||||
- python --version
|
||||
- go get github.com/elastic/beats/vendor/github.com/pierrre/gotestcover
|
||||
|
||||
# To run your custom scripts instead of automatic MSBuild
|
||||
build_script:
|
||||
# Compile
|
||||
- appveyor AddCompilationMessage "Starting Compile"
|
||||
- cd c:\gopath\src\github.com\elastic\gosigar
|
||||
- go get -v -t -d ./...
|
||||
- go build
|
||||
- go build -o examples/df/df.exe ./examples/df
|
||||
- go build -o examples/free/free.exe ./examples/free
|
||||
- go build -o examples/ps/ps.exe ./examples/ps
|
||||
- go build -o examples/uptime/uptime.exe ./examples/uptime
|
||||
- appveyor AddCompilationMessage "Compile Success"
|
||||
|
||||
# To run your custom scripts instead of automatic tests
|
||||
test_script:
|
||||
# Unit tests
|
||||
- ps: Add-AppveyorTest "Unit Tests" -Outcome Running
|
||||
- mkdir build\coverage
|
||||
- gotestcover -v -coverprofile=build/coverage/unit.cov github.com/elastic/gosigar/...
|
||||
- ps: Update-AppveyorTest "Unit Tests" -Outcome Passed
|
||||
- ps: Add-AppveyorTest "Running Examples" -Outcome Running
|
||||
- .\examples\df\df.exe
|
||||
- .\examples\free\free.exe
|
||||
- .\examples\ps\ps.exe
|
||||
- .\examples\uptime\uptime.exe
|
||||
- ps: Update-AppveyorTest "Running Examples" -Outcome Passed
|
||||
|
||||
after_test:
|
||||
- go tool cover -html=build\coverage\unit.cov -o build\coverage\unit.html
|
||||
- ps: Push-AppveyorArtifact build\coverage\unit.cov
|
||||
- ps: Push-AppveyorArtifact build\coverage\unit.html
|
||||
# Upload coverage report.
|
||||
- "SET PATH=C:\\Python34;C:\\Python34\\Scripts;%PATH%"
|
||||
- pip install codecov
|
||||
- codecov -X gcov -f "build\coverage\unit.cov"
|
||||
|
||||
# To disable deployment
|
||||
deploy: off
|
||||
|
||||
# Notifications should only be setup using the AppVeyor UI so that
|
||||
# forks can be created without inheriting the settings.
|
41
vendor/github.com/elastic/gosigar/.gitignore
generated
vendored
Normal file
41
vendor/github.com/elastic/gosigar/.gitignore
generated
vendored
Normal file
@ -0,0 +1,41 @@
|
||||
# Directories
|
||||
/.vagrant
|
||||
/.idea
|
||||
/build
|
||||
|
||||
# Files
|
||||
.DS_Store
|
||||
/*.iml
|
||||
*.h
|
||||
|
||||
# Editor swap files
|
||||
*.swp
|
||||
*.swo
|
||||
*.swn
|
||||
|
||||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
*.exe
|
||||
*.test
|
||||
*.prof
|
||||
*.pyc
|
||||
*.swp
|
||||
|
||||
# Example binaries
|
||||
examples/df/df
|
||||
examples/df/df.exe
|
||||
examples/free/free
|
||||
examples/free/free.exe
|
||||
examples/ps/ps
|
||||
examples/ps/ps.exe
|
||||
examples/ss/ss
|
||||
examples/ss/ss.exe
|
||||
examples/uptime/uptime
|
||||
examples/uptime/uptime.exe
|
||||
|
||||
# Test Data
|
||||
cgroup/testdata/*
|
||||
!cgroup/testdata/*.zip
|
||||
|
37
vendor/github.com/elastic/gosigar/.travis.yml
generated
vendored
Normal file
37
vendor/github.com/elastic/gosigar/.travis.yml
generated
vendored
Normal file
@ -0,0 +1,37 @@
|
||||
language: go
|
||||
|
||||
os:
|
||||
- linux
|
||||
- osx
|
||||
|
||||
go:
|
||||
- 1.8.x
|
||||
- 1.10.x
|
||||
|
||||
env:
|
||||
global:
|
||||
- PROJ="github.com/elastic/gosigar"
|
||||
|
||||
sudo: false
|
||||
|
||||
before_install:
|
||||
# Put project into proper GOPATH location (important for forks).
|
||||
- mkdir -p $HOME/gopath/src/${PROJ}
|
||||
- rsync -az ${TRAVIS_BUILD_DIR}/ $HOME/gopath/src/${PROJ}/
|
||||
- export TRAVIS_BUILD_DIR=$HOME/gopath/src/${PROJ}
|
||||
- cd $HOME/gopath/src/${PROJ}
|
||||
|
||||
install:
|
||||
- go get -v -t -d ./...
|
||||
- go get github.com/elastic/beats/vendor/github.com/pierrre/gotestcover
|
||||
|
||||
script:
|
||||
- gofmt -l . | read && echo "Code differs from gofmt's style. Run 'gofmt -w .'" 1>&2 && exit 1 || true
|
||||
- go vet
|
||||
- go build
|
||||
- mkdir -p build/coverage
|
||||
- gotestcover -v -coverprofile=build/coverage/unit.cov github.com/elastic/gosigar/...
|
||||
- for i in $(ls examples); do go build -o examples/$i/$i ./examples/$i; ./examples/$i/$i; done
|
||||
|
||||
after_success:
|
||||
- bash <(curl -s https://codecov.io/bash) -f build/coverage/unit.cov
|
135
vendor/github.com/elastic/gosigar/CHANGELOG.md
generated
vendored
Normal file
135
vendor/github.com/elastic/gosigar/CHANGELOG.md
generated
vendored
Normal file
@ -0,0 +1,135 @@
|
||||
# Change Log
|
||||
All notable changes to this project will be documented in this file.
|
||||
This project adheres to [Semantic Versioning](http://semver.org/).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
### Fixed
|
||||
|
||||
### Changed
|
||||
|
||||
### Deprecated
|
||||
|
||||
## [0.10.3]
|
||||
|
||||
### Fixed
|
||||
- ProcState.Get() doesn't fail under Windows when it cannot obtain process ownership information. #121
|
||||
|
||||
## [0.10.2]
|
||||
|
||||
### Fixed
|
||||
- Fix memory leak when getting process arguments. #119
|
||||
|
||||
## [0.10.1]
|
||||
|
||||
### Fixed
|
||||
- Replaced the WMI queries with win32 apis due to high CPU usage. #116
|
||||
|
||||
## [0.10.0]
|
||||
|
||||
### Added
|
||||
- List filesystems on Windows that have an access path but not an assigned letter. #112
|
||||
|
||||
### Fixed
|
||||
- Added missing runtime import for FreeBSD. #104
|
||||
- Handle nil command line in Windows processes. #110
|
||||
|
||||
## [0.9.0]
|
||||
|
||||
### Added
|
||||
- Added support for huge TLB pages on Linux #97
|
||||
- Added support for big endian platform #100
|
||||
|
||||
### Fixed
|
||||
- Add missing method for OpenBSD #99
|
||||
|
||||
## [0.8.0]
|
||||
|
||||
### Added
|
||||
- Added partial `getrusage` support for Windows to retrieve system CPU time and user CPU time. #95
|
||||
- Added full `getrusage` support for Unix. #95
|
||||
|
||||
## [0.7.0]
|
||||
|
||||
### Added
|
||||
- Added method stubs for process handling for operating system that are not supported
|
||||
by gosigar. All methods return `ErrNotImplemented` on such systems. #88
|
||||
|
||||
### Fixed
|
||||
- Fix freebsd build by using the common version of Get(pid). #91
|
||||
|
||||
### Changed
|
||||
- Fixed issues in cgroup package by adding missing error checks and closing
|
||||
file handles. #92
|
||||
|
||||
## [0.6.0]
|
||||
|
||||
### Added
|
||||
- Added method stubs to enable compilation for operating systems that are not
|
||||
supported by gosigar. All methods return `ErrNotImplemented` on these unsupported
|
||||
operating systems. #83
|
||||
- FreeBSD returns `ErrNotImplemented` for `ProcTime.Get`. #83
|
||||
|
||||
### Changed
|
||||
- OpenBSD returns `ErrNotImplemented` for `ProcTime.Get` instead of `nil`. #83
|
||||
- Fixed incorrect `Mem.Used` calculation under linux. #82
|
||||
- Fixed `ProcState` on Linux and FreeBSD when process names contain parentheses. #81
|
||||
|
||||
### Removed
|
||||
- Remove NetBSD build from sigar_unix.go as it is not supported by gosigar. #83
|
||||
|
||||
## [0.5.0]
|
||||
|
||||
### Changed
|
||||
- Fixed Trim environment variables when comparing values in the test suite. #79
|
||||
- Make `kern_procargs` more robust under darwin when we cannot retrieve
|
||||
all the information about a process. #78
|
||||
|
||||
## [0.4.0]
|
||||
|
||||
### Changed
|
||||
- Fixed Windows issue that caused a hang during `init()` if WMI wasn't ready. #74
|
||||
|
||||
## [0.3.0]
|
||||
|
||||
### Added
|
||||
- Read `MemAvailable` value for kernel 3.14+ #71
|
||||
|
||||
## [0.2.0]
|
||||
|
||||
### Added
|
||||
- Added `ErrCgroupsMissing` to indicate that /proc/cgroups is missing which is
|
||||
an indicator that cgroups were disabled at compile time. #64
|
||||
|
||||
### Changed
|
||||
- Changed `cgroup.SupportedSubsystems()` to honor the "enabled" column in the
|
||||
/proc/cgroups file. #64
|
||||
|
||||
## [0.1.0]
|
||||
|
||||
### Added
|
||||
- Added `CpuList` implementation for Windows that returns CPU timing information
|
||||
on a per CPU basis. #55
|
||||
- Added `Uptime` implementation for Windows. #55
|
||||
- Added `Swap` implementation for Windows based on page file metrics. #55
|
||||
- Added support to `github.com/gosigar/sys/windows` for querying and enabling
|
||||
privileges in a process token.
|
||||
- Added utility code for interfacing with linux NETLINK_INET_DIAG. #60
|
||||
- Added `ProcEnv` for getting a process's environment variables. #61
|
||||
|
||||
### Changed
|
||||
- Changed several `OpenProcess` calls on Windows to request the lowest possible
|
||||
access privileges. #50
|
||||
- Removed cgo usage from Windows code.
|
||||
- Added OS version checks to `ProcArgs.Get` on Windows because the
|
||||
`Win32_Process` WMI query is not available prior to Windows vista. On XP and
|
||||
Windows 2003, this method returns `ErrNotImplemented`. #55
|
||||
|
||||
### Fixed
|
||||
- Fixed value of `Mem.ActualFree` and `Mem.ActualUsed` on Windows. #49
|
||||
- Fixed `ProcTime.StartTime` on Windows to report value in milliseconds since
|
||||
Unix epoch. #51
|
||||
- Fixed `ProcStatus.PPID` value is wrong on Windows. #55
|
||||
- Fixed `ProcStatus.Username` error on Windows XP #56
|
201
vendor/github.com/elastic/gosigar/LICENSE
generated
vendored
Normal file
201
vendor/github.com/elastic/gosigar/LICENSE
generated
vendored
Normal file
@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
9
vendor/github.com/elastic/gosigar/NOTICE
generated
vendored
Normal file
9
vendor/github.com/elastic/gosigar/NOTICE
generated
vendored
Normal file
@ -0,0 +1,9 @@
|
||||
Copyright (c) [2009-2011] VMware, Inc. All Rights Reserved.
|
||||
|
||||
This product is licensed to you under the Apache License, Version 2.0 (the "License").
|
||||
You may not use this product except in compliance with the License.
|
||||
|
||||
This product includes a number of subcomponents with
|
||||
separate copyright notices and license terms. Your use of these
|
||||
subcomponents is subject to the terms and conditions of the
|
||||
subcomponent's license, as noted in the LICENSE file.
|
58
vendor/github.com/elastic/gosigar/README.md
generated
vendored
Normal file
58
vendor/github.com/elastic/gosigar/README.md
generated
vendored
Normal file
@ -0,0 +1,58 @@
|
||||
# Go sigar [](https://travis-ci.org/elastic/gosigar) [](https://ci.appveyor.com/project/elastic-beats/gosigar/branch/master)
|
||||
|
||||
|
||||
## Overview
|
||||
|
||||
Go sigar is a golang implementation of the
|
||||
[sigar API](https://github.com/hyperic/sigar). The Go version of
|
||||
sigar has a very similar interface, but is being written from scratch
|
||||
in pure go/cgo, rather than cgo bindings for libsigar.
|
||||
|
||||
## Test drive
|
||||
|
||||
$ go get github.com/elastic/gosigar
|
||||
$ cd $GOPATH/src/github.com/elastic/gosigar/examples/ps
|
||||
$ go build
|
||||
$ ./ps
|
||||
|
||||
## Supported platforms
|
||||
|
||||
The features vary by operating system.
|
||||
|
||||
| Feature | Linux | Darwin | Windows | OpenBSD | FreeBSD |
|
||||
|-----------------|:-----:|:------:|:-------:|:-------:|:-------:|
|
||||
| Cpu | X | X | X | X | X |
|
||||
| CpuList | X | X | | X | X |
|
||||
| FDUsage | X | | | | X |
|
||||
| FileSystemList | X | X | X | X | X |
|
||||
| FileSystemUsage | X | X | X | X | X |
|
||||
| HugeTLBPages | X | | | | |
|
||||
| LoadAverage | X | X | | X | X |
|
||||
| Mem | X | X | X | X | X |
|
||||
| ProcArgs | X | X | X | | X |
|
||||
| ProcEnv | X | X | | | X |
|
||||
| ProcExe | X | X | | | X |
|
||||
| ProcFDUsage | X | | | | X |
|
||||
| ProcList | X | X | X | | X |
|
||||
| ProcMem | X | X | X | | X |
|
||||
| ProcState | X | X | X | | X |
|
||||
| ProcTime | X | X | X | | X |
|
||||
| Swap | X | X | | X | X |
|
||||
| Uptime | X | X | | X | X |
|
||||
|
||||
## OS Specific Notes
|
||||
|
||||
### FreeBSD
|
||||
|
||||
Mount both `linprocfs` and `procfs` for compatability. Consider adding these
|
||||
mounts to your `/etc/fstab` file so they are mounted automatically at boot.
|
||||
|
||||
```
|
||||
sudo mount -t procfs proc /proc
|
||||
sudo mkdir -p /compat/linux/proc
|
||||
sudo mount -t linprocfs /dev/null /compat/linux/proc
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
Apache 2.0
|
21
vendor/github.com/elastic/gosigar/codecov.yml
generated
vendored
Normal file
21
vendor/github.com/elastic/gosigar/codecov.yml
generated
vendored
Normal file
@ -0,0 +1,21 @@
|
||||
# Enable coverage report message for diff on commit
|
||||
coverage:
|
||||
status:
|
||||
project: off
|
||||
patch:
|
||||
default:
|
||||
# basic
|
||||
target: auto
|
||||
threshold: null
|
||||
base: auto
|
||||
# advanced
|
||||
branches: null
|
||||
if_no_uploads: error
|
||||
if_not_found: success
|
||||
if_ci_failed: error
|
||||
only_pulls: false
|
||||
flags: null
|
||||
paths: null
|
||||
|
||||
# Disable comments on Pull Requests
|
||||
comment: false
|
89
vendor/github.com/elastic/gosigar/concrete_sigar.go
generated
vendored
Normal file
89
vendor/github.com/elastic/gosigar/concrete_sigar.go
generated
vendored
Normal file
@ -0,0 +1,89 @@
|
||||
package gosigar
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type ConcreteSigar struct{}
|
||||
|
||||
func (c *ConcreteSigar) CollectCpuStats(collectionInterval time.Duration) (<-chan Cpu, chan<- struct{}) {
|
||||
// samplesCh is buffered to 1 value to immediately return first CPU sample
|
||||
samplesCh := make(chan Cpu, 1)
|
||||
|
||||
stopCh := make(chan struct{})
|
||||
|
||||
go func() {
|
||||
var cpuUsage Cpu
|
||||
|
||||
// Immediately provide non-delta value.
|
||||
// samplesCh is buffered to 1 value, so it will not block.
|
||||
cpuUsage.Get()
|
||||
samplesCh <- cpuUsage
|
||||
|
||||
ticker := time.NewTicker(collectionInterval)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
previousCpuUsage := cpuUsage
|
||||
|
||||
cpuUsage.Get()
|
||||
|
||||
select {
|
||||
case samplesCh <- cpuUsage.Delta(previousCpuUsage):
|
||||
default:
|
||||
// Include default to avoid channel blocking
|
||||
}
|
||||
|
||||
case <-stopCh:
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return samplesCh, stopCh
|
||||
}
|
||||
|
||||
func (c *ConcreteSigar) GetLoadAverage() (LoadAverage, error) {
|
||||
l := LoadAverage{}
|
||||
err := l.Get()
|
||||
return l, err
|
||||
}
|
||||
|
||||
func (c *ConcreteSigar) GetMem() (Mem, error) {
|
||||
m := Mem{}
|
||||
err := m.Get()
|
||||
return m, err
|
||||
}
|
||||
|
||||
func (c *ConcreteSigar) GetSwap() (Swap, error) {
|
||||
s := Swap{}
|
||||
err := s.Get()
|
||||
return s, err
|
||||
}
|
||||
|
||||
func (c *ConcreteSigar) GetHugeTLBPages() (HugeTLBPages, error) {
|
||||
p := HugeTLBPages{}
|
||||
err := p.Get()
|
||||
return p, err
|
||||
}
|
||||
|
||||
func (c *ConcreteSigar) GetFileSystemUsage(path string) (FileSystemUsage, error) {
|
||||
f := FileSystemUsage{}
|
||||
err := f.Get(path)
|
||||
return f, err
|
||||
}
|
||||
|
||||
func (c *ConcreteSigar) GetFDUsage() (FDUsage, error) {
|
||||
fd := FDUsage{}
|
||||
err := fd.Get()
|
||||
return fd, err
|
||||
}
|
||||
|
||||
// GetRusage return the resource usage of the process
|
||||
// Possible params: 0 = RUSAGE_SELF, 1 = RUSAGE_CHILDREN, 2 = RUSAGE_THREAD
|
||||
func (c *ConcreteSigar) GetRusage(who int) (Rusage, error) {
|
||||
r := Rusage{}
|
||||
err := r.Get(who)
|
||||
return r, err
|
||||
}
|
498
vendor/github.com/elastic/gosigar/sigar_darwin.go
generated
vendored
Normal file
498
vendor/github.com/elastic/gosigar/sigar_darwin.go
generated
vendored
Normal file
@ -0,0 +1,498 @@
|
||||
// Copyright (c) 2012 VMware, Inc.
|
||||
|
||||
package gosigar
|
||||
|
||||
/*
|
||||
#include <stdlib.h>
|
||||
#include <sys/sysctl.h>
|
||||
#include <sys/mount.h>
|
||||
#include <mach/mach_init.h>
|
||||
#include <mach/mach_host.h>
|
||||
#include <mach/host_info.h>
|
||||
#include <libproc.h>
|
||||
#include <mach/processor_info.h>
|
||||
#include <mach/vm_map.h>
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"os/user"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func (self *LoadAverage) Get() error {
|
||||
avg := []C.double{0, 0, 0}
|
||||
|
||||
C.getloadavg(&avg[0], C.int(len(avg)))
|
||||
|
||||
self.One = float64(avg[0])
|
||||
self.Five = float64(avg[1])
|
||||
self.Fifteen = float64(avg[2])
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Uptime) Get() error {
|
||||
tv := syscall.Timeval32{}
|
||||
|
||||
if err := sysctlbyname("kern.boottime", &tv); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
self.Length = time.Since(time.Unix(int64(tv.Sec), int64(tv.Usec)*1000)).Seconds()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Mem) Get() error {
|
||||
var vmstat C.vm_statistics_data_t
|
||||
|
||||
if err := sysctlbyname("hw.memsize", &self.Total); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := vm_info(&vmstat); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
kern := uint64(vmstat.inactive_count) << 12
|
||||
self.Free = uint64(vmstat.free_count) << 12
|
||||
|
||||
self.Used = self.Total - self.Free
|
||||
self.ActualFree = self.Free + kern
|
||||
self.ActualUsed = self.Used - kern
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type xsw_usage struct {
|
||||
Total, Avail, Used uint64
|
||||
}
|
||||
|
||||
func (self *Swap) Get() error {
|
||||
sw_usage := xsw_usage{}
|
||||
|
||||
if err := sysctlbyname("vm.swapusage", &sw_usage); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
self.Total = sw_usage.Total
|
||||
self.Used = sw_usage.Used
|
||||
self.Free = sw_usage.Avail
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *HugeTLBPages) Get() error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (self *Cpu) Get() error {
|
||||
var count C.mach_msg_type_number_t = C.HOST_CPU_LOAD_INFO_COUNT
|
||||
var cpuload C.host_cpu_load_info_data_t
|
||||
|
||||
status := C.host_statistics(C.host_t(C.mach_host_self()),
|
||||
C.HOST_CPU_LOAD_INFO,
|
||||
C.host_info_t(unsafe.Pointer(&cpuload)),
|
||||
&count)
|
||||
|
||||
if status != C.KERN_SUCCESS {
|
||||
return fmt.Errorf("host_statistics error=%d", status)
|
||||
}
|
||||
|
||||
self.User = uint64(cpuload.cpu_ticks[C.CPU_STATE_USER])
|
||||
self.Sys = uint64(cpuload.cpu_ticks[C.CPU_STATE_SYSTEM])
|
||||
self.Idle = uint64(cpuload.cpu_ticks[C.CPU_STATE_IDLE])
|
||||
self.Nice = uint64(cpuload.cpu_ticks[C.CPU_STATE_NICE])
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *CpuList) Get() error {
|
||||
var count C.mach_msg_type_number_t
|
||||
var cpuload *C.processor_cpu_load_info_data_t
|
||||
var ncpu C.natural_t
|
||||
|
||||
status := C.host_processor_info(C.host_t(C.mach_host_self()),
|
||||
C.PROCESSOR_CPU_LOAD_INFO,
|
||||
&ncpu,
|
||||
(*C.processor_info_array_t)(unsafe.Pointer(&cpuload)),
|
||||
&count)
|
||||
|
||||
if status != C.KERN_SUCCESS {
|
||||
return fmt.Errorf("host_processor_info error=%d", status)
|
||||
}
|
||||
|
||||
// jump through some cgo casting hoops and ensure we properly free
|
||||
// the memory that cpuload points to
|
||||
target := C.vm_map_t(C.mach_task_self_)
|
||||
address := C.vm_address_t(uintptr(unsafe.Pointer(cpuload)))
|
||||
defer C.vm_deallocate(target, address, C.vm_size_t(ncpu))
|
||||
|
||||
// the body of struct processor_cpu_load_info
|
||||
// aka processor_cpu_load_info_data_t
|
||||
var cpu_ticks [C.CPU_STATE_MAX]uint32
|
||||
|
||||
// copy the cpuload array to a []byte buffer
|
||||
// where we can binary.Read the data
|
||||
size := int(ncpu) * binary.Size(cpu_ticks)
|
||||
buf := C.GoBytes(unsafe.Pointer(cpuload), C.int(size))
|
||||
|
||||
bbuf := bytes.NewBuffer(buf)
|
||||
|
||||
self.List = make([]Cpu, 0, ncpu)
|
||||
|
||||
for i := 0; i < int(ncpu); i++ {
|
||||
cpu := Cpu{}
|
||||
|
||||
err := binary.Read(bbuf, binary.LittleEndian, &cpu_ticks)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cpu.User = uint64(cpu_ticks[C.CPU_STATE_USER])
|
||||
cpu.Sys = uint64(cpu_ticks[C.CPU_STATE_SYSTEM])
|
||||
cpu.Idle = uint64(cpu_ticks[C.CPU_STATE_IDLE])
|
||||
cpu.Nice = uint64(cpu_ticks[C.CPU_STATE_NICE])
|
||||
|
||||
self.List = append(self.List, cpu)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *FDUsage) Get() error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (self *FileSystemList) Get() error {
|
||||
num, err := syscall.Getfsstat(nil, C.MNT_NOWAIT)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
buf := make([]syscall.Statfs_t, num)
|
||||
|
||||
_, err = syscall.Getfsstat(buf, C.MNT_NOWAIT)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fslist := make([]FileSystem, 0, num)
|
||||
|
||||
for i := 0; i < num; i++ {
|
||||
fs := FileSystem{}
|
||||
|
||||
fs.DirName = bytePtrToString(&buf[i].Mntonname[0])
|
||||
fs.DevName = bytePtrToString(&buf[i].Mntfromname[0])
|
||||
fs.SysTypeName = bytePtrToString(&buf[i].Fstypename[0])
|
||||
|
||||
fslist = append(fslist, fs)
|
||||
}
|
||||
|
||||
self.List = fslist
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (self *ProcList) Get() error {
|
||||
n := C.proc_listpids(C.PROC_ALL_PIDS, 0, nil, 0)
|
||||
if n <= 0 {
|
||||
return syscall.EINVAL
|
||||
}
|
||||
buf := make([]byte, n)
|
||||
n = C.proc_listpids(C.PROC_ALL_PIDS, 0, unsafe.Pointer(&buf[0]), n)
|
||||
if n <= 0 {
|
||||
return syscall.ENOMEM
|
||||
}
|
||||
|
||||
var pid int32
|
||||
num := int(n) / binary.Size(pid)
|
||||
list := make([]int, 0, num)
|
||||
bbuf := bytes.NewBuffer(buf)
|
||||
|
||||
for i := 0; i < num; i++ {
|
||||
if err := binary.Read(bbuf, binary.LittleEndian, &pid); err != nil {
|
||||
return err
|
||||
}
|
||||
if pid == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
list = append(list, int(pid))
|
||||
}
|
||||
|
||||
self.List = list
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ProcState) Get(pid int) error {
|
||||
info := C.struct_proc_taskallinfo{}
|
||||
|
||||
if err := task_info(pid, &info); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
self.Name = C.GoString(&info.pbsd.pbi_comm[0])
|
||||
|
||||
switch info.pbsd.pbi_status {
|
||||
case C.SIDL:
|
||||
self.State = RunStateIdle
|
||||
case C.SRUN:
|
||||
self.State = RunStateRun
|
||||
case C.SSLEEP:
|
||||
self.State = RunStateSleep
|
||||
case C.SSTOP:
|
||||
self.State = RunStateStop
|
||||
case C.SZOMB:
|
||||
self.State = RunStateZombie
|
||||
default:
|
||||
self.State = RunStateUnknown
|
||||
}
|
||||
|
||||
self.Ppid = int(info.pbsd.pbi_ppid)
|
||||
|
||||
self.Pgid = int(info.pbsd.pbi_pgid)
|
||||
|
||||
self.Tty = int(info.pbsd.e_tdev)
|
||||
|
||||
self.Priority = int(info.ptinfo.pti_priority)
|
||||
|
||||
self.Nice = int(info.pbsd.pbi_nice)
|
||||
|
||||
// Get process username. Fallback to UID if username is not available.
|
||||
uid := strconv.Itoa(int(info.pbsd.pbi_uid))
|
||||
user, err := user.LookupId(uid)
|
||||
if err == nil && user.Username != "" {
|
||||
self.Username = user.Username
|
||||
} else {
|
||||
self.Username = uid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ProcMem) Get(pid int) error {
|
||||
info := C.struct_proc_taskallinfo{}
|
||||
|
||||
if err := task_info(pid, &info); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
self.Size = uint64(info.ptinfo.pti_virtual_size)
|
||||
self.Resident = uint64(info.ptinfo.pti_resident_size)
|
||||
self.PageFaults = uint64(info.ptinfo.pti_faults)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ProcTime) Get(pid int) error {
|
||||
info := C.struct_proc_taskallinfo{}
|
||||
|
||||
if err := task_info(pid, &info); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
self.User =
|
||||
uint64(info.ptinfo.pti_total_user) / uint64(time.Millisecond)
|
||||
|
||||
self.Sys =
|
||||
uint64(info.ptinfo.pti_total_system) / uint64(time.Millisecond)
|
||||
|
||||
self.Total = self.User + self.Sys
|
||||
|
||||
self.StartTime = (uint64(info.pbsd.pbi_start_tvsec) * 1000) +
|
||||
(uint64(info.pbsd.pbi_start_tvusec) / 1000)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ProcArgs) Get(pid int) error {
|
||||
var args []string
|
||||
|
||||
argv := func(arg string) {
|
||||
args = append(args, arg)
|
||||
}
|
||||
|
||||
err := kern_procargs(pid, nil, argv, nil)
|
||||
|
||||
self.List = args
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (self *ProcEnv) Get(pid int) error {
|
||||
if self.Vars == nil {
|
||||
self.Vars = map[string]string{}
|
||||
}
|
||||
|
||||
env := func(k, v string) {
|
||||
self.Vars[k] = v
|
||||
}
|
||||
|
||||
return kern_procargs(pid, nil, nil, env)
|
||||
}
|
||||
|
||||
func (self *ProcExe) Get(pid int) error {
|
||||
exe := func(arg string) {
|
||||
self.Name = arg
|
||||
}
|
||||
|
||||
return kern_procargs(pid, exe, nil, nil)
|
||||
}
|
||||
|
||||
func (self *ProcFDUsage) Get(pid int) error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
// wrapper around sysctl KERN_PROCARGS2
|
||||
// callbacks params are optional,
|
||||
// up to the caller as to which pieces of data they want
|
||||
func kern_procargs(pid int,
|
||||
exe func(string),
|
||||
argv func(string),
|
||||
env func(string, string)) error {
|
||||
|
||||
mib := []C.int{C.CTL_KERN, C.KERN_PROCARGS2, C.int(pid)}
|
||||
argmax := uintptr(C.ARG_MAX)
|
||||
buf := make([]byte, argmax)
|
||||
err := sysctl(mib, &buf[0], &argmax, nil, 0)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
bbuf := bytes.NewBuffer(buf)
|
||||
bbuf.Truncate(int(argmax))
|
||||
|
||||
var argc int32
|
||||
binary.Read(bbuf, binary.LittleEndian, &argc)
|
||||
|
||||
path, err := bbuf.ReadBytes(0)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error reading the argv[0]: %v", err)
|
||||
}
|
||||
if exe != nil {
|
||||
exe(string(chop(path)))
|
||||
}
|
||||
|
||||
// skip trailing \0's
|
||||
for {
|
||||
c, err := bbuf.ReadByte()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error skipping nils: %v", err)
|
||||
}
|
||||
if c != 0 {
|
||||
bbuf.UnreadByte()
|
||||
break // start of argv[0]
|
||||
}
|
||||
}
|
||||
|
||||
for i := 0; i < int(argc); i++ {
|
||||
arg, err := bbuf.ReadBytes(0)
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error reading args: %v", err)
|
||||
}
|
||||
if argv != nil {
|
||||
argv(string(chop(arg)))
|
||||
}
|
||||
}
|
||||
|
||||
if env == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
delim := []byte{61} // "="
|
||||
|
||||
for {
|
||||
line, err := bbuf.ReadBytes(0)
|
||||
if err == io.EOF || line[0] == 0 {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error reading args: %v", err)
|
||||
}
|
||||
pair := bytes.SplitN(chop(line), delim, 2)
|
||||
|
||||
if len(pair) != 2 {
|
||||
return fmt.Errorf("Error reading process information for PID: %d", pid)
|
||||
}
|
||||
|
||||
env(string(pair[0]), string(pair[1]))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// XXX copied from zsyscall_darwin_amd64.go
|
||||
func sysctl(mib []C.int, old *byte, oldlen *uintptr,
|
||||
new *byte, newlen uintptr) (err error) {
|
||||
var p0 unsafe.Pointer
|
||||
p0 = unsafe.Pointer(&mib[0])
|
||||
_, _, e1 := syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(p0),
|
||||
uintptr(len(mib)),
|
||||
uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)),
|
||||
uintptr(unsafe.Pointer(new)), uintptr(newlen))
|
||||
if e1 != 0 {
|
||||
err = e1
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func vm_info(vmstat *C.vm_statistics_data_t) error {
|
||||
var count C.mach_msg_type_number_t = C.HOST_VM_INFO_COUNT
|
||||
|
||||
status := C.host_statistics(
|
||||
C.host_t(C.mach_host_self()),
|
||||
C.HOST_VM_INFO,
|
||||
C.host_info_t(unsafe.Pointer(vmstat)),
|
||||
&count)
|
||||
|
||||
if status != C.KERN_SUCCESS {
|
||||
return fmt.Errorf("host_statistics=%d", status)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// generic Sysctl buffer unmarshalling
|
||||
func sysctlbyname(name string, data interface{}) (err error) {
|
||||
val, err := syscall.Sysctl(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
buf := []byte(val)
|
||||
|
||||
switch v := data.(type) {
|
||||
case *uint64:
|
||||
*v = *(*uint64)(unsafe.Pointer(&buf[0]))
|
||||
return
|
||||
}
|
||||
|
||||
bbuf := bytes.NewBuffer([]byte(val))
|
||||
return binary.Read(bbuf, binary.LittleEndian, data)
|
||||
}
|
||||
|
||||
func task_info(pid int, info *C.struct_proc_taskallinfo) error {
|
||||
size := C.int(unsafe.Sizeof(*info))
|
||||
ptr := unsafe.Pointer(info)
|
||||
|
||||
n := C.proc_pidinfo(C.int(pid), C.PROC_PIDTASKALLINFO, 0, ptr, size)
|
||||
if n != size {
|
||||
return fmt.Errorf("Could not read process info for pid %d", pid)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
126
vendor/github.com/elastic/gosigar/sigar_format.go
generated
vendored
Normal file
126
vendor/github.com/elastic/gosigar/sigar_format.go
generated
vendored
Normal file
@ -0,0 +1,126 @@
|
||||
// Copyright (c) 2012 VMware, Inc.
|
||||
|
||||
package gosigar
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Go version of apr_strfsize
|
||||
func FormatSize(size uint64) string {
|
||||
ord := []string{"K", "M", "G", "T", "P", "E"}
|
||||
o := 0
|
||||
buf := new(bytes.Buffer)
|
||||
w := bufio.NewWriter(buf)
|
||||
|
||||
if size < 973 {
|
||||
fmt.Fprintf(w, "%3d ", size)
|
||||
w.Flush()
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
for {
|
||||
remain := size & 1023
|
||||
size >>= 10
|
||||
|
||||
if size >= 973 {
|
||||
o++
|
||||
continue
|
||||
}
|
||||
|
||||
if size < 9 || (size == 9 && remain < 973) {
|
||||
remain = ((remain * 5) + 256) / 512
|
||||
if remain >= 10 {
|
||||
size++
|
||||
remain = 0
|
||||
}
|
||||
|
||||
fmt.Fprintf(w, "%d.%d%s", size, remain, ord[o])
|
||||
break
|
||||
}
|
||||
|
||||
if remain >= 512 {
|
||||
size++
|
||||
}
|
||||
|
||||
fmt.Fprintf(w, "%3d%s", size, ord[o])
|
||||
break
|
||||
}
|
||||
|
||||
w.Flush()
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func FormatPercent(percent float64) string {
|
||||
return strconv.FormatFloat(percent, 'f', -1, 64) + "%"
|
||||
}
|
||||
|
||||
func (self *FileSystemUsage) UsePercent() float64 {
|
||||
b_used := (self.Total - self.Free) / 1024
|
||||
b_avail := self.Avail / 1024
|
||||
utotal := b_used + b_avail
|
||||
used := b_used
|
||||
|
||||
if utotal != 0 {
|
||||
u100 := used * 100
|
||||
pct := u100 / utotal
|
||||
if u100%utotal != 0 {
|
||||
pct += 1
|
||||
}
|
||||
return (float64(pct) / float64(100)) * 100.0
|
||||
}
|
||||
|
||||
return 0.0
|
||||
}
|
||||
|
||||
func (self *Uptime) Format() string {
|
||||
buf := new(bytes.Buffer)
|
||||
w := bufio.NewWriter(buf)
|
||||
uptime := uint64(self.Length)
|
||||
|
||||
days := uptime / (60 * 60 * 24)
|
||||
|
||||
if days != 0 {
|
||||
s := ""
|
||||
if days > 1 {
|
||||
s = "s"
|
||||
}
|
||||
fmt.Fprintf(w, "%d day%s, ", days, s)
|
||||
}
|
||||
|
||||
minutes := uptime / 60
|
||||
hours := minutes / 60
|
||||
hours %= 24
|
||||
minutes %= 60
|
||||
|
||||
fmt.Fprintf(w, "%2d:%02d", hours, minutes)
|
||||
|
||||
w.Flush()
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func (self *ProcTime) FormatStartTime() string {
|
||||
if self.StartTime == 0 {
|
||||
return "00:00"
|
||||
}
|
||||
start := time.Unix(int64(self.StartTime)/1000, 0)
|
||||
format := "Jan02"
|
||||
if time.Since(start).Seconds() < (60 * 60 * 24) {
|
||||
format = "15:04"
|
||||
}
|
||||
return start.Format(format)
|
||||
}
|
||||
|
||||
func (self *ProcTime) FormatTotal() string {
|
||||
t := self.Total / 1000
|
||||
ss := t % 60
|
||||
t /= 60
|
||||
mm := t % 60
|
||||
t /= 60
|
||||
hh := t % 24
|
||||
return fmt.Sprintf("%02d:%02d:%02d", hh, mm, ss)
|
||||
}
|
158
vendor/github.com/elastic/gosigar/sigar_freebsd.go
generated
vendored
Normal file
158
vendor/github.com/elastic/gosigar/sigar_freebsd.go
generated
vendored
Normal file
@ -0,0 +1,158 @@
|
||||
// Copied and modified from sigar_linux.go.
|
||||
|
||||
package gosigar
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
/*
|
||||
#include <sys/param.h>
|
||||
#include <sys/mount.h>
|
||||
#include <sys/ucred.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/sysctl.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
#include <unistd.h>
|
||||
#include <time.h>
|
||||
*/
|
||||
import "C"
|
||||
|
||||
func init() {
|
||||
system.ticks = uint64(C.sysconf(C._SC_CLK_TCK))
|
||||
|
||||
Procd = "/compat/linux/proc"
|
||||
|
||||
getLinuxBootTime()
|
||||
}
|
||||
|
||||
func getMountTableFileName() string {
|
||||
return Procd + "/mtab"
|
||||
}
|
||||
|
||||
func (self *Uptime) Get() error {
|
||||
ts := C.struct_timespec{}
|
||||
|
||||
if _, err := C.clock_gettime(C.CLOCK_UPTIME, &ts); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
self.Length = float64(ts.tv_sec) + 1e-9*float64(ts.tv_nsec)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *FDUsage) Get() error {
|
||||
val := C.uint32_t(0)
|
||||
sc := C.size_t(4)
|
||||
|
||||
name := C.CString("kern.openfiles")
|
||||
_, err := C.sysctlbyname(name, unsafe.Pointer(&val), &sc, nil, 0)
|
||||
C.free(unsafe.Pointer(name))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
self.Open = uint64(val)
|
||||
|
||||
name = C.CString("kern.maxfiles")
|
||||
_, err = C.sysctlbyname(name, unsafe.Pointer(&val), &sc, nil, 0)
|
||||
C.free(unsafe.Pointer(name))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
self.Max = uint64(val)
|
||||
|
||||
self.Unused = self.Max - self.Open
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ProcFDUsage) Get(pid int) error {
|
||||
err := readFile("/proc/"+strconv.Itoa(pid)+"/rlimit", func(line string) bool {
|
||||
if strings.HasPrefix(line, "nofile") {
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) == 3 {
|
||||
self.SoftLimit, _ = strconv.ParseUint(fields[1], 10, 64)
|
||||
self.HardLimit, _ = strconv.ParseUint(fields[2], 10, 64)
|
||||
}
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// linprocfs only provides this information for this process (self).
|
||||
fds, err := ioutil.ReadDir(procFileName(pid, "fd"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
self.Open = uint64(len(fds))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *HugeTLBPages) Get() error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func parseCpuStat(self *Cpu, line string) error {
|
||||
fields := strings.Fields(line)
|
||||
|
||||
self.User, _ = strtoull(fields[1])
|
||||
self.Nice, _ = strtoull(fields[2])
|
||||
self.Sys, _ = strtoull(fields[3])
|
||||
self.Idle, _ = strtoull(fields[4])
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Mem) Get() error {
|
||||
val := C.uint32_t(0)
|
||||
sc := C.size_t(4)
|
||||
|
||||
name := C.CString("vm.stats.vm.v_page_count")
|
||||
_, err := C.sysctlbyname(name, unsafe.Pointer(&val), &sc, nil, 0)
|
||||
C.free(unsafe.Pointer(name))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pagecount := uint64(val)
|
||||
|
||||
name = C.CString("vm.stats.vm.v_page_size")
|
||||
_, err = C.sysctlbyname(name, unsafe.Pointer(&val), &sc, nil, 0)
|
||||
C.free(unsafe.Pointer(name))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pagesize := uint64(val)
|
||||
|
||||
name = C.CString("vm.stats.vm.v_free_count")
|
||||
_, err = C.sysctlbyname(name, unsafe.Pointer(&val), &sc, nil, 0)
|
||||
C.free(unsafe.Pointer(name))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
self.Free = uint64(val) * pagesize
|
||||
|
||||
name = C.CString("vm.stats.vm.v_inactive_count")
|
||||
_, err = C.sysctlbyname(name, unsafe.Pointer(&val), &sc, nil, 0)
|
||||
C.free(unsafe.Pointer(name))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
kern := uint64(val)
|
||||
|
||||
self.Total = uint64(pagecount * pagesize)
|
||||
|
||||
self.Used = self.Total - self.Free
|
||||
self.ActualFree = self.Free + (kern * pagesize)
|
||||
self.ActualUsed = self.Used - (kern * pagesize)
|
||||
|
||||
return nil
|
||||
}
|
207
vendor/github.com/elastic/gosigar/sigar_interface.go
generated
vendored
Normal file
207
vendor/github.com/elastic/gosigar/sigar_interface.go
generated
vendored
Normal file
@ -0,0 +1,207 @@
|
||||
package gosigar
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type ErrNotImplemented struct {
|
||||
OS string
|
||||
}
|
||||
|
||||
func (e ErrNotImplemented) Error() string {
|
||||
return "not implemented on " + e.OS
|
||||
}
|
||||
|
||||
func IsNotImplemented(err error) bool {
|
||||
switch err.(type) {
|
||||
case ErrNotImplemented, *ErrNotImplemented:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
type Sigar interface {
|
||||
CollectCpuStats(collectionInterval time.Duration) (<-chan Cpu, chan<- struct{})
|
||||
GetLoadAverage() (LoadAverage, error)
|
||||
GetMem() (Mem, error)
|
||||
GetSwap() (Swap, error)
|
||||
GetHugeTLBPages(HugeTLBPages, error)
|
||||
GetFileSystemUsage(string) (FileSystemUsage, error)
|
||||
GetFDUsage() (FDUsage, error)
|
||||
GetRusage(who int) (Rusage, error)
|
||||
}
|
||||
|
||||
type Cpu struct {
|
||||
User uint64
|
||||
Nice uint64
|
||||
Sys uint64
|
||||
Idle uint64
|
||||
Wait uint64
|
||||
Irq uint64
|
||||
SoftIrq uint64
|
||||
Stolen uint64
|
||||
}
|
||||
|
||||
func (cpu *Cpu) Total() uint64 {
|
||||
return cpu.User + cpu.Nice + cpu.Sys + cpu.Idle +
|
||||
cpu.Wait + cpu.Irq + cpu.SoftIrq + cpu.Stolen
|
||||
}
|
||||
|
||||
func (cpu Cpu) Delta(other Cpu) Cpu {
|
||||
return Cpu{
|
||||
User: cpu.User - other.User,
|
||||
Nice: cpu.Nice - other.Nice,
|
||||
Sys: cpu.Sys - other.Sys,
|
||||
Idle: cpu.Idle - other.Idle,
|
||||
Wait: cpu.Wait - other.Wait,
|
||||
Irq: cpu.Irq - other.Irq,
|
||||
SoftIrq: cpu.SoftIrq - other.SoftIrq,
|
||||
Stolen: cpu.Stolen - other.Stolen,
|
||||
}
|
||||
}
|
||||
|
||||
type LoadAverage struct {
|
||||
One, Five, Fifteen float64
|
||||
}
|
||||
|
||||
type Uptime struct {
|
||||
Length float64
|
||||
}
|
||||
|
||||
type Mem struct {
|
||||
Total uint64
|
||||
Used uint64
|
||||
Free uint64
|
||||
ActualFree uint64
|
||||
ActualUsed uint64
|
||||
}
|
||||
|
||||
type Swap struct {
|
||||
Total uint64
|
||||
Used uint64
|
||||
Free uint64
|
||||
}
|
||||
|
||||
type HugeTLBPages struct {
|
||||
Total uint64
|
||||
Free uint64
|
||||
Reserved uint64
|
||||
Surplus uint64
|
||||
DefaultSize uint64
|
||||
TotalAllocatedSize uint64
|
||||
}
|
||||
|
||||
type CpuList struct {
|
||||
List []Cpu
|
||||
}
|
||||
|
||||
type FDUsage struct {
|
||||
Open uint64
|
||||
Unused uint64
|
||||
Max uint64
|
||||
}
|
||||
|
||||
type FileSystem struct {
|
||||
DirName string
|
||||
DevName string
|
||||
TypeName string
|
||||
SysTypeName string
|
||||
Options string
|
||||
Flags uint32
|
||||
}
|
||||
|
||||
type FileSystemList struct {
|
||||
List []FileSystem
|
||||
}
|
||||
|
||||
type FileSystemUsage struct {
|
||||
Total uint64
|
||||
Used uint64
|
||||
Free uint64
|
||||
Avail uint64
|
||||
Files uint64
|
||||
FreeFiles uint64
|
||||
}
|
||||
|
||||
type ProcList struct {
|
||||
List []int
|
||||
}
|
||||
|
||||
type RunState byte
|
||||
|
||||
const (
|
||||
RunStateSleep = 'S'
|
||||
RunStateRun = 'R'
|
||||
RunStateStop = 'T'
|
||||
RunStateZombie = 'Z'
|
||||
RunStateIdle = 'D'
|
||||
RunStateUnknown = '?'
|
||||
)
|
||||
|
||||
type ProcState struct {
|
||||
Name string
|
||||
Username string
|
||||
State RunState
|
||||
Ppid int
|
||||
Pgid int
|
||||
Tty int
|
||||
Priority int
|
||||
Nice int
|
||||
Processor int
|
||||
}
|
||||
|
||||
type ProcMem struct {
|
||||
Size uint64
|
||||
Resident uint64
|
||||
Share uint64
|
||||
MinorFaults uint64
|
||||
MajorFaults uint64
|
||||
PageFaults uint64
|
||||
}
|
||||
|
||||
type ProcTime struct {
|
||||
StartTime uint64
|
||||
User uint64
|
||||
Sys uint64
|
||||
Total uint64
|
||||
}
|
||||
|
||||
type ProcArgs struct {
|
||||
List []string
|
||||
}
|
||||
|
||||
type ProcEnv struct {
|
||||
Vars map[string]string
|
||||
}
|
||||
|
||||
type ProcExe struct {
|
||||
Name string
|
||||
Cwd string
|
||||
Root string
|
||||
}
|
||||
|
||||
type ProcFDUsage struct {
|
||||
Open uint64
|
||||
SoftLimit uint64
|
||||
HardLimit uint64
|
||||
}
|
||||
|
||||
type Rusage struct {
|
||||
Utime time.Duration
|
||||
Stime time.Duration
|
||||
Maxrss int64
|
||||
Ixrss int64
|
||||
Idrss int64
|
||||
Isrss int64
|
||||
Minflt int64
|
||||
Majflt int64
|
||||
Nswap int64
|
||||
Inblock int64
|
||||
Oublock int64
|
||||
Msgsnd int64
|
||||
Msgrcv int64
|
||||
Nsignals int64
|
||||
Nvcsw int64
|
||||
Nivcsw int64
|
||||
}
|
133
vendor/github.com/elastic/gosigar/sigar_linux.go
generated
vendored
Normal file
133
vendor/github.com/elastic/gosigar/sigar_linux.go
generated
vendored
Normal file
@ -0,0 +1,133 @@
|
||||
// Copyright (c) 2012 VMware, Inc.
|
||||
|
||||
package gosigar
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func init() {
|
||||
system.ticks = 100 // C.sysconf(C._SC_CLK_TCK)
|
||||
|
||||
Procd = "/proc"
|
||||
|
||||
getLinuxBootTime()
|
||||
}
|
||||
|
||||
func getMountTableFileName() string {
|
||||
return "/etc/mtab"
|
||||
}
|
||||
|
||||
func (self *Uptime) Get() error {
|
||||
sysinfo := syscall.Sysinfo_t{}
|
||||
|
||||
if err := syscall.Sysinfo(&sysinfo); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
self.Length = float64(sysinfo.Uptime)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *FDUsage) Get() error {
|
||||
return readFile(Procd+"/sys/fs/file-nr", func(line string) bool {
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) == 3 {
|
||||
self.Open, _ = strconv.ParseUint(fields[0], 10, 64)
|
||||
self.Unused, _ = strconv.ParseUint(fields[1], 10, 64)
|
||||
self.Max, _ = strconv.ParseUint(fields[2], 10, 64)
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
func (self *HugeTLBPages) Get() error {
|
||||
table, err := parseMeminfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
self.Total, _ = table["HugePages_Total"]
|
||||
self.Free, _ = table["HugePages_Free"]
|
||||
self.Reserved, _ = table["HugePages_Rsvd"]
|
||||
self.Surplus, _ = table["HugePages_Surp"]
|
||||
self.DefaultSize, _ = table["Hugepagesize"]
|
||||
|
||||
if totalSize, found := table["Hugetlb"]; found {
|
||||
self.TotalAllocatedSize = totalSize
|
||||
} else {
|
||||
// If Hugetlb is not present, or huge pages of different sizes
|
||||
// are used, this figure can be unaccurate.
|
||||
// TODO (jsoriano): Extract information from /sys/kernel/mm/hugepages too
|
||||
self.TotalAllocatedSize = (self.Total - self.Free + self.Reserved) * self.DefaultSize
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ProcFDUsage) Get(pid int) error {
|
||||
err := readFile(procFileName(pid, "limits"), func(line string) bool {
|
||||
if strings.HasPrefix(line, "Max open files") {
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) == 6 {
|
||||
self.SoftLimit, _ = strconv.ParseUint(fields[3], 10, 64)
|
||||
self.HardLimit, _ = strconv.ParseUint(fields[4], 10, 64)
|
||||
}
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fds, err := ioutil.ReadDir(procFileName(pid, "fd"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
self.Open = uint64(len(fds))
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseCpuStat(self *Cpu, line string) error {
|
||||
fields := strings.Fields(line)
|
||||
|
||||
self.User, _ = strtoull(fields[1])
|
||||
self.Nice, _ = strtoull(fields[2])
|
||||
self.Sys, _ = strtoull(fields[3])
|
||||
self.Idle, _ = strtoull(fields[4])
|
||||
self.Wait, _ = strtoull(fields[5])
|
||||
self.Irq, _ = strtoull(fields[6])
|
||||
self.SoftIrq, _ = strtoull(fields[7])
|
||||
self.Stolen, _ = strtoull(fields[8])
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Mem) Get() error {
|
||||
|
||||
table, err := parseMeminfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
self.Total, _ = table["MemTotal"]
|
||||
self.Free, _ = table["MemFree"]
|
||||
buffers, _ := table["Buffers"]
|
||||
cached, _ := table["Cached"]
|
||||
|
||||
if available, ok := table["MemAvailable"]; ok {
|
||||
// MemAvailable is in /proc/meminfo (kernel 3.14+)
|
||||
self.ActualFree = available
|
||||
} else {
|
||||
self.ActualFree = self.Free + buffers + cached
|
||||
}
|
||||
|
||||
self.Used = self.Total - self.Free
|
||||
self.ActualUsed = self.Total - self.ActualFree
|
||||
|
||||
return nil
|
||||
}
|
457
vendor/github.com/elastic/gosigar/sigar_linux_common.go
generated
vendored
Normal file
457
vendor/github.com/elastic/gosigar/sigar_linux_common.go
generated
vendored
Normal file
@ -0,0 +1,457 @@
|
||||
// Copyright (c) 2012 VMware, Inc.
|
||||
|
||||
// +build freebsd linux
|
||||
|
||||
package gosigar
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
var system struct {
|
||||
ticks uint64
|
||||
btime uint64
|
||||
}
|
||||
|
||||
var Procd string
|
||||
|
||||
func getLinuxBootTime() {
|
||||
// grab system boot time
|
||||
readFile(Procd+"/stat", func(line string) bool {
|
||||
if strings.HasPrefix(line, "btime") {
|
||||
system.btime, _ = strtoull(line[6:])
|
||||
return false // stop reading
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
func (self *LoadAverage) Get() error {
|
||||
line, err := ioutil.ReadFile(Procd + "/loadavg")
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
fields := strings.Fields(string(line))
|
||||
|
||||
self.One, _ = strconv.ParseFloat(fields[0], 64)
|
||||
self.Five, _ = strconv.ParseFloat(fields[1], 64)
|
||||
self.Fifteen, _ = strconv.ParseFloat(fields[2], 64)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Swap) Get() error {
|
||||
|
||||
table, err := parseMeminfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
self.Total, _ = table["SwapTotal"]
|
||||
self.Free, _ = table["SwapFree"]
|
||||
|
||||
self.Used = self.Total - self.Free
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Cpu) Get() error {
|
||||
return readFile(Procd+"/stat", func(line string) bool {
|
||||
if len(line) > 4 && line[0:4] == "cpu " {
|
||||
parseCpuStat(self, line)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
func (self *CpuList) Get() error {
|
||||
capacity := len(self.List)
|
||||
if capacity == 0 {
|
||||
capacity = 4
|
||||
}
|
||||
list := make([]Cpu, 0, capacity)
|
||||
|
||||
err := readFile(Procd+"/stat", func(line string) bool {
|
||||
if len(line) > 3 && line[0:3] == "cpu" && line[3] != ' ' {
|
||||
cpu := Cpu{}
|
||||
parseCpuStat(&cpu, line)
|
||||
list = append(list, cpu)
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
self.List = list
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (self *FileSystemList) Get() error {
|
||||
capacity := len(self.List)
|
||||
if capacity == 0 {
|
||||
capacity = 10
|
||||
}
|
||||
fslist := make([]FileSystem, 0, capacity)
|
||||
|
||||
err := readFile(getMountTableFileName(), func(line string) bool {
|
||||
fields := strings.Fields(line)
|
||||
|
||||
fs := FileSystem{}
|
||||
fs.DevName = fields[0]
|
||||
fs.DirName = fields[1]
|
||||
fs.SysTypeName = fields[2]
|
||||
fs.Options = fields[3]
|
||||
|
||||
fslist = append(fslist, fs)
|
||||
|
||||
return true
|
||||
})
|
||||
|
||||
self.List = fslist
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (self *ProcList) Get() error {
|
||||
dir, err := os.Open(Procd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer dir.Close()
|
||||
|
||||
const readAllDirnames = -1 // see os.File.Readdirnames doc
|
||||
|
||||
names, err := dir.Readdirnames(readAllDirnames)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
capacity := len(names)
|
||||
list := make([]int, 0, capacity)
|
||||
|
||||
for _, name := range names {
|
||||
if name[0] < '0' || name[0] > '9' {
|
||||
continue
|
||||
}
|
||||
pid, err := strconv.Atoi(name)
|
||||
if err == nil {
|
||||
list = append(list, pid)
|
||||
}
|
||||
}
|
||||
|
||||
self.List = list
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ProcState) Get(pid int) error {
|
||||
data, err := readProcFile(pid, "stat")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Extract the comm value with is surrounded by parentheses.
|
||||
lIdx := bytes.Index(data, []byte("("))
|
||||
rIdx := bytes.LastIndex(data, []byte(")"))
|
||||
if lIdx < 0 || rIdx < 0 || lIdx >= rIdx || rIdx+2 >= len(data) {
|
||||
return fmt.Errorf("failed to extract comm for pid %d from '%v'", pid, string(data))
|
||||
}
|
||||
self.Name = string(data[lIdx+1 : rIdx])
|
||||
|
||||
// Extract the rest of the fields that we are interested in.
|
||||
fields := bytes.Fields(data[rIdx+2:])
|
||||
if len(fields) <= 36 {
|
||||
return fmt.Errorf("expected more stat fields for pid %d from '%v'", pid, string(data))
|
||||
}
|
||||
|
||||
interests := bytes.Join([][]byte{
|
||||
fields[0], // state
|
||||
fields[1], // ppid
|
||||
fields[2], // pgrp
|
||||
fields[4], // tty_nr
|
||||
fields[15], // priority
|
||||
fields[16], // nice
|
||||
fields[36], // processor (last processor executed on)
|
||||
}, []byte(" "))
|
||||
|
||||
var state string
|
||||
_, err = fmt.Fscan(bytes.NewBuffer(interests),
|
||||
&state,
|
||||
&self.Ppid,
|
||||
&self.Pgid,
|
||||
&self.Tty,
|
||||
&self.Priority,
|
||||
&self.Nice,
|
||||
&self.Processor,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to parse stat fields for pid %d from '%v': %v", pid, string(data), err)
|
||||
}
|
||||
self.State = RunState(state[0])
|
||||
|
||||
// Read /proc/[pid]/status to get the uid, then lookup uid to get username.
|
||||
status, err := getProcStatus(pid)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read process status for pid %d: %v", pid, err)
|
||||
}
|
||||
uids, err := getUIDs(status)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read process status for pid %d: %v", pid, err)
|
||||
}
|
||||
user, err := user.LookupId(uids[0])
|
||||
if err == nil {
|
||||
self.Username = user.Username
|
||||
} else {
|
||||
self.Username = uids[0]
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ProcMem) Get(pid int) error {
|
||||
contents, err := readProcFile(pid, "statm")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fields := strings.Fields(string(contents))
|
||||
|
||||
size, _ := strtoull(fields[0])
|
||||
self.Size = size << 12
|
||||
|
||||
rss, _ := strtoull(fields[1])
|
||||
self.Resident = rss << 12
|
||||
|
||||
share, _ := strtoull(fields[2])
|
||||
self.Share = share << 12
|
||||
|
||||
contents, err = readProcFile(pid, "stat")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fields = strings.Fields(string(contents))
|
||||
|
||||
self.MinorFaults, _ = strtoull(fields[10])
|
||||
self.MajorFaults, _ = strtoull(fields[12])
|
||||
self.PageFaults = self.MinorFaults + self.MajorFaults
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ProcTime) Get(pid int) error {
|
||||
contents, err := readProcFile(pid, "stat")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fields := strings.Fields(string(contents))
|
||||
|
||||
user, _ := strtoull(fields[13])
|
||||
sys, _ := strtoull(fields[14])
|
||||
// convert to millis
|
||||
self.User = user * (1000 / system.ticks)
|
||||
self.Sys = sys * (1000 / system.ticks)
|
||||
self.Total = self.User + self.Sys
|
||||
|
||||
// convert to millis
|
||||
self.StartTime, _ = strtoull(fields[21])
|
||||
self.StartTime /= system.ticks
|
||||
self.StartTime += system.btime
|
||||
self.StartTime *= 1000
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ProcArgs) Get(pid int) error {
|
||||
contents, err := readProcFile(pid, "cmdline")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
bbuf := bytes.NewBuffer(contents)
|
||||
|
||||
var args []string
|
||||
|
||||
for {
|
||||
arg, err := bbuf.ReadBytes(0)
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
args = append(args, string(chop(arg)))
|
||||
}
|
||||
|
||||
self.List = args
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ProcEnv) Get(pid int) error {
|
||||
contents, err := readProcFile(pid, "environ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if self.Vars == nil {
|
||||
self.Vars = map[string]string{}
|
||||
}
|
||||
|
||||
pairs := bytes.Split(contents, []byte{0})
|
||||
for _, kv := range pairs {
|
||||
parts := bytes.SplitN(kv, []byte{'='}, 2)
|
||||
if len(parts) != 2 {
|
||||
continue
|
||||
}
|
||||
|
||||
key := string(bytes.TrimSpace(parts[0]))
|
||||
if key == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
self.Vars[key] = string(bytes.TrimSpace(parts[1]))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ProcExe) Get(pid int) error {
|
||||
fields := map[string]*string{
|
||||
"exe": &self.Name,
|
||||
"cwd": &self.Cwd,
|
||||
"root": &self.Root,
|
||||
}
|
||||
|
||||
for name, field := range fields {
|
||||
val, err := os.Readlink(procFileName(pid, name))
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
*field = val
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseMeminfo() (map[string]uint64, error) {
|
||||
table := map[string]uint64{}
|
||||
|
||||
err := readFile(Procd+"/meminfo", func(line string) bool {
|
||||
fields := strings.Split(line, ":")
|
||||
|
||||
if len(fields) != 2 {
|
||||
return true // skip on errors
|
||||
}
|
||||
|
||||
valueUnit := strings.Fields(fields[1])
|
||||
value, err := strtoull(valueUnit[0])
|
||||
if err != nil {
|
||||
return true // skip on errors
|
||||
}
|
||||
|
||||
if len(valueUnit) > 1 && valueUnit[1] == "kB" {
|
||||
value *= 1024
|
||||
}
|
||||
table[fields[0]] = value
|
||||
|
||||
return true
|
||||
})
|
||||
return table, err
|
||||
}
|
||||
|
||||
func readFile(file string, handler func(string) bool) error {
|
||||
contents, err := ioutil.ReadFile(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
reader := bufio.NewReader(bytes.NewBuffer(contents))
|
||||
|
||||
for {
|
||||
line, _, err := reader.ReadLine()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if !handler(string(line)) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func strtoull(val string) (uint64, error) {
|
||||
return strconv.ParseUint(val, 10, 64)
|
||||
}
|
||||
|
||||
func procFileName(pid int, name string) string {
|
||||
return Procd + "/" + strconv.Itoa(pid) + "/" + name
|
||||
}
|
||||
|
||||
func readProcFile(pid int, name string) (content []byte, err error) {
|
||||
path := procFileName(pid, name)
|
||||
|
||||
// Panics have been reported when reading proc files, let's recover and
|
||||
// report the path if this happens
|
||||
// See https://github.com/elastic/beats/issues/6692
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
content = nil
|
||||
err = fmt.Errorf("recovered panic when reading proc file '%s': %v", path, r)
|
||||
}
|
||||
}()
|
||||
contents, err := ioutil.ReadFile(path)
|
||||
|
||||
if err != nil {
|
||||
if perr, ok := err.(*os.PathError); ok {
|
||||
if perr.Err == syscall.ENOENT {
|
||||
return nil, syscall.ESRCH
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return contents, err
|
||||
}
|
||||
|
||||
// getProcStatus reads /proc/[pid]/status which contains process status
|
||||
// information in human readable form.
|
||||
func getProcStatus(pid int) (map[string]string, error) {
|
||||
status := make(map[string]string, 42)
|
||||
path := filepath.Join(Procd, strconv.Itoa(pid), "status")
|
||||
err := readFile(path, func(line string) bool {
|
||||
fields := strings.SplitN(line, ":", 2)
|
||||
if len(fields) == 2 {
|
||||
status[fields[0]] = strings.TrimSpace(fields[1])
|
||||
}
|
||||
|
||||
return true
|
||||
})
|
||||
return status, err
|
||||
}
|
||||
|
||||
// getUIDs reads the "Uid" value from status and splits it into four values --
|
||||
// real, effective, saved set, and file system UIDs.
|
||||
func getUIDs(status map[string]string) ([]string, error) {
|
||||
uidLine, ok := status["Uid"]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Uid not found in proc status")
|
||||
}
|
||||
|
||||
uidStrs := strings.Fields(uidLine)
|
||||
if len(uidStrs) != 4 {
|
||||
return nil, fmt.Errorf("Uid line ('%s') did not contain four values", uidLine)
|
||||
}
|
||||
|
||||
return uidStrs, nil
|
||||
}
|
426
vendor/github.com/elastic/gosigar/sigar_openbsd.go
generated
vendored
Normal file
426
vendor/github.com/elastic/gosigar/sigar_openbsd.go
generated
vendored
Normal file
@ -0,0 +1,426 @@
|
||||
// Copyright (c) 2016 Jasper Lievisse Adriaanse <j@jasper.la>.
|
||||
|
||||
// +build openbsd
|
||||
|
||||
package gosigar
|
||||
|
||||
/*
|
||||
#include <sys/param.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/sysctl.h>
|
||||
#include <sys/mount.h>
|
||||
#include <sys/sched.h>
|
||||
#include <sys/swap.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
*/
|
||||
import "C"
|
||||
|
||||
//import "github.com/davecgh/go-spew/spew"
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
type Uvmexp struct {
|
||||
pagesize uint32
|
||||
pagemask uint32
|
||||
pageshift uint32
|
||||
npages uint32
|
||||
free uint32
|
||||
active uint32
|
||||
inactive uint32
|
||||
paging uint32
|
||||
wired uint32
|
||||
zeropages uint32
|
||||
reserve_pagedaemon uint32
|
||||
reserve_kernel uint32
|
||||
anonpages uint32
|
||||
vnodepages uint32
|
||||
vtextpages uint32
|
||||
freemin uint32
|
||||
freetarg uint32
|
||||
inactarg uint32
|
||||
wiredmax uint32
|
||||
anonmin uint32
|
||||
vtextmin uint32
|
||||
vnodemin uint32
|
||||
anonminpct uint32
|
||||
vtextmi uint32
|
||||
npct uint32
|
||||
vnodeminpct uint32
|
||||
nswapdev uint32
|
||||
swpages uint32
|
||||
swpginuse uint32
|
||||
swpgonly uint32
|
||||
nswget uint32
|
||||
nanon uint32
|
||||
nanonneeded uint32
|
||||
nfreeanon uint32
|
||||
faults uint32
|
||||
traps uint32
|
||||
intrs uint32
|
||||
swtch uint32
|
||||
softs uint32
|
||||
syscalls uint32
|
||||
pageins uint32
|
||||
obsolete_swapins uint32
|
||||
obsolete_swapouts uint32
|
||||
pgswapin uint32
|
||||
pgswapout uint32
|
||||
forks uint32
|
||||
forks_ppwait uint32
|
||||
forks_sharevm uint32
|
||||
pga_zerohit uint32
|
||||
pga_zeromiss uint32
|
||||
zeroaborts uint32
|
||||
fltnoram uint32
|
||||
fltnoanon uint32
|
||||
fltpgwait uint32
|
||||
fltpgrele uint32
|
||||
fltrelck uint32
|
||||
fltrelckok uint32
|
||||
fltanget uint32
|
||||
fltanretry uint32
|
||||
fltamcopy uint32
|
||||
fltnamap uint32
|
||||
fltnomap uint32
|
||||
fltlget uint32
|
||||
fltget uint32
|
||||
flt_anon uint32
|
||||
flt_acow uint32
|
||||
flt_obj uint32
|
||||
flt_prcopy uint32
|
||||
flt_przero uint32
|
||||
pdwoke uint32
|
||||
pdrevs uint32
|
||||
pdswout uint32
|
||||
pdfreed uint32
|
||||
pdscans uint32
|
||||
pdanscan uint32
|
||||
pdobscan uint32
|
||||
pdreact uint32
|
||||
pdbusy uint32
|
||||
pdpageouts uint32
|
||||
pdpending uint32
|
||||
pddeact uint32
|
||||
pdreanon uint32
|
||||
pdrevnode uint32
|
||||
pdrevtext uint32
|
||||
fpswtch uint32
|
||||
kmapent uint32
|
||||
}
|
||||
|
||||
type Bcachestats struct {
|
||||
numbufs uint64
|
||||
numbufpages uint64
|
||||
numdirtypages uint64
|
||||
numcleanpages uint64
|
||||
pendingwrites uint64
|
||||
pendingreads uint64
|
||||
numwrites uint64
|
||||
numreads uint64
|
||||
cachehits uint64
|
||||
busymapped uint64
|
||||
dmapages uint64
|
||||
highpages uint64
|
||||
delwribufs uint64
|
||||
kvaslots uint64
|
||||
kvaslots_avail uint64
|
||||
}
|
||||
|
||||
type Swapent struct {
|
||||
se_dev C.dev_t
|
||||
se_flags int32
|
||||
se_nblks int32
|
||||
se_inuse int32
|
||||
se_priority int32
|
||||
sw_path []byte
|
||||
}
|
||||
|
||||
func (self *FileSystemList) Get() error {
|
||||
num, err := syscall.Getfsstat(nil, C.MNT_NOWAIT)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
buf := make([]syscall.Statfs_t, num)
|
||||
|
||||
_, err = syscall.Getfsstat(buf, C.MNT_NOWAIT)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fslist := make([]FileSystem, 0, num)
|
||||
|
||||
for i := 0; i < num; i++ {
|
||||
fs := FileSystem{}
|
||||
|
||||
fs.DirName = bytePtrToString(&buf[i].F_mntonname[0])
|
||||
fs.DevName = bytePtrToString(&buf[i].F_mntfromname[0])
|
||||
fs.SysTypeName = bytePtrToString(&buf[i].F_fstypename[0])
|
||||
|
||||
fslist = append(fslist, fs)
|
||||
}
|
||||
|
||||
self.List = fslist
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (self *FileSystemUsage) Get(path string) error {
|
||||
stat := syscall.Statfs_t{}
|
||||
err := syscall.Statfs(path, &stat)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
self.Total = uint64(stat.F_blocks) * uint64(stat.F_bsize)
|
||||
self.Free = uint64(stat.F_bfree) * uint64(stat.F_bsize)
|
||||
self.Avail = uint64(stat.F_bavail) * uint64(stat.F_bsize)
|
||||
self.Used = self.Total - self.Free
|
||||
self.Files = stat.F_files
|
||||
self.FreeFiles = stat.F_ffree
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *FDUsage) Get() error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (self *LoadAverage) Get() error {
|
||||
avg := []C.double{0, 0, 0}
|
||||
|
||||
C.getloadavg(&avg[0], C.int(len(avg)))
|
||||
|
||||
self.One = float64(avg[0])
|
||||
self.Five = float64(avg[1])
|
||||
self.Fifteen = float64(avg[2])
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Uptime) Get() error {
|
||||
tv := syscall.Timeval{}
|
||||
mib := [2]int32{C.CTL_KERN, C.KERN_BOOTTIME}
|
||||
|
||||
n := uintptr(0)
|
||||
// First we determine how much memory we'll need to pass later on (via `n`)
|
||||
_, _, errno := syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), 2, 0, uintptr(unsafe.Pointer(&n)), 0, 0)
|
||||
|
||||
if errno != 0 || n == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Now perform the actual sysctl(3) call, storing the result in tv
|
||||
_, _, errno = syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), 2, uintptr(unsafe.Pointer(&tv)), uintptr(unsafe.Pointer(&n)), 0, 0)
|
||||
|
||||
if errno != 0 || n == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
self.Length = time.Since(time.Unix(int64(tv.Sec), int64(tv.Usec)*1000)).Seconds()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Mem) Get() error {
|
||||
n := uintptr(0)
|
||||
|
||||
var uvmexp Uvmexp
|
||||
mib := [2]int32{C.CTL_VM, C.VM_UVMEXP}
|
||||
n = uintptr(0)
|
||||
// First we determine how much memory we'll need to pass later on (via `n`)
|
||||
_, _, errno := syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), 2, 0, uintptr(unsafe.Pointer(&n)), 0, 0)
|
||||
if errno != 0 || n == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
_, _, errno = syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), 2, uintptr(unsafe.Pointer(&uvmexp)), uintptr(unsafe.Pointer(&n)), 0, 0)
|
||||
if errno != 0 || n == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var bcachestats Bcachestats
|
||||
mib3 := [3]int32{C.CTL_VFS, C.VFS_GENERIC, C.VFS_BCACHESTAT}
|
||||
n = uintptr(0)
|
||||
_, _, errno = syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib3[0])), 3, 0, uintptr(unsafe.Pointer(&n)), 0, 0)
|
||||
if errno != 0 || n == 0 {
|
||||
return nil
|
||||
}
|
||||
_, _, errno = syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib3[0])), 3, uintptr(unsafe.Pointer(&bcachestats)), uintptr(unsafe.Pointer(&n)), 0, 0)
|
||||
if errno != 0 || n == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
self.Total = uint64(uvmexp.npages) << uvmexp.pageshift
|
||||
self.Used = uint64(uvmexp.npages-uvmexp.free) << uvmexp.pageshift
|
||||
self.Free = uint64(uvmexp.free) << uvmexp.pageshift
|
||||
|
||||
self.ActualFree = self.Free + (uint64(bcachestats.numbufpages) << uvmexp.pageshift)
|
||||
self.ActualUsed = self.Used - (uint64(bcachestats.numbufpages) << uvmexp.pageshift)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Swap) Get() error {
|
||||
nswap := C.swapctl(C.SWAP_NSWAP, unsafe.Pointer(uintptr(0)), 0)
|
||||
|
||||
// If there are no swap devices, nothing to do here.
|
||||
if nswap == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
swdev := make([]Swapent, nswap)
|
||||
|
||||
rnswap := C.swapctl(C.SWAP_STATS, unsafe.Pointer(&swdev[0]), nswap)
|
||||
if rnswap == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
for i := 0; i < int(nswap); i++ {
|
||||
if swdev[i].se_flags&C.SWF_ENABLE == 2 {
|
||||
self.Used = self.Used + uint64(swdev[i].se_inuse/(1024/C.DEV_BSIZE))
|
||||
self.Total = self.Total + uint64(swdev[i].se_nblks/(1024/C.DEV_BSIZE))
|
||||
}
|
||||
}
|
||||
|
||||
self.Free = self.Total - self.Used
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *HugeTLBPages) Get() error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (self *Cpu) Get() error {
|
||||
load := [C.CPUSTATES]C.long{C.CP_USER, C.CP_NICE, C.CP_SYS, C.CP_INTR, C.CP_IDLE}
|
||||
|
||||
mib := [2]int32{C.CTL_KERN, C.KERN_CPTIME}
|
||||
n := uintptr(0)
|
||||
// First we determine how much memory we'll need to pass later on (via `n`)
|
||||
_, _, errno := syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), 2, 0, uintptr(unsafe.Pointer(&n)), 0, 0)
|
||||
if errno != 0 || n == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
_, _, errno = syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), 2, uintptr(unsafe.Pointer(&load)), uintptr(unsafe.Pointer(&n)), 0, 0)
|
||||
if errno != 0 || n == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
self.User = uint64(load[0])
|
||||
self.Nice = uint64(load[1])
|
||||
self.Sys = uint64(load[2])
|
||||
self.Irq = uint64(load[3])
|
||||
self.Idle = uint64(load[4])
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *CpuList) Get() error {
|
||||
mib := [2]int32{C.CTL_HW, C.HW_NCPU}
|
||||
var ncpu int
|
||||
|
||||
n := uintptr(0)
|
||||
// First we determine how much memory we'll need to pass later on (via `n`)
|
||||
_, _, errno := syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), 2, 0, uintptr(unsafe.Pointer(&n)), 0, 0)
|
||||
|
||||
if errno != 0 || n == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Now perform the actual sysctl(3) call, storing the result in ncpu
|
||||
_, _, errno = syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), 2, uintptr(unsafe.Pointer(&ncpu)), uintptr(unsafe.Pointer(&n)), 0, 0)
|
||||
|
||||
if errno != 0 || n == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
load := [C.CPUSTATES]C.long{C.CP_USER, C.CP_NICE, C.CP_SYS, C.CP_INTR, C.CP_IDLE}
|
||||
|
||||
self.List = make([]Cpu, ncpu)
|
||||
for curcpu := range self.List {
|
||||
sysctlCptime(ncpu, curcpu, &load)
|
||||
fillCpu(&self.List[curcpu], load)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ProcList) Get() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ProcArgs) Get(pid int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ProcEnv) Get(pid int) error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (self *ProcState) Get(pid int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ProcMem) Get(pid int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ProcTime) Get(pid int) error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (self *ProcExe) Get(pid int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ProcFDUsage) Get(pid int) error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (self *Rusage) Get(pid int) error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func fillCpu(cpu *Cpu, load [C.CPUSTATES]C.long) {
|
||||
cpu.User = uint64(load[0])
|
||||
cpu.Nice = uint64(load[1])
|
||||
cpu.Sys = uint64(load[2])
|
||||
cpu.Irq = uint64(load[3])
|
||||
cpu.Idle = uint64(load[4])
|
||||
}
|
||||
|
||||
func sysctlCptime(ncpu int, curcpu int, load *[C.CPUSTATES]C.long) error {
|
||||
var mib []int32
|
||||
|
||||
// Use the correct mib based on the number of CPUs and fill out the
|
||||
// current CPU number in case of SMP. (0 indexed cf. self.List)
|
||||
if ncpu == 0 {
|
||||
mib = []int32{C.CTL_KERN, C.KERN_CPTIME}
|
||||
} else {
|
||||
mib = []int32{C.CTL_KERN, C.KERN_CPTIME2, int32(curcpu)}
|
||||
}
|
||||
|
||||
len := len(mib)
|
||||
|
||||
n := uintptr(0)
|
||||
// First we determine how much memory we'll need to pass later on (via `n`)
|
||||
_, _, errno := syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), uintptr(len), 0, uintptr(unsafe.Pointer(&n)), 0, 0)
|
||||
if errno != 0 || n == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
_, _, errno = syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), uintptr(len), uintptr(unsafe.Pointer(load)), uintptr(unsafe.Pointer(&n)), 0, 0)
|
||||
if errno != 0 || n == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
75
vendor/github.com/elastic/gosigar/sigar_stub.go
generated
vendored
Normal file
75
vendor/github.com/elastic/gosigar/sigar_stub.go
generated
vendored
Normal file
@ -0,0 +1,75 @@
|
||||
// +build !darwin,!freebsd,!linux,!openbsd,!windows
|
||||
|
||||
package gosigar
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
)
|
||||
|
||||
func (c *Cpu) Get() error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (l *LoadAverage) Get() error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (m *Mem) Get() error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (s *Swap) Get() error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (s *HugeTLBPages) Get() error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (f *FDUsage) Get() error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (p *ProcTime) Get(int) error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (self *FileSystemUsage) Get(path string) error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (self *CpuList) Get() error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (p *ProcState) Get(int) error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (p *ProcExe) Get(int) error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (p *ProcMem) Get(int) error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (p *ProcFDUsage) Get(int) error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (p *ProcEnv) Get(int) error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (p *ProcList) Get() error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (p *ProcArgs) Get(int) error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (self *Rusage) Get(int) error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
69
vendor/github.com/elastic/gosigar/sigar_unix.go
generated
vendored
Normal file
69
vendor/github.com/elastic/gosigar/sigar_unix.go
generated
vendored
Normal file
@ -0,0 +1,69 @@
|
||||
// Copyright (c) 2012 VMware, Inc.
|
||||
|
||||
// +build darwin freebsd linux
|
||||
|
||||
package gosigar
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func (self *FileSystemUsage) Get(path string) error {
|
||||
stat := syscall.Statfs_t{}
|
||||
err := syscall.Statfs(path, &stat)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
self.Total = uint64(stat.Blocks) * uint64(stat.Bsize)
|
||||
self.Free = uint64(stat.Bfree) * uint64(stat.Bsize)
|
||||
self.Avail = uint64(stat.Bavail) * uint64(stat.Bsize)
|
||||
self.Used = self.Total - self.Free
|
||||
self.Files = stat.Files
|
||||
self.FreeFiles = uint64(stat.Ffree)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Rusage) Get(who int) error {
|
||||
ru, err := getResourceUsage(who)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
uTime := convertRtimeToDur(ru.Utime)
|
||||
sTime := convertRtimeToDur(ru.Stime)
|
||||
|
||||
r.Utime = uTime
|
||||
r.Stime = sTime
|
||||
r.Maxrss = int64(ru.Maxrss)
|
||||
r.Ixrss = int64(ru.Ixrss)
|
||||
r.Idrss = int64(ru.Idrss)
|
||||
r.Isrss = int64(ru.Isrss)
|
||||
r.Minflt = int64(ru.Minflt)
|
||||
r.Majflt = int64(ru.Majflt)
|
||||
r.Nswap = int64(ru.Nswap)
|
||||
r.Inblock = int64(ru.Inblock)
|
||||
r.Oublock = int64(ru.Oublock)
|
||||
r.Msgsnd = int64(ru.Msgsnd)
|
||||
r.Msgrcv = int64(ru.Msgrcv)
|
||||
r.Nsignals = int64(ru.Nsignals)
|
||||
r.Nvcsw = int64(ru.Nvcsw)
|
||||
r.Nivcsw = int64(ru.Nivcsw)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func getResourceUsage(who int) (unix.Rusage, error) {
|
||||
r := unix.Rusage{}
|
||||
err := unix.Getrusage(who, &r)
|
||||
|
||||
return r, err
|
||||
}
|
||||
|
||||
func convertRtimeToDur(t unix.Timeval) time.Duration {
|
||||
return time.Duration(t.Nano())
|
||||
}
|
22
vendor/github.com/elastic/gosigar/sigar_util.go
generated
vendored
Normal file
22
vendor/github.com/elastic/gosigar/sigar_util.go
generated
vendored
Normal file
@ -0,0 +1,22 @@
|
||||
// Copyright (c) 2012 VMware, Inc.
|
||||
|
||||
package gosigar
|
||||
|
||||
import (
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func bytePtrToString(ptr *int8) string {
|
||||
bytes := (*[10000]byte)(unsafe.Pointer(ptr))
|
||||
|
||||
n := 0
|
||||
for bytes[n] != 0 {
|
||||
n++
|
||||
}
|
||||
|
||||
return string(bytes[0:n])
|
||||
}
|
||||
|
||||
func chop(buf []byte) []byte {
|
||||
return buf[0 : len(buf)-1]
|
||||
}
|
409
vendor/github.com/elastic/gosigar/sigar_windows.go
generated
vendored
Normal file
409
vendor/github.com/elastic/gosigar/sigar_windows.go
generated
vendored
Normal file
@ -0,0 +1,409 @@
|
||||
// Copyright (c) 2012 VMware, Inc.
|
||||
|
||||
package gosigar
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/elastic/gosigar/sys/windows"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
var (
|
||||
// version is Windows version of the host OS.
|
||||
version = windows.GetWindowsVersion()
|
||||
|
||||
// processQueryLimitedInfoAccess is set to PROCESS_QUERY_INFORMATION for Windows
|
||||
// 2003 and XP where PROCESS_QUERY_LIMITED_INFORMATION is unknown. For all newer
|
||||
// OS versions it is set to PROCESS_QUERY_LIMITED_INFORMATION.
|
||||
processQueryLimitedInfoAccess = windows.PROCESS_QUERY_LIMITED_INFORMATION
|
||||
|
||||
// bootTime is the time when the OS was last booted. This value may be nil
|
||||
// on operating systems that do not support the WMI query used to obtain it.
|
||||
bootTime *time.Time
|
||||
bootTimeLock sync.Mutex
|
||||
)
|
||||
|
||||
func init() {
|
||||
if !version.IsWindowsVistaOrGreater() {
|
||||
// PROCESS_QUERY_LIMITED_INFORMATION cannot be used on 2003 or XP.
|
||||
processQueryLimitedInfoAccess = syscall.PROCESS_QUERY_INFORMATION
|
||||
}
|
||||
}
|
||||
|
||||
func (self *LoadAverage) Get() error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (self *FDUsage) Get() error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (self *ProcEnv) Get(pid int) error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (self *ProcExe) Get(pid int) error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (self *ProcFDUsage) Get(pid int) error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (self *Uptime) Get() error {
|
||||
// Minimum supported OS is Windows Vista.
|
||||
if !version.IsWindowsVistaOrGreater() {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
bootTimeLock.Lock()
|
||||
defer bootTimeLock.Unlock()
|
||||
if bootTime == nil {
|
||||
uptime, err := windows.GetTickCount64()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to get boot time using win32 api")
|
||||
}
|
||||
var boot = time.Unix(int64(uptime), 0)
|
||||
bootTime = &boot
|
||||
}
|
||||
|
||||
self.Length = time.Since(*bootTime).Seconds()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Mem) Get() error {
|
||||
memoryStatusEx, err := windows.GlobalMemoryStatusEx()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "GlobalMemoryStatusEx failed")
|
||||
}
|
||||
|
||||
self.Total = memoryStatusEx.TotalPhys
|
||||
self.Free = memoryStatusEx.AvailPhys
|
||||
self.Used = self.Total - self.Free
|
||||
self.ActualFree = self.Free
|
||||
self.ActualUsed = self.Used
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Swap) Get() error {
|
||||
memoryStatusEx, err := windows.GlobalMemoryStatusEx()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "GlobalMemoryStatusEx failed")
|
||||
}
|
||||
|
||||
self.Total = memoryStatusEx.TotalPageFile
|
||||
self.Free = memoryStatusEx.AvailPageFile
|
||||
self.Used = self.Total - self.Free
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *HugeTLBPages) Get() error {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
func (self *Cpu) Get() error {
|
||||
idle, kernel, user, err := windows.GetSystemTimes()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "GetSystemTimes failed")
|
||||
}
|
||||
|
||||
// CPU times are reported in milliseconds by gosigar.
|
||||
self.Idle = uint64(idle / time.Millisecond)
|
||||
self.Sys = uint64(kernel / time.Millisecond)
|
||||
self.User = uint64(user / time.Millisecond)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *CpuList) Get() error {
|
||||
cpus, err := windows.NtQuerySystemProcessorPerformanceInformation()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "NtQuerySystemProcessorPerformanceInformation failed")
|
||||
}
|
||||
|
||||
self.List = make([]Cpu, 0, len(cpus))
|
||||
for _, cpu := range cpus {
|
||||
self.List = append(self.List, Cpu{
|
||||
Idle: uint64(cpu.IdleTime / time.Millisecond),
|
||||
Sys: uint64(cpu.KernelTime / time.Millisecond),
|
||||
User: uint64(cpu.UserTime / time.Millisecond),
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *FileSystemList) Get() error {
|
||||
drives, err := windows.GetAccessPaths()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "GetAccessPaths failed")
|
||||
}
|
||||
|
||||
for _, drive := range drives {
|
||||
dt, err := windows.GetDriveType(drive)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "GetDriveType failed")
|
||||
}
|
||||
|
||||
self.List = append(self.List, FileSystem{
|
||||
DirName: drive,
|
||||
DevName: drive,
|
||||
TypeName: dt.String(),
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get retrieves a list of all process identifiers (PIDs) in the system.
|
||||
func (self *ProcList) Get() error {
|
||||
pids, err := windows.EnumProcesses()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "EnumProcesses failed")
|
||||
}
|
||||
|
||||
// Convert uint32 PIDs to int.
|
||||
self.List = make([]int, 0, len(pids))
|
||||
for _, pid := range pids {
|
||||
self.List = append(self.List, int(pid))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ProcState) Get(pid int) error {
|
||||
var errs []error
|
||||
|
||||
var err error
|
||||
self.Name, err = getProcName(pid)
|
||||
if err != nil {
|
||||
errs = append(errs, errors.Wrap(err, "getProcName failed"))
|
||||
}
|
||||
|
||||
self.State, err = getProcStatus(pid)
|
||||
if err != nil {
|
||||
errs = append(errs, errors.Wrap(err, "getProcStatus failed"))
|
||||
}
|
||||
|
||||
self.Ppid, err = getParentPid(pid)
|
||||
if err != nil {
|
||||
errs = append(errs, errors.Wrap(err, "getParentPid failed"))
|
||||
}
|
||||
|
||||
// getProcCredName will often fail when run as a non-admin user. This is
|
||||
// caused by strict ACL of the process token belonging to other users.
|
||||
// Instead of failing completely, ignore this error and still return most
|
||||
// data with an empty Username.
|
||||
self.Username, _ = getProcCredName(pid)
|
||||
|
||||
if len(errs) > 0 {
|
||||
errStrs := make([]string, 0, len(errs))
|
||||
for _, e := range errs {
|
||||
errStrs = append(errStrs, e.Error())
|
||||
}
|
||||
return errors.New(strings.Join(errStrs, "; "))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// getProcName returns the process name associated with the PID.
|
||||
func getProcName(pid int) (string, error) {
|
||||
handle, err := syscall.OpenProcess(processQueryLimitedInfoAccess, false, uint32(pid))
|
||||
if err != nil {
|
||||
return "", errors.Wrapf(err, "OpenProcess failed for pid=%v", pid)
|
||||
}
|
||||
defer syscall.CloseHandle(handle)
|
||||
|
||||
filename, err := windows.GetProcessImageFileName(handle)
|
||||
if err != nil {
|
||||
return "", errors.Wrapf(err, "GetProcessImageFileName failed for pid=%v", pid)
|
||||
}
|
||||
|
||||
return filepath.Base(filename), nil
|
||||
}
|
||||
|
||||
// getProcStatus returns the status of a process.
|
||||
func getProcStatus(pid int) (RunState, error) {
|
||||
handle, err := syscall.OpenProcess(processQueryLimitedInfoAccess, false, uint32(pid))
|
||||
if err != nil {
|
||||
return RunStateUnknown, errors.Wrapf(err, "OpenProcess failed for pid=%v", pid)
|
||||
}
|
||||
defer syscall.CloseHandle(handle)
|
||||
|
||||
var exitCode uint32
|
||||
err = syscall.GetExitCodeProcess(handle, &exitCode)
|
||||
if err != nil {
|
||||
return RunStateUnknown, errors.Wrapf(err, "GetExitCodeProcess failed for pid=%v", pid)
|
||||
}
|
||||
|
||||
if exitCode == 259 { //still active
|
||||
return RunStateRun, nil
|
||||
}
|
||||
return RunStateSleep, nil
|
||||
}
|
||||
|
||||
// getParentPid returns the parent process ID of a process.
|
||||
func getParentPid(pid int) (int, error) {
|
||||
handle, err := syscall.OpenProcess(processQueryLimitedInfoAccess, false, uint32(pid))
|
||||
if err != nil {
|
||||
return RunStateUnknown, errors.Wrapf(err, "OpenProcess failed for pid=%v", pid)
|
||||
}
|
||||
defer syscall.CloseHandle(handle)
|
||||
|
||||
procInfo, err := windows.NtQueryProcessBasicInformation(handle)
|
||||
if err != nil {
|
||||
return 0, errors.Wrapf(err, "NtQueryProcessBasicInformation failed for pid=%v", pid)
|
||||
}
|
||||
|
||||
return int(procInfo.InheritedFromUniqueProcessID), nil
|
||||
}
|
||||
|
||||
func getProcCredName(pid int) (string, error) {
|
||||
handle, err := syscall.OpenProcess(syscall.PROCESS_QUERY_INFORMATION, false, uint32(pid))
|
||||
if err != nil {
|
||||
return "", errors.Wrapf(err, "OpenProcess failed for pid=%v", pid)
|
||||
}
|
||||
defer syscall.CloseHandle(handle)
|
||||
|
||||
// Find process token via win32.
|
||||
var token syscall.Token
|
||||
err = syscall.OpenProcessToken(handle, syscall.TOKEN_QUERY, &token)
|
||||
if err != nil {
|
||||
return "", errors.Wrapf(err, "OpenProcessToken failed for pid=%v", pid)
|
||||
}
|
||||
// Close token to prevent handle leaks.
|
||||
defer token.Close()
|
||||
|
||||
// Find the token user.
|
||||
tokenUser, err := token.GetTokenUser()
|
||||
if err != nil {
|
||||
return "", errors.Wrapf(err, "GetTokenInformation failed for pid=%v", pid)
|
||||
}
|
||||
|
||||
// Look up domain account by SID.
|
||||
account, domain, _, err := tokenUser.User.Sid.LookupAccount("")
|
||||
if err != nil {
|
||||
sid, sidErr := tokenUser.User.Sid.String()
|
||||
if sidErr != nil {
|
||||
return "", errors.Wrapf(err, "failed while looking up account name for pid=%v", pid)
|
||||
}
|
||||
return "", errors.Wrapf(err, "failed while looking up account name for SID=%v of pid=%v", sid, pid)
|
||||
}
|
||||
|
||||
return fmt.Sprintf(`%s\%s`, domain, account), nil
|
||||
}
|
||||
|
||||
func (self *ProcMem) Get(pid int) error {
|
||||
handle, err := syscall.OpenProcess(processQueryLimitedInfoAccess|windows.PROCESS_VM_READ, false, uint32(pid))
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "OpenProcess failed for pid=%v", pid)
|
||||
}
|
||||
defer syscall.CloseHandle(handle)
|
||||
|
||||
counters, err := windows.GetProcessMemoryInfo(handle)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "GetProcessMemoryInfo failed for pid=%v", pid)
|
||||
}
|
||||
|
||||
self.Resident = uint64(counters.WorkingSetSize)
|
||||
self.Size = uint64(counters.PrivateUsage)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ProcTime) Get(pid int) error {
|
||||
cpu, err := getProcTimes(pid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Windows epoch times are expressed as time elapsed since midnight on
|
||||
// January 1, 1601 at Greenwich, England. This converts the Filetime to
|
||||
// unix epoch in milliseconds.
|
||||
self.StartTime = uint64(cpu.CreationTime.Nanoseconds() / 1e6)
|
||||
|
||||
// Convert to millis.
|
||||
self.User = uint64(windows.FiletimeToDuration(&cpu.UserTime).Nanoseconds() / 1e6)
|
||||
self.Sys = uint64(windows.FiletimeToDuration(&cpu.KernelTime).Nanoseconds() / 1e6)
|
||||
self.Total = self.User + self.Sys
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func getProcTimes(pid int) (*syscall.Rusage, error) {
|
||||
handle, err := syscall.OpenProcess(processQueryLimitedInfoAccess, false, uint32(pid))
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "OpenProcess failed for pid=%v", pid)
|
||||
}
|
||||
defer syscall.CloseHandle(handle)
|
||||
|
||||
var cpu syscall.Rusage
|
||||
if err := syscall.GetProcessTimes(handle, &cpu.CreationTime, &cpu.ExitTime, &cpu.KernelTime, &cpu.UserTime); err != nil {
|
||||
return nil, errors.Wrapf(err, "GetProcessTimes failed for pid=%v", pid)
|
||||
}
|
||||
|
||||
return &cpu, nil
|
||||
}
|
||||
|
||||
func (self *ProcArgs) Get(pid int) error {
|
||||
// The minimum supported client for Win32_Process is Windows Vista.
|
||||
if !version.IsWindowsVistaOrGreater() {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
handle, err := syscall.OpenProcess(processQueryLimitedInfoAccess|windows.PROCESS_VM_READ, false, uint32(pid))
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "OpenProcess failed for pid=%v", pid)
|
||||
}
|
||||
defer syscall.CloseHandle(handle)
|
||||
pbi, err := windows.NtQueryProcessBasicInformation(handle)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "NtQueryProcessBasicInformation failed for pid=%v", pid)
|
||||
}
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
userProcParams, err := windows.GetUserProcessParams(handle, pbi)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if argsW, err := windows.ReadProcessUnicodeString(handle, &userProcParams.CommandLine); err == nil {
|
||||
self.List, err = windows.ByteSliceToStringSlice(argsW)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *FileSystemUsage) Get(path string) error {
|
||||
freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes, err := windows.GetDiskFreeSpaceEx(path)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "GetDiskFreeSpaceEx failed")
|
||||
}
|
||||
|
||||
self.Total = totalNumberOfBytes
|
||||
self.Free = totalNumberOfFreeBytes
|
||||
self.Used = self.Total - self.Free
|
||||
self.Avail = freeBytesAvailable
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Rusage) Get(who int) error {
|
||||
if who != 0 {
|
||||
return ErrNotImplemented{runtime.GOOS}
|
||||
}
|
||||
|
||||
pid := os.Getpid()
|
||||
cpu, err := getProcTimes(pid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
self.Utime = windows.FiletimeToDuration(&cpu.UserTime)
|
||||
self.Stime = windows.FiletimeToDuration(&cpu.KernelTime)
|
||||
|
||||
return nil
|
||||
}
|
2
vendor/github.com/elastic/gosigar/sys/windows/doc.go
generated
vendored
Normal file
2
vendor/github.com/elastic/gosigar/sys/windows/doc.go
generated
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
// Package windows contains various Windows system call.
|
||||
package windows
|
132
vendor/github.com/elastic/gosigar/sys/windows/ntquery.go
generated
vendored
Normal file
132
vendor/github.com/elastic/gosigar/sys/windows/ntquery.go
generated
vendored
Normal file
@ -0,0 +1,132 @@
|
||||
// +build windows
|
||||
|
||||
package windows
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"runtime"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// On both 32-bit and 64-bit systems NtQuerySystemInformation expects the
|
||||
// size of SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION to be 48.
|
||||
const sizeofSystemProcessorPerformanceInformation = 48
|
||||
|
||||
// ProcessBasicInformation is an equivalent representation of
|
||||
// PROCESS_BASIC_INFORMATION in the Windows API.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms684280(v=vs.85).aspx
|
||||
type ProcessBasicInformation struct {
|
||||
ExitStatus uint
|
||||
PebBaseAddress uintptr
|
||||
AffinityMask uint
|
||||
BasePriority uint
|
||||
UniqueProcessID uint
|
||||
InheritedFromUniqueProcessID uint
|
||||
}
|
||||
|
||||
// NtQueryProcessBasicInformation queries basic information about the process
|
||||
// associated with the given handle (provided by OpenProcess). It uses the
|
||||
// NtQueryInformationProcess function to collect the data.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms684280(v=vs.85).aspx
|
||||
func NtQueryProcessBasicInformation(handle syscall.Handle) (ProcessBasicInformation, error) {
|
||||
var processBasicInfo ProcessBasicInformation
|
||||
processBasicInfoPtr := (*byte)(unsafe.Pointer(&processBasicInfo))
|
||||
size := uint32(unsafe.Sizeof(processBasicInfo))
|
||||
ntStatus, _ := _NtQueryInformationProcess(handle, 0, processBasicInfoPtr, size, nil)
|
||||
if ntStatus != 0 {
|
||||
return ProcessBasicInformation{}, errors.Errorf("NtQueryInformationProcess failed, NTSTATUS=0x%X", ntStatus)
|
||||
}
|
||||
|
||||
return processBasicInfo, nil
|
||||
}
|
||||
|
||||
// SystemProcessorPerformanceInformation contains CPU performance information
|
||||
// for a single CPU.
|
||||
type SystemProcessorPerformanceInformation struct {
|
||||
IdleTime time.Duration // Amount of time spent idle.
|
||||
KernelTime time.Duration // Kernel time does NOT include time spent in idle.
|
||||
UserTime time.Duration // Amount of time spent executing in user mode.
|
||||
}
|
||||
|
||||
// _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION is an equivalent representation of
|
||||
// SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION in the Windows API. This struct is
|
||||
// used internally with NtQuerySystemInformation call and is not exported. The
|
||||
// exported equivalent is SystemProcessorPerformanceInformation.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724509(v=vs.85).aspx
|
||||
type _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION struct {
|
||||
IdleTime int64
|
||||
KernelTime int64
|
||||
UserTime int64
|
||||
Reserved1 [2]int64
|
||||
Reserved2 uint32
|
||||
}
|
||||
|
||||
// NtQuerySystemProcessorPerformanceInformation queries CPU performance
|
||||
// information for each CPU. It uses the NtQuerySystemInformation function to
|
||||
// collect the SystemProcessorPerformanceInformation.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724509(v=vs.85).aspx
|
||||
func NtQuerySystemProcessorPerformanceInformation() ([]SystemProcessorPerformanceInformation, error) {
|
||||
// NTSTATUS code for success.
|
||||
// https://msdn.microsoft.com/en-us/library/cc704588.aspx
|
||||
const STATUS_SUCCESS = 0
|
||||
|
||||
// From the _SYSTEM_INFORMATION_CLASS enum.
|
||||
// http://processhacker.sourceforge.net/doc/ntexapi_8h.html#ad5d815b48e8f4da1ef2eb7a2f18a54e0
|
||||
const systemProcessorPerformanceInformation = 8
|
||||
|
||||
// Create a buffer large enough to hold an entry for each processor.
|
||||
b := make([]byte, runtime.NumCPU()*sizeofSystemProcessorPerformanceInformation)
|
||||
|
||||
// Query the performance information. Note that this function uses 0 to
|
||||
// indicate success. Most other Windows functions use non-zero for success.
|
||||
var returnLength uint32
|
||||
ntStatus, _ := _NtQuerySystemInformation(systemProcessorPerformanceInformation, &b[0], uint32(len(b)), &returnLength)
|
||||
if ntStatus != STATUS_SUCCESS {
|
||||
return nil, errors.Errorf("NtQuerySystemInformation failed, NTSTATUS=0x%X, bufLength=%v, returnLength=%v", ntStatus, len(b), returnLength)
|
||||
}
|
||||
|
||||
return readSystemProcessorPerformanceInformationBuffer(b)
|
||||
}
|
||||
|
||||
// readSystemProcessorPerformanceInformationBuffer reads from a buffer
|
||||
// containing SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION data. The buffer should
|
||||
// contain one entry for each CPU.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724509(v=vs.85).aspx
|
||||
func readSystemProcessorPerformanceInformationBuffer(b []byte) ([]SystemProcessorPerformanceInformation, error) {
|
||||
n := len(b) / sizeofSystemProcessorPerformanceInformation
|
||||
r := bytes.NewReader(b)
|
||||
|
||||
rtn := make([]SystemProcessorPerformanceInformation, 0, n)
|
||||
for i := 0; i < n; i++ {
|
||||
_, err := r.Seek(int64(i*sizeofSystemProcessorPerformanceInformation), io.SeekStart)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "failed to seek to cpuN=%v in buffer", i)
|
||||
}
|
||||
|
||||
times := make([]uint64, 3)
|
||||
for j := range times {
|
||||
err := binary.Read(r, binary.LittleEndian, ×[j])
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "failed reading cpu times for cpuN=%v", i)
|
||||
}
|
||||
}
|
||||
|
||||
idleTime := time.Duration(times[0] * 100)
|
||||
kernelTime := time.Duration(times[1] * 100)
|
||||
userTime := time.Duration(times[2] * 100)
|
||||
|
||||
rtn = append(rtn, SystemProcessorPerformanceInformation{
|
||||
IdleTime: idleTime,
|
||||
KernelTime: kernelTime - idleTime, // Subtract out idle time from kernel time.
|
||||
UserTime: userTime,
|
||||
})
|
||||
}
|
||||
|
||||
return rtn, nil
|
||||
}
|
272
vendor/github.com/elastic/gosigar/sys/windows/privileges.go
generated
vendored
Normal file
272
vendor/github.com/elastic/gosigar/sys/windows/privileges.go
generated
vendored
Normal file
@ -0,0 +1,272 @@
|
||||
// +build windows
|
||||
|
||||
package windows
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// Cache of privilege names to LUIDs.
|
||||
var (
|
||||
privNames = make(map[string]int64)
|
||||
privNameMutex sync.Mutex
|
||||
)
|
||||
|
||||
const (
|
||||
// SeDebugPrivilege is the name of the privilege used to debug programs.
|
||||
SeDebugPrivilege = "SeDebugPrivilege"
|
||||
)
|
||||
|
||||
// Errors returned by AdjustTokenPrivileges.
|
||||
const (
|
||||
ERROR_NOT_ALL_ASSIGNED syscall.Errno = 1300
|
||||
)
|
||||
|
||||
// Attribute bits for privileges.
|
||||
const (
|
||||
_SE_PRIVILEGE_ENABLED_BY_DEFAULT uint32 = 0x00000001
|
||||
_SE_PRIVILEGE_ENABLED uint32 = 0x00000002
|
||||
_SE_PRIVILEGE_REMOVED uint32 = 0x00000004
|
||||
_SE_PRIVILEGE_USED_FOR_ACCESS uint32 = 0x80000000
|
||||
)
|
||||
|
||||
// Privilege contains information about a single privilege associated with a
|
||||
// Token.
|
||||
type Privilege struct {
|
||||
LUID int64 `json:"-"` // Locally unique identifier (guaranteed only until the system is restarted).
|
||||
Name string `json:"-"`
|
||||
EnabledByDefault bool `json:"enabled_by_default,omitempty"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Removed bool `json:"removed,omitempty"`
|
||||
Used bool `json:"used,omitempty"`
|
||||
}
|
||||
|
||||
func (p Privilege) String() string {
|
||||
var buf bytes.Buffer
|
||||
buf.WriteString(p.Name)
|
||||
buf.WriteString("=(")
|
||||
|
||||
opts := make([]string, 0, 4)
|
||||
if p.EnabledByDefault {
|
||||
opts = append(opts, "Default")
|
||||
}
|
||||
if p.Enabled {
|
||||
opts = append(opts, "Enabled")
|
||||
}
|
||||
if !p.EnabledByDefault && !p.Enabled {
|
||||
opts = append(opts, "Disabled")
|
||||
}
|
||||
if p.Removed {
|
||||
opts = append(opts, "Removed")
|
||||
}
|
||||
if p.Used {
|
||||
opts = append(opts, "Used")
|
||||
}
|
||||
|
||||
buf.WriteString(strings.Join(opts, ", "))
|
||||
buf.WriteString(")")
|
||||
|
||||
// Example: SeDebugPrivilege=(Default, Enabled)
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// User represent the information about a Windows account.
|
||||
type User struct {
|
||||
SID string
|
||||
Account string
|
||||
Domain string
|
||||
Type uint32
|
||||
}
|
||||
|
||||
func (u User) String() string {
|
||||
return fmt.Sprintf(`User:%v\%v, SID:%v, Type:%v`, u.Domain, u.Account, u.SID, u.Type)
|
||||
}
|
||||
|
||||
// DebugInfo contains general debug info about the current process.
|
||||
type DebugInfo struct {
|
||||
OSVersion Version // OS version info.
|
||||
Arch string // Architecture of the machine.
|
||||
NumCPU int // Number of CPUs.
|
||||
User User // User that this process is running as.
|
||||
ProcessPrivs map[string]Privilege // Privileges held by the process.
|
||||
}
|
||||
|
||||
func (d DebugInfo) String() string {
|
||||
bytes, _ := json.Marshal(d)
|
||||
return string(bytes)
|
||||
}
|
||||
|
||||
// LookupPrivilegeName looks up a privilege name given a LUID value.
|
||||
func LookupPrivilegeName(systemName string, luid int64) (string, error) {
|
||||
buf := make([]uint16, 256)
|
||||
bufSize := uint32(len(buf))
|
||||
err := _LookupPrivilegeName(systemName, &luid, &buf[0], &bufSize)
|
||||
if err != nil {
|
||||
return "", errors.Wrapf(err, "LookupPrivilegeName failed for luid=%v", luid)
|
||||
}
|
||||
|
||||
return syscall.UTF16ToString(buf), nil
|
||||
}
|
||||
|
||||
// mapPrivileges maps privilege names to LUID values.
|
||||
func mapPrivileges(names []string) ([]int64, error) {
|
||||
var privileges []int64
|
||||
privNameMutex.Lock()
|
||||
defer privNameMutex.Unlock()
|
||||
for _, name := range names {
|
||||
p, ok := privNames[name]
|
||||
if !ok {
|
||||
err := _LookupPrivilegeValue("", name, &p)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "LookupPrivilegeValue failed on '%v'", name)
|
||||
}
|
||||
privNames[name] = p
|
||||
}
|
||||
privileges = append(privileges, p)
|
||||
}
|
||||
return privileges, nil
|
||||
}
|
||||
|
||||
// EnableTokenPrivileges enables the specified privileges in the given
|
||||
// Token. The token must have TOKEN_ADJUST_PRIVILEGES access. If the token
|
||||
// does not already contain the privilege it cannot be enabled.
|
||||
func EnableTokenPrivileges(token syscall.Token, privileges ...string) error {
|
||||
privValues, err := mapPrivileges(privileges)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var b bytes.Buffer
|
||||
binary.Write(&b, binary.LittleEndian, uint32(len(privValues)))
|
||||
for _, p := range privValues {
|
||||
binary.Write(&b, binary.LittleEndian, p)
|
||||
binary.Write(&b, binary.LittleEndian, uint32(_SE_PRIVILEGE_ENABLED))
|
||||
}
|
||||
|
||||
success, err := _AdjustTokenPrivileges(token, false, &b.Bytes()[0], uint32(b.Len()), nil, nil)
|
||||
if !success {
|
||||
return err
|
||||
}
|
||||
if err == ERROR_NOT_ALL_ASSIGNED {
|
||||
return errors.Wrap(err, "error not all privileges were assigned")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetTokenPrivileges returns a list of privileges associated with a token.
|
||||
// The provided token must have at a minimum TOKEN_QUERY access. This is a
|
||||
// wrapper around the GetTokenInformation function.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa446671(v=vs.85).aspx
|
||||
func GetTokenPrivileges(token syscall.Token) (map[string]Privilege, error) {
|
||||
// Determine the required buffer size.
|
||||
var size uint32
|
||||
syscall.GetTokenInformation(token, syscall.TokenPrivileges, nil, 0, &size)
|
||||
|
||||
// This buffer will receive a TOKEN_PRIVILEGE structure.
|
||||
b := bytes.NewBuffer(make([]byte, size))
|
||||
err := syscall.GetTokenInformation(token, syscall.TokenPrivileges, &b.Bytes()[0], uint32(b.Len()), &size)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "GetTokenInformation failed")
|
||||
}
|
||||
|
||||
var privilegeCount uint32
|
||||
err = binary.Read(b, binary.LittleEndian, &privilegeCount)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to read PrivilegeCount")
|
||||
}
|
||||
|
||||
rtn := make(map[string]Privilege, privilegeCount)
|
||||
for i := 0; i < int(privilegeCount); i++ {
|
||||
var luid int64
|
||||
err = binary.Read(b, binary.LittleEndian, &luid)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to read LUID value")
|
||||
}
|
||||
|
||||
var attributes uint32
|
||||
err = binary.Read(b, binary.LittleEndian, &attributes)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to read attributes")
|
||||
}
|
||||
|
||||
name, err := LookupPrivilegeName("", luid)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "LookupPrivilegeName failed for LUID=%v", luid)
|
||||
}
|
||||
|
||||
rtn[name] = Privilege{
|
||||
LUID: luid,
|
||||
Name: name,
|
||||
EnabledByDefault: (attributes & _SE_PRIVILEGE_ENABLED_BY_DEFAULT) > 0,
|
||||
Enabled: (attributes & _SE_PRIVILEGE_ENABLED) > 0,
|
||||
Removed: (attributes & _SE_PRIVILEGE_REMOVED) > 0,
|
||||
Used: (attributes & _SE_PRIVILEGE_USED_FOR_ACCESS) > 0,
|
||||
}
|
||||
}
|
||||
|
||||
return rtn, nil
|
||||
}
|
||||
|
||||
// GetTokenUser returns the User associated with the given Token.
|
||||
func GetTokenUser(token syscall.Token) (User, error) {
|
||||
tokenUser, err := token.GetTokenUser()
|
||||
if err != nil {
|
||||
return User{}, errors.Wrap(err, "GetTokenUser failed")
|
||||
}
|
||||
|
||||
var user User
|
||||
user.SID, err = tokenUser.User.Sid.String()
|
||||
if err != nil {
|
||||
return user, errors.Wrap(err, "ConvertSidToStringSid failed")
|
||||
}
|
||||
|
||||
user.Account, user.Domain, user.Type, err = tokenUser.User.Sid.LookupAccount("")
|
||||
if err != nil {
|
||||
return user, errors.Wrap(err, "LookupAccountSid failed")
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// GetDebugInfo returns general debug info about the current process.
|
||||
func GetDebugInfo() (*DebugInfo, error) {
|
||||
h, err := windows.GetCurrentProcess()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var token syscall.Token
|
||||
err = syscall.OpenProcessToken(syscall.Handle(h), syscall.TOKEN_QUERY, &token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
privs, err := GetTokenPrivileges(token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
user, err := GetTokenUser(token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &DebugInfo{
|
||||
User: user,
|
||||
ProcessPrivs: privs,
|
||||
OSVersion: GetWindowsVersion(),
|
||||
Arch: runtime.GOARCH,
|
||||
NumCPU: runtime.NumCPU(),
|
||||
}, nil
|
||||
}
|
588
vendor/github.com/elastic/gosigar/sys/windows/syscall_windows.go
generated
vendored
Normal file
588
vendor/github.com/elastic/gosigar/sys/windows/syscall_windows.go
generated
vendored
Normal file
@ -0,0 +1,588 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
var (
|
||||
sizeofUint32 = 4
|
||||
sizeofProcessEntry32 = uint32(unsafe.Sizeof(ProcessEntry32{}))
|
||||
sizeofProcessMemoryCountersEx = uint32(unsafe.Sizeof(ProcessMemoryCountersEx{}))
|
||||
sizeofMemoryStatusEx = uint32(unsafe.Sizeof(MemoryStatusEx{}))
|
||||
)
|
||||
|
||||
// Process-specific access rights. Others are declared in the syscall package.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx
|
||||
const (
|
||||
PROCESS_QUERY_LIMITED_INFORMATION uint32 = 0x1000
|
||||
PROCESS_VM_READ uint32 = 0x0010
|
||||
)
|
||||
|
||||
// SizeOfRtlUserProcessParameters gives the size
|
||||
// of the RtlUserProcessParameters struct.
|
||||
const SizeOfRtlUserProcessParameters = unsafe.Sizeof(RtlUserProcessParameters{})
|
||||
|
||||
// MAX_PATH is the maximum length for a path in Windows.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
|
||||
const MAX_PATH = 260
|
||||
|
||||
// DriveType represents a type of drive (removable, fixed, CD-ROM, RAM disk, or
|
||||
// network drive).
|
||||
type DriveType uint32
|
||||
|
||||
// Drive types as returned by GetDriveType.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa364939(v=vs.85).aspx
|
||||
const (
|
||||
DRIVE_UNKNOWN DriveType = iota
|
||||
DRIVE_NO_ROOT_DIR
|
||||
DRIVE_REMOVABLE
|
||||
DRIVE_FIXED
|
||||
DRIVE_REMOTE
|
||||
DRIVE_CDROM
|
||||
DRIVE_RAMDISK
|
||||
)
|
||||
|
||||
// UnicodeString is Go's equivalent for the _UNICODE_STRING struct.
|
||||
type UnicodeString struct {
|
||||
Size uint16
|
||||
MaximumLength uint16
|
||||
Buffer uintptr
|
||||
}
|
||||
|
||||
// RtlUserProcessParameters is Go's equivalent for the
|
||||
// _RTL_USER_PROCESS_PARAMETERS struct.
|
||||
// A few undocumented fields are exposed.
|
||||
type RtlUserProcessParameters struct {
|
||||
Reserved1 [16]byte
|
||||
Reserved2 [5]uintptr
|
||||
CurrentDirectoryPath UnicodeString
|
||||
CurrentDirectoryHandle uintptr
|
||||
DllPath UnicodeString
|
||||
ImagePathName UnicodeString
|
||||
CommandLine UnicodeString
|
||||
}
|
||||
|
||||
func (dt DriveType) String() string {
|
||||
names := map[DriveType]string{
|
||||
DRIVE_UNKNOWN: "unknown",
|
||||
DRIVE_NO_ROOT_DIR: "invalid",
|
||||
DRIVE_REMOVABLE: "removable",
|
||||
DRIVE_FIXED: "fixed",
|
||||
DRIVE_REMOTE: "remote",
|
||||
DRIVE_CDROM: "cdrom",
|
||||
DRIVE_RAMDISK: "ramdisk",
|
||||
}
|
||||
|
||||
name, found := names[dt]
|
||||
if !found {
|
||||
return "unknown DriveType value"
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
// Flags that can be used with CreateToolhelp32Snapshot.
|
||||
const (
|
||||
TH32CS_INHERIT uint32 = 0x80000000 // Indicates that the snapshot handle is to be inheritable.
|
||||
TH32CS_SNAPHEAPLIST uint32 = 0x00000001 // Includes all heaps of the process specified in th32ProcessID in the snapshot.
|
||||
TH32CS_SNAPMODULE uint32 = 0x00000008 // Includes all modules of the process specified in th32ProcessID in the snapshot.
|
||||
TH32CS_SNAPMODULE32 uint32 = 0x00000010 // Includes all 32-bit modules of the process specified in th32ProcessID in the snapshot when called from a 64-bit process.
|
||||
TH32CS_SNAPPROCESS uint32 = 0x00000002 // Includes all processes in the system in the snapshot.
|
||||
TH32CS_SNAPTHREAD uint32 = 0x00000004 // Includes all threads in the system in the snapshot.
|
||||
)
|
||||
|
||||
// ProcessEntry32 is an equivalent representation of PROCESSENTRY32 in the
|
||||
// Windows API. It contains a process's information. Do not modify or reorder.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms684839(v=vs.85).aspx
|
||||
type ProcessEntry32 struct {
|
||||
size uint32
|
||||
CntUsage uint32
|
||||
ProcessID uint32
|
||||
DefaultHeapID uintptr
|
||||
ModuleID uint32
|
||||
CntThreads uint32
|
||||
ParentProcessID uint32
|
||||
PriorityClassBase int32
|
||||
Flags uint32
|
||||
exeFile [MAX_PATH]uint16
|
||||
}
|
||||
|
||||
// ExeFile returns the name of the executable file for the process. It does
|
||||
// not contain the full path.
|
||||
func (p ProcessEntry32) ExeFile() string {
|
||||
return syscall.UTF16ToString(p.exeFile[:])
|
||||
}
|
||||
|
||||
func (p ProcessEntry32) String() string {
|
||||
return fmt.Sprintf("{CntUsage:%v ProcessID:%v DefaultHeapID:%v ModuleID:%v "+
|
||||
"CntThreads:%v ParentProcessID:%v PriorityClassBase:%v Flags:%v ExeFile:%v",
|
||||
p.CntUsage, p.ProcessID, p.DefaultHeapID, p.ModuleID, p.CntThreads,
|
||||
p.ParentProcessID, p.PriorityClassBase, p.Flags, p.ExeFile())
|
||||
}
|
||||
|
||||
// MemoryStatusEx is an equivalent representation of MEMORYSTATUSEX in the
|
||||
// Windows API. It contains information about the current state of both physical
|
||||
// and virtual memory, including extended memory.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366770
|
||||
type MemoryStatusEx struct {
|
||||
length uint32
|
||||
MemoryLoad uint32
|
||||
TotalPhys uint64
|
||||
AvailPhys uint64
|
||||
TotalPageFile uint64
|
||||
AvailPageFile uint64
|
||||
TotalVirtual uint64
|
||||
AvailVirtual uint64
|
||||
AvailExtendedVirtual uint64
|
||||
}
|
||||
|
||||
// ProcessMemoryCountersEx is an equivalent representation of
|
||||
// PROCESS_MEMORY_COUNTERS_EX in the Windows API.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms684874(v=vs.85).aspx
|
||||
type ProcessMemoryCountersEx struct {
|
||||
cb uint32
|
||||
PageFaultCount uint32
|
||||
PeakWorkingSetSize uintptr
|
||||
WorkingSetSize uintptr
|
||||
QuotaPeakPagedPoolUsage uintptr
|
||||
QuotaPagedPoolUsage uintptr
|
||||
QuotaPeakNonPagedPoolUsage uintptr
|
||||
QuotaNonPagedPoolUsage uintptr
|
||||
PagefileUsage uintptr
|
||||
PeakPagefileUsage uintptr
|
||||
PrivateUsage uintptr
|
||||
}
|
||||
|
||||
// GetLogicalDriveStrings returns a list of drives in the system.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa364975(v=vs.85).aspx
|
||||
func GetLogicalDriveStrings() ([]string, error) {
|
||||
// Determine the size of the buffer required to receive all drives.
|
||||
bufferLength, err := _GetLogicalDriveStringsW(0, nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "GetLogicalDriveStringsW failed to get buffer length")
|
||||
}
|
||||
if bufferLength < 0 {
|
||||
return nil, errors.New("GetLogicalDriveStringsW returned an invalid buffer length")
|
||||
}
|
||||
|
||||
buffer := make([]uint16, bufferLength)
|
||||
_, err = _GetLogicalDriveStringsW(uint32(len(buffer)), &buffer[0])
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "GetLogicalDriveStringsW failed")
|
||||
}
|
||||
|
||||
return UTF16SliceToStringSlice(buffer), nil
|
||||
}
|
||||
|
||||
// GetAccessPaths returns the list of access paths for volumes in the system.
|
||||
func GetAccessPaths() ([]string, error) {
|
||||
volumes, err := GetVolumes()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "GetVolumes failed")
|
||||
}
|
||||
|
||||
var paths []string
|
||||
for _, volumeName := range volumes {
|
||||
volumePaths, err := GetVolumePathsForVolume(volumeName)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "failed to get list of access paths for volume '%s'", volumeName)
|
||||
}
|
||||
if len(volumePaths) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// Get only the first path
|
||||
paths = append(paths, volumePaths[0])
|
||||
}
|
||||
|
||||
return paths, nil
|
||||
}
|
||||
|
||||
// GetVolumes returs the list of volumes in the system.
|
||||
// https://docs.microsoft.com/es-es/windows/desktop/api/fileapi/nf-fileapi-findfirstvolumew
|
||||
func GetVolumes() ([]string, error) {
|
||||
buffer := make([]uint16, MAX_PATH+1)
|
||||
|
||||
var volumes []string
|
||||
|
||||
h, err := _FindFirstVolume(&buffer[0], uint32(len(buffer)))
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "FindFirstVolumeW failed")
|
||||
}
|
||||
defer _FindVolumeClose(h)
|
||||
|
||||
for {
|
||||
volumes = append(volumes, syscall.UTF16ToString(buffer))
|
||||
|
||||
err = _FindNextVolume(h, &buffer[0], uint32(len(buffer)))
|
||||
if err != nil {
|
||||
if errors.Cause(err) == syscall.ERROR_NO_MORE_FILES {
|
||||
break
|
||||
}
|
||||
return nil, errors.Wrap(err, "FindNextVolumeW failed")
|
||||
}
|
||||
}
|
||||
|
||||
return volumes, nil
|
||||
}
|
||||
|
||||
// GetVolumePathsForVolume returns the list of volume paths for a volume.
|
||||
// https://docs.microsoft.com/en-us/windows/desktop/api/FileAPI/nf-fileapi-getvolumepathnamesforvolumenamew
|
||||
func GetVolumePathsForVolume(volumeName string) ([]string, error) {
|
||||
var length uint32
|
||||
err := _GetVolumePathNamesForVolumeName(volumeName, nil, 0, &length)
|
||||
if errors.Cause(err) != syscall.ERROR_MORE_DATA {
|
||||
return nil, errors.Wrap(err, "GetVolumePathNamesForVolumeNameW failed to get needed buffer length")
|
||||
}
|
||||
if length == 0 {
|
||||
// Not mounted, no paths, that's ok
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
buffer := make([]uint16, length*(MAX_PATH+1))
|
||||
err = _GetVolumePathNamesForVolumeName(volumeName, &buffer[0], length, &length)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "GetVolumePathNamesForVolumeNameW failed")
|
||||
}
|
||||
|
||||
return UTF16SliceToStringSlice(buffer), nil
|
||||
}
|
||||
|
||||
// GlobalMemoryStatusEx retrieves information about the system's current usage
|
||||
// of both physical and virtual memory.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366589(v=vs.85).aspx
|
||||
func GlobalMemoryStatusEx() (MemoryStatusEx, error) {
|
||||
memoryStatusEx := MemoryStatusEx{length: sizeofMemoryStatusEx}
|
||||
err := _GlobalMemoryStatusEx(&memoryStatusEx)
|
||||
if err != nil {
|
||||
return MemoryStatusEx{}, errors.Wrap(err, "GlobalMemoryStatusEx failed")
|
||||
}
|
||||
|
||||
return memoryStatusEx, nil
|
||||
}
|
||||
|
||||
// GetProcessMemoryInfo retrieves information about the memory usage of the
|
||||
// specified process.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms683219(v=vs.85).aspx
|
||||
func GetProcessMemoryInfo(handle syscall.Handle) (ProcessMemoryCountersEx, error) {
|
||||
processMemoryCountersEx := ProcessMemoryCountersEx{cb: sizeofProcessMemoryCountersEx}
|
||||
err := _GetProcessMemoryInfo(handle, &processMemoryCountersEx, processMemoryCountersEx.cb)
|
||||
if err != nil {
|
||||
return ProcessMemoryCountersEx{}, errors.Wrap(err, "GetProcessMemoryInfo failed")
|
||||
}
|
||||
|
||||
return processMemoryCountersEx, nil
|
||||
}
|
||||
|
||||
// GetProcessImageFileName Retrieves the name of the executable file for the
|
||||
// specified process.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms683217(v=vs.85).aspx
|
||||
func GetProcessImageFileName(handle syscall.Handle) (string, error) {
|
||||
buffer := make([]uint16, MAX_PATH)
|
||||
_, err := _GetProcessImageFileName(handle, &buffer[0], uint32(len(buffer)))
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, "GetProcessImageFileName failed")
|
||||
}
|
||||
|
||||
return syscall.UTF16ToString(buffer), nil
|
||||
}
|
||||
|
||||
// GetSystemTimes retrieves system timing information. On a multiprocessor
|
||||
// system, the values returned are the sum of the designated times across all
|
||||
// processors. The returned kernel time does not include the system idle time.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724400(v=vs.85).aspx
|
||||
func GetSystemTimes() (idle, kernel, user time.Duration, err error) {
|
||||
var idleTime, kernelTime, userTime syscall.Filetime
|
||||
err = _GetSystemTimes(&idleTime, &kernelTime, &userTime)
|
||||
if err != nil {
|
||||
return 0, 0, 0, errors.Wrap(err, "GetSystemTimes failed")
|
||||
}
|
||||
|
||||
idle = FiletimeToDuration(&idleTime)
|
||||
kernel = FiletimeToDuration(&kernelTime) // Kernel time includes idle time so we subtract it out.
|
||||
user = FiletimeToDuration(&userTime)
|
||||
|
||||
return idle, kernel - idle, user, nil
|
||||
}
|
||||
|
||||
// FiletimeToDuration converts a Filetime to a time.Duration. Do not use this
|
||||
// method to convert a Filetime to an actual clock time, for that use
|
||||
// Filetime.Nanosecond().
|
||||
func FiletimeToDuration(ft *syscall.Filetime) time.Duration {
|
||||
n := int64(ft.HighDateTime)<<32 + int64(ft.LowDateTime) // in 100-nanosecond intervals
|
||||
return time.Duration(n * 100)
|
||||
}
|
||||
|
||||
// GetDriveType Determines whether a disk drive is a removable, fixed, CD-ROM,
|
||||
// RAM disk, or network drive. A trailing backslash is required on the
|
||||
// rootPathName.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa364939
|
||||
func GetDriveType(rootPathName string) (DriveType, error) {
|
||||
rootPathNamePtr, err := syscall.UTF16PtrFromString(rootPathName)
|
||||
if err != nil {
|
||||
return DRIVE_UNKNOWN, errors.Wrapf(err, "UTF16PtrFromString failed for rootPathName=%v", rootPathName)
|
||||
}
|
||||
|
||||
dt, err := _GetDriveType(rootPathNamePtr)
|
||||
if err != nil {
|
||||
return DRIVE_UNKNOWN, errors.Wrapf(err, "GetDriveType failed for rootPathName=%v", rootPathName)
|
||||
}
|
||||
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
// EnumProcesses retrieves the process identifier for each process object in the
|
||||
// system. This function can return a max of 65536 PIDs. If there are more
|
||||
// processes than that then this will not return them all.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms682629(v=vs.85).aspx
|
||||
func EnumProcesses() ([]uint32, error) {
|
||||
enumProcesses := func(size int) ([]uint32, error) {
|
||||
var (
|
||||
pids = make([]uint32, size)
|
||||
sizeBytes = len(pids) * sizeofUint32
|
||||
bytesWritten uint32
|
||||
)
|
||||
|
||||
err := _EnumProcesses(&pids[0], uint32(sizeBytes), &bytesWritten)
|
||||
|
||||
pidsWritten := int(bytesWritten) / sizeofUint32
|
||||
if int(bytesWritten)%sizeofUint32 != 0 || pidsWritten > len(pids) {
|
||||
return nil, errors.Errorf("EnumProcesses returned an invalid bytesWritten value of %v", bytesWritten)
|
||||
}
|
||||
pids = pids[:pidsWritten]
|
||||
|
||||
return pids, err
|
||||
}
|
||||
|
||||
// Retry the EnumProcesses call with larger arrays if needed.
|
||||
size := 2048
|
||||
var pids []uint32
|
||||
for tries := 0; tries < 5; tries++ {
|
||||
var err error
|
||||
pids, err = enumProcesses(size)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "EnumProcesses failed")
|
||||
}
|
||||
|
||||
if len(pids) < size {
|
||||
break
|
||||
}
|
||||
|
||||
// Increase the size the pids array and retry the enumProcesses call
|
||||
// because the array wasn't large enough to hold all of the processes.
|
||||
size *= 2
|
||||
}
|
||||
|
||||
return pids, nil
|
||||
}
|
||||
|
||||
// GetDiskFreeSpaceEx retrieves information about the amount of space that is
|
||||
// available on a disk volume, which is the total amount of space, the total
|
||||
// amount of free space, and the total amount of free space available to the
|
||||
// user that is associated with the calling thread.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa364937(v=vs.85).aspx
|
||||
func GetDiskFreeSpaceEx(directoryName string) (freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes uint64, err error) {
|
||||
directoryNamePtr, err := syscall.UTF16PtrFromString(directoryName)
|
||||
if err != nil {
|
||||
return 0, 0, 0, errors.Wrapf(err, "UTF16PtrFromString failed for directoryName=%v", directoryName)
|
||||
}
|
||||
|
||||
err = _GetDiskFreeSpaceEx(directoryNamePtr, &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes)
|
||||
if err != nil {
|
||||
return 0, 0, 0, err
|
||||
}
|
||||
|
||||
return freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes, nil
|
||||
}
|
||||
|
||||
// CreateToolhelp32Snapshot takes a snapshot of the specified processes, as well
|
||||
// as the heaps, modules, and threads used by these processes.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms682489(v=vs.85).aspx
|
||||
func CreateToolhelp32Snapshot(flags, pid uint32) (syscall.Handle, error) {
|
||||
h, err := _CreateToolhelp32Snapshot(flags, pid)
|
||||
if err != nil {
|
||||
return syscall.InvalidHandle, err
|
||||
}
|
||||
if h == syscall.InvalidHandle {
|
||||
return syscall.InvalidHandle, syscall.GetLastError()
|
||||
}
|
||||
|
||||
return h, nil
|
||||
}
|
||||
|
||||
// Process32First retrieves information about the first process encountered in a
|
||||
// system snapshot.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms684834
|
||||
func Process32First(handle syscall.Handle) (ProcessEntry32, error) {
|
||||
processEntry32 := ProcessEntry32{size: sizeofProcessEntry32}
|
||||
err := _Process32First(handle, &processEntry32)
|
||||
if err != nil {
|
||||
return ProcessEntry32{}, errors.Wrap(err, "Process32First failed")
|
||||
}
|
||||
|
||||
return processEntry32, nil
|
||||
}
|
||||
|
||||
// Process32Next retrieves information about the next process recorded in a
|
||||
// system snapshot. When there are no more processes to iterate then
|
||||
// syscall.ERROR_NO_MORE_FILES is returned (use errors.Cause() to unwrap).
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms684836
|
||||
func Process32Next(handle syscall.Handle) (ProcessEntry32, error) {
|
||||
processEntry32 := ProcessEntry32{size: sizeofProcessEntry32}
|
||||
err := _Process32Next(handle, &processEntry32)
|
||||
if err != nil {
|
||||
return ProcessEntry32{}, errors.Wrap(err, "Process32Next failed")
|
||||
}
|
||||
|
||||
return processEntry32, nil
|
||||
}
|
||||
|
||||
// UTF16SliceToStringSlice converts slice of uint16 containing a list of UTF16
|
||||
// strings to a slice of strings.
|
||||
func UTF16SliceToStringSlice(buffer []uint16) []string {
|
||||
// Split the uint16 slice at null-terminators.
|
||||
var startIdx int
|
||||
var stringsUTF16 [][]uint16
|
||||
for i, value := range buffer {
|
||||
if value == 0 {
|
||||
stringsUTF16 = append(stringsUTF16, buffer[startIdx:i])
|
||||
startIdx = i + 1
|
||||
}
|
||||
}
|
||||
|
||||
// Convert the utf16 slices to strings.
|
||||
result := make([]string, 0, len(stringsUTF16))
|
||||
for _, stringUTF16 := range stringsUTF16 {
|
||||
if len(stringUTF16) > 0 {
|
||||
result = append(result, syscall.UTF16ToString(stringUTF16))
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func GetUserProcessParams(handle syscall.Handle, pbi ProcessBasicInformation) (params RtlUserProcessParameters, err error) {
|
||||
const is32bitProc = unsafe.Sizeof(uintptr(0)) == 4
|
||||
|
||||
// Offset of params field within PEB structure.
|
||||
// This structure is different in 32 and 64 bit.
|
||||
paramsOffset := 0x20
|
||||
if is32bitProc {
|
||||
paramsOffset = 0x10
|
||||
}
|
||||
|
||||
// Read the PEB from the target process memory
|
||||
pebSize := paramsOffset + 8
|
||||
peb := make([]byte, pebSize)
|
||||
nRead, err := ReadProcessMemory(handle, pbi.PebBaseAddress, peb)
|
||||
if err != nil {
|
||||
return params, err
|
||||
}
|
||||
if nRead != uintptr(pebSize) {
|
||||
return params, errors.Errorf("PEB: short read (%d/%d)", nRead, pebSize)
|
||||
}
|
||||
|
||||
// Get the RTL_USER_PROCESS_PARAMETERS struct pointer from the PEB
|
||||
paramsAddr := *(*uintptr)(unsafe.Pointer(&peb[paramsOffset]))
|
||||
|
||||
// Read the RTL_USER_PROCESS_PARAMETERS from the target process memory
|
||||
paramsBuf := make([]byte, SizeOfRtlUserProcessParameters)
|
||||
nRead, err = ReadProcessMemory(handle, paramsAddr, paramsBuf)
|
||||
if err != nil {
|
||||
return params, err
|
||||
}
|
||||
if nRead != uintptr(SizeOfRtlUserProcessParameters) {
|
||||
return params, errors.Errorf("RTL_USER_PROCESS_PARAMETERS: short read (%d/%d)", nRead, SizeOfRtlUserProcessParameters)
|
||||
}
|
||||
|
||||
params = *(*RtlUserProcessParameters)(unsafe.Pointer(¶msBuf[0]))
|
||||
return params, nil
|
||||
}
|
||||
|
||||
func ReadProcessUnicodeString(handle syscall.Handle, s *UnicodeString) ([]byte, error) {
|
||||
buf := make([]byte, s.Size)
|
||||
nRead, err := ReadProcessMemory(handle, s.Buffer, buf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if nRead != uintptr(s.Size) {
|
||||
return nil, errors.Errorf("unicode string: short read: (%d/%d)", nRead, s.Size)
|
||||
}
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
// Use Windows' CommandLineToArgv API to split an UTF-16 command line string
|
||||
// into a list of parameters.
|
||||
func ByteSliceToStringSlice(utf16 []byte) ([]string, error) {
|
||||
if len(utf16) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var numArgs int32
|
||||
argsWide, err := syscall.CommandLineToArgv((*uint16)(unsafe.Pointer(&utf16[0])), &numArgs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Free memory allocated for CommandLineToArgvW arguments.
|
||||
defer syscall.LocalFree((syscall.Handle)(unsafe.Pointer(argsWide)))
|
||||
|
||||
args := make([]string, numArgs)
|
||||
for idx := range args {
|
||||
args[idx] = syscall.UTF16ToString(argsWide[idx][:])
|
||||
}
|
||||
return args, nil
|
||||
}
|
||||
|
||||
// ReadProcessMemory reads from another process memory. The Handle needs to have
|
||||
// the PROCESS_VM_READ right.
|
||||
// A zero-byte read is a no-op, no error is returned.
|
||||
func ReadProcessMemory(handle syscall.Handle, baseAddress uintptr, dest []byte) (numRead uintptr, err error) {
|
||||
n := len(dest)
|
||||
if n == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
if err = _ReadProcessMemory(handle, baseAddress, uintptr(unsafe.Pointer(&dest[0])), uintptr(n), &numRead); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return numRead, nil
|
||||
}
|
||||
|
||||
func GetTickCount64() (uptime uint64, err error) {
|
||||
if uptime, err = _GetTickCount64(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return uptime, nil
|
||||
}
|
||||
|
||||
// Use "GOOS=windows go generate -v -x ." to generate the source.
|
||||
|
||||
// Add -trace to enable debug prints around syscalls.
|
||||
//go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -systemdll=false -output zsyscall_windows.go syscall_windows.go
|
||||
|
||||
// Windows API calls
|
||||
//sys _GlobalMemoryStatusEx(buffer *MemoryStatusEx) (err error) = kernel32.GlobalMemoryStatusEx
|
||||
//sys _GetLogicalDriveStringsW(bufferLength uint32, buffer *uint16) (length uint32, err error) = kernel32.GetLogicalDriveStringsW
|
||||
//sys _GetProcessMemoryInfo(handle syscall.Handle, psmemCounters *ProcessMemoryCountersEx, cb uint32) (err error) = psapi.GetProcessMemoryInfo
|
||||
//sys _GetProcessImageFileName(handle syscall.Handle, outImageFileName *uint16, size uint32) (length uint32, err error) = psapi.GetProcessImageFileNameW
|
||||
//sys _GetSystemTimes(idleTime *syscall.Filetime, kernelTime *syscall.Filetime, userTime *syscall.Filetime) (err error) = kernel32.GetSystemTimes
|
||||
//sys _GetDriveType(rootPathName *uint16) (dt DriveType, err error) = kernel32.GetDriveTypeW
|
||||
//sys _EnumProcesses(processIds *uint32, sizeBytes uint32, bytesReturned *uint32) (err error) = psapi.EnumProcesses
|
||||
//sys _GetDiskFreeSpaceEx(directoryName *uint16, freeBytesAvailable *uint64, totalNumberOfBytes *uint64, totalNumberOfFreeBytes *uint64) (err error) = kernel32.GetDiskFreeSpaceExW
|
||||
//sys _Process32First(handle syscall.Handle, processEntry32 *ProcessEntry32) (err error) = kernel32.Process32FirstW
|
||||
//sys _Process32Next(handle syscall.Handle, processEntry32 *ProcessEntry32) (err error) = kernel32.Process32NextW
|
||||
//sys _CreateToolhelp32Snapshot(flags uint32, processID uint32) (handle syscall.Handle, err error) = kernel32.CreateToolhelp32Snapshot
|
||||
//sys _NtQuerySystemInformation(systemInformationClass uint32, systemInformation *byte, systemInformationLength uint32, returnLength *uint32) (ntstatus uint32, err error) = ntdll.NtQuerySystemInformation
|
||||
//sys _NtQueryInformationProcess(processHandle syscall.Handle, processInformationClass uint32, processInformation *byte, processInformationLength uint32, returnLength *uint32) (ntstatus uint32, err error) = ntdll.NtQueryInformationProcess
|
||||
//sys _LookupPrivilegeName(systemName string, luid *int64, buffer *uint16, size *uint32) (err error) = advapi32.LookupPrivilegeNameW
|
||||
//sys _LookupPrivilegeValue(systemName string, name string, luid *int64) (err error) = advapi32.LookupPrivilegeValueW
|
||||
//sys _AdjustTokenPrivileges(token syscall.Token, releaseAll bool, input *byte, outputSize uint32, output *byte, requiredSize *uint32) (success bool, err error) [true] = advapi32.AdjustTokenPrivileges
|
||||
//sys _FindFirstVolume(volumeName *uint16, size uint32) (handle syscall.Handle, err error) = kernel32.FindFirstVolumeW
|
||||
//sys _FindNextVolume(handle syscall.Handle, volumeName *uint16, size uint32) (err error) = kernel32.FindNextVolumeW
|
||||
//sys _FindVolumeClose(handle syscall.Handle) (err error) = kernel32.FindVolumeClose
|
||||
//sys _GetVolumePathNamesForVolumeName(volumeName string, buffer *uint16, bufferSize uint32, length *uint32) (err error) = kernel32.GetVolumePathNamesForVolumeNameW
|
||||
//sys _ReadProcessMemory(handle syscall.Handle, baseAddress uintptr, buffer uintptr, size uintptr, numRead *uintptr) (err error) = kernel32.ReadProcessMemory
|
||||
//sys _GetTickCount64() (uptime uint64, err error) = kernel32.GetTickCount64
|
43
vendor/github.com/elastic/gosigar/sys/windows/version.go
generated
vendored
Normal file
43
vendor/github.com/elastic/gosigar/sys/windows/version.go
generated
vendored
Normal file
@ -0,0 +1,43 @@
|
||||
// +build windows
|
||||
|
||||
package windows
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// Version identifies a Windows version by major, minor, and build number.
|
||||
type Version struct {
|
||||
Major int
|
||||
Minor int
|
||||
Build int
|
||||
}
|
||||
|
||||
// GetWindowsVersion returns the Windows version information. Applications not
|
||||
// manifested for Windows 8.1 or Windows 10 will return the Windows 8 OS version
|
||||
// value (6.2).
|
||||
//
|
||||
// For a table of version numbers see:
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724833(v=vs.85).aspx
|
||||
func GetWindowsVersion() Version {
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724439(v=vs.85).aspx
|
||||
ver, err := syscall.GetVersion()
|
||||
if err != nil {
|
||||
// GetVersion should never return an error.
|
||||
panic(fmt.Errorf("GetVersion failed: %v", err))
|
||||
}
|
||||
|
||||
return Version{
|
||||
Major: int(ver & 0xFF),
|
||||
Minor: int(ver >> 8 & 0xFF),
|
||||
Build: int(ver >> 16),
|
||||
}
|
||||
}
|
||||
|
||||
// IsWindowsVistaOrGreater returns true if the Windows version is Vista or
|
||||
// greater.
|
||||
func (v Version) IsWindowsVistaOrGreater() bool {
|
||||
// Vista is 6.0.
|
||||
return v.Major >= 6 && v.Minor >= 0
|
||||
}
|
376
vendor/github.com/elastic/gosigar/sys/windows/zsyscall_windows.go
generated
vendored
Normal file
376
vendor/github.com/elastic/gosigar/sys/windows/zsyscall_windows.go
generated
vendored
Normal file
@ -0,0 +1,376 @@
|
||||
// Code generated by 'go generate'; DO NOT EDIT.
|
||||
|
||||
package windows
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var _ unsafe.Pointer
|
||||
|
||||
// Do the interface allocations only once for common
|
||||
// Errno values.
|
||||
const (
|
||||
errnoERROR_IO_PENDING = 997
|
||||
)
|
||||
|
||||
var (
|
||||
errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING)
|
||||
)
|
||||
|
||||
// errnoErr returns common boxed Errno values, to prevent
|
||||
// allocations at runtime.
|
||||
func errnoErr(e syscall.Errno) error {
|
||||
switch e {
|
||||
case 0:
|
||||
return nil
|
||||
case errnoERROR_IO_PENDING:
|
||||
return errERROR_IO_PENDING
|
||||
}
|
||||
// TODO: add more here, after collecting data on the common
|
||||
// error values see on Windows. (perhaps when running
|
||||
// all.bat?)
|
||||
return e
|
||||
}
|
||||
|
||||
var (
|
||||
modkernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||||
modpsapi = syscall.NewLazyDLL("psapi.dll")
|
||||
modntdll = syscall.NewLazyDLL("ntdll.dll")
|
||||
modadvapi32 = syscall.NewLazyDLL("advapi32.dll")
|
||||
|
||||
procGlobalMemoryStatusEx = modkernel32.NewProc("GlobalMemoryStatusEx")
|
||||
procGetLogicalDriveStringsW = modkernel32.NewProc("GetLogicalDriveStringsW")
|
||||
procGetProcessMemoryInfo = modpsapi.NewProc("GetProcessMemoryInfo")
|
||||
procGetProcessImageFileNameW = modpsapi.NewProc("GetProcessImageFileNameW")
|
||||
procGetSystemTimes = modkernel32.NewProc("GetSystemTimes")
|
||||
procGetDriveTypeW = modkernel32.NewProc("GetDriveTypeW")
|
||||
procEnumProcesses = modpsapi.NewProc("EnumProcesses")
|
||||
procGetDiskFreeSpaceExW = modkernel32.NewProc("GetDiskFreeSpaceExW")
|
||||
procProcess32FirstW = modkernel32.NewProc("Process32FirstW")
|
||||
procProcess32NextW = modkernel32.NewProc("Process32NextW")
|
||||
procCreateToolhelp32Snapshot = modkernel32.NewProc("CreateToolhelp32Snapshot")
|
||||
procNtQuerySystemInformation = modntdll.NewProc("NtQuerySystemInformation")
|
||||
procNtQueryInformationProcess = modntdll.NewProc("NtQueryInformationProcess")
|
||||
procLookupPrivilegeNameW = modadvapi32.NewProc("LookupPrivilegeNameW")
|
||||
procLookupPrivilegeValueW = modadvapi32.NewProc("LookupPrivilegeValueW")
|
||||
procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges")
|
||||
procFindFirstVolumeW = modkernel32.NewProc("FindFirstVolumeW")
|
||||
procFindNextVolumeW = modkernel32.NewProc("FindNextVolumeW")
|
||||
procFindVolumeClose = modkernel32.NewProc("FindVolumeClose")
|
||||
procGetVolumePathNamesForVolumeNameW = modkernel32.NewProc("GetVolumePathNamesForVolumeNameW")
|
||||
procReadProcessMemory = modkernel32.NewProc("ReadProcessMemory")
|
||||
procGetTickCount64 = modkernel32.NewProc("GetTickCount64")
|
||||
)
|
||||
|
||||
func _GlobalMemoryStatusEx(buffer *MemoryStatusEx) (err error) {
|
||||
r1, _, e1 := syscall.Syscall(procGlobalMemoryStatusEx.Addr(), 1, uintptr(unsafe.Pointer(buffer)), 0, 0)
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func _GetLogicalDriveStringsW(bufferLength uint32, buffer *uint16) (length uint32, err error) {
|
||||
r0, _, e1 := syscall.Syscall(procGetLogicalDriveStringsW.Addr(), 2, uintptr(bufferLength), uintptr(unsafe.Pointer(buffer)), 0)
|
||||
length = uint32(r0)
|
||||
if length == 0 {
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func _GetProcessMemoryInfo(handle syscall.Handle, psmemCounters *ProcessMemoryCountersEx, cb uint32) (err error) {
|
||||
r1, _, e1 := syscall.Syscall(procGetProcessMemoryInfo.Addr(), 3, uintptr(handle), uintptr(unsafe.Pointer(psmemCounters)), uintptr(cb))
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func _GetProcessImageFileName(handle syscall.Handle, outImageFileName *uint16, size uint32) (length uint32, err error) {
|
||||
r0, _, e1 := syscall.Syscall(procGetProcessImageFileNameW.Addr(), 3, uintptr(handle), uintptr(unsafe.Pointer(outImageFileName)), uintptr(size))
|
||||
length = uint32(r0)
|
||||
if length == 0 {
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func _GetSystemTimes(idleTime *syscall.Filetime, kernelTime *syscall.Filetime, userTime *syscall.Filetime) (err error) {
|
||||
r1, _, e1 := syscall.Syscall(procGetSystemTimes.Addr(), 3, uintptr(unsafe.Pointer(idleTime)), uintptr(unsafe.Pointer(kernelTime)), uintptr(unsafe.Pointer(userTime)))
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func _GetDriveType(rootPathName *uint16) (dt DriveType, err error) {
|
||||
r0, _, e1 := syscall.Syscall(procGetDriveTypeW.Addr(), 1, uintptr(unsafe.Pointer(rootPathName)), 0, 0)
|
||||
dt = DriveType(r0)
|
||||
if dt == 0 {
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func _EnumProcesses(processIds *uint32, sizeBytes uint32, bytesReturned *uint32) (err error) {
|
||||
r1, _, e1 := syscall.Syscall(procEnumProcesses.Addr(), 3, uintptr(unsafe.Pointer(processIds)), uintptr(sizeBytes), uintptr(unsafe.Pointer(bytesReturned)))
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func _GetDiskFreeSpaceEx(directoryName *uint16, freeBytesAvailable *uint64, totalNumberOfBytes *uint64, totalNumberOfFreeBytes *uint64) (err error) {
|
||||
r1, _, e1 := syscall.Syscall6(procGetDiskFreeSpaceExW.Addr(), 4, uintptr(unsafe.Pointer(directoryName)), uintptr(unsafe.Pointer(freeBytesAvailable)), uintptr(unsafe.Pointer(totalNumberOfBytes)), uintptr(unsafe.Pointer(totalNumberOfFreeBytes)), 0, 0)
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func _Process32First(handle syscall.Handle, processEntry32 *ProcessEntry32) (err error) {
|
||||
r1, _, e1 := syscall.Syscall(procProcess32FirstW.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(processEntry32)), 0)
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func _Process32Next(handle syscall.Handle, processEntry32 *ProcessEntry32) (err error) {
|
||||
r1, _, e1 := syscall.Syscall(procProcess32NextW.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(processEntry32)), 0)
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func _CreateToolhelp32Snapshot(flags uint32, processID uint32) (handle syscall.Handle, err error) {
|
||||
r0, _, e1 := syscall.Syscall(procCreateToolhelp32Snapshot.Addr(), 2, uintptr(flags), uintptr(processID), 0)
|
||||
handle = syscall.Handle(r0)
|
||||
if handle == 0 {
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func _NtQuerySystemInformation(systemInformationClass uint32, systemInformation *byte, systemInformationLength uint32, returnLength *uint32) (ntstatus uint32, err error) {
|
||||
r0, _, e1 := syscall.Syscall6(procNtQuerySystemInformation.Addr(), 4, uintptr(systemInformationClass), uintptr(unsafe.Pointer(systemInformation)), uintptr(systemInformationLength), uintptr(unsafe.Pointer(returnLength)), 0, 0)
|
||||
ntstatus = uint32(r0)
|
||||
if ntstatus == 0 {
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func _NtQueryInformationProcess(processHandle syscall.Handle, processInformationClass uint32, processInformation *byte, processInformationLength uint32, returnLength *uint32) (ntstatus uint32, err error) {
|
||||
r0, _, e1 := syscall.Syscall6(procNtQueryInformationProcess.Addr(), 5, uintptr(processHandle), uintptr(processInformationClass), uintptr(unsafe.Pointer(processInformation)), uintptr(processInformationLength), uintptr(unsafe.Pointer(returnLength)), 0)
|
||||
ntstatus = uint32(r0)
|
||||
if ntstatus == 0 {
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func _LookupPrivilegeName(systemName string, luid *int64, buffer *uint16, size *uint32) (err error) {
|
||||
var _p0 *uint16
|
||||
_p0, err = syscall.UTF16PtrFromString(systemName)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return __LookupPrivilegeName(_p0, luid, buffer, size)
|
||||
}
|
||||
|
||||
func __LookupPrivilegeName(systemName *uint16, luid *int64, buffer *uint16, size *uint32) (err error) {
|
||||
r1, _, e1 := syscall.Syscall6(procLookupPrivilegeNameW.Addr(), 4, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(luid)), uintptr(unsafe.Pointer(buffer)), uintptr(unsafe.Pointer(size)), 0, 0)
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func _LookupPrivilegeValue(systemName string, name string, luid *int64) (err error) {
|
||||
var _p0 *uint16
|
||||
_p0, err = syscall.UTF16PtrFromString(systemName)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var _p1 *uint16
|
||||
_p1, err = syscall.UTF16PtrFromString(name)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return __LookupPrivilegeValue(_p0, _p1, luid)
|
||||
}
|
||||
|
||||
func __LookupPrivilegeValue(systemName *uint16, name *uint16, luid *int64) (err error) {
|
||||
r1, _, e1 := syscall.Syscall(procLookupPrivilegeValueW.Addr(), 3, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(luid)))
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func _AdjustTokenPrivileges(token syscall.Token, releaseAll bool, input *byte, outputSize uint32, output *byte, requiredSize *uint32) (success bool, err error) {
|
||||
var _p0 uint32
|
||||
if releaseAll {
|
||||
_p0 = 1
|
||||
} else {
|
||||
_p0 = 0
|
||||
}
|
||||
r0, _, e1 := syscall.Syscall6(procAdjustTokenPrivileges.Addr(), 6, uintptr(token), uintptr(_p0), uintptr(unsafe.Pointer(input)), uintptr(outputSize), uintptr(unsafe.Pointer(output)), uintptr(unsafe.Pointer(requiredSize)))
|
||||
success = r0 != 0
|
||||
if true {
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func _FindFirstVolume(volumeName *uint16, size uint32) (handle syscall.Handle, err error) {
|
||||
r0, _, e1 := syscall.Syscall(procFindFirstVolumeW.Addr(), 2, uintptr(unsafe.Pointer(volumeName)), uintptr(size), 0)
|
||||
handle = syscall.Handle(r0)
|
||||
if handle == 0 {
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func _FindNextVolume(handle syscall.Handle, volumeName *uint16, size uint32) (err error) {
|
||||
r1, _, e1 := syscall.Syscall(procFindNextVolumeW.Addr(), 3, uintptr(handle), uintptr(unsafe.Pointer(volumeName)), uintptr(size))
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func _FindVolumeClose(handle syscall.Handle) (err error) {
|
||||
r1, _, e1 := syscall.Syscall(procFindVolumeClose.Addr(), 1, uintptr(handle), 0, 0)
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func _GetVolumePathNamesForVolumeName(volumeName string, buffer *uint16, bufferSize uint32, length *uint32) (err error) {
|
||||
var _p0 *uint16
|
||||
_p0, err = syscall.UTF16PtrFromString(volumeName)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return __GetVolumePathNamesForVolumeName(_p0, buffer, bufferSize, length)
|
||||
}
|
||||
|
||||
func __GetVolumePathNamesForVolumeName(volumeName *uint16, buffer *uint16, bufferSize uint32, length *uint32) (err error) {
|
||||
r1, _, e1 := syscall.Syscall6(procGetVolumePathNamesForVolumeNameW.Addr(), 4, uintptr(unsafe.Pointer(volumeName)), uintptr(unsafe.Pointer(buffer)), uintptr(bufferSize), uintptr(unsafe.Pointer(length)), 0, 0)
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func _ReadProcessMemory(handle syscall.Handle, baseAddress uintptr, buffer uintptr, size uintptr, numRead *uintptr) (err error) {
|
||||
r1, _, e1 := syscall.Syscall6(procReadProcessMemory.Addr(), 5, uintptr(handle), uintptr(baseAddress), uintptr(buffer), uintptr(size), uintptr(unsafe.Pointer(numRead)), 0)
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func _GetTickCount64() (uptime uint64, err error) {
|
||||
r0, _, e1 := syscall.Syscall(procGetTickCount64.Addr(), 0, 0, 0, 0)
|
||||
uptime = uint64(r0)
|
||||
if uptime == 0 {
|
||||
if e1 != 0 {
|
||||
err = errnoErr(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
5
vendor/github.com/ethereum/go-ethereum/.dockerignore
generated
vendored
Normal file
5
vendor/github.com/ethereum/go-ethereum/.dockerignore
generated
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
**/*_test.go
|
||||
|
||||
build/_workspace
|
||||
build/_bin
|
||||
tests/testdata
|
15
vendor/github.com/ethereum/go-ethereum/.github/CODEOWNERS
generated
vendored
15
vendor/github.com/ethereum/go-ethereum/.github/CODEOWNERS
generated
vendored
@ -4,15 +4,20 @@
|
||||
accounts/usbwallet @karalabe
|
||||
accounts/scwallet @gballet
|
||||
accounts/abi @gballet
|
||||
cmd/clef @holiman
|
||||
cmd/puppeth @karalabe
|
||||
consensus @karalabe
|
||||
core/ @karalabe @holiman
|
||||
eth/ @karalabe
|
||||
core/ @karalabe @holiman @rjl493456442
|
||||
dashboard/ @kurkomisi
|
||||
eth/ @karalabe @holiman @rjl493456442
|
||||
graphql/ @gballet
|
||||
les/ @zsfelfoldi
|
||||
light/ @zsfelfoldi
|
||||
mobile/ @karalabe
|
||||
les/ @zsfelfoldi @rjl493456442
|
||||
light/ @zsfelfoldi @rjl493456442
|
||||
mobile/ @karalabe @ligi
|
||||
p2p/ @fjl @zsfelfoldi
|
||||
rpc/ @fjl @holiman
|
||||
p2p/simulations @zelig @nonsense @janos @justelad
|
||||
p2p/protocols @zelig @nonsense @janos @justelad
|
||||
p2p/testing @zelig @nonsense @janos @justelad
|
||||
signer/ @holiman
|
||||
whisper/ @gballet @gluk256
|
||||
|
33
vendor/github.com/ethereum/go-ethereum/.travis.yml
generated
vendored
33
vendor/github.com/ethereum/go-ethereum/.travis.yml
generated
vendored
@ -5,35 +5,23 @@ matrix:
|
||||
include:
|
||||
- os: linux
|
||||
dist: xenial
|
||||
sudo: required
|
||||
go: 1.10.x
|
||||
script:
|
||||
- sudo modprobe fuse
|
||||
- sudo chmod 666 /dev/fuse
|
||||
- sudo chown root:$USER /etc/fuse.conf
|
||||
- go run build/ci.go install
|
||||
- go run build/ci.go test -coverage $TEST_PACKAGES
|
||||
|
||||
- os: linux
|
||||
dist: xenial
|
||||
sudo: required
|
||||
go: 1.11.x
|
||||
script:
|
||||
- sudo modprobe fuse
|
||||
- sudo chmod 666 /dev/fuse
|
||||
- sudo chown root:$USER /etc/fuse.conf
|
||||
- go run build/ci.go install
|
||||
- go run build/ci.go test -coverage $TEST_PACKAGES
|
||||
|
||||
# These are the latest Go versions.
|
||||
- os: linux
|
||||
dist: xenial
|
||||
sudo: required
|
||||
go: 1.12.x
|
||||
script:
|
||||
- sudo modprobe fuse
|
||||
- sudo chmod 666 /dev/fuse
|
||||
- sudo chown root:$USER /etc/fuse.conf
|
||||
- go run build/ci.go install
|
||||
- go run build/ci.go test -coverage $TEST_PACKAGES
|
||||
|
||||
@ -64,7 +52,7 @@ matrix:
|
||||
- go run build/ci.go lint
|
||||
|
||||
# This builder does the Ubuntu PPA upload
|
||||
- if: repo = ethereum/go-ethereum AND type = push
|
||||
- if: type = push
|
||||
os: linux
|
||||
dist: xenial
|
||||
go: 1.12.x
|
||||
@ -86,7 +74,7 @@ matrix:
|
||||
- go run build/ci.go debsrc -upload ethereum/ethereum -sftp-user geth-ci -signer "Go Ethereum Linux Builder <geth-ci@ethereum.org>"
|
||||
|
||||
# This builder does the Linux Azure uploads
|
||||
- if: repo = ethereum/go-ethereum AND type = push
|
||||
- if: type = push
|
||||
os: linux
|
||||
dist: xenial
|
||||
sudo: required
|
||||
@ -120,7 +108,7 @@ matrix:
|
||||
- go run build/ci.go archive -arch arm64 -type tar -signer LINUX_SIGNING_KEY -upload gethstore/builds
|
||||
|
||||
# This builder does the Linux Azure MIPS xgo uploads
|
||||
- if: repo = ethereum/go-ethereum AND type = push
|
||||
- if: type = push
|
||||
os: linux
|
||||
dist: xenial
|
||||
services:
|
||||
@ -148,7 +136,7 @@ matrix:
|
||||
- go run build/ci.go archive -arch mips64le -type tar -signer LINUX_SIGNING_KEY -upload gethstore/builds
|
||||
|
||||
# This builder does the Android Maven and Azure uploads
|
||||
- if: repo = ethereum/go-ethereum AND type = push
|
||||
- if: type = push
|
||||
os: linux
|
||||
dist: xenial
|
||||
addons:
|
||||
@ -185,7 +173,7 @@ matrix:
|
||||
- go run build/ci.go aar -signer ANDROID_SIGNING_KEY -deploy https://oss.sonatype.org -upload gethstore/builds
|
||||
|
||||
# This builder does the OSX Azure, iOS CocoaPods and iOS Azure uploads
|
||||
- if: repo = ethereum/go-ethereum AND type = push
|
||||
- if: type = push
|
||||
os: osx
|
||||
go: 1.12.x
|
||||
env:
|
||||
@ -214,7 +202,7 @@ matrix:
|
||||
- go run build/ci.go xcode -signer IOS_SIGNING_KEY -deploy trunk -upload gethstore/builds
|
||||
|
||||
# This builder does the Azure archive purges to avoid accumulating junk
|
||||
- if: repo = ethereum/go-ethereum AND type = cron
|
||||
- if: type = cron
|
||||
os: linux
|
||||
dist: xenial
|
||||
go: 1.12.x
|
||||
@ -224,12 +212,3 @@ matrix:
|
||||
submodules: false # avoid cloning ethereum/tests
|
||||
script:
|
||||
- go run build/ci.go purge -store gethstore/builds -days 14
|
||||
|
||||
- name: Race Detector for Swarm
|
||||
if: repo = ethersphere/go-ethereum
|
||||
os: linux
|
||||
dist: xenial
|
||||
go: 1.12.x
|
||||
git:
|
||||
submodules: false # avoid cloning ethereum/tests
|
||||
script: ./build/travis_keepalive.sh go test -timeout 20m -race ./swarm... ./p2p/{protocols,simulations,testing}/...
|
||||
|
16
vendor/github.com/ethereum/go-ethereum/Dockerfile
generated
vendored
Normal file
16
vendor/github.com/ethereum/go-ethereum/Dockerfile
generated
vendored
Normal file
@ -0,0 +1,16 @@
|
||||
# Build Geth in a stock Go builder container
|
||||
FROM golang:1.12-alpine as builder
|
||||
|
||||
RUN apk add --no-cache make gcc musl-dev linux-headers git
|
||||
|
||||
ADD . /go-ethereum
|
||||
RUN cd /go-ethereum && make geth
|
||||
|
||||
# Pull Geth into a second stage deploy alpine container
|
||||
FROM alpine:latest
|
||||
|
||||
RUN apk add --no-cache ca-certificates
|
||||
COPY --from=builder /go-ethereum/build/bin/geth /usr/local/bin/
|
||||
|
||||
EXPOSE 8545 8546 30303 30303/udp
|
||||
ENTRYPOINT ["geth"]
|
15
vendor/github.com/ethereum/go-ethereum/Dockerfile.alltools
generated
vendored
Normal file
15
vendor/github.com/ethereum/go-ethereum/Dockerfile.alltools
generated
vendored
Normal file
@ -0,0 +1,15 @@
|
||||
# Build Geth in a stock Go builder container
|
||||
FROM golang:1.12-alpine as builder
|
||||
|
||||
RUN apk add --no-cache make gcc musl-dev linux-headers git
|
||||
|
||||
ADD . /go-ethereum
|
||||
RUN cd /go-ethereum && make all
|
||||
|
||||
# Pull all binaries into a second stage deploy alpine container
|
||||
FROM alpine:latest
|
||||
|
||||
RUN apk add --no-cache ca-certificates
|
||||
COPY --from=builder /go-ethereum/build/bin/* /usr/local/bin/
|
||||
|
||||
EXPOSE 8545 8546 30303 30303/udp
|
145
vendor/github.com/ethereum/go-ethereum/Makefile
generated
vendored
Normal file
145
vendor/github.com/ethereum/go-ethereum/Makefile
generated
vendored
Normal file
@ -0,0 +1,145 @@
|
||||
# This Makefile is meant to be used by people that do not usually work
|
||||
# with Go source code. If you know what GOPATH is then you probably
|
||||
# don't need to bother with make.
|
||||
|
||||
.PHONY: geth android ios geth-cross evm all test clean
|
||||
.PHONY: geth-linux geth-linux-386 geth-linux-amd64 geth-linux-mips64 geth-linux-mips64le
|
||||
.PHONY: geth-linux-arm geth-linux-arm-5 geth-linux-arm-6 geth-linux-arm-7 geth-linux-arm64
|
||||
.PHONY: geth-darwin geth-darwin-386 geth-darwin-amd64
|
||||
.PHONY: geth-windows geth-windows-386 geth-windows-amd64
|
||||
|
||||
GOBIN = $(shell pwd)/build/bin
|
||||
GO ?= latest
|
||||
|
||||
geth:
|
||||
build/env.sh go run build/ci.go install ./cmd/geth
|
||||
@echo "Done building."
|
||||
@echo "Run \"$(GOBIN)/geth\" to launch geth."
|
||||
|
||||
all:
|
||||
build/env.sh go run build/ci.go install
|
||||
|
||||
android:
|
||||
build/env.sh go run build/ci.go aar --local
|
||||
@echo "Done building."
|
||||
@echo "Import \"$(GOBIN)/geth.aar\" to use the library."
|
||||
|
||||
ios:
|
||||
build/env.sh go run build/ci.go xcode --local
|
||||
@echo "Done building."
|
||||
@echo "Import \"$(GOBIN)/Geth.framework\" to use the library."
|
||||
|
||||
test: all
|
||||
build/env.sh go run build/ci.go test
|
||||
|
||||
lint: ## Run linters.
|
||||
build/env.sh go run build/ci.go lint
|
||||
|
||||
clean:
|
||||
./build/clean_go_build_cache.sh
|
||||
rm -fr build/_workspace/pkg/ $(GOBIN)/*
|
||||
|
||||
# The devtools target installs tools required for 'go generate'.
|
||||
# You need to put $GOBIN (or $GOPATH/bin) in your PATH to use 'go generate'.
|
||||
|
||||
devtools:
|
||||
env GOBIN= go get -u golang.org/x/tools/cmd/stringer
|
||||
env GOBIN= go get -u github.com/kevinburke/go-bindata/go-bindata
|
||||
env GOBIN= go get -u github.com/fjl/gencodec
|
||||
env GOBIN= go get -u github.com/golang/protobuf/protoc-gen-go
|
||||
env GOBIN= go install ./cmd/abigen
|
||||
@type "npm" 2> /dev/null || echo 'Please install node.js and npm'
|
||||
@type "solc" 2> /dev/null || echo 'Please install solc'
|
||||
@type "protoc" 2> /dev/null || echo 'Please install protoc'
|
||||
|
||||
# Cross Compilation Targets (xgo)
|
||||
|
||||
geth-cross: geth-linux geth-darwin geth-windows geth-android geth-ios
|
||||
@echo "Full cross compilation done:"
|
||||
@ls -ld $(GOBIN)/geth-*
|
||||
|
||||
geth-linux: geth-linux-386 geth-linux-amd64 geth-linux-arm geth-linux-mips64 geth-linux-mips64le
|
||||
@echo "Linux cross compilation done:"
|
||||
@ls -ld $(GOBIN)/geth-linux-*
|
||||
|
||||
geth-linux-386:
|
||||
build/env.sh go run build/ci.go xgo -- --go=$(GO) --targets=linux/386 -v ./cmd/geth
|
||||
@echo "Linux 386 cross compilation done:"
|
||||
@ls -ld $(GOBIN)/geth-linux-* | grep 386
|
||||
|
||||
geth-linux-amd64:
|
||||
build/env.sh go run build/ci.go xgo -- --go=$(GO) --targets=linux/amd64 -v ./cmd/geth
|
||||
@echo "Linux amd64 cross compilation done:"
|
||||
@ls -ld $(GOBIN)/geth-linux-* | grep amd64
|
||||
|
||||
geth-linux-arm: geth-linux-arm-5 geth-linux-arm-6 geth-linux-arm-7 geth-linux-arm64
|
||||
@echo "Linux ARM cross compilation done:"
|
||||
@ls -ld $(GOBIN)/geth-linux-* | grep arm
|
||||
|
||||
geth-linux-arm-5:
|
||||
build/env.sh go run build/ci.go xgo -- --go=$(GO) --targets=linux/arm-5 -v ./cmd/geth
|
||||
@echo "Linux ARMv5 cross compilation done:"
|
||||
@ls -ld $(GOBIN)/geth-linux-* | grep arm-5
|
||||
|
||||
geth-linux-arm-6:
|
||||
build/env.sh go run build/ci.go xgo -- --go=$(GO) --targets=linux/arm-6 -v ./cmd/geth
|
||||
@echo "Linux ARMv6 cross compilation done:"
|
||||
@ls -ld $(GOBIN)/geth-linux-* | grep arm-6
|
||||
|
||||
geth-linux-arm-7:
|
||||
build/env.sh go run build/ci.go xgo -- --go=$(GO) --targets=linux/arm-7 -v ./cmd/geth
|
||||
@echo "Linux ARMv7 cross compilation done:"
|
||||
@ls -ld $(GOBIN)/geth-linux-* | grep arm-7
|
||||
|
||||
geth-linux-arm64:
|
||||
build/env.sh go run build/ci.go xgo -- --go=$(GO) --targets=linux/arm64 -v ./cmd/geth
|
||||
@echo "Linux ARM64 cross compilation done:"
|
||||
@ls -ld $(GOBIN)/geth-linux-* | grep arm64
|
||||
|
||||
geth-linux-mips:
|
||||
build/env.sh go run build/ci.go xgo -- --go=$(GO) --targets=linux/mips --ldflags '-extldflags "-static"' -v ./cmd/geth
|
||||
@echo "Linux MIPS cross compilation done:"
|
||||
@ls -ld $(GOBIN)/geth-linux-* | grep mips
|
||||
|
||||
geth-linux-mipsle:
|
||||
build/env.sh go run build/ci.go xgo -- --go=$(GO) --targets=linux/mipsle --ldflags '-extldflags "-static"' -v ./cmd/geth
|
||||
@echo "Linux MIPSle cross compilation done:"
|
||||
@ls -ld $(GOBIN)/geth-linux-* | grep mipsle
|
||||
|
||||
geth-linux-mips64:
|
||||
build/env.sh go run build/ci.go xgo -- --go=$(GO) --targets=linux/mips64 --ldflags '-extldflags "-static"' -v ./cmd/geth
|
||||
@echo "Linux MIPS64 cross compilation done:"
|
||||
@ls -ld $(GOBIN)/geth-linux-* | grep mips64
|
||||
|
||||
geth-linux-mips64le:
|
||||
build/env.sh go run build/ci.go xgo -- --go=$(GO) --targets=linux/mips64le --ldflags '-extldflags "-static"' -v ./cmd/geth
|
||||
@echo "Linux MIPS64le cross compilation done:"
|
||||
@ls -ld $(GOBIN)/geth-linux-* | grep mips64le
|
||||
|
||||
geth-darwin: geth-darwin-386 geth-darwin-amd64
|
||||
@echo "Darwin cross compilation done:"
|
||||
@ls -ld $(GOBIN)/geth-darwin-*
|
||||
|
||||
geth-darwin-386:
|
||||
build/env.sh go run build/ci.go xgo -- --go=$(GO) --targets=darwin/386 -v ./cmd/geth
|
||||
@echo "Darwin 386 cross compilation done:"
|
||||
@ls -ld $(GOBIN)/geth-darwin-* | grep 386
|
||||
|
||||
geth-darwin-amd64:
|
||||
build/env.sh go run build/ci.go xgo -- --go=$(GO) --targets=darwin/amd64 -v ./cmd/geth
|
||||
@echo "Darwin amd64 cross compilation done:"
|
||||
@ls -ld $(GOBIN)/geth-darwin-* | grep amd64
|
||||
|
||||
geth-windows: geth-windows-386 geth-windows-amd64
|
||||
@echo "Windows cross compilation done:"
|
||||
@ls -ld $(GOBIN)/geth-windows-*
|
||||
|
||||
geth-windows-386:
|
||||
build/env.sh go run build/ci.go xgo -- --go=$(GO) --targets=windows/386 -v ./cmd/geth
|
||||
@echo "Windows 386 cross compilation done:"
|
||||
@ls -ld $(GOBIN)/geth-windows-* | grep 386
|
||||
|
||||
geth-windows-amd64:
|
||||
build/env.sh go run build/ci.go xgo -- --go=$(GO) --targets=windows/amd64 -v ./cmd/geth
|
||||
@echo "Windows amd64 cross compilation done:"
|
||||
@ls -ld $(GOBIN)/geth-windows-* | grep amd64
|
310
vendor/github.com/ethereum/go-ethereum/README.md
generated
vendored
Normal file
310
vendor/github.com/ethereum/go-ethereum/README.md
generated
vendored
Normal file
@ -0,0 +1,310 @@
|
||||
## Go Ethereum
|
||||
|
||||
Official Golang implementation of the Ethereum protocol.
|
||||
|
||||
[](https://godoc.org/github.com/ethereum/go-ethereum)
|
||||
[](https://goreportcard.com/report/github.com/ethereum/go-ethereum)
|
||||
[](https://travis-ci.org/ethereum/go-ethereum)
|
||||
[](https://discord.gg/nthXNEv)
|
||||
|
||||
Automated builds are available for stable releases and the unstable master branch.
|
||||
Binary archives are published at https://geth.ethereum.org/downloads/.
|
||||
|
||||
## Building the source
|
||||
|
||||
For prerequisites and detailed build instructions please read the
|
||||
[Installation Instructions](https://github.com/ethereum/go-ethereum/wiki/Building-Ethereum)
|
||||
on the wiki.
|
||||
|
||||
Building geth requires both a Go (version 1.10 or later) and a C compiler.
|
||||
You can install them using your favourite package manager.
|
||||
Once the dependencies are installed, run
|
||||
|
||||
make geth
|
||||
|
||||
or, to build the full suite of utilities:
|
||||
|
||||
make all
|
||||
|
||||
## Executables
|
||||
|
||||
The go-ethereum project comes with several wrappers/executables found in the `cmd` directory.
|
||||
|
||||
| Command | Description |
|
||||
| :-----------: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **`geth`** | Our main Ethereum CLI client. It is the entry point into the Ethereum network (main-, test- or private net), capable of running as a full node (default), archive node (retaining all historical state) or a light node (retrieving data live). It can be used by other processes as a gateway into the Ethereum network via JSON RPC endpoints exposed on top of HTTP, WebSocket and/or IPC transports. `geth --help` and the [CLI Wiki page](https://github.com/ethereum/go-ethereum/wiki/Command-Line-Options) for command line options. |
|
||||
| `abigen` | Source code generator to convert Ethereum contract definitions into easy to use, compile-time type-safe Go packages. It operates on plain [Ethereum contract ABIs](https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI) with expanded functionality if the contract bytecode is also available. However, it also accepts Solidity source files, making development much more streamlined. Please see our [Native DApps](https://github.com/ethereum/go-ethereum/wiki/Native-DApps:-Go-bindings-to-Ethereum-contracts) wiki page for details. |
|
||||
| `bootnode` | Stripped down version of our Ethereum client implementation that only takes part in the network node discovery protocol, but does not run any of the higher level application protocols. It can be used as a lightweight bootstrap node to aid in finding peers in private networks. |
|
||||
| `evm` | Developer utility version of the EVM (Ethereum Virtual Machine) that is capable of running bytecode snippets within a configurable environment and execution mode. Its purpose is to allow isolated, fine-grained debugging of EVM opcodes (e.g. `evm --code 60ff60ff --debug`). |
|
||||
| `gethrpctest` | Developer utility tool to support our [ethereum/rpc-test](https://github.com/ethereum/rpc-tests) test suite which validates baseline conformity to the [Ethereum JSON RPC](https://github.com/ethereum/wiki/wiki/JSON-RPC) specs. Please see the [test suite's readme](https://github.com/ethereum/rpc-tests/blob/master/README.md) for details. |
|
||||
| `rlpdump` | Developer utility tool to convert binary RLP ([Recursive Length Prefix](https://github.com/ethereum/wiki/wiki/RLP)) dumps (data encoding used by the Ethereum protocol both network as well as consensus wise) to user-friendlier hierarchical representation (e.g. `rlpdump --hex CE0183FFFFFFC4C304050583616263`). |
|
||||
| `puppeth` | a CLI wizard that aids in creating a new Ethereum network. |
|
||||
|
||||
## Running geth
|
||||
|
||||
Going through all the possible command line flags is out of scope here (please consult our
|
||||
[CLI Wiki page](https://github.com/ethereum/go-ethereum/wiki/Command-Line-Options)), but we've
|
||||
enumerated a few common parameter combos to get you up to speed quickly on how you can run your
|
||||
own Geth instance.
|
||||
|
||||
### Full node on the main Ethereum network
|
||||
|
||||
By far the most common scenario is people wanting to simply interact with the Ethereum network:
|
||||
create accounts; transfer funds; deploy and interact with contracts. For this particular use-case
|
||||
the user doesn't care about years-old historical data, so we can fast-sync quickly to the current
|
||||
state of the network. To do so:
|
||||
|
||||
```
|
||||
$ geth console
|
||||
```
|
||||
|
||||
This command will:
|
||||
|
||||
* Start geth in fast sync mode (default, can be changed with the `--syncmode` flag), causing it to
|
||||
download more data in exchange for avoiding processing the entire history of the Ethereum network,
|
||||
which is very CPU intensive.
|
||||
* Start up Geth's built-in interactive [JavaScript console](https://github.com/ethereum/go-ethereum/wiki/JavaScript-Console),
|
||||
(via the trailing `console` subcommand) through which you can invoke all official [`web3` methods](https://github.com/ethereum/wiki/wiki/JavaScript-API)
|
||||
as well as Geth's own [management APIs](https://github.com/ethereum/go-ethereum/wiki/Management-APIs).
|
||||
This tool is optional and if you leave it out you can always attach to an already running Geth instance
|
||||
with `geth attach`.
|
||||
|
||||
### A Full node on the Ethereum test network
|
||||
|
||||
Transitioning towards developers, if you'd like to play around with creating Ethereum contracts, you
|
||||
almost certainly would like to do that without any real money involved until you get the hang of the
|
||||
entire system. In other words, instead of attaching to the main network, you want to join the **test**
|
||||
network with your node, which is fully equivalent to the main network, but with play-Ether only.
|
||||
|
||||
```
|
||||
$ geth --testnet console
|
||||
```
|
||||
|
||||
The `console` subcommand has the exact same meaning as above and they are equally useful on the
|
||||
testnet too. Please see above for their explanations if you've skipped here.
|
||||
|
||||
Specifying the `--testnet` flag, however, will reconfigure your Geth instance a bit:
|
||||
|
||||
* Instead of using the default data directory (`~/.ethereum` on Linux for example), Geth will nest
|
||||
itself one level deeper into a `testnet` subfolder (`~/.ethereum/testnet` on Linux). Note, on OSX
|
||||
and Linux this also means that attaching to a running testnet node requires the use of a custom
|
||||
endpoint since `geth attach` will try to attach to a production node endpoint by default. E.g.
|
||||
`geth attach <datadir>/testnet/geth.ipc`. Windows users are not affected by this.
|
||||
* Instead of connecting the main Ethereum network, the client will connect to the test network,
|
||||
which uses different P2P bootnodes, different network IDs and genesis states.
|
||||
|
||||
*Note: Although there are some internal protective measures to prevent transactions from crossing
|
||||
over between the main network and test network, you should make sure to always use separate accounts
|
||||
for play-money and real-money. Unless you manually move accounts, Geth will by default correctly
|
||||
separate the two networks and will not make any accounts available between them.*
|
||||
|
||||
### Full node on the Rinkeby test network
|
||||
|
||||
The above test network is a cross-client one based on the ethash proof-of-work consensus algorithm. As such, it has certain extra overhead and is more susceptible to reorganization attacks due to the network's low difficulty/security. Go Ethereum also supports connecting to a proof-of-authority based test network called [*Rinkeby*](https://www.rinkeby.io) (operated by members of the community). This network is lighter, more secure, but is only supported by go-ethereum.
|
||||
|
||||
```
|
||||
$ geth --rinkeby console
|
||||
```
|
||||
|
||||
### Configuration
|
||||
|
||||
As an alternative to passing the numerous flags to the `geth` binary, you can also pass a configuration file via:
|
||||
|
||||
```
|
||||
$ geth --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:
|
||||
|
||||
```
|
||||
$ geth --your-favourite-flags dumpconfig
|
||||
```
|
||||
|
||||
*Note: This works only with geth v1.6.0 and above.*
|
||||
|
||||
#### Docker quick start
|
||||
|
||||
One of the quickest ways to get Ethereum up and running on your machine is by using Docker:
|
||||
|
||||
```
|
||||
docker run -d --name ethereum-node -v /Users/alice/ethereum:/root \
|
||||
-p 8545:8545 -p 30303:30303 \
|
||||
ethereum/client-go
|
||||
```
|
||||
|
||||
This will start geth in fast-sync mode with a DB memory allowance of 1GB just as the above command does. It will also create a persistent volume in your home directory for saving your blockchain as well as map the default ports. There is also an `alpine` tag available for a slim version of the image.
|
||||
|
||||
Do not forget `--rpcaddr 0.0.0.0`, if you want to access RPC from other containers and/or hosts. By default, `geth` binds to the local interface and RPC endpoints is not accessible from the outside.
|
||||
|
||||
### Programmatically interfacing Geth nodes
|
||||
|
||||
As a developer, sooner rather than later you'll want to start interacting with Geth and the Ethereum
|
||||
network via your own programs and not manually through the console. To aid this, Geth has built-in
|
||||
support for a JSON-RPC based APIs ([standard APIs](https://github.com/ethereum/wiki/wiki/JSON-RPC) and
|
||||
[Geth specific APIs](https://github.com/ethereum/go-ethereum/wiki/Management-APIs)). These can be
|
||||
exposed via HTTP, WebSockets and IPC (UNIX sockets on UNIX based platforms, and named pipes on Windows).
|
||||
|
||||
The IPC interface is enabled by default and exposes all the APIs supported by Geth, whereas the HTTP
|
||||
and WS interfaces need to manually be enabled and only expose a subset of APIs due to security reasons.
|
||||
These can be turned on/off and configured as you'd expect.
|
||||
|
||||
HTTP based JSON-RPC API options:
|
||||
|
||||
* `--rpc` Enable the HTTP-RPC server
|
||||
* `--rpcaddr` HTTP-RPC server listening interface (default: "localhost")
|
||||
* `--rpcport` HTTP-RPC server listening port (default: 8545)
|
||||
* `--rpcapi` API's offered over the HTTP-RPC interface (default: "eth,net,web3")
|
||||
* `--rpccorsdomain` Comma separated list of domains from which to accept cross origin requests (browser enforced)
|
||||
* `--ws` Enable the WS-RPC server
|
||||
* `--wsaddr` WS-RPC server listening interface (default: "localhost")
|
||||
* `--wsport` WS-RPC server listening port (default: 8546)
|
||||
* `--wsapi` API's offered over the WS-RPC interface (default: "eth,net,web3")
|
||||
* `--wsorigins` Origins from which to accept websockets requests
|
||||
* `--ipcdisable` Disable the IPC-RPC server
|
||||
* `--ipcapi` API's offered over the IPC-RPC interface (default: "admin,debug,eth,miner,net,personal,shh,txpool,web3")
|
||||
* `--ipcpath` Filename for IPC socket/pipe within the datadir (explicit paths escape it)
|
||||
|
||||
You'll need to use your own programming environments' capabilities (libraries, tools, etc) to connect
|
||||
via HTTP, WS or IPC to a Geth node configured with the above flags and you'll need to speak [JSON-RPC](https://www.jsonrpc.org/specification)
|
||||
on all transports. You can reuse the same connection for multiple requests!
|
||||
|
||||
**Note: Please understand the security implications of opening up an HTTP/WS based transport before
|
||||
doing so! Hackers on the internet are actively trying to subvert Ethereum nodes with exposed APIs!
|
||||
Further, all browser tabs can access locally running web servers, so malicious web pages could try to
|
||||
subvert locally available APIs!**
|
||||
|
||||
### Operating a private network
|
||||
|
||||
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.
|
||||
|
||||
#### Defining the private genesis state
|
||||
|
||||
First, you'll need to create the genesis state of your networks, which all nodes need to be aware of
|
||||
and agree upon. This consists of a small JSON file (e.g. call it `genesis.json`):
|
||||
|
||||
```json
|
||||
{
|
||||
"config": {
|
||||
"chainId": 0,
|
||||
"homesteadBlock": 0,
|
||||
"eip155Block": 0,
|
||||
"eip158Block": 0
|
||||
},
|
||||
"alloc" : {},
|
||||
"coinbase" : "0x0000000000000000000000000000000000000000",
|
||||
"difficulty" : "0x20000",
|
||||
"extraData" : "",
|
||||
"gasLimit" : "0x2fefd8",
|
||||
"nonce" : "0x0000000000000042",
|
||||
"mixhash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"timestamp" : "0x00"
|
||||
}
|
||||
```
|
||||
|
||||
The above fields should be fine for most purposes, although we'd recommend changing the `nonce` to
|
||||
some random value so you prevent unknown remote nodes from being able to connect to you. If you'd
|
||||
like to pre-fund some accounts for easier testing, you can populate the `alloc` field with account
|
||||
configs:
|
||||
|
||||
```json
|
||||
"alloc": {
|
||||
"0x0000000000000000000000000000000000000001": {"balance": "111111111"},
|
||||
"0x0000000000000000000000000000000000000002": {"balance": "222222222"}
|
||||
}
|
||||
```
|
||||
|
||||
With the genesis state defined in the above JSON file, you'll need to initialize **every** Geth node
|
||||
with it prior to starting it up to ensure all blockchain parameters are correctly set:
|
||||
|
||||
```
|
||||
$ geth init path/to/genesis.json
|
||||
```
|
||||
|
||||
#### Creating the rendezvous point
|
||||
|
||||
With all nodes that you want to run initialized to the desired genesis state, you'll need to start a
|
||||
bootstrap node that others can use to find each other in your network and/or over the internet. The
|
||||
clean way is to configure and run a dedicated bootnode:
|
||||
|
||||
```
|
||||
$ bootnode --genkey=boot.key
|
||||
$ bootnode --nodekey=boot.key
|
||||
```
|
||||
|
||||
With the bootnode online, it will display an [`enode` URL](https://github.com/ethereum/wiki/wiki/enode-url-format)
|
||||
that other nodes can use to connect to it and exchange peer information. Make sure to replace the
|
||||
displayed IP address information (most probably `[::]`) with your externally accessible IP to get the
|
||||
actual `enode` URL.
|
||||
|
||||
*Note: You could also use a full-fledged Geth node as a bootnode, but it's the less recommended way.*
|
||||
|
||||
#### Starting up your member nodes
|
||||
|
||||
With the bootnode operational and externally reachable (you can try `telnet <ip> <port>` to ensure
|
||||
it's indeed reachable), start every subsequent Geth node pointed to the bootnode for peer discovery
|
||||
via the `--bootnodes` flag. It will probably also be desirable to keep the data directory of your
|
||||
private network separated, so do also specify a custom `--datadir` flag.
|
||||
|
||||
```
|
||||
$ geth --datadir=path/to/custom/data/folder --bootnodes=<bootnode-enode-url-from-above>
|
||||
```
|
||||
|
||||
*Note: Since your network will be completely cut off from the main and test networks, you'll also
|
||||
need to configure a miner to process transactions and create new blocks for you.*
|
||||
|
||||
#### Running a private miner
|
||||
|
||||
Mining on the public Ethereum network is a complex task as it's only feasible using GPUs, requiring
|
||||
an OpenCL or CUDA enabled `ethminer` instance. For information on such a setup, please consult the
|
||||
[EtherMining subreddit](https://www.reddit.com/r/EtherMining/) and the [Genoil miner](https://github.com/Genoil/cpp-ethereum)
|
||||
repository.
|
||||
|
||||
In a private network setting, however a single CPU miner instance is more than enough for practical
|
||||
purposes as it can produce a stable stream of blocks at the correct intervals without needing heavy
|
||||
resources (consider running on a single thread, no need for multiple ones either). To start a Geth
|
||||
instance for mining, run it with all your usual flags, extended by:
|
||||
|
||||
```
|
||||
$ geth <usual-flags> --mine --minerthreads=1 --etherbase=0x0000000000000000000000000000000000000000
|
||||
```
|
||||
|
||||
Which will start mining blocks and transactions on a single CPU thread, crediting all proceedings to
|
||||
the account specified by `--etherbase`. You can further tune the mining by changing the default gas
|
||||
limit blocks converge to (`--targetgaslimit`) and the price transactions are accepted at (`--gasprice`).
|
||||
|
||||
## Contribution
|
||||
|
||||
Thank you for considering to help out with the source code! We welcome contributions from
|
||||
anyone on the internet, and are grateful for even the smallest of fixes!
|
||||
|
||||
If you'd like to contribute to go-ethereum, please fork, fix, commit and send a pull request
|
||||
for the maintainers to review and merge into the main code base. If you wish to submit more
|
||||
complex changes though, please check up with the core devs first on [our gitter channel](https://gitter.im/ethereum/go-ethereum)
|
||||
to ensure those changes are in line with the general philosophy of the project and/or get some
|
||||
early feedback which can make both your efforts much lighter as well as our review and merge
|
||||
procedures quick and simple.
|
||||
|
||||
Please make sure your contributions adhere to our coding guidelines:
|
||||
|
||||
* Code must adhere to the official Go [formatting](https://golang.org/doc/effective_go.html#formatting) guidelines (i.e. uses [gofmt](https://golang.org/cmd/gofmt/)).
|
||||
* Code must be documented adhering to the official Go [commentary](https://golang.org/doc/effective_go.html#commentary) guidelines.
|
||||
* Pull requests need to be based on and opened against the `master` branch.
|
||||
* Commit messages should be prefixed with the package(s) they modify.
|
||||
* E.g. "eth, rpc: make trace configs optional"
|
||||
|
||||
Please see the [Developers' Guide](https://github.com/ethereum/go-ethereum/wiki/Developers'-Guide)
|
||||
for more details on configuring your environment, managing project dependencies, and testing procedures.
|
||||
|
||||
## License
|
||||
|
||||
The go-ethereum library (i.e. all code outside of the `cmd` directory) is licensed under the
|
||||
[GNU Lesser General Public License v3.0](https://www.gnu.org/licenses/lgpl-3.0.en.html), also
|
||||
included in our repository in the `COPYING.LESSER` file.
|
||||
|
||||
The go-ethereum binaries (i.e. all code inside of the `cmd` directory) is licensed under the
|
||||
[GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0.en.html), also included
|
||||
in our repository in the `COPYING` file.
|
120
vendor/github.com/ethereum/go-ethereum/SECURITY.md
generated
vendored
Normal file
120
vendor/github.com/ethereum/go-ethereum/SECURITY.md
generated
vendored
Normal file
@ -0,0 +1,120 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Versions
|
||||
|
||||
Please see Releases. We recommend to use the most recent released version.
|
||||
|
||||
## Audit reports
|
||||
|
||||
Audit reports are published in the `docs` folder: https://github.com/ethereum/go-ethereum/tree/master/docs/audits
|
||||
|
||||
|
||||
| Scope | Date | Report Link |
|
||||
| ------- | ------- | ----------- |
|
||||
| `geth` | 20170425 | [pdf](https://github.com/ethereum/go-ethereum/blob/master/docs/audits/2017-04-25_Geth-audit_Truesec.pdf) |
|
||||
| `clef` | 20180914 | [pdf](https://github.com/ethereum/go-ethereum/blob/master/docs/audits/2018-09-14_Clef-audit_NCC.pdf) |
|
||||
|
||||
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
**Please do not file a public ticket** mentioning the vulnerability.
|
||||
|
||||
To find out how to disclose a vulnerability in Ethereum visit [https://bounty.ethereum.org](https://bounty.ethereum.org) or email bounty@ethereum.org.
|
||||
|
||||
The following key may be used to communicate sensitive information to developers.
|
||||
|
||||
Fingerprint: `AE96 ED96 9E47 9B00 84F3 E17F E88D 3334 FA5F 6A0A`
|
||||
|
||||
|
||||
```
|
||||
-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||
Version: GnuPG v1
|
||||
|
||||
mQINBFgl3tgBEAC8A1tUBkD9YV+eLrOmtgy+/JS/H9RoZvkg3K1WZ8IYfj6iIRaY
|
||||
neAk3Bp182GUPVz/zhKr2g0tMXIScDR3EnaDsY+Qg+JqQl8NOG+Cikr1nnkG2on9
|
||||
L8c8yiqry1ZTCmYMqCa2acTFqnyuXJ482aZNtB4QG2BpzfhW4k8YThpegk/EoRUi
|
||||
m+y7buJDtoNf7YILlhDQXN8qlHB02DWOVUihph9tUIFsPK6BvTr9SIr/eG6j6k0b
|
||||
fUo9pexOn7LS4SojoJmsm/5dp6AoKlac48cZU5zwR9AYcq/nvkrfmf2WkObg/xRd
|
||||
EvKZzn05jRopmAIwmoC3CiLmqCHPmT5a29vEob/yPFE335k+ujjZCPOu7OwjzDk7
|
||||
M0zMSfnNfDq8bXh16nn+ueBxJ0NzgD1oC6c2PhM+XRQCXChoyI8vbfp4dGvCvYqv
|
||||
QAE1bWjqnumZ/7vUPgZN6gDfiAzG2mUxC2SeFBhacgzDvtQls+uuvm+FnQOUgg2H
|
||||
h8x2zgoZ7kqV29wjaUPFREuew7e+Th5BxielnzOfVycVXeSuvvIn6cd3g/s8mX1c
|
||||
2kLSXJR7+KdWDrIrR5Az0kwAqFZt6B6QTlDrPswu3mxsm5TzMbny0PsbL/HBM+GZ
|
||||
EZCjMXxB8bqV2eSaktjnSlUNX1VXxyOxXA+ZG2jwpr51egi57riVRXokrQARAQAB
|
||||
tDlFdGhlcmV1bSBGb3VuZGF0aW9uIFNlY3VyaXR5IFRlYW0gPHNlY3VyaXR5QGV0
|
||||
aGVyZXVtLm9yZz6JAj4EEwECACgCGwMGCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheA
|
||||
BQJaCWH6BQkFo2BYAAoJEOiNMzT6X2oK+DEP/3H6dxkm0hvHZKoHLVuuxcu3EHYo
|
||||
k5sd3MMWPrZSN8qzZnY7ayEDMxnarWOizc+2jfOxfJlzX/g8lR1/fsHdWPFPhPoV
|
||||
Qk8ygrHn1H8U8+rpw/U03BqmqHpYCDzJ+CIis9UWROniqXw1nuqu/FtWOsdWxNKh
|
||||
jUo6k/0EsaXsxRPzgJv7fEUcVcQ7as/C3x9sy3muc2gvgA4/BKoGPb1/U0GuA8lV
|
||||
fDIDshAggmnSUAg+TuYSAAdoFQ1sKwFMPigcLJF2eyKuK3iUyixJrec/c4LSf3wA
|
||||
cGghbeuqI8INP0Y2zvXDQN2cByxsFAuoZG+m0cyKGaDH2MVUvOKKYqn/03qvrf15
|
||||
AWAsW0l0yQwOTCo3FbsNzemClm5Bj/xH0E4XuwXwChcMCMOWJrFoxyvCEI+keoQc
|
||||
c08/a8/MtS7vBAABXwOziSmm6CNqmzpWrh/fDrjlJlba9U3MxzvqU3IFlTdMratv
|
||||
6V+SgX+L25lCzW4NxxUavoB8fAlvo8lxpHKo24FP+RcLQ8XqkU3RiUsgRjQRFOqQ
|
||||
TaJcsp8mimmiYyf24mNu6b48pi+a5c/eQR9w59emeEUZqsJU+nqv8BWIIp7o4Agh
|
||||
NYnKjkhPlY5e1fLVfAHIADZFynWwRPkPMJSrBiP5EtcOFxQGHGjRxU/KjXkvE0hV
|
||||
xYb1PB8pWMTu/beeiQI+BBMBAgAoBQJYJd7YAhsDBQkB4TOABgsJCAcDAgYVCAIJ
|
||||
CgsEFgIDAQIeAQIXgAAKCRDojTM0+l9qCplDD/9IZ2i+m1cnqQKtiyHbyFGx32oL
|
||||
fzqPylX2bOG5DPsSTorSUdJMGVfT04oVxXc4S/2DVnNvi7RAbSiLapCWSplgtBOj
|
||||
j1xlblOoXxT3m7s1XHGCX5tENxI9fVSSPVKJn+fQaWpPB2MhBA+1lUI6GJ+11T7K
|
||||
J8LrP/fiw1/nOb7rW61HW44Gtyox23sA/d1+DsFVaF8hxJlNj5coPKr8xWzQ8pQl
|
||||
juzdjHDukjevuw4rRmRq9vozvj9keEU9XJ5dldyEVXFmdDk7KT0p0Rla9nxYhzf/
|
||||
r/Bv8Bzy0HCWRb2D31BjXXGG05oVnYmNGxGFxYja4MwgrMmne3ilEVjfUJsapsqi
|
||||
w41BAyQgIdfREulYN7ahsF5PrjVAqBd9IGtE8ULelF2SQxEBQBngEkP0ahP6tRAL
|
||||
i7/CBjPKOyKijtqVny7qrGOnU2ygcA88/WDibexDhrjz0Gx8WmErU7rIWZiZ5u4Y
|
||||
vJYVRo0+6rBCXRPeSJfiP5h1p17Anr2l42boAYslfcrzquB8MHtrNcyn650OLtHG
|
||||
nbxgIdniKrpuzGN6Opw+O2id2JhD1/1p4SOemwAmthplr1MIyOHNP3q93rEj2J7h
|
||||
5zPS/AJuKkMDFUpslPNLQjCOwPXtdzL7/kUZGBSyez1T3TaW1uY6l9XaJJRaSn+v
|
||||
1zPgfp4GJ3lPs4AlAbQ0RXRoZXJldW0gRm91bmRhdGlvbiBCdWcgQm91bnR5IDxi
|
||||
b3VudHlAZXRoZXJldW0ub3JnPokCPgQTAQIAKAIbAwYLCQgHAwIGFQgCCQoLBBYC
|
||||
AwECHgECF4AFAloJYfoFCQWjYFgACgkQ6I0zNPpfagoENg/+LnSaVeMxiGVtcjWl
|
||||
b7Xd73yrEy4uxiESS1AalW9mMf7oZzfI05f7QIQlaLAkNac74vZDJbPKjtb7tpMO
|
||||
RFhRZMCveq6CPKU6pd1SI8IUVUKwpEe6AJP3lHdVP57dquieFE2HlYKm6uHbCGWU
|
||||
0cjyTA+uu2KbgCHGmofsPY/xOcZLGEHTHqa5w60JJAQm+BSDKnw8wTyrxGvA3EK/
|
||||
ePSvOZMYa+iw6vYuZeBIMbdiXR/A2keBi3GuvqB8tDMj7P22TrH5mVDm3zNqGYD6
|
||||
amDPeiWp4cztY3aZyLcgYotqXPpDceZzDn+HopBPzAb/llCdE7bVswKRhphVMw4b
|
||||
bhL0R/TQY7Sf6TK2LKSBrjv0DWOSijikE71SJcBnJvHU7EpKrQQ0lMGclm3ynyji
|
||||
Nf0YTPXQt4I+fwTmOew2GFeK3UytNWbWI7oXX7Nm4bj9bhf3IJ0kmZb/Gs73+xII
|
||||
e7Rz52Mby436tWyQIQiF9ITYNGvNf53TwBBZMn0pKPiTyr3Ur7FHEotkEOFNh1//
|
||||
4zQY10XxuBdLrYGyZ4V8xHJM+oKre8Eg2R9qHXVbjvErHE+7CvgnV7YUip0criPr
|
||||
BlKRvuoJaSliH2JFhSjWVrkPmFGrWN0BAx10yIqMnEplfKeHf4P9Elek3oInS8WP
|
||||
G1zJG6s/t5+hQK0X37+TB+6rd3GJAj4EEwECACgFAlgl4TsCGwMFCQHhM4AGCwkI
|
||||
BwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEOiNMzT6X2oKzf8P/iIKd77WHTbp4pMN
|
||||
8h52HyZJtDJmjA1DPZrbGl1TesW/Z9uTd12txlgqZnbG2GfN9+LSP6EOPzR6v2xC
|
||||
OVhR+RdWhZDJJuQCVS7lJIqQrZgmeTZG0TyQPZdLjVFBOrrhVwYX+HXbu429IzHr
|
||||
URf5InyR1QgqOXyElDYS6e28HFqvaoA0DWTWDDqOLPVl+U5fuceIE2XXdv3AGLeP
|
||||
Yf8J5MPobjPiZtBqI6S6iENY2Yn35qLX+axeC/iYSCHVtFuCCIdb/QYR1ZZV8Ps/
|
||||
aI9DwC7LU+YfPw7iqCIoqxSeA3o1PORkdSigEg3jtfRv5UqVo9a0oBb9jdoADsat
|
||||
F/gW0E7mto3XGOiaR0eB9SSdsM3x7Bz4A0HIGNaxpZo1RWqlO91leP4c13Px7ISv
|
||||
5OGXfLg+M8qb+qxbGd1HpitGi9s1y1aVfEj1kOtZ0tN8eu+Upg5WKwPNBDX3ar7J
|
||||
9NCULgVSL+E79FG+zXw62gxiQrLfKzm4wU/9L5wVkwQnm29hLJ0tokrSBZFnc/1l
|
||||
7OC+GM63tYicKkY4rqmoWUeYx7IwFH9mtDtvR1RxO85RbQhZizwpZpdpRkH0DqZu
|
||||
ZJRmRa5r7rPqmfa7d+VIFhz2Xs8pJMLVqxTsLKcLglmjw7aOrYG0SWeH7YraXWGD
|
||||
N3SlvSBiVwcK7QUKzLLvpadLwxfsuQINBFgl3tgBEACbgq6HTN5gEBi0lkD/MafI
|
||||
nmNi+59U5gRGYqk46WlfRjhHudXjDpgD0lolGb4hYontkMaKRlCg2Rvgjvk3Zve0
|
||||
PKWjKw7gr8YBa9fMFY8BhAXI32OdyI9rFhxEZFfWAfwKVmT19BdeAQRFvcfd+8w8
|
||||
f1XVc+zddULMJFBTr+xKDlIRWwTkdLPQeWbjo0eHl/g4tuLiLrTxVbnj26bf+2+1
|
||||
DbM/w5VavzPrkviHqvKe/QP/gay4QDViWvFgLb90idfAHIdsPgflp0VDS5rVHFL6
|
||||
D73rSRdIRo3I8c8mYoNjSR4XDuvgOkAKW9LR3pvouFHHjp6Fr0GesRbrbb2EG66i
|
||||
PsR99MQ7FqIL9VMHPm2mtR+XvbnKkH2rYyEqaMbSdk29jGapkAWle4sIhSKk749A
|
||||
4tGkHl08KZ2N9o6GrfUehP/V2eJLaph2DioFL1HxRryrKy80QQKLMJRekxigq8gr
|
||||
eW8xB4zuf9Mkuou+RHNmo8PebHjFstLigiD6/zP2e+4tUmrT0/JTGOShoGMl8Rt0
|
||||
VRxdPImKun+4LOXbfOxArOSkY6i35+gsgkkSy1gTJE0BY3S9auT6+YrglY/TWPQ9
|
||||
IJxWVOKlT+3WIp5wJu2bBKQ420VLqDYzkoWytel/bM1ACUtipMiIVeUs2uFiRjpz
|
||||
A1Wy0QHKPTdSuGlJPRrfcQARAQABiQIlBBgBAgAPAhsMBQJaCWIIBQkFo2BYAAoJ
|
||||
EOiNMzT6X2oKgSwQAKKs7BGF8TyZeIEO2EUK7R2bdQDCdSGZY06tqLFg3IHMGxDM
|
||||
b/7FVoa2AEsFgv6xpoebxBB5zkhUk7lslgxvKiSLYjxfNjTBltfiFJ+eQnf+OTs8
|
||||
KeR51lLa66rvIH2qUzkNDCCTF45H4wIDpV05AXhBjKYkrDCrtey1rQyFp5fxI+0I
|
||||
Q1UKKXvzZK4GdxhxDbOUSd38MYy93nqcmclGSGK/gF8XiyuVjeifDCM6+T1NQTX0
|
||||
K9lneidcqtBDvlggJTLJtQPO33o5EHzXSiud+dKth1uUhZOFEaYRZoye1YE3yB0T
|
||||
NOOE8fXlvu8iuIAMBSDL9ep6sEIaXYwoD60I2gHdWD0lkP0DOjGQpi4ouXM3Edsd
|
||||
5MTi0MDRNTij431kn8T/D0LCgmoUmYYMBgbwFhXr67axPZlKjrqR0z3F/Elv0ZPP
|
||||
cVg1tNznsALYQ9Ovl6b5M3cJ5GapbbvNWC7yEE1qScl9HiMxjt/H6aPastH63/7w
|
||||
cN0TslW+zRBy05VNJvpWGStQXcngsSUeJtI1Gd992YNjUJq4/Lih6Z1TlwcFVap+
|
||||
cTcDptoUvXYGg/9mRNNPZwErSfIJ0Ibnx9wPVuRN6NiCLOt2mtKp2F1pM6AOQPpZ
|
||||
85vEh6I8i6OaO0w/Z0UHBwvpY6jDUliaROsWUQsqz78Z34CVj4cy6vPW2EF4
|
||||
=r6KK
|
||||
-----END PGP PUBLIC KEY BLOCK-----
|
||||
```
|
81
vendor/github.com/ethereum/go-ethereum/accounts/abi/bind/auth.go
generated
vendored
Normal file
81
vendor/github.com/ethereum/go-ethereum/accounts/abi/bind/auth.go
generated
vendored
Normal file
@ -0,0 +1,81 @@
|
||||
// Copyright 2016 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package bind
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"errors"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
|
||||
"github.com/ethereum/go-ethereum/accounts"
|
||||
"github.com/ethereum/go-ethereum/accounts/keystore"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
)
|
||||
|
||||
// NewTransactor is a utility method to easily create a transaction signer from
|
||||
// an encrypted json key stream and the associated passphrase.
|
||||
func NewTransactor(keyin io.Reader, passphrase string) (*TransactOpts, error) {
|
||||
json, err := ioutil.ReadAll(keyin)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
key, err := keystore.DecryptKey(json, passphrase)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewKeyedTransactor(key.PrivateKey), nil
|
||||
}
|
||||
|
||||
// NewKeystoreTransactor is a utility method to easily create a transaction signer from
|
||||
// an decrypted key from a keystore
|
||||
func NewKeyStoreTransactor(keystore *keystore.KeyStore, account accounts.Account) (*TransactOpts, error) {
|
||||
return &TransactOpts{
|
||||
From: account.Address,
|
||||
Signer: func(signer types.Signer, address common.Address, tx *types.Transaction) (*types.Transaction, error) {
|
||||
if address != account.Address {
|
||||
return nil, errors.New("not authorized to sign this account")
|
||||
}
|
||||
signature, err := keystore.SignHash(account, signer.Hash(tx).Bytes())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tx.WithSignature(signer, signature)
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// NewKeyedTransactor is a utility method to easily create a transaction signer
|
||||
// from a single private key.
|
||||
func NewKeyedTransactor(key *ecdsa.PrivateKey) *TransactOpts {
|
||||
keyAddr := crypto.PubkeyToAddress(key.PublicKey)
|
||||
return &TransactOpts{
|
||||
From: keyAddr,
|
||||
Signer: func(signer types.Signer, address common.Address, tx *types.Transaction) (*types.Transaction, error) {
|
||||
if address != keyAddr {
|
||||
return nil, errors.New("not authorized to sign this account")
|
||||
}
|
||||
signature, err := crypto.Sign(signer.Hash(tx).Bytes(), key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tx.WithSignature(signer, signature)
|
||||
},
|
||||
}
|
||||
}
|
6
vendor/github.com/ethereum/go-ethereum/accounts/abi/bind/backends/simulated.go
generated
vendored
6
vendor/github.com/ethereum/go-ethereum/accounts/abi/bind/backends/simulated.go
generated
vendored
@ -160,7 +160,7 @@ func (b *SimulatedBackend) StorageAt(ctx context.Context, contract common.Addres
|
||||
|
||||
// TransactionReceipt returns the receipt of a transaction.
|
||||
func (b *SimulatedBackend) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) {
|
||||
receipt, _, _, _ := rawdb.ReadReceipt(b.database, txHash)
|
||||
receipt, _, _, _ := rawdb.ReadReceipt(b.database, txHash, b.config)
|
||||
return receipt, nil
|
||||
}
|
||||
|
||||
@ -464,7 +464,7 @@ func (fb *filterBackend) GetReceipts(ctx context.Context, hash common.Hash) (typ
|
||||
if number == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return rawdb.ReadReceipts(fb.db, hash, *number), nil
|
||||
return rawdb.ReadReceipts(fb.db, hash, *number, fb.bc.Config()), nil
|
||||
}
|
||||
|
||||
func (fb *filterBackend) GetLogs(ctx context.Context, hash common.Hash) ([][]*types.Log, error) {
|
||||
@ -472,7 +472,7 @@ func (fb *filterBackend) GetLogs(ctx context.Context, hash common.Hash) ([][]*ty
|
||||
if number == nil {
|
||||
return nil, nil
|
||||
}
|
||||
receipts := rawdb.ReadReceipts(fb.db, hash, *number)
|
||||
receipts := rawdb.ReadReceipts(fb.db, hash, *number, fb.bc.Config())
|
||||
if receipts == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
77
vendor/github.com/ethereum/go-ethereum/accounts/abi/method.go
generated
vendored
Normal file
77
vendor/github.com/ethereum/go-ethereum/accounts/abi/method.go
generated
vendored
Normal file
@ -0,0 +1,77 @@
|
||||
// Copyright 2015 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package abi
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
)
|
||||
|
||||
// Method represents a callable given a `Name` and whether the method is a constant.
|
||||
// If the method is `Const` no transaction needs to be created for this
|
||||
// particular Method call. It can easily be simulated using a local VM.
|
||||
// For example a `Balance()` method only needs to retrieve something
|
||||
// from the storage and therefore requires no Tx to be send to the
|
||||
// network. A method such as `Transact` does require a Tx and thus will
|
||||
// be flagged `false`.
|
||||
// Input specifies the required input parameters for this gives method.
|
||||
type Method struct {
|
||||
Name string
|
||||
Const bool
|
||||
Inputs Arguments
|
||||
Outputs Arguments
|
||||
}
|
||||
|
||||
// Sig returns the methods string signature according to the ABI spec.
|
||||
//
|
||||
// Example
|
||||
//
|
||||
// function foo(uint32 a, int b) = "foo(uint32,int256)"
|
||||
//
|
||||
// Please note that "int" is substitute for its canonical representation "int256"
|
||||
func (method Method) Sig() string {
|
||||
types := make([]string, len(method.Inputs))
|
||||
for i, input := range method.Inputs {
|
||||
types[i] = input.Type.String()
|
||||
}
|
||||
return fmt.Sprintf("%v(%v)", method.Name, strings.Join(types, ","))
|
||||
}
|
||||
|
||||
func (method Method) String() string {
|
||||
inputs := make([]string, len(method.Inputs))
|
||||
for i, input := range method.Inputs {
|
||||
inputs[i] = fmt.Sprintf("%v %v", input.Type, input.Name)
|
||||
}
|
||||
outputs := make([]string, len(method.Outputs))
|
||||
for i, output := range method.Outputs {
|
||||
outputs[i] = output.Type.String()
|
||||
if len(output.Name) > 0 {
|
||||
outputs[i] += fmt.Sprintf(" %v", output.Name)
|
||||
}
|
||||
}
|
||||
constant := ""
|
||||
if method.Const {
|
||||
constant = "constant "
|
||||
}
|
||||
return fmt.Sprintf("function %v(%v) %sreturns(%v)", method.Name, strings.Join(inputs, ", "), constant, strings.Join(outputs, ", "))
|
||||
}
|
||||
|
||||
func (method Method) Id() []byte {
|
||||
return crypto.Keccak256([]byte(method.Sig()))[:4]
|
||||
}
|
222
vendor/github.com/ethereum/go-ethereum/accounts/accounts.go
generated
vendored
Normal file
222
vendor/github.com/ethereum/go-ethereum/accounts/accounts.go
generated
vendored
Normal file
@ -0,0 +1,222 @@
|
||||
// Copyright 2017 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
// Package accounts implements high level Ethereum account management.
|
||||
package accounts
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/big"
|
||||
|
||||
ethereum "github.com/ethereum/go-ethereum"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/event"
|
||||
"golang.org/x/crypto/sha3"
|
||||
)
|
||||
|
||||
// Account represents an Ethereum account located at a specific location defined
|
||||
// by the optional URL field.
|
||||
type Account struct {
|
||||
Address common.Address `json:"address"` // Ethereum account address derived from the key
|
||||
URL URL `json:"url"` // Optional resource locator within a backend
|
||||
}
|
||||
|
||||
const (
|
||||
MimetypeDataWithValidator = "data/validator"
|
||||
MimetypeTypedData = "data/typed"
|
||||
MimetypeClique = "application/x-clique-header"
|
||||
MimetypeTextPlain = "text/plain"
|
||||
)
|
||||
|
||||
// Wallet represents a software or hardware wallet that might contain one or more
|
||||
// accounts (derived from the same seed).
|
||||
type Wallet interface {
|
||||
// URL retrieves the canonical path under which this wallet is reachable. It is
|
||||
// user by upper layers to define a sorting order over all wallets from multiple
|
||||
// backends.
|
||||
URL() URL
|
||||
|
||||
// Status returns a textual status to aid the user in the current state of the
|
||||
// wallet. It also returns an error indicating any failure the wallet might have
|
||||
// encountered.
|
||||
Status() (string, error)
|
||||
|
||||
// Open initializes access to a wallet instance. It is not meant to unlock or
|
||||
// decrypt account keys, rather simply to establish a connection to hardware
|
||||
// wallets and/or to access derivation seeds.
|
||||
//
|
||||
// The passphrase parameter may or may not be used by the implementation of a
|
||||
// particular wallet instance. The reason there is no passwordless open method
|
||||
// is to strive towards a uniform wallet handling, oblivious to the different
|
||||
// backend providers.
|
||||
//
|
||||
// Please note, if you open a wallet, you must close it to release any allocated
|
||||
// resources (especially important when working with hardware wallets).
|
||||
Open(passphrase string) error
|
||||
|
||||
// Close releases any resources held by an open wallet instance.
|
||||
Close() error
|
||||
|
||||
// Accounts retrieves the list of signing accounts the wallet is currently aware
|
||||
// of. For hierarchical deterministic wallets, the list will not be exhaustive,
|
||||
// rather only contain the accounts explicitly pinned during account derivation.
|
||||
Accounts() []Account
|
||||
|
||||
// Contains returns whether an account is part of this particular wallet or not.
|
||||
Contains(account Account) bool
|
||||
|
||||
// Derive attempts to explicitly derive a hierarchical deterministic account at
|
||||
// the specified derivation path. If requested, the derived account will be added
|
||||
// to the wallet's tracked account list.
|
||||
Derive(path DerivationPath, pin bool) (Account, error)
|
||||
|
||||
// SelfDerive sets a base account derivation path from which the wallet attempts
|
||||
// to discover non zero accounts and automatically add them to list of tracked
|
||||
// accounts.
|
||||
//
|
||||
// Note, self derivaton will increment the last component of the specified path
|
||||
// opposed to decending into a child path to allow discovering accounts starting
|
||||
// from non zero components.
|
||||
//
|
||||
// Some hardware wallets switched derivation paths through their evolution, so
|
||||
// this method supports providing multiple bases to discover old user accounts
|
||||
// too. Only the last base will be used to derive the next empty account.
|
||||
//
|
||||
// You can disable automatic account discovery by calling SelfDerive with a nil
|
||||
// chain state reader.
|
||||
SelfDerive(bases []DerivationPath, chain ethereum.ChainStateReader)
|
||||
|
||||
// SignData requests the wallet to sign the hash of the given data
|
||||
// It looks up the account specified either solely via its address contained within,
|
||||
// or optionally with the aid of any location metadata from the embedded URL field.
|
||||
//
|
||||
// If the wallet requires additional authentication to sign the request (e.g.
|
||||
// a password to decrypt the account, or a PIN code o verify the transaction),
|
||||
// an AuthNeededError instance will be returned, containing infos for the user
|
||||
// about which fields or actions are needed. The user may retry by providing
|
||||
// the needed details via SignDataWithPassphrase, or by other means (e.g. unlock
|
||||
// the account in a keystore).
|
||||
SignData(account Account, mimeType string, data []byte) ([]byte, error)
|
||||
|
||||
// SignDataWithPassphrase is identical to SignData, but also takes a password
|
||||
// NOTE: there's an chance that an erroneous call might mistake the two strings, and
|
||||
// supply password in the mimetype field, or vice versa. Thus, an implementation
|
||||
// should never echo the mimetype or return the mimetype in the error-response
|
||||
SignDataWithPassphrase(account Account, passphrase, mimeType string, data []byte) ([]byte, error)
|
||||
|
||||
// SignText requests the wallet to sign the hash of a given piece of data, prefixed
|
||||
// by the Ethereum prefix scheme
|
||||
// It looks up the account specified either solely via its address contained within,
|
||||
// or optionally with the aid of any location metadata from the embedded URL field.
|
||||
//
|
||||
// If the wallet requires additional authentication to sign the request (e.g.
|
||||
// a password to decrypt the account, or a PIN code o verify the transaction),
|
||||
// an AuthNeededError instance will be returned, containing infos for the user
|
||||
// about which fields or actions are needed. The user may retry by providing
|
||||
// the needed details via SignHashWithPassphrase, or by other means (e.g. unlock
|
||||
// the account in a keystore).
|
||||
SignText(account Account, text []byte) ([]byte, error)
|
||||
|
||||
// SignTextWithPassphrase is identical to Signtext, but also takes a password
|
||||
SignTextWithPassphrase(account Account, passphrase string, hash []byte) ([]byte, error)
|
||||
|
||||
// SignTx requests the wallet to sign the given transaction.
|
||||
//
|
||||
// It looks up the account specified either solely via its address contained within,
|
||||
// or optionally with the aid of any location metadata from the embedded URL field.
|
||||
//
|
||||
// If the wallet requires additional authentication to sign the request (e.g.
|
||||
// a password to decrypt the account, or a PIN code to verify the transaction),
|
||||
// an AuthNeededError instance will be returned, containing infos for the user
|
||||
// about which fields or actions are needed. The user may retry by providing
|
||||
// the needed details via SignTxWithPassphrase, or by other means (e.g. unlock
|
||||
// the account in a keystore).
|
||||
SignTx(account Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error)
|
||||
|
||||
// SignTxWithPassphrase is identical to SignTx, but also takes a password
|
||||
SignTxWithPassphrase(account Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error)
|
||||
}
|
||||
|
||||
// Backend is a "wallet provider" that may contain a batch of accounts they can
|
||||
// sign transactions with and upon request, do so.
|
||||
type Backend interface {
|
||||
// Wallets retrieves the list of wallets the backend is currently aware of.
|
||||
//
|
||||
// The returned wallets are not opened by default. For software HD wallets this
|
||||
// means that no base seeds are decrypted, and for hardware wallets that no actual
|
||||
// connection is established.
|
||||
//
|
||||
// The resulting wallet list will be sorted alphabetically based on its internal
|
||||
// URL assigned by the backend. Since wallets (especially hardware) may come and
|
||||
// go, the same wallet might appear at a different positions in the list during
|
||||
// subsequent retrievals.
|
||||
Wallets() []Wallet
|
||||
|
||||
// Subscribe creates an async subscription to receive notifications when the
|
||||
// backend detects the arrival or departure of a wallet.
|
||||
Subscribe(sink chan<- WalletEvent) event.Subscription
|
||||
}
|
||||
|
||||
// TextHash is a helper function that calculates a hash for the given message that can be
|
||||
// safely used to calculate a signature from.
|
||||
//
|
||||
// The hash is calulcated as
|
||||
// keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
|
||||
//
|
||||
// This gives context to the signed message and prevents signing of transactions.
|
||||
func TextHash(data []byte) []byte {
|
||||
hash, _ := TextAndHash(data)
|
||||
return hash
|
||||
}
|
||||
|
||||
// TextAndHash is a helper function that calculates a hash for the given message that can be
|
||||
// safely used to calculate a signature from.
|
||||
//
|
||||
// The hash is calulcated as
|
||||
// keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
|
||||
//
|
||||
// This gives context to the signed message and prevents signing of transactions.
|
||||
func TextAndHash(data []byte) ([]byte, string) {
|
||||
msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), string(data))
|
||||
hasher := sha3.NewLegacyKeccak256()
|
||||
hasher.Write([]byte(msg))
|
||||
return hasher.Sum(nil), msg
|
||||
}
|
||||
|
||||
// WalletEventType represents the different event types that can be fired by
|
||||
// the wallet subscription subsystem.
|
||||
type WalletEventType int
|
||||
|
||||
const (
|
||||
// WalletArrived is fired when a new wallet is detected either via USB or via
|
||||
// a filesystem event in the keystore.
|
||||
WalletArrived WalletEventType = iota
|
||||
|
||||
// WalletOpened is fired when a wallet is successfully opened with the purpose
|
||||
// of starting any background processes such as automatic key derivation.
|
||||
WalletOpened
|
||||
|
||||
// WalletDropped
|
||||
WalletDropped
|
||||
)
|
||||
|
||||
// WalletEvent is an event fired by an account backend when a wallet arrival or
|
||||
// departure is detected.
|
||||
type WalletEvent struct {
|
||||
Wallet Wallet // Wallet instance arrived or departed
|
||||
Kind WalletEventType // Event type that happened in the system
|
||||
}
|
228
vendor/github.com/ethereum/go-ethereum/accounts/external/backend.go
generated
vendored
Normal file
228
vendor/github.com/ethereum/go-ethereum/accounts/external/backend.go
generated
vendored
Normal file
@ -0,0 +1,228 @@
|
||||
// Copyright 2018 The go-ethereum Authors
|
||||
// This file is part of go-ethereum.
|
||||
//
|
||||
// go-ethereum is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// go-ethereum is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package external
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/big"
|
||||
"sync"
|
||||
|
||||
"github.com/ethereum/go-ethereum"
|
||||
"github.com/ethereum/go-ethereum/accounts"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/common/hexutil"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/event"
|
||||
"github.com/ethereum/go-ethereum/internal/ethapi"
|
||||
"github.com/ethereum/go-ethereum/log"
|
||||
"github.com/ethereum/go-ethereum/rpc"
|
||||
"github.com/ethereum/go-ethereum/signer/core"
|
||||
)
|
||||
|
||||
type ExternalBackend struct {
|
||||
signers []accounts.Wallet
|
||||
}
|
||||
|
||||
func (eb *ExternalBackend) Wallets() []accounts.Wallet {
|
||||
return eb.signers
|
||||
}
|
||||
|
||||
func NewExternalBackend(endpoint string) (*ExternalBackend, error) {
|
||||
signer, err := NewExternalSigner(endpoint)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ExternalBackend{
|
||||
signers: []accounts.Wallet{signer},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (eb *ExternalBackend) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
|
||||
return event.NewSubscription(func(quit <-chan struct{}) error {
|
||||
<-quit
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// ExternalSigner provides an API to interact with an external signer (clef)
|
||||
// It proxies request to the external signer while forwarding relevant
|
||||
// request headers
|
||||
type ExternalSigner struct {
|
||||
client *rpc.Client
|
||||
endpoint string
|
||||
status string
|
||||
cacheMu sync.RWMutex
|
||||
cache []accounts.Account
|
||||
}
|
||||
|
||||
func NewExternalSigner(endpoint string) (*ExternalSigner, error) {
|
||||
client, err := rpc.Dial(endpoint)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
extsigner := &ExternalSigner{
|
||||
client: client,
|
||||
endpoint: endpoint,
|
||||
}
|
||||
// Check if reachable
|
||||
version, err := extsigner.pingVersion()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
extsigner.status = fmt.Sprintf("ok [version=%v]", version)
|
||||
return extsigner, nil
|
||||
}
|
||||
|
||||
func (api *ExternalSigner) URL() accounts.URL {
|
||||
return accounts.URL{
|
||||
Scheme: "extapi",
|
||||
Path: api.endpoint,
|
||||
}
|
||||
}
|
||||
|
||||
func (api *ExternalSigner) Status() (string, error) {
|
||||
return api.status, nil
|
||||
}
|
||||
|
||||
func (api *ExternalSigner) Open(passphrase string) error {
|
||||
return fmt.Errorf("operation not supported on external signers")
|
||||
}
|
||||
|
||||
func (api *ExternalSigner) Close() error {
|
||||
return fmt.Errorf("operation not supported on external signers")
|
||||
}
|
||||
|
||||
func (api *ExternalSigner) Accounts() []accounts.Account {
|
||||
var accnts []accounts.Account
|
||||
res, err := api.listAccounts()
|
||||
if err != nil {
|
||||
log.Error("account listing failed", "error", err)
|
||||
return accnts
|
||||
}
|
||||
for _, addr := range res {
|
||||
accnts = append(accnts, accounts.Account{
|
||||
URL: accounts.URL{
|
||||
Scheme: "extapi",
|
||||
Path: api.endpoint,
|
||||
},
|
||||
Address: addr,
|
||||
})
|
||||
}
|
||||
api.cacheMu.Lock()
|
||||
api.cache = accnts
|
||||
api.cacheMu.Unlock()
|
||||
return accnts
|
||||
}
|
||||
|
||||
func (api *ExternalSigner) Contains(account accounts.Account) bool {
|
||||
api.cacheMu.RLock()
|
||||
defer api.cacheMu.RUnlock()
|
||||
for _, a := range api.cache {
|
||||
if a.Address == account.Address && (account.URL == (accounts.URL{}) || account.URL == api.URL()) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (api *ExternalSigner) Derive(path accounts.DerivationPath, pin bool) (accounts.Account, error) {
|
||||
return accounts.Account{}, fmt.Errorf("operation not supported on external signers")
|
||||
}
|
||||
|
||||
func (api *ExternalSigner) SelfDerive(bases []accounts.DerivationPath, chain ethereum.ChainStateReader) {
|
||||
log.Error("operation SelfDerive not supported on external signers")
|
||||
}
|
||||
|
||||
func (api *ExternalSigner) signHash(account accounts.Account, hash []byte) ([]byte, error) {
|
||||
return []byte{}, fmt.Errorf("operation not supported on external signers")
|
||||
}
|
||||
|
||||
// SignData signs keccak256(data). The mimetype parameter describes the type of data being signed
|
||||
func (api *ExternalSigner) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) {
|
||||
var res hexutil.Bytes
|
||||
var signAddress = common.NewMixedcaseAddress(account.Address)
|
||||
if err := api.client.Call(&res, "account_signData",
|
||||
mimeType,
|
||||
&signAddress, // Need to use the pointer here, because of how MarshalJSON is defined
|
||||
hexutil.Encode(data)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// If V is on 27/28-form, convert to to 0/1 for Clique
|
||||
if mimeType == accounts.MimetypeClique && (res[64] == 27 || res[64] == 28) {
|
||||
res[64] -= 27 // Transform V from 27/28 to 0/1 for Clique use
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (api *ExternalSigner) SignText(account accounts.Account, text []byte) ([]byte, error) {
|
||||
var res hexutil.Bytes
|
||||
var signAddress = common.NewMixedcaseAddress(account.Address)
|
||||
if err := api.client.Call(&res, "account_signData",
|
||||
accounts.MimetypeTextPlain,
|
||||
&signAddress, // Need to use the pointer here, because of how MarshalJSON is defined
|
||||
hexutil.Encode(text)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (api *ExternalSigner) SignTx(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
|
||||
res := ethapi.SignTransactionResult{}
|
||||
to := common.NewMixedcaseAddress(*tx.To())
|
||||
data := hexutil.Bytes(tx.Data())
|
||||
args := &core.SendTxArgs{
|
||||
Data: &data,
|
||||
Nonce: hexutil.Uint64(tx.Nonce()),
|
||||
Value: hexutil.Big(*tx.Value()),
|
||||
Gas: hexutil.Uint64(tx.Gas()),
|
||||
GasPrice: hexutil.Big(*tx.GasPrice()),
|
||||
To: &to,
|
||||
From: common.NewMixedcaseAddress(account.Address),
|
||||
}
|
||||
|
||||
if err := api.client.Call(&res, "account_signTransaction", args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return res.Tx, nil
|
||||
}
|
||||
|
||||
func (api *ExternalSigner) SignTextWithPassphrase(account accounts.Account, passphrase string, text []byte) ([]byte, error) {
|
||||
return []byte{}, fmt.Errorf("passphrase-operations not supported on external signers")
|
||||
}
|
||||
|
||||
func (api *ExternalSigner) SignTxWithPassphrase(account accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
|
||||
return nil, fmt.Errorf("passphrase-operations not supported on external signers")
|
||||
}
|
||||
func (api *ExternalSigner) SignDataWithPassphrase(account accounts.Account, passphrase, mimeType string, data []byte) ([]byte, error) {
|
||||
return nil, fmt.Errorf("passphrase-operations not supported on external signers")
|
||||
}
|
||||
|
||||
func (api *ExternalSigner) listAccounts() ([]common.Address, error) {
|
||||
var res []common.Address
|
||||
if err := api.client.Call(&res, "account_list"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (api *ExternalSigner) pingVersion() (string, error) {
|
||||
var v string
|
||||
if err := api.client.Call(&v, "account_version"); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return v, nil
|
||||
}
|
8
vendor/github.com/ethereum/go-ethereum/accounts/hd.go
generated
vendored
8
vendor/github.com/ethereum/go-ethereum/accounts/hd.go
generated
vendored
@ -35,10 +35,10 @@ var DefaultRootDerivationPath = DerivationPath{0x80000000 + 44, 0x80000000 + 60,
|
||||
// at m/44'/60'/0'/0/1, etc.
|
||||
var DefaultBaseDerivationPath = DerivationPath{0x80000000 + 44, 0x80000000 + 60, 0x80000000 + 0, 0, 0}
|
||||
|
||||
// DefaultLedgerBaseDerivationPath is the base path from which custom derivation endpoints
|
||||
// are incremented. As such, the first account will be at m/44'/60'/0'/0, the second
|
||||
// at m/44'/60'/0'/1, etc.
|
||||
var DefaultLedgerBaseDerivationPath = DerivationPath{0x80000000 + 44, 0x80000000 + 60, 0x80000000 + 0, 0}
|
||||
// LegacyLedgerBaseDerivationPath is the legacy base path from which custom derivation
|
||||
// endpoints are incremented. As such, the first account will be at m/44'/60'/0'/0, the
|
||||
// second at m/44'/60'/0'/1, etc.
|
||||
var LegacyLedgerBaseDerivationPath = DerivationPath{0x80000000 + 44, 0x80000000 + 60, 0x80000000 + 0, 0}
|
||||
|
||||
// DerivationPath represents the computer friendly version of a hierarchical
|
||||
// deterministic wallet account derivaion path.
|
||||
|
356
vendor/github.com/ethereum/go-ethereum/accounts/keystore/passphrase.go
generated
vendored
Normal file
356
vendor/github.com/ethereum/go-ethereum/accounts/keystore/passphrase.go
generated
vendored
Normal file
@ -0,0 +1,356 @@
|
||||
// Copyright 2014 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
/*
|
||||
|
||||
This key store behaves as KeyStorePlain with the difference that
|
||||
the private key is encrypted and on disk uses another JSON encoding.
|
||||
|
||||
The crypto is documented at https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition
|
||||
|
||||
*/
|
||||
|
||||
package keystore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/ethereum/go-ethereum/accounts"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/common/math"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/pborman/uuid"
|
||||
"golang.org/x/crypto/pbkdf2"
|
||||
"golang.org/x/crypto/scrypt"
|
||||
)
|
||||
|
||||
const (
|
||||
keyHeaderKDF = "scrypt"
|
||||
|
||||
// StandardScryptN is the N parameter of Scrypt encryption algorithm, using 256MB
|
||||
// memory and taking approximately 1s CPU time on a modern processor.
|
||||
StandardScryptN = 1 << 18
|
||||
|
||||
// StandardScryptP is the P parameter of Scrypt encryption algorithm, using 256MB
|
||||
// memory and taking approximately 1s CPU time on a modern processor.
|
||||
StandardScryptP = 1
|
||||
|
||||
// LightScryptN is the N parameter of Scrypt encryption algorithm, using 4MB
|
||||
// memory and taking approximately 100ms CPU time on a modern processor.
|
||||
LightScryptN = 1 << 12
|
||||
|
||||
// LightScryptP is the P parameter of Scrypt encryption algorithm, using 4MB
|
||||
// memory and taking approximately 100ms CPU time on a modern processor.
|
||||
LightScryptP = 6
|
||||
|
||||
scryptR = 8
|
||||
scryptDKLen = 32
|
||||
)
|
||||
|
||||
type keyStorePassphrase struct {
|
||||
keysDirPath string
|
||||
scryptN int
|
||||
scryptP int
|
||||
// skipKeyFileVerification disables the security-feature which does
|
||||
// reads and decrypts any newly created keyfiles. This should be 'false' in all
|
||||
// cases except tests -- setting this to 'true' is not recommended.
|
||||
skipKeyFileVerification bool
|
||||
}
|
||||
|
||||
func (ks keyStorePassphrase) GetKey(addr common.Address, filename, auth string) (*Key, error) {
|
||||
// Load the key from the keystore and decrypt its contents
|
||||
keyjson, err := ioutil.ReadFile(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
key, err := DecryptKey(keyjson, auth)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Make sure we're really operating on the requested key (no swap attacks)
|
||||
if key.Address != addr {
|
||||
return nil, fmt.Errorf("key content mismatch: have account %x, want %x", key.Address, addr)
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// StoreKey generates a key, encrypts with 'auth' and stores in the given directory
|
||||
func StoreKey(dir, auth string, scryptN, scryptP int) (accounts.Account, error) {
|
||||
_, a, err := storeNewKey(&keyStorePassphrase{dir, scryptN, scryptP, false}, rand.Reader, auth)
|
||||
return a, err
|
||||
}
|
||||
|
||||
func (ks keyStorePassphrase) StoreKey(filename string, key *Key, auth string) error {
|
||||
keyjson, err := EncryptKey(key, auth, ks.scryptN, ks.scryptP)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Write into temporary file
|
||||
tmpName, err := writeTemporaryKeyFile(filename, keyjson)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ks.skipKeyFileVerification {
|
||||
// Verify that we can decrypt the file with the given password.
|
||||
_, err = ks.GetKey(key.Address, tmpName, auth)
|
||||
if err != nil {
|
||||
msg := "An error was encountered when saving and verifying the keystore file. \n" +
|
||||
"This indicates that the keystore is corrupted. \n" +
|
||||
"The corrupted file is stored at \n%v\n" +
|
||||
"Please file a ticket at:\n\n" +
|
||||
"https://github.com/ethereum/go-ethereum/issues." +
|
||||
"The error was : %s"
|
||||
return fmt.Errorf(msg, tmpName, err)
|
||||
}
|
||||
}
|
||||
return os.Rename(tmpName, filename)
|
||||
}
|
||||
|
||||
func (ks keyStorePassphrase) JoinPath(filename string) string {
|
||||
if filepath.IsAbs(filename) {
|
||||
return filename
|
||||
}
|
||||
return filepath.Join(ks.keysDirPath, filename)
|
||||
}
|
||||
|
||||
// Encryptdata encrypts the data given as 'data' with the password 'auth'.
|
||||
func EncryptDataV3(data, auth []byte, scryptN, scryptP int) (CryptoJSON, error) {
|
||||
|
||||
salt := make([]byte, 32)
|
||||
if _, err := io.ReadFull(rand.Reader, salt); err != nil {
|
||||
panic("reading from crypto/rand failed: " + err.Error())
|
||||
}
|
||||
derivedKey, err := scrypt.Key(auth, salt, scryptN, scryptR, scryptP, scryptDKLen)
|
||||
if err != nil {
|
||||
return CryptoJSON{}, err
|
||||
}
|
||||
encryptKey := derivedKey[:16]
|
||||
|
||||
iv := make([]byte, aes.BlockSize) // 16
|
||||
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
|
||||
panic("reading from crypto/rand failed: " + err.Error())
|
||||
}
|
||||
cipherText, err := aesCTRXOR(encryptKey, data, iv)
|
||||
if err != nil {
|
||||
return CryptoJSON{}, err
|
||||
}
|
||||
mac := crypto.Keccak256(derivedKey[16:32], cipherText)
|
||||
|
||||
scryptParamsJSON := make(map[string]interface{}, 5)
|
||||
scryptParamsJSON["n"] = scryptN
|
||||
scryptParamsJSON["r"] = scryptR
|
||||
scryptParamsJSON["p"] = scryptP
|
||||
scryptParamsJSON["dklen"] = scryptDKLen
|
||||
scryptParamsJSON["salt"] = hex.EncodeToString(salt)
|
||||
cipherParamsJSON := cipherparamsJSON{
|
||||
IV: hex.EncodeToString(iv),
|
||||
}
|
||||
|
||||
cryptoStruct := CryptoJSON{
|
||||
Cipher: "aes-128-ctr",
|
||||
CipherText: hex.EncodeToString(cipherText),
|
||||
CipherParams: cipherParamsJSON,
|
||||
KDF: keyHeaderKDF,
|
||||
KDFParams: scryptParamsJSON,
|
||||
MAC: hex.EncodeToString(mac),
|
||||
}
|
||||
return cryptoStruct, nil
|
||||
}
|
||||
|
||||
// EncryptKey encrypts a key using the specified scrypt parameters into a json
|
||||
// blob that can be decrypted later on.
|
||||
func EncryptKey(key *Key, auth string, scryptN, scryptP int) ([]byte, error) {
|
||||
keyBytes := math.PaddedBigBytes(key.PrivateKey.D, 32)
|
||||
cryptoStruct, err := EncryptDataV3(keyBytes, []byte(auth), scryptN, scryptP)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
encryptedKeyJSONV3 := encryptedKeyJSONV3{
|
||||
hex.EncodeToString(key.Address[:]),
|
||||
cryptoStruct,
|
||||
key.Id.String(),
|
||||
version,
|
||||
}
|
||||
return json.Marshal(encryptedKeyJSONV3)
|
||||
}
|
||||
|
||||
// DecryptKey decrypts a key from a json blob, returning the private key itself.
|
||||
func DecryptKey(keyjson []byte, auth string) (*Key, error) {
|
||||
// Parse the json into a simple map to fetch the key version
|
||||
m := make(map[string]interface{})
|
||||
if err := json.Unmarshal(keyjson, &m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Depending on the version try to parse one way or another
|
||||
var (
|
||||
keyBytes, keyId []byte
|
||||
err error
|
||||
)
|
||||
if version, ok := m["version"].(string); ok && version == "1" {
|
||||
k := new(encryptedKeyJSONV1)
|
||||
if err := json.Unmarshal(keyjson, k); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
keyBytes, keyId, err = decryptKeyV1(k, auth)
|
||||
} else {
|
||||
k := new(encryptedKeyJSONV3)
|
||||
if err := json.Unmarshal(keyjson, k); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
keyBytes, keyId, err = decryptKeyV3(k, auth)
|
||||
}
|
||||
// Handle any decryption errors and return the key
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
key := crypto.ToECDSAUnsafe(keyBytes)
|
||||
|
||||
return &Key{
|
||||
Id: uuid.UUID(keyId),
|
||||
Address: crypto.PubkeyToAddress(key.PublicKey),
|
||||
PrivateKey: key,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func DecryptDataV3(cryptoJson CryptoJSON, auth string) ([]byte, error) {
|
||||
if cryptoJson.Cipher != "aes-128-ctr" {
|
||||
return nil, fmt.Errorf("Cipher not supported: %v", cryptoJson.Cipher)
|
||||
}
|
||||
mac, err := hex.DecodeString(cryptoJson.MAC)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
iv, err := hex.DecodeString(cryptoJson.CipherParams.IV)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cipherText, err := hex.DecodeString(cryptoJson.CipherText)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
derivedKey, err := getKDFKey(cryptoJson, auth)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
calculatedMAC := crypto.Keccak256(derivedKey[16:32], cipherText)
|
||||
if !bytes.Equal(calculatedMAC, mac) {
|
||||
return nil, ErrDecrypt
|
||||
}
|
||||
|
||||
plainText, err := aesCTRXOR(derivedKey[:16], cipherText, iv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return plainText, err
|
||||
}
|
||||
|
||||
func decryptKeyV3(keyProtected *encryptedKeyJSONV3, auth string) (keyBytes []byte, keyId []byte, err error) {
|
||||
if keyProtected.Version != version {
|
||||
return nil, nil, fmt.Errorf("Version not supported: %v", keyProtected.Version)
|
||||
}
|
||||
keyId = uuid.Parse(keyProtected.Id)
|
||||
plainText, err := DecryptDataV3(keyProtected.Crypto, auth)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return plainText, keyId, err
|
||||
}
|
||||
|
||||
func decryptKeyV1(keyProtected *encryptedKeyJSONV1, auth string) (keyBytes []byte, keyId []byte, err error) {
|
||||
keyId = uuid.Parse(keyProtected.Id)
|
||||
mac, err := hex.DecodeString(keyProtected.Crypto.MAC)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
iv, err := hex.DecodeString(keyProtected.Crypto.CipherParams.IV)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
cipherText, err := hex.DecodeString(keyProtected.Crypto.CipherText)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
derivedKey, err := getKDFKey(keyProtected.Crypto, auth)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
calculatedMAC := crypto.Keccak256(derivedKey[16:32], cipherText)
|
||||
if !bytes.Equal(calculatedMAC, mac) {
|
||||
return nil, nil, ErrDecrypt
|
||||
}
|
||||
|
||||
plainText, err := aesCBCDecrypt(crypto.Keccak256(derivedKey[:16])[:16], cipherText, iv)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return plainText, keyId, err
|
||||
}
|
||||
|
||||
func getKDFKey(cryptoJSON CryptoJSON, auth string) ([]byte, error) {
|
||||
authArray := []byte(auth)
|
||||
salt, err := hex.DecodeString(cryptoJSON.KDFParams["salt"].(string))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dkLen := ensureInt(cryptoJSON.KDFParams["dklen"])
|
||||
|
||||
if cryptoJSON.KDF == keyHeaderKDF {
|
||||
n := ensureInt(cryptoJSON.KDFParams["n"])
|
||||
r := ensureInt(cryptoJSON.KDFParams["r"])
|
||||
p := ensureInt(cryptoJSON.KDFParams["p"])
|
||||
return scrypt.Key(authArray, salt, n, r, p, dkLen)
|
||||
|
||||
} else if cryptoJSON.KDF == "pbkdf2" {
|
||||
c := ensureInt(cryptoJSON.KDFParams["c"])
|
||||
prf := cryptoJSON.KDFParams["prf"].(string)
|
||||
if prf != "hmac-sha256" {
|
||||
return nil, fmt.Errorf("Unsupported PBKDF2 PRF: %s", prf)
|
||||
}
|
||||
key := pbkdf2.Key(authArray, salt, c, dkLen, sha256.New)
|
||||
return key, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("Unsupported KDF: %s", cryptoJSON.KDF)
|
||||
}
|
||||
|
||||
// TODO: can we do without this when unmarshalling dynamic JSON?
|
||||
// why do integers in KDF params end up as float64 and not int after
|
||||
// unmarshal?
|
||||
func ensureInt(x interface{}) int {
|
||||
res, ok := x.(int)
|
||||
if !ok {
|
||||
res = int(x.(float64))
|
||||
}
|
||||
return res
|
||||
}
|
148
vendor/github.com/ethereum/go-ethereum/accounts/keystore/wallet.go
generated
vendored
Normal file
148
vendor/github.com/ethereum/go-ethereum/accounts/keystore/wallet.go
generated
vendored
Normal file
@ -0,0 +1,148 @@
|
||||
// Copyright 2017 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package keystore
|
||||
|
||||
import (
|
||||
"math/big"
|
||||
|
||||
ethereum "github.com/ethereum/go-ethereum"
|
||||
"github.com/ethereum/go-ethereum/accounts"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
)
|
||||
|
||||
// keystoreWallet implements the accounts.Wallet interface for the original
|
||||
// keystore.
|
||||
type keystoreWallet struct {
|
||||
account accounts.Account // Single account contained in this wallet
|
||||
keystore *KeyStore // Keystore where the account originates from
|
||||
}
|
||||
|
||||
// URL implements accounts.Wallet, returning the URL of the account within.
|
||||
func (w *keystoreWallet) URL() accounts.URL {
|
||||
return w.account.URL
|
||||
}
|
||||
|
||||
// Status implements accounts.Wallet, returning whether the account held by the
|
||||
// keystore wallet is unlocked or not.
|
||||
func (w *keystoreWallet) Status() (string, error) {
|
||||
w.keystore.mu.RLock()
|
||||
defer w.keystore.mu.RUnlock()
|
||||
|
||||
if _, ok := w.keystore.unlocked[w.account.Address]; ok {
|
||||
return "Unlocked", nil
|
||||
}
|
||||
return "Locked", nil
|
||||
}
|
||||
|
||||
// Open implements accounts.Wallet, but is a noop for plain wallets since there
|
||||
// is no connection or decryption step necessary to access the list of accounts.
|
||||
func (w *keystoreWallet) Open(passphrase string) error { return nil }
|
||||
|
||||
// Close implements accounts.Wallet, but is a noop for plain wallets since there
|
||||
// is no meaningful open operation.
|
||||
func (w *keystoreWallet) Close() error { return nil }
|
||||
|
||||
// Accounts implements accounts.Wallet, returning an account list consisting of
|
||||
// a single account that the plain kestore wallet contains.
|
||||
func (w *keystoreWallet) Accounts() []accounts.Account {
|
||||
return []accounts.Account{w.account}
|
||||
}
|
||||
|
||||
// Contains implements accounts.Wallet, returning whether a particular account is
|
||||
// or is not wrapped by this wallet instance.
|
||||
func (w *keystoreWallet) Contains(account accounts.Account) bool {
|
||||
return account.Address == w.account.Address && (account.URL == (accounts.URL{}) || account.URL == w.account.URL)
|
||||
}
|
||||
|
||||
// Derive implements accounts.Wallet, but is a noop for plain wallets since there
|
||||
// is no notion of hierarchical account derivation for plain keystore accounts.
|
||||
func (w *keystoreWallet) Derive(path accounts.DerivationPath, pin bool) (accounts.Account, error) {
|
||||
return accounts.Account{}, accounts.ErrNotSupported
|
||||
}
|
||||
|
||||
// SelfDerive implements accounts.Wallet, but is a noop for plain wallets since
|
||||
// there is no notion of hierarchical account derivation for plain keystore accounts.
|
||||
func (w *keystoreWallet) SelfDerive(bases []accounts.DerivationPath, chain ethereum.ChainStateReader) {
|
||||
}
|
||||
|
||||
// signHash attempts to sign the given hash with
|
||||
// the given account. If the wallet does not wrap this particular account, an
|
||||
// error is returned to avoid account leakage (even though in theory we may be
|
||||
// able to sign via our shared keystore backend).
|
||||
func (w *keystoreWallet) signHash(account accounts.Account, hash []byte) ([]byte, error) {
|
||||
// Make sure the requested account is contained within
|
||||
if !w.Contains(account) {
|
||||
return nil, accounts.ErrUnknownAccount
|
||||
}
|
||||
// Account seems valid, request the keystore to sign
|
||||
return w.keystore.SignHash(account, hash)
|
||||
}
|
||||
|
||||
// SignData signs keccak256(data). The mimetype parameter describes the type of data being signed
|
||||
func (w *keystoreWallet) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) {
|
||||
return w.signHash(account, crypto.Keccak256(data))
|
||||
}
|
||||
|
||||
// SignDataWithPassphrase signs keccak256(data). The mimetype parameter describes the type of data being signed
|
||||
func (w *keystoreWallet) SignDataWithPassphrase(account accounts.Account, passphrase, mimeType string, data []byte) ([]byte, error) {
|
||||
// Make sure the requested account is contained within
|
||||
if !w.Contains(account) {
|
||||
return nil, accounts.ErrUnknownAccount
|
||||
}
|
||||
// Account seems valid, request the keystore to sign
|
||||
return w.keystore.SignHashWithPassphrase(account, passphrase, crypto.Keccak256(data))
|
||||
}
|
||||
|
||||
func (w *keystoreWallet) SignText(account accounts.Account, text []byte) ([]byte, error) {
|
||||
return w.signHash(account, accounts.TextHash(text))
|
||||
}
|
||||
|
||||
// SignTextWithPassphrase implements accounts.Wallet, attempting to sign the
|
||||
// given hash with the given account using passphrase as extra authentication.
|
||||
func (w *keystoreWallet) SignTextWithPassphrase(account accounts.Account, passphrase string, text []byte) ([]byte, error) {
|
||||
// Make sure the requested account is contained within
|
||||
if !w.Contains(account) {
|
||||
return nil, accounts.ErrUnknownAccount
|
||||
}
|
||||
// Account seems valid, request the keystore to sign
|
||||
return w.keystore.SignHashWithPassphrase(account, passphrase, accounts.TextHash(text))
|
||||
}
|
||||
|
||||
// SignTx implements accounts.Wallet, attempting to sign the given transaction
|
||||
// with the given account. If the wallet does not wrap this particular account,
|
||||
// an error is returned to avoid account leakage (even though in theory we may
|
||||
// be able to sign via our shared keystore backend).
|
||||
func (w *keystoreWallet) SignTx(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
|
||||
// Make sure the requested account is contained within
|
||||
if !w.Contains(account) {
|
||||
return nil, accounts.ErrUnknownAccount
|
||||
}
|
||||
// Account seems valid, request the keystore to sign
|
||||
return w.keystore.SignTx(account, tx, chainID)
|
||||
}
|
||||
|
||||
// SignTxWithPassphrase implements accounts.Wallet, attempting to sign the given
|
||||
// transaction with the given account using passphrase as extra authentication.
|
||||
func (w *keystoreWallet) SignTxWithPassphrase(account accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
|
||||
// Make sure the requested account is contained within
|
||||
if !w.Contains(account) {
|
||||
return nil, accounts.ErrUnknownAccount
|
||||
}
|
||||
// Account seems valid, request the keystore to sign
|
||||
return w.keystore.SignTxWithPassphrase(account, passphrase, tx, chainID)
|
||||
}
|
108
vendor/github.com/ethereum/go-ethereum/accounts/keystore/watch.go
generated
vendored
Normal file
108
vendor/github.com/ethereum/go-ethereum/accounts/keystore/watch.go
generated
vendored
Normal file
@ -0,0 +1,108 @@
|
||||
// Copyright 2016 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
// +build darwin,!ios,cgo freebsd linux,!arm64 netbsd solaris
|
||||
|
||||
package keystore
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/ethereum/go-ethereum/log"
|
||||
"github.com/rjeczalik/notify"
|
||||
)
|
||||
|
||||
type watcher struct {
|
||||
ac *accountCache
|
||||
starting bool
|
||||
running bool
|
||||
ev chan notify.EventInfo
|
||||
quit chan struct{}
|
||||
}
|
||||
|
||||
func newWatcher(ac *accountCache) *watcher {
|
||||
return &watcher{
|
||||
ac: ac,
|
||||
ev: make(chan notify.EventInfo, 10),
|
||||
quit: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
// starts the watcher loop in the background.
|
||||
// Start a watcher in the background if that's not already in progress.
|
||||
// The caller must hold w.ac.mu.
|
||||
func (w *watcher) start() {
|
||||
if w.starting || w.running {
|
||||
return
|
||||
}
|
||||
w.starting = true
|
||||
go w.loop()
|
||||
}
|
||||
|
||||
func (w *watcher) close() {
|
||||
close(w.quit)
|
||||
}
|
||||
|
||||
func (w *watcher) loop() {
|
||||
defer func() {
|
||||
w.ac.mu.Lock()
|
||||
w.running = false
|
||||
w.starting = false
|
||||
w.ac.mu.Unlock()
|
||||
}()
|
||||
logger := log.New("path", w.ac.keydir)
|
||||
|
||||
if err := notify.Watch(w.ac.keydir, w.ev, notify.All); err != nil {
|
||||
logger.Trace("Failed to watch keystore folder", "err", err)
|
||||
return
|
||||
}
|
||||
defer notify.Stop(w.ev)
|
||||
logger.Trace("Started watching keystore folder")
|
||||
defer logger.Trace("Stopped watching keystore folder")
|
||||
|
||||
w.ac.mu.Lock()
|
||||
w.running = true
|
||||
w.ac.mu.Unlock()
|
||||
|
||||
// Wait for file system events and reload.
|
||||
// When an event occurs, the reload call is delayed a bit so that
|
||||
// multiple events arriving quickly only cause a single reload.
|
||||
var (
|
||||
debounceDuration = 500 * time.Millisecond
|
||||
rescanTriggered = false
|
||||
debounce = time.NewTimer(0)
|
||||
)
|
||||
// Ignore initial trigger
|
||||
if !debounce.Stop() {
|
||||
<-debounce.C
|
||||
}
|
||||
defer debounce.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-w.quit:
|
||||
return
|
||||
case <-w.ev:
|
||||
// Trigger the scan (with delay), if not already triggered
|
||||
if !rescanTriggered {
|
||||
debounce.Reset(debounceDuration)
|
||||
rescanTriggered = true
|
||||
}
|
||||
case <-debounce.C:
|
||||
w.ac.scanAccounts()
|
||||
rescanTriggered = false
|
||||
}
|
||||
}
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
// Copyright 2017 The go-ethereum Authors
|
||||
// Copyright 2016 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
@ -14,28 +14,15 @@
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package storage
|
||||
// +build darwin,!cgo ios linux,arm64 windows !darwin,!freebsd,!linux,!netbsd,!solaris
|
||||
|
||||
import (
|
||||
"hash"
|
||||
)
|
||||
// This is the fallback implementation of directory watching.
|
||||
// It is used on unsupported platforms.
|
||||
|
||||
const (
|
||||
BMTHash = "BMT"
|
||||
SHA3Hash = "SHA3" // http://golang.org/pkg/hash/#Hash
|
||||
DefaultHash = BMTHash
|
||||
)
|
||||
package keystore
|
||||
|
||||
type SwarmHash interface {
|
||||
hash.Hash
|
||||
ResetWithLength([]byte)
|
||||
}
|
||||
type watcher struct{ running bool }
|
||||
|
||||
type HashWithLength struct {
|
||||
hash.Hash
|
||||
}
|
||||
|
||||
func (h *HashWithLength) ResetWithLength(length []byte) {
|
||||
h.Reset()
|
||||
h.Write(length)
|
||||
}
|
||||
func newWatcher(*accountCache) *watcher { return new(watcher) }
|
||||
func (*watcher) start() {}
|
||||
func (*watcher) close() {}
|
20
vendor/github.com/ethereum/go-ethereum/accounts/scwallet/README.md
generated
vendored
20
vendor/github.com/ethereum/go-ethereum/accounts/scwallet/README.md
generated
vendored
@ -25,13 +25,13 @@
|
||||
Start `geth` with the `console` command. You will notice the following warning:
|
||||
|
||||
```
|
||||
WARN [04-09|16:58:38.898] Failed to open wallet url=pcsc://044def09 err="smartcard: pairing password needed"
|
||||
WARN [04-09|16:58:38.898] Failed to open wallet url=keycard://044def09 err="smartcard: pairing password needed"
|
||||
```
|
||||
|
||||
Write down the URL (`pcsc://044def09` in this example). Then ask `geth` to open the wallet:
|
||||
Write down the URL (`keycard://044def09` in this example). Then ask `geth` to open the wallet:
|
||||
|
||||
```
|
||||
> personal.openWallet("pcsc://044def09")
|
||||
> personal.openWallet("keycard://044def09")
|
||||
Please enter the pairing password:
|
||||
```
|
||||
|
||||
@ -42,12 +42,12 @@
|
||||
|
||||
```
|
||||
> personal
|
||||
WARN [04-09|17:02:07.330] Smartcard wallet account derivation failed url=pcsc://044def09 err="Unexpected response status Cla=0x80, Ins=0xd1, Sw=0x6985"
|
||||
WARN [04-09|17:02:07.330] Smartcard wallet account derivation failed url=keycard://044def09 err="Unexpected response status Cla=0x80, Ins=0xd1, Sw=0x6985"
|
||||
{
|
||||
listAccounts: [],
|
||||
listWallets: [{
|
||||
status: "Empty, waiting for initialization",
|
||||
url: "pcsc://044def09"
|
||||
url: "keycard://044def09"
|
||||
}],
|
||||
...
|
||||
}
|
||||
@ -56,7 +56,7 @@
|
||||
So the communication with the card is working, but there is no key associated with this wallet. Let's create it:
|
||||
|
||||
```
|
||||
> personal.initializeWallet("pcsc://044def09")
|
||||
> personal.initializeWallet("keycard://044def09")
|
||||
"tilt ... impact"
|
||||
```
|
||||
|
||||
@ -67,10 +67,10 @@
|
||||
[{
|
||||
accounts: [{
|
||||
address: "0x678b7cd55c61917defb23546a41803c5bfefbc7a",
|
||||
url: "pcsc://044d/m/44'/60'/0'/0/0"
|
||||
url: "keycard://044d/m/44'/60'/0'/0/0"
|
||||
}],
|
||||
status: "Online",
|
||||
url: "pcsc://044def09"
|
||||
url: "keycard://044def09"
|
||||
}]
|
||||
```
|
||||
|
||||
@ -84,14 +84,14 @@
|
||||
```
|
||||
listWallets: [{
|
||||
status: "Online, can derive public keys",
|
||||
url: "pcsc://a4d73015"
|
||||
url: "keycard://a4d73015"
|
||||
}]
|
||||
```
|
||||
|
||||
3. Open the wallet, you will be prompted for your pairing password, then PIN:
|
||||
|
||||
```
|
||||
personal.openWallet("pcsc://a4d73015")
|
||||
personal.openWallet("keycard://a4d73015")
|
||||
```
|
||||
|
||||
4. Check that creation was successful by typing e.g. `personal`. Then use it like a regular wallet.
|
||||
|
6
vendor/github.com/ethereum/go-ethereum/accounts/scwallet/hub.go
generated
vendored
6
vendor/github.com/ethereum/go-ethereum/accounts/scwallet/hub.go
generated
vendored
@ -49,7 +49,7 @@ import (
|
||||
)
|
||||
|
||||
// Scheme is the URI prefix for smartcard wallets.
|
||||
const Scheme = "pcsc"
|
||||
const Scheme = "keycard"
|
||||
|
||||
// refreshCycle is the maximum time between wallet refreshes (if USB hotplug
|
||||
// notifications don't work).
|
||||
@ -152,8 +152,8 @@ func (hub *Hub) setPairing(wallet *Wallet, pairing *smartcardPairing) error {
|
||||
}
|
||||
|
||||
// NewHub creates a new hardware wallet manager for smartcards.
|
||||
func NewHub(scheme string, datadir string) (*Hub, error) {
|
||||
context, err := pcsc.EstablishContext(pcsc.ScopeSystem)
|
||||
func NewHub(daemonPath string, scheme string, datadir string) (*Hub, error) {
|
||||
context, err := pcsc.EstablishContext(daemonPath, pcsc.ScopeSystem)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
178
vendor/github.com/ethereum/go-ethereum/accounts/scwallet/wallet.go
generated
vendored
178
vendor/github.com/ethereum/go-ethereum/accounts/scwallet/wallet.go
generated
vendored
@ -27,6 +27,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
@ -37,7 +38,6 @@ import (
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/ethereum/go-ethereum/crypto/secp256k1"
|
||||
"github.com/ethereum/go-ethereum/log"
|
||||
pcsc "github.com/gballet/go-libpcsclite"
|
||||
"github.com/status-im/keycard-go/derivationpath"
|
||||
@ -119,11 +119,11 @@ type Wallet struct {
|
||||
session *Session // The secure communication session with the card
|
||||
log log.Logger // Contextual logger to tag the base with its id
|
||||
|
||||
deriveNextPath accounts.DerivationPath // Next derivation path for account auto-discovery
|
||||
deriveNextAddr common.Address // Next derived account address for auto-discovery
|
||||
deriveChain ethereum.ChainStateReader // Blockchain state reader to discover used account with
|
||||
deriveReq chan chan struct{} // Channel to request a self-derivation on
|
||||
deriveQuit chan chan error // Channel to terminate the self-deriver with
|
||||
deriveNextPaths []accounts.DerivationPath // Next derivation paths for account auto-discovery (multiple bases supported)
|
||||
deriveNextAddrs []common.Address // Next derived account addresses for auto-discovery (multiple bases supported)
|
||||
deriveChain ethereum.ChainStateReader // Blockchain state reader to discover used account with
|
||||
deriveReq chan chan struct{} // Channel to request a self-derivation on
|
||||
deriveQuit chan chan error // Channel to terminate the self-deriver with
|
||||
}
|
||||
|
||||
// NewWallet constructs and returns a new Wallet instance.
|
||||
@ -311,8 +311,10 @@ func (w *Wallet) Status() (string, error) {
|
||||
return fmt.Sprintf("Failed: %v", err), err
|
||||
}
|
||||
switch {
|
||||
case !w.session.verified && status.PinRetryCount == 0 && status.PukRetryCount == 0:
|
||||
return fmt.Sprintf("Bricked, waiting for full wipe"), nil
|
||||
case !w.session.verified && status.PinRetryCount == 0:
|
||||
return fmt.Sprintf("Blocked, waiting for PUK and new PIN"), nil
|
||||
return fmt.Sprintf("Blocked, waiting for PUK (%d attempts left) and new PIN", status.PukRetryCount), nil
|
||||
case !w.session.verified:
|
||||
return fmt.Sprintf("Locked, waiting for PIN (%d attempts left)", status.PinRetryCount), nil
|
||||
case !status.Initialized:
|
||||
@ -378,10 +380,18 @@ func (w *Wallet) Open(passphrase string) error {
|
||||
case passphrase == "":
|
||||
return ErrPINUnblockNeeded
|
||||
case status.PinRetryCount > 0:
|
||||
if !regexp.MustCompile(`^[0-9]{6,}$`).MatchString(passphrase) {
|
||||
w.log.Error("PIN needs to be at least 6 digits")
|
||||
return ErrPINNeeded
|
||||
}
|
||||
if err := w.session.verifyPin([]byte(passphrase)); err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
if !regexp.MustCompile(`^[0-9]{12,}$`).MatchString(passphrase) {
|
||||
w.log.Error("PUK needs to be at least 12 digits")
|
||||
return ErrPINUnblockNeeded
|
||||
}
|
||||
if err := w.session.unblockPin([]byte(passphrase)); err != nil {
|
||||
return err
|
||||
}
|
||||
@ -390,7 +400,7 @@ func (w *Wallet) Open(passphrase string) error {
|
||||
w.deriveReq = make(chan chan struct{})
|
||||
w.deriveQuit = make(chan chan error)
|
||||
|
||||
go w.selfDerive(0)
|
||||
go w.selfDerive()
|
||||
|
||||
// Notify anyone listening for wallet events that a new device is accessible
|
||||
go w.Hub.updateFeed.Send(accounts.WalletEvent{Wallet: w, Kind: accounts.WalletOpened})
|
||||
@ -426,9 +436,8 @@ func (w *Wallet) Close() error {
|
||||
}
|
||||
|
||||
// selfDerive is an account derivation loop that upon request attempts to find
|
||||
// new non-zero accounts. maxEmpty specifies the number of empty accounts that
|
||||
// should be derived once an initial empty account has been found.
|
||||
func (w *Wallet) selfDerive(maxEmpty int) {
|
||||
// new non-zero accounts.
|
||||
func (w *Wallet) selfDerive() {
|
||||
w.log.Debug("Smart card wallet self-derivation started")
|
||||
defer w.log.Debug("Smart card wallet self-derivation stopped")
|
||||
|
||||
@ -461,56 +470,59 @@ func (w *Wallet) selfDerive(maxEmpty int) {
|
||||
paths []accounts.DerivationPath
|
||||
nextAcc accounts.Account
|
||||
|
||||
nextAddr = w.deriveNextAddr
|
||||
nextPath = w.deriveNextPath
|
||||
nextPaths = append([]accounts.DerivationPath{}, w.deriveNextPaths...)
|
||||
nextAddrs = append([]common.Address{}, w.deriveNextAddrs...)
|
||||
|
||||
context = context.Background()
|
||||
)
|
||||
for empty, emptyCount := false, maxEmpty+1; !empty || emptyCount > 0; {
|
||||
// Retrieve the next derived Ethereum account
|
||||
if nextAddr == (common.Address{}) {
|
||||
if nextAcc, err = w.session.derive(nextPath); err != nil {
|
||||
w.log.Warn("Smartcard wallet account derivation failed", "err", err)
|
||||
for i := 0; i < len(nextAddrs); i++ {
|
||||
for empty := false; !empty; {
|
||||
// Retrieve the next derived Ethereum account
|
||||
if nextAddrs[i] == (common.Address{}) {
|
||||
if nextAcc, err = w.session.derive(nextPaths[i]); err != nil {
|
||||
w.log.Warn("Smartcard wallet account derivation failed", "err", err)
|
||||
break
|
||||
}
|
||||
nextAddrs[i] = nextAcc.Address
|
||||
}
|
||||
// Check the account's status against the current chain state
|
||||
var (
|
||||
balance *big.Int
|
||||
nonce uint64
|
||||
)
|
||||
balance, err = w.deriveChain.BalanceAt(context, nextAddrs[i], nil)
|
||||
if err != nil {
|
||||
w.log.Warn("Smartcard wallet balance retrieval failed", "err", err)
|
||||
break
|
||||
}
|
||||
nextAddr = nextAcc.Address
|
||||
}
|
||||
// Check the account's status against the current chain state
|
||||
var (
|
||||
balance *big.Int
|
||||
nonce uint64
|
||||
)
|
||||
balance, err = w.deriveChain.BalanceAt(context, nextAddr, nil)
|
||||
if err != nil {
|
||||
w.log.Warn("Smartcard wallet balance retrieval failed", "err", err)
|
||||
break
|
||||
}
|
||||
nonce, err = w.deriveChain.NonceAt(context, nextAddr, nil)
|
||||
if err != nil {
|
||||
w.log.Warn("Smartcard wallet nonce retrieval failed", "err", err)
|
||||
break
|
||||
}
|
||||
// If the next account is empty and no more empty accounts are
|
||||
// allowed, stop self-derivation. Add the current one nonetheless.
|
||||
if balance.Sign() == 0 && nonce == 0 {
|
||||
empty = true
|
||||
emptyCount--
|
||||
}
|
||||
// We've just self-derived a new account, start tracking it locally
|
||||
path := make(accounts.DerivationPath, len(nextPath))
|
||||
copy(path[:], nextPath[:])
|
||||
paths = append(paths, path)
|
||||
nonce, err = w.deriveChain.NonceAt(context, nextAddrs[i], nil)
|
||||
if err != nil {
|
||||
w.log.Warn("Smartcard wallet nonce retrieval failed", "err", err)
|
||||
break
|
||||
}
|
||||
// If the next account is empty, stop self-derivation, but add for the last base path
|
||||
if balance.Sign() == 0 && nonce == 0 {
|
||||
empty = true
|
||||
if i < len(nextAddrs)-1 {
|
||||
break
|
||||
}
|
||||
}
|
||||
// We've just self-derived a new account, start tracking it locally
|
||||
path := make(accounts.DerivationPath, len(nextPaths[i]))
|
||||
copy(path[:], nextPaths[i][:])
|
||||
paths = append(paths, path)
|
||||
|
||||
// Display a log message to the user for new (or previously empty accounts)
|
||||
if _, known := pairing.Accounts[nextAddr]; !known || !empty || nextAddr != w.deriveNextAddr {
|
||||
w.log.Info("Smartcard wallet discovered new account", "address", nextAddr, "path", path, "balance", balance, "nonce", nonce)
|
||||
}
|
||||
pairing.Accounts[nextAddr] = path
|
||||
// Display a log message to the user for new (or previously empty accounts)
|
||||
if _, known := pairing.Accounts[nextAddrs[i]]; !known || !empty || nextAddrs[i] != w.deriveNextAddrs[i] {
|
||||
w.log.Info("Smartcard wallet discovered new account", "address", nextAddrs[i], "path", path, "balance", balance, "nonce", nonce)
|
||||
}
|
||||
pairing.Accounts[nextAddrs[i]] = path
|
||||
|
||||
// Fetch the next potential account
|
||||
if !empty || emptyCount > 0 {
|
||||
nextAddr = common.Address{}
|
||||
nextPath[len(nextPath)-1]++
|
||||
// Fetch the next potential account
|
||||
if !empty {
|
||||
nextAddrs[i] = common.Address{}
|
||||
nextPaths[i][len(nextPaths[i])-1]++
|
||||
}
|
||||
}
|
||||
}
|
||||
// If there are new accounts, write them out
|
||||
@ -518,8 +530,8 @@ func (w *Wallet) selfDerive(maxEmpty int) {
|
||||
err = w.Hub.setPairing(w, pairing)
|
||||
}
|
||||
// Shift the self-derivation forward
|
||||
w.deriveNextAddr = nextAddr
|
||||
w.deriveNextPath = nextPath
|
||||
w.deriveNextAddrs = nextAddrs
|
||||
w.deriveNextPaths = nextPaths
|
||||
|
||||
// Self derivation complete, release device lock
|
||||
w.lock.Unlock()
|
||||
@ -592,7 +604,7 @@ func (w *Wallet) Contains(account accounts.Account) bool {
|
||||
|
||||
// Initialize installs a keypair generated from the provided key into the wallet.
|
||||
func (w *Wallet) Initialize(seed []byte) error {
|
||||
go w.selfDerive(0)
|
||||
go w.selfDerive()
|
||||
// DO NOT lock at this stage, as the initialize
|
||||
// function relies on Status()
|
||||
return w.session.initialize(seed)
|
||||
@ -629,16 +641,22 @@ func (w *Wallet) Derive(path accounts.DerivationPath, pin bool) (accounts.Accoun
|
||||
// opposed to decending into a child path to allow discovering accounts starting
|
||||
// from non zero components.
|
||||
//
|
||||
// Some hardware wallets switched derivation paths through their evolution, so
|
||||
// this method supports providing multiple bases to discover old user accounts
|
||||
// too. Only the last base will be used to derive the next empty account.
|
||||
//
|
||||
// You can disable automatic account discovery by calling SelfDerive with a nil
|
||||
// chain state reader.
|
||||
func (w *Wallet) SelfDerive(base accounts.DerivationPath, chain ethereum.ChainStateReader) {
|
||||
func (w *Wallet) SelfDerive(bases []accounts.DerivationPath, chain ethereum.ChainStateReader) {
|
||||
w.lock.Lock()
|
||||
defer w.lock.Unlock()
|
||||
|
||||
w.deriveNextPath = make(accounts.DerivationPath, len(base))
|
||||
copy(w.deriveNextPath[:], base[:])
|
||||
|
||||
w.deriveNextAddr = common.Address{}
|
||||
w.deriveNextPaths = make([]accounts.DerivationPath, len(bases))
|
||||
for i, base := range bases {
|
||||
w.deriveNextPaths[i] = make(accounts.DerivationPath, len(base))
|
||||
copy(w.deriveNextPaths[i][:], base[:])
|
||||
}
|
||||
w.deriveNextAddrs = make([]common.Address, len(bases))
|
||||
w.deriveChain = chain
|
||||
}
|
||||
|
||||
@ -964,12 +982,10 @@ func (s *Session) derive(path accounts.DerivationPath) (accounts.Account, error)
|
||||
copy(sig[32-len(rbytes):32], rbytes)
|
||||
copy(sig[64-len(sbytes):64], sbytes)
|
||||
|
||||
pubkey, err := determinePublicKey(sig, sigdata.PublicKey)
|
||||
if err != nil {
|
||||
if err := confirmPublicKey(sig, sigdata.PublicKey); err != nil {
|
||||
return accounts.Account{}, err
|
||||
}
|
||||
|
||||
pub, err := crypto.UnmarshalPubkey(pubkey)
|
||||
pub, err := crypto.UnmarshalPubkey(sigdata.PublicKey)
|
||||
if err != nil {
|
||||
return accounts.Account{}, err
|
||||
}
|
||||
@ -1039,36 +1055,28 @@ func (s *Session) sign(path accounts.DerivationPath, hash []byte) ([]byte, error
|
||||
return sig, nil
|
||||
}
|
||||
|
||||
// determinePublicKey uses a signature and the X component of a public key to
|
||||
// recover the entire public key.
|
||||
func determinePublicKey(sig, pubkeyX []byte) ([]byte, error) {
|
||||
for v := 0; v < 2; v++ {
|
||||
sig[64] = byte(v)
|
||||
pubkey, err := crypto.Ecrecover(DerivationSignatureHash[:], sig)
|
||||
if err == nil {
|
||||
if bytes.Equal(pubkey, pubkeyX) {
|
||||
return pubkey, nil
|
||||
}
|
||||
} else if v == 1 || err != secp256k1.ErrRecoverFailed {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nil, ErrPubkeyMismatch
|
||||
// confirmPublicKey confirms that the given signature belongs to the specified key.
|
||||
func confirmPublicKey(sig, pubkey []byte) error {
|
||||
_, err := makeRecoverableSignature(DerivationSignatureHash[:], sig, pubkey)
|
||||
return err
|
||||
}
|
||||
|
||||
// makeRecoverableSignature uses a signature and an expected public key to
|
||||
// recover the v value and produce a recoverable signature.
|
||||
func makeRecoverableSignature(hash, sig, expectedPubkey []byte) ([]byte, error) {
|
||||
var libraryError error
|
||||
for v := 0; v < 2; v++ {
|
||||
sig[64] = byte(v)
|
||||
pubkey, err := crypto.Ecrecover(hash, sig)
|
||||
if err == nil {
|
||||
if pubkey, err := crypto.Ecrecover(hash, sig); err == nil {
|
||||
if bytes.Equal(pubkey, expectedPubkey) {
|
||||
return sig, nil
|
||||
}
|
||||
} else if v == 1 || err != secp256k1.ErrRecoverFailed {
|
||||
return nil, err
|
||||
} else {
|
||||
libraryError = err
|
||||
}
|
||||
}
|
||||
if libraryError != nil {
|
||||
return nil, libraryError
|
||||
}
|
||||
return nil, ErrPubkeyMismatch
|
||||
}
|
||||
|
279
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/hub.go
generated
vendored
Normal file
279
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/hub.go
generated
vendored
Normal file
@ -0,0 +1,279 @@
|
||||
// Copyright 2017 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package usbwallet
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"runtime"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/ethereum/go-ethereum/accounts"
|
||||
"github.com/ethereum/go-ethereum/event"
|
||||
"github.com/ethereum/go-ethereum/log"
|
||||
"github.com/karalabe/usb"
|
||||
)
|
||||
|
||||
// LedgerScheme is the protocol scheme prefixing account and wallet URLs.
|
||||
const LedgerScheme = "ledger"
|
||||
|
||||
// TrezorScheme is the protocol scheme prefixing account and wallet URLs.
|
||||
const TrezorScheme = "trezor"
|
||||
|
||||
// refreshCycle is the maximum time between wallet refreshes (if USB hotplug
|
||||
// notifications don't work).
|
||||
const refreshCycle = time.Second
|
||||
|
||||
// refreshThrottling is the minimum time between wallet refreshes to avoid USB
|
||||
// trashing.
|
||||
const refreshThrottling = 500 * time.Millisecond
|
||||
|
||||
// Hub is a accounts.Backend that can find and handle generic USB hardware wallets.
|
||||
type Hub struct {
|
||||
scheme string // Protocol scheme prefixing account and wallet URLs.
|
||||
vendorID uint16 // USB vendor identifier used for device discovery
|
||||
productIDs []uint16 // USB product identifiers used for device discovery
|
||||
usageID uint16 // USB usage page identifier used for macOS device discovery
|
||||
endpointID int // USB endpoint identifier used for non-macOS device discovery
|
||||
makeDriver func(log.Logger) driver // Factory method to construct a vendor specific driver
|
||||
|
||||
refreshed time.Time // Time instance when the list of wallets was last refreshed
|
||||
wallets []accounts.Wallet // List of USB wallet devices currently tracking
|
||||
updateFeed event.Feed // Event feed to notify wallet additions/removals
|
||||
updateScope event.SubscriptionScope // Subscription scope tracking current live listeners
|
||||
updating bool // Whether the event notification loop is running
|
||||
|
||||
quit chan chan error
|
||||
|
||||
stateLock sync.RWMutex // Protects the internals of the hub from racey access
|
||||
|
||||
// TODO(karalabe): remove if hotplug lands on Windows
|
||||
commsPend int // Number of operations blocking enumeration
|
||||
commsLock sync.Mutex // Lock protecting the pending counter and enumeration
|
||||
enumFails uint32 // Number of times enumeration has failed
|
||||
}
|
||||
|
||||
// NewLedgerHub creates a new hardware wallet manager for Ledger devices.
|
||||
func NewLedgerHub() (*Hub, error) {
|
||||
return newHub(LedgerScheme, 0x2c97, []uint16{
|
||||
// Original product IDs
|
||||
0x0000, /* Ledger Blue */
|
||||
0x0001, /* Ledger Nano S */
|
||||
0x0004, /* Ledger Nano X */
|
||||
|
||||
// Upcoming product IDs: https://www.ledger.com/2019/05/17/windows-10-update-sunsetting-u2f-tunnel-transport-for-ledger-devices/
|
||||
0x0015, /* HID + U2F + WebUSB Ledger Blue */
|
||||
0x1015, /* HID + U2F + WebUSB Ledger Nano S */
|
||||
0x4015, /* HID + U2F + WebUSB Ledger Nano X */
|
||||
0x0011, /* HID + WebUSB Ledger Blue */
|
||||
0x1011, /* HID + WebUSB Ledger Nano S */
|
||||
0x4011, /* HID + WebUSB Ledger Nano X */
|
||||
}, 0xffa0, 0, newLedgerDriver)
|
||||
}
|
||||
|
||||
// NewTrezorHubWithHID creates a new hardware wallet manager for Trezor devices.
|
||||
func NewTrezorHubWithHID() (*Hub, error) {
|
||||
return newHub(TrezorScheme, 0x534c, []uint16{0x0001 /* Trezor HID */}, 0xff00, 0, newTrezorDriver)
|
||||
}
|
||||
|
||||
// NewTrezorHubWithWebUSB creates a new hardware wallet manager for Trezor devices with
|
||||
// firmware version > 1.8.0
|
||||
func NewTrezorHubWithWebUSB() (*Hub, error) {
|
||||
return newHub(TrezorScheme, 0x1209, []uint16{0x53c1 /* Trezor WebUSB */}, 0xffff /* No usage id on webusb, don't match unset (0) */, 0, newTrezorDriver)
|
||||
}
|
||||
|
||||
// newHub creates a new hardware wallet manager for generic USB devices.
|
||||
func newHub(scheme string, vendorID uint16, productIDs []uint16, usageID uint16, endpointID int, makeDriver func(log.Logger) driver) (*Hub, error) {
|
||||
if !usb.Supported() {
|
||||
return nil, errors.New("unsupported platform")
|
||||
}
|
||||
hub := &Hub{
|
||||
scheme: scheme,
|
||||
vendorID: vendorID,
|
||||
productIDs: productIDs,
|
||||
usageID: usageID,
|
||||
endpointID: endpointID,
|
||||
makeDriver: makeDriver,
|
||||
quit: make(chan chan error),
|
||||
}
|
||||
hub.refreshWallets()
|
||||
return hub, nil
|
||||
}
|
||||
|
||||
// Wallets implements accounts.Backend, returning all the currently tracked USB
|
||||
// devices that appear to be hardware wallets.
|
||||
func (hub *Hub) Wallets() []accounts.Wallet {
|
||||
// Make sure the list of wallets is up to date
|
||||
hub.refreshWallets()
|
||||
|
||||
hub.stateLock.RLock()
|
||||
defer hub.stateLock.RUnlock()
|
||||
|
||||
cpy := make([]accounts.Wallet, len(hub.wallets))
|
||||
copy(cpy, hub.wallets)
|
||||
return cpy
|
||||
}
|
||||
|
||||
// refreshWallets scans the USB devices attached to the machine and updates the
|
||||
// list of wallets based on the found devices.
|
||||
func (hub *Hub) refreshWallets() {
|
||||
// Don't scan the USB like crazy it the user fetches wallets in a loop
|
||||
hub.stateLock.RLock()
|
||||
elapsed := time.Since(hub.refreshed)
|
||||
hub.stateLock.RUnlock()
|
||||
|
||||
if elapsed < refreshThrottling {
|
||||
return
|
||||
}
|
||||
// If USB enumeration is continually failing, don't keep trying indefinitely
|
||||
if atomic.LoadUint32(&hub.enumFails) > 2 {
|
||||
return
|
||||
}
|
||||
// Retrieve the current list of USB wallet devices
|
||||
var devices []usb.DeviceInfo
|
||||
|
||||
if runtime.GOOS == "linux" {
|
||||
// hidapi on Linux opens the device during enumeration to retrieve some infos,
|
||||
// breaking the Ledger protocol if that is waiting for user confirmation. This
|
||||
// is a bug acknowledged at Ledger, but it won't be fixed on old devices so we
|
||||
// need to prevent concurrent comms ourselves. The more elegant solution would
|
||||
// be to ditch enumeration in favor of hotplug events, but that don't work yet
|
||||
// on Windows so if we need to hack it anyway, this is more elegant for now.
|
||||
hub.commsLock.Lock()
|
||||
if hub.commsPend > 0 { // A confirmation is pending, don't refresh
|
||||
hub.commsLock.Unlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
infos, err := usb.Enumerate(hub.vendorID, 0)
|
||||
if err != nil {
|
||||
failcount := atomic.AddUint32(&hub.enumFails, 1)
|
||||
if runtime.GOOS == "linux" {
|
||||
// See rationale before the enumeration why this is needed and only on Linux.
|
||||
hub.commsLock.Unlock()
|
||||
}
|
||||
log.Error("Failed to enumerate USB devices", "hub", hub.scheme,
|
||||
"vendor", hub.vendorID, "failcount", failcount, "err", err)
|
||||
return
|
||||
}
|
||||
atomic.StoreUint32(&hub.enumFails, 0)
|
||||
|
||||
for _, info := range infos {
|
||||
for _, id := range hub.productIDs {
|
||||
// Windows and Macos use UsageID matching, Linux uses Interface matching
|
||||
if info.ProductID == id && (info.UsagePage == hub.usageID || info.Interface == hub.endpointID) {
|
||||
devices = append(devices, info)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if runtime.GOOS == "linux" {
|
||||
// See rationale before the enumeration why this is needed and only on Linux.
|
||||
hub.commsLock.Unlock()
|
||||
}
|
||||
// Transform the current list of wallets into the new one
|
||||
hub.stateLock.Lock()
|
||||
|
||||
var (
|
||||
wallets = make([]accounts.Wallet, 0, len(devices))
|
||||
events []accounts.WalletEvent
|
||||
)
|
||||
|
||||
for _, device := range devices {
|
||||
url := accounts.URL{Scheme: hub.scheme, Path: device.Path}
|
||||
|
||||
// Drop wallets in front of the next device or those that failed for some reason
|
||||
for len(hub.wallets) > 0 {
|
||||
// Abort if we're past the current device and found an operational one
|
||||
_, failure := hub.wallets[0].Status()
|
||||
if hub.wallets[0].URL().Cmp(url) >= 0 || failure == nil {
|
||||
break
|
||||
}
|
||||
// Drop the stale and failed devices
|
||||
events = append(events, accounts.WalletEvent{Wallet: hub.wallets[0], Kind: accounts.WalletDropped})
|
||||
hub.wallets = hub.wallets[1:]
|
||||
}
|
||||
// If there are no more wallets or the device is before the next, wrap new wallet
|
||||
if len(hub.wallets) == 0 || hub.wallets[0].URL().Cmp(url) > 0 {
|
||||
logger := log.New("url", url)
|
||||
wallet := &wallet{hub: hub, driver: hub.makeDriver(logger), url: &url, info: device, log: logger}
|
||||
|
||||
events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived})
|
||||
wallets = append(wallets, wallet)
|
||||
continue
|
||||
}
|
||||
// If the device is the same as the first wallet, keep it
|
||||
if hub.wallets[0].URL().Cmp(url) == 0 {
|
||||
wallets = append(wallets, hub.wallets[0])
|
||||
hub.wallets = hub.wallets[1:]
|
||||
continue
|
||||
}
|
||||
}
|
||||
// Drop any leftover wallets and set the new batch
|
||||
for _, wallet := range hub.wallets {
|
||||
events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped})
|
||||
}
|
||||
hub.refreshed = time.Now()
|
||||
hub.wallets = wallets
|
||||
hub.stateLock.Unlock()
|
||||
|
||||
// Fire all wallet events and return
|
||||
for _, event := range events {
|
||||
hub.updateFeed.Send(event)
|
||||
}
|
||||
}
|
||||
|
||||
// Subscribe implements accounts.Backend, creating an async subscription to
|
||||
// receive notifications on the addition or removal of USB wallets.
|
||||
func (hub *Hub) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
|
||||
// We need the mutex to reliably start/stop the update loop
|
||||
hub.stateLock.Lock()
|
||||
defer hub.stateLock.Unlock()
|
||||
|
||||
// Subscribe the caller and track the subscriber count
|
||||
sub := hub.updateScope.Track(hub.updateFeed.Subscribe(sink))
|
||||
|
||||
// Subscribers require an active notification loop, start it
|
||||
if !hub.updating {
|
||||
hub.updating = true
|
||||
go hub.updater()
|
||||
}
|
||||
return sub
|
||||
}
|
||||
|
||||
// updater is responsible for maintaining an up-to-date list of wallets managed
|
||||
// by the USB hub, and for firing wallet addition/removal events.
|
||||
func (hub *Hub) updater() {
|
||||
for {
|
||||
// TODO: Wait for a USB hotplug event (not supported yet) or a refresh timeout
|
||||
// <-hub.changes
|
||||
time.Sleep(refreshCycle)
|
||||
|
||||
// Run the wallet refresher
|
||||
hub.refreshWallets()
|
||||
|
||||
// If all our subscribers left, stop the updater
|
||||
hub.stateLock.Lock()
|
||||
if hub.updateScope.Count() == 0 {
|
||||
hub.updating = false
|
||||
hub.stateLock.Unlock()
|
||||
return
|
||||
}
|
||||
hub.stateLock.Unlock()
|
||||
}
|
||||
}
|
365
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/trezor.go
generated
vendored
Normal file
365
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/trezor.go
generated
vendored
Normal file
@ -0,0 +1,365 @@
|
||||
// Copyright 2017 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
// This file contains the implementation for interacting with the Trezor hardware
|
||||
// wallets. The wire protocol spec can be found on the SatoshiLabs website:
|
||||
// https://doc.satoshilabs.com/trezor-tech/api-protobuf.html
|
||||
|
||||
package usbwallet
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
|
||||
"github.com/ethereum/go-ethereum/accounts"
|
||||
"github.com/ethereum/go-ethereum/accounts/usbwallet/trezor"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/common/hexutil"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/log"
|
||||
"github.com/golang/protobuf/proto"
|
||||
)
|
||||
|
||||
// ErrTrezorPINNeeded is returned if opening the trezor requires a PIN code. In
|
||||
// this case, the calling application should display a pinpad and send back the
|
||||
// encoded passphrase.
|
||||
var ErrTrezorPINNeeded = errors.New("trezor: pin needed")
|
||||
|
||||
// ErrTrezorPassphraseNeeded is returned if opening the trezor requires a passphrase
|
||||
var ErrTrezorPassphraseNeeded = errors.New("trezor: passphrase needed")
|
||||
|
||||
// errTrezorReplyInvalidHeader is the error message returned by a Trezor data exchange
|
||||
// if the device replies with a mismatching header. This usually means the device
|
||||
// is in browser mode.
|
||||
var errTrezorReplyInvalidHeader = errors.New("trezor: invalid reply header")
|
||||
|
||||
// trezorDriver implements the communication with a Trezor hardware wallet.
|
||||
type trezorDriver struct {
|
||||
device io.ReadWriter // USB device connection to communicate through
|
||||
version [3]uint32 // Current version of the Trezor firmware
|
||||
label string // Current textual label of the Trezor device
|
||||
pinwait bool // Flags whether the device is waiting for PIN entry
|
||||
passphrasewait bool // Flags whether the device is waiting for passphrase entry
|
||||
failure error // Any failure that would make the device unusable
|
||||
log log.Logger // Contextual logger to tag the trezor with its id
|
||||
}
|
||||
|
||||
// newTrezorDriver creates a new instance of a Trezor USB protocol driver.
|
||||
func newTrezorDriver(logger log.Logger) driver {
|
||||
return &trezorDriver{
|
||||
log: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Status implements accounts.Wallet, always whether the Trezor is opened, closed
|
||||
// or whether the Ethereum app was not started on it.
|
||||
func (w *trezorDriver) Status() (string, error) {
|
||||
if w.failure != nil {
|
||||
return fmt.Sprintf("Failed: %v", w.failure), w.failure
|
||||
}
|
||||
if w.device == nil {
|
||||
return "Closed", w.failure
|
||||
}
|
||||
if w.pinwait {
|
||||
return fmt.Sprintf("Trezor v%d.%d.%d '%s' waiting for PIN", w.version[0], w.version[1], w.version[2], w.label), w.failure
|
||||
}
|
||||
return fmt.Sprintf("Trezor v%d.%d.%d '%s' online", w.version[0], w.version[1], w.version[2], w.label), w.failure
|
||||
}
|
||||
|
||||
// Open implements usbwallet.driver, attempting to initialize the connection to
|
||||
// the Trezor hardware wallet. Initializing the Trezor is a two or three phase operation:
|
||||
// * The first phase is to initialize the connection and read the wallet's
|
||||
// features. This phase is invoked if the provided passphrase is empty. The
|
||||
// device will display the pinpad as a result and will return an appropriate
|
||||
// error to notify the user that a second open phase is needed.
|
||||
// * The second phase is to unlock access to the Trezor, which is done by the
|
||||
// user actually providing a passphrase mapping a keyboard keypad to the pin
|
||||
// number of the user (shuffled according to the pinpad displayed).
|
||||
// * If needed the device will ask for passphrase which will require calling
|
||||
// open again with the actual passphrase (3rd phase)
|
||||
func (w *trezorDriver) Open(device io.ReadWriter, passphrase string) error {
|
||||
w.device, w.failure = device, nil
|
||||
|
||||
// If phase 1 is requested, init the connection and wait for user callback
|
||||
if passphrase == "" && !w.passphrasewait {
|
||||
// If we're already waiting for a PIN entry, insta-return
|
||||
if w.pinwait {
|
||||
return ErrTrezorPINNeeded
|
||||
}
|
||||
// Initialize a connection to the device
|
||||
features := new(trezor.Features)
|
||||
if _, err := w.trezorExchange(&trezor.Initialize{}, features); err != nil {
|
||||
return err
|
||||
}
|
||||
w.version = [3]uint32{features.GetMajorVersion(), features.GetMinorVersion(), features.GetPatchVersion()}
|
||||
w.label = features.GetLabel()
|
||||
|
||||
// Do a manual ping, forcing the device to ask for its PIN and Passphrase
|
||||
askPin := true
|
||||
askPassphrase := true
|
||||
res, err := w.trezorExchange(&trezor.Ping{PinProtection: &askPin, PassphraseProtection: &askPassphrase}, new(trezor.PinMatrixRequest), new(trezor.PassphraseRequest), new(trezor.Success))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Only return the PIN request if the device wasn't unlocked until now
|
||||
switch res {
|
||||
case 0:
|
||||
w.pinwait = true
|
||||
return ErrTrezorPINNeeded
|
||||
case 1:
|
||||
w.pinwait = false
|
||||
w.passphrasewait = true
|
||||
return ErrTrezorPassphraseNeeded
|
||||
case 2:
|
||||
return nil // responded with trezor.Success
|
||||
}
|
||||
}
|
||||
// Phase 2 requested with actual PIN entry
|
||||
if w.pinwait {
|
||||
w.pinwait = false
|
||||
res, err := w.trezorExchange(&trezor.PinMatrixAck{Pin: &passphrase}, new(trezor.Success), new(trezor.PassphraseRequest))
|
||||
if err != nil {
|
||||
w.failure = err
|
||||
return err
|
||||
}
|
||||
if res == 1 {
|
||||
w.passphrasewait = true
|
||||
return ErrTrezorPassphraseNeeded
|
||||
}
|
||||
} else if w.passphrasewait {
|
||||
w.passphrasewait = false
|
||||
if _, err := w.trezorExchange(&trezor.PassphraseAck{Passphrase: &passphrase}, new(trezor.Success)); err != nil {
|
||||
w.failure = err
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close implements usbwallet.driver, cleaning up and metadata maintained within
|
||||
// the Trezor driver.
|
||||
func (w *trezorDriver) Close() error {
|
||||
w.version, w.label, w.pinwait = [3]uint32{}, "", false
|
||||
return nil
|
||||
}
|
||||
|
||||
// Heartbeat implements usbwallet.driver, performing a sanity check against the
|
||||
// Trezor to see if it's still online.
|
||||
func (w *trezorDriver) Heartbeat() error {
|
||||
if _, err := w.trezorExchange(&trezor.Ping{}, new(trezor.Success)); err != nil {
|
||||
w.failure = err
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Derive implements usbwallet.driver, sending a derivation request to the Trezor
|
||||
// and returning the Ethereum address located on that derivation path.
|
||||
func (w *trezorDriver) Derive(path accounts.DerivationPath) (common.Address, error) {
|
||||
return w.trezorDerive(path)
|
||||
}
|
||||
|
||||
// SignTx implements usbwallet.driver, sending the transaction to the Trezor and
|
||||
// waiting for the user to confirm or deny the transaction.
|
||||
func (w *trezorDriver) SignTx(path accounts.DerivationPath, tx *types.Transaction, chainID *big.Int) (common.Address, *types.Transaction, error) {
|
||||
if w.device == nil {
|
||||
return common.Address{}, nil, accounts.ErrWalletClosed
|
||||
}
|
||||
return w.trezorSign(path, tx, chainID)
|
||||
}
|
||||
|
||||
// trezorDerive sends a derivation request to the Trezor device and returns the
|
||||
// Ethereum address located on that path.
|
||||
func (w *trezorDriver) trezorDerive(derivationPath []uint32) (common.Address, error) {
|
||||
address := new(trezor.EthereumAddress)
|
||||
if _, err := w.trezorExchange(&trezor.EthereumGetAddress{AddressN: derivationPath}, address); err != nil {
|
||||
return common.Address{}, err
|
||||
}
|
||||
if addr := address.GetAddressBin(); len(addr) > 0 { // Older firmwares use binary fomats
|
||||
return common.BytesToAddress(addr), nil
|
||||
}
|
||||
if addr := address.GetAddressHex(); len(addr) > 0 { // Newer firmwares use hexadecimal fomats
|
||||
return common.HexToAddress(addr), nil
|
||||
}
|
||||
return common.Address{}, errors.New("missing derived address")
|
||||
}
|
||||
|
||||
// trezorSign sends the transaction to the Trezor wallet, and waits for the user
|
||||
// to confirm or deny the transaction.
|
||||
func (w *trezorDriver) trezorSign(derivationPath []uint32, tx *types.Transaction, chainID *big.Int) (common.Address, *types.Transaction, error) {
|
||||
// Create the transaction initiation message
|
||||
data := tx.Data()
|
||||
length := uint32(len(data))
|
||||
|
||||
request := &trezor.EthereumSignTx{
|
||||
AddressN: derivationPath,
|
||||
Nonce: new(big.Int).SetUint64(tx.Nonce()).Bytes(),
|
||||
GasPrice: tx.GasPrice().Bytes(),
|
||||
GasLimit: new(big.Int).SetUint64(tx.Gas()).Bytes(),
|
||||
Value: tx.Value().Bytes(),
|
||||
DataLength: &length,
|
||||
}
|
||||
if to := tx.To(); to != nil {
|
||||
// Non contract deploy, set recipient explicitly
|
||||
hex := to.Hex()
|
||||
request.ToHex = &hex // Newer firmwares (old will ignore)
|
||||
request.ToBin = (*to)[:] // Older firmwares (new will ignore)
|
||||
}
|
||||
if length > 1024 { // Send the data chunked if that was requested
|
||||
request.DataInitialChunk, data = data[:1024], data[1024:]
|
||||
} else {
|
||||
request.DataInitialChunk, data = data, nil
|
||||
}
|
||||
if chainID != nil { // EIP-155 transaction, set chain ID explicitly (only 32 bit is supported!?)
|
||||
id := uint32(chainID.Int64())
|
||||
request.ChainId = &id
|
||||
}
|
||||
// Send the initiation message and stream content until a signature is returned
|
||||
response := new(trezor.EthereumTxRequest)
|
||||
if _, err := w.trezorExchange(request, response); err != nil {
|
||||
return common.Address{}, nil, err
|
||||
}
|
||||
for response.DataLength != nil && int(*response.DataLength) <= len(data) {
|
||||
chunk := data[:*response.DataLength]
|
||||
data = data[*response.DataLength:]
|
||||
|
||||
if _, err := w.trezorExchange(&trezor.EthereumTxAck{DataChunk: chunk}, response); err != nil {
|
||||
return common.Address{}, nil, err
|
||||
}
|
||||
}
|
||||
// Extract the Ethereum signature and do a sanity validation
|
||||
if len(response.GetSignatureR()) == 0 || len(response.GetSignatureS()) == 0 || response.GetSignatureV() == 0 {
|
||||
return common.Address{}, nil, errors.New("reply lacks signature")
|
||||
}
|
||||
signature := append(append(response.GetSignatureR(), response.GetSignatureS()...), byte(response.GetSignatureV()))
|
||||
|
||||
// Create the correct signer and signature transform based on the chain ID
|
||||
var signer types.Signer
|
||||
if chainID == nil {
|
||||
signer = new(types.HomesteadSigner)
|
||||
} else {
|
||||
signer = types.NewEIP155Signer(chainID)
|
||||
signature[64] -= byte(chainID.Uint64()*2 + 35)
|
||||
}
|
||||
// Inject the final signature into the transaction and sanity check the sender
|
||||
signed, err := tx.WithSignature(signer, signature)
|
||||
if err != nil {
|
||||
return common.Address{}, nil, err
|
||||
}
|
||||
sender, err := types.Sender(signer, signed)
|
||||
if err != nil {
|
||||
return common.Address{}, nil, err
|
||||
}
|
||||
return sender, signed, nil
|
||||
}
|
||||
|
||||
// trezorExchange performs a data exchange with the Trezor wallet, sending it a
|
||||
// message and retrieving the response. If multiple responses are possible, the
|
||||
// method will also return the index of the destination object used.
|
||||
func (w *trezorDriver) trezorExchange(req proto.Message, results ...proto.Message) (int, error) {
|
||||
// Construct the original message payload to chunk up
|
||||
data, err := proto.Marshal(req)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
payload := make([]byte, 8+len(data))
|
||||
copy(payload, []byte{0x23, 0x23})
|
||||
binary.BigEndian.PutUint16(payload[2:], trezor.Type(req))
|
||||
binary.BigEndian.PutUint32(payload[4:], uint32(len(data)))
|
||||
copy(payload[8:], data)
|
||||
|
||||
// Stream all the chunks to the device
|
||||
chunk := make([]byte, 64)
|
||||
chunk[0] = 0x3f // Report ID magic number
|
||||
|
||||
for len(payload) > 0 {
|
||||
// Construct the new message to stream, padding with zeroes if needed
|
||||
if len(payload) > 63 {
|
||||
copy(chunk[1:], payload[:63])
|
||||
payload = payload[63:]
|
||||
} else {
|
||||
copy(chunk[1:], payload)
|
||||
copy(chunk[1+len(payload):], make([]byte, 63-len(payload)))
|
||||
payload = nil
|
||||
}
|
||||
// Send over to the device
|
||||
w.log.Trace("Data chunk sent to the Trezor", "chunk", hexutil.Bytes(chunk))
|
||||
if _, err := w.device.Write(chunk); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
// Stream the reply back from the wallet in 64 byte chunks
|
||||
var (
|
||||
kind uint16
|
||||
reply []byte
|
||||
)
|
||||
for {
|
||||
// Read the next chunk from the Trezor wallet
|
||||
if _, err := io.ReadFull(w.device, chunk); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
w.log.Trace("Data chunk received from the Trezor", "chunk", hexutil.Bytes(chunk))
|
||||
|
||||
// Make sure the transport header matches
|
||||
if chunk[0] != 0x3f || (len(reply) == 0 && (chunk[1] != 0x23 || chunk[2] != 0x23)) {
|
||||
return 0, errTrezorReplyInvalidHeader
|
||||
}
|
||||
// If it's the first chunk, retrieve the reply message type and total message length
|
||||
var payload []byte
|
||||
|
||||
if len(reply) == 0 {
|
||||
kind = binary.BigEndian.Uint16(chunk[3:5])
|
||||
reply = make([]byte, 0, int(binary.BigEndian.Uint32(chunk[5:9])))
|
||||
payload = chunk[9:]
|
||||
} else {
|
||||
payload = chunk[1:]
|
||||
}
|
||||
// Append to the reply and stop when filled up
|
||||
if left := cap(reply) - len(reply); left > len(payload) {
|
||||
reply = append(reply, payload...)
|
||||
} else {
|
||||
reply = append(reply, payload[:left]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
// Try to parse the reply into the requested reply message
|
||||
if kind == uint16(trezor.MessageType_MessageType_Failure) {
|
||||
// Trezor returned a failure, extract and return the message
|
||||
failure := new(trezor.Failure)
|
||||
if err := proto.Unmarshal(reply, failure); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return 0, errors.New("trezor: " + failure.GetMessage())
|
||||
}
|
||||
if kind == uint16(trezor.MessageType_MessageType_ButtonRequest) {
|
||||
// Trezor is waiting for user confirmation, ack and wait for the next message
|
||||
return w.trezorExchange(&trezor.ButtonAck{}, results...)
|
||||
}
|
||||
for i, res := range results {
|
||||
if trezor.Type(res) == kind {
|
||||
return i, proto.Unmarshal(reply, res)
|
||||
}
|
||||
}
|
||||
expected := make([]string, len(results))
|
||||
for i, res := range results {
|
||||
expected[i] = trezor.Name(trezor.Type(res))
|
||||
}
|
||||
return 0, fmt.Errorf("trezor: expected reply types %s, got %s", expected, trezor.Name(kind))
|
||||
}
|
811
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/trezor/messages-common.pb.go
generated
vendored
Normal file
811
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/trezor/messages-common.pb.go
generated
vendored
Normal file
@ -0,0 +1,811 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// source: messages-common.proto
|
||||
|
||||
package trezor
|
||||
|
||||
import (
|
||||
fmt "fmt"
|
||||
math "math"
|
||||
|
||||
proto "github.com/golang/protobuf/proto"
|
||||
)
|
||||
|
||||
// Reference imports to suppress errors if they are not otherwise used.
|
||||
var _ = proto.Marshal
|
||||
var _ = fmt.Errorf
|
||||
var _ = math.Inf
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the proto package it is being compiled against.
|
||||
// A compilation error at this line likely means your copy of the
|
||||
// proto package needs to be updated.
|
||||
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
|
||||
|
||||
type Failure_FailureType int32
|
||||
|
||||
const (
|
||||
Failure_Failure_UnexpectedMessage Failure_FailureType = 1
|
||||
Failure_Failure_ButtonExpected Failure_FailureType = 2
|
||||
Failure_Failure_DataError Failure_FailureType = 3
|
||||
Failure_Failure_ActionCancelled Failure_FailureType = 4
|
||||
Failure_Failure_PinExpected Failure_FailureType = 5
|
||||
Failure_Failure_PinCancelled Failure_FailureType = 6
|
||||
Failure_Failure_PinInvalid Failure_FailureType = 7
|
||||
Failure_Failure_InvalidSignature Failure_FailureType = 8
|
||||
Failure_Failure_ProcessError Failure_FailureType = 9
|
||||
Failure_Failure_NotEnoughFunds Failure_FailureType = 10
|
||||
Failure_Failure_NotInitialized Failure_FailureType = 11
|
||||
Failure_Failure_PinMismatch Failure_FailureType = 12
|
||||
Failure_Failure_FirmwareError Failure_FailureType = 99
|
||||
)
|
||||
|
||||
var Failure_FailureType_name = map[int32]string{
|
||||
1: "Failure_UnexpectedMessage",
|
||||
2: "Failure_ButtonExpected",
|
||||
3: "Failure_DataError",
|
||||
4: "Failure_ActionCancelled",
|
||||
5: "Failure_PinExpected",
|
||||
6: "Failure_PinCancelled",
|
||||
7: "Failure_PinInvalid",
|
||||
8: "Failure_InvalidSignature",
|
||||
9: "Failure_ProcessError",
|
||||
10: "Failure_NotEnoughFunds",
|
||||
11: "Failure_NotInitialized",
|
||||
12: "Failure_PinMismatch",
|
||||
99: "Failure_FirmwareError",
|
||||
}
|
||||
|
||||
var Failure_FailureType_value = map[string]int32{
|
||||
"Failure_UnexpectedMessage": 1,
|
||||
"Failure_ButtonExpected": 2,
|
||||
"Failure_DataError": 3,
|
||||
"Failure_ActionCancelled": 4,
|
||||
"Failure_PinExpected": 5,
|
||||
"Failure_PinCancelled": 6,
|
||||
"Failure_PinInvalid": 7,
|
||||
"Failure_InvalidSignature": 8,
|
||||
"Failure_ProcessError": 9,
|
||||
"Failure_NotEnoughFunds": 10,
|
||||
"Failure_NotInitialized": 11,
|
||||
"Failure_PinMismatch": 12,
|
||||
"Failure_FirmwareError": 99,
|
||||
}
|
||||
|
||||
func (x Failure_FailureType) Enum() *Failure_FailureType {
|
||||
p := new(Failure_FailureType)
|
||||
*p = x
|
||||
return p
|
||||
}
|
||||
|
||||
func (x Failure_FailureType) String() string {
|
||||
return proto.EnumName(Failure_FailureType_name, int32(x))
|
||||
}
|
||||
|
||||
func (x *Failure_FailureType) UnmarshalJSON(data []byte) error {
|
||||
value, err := proto.UnmarshalJSONEnum(Failure_FailureType_value, data, "Failure_FailureType")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*x = Failure_FailureType(value)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (Failure_FailureType) EnumDescriptor() ([]byte, []int) {
|
||||
return fileDescriptor_aaf30d059fdbc38d, []int{1, 0}
|
||||
}
|
||||
|
||||
//*
|
||||
// Type of button request
|
||||
type ButtonRequest_ButtonRequestType int32
|
||||
|
||||
const (
|
||||
ButtonRequest_ButtonRequest_Other ButtonRequest_ButtonRequestType = 1
|
||||
ButtonRequest_ButtonRequest_FeeOverThreshold ButtonRequest_ButtonRequestType = 2
|
||||
ButtonRequest_ButtonRequest_ConfirmOutput ButtonRequest_ButtonRequestType = 3
|
||||
ButtonRequest_ButtonRequest_ResetDevice ButtonRequest_ButtonRequestType = 4
|
||||
ButtonRequest_ButtonRequest_ConfirmWord ButtonRequest_ButtonRequestType = 5
|
||||
ButtonRequest_ButtonRequest_WipeDevice ButtonRequest_ButtonRequestType = 6
|
||||
ButtonRequest_ButtonRequest_ProtectCall ButtonRequest_ButtonRequestType = 7
|
||||
ButtonRequest_ButtonRequest_SignTx ButtonRequest_ButtonRequestType = 8
|
||||
ButtonRequest_ButtonRequest_FirmwareCheck ButtonRequest_ButtonRequestType = 9
|
||||
ButtonRequest_ButtonRequest_Address ButtonRequest_ButtonRequestType = 10
|
||||
ButtonRequest_ButtonRequest_PublicKey ButtonRequest_ButtonRequestType = 11
|
||||
ButtonRequest_ButtonRequest_MnemonicWordCount ButtonRequest_ButtonRequestType = 12
|
||||
ButtonRequest_ButtonRequest_MnemonicInput ButtonRequest_ButtonRequestType = 13
|
||||
ButtonRequest_ButtonRequest_PassphraseType ButtonRequest_ButtonRequestType = 14
|
||||
ButtonRequest_ButtonRequest_UnknownDerivationPath ButtonRequest_ButtonRequestType = 15
|
||||
)
|
||||
|
||||
var ButtonRequest_ButtonRequestType_name = map[int32]string{
|
||||
1: "ButtonRequest_Other",
|
||||
2: "ButtonRequest_FeeOverThreshold",
|
||||
3: "ButtonRequest_ConfirmOutput",
|
||||
4: "ButtonRequest_ResetDevice",
|
||||
5: "ButtonRequest_ConfirmWord",
|
||||
6: "ButtonRequest_WipeDevice",
|
||||
7: "ButtonRequest_ProtectCall",
|
||||
8: "ButtonRequest_SignTx",
|
||||
9: "ButtonRequest_FirmwareCheck",
|
||||
10: "ButtonRequest_Address",
|
||||
11: "ButtonRequest_PublicKey",
|
||||
12: "ButtonRequest_MnemonicWordCount",
|
||||
13: "ButtonRequest_MnemonicInput",
|
||||
14: "ButtonRequest_PassphraseType",
|
||||
15: "ButtonRequest_UnknownDerivationPath",
|
||||
}
|
||||
|
||||
var ButtonRequest_ButtonRequestType_value = map[string]int32{
|
||||
"ButtonRequest_Other": 1,
|
||||
"ButtonRequest_FeeOverThreshold": 2,
|
||||
"ButtonRequest_ConfirmOutput": 3,
|
||||
"ButtonRequest_ResetDevice": 4,
|
||||
"ButtonRequest_ConfirmWord": 5,
|
||||
"ButtonRequest_WipeDevice": 6,
|
||||
"ButtonRequest_ProtectCall": 7,
|
||||
"ButtonRequest_SignTx": 8,
|
||||
"ButtonRequest_FirmwareCheck": 9,
|
||||
"ButtonRequest_Address": 10,
|
||||
"ButtonRequest_PublicKey": 11,
|
||||
"ButtonRequest_MnemonicWordCount": 12,
|
||||
"ButtonRequest_MnemonicInput": 13,
|
||||
"ButtonRequest_PassphraseType": 14,
|
||||
"ButtonRequest_UnknownDerivationPath": 15,
|
||||
}
|
||||
|
||||
func (x ButtonRequest_ButtonRequestType) Enum() *ButtonRequest_ButtonRequestType {
|
||||
p := new(ButtonRequest_ButtonRequestType)
|
||||
*p = x
|
||||
return p
|
||||
}
|
||||
|
||||
func (x ButtonRequest_ButtonRequestType) String() string {
|
||||
return proto.EnumName(ButtonRequest_ButtonRequestType_name, int32(x))
|
||||
}
|
||||
|
||||
func (x *ButtonRequest_ButtonRequestType) UnmarshalJSON(data []byte) error {
|
||||
value, err := proto.UnmarshalJSONEnum(ButtonRequest_ButtonRequestType_value, data, "ButtonRequest_ButtonRequestType")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*x = ButtonRequest_ButtonRequestType(value)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ButtonRequest_ButtonRequestType) EnumDescriptor() ([]byte, []int) {
|
||||
return fileDescriptor_aaf30d059fdbc38d, []int{2, 0}
|
||||
}
|
||||
|
||||
//*
|
||||
// Type of PIN request
|
||||
type PinMatrixRequest_PinMatrixRequestType int32
|
||||
|
||||
const (
|
||||
PinMatrixRequest_PinMatrixRequestType_Current PinMatrixRequest_PinMatrixRequestType = 1
|
||||
PinMatrixRequest_PinMatrixRequestType_NewFirst PinMatrixRequest_PinMatrixRequestType = 2
|
||||
PinMatrixRequest_PinMatrixRequestType_NewSecond PinMatrixRequest_PinMatrixRequestType = 3
|
||||
)
|
||||
|
||||
var PinMatrixRequest_PinMatrixRequestType_name = map[int32]string{
|
||||
1: "PinMatrixRequestType_Current",
|
||||
2: "PinMatrixRequestType_NewFirst",
|
||||
3: "PinMatrixRequestType_NewSecond",
|
||||
}
|
||||
|
||||
var PinMatrixRequest_PinMatrixRequestType_value = map[string]int32{
|
||||
"PinMatrixRequestType_Current": 1,
|
||||
"PinMatrixRequestType_NewFirst": 2,
|
||||
"PinMatrixRequestType_NewSecond": 3,
|
||||
}
|
||||
|
||||
func (x PinMatrixRequest_PinMatrixRequestType) Enum() *PinMatrixRequest_PinMatrixRequestType {
|
||||
p := new(PinMatrixRequest_PinMatrixRequestType)
|
||||
*p = x
|
||||
return p
|
||||
}
|
||||
|
||||
func (x PinMatrixRequest_PinMatrixRequestType) String() string {
|
||||
return proto.EnumName(PinMatrixRequest_PinMatrixRequestType_name, int32(x))
|
||||
}
|
||||
|
||||
func (x *PinMatrixRequest_PinMatrixRequestType) UnmarshalJSON(data []byte) error {
|
||||
value, err := proto.UnmarshalJSONEnum(PinMatrixRequest_PinMatrixRequestType_value, data, "PinMatrixRequest_PinMatrixRequestType")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*x = PinMatrixRequest_PinMatrixRequestType(value)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (PinMatrixRequest_PinMatrixRequestType) EnumDescriptor() ([]byte, []int) {
|
||||
return fileDescriptor_aaf30d059fdbc38d, []int{4, 0}
|
||||
}
|
||||
|
||||
//*
|
||||
// Response: Success of the previous request
|
||||
// @end
|
||||
type Success struct {
|
||||
Message *string `protobuf:"bytes,1,opt,name=message" json:"message,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *Success) Reset() { *m = Success{} }
|
||||
func (m *Success) String() string { return proto.CompactTextString(m) }
|
||||
func (*Success) ProtoMessage() {}
|
||||
func (*Success) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_aaf30d059fdbc38d, []int{0}
|
||||
}
|
||||
|
||||
func (m *Success) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_Success.Unmarshal(m, b)
|
||||
}
|
||||
func (m *Success) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_Success.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (m *Success) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_Success.Merge(m, src)
|
||||
}
|
||||
func (m *Success) XXX_Size() int {
|
||||
return xxx_messageInfo_Success.Size(m)
|
||||
}
|
||||
func (m *Success) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_Success.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_Success proto.InternalMessageInfo
|
||||
|
||||
func (m *Success) GetMessage() string {
|
||||
if m != nil && m.Message != nil {
|
||||
return *m.Message
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
//*
|
||||
// Response: Failure of the previous request
|
||||
// @end
|
||||
type Failure struct {
|
||||
Code *Failure_FailureType `protobuf:"varint,1,opt,name=code,enum=hw.trezor.messages.common.Failure_FailureType" json:"code,omitempty"`
|
||||
Message *string `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *Failure) Reset() { *m = Failure{} }
|
||||
func (m *Failure) String() string { return proto.CompactTextString(m) }
|
||||
func (*Failure) ProtoMessage() {}
|
||||
func (*Failure) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_aaf30d059fdbc38d, []int{1}
|
||||
}
|
||||
|
||||
func (m *Failure) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_Failure.Unmarshal(m, b)
|
||||
}
|
||||
func (m *Failure) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_Failure.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (m *Failure) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_Failure.Merge(m, src)
|
||||
}
|
||||
func (m *Failure) XXX_Size() int {
|
||||
return xxx_messageInfo_Failure.Size(m)
|
||||
}
|
||||
func (m *Failure) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_Failure.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_Failure proto.InternalMessageInfo
|
||||
|
||||
func (m *Failure) GetCode() Failure_FailureType {
|
||||
if m != nil && m.Code != nil {
|
||||
return *m.Code
|
||||
}
|
||||
return Failure_Failure_UnexpectedMessage
|
||||
}
|
||||
|
||||
func (m *Failure) GetMessage() string {
|
||||
if m != nil && m.Message != nil {
|
||||
return *m.Message
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
//*
|
||||
// Response: Device is waiting for HW button press.
|
||||
// @auxstart
|
||||
// @next ButtonAck
|
||||
type ButtonRequest struct {
|
||||
Code *ButtonRequest_ButtonRequestType `protobuf:"varint,1,opt,name=code,enum=hw.trezor.messages.common.ButtonRequest_ButtonRequestType" json:"code,omitempty"`
|
||||
Data *string `protobuf:"bytes,2,opt,name=data" json:"data,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *ButtonRequest) Reset() { *m = ButtonRequest{} }
|
||||
func (m *ButtonRequest) String() string { return proto.CompactTextString(m) }
|
||||
func (*ButtonRequest) ProtoMessage() {}
|
||||
func (*ButtonRequest) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_aaf30d059fdbc38d, []int{2}
|
||||
}
|
||||
|
||||
func (m *ButtonRequest) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_ButtonRequest.Unmarshal(m, b)
|
||||
}
|
||||
func (m *ButtonRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_ButtonRequest.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (m *ButtonRequest) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_ButtonRequest.Merge(m, src)
|
||||
}
|
||||
func (m *ButtonRequest) XXX_Size() int {
|
||||
return xxx_messageInfo_ButtonRequest.Size(m)
|
||||
}
|
||||
func (m *ButtonRequest) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_ButtonRequest.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_ButtonRequest proto.InternalMessageInfo
|
||||
|
||||
func (m *ButtonRequest) GetCode() ButtonRequest_ButtonRequestType {
|
||||
if m != nil && m.Code != nil {
|
||||
return *m.Code
|
||||
}
|
||||
return ButtonRequest_ButtonRequest_Other
|
||||
}
|
||||
|
||||
func (m *ButtonRequest) GetData() string {
|
||||
if m != nil && m.Data != nil {
|
||||
return *m.Data
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
//*
|
||||
// Request: Computer agrees to wait for HW button press
|
||||
// @auxend
|
||||
type ButtonAck struct {
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *ButtonAck) Reset() { *m = ButtonAck{} }
|
||||
func (m *ButtonAck) String() string { return proto.CompactTextString(m) }
|
||||
func (*ButtonAck) ProtoMessage() {}
|
||||
func (*ButtonAck) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_aaf30d059fdbc38d, []int{3}
|
||||
}
|
||||
|
||||
func (m *ButtonAck) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_ButtonAck.Unmarshal(m, b)
|
||||
}
|
||||
func (m *ButtonAck) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_ButtonAck.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (m *ButtonAck) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_ButtonAck.Merge(m, src)
|
||||
}
|
||||
func (m *ButtonAck) XXX_Size() int {
|
||||
return xxx_messageInfo_ButtonAck.Size(m)
|
||||
}
|
||||
func (m *ButtonAck) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_ButtonAck.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_ButtonAck proto.InternalMessageInfo
|
||||
|
||||
//*
|
||||
// Response: Device is asking computer to show PIN matrix and awaits PIN encoded using this matrix scheme
|
||||
// @auxstart
|
||||
// @next PinMatrixAck
|
||||
type PinMatrixRequest struct {
|
||||
Type *PinMatrixRequest_PinMatrixRequestType `protobuf:"varint,1,opt,name=type,enum=hw.trezor.messages.common.PinMatrixRequest_PinMatrixRequestType" json:"type,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *PinMatrixRequest) Reset() { *m = PinMatrixRequest{} }
|
||||
func (m *PinMatrixRequest) String() string { return proto.CompactTextString(m) }
|
||||
func (*PinMatrixRequest) ProtoMessage() {}
|
||||
func (*PinMatrixRequest) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_aaf30d059fdbc38d, []int{4}
|
||||
}
|
||||
|
||||
func (m *PinMatrixRequest) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_PinMatrixRequest.Unmarshal(m, b)
|
||||
}
|
||||
func (m *PinMatrixRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_PinMatrixRequest.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (m *PinMatrixRequest) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_PinMatrixRequest.Merge(m, src)
|
||||
}
|
||||
func (m *PinMatrixRequest) XXX_Size() int {
|
||||
return xxx_messageInfo_PinMatrixRequest.Size(m)
|
||||
}
|
||||
func (m *PinMatrixRequest) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_PinMatrixRequest.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_PinMatrixRequest proto.InternalMessageInfo
|
||||
|
||||
func (m *PinMatrixRequest) GetType() PinMatrixRequest_PinMatrixRequestType {
|
||||
if m != nil && m.Type != nil {
|
||||
return *m.Type
|
||||
}
|
||||
return PinMatrixRequest_PinMatrixRequestType_Current
|
||||
}
|
||||
|
||||
//*
|
||||
// Request: Computer responds with encoded PIN
|
||||
// @auxend
|
||||
type PinMatrixAck struct {
|
||||
Pin *string `protobuf:"bytes,1,req,name=pin" json:"pin,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *PinMatrixAck) Reset() { *m = PinMatrixAck{} }
|
||||
func (m *PinMatrixAck) String() string { return proto.CompactTextString(m) }
|
||||
func (*PinMatrixAck) ProtoMessage() {}
|
||||
func (*PinMatrixAck) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_aaf30d059fdbc38d, []int{5}
|
||||
}
|
||||
|
||||
func (m *PinMatrixAck) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_PinMatrixAck.Unmarshal(m, b)
|
||||
}
|
||||
func (m *PinMatrixAck) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_PinMatrixAck.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (m *PinMatrixAck) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_PinMatrixAck.Merge(m, src)
|
||||
}
|
||||
func (m *PinMatrixAck) XXX_Size() int {
|
||||
return xxx_messageInfo_PinMatrixAck.Size(m)
|
||||
}
|
||||
func (m *PinMatrixAck) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_PinMatrixAck.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_PinMatrixAck proto.InternalMessageInfo
|
||||
|
||||
func (m *PinMatrixAck) GetPin() string {
|
||||
if m != nil && m.Pin != nil {
|
||||
return *m.Pin
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
//*
|
||||
// Response: Device awaits encryption passphrase
|
||||
// @auxstart
|
||||
// @next PassphraseAck
|
||||
type PassphraseRequest struct {
|
||||
OnDevice *bool `protobuf:"varint,1,opt,name=on_device,json=onDevice" json:"on_device,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *PassphraseRequest) Reset() { *m = PassphraseRequest{} }
|
||||
func (m *PassphraseRequest) String() string { return proto.CompactTextString(m) }
|
||||
func (*PassphraseRequest) ProtoMessage() {}
|
||||
func (*PassphraseRequest) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_aaf30d059fdbc38d, []int{6}
|
||||
}
|
||||
|
||||
func (m *PassphraseRequest) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_PassphraseRequest.Unmarshal(m, b)
|
||||
}
|
||||
func (m *PassphraseRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_PassphraseRequest.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (m *PassphraseRequest) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_PassphraseRequest.Merge(m, src)
|
||||
}
|
||||
func (m *PassphraseRequest) XXX_Size() int {
|
||||
return xxx_messageInfo_PassphraseRequest.Size(m)
|
||||
}
|
||||
func (m *PassphraseRequest) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_PassphraseRequest.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_PassphraseRequest proto.InternalMessageInfo
|
||||
|
||||
func (m *PassphraseRequest) GetOnDevice() bool {
|
||||
if m != nil && m.OnDevice != nil {
|
||||
return *m.OnDevice
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
//*
|
||||
// Request: Send passphrase back
|
||||
// @next PassphraseStateRequest
|
||||
type PassphraseAck struct {
|
||||
Passphrase *string `protobuf:"bytes,1,opt,name=passphrase" json:"passphrase,omitempty"`
|
||||
State []byte `protobuf:"bytes,2,opt,name=state" json:"state,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *PassphraseAck) Reset() { *m = PassphraseAck{} }
|
||||
func (m *PassphraseAck) String() string { return proto.CompactTextString(m) }
|
||||
func (*PassphraseAck) ProtoMessage() {}
|
||||
func (*PassphraseAck) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_aaf30d059fdbc38d, []int{7}
|
||||
}
|
||||
|
||||
func (m *PassphraseAck) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_PassphraseAck.Unmarshal(m, b)
|
||||
}
|
||||
func (m *PassphraseAck) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_PassphraseAck.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (m *PassphraseAck) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_PassphraseAck.Merge(m, src)
|
||||
}
|
||||
func (m *PassphraseAck) XXX_Size() int {
|
||||
return xxx_messageInfo_PassphraseAck.Size(m)
|
||||
}
|
||||
func (m *PassphraseAck) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_PassphraseAck.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_PassphraseAck proto.InternalMessageInfo
|
||||
|
||||
func (m *PassphraseAck) GetPassphrase() string {
|
||||
if m != nil && m.Passphrase != nil {
|
||||
return *m.Passphrase
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *PassphraseAck) GetState() []byte {
|
||||
if m != nil {
|
||||
return m.State
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//*
|
||||
// Response: Device awaits passphrase state
|
||||
// @next PassphraseStateAck
|
||||
type PassphraseStateRequest struct {
|
||||
State []byte `protobuf:"bytes,1,opt,name=state" json:"state,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *PassphraseStateRequest) Reset() { *m = PassphraseStateRequest{} }
|
||||
func (m *PassphraseStateRequest) String() string { return proto.CompactTextString(m) }
|
||||
func (*PassphraseStateRequest) ProtoMessage() {}
|
||||
func (*PassphraseStateRequest) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_aaf30d059fdbc38d, []int{8}
|
||||
}
|
||||
|
||||
func (m *PassphraseStateRequest) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_PassphraseStateRequest.Unmarshal(m, b)
|
||||
}
|
||||
func (m *PassphraseStateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_PassphraseStateRequest.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (m *PassphraseStateRequest) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_PassphraseStateRequest.Merge(m, src)
|
||||
}
|
||||
func (m *PassphraseStateRequest) XXX_Size() int {
|
||||
return xxx_messageInfo_PassphraseStateRequest.Size(m)
|
||||
}
|
||||
func (m *PassphraseStateRequest) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_PassphraseStateRequest.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_PassphraseStateRequest proto.InternalMessageInfo
|
||||
|
||||
func (m *PassphraseStateRequest) GetState() []byte {
|
||||
if m != nil {
|
||||
return m.State
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//*
|
||||
// Request: Send passphrase state back
|
||||
// @auxend
|
||||
type PassphraseStateAck struct {
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *PassphraseStateAck) Reset() { *m = PassphraseStateAck{} }
|
||||
func (m *PassphraseStateAck) String() string { return proto.CompactTextString(m) }
|
||||
func (*PassphraseStateAck) ProtoMessage() {}
|
||||
func (*PassphraseStateAck) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_aaf30d059fdbc38d, []int{9}
|
||||
}
|
||||
|
||||
func (m *PassphraseStateAck) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_PassphraseStateAck.Unmarshal(m, b)
|
||||
}
|
||||
func (m *PassphraseStateAck) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_PassphraseStateAck.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (m *PassphraseStateAck) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_PassphraseStateAck.Merge(m, src)
|
||||
}
|
||||
func (m *PassphraseStateAck) XXX_Size() int {
|
||||
return xxx_messageInfo_PassphraseStateAck.Size(m)
|
||||
}
|
||||
func (m *PassphraseStateAck) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_PassphraseStateAck.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_PassphraseStateAck proto.InternalMessageInfo
|
||||
|
||||
//*
|
||||
// Structure representing BIP32 (hierarchical deterministic) node
|
||||
// Used for imports of private key into the device and exporting public key out of device
|
||||
// @embed
|
||||
type HDNodeType struct {
|
||||
Depth *uint32 `protobuf:"varint,1,req,name=depth" json:"depth,omitempty"`
|
||||
Fingerprint *uint32 `protobuf:"varint,2,req,name=fingerprint" json:"fingerprint,omitempty"`
|
||||
ChildNum *uint32 `protobuf:"varint,3,req,name=child_num,json=childNum" json:"child_num,omitempty"`
|
||||
ChainCode []byte `protobuf:"bytes,4,req,name=chain_code,json=chainCode" json:"chain_code,omitempty"`
|
||||
PrivateKey []byte `protobuf:"bytes,5,opt,name=private_key,json=privateKey" json:"private_key,omitempty"`
|
||||
PublicKey []byte `protobuf:"bytes,6,opt,name=public_key,json=publicKey" json:"public_key,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *HDNodeType) Reset() { *m = HDNodeType{} }
|
||||
func (m *HDNodeType) String() string { return proto.CompactTextString(m) }
|
||||
func (*HDNodeType) ProtoMessage() {}
|
||||
func (*HDNodeType) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_aaf30d059fdbc38d, []int{10}
|
||||
}
|
||||
|
||||
func (m *HDNodeType) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_HDNodeType.Unmarshal(m, b)
|
||||
}
|
||||
func (m *HDNodeType) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_HDNodeType.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (m *HDNodeType) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_HDNodeType.Merge(m, src)
|
||||
}
|
||||
func (m *HDNodeType) XXX_Size() int {
|
||||
return xxx_messageInfo_HDNodeType.Size(m)
|
||||
}
|
||||
func (m *HDNodeType) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_HDNodeType.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_HDNodeType proto.InternalMessageInfo
|
||||
|
||||
func (m *HDNodeType) GetDepth() uint32 {
|
||||
if m != nil && m.Depth != nil {
|
||||
return *m.Depth
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *HDNodeType) GetFingerprint() uint32 {
|
||||
if m != nil && m.Fingerprint != nil {
|
||||
return *m.Fingerprint
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *HDNodeType) GetChildNum() uint32 {
|
||||
if m != nil && m.ChildNum != nil {
|
||||
return *m.ChildNum
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *HDNodeType) GetChainCode() []byte {
|
||||
if m != nil {
|
||||
return m.ChainCode
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *HDNodeType) GetPrivateKey() []byte {
|
||||
if m != nil {
|
||||
return m.PrivateKey
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *HDNodeType) GetPublicKey() []byte {
|
||||
if m != nil {
|
||||
return m.PublicKey
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
proto.RegisterEnum("hw.trezor.messages.common.Failure_FailureType", Failure_FailureType_name, Failure_FailureType_value)
|
||||
proto.RegisterEnum("hw.trezor.messages.common.ButtonRequest_ButtonRequestType", ButtonRequest_ButtonRequestType_name, ButtonRequest_ButtonRequestType_value)
|
||||
proto.RegisterEnum("hw.trezor.messages.common.PinMatrixRequest_PinMatrixRequestType", PinMatrixRequest_PinMatrixRequestType_name, PinMatrixRequest_PinMatrixRequestType_value)
|
||||
proto.RegisterType((*Success)(nil), "hw.trezor.messages.common.Success")
|
||||
proto.RegisterType((*Failure)(nil), "hw.trezor.messages.common.Failure")
|
||||
proto.RegisterType((*ButtonRequest)(nil), "hw.trezor.messages.common.ButtonRequest")
|
||||
proto.RegisterType((*ButtonAck)(nil), "hw.trezor.messages.common.ButtonAck")
|
||||
proto.RegisterType((*PinMatrixRequest)(nil), "hw.trezor.messages.common.PinMatrixRequest")
|
||||
proto.RegisterType((*PinMatrixAck)(nil), "hw.trezor.messages.common.PinMatrixAck")
|
||||
proto.RegisterType((*PassphraseRequest)(nil), "hw.trezor.messages.common.PassphraseRequest")
|
||||
proto.RegisterType((*PassphraseAck)(nil), "hw.trezor.messages.common.PassphraseAck")
|
||||
proto.RegisterType((*PassphraseStateRequest)(nil), "hw.trezor.messages.common.PassphraseStateRequest")
|
||||
proto.RegisterType((*PassphraseStateAck)(nil), "hw.trezor.messages.common.PassphraseStateAck")
|
||||
proto.RegisterType((*HDNodeType)(nil), "hw.trezor.messages.common.HDNodeType")
|
||||
}
|
||||
|
||||
func init() { proto.RegisterFile("messages-common.proto", fileDescriptor_aaf30d059fdbc38d) }
|
||||
|
||||
var fileDescriptor_aaf30d059fdbc38d = []byte{
|
||||
// 846 bytes of a gzipped FileDescriptorProto
|
||||
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x54, 0xcd, 0x52, 0x23, 0x37,
|
||||
0x10, 0x2e, 0xff, 0x80, 0xed, 0xb6, 0xd9, 0x08, 0xc5, 0x80, 0x09, 0xb0, 0x38, 0xc3, 0x21, 0x5c,
|
||||
0xe2, 0x4a, 0xe5, 0x98, 0x53, 0x58, 0x83, 0x2b, 0xd4, 0x16, 0x86, 0x1a, 0xd8, 0xda, 0xa3, 0x4b,
|
||||
0xd1, 0xf4, 0x32, 0x2a, 0xcf, 0x48, 0x13, 0x8d, 0x06, 0xf0, 0x5e, 0xf2, 0x6a, 0x79, 0x89, 0xbc,
|
||||
0x42, 0xaa, 0x52, 0xb9, 0xe4, 0x11, 0xb6, 0x34, 0x3f, 0x78, 0xc6, 0x66, 0x39, 0xcd, 0xe8, 0xfb,
|
||||
0xbe, 0xee, 0x96, 0xba, 0x3f, 0x09, 0x76, 0x42, 0x8c, 0x63, 0x76, 0x8f, 0xf1, 0x8f, 0x5c, 0x85,
|
||||
0xa1, 0x92, 0xa3, 0x48, 0x2b, 0xa3, 0xe8, 0xbe, 0xff, 0x38, 0x32, 0x1a, 0x3f, 0x2b, 0x3d, 0x2a,
|
||||
0x04, 0xa3, 0x4c, 0xe0, 0x9c, 0x40, 0xeb, 0x36, 0xe1, 0x1c, 0xe3, 0x98, 0x0e, 0xa0, 0x95, 0xb3,
|
||||
0x83, 0xda, 0xb0, 0x76, 0xda, 0x71, 0x8b, 0xa5, 0xf3, 0x77, 0x03, 0x5a, 0x13, 0x26, 0x82, 0x44,
|
||||
0x23, 0x7d, 0x07, 0x4d, 0xae, 0xbc, 0x4c, 0xf2, 0xe6, 0xe7, 0xd1, 0xe8, 0xab, 0xa9, 0x47, 0x79,
|
||||
0x44, 0xf1, 0xbd, 0x5b, 0x44, 0xe8, 0xa6, 0xb1, 0xe5, 0x4a, 0xf5, 0x6a, 0xa5, 0xff, 0xea, 0xd0,
|
||||
0x2d, 0xe9, 0xe9, 0x11, 0xec, 0xe7, 0xcb, 0xd9, 0x07, 0x89, 0x4f, 0x11, 0x72, 0x83, 0xde, 0x55,
|
||||
0x26, 0x26, 0x35, 0xfa, 0x1d, 0xec, 0x16, 0xf4, 0xbb, 0xc4, 0x18, 0x25, 0x2f, 0x72, 0x09, 0xa9,
|
||||
0xd3, 0x1d, 0xd8, 0x2e, 0xb8, 0x73, 0x66, 0xd8, 0x85, 0xd6, 0x4a, 0x93, 0x06, 0x3d, 0x80, 0xbd,
|
||||
0x02, 0x3e, 0xe3, 0x46, 0x28, 0x39, 0x66, 0x92, 0x63, 0x10, 0xa0, 0x47, 0x9a, 0x74, 0x0f, 0xbe,
|
||||
0x2d, 0xc8, 0x1b, 0xb1, 0x4c, 0xb6, 0x41, 0x07, 0xd0, 0x2f, 0x11, 0xcb, 0x90, 0x4d, 0xba, 0x0b,
|
||||
0xb4, 0xc4, 0x5c, 0xca, 0x07, 0x16, 0x08, 0x8f, 0xb4, 0xe8, 0x21, 0x0c, 0x0a, 0x3c, 0x07, 0x6f,
|
||||
0xc5, 0xbd, 0x64, 0x26, 0xd1, 0x48, 0xda, 0x95, 0x7c, 0x5a, 0xd9, 0xf6, 0x67, 0xfb, 0xeb, 0x94,
|
||||
0x8f, 0x34, 0x55, 0xe6, 0x42, 0xaa, 0xe4, 0xde, 0x9f, 0x24, 0xd2, 0x8b, 0x09, 0xac, 0x70, 0x97,
|
||||
0x52, 0x18, 0xc1, 0x02, 0xf1, 0x19, 0x3d, 0xd2, 0x5d, 0xd9, 0xfa, 0x95, 0x88, 0x43, 0x66, 0xb8,
|
||||
0x4f, 0x7a, 0x74, 0x1f, 0x76, 0x0a, 0x62, 0x22, 0x74, 0xf8, 0xc8, 0x34, 0x66, 0xb5, 0xb8, 0xf3,
|
||||
0x4f, 0x13, 0xb6, 0xb2, 0xbe, 0xb9, 0xf8, 0x47, 0x82, 0xb1, 0xa1, 0xd3, 0xca, 0x74, 0x7f, 0x79,
|
||||
0x65, 0xba, 0x95, 0xb8, 0xea, 0xaa, 0x34, 0x69, 0x0a, 0x4d, 0x8f, 0x19, 0x96, 0x8f, 0x39, 0xfd,
|
||||
0x77, 0xfe, 0x6f, 0xc0, 0xf6, 0x9a, 0xde, 0xee, 0xbf, 0x02, 0xce, 0xae, 0x8d, 0x8f, 0x9a, 0xd4,
|
||||
0xa8, 0x03, 0x6f, 0xab, 0xc4, 0x04, 0xf1, 0xfa, 0x01, 0xf5, 0x9d, 0xaf, 0x31, 0xf6, 0x55, 0x60,
|
||||
0x67, 0x7d, 0x0c, 0x07, 0x55, 0xcd, 0x58, 0xc9, 0x4f, 0x42, 0x87, 0xd7, 0x89, 0x89, 0x12, 0x43,
|
||||
0x1a, 0xd6, 0x47, 0x55, 0x81, 0x8b, 0x31, 0x9a, 0x73, 0x7c, 0x10, 0x1c, 0x49, 0x73, 0x9d, 0xce,
|
||||
0xe3, 0x3f, 0x2a, 0x6d, 0xa7, 0x7f, 0x08, 0x83, 0x2a, 0xfd, 0x51, 0x44, 0x98, 0x07, 0x6f, 0xae,
|
||||
0x07, 0xdf, 0x68, 0x65, 0x90, 0x9b, 0x31, 0x0b, 0x02, 0xd2, 0xb2, 0xa3, 0xae, 0xd2, 0xd6, 0x07,
|
||||
0x77, 0x4f, 0xa4, 0xbd, 0xbe, 0xeb, 0x62, 0x3e, 0x63, 0x1f, 0xf9, 0x9c, 0x74, 0xec, 0xe8, 0xaa,
|
||||
0x82, 0x33, 0xcf, 0xd3, 0x18, 0x5b, 0x2b, 0x1c, 0xc0, 0xde, 0x4a, 0xd1, 0xe4, 0xf7, 0x40, 0xf0,
|
||||
0xf7, 0xb8, 0x20, 0x5d, 0x7a, 0x02, 0xc7, 0x55, 0xf2, 0x4a, 0x62, 0xa8, 0xa4, 0xe0, 0xf6, 0x3c,
|
||||
0x63, 0x95, 0x48, 0x43, 0x7a, 0xeb, 0xd5, 0x0b, 0xd1, 0xa5, 0xb4, 0x3d, 0xdb, 0xa2, 0x43, 0x38,
|
||||
0x5c, 0x29, 0xc1, 0xe2, 0x38, 0xf2, 0x35, 0x8b, 0xd3, 0xbb, 0x49, 0xde, 0xd0, 0x1f, 0xe0, 0xa4,
|
||||
0xaa, 0xf8, 0x20, 0xe7, 0x52, 0x3d, 0xca, 0x73, 0xd4, 0xe2, 0x81, 0xd9, 0xcb, 0x75, 0xc3, 0x8c,
|
||||
0x4f, 0xbe, 0x71, 0xba, 0xd0, 0xc9, 0x84, 0x67, 0x7c, 0xee, 0xfc, 0x5b, 0x03, 0x62, 0x2d, 0xca,
|
||||
0x8c, 0x16, 0x4f, 0x85, 0xf1, 0xee, 0xa0, 0x69, 0x16, 0x51, 0x61, 0xbc, 0x5f, 0x5f, 0x31, 0xde,
|
||||
0x6a, 0xe8, 0x1a, 0x90, 0xd9, 0xcf, 0x66, 0x73, 0xfe, 0x84, 0xfe, 0x4b, 0xac, 0x3d, 0xda, 0x4b,
|
||||
0xf8, 0x6c, 0x9c, 0x68, 0x8d, 0xd2, 0x90, 0x1a, 0xfd, 0x1e, 0x8e, 0x5e, 0x54, 0x4c, 0xf1, 0x71,
|
||||
0x22, 0x74, 0x6c, 0x48, 0xdd, 0x1a, 0xf3, 0x6b, 0x92, 0x5b, 0xe4, 0x4a, 0x7a, 0xa4, 0xe1, 0x0c,
|
||||
0xa1, 0xf7, 0xac, 0x39, 0xe3, 0x73, 0x4a, 0xa0, 0x11, 0x09, 0x39, 0xa8, 0x0d, 0xeb, 0xa7, 0x1d,
|
||||
0xd7, 0xfe, 0x3a, 0x3f, 0xc1, 0xf6, 0xb2, 0xaf, 0x45, 0x37, 0x0e, 0xa0, 0xa3, 0xe4, 0xcc, 0x4b,
|
||||
0x1d, 0x96, 0xb6, 0xa4, 0xed, 0xb6, 0x95, 0xcc, 0x1c, 0xe7, 0x5c, 0xc0, 0xd6, 0x32, 0xc2, 0x26,
|
||||
0x7d, 0x0b, 0x10, 0x3d, 0x03, 0xf9, 0xdb, 0x5d, 0x42, 0x68, 0x1f, 0x36, 0x62, 0xc3, 0x4c, 0xf6,
|
||||
0xd8, 0xf6, 0xdc, 0x6c, 0xe1, 0x8c, 0x60, 0x77, 0x99, 0xe6, 0xd6, 0x42, 0x45, 0xf5, 0x67, 0x7d,
|
||||
0xad, 0xac, 0xef, 0x03, 0x5d, 0xd1, 0xdb, 0x61, 0xfe, 0x55, 0x03, 0xf8, 0xed, 0x7c, 0xaa, 0xbc,
|
||||
0xec, 0xbd, 0xee, 0xc3, 0x86, 0x87, 0x91, 0xf1, 0xd3, 0x13, 0x6e, 0xb9, 0xd9, 0x82, 0x0e, 0xa1,
|
||||
0xfb, 0x49, 0xc8, 0x7b, 0xd4, 0x91, 0x16, 0xd2, 0x0c, 0xea, 0x29, 0x57, 0x86, 0xec, 0x81, 0xb9,
|
||||
0x2f, 0x02, 0x6f, 0x26, 0x93, 0x70, 0xd0, 0x48, 0xf9, 0x76, 0x0a, 0x4c, 0x93, 0x90, 0x1e, 0x01,
|
||||
0x70, 0x9f, 0x09, 0x39, 0x4b, 0x9f, 0xa6, 0xe6, 0xb0, 0x7e, 0xda, 0x73, 0x3b, 0x29, 0x32, 0xb6,
|
||||
0x6f, 0xcc, 0x31, 0x74, 0xa3, 0xd4, 0x6f, 0x38, 0x9b, 0xe3, 0x62, 0xb0, 0x91, 0x6e, 0x1a, 0x72,
|
||||
0xe8, 0x3d, 0x2e, 0x6c, 0x7c, 0x94, 0xde, 0x8e, 0x94, 0xdf, 0x4c, 0xf9, 0x4e, 0x54, 0xdc, 0x97,
|
||||
0x2f, 0x01, 0x00, 0x00, 0xff, 0xff, 0xb2, 0x7d, 0x20, 0xa6, 0x35, 0x07, 0x00, 0x00,
|
||||
}
|
147
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/trezor/messages-common.proto
generated
vendored
Normal file
147
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/trezor/messages-common.proto
generated
vendored
Normal file
@ -0,0 +1,147 @@
|
||||
// This file originates from the SatoshiLabs Trezor `common` repository at:
|
||||
// https://github.com/trezor/trezor-common/blob/master/protob/messages-common.proto
|
||||
// dated 28.05.2019, commit 893fd219d4a01bcffa0cd9cfa631856371ec5aa9.
|
||||
|
||||
syntax = "proto2";
|
||||
package hw.trezor.messages.common;
|
||||
|
||||
/**
|
||||
* Response: Success of the previous request
|
||||
* @end
|
||||
*/
|
||||
message Success {
|
||||
optional string message = 1; // human readable description of action or request-specific payload
|
||||
}
|
||||
|
||||
/**
|
||||
* Response: Failure of the previous request
|
||||
* @end
|
||||
*/
|
||||
message Failure {
|
||||
optional FailureType code = 1; // computer-readable definition of the error state
|
||||
optional string message = 2; // human-readable message of the error state
|
||||
enum FailureType {
|
||||
Failure_UnexpectedMessage = 1;
|
||||
Failure_ButtonExpected = 2;
|
||||
Failure_DataError = 3;
|
||||
Failure_ActionCancelled = 4;
|
||||
Failure_PinExpected = 5;
|
||||
Failure_PinCancelled = 6;
|
||||
Failure_PinInvalid = 7;
|
||||
Failure_InvalidSignature = 8;
|
||||
Failure_ProcessError = 9;
|
||||
Failure_NotEnoughFunds = 10;
|
||||
Failure_NotInitialized = 11;
|
||||
Failure_PinMismatch = 12;
|
||||
Failure_FirmwareError = 99;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Response: Device is waiting for HW button press.
|
||||
* @auxstart
|
||||
* @next ButtonAck
|
||||
*/
|
||||
message ButtonRequest {
|
||||
optional ButtonRequestType code = 1;
|
||||
optional string data = 2;
|
||||
/**
|
||||
* Type of button request
|
||||
*/
|
||||
enum ButtonRequestType {
|
||||
ButtonRequest_Other = 1;
|
||||
ButtonRequest_FeeOverThreshold = 2;
|
||||
ButtonRequest_ConfirmOutput = 3;
|
||||
ButtonRequest_ResetDevice = 4;
|
||||
ButtonRequest_ConfirmWord = 5;
|
||||
ButtonRequest_WipeDevice = 6;
|
||||
ButtonRequest_ProtectCall = 7;
|
||||
ButtonRequest_SignTx = 8;
|
||||
ButtonRequest_FirmwareCheck = 9;
|
||||
ButtonRequest_Address = 10;
|
||||
ButtonRequest_PublicKey = 11;
|
||||
ButtonRequest_MnemonicWordCount = 12;
|
||||
ButtonRequest_MnemonicInput = 13;
|
||||
ButtonRequest_PassphraseType = 14;
|
||||
ButtonRequest_UnknownDerivationPath = 15;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: Computer agrees to wait for HW button press
|
||||
* @auxend
|
||||
*/
|
||||
message ButtonAck {
|
||||
}
|
||||
|
||||
/**
|
||||
* Response: Device is asking computer to show PIN matrix and awaits PIN encoded using this matrix scheme
|
||||
* @auxstart
|
||||
* @next PinMatrixAck
|
||||
*/
|
||||
message PinMatrixRequest {
|
||||
optional PinMatrixRequestType type = 1;
|
||||
/**
|
||||
* Type of PIN request
|
||||
*/
|
||||
enum PinMatrixRequestType {
|
||||
PinMatrixRequestType_Current = 1;
|
||||
PinMatrixRequestType_NewFirst = 2;
|
||||
PinMatrixRequestType_NewSecond = 3;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: Computer responds with encoded PIN
|
||||
* @auxend
|
||||
*/
|
||||
message PinMatrixAck {
|
||||
required string pin = 1; // matrix encoded PIN entered by user
|
||||
}
|
||||
|
||||
/**
|
||||
* Response: Device awaits encryption passphrase
|
||||
* @auxstart
|
||||
* @next PassphraseAck
|
||||
*/
|
||||
message PassphraseRequest {
|
||||
optional bool on_device = 1; // passphrase is being entered on the device
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: Send passphrase back
|
||||
* @next PassphraseStateRequest
|
||||
*/
|
||||
message PassphraseAck {
|
||||
optional string passphrase = 1;
|
||||
optional bytes state = 2; // expected device state
|
||||
}
|
||||
|
||||
/**
|
||||
* Response: Device awaits passphrase state
|
||||
* @next PassphraseStateAck
|
||||
*/
|
||||
message PassphraseStateRequest {
|
||||
optional bytes state = 1; // actual device state
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: Send passphrase state back
|
||||
* @auxend
|
||||
*/
|
||||
message PassphraseStateAck {
|
||||
}
|
||||
|
||||
/**
|
||||
* Structure representing BIP32 (hierarchical deterministic) node
|
||||
* Used for imports of private key into the device and exporting public key out of device
|
||||
* @embed
|
||||
*/
|
||||
message HDNodeType {
|
||||
required uint32 depth = 1;
|
||||
required uint32 fingerprint = 2;
|
||||
required uint32 child_num = 3;
|
||||
required bytes chain_code = 4;
|
||||
optional bytes private_key = 5;
|
||||
optional bytes public_key = 6;
|
||||
}
|
698
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/trezor/messages-ethereum.pb.go
generated
vendored
Normal file
698
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/trezor/messages-ethereum.pb.go
generated
vendored
Normal file
@ -0,0 +1,698 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// source: messages-ethereum.proto
|
||||
|
||||
package trezor
|
||||
|
||||
import (
|
||||
fmt "fmt"
|
||||
math "math"
|
||||
|
||||
proto "github.com/golang/protobuf/proto"
|
||||
)
|
||||
|
||||
// Reference imports to suppress errors if they are not otherwise used.
|
||||
var _ = proto.Marshal
|
||||
var _ = fmt.Errorf
|
||||
var _ = math.Inf
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the proto package it is being compiled against.
|
||||
// A compilation error at this line likely means your copy of the
|
||||
// proto package needs to be updated.
|
||||
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
|
||||
|
||||
//*
|
||||
// Request: Ask device for public key corresponding to address_n path
|
||||
// @start
|
||||
// @next EthereumPublicKey
|
||||
// @next Failure
|
||||
type EthereumGetPublicKey struct {
|
||||
AddressN []uint32 `protobuf:"varint,1,rep,name=address_n,json=addressN" json:"address_n,omitempty"`
|
||||
ShowDisplay *bool `protobuf:"varint,2,opt,name=show_display,json=showDisplay" json:"show_display,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *EthereumGetPublicKey) Reset() { *m = EthereumGetPublicKey{} }
|
||||
func (m *EthereumGetPublicKey) String() string { return proto.CompactTextString(m) }
|
||||
func (*EthereumGetPublicKey) ProtoMessage() {}
|
||||
func (*EthereumGetPublicKey) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_cb33f46ba915f15c, []int{0}
|
||||
}
|
||||
|
||||
func (m *EthereumGetPublicKey) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_EthereumGetPublicKey.Unmarshal(m, b)
|
||||
}
|
||||
func (m *EthereumGetPublicKey) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_EthereumGetPublicKey.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (m *EthereumGetPublicKey) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_EthereumGetPublicKey.Merge(m, src)
|
||||
}
|
||||
func (m *EthereumGetPublicKey) XXX_Size() int {
|
||||
return xxx_messageInfo_EthereumGetPublicKey.Size(m)
|
||||
}
|
||||
func (m *EthereumGetPublicKey) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_EthereumGetPublicKey.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_EthereumGetPublicKey proto.InternalMessageInfo
|
||||
|
||||
func (m *EthereumGetPublicKey) GetAddressN() []uint32 {
|
||||
if m != nil {
|
||||
return m.AddressN
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *EthereumGetPublicKey) GetShowDisplay() bool {
|
||||
if m != nil && m.ShowDisplay != nil {
|
||||
return *m.ShowDisplay
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
//*
|
||||
// Response: Contains public key derived from device private seed
|
||||
// @end
|
||||
type EthereumPublicKey struct {
|
||||
Node *HDNodeType `protobuf:"bytes,1,opt,name=node" json:"node,omitempty"`
|
||||
Xpub *string `protobuf:"bytes,2,opt,name=xpub" json:"xpub,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *EthereumPublicKey) Reset() { *m = EthereumPublicKey{} }
|
||||
func (m *EthereumPublicKey) String() string { return proto.CompactTextString(m) }
|
||||
func (*EthereumPublicKey) ProtoMessage() {}
|
||||
func (*EthereumPublicKey) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_cb33f46ba915f15c, []int{1}
|
||||
}
|
||||
|
||||
func (m *EthereumPublicKey) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_EthereumPublicKey.Unmarshal(m, b)
|
||||
}
|
||||
func (m *EthereumPublicKey) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_EthereumPublicKey.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (m *EthereumPublicKey) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_EthereumPublicKey.Merge(m, src)
|
||||
}
|
||||
func (m *EthereumPublicKey) XXX_Size() int {
|
||||
return xxx_messageInfo_EthereumPublicKey.Size(m)
|
||||
}
|
||||
func (m *EthereumPublicKey) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_EthereumPublicKey.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_EthereumPublicKey proto.InternalMessageInfo
|
||||
|
||||
func (m *EthereumPublicKey) GetNode() *HDNodeType {
|
||||
if m != nil {
|
||||
return m.Node
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *EthereumPublicKey) GetXpub() string {
|
||||
if m != nil && m.Xpub != nil {
|
||||
return *m.Xpub
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
//*
|
||||
// Request: Ask device for Ethereum address corresponding to address_n path
|
||||
// @start
|
||||
// @next EthereumAddress
|
||||
// @next Failure
|
||||
type EthereumGetAddress struct {
|
||||
AddressN []uint32 `protobuf:"varint,1,rep,name=address_n,json=addressN" json:"address_n,omitempty"`
|
||||
ShowDisplay *bool `protobuf:"varint,2,opt,name=show_display,json=showDisplay" json:"show_display,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *EthereumGetAddress) Reset() { *m = EthereumGetAddress{} }
|
||||
func (m *EthereumGetAddress) String() string { return proto.CompactTextString(m) }
|
||||
func (*EthereumGetAddress) ProtoMessage() {}
|
||||
func (*EthereumGetAddress) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_cb33f46ba915f15c, []int{2}
|
||||
}
|
||||
|
||||
func (m *EthereumGetAddress) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_EthereumGetAddress.Unmarshal(m, b)
|
||||
}
|
||||
func (m *EthereumGetAddress) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_EthereumGetAddress.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (m *EthereumGetAddress) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_EthereumGetAddress.Merge(m, src)
|
||||
}
|
||||
func (m *EthereumGetAddress) XXX_Size() int {
|
||||
return xxx_messageInfo_EthereumGetAddress.Size(m)
|
||||
}
|
||||
func (m *EthereumGetAddress) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_EthereumGetAddress.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_EthereumGetAddress proto.InternalMessageInfo
|
||||
|
||||
func (m *EthereumGetAddress) GetAddressN() []uint32 {
|
||||
if m != nil {
|
||||
return m.AddressN
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *EthereumGetAddress) GetShowDisplay() bool {
|
||||
if m != nil && m.ShowDisplay != nil {
|
||||
return *m.ShowDisplay
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
//*
|
||||
// Response: Contains an Ethereum address derived from device private seed
|
||||
// @end
|
||||
type EthereumAddress struct {
|
||||
AddressBin []byte `protobuf:"bytes,1,opt,name=addressBin" json:"addressBin,omitempty"`
|
||||
AddressHex *string `protobuf:"bytes,2,opt,name=addressHex" json:"addressHex,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *EthereumAddress) Reset() { *m = EthereumAddress{} }
|
||||
func (m *EthereumAddress) String() string { return proto.CompactTextString(m) }
|
||||
func (*EthereumAddress) ProtoMessage() {}
|
||||
func (*EthereumAddress) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_cb33f46ba915f15c, []int{3}
|
||||
}
|
||||
|
||||
func (m *EthereumAddress) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_EthereumAddress.Unmarshal(m, b)
|
||||
}
|
||||
func (m *EthereumAddress) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_EthereumAddress.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (m *EthereumAddress) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_EthereumAddress.Merge(m, src)
|
||||
}
|
||||
func (m *EthereumAddress) XXX_Size() int {
|
||||
return xxx_messageInfo_EthereumAddress.Size(m)
|
||||
}
|
||||
func (m *EthereumAddress) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_EthereumAddress.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_EthereumAddress proto.InternalMessageInfo
|
||||
|
||||
func (m *EthereumAddress) GetAddressBin() []byte {
|
||||
if m != nil {
|
||||
return m.AddressBin
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *EthereumAddress) GetAddressHex() string {
|
||||
if m != nil && m.AddressHex != nil {
|
||||
return *m.AddressHex
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
//*
|
||||
// Request: Ask device to sign transaction
|
||||
// All fields are optional from the protocol's point of view. Each field defaults to value `0` if missing.
|
||||
// Note: the first at most 1024 bytes of data MUST be transmitted as part of this message.
|
||||
// @start
|
||||
// @next EthereumTxRequest
|
||||
// @next Failure
|
||||
type EthereumSignTx struct {
|
||||
AddressN []uint32 `protobuf:"varint,1,rep,name=address_n,json=addressN" json:"address_n,omitempty"`
|
||||
Nonce []byte `protobuf:"bytes,2,opt,name=nonce" json:"nonce,omitempty"`
|
||||
GasPrice []byte `protobuf:"bytes,3,opt,name=gas_price,json=gasPrice" json:"gas_price,omitempty"`
|
||||
GasLimit []byte `protobuf:"bytes,4,opt,name=gas_limit,json=gasLimit" json:"gas_limit,omitempty"`
|
||||
ToBin []byte `protobuf:"bytes,5,opt,name=toBin" json:"toBin,omitempty"`
|
||||
ToHex *string `protobuf:"bytes,11,opt,name=toHex" json:"toHex,omitempty"`
|
||||
Value []byte `protobuf:"bytes,6,opt,name=value" json:"value,omitempty"`
|
||||
DataInitialChunk []byte `protobuf:"bytes,7,opt,name=data_initial_chunk,json=dataInitialChunk" json:"data_initial_chunk,omitempty"`
|
||||
DataLength *uint32 `protobuf:"varint,8,opt,name=data_length,json=dataLength" json:"data_length,omitempty"`
|
||||
ChainId *uint32 `protobuf:"varint,9,opt,name=chain_id,json=chainId" json:"chain_id,omitempty"`
|
||||
TxType *uint32 `protobuf:"varint,10,opt,name=tx_type,json=txType" json:"tx_type,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *EthereumSignTx) Reset() { *m = EthereumSignTx{} }
|
||||
func (m *EthereumSignTx) String() string { return proto.CompactTextString(m) }
|
||||
func (*EthereumSignTx) ProtoMessage() {}
|
||||
func (*EthereumSignTx) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_cb33f46ba915f15c, []int{4}
|
||||
}
|
||||
|
||||
func (m *EthereumSignTx) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_EthereumSignTx.Unmarshal(m, b)
|
||||
}
|
||||
func (m *EthereumSignTx) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_EthereumSignTx.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (m *EthereumSignTx) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_EthereumSignTx.Merge(m, src)
|
||||
}
|
||||
func (m *EthereumSignTx) XXX_Size() int {
|
||||
return xxx_messageInfo_EthereumSignTx.Size(m)
|
||||
}
|
||||
func (m *EthereumSignTx) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_EthereumSignTx.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_EthereumSignTx proto.InternalMessageInfo
|
||||
|
||||
func (m *EthereumSignTx) GetAddressN() []uint32 {
|
||||
if m != nil {
|
||||
return m.AddressN
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *EthereumSignTx) GetNonce() []byte {
|
||||
if m != nil {
|
||||
return m.Nonce
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *EthereumSignTx) GetGasPrice() []byte {
|
||||
if m != nil {
|
||||
return m.GasPrice
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *EthereumSignTx) GetGasLimit() []byte {
|
||||
if m != nil {
|
||||
return m.GasLimit
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *EthereumSignTx) GetToBin() []byte {
|
||||
if m != nil {
|
||||
return m.ToBin
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *EthereumSignTx) GetToHex() string {
|
||||
if m != nil && m.ToHex != nil {
|
||||
return *m.ToHex
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *EthereumSignTx) GetValue() []byte {
|
||||
if m != nil {
|
||||
return m.Value
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *EthereumSignTx) GetDataInitialChunk() []byte {
|
||||
if m != nil {
|
||||
return m.DataInitialChunk
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *EthereumSignTx) GetDataLength() uint32 {
|
||||
if m != nil && m.DataLength != nil {
|
||||
return *m.DataLength
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *EthereumSignTx) GetChainId() uint32 {
|
||||
if m != nil && m.ChainId != nil {
|
||||
return *m.ChainId
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *EthereumSignTx) GetTxType() uint32 {
|
||||
if m != nil && m.TxType != nil {
|
||||
return *m.TxType
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
//*
|
||||
// Response: Device asks for more data from transaction payload, or returns the signature.
|
||||
// If data_length is set, device awaits that many more bytes of payload.
|
||||
// Otherwise, the signature_* fields contain the computed transaction signature. All three fields will be present.
|
||||
// @end
|
||||
// @next EthereumTxAck
|
||||
type EthereumTxRequest struct {
|
||||
DataLength *uint32 `protobuf:"varint,1,opt,name=data_length,json=dataLength" json:"data_length,omitempty"`
|
||||
SignatureV *uint32 `protobuf:"varint,2,opt,name=signature_v,json=signatureV" json:"signature_v,omitempty"`
|
||||
SignatureR []byte `protobuf:"bytes,3,opt,name=signature_r,json=signatureR" json:"signature_r,omitempty"`
|
||||
SignatureS []byte `protobuf:"bytes,4,opt,name=signature_s,json=signatureS" json:"signature_s,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *EthereumTxRequest) Reset() { *m = EthereumTxRequest{} }
|
||||
func (m *EthereumTxRequest) String() string { return proto.CompactTextString(m) }
|
||||
func (*EthereumTxRequest) ProtoMessage() {}
|
||||
func (*EthereumTxRequest) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_cb33f46ba915f15c, []int{5}
|
||||
}
|
||||
|
||||
func (m *EthereumTxRequest) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_EthereumTxRequest.Unmarshal(m, b)
|
||||
}
|
||||
func (m *EthereumTxRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_EthereumTxRequest.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (m *EthereumTxRequest) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_EthereumTxRequest.Merge(m, src)
|
||||
}
|
||||
func (m *EthereumTxRequest) XXX_Size() int {
|
||||
return xxx_messageInfo_EthereumTxRequest.Size(m)
|
||||
}
|
||||
func (m *EthereumTxRequest) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_EthereumTxRequest.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_EthereumTxRequest proto.InternalMessageInfo
|
||||
|
||||
func (m *EthereumTxRequest) GetDataLength() uint32 {
|
||||
if m != nil && m.DataLength != nil {
|
||||
return *m.DataLength
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *EthereumTxRequest) GetSignatureV() uint32 {
|
||||
if m != nil && m.SignatureV != nil {
|
||||
return *m.SignatureV
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *EthereumTxRequest) GetSignatureR() []byte {
|
||||
if m != nil {
|
||||
return m.SignatureR
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *EthereumTxRequest) GetSignatureS() []byte {
|
||||
if m != nil {
|
||||
return m.SignatureS
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//*
|
||||
// Request: Transaction payload data.
|
||||
// @next EthereumTxRequest
|
||||
type EthereumTxAck struct {
|
||||
DataChunk []byte `protobuf:"bytes,1,opt,name=data_chunk,json=dataChunk" json:"data_chunk,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *EthereumTxAck) Reset() { *m = EthereumTxAck{} }
|
||||
func (m *EthereumTxAck) String() string { return proto.CompactTextString(m) }
|
||||
func (*EthereumTxAck) ProtoMessage() {}
|
||||
func (*EthereumTxAck) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_cb33f46ba915f15c, []int{6}
|
||||
}
|
||||
|
||||
func (m *EthereumTxAck) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_EthereumTxAck.Unmarshal(m, b)
|
||||
}
|
||||
func (m *EthereumTxAck) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_EthereumTxAck.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (m *EthereumTxAck) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_EthereumTxAck.Merge(m, src)
|
||||
}
|
||||
func (m *EthereumTxAck) XXX_Size() int {
|
||||
return xxx_messageInfo_EthereumTxAck.Size(m)
|
||||
}
|
||||
func (m *EthereumTxAck) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_EthereumTxAck.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_EthereumTxAck proto.InternalMessageInfo
|
||||
|
||||
func (m *EthereumTxAck) GetDataChunk() []byte {
|
||||
if m != nil {
|
||||
return m.DataChunk
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//*
|
||||
// Request: Ask device to sign message
|
||||
// @start
|
||||
// @next EthereumMessageSignature
|
||||
// @next Failure
|
||||
type EthereumSignMessage struct {
|
||||
AddressN []uint32 `protobuf:"varint,1,rep,name=address_n,json=addressN" json:"address_n,omitempty"`
|
||||
Message []byte `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *EthereumSignMessage) Reset() { *m = EthereumSignMessage{} }
|
||||
func (m *EthereumSignMessage) String() string { return proto.CompactTextString(m) }
|
||||
func (*EthereumSignMessage) ProtoMessage() {}
|
||||
func (*EthereumSignMessage) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_cb33f46ba915f15c, []int{7}
|
||||
}
|
||||
|
||||
func (m *EthereumSignMessage) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_EthereumSignMessage.Unmarshal(m, b)
|
||||
}
|
||||
func (m *EthereumSignMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_EthereumSignMessage.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (m *EthereumSignMessage) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_EthereumSignMessage.Merge(m, src)
|
||||
}
|
||||
func (m *EthereumSignMessage) XXX_Size() int {
|
||||
return xxx_messageInfo_EthereumSignMessage.Size(m)
|
||||
}
|
||||
func (m *EthereumSignMessage) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_EthereumSignMessage.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_EthereumSignMessage proto.InternalMessageInfo
|
||||
|
||||
func (m *EthereumSignMessage) GetAddressN() []uint32 {
|
||||
if m != nil {
|
||||
return m.AddressN
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *EthereumSignMessage) GetMessage() []byte {
|
||||
if m != nil {
|
||||
return m.Message
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//*
|
||||
// Response: Signed message
|
||||
// @end
|
||||
type EthereumMessageSignature struct {
|
||||
AddressBin []byte `protobuf:"bytes,1,opt,name=addressBin" json:"addressBin,omitempty"`
|
||||
Signature []byte `protobuf:"bytes,2,opt,name=signature" json:"signature,omitempty"`
|
||||
AddressHex *string `protobuf:"bytes,3,opt,name=addressHex" json:"addressHex,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *EthereumMessageSignature) Reset() { *m = EthereumMessageSignature{} }
|
||||
func (m *EthereumMessageSignature) String() string { return proto.CompactTextString(m) }
|
||||
func (*EthereumMessageSignature) ProtoMessage() {}
|
||||
func (*EthereumMessageSignature) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_cb33f46ba915f15c, []int{8}
|
||||
}
|
||||
|
||||
func (m *EthereumMessageSignature) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_EthereumMessageSignature.Unmarshal(m, b)
|
||||
}
|
||||
func (m *EthereumMessageSignature) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_EthereumMessageSignature.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (m *EthereumMessageSignature) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_EthereumMessageSignature.Merge(m, src)
|
||||
}
|
||||
func (m *EthereumMessageSignature) XXX_Size() int {
|
||||
return xxx_messageInfo_EthereumMessageSignature.Size(m)
|
||||
}
|
||||
func (m *EthereumMessageSignature) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_EthereumMessageSignature.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_EthereumMessageSignature proto.InternalMessageInfo
|
||||
|
||||
func (m *EthereumMessageSignature) GetAddressBin() []byte {
|
||||
if m != nil {
|
||||
return m.AddressBin
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *EthereumMessageSignature) GetSignature() []byte {
|
||||
if m != nil {
|
||||
return m.Signature
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *EthereumMessageSignature) GetAddressHex() string {
|
||||
if m != nil && m.AddressHex != nil {
|
||||
return *m.AddressHex
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
//*
|
||||
// Request: Ask device to verify message
|
||||
// @start
|
||||
// @next Success
|
||||
// @next Failure
|
||||
type EthereumVerifyMessage struct {
|
||||
AddressBin []byte `protobuf:"bytes,1,opt,name=addressBin" json:"addressBin,omitempty"`
|
||||
Signature []byte `protobuf:"bytes,2,opt,name=signature" json:"signature,omitempty"`
|
||||
Message []byte `protobuf:"bytes,3,opt,name=message" json:"message,omitempty"`
|
||||
AddressHex *string `protobuf:"bytes,4,opt,name=addressHex" json:"addressHex,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *EthereumVerifyMessage) Reset() { *m = EthereumVerifyMessage{} }
|
||||
func (m *EthereumVerifyMessage) String() string { return proto.CompactTextString(m) }
|
||||
func (*EthereumVerifyMessage) ProtoMessage() {}
|
||||
func (*EthereumVerifyMessage) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_cb33f46ba915f15c, []int{9}
|
||||
}
|
||||
|
||||
func (m *EthereumVerifyMessage) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_EthereumVerifyMessage.Unmarshal(m, b)
|
||||
}
|
||||
func (m *EthereumVerifyMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_EthereumVerifyMessage.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (m *EthereumVerifyMessage) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_EthereumVerifyMessage.Merge(m, src)
|
||||
}
|
||||
func (m *EthereumVerifyMessage) XXX_Size() int {
|
||||
return xxx_messageInfo_EthereumVerifyMessage.Size(m)
|
||||
}
|
||||
func (m *EthereumVerifyMessage) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_EthereumVerifyMessage.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_EthereumVerifyMessage proto.InternalMessageInfo
|
||||
|
||||
func (m *EthereumVerifyMessage) GetAddressBin() []byte {
|
||||
if m != nil {
|
||||
return m.AddressBin
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *EthereumVerifyMessage) GetSignature() []byte {
|
||||
if m != nil {
|
||||
return m.Signature
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *EthereumVerifyMessage) GetMessage() []byte {
|
||||
if m != nil {
|
||||
return m.Message
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *EthereumVerifyMessage) GetAddressHex() string {
|
||||
if m != nil && m.AddressHex != nil {
|
||||
return *m.AddressHex
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func init() {
|
||||
proto.RegisterType((*EthereumGetPublicKey)(nil), "hw.trezor.messages.ethereum.EthereumGetPublicKey")
|
||||
proto.RegisterType((*EthereumPublicKey)(nil), "hw.trezor.messages.ethereum.EthereumPublicKey")
|
||||
proto.RegisterType((*EthereumGetAddress)(nil), "hw.trezor.messages.ethereum.EthereumGetAddress")
|
||||
proto.RegisterType((*EthereumAddress)(nil), "hw.trezor.messages.ethereum.EthereumAddress")
|
||||
proto.RegisterType((*EthereumSignTx)(nil), "hw.trezor.messages.ethereum.EthereumSignTx")
|
||||
proto.RegisterType((*EthereumTxRequest)(nil), "hw.trezor.messages.ethereum.EthereumTxRequest")
|
||||
proto.RegisterType((*EthereumTxAck)(nil), "hw.trezor.messages.ethereum.EthereumTxAck")
|
||||
proto.RegisterType((*EthereumSignMessage)(nil), "hw.trezor.messages.ethereum.EthereumSignMessage")
|
||||
proto.RegisterType((*EthereumMessageSignature)(nil), "hw.trezor.messages.ethereum.EthereumMessageSignature")
|
||||
proto.RegisterType((*EthereumVerifyMessage)(nil), "hw.trezor.messages.ethereum.EthereumVerifyMessage")
|
||||
}
|
||||
|
||||
func init() { proto.RegisterFile("messages-ethereum.proto", fileDescriptor_cb33f46ba915f15c) }
|
||||
|
||||
var fileDescriptor_cb33f46ba915f15c = []byte{
|
||||
// 593 bytes of a gzipped FileDescriptorProto
|
||||
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x54, 0x4d, 0x6f, 0xd3, 0x40,
|
||||
0x10, 0x95, 0x9b, 0xb4, 0x49, 0x26, 0x0d, 0x1f, 0xa6, 0x55, 0x17, 0x0a, 0x34, 0x18, 0x21, 0xe5,
|
||||
0x00, 0x3e, 0x70, 0x43, 0xe2, 0xd2, 0x52, 0x44, 0x2b, 0x4a, 0x55, 0xdc, 0xa8, 0x57, 0x6b, 0x63,
|
||||
0x6f, 0xe3, 0x55, 0x9d, 0xdd, 0xe0, 0x5d, 0xb7, 0x0e, 0x7f, 0x82, 0x23, 0xff, 0x87, 0x5f, 0x86,
|
||||
0xf6, 0x2b, 0x71, 0x52, 0x54, 0x0e, 0xbd, 0x65, 0xde, 0xbc, 0x7d, 0xf3, 0x66, 0xf4, 0x62, 0xd8,
|
||||
0x99, 0x10, 0x21, 0xf0, 0x98, 0x88, 0x77, 0x44, 0x66, 0xa4, 0x20, 0xe5, 0x24, 0x9c, 0x16, 0x5c,
|
||||
0x72, 0x7f, 0x37, 0xbb, 0x09, 0x65, 0x41, 0x7e, 0xf2, 0x22, 0x74, 0x94, 0xd0, 0x51, 0x9e, 0x6d,
|
||||
0xcf, 0x5f, 0x25, 0x7c, 0x32, 0xe1, 0xcc, 0xbc, 0x09, 0x2e, 0x60, 0xeb, 0xb3, 0xa5, 0x7c, 0x21,
|
||||
0xf2, 0xac, 0x1c, 0xe5, 0x34, 0xf9, 0x4a, 0x66, 0xfe, 0x2e, 0x74, 0x70, 0x9a, 0x16, 0x44, 0x88,
|
||||
0x98, 0x21, 0xaf, 0xdf, 0x18, 0xf4, 0xa2, 0xb6, 0x05, 0x4e, 0xfd, 0x57, 0xb0, 0x29, 0x32, 0x7e,
|
||||
0x13, 0xa7, 0x54, 0x4c, 0x73, 0x3c, 0x43, 0x6b, 0x7d, 0x6f, 0xd0, 0x8e, 0xba, 0x0a, 0x3b, 0x34,
|
||||
0x50, 0x30, 0x82, 0xc7, 0x4e, 0x77, 0x21, 0xfa, 0x01, 0x9a, 0x8c, 0xa7, 0x04, 0x79, 0x7d, 0x6f,
|
||||
0xd0, 0x7d, 0xff, 0x26, 0xfc, 0x87, 0x5f, 0x6b, 0xee, 0xe8, 0xf0, 0x94, 0xa7, 0x64, 0x38, 0x9b,
|
||||
0x92, 0x48, 0x3f, 0xf1, 0x7d, 0x68, 0x56, 0xd3, 0x72, 0xa4, 0x47, 0x75, 0x22, 0xfd, 0x3b, 0x18,
|
||||
0x82, 0x5f, 0xf3, 0xbe, 0x6f, 0xdc, 0xdd, 0xdb, 0xf9, 0x77, 0x78, 0xe8, 0x54, 0x9d, 0xe4, 0x4b,
|
||||
0x00, 0xab, 0x70, 0x40, 0x99, 0x76, 0xbf, 0x19, 0xd5, 0x90, 0x5a, 0xff, 0x88, 0x54, 0xd6, 0x62,
|
||||
0x0d, 0x09, 0xfe, 0xac, 0xc1, 0x03, 0xa7, 0x79, 0x4e, 0xc7, 0x6c, 0x58, 0xdd, 0xed, 0x72, 0x0b,
|
||||
0xd6, 0x19, 0x67, 0x09, 0xd1, 0x52, 0x9b, 0x91, 0x29, 0xd4, 0x93, 0x31, 0x16, 0xf1, 0xb4, 0xa0,
|
||||
0x09, 0x41, 0x0d, 0xdd, 0x69, 0x8f, 0xb1, 0x38, 0x53, 0xb5, 0x6b, 0xe6, 0x74, 0x42, 0x25, 0x6a,
|
||||
0xce, 0x9b, 0x27, 0xaa, 0x56, 0x7a, 0x92, 0x2b, 0xeb, 0xeb, 0x46, 0x4f, 0x17, 0x06, 0x55, 0x86,
|
||||
0xbb, 0xda, 0xb0, 0x29, 0x14, 0x7a, 0x8d, 0xf3, 0x92, 0xa0, 0x0d, 0xc3, 0xd5, 0x85, 0xff, 0x16,
|
||||
0xfc, 0x14, 0x4b, 0x1c, 0x53, 0x46, 0x25, 0xc5, 0x79, 0x9c, 0x64, 0x25, 0xbb, 0x42, 0x2d, 0x4d,
|
||||
0x79, 0xa4, 0x3a, 0xc7, 0xa6, 0xf1, 0x49, 0xe1, 0xfe, 0x1e, 0x74, 0x35, 0x3b, 0x27, 0x6c, 0x2c,
|
||||
0x33, 0xd4, 0xee, 0x7b, 0x83, 0x5e, 0x04, 0x0a, 0x3a, 0xd1, 0x88, 0xff, 0x14, 0xda, 0x49, 0x86,
|
||||
0x29, 0x8b, 0x69, 0x8a, 0x3a, 0xba, 0xdb, 0xd2, 0xf5, 0x71, 0xea, 0xef, 0x40, 0x4b, 0x56, 0xb1,
|
||||
0x9c, 0x4d, 0x09, 0x02, 0xdd, 0xd9, 0x90, 0x95, 0xca, 0x41, 0xf0, 0xdb, 0x5b, 0x44, 0x6a, 0x58,
|
||||
0x45, 0xe4, 0x47, 0x49, 0x84, 0x5c, 0x1d, 0xe5, 0xdd, 0x1a, 0xb5, 0x07, 0x5d, 0x41, 0xc7, 0x0c,
|
||||
0xcb, 0xb2, 0x20, 0xf1, 0xb5, 0xbe, 0x68, 0x2f, 0x82, 0x39, 0x74, 0xb1, 0x4c, 0x28, 0xec, 0x61,
|
||||
0x17, 0x84, 0x68, 0x99, 0x20, 0xec, 0x71, 0x17, 0x84, 0xf3, 0x20, 0x84, 0xde, 0xc2, 0xd8, 0x7e,
|
||||
0x72, 0xe5, 0xbf, 0x00, 0xed, 0xc0, 0x5e, 0xc9, 0xe4, 0xa5, 0xa3, 0x10, 0x7d, 0x9e, 0xe0, 0x04,
|
||||
0x9e, 0xd4, 0xd3, 0xf0, 0xcd, 0x64, 0xff, 0xee, 0x48, 0x20, 0x68, 0xd9, 0xff, 0x88, 0x0d, 0x85,
|
||||
0x2b, 0x83, 0x0a, 0x90, 0x53, 0xb3, 0x4a, 0xe7, 0xce, 0xda, 0x7f, 0x83, 0xfb, 0x1c, 0x3a, 0xf3,
|
||||
0x3d, 0xac, 0xee, 0x02, 0x58, 0x89, 0x75, 0xe3, 0x56, 0xac, 0x7f, 0x79, 0xb0, 0xed, 0x46, 0x5f,
|
||||
0x90, 0x82, 0x5e, 0xce, 0xdc, 0x2a, 0xf7, 0x9b, 0x5b, 0xdb, 0xb5, 0xb1, 0xb4, 0xeb, 0x8a, 0xa3,
|
||||
0xe6, 0xaa, 0xa3, 0x83, 0x8f, 0xf0, 0x3a, 0xe1, 0x93, 0x50, 0x60, 0xc9, 0x45, 0x46, 0x73, 0x3c,
|
||||
0x12, 0xee, 0x03, 0x93, 0xd3, 0x91, 0xf9, 0xe2, 0x8d, 0xca, 0xcb, 0x83, 0xed, 0xa1, 0x06, 0xad,
|
||||
0x5b, 0xb7, 0xc2, 0xdf, 0x00, 0x00, 0x00, 0xff, 0xff, 0x8a, 0xce, 0x81, 0xc8, 0x59, 0x05, 0x00,
|
||||
0x00,
|
||||
}
|
131
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/trezor/messages-ethereum.proto
generated
vendored
Normal file
131
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/trezor/messages-ethereum.proto
generated
vendored
Normal file
@ -0,0 +1,131 @@
|
||||
// This file originates from the SatoshiLabs Trezor `common` repository at:
|
||||
// https://github.com/trezor/trezor-common/blob/master/protob/messages-ethereum.proto
|
||||
// dated 28.05.2019, commit 893fd219d4a01bcffa0cd9cfa631856371ec5aa9.
|
||||
|
||||
syntax = "proto2";
|
||||
package hw.trezor.messages.ethereum;
|
||||
|
||||
// Sugar for easier handling in Java
|
||||
option java_package = "com.satoshilabs.trezor.lib.protobuf";
|
||||
option java_outer_classname = "TrezorMessageEthereum";
|
||||
|
||||
import "messages-common.proto";
|
||||
|
||||
|
||||
/**
|
||||
* Request: Ask device for public key corresponding to address_n path
|
||||
* @start
|
||||
* @next EthereumPublicKey
|
||||
* @next Failure
|
||||
*/
|
||||
message EthereumGetPublicKey {
|
||||
repeated uint32 address_n = 1; // BIP-32 path to derive the key from master node
|
||||
optional bool show_display = 2; // optionally show on display before sending the result
|
||||
}
|
||||
|
||||
/**
|
||||
* Response: Contains public key derived from device private seed
|
||||
* @end
|
||||
*/
|
||||
message EthereumPublicKey {
|
||||
optional hw.trezor.messages.common.HDNodeType node = 1; // BIP32 public node
|
||||
optional string xpub = 2; // serialized form of public node
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: Ask device for Ethereum address corresponding to address_n path
|
||||
* @start
|
||||
* @next EthereumAddress
|
||||
* @next Failure
|
||||
*/
|
||||
message EthereumGetAddress {
|
||||
repeated uint32 address_n = 1; // BIP-32 path to derive the key from master node
|
||||
optional bool show_display = 2; // optionally show on display before sending the result
|
||||
}
|
||||
|
||||
/**
|
||||
* Response: Contains an Ethereum address derived from device private seed
|
||||
* @end
|
||||
*/
|
||||
message EthereumAddress {
|
||||
optional bytes addressBin = 1; // Ethereum address as 20 bytes (legacy firmwares)
|
||||
optional string addressHex = 2; // Ethereum address as hex string (newer firmwares)
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: Ask device to sign transaction
|
||||
* All fields are optional from the protocol's point of view. Each field defaults to value `0` if missing.
|
||||
* Note: the first at most 1024 bytes of data MUST be transmitted as part of this message.
|
||||
* @start
|
||||
* @next EthereumTxRequest
|
||||
* @next Failure
|
||||
*/
|
||||
message EthereumSignTx {
|
||||
repeated uint32 address_n = 1; // BIP-32 path to derive the key from master node
|
||||
optional bytes nonce = 2; // <=256 bit unsigned big endian
|
||||
optional bytes gas_price = 3; // <=256 bit unsigned big endian (in wei)
|
||||
optional bytes gas_limit = 4; // <=256 bit unsigned big endian
|
||||
optional bytes toBin = 5; // recipient address (20 bytes, legacy firmware)
|
||||
optional string toHex = 11; // recipient address (hex string, newer firmware)
|
||||
optional bytes value = 6; // <=256 bit unsigned big endian (in wei)
|
||||
optional bytes data_initial_chunk = 7; // The initial data chunk (<= 1024 bytes)
|
||||
optional uint32 data_length = 8; // Length of transaction payload
|
||||
optional uint32 chain_id = 9; // Chain Id for EIP 155
|
||||
optional uint32 tx_type = 10; // (only for Wanchain)
|
||||
}
|
||||
|
||||
/**
|
||||
* Response: Device asks for more data from transaction payload, or returns the signature.
|
||||
* If data_length is set, device awaits that many more bytes of payload.
|
||||
* Otherwise, the signature_* fields contain the computed transaction signature. All three fields will be present.
|
||||
* @end
|
||||
* @next EthereumTxAck
|
||||
*/
|
||||
message EthereumTxRequest {
|
||||
optional uint32 data_length = 1; // Number of bytes being requested (<= 1024)
|
||||
optional uint32 signature_v = 2; // Computed signature (recovery parameter, limited to 27 or 28)
|
||||
optional bytes signature_r = 3; // Computed signature R component (256 bit)
|
||||
optional bytes signature_s = 4; // Computed signature S component (256 bit)
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: Transaction payload data.
|
||||
* @next EthereumTxRequest
|
||||
*/
|
||||
message EthereumTxAck {
|
||||
optional bytes data_chunk = 1; // Bytes from transaction payload (<= 1024 bytes)
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: Ask device to sign message
|
||||
* @start
|
||||
* @next EthereumMessageSignature
|
||||
* @next Failure
|
||||
*/
|
||||
message EthereumSignMessage {
|
||||
repeated uint32 address_n = 1; // BIP-32 path to derive the key from master node
|
||||
optional bytes message = 2; // message to be signed
|
||||
}
|
||||
|
||||
/**
|
||||
* Response: Signed message
|
||||
* @end
|
||||
*/
|
||||
message EthereumMessageSignature {
|
||||
optional bytes addressBin = 1; // address used to sign the message (20 bytes, legacy firmware)
|
||||
optional bytes signature = 2; // signature of the message
|
||||
optional string addressHex = 3; // address used to sign the message (hex string, newer firmware)
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: Ask device to verify message
|
||||
* @start
|
||||
* @next Success
|
||||
* @next Failure
|
||||
*/
|
||||
message EthereumVerifyMessage {
|
||||
optional bytes addressBin = 1; // address to verify (20 bytes, legacy firmware)
|
||||
optional bytes signature = 2; // signature to verify
|
||||
optional bytes message = 3; // message to verify
|
||||
optional string addressHex = 4; // address to verify (hex string, newer firmware)
|
||||
}
|
1621
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/trezor/messages-management.pb.go
generated
vendored
Normal file
1621
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/trezor/messages-management.pb.go
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
289
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/trezor/messages-management.proto
generated
vendored
Normal file
289
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/trezor/messages-management.proto
generated
vendored
Normal file
@ -0,0 +1,289 @@
|
||||
// This file originates from the SatoshiLabs Trezor `common` repository at:
|
||||
// https://github.com/trezor/trezor-common/blob/master/protob/messages-management.proto
|
||||
// dated 28.05.2019, commit 893fd219d4a01bcffa0cd9cfa631856371ec5aa9.
|
||||
|
||||
syntax = "proto2";
|
||||
package hw.trezor.messages.management;
|
||||
|
||||
// Sugar for easier handling in Java
|
||||
option java_package = "com.satoshilabs.trezor.lib.protobuf";
|
||||
option java_outer_classname = "TrezorMessageManagement";
|
||||
|
||||
import "messages-common.proto";
|
||||
|
||||
/**
|
||||
* Request: Reset device to default state and ask for device details
|
||||
* @start
|
||||
* @next Features
|
||||
*/
|
||||
message Initialize {
|
||||
optional bytes state = 1; // assumed device state, clear session if set and different
|
||||
optional bool skip_passphrase = 2; // this session should always assume empty passphrase
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: Ask for device details (no device reset)
|
||||
* @start
|
||||
* @next Features
|
||||
*/
|
||||
message GetFeatures {
|
||||
}
|
||||
|
||||
/**
|
||||
* Response: Reports various information about the device
|
||||
* @end
|
||||
*/
|
||||
message Features {
|
||||
optional string vendor = 1; // name of the manufacturer, e.g. "trezor.io"
|
||||
optional uint32 major_version = 2; // major version of the firmware/bootloader, e.g. 1
|
||||
optional uint32 minor_version = 3; // minor version of the firmware/bootloader, e.g. 0
|
||||
optional uint32 patch_version = 4; // patch version of the firmware/bootloader, e.g. 0
|
||||
optional bool bootloader_mode = 5; // is device in bootloader mode?
|
||||
optional string device_id = 6; // device's unique identifier
|
||||
optional bool pin_protection = 7; // is device protected by PIN?
|
||||
optional bool passphrase_protection = 8; // is node/mnemonic encrypted using passphrase?
|
||||
optional string language = 9; // device language
|
||||
optional string label = 10; // device description label
|
||||
optional bool initialized = 12; // does device contain seed?
|
||||
optional bytes revision = 13; // SCM revision of firmware
|
||||
optional bytes bootloader_hash = 14; // hash of the bootloader
|
||||
optional bool imported = 15; // was storage imported from an external source?
|
||||
optional bool pin_cached = 16; // is PIN already cached in session?
|
||||
optional bool passphrase_cached = 17; // is passphrase already cached in session?
|
||||
optional bool firmware_present = 18; // is valid firmware loaded?
|
||||
optional bool needs_backup = 19; // does storage need backup? (equals to Storage.needs_backup)
|
||||
optional uint32 flags = 20; // device flags (equals to Storage.flags)
|
||||
optional string model = 21; // device hardware model
|
||||
optional uint32 fw_major = 22; // reported firmware version if in bootloader mode
|
||||
optional uint32 fw_minor = 23; // reported firmware version if in bootloader mode
|
||||
optional uint32 fw_patch = 24; // reported firmware version if in bootloader mode
|
||||
optional string fw_vendor = 25; // reported firmware vendor if in bootloader mode
|
||||
optional bytes fw_vendor_keys = 26; // reported firmware vendor keys (their hash)
|
||||
optional bool unfinished_backup = 27; // report unfinished backup (equals to Storage.unfinished_backup)
|
||||
optional bool no_backup = 28; // report no backup (equals to Storage.no_backup)
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: clear session (removes cached PIN, passphrase, etc).
|
||||
* @start
|
||||
* @next Success
|
||||
*/
|
||||
message ClearSession {
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: change language and/or label of the device
|
||||
* @start
|
||||
* @next Success
|
||||
* @next Failure
|
||||
*/
|
||||
message ApplySettings {
|
||||
optional string language = 1;
|
||||
optional string label = 2;
|
||||
optional bool use_passphrase = 3;
|
||||
optional bytes homescreen = 4;
|
||||
optional PassphraseSourceType passphrase_source = 5;
|
||||
optional uint32 auto_lock_delay_ms = 6;
|
||||
optional uint32 display_rotation = 7; // in degrees from North
|
||||
/**
|
||||
* Structure representing passphrase source
|
||||
*/
|
||||
enum PassphraseSourceType {
|
||||
ASK = 0;
|
||||
DEVICE = 1;
|
||||
HOST = 2;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: set flags of the device
|
||||
* @start
|
||||
* @next Success
|
||||
* @next Failure
|
||||
*/
|
||||
message ApplyFlags {
|
||||
optional uint32 flags = 1; // bitmask, can only set bits, not unset
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: Starts workflow for setting/changing/removing the PIN
|
||||
* @start
|
||||
* @next Success
|
||||
* @next Failure
|
||||
*/
|
||||
message ChangePin {
|
||||
optional bool remove = 1; // is PIN removal requested?
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: Test if the device is alive, device sends back the message in Success response
|
||||
* @start
|
||||
* @next Success
|
||||
*/
|
||||
message Ping {
|
||||
optional string message = 1; // message to send back in Success message
|
||||
optional bool button_protection = 2; // ask for button press
|
||||
optional bool pin_protection = 3; // ask for PIN if set in device
|
||||
optional bool passphrase_protection = 4; // ask for passphrase if set in device
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: Abort last operation that required user interaction
|
||||
* @start
|
||||
* @next Failure
|
||||
*/
|
||||
message Cancel {
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: Request a sample of random data generated by hardware RNG. May be used for testing.
|
||||
* @start
|
||||
* @next Entropy
|
||||
* @next Failure
|
||||
*/
|
||||
message GetEntropy {
|
||||
required uint32 size = 1; // size of requested entropy
|
||||
}
|
||||
|
||||
/**
|
||||
* Response: Reply with random data generated by internal RNG
|
||||
* @end
|
||||
*/
|
||||
message Entropy {
|
||||
required bytes entropy = 1; // chunk of random generated bytes
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: Request device to wipe all sensitive data and settings
|
||||
* @start
|
||||
* @next Success
|
||||
* @next Failure
|
||||
*/
|
||||
message WipeDevice {
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: Load seed and related internal settings from the computer
|
||||
* @start
|
||||
* @next Success
|
||||
* @next Failure
|
||||
*/
|
||||
message LoadDevice {
|
||||
optional string mnemonic = 1; // seed encoded as BIP-39 mnemonic (12, 18 or 24 words)
|
||||
optional hw.trezor.messages.common.HDNodeType node = 2; // BIP-32 node
|
||||
optional string pin = 3; // set PIN protection
|
||||
optional bool passphrase_protection = 4; // enable master node encryption using passphrase
|
||||
optional string language = 5 [default='english']; // device language
|
||||
optional string label = 6; // device label
|
||||
optional bool skip_checksum = 7; // do not test mnemonic for valid BIP-39 checksum
|
||||
optional uint32 u2f_counter = 8; // U2F counter
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: Ask device to do initialization involving user interaction
|
||||
* @start
|
||||
* @next EntropyRequest
|
||||
* @next Failure
|
||||
*/
|
||||
message ResetDevice {
|
||||
optional bool display_random = 1; // display entropy generated by the device before asking for additional entropy
|
||||
optional uint32 strength = 2 [default=256]; // strength of seed in bits
|
||||
optional bool passphrase_protection = 3; // enable master node encryption using passphrase
|
||||
optional bool pin_protection = 4; // enable PIN protection
|
||||
optional string language = 5 [default='english']; // device language
|
||||
optional string label = 6; // device label
|
||||
optional uint32 u2f_counter = 7; // U2F counter
|
||||
optional bool skip_backup = 8; // postpone seed backup to BackupDevice workflow
|
||||
optional bool no_backup = 9; // indicate that no backup is going to be made
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: Perform backup of the device seed if not backed up using ResetDevice
|
||||
* @start
|
||||
* @next Success
|
||||
*/
|
||||
message BackupDevice {
|
||||
}
|
||||
|
||||
/**
|
||||
* Response: Ask for additional entropy from host computer
|
||||
* @next EntropyAck
|
||||
*/
|
||||
message EntropyRequest {
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: Provide additional entropy for seed generation function
|
||||
* @next Success
|
||||
*/
|
||||
message EntropyAck {
|
||||
optional bytes entropy = 1; // 256 bits (32 bytes) of random data
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: Start recovery workflow asking user for specific words of mnemonic
|
||||
* Used to recovery device safely even on untrusted computer.
|
||||
* @start
|
||||
* @next WordRequest
|
||||
*/
|
||||
message RecoveryDevice {
|
||||
optional uint32 word_count = 1; // number of words in BIP-39 mnemonic
|
||||
optional bool passphrase_protection = 2; // enable master node encryption using passphrase
|
||||
optional bool pin_protection = 3; // enable PIN protection
|
||||
optional string language = 4 [default='english']; // device language
|
||||
optional string label = 5; // device label
|
||||
optional bool enforce_wordlist = 6; // enforce BIP-39 wordlist during the process
|
||||
// 7 reserved for unused recovery method
|
||||
optional RecoveryDeviceType type = 8; // supported recovery type
|
||||
optional uint32 u2f_counter = 9; // U2F counter
|
||||
optional bool dry_run = 10; // perform dry-run recovery workflow (for safe mnemonic validation)
|
||||
/**
|
||||
* Type of recovery procedure. These should be used as bitmask, e.g.,
|
||||
* `RecoveryDeviceType_ScrambledWords | RecoveryDeviceType_Matrix`
|
||||
* listing every method supported by the host computer.
|
||||
*
|
||||
* Note that ScrambledWords must be supported by every implementation
|
||||
* for backward compatibility; there is no way to not support it.
|
||||
*/
|
||||
enum RecoveryDeviceType {
|
||||
// use powers of two when extending this field
|
||||
RecoveryDeviceType_ScrambledWords = 0; // words in scrambled order
|
||||
RecoveryDeviceType_Matrix = 1; // matrix recovery type
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Response: Device is waiting for user to enter word of the mnemonic
|
||||
* Its position is shown only on device's internal display.
|
||||
* @next WordAck
|
||||
*/
|
||||
message WordRequest {
|
||||
optional WordRequestType type = 1;
|
||||
/**
|
||||
* Type of Recovery Word request
|
||||
*/
|
||||
enum WordRequestType {
|
||||
WordRequestType_Plain = 0;
|
||||
WordRequestType_Matrix9 = 1;
|
||||
WordRequestType_Matrix6 = 2;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: Computer replies with word from the mnemonic
|
||||
* @next WordRequest
|
||||
* @next Success
|
||||
* @next Failure
|
||||
*/
|
||||
message WordAck {
|
||||
required string word = 1; // one word of mnemonic on asked position
|
||||
}
|
||||
|
||||
/**
|
||||
* Request: Set U2F counter
|
||||
* @start
|
||||
* @next Success
|
||||
*/
|
||||
message SetU2FCounter {
|
||||
optional uint32 u2f_counter = 1; // counter
|
||||
}
|
889
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/trezor/messages.pb.go
generated
vendored
Normal file
889
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/trezor/messages.pb.go
generated
vendored
Normal file
@ -0,0 +1,889 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// source: messages.proto
|
||||
|
||||
package trezor
|
||||
|
||||
import (
|
||||
fmt "fmt"
|
||||
math "math"
|
||||
|
||||
proto "github.com/golang/protobuf/proto"
|
||||
descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor"
|
||||
)
|
||||
|
||||
// Reference imports to suppress errors if they are not otherwise used.
|
||||
var _ = proto.Marshal
|
||||
var _ = fmt.Errorf
|
||||
var _ = math.Inf
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the proto package it is being compiled against.
|
||||
// A compilation error at this line likely means your copy of the
|
||||
// proto package needs to be updated.
|
||||
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
|
||||
|
||||
//*
|
||||
// Mapping between TREZOR wire identifier (uint) and a protobuf message
|
||||
type MessageType int32
|
||||
|
||||
const (
|
||||
// Management
|
||||
MessageType_MessageType_Initialize MessageType = 0
|
||||
MessageType_MessageType_Ping MessageType = 1
|
||||
MessageType_MessageType_Success MessageType = 2
|
||||
MessageType_MessageType_Failure MessageType = 3
|
||||
MessageType_MessageType_ChangePin MessageType = 4
|
||||
MessageType_MessageType_WipeDevice MessageType = 5
|
||||
MessageType_MessageType_GetEntropy MessageType = 9
|
||||
MessageType_MessageType_Entropy MessageType = 10
|
||||
MessageType_MessageType_LoadDevice MessageType = 13
|
||||
MessageType_MessageType_ResetDevice MessageType = 14
|
||||
MessageType_MessageType_Features MessageType = 17
|
||||
MessageType_MessageType_PinMatrixRequest MessageType = 18
|
||||
MessageType_MessageType_PinMatrixAck MessageType = 19
|
||||
MessageType_MessageType_Cancel MessageType = 20
|
||||
MessageType_MessageType_ClearSession MessageType = 24
|
||||
MessageType_MessageType_ApplySettings MessageType = 25
|
||||
MessageType_MessageType_ButtonRequest MessageType = 26
|
||||
MessageType_MessageType_ButtonAck MessageType = 27
|
||||
MessageType_MessageType_ApplyFlags MessageType = 28
|
||||
MessageType_MessageType_BackupDevice MessageType = 34
|
||||
MessageType_MessageType_EntropyRequest MessageType = 35
|
||||
MessageType_MessageType_EntropyAck MessageType = 36
|
||||
MessageType_MessageType_PassphraseRequest MessageType = 41
|
||||
MessageType_MessageType_PassphraseAck MessageType = 42
|
||||
MessageType_MessageType_PassphraseStateRequest MessageType = 77
|
||||
MessageType_MessageType_PassphraseStateAck MessageType = 78
|
||||
MessageType_MessageType_RecoveryDevice MessageType = 45
|
||||
MessageType_MessageType_WordRequest MessageType = 46
|
||||
MessageType_MessageType_WordAck MessageType = 47
|
||||
MessageType_MessageType_GetFeatures MessageType = 55
|
||||
MessageType_MessageType_SetU2FCounter MessageType = 63
|
||||
// Bootloader
|
||||
MessageType_MessageType_FirmwareErase MessageType = 6
|
||||
MessageType_MessageType_FirmwareUpload MessageType = 7
|
||||
MessageType_MessageType_FirmwareRequest MessageType = 8
|
||||
MessageType_MessageType_SelfTest MessageType = 32
|
||||
// Bitcoin
|
||||
MessageType_MessageType_GetPublicKey MessageType = 11
|
||||
MessageType_MessageType_PublicKey MessageType = 12
|
||||
MessageType_MessageType_SignTx MessageType = 15
|
||||
MessageType_MessageType_TxRequest MessageType = 21
|
||||
MessageType_MessageType_TxAck MessageType = 22
|
||||
MessageType_MessageType_GetAddress MessageType = 29
|
||||
MessageType_MessageType_Address MessageType = 30
|
||||
MessageType_MessageType_SignMessage MessageType = 38
|
||||
MessageType_MessageType_VerifyMessage MessageType = 39
|
||||
MessageType_MessageType_MessageSignature MessageType = 40
|
||||
// Crypto
|
||||
MessageType_MessageType_CipherKeyValue MessageType = 23
|
||||
MessageType_MessageType_CipheredKeyValue MessageType = 48
|
||||
MessageType_MessageType_SignIdentity MessageType = 53
|
||||
MessageType_MessageType_SignedIdentity MessageType = 54
|
||||
MessageType_MessageType_GetECDHSessionKey MessageType = 61
|
||||
MessageType_MessageType_ECDHSessionKey MessageType = 62
|
||||
MessageType_MessageType_CosiCommit MessageType = 71
|
||||
MessageType_MessageType_CosiCommitment MessageType = 72
|
||||
MessageType_MessageType_CosiSign MessageType = 73
|
||||
MessageType_MessageType_CosiSignature MessageType = 74
|
||||
// Debug
|
||||
MessageType_MessageType_DebugLinkDecision MessageType = 100
|
||||
MessageType_MessageType_DebugLinkGetState MessageType = 101
|
||||
MessageType_MessageType_DebugLinkState MessageType = 102
|
||||
MessageType_MessageType_DebugLinkStop MessageType = 103
|
||||
MessageType_MessageType_DebugLinkLog MessageType = 104
|
||||
MessageType_MessageType_DebugLinkMemoryRead MessageType = 110
|
||||
MessageType_MessageType_DebugLinkMemory MessageType = 111
|
||||
MessageType_MessageType_DebugLinkMemoryWrite MessageType = 112
|
||||
MessageType_MessageType_DebugLinkFlashErase MessageType = 113
|
||||
// Ethereum
|
||||
MessageType_MessageType_EthereumGetPublicKey MessageType = 450
|
||||
MessageType_MessageType_EthereumPublicKey MessageType = 451
|
||||
MessageType_MessageType_EthereumGetAddress MessageType = 56
|
||||
MessageType_MessageType_EthereumAddress MessageType = 57
|
||||
MessageType_MessageType_EthereumSignTx MessageType = 58
|
||||
MessageType_MessageType_EthereumTxRequest MessageType = 59
|
||||
MessageType_MessageType_EthereumTxAck MessageType = 60
|
||||
MessageType_MessageType_EthereumSignMessage MessageType = 64
|
||||
MessageType_MessageType_EthereumVerifyMessage MessageType = 65
|
||||
MessageType_MessageType_EthereumMessageSignature MessageType = 66
|
||||
// NEM
|
||||
MessageType_MessageType_NEMGetAddress MessageType = 67
|
||||
MessageType_MessageType_NEMAddress MessageType = 68
|
||||
MessageType_MessageType_NEMSignTx MessageType = 69
|
||||
MessageType_MessageType_NEMSignedTx MessageType = 70
|
||||
MessageType_MessageType_NEMDecryptMessage MessageType = 75
|
||||
MessageType_MessageType_NEMDecryptedMessage MessageType = 76
|
||||
// Lisk
|
||||
MessageType_MessageType_LiskGetAddress MessageType = 114
|
||||
MessageType_MessageType_LiskAddress MessageType = 115
|
||||
MessageType_MessageType_LiskSignTx MessageType = 116
|
||||
MessageType_MessageType_LiskSignedTx MessageType = 117
|
||||
MessageType_MessageType_LiskSignMessage MessageType = 118
|
||||
MessageType_MessageType_LiskMessageSignature MessageType = 119
|
||||
MessageType_MessageType_LiskVerifyMessage MessageType = 120
|
||||
MessageType_MessageType_LiskGetPublicKey MessageType = 121
|
||||
MessageType_MessageType_LiskPublicKey MessageType = 122
|
||||
// Tezos
|
||||
MessageType_MessageType_TezosGetAddress MessageType = 150
|
||||
MessageType_MessageType_TezosAddress MessageType = 151
|
||||
MessageType_MessageType_TezosSignTx MessageType = 152
|
||||
MessageType_MessageType_TezosSignedTx MessageType = 153
|
||||
MessageType_MessageType_TezosGetPublicKey MessageType = 154
|
||||
MessageType_MessageType_TezosPublicKey MessageType = 155
|
||||
// Stellar
|
||||
MessageType_MessageType_StellarSignTx MessageType = 202
|
||||
MessageType_MessageType_StellarTxOpRequest MessageType = 203
|
||||
MessageType_MessageType_StellarGetAddress MessageType = 207
|
||||
MessageType_MessageType_StellarAddress MessageType = 208
|
||||
MessageType_MessageType_StellarCreateAccountOp MessageType = 210
|
||||
MessageType_MessageType_StellarPaymentOp MessageType = 211
|
||||
MessageType_MessageType_StellarPathPaymentOp MessageType = 212
|
||||
MessageType_MessageType_StellarManageOfferOp MessageType = 213
|
||||
MessageType_MessageType_StellarCreatePassiveOfferOp MessageType = 214
|
||||
MessageType_MessageType_StellarSetOptionsOp MessageType = 215
|
||||
MessageType_MessageType_StellarChangeTrustOp MessageType = 216
|
||||
MessageType_MessageType_StellarAllowTrustOp MessageType = 217
|
||||
MessageType_MessageType_StellarAccountMergeOp MessageType = 218
|
||||
// omitted: StellarInflationOp is not a supported operation, would be 219
|
||||
MessageType_MessageType_StellarManageDataOp MessageType = 220
|
||||
MessageType_MessageType_StellarBumpSequenceOp MessageType = 221
|
||||
MessageType_MessageType_StellarSignedTx MessageType = 230
|
||||
// TRON
|
||||
MessageType_MessageType_TronGetAddress MessageType = 250
|
||||
MessageType_MessageType_TronAddress MessageType = 251
|
||||
MessageType_MessageType_TronSignTx MessageType = 252
|
||||
MessageType_MessageType_TronSignedTx MessageType = 253
|
||||
// Cardano
|
||||
// dropped Sign/VerifyMessage ids 300-302
|
||||
MessageType_MessageType_CardanoSignTx MessageType = 303
|
||||
MessageType_MessageType_CardanoTxRequest MessageType = 304
|
||||
MessageType_MessageType_CardanoGetPublicKey MessageType = 305
|
||||
MessageType_MessageType_CardanoPublicKey MessageType = 306
|
||||
MessageType_MessageType_CardanoGetAddress MessageType = 307
|
||||
MessageType_MessageType_CardanoAddress MessageType = 308
|
||||
MessageType_MessageType_CardanoTxAck MessageType = 309
|
||||
MessageType_MessageType_CardanoSignedTx MessageType = 310
|
||||
// Ontology
|
||||
MessageType_MessageType_OntologyGetAddress MessageType = 350
|
||||
MessageType_MessageType_OntologyAddress MessageType = 351
|
||||
MessageType_MessageType_OntologyGetPublicKey MessageType = 352
|
||||
MessageType_MessageType_OntologyPublicKey MessageType = 353
|
||||
MessageType_MessageType_OntologySignTransfer MessageType = 354
|
||||
MessageType_MessageType_OntologySignedTransfer MessageType = 355
|
||||
MessageType_MessageType_OntologySignWithdrawOng MessageType = 356
|
||||
MessageType_MessageType_OntologySignedWithdrawOng MessageType = 357
|
||||
MessageType_MessageType_OntologySignOntIdRegister MessageType = 358
|
||||
MessageType_MessageType_OntologySignedOntIdRegister MessageType = 359
|
||||
MessageType_MessageType_OntologySignOntIdAddAttributes MessageType = 360
|
||||
MessageType_MessageType_OntologySignedOntIdAddAttributes MessageType = 361
|
||||
// Ripple
|
||||
MessageType_MessageType_RippleGetAddress MessageType = 400
|
||||
MessageType_MessageType_RippleAddress MessageType = 401
|
||||
MessageType_MessageType_RippleSignTx MessageType = 402
|
||||
MessageType_MessageType_RippleSignedTx MessageType = 403
|
||||
// Monero
|
||||
MessageType_MessageType_MoneroTransactionInitRequest MessageType = 501
|
||||
MessageType_MessageType_MoneroTransactionInitAck MessageType = 502
|
||||
MessageType_MessageType_MoneroTransactionSetInputRequest MessageType = 503
|
||||
MessageType_MessageType_MoneroTransactionSetInputAck MessageType = 504
|
||||
MessageType_MessageType_MoneroTransactionInputsPermutationRequest MessageType = 505
|
||||
MessageType_MessageType_MoneroTransactionInputsPermutationAck MessageType = 506
|
||||
MessageType_MessageType_MoneroTransactionInputViniRequest MessageType = 507
|
||||
MessageType_MessageType_MoneroTransactionInputViniAck MessageType = 508
|
||||
MessageType_MessageType_MoneroTransactionAllInputsSetRequest MessageType = 509
|
||||
MessageType_MessageType_MoneroTransactionAllInputsSetAck MessageType = 510
|
||||
MessageType_MessageType_MoneroTransactionSetOutputRequest MessageType = 511
|
||||
MessageType_MessageType_MoneroTransactionSetOutputAck MessageType = 512
|
||||
MessageType_MessageType_MoneroTransactionAllOutSetRequest MessageType = 513
|
||||
MessageType_MessageType_MoneroTransactionAllOutSetAck MessageType = 514
|
||||
MessageType_MessageType_MoneroTransactionSignInputRequest MessageType = 515
|
||||
MessageType_MessageType_MoneroTransactionSignInputAck MessageType = 516
|
||||
MessageType_MessageType_MoneroTransactionFinalRequest MessageType = 517
|
||||
MessageType_MessageType_MoneroTransactionFinalAck MessageType = 518
|
||||
MessageType_MessageType_MoneroKeyImageExportInitRequest MessageType = 530
|
||||
MessageType_MessageType_MoneroKeyImageExportInitAck MessageType = 531
|
||||
MessageType_MessageType_MoneroKeyImageSyncStepRequest MessageType = 532
|
||||
MessageType_MessageType_MoneroKeyImageSyncStepAck MessageType = 533
|
||||
MessageType_MessageType_MoneroKeyImageSyncFinalRequest MessageType = 534
|
||||
MessageType_MessageType_MoneroKeyImageSyncFinalAck MessageType = 535
|
||||
MessageType_MessageType_MoneroGetAddress MessageType = 540
|
||||
MessageType_MessageType_MoneroAddress MessageType = 541
|
||||
MessageType_MessageType_MoneroGetWatchKey MessageType = 542
|
||||
MessageType_MessageType_MoneroWatchKey MessageType = 543
|
||||
MessageType_MessageType_DebugMoneroDiagRequest MessageType = 546
|
||||
MessageType_MessageType_DebugMoneroDiagAck MessageType = 547
|
||||
MessageType_MessageType_MoneroGetTxKeyRequest MessageType = 550
|
||||
MessageType_MessageType_MoneroGetTxKeyAck MessageType = 551
|
||||
MessageType_MessageType_MoneroLiveRefreshStartRequest MessageType = 552
|
||||
MessageType_MessageType_MoneroLiveRefreshStartAck MessageType = 553
|
||||
MessageType_MessageType_MoneroLiveRefreshStepRequest MessageType = 554
|
||||
MessageType_MessageType_MoneroLiveRefreshStepAck MessageType = 555
|
||||
MessageType_MessageType_MoneroLiveRefreshFinalRequest MessageType = 556
|
||||
MessageType_MessageType_MoneroLiveRefreshFinalAck MessageType = 557
|
||||
// EOS
|
||||
MessageType_MessageType_EosGetPublicKey MessageType = 600
|
||||
MessageType_MessageType_EosPublicKey MessageType = 601
|
||||
MessageType_MessageType_EosSignTx MessageType = 602
|
||||
MessageType_MessageType_EosTxActionRequest MessageType = 603
|
||||
MessageType_MessageType_EosTxActionAck MessageType = 604
|
||||
MessageType_MessageType_EosSignedTx MessageType = 605
|
||||
// Binance
|
||||
MessageType_MessageType_BinanceGetAddress MessageType = 700
|
||||
MessageType_MessageType_BinanceAddress MessageType = 701
|
||||
MessageType_MessageType_BinanceGetPublicKey MessageType = 702
|
||||
MessageType_MessageType_BinancePublicKey MessageType = 703
|
||||
MessageType_MessageType_BinanceSignTx MessageType = 704
|
||||
MessageType_MessageType_BinanceTxRequest MessageType = 705
|
||||
MessageType_MessageType_BinanceTransferMsg MessageType = 706
|
||||
MessageType_MessageType_BinanceOrderMsg MessageType = 707
|
||||
MessageType_MessageType_BinanceCancelMsg MessageType = 708
|
||||
MessageType_MessageType_BinanceSignedTx MessageType = 709
|
||||
)
|
||||
|
||||
var MessageType_name = map[int32]string{
|
||||
0: "MessageType_Initialize",
|
||||
1: "MessageType_Ping",
|
||||
2: "MessageType_Success",
|
||||
3: "MessageType_Failure",
|
||||
4: "MessageType_ChangePin",
|
||||
5: "MessageType_WipeDevice",
|
||||
9: "MessageType_GetEntropy",
|
||||
10: "MessageType_Entropy",
|
||||
13: "MessageType_LoadDevice",
|
||||
14: "MessageType_ResetDevice",
|
||||
17: "MessageType_Features",
|
||||
18: "MessageType_PinMatrixRequest",
|
||||
19: "MessageType_PinMatrixAck",
|
||||
20: "MessageType_Cancel",
|
||||
24: "MessageType_ClearSession",
|
||||
25: "MessageType_ApplySettings",
|
||||
26: "MessageType_ButtonRequest",
|
||||
27: "MessageType_ButtonAck",
|
||||
28: "MessageType_ApplyFlags",
|
||||
34: "MessageType_BackupDevice",
|
||||
35: "MessageType_EntropyRequest",
|
||||
36: "MessageType_EntropyAck",
|
||||
41: "MessageType_PassphraseRequest",
|
||||
42: "MessageType_PassphraseAck",
|
||||
77: "MessageType_PassphraseStateRequest",
|
||||
78: "MessageType_PassphraseStateAck",
|
||||
45: "MessageType_RecoveryDevice",
|
||||
46: "MessageType_WordRequest",
|
||||
47: "MessageType_WordAck",
|
||||
55: "MessageType_GetFeatures",
|
||||
63: "MessageType_SetU2FCounter",
|
||||
6: "MessageType_FirmwareErase",
|
||||
7: "MessageType_FirmwareUpload",
|
||||
8: "MessageType_FirmwareRequest",
|
||||
32: "MessageType_SelfTest",
|
||||
11: "MessageType_GetPublicKey",
|
||||
12: "MessageType_PublicKey",
|
||||
15: "MessageType_SignTx",
|
||||
21: "MessageType_TxRequest",
|
||||
22: "MessageType_TxAck",
|
||||
29: "MessageType_GetAddress",
|
||||
30: "MessageType_Address",
|
||||
38: "MessageType_SignMessage",
|
||||
39: "MessageType_VerifyMessage",
|
||||
40: "MessageType_MessageSignature",
|
||||
23: "MessageType_CipherKeyValue",
|
||||
48: "MessageType_CipheredKeyValue",
|
||||
53: "MessageType_SignIdentity",
|
||||
54: "MessageType_SignedIdentity",
|
||||
61: "MessageType_GetECDHSessionKey",
|
||||
62: "MessageType_ECDHSessionKey",
|
||||
71: "MessageType_CosiCommit",
|
||||
72: "MessageType_CosiCommitment",
|
||||
73: "MessageType_CosiSign",
|
||||
74: "MessageType_CosiSignature",
|
||||
100: "MessageType_DebugLinkDecision",
|
||||
101: "MessageType_DebugLinkGetState",
|
||||
102: "MessageType_DebugLinkState",
|
||||
103: "MessageType_DebugLinkStop",
|
||||
104: "MessageType_DebugLinkLog",
|
||||
110: "MessageType_DebugLinkMemoryRead",
|
||||
111: "MessageType_DebugLinkMemory",
|
||||
112: "MessageType_DebugLinkMemoryWrite",
|
||||
113: "MessageType_DebugLinkFlashErase",
|
||||
450: "MessageType_EthereumGetPublicKey",
|
||||
451: "MessageType_EthereumPublicKey",
|
||||
56: "MessageType_EthereumGetAddress",
|
||||
57: "MessageType_EthereumAddress",
|
||||
58: "MessageType_EthereumSignTx",
|
||||
59: "MessageType_EthereumTxRequest",
|
||||
60: "MessageType_EthereumTxAck",
|
||||
64: "MessageType_EthereumSignMessage",
|
||||
65: "MessageType_EthereumVerifyMessage",
|
||||
66: "MessageType_EthereumMessageSignature",
|
||||
67: "MessageType_NEMGetAddress",
|
||||
68: "MessageType_NEMAddress",
|
||||
69: "MessageType_NEMSignTx",
|
||||
70: "MessageType_NEMSignedTx",
|
||||
75: "MessageType_NEMDecryptMessage",
|
||||
76: "MessageType_NEMDecryptedMessage",
|
||||
114: "MessageType_LiskGetAddress",
|
||||
115: "MessageType_LiskAddress",
|
||||
116: "MessageType_LiskSignTx",
|
||||
117: "MessageType_LiskSignedTx",
|
||||
118: "MessageType_LiskSignMessage",
|
||||
119: "MessageType_LiskMessageSignature",
|
||||
120: "MessageType_LiskVerifyMessage",
|
||||
121: "MessageType_LiskGetPublicKey",
|
||||
122: "MessageType_LiskPublicKey",
|
||||
150: "MessageType_TezosGetAddress",
|
||||
151: "MessageType_TezosAddress",
|
||||
152: "MessageType_TezosSignTx",
|
||||
153: "MessageType_TezosSignedTx",
|
||||
154: "MessageType_TezosGetPublicKey",
|
||||
155: "MessageType_TezosPublicKey",
|
||||
202: "MessageType_StellarSignTx",
|
||||
203: "MessageType_StellarTxOpRequest",
|
||||
207: "MessageType_StellarGetAddress",
|
||||
208: "MessageType_StellarAddress",
|
||||
210: "MessageType_StellarCreateAccountOp",
|
||||
211: "MessageType_StellarPaymentOp",
|
||||
212: "MessageType_StellarPathPaymentOp",
|
||||
213: "MessageType_StellarManageOfferOp",
|
||||
214: "MessageType_StellarCreatePassiveOfferOp",
|
||||
215: "MessageType_StellarSetOptionsOp",
|
||||
216: "MessageType_StellarChangeTrustOp",
|
||||
217: "MessageType_StellarAllowTrustOp",
|
||||
218: "MessageType_StellarAccountMergeOp",
|
||||
220: "MessageType_StellarManageDataOp",
|
||||
221: "MessageType_StellarBumpSequenceOp",
|
||||
230: "MessageType_StellarSignedTx",
|
||||
250: "MessageType_TronGetAddress",
|
||||
251: "MessageType_TronAddress",
|
||||
252: "MessageType_TronSignTx",
|
||||
253: "MessageType_TronSignedTx",
|
||||
303: "MessageType_CardanoSignTx",
|
||||
304: "MessageType_CardanoTxRequest",
|
||||
305: "MessageType_CardanoGetPublicKey",
|
||||
306: "MessageType_CardanoPublicKey",
|
||||
307: "MessageType_CardanoGetAddress",
|
||||
308: "MessageType_CardanoAddress",
|
||||
309: "MessageType_CardanoTxAck",
|
||||
310: "MessageType_CardanoSignedTx",
|
||||
350: "MessageType_OntologyGetAddress",
|
||||
351: "MessageType_OntologyAddress",
|
||||
352: "MessageType_OntologyGetPublicKey",
|
||||
353: "MessageType_OntologyPublicKey",
|
||||
354: "MessageType_OntologySignTransfer",
|
||||
355: "MessageType_OntologySignedTransfer",
|
||||
356: "MessageType_OntologySignWithdrawOng",
|
||||
357: "MessageType_OntologySignedWithdrawOng",
|
||||
358: "MessageType_OntologySignOntIdRegister",
|
||||
359: "MessageType_OntologySignedOntIdRegister",
|
||||
360: "MessageType_OntologySignOntIdAddAttributes",
|
||||
361: "MessageType_OntologySignedOntIdAddAttributes",
|
||||
400: "MessageType_RippleGetAddress",
|
||||
401: "MessageType_RippleAddress",
|
||||
402: "MessageType_RippleSignTx",
|
||||
403: "MessageType_RippleSignedTx",
|
||||
501: "MessageType_MoneroTransactionInitRequest",
|
||||
502: "MessageType_MoneroTransactionInitAck",
|
||||
503: "MessageType_MoneroTransactionSetInputRequest",
|
||||
504: "MessageType_MoneroTransactionSetInputAck",
|
||||
505: "MessageType_MoneroTransactionInputsPermutationRequest",
|
||||
506: "MessageType_MoneroTransactionInputsPermutationAck",
|
||||
507: "MessageType_MoneroTransactionInputViniRequest",
|
||||
508: "MessageType_MoneroTransactionInputViniAck",
|
||||
509: "MessageType_MoneroTransactionAllInputsSetRequest",
|
||||
510: "MessageType_MoneroTransactionAllInputsSetAck",
|
||||
511: "MessageType_MoneroTransactionSetOutputRequest",
|
||||
512: "MessageType_MoneroTransactionSetOutputAck",
|
||||
513: "MessageType_MoneroTransactionAllOutSetRequest",
|
||||
514: "MessageType_MoneroTransactionAllOutSetAck",
|
||||
515: "MessageType_MoneroTransactionSignInputRequest",
|
||||
516: "MessageType_MoneroTransactionSignInputAck",
|
||||
517: "MessageType_MoneroTransactionFinalRequest",
|
||||
518: "MessageType_MoneroTransactionFinalAck",
|
||||
530: "MessageType_MoneroKeyImageExportInitRequest",
|
||||
531: "MessageType_MoneroKeyImageExportInitAck",
|
||||
532: "MessageType_MoneroKeyImageSyncStepRequest",
|
||||
533: "MessageType_MoneroKeyImageSyncStepAck",
|
||||
534: "MessageType_MoneroKeyImageSyncFinalRequest",
|
||||
535: "MessageType_MoneroKeyImageSyncFinalAck",
|
||||
540: "MessageType_MoneroGetAddress",
|
||||
541: "MessageType_MoneroAddress",
|
||||
542: "MessageType_MoneroGetWatchKey",
|
||||
543: "MessageType_MoneroWatchKey",
|
||||
546: "MessageType_DebugMoneroDiagRequest",
|
||||
547: "MessageType_DebugMoneroDiagAck",
|
||||
550: "MessageType_MoneroGetTxKeyRequest",
|
||||
551: "MessageType_MoneroGetTxKeyAck",
|
||||
552: "MessageType_MoneroLiveRefreshStartRequest",
|
||||
553: "MessageType_MoneroLiveRefreshStartAck",
|
||||
554: "MessageType_MoneroLiveRefreshStepRequest",
|
||||
555: "MessageType_MoneroLiveRefreshStepAck",
|
||||
556: "MessageType_MoneroLiveRefreshFinalRequest",
|
||||
557: "MessageType_MoneroLiveRefreshFinalAck",
|
||||
600: "MessageType_EosGetPublicKey",
|
||||
601: "MessageType_EosPublicKey",
|
||||
602: "MessageType_EosSignTx",
|
||||
603: "MessageType_EosTxActionRequest",
|
||||
604: "MessageType_EosTxActionAck",
|
||||
605: "MessageType_EosSignedTx",
|
||||
700: "MessageType_BinanceGetAddress",
|
||||
701: "MessageType_BinanceAddress",
|
||||
702: "MessageType_BinanceGetPublicKey",
|
||||
703: "MessageType_BinancePublicKey",
|
||||
704: "MessageType_BinanceSignTx",
|
||||
705: "MessageType_BinanceTxRequest",
|
||||
706: "MessageType_BinanceTransferMsg",
|
||||
707: "MessageType_BinanceOrderMsg",
|
||||
708: "MessageType_BinanceCancelMsg",
|
||||
709: "MessageType_BinanceSignedTx",
|
||||
}
|
||||
|
||||
var MessageType_value = map[string]int32{
|
||||
"MessageType_Initialize": 0,
|
||||
"MessageType_Ping": 1,
|
||||
"MessageType_Success": 2,
|
||||
"MessageType_Failure": 3,
|
||||
"MessageType_ChangePin": 4,
|
||||
"MessageType_WipeDevice": 5,
|
||||
"MessageType_GetEntropy": 9,
|
||||
"MessageType_Entropy": 10,
|
||||
"MessageType_LoadDevice": 13,
|
||||
"MessageType_ResetDevice": 14,
|
||||
"MessageType_Features": 17,
|
||||
"MessageType_PinMatrixRequest": 18,
|
||||
"MessageType_PinMatrixAck": 19,
|
||||
"MessageType_Cancel": 20,
|
||||
"MessageType_ClearSession": 24,
|
||||
"MessageType_ApplySettings": 25,
|
||||
"MessageType_ButtonRequest": 26,
|
||||
"MessageType_ButtonAck": 27,
|
||||
"MessageType_ApplyFlags": 28,
|
||||
"MessageType_BackupDevice": 34,
|
||||
"MessageType_EntropyRequest": 35,
|
||||
"MessageType_EntropyAck": 36,
|
||||
"MessageType_PassphraseRequest": 41,
|
||||
"MessageType_PassphraseAck": 42,
|
||||
"MessageType_PassphraseStateRequest": 77,
|
||||
"MessageType_PassphraseStateAck": 78,
|
||||
"MessageType_RecoveryDevice": 45,
|
||||
"MessageType_WordRequest": 46,
|
||||
"MessageType_WordAck": 47,
|
||||
"MessageType_GetFeatures": 55,
|
||||
"MessageType_SetU2FCounter": 63,
|
||||
"MessageType_FirmwareErase": 6,
|
||||
"MessageType_FirmwareUpload": 7,
|
||||
"MessageType_FirmwareRequest": 8,
|
||||
"MessageType_SelfTest": 32,
|
||||
"MessageType_GetPublicKey": 11,
|
||||
"MessageType_PublicKey": 12,
|
||||
"MessageType_SignTx": 15,
|
||||
"MessageType_TxRequest": 21,
|
||||
"MessageType_TxAck": 22,
|
||||
"MessageType_GetAddress": 29,
|
||||
"MessageType_Address": 30,
|
||||
"MessageType_SignMessage": 38,
|
||||
"MessageType_VerifyMessage": 39,
|
||||
"MessageType_MessageSignature": 40,
|
||||
"MessageType_CipherKeyValue": 23,
|
||||
"MessageType_CipheredKeyValue": 48,
|
||||
"MessageType_SignIdentity": 53,
|
||||
"MessageType_SignedIdentity": 54,
|
||||
"MessageType_GetECDHSessionKey": 61,
|
||||
"MessageType_ECDHSessionKey": 62,
|
||||
"MessageType_CosiCommit": 71,
|
||||
"MessageType_CosiCommitment": 72,
|
||||
"MessageType_CosiSign": 73,
|
||||
"MessageType_CosiSignature": 74,
|
||||
"MessageType_DebugLinkDecision": 100,
|
||||
"MessageType_DebugLinkGetState": 101,
|
||||
"MessageType_DebugLinkState": 102,
|
||||
"MessageType_DebugLinkStop": 103,
|
||||
"MessageType_DebugLinkLog": 104,
|
||||
"MessageType_DebugLinkMemoryRead": 110,
|
||||
"MessageType_DebugLinkMemory": 111,
|
||||
"MessageType_DebugLinkMemoryWrite": 112,
|
||||
"MessageType_DebugLinkFlashErase": 113,
|
||||
"MessageType_EthereumGetPublicKey": 450,
|
||||
"MessageType_EthereumPublicKey": 451,
|
||||
"MessageType_EthereumGetAddress": 56,
|
||||
"MessageType_EthereumAddress": 57,
|
||||
"MessageType_EthereumSignTx": 58,
|
||||
"MessageType_EthereumTxRequest": 59,
|
||||
"MessageType_EthereumTxAck": 60,
|
||||
"MessageType_EthereumSignMessage": 64,
|
||||
"MessageType_EthereumVerifyMessage": 65,
|
||||
"MessageType_EthereumMessageSignature": 66,
|
||||
"MessageType_NEMGetAddress": 67,
|
||||
"MessageType_NEMAddress": 68,
|
||||
"MessageType_NEMSignTx": 69,
|
||||
"MessageType_NEMSignedTx": 70,
|
||||
"MessageType_NEMDecryptMessage": 75,
|
||||
"MessageType_NEMDecryptedMessage": 76,
|
||||
"MessageType_LiskGetAddress": 114,
|
||||
"MessageType_LiskAddress": 115,
|
||||
"MessageType_LiskSignTx": 116,
|
||||
"MessageType_LiskSignedTx": 117,
|
||||
"MessageType_LiskSignMessage": 118,
|
||||
"MessageType_LiskMessageSignature": 119,
|
||||
"MessageType_LiskVerifyMessage": 120,
|
||||
"MessageType_LiskGetPublicKey": 121,
|
||||
"MessageType_LiskPublicKey": 122,
|
||||
"MessageType_TezosGetAddress": 150,
|
||||
"MessageType_TezosAddress": 151,
|
||||
"MessageType_TezosSignTx": 152,
|
||||
"MessageType_TezosSignedTx": 153,
|
||||
"MessageType_TezosGetPublicKey": 154,
|
||||
"MessageType_TezosPublicKey": 155,
|
||||
"MessageType_StellarSignTx": 202,
|
||||
"MessageType_StellarTxOpRequest": 203,
|
||||
"MessageType_StellarGetAddress": 207,
|
||||
"MessageType_StellarAddress": 208,
|
||||
"MessageType_StellarCreateAccountOp": 210,
|
||||
"MessageType_StellarPaymentOp": 211,
|
||||
"MessageType_StellarPathPaymentOp": 212,
|
||||
"MessageType_StellarManageOfferOp": 213,
|
||||
"MessageType_StellarCreatePassiveOfferOp": 214,
|
||||
"MessageType_StellarSetOptionsOp": 215,
|
||||
"MessageType_StellarChangeTrustOp": 216,
|
||||
"MessageType_StellarAllowTrustOp": 217,
|
||||
"MessageType_StellarAccountMergeOp": 218,
|
||||
"MessageType_StellarManageDataOp": 220,
|
||||
"MessageType_StellarBumpSequenceOp": 221,
|
||||
"MessageType_StellarSignedTx": 230,
|
||||
"MessageType_TronGetAddress": 250,
|
||||
"MessageType_TronAddress": 251,
|
||||
"MessageType_TronSignTx": 252,
|
||||
"MessageType_TronSignedTx": 253,
|
||||
"MessageType_CardanoSignTx": 303,
|
||||
"MessageType_CardanoTxRequest": 304,
|
||||
"MessageType_CardanoGetPublicKey": 305,
|
||||
"MessageType_CardanoPublicKey": 306,
|
||||
"MessageType_CardanoGetAddress": 307,
|
||||
"MessageType_CardanoAddress": 308,
|
||||
"MessageType_CardanoTxAck": 309,
|
||||
"MessageType_CardanoSignedTx": 310,
|
||||
"MessageType_OntologyGetAddress": 350,
|
||||
"MessageType_OntologyAddress": 351,
|
||||
"MessageType_OntologyGetPublicKey": 352,
|
||||
"MessageType_OntologyPublicKey": 353,
|
||||
"MessageType_OntologySignTransfer": 354,
|
||||
"MessageType_OntologySignedTransfer": 355,
|
||||
"MessageType_OntologySignWithdrawOng": 356,
|
||||
"MessageType_OntologySignedWithdrawOng": 357,
|
||||
"MessageType_OntologySignOntIdRegister": 358,
|
||||
"MessageType_OntologySignedOntIdRegister": 359,
|
||||
"MessageType_OntologySignOntIdAddAttributes": 360,
|
||||
"MessageType_OntologySignedOntIdAddAttributes": 361,
|
||||
"MessageType_RippleGetAddress": 400,
|
||||
"MessageType_RippleAddress": 401,
|
||||
"MessageType_RippleSignTx": 402,
|
||||
"MessageType_RippleSignedTx": 403,
|
||||
"MessageType_MoneroTransactionInitRequest": 501,
|
||||
"MessageType_MoneroTransactionInitAck": 502,
|
||||
"MessageType_MoneroTransactionSetInputRequest": 503,
|
||||
"MessageType_MoneroTransactionSetInputAck": 504,
|
||||
"MessageType_MoneroTransactionInputsPermutationRequest": 505,
|
||||
"MessageType_MoneroTransactionInputsPermutationAck": 506,
|
||||
"MessageType_MoneroTransactionInputViniRequest": 507,
|
||||
"MessageType_MoneroTransactionInputViniAck": 508,
|
||||
"MessageType_MoneroTransactionAllInputsSetRequest": 509,
|
||||
"MessageType_MoneroTransactionAllInputsSetAck": 510,
|
||||
"MessageType_MoneroTransactionSetOutputRequest": 511,
|
||||
"MessageType_MoneroTransactionSetOutputAck": 512,
|
||||
"MessageType_MoneroTransactionAllOutSetRequest": 513,
|
||||
"MessageType_MoneroTransactionAllOutSetAck": 514,
|
||||
"MessageType_MoneroTransactionSignInputRequest": 515,
|
||||
"MessageType_MoneroTransactionSignInputAck": 516,
|
||||
"MessageType_MoneroTransactionFinalRequest": 517,
|
||||
"MessageType_MoneroTransactionFinalAck": 518,
|
||||
"MessageType_MoneroKeyImageExportInitRequest": 530,
|
||||
"MessageType_MoneroKeyImageExportInitAck": 531,
|
||||
"MessageType_MoneroKeyImageSyncStepRequest": 532,
|
||||
"MessageType_MoneroKeyImageSyncStepAck": 533,
|
||||
"MessageType_MoneroKeyImageSyncFinalRequest": 534,
|
||||
"MessageType_MoneroKeyImageSyncFinalAck": 535,
|
||||
"MessageType_MoneroGetAddress": 540,
|
||||
"MessageType_MoneroAddress": 541,
|
||||
"MessageType_MoneroGetWatchKey": 542,
|
||||
"MessageType_MoneroWatchKey": 543,
|
||||
"MessageType_DebugMoneroDiagRequest": 546,
|
||||
"MessageType_DebugMoneroDiagAck": 547,
|
||||
"MessageType_MoneroGetTxKeyRequest": 550,
|
||||
"MessageType_MoneroGetTxKeyAck": 551,
|
||||
"MessageType_MoneroLiveRefreshStartRequest": 552,
|
||||
"MessageType_MoneroLiveRefreshStartAck": 553,
|
||||
"MessageType_MoneroLiveRefreshStepRequest": 554,
|
||||
"MessageType_MoneroLiveRefreshStepAck": 555,
|
||||
"MessageType_MoneroLiveRefreshFinalRequest": 556,
|
||||
"MessageType_MoneroLiveRefreshFinalAck": 557,
|
||||
"MessageType_EosGetPublicKey": 600,
|
||||
"MessageType_EosPublicKey": 601,
|
||||
"MessageType_EosSignTx": 602,
|
||||
"MessageType_EosTxActionRequest": 603,
|
||||
"MessageType_EosTxActionAck": 604,
|
||||
"MessageType_EosSignedTx": 605,
|
||||
"MessageType_BinanceGetAddress": 700,
|
||||
"MessageType_BinanceAddress": 701,
|
||||
"MessageType_BinanceGetPublicKey": 702,
|
||||
"MessageType_BinancePublicKey": 703,
|
||||
"MessageType_BinanceSignTx": 704,
|
||||
"MessageType_BinanceTxRequest": 705,
|
||||
"MessageType_BinanceTransferMsg": 706,
|
||||
"MessageType_BinanceOrderMsg": 707,
|
||||
"MessageType_BinanceCancelMsg": 708,
|
||||
"MessageType_BinanceSignedTx": 709,
|
||||
}
|
||||
|
||||
func (x MessageType) Enum() *MessageType {
|
||||
p := new(MessageType)
|
||||
*p = x
|
||||
return p
|
||||
}
|
||||
|
||||
func (x MessageType) String() string {
|
||||
return proto.EnumName(MessageType_name, int32(x))
|
||||
}
|
||||
|
||||
func (x *MessageType) UnmarshalJSON(data []byte) error {
|
||||
value, err := proto.UnmarshalJSONEnum(MessageType_value, data, "MessageType")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*x = MessageType(value)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (MessageType) EnumDescriptor() ([]byte, []int) {
|
||||
return fileDescriptor_4dc296cbfe5ffcd5, []int{0}
|
||||
}
|
||||
|
||||
var E_WireIn = &proto.ExtensionDesc{
|
||||
ExtendedType: (*descriptor.EnumValueOptions)(nil),
|
||||
ExtensionType: (*bool)(nil),
|
||||
Field: 50002,
|
||||
Name: "hw.trezor.messages.wire_in",
|
||||
Tag: "varint,50002,opt,name=wire_in",
|
||||
Filename: "messages.proto",
|
||||
}
|
||||
|
||||
var E_WireOut = &proto.ExtensionDesc{
|
||||
ExtendedType: (*descriptor.EnumValueOptions)(nil),
|
||||
ExtensionType: (*bool)(nil),
|
||||
Field: 50003,
|
||||
Name: "hw.trezor.messages.wire_out",
|
||||
Tag: "varint,50003,opt,name=wire_out",
|
||||
Filename: "messages.proto",
|
||||
}
|
||||
|
||||
var E_WireDebugIn = &proto.ExtensionDesc{
|
||||
ExtendedType: (*descriptor.EnumValueOptions)(nil),
|
||||
ExtensionType: (*bool)(nil),
|
||||
Field: 50004,
|
||||
Name: "hw.trezor.messages.wire_debug_in",
|
||||
Tag: "varint,50004,opt,name=wire_debug_in",
|
||||
Filename: "messages.proto",
|
||||
}
|
||||
|
||||
var E_WireDebugOut = &proto.ExtensionDesc{
|
||||
ExtendedType: (*descriptor.EnumValueOptions)(nil),
|
||||
ExtensionType: (*bool)(nil),
|
||||
Field: 50005,
|
||||
Name: "hw.trezor.messages.wire_debug_out",
|
||||
Tag: "varint,50005,opt,name=wire_debug_out",
|
||||
Filename: "messages.proto",
|
||||
}
|
||||
|
||||
var E_WireTiny = &proto.ExtensionDesc{
|
||||
ExtendedType: (*descriptor.EnumValueOptions)(nil),
|
||||
ExtensionType: (*bool)(nil),
|
||||
Field: 50006,
|
||||
Name: "hw.trezor.messages.wire_tiny",
|
||||
Tag: "varint,50006,opt,name=wire_tiny",
|
||||
Filename: "messages.proto",
|
||||
}
|
||||
|
||||
var E_WireBootloader = &proto.ExtensionDesc{
|
||||
ExtendedType: (*descriptor.EnumValueOptions)(nil),
|
||||
ExtensionType: (*bool)(nil),
|
||||
Field: 50007,
|
||||
Name: "hw.trezor.messages.wire_bootloader",
|
||||
Tag: "varint,50007,opt,name=wire_bootloader",
|
||||
Filename: "messages.proto",
|
||||
}
|
||||
|
||||
var E_WireNoFsm = &proto.ExtensionDesc{
|
||||
ExtendedType: (*descriptor.EnumValueOptions)(nil),
|
||||
ExtensionType: (*bool)(nil),
|
||||
Field: 50008,
|
||||
Name: "hw.trezor.messages.wire_no_fsm",
|
||||
Tag: "varint,50008,opt,name=wire_no_fsm",
|
||||
Filename: "messages.proto",
|
||||
}
|
||||
|
||||
func init() {
|
||||
proto.RegisterEnum("hw.trezor.messages.MessageType", MessageType_name, MessageType_value)
|
||||
proto.RegisterExtension(E_WireIn)
|
||||
proto.RegisterExtension(E_WireOut)
|
||||
proto.RegisterExtension(E_WireDebugIn)
|
||||
proto.RegisterExtension(E_WireDebugOut)
|
||||
proto.RegisterExtension(E_WireTiny)
|
||||
proto.RegisterExtension(E_WireBootloader)
|
||||
proto.RegisterExtension(E_WireNoFsm)
|
||||
}
|
||||
|
||||
func init() { proto.RegisterFile("messages.proto", fileDescriptor_4dc296cbfe5ffcd5) }
|
||||
|
||||
var fileDescriptor_4dc296cbfe5ffcd5 = []byte{
|
||||
// 2430 bytes of a gzipped FileDescriptorProto
|
||||
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x9a, 0xd9, 0x73, 0x1c, 0xc5,
|
||||
0x1d, 0xc7, 0xb3, 0xab, 0x11, 0x88, 0xf6, 0x41, 0x23, 0xb0, 0x2d, 0xaf, 0x2f, 0xf9, 0xc0, 0x96,
|
||||
0x2f, 0xd9, 0x10, 0x0c, 0x44, 0x38, 0x60, 0x69, 0xb5, 0x12, 0x8a, 0xb5, 0x5a, 0x97, 0x76, 0xb1,
|
||||
0x1f, 0x5d, 0xa3, 0x9d, 0xd6, 0x6e, 0x97, 0x67, 0x67, 0x86, 0x9e, 0x1e, 0x49, 0xeb, 0xa7, 0x9c,
|
||||
0x3c, 0x13, 0x48, 0xc0, 0xb9, 0xa9, 0xa4, 0x2a, 0x21, 0x57, 0x85, 0x1c, 0x4e, 0x25, 0x55, 0x39,
|
||||
0x08, 0x24, 0x2f, 0xc9, 0x43, 0x52, 0x9c, 0x86, 0x40, 0xee, 0x90, 0xe4, 0x0f, 0xc8, 0xc5, 0x91,
|
||||
0xa4, 0x7a, 0xa6, 0xbb, 0xe7, 0xd8, 0xdf, 0xae, 0x36, 0x6f, 0x58, 0xf3, 0xf9, 0x7d, 0x7f, 0x47,
|
||||
0xff, 0xfa, 0x37, 0xdd, 0xb3, 0xa0, 0xcd, 0x2d, 0xe2, 0xfb, 0x66, 0x83, 0xf8, 0xe3, 0x1e, 0x73,
|
||||
0xb9, 0x3b, 0x3c, 0xdc, 0x5c, 0x1d, 0xe7, 0x8c, 0x5c, 0x76, 0xd9, 0xb8, 0x7a, 0x52, 0x18, 0x6d,
|
||||
0xb8, 0x6e, 0xc3, 0x26, 0x27, 0x42, 0x62, 0x29, 0x58, 0x3e, 0x61, 0x11, 0xbf, 0xce, 0xa8, 0xc7,
|
||||
0x5d, 0x16, 0x59, 0x1d, 0xf9, 0xfe, 0x7d, 0x68, 0x43, 0x39, 0xc2, 0x6b, 0x6d, 0x8f, 0x0c, 0x1f,
|
||||
0x40, 0x5b, 0x13, 0xff, 0xbc, 0x38, 0xe7, 0x50, 0x4e, 0x4d, 0x9b, 0x5e, 0x26, 0xf8, 0x5d, 0x85,
|
||||
0xa1, 0x87, 0xaf, 0x8e, 0xe4, 0x9e, 0xba, 0x3a, 0x92, 0x1b, 0x2e, 0x20, 0x9c, 0xa4, 0xce, 0x51,
|
||||
0xa7, 0x81, 0x73, 0x05, 0x43, 0x3c, 0x1f, 0xde, 0x85, 0x6e, 0x4e, 0x3e, 0xab, 0x06, 0xf5, 0x3a,
|
||||
0xf1, 0x7d, 0x9c, 0x2f, 0x18, 0x57, 0x80, 0xc7, 0x33, 0x26, 0xb5, 0x03, 0x46, 0xf0, 0x80, 0x7c,
|
||||
0xbc, 0x07, 0x6d, 0x49, 0x3e, 0x2e, 0x36, 0x4d, 0xa7, 0x41, 0xce, 0x51, 0x07, 0x1b, 0x52, 0x7e,
|
||||
0x34, 0x1d, 0xe0, 0x05, 0xea, 0x91, 0x69, 0xb2, 0x42, 0xeb, 0x04, 0x0f, 0xc2, 0xc4, 0x2c, 0xe1,
|
||||
0x25, 0x87, 0x33, 0xd7, 0x6b, 0xe3, 0x1b, 0xe0, 0x10, 0xd5, 0x63, 0x24, 0x63, 0xc8, 0x08, 0xcc,
|
||||
0xbb, 0xa6, 0x25, 0x5d, 0x6c, 0x92, 0x02, 0x7b, 0xd1, 0xb6, 0x24, 0xb1, 0x48, 0x7c, 0xc2, 0x25,
|
||||
0xb2, 0x59, 0x22, 0xbb, 0xd1, 0x2d, 0xa9, 0x3c, 0x89, 0xc9, 0x03, 0x46, 0x7c, 0x7c, 0x93, 0x74,
|
||||
0x72, 0x10, 0xed, 0xcc, 0x94, 0xb0, 0x6c, 0x72, 0x46, 0xd7, 0x16, 0xc9, 0x83, 0x01, 0xf1, 0x39,
|
||||
0x1e, 0x96, 0xdc, 0x11, 0x34, 0x02, 0x72, 0x93, 0xf5, 0x4b, 0xf8, 0xe6, 0xc2, 0x46, 0xb5, 0x24,
|
||||
0x4f, 0x47, 0x81, 0x0f, 0xa7, 0x8a, 0x67, 0x3a, 0x75, 0x62, 0xe3, 0x5b, 0x12, 0x0b, 0xb7, 0x2f,
|
||||
0xad, 0x56, 0xb4, 0x89, 0xc9, 0xaa, 0xc4, 0xf7, 0xa9, 0xeb, 0xe0, 0x11, 0x19, 0xf9, 0x7e, 0xb4,
|
||||
0x3d, 0xc9, 0x4c, 0x7a, 0x9e, 0xdd, 0xae, 0x12, 0xce, 0xa9, 0xd3, 0xf0, 0xf1, 0x76, 0x18, 0x9a,
|
||||
0x0a, 0x38, 0x77, 0x1d, 0x15, 0x7b, 0x41, 0xc6, 0x7e, 0x28, 0xbd, 0x98, 0x11, 0x24, 0x02, 0xdf,
|
||||
0xd1, 0x11, 0xf8, 0xd6, 0x0e, 0x97, 0x33, 0xb6, 0xd9, 0xf0, 0xf1, 0x4e, 0xe9, 0x2f, 0x13, 0xf8,
|
||||
0x94, 0x59, 0xbf, 0x14, 0x78, 0xb2, 0xe4, 0xfb, 0x24, 0x73, 0x00, 0x15, 0x80, 0x65, 0x55, 0x41,
|
||||
0xed, 0x87, 0x57, 0x57, 0x52, 0x22, 0xaa, 0x03, 0x52, 0xe7, 0x10, 0xda, 0x95, 0x2a, 0xb9, 0xe9,
|
||||
0xfb, 0x5e, 0x93, 0x99, 0x3e, 0x51, 0x52, 0x87, 0xa5, 0xd4, 0xd1, 0x74, 0x11, 0x62, 0x50, 0xa8,
|
||||
0x1d, 0xc9, 0xe4, 0x78, 0x0c, 0xed, 0x83, 0xe1, 0x2a, 0x37, 0xb9, 0x96, 0x2e, 0x4b, 0xe9, 0x93,
|
||||
0x68, 0x77, 0x0f, 0x5a, 0xe8, 0x2f, 0x64, 0xf4, 0x33, 0xd9, 0x2f, 0x92, 0xba, 0xbb, 0x42, 0x58,
|
||||
0x5b, 0xd6, 0xe8, 0x38, 0xdc, 0xb9, 0x17, 0x5c, 0x66, 0x29, 0xd7, 0xe3, 0xf0, 0x0e, 0x15, 0x88,
|
||||
0xf0, 0x77, 0x02, 0x56, 0x98, 0x25, 0x5c, 0xf7, 0xf6, 0x5d, 0x70, 0x73, 0x54, 0x09, 0x7f, 0xe0,
|
||||
0xf6, 0x99, 0xa2, 0x1b, 0x38, 0x9c, 0x30, 0x7c, 0x9f, 0xae, 0x72, 0x0a, 0x9a, 0xa1, 0xac, 0xb5,
|
||||
0x6a, 0x32, 0x52, 0x12, 0x49, 0xe2, 0xeb, 0xa2, 0x9e, 0xfd, 0x9e, 0x00, 0xc7, 0xd2, 0x89, 0x29,
|
||||
0xf0, 0x01, 0xcf, 0x76, 0x4d, 0x0b, 0x5f, 0x9f, 0x20, 0x0f, 0xa3, 0x1d, 0x10, 0xa9, 0x12, 0x1c,
|
||||
0x2a, 0x0c, 0x5d, 0x51, 0xe8, 0xbe, 0xf4, 0xf6, 0xac, 0x12, 0x7b, 0xb9, 0x26, 0x98, 0xd1, 0x84,
|
||||
0x5c, 0xa6, 0xe7, 0x66, 0x09, 0x3f, 0x17, 0x2c, 0xd9, 0xb4, 0x7e, 0x96, 0xb4, 0xf1, 0x06, 0x99,
|
||||
0x45, 0x66, 0x5e, 0xc5, 0xc0, 0x46, 0x59, 0xcd, 0x9d, 0xe9, 0x3d, 0x59, 0xa5, 0x0d, 0xa7, 0xb6,
|
||||
0x86, 0x6f, 0x84, 0xcd, 0x6b, 0x7a, 0xfb, 0x6f, 0x91, 0xe6, 0x3b, 0xd0, 0x4d, 0x69, 0x40, 0x2c,
|
||||
0xc5, 0xd6, 0xae, 0x93, 0x6e, 0xd2, 0xb2, 0x98, 0x98, 0xb6, 0xbb, 0xe0, 0x49, 0xa7, 0x1e, 0xef,
|
||||
0x96, 0xea, 0x99, 0xb5, 0x14, 0xc1, 0xc9, 0x7f, 0xe3, 0x83, 0xf0, 0x5a, 0x9e, 0x27, 0x8c, 0x2e,
|
||||
0xb7, 0x15, 0x74, 0x48, 0x42, 0x99, 0x61, 0x26, 0xff, 0x5b, 0xc8, 0x85, 0x9d, 0x81, 0xc7, 0xa4,
|
||||
0xbf, 0x4c, 0x8f, 0x16, 0xa9, 0xd7, 0x24, 0xec, 0x2c, 0x69, 0x9f, 0x37, 0xed, 0x80, 0xe0, 0x6d,
|
||||
0xb0, 0x5a, 0x44, 0x11, 0x4b, 0x73, 0x27, 0xa5, 0x5a, 0x66, 0x7d, 0x84, 0xbb, 0x39, 0x8b, 0x38,
|
||||
0x9c, 0xf2, 0x36, 0x3e, 0x05, 0xcf, 0x04, 0xc1, 0x10, 0x4b, 0x53, 0x77, 0xea, 0x41, 0xb5, 0x2b,
|
||||
0xfb, 0xca, 0x28, 0x4e, 0xdf, 0x2f, 0x07, 0xa3, 0x58, 0xcd, 0xf7, 0x76, 0x19, 0x31, 0x69, 0xea,
|
||||
0x5e, 0x78, 0xc4, 0x14, 0x5d, 0x9f, 0x16, 0xdd, 0x56, 0x8b, 0x72, 0x3c, 0x0b, 0xeb, 0xc4, 0x44,
|
||||
0x8b, 0x38, 0x1c, 0xdf, 0x2f, 0x75, 0x32, 0xef, 0x10, 0x41, 0x89, 0x04, 0xf0, 0x1c, 0xbc, 0x36,
|
||||
0xea, 0x79, 0x54, 0xf3, 0xf7, 0x49, 0x91, 0x13, 0xe9, 0xdc, 0xa6, 0xc9, 0x52, 0xd0, 0x98, 0xa7,
|
||||
0xce, 0xa5, 0x69, 0x52, 0xa7, 0xe1, 0xdc, 0xb7, 0x0a, 0x1b, 0x9f, 0x48, 0x0e, 0x92, 0xa3, 0x5d,
|
||||
0x0c, 0x66, 0x09, 0x0f, 0x87, 0x0f, 0x26, 0x85, 0x21, 0x65, 0x90, 0x4d, 0x44, 0xc3, 0x11, 0xb9,
|
||||
0x5c, 0x30, 0x9e, 0x04, 0x02, 0x4d, 0x50, 0xae, 0x87, 0x1b, 0x05, 0xe3, 0x09, 0x60, 0x39, 0x35,
|
||||
0x34, 0xef, 0x36, 0x70, 0x53, 0x0a, 0x1d, 0x46, 0x7b, 0x40, 0xa6, 0x4c, 0x5a, 0x2e, 0x6b, 0x2f,
|
||||
0x12, 0xd3, 0xc2, 0x8e, 0x94, 0xbb, 0x35, 0x3d, 0x0c, 0x32, 0x28, 0x76, 0xa5, 0xe2, 0x11, 0x34,
|
||||
0xda, 0x03, 0xbb, 0xc0, 0x28, 0x27, 0xd8, 0x93, 0x92, 0xdd, 0xbc, 0xcf, 0xd8, 0xa6, 0xdf, 0x8c,
|
||||
0x06, 0xd7, 0x83, 0x12, 0x3d, 0x9a, 0x96, 0x2d, 0x71, 0xd1, 0xc2, 0x41, 0x2b, 0x35, 0x43, 0x9e,
|
||||
0x19, 0x90, 0xeb, 0x38, 0x96, 0xae, 0xb8, 0x82, 0x63, 0xf2, 0x59, 0x75, 0x3c, 0x1a, 0x4b, 0xbf,
|
||||
0x16, 0x12, 0xb2, 0x6a, 0x6b, 0xdf, 0x2d, 0x35, 0x33, 0xe9, 0x2b, 0x52, 0x61, 0xef, 0x81, 0x77,
|
||||
0xa4, 0xc2, 0xe4, 0x98, 0x9a, 0x80, 0xdf, 0x88, 0x8a, 0x8a, 0xc7, 0xd5, 0x3d, 0x52, 0x2e, 0xb3,
|
||||
0xd0, 0x31, 0x28, 0xc6, 0xd6, 0x69, 0xa9, 0x96, 0x29, 0x63, 0xd2, 0xa7, 0x1a, 0x2c, 0x67, 0x24,
|
||||
0x7a, 0x14, 0xed, 0x85, 0xd0, 0xf4, 0x14, 0x9a, 0x94, 0xf0, 0x38, 0x3a, 0x00, 0xc1, 0x1d, 0xd3,
|
||||
0x68, 0x0a, 0x0e, 0x76, 0xa1, 0x54, 0x4e, 0xd4, 0xb1, 0x08, 0xcf, 0xd8, 0x85, 0x52, 0x59, 0x11,
|
||||
0xd3, 0xf0, 0x91, 0x75, 0xa1, 0x54, 0x96, 0xd5, 0x2b, 0xc1, 0x6f, 0x4c, 0x09, 0x10, 0xab, 0xb6,
|
||||
0x86, 0x67, 0xe0, 0x01, 0xb4, 0x50, 0x2a, 0x4f, 0x93, 0x3a, 0x6b, 0x7b, 0x5c, 0xe5, 0x78, 0x16,
|
||||
0xae, 0x5d, 0x0c, 0x12, 0x4b, 0xa1, 0xf3, 0xf0, 0xd2, 0xce, 0x53, 0xff, 0x52, 0x22, 0x3f, 0x06,
|
||||
0x07, 0x27, 0x28, 0x85, 0xf8, 0x5d, 0xce, 0xc3, 0xd4, 0xbf, 0x24, 0x33, 0xe4, 0xf0, 0xe9, 0x4c,
|
||||
0x11, 0x61, 0x8a, 0x81, 0x54, 0xc9, 0x34, 0xa4, 0x62, 0x54, 0xd4, 0x2b, 0x52, 0x2a, 0xb3, 0x1f,
|
||||
0x05, 0xd6, 0xb1, 0x80, 0xab, 0x70, 0xd5, 0x04, 0x9b, 0xee, 0x8c, 0x35, 0xf8, 0x8d, 0x22, 0x4b,
|
||||
0x11, 0xef, 0xaf, 0x36, 0x3c, 0x50, 0x05, 0x17, 0x43, 0x97, 0xf5, 0xc9, 0x3d, 0x95, 0x48, 0x8d,
|
||||
0x5c, 0x76, 0xfd, 0x44, 0x61, 0x1f, 0xcb, 0x69, 0xb1, 0x91, 0x0e, 0x4e, 0x41, 0x8f, 0xe7, 0xf4,
|
||||
0x3b, 0x6c, 0x5b, 0x07, 0x24, 0x8b, 0x7b, 0x25, 0xa7, 0x5f, 0x16, 0xdb, 0x41, 0x26, 0x2c, 0xef,
|
||||
0x27, 0x72, 0x7a, 0x34, 0xec, 0x82, 0xc2, 0x8a, 0xe3, 0xff, 0x64, 0x4e, 0x8f, 0x86, 0x42, 0x07,
|
||||
0x19, 0x63, 0x9f, 0xca, 0xe9, 0xfe, 0x49, 0x9f, 0xe2, 0x38, 0xb1, 0x6d, 0x93, 0xc9, 0xe0, 0x7e,
|
||||
0x9e, 0xd3, 0x0d, 0xb9, 0x1b, 0xa0, 0x6a, 0x6b, 0x15, 0x4f, 0xcd, 0x86, 0x5f, 0x74, 0x89, 0x50,
|
||||
0xa2, 0x89, 0xd2, 0xfd, 0xb2, 0x4b, 0x84, 0x92, 0x54, 0xd8, 0xaf, 0x94, 0xe0, 0xf1, 0xf4, 0x91,
|
||||
0x5a, 0x62, 0x45, 0x46, 0xc2, 0x23, 0x72, 0x5d, 0x1c, 0x38, 0x2b, 0x1e, 0x7e, 0x2e, 0xa7, 0xa7,
|
||||
0xd8, 0x4e, 0x00, 0x3f, 0x67, 0xb6, 0xc5, 0x4b, 0xb7, 0xe2, 0xe1, 0xe7, 0x73, 0x7a, 0xea, 0x8c,
|
||||
0x82, 0x20, 0x6f, 0xc6, 0xf0, 0x0b, 0xbd, 0xe1, 0xb2, 0xe9, 0x98, 0x0d, 0x52, 0x59, 0x5e, 0x26,
|
||||
0xac, 0xe2, 0xe1, 0x17, 0x15, 0x7c, 0x3b, 0x3a, 0xd4, 0x35, 0x62, 0x71, 0xc6, 0xa7, 0x2b, 0xda,
|
||||
0xe6, 0xa5, 0x9c, 0xde, 0x11, 0x7b, 0xa0, 0x75, 0x20, 0xbc, 0xe2, 0x71, 0xea, 0x3a, 0x7e, 0xc5,
|
||||
0xc3, 0x2f, 0xf7, 0x0e, 0x26, 0xba, 0x45, 0xd7, 0x58, 0xe0, 0x8b, 0xc8, 0xaf, 0xf5, 0x16, 0x9e,
|
||||
0xb4, 0x6d, 0x77, 0x55, 0xb1, 0xaf, 0x28, 0xf6, 0x58, 0x7a, 0x10, 0x2b, 0x36, 0x2a, 0x72, 0x99,
|
||||
0xb0, 0x06, 0xa9, 0x78, 0xf8, 0xd5, 0xde, 0xca, 0x51, 0x4d, 0xa6, 0x4d, 0x6e, 0x56, 0x3c, 0xfc,
|
||||
0x5a, 0x6f, 0xe5, 0xa9, 0xa0, 0xe5, 0x55, 0x45, 0x03, 0x39, 0x75, 0xa1, 0xfc, 0x7a, 0x4e, 0xef,
|
||||
0xe4, 0x1d, 0x5d, 0x9a, 0x32, 0xdc, 0x0d, 0x6f, 0xe4, 0xf4, 0xb4, 0x49, 0xf7, 0x38, 0x73, 0x9d,
|
||||
0x44, 0xa3, 0xbd, 0x99, 0xd3, 0x83, 0x6b, 0x5b, 0x16, 0x53, 0xcc, 0x5b, 0x39, 0x7d, 0x48, 0xde,
|
||||
0x9a, 0x65, 0xe4, 0x26, 0x78, 0xbb, 0xdb, 0x56, 0x97, 0x48, 0x18, 0xd2, 0x3b, 0x5d, 0xf6, 0x53,
|
||||
0xd1, 0x64, 0x96, 0xe9, 0xb8, 0x52, 0xea, 0x1b, 0x79, 0xb8, 0x49, 0x25, 0x15, 0xbf, 0x69, 0x9f,
|
||||
0xca, 0xeb, 0x0f, 0x03, 0x7b, 0x00, 0x30, 0xb5, 0xe3, 0xbf, 0xd9, 0x5b, 0x34, 0x06, 0xbf, 0x95,
|
||||
0x87, 0xb7, 0x68, 0x2c, 0xaa, 0xaa, 0xf2, 0xed, 0x3c, 0xbc, 0x45, 0x25, 0xa9, 0xb0, 0xef, 0xe4,
|
||||
0xf5, 0x3b, 0x76, 0x04, 0x4c, 0x47, 0x9c, 0x07, 0xae, 0xe6, 0xe1, 0x45, 0x4d, 0x54, 0x26, 0xac,
|
||||
0xe0, 0x77, 0x95, 0x58, 0x66, 0xd6, 0x54, 0x1c, 0xee, 0xda, 0x6e, 0xa3, 0x9d, 0x08, 0xef, 0x37,
|
||||
0x5d, 0x24, 0x15, 0xaa, 0xb8, 0xdf, 0xe6, 0xf5, 0x15, 0x7e, 0xb4, 0x8b, 0x64, 0x5c, 0x9d, 0xdf,
|
||||
0xe5, 0xe1, 0x73, 0x9a, 0x82, 0x63, 0xf2, 0xf7, 0xeb, 0xc8, 0x86, 0x8b, 0xcd, 0x4c, 0xc7, 0x5f,
|
||||
0x26, 0x0c, 0xff, 0x41, 0xc9, 0x66, 0xc6, 0x58, 0x12, 0x26, 0x96, 0xc6, 0xff, 0xa8, 0xb4, 0xc7,
|
||||
0xd1, 0xfe, 0x6e, 0xf8, 0x05, 0xca, 0x9b, 0x16, 0x33, 0x57, 0x2b, 0x4e, 0x03, 0xff, 0x49, 0xc9,
|
||||
0x9f, 0x44, 0xb7, 0x76, 0x97, 0x4f, 0x5a, 0xfc, 0x39, 0xaf, 0x3f, 0x3e, 0x74, 0xb5, 0xa8, 0x38,
|
||||
0x7c, 0xce, 0x5a, 0x24, 0x0d, 0xea, 0x8b, 0xbb, 0xfc, 0x1b, 0x79, 0x78, 0xae, 0xa5, 0x7d, 0xa4,
|
||||
0x6d, 0xfe, 0xa2, 0xbc, 0x9c, 0x42, 0x47, 0x7a, 0x7a, 0x99, 0xb4, 0xac, 0x49, 0xce, 0x19, 0x5d,
|
||||
0x0a, 0x38, 0xf1, 0xf1, 0x5f, 0x95, 0xab, 0xbb, 0xd0, 0xb1, 0x75, 0x5c, 0xa5, 0x0d, 0xff, 0x96,
|
||||
0xd7, 0xa7, 0x85, 0xd4, 0x26, 0x58, 0xa4, 0x9e, 0x67, 0x93, 0x44, 0xef, 0x3c, 0x3c, 0x00, 0xbf,
|
||||
0x6f, 0x23, 0x50, 0x51, 0x1f, 0x1d, 0x80, 0x3b, 0x3b, 0xa2, 0xe4, 0x6e, 0x7e, 0x64, 0x00, 0xde,
|
||||
0x25, 0x31, 0x14, 0x36, 0xf6, 0xa3, 0x0a, 0x7b, 0x37, 0x1a, 0x4b, 0xdd, 0x9f, 0x5d, 0x87, 0x30,
|
||||
0x37, 0x5c, 0x79, 0xb3, 0x2e, 0x66, 0xfc, 0x9c, 0x43, 0xb9, 0x1a, 0x00, 0x7f, 0x1f, 0xd0, 0x17,
|
||||
0xbb, 0x03, 0xeb, 0x1a, 0x89, 0x6d, 0xf6, 0x0f, 0x65, 0x90, 0xa9, 0x5c, 0x87, 0x41, 0x95, 0xf0,
|
||||
0x39, 0xc7, 0x0b, 0xb4, 0xa7, 0x7f, 0x2a, 0xc3, 0xf5, 0xc2, 0x53, 0x86, 0xc2, 0xdb, 0xbf, 0x94,
|
||||
0xd1, 0x19, 0x74, 0x6a, 0x9d, 0xf0, 0xbc, 0x80, 0xfb, 0xe7, 0x08, 0x6b, 0x05, 0xdc, 0x14, 0x7f,
|
||||
0x50, 0x6e, 0xff, 0xad, 0x14, 0x4e, 0xa3, 0xdb, 0xfe, 0x3f, 0x05, 0xe1, 0xff, 0x4d, 0x65, 0x7d,
|
||||
0x37, 0x3a, 0xbe, 0xbe, 0xf5, 0x79, 0xea, 0x50, 0xe5, 0xf7, 0x2d, 0x65, 0x79, 0x07, 0x3a, 0xdc,
|
||||
0x9f, 0xa5, 0xf0, 0xf7, 0xb6, 0xb2, 0xba, 0x07, 0x9d, 0xec, 0x69, 0x35, 0x69, 0xdb, 0x51, 0xc0,
|
||||
0x55, 0xa2, 0x2b, 0xfc, 0x4e, 0xbf, 0x4b, 0x93, 0x34, 0x16, 0x5e, 0xff, 0xd3, 0x6f, 0x96, 0xe2,
|
||||
0x98, 0x10, 0xf0, 0xc4, 0xa2, 0xfe, 0xb7, 0xdf, 0x2c, 0xb5, 0xa5, 0xf0, 0xf7, 0x7e, 0xa3, 0x4f,
|
||||
0x7f, 0x93, 0xb6, 0x5d, 0x09, 0x78, 0x22, 0xc5, 0x0f, 0x18, 0x7d, 0xfa, 0xd3, 0x96, 0xc2, 0xdf,
|
||||
0x07, 0xfb, 0xf5, 0x17, 0x7e, 0xf4, 0x49, 0x36, 0xed, 0x87, 0xfa, 0xf5, 0xa7, 0x2d, 0x85, 0xbf,
|
||||
0x0f, 0xf7, 0x6b, 0x35, 0x43, 0x1d, 0xd3, 0x56, 0xbe, 0x3e, 0x62, 0xc0, 0x03, 0x13, 0xb6, 0x12,
|
||||
0x7e, 0x1e, 0x52, 0x16, 0x77, 0xa2, 0xa3, 0x9d, 0x16, 0x67, 0x49, 0x7b, 0xae, 0x65, 0x36, 0x48,
|
||||
0x69, 0xcd, 0x73, 0x19, 0x4f, 0x6e, 0xfa, 0x47, 0x94, 0x5d, 0x66, 0xd0, 0x76, 0xb3, 0x13, 0xbe,
|
||||
0x1e, 0xed, 0x99, 0x93, 0xb2, 0xa9, 0xb6, 0x9d, 0x7a, 0x95, 0x13, 0x7d, 0x5a, 0xff, 0x58, 0xcf,
|
||||
0x9c, 0xb2, 0x56, 0xc2, 0xcf, 0xc7, 0x0d, 0x78, 0xa0, 0x77, 0x5a, 0xa4, 0x8a, 0xf7, 0x98, 0x32,
|
||||
0xbb, 0x0d, 0x1d, 0xec, 0xc3, 0x4c, 0x78, 0x7a, 0xdc, 0x80, 0x47, 0x79, 0x64, 0x92, 0x18, 0xe5,
|
||||
0x9f, 0x36, 0xe0, 0x51, 0x1e, 0x81, 0x8a, 0xfa, 0x8c, 0x01, 0x9f, 0x7a, 0xb4, 0xdc, 0x05, 0x93,
|
||||
0xd7, 0x9b, 0xe2, 0xbd, 0xfe, 0x59, 0x03, 0x9e, 0xe7, 0x11, 0xa9, 0xb1, 0xcf, 0x19, 0xf0, 0xc5,
|
||||
0x24, 0xfc, 0x50, 0x14, 0xb1, 0xd3, 0xd4, 0x6c, 0xa8, 0x0a, 0x7c, 0xde, 0x80, 0xef, 0x50, 0x19,
|
||||
0x5c, 0x64, 0xfe, 0x05, 0xa5, 0x9c, 0x39, 0x2d, 0xeb, 0x50, 0x6b, 0x6b, 0x67, 0x89, 0xfe, 0xa9,
|
||||
0xe3, 0x8b, 0x06, 0x7c, 0x60, 0x49, 0xd3, 0x42, 0xf7, 0x4b, 0x3d, 0x7b, 0x64, 0x9e, 0xae, 0x90,
|
||||
0x45, 0xb2, 0xcc, 0x88, 0xdf, 0xac, 0x72, 0x93, 0xe9, 0x6e, 0x7c, 0xd2, 0x80, 0x8f, 0x16, 0xb0,
|
||||
0x95, 0xf0, 0xf3, 0x65, 0xa3, 0xd7, 0xab, 0x24, 0x65, 0x11, 0xb7, 0xe2, 0x57, 0x94, 0x1b, 0xf0,
|
||||
0x4d, 0x97, 0x31, 0x12, 0x5e, 0xbe, 0xda, 0x6f, 0x36, 0xa9, 0x46, 0xfc, 0x5a, 0xbf, 0xd9, 0xe8,
|
||||
0x3e, 0xfc, 0xba, 0x01, 0x7f, 0x0a, 0x28, 0x65, 0x6e, 0xdc, 0xd7, 0x0c, 0xf8, 0x7e, 0x50, 0x4a,
|
||||
0xde, 0xb7, 0x5f, 0x31, 0xf4, 0x67, 0x96, 0x2d, 0x19, 0x48, 0x9e, 0x26, 0x5e, 0xed, 0xd2, 0x27,
|
||||
0x25, 0xd7, 0x17, 0x07, 0xe9, 0xe4, 0xbb, 0xf3, 0xd7, 0x06, 0x7c, 0xff, 0x49, 0xa0, 0x22, 0x81,
|
||||
0xd7, 0x0c, 0xf8, 0xfe, 0x53, 0x4a, 0x7c, 0x58, 0x78, 0xbd, 0xcb, 0xee, 0x98, 0xa2, 0x8e, 0xe9,
|
||||
0xd4, 0x93, 0x07, 0xa7, 0x1f, 0x0c, 0xc2, 0xbb, 0x43, 0x92, 0x0a, 0xfb, 0xe1, 0x20, 0x7c, 0x73,
|
||||
0x89, 0x05, 0xe3, 0xa2, 0xfc, 0x68, 0x10, 0xbe, 0xb9, 0x48, 0x36, 0x06, 0x7f, 0x3c, 0x08, 0xdf,
|
||||
0xae, 0x24, 0x28, 0x2b, 0xf8, 0x74, 0x6f, 0xb9, 0xf8, 0x76, 0xf5, 0x93, 0x41, 0xf8, 0xaa, 0xa1,
|
||||
0x40, 0x79, 0x18, 0x2f, 0xfb, 0x0d, 0xfc, 0xcc, 0x20, 0x7c, 0xd5, 0x90, 0x68, 0x85, 0x59, 0x11,
|
||||
0xf7, 0x6c, 0x6f, 0xdf, 0xd1, 0x8f, 0xb4, 0x02, 0xfc, 0x69, 0x6f, 0x41, 0xbd, 0x30, 0x3f, 0x93,
|
||||
0x31, 0x4e, 0x9c, 0x46, 0xd7, 0xaf, 0x52, 0x46, 0x2e, 0x52, 0x67, 0x78, 0xef, 0x78, 0xf4, 0x4b,
|
||||
0xff, 0xb8, 0xfa, 0xa5, 0x7f, 0xbc, 0xe4, 0x04, 0xad, 0xf0, 0xe7, 0x12, 0xf9, 0x95, 0x60, 0xe4,
|
||||
0xb9, 0x87, 0x06, 0x46, 0x73, 0x63, 0x43, 0x8b, 0xd7, 0x09, 0x9b, 0x39, 0x67, 0xe2, 0x5e, 0x34,
|
||||
0x14, 0x5a, 0xbb, 0x01, 0xef, 0xc7, 0xfc, 0x79, 0x69, 0x1e, 0xba, 0xac, 0x04, 0x7c, 0x62, 0x16,
|
||||
0x6d, 0x0a, 0xed, 0x2d, 0x31, 0xad, 0xfa, 0x8c, 0xe1, 0x05, 0x29, 0xb2, 0x41, 0x58, 0x86, 0x63,
|
||||
0x6e, 0xce, 0x99, 0x98, 0x43, 0x9b, 0x13, 0x42, 0x7d, 0x86, 0xf3, 0xa2, 0x54, 0xda, 0xa8, 0x95,
|
||||
0x44, 0x4c, 0x67, 0xd0, 0x0d, 0xa1, 0x14, 0xa7, 0x4e, 0xbb, 0x1f, 0x95, 0x97, 0xa4, 0x4a, 0x58,
|
||||
0x89, 0x1a, 0x75, 0xda, 0x13, 0xf3, 0xe8, 0xc6, 0x50, 0x61, 0xc9, 0x75, 0xb9, 0xed, 0x9a, 0x16,
|
||||
0x61, 0xfd, 0xe8, 0xbc, 0x2c, 0x75, 0xc2, 0x44, 0xa6, 0xb4, 0xe9, 0x44, 0x11, 0x85, 0x99, 0x5e,
|
||||
0x74, 0xdc, 0x8b, 0xcb, 0x7e, 0xab, 0x1f, 0xa5, 0x6b, 0x52, 0x29, 0xcc, 0x63, 0xc1, 0x9d, 0xf1,
|
||||
0x5b, 0x53, 0x77, 0xa0, 0xfd, 0x75, 0xb7, 0x35, 0xee, 0x9b, 0xdc, 0xf5, 0x9b, 0xd4, 0x36, 0x97,
|
||||
0x7c, 0xf5, 0xff, 0x79, 0xd8, 0x74, 0x49, 0x4b, 0x4d, 0x6d, 0xaa, 0x85, 0x7f, 0x94, 0x9d, 0xf3,
|
||||
0xbf, 0x00, 0x00, 0x00, 0xff, 0xff, 0xa3, 0x69, 0x67, 0x5d, 0x1f, 0x22, 0x00, 0x00,
|
||||
}
|
264
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/trezor/messages.proto
generated
vendored
Normal file
264
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/trezor/messages.proto
generated
vendored
Normal file
@ -0,0 +1,264 @@
|
||||
// This file originates from the SatoshiLabs Trezor `common` repository at:
|
||||
// https://github.com/trezor/trezor-common/blob/master/protob/messages.proto
|
||||
// dated 28.05.2019, commit 893fd219d4a01bcffa0cd9cfa631856371ec5aa9.
|
||||
|
||||
syntax = "proto2";
|
||||
package hw.trezor.messages;
|
||||
|
||||
/**
|
||||
* Messages for TREZOR communication
|
||||
*/
|
||||
|
||||
// Sugar for easier handling in Java
|
||||
option java_package = "com.satoshilabs.trezor.lib.protobuf";
|
||||
option java_outer_classname = "TrezorMessage";
|
||||
|
||||
import "google/protobuf/descriptor.proto";
|
||||
|
||||
/**
|
||||
* Options for specifying message direction and type of wire (normal/debug)
|
||||
*/
|
||||
extend google.protobuf.EnumValueOptions {
|
||||
optional bool wire_in = 50002; // message can be transmitted via wire from PC to TREZOR
|
||||
optional bool wire_out = 50003; // message can be transmitted via wire from TREZOR to PC
|
||||
optional bool wire_debug_in = 50004; // message can be transmitted via debug wire from PC to TREZOR
|
||||
optional bool wire_debug_out = 50005; // message can be transmitted via debug wire from TREZOR to PC
|
||||
optional bool wire_tiny = 50006; // message is handled by TREZOR when the USB stack is in tiny mode
|
||||
optional bool wire_bootloader = 50007; // message is only handled by TREZOR Bootloader
|
||||
optional bool wire_no_fsm = 50008; // message is not handled by TREZOR unless the USB stack is in tiny mode
|
||||
}
|
||||
|
||||
/**
|
||||
* Mapping between TREZOR wire identifier (uint) and a protobuf message
|
||||
*/
|
||||
enum MessageType {
|
||||
|
||||
// Management
|
||||
MessageType_Initialize = 0 [(wire_in) = true, (wire_tiny) = true];
|
||||
MessageType_Ping = 1 [(wire_in) = true];
|
||||
MessageType_Success = 2 [(wire_out) = true];
|
||||
MessageType_Failure = 3 [(wire_out) = true];
|
||||
MessageType_ChangePin = 4 [(wire_in) = true];
|
||||
MessageType_WipeDevice = 5 [(wire_in) = true];
|
||||
MessageType_GetEntropy = 9 [(wire_in) = true];
|
||||
MessageType_Entropy = 10 [(wire_out) = true];
|
||||
MessageType_LoadDevice = 13 [(wire_in) = true];
|
||||
MessageType_ResetDevice = 14 [(wire_in) = true];
|
||||
MessageType_Features = 17 [(wire_out) = true];
|
||||
MessageType_PinMatrixRequest = 18 [(wire_out) = true];
|
||||
MessageType_PinMatrixAck = 19 [(wire_in) = true, (wire_tiny) = true, (wire_no_fsm) = true];
|
||||
MessageType_Cancel = 20 [(wire_in) = true, (wire_tiny) = true];
|
||||
MessageType_ClearSession = 24 [(wire_in) = true];
|
||||
MessageType_ApplySettings = 25 [(wire_in) = true];
|
||||
MessageType_ButtonRequest = 26 [(wire_out) = true];
|
||||
MessageType_ButtonAck = 27 [(wire_in) = true, (wire_tiny) = true, (wire_no_fsm) = true];
|
||||
MessageType_ApplyFlags = 28 [(wire_in) = true];
|
||||
MessageType_BackupDevice = 34 [(wire_in) = true];
|
||||
MessageType_EntropyRequest = 35 [(wire_out) = true];
|
||||
MessageType_EntropyAck = 36 [(wire_in) = true];
|
||||
MessageType_PassphraseRequest = 41 [(wire_out) = true];
|
||||
MessageType_PassphraseAck = 42 [(wire_in) = true, (wire_tiny) = true, (wire_no_fsm) = true];
|
||||
MessageType_PassphraseStateRequest = 77 [(wire_out) = true];
|
||||
MessageType_PassphraseStateAck = 78 [(wire_in) = true, (wire_tiny) = true, (wire_no_fsm) = true];
|
||||
MessageType_RecoveryDevice = 45 [(wire_in) = true];
|
||||
MessageType_WordRequest = 46 [(wire_out) = true];
|
||||
MessageType_WordAck = 47 [(wire_in) = true];
|
||||
MessageType_GetFeatures = 55 [(wire_in) = true];
|
||||
MessageType_SetU2FCounter = 63 [(wire_in) = true];
|
||||
|
||||
// Bootloader
|
||||
MessageType_FirmwareErase = 6 [(wire_in) = true, (wire_bootloader) = true];
|
||||
MessageType_FirmwareUpload = 7 [(wire_in) = true, (wire_bootloader) = true];
|
||||
MessageType_FirmwareRequest = 8 [(wire_out) = true, (wire_bootloader) = true];
|
||||
MessageType_SelfTest = 32 [(wire_in) = true, (wire_bootloader) = true];
|
||||
|
||||
// Bitcoin
|
||||
MessageType_GetPublicKey = 11 [(wire_in) = true];
|
||||
MessageType_PublicKey = 12 [(wire_out) = true];
|
||||
MessageType_SignTx = 15 [(wire_in) = true];
|
||||
MessageType_TxRequest = 21 [(wire_out) = true];
|
||||
MessageType_TxAck = 22 [(wire_in) = true];
|
||||
MessageType_GetAddress = 29 [(wire_in) = true];
|
||||
MessageType_Address = 30 [(wire_out) = true];
|
||||
MessageType_SignMessage = 38 [(wire_in) = true];
|
||||
MessageType_VerifyMessage = 39 [(wire_in) = true];
|
||||
MessageType_MessageSignature = 40 [(wire_out) = true];
|
||||
|
||||
// Crypto
|
||||
MessageType_CipherKeyValue = 23 [(wire_in) = true];
|
||||
MessageType_CipheredKeyValue = 48 [(wire_out) = true];
|
||||
MessageType_SignIdentity = 53 [(wire_in) = true];
|
||||
MessageType_SignedIdentity = 54 [(wire_out) = true];
|
||||
MessageType_GetECDHSessionKey = 61 [(wire_in) = true];
|
||||
MessageType_ECDHSessionKey = 62 [(wire_out) = true];
|
||||
MessageType_CosiCommit = 71 [(wire_in) = true];
|
||||
MessageType_CosiCommitment = 72 [(wire_out) = true];
|
||||
MessageType_CosiSign = 73 [(wire_in) = true];
|
||||
MessageType_CosiSignature = 74 [(wire_out) = true];
|
||||
|
||||
// Debug
|
||||
MessageType_DebugLinkDecision = 100 [(wire_debug_in) = true, (wire_tiny) = true, (wire_no_fsm) = true];
|
||||
MessageType_DebugLinkGetState = 101 [(wire_debug_in) = true, (wire_tiny) = true];
|
||||
MessageType_DebugLinkState = 102 [(wire_debug_out) = true];
|
||||
MessageType_DebugLinkStop = 103 [(wire_debug_in) = true];
|
||||
MessageType_DebugLinkLog = 104 [(wire_debug_out) = true];
|
||||
MessageType_DebugLinkMemoryRead = 110 [(wire_debug_in) = true];
|
||||
MessageType_DebugLinkMemory = 111 [(wire_debug_out) = true];
|
||||
MessageType_DebugLinkMemoryWrite = 112 [(wire_debug_in) = true];
|
||||
MessageType_DebugLinkFlashErase = 113 [(wire_debug_in) = true];
|
||||
|
||||
// Ethereum
|
||||
MessageType_EthereumGetPublicKey = 450 [(wire_in) = true];
|
||||
MessageType_EthereumPublicKey = 451 [(wire_out) = true];
|
||||
MessageType_EthereumGetAddress = 56 [(wire_in) = true];
|
||||
MessageType_EthereumAddress = 57 [(wire_out) = true];
|
||||
MessageType_EthereumSignTx = 58 [(wire_in) = true];
|
||||
MessageType_EthereumTxRequest = 59 [(wire_out) = true];
|
||||
MessageType_EthereumTxAck = 60 [(wire_in) = true];
|
||||
MessageType_EthereumSignMessage = 64 [(wire_in) = true];
|
||||
MessageType_EthereumVerifyMessage = 65 [(wire_in) = true];
|
||||
MessageType_EthereumMessageSignature = 66 [(wire_out) = true];
|
||||
|
||||
// NEM
|
||||
MessageType_NEMGetAddress = 67 [(wire_in) = true];
|
||||
MessageType_NEMAddress = 68 [(wire_out) = true];
|
||||
MessageType_NEMSignTx = 69 [(wire_in) = true];
|
||||
MessageType_NEMSignedTx = 70 [(wire_out) = true];
|
||||
MessageType_NEMDecryptMessage = 75 [(wire_in) = true];
|
||||
MessageType_NEMDecryptedMessage = 76 [(wire_out) = true];
|
||||
|
||||
// Lisk
|
||||
MessageType_LiskGetAddress = 114 [(wire_in) = true];
|
||||
MessageType_LiskAddress = 115 [(wire_out) = true];
|
||||
MessageType_LiskSignTx = 116 [(wire_in) = true];
|
||||
MessageType_LiskSignedTx = 117 [(wire_out) = true];
|
||||
MessageType_LiskSignMessage = 118 [(wire_in) = true];
|
||||
MessageType_LiskMessageSignature = 119 [(wire_out) = true];
|
||||
MessageType_LiskVerifyMessage = 120 [(wire_in) = true];
|
||||
MessageType_LiskGetPublicKey = 121 [(wire_in) = true];
|
||||
MessageType_LiskPublicKey = 122 [(wire_out) = true];
|
||||
|
||||
// Tezos
|
||||
MessageType_TezosGetAddress = 150 [(wire_in) = true];
|
||||
MessageType_TezosAddress = 151 [(wire_out) = true];
|
||||
MessageType_TezosSignTx = 152 [(wire_in) = true];
|
||||
MessageType_TezosSignedTx = 153 [(wire_out) = true];
|
||||
MessageType_TezosGetPublicKey = 154 [(wire_in) = true];
|
||||
MessageType_TezosPublicKey = 155 [(wire_out) = true];
|
||||
|
||||
// Stellar
|
||||
MessageType_StellarSignTx = 202 [(wire_in) = true];
|
||||
MessageType_StellarTxOpRequest = 203 [(wire_out) = true];
|
||||
MessageType_StellarGetAddress = 207 [(wire_in) = true];
|
||||
MessageType_StellarAddress = 208 [(wire_out) = true];
|
||||
MessageType_StellarCreateAccountOp = 210 [(wire_in) = true];
|
||||
MessageType_StellarPaymentOp = 211 [(wire_in) = true];
|
||||
MessageType_StellarPathPaymentOp = 212 [(wire_in) = true];
|
||||
MessageType_StellarManageOfferOp = 213 [(wire_in) = true];
|
||||
MessageType_StellarCreatePassiveOfferOp = 214 [(wire_in) = true];
|
||||
MessageType_StellarSetOptionsOp = 215 [(wire_in) = true];
|
||||
MessageType_StellarChangeTrustOp = 216 [(wire_in) = true];
|
||||
MessageType_StellarAllowTrustOp = 217 [(wire_in) = true];
|
||||
MessageType_StellarAccountMergeOp = 218 [(wire_in) = true];
|
||||
// omitted: StellarInflationOp is not a supported operation, would be 219
|
||||
MessageType_StellarManageDataOp = 220 [(wire_in) = true];
|
||||
MessageType_StellarBumpSequenceOp = 221 [(wire_in) = true];
|
||||
MessageType_StellarSignedTx = 230 [(wire_out) = true];
|
||||
|
||||
// TRON
|
||||
MessageType_TronGetAddress = 250 [(wire_in) = true];
|
||||
MessageType_TronAddress = 251 [(wire_out) = true];
|
||||
MessageType_TronSignTx = 252 [(wire_in) = true];
|
||||
MessageType_TronSignedTx = 253 [(wire_out) = true];
|
||||
|
||||
// Cardano
|
||||
// dropped Sign/VerifyMessage ids 300-302
|
||||
MessageType_CardanoSignTx = 303 [(wire_in) = true];
|
||||
MessageType_CardanoTxRequest = 304 [(wire_out) = true];
|
||||
MessageType_CardanoGetPublicKey = 305 [(wire_in) = true];
|
||||
MessageType_CardanoPublicKey = 306 [(wire_out) = true];
|
||||
MessageType_CardanoGetAddress = 307 [(wire_in) = true];
|
||||
MessageType_CardanoAddress = 308 [(wire_out) = true];
|
||||
MessageType_CardanoTxAck = 309 [(wire_in) = true];
|
||||
MessageType_CardanoSignedTx = 310 [(wire_out) = true];
|
||||
|
||||
// Ontology
|
||||
MessageType_OntologyGetAddress = 350 [(wire_in) = true];
|
||||
MessageType_OntologyAddress = 351 [(wire_out) = true];
|
||||
MessageType_OntologyGetPublicKey = 352 [(wire_in) = true];
|
||||
MessageType_OntologyPublicKey = 353 [(wire_out) = true];
|
||||
MessageType_OntologySignTransfer = 354 [(wire_in) = true];
|
||||
MessageType_OntologySignedTransfer = 355 [(wire_out) = true];
|
||||
MessageType_OntologySignWithdrawOng = 356 [(wire_in) = true];
|
||||
MessageType_OntologySignedWithdrawOng = 357 [(wire_out) = true];
|
||||
MessageType_OntologySignOntIdRegister = 358 [(wire_in) = true];
|
||||
MessageType_OntologySignedOntIdRegister = 359 [(wire_out) = true];
|
||||
MessageType_OntologySignOntIdAddAttributes = 360 [(wire_in) = true];
|
||||
MessageType_OntologySignedOntIdAddAttributes = 361 [(wire_out) = true];
|
||||
|
||||
// Ripple
|
||||
MessageType_RippleGetAddress = 400 [(wire_in) = true];
|
||||
MessageType_RippleAddress = 401 [(wire_out) = true];
|
||||
MessageType_RippleSignTx = 402 [(wire_in) = true];
|
||||
MessageType_RippleSignedTx = 403 [(wire_in) = true];
|
||||
|
||||
// Monero
|
||||
MessageType_MoneroTransactionInitRequest = 501 [(wire_out) = true];
|
||||
MessageType_MoneroTransactionInitAck = 502 [(wire_out) = true];
|
||||
MessageType_MoneroTransactionSetInputRequest = 503 [(wire_out) = true];
|
||||
MessageType_MoneroTransactionSetInputAck = 504 [(wire_out) = true];
|
||||
MessageType_MoneroTransactionInputsPermutationRequest = 505 [(wire_out) = true];
|
||||
MessageType_MoneroTransactionInputsPermutationAck = 506 [(wire_out) = true];
|
||||
MessageType_MoneroTransactionInputViniRequest = 507 [(wire_out) = true];
|
||||
MessageType_MoneroTransactionInputViniAck = 508 [(wire_out) = true];
|
||||
MessageType_MoneroTransactionAllInputsSetRequest = 509 [(wire_out) = true];
|
||||
MessageType_MoneroTransactionAllInputsSetAck = 510 [(wire_out) = true];
|
||||
MessageType_MoneroTransactionSetOutputRequest = 511 [(wire_out) = true];
|
||||
MessageType_MoneroTransactionSetOutputAck = 512 [(wire_out) = true];
|
||||
MessageType_MoneroTransactionAllOutSetRequest = 513 [(wire_out) = true];
|
||||
MessageType_MoneroTransactionAllOutSetAck = 514 [(wire_out) = true];
|
||||
MessageType_MoneroTransactionSignInputRequest = 515 [(wire_out) = true];
|
||||
MessageType_MoneroTransactionSignInputAck = 516 [(wire_out) = true];
|
||||
MessageType_MoneroTransactionFinalRequest = 517 [(wire_out) = true];
|
||||
MessageType_MoneroTransactionFinalAck = 518 [(wire_out) = true];
|
||||
MessageType_MoneroKeyImageExportInitRequest = 530 [(wire_out) = true];
|
||||
MessageType_MoneroKeyImageExportInitAck = 531 [(wire_out) = true];
|
||||
MessageType_MoneroKeyImageSyncStepRequest = 532 [(wire_out) = true];
|
||||
MessageType_MoneroKeyImageSyncStepAck = 533 [(wire_out) = true];
|
||||
MessageType_MoneroKeyImageSyncFinalRequest = 534 [(wire_out) = true];
|
||||
MessageType_MoneroKeyImageSyncFinalAck = 535 [(wire_out) = true];
|
||||
MessageType_MoneroGetAddress = 540 [(wire_in) = true];
|
||||
MessageType_MoneroAddress = 541 [(wire_out) = true];
|
||||
MessageType_MoneroGetWatchKey = 542 [(wire_in) = true];
|
||||
MessageType_MoneroWatchKey = 543 [(wire_out) = true];
|
||||
MessageType_DebugMoneroDiagRequest = 546 [(wire_in) = true];
|
||||
MessageType_DebugMoneroDiagAck = 547 [(wire_out) = true];
|
||||
MessageType_MoneroGetTxKeyRequest = 550 [(wire_in) = true];
|
||||
MessageType_MoneroGetTxKeyAck = 551 [(wire_out) = true];
|
||||
MessageType_MoneroLiveRefreshStartRequest = 552 [(wire_in) = true];
|
||||
MessageType_MoneroLiveRefreshStartAck = 553 [(wire_out) = true];
|
||||
MessageType_MoneroLiveRefreshStepRequest = 554 [(wire_in) = true];
|
||||
MessageType_MoneroLiveRefreshStepAck = 555 [(wire_out) = true];
|
||||
MessageType_MoneroLiveRefreshFinalRequest = 556 [(wire_in) = true];
|
||||
MessageType_MoneroLiveRefreshFinalAck = 557 [(wire_out) = true];
|
||||
|
||||
// EOS
|
||||
MessageType_EosGetPublicKey = 600 [(wire_in) = true];
|
||||
MessageType_EosPublicKey = 601 [(wire_out) = true];
|
||||
MessageType_EosSignTx = 602 [(wire_in) = true];
|
||||
MessageType_EosTxActionRequest = 603 [(wire_out) = true];
|
||||
MessageType_EosTxActionAck = 604 [(wire_in) = true];
|
||||
MessageType_EosSignedTx = 605 [(wire_out) = true];
|
||||
|
||||
// Binance
|
||||
MessageType_BinanceGetAddress = 700 [(wire_in) = true];
|
||||
MessageType_BinanceAddress = 701 [(wire_out) = true];
|
||||
MessageType_BinanceGetPublicKey = 702 [(wire_in) = true];
|
||||
MessageType_BinancePublicKey = 703 [(wire_out) = true];
|
||||
MessageType_BinanceSignTx = 704 [(wire_in) = true];
|
||||
MessageType_BinanceTxRequest = 705 [(wire_out) = true];
|
||||
MessageType_BinanceTransferMsg = 706 [(wire_in) = true];
|
||||
MessageType_BinanceOrderMsg = 707 [(wire_in) = true];
|
||||
MessageType_BinanceCancelMsg = 708 [(wire_in) = true];
|
||||
MessageType_BinanceSignedTx = 709 [(wire_out) = true];
|
||||
}
|
70
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/trezor/trezor.go
generated
vendored
Normal file
70
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/trezor/trezor.go
generated
vendored
Normal file
@ -0,0 +1,70 @@
|
||||
// Copyright 2019 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
// This file contains the implementation for interacting with the Trezor hardware
|
||||
// wallets. The wire protocol spec can be found on the SatoshiLabs website:
|
||||
// https://wiki.trezor.io/Developers_guide-Message_Workflows
|
||||
|
||||
// !!! STAHP !!!
|
||||
//
|
||||
// Before you touch the protocol files, you need to be aware of a breaking change
|
||||
// that occurred between firmware versions 1.7.3->1.8.0 (Model One) and 2.0.10->
|
||||
// 2.1.0 (Model T). The Ethereum address representation was changed from the 20
|
||||
// byte binary blob to a 42 byte hex string. The upstream protocol buffer files
|
||||
// only support the new format, so blindly pulling in a new spec will break old
|
||||
// devices!
|
||||
//
|
||||
// The Trezor devs had the foresight to add the string version as a new message
|
||||
// code instead of replacing the binary one. This means that the proto file can
|
||||
// actually define both the old and the new versions as optional. Please ensure
|
||||
// that you add back the old addresses everywhere (to avoid name clash. use the
|
||||
// addressBin and addressHex names).
|
||||
//
|
||||
// If in doubt, reach out to @karalabe.
|
||||
|
||||
// To regenerate the protocol files in this package:
|
||||
// - Download the latest protoc https://github.com/protocolbuffers/protobuf/releases
|
||||
// - Build with the usual `./configure && make` and ensure it's on your $PATH
|
||||
// - Delete all the .proto and .pb.go files, pull in fresh ones from Trezor
|
||||
// - Grab the latest Go plugin `go get -u github.com/golang/protobuf/protoc-gen-go`
|
||||
// - Vendor in the latest Go plugin `govendor fetch github.com/golang/protobuf/...`
|
||||
|
||||
//go:generate protoc -I/usr/local/include:. --go_out=import_path=trezor:. messages.proto messages-common.proto messages-management.proto messages-ethereum.proto
|
||||
|
||||
// Package trezor contains the wire protocol.
|
||||
package trezor
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
|
||||
"github.com/golang/protobuf/proto"
|
||||
)
|
||||
|
||||
// Type returns the protocol buffer type number of a specific message. If the
|
||||
// message is nil, this method panics!
|
||||
func Type(msg proto.Message) uint16 {
|
||||
return uint16(MessageType_value["MessageType_"+reflect.TypeOf(msg).Elem().Name()])
|
||||
}
|
||||
|
||||
// Name returns the friendly message type name of a specific protocol buffer
|
||||
// type number.
|
||||
func Name(kind uint16) string {
|
||||
name := MessageType_name[int32(kind)]
|
||||
if len(name) < 12 {
|
||||
return name
|
||||
}
|
||||
return name[12:]
|
||||
}
|
594
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/wallet.go
generated
vendored
Normal file
594
vendor/github.com/ethereum/go-ethereum/accounts/usbwallet/wallet.go
generated
vendored
Normal file
@ -0,0 +1,594 @@
|
||||
// Copyright 2017 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
// Package usbwallet implements support for USB hardware wallets.
|
||||
package usbwallet
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
ethereum "github.com/ethereum/go-ethereum"
|
||||
"github.com/ethereum/go-ethereum/accounts"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/ethereum/go-ethereum/log"
|
||||
"github.com/karalabe/usb"
|
||||
)
|
||||
|
||||
// Maximum time between wallet health checks to detect USB unplugs.
|
||||
const heartbeatCycle = time.Second
|
||||
|
||||
// Minimum time to wait between self derivation attempts, even it the user is
|
||||
// requesting accounts like crazy.
|
||||
const selfDeriveThrottling = time.Second
|
||||
|
||||
// driver defines the vendor specific functionality hardware wallets instances
|
||||
// must implement to allow using them with the wallet lifecycle management.
|
||||
type driver interface {
|
||||
// Status returns a textual status to aid the user in the current state of the
|
||||
// wallet. It also returns an error indicating any failure the wallet might have
|
||||
// encountered.
|
||||
Status() (string, error)
|
||||
|
||||
// Open initializes access to a wallet instance. The passphrase parameter may
|
||||
// or may not be used by the implementation of a particular wallet instance.
|
||||
Open(device io.ReadWriter, passphrase string) error
|
||||
|
||||
// Close releases any resources held by an open wallet instance.
|
||||
Close() error
|
||||
|
||||
// Heartbeat performs a sanity check against the hardware wallet to see if it
|
||||
// is still online and healthy.
|
||||
Heartbeat() error
|
||||
|
||||
// Derive sends a derivation request to the USB device and returns the Ethereum
|
||||
// address located on that path.
|
||||
Derive(path accounts.DerivationPath) (common.Address, error)
|
||||
|
||||
// SignTx sends the transaction to the USB device and waits for the user to confirm
|
||||
// or deny the transaction.
|
||||
SignTx(path accounts.DerivationPath, tx *types.Transaction, chainID *big.Int) (common.Address, *types.Transaction, error)
|
||||
}
|
||||
|
||||
// wallet represents the common functionality shared by all USB hardware
|
||||
// wallets to prevent reimplementing the same complex maintenance mechanisms
|
||||
// for different vendors.
|
||||
type wallet struct {
|
||||
hub *Hub // USB hub scanning
|
||||
driver driver // Hardware implementation of the low level device operations
|
||||
url *accounts.URL // Textual URL uniquely identifying this wallet
|
||||
|
||||
info usb.DeviceInfo // Known USB device infos about the wallet
|
||||
device usb.Device // USB device advertising itself as a hardware wallet
|
||||
|
||||
accounts []accounts.Account // List of derive accounts pinned on the hardware wallet
|
||||
paths map[common.Address]accounts.DerivationPath // Known derivation paths for signing operations
|
||||
|
||||
deriveNextPaths []accounts.DerivationPath // Next derivation paths for account auto-discovery (multiple bases supported)
|
||||
deriveNextAddrs []common.Address // Next derived account addresses for auto-discovery (multiple bases supported)
|
||||
deriveChain ethereum.ChainStateReader // Blockchain state reader to discover used account with
|
||||
deriveReq chan chan struct{} // Channel to request a self-derivation on
|
||||
deriveQuit chan chan error // Channel to terminate the self-deriver with
|
||||
|
||||
healthQuit chan chan error
|
||||
|
||||
// Locking a hardware wallet is a bit special. Since hardware devices are lower
|
||||
// performing, any communication with them might take a non negligible amount of
|
||||
// time. Worse still, waiting for user confirmation can take arbitrarily long,
|
||||
// but exclusive communication must be upheld during. Locking the entire wallet
|
||||
// in the mean time however would stall any parts of the system that don't want
|
||||
// to communicate, just read some state (e.g. list the accounts).
|
||||
//
|
||||
// As such, a hardware wallet needs two locks to function correctly. A state
|
||||
// lock can be used to protect the wallet's software-side internal state, which
|
||||
// must not be held exclusively during hardware communication. A communication
|
||||
// lock can be used to achieve exclusive access to the device itself, this one
|
||||
// however should allow "skipping" waiting for operations that might want to
|
||||
// use the device, but can live without too (e.g. account self-derivation).
|
||||
//
|
||||
// Since we have two locks, it's important to know how to properly use them:
|
||||
// - Communication requires the `device` to not change, so obtaining the
|
||||
// commsLock should be done after having a stateLock.
|
||||
// - Communication must not disable read access to the wallet state, so it
|
||||
// must only ever hold a *read* lock to stateLock.
|
||||
commsLock chan struct{} // Mutex (buf=1) for the USB comms without keeping the state locked
|
||||
stateLock sync.RWMutex // Protects read and write access to the wallet struct fields
|
||||
|
||||
log log.Logger // Contextual logger to tag the base with its id
|
||||
}
|
||||
|
||||
// URL implements accounts.Wallet, returning the URL of the USB hardware device.
|
||||
func (w *wallet) URL() accounts.URL {
|
||||
return *w.url // Immutable, no need for a lock
|
||||
}
|
||||
|
||||
// Status implements accounts.Wallet, returning a custom status message from the
|
||||
// underlying vendor-specific hardware wallet implementation.
|
||||
func (w *wallet) Status() (string, error) {
|
||||
w.stateLock.RLock() // No device communication, state lock is enough
|
||||
defer w.stateLock.RUnlock()
|
||||
|
||||
status, failure := w.driver.Status()
|
||||
if w.device == nil {
|
||||
return "Closed", failure
|
||||
}
|
||||
return status, failure
|
||||
}
|
||||
|
||||
// Open implements accounts.Wallet, attempting to open a USB connection to the
|
||||
// hardware wallet.
|
||||
func (w *wallet) Open(passphrase string) error {
|
||||
w.stateLock.Lock() // State lock is enough since there's no connection yet at this point
|
||||
defer w.stateLock.Unlock()
|
||||
|
||||
// If the device was already opened once, refuse to try again
|
||||
if w.paths != nil {
|
||||
return accounts.ErrWalletAlreadyOpen
|
||||
}
|
||||
// Make sure the actual device connection is done only once
|
||||
if w.device == nil {
|
||||
device, err := w.info.Open()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w.device = device
|
||||
w.commsLock = make(chan struct{}, 1)
|
||||
w.commsLock <- struct{}{} // Enable lock
|
||||
}
|
||||
// Delegate device initialization to the underlying driver
|
||||
if err := w.driver.Open(w.device, passphrase); err != nil {
|
||||
return err
|
||||
}
|
||||
// Connection successful, start life-cycle management
|
||||
w.paths = make(map[common.Address]accounts.DerivationPath)
|
||||
|
||||
w.deriveReq = make(chan chan struct{})
|
||||
w.deriveQuit = make(chan chan error)
|
||||
w.healthQuit = make(chan chan error)
|
||||
|
||||
go w.heartbeat()
|
||||
go w.selfDerive()
|
||||
|
||||
// Notify anyone listening for wallet events that a new device is accessible
|
||||
go w.hub.updateFeed.Send(accounts.WalletEvent{Wallet: w, Kind: accounts.WalletOpened})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// heartbeat is a health check loop for the USB wallets to periodically verify
|
||||
// whether they are still present or if they malfunctioned.
|
||||
func (w *wallet) heartbeat() {
|
||||
w.log.Debug("USB wallet health-check started")
|
||||
defer w.log.Debug("USB wallet health-check stopped")
|
||||
|
||||
// Execute heartbeat checks until termination or error
|
||||
var (
|
||||
errc chan error
|
||||
err error
|
||||
)
|
||||
for errc == nil && err == nil {
|
||||
// Wait until termination is requested or the heartbeat cycle arrives
|
||||
select {
|
||||
case errc = <-w.healthQuit:
|
||||
// Termination requested
|
||||
continue
|
||||
case <-time.After(heartbeatCycle):
|
||||
// Heartbeat time
|
||||
}
|
||||
// Execute a tiny data exchange to see responsiveness
|
||||
w.stateLock.RLock()
|
||||
if w.device == nil {
|
||||
// Terminated while waiting for the lock
|
||||
w.stateLock.RUnlock()
|
||||
continue
|
||||
}
|
||||
<-w.commsLock // Don't lock state while resolving version
|
||||
err = w.driver.Heartbeat()
|
||||
w.commsLock <- struct{}{}
|
||||
w.stateLock.RUnlock()
|
||||
|
||||
if err != nil {
|
||||
w.stateLock.Lock() // Lock state to tear the wallet down
|
||||
w.close()
|
||||
w.stateLock.Unlock()
|
||||
}
|
||||
// Ignore non hardware related errors
|
||||
err = nil
|
||||
}
|
||||
// In case of error, wait for termination
|
||||
if err != nil {
|
||||
w.log.Debug("USB wallet health-check failed", "err", err)
|
||||
errc = <-w.healthQuit
|
||||
}
|
||||
errc <- err
|
||||
}
|
||||
|
||||
// Close implements accounts.Wallet, closing the USB connection to the device.
|
||||
func (w *wallet) Close() error {
|
||||
// Ensure the wallet was opened
|
||||
w.stateLock.RLock()
|
||||
hQuit, dQuit := w.healthQuit, w.deriveQuit
|
||||
w.stateLock.RUnlock()
|
||||
|
||||
// Terminate the health checks
|
||||
var herr error
|
||||
if hQuit != nil {
|
||||
errc := make(chan error)
|
||||
hQuit <- errc
|
||||
herr = <-errc // Save for later, we *must* close the USB
|
||||
}
|
||||
// Terminate the self-derivations
|
||||
var derr error
|
||||
if dQuit != nil {
|
||||
errc := make(chan error)
|
||||
dQuit <- errc
|
||||
derr = <-errc // Save for later, we *must* close the USB
|
||||
}
|
||||
// Terminate the device connection
|
||||
w.stateLock.Lock()
|
||||
defer w.stateLock.Unlock()
|
||||
|
||||
w.healthQuit = nil
|
||||
w.deriveQuit = nil
|
||||
w.deriveReq = nil
|
||||
|
||||
if err := w.close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if herr != nil {
|
||||
return herr
|
||||
}
|
||||
return derr
|
||||
}
|
||||
|
||||
// close is the internal wallet closer that terminates the USB connection and
|
||||
// resets all the fields to their defaults.
|
||||
//
|
||||
// Note, close assumes the state lock is held!
|
||||
func (w *wallet) close() error {
|
||||
// Allow duplicate closes, especially for health-check failures
|
||||
if w.device == nil {
|
||||
return nil
|
||||
}
|
||||
// Close the device, clear everything, then return
|
||||
w.device.Close()
|
||||
w.device = nil
|
||||
|
||||
w.accounts, w.paths = nil, nil
|
||||
return w.driver.Close()
|
||||
}
|
||||
|
||||
// Accounts implements accounts.Wallet, returning the list of accounts pinned to
|
||||
// the USB hardware wallet. If self-derivation was enabled, the account list is
|
||||
// periodically expanded based on current chain state.
|
||||
func (w *wallet) Accounts() []accounts.Account {
|
||||
// Attempt self-derivation if it's running
|
||||
reqc := make(chan struct{}, 1)
|
||||
select {
|
||||
case w.deriveReq <- reqc:
|
||||
// Self-derivation request accepted, wait for it
|
||||
<-reqc
|
||||
default:
|
||||
// Self-derivation offline, throttled or busy, skip
|
||||
}
|
||||
// Return whatever account list we ended up with
|
||||
w.stateLock.RLock()
|
||||
defer w.stateLock.RUnlock()
|
||||
|
||||
cpy := make([]accounts.Account, len(w.accounts))
|
||||
copy(cpy, w.accounts)
|
||||
return cpy
|
||||
}
|
||||
|
||||
// selfDerive is an account derivation loop that upon request attempts to find
|
||||
// new non-zero accounts.
|
||||
func (w *wallet) selfDerive() {
|
||||
w.log.Debug("USB wallet self-derivation started")
|
||||
defer w.log.Debug("USB wallet self-derivation stopped")
|
||||
|
||||
// Execute self-derivations until termination or error
|
||||
var (
|
||||
reqc chan struct{}
|
||||
errc chan error
|
||||
err error
|
||||
)
|
||||
for errc == nil && err == nil {
|
||||
// Wait until either derivation or termination is requested
|
||||
select {
|
||||
case errc = <-w.deriveQuit:
|
||||
// Termination requested
|
||||
continue
|
||||
case reqc = <-w.deriveReq:
|
||||
// Account discovery requested
|
||||
}
|
||||
// Derivation needs a chain and device access, skip if either unavailable
|
||||
w.stateLock.RLock()
|
||||
if w.device == nil || w.deriveChain == nil {
|
||||
w.stateLock.RUnlock()
|
||||
reqc <- struct{}{}
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case <-w.commsLock:
|
||||
default:
|
||||
w.stateLock.RUnlock()
|
||||
reqc <- struct{}{}
|
||||
continue
|
||||
}
|
||||
// Device lock obtained, derive the next batch of accounts
|
||||
var (
|
||||
accs []accounts.Account
|
||||
paths []accounts.DerivationPath
|
||||
|
||||
nextPaths = append([]accounts.DerivationPath{}, w.deriveNextPaths...)
|
||||
nextAddrs = append([]common.Address{}, w.deriveNextAddrs...)
|
||||
|
||||
context = context.Background()
|
||||
)
|
||||
for i := 0; i < len(nextAddrs); i++ {
|
||||
for empty := false; !empty; {
|
||||
// Retrieve the next derived Ethereum account
|
||||
if nextAddrs[i] == (common.Address{}) {
|
||||
if nextAddrs[i], err = w.driver.Derive(nextPaths[i]); err != nil {
|
||||
w.log.Warn("USB wallet account derivation failed", "err", err)
|
||||
break
|
||||
}
|
||||
}
|
||||
// Check the account's status against the current chain state
|
||||
var (
|
||||
balance *big.Int
|
||||
nonce uint64
|
||||
)
|
||||
balance, err = w.deriveChain.BalanceAt(context, nextAddrs[i], nil)
|
||||
if err != nil {
|
||||
w.log.Warn("USB wallet balance retrieval failed", "err", err)
|
||||
break
|
||||
}
|
||||
nonce, err = w.deriveChain.NonceAt(context, nextAddrs[i], nil)
|
||||
if err != nil {
|
||||
w.log.Warn("USB wallet nonce retrieval failed", "err", err)
|
||||
break
|
||||
}
|
||||
// If the next account is empty, stop self-derivation, but add for the last base path
|
||||
if balance.Sign() == 0 && nonce == 0 {
|
||||
empty = true
|
||||
if i < len(nextAddrs)-1 {
|
||||
break
|
||||
}
|
||||
}
|
||||
// We've just self-derived a new account, start tracking it locally
|
||||
path := make(accounts.DerivationPath, len(nextPaths[i]))
|
||||
copy(path[:], nextPaths[i][:])
|
||||
paths = append(paths, path)
|
||||
|
||||
account := accounts.Account{
|
||||
Address: nextAddrs[i],
|
||||
URL: accounts.URL{Scheme: w.url.Scheme, Path: fmt.Sprintf("%s/%s", w.url.Path, path)},
|
||||
}
|
||||
accs = append(accs, account)
|
||||
|
||||
// Display a log message to the user for new (or previously empty accounts)
|
||||
if _, known := w.paths[nextAddrs[i]]; !known || (!empty && nextAddrs[i] == w.deriveNextAddrs[i]) {
|
||||
w.log.Info("USB wallet discovered new account", "address", nextAddrs[i], "path", path, "balance", balance, "nonce", nonce)
|
||||
}
|
||||
// Fetch the next potential account
|
||||
if !empty {
|
||||
nextAddrs[i] = common.Address{}
|
||||
nextPaths[i][len(nextPaths[i])-1]++
|
||||
}
|
||||
}
|
||||
}
|
||||
// Self derivation complete, release device lock
|
||||
w.commsLock <- struct{}{}
|
||||
w.stateLock.RUnlock()
|
||||
|
||||
// Insert any accounts successfully derived
|
||||
w.stateLock.Lock()
|
||||
for i := 0; i < len(accs); i++ {
|
||||
if _, ok := w.paths[accs[i].Address]; !ok {
|
||||
w.accounts = append(w.accounts, accs[i])
|
||||
w.paths[accs[i].Address] = paths[i]
|
||||
}
|
||||
}
|
||||
// Shift the self-derivation forward
|
||||
// TODO(karalabe): don't overwrite changes from wallet.SelfDerive
|
||||
w.deriveNextAddrs = nextAddrs
|
||||
w.deriveNextPaths = nextPaths
|
||||
w.stateLock.Unlock()
|
||||
|
||||
// Notify the user of termination and loop after a bit of time (to avoid trashing)
|
||||
reqc <- struct{}{}
|
||||
if err == nil {
|
||||
select {
|
||||
case errc = <-w.deriveQuit:
|
||||
// Termination requested, abort
|
||||
case <-time.After(selfDeriveThrottling):
|
||||
// Waited enough, willing to self-derive again
|
||||
}
|
||||
}
|
||||
}
|
||||
// In case of error, wait for termination
|
||||
if err != nil {
|
||||
w.log.Debug("USB wallet self-derivation failed", "err", err)
|
||||
errc = <-w.deriveQuit
|
||||
}
|
||||
errc <- err
|
||||
}
|
||||
|
||||
// Contains implements accounts.Wallet, returning whether a particular account is
|
||||
// or is not pinned into this wallet instance. Although we could attempt to resolve
|
||||
// unpinned accounts, that would be an non-negligible hardware operation.
|
||||
func (w *wallet) Contains(account accounts.Account) bool {
|
||||
w.stateLock.RLock()
|
||||
defer w.stateLock.RUnlock()
|
||||
|
||||
_, exists := w.paths[account.Address]
|
||||
return exists
|
||||
}
|
||||
|
||||
// Derive implements accounts.Wallet, deriving a new account at the specific
|
||||
// derivation path. If pin is set to true, the account will be added to the list
|
||||
// of tracked accounts.
|
||||
func (w *wallet) Derive(path accounts.DerivationPath, pin bool) (accounts.Account, error) {
|
||||
// Try to derive the actual account and update its URL if successful
|
||||
w.stateLock.RLock() // Avoid device disappearing during derivation
|
||||
|
||||
if w.device == nil {
|
||||
w.stateLock.RUnlock()
|
||||
return accounts.Account{}, accounts.ErrWalletClosed
|
||||
}
|
||||
<-w.commsLock // Avoid concurrent hardware access
|
||||
address, err := w.driver.Derive(path)
|
||||
w.commsLock <- struct{}{}
|
||||
|
||||
w.stateLock.RUnlock()
|
||||
|
||||
// If an error occurred or no pinning was requested, return
|
||||
if err != nil {
|
||||
return accounts.Account{}, err
|
||||
}
|
||||
account := accounts.Account{
|
||||
Address: address,
|
||||
URL: accounts.URL{Scheme: w.url.Scheme, Path: fmt.Sprintf("%s/%s", w.url.Path, path)},
|
||||
}
|
||||
if !pin {
|
||||
return account, nil
|
||||
}
|
||||
// Pinning needs to modify the state
|
||||
w.stateLock.Lock()
|
||||
defer w.stateLock.Unlock()
|
||||
|
||||
if _, ok := w.paths[address]; !ok {
|
||||
w.accounts = append(w.accounts, account)
|
||||
w.paths[address] = path
|
||||
}
|
||||
return account, nil
|
||||
}
|
||||
|
||||
// SelfDerive sets a base account derivation path from which the wallet attempts
|
||||
// to discover non zero accounts and automatically add them to list of tracked
|
||||
// accounts.
|
||||
//
|
||||
// Note, self derivaton will increment the last component of the specified path
|
||||
// opposed to decending into a child path to allow discovering accounts starting
|
||||
// from non zero components.
|
||||
//
|
||||
// Some hardware wallets switched derivation paths through their evolution, so
|
||||
// this method supports providing multiple bases to discover old user accounts
|
||||
// too. Only the last base will be used to derive the next empty account.
|
||||
//
|
||||
// You can disable automatic account discovery by calling SelfDerive with a nil
|
||||
// chain state reader.
|
||||
func (w *wallet) SelfDerive(bases []accounts.DerivationPath, chain ethereum.ChainStateReader) {
|
||||
w.stateLock.Lock()
|
||||
defer w.stateLock.Unlock()
|
||||
|
||||
w.deriveNextPaths = make([]accounts.DerivationPath, len(bases))
|
||||
for i, base := range bases {
|
||||
w.deriveNextPaths[i] = make(accounts.DerivationPath, len(base))
|
||||
copy(w.deriveNextPaths[i][:], base[:])
|
||||
}
|
||||
w.deriveNextAddrs = make([]common.Address, len(bases))
|
||||
w.deriveChain = chain
|
||||
}
|
||||
|
||||
// signHash implements accounts.Wallet, however signing arbitrary data is not
|
||||
// supported for hardware wallets, so this method will always return an error.
|
||||
func (w *wallet) signHash(account accounts.Account, hash []byte) ([]byte, error) {
|
||||
return nil, accounts.ErrNotSupported
|
||||
}
|
||||
|
||||
// SignData signs keccak256(data). The mimetype parameter describes the type of data being signed
|
||||
func (w *wallet) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) {
|
||||
return w.signHash(account, crypto.Keccak256(data))
|
||||
}
|
||||
|
||||
// SignDataWithPassphrase implements accounts.Wallet, attempting to sign the given
|
||||
// data with the given account using passphrase as extra authentication.
|
||||
// Since USB wallets don't rely on passphrases, these are silently ignored.
|
||||
func (w *wallet) SignDataWithPassphrase(account accounts.Account, passphrase, mimeType string, data []byte) ([]byte, error) {
|
||||
return w.SignData(account, mimeType, data)
|
||||
}
|
||||
|
||||
func (w *wallet) SignText(account accounts.Account, text []byte) ([]byte, error) {
|
||||
return w.signHash(account, accounts.TextHash(text))
|
||||
}
|
||||
|
||||
// SignTx implements accounts.Wallet. It sends the transaction over to the Ledger
|
||||
// wallet to request a confirmation from the user. It returns either the signed
|
||||
// transaction or a failure if the user denied the transaction.
|
||||
//
|
||||
// Note, if the version of the Ethereum application running on the Ledger wallet is
|
||||
// too old to sign EIP-155 transactions, but such is requested nonetheless, an error
|
||||
// will be returned opposed to silently signing in Homestead mode.
|
||||
func (w *wallet) SignTx(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
|
||||
w.stateLock.RLock() // Comms have own mutex, this is for the state fields
|
||||
defer w.stateLock.RUnlock()
|
||||
|
||||
// If the wallet is closed, abort
|
||||
if w.device == nil {
|
||||
return nil, accounts.ErrWalletClosed
|
||||
}
|
||||
// Make sure the requested account is contained within
|
||||
path, ok := w.paths[account.Address]
|
||||
if !ok {
|
||||
return nil, accounts.ErrUnknownAccount
|
||||
}
|
||||
// All infos gathered and metadata checks out, request signing
|
||||
<-w.commsLock
|
||||
defer func() { w.commsLock <- struct{}{} }()
|
||||
|
||||
// Ensure the device isn't screwed with while user confirmation is pending
|
||||
// TODO(karalabe): remove if hotplug lands on Windows
|
||||
w.hub.commsLock.Lock()
|
||||
w.hub.commsPend++
|
||||
w.hub.commsLock.Unlock()
|
||||
|
||||
defer func() {
|
||||
w.hub.commsLock.Lock()
|
||||
w.hub.commsPend--
|
||||
w.hub.commsLock.Unlock()
|
||||
}()
|
||||
// Sign the transaction and verify the sender to avoid hardware fault surprises
|
||||
sender, signed, err := w.driver.SignTx(path, tx, chainID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if sender != account.Address {
|
||||
return nil, fmt.Errorf("signer mismatch: expected %s, got %s", account.Address.Hex(), sender.Hex())
|
||||
}
|
||||
return signed, nil
|
||||
}
|
||||
|
||||
// SignHashWithPassphrase implements accounts.Wallet, however signing arbitrary
|
||||
// data is not supported for Ledger wallets, so this method will always return
|
||||
// an error.
|
||||
func (w *wallet) SignTextWithPassphrase(account accounts.Account, passphrase string, text []byte) ([]byte, error) {
|
||||
return w.SignText(account, accounts.TextHash(text))
|
||||
}
|
||||
|
||||
// SignTxWithPassphrase implements accounts.Wallet, attempting to sign the given
|
||||
// transaction with the given account using passphrase as extra authentication.
|
||||
// Since USB wallets don't rely on passphrases, these are silently ignored.
|
||||
func (w *wallet) SignTxWithPassphrase(account accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
|
||||
return w.SignTx(account, tx, chainID)
|
||||
}
|
4
vendor/github.com/ethereum/go-ethereum/appveyor.yml
generated
vendored
4
vendor/github.com/ethereum/go-ethereum/appveyor.yml
generated
vendored
@ -23,8 +23,8 @@ environment:
|
||||
install:
|
||||
- git submodule update --init
|
||||
- rmdir C:\go /s /q
|
||||
- appveyor DownloadFile https://dl.google.com/go/go1.12.3.windows-%GETH_ARCH%.zip
|
||||
- 7z x go1.12.3.windows-%GETH_ARCH%.zip -y -oC:\ > NUL
|
||||
- appveyor DownloadFile https://dl.google.com/go/go1.12.5.windows-%GETH_ARCH%.zip
|
||||
- 7z x go1.12.5.windows-%GETH_ARCH%.zip -y -oC:\ > NUL
|
||||
- go version
|
||||
- gcc --version
|
||||
|
||||
|
47
vendor/github.com/ethereum/go-ethereum/build/ci.go
generated
vendored
47
vendor/github.com/ethereum/go-ethereum/build/ci.go
generated
vendored
@ -60,7 +60,6 @@ import (
|
||||
|
||||
"github.com/ethereum/go-ethereum/internal/build"
|
||||
"github.com/ethereum/go-ethereum/params"
|
||||
sv "github.com/ethereum/go-ethereum/swarm/version"
|
||||
)
|
||||
|
||||
var (
|
||||
@ -83,12 +82,6 @@ var (
|
||||
executablePath("clef"),
|
||||
}
|
||||
|
||||
// Files that end up in the swarm*.zip archive.
|
||||
swarmArchiveFiles = []string{
|
||||
"COPYING",
|
||||
executablePath("swarm"),
|
||||
}
|
||||
|
||||
// A debian package is created for all executables listed here.
|
||||
debExecutables = []debExecutable{
|
||||
{
|
||||
@ -126,13 +119,6 @@ var (
|
||||
}
|
||||
|
||||
// A debian package is created for all executables listed here.
|
||||
debSwarmExecutables = []debExecutable{
|
||||
{
|
||||
BinaryName: "swarm",
|
||||
PackageName: "ethereum-swarm",
|
||||
Description: "Ethereum Swarm daemon and tools",
|
||||
},
|
||||
}
|
||||
|
||||
debEthereum = debPackage{
|
||||
Name: "ethereum",
|
||||
@ -140,27 +126,17 @@ var (
|
||||
Executables: debExecutables,
|
||||
}
|
||||
|
||||
debSwarm = debPackage{
|
||||
Name: "ethereum-swarm",
|
||||
Version: sv.Version,
|
||||
Executables: debSwarmExecutables,
|
||||
}
|
||||
|
||||
// Debian meta packages to build and push to Ubuntu PPA
|
||||
debPackages = []debPackage{
|
||||
debSwarm,
|
||||
debEthereum,
|
||||
}
|
||||
|
||||
// Packages to be cross-compiled by the xgo command
|
||||
allCrossCompiledArchiveFiles = append(allToolsArchiveFiles, swarmArchiveFiles...)
|
||||
|
||||
// Distros for which packages are created.
|
||||
// Note: vivid is unsupported because there is no golang-1.6 package for it.
|
||||
// Note: wily is unsupported because it was officially deprecated on lanchpad.
|
||||
// Note: yakkety is unsupported because it was officially deprecated on lanchpad.
|
||||
// Note: zesty is unsupported because it was officially deprecated on lanchpad.
|
||||
// Note: artful is unsupported because it was officially deprecated on lanchpad.
|
||||
// Note: wily is unsupported because it was officially deprecated on Launchpad.
|
||||
// Note: yakkety is unsupported because it was officially deprecated on Launchpad.
|
||||
// Note: zesty is unsupported because it was officially deprecated on Launchpad.
|
||||
// Note: artful is unsupported because it was officially deprecated on Launchpad.
|
||||
debDistros = []string{"trusty", "xenial", "bionic", "cosmic", "disco"}
|
||||
)
|
||||
|
||||
@ -284,6 +260,7 @@ func buildFlags(env build.Environment) (flags []string) {
|
||||
var ld []string
|
||||
if env.Commit != "" {
|
||||
ld = append(ld, "-X", "main.gitCommit="+env.Commit)
|
||||
ld = append(ld, "-X", "main.gitDate="+env.Date)
|
||||
}
|
||||
if runtime.GOOS == "darwin" {
|
||||
ld = append(ld, "-s")
|
||||
@ -408,9 +385,6 @@ func doArchive(cmdline []string) {
|
||||
basegeth = archiveBasename(*arch, params.ArchiveVersion(env.Commit))
|
||||
geth = "geth-" + basegeth + ext
|
||||
alltools = "geth-alltools-" + basegeth + ext
|
||||
|
||||
baseswarm = archiveBasename(*arch, sv.ArchiveVersion(env.Commit))
|
||||
swarm = "swarm-" + baseswarm + ext
|
||||
)
|
||||
maybeSkipArchive(env)
|
||||
if err := build.WriteArchive(geth, gethArchiveFiles); err != nil {
|
||||
@ -419,10 +393,7 @@ func doArchive(cmdline []string) {
|
||||
if err := build.WriteArchive(alltools, allToolsArchiveFiles); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err := build.WriteArchive(swarm, swarmArchiveFiles); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
for _, archive := range []string{geth, alltools, swarm} {
|
||||
for _, archive := range []string{geth, alltools} {
|
||||
if err := archiveUpload(archive, *upload, *signer); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
@ -585,8 +556,8 @@ func isUnstableBuild(env build.Environment) bool {
|
||||
}
|
||||
|
||||
type debPackage struct {
|
||||
Name string // the name of the Debian package to produce, e.g. "ethereum", or "ethereum-swarm"
|
||||
Version string // the clean version of the debPackage, e.g. 1.8.12 or 0.3.0, without any metadata
|
||||
Name string // the name of the Debian package to produce, e.g. "ethereum"
|
||||
Version string // the clean version of the debPackage, e.g. 1.8.12, without any metadata
|
||||
Executables []debExecutable // executables to be included in the package
|
||||
}
|
||||
|
||||
@ -1022,7 +993,7 @@ func doXgo(cmdline []string) {
|
||||
|
||||
if *alltools {
|
||||
args = append(args, []string{"--dest", GOBIN}...)
|
||||
for _, res := range allCrossCompiledArchiveFiles {
|
||||
for _, res := range allToolsArchiveFiles {
|
||||
if strings.HasPrefix(res, GOBIN) {
|
||||
// Binary tool found, cross build it explicitly
|
||||
args = append(args, "./"+filepath.Join("cmd", filepath.Base(res)))
|
||||
|
5
vendor/github.com/ethereum/go-ethereum/build/deb/ethereum-swarm/deb.changelog
generated
vendored
5
vendor/github.com/ethereum/go-ethereum/build/deb/ethereum-swarm/deb.changelog
generated
vendored
@ -1,5 +0,0 @@
|
||||
{{.Name}} ({{.VersionString}}) {{.Distro}}; urgency=low
|
||||
|
||||
* git build of {{.Env.Commit}}
|
||||
|
||||
-- {{.Author}} {{.Time}}
|
19
vendor/github.com/ethereum/go-ethereum/build/deb/ethereum-swarm/deb.control
generated
vendored
19
vendor/github.com/ethereum/go-ethereum/build/deb/ethereum-swarm/deb.control
generated
vendored
@ -1,19 +0,0 @@
|
||||
Source: {{.Name}}
|
||||
Section: science
|
||||
Priority: extra
|
||||
Maintainer: {{.Author}}
|
||||
Build-Depends: debhelper (>= 8.0.0), golang-1.11
|
||||
Standards-Version: 3.9.5
|
||||
Homepage: https://ethereum.org
|
||||
Vcs-Git: git://github.com/ethereum/go-ethereum.git
|
||||
Vcs-Browser: https://github.com/ethereum/go-ethereum
|
||||
|
||||
{{range .Executables}}
|
||||
Package: {{$.ExeName .}}
|
||||
Conflicts: {{$.ExeConflicts .}}
|
||||
Architecture: any
|
||||
Depends: ${shlibs:Depends}, ${misc:Depends}
|
||||
Built-Using: ${misc:Built-Using}
|
||||
Description: {{.Description}}
|
||||
{{.Description}}
|
||||
{{end}}
|
14
vendor/github.com/ethereum/go-ethereum/build/deb/ethereum-swarm/deb.copyright
generated
vendored
14
vendor/github.com/ethereum/go-ethereum/build/deb/ethereum-swarm/deb.copyright
generated
vendored
@ -1,14 +0,0 @@
|
||||
Copyright 2018 The go-ethereum Authors
|
||||
|
||||
go-ethereum is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
go-ethereum is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
|
1
vendor/github.com/ethereum/go-ethereum/build/deb/ethereum-swarm/deb.docs
generated
vendored
1
vendor/github.com/ethereum/go-ethereum/build/deb/ethereum-swarm/deb.docs
generated
vendored
@ -1 +0,0 @@
|
||||
AUTHORS
|
1
vendor/github.com/ethereum/go-ethereum/build/deb/ethereum-swarm/deb.install
generated
vendored
1
vendor/github.com/ethereum/go-ethereum/build/deb/ethereum-swarm/deb.install
generated
vendored
@ -1 +0,0 @@
|
||||
build/bin/{{.BinaryName}} usr/bin
|
16
vendor/github.com/ethereum/go-ethereum/build/deb/ethereum-swarm/deb.rules
generated
vendored
16
vendor/github.com/ethereum/go-ethereum/build/deb/ethereum-swarm/deb.rules
generated
vendored
@ -1,16 +0,0 @@
|
||||
#!/usr/bin/make -f
|
||||
# -*- makefile -*-
|
||||
|
||||
# Uncomment this to turn on verbose mode.
|
||||
#export DH_VERBOSE=1
|
||||
|
||||
# Launchpad rejects Go's access to $HOME/.cache, use custom folder
|
||||
export GOCACHE=/tmp/go-build
|
||||
|
||||
override_dh_auto_build:
|
||||
build/env.sh /usr/lib/go-1.11/bin/go run build/ci.go install -git-commit={{.Env.Commit}} -git-branch={{.Env.Branch}} -git-tag={{.Env.Tag}} -buildnum={{.Env.Buildnum}} -pull-request={{.Env.IsPullRequest}}
|
||||
|
||||
override_dh_auto_test:
|
||||
|
||||
%:
|
||||
dh $@
|
4
vendor/github.com/ethereum/go-ethereum/build/deb/ethereum/deb.control
generated
vendored
4
vendor/github.com/ethereum/go-ethereum/build/deb/ethereum/deb.control
generated
vendored
@ -11,8 +11,8 @@ Vcs-Browser: https://github.com/ethereum/go-ethereum
|
||||
Package: {{.Name}}
|
||||
Architecture: any
|
||||
Depends: ${misc:Depends}, {{.ExeList}}
|
||||
Description: Meta-package to install geth, swarm, and other tools
|
||||
Meta-package to install geth, swarm and other tools
|
||||
Description: Meta-package to install geth and other tools
|
||||
Meta-package to install geth and other tools
|
||||
|
||||
{{range .Executables}}
|
||||
Package: {{$.ExeName .}}
|
||||
|
2
vendor/github.com/ethereum/go-ethereum/build/update-license.go
generated
vendored
2
vendor/github.com/ethereum/go-ethereum/build/update-license.go
generated
vendored
@ -72,8 +72,6 @@ var (
|
||||
"internal/jsre/deps",
|
||||
"log/",
|
||||
"common/bitutil/bitutil",
|
||||
// don't license generated files
|
||||
"contracts/chequebook/contract/code.go",
|
||||
}
|
||||
|
||||
// paths with this prefix are licensed as GPL. all other files are LGPL.
|
||||
|
11
vendor/github.com/ethereum/go-ethereum/cmd/abigen/main.go
generated
vendored
11
vendor/github.com/ethereum/go-ethereum/cmd/abigen/main.go
generated
vendored
@ -81,7 +81,7 @@ func main() {
|
||||
bins []string
|
||||
types []string
|
||||
)
|
||||
if *solFlag != "" || *vyFlag != "" || (*abiFlag == "-" && *pkgFlag == "") {
|
||||
if *solFlag != "" || *vyFlag != "" || *abiFlag == "-" {
|
||||
// Generate the list of types to exclude from binding
|
||||
exclude := make(map[string]bool)
|
||||
for _, kind := range strings.Split(*excFlag, ",") {
|
||||
@ -129,13 +129,8 @@ func main() {
|
||||
}
|
||||
} else {
|
||||
// Otherwise load up the ABI, optional bytecode and type name from the parameters
|
||||
var abi []byte
|
||||
var err error
|
||||
if *abiFlag == "-" {
|
||||
abi, err = ioutil.ReadAll(os.Stdin)
|
||||
} else {
|
||||
abi, err = ioutil.ReadFile(*abiFlag)
|
||||
}
|
||||
abi, err := ioutil.ReadFile(*abiFlag)
|
||||
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to read input ABI: %v\n", err)
|
||||
os.Exit(-1)
|
||||
|
2
vendor/github.com/ethereum/go-ethereum/cmd/bootnode/main.go
generated
vendored
2
vendor/github.com/ethereum/go-ethereum/cmd/bootnode/main.go
generated
vendored
@ -143,7 +143,7 @@ func printNotice(nodeKey *ecdsa.PublicKey, addr net.UDPAddr) {
|
||||
addr.IP = net.IP{127, 0, 0, 1}
|
||||
}
|
||||
n := enode.NewV4(nodeKey, addr.IP, 0, addr.Port)
|
||||
fmt.Println(n.String())
|
||||
fmt.Println(n.URLv4())
|
||||
fmt.Println("Note: you're using cmd/bootnode, a developer tool.")
|
||||
fmt.Println("We recommend using a regular node as bootstrap node for production deployments.")
|
||||
}
|
||||
|
39
vendor/github.com/ethereum/go-ethereum/cmd/clef/main.go
generated
vendored
39
vendor/github.com/ethereum/go-ethereum/cmd/clef/main.go
generated
vendored
@ -33,6 +33,7 @@ import (
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/ethereum/go-ethereum/accounts"
|
||||
"github.com/ethereum/go-ethereum/accounts/keystore"
|
||||
@ -193,6 +194,7 @@ func init() {
|
||||
chainIdFlag,
|
||||
utils.LightKDFFlag,
|
||||
utils.NoUSBFlag,
|
||||
utils.SmartCardDaemonPathFlag,
|
||||
utils.RPCListenAddrFlag,
|
||||
utils.RPCVirtualHostsFlag,
|
||||
utils.IPCDisabledFlag,
|
||||
@ -418,10 +420,11 @@ func signer(c *cli.Context) error {
|
||||
lightKdf = c.GlobalBool(utils.LightKDFFlag.Name)
|
||||
advanced = c.GlobalBool(advancedMode.Name)
|
||||
nousb = c.GlobalBool(utils.NoUSBFlag.Name)
|
||||
scpath = c.GlobalString(utils.SmartCardDaemonPathFlag.Name)
|
||||
)
|
||||
log.Info("Starting signer", "chainid", chainId, "keystore", ksLoc,
|
||||
"light-kdf", lightKdf, "advanced", advanced)
|
||||
am := core.StartClefAccountManager(ksLoc, nousb, lightKdf)
|
||||
am := core.StartClefAccountManager(ksLoc, nousb, lightKdf, scpath)
|
||||
apiImpl := core.NewSignerAPI(am, chainId, nousb, ui, db, advanced, pwStorage)
|
||||
|
||||
// Establish the bidirectional communication, by creating a new UI backend and registering
|
||||
@ -638,6 +641,10 @@ func testExternalUI(api *core.SignerAPI) {
|
||||
errs := make([]string, 0)
|
||||
|
||||
a := common.HexToAddress("0xdeadbeef000000000000000000000000deadbeef")
|
||||
addErr := func(errStr string) {
|
||||
log.Info("Test error", "error", errStr)
|
||||
errs = append(errs, errStr)
|
||||
}
|
||||
|
||||
queryUser := func(q string) string {
|
||||
resp, err := api.UI.OnInputRequired(core.UserInputRequest{
|
||||
@ -645,36 +652,39 @@ func testExternalUI(api *core.SignerAPI) {
|
||||
Prompt: q,
|
||||
})
|
||||
if err != nil {
|
||||
errs = append(errs, err.Error())
|
||||
addErr(err.Error())
|
||||
}
|
||||
return resp.Text
|
||||
}
|
||||
expectResponse := func(testcase, question, expect string) {
|
||||
if got := queryUser(question); got != expect {
|
||||
errs = append(errs, fmt.Sprintf("%s: got %v, expected %v", testcase, got, expect))
|
||||
addErr(fmt.Sprintf("%s: got %v, expected %v", testcase, got, expect))
|
||||
}
|
||||
}
|
||||
expectApprove := func(testcase string, err error) {
|
||||
if err == nil || err == accounts.ErrUnknownAccount {
|
||||
return
|
||||
}
|
||||
errs = append(errs, fmt.Sprintf("%v: expected no error, got %v", testcase, err.Error()))
|
||||
addErr(fmt.Sprintf("%v: expected no error, got %v", testcase, err.Error()))
|
||||
}
|
||||
expectDeny := func(testcase string, err error) {
|
||||
if err == nil || err != core.ErrRequestDenied {
|
||||
errs = append(errs, fmt.Sprintf("%v: expected ErrRequestDenied, got %v", testcase, err))
|
||||
addErr(fmt.Sprintf("%v: expected ErrRequestDenied, got %v", testcase, err))
|
||||
}
|
||||
}
|
||||
|
||||
var delay = 1 * time.Second
|
||||
// Test display of info and error
|
||||
{
|
||||
api.UI.ShowInfo("If you see this message, enter 'yes' to next question")
|
||||
time.Sleep(delay)
|
||||
expectResponse("showinfo", "Did you see the message? [yes/no]", "yes")
|
||||
api.UI.ShowError("If you see this message, enter 'yes' to the next question")
|
||||
time.Sleep(delay)
|
||||
expectResponse("showerror", "Did you see the message? [yes/no]", "yes")
|
||||
}
|
||||
{ // Sign data test - clique header
|
||||
api.UI.ShowInfo("Please approve the next request for signing a clique header")
|
||||
time.Sleep(delay)
|
||||
cliqueHeader := types.Header{
|
||||
common.HexToHash("0000H45H"),
|
||||
common.HexToHash("0000H45H"),
|
||||
@ -700,14 +710,27 @@ func testExternalUI(api *core.SignerAPI) {
|
||||
_, err = api.SignData(ctx, accounts.MimetypeClique, *addr, hexutil.Encode(cliqueRlp))
|
||||
expectApprove("signdata - clique header", err)
|
||||
}
|
||||
{ // Sign data test - typed data
|
||||
api.UI.ShowInfo("Please approve the next request for signing EIP-712 typed data")
|
||||
time.Sleep(delay)
|
||||
addr, _ := common.NewMixedcaseAddressFromString("0x0011223344556677889900112233445566778899")
|
||||
data := `{"types":{"EIP712Domain":[{"name":"name","type":"string"},{"name":"version","type":"string"},{"name":"chainId","type":"uint256"},{"name":"verifyingContract","type":"address"}],"Person":[{"name":"name","type":"string"},{"name":"test","type":"uint8"},{"name":"wallet","type":"address"}],"Mail":[{"name":"from","type":"Person"},{"name":"to","type":"Person"},{"name":"contents","type":"string"}]},"primaryType":"Mail","domain":{"name":"Ether Mail","version":"1","chainId":"1","verifyingContract":"0xCCCcccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC"},"message":{"from":{"name":"Cow","test":"3","wallet":"0xcD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826"},"to":{"name":"Bob","wallet":"0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB","test":"2"},"contents":"Hello, Bob!"}}`
|
||||
//_, err := api.SignData(ctx, accounts.MimetypeTypedData, *addr, hexutil.Encode([]byte(data)))
|
||||
var typedData core.TypedData
|
||||
err := json.Unmarshal([]byte(data), &typedData)
|
||||
_, err = api.SignTypedData(ctx, *addr, typedData)
|
||||
expectApprove("sign 712 typed data", err)
|
||||
}
|
||||
{ // Sign data test - plain text
|
||||
api.UI.ShowInfo("Please approve the next request for signing text")
|
||||
time.Sleep(delay)
|
||||
addr, _ := common.NewMixedcaseAddressFromString("0x0011223344556677889900112233445566778899")
|
||||
_, err := api.SignData(ctx, accounts.MimetypeTextPlain, *addr, hexutil.Encode([]byte("hello world")))
|
||||
expectApprove("signdata - text", err)
|
||||
}
|
||||
{ // Sign data test - plain text reject
|
||||
api.UI.ShowInfo("Please deny the next request for signing text")
|
||||
time.Sleep(delay)
|
||||
addr, _ := common.NewMixedcaseAddressFromString("0x0011223344556677889900112233445566778899")
|
||||
_, err := api.SignData(ctx, accounts.MimetypeTextPlain, *addr, hexutil.Encode([]byte("hello world")))
|
||||
expectDeny("signdata - text", err)
|
||||
@ -715,6 +738,7 @@ func testExternalUI(api *core.SignerAPI) {
|
||||
{ // Sign transaction
|
||||
|
||||
api.UI.ShowInfo("Please reject next transaction")
|
||||
time.Sleep(delay)
|
||||
data := hexutil.Bytes([]byte{})
|
||||
to := common.NewMixedcaseAddress(a)
|
||||
tx := core.SendTxArgs{
|
||||
@ -733,16 +757,19 @@ func testExternalUI(api *core.SignerAPI) {
|
||||
}
|
||||
{ // Listing
|
||||
api.UI.ShowInfo("Please reject listing-request")
|
||||
time.Sleep(delay)
|
||||
_, err := api.List(ctx)
|
||||
expectDeny("list", err)
|
||||
}
|
||||
{ // Import
|
||||
api.UI.ShowInfo("Please reject new account-request")
|
||||
time.Sleep(delay)
|
||||
_, err := api.New(ctx)
|
||||
expectDeny("newaccount", err)
|
||||
}
|
||||
{ // Metadata
|
||||
api.UI.ShowInfo("Please check if you see the Origin in next listing (approve or deny)")
|
||||
time.Sleep(delay)
|
||||
api.List(context.WithValue(ctx, "Origin", "origin.com"))
|
||||
expectResponse("metadata - origin", "Did you see origin (origin.com)? [yes/no] ", "yes")
|
||||
}
|
||||
|
166
vendor/github.com/ethereum/go-ethereum/cmd/devp2p/discv4cmd.go
generated
vendored
Normal file
166
vendor/github.com/ethereum/go-ethereum/cmd/devp2p/discv4cmd.go
generated
vendored
Normal file
@ -0,0 +1,166 @@
|
||||
// Copyright 2019 The go-ethereum Authors
|
||||
// This file is part of go-ethereum.
|
||||
//
|
||||
// go-ethereum is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// go-ethereum is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/ethereum/go-ethereum/p2p/discover"
|
||||
"github.com/ethereum/go-ethereum/p2p/enode"
|
||||
"github.com/ethereum/go-ethereum/params"
|
||||
"gopkg.in/urfave/cli.v1"
|
||||
)
|
||||
|
||||
var (
|
||||
discv4Command = cli.Command{
|
||||
Name: "discv4",
|
||||
Usage: "Node Discovery v4 tools",
|
||||
Subcommands: []cli.Command{
|
||||
discv4PingCommand,
|
||||
discv4RequestRecordCommand,
|
||||
discv4ResolveCommand,
|
||||
},
|
||||
}
|
||||
discv4PingCommand = cli.Command{
|
||||
Name: "ping",
|
||||
Usage: "Sends ping to a node",
|
||||
Action: discv4Ping,
|
||||
}
|
||||
discv4RequestRecordCommand = cli.Command{
|
||||
Name: "requestenr",
|
||||
Usage: "Requests a node record using EIP-868 enrRequest",
|
||||
Action: discv4RequestRecord,
|
||||
}
|
||||
discv4ResolveCommand = cli.Command{
|
||||
Name: "resolve",
|
||||
Usage: "Finds a node in the DHT",
|
||||
Action: discv4Resolve,
|
||||
Flags: []cli.Flag{bootnodesFlag},
|
||||
}
|
||||
)
|
||||
|
||||
var bootnodesFlag = cli.StringFlag{
|
||||
Name: "bootnodes",
|
||||
Usage: "Comma separated nodes used for bootstrapping",
|
||||
}
|
||||
|
||||
func discv4Ping(ctx *cli.Context) error {
|
||||
n, disc, err := getNodeArgAndStartV4(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer disc.Close()
|
||||
|
||||
start := time.Now()
|
||||
if err := disc.Ping(n); err != nil {
|
||||
return fmt.Errorf("node didn't respond: %v", err)
|
||||
}
|
||||
fmt.Printf("node responded to ping (RTT %v).\n", time.Since(start))
|
||||
return nil
|
||||
}
|
||||
|
||||
func discv4RequestRecord(ctx *cli.Context) error {
|
||||
n, disc, err := getNodeArgAndStartV4(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer disc.Close()
|
||||
|
||||
respN, err := disc.RequestENR(n)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't retrieve record: %v", err)
|
||||
}
|
||||
fmt.Println(respN.String())
|
||||
return nil
|
||||
}
|
||||
|
||||
func discv4Resolve(ctx *cli.Context) error {
|
||||
n, disc, err := getNodeArgAndStartV4(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer disc.Close()
|
||||
|
||||
fmt.Println(disc.Resolve(n).String())
|
||||
return nil
|
||||
}
|
||||
|
||||
func getNodeArgAndStartV4(ctx *cli.Context) (*enode.Node, *discover.UDPv4, error) {
|
||||
if ctx.NArg() != 1 {
|
||||
return nil, nil, fmt.Errorf("missing node as command-line argument")
|
||||
}
|
||||
n, err := parseNode(ctx.Args()[0])
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var bootnodes []*enode.Node
|
||||
if commandHasFlag(ctx, bootnodesFlag) {
|
||||
bootnodes, err = parseBootnodes(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
disc, err := startV4(bootnodes)
|
||||
return n, disc, err
|
||||
}
|
||||
|
||||
func parseBootnodes(ctx *cli.Context) ([]*enode.Node, error) {
|
||||
s := params.RinkebyBootnodes
|
||||
if ctx.IsSet(bootnodesFlag.Name) {
|
||||
s = strings.Split(ctx.String(bootnodesFlag.Name), ",")
|
||||
}
|
||||
nodes := make([]*enode.Node, len(s))
|
||||
var err error
|
||||
for i, record := range s {
|
||||
nodes[i], err = parseNode(record)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid bootstrap node: %v", err)
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
// commandHasFlag returns true if the current command supports the given flag.
|
||||
func commandHasFlag(ctx *cli.Context, flag cli.Flag) bool {
|
||||
flags := ctx.FlagNames()
|
||||
sort.Strings(flags)
|
||||
i := sort.SearchStrings(flags, flag.GetName())
|
||||
return i != len(flags) && flags[i] == flag.GetName()
|
||||
}
|
||||
|
||||
// startV4 starts an ephemeral discovery V4 node.
|
||||
func startV4(bootnodes []*enode.Node) (*discover.UDPv4, error) {
|
||||
var cfg discover.Config
|
||||
cfg.Bootnodes = bootnodes
|
||||
cfg.PrivateKey, _ = crypto.GenerateKey()
|
||||
db, _ := enode.OpenDB("")
|
||||
ln := enode.NewLocalNode(db, cfg.PrivateKey)
|
||||
|
||||
socket, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IP{0, 0, 0, 0}})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
addr := socket.LocalAddr().(*net.UDPAddr)
|
||||
ln.SetFallbackIP(net.IP{127, 0, 0, 1})
|
||||
ln.SetFallbackUDP(addr.Port)
|
||||
return discover.ListenUDP(socket, ln, cfg)
|
||||
}
|
198
vendor/github.com/ethereum/go-ethereum/cmd/devp2p/enrcmd.go
generated
vendored
Normal file
198
vendor/github.com/ethereum/go-ethereum/cmd/devp2p/enrcmd.go
generated
vendored
Normal file
@ -0,0 +1,198 @@
|
||||
// Copyright 2019 The go-ethereum Authors
|
||||
// This file is part of go-ethereum.
|
||||
//
|
||||
// go-ethereum is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// go-ethereum is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/ethereum/go-ethereum/p2p/enode"
|
||||
"github.com/ethereum/go-ethereum/p2p/enr"
|
||||
"github.com/ethereum/go-ethereum/rlp"
|
||||
"gopkg.in/urfave/cli.v1"
|
||||
)
|
||||
|
||||
var enrdumpCommand = cli.Command{
|
||||
Name: "enrdump",
|
||||
Usage: "Pretty-prints node records",
|
||||
Action: enrdump,
|
||||
Flags: []cli.Flag{
|
||||
cli.StringFlag{Name: "file"},
|
||||
},
|
||||
}
|
||||
|
||||
func enrdump(ctx *cli.Context) error {
|
||||
var source string
|
||||
if file := ctx.String("file"); file != "" {
|
||||
if ctx.NArg() != 0 {
|
||||
return fmt.Errorf("can't dump record from command-line argument in -file mode")
|
||||
}
|
||||
var b []byte
|
||||
var err error
|
||||
if file == "-" {
|
||||
b, err = ioutil.ReadAll(os.Stdin)
|
||||
} else {
|
||||
b, err = ioutil.ReadFile(file)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
source = string(b)
|
||||
} else if ctx.NArg() == 1 {
|
||||
source = ctx.Args()[0]
|
||||
} else {
|
||||
return fmt.Errorf("need record as argument")
|
||||
}
|
||||
|
||||
r, err := parseRecord(source)
|
||||
if err != nil {
|
||||
return fmt.Errorf("INVALID: %v", err)
|
||||
}
|
||||
fmt.Print(dumpRecord(r))
|
||||
return nil
|
||||
}
|
||||
|
||||
// dumpRecord creates a human-readable description of the given node record.
|
||||
func dumpRecord(r *enr.Record) string {
|
||||
out := new(bytes.Buffer)
|
||||
if n, err := enode.New(enode.ValidSchemes, r); err != nil {
|
||||
fmt.Fprintf(out, "INVALID: %v\n", err)
|
||||
} else {
|
||||
fmt.Fprintf(out, "Node ID: %v\n", n.ID())
|
||||
}
|
||||
kv := r.AppendElements(nil)[1:]
|
||||
fmt.Fprintf(out, "Record has sequence number %d and %d key/value pairs.\n", r.Seq(), len(kv)/2)
|
||||
fmt.Fprint(out, dumpRecordKV(kv, 2))
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func dumpRecordKV(kv []interface{}, indent int) string {
|
||||
// Determine the longest key name for alignment.
|
||||
var out string
|
||||
var longestKey = 0
|
||||
for i := 0; i < len(kv); i += 2 {
|
||||
key := kv[i].(string)
|
||||
if len(key) > longestKey {
|
||||
longestKey = len(key)
|
||||
}
|
||||
}
|
||||
// Print the keys, invoking formatters for known keys.
|
||||
for i := 0; i < len(kv); i += 2 {
|
||||
key := kv[i].(string)
|
||||
val := kv[i+1].(rlp.RawValue)
|
||||
pad := longestKey - len(key)
|
||||
out += strings.Repeat(" ", indent) + strconv.Quote(key) + strings.Repeat(" ", pad+1)
|
||||
formatter := attrFormatters[key]
|
||||
if formatter == nil {
|
||||
formatter = formatAttrRaw
|
||||
}
|
||||
fmtval, ok := formatter(val)
|
||||
if ok {
|
||||
out += fmtval + "\n"
|
||||
} else {
|
||||
out += hex.EncodeToString(val) + " (!)\n"
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// parseNode parses a node record and verifies its signature.
|
||||
func parseNode(source string) (*enode.Node, error) {
|
||||
if strings.HasPrefix(source, "enode://") {
|
||||
return enode.ParseV4(source)
|
||||
}
|
||||
r, err := parseRecord(source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return enode.New(enode.ValidSchemes, r)
|
||||
}
|
||||
|
||||
// parseRecord parses a node record from hex, base64, or raw binary input.
|
||||
func parseRecord(source string) (*enr.Record, error) {
|
||||
bin := []byte(source)
|
||||
if d, ok := decodeRecordHex(bytes.TrimSpace(bin)); ok {
|
||||
bin = d
|
||||
} else if d, ok := decodeRecordBase64(bytes.TrimSpace(bin)); ok {
|
||||
bin = d
|
||||
}
|
||||
var r enr.Record
|
||||
err := rlp.DecodeBytes(bin, &r)
|
||||
return &r, err
|
||||
}
|
||||
|
||||
func decodeRecordHex(b []byte) ([]byte, bool) {
|
||||
if bytes.HasPrefix(b, []byte("0x")) {
|
||||
b = b[2:]
|
||||
}
|
||||
dec := make([]byte, hex.DecodedLen(len(b)))
|
||||
_, err := hex.Decode(dec, b)
|
||||
return dec, err == nil
|
||||
}
|
||||
|
||||
func decodeRecordBase64(b []byte) ([]byte, bool) {
|
||||
if bytes.HasPrefix(b, []byte("enr:")) {
|
||||
b = b[4:]
|
||||
}
|
||||
dec := make([]byte, base64.RawURLEncoding.DecodedLen(len(b)))
|
||||
n, err := base64.RawURLEncoding.Decode(dec, b)
|
||||
return dec[:n], err == nil
|
||||
}
|
||||
|
||||
// attrFormatters contains formatting functions for well-known ENR keys.
|
||||
var attrFormatters = map[string]func(rlp.RawValue) (string, bool){
|
||||
"id": formatAttrString,
|
||||
"ip": formatAttrIP,
|
||||
"ip6": formatAttrIP,
|
||||
"tcp": formatAttrUint,
|
||||
"tcp6": formatAttrUint,
|
||||
"udp": formatAttrUint,
|
||||
"udp6": formatAttrUint,
|
||||
}
|
||||
|
||||
func formatAttrRaw(v rlp.RawValue) (string, bool) {
|
||||
s := hex.EncodeToString(v)
|
||||
return s, true
|
||||
}
|
||||
|
||||
func formatAttrString(v rlp.RawValue) (string, bool) {
|
||||
content, _, err := rlp.SplitString(v)
|
||||
return strconv.Quote(string(content)), err == nil
|
||||
}
|
||||
|
||||
func formatAttrIP(v rlp.RawValue) (string, bool) {
|
||||
content, _, err := rlp.SplitString(v)
|
||||
if err != nil || len(content) != 4 && len(content) != 6 {
|
||||
return "", false
|
||||
}
|
||||
return net.IP(content).String(), true
|
||||
}
|
||||
|
||||
func formatAttrUint(v rlp.RawValue) (string, bool) {
|
||||
var x uint64
|
||||
if err := rlp.DecodeBytes(v, &x); err != nil {
|
||||
return "", false
|
||||
}
|
||||
return strconv.FormatUint(x, 10), true
|
||||
}
|
68
vendor/github.com/ethereum/go-ethereum/cmd/devp2p/main.go
generated
vendored
Normal file
68
vendor/github.com/ethereum/go-ethereum/cmd/devp2p/main.go
generated
vendored
Normal file
@ -0,0 +1,68 @@
|
||||
// Copyright 2019 The go-ethereum Authors
|
||||
// This file is part of go-ethereum.
|
||||
//
|
||||
// go-ethereum is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// go-ethereum is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/ethereum/go-ethereum/internal/debug"
|
||||
"github.com/ethereum/go-ethereum/params"
|
||||
"gopkg.in/urfave/cli.v1"
|
||||
)
|
||||
|
||||
var (
|
||||
// Git information set by linker when building with ci.go.
|
||||
gitCommit string
|
||||
gitDate string
|
||||
app = &cli.App{
|
||||
Name: filepath.Base(os.Args[0]),
|
||||
Usage: "go-ethereum devp2p tool",
|
||||
Version: params.VersionWithCommit(gitCommit, gitDate),
|
||||
Writer: os.Stdout,
|
||||
HideVersion: true,
|
||||
}
|
||||
)
|
||||
|
||||
func init() {
|
||||
// Set up the CLI app.
|
||||
app.Flags = append(app.Flags, debug.Flags...)
|
||||
app.Before = func(ctx *cli.Context) error {
|
||||
return debug.Setup(ctx, "")
|
||||
}
|
||||
app.After = func(ctx *cli.Context) error {
|
||||
debug.Exit()
|
||||
return nil
|
||||
}
|
||||
app.CommandNotFound = func(ctx *cli.Context, cmd string) {
|
||||
fmt.Fprintf(os.Stderr, "No such command: %s\n", cmd)
|
||||
os.Exit(1)
|
||||
}
|
||||
// Add subcommands.
|
||||
app.Commands = []cli.Command{
|
||||
enrdumpCommand,
|
||||
discv4Command,
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
if err := app.Run(os.Args); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
3
vendor/github.com/ethereum/go-ethereum/cmd/ethkey/main.go
generated
vendored
3
vendor/github.com/ethereum/go-ethereum/cmd/ethkey/main.go
generated
vendored
@ -30,11 +30,12 @@ const (
|
||||
|
||||
// Git SHA1 commit hash of the release (set via linker flags)
|
||||
var gitCommit = ""
|
||||
var gitDate = ""
|
||||
|
||||
var app *cli.App
|
||||
|
||||
func init() {
|
||||
app = utils.NewApp(gitCommit, "an Ethereum key manager")
|
||||
app = utils.NewApp(gitCommit, gitDate, "an Ethereum key manager")
|
||||
app.Commands = []cli.Command{
|
||||
commandGenerate,
|
||||
commandInspect,
|
||||
|
3
vendor/github.com/ethereum/go-ethereum/cmd/evm/main.go
generated
vendored
3
vendor/github.com/ethereum/go-ethereum/cmd/evm/main.go
generated
vendored
@ -27,9 +27,10 @@ import (
|
||||
)
|
||||
|
||||
var gitCommit = "" // Git SHA1 commit hash of the release (set via linker flags)
|
||||
var gitDate = ""
|
||||
|
||||
var (
|
||||
app = utils.NewApp(gitCommit, "the evm command line interface")
|
||||
app = utils.NewApp(gitCommit, gitDate, "the evm command line interface")
|
||||
|
||||
DebugFlag = cli.BoolFlag{
|
||||
Name: "debug",
|
||||
|
51
vendor/github.com/ethereum/go-ethereum/cmd/faucet/faucet.go
generated
vendored
51
vendor/github.com/ethereum/go-ethereum/cmd/faucet/faucet.go
generated
vendored
@ -88,6 +88,11 @@ var (
|
||||
ether = new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil)
|
||||
)
|
||||
|
||||
var (
|
||||
gitCommit = "" // Git SHA1 commit hash of the release (set via linker flags)
|
||||
gitDate = "" // Git commit date YYYYMMDD of the release (set via linker flags)
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Parse the flags and set up the logger to print everything requested
|
||||
flag.Parse()
|
||||
@ -216,7 +221,7 @@ func newFaucet(genesis *core.Genesis, port int, enodes []*discv5.Node, network u
|
||||
// Assemble the raw devp2p protocol stack
|
||||
stack, err := node.New(&node.Config{
|
||||
Name: "geth",
|
||||
Version: params.VersionWithMeta,
|
||||
Version: params.VersionWithCommit(gitCommit, gitDate),
|
||||
DataDir: filepath.Join(os.Getenv("HOME"), ".faucet"),
|
||||
P2P: p2p.Config{
|
||||
NAT: nat.Any(),
|
||||
@ -255,7 +260,7 @@ func newFaucet(genesis *core.Genesis, port int, enodes []*discv5.Node, network u
|
||||
return nil, err
|
||||
}
|
||||
for _, boot := range enodes {
|
||||
old, err := enode.ParseV4(boot.String())
|
||||
old, err := enode.Parse(enode.ValidSchemes, boot.String())
|
||||
if err == nil {
|
||||
stack.Server().AddPeer(old)
|
||||
}
|
||||
@ -440,10 +445,14 @@ func (f *faucet) apiHandler(conn *websocket.Conn) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
case strings.HasPrefix(msg.URL, "https://plus.google.com/"):
|
||||
if err = sendError(conn, errors.New("Google+ authentication discontinued as the service was sunset")); err != nil {
|
||||
log.Warn("Failed to send Google+ deprecation to client", "err", err)
|
||||
return
|
||||
}
|
||||
continue
|
||||
case strings.HasPrefix(msg.URL, "https://twitter.com/"):
|
||||
username, avatar, address, err = authTwitter(msg.URL)
|
||||
case strings.HasPrefix(msg.URL, "https://plus.google.com/"):
|
||||
username, avatar, address, err = authGooglePlus(msg.URL)
|
||||
case strings.HasPrefix(msg.URL, "https://www.facebook.com/"):
|
||||
username, avatar, address, err = authFacebook(msg.URL)
|
||||
case *noauthFlag:
|
||||
@ -699,40 +708,6 @@ func authTwitter(url string) (string, string, common.Address, error) {
|
||||
return username + "@twitter", avatar, address, nil
|
||||
}
|
||||
|
||||
// authGooglePlus tries to authenticate a faucet request using GooglePlus posts,
|
||||
// returning the username, avatar URL and Ethereum address to fund on success.
|
||||
func authGooglePlus(url string) (string, string, common.Address, error) {
|
||||
// Ensure the user specified a meaningful URL, no fancy nonsense
|
||||
parts := strings.Split(url, "/")
|
||||
if len(parts) < 4 || parts[len(parts)-2] != "posts" {
|
||||
return "", "", common.Address{}, errors.New("Invalid Google+ post URL")
|
||||
}
|
||||
username := parts[len(parts)-3]
|
||||
|
||||
// Google's API isn't really friendly with direct links. Still, we don't
|
||||
// want to do ask read permissions from users, so just load the public posts and
|
||||
// scrape it for the Ethereum address and profile URL.
|
||||
res, err := http.Get(url)
|
||||
if err != nil {
|
||||
return "", "", common.Address{}, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
body, err := ioutil.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
return "", "", common.Address{}, err
|
||||
}
|
||||
address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body)))
|
||||
if address == (common.Address{}) {
|
||||
return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
|
||||
}
|
||||
var avatar string
|
||||
if parts = regexp.MustCompile("src=\"([^\"]+googleusercontent.com[^\"]+photo.jpg)\"").FindStringSubmatch(string(body)); len(parts) == 2 {
|
||||
avatar = parts[1]
|
||||
}
|
||||
return username + "@google+", avatar, address, nil
|
||||
}
|
||||
|
||||
// authFacebook tries to authenticate a faucet request using Facebook posts,
|
||||
// returning the username, avatar URL and Ethereum address to fund on success.
|
||||
func authFacebook(url string) (string, string, common.Address, error) {
|
||||
|
5
vendor/github.com/ethereum/go-ethereum/cmd/faucet/faucet.html
generated
vendored
5
vendor/github.com/ethereum/go-ethereum/cmd/faucet/faucet.html
generated
vendored
@ -80,14 +80,11 @@
|
||||
<div class="row" style="margin-top: 32px;">
|
||||
<div class="col-lg-12">
|
||||
<h3>How does this work?</h3>
|
||||
<p>This Ether faucet is running on the {{.Network}} network. To prevent malicious actors from exhausting all available funds or accumulating enough Ether to mount long running spam attacks, requests are tied to common 3rd party social network accounts. Anyone having a Twitter, Google+ or Facebook account may request funds within the permitted limits.</p>
|
||||
<p>This Ether faucet is running on the {{.Network}} network. To prevent malicious actors from exhausting all available funds or accumulating enough Ether to mount long running spam attacks, requests are tied to common 3rd party social network accounts. Anyone having a Twitter or Facebook account may request funds within the permitted limits.</p>
|
||||
<dl class="dl-horizontal">
|
||||
<dt style="width: auto; margin-left: 40px;"><i class="fa fa-twitter" aria-hidden="true" style="font-size: 36px;"></i></dt>
|
||||
<dd style="margin-left: 88px; margin-bottom: 10px;"></i> To request funds via Twitter, make a <a href="https://twitter.com/intent/tweet?text=Requesting%20faucet%20funds%20into%200x0000000000000000000000000000000000000000%20on%20the%20%23{{.Network}}%20%23Ethereum%20test%20network." target="_about:blank">tweet</a> with your Ethereum address pasted into the contents (surrounding text doesn't matter).<br/>Copy-paste the <a href="https://support.twitter.com/articles/80586" target="_about:blank">tweets URL</a> into the above input box and fire away!</dd>
|
||||
|
||||
<dt style="width: auto; margin-left: 40px;"><i class="fa fa-google-plus-official" aria-hidden="true" style="font-size: 36px;"></i></dt>
|
||||
<dd style="margin-left: 88px; margin-bottom: 10px;"></i> To request funds via Google Plus, publish a new <strong>public</strong> post with your Ethereum address embedded into the content (surrounding text doesn't matter).<br/>Copy-paste the posts URL into the above input box and fire away!</dd>
|
||||
|
||||
<dt style="width: auto; margin-left: 40px;"><i class="fa fa-facebook" aria-hidden="true" style="font-size: 36px;"></i></dt>
|
||||
<dd style="margin-left: 88px; margin-bottom: 10px;"></i> To request funds via Facebook, publish a new <strong>public</strong> post with your Ethereum address embedded into the content (surrounding text doesn't matter).<br/>Copy-paste the <a href="https://www.facebook.com/help/community/question/?id=282662498552845" target="_about:blank">posts URL</a> into the above input box and fire away!</dd>
|
||||
|
||||
|
65
vendor/github.com/ethereum/go-ethereum/cmd/faucet/website.go
generated
vendored
65
vendor/github.com/ethereum/go-ethereum/cmd/faucet/website.go
generated
vendored
File diff suppressed because one or more lines are too long
10
vendor/github.com/ethereum/go-ethereum/cmd/geth/accountcmd.go
generated
vendored
10
vendor/github.com/ethereum/go-ethereum/cmd/geth/accountcmd.go
generated
vendored
@ -307,12 +307,18 @@ func accountCreate(ctx *cli.Context) error {
|
||||
|
||||
password := getPassPhrase("Your new account is locked with a password. Please give a password. Do not forget this password.", true, 0, utils.MakePasswordList(ctx))
|
||||
|
||||
address, err := keystore.StoreKey(keydir, password, scryptN, scryptP)
|
||||
account, err := keystore.StoreKey(keydir, password, scryptN, scryptP)
|
||||
|
||||
if err != nil {
|
||||
utils.Fatalf("Failed to create account: %v", err)
|
||||
}
|
||||
fmt.Printf("Address: {%x}\n", address)
|
||||
fmt.Printf("\nYour new key was generated\n\n")
|
||||
fmt.Printf("Public address of the key: %s\n", account.Address.Hex())
|
||||
fmt.Printf("Path of the secret key file: %s\n\n", account.URL.Path)
|
||||
fmt.Printf("- You can share your public address with anyone. Others need it to interact with you.\n")
|
||||
fmt.Printf("- You must NEVER share the secret key with anyone! The key controls access to your funds!\n")
|
||||
fmt.Printf("- You must BACKUP your key file! Without the key, it's impossible to access account funds!\n")
|
||||
fmt.Printf("- You must REMEMBER your password! Without the password, it's impossible to decrypt the key!\n\n")
|
||||
return nil
|
||||
}
|
||||
|
||||
|
123
vendor/github.com/ethereum/go-ethereum/cmd/geth/chaincmd.go
generated
vendored
123
vendor/github.com/ethereum/go-ethereum/cmd/geth/chaincmd.go
generated
vendored
@ -20,6 +20,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
@ -35,6 +36,7 @@ import (
|
||||
"github.com/ethereum/go-ethereum/eth/downloader"
|
||||
"github.com/ethereum/go-ethereum/event"
|
||||
"github.com/ethereum/go-ethereum/log"
|
||||
"github.com/ethereum/go-ethereum/trie"
|
||||
"gopkg.in/urfave/cli.v1"
|
||||
)
|
||||
|
||||
@ -166,6 +168,22 @@ Remove blockchain and state databases`,
|
||||
The arguments are interpreted as block numbers or hashes.
|
||||
Use "ethereum dump 0" to dump the genesis block.`,
|
||||
}
|
||||
inspectCommand = cli.Command{
|
||||
Action: utils.MigrateFlags(inspect),
|
||||
Name: "inspect",
|
||||
Usage: "Inspect the storage size for each type of data in the database",
|
||||
ArgsUsage: " ",
|
||||
Flags: []cli.Flag{
|
||||
utils.DataDirFlag,
|
||||
utils.AncientFlag,
|
||||
utils.CacheFlag,
|
||||
utils.TestnetFlag,
|
||||
utils.RinkebyFlag,
|
||||
utils.GoerliFlag,
|
||||
utils.SyncModeFlag,
|
||||
},
|
||||
Category: "BLOCKCHAIN COMMANDS",
|
||||
}
|
||||
)
|
||||
|
||||
// initGenesis will initialise the given JSON format genesis file and writes it as
|
||||
@ -367,19 +385,27 @@ func exportPreimages(ctx *cli.Context) error {
|
||||
|
||||
func copyDb(ctx *cli.Context) error {
|
||||
// Ensure we have a source chain directory to copy
|
||||
if len(ctx.Args()) != 1 {
|
||||
if len(ctx.Args()) < 1 {
|
||||
utils.Fatalf("Source chaindata directory path argument missing")
|
||||
}
|
||||
if len(ctx.Args()) < 2 {
|
||||
utils.Fatalf("Source ancient chain directory path argument missing")
|
||||
}
|
||||
// Initialize a new chain for the running node to sync into
|
||||
stack := makeFullNode(ctx)
|
||||
defer stack.Close()
|
||||
|
||||
chain, chainDb := utils.MakeChain(ctx, stack)
|
||||
syncmode := *utils.GlobalTextMarshaler(ctx, utils.SyncModeFlag.Name).(*downloader.SyncMode)
|
||||
dl := downloader.New(syncmode, chainDb, new(event.TypeMux), chain, nil, nil)
|
||||
syncMode := *utils.GlobalTextMarshaler(ctx, utils.SyncModeFlag.Name).(*downloader.SyncMode)
|
||||
|
||||
var syncBloom *trie.SyncBloom
|
||||
if syncMode == downloader.FastSync {
|
||||
syncBloom = trie.NewSyncBloom(uint64(ctx.GlobalInt(utils.CacheFlag.Name)/2), chainDb)
|
||||
}
|
||||
dl := downloader.New(0, chainDb, syncBloom, new(event.TypeMux), chain, nil, nil)
|
||||
|
||||
// Create a source peer to satisfy downloader requests from
|
||||
db, err := rawdb.NewLevelDBDatabase(ctx.Args().First(), ctx.GlobalInt(utils.CacheFlag.Name), 256, "")
|
||||
db, err := rawdb.NewLevelDBDatabaseWithFreezer(ctx.Args().First(), ctx.GlobalInt(utils.CacheFlag.Name)/2, 256, ctx.Args().Get(1), "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@ -395,7 +421,7 @@ func copyDb(ctx *cli.Context) error {
|
||||
start := time.Now()
|
||||
|
||||
currentHeader := hc.CurrentHeader()
|
||||
if err = dl.Synchronise("local", currentHeader.Hash(), hc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64()), syncmode); err != nil {
|
||||
if err = dl.Synchronise("local", currentHeader.Hash(), hc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64()), syncMode); err != nil {
|
||||
return err
|
||||
}
|
||||
for dl.Synchronising() {
|
||||
@ -414,34 +440,65 @@ func copyDb(ctx *cli.Context) error {
|
||||
}
|
||||
|
||||
func removeDB(ctx *cli.Context) error {
|
||||
stack, _ := makeConfigNode(ctx)
|
||||
stack, config := makeConfigNode(ctx)
|
||||
|
||||
for _, name := range []string{"chaindata", "lightchaindata"} {
|
||||
// Ensure the database exists in the first place
|
||||
logger := log.New("database", name)
|
||||
|
||||
dbdir := stack.ResolvePath(name)
|
||||
if !common.FileExist(dbdir) {
|
||||
logger.Info("Database doesn't exist, skipping", "path", dbdir)
|
||||
continue
|
||||
}
|
||||
// Confirm removal and execute
|
||||
fmt.Println(dbdir)
|
||||
confirm, err := console.Stdin.PromptConfirm("Remove this database?")
|
||||
switch {
|
||||
case err != nil:
|
||||
utils.Fatalf("%v", err)
|
||||
case !confirm:
|
||||
logger.Warn("Database deletion aborted")
|
||||
default:
|
||||
start := time.Now()
|
||||
os.RemoveAll(dbdir)
|
||||
logger.Info("Database successfully deleted", "elapsed", common.PrettyDuration(time.Since(start)))
|
||||
}
|
||||
// Remove the full node state database
|
||||
path := stack.ResolvePath("chaindata")
|
||||
if common.FileExist(path) {
|
||||
confirmAndRemoveDB(path, "full node state database")
|
||||
} else {
|
||||
log.Info("Full node state database missing", "path", path)
|
||||
}
|
||||
// Remove the full node ancient database
|
||||
path = config.Eth.DatabaseFreezer
|
||||
switch {
|
||||
case path == "":
|
||||
path = filepath.Join(stack.ResolvePath("chaindata"), "ancient")
|
||||
case !filepath.IsAbs(path):
|
||||
path = config.Node.ResolvePath(path)
|
||||
}
|
||||
if common.FileExist(path) {
|
||||
confirmAndRemoveDB(path, "full node ancient database")
|
||||
} else {
|
||||
log.Info("Full node ancient database missing", "path", path)
|
||||
}
|
||||
// Remove the light node database
|
||||
path = stack.ResolvePath("lightchaindata")
|
||||
if common.FileExist(path) {
|
||||
confirmAndRemoveDB(path, "light node database")
|
||||
} else {
|
||||
log.Info("Light node database missing", "path", path)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// confirmAndRemoveDB prompts the user for a last confirmation and removes the
|
||||
// folder if accepted.
|
||||
func confirmAndRemoveDB(database string, kind string) {
|
||||
confirm, err := console.Stdin.PromptConfirm(fmt.Sprintf("Remove %s (%s)?", kind, database))
|
||||
switch {
|
||||
case err != nil:
|
||||
utils.Fatalf("%v", err)
|
||||
case !confirm:
|
||||
log.Info("Database deletion skipped", "path", database)
|
||||
default:
|
||||
start := time.Now()
|
||||
filepath.Walk(database, func(path string, info os.FileInfo, err error) error {
|
||||
// If we're at the top level folder, recurse into
|
||||
if path == database {
|
||||
return nil
|
||||
}
|
||||
// Delete all the files, but not subfolders
|
||||
if !info.IsDir() {
|
||||
os.Remove(path)
|
||||
return nil
|
||||
}
|
||||
return filepath.SkipDir
|
||||
})
|
||||
log.Info("Database successfully deleted", "path", database, "elapsed", common.PrettyDuration(time.Since(start)))
|
||||
}
|
||||
}
|
||||
|
||||
func dump(ctx *cli.Context) error {
|
||||
stack := makeFullNode(ctx)
|
||||
defer stack.Close()
|
||||
@ -470,6 +527,16 @@ func dump(ctx *cli.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func inspect(ctx *cli.Context) error {
|
||||
node, _ := makeConfigNode(ctx)
|
||||
defer node.Close()
|
||||
|
||||
_, chainDb := utils.MakeChain(ctx, node)
|
||||
defer chainDb.Close()
|
||||
|
||||
return rawdb.InspectDatabase(chainDb)
|
||||
}
|
||||
|
||||
// hashish returns true for strings that look like hashes.
|
||||
func hashish(x string) bool {
|
||||
_, err := strconv.Atoi(x)
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user