├── .gitignore ├── Dockerfile ├── LICENSE.txt ├── README-cn.md ├── README.md ├── cloudbuild.yaml ├── k8s └── deployment.yaml ├── main.go ├── submit.sh └── vendor ├── github.com └── eoscanada │ └── eos-go │ ├── LICENSE.txt │ ├── README.md │ ├── abi.go │ ├── actions.go │ ├── api.go │ ├── btcsuite │ ├── btcd │ │ ├── LICENSE │ │ └── btcec │ │ │ ├── README.md │ │ │ ├── btcec.go │ │ │ ├── ciphering.go │ │ │ ├── doc.go │ │ │ ├── field.go │ │ │ ├── gensecp256k1.go │ │ │ ├── precompute.go │ │ │ ├── privkey.go │ │ │ ├── pubkey.go │ │ │ ├── secp256k1.go │ │ │ └── signature.go │ └── btcutil │ │ ├── LICENSE │ │ ├── README.md │ │ ├── base58 │ │ ├── README.md │ │ ├── alphabet.go │ │ ├── base58.go │ │ ├── base58check.go │ │ ├── cov_report.sh │ │ ├── doc.go │ │ └── genalphabet.go │ │ ├── doc.go │ │ ├── doublehash.go │ │ └── wif.go │ ├── decoder.go │ ├── ecc │ ├── README.md │ ├── curve.go │ ├── privkey.go │ ├── pubkey.go │ └── signature.go │ ├── encoder.go │ ├── error.go │ ├── name.go │ ├── p2p.go │ ├── p2ptypes.go │ ├── responses.go │ ├── signer.go │ ├── system │ ├── bidname.go │ ├── buyram.go │ ├── buyrambytes.go │ ├── claimrewards.go │ ├── delegatebw.go │ ├── init.go │ ├── newaccount.go │ ├── nonce.go │ ├── refund.go │ ├── regproducer.go │ ├── regproxy.go │ ├── rmvproducer.go │ ├── setcode.go │ ├── setpriv.go │ ├── setprods.go │ ├── setram.go │ ├── types.go │ ├── undelegatebw.go │ ├── unregprod.go │ ├── updateauth.go │ └── voteproducer.go │ ├── transaction.go │ └── types.go ├── golang.org └── x │ └── crypto │ ├── LICENSE │ ├── PATENTS │ └── ripemd160 │ ├── ripemd160.go │ └── ripemd160block.go └── vendor.json /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM gcr.io/cloud-builders/go as builder 2 | 3 | ENV CGO_ENABLED 0 4 | ENV PKG /root/go/src/github.com/eoscanada/eos-claimer 5 | RUN mkdir -p $PKG 6 | COPY . $PKG 7 | RUN cd $PKG \ 8 | && go get -v -t . \ 9 | && go test -v \ 10 | && go build -v -o /eos-claimer 11 | 12 | 13 | FROM alpine:latest 14 | 15 | RUN apk update && apk add ca-certificates && rm -rf /var/cache/apk/* 16 | COPY --from=builder /eos-claimer /app/eos-claimer 17 | 18 | ENV EOS_CLAIMER_URL https://mainnet.eoscanada.com 19 | ENV EOS_CLAIMER_OWNER eoscanadacom 20 | ENV EOS_CLAIMER_PERMISSION claimer 21 | ENV EOS_CLAIMER_KEY none 22 | 23 | CMD /app/eos-claimer 24 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright 2018 EOS Canada 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 18 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 19 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 20 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /README-cn.md: -------------------------------------------------------------------------------- 1 | 千万别忘了 claimrewards! 2 | ---------------------------- 3 | 4 | Just claim it, claim it, claim it before it's gone. 5 | 6 | 7 | 8 | 设置权限 9 | ----------------- 10 | 11 | 请用一次性密钥进行此操作。 12 | 13 | ``` 14 | cleos set account permission PRODUCERACCT claimer '{"threshold":1,"keys":[{"key":"YOUR_PUB_KEY","weight":1}]}' "active" -p PRODUCERACCT@active 15 | cleos set action permission PRODUCERACCT eosio claimrewards claimer 16 | ``` 17 | 18 | 用 Kubernetes,输入 secret: 19 | 20 | ``` 21 | kubectl create secret generic claimer --from-literal=privkey=PRIVATEKEY --from-literal=pubkey=YOUR_PUB_KEY 22 | ``` 23 | 启动后等着获益吧。 24 | 25 | 26 | 27 | 28 | 安装 29 | ------- 30 | 31 | 请用: 32 | 33 | ``` 34 | go get -u -v github.com/eoscanada/eos-claimer 35 | ``` 36 | 37 | 38 | 常见问题 39 | --- 40 | 41 | 42 | 问:10秒是不是有点太短了? 43 | 44 | 答:不是。再少点也没问题。它会撞到前面接收你交易的节点, 45 | 一直失败到你的获得奖励时间。交易不会广播,因为它不会通过24小时的断言。 46 | 不过,对着你自己的节点这样做,别弄我们的。 47 | 48 | 49 | 问: `set action permission` 是什么玩意儿? 50 | 51 | 答:它会调用 `eosio::linkauth` 并为这个 action 分配一个命名权限。 52 | 这意味着您现在可以签署一个交易,用 `claimer` 权限来授权 *这个合约* 上的 *这个 action*。 53 | 这是个EOS.IO区块链上还没有得到应有的注意力的,非常强大的功能。 54 | 不过请注意,1.0版本的 `get_account` 指令不会给你一个具象化的链接身份验证和action到权限映射。 55 | 不过我肯定马上就会有的。 有了这样的设置和 56 | `claimrewards` action 的设计..你甚至可以把相关的私钥给你的敌人...... 57 | 他们可以替你 claimrewards。 **但是别这么做啊**......你知道吧,以防万一。 58 | 59 | 证书 60 | ------- 61 | 62 | MIT 63 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Never forget to claimrewards 2 | ---------------------------- 3 | 4 | [点击查看中文版](./README-cn.md) 5 | 6 | Just claim it, claim it, claim it before it's gone. 7 | 8 | 9 | 10 | Setup permissions 11 | ----------------- 12 | 13 | Use a throw-away key for this action. 14 | 15 | ``` 16 | cleos set account permission PRODUCERACCT claimer '{"threshold":1,"keys":[{"key":"YOUR_PUB_KEY","weight":1}]}' "active" -p PRODUCERACCT@active 17 | cleos set action permission PRODUCERACCT eosio claimrewards claimer 18 | ``` 19 | 20 | With Kubernetes, inject secret with: 21 | 22 | ``` 23 | kubectl create secret generic claimer --from-literal=privkey=PRIVATEKEY --from-literal=pubkey=YOUR_PUB_KEY 24 | ``` 25 | 26 | Boot and profit. 27 | 28 | 29 | 30 | 31 | Install 32 | ------- 33 | 34 | With: 35 | 36 | ``` 37 | go get -u -v github.com/eoscanada/eos-claimer 38 | ``` 39 | 40 | 41 | FAQ 42 | --- 43 | 44 | Q: Isn't 10 secs a bit aggressive ? 45 | 46 | A: Not really. Could even be lowered. It'll bump against the front 47 | node receiving your transaction and fail each time until the time 48 | comes and is ready for your claim. The transaction will not propagate 49 | because it fails the 24h assertion. Do it against your nodes though, 50 | not ours. 51 | 52 | 53 | Q: Wut's that `set action permission` thing ? 54 | 55 | A: This calls `eosio::linkauth` and assigns a named permission to that 56 | particular action. This means you can now sign a transaction that 57 | authorizes *that specific action* on *that specific contract* with the 58 | permission `claimer`. This is a really powerful feature of EOS.IO 59 | blockchains that isn't shining as it should right now. Mind you, with 60 | release 1.0, the `get_account` calls do not give you a portrait of 61 | your linked auths and actions-to-permissions mapping. I'm sure that's 62 | coming soon though. With a setup like this here, and the design of 63 | the `claimrewards` action.. you could almost give the associated 64 | private key to your enemies.. they could claimrewards for you. BUT HEY 65 | DON'T DO THAT.. you know, just in case. 66 | 67 | LICENSE 68 | ------- 69 | 70 | MIT 71 | -------------------------------------------------------------------------------- /cloudbuild.yaml: -------------------------------------------------------------------------------- 1 | steps: 2 | 3 | - id: docker-build 4 | name: gcr.io/cloud-builders/docker 5 | args: [ 6 | 'build', 7 | '-t', 'gcr.io/$PROJECT_ID/eos-claimer:$COMMIT_SHA', 8 | '-t', 'gcr.io/$PROJECT_ID/eos-claimer:latest', 9 | '-f', 'Dockerfile', 10 | '.' 11 | ] 12 | 13 | images: 14 | - gcr.io/$PROJECT_ID/eos-claimer:latest 15 | - gcr.io/$PROJECT_ID/eos-claimer:$COMMIT_SHA 16 | -------------------------------------------------------------------------------- /k8s/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: claimer 5 | spec: 6 | replicas: 1 7 | selector: 8 | matchLabels: 9 | app: claimer 10 | template: 11 | metadata: 12 | name: claimer 13 | labels: 14 | app: claimer 15 | spec: 16 | containers: 17 | - name: claimer 18 | image: gcr.io/eoscanada-testnets/eos-claimer:latest 19 | imagePullPolicy: Always 20 | env: 21 | - name: EOS_CLAIMER_URL 22 | value: http://mainnet.eoscanada.com 23 | - name: EOS_CLAIMER_OWNER 24 | value: eoscanadacom 25 | - name: EOS_CLAIMER_PERMISSION 26 | value: claimer 27 | - name: EOS_CLAIMER_KEY 28 | valueFrom: 29 | secretKeyRef: 30 | name: claimer 31 | key: privkey 32 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | "time" 8 | 9 | eos "github.com/eoscanada/eos-go" 10 | "github.com/eoscanada/eos-go/system" 11 | ) 12 | 13 | // Define EOS_CLAIMER_KEY (with the private key that is allowed to 14 | // call `eosio::claimrewards`) 15 | // 16 | // Define EOS_CLAIMER_PERMISSION if the permission of the 17 | // EOS_CLAIMER_OWNER account is not `active` (because you linkauth'd 18 | // the action to another permission. 19 | // 20 | // Define EOS_CLAIMER_OWNER which is your BP account. 21 | // 22 | // Define EOS_CLAIMER_URL to a reachable endpoint where to send 23 | // transactions. 24 | 25 | func main() { 26 | if os.Getenv("EOS_CLAIMER_URL") == "" { 27 | log.Fatalln("EOS_CLAIMER_URL not set: make sure you set all of the required env vars. See main.go for details.") 28 | } 29 | 30 | api := eos.New(os.Getenv("EOS_CLAIMER_URL")) 31 | 32 | keyBag := eos.NewKeyBag() 33 | for _, key := range []string{ 34 | os.Getenv("EOS_CLAIMER_KEY"), 35 | } { 36 | if err := keyBag.Add(key); err != nil { 37 | log.Fatalln("Couldn't load private key specified by env var EOS_CLAIMER_KEY:", err) 38 | } 39 | } 40 | 41 | api.SetSigner(keyBag) 42 | 43 | act := system.NewClaimRewards(eos.AccountName(os.Getenv("EOS_CLAIMER_OWNER"))) 44 | if perm := os.Getenv("EOS_CLAIMER_PERMISSION"); perm != "" { 45 | act.Authorization[0].Permission = eos.PermissionName(perm) 46 | } 47 | 48 | var sleep time.Duration 49 | for { 50 | time.Sleep(sleep) 51 | sleep = 10 * time.Second 52 | 53 | log.Println("Submitting claimrewards") 54 | actionResp, err := api.SignPushActions(act) 55 | if err != nil { 56 | fmt.Println("ERROR sending claimrewards:", err) 57 | } else { 58 | fmt.Println("SUCCESSFUL RESP:", actionResp) 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /submit.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | gcloud container builds submit . --config cloudbuild.yaml --timeout 5m --substitutions COMMIT_SHA=`date +"%Y-%m-%d"` 4 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright 2018 EOS Canada 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 18 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 19 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 20 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/README.md: -------------------------------------------------------------------------------- 1 | EOS.IO API library for Go 2 | ========================= 3 | 4 | [![GoDoc](https://godoc.org/github.com/eoscanada/eos-go?status.svg)](https://godoc.org/github.com/eoscanada/eos-go) 5 | 6 | This library provides simple access to data structures (binary packing 7 | and JSON interface) and API calls to an EOS.IO RPC server, running 8 | remotely or locally. It provides wallet functionalities (KeyBag), or 9 | can sign transaction through the `keosd` wallet. It also knows about 10 | the P2P protocol on port 9876. 11 | 12 | As of before the June launch, this library is pretty much in 13 | flux. Don't expect stability, as we're moving alongside the main 14 | `eosio` codebase, which changes very fast. 15 | 16 | This library is the basis for the `eos-bios` launch orchestrator tool 17 | at https://github.com/eoscanada/eos-bios 18 | 19 | 20 | Basic usage 21 | ----------- 22 | 23 | ```go 24 | api := eos.New("http://testnet1.eos.io") 25 | 26 | infoResp, _ := api.GetInfo() 27 | accountResp, _ := api.GetAccount("initn") 28 | fmt.Println("Permission for initn:", accountResp.Permissions[0].RequiredAuth.Keys) 29 | ``` 30 | 31 | `eosio.system` and `eosio.token` contract _Actions_ are respectively in: 32 | * https://github.com/eoscanada/eos-go/tree/master/system ([godocs](https://godoc.org/github.com/eoscanada/eos-go/system)) 33 | * https://github.com/eoscanada/eos-go/tree/master/token ([godocs](https://godoc.org/github.com/eoscanada/eos-go/token)) 34 | 35 | Example 36 | ------- 37 | 38 | See example usages of the library: 39 | 40 | * https://github.com/eoscanada/eos-bios/blob/master/bios.go 41 | * https://github.com/eoscanada/eos-bios/blob/master/ops.go 42 | * Some other `main` packages under `cmd/`. 43 | 44 | 45 | Contributing 46 | ------------ 47 | 48 | Any contributions are welcome, use your standard GitHub-fu to pitch in and improve. 49 | 50 | 51 | License 52 | ------- 53 | 54 | MIT 55 | 56 | 57 | 58 | 59 | TODO notes 60 | ---------- 61 | 62 | Changes to dawn4: 63 | * sig_digest always adds something even with empty context free actions. 64 | * PUB, PVT, SIG 65 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/abi.go: -------------------------------------------------------------------------------- 1 | package eos 2 | 3 | // see: libraries/chain/contracts/abi_serializer.cpp:53... 4 | // see: libraries/chain/include/eosio/chain/contracts/types.hpp:100 5 | type ABI struct { 6 | Version string `json:"version"` 7 | Types []ABIType `json:"types,omitempty"` 8 | Structs []StructDef `json:"structs,omitempty"` 9 | Actions []ActionDef `json:"actions,omitempty"` 10 | Tables []TableDef `json:"tables,omitempty"` 11 | RicardianClauses []ClausePair `json:"ricardian_clauses,omitempty"` 12 | ErrorMessages []ABIErrorMessage `json:"error_messages,omitempty"` 13 | Extensions []*Extension `json:"abi_extensions,omitempty"` 14 | } 15 | 16 | type ABIType struct { 17 | NewTypeName string `json:"new_type_name"` 18 | Type string `json:"type"` 19 | } 20 | 21 | type StructDef struct { 22 | Name string `json:"name"` 23 | Base string `json:"base"` 24 | Fields []FieldDef `json:"fields,omitempty"` 25 | } 26 | 27 | type FieldDef struct { 28 | Name string `json:"name"` 29 | Type string `json:"type"` 30 | } 31 | 32 | type ActionDef struct { 33 | Name ActionName `json:"name"` 34 | Type string `json:"type"` 35 | RicardianContract string `json:"ricardian_contract"` 36 | } 37 | 38 | // TableDef defines a table. See libraries/chain/include/eosio/chain/contracts/types.hpp:78 39 | type TableDef struct { 40 | Name TableName `json:"name"` 41 | IndexType string `json:"index_type"` 42 | KeyNames []string `json:"key_names,omitempty"` 43 | KeyTypes []string `json:"key_types,omitempty"` 44 | Type string `json:"type"` 45 | } 46 | 47 | // ClausePair represents clauses, related to Ricardian Contracts. 48 | type ClausePair struct { 49 | ID string `json:"id"` 50 | Body string `json:"body"` 51 | } 52 | 53 | type ABIErrorMessage struct { 54 | Code uint64 `json:"error_code"` 55 | Message string `json:"error_msg"` 56 | } 57 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/actions.go: -------------------------------------------------------------------------------- 1 | package eos 2 | 3 | import ( 4 | "bytes" 5 | "crypto/sha256" 6 | "encoding/json" 7 | "fmt" 8 | "reflect" 9 | ) 10 | 11 | // See: libraries/chain/include/eosio/chain/contracts/types.hpp:203 12 | // See: build/contracts/eosio.system/eosio.system.abi 13 | 14 | // SetCode represents the hard-coded `setcode` action. 15 | type SetCode struct { 16 | Account AccountName `json:"account"` 17 | VMType byte `json:"vmtype"` 18 | VMVersion byte `json:"vmversion"` 19 | Code HexBytes `json:"bytes"` 20 | } 21 | 22 | // SetABI represents the hard-coded `setabi` action. 23 | type SetABI struct { 24 | Account AccountName `json:"account"` 25 | ABI ABI `json:"abi"` 26 | } 27 | 28 | // Action 29 | type Action struct { 30 | Account AccountName `json:"account"` 31 | Name ActionName `json:"name"` 32 | Authorization []PermissionLevel `json:"authorization,omitempty"` 33 | ActionData 34 | } 35 | 36 | func (a Action) Digest() SHA256Bytes { 37 | toEat := jsonActionToServer{ 38 | Account: a.Account, 39 | Name: a.Name, 40 | Authorization: a.Authorization, 41 | Data: a.ActionData.HexData, 42 | } 43 | bin, err := MarshalBinary(toEat) 44 | if err != nil { 45 | panic("this should never panic, we know it marshals properly all the time") 46 | } 47 | 48 | h := sha256.New() 49 | _, _ = h.Write(bin) 50 | return h.Sum(nil) 51 | } 52 | 53 | type ActionData struct { 54 | HexData HexBytes `json:"hex_data,omitempty"` 55 | Data interface{} `json:"data,omitempty" eos:"-"` 56 | abi []byte // TBD: we could use the ABI to decode in obj 57 | toServer bool 58 | } 59 | 60 | func NewActionData(obj interface{}) ActionData { 61 | return ActionData{ 62 | HexData: []byte{}, 63 | Data: obj, 64 | toServer: true, 65 | } 66 | } 67 | func (a *ActionData) SetToServer(toServer bool) { 68 | // FIXME: let's clarify this design, make it simpler.. 69 | // toServer doesn't speak of the intent.. 70 | a.toServer = toServer 71 | } 72 | 73 | // jsonActionToServer represents what /v1/chain/push_transaction 74 | // expects, which isn't allllways the same everywhere. 75 | type jsonActionToServer struct { 76 | Account AccountName `json:"account"` 77 | Name ActionName `json:"name"` 78 | Authorization []PermissionLevel `json:"authorization,omitempty"` 79 | Data HexBytes `json:"data,omitempty"` 80 | } 81 | 82 | type jsonActionFromServer struct { 83 | Account AccountName `json:"account"` 84 | Name ActionName `json:"name"` 85 | Authorization []PermissionLevel `json:"authorization,omitempty"` 86 | Data interface{} `json:"data,omitempty"` 87 | HexData HexBytes `json:"hex_data,omitempty"` 88 | } 89 | 90 | func (a *Action) MarshalJSON() ([]byte, error) { 91 | println(fmt.Sprintf("MarshalJSON toServer? %t", a.toServer)) 92 | 93 | if a.toServer { 94 | buf := new(bytes.Buffer) 95 | encoder := NewEncoder(buf) 96 | 97 | println("MarshalJSON, encoding action data to binary") 98 | if err := encoder.Encode(a.ActionData.Data); err != nil { 99 | return nil, err 100 | } 101 | data := buf.Bytes() 102 | println("MarshalJSON data length : ", len(data)) /**/ 103 | 104 | return json.Marshal(&jsonActionToServer{ 105 | Account: a.Account, 106 | Name: a.Name, 107 | Authorization: a.Authorization, 108 | Data: data, 109 | }) 110 | } 111 | 112 | return json.Marshal(&jsonActionFromServer{ 113 | Account: a.Account, 114 | Name: a.Name, 115 | Authorization: a.Authorization, 116 | HexData: a.HexData, 117 | Data: a.Data, 118 | }) 119 | } 120 | 121 | func (a *Action) MapToRegisteredAction() error { 122 | src, ok := a.ActionData.Data.(map[string]interface{}) 123 | if !ok { 124 | return nil 125 | } 126 | 127 | actionMap := RegisteredActions[a.Account] 128 | 129 | var decodeInto reflect.Type 130 | if actionMap != nil { 131 | objType := actionMap[a.Name] 132 | if objType != nil { 133 | decodeInto = objType 134 | } 135 | } 136 | if decodeInto == nil { 137 | return nil 138 | } 139 | 140 | obj := reflect.New(decodeInto) 141 | objIface := obj.Interface() 142 | 143 | cnt, err := json.Marshal(src) 144 | if err != nil { 145 | return fmt.Errorf("marshaling data: %s", err) 146 | } 147 | err = json.Unmarshal(cnt, objIface) 148 | if err != nil { 149 | return fmt.Errorf("json unmarshal into registered actions: %s", err) 150 | } 151 | 152 | a.ActionData.Data = objIface 153 | 154 | return nil 155 | } 156 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/api.go: -------------------------------------------------------------------------------- 1 | package eos 2 | 3 | import ( 4 | "bytes" 5 | "encoding/hex" 6 | "encoding/json" 7 | "errors" 8 | "fmt" 9 | "io" 10 | "log" 11 | "net" 12 | "net/http" 13 | "net/http/httputil" 14 | "sync" 15 | "time" 16 | 17 | "github.com/eoscanada/eos-go/ecc" 18 | ) 19 | 20 | type API struct { 21 | HttpClient *http.Client 22 | BaseURL string 23 | Signer Signer 24 | Debug bool 25 | Compress CompressionType 26 | DefaultMaxCPUUsageMS uint8 27 | DefaultMaxNetUsageWords uint32 // in 8-bytes words 28 | 29 | lastGetInfo *InfoResp 30 | lastGetInfoStamp time.Time 31 | lastGetInfoLock sync.Mutex 32 | 33 | customGetRequiredKeys func(tx *Transaction) ([]ecc.PublicKey, error) 34 | } 35 | 36 | func New(baseURL string) *API { 37 | api := &API{ 38 | HttpClient: &http.Client{ 39 | Transport: &http.Transport{ 40 | Proxy: http.ProxyFromEnvironment, 41 | DialContext: (&net.Dialer{ 42 | Timeout: 30 * time.Second, 43 | KeepAlive: 30 * time.Second, 44 | DualStack: true, 45 | }).DialContext, 46 | MaxIdleConns: 100, 47 | IdleConnTimeout: 90 * time.Second, 48 | TLSHandshakeTimeout: 10 * time.Second, 49 | ExpectContinueTimeout: 1 * time.Second, 50 | DisableKeepAlives: true, // default behavior, because of `nodeos`'s lack of support for Keep alives. 51 | }, 52 | }, 53 | BaseURL: baseURL, 54 | Compress: CompressionZlib, 55 | } 56 | 57 | return api 58 | } 59 | 60 | // FixKeepAlives tests the remote server for keepalive support (the 61 | // main `nodeos` software doesn't in the version from March 22nd 62 | // 2018). Some endpoints front their node with a keep-alive 63 | // supporting web server. Adjust the `KeepAlive` support of the 64 | // client accordingly. 65 | func (api *API) FixKeepAlives() bool { 66 | // Yeah, to provoke a keep alive, you need to query twice. 67 | for i := 0; i < 5; i++ { 68 | _, err := api.GetInfo() 69 | if api.Debug { 70 | log.Println("err", err) 71 | } 72 | if err == io.EOF { 73 | if tr, ok := api.HttpClient.Transport.(*http.Transport); ok { 74 | tr.DisableKeepAlives = true 75 | return true 76 | } 77 | } 78 | _, err = api.GetNetConnections() 79 | if api.Debug { 80 | log.Println("err", err) 81 | } 82 | if err == io.EOF { 83 | if tr, ok := api.HttpClient.Transport.(*http.Transport); ok { 84 | tr.DisableKeepAlives = true 85 | return true 86 | } 87 | } 88 | } 89 | return false 90 | } 91 | 92 | func (api *API) EnableKeepAlives() bool { 93 | if tr, ok := api.HttpClient.Transport.(*http.Transport); ok { 94 | tr.DisableKeepAlives = false 95 | return true 96 | } 97 | return false 98 | } 99 | 100 | func (api *API) SetCustomGetRequiredKeys(f func(tx *Transaction) ([]ecc.PublicKey, error)) { 101 | api.customGetRequiredKeys = f 102 | } 103 | 104 | func (api *API) SetSigner(s Signer) { 105 | api.Signer = s 106 | } 107 | 108 | // ProducerPause will pause block production on a nodeos with 109 | // `producer_api` plugin loaded. 110 | func (api *API) ProducerPause() error { 111 | return api.call("producer", "pause", nil, nil) 112 | } 113 | 114 | // ProducerResume will resume block production on a nodeos with 115 | // `producer_api` plugin loaded. Obviously, this needs to be a 116 | // producing node on the producers schedule for it to do anything. 117 | func (api *API) ProducerResume() error { 118 | return api.call("producer", "resume", nil, nil) 119 | } 120 | 121 | // IsProducerPaused queries the blockchain for the pause statement of 122 | // block production. 123 | func (api *API) IsProducerPaused() (out bool, err error) { 124 | err = api.call("producer", "paused", nil, &out) 125 | return 126 | } 127 | 128 | func (api *API) GetAccount(name AccountName) (out *AccountResp, err error) { 129 | err = api.call("chain", "get_account", M{"account_name": name}, &out) 130 | return 131 | } 132 | 133 | func (api *API) GetCode(account AccountName) (out *GetCodeResp, err error) { 134 | err = api.call("chain", "get_code", M{"account_name": account, "code_as_wasm": true}, &out) 135 | return 136 | } 137 | 138 | func (api *API) GetABI(account AccountName) (out *GetABIResp, err error) { 139 | err = api.call("chain", "get_abi", M{"account_name": account}, &out) 140 | return 141 | } 142 | 143 | // WalletImportKey loads a new WIF-encoded key into the wallet. 144 | func (api *API) WalletImportKey(walletName, wifPrivKey string) (err error) { 145 | return api.call("wallet", "import_key", []string{walletName, wifPrivKey}, nil) 146 | } 147 | 148 | func (api *API) WalletPublicKeys() (out []ecc.PublicKey, err error) { 149 | var textKeys []string 150 | err = api.call("wallet", "get_public_keys", nil, &textKeys) 151 | if err != nil { 152 | return nil, err 153 | } 154 | 155 | for _, k := range textKeys { 156 | newKey, err := ecc.NewPublicKey(k) 157 | if err != nil { 158 | return nil, err 159 | } 160 | 161 | out = append(out, newKey) 162 | } 163 | return 164 | } 165 | 166 | func (api *API) ListKeys() (out []*ecc.PrivateKey, err error) { 167 | var textKeys []string 168 | err = api.call("wallet", "list_keys", nil, &textKeys) 169 | if err != nil { 170 | return nil, err 171 | } 172 | 173 | for _, k := range textKeys { 174 | newKey, err := ecc.NewPrivateKey(k) 175 | if err != nil { 176 | return nil, err 177 | } 178 | 179 | out = append(out, newKey) 180 | } 181 | return 182 | } 183 | 184 | func (api *API) WalletSignTransaction(tx *SignedTransaction, chainID []byte, pubKeys ...ecc.PublicKey) (out *WalletSignTransactionResp, err error) { 185 | var textKeys []string 186 | for _, key := range pubKeys { 187 | textKeys = append(textKeys, key.String()) 188 | } 189 | 190 | err = api.call("wallet", "sign_transaction", []interface{}{ 191 | tx, 192 | textKeys, 193 | hex.EncodeToString(chainID), 194 | }, &out) 195 | return 196 | } 197 | 198 | // SignPushActions will create a transaction, fill it with default 199 | // values, sign it and submit it to the chain. It is the highest 200 | // level function on top of the `/v1/chain/push_transaction` endpoint. 201 | func (api *API) SignPushActions(a ...*Action) (out *PushTransactionFullResp, err error) { 202 | return api.SignPushActionsWithOpts(a, nil) 203 | } 204 | 205 | func (api *API) SignPushActionsWithOpts(actions []*Action, opts *TxOptions) (out *PushTransactionFullResp, err error) { 206 | if opts == nil { 207 | opts = &TxOptions{} 208 | } 209 | 210 | if err := opts.FillFromChain(api); err != nil { 211 | return nil, err 212 | } 213 | 214 | tx := NewTransaction(actions, opts) 215 | 216 | return api.SignPushTransaction(tx, opts.ChainID, opts.Compress) 217 | } 218 | 219 | // SignPushTransaction will sign a transaction and submit it to the 220 | // chain. 221 | func (api *API) SignPushTransaction(tx *Transaction, chainID SHA256Bytes, compression CompressionType) (out *PushTransactionFullResp, err error) { 222 | _, packed, err := api.SignTransaction(tx, chainID, compression) 223 | if err != nil { 224 | return nil, err 225 | } 226 | 227 | return api.PushTransaction(packed) 228 | } 229 | 230 | // SignTransaction will sign and pack a transaction, but not submit to 231 | // the chain. It lives on the `api` object because it might query the 232 | // blockchain to learn which keys are required to sign this particular 233 | // transaction. 234 | // 235 | // You can override the way we request keys (which defaults to 236 | // `api.GetRequiredKeys()`) with SetCustomGetRequiredKeys(). 237 | // 238 | // To sign a transaction, you need a Signer defined on the `API` 239 | // object. See SetSigner. 240 | func (api *API) SignTransaction(tx *Transaction, chainID SHA256Bytes, compression CompressionType) (*SignedTransaction, *PackedTransaction, error) { 241 | if api.Signer == nil { 242 | return nil, nil, fmt.Errorf("no Signer configured") 243 | } 244 | 245 | stx := NewSignedTransaction(tx) 246 | 247 | var requiredKeys []ecc.PublicKey 248 | if api.customGetRequiredKeys != nil { 249 | var err error 250 | requiredKeys, err = api.customGetRequiredKeys(tx) 251 | if err != nil { 252 | return nil, nil, fmt.Errorf("custom_get_required_keys: %s", err) 253 | } 254 | } else { 255 | resp, err := api.GetRequiredKeys(tx) 256 | if err != nil { 257 | return nil, nil, fmt.Errorf("get_required_keys: %s", err) 258 | } 259 | requiredKeys = resp.RequiredKeys 260 | } 261 | 262 | signedTx, err := api.Signer.Sign(stx, chainID, requiredKeys...) 263 | if err != nil { 264 | return nil, nil, fmt.Errorf("signing through wallet: %s", err) 265 | } 266 | 267 | packed, err := signedTx.Pack(compression) 268 | if err != nil { 269 | return nil, nil, err 270 | } 271 | 272 | return signedTx, packed, nil 273 | } 274 | 275 | // PushTransaction submits a properly filled (tapos), packed and 276 | // signed transaction to the blockchain. 277 | func (api *API) PushTransaction(tx *PackedTransaction) (out *PushTransactionFullResp, err error) { 278 | err = api.call("chain", "push_transaction", tx, &out) 279 | return 280 | } 281 | 282 | func (api *API) GetInfo() (out *InfoResp, err error) { 283 | err = api.call("chain", "get_info", nil, &out) 284 | return 285 | } 286 | 287 | func (api *API) cachedGetInfo() (*InfoResp, error) { 288 | api.lastGetInfoLock.Lock() 289 | defer api.lastGetInfoLock.Unlock() 290 | 291 | var info *InfoResp 292 | var err error 293 | 294 | if !api.lastGetInfoStamp.IsZero() && time.Now().Add(-1*time.Second).Before(api.lastGetInfoStamp) { 295 | info = api.lastGetInfo 296 | } else { 297 | info, err = api.GetInfo() 298 | if err != nil { 299 | return nil, err 300 | } 301 | api.lastGetInfoStamp = time.Now() 302 | api.lastGetInfo = info 303 | } 304 | if err != nil { 305 | return nil, err 306 | } 307 | 308 | return api.lastGetInfo, nil 309 | } 310 | 311 | func (api *API) GetNetConnections() (out []*NetConnectionsResp, err error) { 312 | err = api.call("net", "connections", nil, &out) 313 | return 314 | } 315 | 316 | func (api *API) NetConnect(host string) (out NetConnectResp, err error) { 317 | err = api.call("net", "connect", host, &out) 318 | return 319 | } 320 | 321 | func (api *API) NetDisconnect(host string) (out NetDisconnectResp, err error) { 322 | err = api.call("net", "disconnect", host, &out) 323 | return 324 | } 325 | 326 | func (api *API) GetNetStatus(host string) (out *NetStatusResp, err error) { 327 | err = api.call("net", "status", M{"host": host}, &out) 328 | return 329 | } 330 | 331 | func (api *API) GetBlockByID(id string) (out *BlockResp, err error) { 332 | err = api.call("chain", "get_block", M{"block_num_or_id": id}, &out) 333 | return 334 | } 335 | 336 | func (api *API) GetProducers() (out *ProducersResp, err error) { 337 | /* 338 | +FC_REFLECT( eosio::chain_apis::read_only::get_producers_params, (json)(lower_bound)(limit) ) 339 | +FC_REFLECT( eosio::chain_apis::read_only::get_producers_result, (rows)(total_producer_vote_weight)(more) ); */ 340 | err = api.call("chain", "get_producers", nil, &out) 341 | return 342 | } 343 | 344 | func (api *API) GetBlockByNum(num uint32) (out *BlockResp, err error) { 345 | err = api.call("chain", "get_block", M{"block_num_or_id": fmt.Sprintf("%d", num)}, &out) 346 | //err = api.call("chain", "get_block", M{"block_num_or_id": num}, &out) 347 | return 348 | } 349 | 350 | func (api *API) GetBlockByNumOrID(query string) (out *SignedBlock, err error) { 351 | err = api.call("chain", "get_block", M{"block_num_or_id": query}, &out) 352 | return 353 | } 354 | 355 | func (api *API) GetBlockByNumOrIDRaw(query string) (out interface{}, err error) { 356 | err = api.call("chain", "get_block", M{"block_num_or_id": query}, &out) 357 | return 358 | } 359 | 360 | func (api *API) GetTransaction(id string) (out *TransactionResp, err error) { 361 | err = api.call("history", "get_transaction", M{"id": id}, &out) 362 | return 363 | } 364 | 365 | func (api *API) GetTransactions(name AccountName) (out *TransactionsResp, err error) { 366 | err = api.call("account_history", "get_transactions", M{"account_name": name}, &out) 367 | return 368 | } 369 | 370 | func (api *API) GetTableRows(params GetTableRowsRequest) (out *GetTableRowsResp, err error) { 371 | err = api.call("chain", "get_table_rows", params, &out) 372 | return 373 | } 374 | 375 | func (api *API) GetRequiredKeys(tx *Transaction) (out *GetRequiredKeysResp, err error) { 376 | keys, err := api.Signer.AvailableKeys() 377 | if err != nil { 378 | return nil, err 379 | } 380 | 381 | err = api.call("chain", "get_required_keys", M{"transaction": tx, "available_keys": keys}, &out) 382 | return 383 | } 384 | 385 | func (api *API) GetCurrencyBalance(account AccountName, symbol string, code AccountName) (out []Asset, err error) { 386 | params := M{"account": account, "code": code} 387 | if symbol != "" { 388 | params["symbol"] = symbol 389 | } 390 | err = api.call("chain", "get_currency_balance", params, &out) 391 | return 392 | } 393 | 394 | // See more here: libraries/chain/contracts/abi_serializer.cpp:58... 395 | 396 | func (api *API) call(baseAPI string, endpoint string, body interface{}, out interface{}) error { 397 | jsonBody, err := enc(body) 398 | if err != nil { 399 | return err 400 | } 401 | 402 | targetURL := fmt.Sprintf("%s/v1/%s/%s", api.BaseURL, baseAPI, endpoint) 403 | req, err := http.NewRequest("POST", targetURL, jsonBody) 404 | if err != nil { 405 | return fmt.Errorf("NewRequest: %s", err) 406 | } 407 | 408 | if api.Debug { 409 | // Useful when debugging API calls 410 | requestDump, err := httputil.DumpRequest(req, true) 411 | if err != nil { 412 | fmt.Println(err) 413 | } 414 | fmt.Println("-------------------------------") 415 | fmt.Println(string(requestDump)) 416 | fmt.Println("") 417 | } 418 | 419 | resp, err := api.HttpClient.Do(req) 420 | if err != nil { 421 | return fmt.Errorf("%s: %s", req.URL.String(), err) 422 | } 423 | defer resp.Body.Close() 424 | 425 | var cnt bytes.Buffer 426 | _, err = io.Copy(&cnt, resp.Body) 427 | if err != nil { 428 | return fmt.Errorf("Copy: %s", err) 429 | } 430 | 431 | if resp.StatusCode == 404 { 432 | return ErrNotFound 433 | } 434 | if resp.StatusCode > 299 { 435 | return fmt.Errorf("%s: status code=%d, body=%s", req.URL.String(), resp.StatusCode, cnt.String()) 436 | } 437 | 438 | if api.Debug { 439 | fmt.Println("RESPONSE:") 440 | fmt.Println(cnt.String()) 441 | fmt.Println("") 442 | } 443 | 444 | if err := json.Unmarshal(cnt.Bytes(), &out); err != nil { 445 | return fmt.Errorf("Unmarshal: %s", err) 446 | } 447 | 448 | return nil 449 | } 450 | 451 | var ErrNotFound = errors.New("resource not found") 452 | 453 | type M map[string]interface{} 454 | 455 | func enc(v interface{}) (io.Reader, error) { 456 | if v == nil { 457 | return nil, nil 458 | } 459 | 460 | cnt, err := json.Marshal(v) 461 | if err != nil { 462 | return nil, err 463 | } 464 | 465 | //fmt.Println("BODY", string(cnt)) 466 | 467 | return bytes.NewReader(cnt), nil 468 | } 469 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/btcsuite/btcd/LICENSE: -------------------------------------------------------------------------------- 1 | ISC License 2 | 3 | Copyright (c) 2013-2017 The btcsuite developers 4 | Copyright (c) 2015-2016 The Decred developers 5 | 6 | Permission to use, copy, modify, and distribute this software for any 7 | purpose with or without fee is hereby granted, provided that the above 8 | copyright notice and this permission notice appear in all copies. 9 | 10 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 11 | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12 | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 13 | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 15 | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 16 | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 17 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/btcsuite/btcd/btcec/README.md: -------------------------------------------------------------------------------- 1 | btcec 2 | ===== 3 | 4 | [![Build Status](https://travis-ci.org/btcsuite/btcd.png?branch=master)](https://travis-ci.org/btcsuite/btcec) 5 | [![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) 6 | [![GoDoc](https://godoc.org/github.com/btcsuite/btcd/btcec?status.png)](http://godoc.org/github.com/btcsuite/btcd/btcec) 7 | 8 | Package btcec implements elliptic curve cryptography needed for working with 9 | Bitcoin (secp256k1 only for now). It is designed so that it may be used with the 10 | standard crypto/ecdsa packages provided with go. A comprehensive suite of test 11 | is provided to ensure proper functionality. Package btcec was originally based 12 | on work from ThePiachu which is licensed under the same terms as Go, but it has 13 | signficantly diverged since then. The btcsuite developers original is licensed 14 | under the liberal ISC license. 15 | 16 | Although this package was primarily written for btcd, it has intentionally been 17 | designed so it can be used as a standalone package for any projects needing to 18 | use secp256k1 elliptic curve cryptography. 19 | 20 | ## Installation and Updating 21 | 22 | ```bash 23 | $ go get -u github.com/btcsuite/btcd/btcec 24 | ``` 25 | 26 | ## Examples 27 | 28 | * [Sign Message](http://godoc.org/github.com/btcsuite/btcd/btcec#example-package--SignMessage) 29 | Demonstrates signing a message with a secp256k1 private key that is first 30 | parsed form raw bytes and serializing the generated signature. 31 | 32 | * [Verify Signature](http://godoc.org/github.com/btcsuite/btcd/btcec#example-package--VerifySignature) 33 | Demonstrates verifying a secp256k1 signature against a public key that is 34 | first parsed from raw bytes. The signature is also parsed from raw bytes. 35 | 36 | * [Encryption](http://godoc.org/github.com/btcsuite/btcd/btcec#example-package--EncryptMessage) 37 | Demonstrates encrypting a message for a public key that is first parsed from 38 | raw bytes, then decrypting it using the corresponding private key. 39 | 40 | * [Decryption](http://godoc.org/github.com/btcsuite/btcd/btcec#example-package--DecryptMessage) 41 | Demonstrates decrypting a message using a private key that is first parsed 42 | from raw bytes. 43 | 44 | ## GPG Verification Key 45 | 46 | All official release tags are signed by Conformal so users can ensure the code 47 | has not been tampered with and is coming from the btcsuite developers. To 48 | verify the signature perform the following: 49 | 50 | - Download the public key from the Conformal website at 51 | https://opensource.conformal.com/GIT-GPG-KEY-conformal.txt 52 | 53 | - Import the public key into your GPG keyring: 54 | ```bash 55 | gpg --import GIT-GPG-KEY-conformal.txt 56 | ``` 57 | 58 | - Verify the release tag with the following command where `TAG_NAME` is a 59 | placeholder for the specific tag: 60 | ```bash 61 | git tag -v TAG_NAME 62 | ``` 63 | 64 | ## License 65 | 66 | Package btcec is licensed under the [copyfree](http://copyfree.org) ISC License 67 | except for btcec.go and btcec_test.go which is under the same license as Go. 68 | 69 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/btcsuite/btcd/btcec/ciphering.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package btcec 6 | 7 | import ( 8 | "bytes" 9 | "crypto/aes" 10 | "crypto/cipher" 11 | "crypto/hmac" 12 | "crypto/rand" 13 | "crypto/sha256" 14 | "crypto/sha512" 15 | "errors" 16 | "io" 17 | ) 18 | 19 | var ( 20 | // ErrInvalidMAC occurs when Message Authentication Check (MAC) fails 21 | // during decryption. This happens because of either invalid private key or 22 | // corrupt ciphertext. 23 | ErrInvalidMAC = errors.New("invalid mac hash") 24 | 25 | // errInputTooShort occurs when the input ciphertext to the Decrypt 26 | // function is less than 134 bytes long. 27 | errInputTooShort = errors.New("ciphertext too short") 28 | 29 | // errUnsupportedCurve occurs when the first two bytes of the encrypted 30 | // text aren't 0x02CA (= 712 = secp256k1, from OpenSSL). 31 | errUnsupportedCurve = errors.New("unsupported curve") 32 | 33 | errInvalidXLength = errors.New("invalid X length, must be 32") 34 | errInvalidYLength = errors.New("invalid Y length, must be 32") 35 | errInvalidPadding = errors.New("invalid PKCS#7 padding") 36 | 37 | // 0x02CA = 714 38 | ciphCurveBytes = [2]byte{0x02, 0xCA} 39 | // 0x20 = 32 40 | ciphCoordLength = [2]byte{0x00, 0x20} 41 | ) 42 | 43 | // GenerateSharedSecret generates a shared secret based on a private key and a 44 | // public key using Diffie-Hellman key exchange (ECDH) (RFC 4753). 45 | // RFC5903 Section 9 states we should only return x. 46 | func GenerateSharedSecret(privkey *PrivateKey, pubkey *PublicKey) []byte { 47 | x, _ := pubkey.Curve.ScalarMult(pubkey.X, pubkey.Y, privkey.D.Bytes()) 48 | return x.Bytes() 49 | } 50 | 51 | // Encrypt encrypts data for the target public key using AES-256-CBC. It also 52 | // generates a private key (the pubkey of which is also in the output). The only 53 | // supported curve is secp256k1. The `structure' that it encodes everything into 54 | // is: 55 | // 56 | // struct { 57 | // // Initialization Vector used for AES-256-CBC 58 | // IV [16]byte 59 | // // Public Key: curve(2) + len_of_pubkeyX(2) + pubkeyX + 60 | // // len_of_pubkeyY(2) + pubkeyY (curve = 714) 61 | // PublicKey [70]byte 62 | // // Cipher text 63 | // Data []byte 64 | // // HMAC-SHA-256 Message Authentication Code 65 | // HMAC [32]byte 66 | // } 67 | // 68 | // The primary aim is to ensure byte compatibility with Pyelliptic. Also, refer 69 | // to section 5.8.1 of ANSI X9.63 for rationale on this format. 70 | func Encrypt(pubkey *PublicKey, in []byte) ([]byte, error) { 71 | ephemeral, err := NewPrivateKey(S256()) 72 | if err != nil { 73 | return nil, err 74 | } 75 | ecdhKey := GenerateSharedSecret(ephemeral, pubkey) 76 | derivedKey := sha512.Sum512(ecdhKey) 77 | keyE := derivedKey[:32] 78 | keyM := derivedKey[32:] 79 | 80 | paddedIn := addPKCSPadding(in) 81 | // IV + Curve params/X/Y + padded plaintext/ciphertext + HMAC-256 82 | out := make([]byte, aes.BlockSize+70+len(paddedIn)+sha256.Size) 83 | iv := out[:aes.BlockSize] 84 | if _, err = io.ReadFull(rand.Reader, iv); err != nil { 85 | return nil, err 86 | } 87 | // start writing public key 88 | pb := ephemeral.PubKey().SerializeUncompressed() 89 | offset := aes.BlockSize 90 | 91 | // curve and X length 92 | copy(out[offset:offset+4], append(ciphCurveBytes[:], ciphCoordLength[:]...)) 93 | offset += 4 94 | // X 95 | copy(out[offset:offset+32], pb[1:33]) 96 | offset += 32 97 | // Y length 98 | copy(out[offset:offset+2], ciphCoordLength[:]) 99 | offset += 2 100 | // Y 101 | copy(out[offset:offset+32], pb[33:]) 102 | offset += 32 103 | 104 | // start encryption 105 | block, err := aes.NewCipher(keyE) 106 | if err != nil { 107 | return nil, err 108 | } 109 | mode := cipher.NewCBCEncrypter(block, iv) 110 | mode.CryptBlocks(out[offset:len(out)-sha256.Size], paddedIn) 111 | 112 | // start HMAC-SHA-256 113 | hm := hmac.New(sha256.New, keyM) 114 | hm.Write(out[:len(out)-sha256.Size]) // everything is hashed 115 | copy(out[len(out)-sha256.Size:], hm.Sum(nil)) // write checksum 116 | 117 | return out, nil 118 | } 119 | 120 | // Decrypt decrypts data that was encrypted using the Encrypt function. 121 | func Decrypt(priv *PrivateKey, in []byte) ([]byte, error) { 122 | // IV + Curve params/X/Y + 1 block + HMAC-256 123 | if len(in) < aes.BlockSize+70+aes.BlockSize+sha256.Size { 124 | return nil, errInputTooShort 125 | } 126 | 127 | // read iv 128 | iv := in[:aes.BlockSize] 129 | offset := aes.BlockSize 130 | 131 | // start reading pubkey 132 | if !bytes.Equal(in[offset:offset+2], ciphCurveBytes[:]) { 133 | return nil, errUnsupportedCurve 134 | } 135 | offset += 2 136 | 137 | if !bytes.Equal(in[offset:offset+2], ciphCoordLength[:]) { 138 | return nil, errInvalidXLength 139 | } 140 | offset += 2 141 | 142 | xBytes := in[offset : offset+32] 143 | offset += 32 144 | 145 | if !bytes.Equal(in[offset:offset+2], ciphCoordLength[:]) { 146 | return nil, errInvalidYLength 147 | } 148 | offset += 2 149 | 150 | yBytes := in[offset : offset+32] 151 | offset += 32 152 | 153 | pb := make([]byte, 65) 154 | pb[0] = byte(0x04) // uncompressed 155 | copy(pb[1:33], xBytes) 156 | copy(pb[33:], yBytes) 157 | // check if (X, Y) lies on the curve and create a Pubkey if it does 158 | pubkey, err := ParsePubKey(pb, S256()) 159 | if err != nil { 160 | return nil, err 161 | } 162 | 163 | // check for cipher text length 164 | if (len(in)-aes.BlockSize-offset-sha256.Size)%aes.BlockSize != 0 { 165 | return nil, errInvalidPadding // not padded to 16 bytes 166 | } 167 | 168 | // read hmac 169 | messageMAC := in[len(in)-sha256.Size:] 170 | 171 | // generate shared secret 172 | ecdhKey := GenerateSharedSecret(priv, pubkey) 173 | derivedKey := sha512.Sum512(ecdhKey) 174 | keyE := derivedKey[:32] 175 | keyM := derivedKey[32:] 176 | 177 | // verify mac 178 | hm := hmac.New(sha256.New, keyM) 179 | hm.Write(in[:len(in)-sha256.Size]) // everything is hashed 180 | expectedMAC := hm.Sum(nil) 181 | if !hmac.Equal(messageMAC, expectedMAC) { 182 | return nil, ErrInvalidMAC 183 | } 184 | 185 | // start decryption 186 | block, err := aes.NewCipher(keyE) 187 | if err != nil { 188 | return nil, err 189 | } 190 | mode := cipher.NewCBCDecrypter(block, iv) 191 | // same length as ciphertext 192 | plaintext := make([]byte, len(in)-offset-sha256.Size) 193 | mode.CryptBlocks(plaintext, in[offset:len(in)-sha256.Size]) 194 | 195 | return removePKCSPadding(plaintext) 196 | } 197 | 198 | // Implement PKCS#7 padding with block size of 16 (AES block size). 199 | 200 | // addPKCSPadding adds padding to a block of data 201 | func addPKCSPadding(src []byte) []byte { 202 | padding := aes.BlockSize - len(src)%aes.BlockSize 203 | padtext := bytes.Repeat([]byte{byte(padding)}, padding) 204 | return append(src, padtext...) 205 | } 206 | 207 | // removePKCSPadding removes padding from data that was added with addPKCSPadding 208 | func removePKCSPadding(src []byte) ([]byte, error) { 209 | length := len(src) 210 | padLength := int(src[length-1]) 211 | if padLength > aes.BlockSize || length < aes.BlockSize { 212 | return nil, errInvalidPadding 213 | } 214 | 215 | return src[:length-padLength], nil 216 | } 217 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/btcsuite/btcd/btcec/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2014 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | Package btcec implements support for the elliptic curves needed for bitcoin. 7 | 8 | Bitcoin uses elliptic curve cryptography using koblitz curves 9 | (specifically secp256k1) for cryptographic functions. See 10 | http://www.secg.org/collateral/sec2_final.pdf for details on the 11 | standard. 12 | 13 | This package provides the data structures and functions implementing the 14 | crypto/elliptic Curve interface in order to permit using these curves 15 | with the standard crypto/ecdsa package provided with go. Helper 16 | functionality is provided to parse signatures and public keys from 17 | standard formats. It was designed for use with btcd, but should be 18 | general enough for other uses of elliptic curve crypto. It was originally based 19 | on some initial work by ThePiachu, but has significantly diverged since then. 20 | */ 21 | package btcec 22 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/btcsuite/btcd/btcec/gensecp256k1.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014-2015 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | // This file is ignored during the regular build due to the following build tag. 6 | // This build tag is set during go generate. 7 | // +build gensecp256k1 8 | 9 | package btcec 10 | 11 | // References: 12 | // [GECC]: Guide to Elliptic Curve Cryptography (Hankerson, Menezes, Vanstone) 13 | 14 | import ( 15 | "encoding/binary" 16 | "math/big" 17 | ) 18 | 19 | // secp256k1BytePoints are dummy points used so the code which generates the 20 | // real values can compile. 21 | var secp256k1BytePoints = "" 22 | 23 | // getDoublingPoints returns all the possible G^(2^i) for i in 24 | // 0..n-1 where n is the curve's bit size (256 in the case of secp256k1) 25 | // the coordinates are recorded as Jacobian coordinates. 26 | func (curve *KoblitzCurve) getDoublingPoints() [][3]fieldVal { 27 | doublingPoints := make([][3]fieldVal, curve.BitSize) 28 | 29 | // initialize px, py, pz to the Jacobian coordinates for the base point 30 | px, py := curve.bigAffineToField(curve.Gx, curve.Gy) 31 | pz := new(fieldVal).SetInt(1) 32 | for i := 0; i < curve.BitSize; i++ { 33 | doublingPoints[i] = [3]fieldVal{*px, *py, *pz} 34 | // P = 2*P 35 | curve.doubleJacobian(px, py, pz, px, py, pz) 36 | } 37 | return doublingPoints 38 | } 39 | 40 | // SerializedBytePoints returns a serialized byte slice which contains all of 41 | // the possible points per 8-bit window. This is used to when generating 42 | // secp256k1.go. 43 | func (curve *KoblitzCurve) SerializedBytePoints() []byte { 44 | doublingPoints := curve.getDoublingPoints() 45 | 46 | // Segregate the bits into byte-sized windows 47 | serialized := make([]byte, curve.byteSize*256*3*10*4) 48 | offset := 0 49 | for byteNum := 0; byteNum < curve.byteSize; byteNum++ { 50 | // Grab the 8 bits that make up this byte from doublingPoints. 51 | startingBit := 8 * (curve.byteSize - byteNum - 1) 52 | computingPoints := doublingPoints[startingBit : startingBit+8] 53 | 54 | // Compute all points in this window and serialize them. 55 | for i := 0; i < 256; i++ { 56 | px, py, pz := new(fieldVal), new(fieldVal), new(fieldVal) 57 | for j := 0; j < 8; j++ { 58 | if i>>uint(j)&1 == 1 { 59 | curve.addJacobian(px, py, pz, &computingPoints[j][0], 60 | &computingPoints[j][1], &computingPoints[j][2], px, py, pz) 61 | } 62 | } 63 | for i := 0; i < 10; i++ { 64 | binary.LittleEndian.PutUint32(serialized[offset:], px.n[i]) 65 | offset += 4 66 | } 67 | for i := 0; i < 10; i++ { 68 | binary.LittleEndian.PutUint32(serialized[offset:], py.n[i]) 69 | offset += 4 70 | } 71 | for i := 0; i < 10; i++ { 72 | binary.LittleEndian.PutUint32(serialized[offset:], pz.n[i]) 73 | offset += 4 74 | } 75 | } 76 | } 77 | 78 | return serialized 79 | } 80 | 81 | // sqrt returns the square root of the provided big integer using Newton's 82 | // method. It's only compiled and used during generation of pre-computed 83 | // values, so speed is not a huge concern. 84 | func sqrt(n *big.Int) *big.Int { 85 | // Initial guess = 2^(log_2(n)/2) 86 | guess := big.NewInt(2) 87 | guess.Exp(guess, big.NewInt(int64(n.BitLen()/2)), nil) 88 | 89 | // Now refine using Newton's method. 90 | big2 := big.NewInt(2) 91 | prevGuess := big.NewInt(0) 92 | for { 93 | prevGuess.Set(guess) 94 | guess.Add(guess, new(big.Int).Div(n, guess)) 95 | guess.Div(guess, big2) 96 | if guess.Cmp(prevGuess) == 0 { 97 | break 98 | } 99 | } 100 | return guess 101 | } 102 | 103 | // EndomorphismVectors runs the first 3 steps of algorithm 3.74 from [GECC] to 104 | // generate the linearly independent vectors needed to generate a balanced 105 | // length-two representation of a multiplier such that k = k1 + k2λ (mod N) and 106 | // returns them. Since the values will always be the same given the fact that N 107 | // and λ are fixed, the final results can be accelerated by storing the 108 | // precomputed values with the curve. 109 | func (curve *KoblitzCurve) EndomorphismVectors() (a1, b1, a2, b2 *big.Int) { 110 | bigMinus1 := big.NewInt(-1) 111 | 112 | // This section uses an extended Euclidean algorithm to generate a 113 | // sequence of equations: 114 | // s[i] * N + t[i] * λ = r[i] 115 | 116 | nSqrt := sqrt(curve.N) 117 | u, v := new(big.Int).Set(curve.N), new(big.Int).Set(curve.lambda) 118 | x1, y1 := big.NewInt(1), big.NewInt(0) 119 | x2, y2 := big.NewInt(0), big.NewInt(1) 120 | q, r := new(big.Int), new(big.Int) 121 | qu, qx1, qy1 := new(big.Int), new(big.Int), new(big.Int) 122 | s, t := new(big.Int), new(big.Int) 123 | ri, ti := new(big.Int), new(big.Int) 124 | a1, b1, a2, b2 = new(big.Int), new(big.Int), new(big.Int), new(big.Int) 125 | found, oneMore := false, false 126 | for u.Sign() != 0 { 127 | // q = v/u 128 | q.Div(v, u) 129 | 130 | // r = v - q*u 131 | qu.Mul(q, u) 132 | r.Sub(v, qu) 133 | 134 | // s = x2 - q*x1 135 | qx1.Mul(q, x1) 136 | s.Sub(x2, qx1) 137 | 138 | // t = y2 - q*y1 139 | qy1.Mul(q, y1) 140 | t.Sub(y2, qy1) 141 | 142 | // v = u, u = r, x2 = x1, x1 = s, y2 = y1, y1 = t 143 | v.Set(u) 144 | u.Set(r) 145 | x2.Set(x1) 146 | x1.Set(s) 147 | y2.Set(y1) 148 | y1.Set(t) 149 | 150 | // As soon as the remainder is less than the sqrt of n, the 151 | // values of a1 and b1 are known. 152 | if !found && r.Cmp(nSqrt) < 0 { 153 | // When this condition executes ri and ti represent the 154 | // r[i] and t[i] values such that i is the greatest 155 | // index for which r >= sqrt(n). Meanwhile, the current 156 | // r and t values are r[i+1] and t[i+1], respectively. 157 | 158 | // a1 = r[i+1], b1 = -t[i+1] 159 | a1.Set(r) 160 | b1.Mul(t, bigMinus1) 161 | found = true 162 | oneMore = true 163 | 164 | // Skip to the next iteration so ri and ti are not 165 | // modified. 166 | continue 167 | 168 | } else if oneMore { 169 | // When this condition executes ri and ti still 170 | // represent the r[i] and t[i] values while the current 171 | // r and t are r[i+2] and t[i+2], respectively. 172 | 173 | // sum1 = r[i]^2 + t[i]^2 174 | rSquared := new(big.Int).Mul(ri, ri) 175 | tSquared := new(big.Int).Mul(ti, ti) 176 | sum1 := new(big.Int).Add(rSquared, tSquared) 177 | 178 | // sum2 = r[i+2]^2 + t[i+2]^2 179 | r2Squared := new(big.Int).Mul(r, r) 180 | t2Squared := new(big.Int).Mul(t, t) 181 | sum2 := new(big.Int).Add(r2Squared, t2Squared) 182 | 183 | // if (r[i]^2 + t[i]^2) <= (r[i+2]^2 + t[i+2]^2) 184 | if sum1.Cmp(sum2) <= 0 { 185 | // a2 = r[i], b2 = -t[i] 186 | a2.Set(ri) 187 | b2.Mul(ti, bigMinus1) 188 | } else { 189 | // a2 = r[i+2], b2 = -t[i+2] 190 | a2.Set(r) 191 | b2.Mul(t, bigMinus1) 192 | } 193 | 194 | // All done. 195 | break 196 | } 197 | 198 | ri.Set(r) 199 | ti.Set(t) 200 | } 201 | 202 | return a1, b1, a2, b2 203 | } 204 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/btcsuite/btcd/btcec/precompute.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package btcec 6 | 7 | import ( 8 | "compress/zlib" 9 | "encoding/base64" 10 | "encoding/binary" 11 | "io/ioutil" 12 | "strings" 13 | ) 14 | 15 | //go:generate go run -tags gensecp256k1 genprecomps.go 16 | 17 | // loadS256BytePoints decompresses and deserializes the pre-computed byte points 18 | // used to accelerate scalar base multiplication for the secp256k1 curve. This 19 | // approach is used since it allows the compile to use significantly less ram 20 | // and be performed much faster than it is with hard-coding the final in-memory 21 | // data structure. At the same time, it is quite fast to generate the in-memory 22 | // data structure at init time with this approach versus computing the table. 23 | func loadS256BytePoints() error { 24 | // There will be no byte points to load when generating them. 25 | bp := secp256k1BytePoints 26 | if len(bp) == 0 { 27 | return nil 28 | } 29 | 30 | // Decompress the pre-computed table used to accelerate scalar base 31 | // multiplication. 32 | decoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(bp)) 33 | r, err := zlib.NewReader(decoder) 34 | if err != nil { 35 | return err 36 | } 37 | serialized, err := ioutil.ReadAll(r) 38 | if err != nil { 39 | return err 40 | } 41 | 42 | // Deserialize the precomputed byte points and set the curve to them. 43 | offset := 0 44 | var bytePoints [32][256][3]fieldVal 45 | for byteNum := 0; byteNum < 32; byteNum++ { 46 | // All points in this window. 47 | for i := 0; i < 256; i++ { 48 | px := &bytePoints[byteNum][i][0] 49 | py := &bytePoints[byteNum][i][1] 50 | pz := &bytePoints[byteNum][i][2] 51 | for i := 0; i < 10; i++ { 52 | px.n[i] = binary.LittleEndian.Uint32(serialized[offset:]) 53 | offset += 4 54 | } 55 | for i := 0; i < 10; i++ { 56 | py.n[i] = binary.LittleEndian.Uint32(serialized[offset:]) 57 | offset += 4 58 | } 59 | for i := 0; i < 10; i++ { 60 | pz.n[i] = binary.LittleEndian.Uint32(serialized[offset:]) 61 | offset += 4 62 | } 63 | } 64 | } 65 | secp256k1.bytePoints = &bytePoints 66 | return nil 67 | } 68 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/btcsuite/btcd/btcec/privkey.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package btcec 6 | 7 | import ( 8 | "crypto/ecdsa" 9 | "crypto/elliptic" 10 | "crypto/rand" 11 | "errors" 12 | "math/big" 13 | ) 14 | 15 | // PrivateKey wraps an ecdsa.PrivateKey as a convenience mainly for signing 16 | // things with the the private key without having to directly import the ecdsa 17 | // package. 18 | type PrivateKey ecdsa.PrivateKey 19 | 20 | // PrivKeyFromBytes returns a private and public key for `curve' based on the 21 | // private key passed as an argument as a byte slice. 22 | func PrivKeyFromBytes(curve elliptic.Curve, pk []byte) (*PrivateKey, 23 | *PublicKey) { 24 | x, y := curve.ScalarBaseMult(pk) 25 | 26 | priv := &ecdsa.PrivateKey{ 27 | PublicKey: ecdsa.PublicKey{ 28 | Curve: curve, 29 | X: x, 30 | Y: y, 31 | }, 32 | D: new(big.Int).SetBytes(pk), 33 | } 34 | 35 | return (*PrivateKey)(priv), (*PublicKey)(&priv.PublicKey) 36 | } 37 | 38 | // NewPrivateKey is a wrapper for ecdsa.GenerateKey that returns a PrivateKey 39 | // instead of the normal ecdsa.PrivateKey. 40 | func NewPrivateKey(curve elliptic.Curve) (*PrivateKey, error) { 41 | key, err := ecdsa.GenerateKey(curve, rand.Reader) 42 | if err != nil { 43 | return nil, err 44 | } 45 | return (*PrivateKey)(key), nil 46 | } 47 | 48 | // PubKey returns the PublicKey corresponding to this private key. 49 | func (p *PrivateKey) PubKey() *PublicKey { 50 | return (*PublicKey)(&p.PublicKey) 51 | } 52 | 53 | // ToECDSA returns the private key as a *ecdsa.PrivateKey. 54 | func (p *PrivateKey) ToECDSA() *ecdsa.PrivateKey { 55 | return (*ecdsa.PrivateKey)(p) 56 | } 57 | 58 | // Sign generates an ECDSA signature for the provided hash (which should be the result 59 | // of hashing a larger message) using the private key. Produced signature 60 | // is deterministic (same message and same key yield the same signature) and canonical 61 | // in accordance with RFC6979 and BIP0062. 62 | func (p *PrivateKey) Sign(hash []byte) (*Signature, error) { 63 | return signRFC6979(p, hash, 0) 64 | } 65 | 66 | // SignCanonical goes through signatures and returns only a canonical 67 | // representations. This matches the EOS blockchain expectations. 68 | func (p *PrivateKey) SignCanonical(curve *KoblitzCurve, hash []byte) ([]byte, error) { 69 | for i := 0; i < 25; i++ { 70 | sig, err := signRFC6979(p, hash, i) 71 | if err != nil { 72 | return nil, err 73 | } 74 | 75 | compactSig, err := makeCompact(curve, sig, p, hash, true) 76 | if err != nil { 77 | continue 78 | } 79 | 80 | if isCanonical(compactSig) { 81 | return compactSig, nil 82 | } 83 | } 84 | return nil, errors.New("couldn't find a canonical signature") 85 | } 86 | 87 | // PrivKeyBytesLen defines the length in bytes of a serialized private key. 88 | const PrivKeyBytesLen = 32 89 | 90 | // Serialize returns the private key number d as a big-endian binary-encoded 91 | // number, padded to a length of 32 bytes. 92 | func (p *PrivateKey) Serialize() []byte { 93 | b := make([]byte, 0, PrivKeyBytesLen) 94 | return paddedAppend(PrivKeyBytesLen, b, p.ToECDSA().D.Bytes()) 95 | } 96 | 97 | func isCanonical(compactSig []byte) bool { 98 | // From EOS's codebase, our way of doing Canonical sigs. 99 | // https://steemit.com/steem/@dantheman/steem-and-bitshares-cryptographic-security-update 100 | // 101 | // !(c.data[1] & 0x80) 102 | // && !(c.data[1] == 0 && !(c.data[2] & 0x80)) 103 | // && !(c.data[33] & 0x80) 104 | // && !(c.data[33] == 0 && !(c.data[34] & 0x80)); 105 | 106 | d := compactSig 107 | t1 := (d[1] & 0x80) == 0 108 | t2 := !(d[1] == 0 && ((d[2] & 0x80) == 0)) 109 | t3 := (d[33] & 0x80) == 0 110 | t4 := !(d[33] == 0 && ((d[34] & 0x80) == 0)) 111 | return t1 && t2 && t3 && t4 112 | } 113 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/btcsuite/btcd/btcec/pubkey.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2014 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package btcec 6 | 7 | import ( 8 | "crypto/ecdsa" 9 | "errors" 10 | "fmt" 11 | "math/big" 12 | ) 13 | 14 | // These constants define the lengths of serialized public keys. 15 | const ( 16 | PubKeyBytesLenCompressed = 33 17 | PubKeyBytesLenUncompressed = 65 18 | PubKeyBytesLenHybrid = 65 19 | ) 20 | 21 | func isOdd(a *big.Int) bool { 22 | return a.Bit(0) == 1 23 | } 24 | 25 | // decompressPoint decompresses a point on the given curve given the X point and 26 | // the solution to use. 27 | func decompressPoint(curve *KoblitzCurve, x *big.Int, ybit bool) (*big.Int, error) { 28 | // TODO: This will probably only work for secp256k1 due to 29 | // optimizations. 30 | 31 | // Y = +-sqrt(x^3 + B) 32 | x3 := new(big.Int).Mul(x, x) 33 | x3.Mul(x3, x) 34 | x3.Add(x3, curve.Params().B) 35 | 36 | // now calculate sqrt mod p of x2 + B 37 | // This code used to do a full sqrt based on tonelli/shanks, 38 | // but this was replaced by the algorithms referenced in 39 | // https://bitcointalk.org/index.php?topic=162805.msg1712294#msg1712294 40 | y := new(big.Int).Exp(x3, curve.QPlus1Div4(), curve.Params().P) 41 | 42 | if ybit != isOdd(y) { 43 | y.Sub(curve.Params().P, y) 44 | } 45 | if ybit != isOdd(y) { 46 | return nil, fmt.Errorf("ybit doesn't match oddness") 47 | } 48 | return y, nil 49 | } 50 | 51 | const ( 52 | pubkeyCompressed byte = 0x2 // y_bit + x coord 53 | pubkeyUncompressed byte = 0x4 // x coord + y coord 54 | pubkeyHybrid byte = 0x6 // y_bit + x coord + y coord 55 | ) 56 | 57 | // IsCompressedPubKey returns true the the passed serialized public key has 58 | // been encoded in compressed format, and false otherwise. 59 | func IsCompressedPubKey(pubKey []byte) bool { 60 | // The public key is only compressed if it is the correct length and 61 | // the format (first byte) is one of the compressed pubkey values. 62 | return len(pubKey) == PubKeyBytesLenCompressed && 63 | (pubKey[0]&^byte(0x1) == pubkeyCompressed) 64 | } 65 | 66 | // ParsePubKey parses a public key for a koblitz curve from a bytestring into a 67 | // ecdsa.Publickey, verifying that it is valid. It supports compressed, 68 | // uncompressed and hybrid signature formats. 69 | func ParsePubKey(pubKeyStr []byte, curve *KoblitzCurve) (key *PublicKey, err error) { 70 | pubkey := PublicKey{} 71 | pubkey.Curve = curve 72 | 73 | if len(pubKeyStr) == 0 { 74 | return nil, errors.New("pubkey string is empty") 75 | } 76 | 77 | format := pubKeyStr[0] 78 | ybit := (format & 0x1) == 0x1 79 | format &= ^byte(0x1) 80 | 81 | switch len(pubKeyStr) { 82 | case PubKeyBytesLenUncompressed: 83 | if format != pubkeyUncompressed && format != pubkeyHybrid { 84 | return nil, fmt.Errorf("invalid magic in pubkey str: "+ 85 | "%d", pubKeyStr[0]) 86 | } 87 | 88 | pubkey.X = new(big.Int).SetBytes(pubKeyStr[1:33]) 89 | pubkey.Y = new(big.Int).SetBytes(pubKeyStr[33:]) 90 | // hybrid keys have extra information, make use of it. 91 | if format == pubkeyHybrid && ybit != isOdd(pubkey.Y) { 92 | return nil, fmt.Errorf("ybit doesn't match oddness") 93 | } 94 | case PubKeyBytesLenCompressed: 95 | // format is 0x2 | solution, 96 | // solution determines which solution of the curve we use. 97 | /// y^2 = x^3 + Curve.B 98 | if format != pubkeyCompressed { 99 | return nil, fmt.Errorf("invalid magic in compressed "+ 100 | "pubkey string: %d", pubKeyStr[0]) 101 | } 102 | pubkey.X = new(big.Int).SetBytes(pubKeyStr[1:33]) 103 | pubkey.Y, err = decompressPoint(curve, pubkey.X, ybit) 104 | if err != nil { 105 | return nil, err 106 | } 107 | default: // wrong! 108 | return nil, fmt.Errorf("invalid pub key length %d", 109 | len(pubKeyStr)) 110 | } 111 | 112 | if pubkey.X.Cmp(pubkey.Curve.Params().P) >= 0 { 113 | return nil, fmt.Errorf("pubkey X parameter is >= to P") 114 | } 115 | if pubkey.Y.Cmp(pubkey.Curve.Params().P) >= 0 { 116 | return nil, fmt.Errorf("pubkey Y parameter is >= to P") 117 | } 118 | if !pubkey.Curve.IsOnCurve(pubkey.X, pubkey.Y) { 119 | return nil, fmt.Errorf("pubkey isn't on secp256k1 curve") 120 | } 121 | return &pubkey, nil 122 | } 123 | 124 | // PublicKey is an ecdsa.PublicKey with additional functions to 125 | // serialize in uncompressed, compressed, and hybrid formats. 126 | type PublicKey ecdsa.PublicKey 127 | 128 | // ToECDSA returns the public key as a *ecdsa.PublicKey. 129 | func (p *PublicKey) ToECDSA() *ecdsa.PublicKey { 130 | return (*ecdsa.PublicKey)(p) 131 | } 132 | 133 | // SerializeUncompressed serializes a public key in a 65-byte uncompressed 134 | // format. 135 | func (p *PublicKey) SerializeUncompressed() []byte { 136 | b := make([]byte, 0, PubKeyBytesLenUncompressed) 137 | b = append(b, pubkeyUncompressed) 138 | b = paddedAppend(32, b, p.X.Bytes()) 139 | return paddedAppend(32, b, p.Y.Bytes()) 140 | } 141 | 142 | // SerializeCompressed serializes a public key in a 33-byte compressed format. 143 | func (p *PublicKey) SerializeCompressed() []byte { 144 | b := make([]byte, 0, PubKeyBytesLenCompressed) 145 | format := pubkeyCompressed 146 | if isOdd(p.Y) { 147 | format |= 0x1 148 | } 149 | b = append(b, format) 150 | return paddedAppend(32, b, p.X.Bytes()) 151 | } 152 | 153 | // SerializeHybrid serializes a public key in a 65-byte hybrid format. 154 | func (p *PublicKey) SerializeHybrid() []byte { 155 | b := make([]byte, 0, PubKeyBytesLenHybrid) 156 | format := pubkeyHybrid 157 | if isOdd(p.Y) { 158 | format |= 0x1 159 | } 160 | b = append(b, format) 161 | b = paddedAppend(32, b, p.X.Bytes()) 162 | return paddedAppend(32, b, p.Y.Bytes()) 163 | } 164 | 165 | // IsEqual compares this PublicKey instance to the one passed, returning true if 166 | // both PublicKeys are equivalent. A PublicKey is equivalent to another, if they 167 | // both have the same X and Y coordinate. 168 | func (p *PublicKey) IsEqual(otherPubKey *PublicKey) bool { 169 | return p.X.Cmp(otherPubKey.X) == 0 && 170 | p.Y.Cmp(otherPubKey.Y) == 0 171 | } 172 | 173 | // paddedAppend appends the src byte slice to dst, returning the new slice. 174 | // If the length of the source is smaller than the passed size, leading zero 175 | // bytes are appended to the dst slice before appending src. 176 | func paddedAppend(size uint, dst, src []byte) []byte { 177 | for i := 0; i < int(size)-len(src); i++ { 178 | dst = append(dst, 0) 179 | } 180 | return append(dst, src...) 181 | } 182 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/btcsuite/btcutil/LICENSE: -------------------------------------------------------------------------------- 1 | ISC License 2 | 3 | Copyright (c) 2013-2016 The btcsuite developers 4 | 5 | Permission to use, copy, modify, and distribute this software for any 6 | purpose with or without fee is hereby granted, provided that the above 7 | copyright notice and this permission notice appear in all copies. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 10 | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 11 | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 12 | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 13 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 14 | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 15 | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 16 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/btcsuite/btcutil/README.md: -------------------------------------------------------------------------------- 1 | btcutil 2 | ======= 3 | 4 | [![Build Status](http://img.shields.io/travis/btcsuite/btcutil.svg)](https://travis-ci.org/btcsuite/btcutil) 5 | [![Coverage Status](http://img.shields.io/coveralls/btcsuite/btcutil.svg)](https://coveralls.io/r/btcsuite/btcutil?branch=master) 6 | [![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) 7 | [![GoDoc](http://img.shields.io/badge/godoc-reference-blue.svg)](http://godoc.org/github.com/btcsuite/btcutil) 8 | 9 | Package btcutil provides bitcoin-specific convenience functions and types. 10 | A comprehensive suite of tests is provided to ensure proper functionality. See 11 | `test_coverage.txt` for the gocov coverage report. Alternatively, if you are 12 | running a POSIX OS, you can run the `cov_report.sh` script for a real-time 13 | report. 14 | 15 | This package was developed for btcd, an alternative full-node implementation of 16 | bitcoin which is under active development by Conformal. Although it was 17 | primarily written for btcd, this package has intentionally been designed so it 18 | can be used as a standalone package for any projects needing the functionality 19 | provided. 20 | 21 | ## Installation and Updating 22 | 23 | ```bash 24 | $ go get -u github.com/btcsuite/btcutil 25 | ``` 26 | 27 | ## GPG Verification Key 28 | 29 | All official release tags are signed by Conformal so users can ensure the code 30 | has not been tampered with and is coming from the btcsuite developers. To 31 | verify the signature perform the following: 32 | 33 | - Download the public key from the Conformal website at 34 | https://opensource.conformal.com/GIT-GPG-KEY-conformal.txt 35 | 36 | - Import the public key into your GPG keyring: 37 | ```bash 38 | gpg --import GIT-GPG-KEY-conformal.txt 39 | ``` 40 | 41 | - Verify the release tag with the following command where `TAG_NAME` is a 42 | placeholder for the specific tag: 43 | ```bash 44 | git tag -v TAG_NAME 45 | ``` 46 | 47 | ## License 48 | 49 | Package btcutil is licensed under the [copyfree](http://copyfree.org) ISC 50 | License. 51 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/btcsuite/btcutil/base58/README.md: -------------------------------------------------------------------------------- 1 | base58 2 | ========== 3 | 4 | [![Build Status](http://img.shields.io/travis/btcsuite/btcutil.svg)](https://travis-ci.org/btcsuite/btcutil) 5 | [![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) 6 | [![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](http://godoc.org/github.com/btcsuite/btcutil/base58) 7 | 8 | Package base58 provides an API for encoding and decoding to and from the 9 | modified base58 encoding. It also provides an API to do Base58Check encoding, 10 | as described [here](https://en.bitcoin.it/wiki/Base58Check_encoding). 11 | 12 | A comprehensive suite of tests is provided to ensure proper functionality. 13 | 14 | ## Installation and Updating 15 | 16 | ```bash 17 | $ go get -u github.com/btcsuite/btcutil/base58 18 | ``` 19 | 20 | ## Examples 21 | 22 | * [Decode Example](http://godoc.org/github.com/btcsuite/btcutil/base58#example-Decode) 23 | Demonstrates how to decode modified base58 encoded data. 24 | * [Encode Example](http://godoc.org/github.com/btcsuite/btcutil/base58#example-Encode) 25 | Demonstrates how to encode data using the modified base58 encoding scheme. 26 | * [CheckDecode Example](http://godoc.org/github.com/btcsuite/btcutil/base58#example-CheckDecode) 27 | Demonstrates how to decode Base58Check encoded data. 28 | * [CheckEncode Example](http://godoc.org/github.com/btcsuite/btcutil/base58#example-CheckEncode) 29 | Demonstrates how to encode data using the Base58Check encoding scheme. 30 | 31 | ## License 32 | 33 | Package base58 is licensed under the [copyfree](http://copyfree.org) ISC 34 | License. 35 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/btcsuite/btcutil/base58/alphabet.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | // AUTOGENERATED by genalphabet.go; do not edit. 6 | 7 | package base58 8 | 9 | const ( 10 | // alphabet is the modified base58 alphabet used by Bitcoin. 11 | alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" 12 | 13 | alphabetIdx0 = '1' 14 | ) 15 | 16 | var b58 = [256]byte{ 17 | 255, 255, 255, 255, 255, 255, 255, 255, 18 | 255, 255, 255, 255, 255, 255, 255, 255, 19 | 255, 255, 255, 255, 255, 255, 255, 255, 20 | 255, 255, 255, 255, 255, 255, 255, 255, 21 | 255, 255, 255, 255, 255, 255, 255, 255, 22 | 255, 255, 255, 255, 255, 255, 255, 255, 23 | 255, 0, 1, 2, 3, 4, 5, 6, 24 | 7, 8, 255, 255, 255, 255, 255, 255, 25 | 255, 9, 10, 11, 12, 13, 14, 15, 26 | 16, 255, 17, 18, 19, 20, 21, 255, 27 | 22, 23, 24, 25, 26, 27, 28, 29, 28 | 30, 31, 32, 255, 255, 255, 255, 255, 29 | 255, 33, 34, 35, 36, 37, 38, 39, 30 | 40, 41, 42, 43, 255, 44, 45, 46, 31 | 47, 48, 49, 50, 51, 52, 53, 54, 32 | 55, 56, 57, 255, 255, 255, 255, 255, 33 | 255, 255, 255, 255, 255, 255, 255, 255, 34 | 255, 255, 255, 255, 255, 255, 255, 255, 35 | 255, 255, 255, 255, 255, 255, 255, 255, 36 | 255, 255, 255, 255, 255, 255, 255, 255, 37 | 255, 255, 255, 255, 255, 255, 255, 255, 38 | 255, 255, 255, 255, 255, 255, 255, 255, 39 | 255, 255, 255, 255, 255, 255, 255, 255, 40 | 255, 255, 255, 255, 255, 255, 255, 255, 41 | 255, 255, 255, 255, 255, 255, 255, 255, 42 | 255, 255, 255, 255, 255, 255, 255, 255, 43 | 255, 255, 255, 255, 255, 255, 255, 255, 44 | 255, 255, 255, 255, 255, 255, 255, 255, 45 | 255, 255, 255, 255, 255, 255, 255, 255, 46 | 255, 255, 255, 255, 255, 255, 255, 255, 47 | 255, 255, 255, 255, 255, 255, 255, 255, 48 | 255, 255, 255, 255, 255, 255, 255, 255, 49 | } 50 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/btcsuite/btcutil/base58/base58.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2015 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package base58 6 | 7 | import ( 8 | "math/big" 9 | ) 10 | 11 | //go:generate go run genalphabet.go 12 | 13 | var bigRadix = big.NewInt(58) 14 | var bigZero = big.NewInt(0) 15 | 16 | // Decode decodes a modified base58 string to a byte slice. 17 | func Decode(b string) []byte { 18 | answer := big.NewInt(0) 19 | j := big.NewInt(1) 20 | 21 | scratch := new(big.Int) 22 | for i := len(b) - 1; i >= 0; i-- { 23 | tmp := b58[b[i]] 24 | if tmp == 255 { 25 | return []byte("") 26 | } 27 | scratch.SetInt64(int64(tmp)) 28 | scratch.Mul(j, scratch) 29 | answer.Add(answer, scratch) 30 | j.Mul(j, bigRadix) 31 | } 32 | 33 | tmpval := answer.Bytes() 34 | 35 | var numZeros int 36 | for numZeros = 0; numZeros < len(b); numZeros++ { 37 | if b[numZeros] != alphabetIdx0 { 38 | break 39 | } 40 | } 41 | flen := numZeros + len(tmpval) 42 | val := make([]byte, flen, flen) 43 | copy(val[numZeros:], tmpval) 44 | 45 | return val 46 | } 47 | 48 | // Encode encodes a byte slice to a modified base58 string. 49 | func Encode(b []byte) string { 50 | x := new(big.Int) 51 | x.SetBytes(b) 52 | 53 | answer := make([]byte, 0, len(b)*136/100) 54 | for x.Cmp(bigZero) > 0 { 55 | mod := new(big.Int) 56 | x.DivMod(x, bigRadix, mod) 57 | answer = append(answer, alphabet[mod.Int64()]) 58 | } 59 | 60 | // leading zero bytes 61 | for _, i := range b { 62 | if i != 0 { 63 | break 64 | } 65 | answer = append(answer, alphabetIdx0) 66 | } 67 | 68 | // reverse 69 | alen := len(answer) 70 | for i := 0; i < alen/2; i++ { 71 | answer[i], answer[alen-1-i] = answer[alen-1-i], answer[i] 72 | } 73 | 74 | return string(answer) 75 | } 76 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/btcsuite/btcutil/base58/base58check.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2014 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package base58 6 | 7 | import ( 8 | "crypto/sha256" 9 | "errors" 10 | ) 11 | 12 | // ErrChecksum indicates that the checksum of a check-encoded string does not verify against 13 | // the checksum. 14 | var ErrChecksum = errors.New("checksum error") 15 | 16 | // ErrInvalidFormat indicates that the check-encoded string has an invalid format. 17 | var ErrInvalidFormat = errors.New("invalid format: version and/or checksum bytes missing") 18 | 19 | // checksum: first four bytes of sha256^2 20 | func checksum(input []byte) (cksum [4]byte) { 21 | h := sha256.Sum256(input) 22 | h2 := sha256.Sum256(h[:]) 23 | copy(cksum[:], h2[:4]) 24 | return 25 | } 26 | 27 | // CheckEncode prepends a version byte and appends a four byte checksum. 28 | func CheckEncode(input []byte, version byte) string { 29 | b := make([]byte, 0, 1+len(input)+4) 30 | b = append(b, version) 31 | b = append(b, input[:]...) 32 | cksum := checksum(b) 33 | b = append(b, cksum[:]...) 34 | return Encode(b) 35 | } 36 | 37 | // CheckDecode decodes a string that was encoded with CheckEncode and verifies the checksum. 38 | func CheckDecode(input string) (result []byte, version byte, err error) { 39 | decoded := Decode(input) 40 | if len(decoded) < 5 { 41 | return nil, 0, ErrInvalidFormat 42 | } 43 | version = decoded[0] 44 | var cksum [4]byte 45 | copy(cksum[:], decoded[len(decoded)-4:]) 46 | if checksum(decoded[:len(decoded)-4]) != cksum { 47 | return nil, 0, ErrChecksum 48 | } 49 | payload := decoded[1 : len(decoded)-4] 50 | result = append(result, payload...) 51 | return 52 | } 53 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/btcsuite/btcutil/base58/cov_report.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # This script uses gocov to generate a test coverage report. 4 | # The gocov tool my be obtained with the following command: 5 | # go get github.com/axw/gocov/gocov 6 | # 7 | # It will be installed to $GOPATH/bin, so ensure that location is in your $PATH. 8 | 9 | # Check for gocov. 10 | type gocov >/dev/null 2>&1 11 | if [ $? -ne 0 ]; then 12 | echo >&2 "This script requires the gocov tool." 13 | echo >&2 "You may obtain it with the following command:" 14 | echo >&2 "go get github.com/axw/gocov/gocov" 15 | exit 1 16 | fi 17 | gocov test | gocov report 18 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/btcsuite/btcutil/base58/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | Package base58 provides an API for working with modified base58 and Base58Check 7 | encodings. 8 | 9 | Modified Base58 Encoding 10 | 11 | Standard base58 encoding is similar to standard base64 encoding except, as the 12 | name implies, it uses a 58 character alphabet which results in an alphanumeric 13 | string and allows some characters which are problematic for humans to be 14 | excluded. Due to this, there can be various base58 alphabets. 15 | 16 | The modified base58 alphabet used by Bitcoin, and hence this package, omits the 17 | 0, O, I, and l characters that look the same in many fonts and are therefore 18 | hard to humans to distinguish. 19 | 20 | Base58Check Encoding Scheme 21 | 22 | The Base58Check encoding scheme is primarily used for Bitcoin addresses at the 23 | time of this writing, however it can be used to generically encode arbitrary 24 | byte arrays into human-readable strings along with a version byte that can be 25 | used to differentiate the same payload. For Bitcoin addresses, the extra 26 | version is used to differentiate the network of otherwise identical public keys 27 | which helps prevent using an address intended for one network on another. 28 | */ 29 | package base58 30 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/btcsuite/btcutil/base58/genalphabet.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | //+build ignore 6 | 7 | package main 8 | 9 | import ( 10 | "bytes" 11 | "io" 12 | "log" 13 | "os" 14 | "strconv" 15 | ) 16 | 17 | var ( 18 | start = []byte(`// Copyright (c) 2015 The btcsuite developers 19 | // Use of this source code is governed by an ISC 20 | // license that can be found in the LICENSE file. 21 | 22 | // AUTOGENERATED by genalphabet.go; do not edit. 23 | 24 | package base58 25 | 26 | const ( 27 | // alphabet is the modified base58 alphabet used by Bitcoin. 28 | alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" 29 | 30 | alphabetIdx0 = '1' 31 | ) 32 | 33 | var b58 = [256]byte{`) 34 | 35 | end = []byte(`}`) 36 | 37 | alphabet = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") 38 | tab = []byte("\t") 39 | invalid = []byte("255") 40 | comma = []byte(",") 41 | space = []byte(" ") 42 | nl = []byte("\n") 43 | ) 44 | 45 | func write(w io.Writer, b []byte) { 46 | _, err := w.Write(b) 47 | if err != nil { 48 | log.Fatal(err) 49 | } 50 | } 51 | 52 | func main() { 53 | fi, err := os.Create("alphabet.go") 54 | if err != nil { 55 | log.Fatal(err) 56 | } 57 | defer fi.Close() 58 | 59 | write(fi, start) 60 | write(fi, nl) 61 | for i := byte(0); i < 32; i++ { 62 | write(fi, tab) 63 | for j := byte(0); j < 8; j++ { 64 | idx := bytes.IndexByte(alphabet, i*8+j) 65 | if idx == -1 { 66 | write(fi, invalid) 67 | } else { 68 | write(fi, strconv.AppendInt(nil, int64(idx), 10)) 69 | } 70 | write(fi, comma) 71 | if j != 7 { 72 | write(fi, space) 73 | } 74 | } 75 | write(fi, nl) 76 | } 77 | write(fi, end) 78 | write(fi, nl) 79 | } 80 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/btcsuite/btcutil/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2014 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | Package btcutil provides bitcoin-specific convenience functions and types. 7 | 8 | Block Overview 9 | 10 | A Block defines a bitcoin block that provides easier and more efficient 11 | manipulation of raw wire protocol blocks. It also memoizes hashes for the 12 | block and its transactions on their first access so subsequent accesses don't 13 | have to repeat the relatively expensive hashing operations. 14 | 15 | Tx Overview 16 | 17 | A Tx defines a bitcoin transaction that provides more efficient manipulation of 18 | raw wire protocol transactions. It memoizes the hash for the transaction on its 19 | first access so subsequent accesses don't have to repeat the relatively 20 | expensive hashing operations. 21 | 22 | Address Overview 23 | 24 | The Address interface provides an abstraction for a Bitcoin address. While the 25 | most common type is a pay-to-pubkey-hash, Bitcoin already supports others and 26 | may well support more in the future. This package currently provides 27 | implementations for the pay-to-pubkey, pay-to-pubkey-hash, and 28 | pay-to-script-hash address types. 29 | 30 | To decode/encode an address: 31 | 32 | // NOTE: The default network is only used for address types which do not 33 | // already contain that information. At this time, that is only 34 | // pay-to-pubkey addresses. 35 | addrString := "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962" + 36 | "e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d57" + 37 | "8a4c702b6bf11d5f" 38 | defaultNet := &chaincfg.MainNetParams 39 | addr, err := btcutil.DecodeAddress(addrString, defaultNet) 40 | if err != nil { 41 | fmt.Println(err) 42 | return 43 | } 44 | fmt.Println(addr.EncodeAddress()) 45 | */ 46 | package btcutil 47 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/btcsuite/btcutil/doublehash.go: -------------------------------------------------------------------------------- 1 | package btcutil 2 | 3 | import "crypto/sha256" 4 | 5 | // DoubleHashB calculates hash(hash(b)) and returns the resulting bytes. 6 | func DoubleHashB(b []byte) []byte { 7 | first := sha256.Sum256(b) 8 | second := sha256.Sum256(first[:]) 9 | return second[:] 10 | } 11 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/btcsuite/btcutil/wif.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package btcutil 6 | 7 | import ( 8 | "bytes" 9 | "errors" 10 | 11 | "github.com/eoscanada/eos-go/btcsuite/btcd/btcec" 12 | "github.com/eoscanada/eos-go/btcsuite/btcutil/base58" 13 | ) 14 | 15 | // ErrMalformedPrivateKey describes an error where a WIF-encoded private 16 | // key cannot be decoded due to being improperly formatted. This may occur 17 | // if the byte length is incorrect or an unexpected magic number was 18 | // encountered. 19 | var ErrMalformedPrivateKey = errors.New("malformed private key") 20 | 21 | // ErrChecksumMismatch describes an error where decoding failed due to 22 | // a bad checksum. 23 | var ErrChecksumMismatch = errors.New("checksum mismatch") 24 | 25 | // compressMagic is the magic byte used to identify a WIF encoding for 26 | // an address created from a compressed serialized public key. 27 | const compressMagic byte = 0x01 28 | 29 | // WIF contains the individual components described by the Wallet Import Format 30 | // (WIF). A WIF string is typically used to represent a private key and its 31 | // associated address in a way that may be easily copied and imported into or 32 | // exported from wallet software. WIF strings may be decoded into this 33 | // structure by calling DecodeWIF or created with a user-provided private key 34 | // by calling NewWIF. 35 | type WIF struct { 36 | // PrivKey is the private key being imported or exported. 37 | PrivKey *btcec.PrivateKey 38 | 39 | // CompressPubKey specifies whether the address controlled by the 40 | // imported or exported private key was created by hashing a 41 | // compressed (33-byte) serialized public key, rather than an 42 | // uncompressed (65-byte) one. 43 | CompressPubKey bool 44 | 45 | // netID is the bitcoin network identifier byte used when 46 | // WIF encoding the private key. 47 | netID byte 48 | } 49 | 50 | // NewWIF creates a new WIF structure to export an address and its private key 51 | // as a string encoded in the Wallet Import Format. The compress argument 52 | // specifies whether the address intended to be imported or exported was created 53 | // by serializing the public key compressed rather than uncompressed. 54 | func NewWIF(privKey *btcec.PrivateKey, privateKeyID byte, compress bool) (*WIF, error) { 55 | return &WIF{privKey, compress, privateKeyID}, nil 56 | } 57 | 58 | // DecodeWIF creates a new WIF structure by decoding the string encoding of 59 | // the import format. 60 | // 61 | // The WIF string must be a base58-encoded string of the following byte 62 | // sequence: 63 | // 64 | // * 1 byte to identify the network, must be 0x80 for mainnet or 0xef for 65 | // either testnet3 or the regression test network 66 | // * 32 bytes of a binary-encoded, big-endian, zero-padded private key 67 | // * Optional 1 byte (equal to 0x01) if the address being imported or exported 68 | // was created by taking the RIPEMD160 after SHA256 hash of a serialized 69 | // compressed (33-byte) public key 70 | // * 4 bytes of checksum, must equal the first four bytes of the double SHA256 71 | // of every byte before the checksum in this sequence 72 | // 73 | // If the base58-decoded byte sequence does not match this, DecodeWIF will 74 | // return a non-nil error. ErrMalformedPrivateKey is returned when the WIF 75 | // is of an impossible length or the expected compressed pubkey magic number 76 | // does not equal the expected value of 0x01. ErrChecksumMismatch is returned 77 | // if the expected WIF checksum does not match the calculated checksum. 78 | func DecodeWIF(wif string) (*WIF, error) { 79 | decoded := base58.Decode(wif) 80 | decodedLen := len(decoded) 81 | var compress bool 82 | 83 | // Length of base58 decoded WIF must be 32 bytes + an optional 1 byte 84 | // (0x01) if compressed, plus 1 byte for netID + 4 bytes of checksum. 85 | switch decodedLen { 86 | case 1 + btcec.PrivKeyBytesLen + 1 + 4: 87 | if decoded[33] != compressMagic { 88 | return nil, ErrMalformedPrivateKey 89 | } 90 | compress = true 91 | case 1 + btcec.PrivKeyBytesLen + 4: 92 | compress = false 93 | default: 94 | return nil, ErrMalformedPrivateKey 95 | } 96 | 97 | // Checksum is first four bytes of double SHA256 of the identifier byte 98 | // and privKey. Verify this matches the final 4 bytes of the decoded 99 | // private key. 100 | var tosum []byte 101 | if compress { 102 | tosum = decoded[:1+btcec.PrivKeyBytesLen+1] 103 | } else { 104 | tosum = decoded[:1+btcec.PrivKeyBytesLen] 105 | } 106 | cksum := DoubleHashB(tosum)[:4] 107 | if !bytes.Equal(cksum, decoded[decodedLen-4:]) { 108 | return nil, ErrChecksumMismatch 109 | } 110 | 111 | netID := decoded[0] 112 | privKeyBytes := decoded[1 : 1+btcec.PrivKeyBytesLen] 113 | privKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), privKeyBytes) 114 | return &WIF{privKey, compress, netID}, nil 115 | } 116 | 117 | // String creates the Wallet Import Format string encoding of a WIF structure. 118 | // See DecodeWIF for a detailed breakdown of the format and requirements of 119 | // a valid WIF string. 120 | func (w *WIF) String() string { 121 | // Precalculate size. Maximum number of bytes before base58 encoding 122 | // is one byte for the network, 32 bytes of private key, possibly one 123 | // extra byte if the pubkey is to be compressed, and finally four 124 | // bytes of checksum. 125 | encodeLen := 1 + btcec.PrivKeyBytesLen + 4 126 | if w.CompressPubKey { 127 | encodeLen++ 128 | } 129 | 130 | a := make([]byte, 0, encodeLen) 131 | a = append(a, w.netID) 132 | // Pad and append bytes manually, instead of using Serialize, to 133 | // avoid another call to make. 134 | a = paddedAppend(btcec.PrivKeyBytesLen, a, w.PrivKey.D.Bytes()) 135 | if w.CompressPubKey { 136 | a = append(a, compressMagic) 137 | } 138 | cksum := DoubleHashB(a)[:4] 139 | a = append(a, cksum...) 140 | return base58.Encode(a) 141 | } 142 | 143 | // SerializePubKey serializes the associated public key of the imported or 144 | // exported private key in either a compressed or uncompressed format. The 145 | // serialization format chosen depends on the value of w.CompressPubKey. 146 | func (w *WIF) SerializePubKey() []byte { 147 | pk := (*btcec.PublicKey)(&w.PrivKey.PublicKey) 148 | if w.CompressPubKey { 149 | return pk.SerializeCompressed() 150 | } 151 | return pk.SerializeUncompressed() 152 | } 153 | 154 | // paddedAppend appends the src byte slice to dst, returning the new slice. 155 | // If the length of the source is smaller than the passed size, leading zero 156 | // bytes are appended to the dst slice before appending src. 157 | func paddedAppend(size uint, dst, src []byte) []byte { 158 | for i := 0; i < int(size)-len(src); i++ { 159 | dst = append(dst, 0) 160 | } 161 | return append(dst, src...) 162 | } 163 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/ecc/README.md: -------------------------------------------------------------------------------- 1 | EOSIO Elliptic Curve Cryptography Wrapper 2 | ========================================= 3 | 4 | This is a simple wrapper for `btcec`, that handles the specificities 5 | of the format for keys in EOS. 6 | 7 | It was crafted in reference to `eosjs-ecc`, `eosjs-keygen` and the C++ 8 | codebase of EOS.IO Software. 9 | 10 | This handles the `EOS` prefix on public keys, manages the version and 11 | checksums in public and private keys. 12 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/ecc/curve.go: -------------------------------------------------------------------------------- 1 | package ecc 2 | 3 | type CurveID uint8 4 | 5 | const ( 6 | CurveK1 = CurveID(iota) 7 | CurveR1 8 | ) 9 | 10 | func (c CurveID) String() string { 11 | switch c { 12 | case CurveK1: 13 | return "K1" 14 | case CurveR1: 15 | return "R1" 16 | default: 17 | return "UN" // unknown 18 | } 19 | } 20 | 21 | func (c CurveID) StringPrefix() string { 22 | return c.String() + "_" 23 | } 24 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/ecc/privkey.go: -------------------------------------------------------------------------------- 1 | package ecc 2 | 3 | import ( 4 | cryptorand "crypto/rand" 5 | "crypto/sha256" 6 | "encoding/json" 7 | "fmt" 8 | "io" 9 | "strings" 10 | 11 | "github.com/eoscanada/eos-go/btcsuite/btcd/btcec" 12 | "github.com/eoscanada/eos-go/btcsuite/btcutil" 13 | ) 14 | 15 | const PrivateKeyPrefix = "PVT_" 16 | 17 | func NewRandomPrivateKey() (*PrivateKey, error) { 18 | return newRandomPrivateKey(cryptorand.Reader) 19 | } 20 | 21 | func NewDeterministicPrivateKey(randSource io.Reader) (*PrivateKey, error) { 22 | return newRandomPrivateKey(randSource) 23 | } 24 | 25 | func newRandomPrivateKey(randSource io.Reader) (*PrivateKey, error) { 26 | rawPrivKey := make([]byte, 32) 27 | written, err := io.ReadFull(randSource, rawPrivKey) 28 | if err != nil { 29 | return nil, fmt.Errorf("error feeding crypto-rand numbers to seed ephemeral private key: %s", err) 30 | } 31 | if written != 32 { 32 | return nil, fmt.Errorf("couldn't write 32 bytes of randomness to seed ephemeral private key") 33 | } 34 | 35 | h := sha256.New() 36 | h.Write(rawPrivKey) 37 | privKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), h.Sum(nil)) 38 | 39 | return &PrivateKey{Curve: CurveK1, privKey: privKey}, nil 40 | } 41 | 42 | func NewPrivateKey(wif string) (*PrivateKey, error) { 43 | // Strip potential prefix, and set curve 44 | var privKeyMaterial string 45 | var curveID CurveID 46 | if strings.HasPrefix(wif, PrivateKeyPrefix) { // "PVT_" 47 | privKeyMaterial = wif[len(PrivateKeyPrefix):] 48 | 49 | // check the subcurve 50 | curvePrefix := privKeyMaterial[:3] 51 | switch curvePrefix { 52 | case "K1_": 53 | curveID = CurveK1 54 | case "R1_": 55 | curveID = CurveR1 56 | default: 57 | return nil, fmt.Errorf("unsupported curve prefix %q", curvePrefix) 58 | } 59 | 60 | privKeyMaterial = privKeyMaterial[3:] // remove "K1_"... 61 | 62 | } else { // no-prefix, like before 63 | privKeyMaterial = wif 64 | curveID = CurveK1 65 | } 66 | 67 | wifObj, err := btcutil.DecodeWIF(privKeyMaterial) 68 | if err != nil { 69 | return nil, err 70 | } 71 | 72 | return &PrivateKey{Curve: curveID, privKey: wifObj.PrivKey}, nil 73 | } 74 | 75 | type PrivateKey struct { 76 | Curve CurveID 77 | privKey *btcec.PrivateKey 78 | } 79 | 80 | func (p *PrivateKey) PublicKey() PublicKey { 81 | return PublicKey{Curve: p.Curve, Content: p.privKey.PubKey().SerializeCompressed()} 82 | } 83 | 84 | // Sign signs a 32 bytes SHA256 hash.. 85 | func (p *PrivateKey) Sign(hash []byte) (out Signature, err error) { 86 | if len(hash) != 32 { 87 | return out, fmt.Errorf("hash should be 32 bytes") 88 | } 89 | 90 | if p.Curve != CurveK1 { 91 | return out, fmt.Errorf("curve R1 not supported for signature") 92 | } 93 | 94 | // TODO: implement the R1 curve.. 95 | compactSig, err := p.privKey.SignCanonical(btcec.S256(), hash) 96 | if err != nil { 97 | return out, fmt.Errorf("canonical, %s", err) 98 | } 99 | 100 | return Signature{Curve: p.Curve, Content: compactSig}, nil 101 | } 102 | 103 | func (p *PrivateKey) String() string { 104 | wif, _ := btcutil.NewWIF(p.privKey, '\x80', false) // no error possible 105 | return wif.String() 106 | // FIXME: when we decide to go ahead with the new representation. 107 | //return PrivateKeyPrefix + p.Curve.StringPrefix() + wif.String() 108 | } 109 | 110 | func (p *PrivateKey) MarshalJSON() ([]byte, error) { 111 | return json.Marshal(p.String()) 112 | } 113 | 114 | func (p *PrivateKey) UnmarshalJSON(v []byte) (err error) { 115 | var s string 116 | if err = json.Unmarshal(v, &s); err != nil { 117 | return 118 | } 119 | 120 | newPrivKey, err := NewPrivateKey(s) 121 | if err != nil { 122 | return 123 | } 124 | 125 | *p = *newPrivKey 126 | 127 | return 128 | } 129 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/ecc/pubkey.go: -------------------------------------------------------------------------------- 1 | package ecc 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "strings" 8 | 9 | "github.com/eoscanada/eos-go/btcsuite/btcd/btcec" 10 | "github.com/eoscanada/eos-go/btcsuite/btcutil/base58" 11 | "golang.org/x/crypto/ripemd160" 12 | ) 13 | 14 | const PublicKeyPrefix = "PUB_" 15 | const PublicKeyPrefixCompat = "EOS" 16 | 17 | type PublicKey struct { 18 | Curve CurveID 19 | Content []byte 20 | } 21 | 22 | func NewPublicKey(pubKey string) (out PublicKey, err error) { 23 | if len(pubKey) < 8 { 24 | return out, fmt.Errorf("invalid format") 25 | } 26 | 27 | var pubKeyMaterial string 28 | var curveID CurveID 29 | if strings.HasPrefix(pubKey, PublicKeyPrefix) { 30 | pubKeyMaterial = pubKey[len(PublicKeyPrefix):] // strip "PUB_" 31 | 32 | curvePrefix := pubKeyMaterial[:3] 33 | switch curvePrefix { 34 | case "K1_": 35 | curveID = CurveK1 36 | case "R1_": 37 | curveID = CurveR1 38 | default: 39 | return out, fmt.Errorf("unsupported curve prefix %q", curvePrefix) 40 | } 41 | pubKeyMaterial = pubKeyMaterial[3:] // strip "K1_" 42 | 43 | } else if strings.HasPrefix(pubKey, PublicKeyPrefixCompat) { // "EOS" 44 | pubKeyMaterial = pubKey[len(PublicKeyPrefixCompat):] // strip "EOS" 45 | curveID = CurveK1 46 | 47 | } else { 48 | return out, fmt.Errorf("public key should start with %q (or the old %q)", PublicKeyPrefix, PublicKeyPrefixCompat) 49 | } 50 | 51 | pubDecoded, err := checkDecode(pubKeyMaterial, curveID) 52 | if err != nil { 53 | return out, fmt.Errorf("checkDecode: %s", err) 54 | } 55 | 56 | return PublicKey{Curve: curveID, Content: pubDecoded}, nil 57 | } 58 | 59 | func MustNewPublicKey(pubKey string) PublicKey { 60 | key, err := NewPublicKey(pubKey) 61 | if err != nil { 62 | panic(err.Error()) 63 | } 64 | return key 65 | } 66 | 67 | // CheckDecode decodes a string that was encoded with CheckEncode and verifies the checksum. 68 | func checkDecode(input string, curve CurveID) (result []byte, err error) { 69 | decoded := base58.Decode(input) 70 | if len(decoded) < 5 { 71 | return nil, fmt.Errorf("invalid format") 72 | } 73 | var cksum [4]byte 74 | copy(cksum[:], decoded[len(decoded)-4:]) 75 | ///// WARN: ok the ripemd160checksum should include the prefix in CERTAIN situations, 76 | // like when we imported the PubKey without a prefix ?! tied to the string representation 77 | // or something ? weird.. checksum shouldn't change based on the string reprsentation. 78 | if bytes.Compare(ripemd160checksum(decoded[:len(decoded)-4], curve), cksum[:]) != 0 { 79 | return nil, fmt.Errorf("invalid checksum") 80 | } 81 | // perhaps bitcoin has a leading net ID / version, but EOS doesn't 82 | payload := decoded[:len(decoded)-4] 83 | result = append(result, payload...) 84 | return 85 | } 86 | 87 | func ripemd160checksum(in []byte, curve CurveID) []byte { 88 | h := ripemd160.New() 89 | _, _ = h.Write(in) // this implementation has no error path 90 | 91 | // if curve != CurveK1 { 92 | // _, _ = h.Write([]byte(curve.String())) // conditionally ? 93 | // } 94 | sum := h.Sum(nil) 95 | return sum[:4] 96 | } 97 | 98 | func Ripemd160checksumHashCurve(in []byte, curve CurveID) []byte { 99 | h := ripemd160.New() 100 | _, _ = h.Write(in) // this implementation has no error path 101 | 102 | // FIXME: this seems to be only rolled out to the `SIG_` things.. 103 | // proper support for importing `EOS` keys isn't rolled out into `dawn4`. 104 | _, _ = h.Write([]byte(curve.String())) // conditionally ? 105 | sum := h.Sum(nil) 106 | return sum[:4] 107 | } 108 | 109 | func (p PublicKey) Key() (*btcec.PublicKey, error) { 110 | // TODO: implement the curve switch according to `p.Curve` 111 | key, err := btcec.ParsePubKey(p.Content, btcec.S256()) 112 | if err != nil { 113 | return nil, fmt.Errorf("parsePubKey: %s", err) 114 | } 115 | 116 | return key, nil 117 | } 118 | 119 | func (p PublicKey) String() string { 120 | //hash := ripemd160checksum(append([]byte{byte(p.Curve)}, p.Content...)) does the checksum include the curve ID?! 121 | hash := ripemd160checksum(p.Content, p.Curve) 122 | rawkey := append(p.Content, hash[:4]...) 123 | return PublicKeyPrefixCompat + base58.Encode(rawkey) 124 | // FIXME: when we decide to go ahead with the new representation. 125 | //return PublicKeyPrefix + p.Curve.StringPrefix() + base58.Encode(rawkey) 126 | } 127 | 128 | func (p PublicKey) MarshalJSON() ([]byte, error) { 129 | s := p.String() 130 | return json.Marshal(s) 131 | } 132 | 133 | func (p *PublicKey) UnmarshalJSON(data []byte) error { 134 | var s string 135 | err := json.Unmarshal(data, &s) 136 | if err != nil { 137 | return err 138 | } 139 | 140 | newKey, err := NewPublicKey(s) 141 | if err != nil { 142 | return err 143 | } 144 | 145 | *p = newKey 146 | 147 | return nil 148 | } 149 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/ecc/signature.go: -------------------------------------------------------------------------------- 1 | package ecc 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "strings" 8 | 9 | "github.com/eoscanada/eos-go/btcsuite/btcd/btcec" 10 | "github.com/eoscanada/eos-go/btcsuite/btcutil/base58" 11 | ) 12 | 13 | // Signature represents a signature for some hash 14 | type Signature struct { 15 | Curve CurveID 16 | Content []byte // the Compact signature as bytes 17 | } 18 | 19 | // Verify checks the signature against the pubKey. `hash` is a sha256 20 | // hash of the payload to verify. 21 | func (s Signature) Verify(hash []byte, pubKey PublicKey) bool { 22 | if s.Curve != CurveK1 { 23 | fmt.Println("WARN: github.com/eoscanada/eos-go/ecc library does not support the R1 curve yet") 24 | return false 25 | } 26 | 27 | // TODO: choose the S256 curve, based on s.Curve 28 | recoveredKey, _, err := btcec.RecoverCompact(btcec.S256(), s.Content, hash) 29 | if err != nil { 30 | return false 31 | } 32 | key, err := pubKey.Key() 33 | if err != nil { 34 | return false 35 | } 36 | if recoveredKey.IsEqual(key) { 37 | return true 38 | } 39 | return false 40 | } 41 | 42 | // PublicKey retrieves the public key, but requires the 43 | // payload.. that's the way to validate the signature. Use Verify() if 44 | // you only want to validate. 45 | func (s Signature) PublicKey(hash []byte) (out PublicKey, err error) { 46 | if s.Curve != CurveK1 { 47 | return out, fmt.Errorf("WARN: github.com/eoscanada/eos-go/ecc library does not support the R1 curve yet") 48 | } 49 | 50 | recoveredKey, _, err := btcec.RecoverCompact(btcec.S256(), s.Content, hash) 51 | if err != nil { 52 | return out, err 53 | } 54 | 55 | return PublicKey{ 56 | Curve: s.Curve, 57 | Content: recoveredKey.SerializeCompressed(), 58 | }, nil 59 | } 60 | 61 | func (s Signature) String() string { 62 | checksum := Ripemd160checksumHashCurve(s.Content, s.Curve) 63 | buf := append(s.Content[:], checksum...) 64 | return "SIG_" + s.Curve.StringPrefix() + base58.Encode(buf) 65 | //return "SIG_" + base58.Encode(buf) 66 | //return base58.Encode(buf) 67 | } 68 | 69 | func NewSignature(fromText string) (Signature, error) { 70 | if !strings.HasPrefix(fromText, "SIG_") { 71 | return Signature{}, fmt.Errorf("signature should start with SIG_") 72 | } 73 | if len(fromText) < 8 { 74 | return Signature{}, fmt.Errorf("invalid signature length") 75 | } 76 | 77 | fromText = fromText[4:] // remove the `SIG_` prefix 78 | 79 | var curveID CurveID 80 | var curvePrefix = fromText[:3] 81 | switch curvePrefix { 82 | case "K1_": 83 | curveID = CurveK1 84 | case "R1_": 85 | curveID = CurveR1 86 | default: 87 | return Signature{}, fmt.Errorf("invalid curve prefix %q", curvePrefix) 88 | } 89 | fromText = fromText[3:] // strip curve ID 90 | 91 | sigbytes := base58.Decode(fromText) 92 | 93 | content := sigbytes[:len(sigbytes)-4] 94 | checksum := sigbytes[len(sigbytes)-4:] 95 | verifyChecksum := Ripemd160checksumHashCurve(content, curveID) 96 | if !bytes.Equal(verifyChecksum, checksum) { 97 | return Signature{}, fmt.Errorf("signature checksum failed, found %x expected %x", verifyChecksum, checksum) 98 | } 99 | 100 | return Signature{Curve: curveID, Content: content}, nil 101 | } 102 | 103 | func (a Signature) MarshalJSON() ([]byte, error) { 104 | return json.Marshal(a.String()) 105 | } 106 | 107 | func (a *Signature) UnmarshalJSON(data []byte) (err error) { 108 | var s string 109 | err = json.Unmarshal(data, &s) 110 | if err != nil { 111 | return 112 | } 113 | 114 | *a, err = NewSignature(s) 115 | 116 | return 117 | } 118 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/encoder.go: -------------------------------------------------------------------------------- 1 | package eos 2 | 3 | import ( 4 | "bytes" 5 | "encoding/binary" 6 | "encoding/hex" 7 | "errors" 8 | "fmt" 9 | "io" 10 | "reflect" 11 | 12 | "github.com/eoscanada/eos-go/ecc" 13 | ) 14 | 15 | // -------------------------------------------------------------- 16 | // Encoder implements the EOS packing, similar to FC_BUFFER 17 | // -------------------------------------------------------------- 18 | type Encoder struct { 19 | output io.Writer 20 | Order binary.ByteOrder 21 | count int 22 | } 23 | 24 | func NewEncoder(w io.Writer) *Encoder { 25 | return &Encoder{ 26 | output: w, 27 | Order: binary.LittleEndian, 28 | count: 0, 29 | } 30 | } 31 | 32 | func (e *Encoder) writeName(name Name) error { 33 | val, err := StringToName(string(name)) 34 | if err != nil { 35 | return fmt.Errorf("writeName: %s", err) 36 | } 37 | return e.writeUint64(val) 38 | } 39 | 40 | func (e *Encoder) Encode(v interface{}) (err error) { 41 | switch cv := v.(type) { 42 | case Name: 43 | return e.writeName(cv) 44 | case AccountName: 45 | name := Name(cv) 46 | return e.writeName(name) 47 | case PermissionName: 48 | name := Name(cv) 49 | return e.writeName(name) 50 | case ActionName: 51 | name := Name(cv) 52 | return e.writeName(name) 53 | case TableName: 54 | name := Name(cv) 55 | return e.writeName(name) 56 | case ScopeName: 57 | name := Name(cv) 58 | return e.writeName(name) 59 | case string: 60 | return e.writeString(cv) 61 | case TransactionStatus: 62 | return e.writeByte(uint8(cv)) 63 | case IDListMode: 64 | return e.writeByte(byte(cv)) 65 | case byte: 66 | return e.writeByte(cv) 67 | case int8: 68 | return e.writeByte(byte(cv)) 69 | case int16: 70 | return e.writeInt16(cv) 71 | case uint16: 72 | return e.writeUint16(cv) 73 | case uint32: 74 | return e.writeUint32(cv) 75 | case uint64: 76 | return e.writeUint64(cv) 77 | case Varuint32: 78 | return e.writeUVarInt(int(cv)) 79 | case bool: 80 | return e.writeBool(cv) 81 | case Bool: 82 | return e.writeBool(bool(cv)) 83 | case JSONTime: 84 | return e.writeJSONTime(cv) 85 | case HexBytes: 86 | return e.writeByteArray(cv) 87 | case []byte: 88 | return e.writeByteArray(cv) 89 | case SHA256Bytes: 90 | return e.writeSHA256Bytes(cv) 91 | case ecc.PublicKey: 92 | return e.writePublicKey(cv) 93 | case ecc.Signature: 94 | return e.writeSignature(cv) 95 | case Tstamp: 96 | return e.writeTstamp(cv) 97 | case BlockTimestamp: 98 | return e.writeBlockTimestamp(cv) 99 | case CurrencyName: 100 | return e.writeCurrencyName(cv) 101 | case Asset: 102 | return e.writeAsset(cv) 103 | // case *OptionalProducerSchedule: 104 | // isPresent := cv != nil 105 | // e.writeBool(isPresent) 106 | // if isPresent { 107 | 108 | // } 109 | case ActionData: 110 | println("ActionData") 111 | return e.writeActionData(cv) 112 | case *ActionData: 113 | println("*ActionData") 114 | return e.writeActionData(*cv) 115 | case *P2PMessageEnvelope: 116 | return e.writeBlockP2PMessageEnvelope(*cv) 117 | default: 118 | 119 | rv := reflect.Indirect(reflect.ValueOf(v)) 120 | t := rv.Type() 121 | 122 | switch t.Kind() { 123 | 124 | case reflect.Array: 125 | l := t.Len() 126 | //prefix = append(prefix, " ") 127 | println(fmt.Sprintf("Encode: array [%T] of length: %d", v, l)) 128 | 129 | for i := 0; i < l; i++ { 130 | if err = e.Encode(rv.Index(i).Interface()); err != nil { 131 | return 132 | } 133 | } 134 | //prefix = prefix[:len(prefix)-1] 135 | case reflect.Slice: 136 | l := rv.Len() 137 | if err = e.writeUVarInt(l); err != nil { 138 | return 139 | } 140 | //prefix = append(prefix, " ") 141 | println(fmt.Sprintf("Encode: slice [%T] of length: %d", v, l)) 142 | 143 | for i := 0; i < l; i++ { 144 | if err = e.Encode(rv.Index(i).Interface()); err != nil { 145 | return 146 | } 147 | } 148 | //prefix = prefix[:len(prefix)-1] 149 | //case reflect.Ptr: 150 | // println("*************************************************") 151 | // println("*************************************************") 152 | // println(fmt.Sprintf("PTR [%T]", v)) 153 | // println("*************************************************") 154 | // println("*************************************************") 155 | case reflect.Struct: 156 | l := rv.NumField() 157 | println(fmt.Sprintf("Encode: struct [%T] with %d field.", v, l)) 158 | //prefix = append(prefix, " ") 159 | 160 | for i := 0; i < l; i++ { 161 | field := t.Field(i) 162 | println(fmt.Sprintf("field -> %s", field.Name)) 163 | //fmt.Println(fmt.Sprintf("field -> %s", field.Name)) 164 | 165 | tag := field.Tag.Get("eos") 166 | if tag == "-" { 167 | continue 168 | } 169 | 170 | if v := rv.Field(i); t.Field(i).Name != "_" { 171 | if v.CanInterface() { 172 | isPresent := true 173 | if tag == "optional" { 174 | isPresent = !v.IsNil() 175 | e.writeBool(isPresent) 176 | } 177 | 178 | //fmt.Printf("IS PRESENT: %T %#v\n", iface, iface, isPresent) 179 | 180 | if isPresent { 181 | if err = e.Encode(v.Interface()); err != nil { 182 | return 183 | } 184 | } 185 | } 186 | } 187 | } 188 | //prefix = prefix[:len(prefix)-1] 189 | 190 | case reflect.Map: 191 | l := rv.Len() 192 | if err = e.writeUVarInt(l); err != nil { 193 | return 194 | } 195 | println(fmt.Sprintf("Map [%T] of length: %d", v, l)) 196 | for _, key := range rv.MapKeys() { 197 | value := rv.MapIndex(key) 198 | if err = e.Encode(key.Interface()); err != nil { 199 | return err 200 | } 201 | if err = e.Encode(value.Interface()); err != nil { 202 | return err 203 | } 204 | } 205 | default: 206 | return errors.New("Encode: unsupported type " + t.String()) 207 | } 208 | } 209 | 210 | return 211 | } 212 | 213 | func (e *Encoder) toWriter(bytes []byte) (err error) { 214 | 215 | e.count += len(bytes) 216 | println(fmt.Sprintf(" Appending : [%s] pos [%d]", hex.EncodeToString(bytes), e.count)) 217 | _, err = e.output.Write(bytes) 218 | return 219 | } 220 | 221 | func (e *Encoder) writeByteArray(b []byte) error { 222 | println(fmt.Sprintf("writing byte array of len [%d]", len(b))) 223 | if err := e.writeUVarInt(len(b)); err != nil { 224 | return err 225 | } 226 | return e.toWriter(b) 227 | } 228 | 229 | func (e *Encoder) writeUVarInt(v int) (err error) { 230 | buf := make([]byte, 8) 231 | l := binary.PutUvarint(buf, uint64(v)) 232 | return e.toWriter(buf[:l]) 233 | } 234 | 235 | func (e *Encoder) writeByte(b byte) (err error) { 236 | return e.toWriter([]byte{b}) 237 | } 238 | 239 | func (e *Encoder) writeBool(b bool) (err error) { 240 | var out byte 241 | if b { 242 | out = 1 243 | } 244 | return e.writeByte(out) 245 | } 246 | 247 | func (e *Encoder) writeUint16(i uint16) (err error) { 248 | buf := make([]byte, TypeSize.UInt16) 249 | binary.LittleEndian.PutUint16(buf, i) 250 | return e.toWriter(buf) 251 | } 252 | 253 | func (e *Encoder) writeInt16(i int16) (err error) { 254 | return e.writeUint16(uint16(i)) 255 | } 256 | 257 | func (e *Encoder) writeUint32(i uint32) (err error) { 258 | buf := make([]byte, TypeSize.UInt32) 259 | binary.LittleEndian.PutUint32(buf, i) 260 | return e.toWriter(buf) 261 | 262 | } 263 | 264 | func (e *Encoder) writeUint64(i uint64) (err error) { 265 | buf := make([]byte, TypeSize.UInt64) 266 | binary.LittleEndian.PutUint64(buf, i) 267 | return e.toWriter(buf) 268 | 269 | } 270 | 271 | func (e *Encoder) writeString(s string) (err error) { 272 | return e.writeByteArray([]byte(s)) 273 | } 274 | 275 | func (e *Encoder) writeSHA256Bytes(s SHA256Bytes) error { 276 | if len(s) == 0 { 277 | return e.toWriter(bytes.Repeat([]byte{0}, TypeSize.SHA256Bytes)) 278 | } 279 | return e.toWriter(s) 280 | } 281 | 282 | func (e *Encoder) writePublicKey(pk ecc.PublicKey) (err error) { 283 | if len(pk.Content) != 33 { 284 | return fmt.Errorf("public key %q should be 33 bytes, was %d", hex.EncodeToString(pk.Content), len(pk.Content)) 285 | } 286 | 287 | if err = e.writeByte(byte(pk.Curve)); err != nil { 288 | return err 289 | } 290 | 291 | return e.toWriter(pk.Content) 292 | } 293 | 294 | func (e *Encoder) writeSignature(s ecc.Signature) (err error) { 295 | if len(s.Content) != 65 { 296 | return fmt.Errorf("signature should be 65 bytes, was %d", len(s.Content)) 297 | } 298 | 299 | if err = e.writeByte(byte(s.Curve)); err != nil { 300 | return 301 | } 302 | 303 | return e.toWriter(s.Content) // should write 65 bytes 304 | } 305 | 306 | func (e *Encoder) writeTstamp(t Tstamp) (err error) { 307 | n := uint64(t.UnixNano()) 308 | return e.writeUint64(n) 309 | } 310 | 311 | func (e *Encoder) writeBlockTimestamp(bt BlockTimestamp) (err error) { 312 | n := uint32(bt.Unix() - 946684800) 313 | return e.writeUint32(n) 314 | } 315 | 316 | func (e *Encoder) writeCurrencyName(curreny CurrencyName) (err error) { 317 | out := make([]byte, 7, 7) 318 | copy(out, []byte(curreny)) 319 | 320 | return e.toWriter(out) 321 | } 322 | 323 | func (e *Encoder) writeAsset(asset Asset) (err error) { 324 | 325 | e.writeUint64(uint64(asset.Amount)) 326 | e.writeByte(asset.Precision) 327 | 328 | symbol := make([]byte, 7, 7) 329 | 330 | copy(symbol[:], []byte(asset.Symbol.Symbol)) 331 | return e.toWriter(symbol) 332 | } 333 | 334 | func (e *Encoder) writeJSONTime(time JSONTime) (err error) { 335 | return e.writeUint32(uint32(time.Unix())) 336 | } 337 | 338 | func (e *Encoder) writeBlockP2PMessageEnvelope(envelope P2PMessageEnvelope) (err error) { 339 | 340 | println("writeBlockP2PMessageEnvelope") 341 | 342 | if envelope.P2PMessage != nil { 343 | buf := new(bytes.Buffer) 344 | subEncoder := NewEncoder(buf) 345 | err = subEncoder.Encode(envelope.P2PMessage) 346 | if err != nil { 347 | err = fmt.Errorf("p2p message, %s", err) 348 | return 349 | } 350 | envelope.Payload = buf.Bytes() 351 | } 352 | 353 | messageLen := uint32(len(envelope.Payload) + 1) 354 | println(fmt.Sprintf("Message length: %d", messageLen)) 355 | err = e.writeUint32(messageLen) 356 | if err == nil { 357 | err = e.writeByte(byte(envelope.Type)) 358 | 359 | if err == nil { 360 | return e.toWriter(envelope.Payload) 361 | } 362 | } 363 | return 364 | } 365 | 366 | func (e *Encoder) writeActionData(actionData ActionData) (err error) { 367 | if actionData.Data != nil { 368 | //if reflect.TypeOf(actionData.Data) == reflect.TypeOf(&ActionData{}) { 369 | // log.Fatal("pas cool") 370 | //} 371 | 372 | println(fmt.Sprintf("entering action data, %T", actionData)) 373 | var d interface{} 374 | d = actionData.Data 375 | if reflect.TypeOf(d).Kind() == reflect.Ptr { 376 | d = reflect.ValueOf(actionData.Data).Elem().Interface() 377 | } 378 | 379 | if reflect.TypeOf(d).Kind() == reflect.String { //todo : this is a very bad ack ...... 380 | 381 | data, err := hex.DecodeString(d.(string)) 382 | if err != nil { 383 | return fmt.Errorf("ack, %s", err) 384 | } 385 | e.writeByteArray(data) 386 | return nil 387 | 388 | } 389 | 390 | println(fmt.Sprintf("encoding action data, %T", d)) 391 | raw, err := MarshalBinary(d) 392 | if err != nil { 393 | return err 394 | } 395 | println(fmt.Sprintf("writing action data, %T", d)) 396 | return e.writeByteArray(raw) 397 | } 398 | 399 | return e.writeByteArray(actionData.HexData) 400 | } 401 | 402 | func MarshalBinary(v interface{}) ([]byte, error) { 403 | buf := new(bytes.Buffer) 404 | encoder := NewEncoder(buf) 405 | err := encoder.Encode(v) 406 | return buf.Bytes(), err 407 | } 408 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/error.go: -------------------------------------------------------------------------------- 1 | package eos 2 | 3 | import "errors" 4 | 5 | // APIError represents the errors as reported by the server 6 | type APIError struct { 7 | Code int 8 | Message string 9 | ErrorStruct struct { 10 | Code int 11 | Name string 12 | What string 13 | Details []struct { 14 | Message string 15 | File string 16 | LineNumber int `json:"line_number"` 17 | Method string 18 | } 19 | } `json:"error"` 20 | } 21 | 22 | func (e APIError) Error() error { 23 | return errors.New(e.String()) 24 | } 25 | 26 | func (e APIError) String() string { 27 | return e.Message 28 | } 29 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/name.go: -------------------------------------------------------------------------------- 1 | package eos 2 | 3 | import "strings" 4 | 5 | func StringToName(s string) (val uint64, err error) { 6 | // ported from the eosio codebase, libraries/chain/include/eosio/chain/name.hpp 7 | var i uint32 8 | sLen := uint32(len(s)) 9 | for ; i <= 12; i++ { 10 | var c uint64 11 | if i < sLen { 12 | c = uint64(charToSymbol(s[i])) 13 | } 14 | 15 | if i < 12 { 16 | c &= 0x1f 17 | c <<= 64 - 5*(i+1) 18 | } else { 19 | c &= 0x0f 20 | } 21 | 22 | val |= c 23 | } 24 | 25 | return 26 | } 27 | 28 | func charToSymbol(c byte) byte { 29 | if c >= 'a' && c <= 'z' { 30 | return c - 'a' + 6 31 | } 32 | if c >= '1' && c <= '5' { 33 | return c - '1' + 1 34 | } 35 | return 0 36 | } 37 | 38 | var base32Alphabet = []byte(".12345abcdefghijklmnopqrstuvwxyz") 39 | 40 | func NameToString(in uint64) string { 41 | // ported from libraries/chain/name.cpp in eosio 42 | a := []byte{'.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.'} 43 | 44 | tmp := in 45 | i := uint32(0) 46 | for ; i <= 12; i++ { 47 | bit := 0x1f 48 | if i == 0 { 49 | bit = 0x0f 50 | } 51 | c := base32Alphabet[tmp&uint64(bit)] 52 | a[12-i] = c 53 | 54 | shift := uint(5) 55 | if i == 0 { 56 | shift = 4 57 | } 58 | 59 | tmp >>= shift 60 | } 61 | 62 | return strings.TrimRight(string(a), ".") 63 | } 64 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/p2p.go: -------------------------------------------------------------------------------- 1 | package eos 2 | 3 | import ( 4 | "encoding/binary" 5 | "encoding/hex" 6 | "errors" 7 | "fmt" 8 | "io" 9 | "reflect" 10 | ) 11 | 12 | // Work-in-progress p2p comms implementation 13 | // 14 | // See /home/abourget/build/eos3/plugins/net_plugin/include/eosio/net_plugin/protocol.hpp:219 15 | // 16 | 17 | type P2PMessageType byte 18 | 19 | const ( 20 | HandshakeMessageType P2PMessageType = iota // 0 21 | ChainSizeType 22 | GoAwayMessageType // 2 23 | TimeMessageType 24 | NoticeMessageType // 4 25 | RequestMessageType 26 | SyncRequestMessageType // 6 27 | SignedBlockType // 7 28 | PackedTransactionMessageType // 8 29 | ) 30 | 31 | type MessageReflectTypes struct { 32 | Name string 33 | ReflectType reflect.Type 34 | } 35 | 36 | var messageAttributes = []MessageReflectTypes{ 37 | {Name: "Handshake", ReflectType: reflect.TypeOf(HandshakeMessage{})}, 38 | {Name: "ChainSize", ReflectType: reflect.TypeOf(ChainSizeMessage{})}, 39 | {Name: "GoAway", ReflectType: reflect.TypeOf(GoAwayMessage{})}, 40 | {Name: "Time", ReflectType: reflect.TypeOf(TimeMessage{})}, 41 | {Name: "Notice", ReflectType: reflect.TypeOf(NoticeMessage{})}, 42 | {Name: "Request", ReflectType: reflect.TypeOf(RequestMessage{})}, 43 | {Name: "SyncRequest", ReflectType: reflect.TypeOf(SyncRequestMessage{})}, 44 | {Name: "SignedBlock", ReflectType: reflect.TypeOf(SignedBlock{})}, 45 | {Name: "PackedTransaction", ReflectType: reflect.TypeOf(PackedTransactionMessage{})}, 46 | } 47 | 48 | var ErrUnknownMessageType = errors.New("unknown type") 49 | 50 | func NewMessageType(aType byte) (t P2PMessageType, err error) { 51 | t = P2PMessageType(aType) 52 | if !t.isValid() { 53 | return t, ErrUnknownMessageType 54 | } 55 | 56 | return 57 | } 58 | 59 | func (t P2PMessageType) isValid() bool { 60 | index := byte(t) 61 | return int(index) < len(messageAttributes) && index >= 0 62 | } 63 | 64 | func (t P2PMessageType) Name() (string, bool) { 65 | index := byte(t) 66 | 67 | if !t.isValid() { 68 | return "Unknown", false 69 | } 70 | 71 | attr := messageAttributes[index] 72 | return attr.Name, true 73 | } 74 | 75 | func (t P2PMessageType) reflectTypes() (MessageReflectTypes, bool) { 76 | index := byte(t) 77 | 78 | if !t.isValid() { 79 | return MessageReflectTypes{}, false 80 | } 81 | 82 | attr := messageAttributes[index] 83 | return attr, true 84 | } 85 | 86 | type P2PMessageEnvelope struct { 87 | Length uint32 `json:"length"` 88 | Type P2PMessageType `json:"type"` 89 | Payload []byte `json:"-"` 90 | P2PMessage P2PMessage `json:"message" eos:"-"` 91 | Raw []byte `json:"-"` 92 | } 93 | 94 | func ReadP2PMessageData(r io.Reader) (envelope *P2PMessageEnvelope, err error) { 95 | data := make([]byte, 0) 96 | 97 | lengthBytes := make([]byte, 4, 4) 98 | //_, err = r.Read(lengthBytes) 99 | _, err = io.ReadFull(r, lengthBytes) 100 | if err != nil { 101 | return 102 | } 103 | 104 | data = append(data, lengthBytes...) 105 | 106 | size := binary.LittleEndian.Uint32(lengthBytes) 107 | 108 | payloadBytes := make([]byte, size, size) 109 | count, err := io.ReadFull(r, payloadBytes) 110 | 111 | if count != int(size) { 112 | err = fmt.Errorf("readfull not full read[%d] expected[%d]", count, size) 113 | return 114 | } 115 | 116 | if err != nil { 117 | fmt.Println("ReadFull, error: ", err) 118 | return 119 | } 120 | 121 | data = append(data, payloadBytes...) 122 | 123 | envelope = &P2PMessageEnvelope{} 124 | decoder := NewDecoder(data) 125 | decoder.DecodeActions(false) 126 | err = decoder.Decode(envelope) 127 | if err != nil { 128 | fmt.Println("Failing data: ", hex.EncodeToString(data)) 129 | } 130 | envelope.Raw = data 131 | return 132 | } 133 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/p2ptypes.go: -------------------------------------------------------------------------------- 1 | package eos 2 | 3 | import ( 4 | "crypto/sha256" 5 | "fmt" 6 | 7 | "encoding/binary" 8 | "encoding/hex" 9 | "encoding/json" 10 | 11 | "github.com/eoscanada/eos-go/ecc" 12 | ) 13 | 14 | type P2PMessage interface { 15 | GetType() P2PMessageType 16 | } 17 | 18 | type HandshakeMessage struct { 19 | // net_plugin/protocol.hpp handshake_message 20 | NetworkVersion uint16 `json:"network_version"` 21 | ChainID SHA256Bytes `json:"chain_id"` 22 | NodeID SHA256Bytes `json:"node_id"` // sha256 23 | Key ecc.PublicKey `json:"key"` // can be empty, producer key, or peer key 24 | Time Tstamp `json:"time"` // time?! 25 | Token SHA256Bytes `json:"token"` // digest of time to prove we own the private `key` 26 | Signature ecc.Signature `json:"sig"` // can be empty if no key, signature of the digest above 27 | P2PAddress string `json:"p2p_address"` 28 | LastIrreversibleBlockNum uint32 `json:"last_irreversible_block_num"` 29 | LastIrreversibleBlockID SHA256Bytes `json:"last_irreversible_block_id"` 30 | HeadNum uint32 `json:"head_num"` 31 | HeadID SHA256Bytes `json:"head_id"` 32 | OS string `json:"os"` 33 | Agent string `json:"agent"` 34 | Generation int16 `json:"generation"` 35 | } 36 | 37 | func (m *HandshakeMessage) GetType() P2PMessageType { 38 | return HandshakeMessageType 39 | } 40 | 41 | type ChainSizeMessage struct { 42 | LastIrreversibleBlockNum uint32 `json:"last_irreversible_block_num"` 43 | LastIrreversibleBlockID SHA256Bytes `json:"last_irreversible_block_id"` 44 | HeadNum uint32 `json:"head_num"` 45 | HeadID SHA256Bytes `json:"head_id"` 46 | } 47 | 48 | func (m *ChainSizeMessage) GetType() P2PMessageType { 49 | return ChainSizeType 50 | } 51 | 52 | func (m *HandshakeMessage) String() string { 53 | return fmt.Sprintf("Handshake: Head [%d] Last Irreversible [%d] Time [%s]", m.HeadNum, m.LastIrreversibleBlockNum, m.Time) 54 | } 55 | 56 | type GoAwayReason uint8 57 | 58 | const ( 59 | GoAwayNoReason = uint8(iota) 60 | GoAwaySelfConnect 61 | GoAwayDuplicate 62 | GoAwayWrongChain 63 | GoAwayWrongVersion 64 | GoAwayForked 65 | GoAwayUnlinkable 66 | GoAwayBadTransaction 67 | GoAwayValidation 68 | GoAwayAuthentication 69 | GoAwayFatalOther 70 | GoAwayBenignOther 71 | GoAwayCrazy 72 | ) 73 | 74 | type GoAwayMessage struct { 75 | Reason GoAwayReason `json:"reason"` 76 | NodeID SHA256Bytes `json:"node_id"` 77 | } 78 | 79 | func (m *GoAwayMessage) GetType() P2PMessageType { 80 | return GoAwayMessageType 81 | } 82 | 83 | type TimeMessage struct { 84 | Origin Tstamp `json:"org"` 85 | Receive Tstamp `json:"rec"` 86 | Transmit Tstamp `json:"xmt"` 87 | Destination Tstamp `json:"dst"` 88 | } 89 | 90 | func (m *TimeMessage) GetType() P2PMessageType { 91 | return TimeMessageType 92 | } 93 | 94 | func (t *TimeMessage) String() string { 95 | return fmt.Sprintf("Origin [%s], Receive [%s], Transmit [%s], Destination [%s]", t.Origin, t.Receive, t.Transmit, t.Destination) 96 | } 97 | 98 | type TransactionStatus uint8 99 | 100 | const ( 101 | TransactionStatusExecuted TransactionStatus = iota ///< succeed, no error handler executed 102 | TransactionStatusSoftFail ///< objectively failed (not executed), error handler executed 103 | TransactionStatusHardFail ///< objectively failed and error handler objectively failed thus no state change 104 | TransactionStatusDelayed ///< transaction delayed 105 | TransactionStatusUnknown = TransactionStatus(255) 106 | ) 107 | 108 | func (s *TransactionStatus) UnmarshalJSON(data []byte) error { 109 | var decoded string 110 | if err := json.Unmarshal(data, &decoded); err != nil { 111 | return err 112 | } 113 | switch decoded { 114 | case "executed": 115 | *s = TransactionStatusExecuted 116 | case "soft_fail": 117 | *s = TransactionStatusSoftFail 118 | 119 | case "hard_fail": 120 | *s = TransactionStatusHardFail 121 | case "delayed": 122 | *s = TransactionStatusDelayed 123 | default: 124 | *s = TransactionStatusUnknown 125 | } 126 | return nil 127 | } 128 | 129 | func (s TransactionStatus) MarshalJSON() (data []byte, err error) { 130 | out := "unknown" 131 | switch s { 132 | case TransactionStatusExecuted: 133 | out = "executed" 134 | case TransactionStatusSoftFail: 135 | out = "soft_fail" 136 | case TransactionStatusHardFail: 137 | out = "hard_fail" 138 | case TransactionStatusDelayed: 139 | out = "delayed" 140 | } 141 | return json.Marshal(out) 142 | } 143 | func (s TransactionStatus) String() string { 144 | 145 | switch s { 146 | case TransactionStatusExecuted: 147 | return "executed" 148 | case TransactionStatusSoftFail: 149 | return "soft fail" 150 | case TransactionStatusHardFail: 151 | return "hard fail" 152 | case TransactionStatusDelayed: 153 | return "delayed" 154 | default: 155 | return "unknown" 156 | } 157 | 158 | } 159 | 160 | //type TransactionID SHA256Bytes 161 | 162 | type ShardLock struct { 163 | AccountName AccountName `json:"account_name"` 164 | ScopeName ScopeName `json:"scope_name"` 165 | } 166 | 167 | type ShardSummary struct { 168 | ReadLocks []ShardLock `json:"read_locks"` 169 | WriteLocks []ShardLock `json:"write_locks"` 170 | Transactions []TransactionReceipt `json:"transactions"` 171 | } 172 | 173 | type Cycles []ShardSummary 174 | type RegionSummary struct { 175 | Region uint16 `json:"region"` 176 | CyclesSummary []Cycles `json:"cycles_summary"` 177 | } 178 | 179 | type ProducerKey struct { 180 | AccountName AccountName `json:"account_name"` 181 | BlockSigningKey ecc.PublicKey `json:"block_signing_key"` 182 | } 183 | 184 | type ProducerSchedule struct { 185 | Version uint32 `json:"version"` 186 | Producers []ProducerKey `json:"producers"` 187 | } 188 | 189 | type BlockHeader struct { 190 | Timestamp BlockTimestamp `json:"timestamp"` 191 | Producer AccountName `json:"producer"` 192 | Confirmed uint16 `json:"confirmed"` 193 | Previous SHA256Bytes `json:"previous"` 194 | TransactionMRoot SHA256Bytes `json:"transaction_mroot"` 195 | ActionMRoot SHA256Bytes `json:"action_mroot"` 196 | ScheduleVersion uint32 `json:"schedule_version"` 197 | NewProducers *OptionalProducerSchedule `json:"new_producers" eos:"optional"` 198 | HeaderExtensions []*Extension `json:"header_extensions"` 199 | } 200 | 201 | func (b *BlockHeader) BlockNumber() uint32 { 202 | return binary.BigEndian.Uint32(b.Previous[:4]) + 1 203 | } 204 | 205 | func (b *BlockHeader) BlockID() (SHA256Bytes, error) { 206 | cereal, err := MarshalBinary(b) 207 | if err != nil { 208 | return nil, err 209 | } 210 | 211 | h := sha256.New() 212 | _, _ = h.Write(cereal) 213 | hashed := h.Sum(nil) 214 | 215 | binary.BigEndian.PutUint32(hashed, b.BlockNumber()) 216 | 217 | return SHA256Bytes(hashed), nil 218 | } 219 | 220 | type OptionalProducerSchedule struct { 221 | ProducerSchedule 222 | } 223 | 224 | type SignedBlockHeader struct { 225 | BlockHeader 226 | ProducerSignature ecc.Signature `json:"producer_signature"` 227 | } 228 | 229 | type SignedBlock struct { 230 | SignedBlockHeader 231 | Transactions []TransactionReceipt `json:"transactions"` 232 | BlockExtensions []*Extension `json:"block_extensions"` 233 | } 234 | 235 | func (m *SignedBlock) String() string { 236 | return "SignedBlock" 237 | } 238 | 239 | func (m *SignedBlock) GetType() P2PMessageType { 240 | return SignedBlockType 241 | } 242 | 243 | type TransactionReceiptHeader struct { 244 | Status TransactionStatus `json:"status"` 245 | CPUUsageMicroSeconds uint32 `json:"cpu_usage_us"` 246 | NetUsageWords Varuint32 `json:"net_usage_words"` 247 | } 248 | 249 | type TransactionReceipt struct { 250 | TransactionReceiptHeader 251 | Transaction TransactionWithID `json:"trx"` 252 | } 253 | 254 | type TransactionWithID struct { 255 | ID SHA256Bytes 256 | Packed *PackedTransaction 257 | } 258 | 259 | func (t TransactionWithID) MarshalJSON() ([]byte, error) { 260 | return json.Marshal([]interface{}{ 261 | t.ID, 262 | t.Packed, 263 | }) 264 | } 265 | 266 | func (t *TransactionWithID) UnmarshalJSON(data []byte) error { 267 | var packed PackedTransaction 268 | if data[0] == '{' { 269 | if err := json.Unmarshal(data, &packed); err != nil { 270 | return err 271 | } 272 | *t = TransactionWithID{ 273 | ID: packed.ID(), 274 | Packed: &packed, 275 | } 276 | 277 | return nil 278 | } else if data[0] == '"' { 279 | var id string 280 | err := json.Unmarshal(data, &id) 281 | if err != nil { 282 | return err 283 | } 284 | 285 | shaID, err := hex.DecodeString(id) 286 | if err != nil { 287 | return fmt.Errorf("decoding id in trx: %s", err) 288 | } 289 | 290 | *t = TransactionWithID{ 291 | ID: SHA256Bytes(shaID), 292 | } 293 | 294 | return nil 295 | } 296 | 297 | var in []json.RawMessage 298 | err := json.Unmarshal(data, &in) 299 | if err != nil { 300 | return err 301 | } 302 | 303 | if len(in) != 2 { 304 | return fmt.Errorf("expected two params for TransactionWithID, got %d", len(in)) 305 | } 306 | 307 | // ignore the ID field right now.. 308 | err = json.Unmarshal(in[1], &packed) 309 | if err != nil { 310 | return err 311 | } 312 | 313 | *t = TransactionWithID{ 314 | ID: packed.ID(), 315 | Packed: &packed, 316 | } 317 | 318 | return nil 319 | } 320 | 321 | type IDListMode byte 322 | 323 | const ( 324 | none IDListMode = iota 325 | catch_up 326 | last_irr_catch_up 327 | normal 328 | ) 329 | 330 | type OrderedTransactionIDs struct { 331 | Unknown [3]byte `json:"-"` ///// WWUUuuuuuuuuuuuutzthat ? 332 | Mode IDListMode `json:"mode"` 333 | Pending uint32 `json:"pending"` 334 | IDs []SHA256Bytes `json:"ids"` 335 | } 336 | type OrderedBlockIDs struct { 337 | Unknown [3]byte `json:"-"` ///// wuuttzthat? 338 | Mode IDListMode `json:"mode"` 339 | Pending uint32 `json:"pending"` 340 | IDs []SHA256Bytes `json:"ids"` 341 | } 342 | 343 | type NoticeMessage struct { 344 | KnownTrx OrderedBlockIDs `json:"known_trx"` 345 | KnownBlocks OrderedBlockIDs `json:"known_blocks"` 346 | } 347 | 348 | func (m *NoticeMessage) GetType() P2PMessageType { 349 | return NoticeMessageType 350 | } 351 | 352 | type SyncRequestMessage struct { 353 | StartBlock uint32 `json:"start_block"` 354 | EndBlock uint32 `json:"end_block"` 355 | } 356 | 357 | func (m *SyncRequestMessage) GetType() P2PMessageType { 358 | return SyncRequestMessageType 359 | } 360 | func (m *SyncRequestMessage) String() string { 361 | return fmt.Sprintf("SyncRequest: Start Block [%d] End Block [%d]", m.StartBlock, m.EndBlock) 362 | } 363 | 364 | type RequestMessage struct { 365 | ReqTrx OrderedBlockIDs `json:"req_trx"` 366 | ReqBlocks OrderedBlockIDs `json:"req_blocks"` 367 | } 368 | 369 | func (m *RequestMessage) GetType() P2PMessageType { 370 | return RequestMessageType 371 | } 372 | 373 | type SignedTransactionMessage struct { 374 | Signatures []ecc.Signature `json:"signatures"` 375 | ContextFreeData []byte `json:"context_free_data"` 376 | } 377 | 378 | type PackedTransactionMessage struct { 379 | PackedTransaction 380 | } 381 | 382 | func (m *PackedTransactionMessage) GetType() P2PMessageType { 383 | return PackedTransactionMessageType 384 | } 385 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/responses.go: -------------------------------------------------------------------------------- 1 | package eos 2 | 3 | import ( 4 | "encoding/hex" 5 | "encoding/json" 6 | "fmt" 7 | "reflect" 8 | 9 | "github.com/eoscanada/eos-go/ecc" 10 | ) 11 | 12 | /* 13 | { 14 | "server_version": "f537bc50", 15 | "head_block_num": 9, 16 | "last_irreversible_block_num": 8, 17 | "last_irreversible_block_id": "00000008f98f0580d7efe7abc60abaaf8a865c9428a4267df30ff7d1937a1084", 18 | "head_block_id": "00000009ecd0e9fb5719431f4b86f5c9ca1887f6b6f73e5a301aaff740fd6bd3", 19 | "head_block_time": "2018-05-19T07:47:31", 20 | "head_block_producer": "eosio", 21 | "virtual_block_cpu_limit": 100800, 22 | "virtual_block_net_limit": 1056996, 23 | "block_cpu_limit": 99900, 24 | "block_net_limit": 1048576 25 | } 26 | 27 | */ 28 | 29 | type InfoResp struct { 30 | ServerVersion string `json:"server_version"` // "2cc40a4e" 31 | ChainID SHA256Bytes `json:"chain_id"` 32 | HeadBlockNum uint32 `json:"head_block_num"` // 2465669, 33 | LastIrreversibleBlockNum uint32 `json:"last_irreversible_block_num"` // 2465655 34 | LastIrreversibleBlockID SHA256Bytes `json:"last_irreversible_block_id"` // "00000008f98f0580d7efe7abc60abaaf8a865c9428a4267df30ff7d1937a1084" 35 | HeadBlockID SHA256Bytes `json:"head_block_id"` // "00259f856bfa142d1d60aff77e70f0c4f3eab30789e9539d2684f9f8758f1b88", 36 | HeadBlockTime JSONTime `json:"head_block_time"` // "2018-02-02T04:19:32" 37 | HeadBlockProducer AccountName `json:"head_block_producer"` // "inita" 38 | 39 | VirtualBlockCPULimit uint64 `json:"virtual_block_cpu_limit"` 40 | VirtualBlockNetLimit uint64 `json:"virtual_block_net_limit"` 41 | BlockCPULimit uint64 `json:"block_cpu_limit"` 42 | BlockNetLimit uint64 `json:"block_net_limit"` 43 | } 44 | 45 | type BlockResp struct { 46 | SignedBlock 47 | ID SHA256Bytes `json:"id"` 48 | BlockNum uint32 `json:"block_num"` 49 | RefBlockPrefix uint32 `json:"ref_block_prefix"` 50 | BlockExtensions []*Extension `json:"block_extensions"` 51 | } 52 | 53 | // type BlockTransaction struct { 54 | // Status string `json:"status"` 55 | // CPUUsageUS int `json:"cpu_usage_us"` 56 | // NetUsageWords int `json:"net_usage_words"` 57 | // Trx []json.RawMessage `json:"trx"` 58 | // } 59 | 60 | type TransactionResp struct { 61 | ID SHA256Bytes `json:"id"` 62 | Receipt struct { 63 | Status TransactionStatus `json:"status"` 64 | CPUUsageMicrosec int `json:"cpu_usage_us"` 65 | NetUsageWords int `json:"net_usage_words"` 66 | PackedTransaction TransactionWithID `json:"trx"` 67 | } `json:"receipt"` 68 | Transaction ProcessedTransaction `json:"trx"` 69 | BlockTime JSONTime `json:"block_time"` 70 | BlockNum uint32 `json:"block_num"` 71 | LastIrreversibleBlock uint32 `json:"last_irreversible_block"` 72 | Traces []TransactionTrace `json:"traces"` 73 | } 74 | 75 | type ProcessedTransaction struct { 76 | Transaction SignedTransaction `json:"trx"` 77 | } 78 | 79 | type TransactionTrace struct { 80 | Receipt struct { 81 | Receiver AccountName `json:"receiver"` 82 | ActionDigest string `json:"act_digest"` 83 | GlobalSequence int64 `json:"global_sequence"` 84 | ReceiveSequence int64 `json:"recv_sequence"` 85 | AuthSequence []TransactionTraceAuthSequence `json:"auth_sequence"` // [["account", sequence], ["account", sequence]] 86 | CodeSequence int64 `json:"code_sequence"` 87 | ABISequence int64 `json:"abi_sequence"` 88 | } `json:"receipt"` 89 | Action *Action `json:"act"` 90 | Elapsed int `json:"elapsed"` 91 | CPUUsage int `json:"cpu_usage"` 92 | Console string `json:"console"` 93 | TotalCPUUsage int `json:"total_cpu_usage"` 94 | TransactionID SHA256Bytes `json:"trx_id"` 95 | InlineTraces []*TransactionTrace `json:"inline_traces"` 96 | } 97 | 98 | type TransactionTraceAuthSequence struct { 99 | Account AccountName 100 | Sequence int64 101 | } 102 | 103 | // [ ["account", 123123], ["account2", 345] ] 104 | func (auth *TransactionTraceAuthSequence) UnmarshalJSON(data []byte) error { 105 | var ins []interface{} 106 | if err := json.Unmarshal(data, &ins); err != nil { 107 | return err 108 | } 109 | 110 | if len(ins) != 2 { 111 | return fmt.Errorf("expected 2 items, received %d", len(ins)) 112 | } 113 | 114 | account, ok := ins[0].(string) 115 | if !ok { 116 | return fmt.Errorf("expected 1st item to be a string (account name)") 117 | } 118 | 119 | seq, ok := ins[1].(float64) 120 | if !ok { 121 | return fmt.Errorf("expected 2nd item to be a sequence number (float64)") 122 | } 123 | 124 | *auth = TransactionTraceAuthSequence{AccountName(account), int64(seq)} 125 | 126 | return nil 127 | } 128 | 129 | func (auth TransactionTraceAuthSequence) MarshalJSON() (data []byte, err error) { 130 | return json.Marshal([]interface{}{auth.Account, auth.Sequence}) 131 | } 132 | 133 | type SequencedTransactionResp struct { 134 | SeqNum int `json:"seq_num"` 135 | TransactionResp 136 | } 137 | 138 | type TransactionsResp struct { 139 | Transactions []SequencedTransactionResp 140 | } 141 | 142 | type ProducerChange struct { 143 | } 144 | 145 | type AccountResp struct { 146 | AccountName AccountName `json:"account_name"` 147 | Privileged bool `json:"privileged"` 148 | LastCodeUpdate JSONTime `json:"last_code_update"` 149 | Created JSONTime `json:"created"` 150 | RAMQuota int64 `json:"ram_quota"` 151 | RAMUsage int64 `json:"ram_usage"` 152 | NetWeight JSONInt64 `json:"net_weight"` 153 | CPUWeight JSONInt64 `json:"cpu_weight"` 154 | NetLimit AccountResourceLimit `json:"net_limit"` 155 | CPULimit AccountResourceLimit `json:"cpu_limit"` 156 | Permissions []Permission `json:"permissions"` 157 | TotalResources TotalResources `json:"total_resources"` 158 | DelegatedBandwidth DelegatedBandwidth `json:"delegated_bandwidth"` 159 | VoterInfo VoterInfo `json:"voter_info"` 160 | } 161 | 162 | type CurrencyBalanceResp struct { 163 | EOSBalance Asset `json:"eos_balance"` 164 | StakedBalance Asset `json:"staked_balance"` 165 | UnstakingBalance Asset `json:"unstaking_balance"` 166 | LastUnstakingTime JSONTime `json:"last_unstaking_time"` 167 | } 168 | 169 | type GetTableRowsRequest struct { 170 | JSON bool `json:"json"` 171 | Scope string `json:"scope"` 172 | Code string `json:"code"` 173 | Table string `json:"table"` 174 | TableKey string `json:"table_key"` 175 | LowerBound string `json:"lower_bound"` 176 | UpperBound string `json:"upper_bound"` 177 | Limit uint32 `json:"limit,omitempty"` // defaults to 10 => chain_plugin.hpp:struct get_table_rows_params 178 | } 179 | 180 | type GetTableRowsResp struct { 181 | More bool `json:"more"` 182 | Rows json.RawMessage `json:"rows"` // defer loading, as it depends on `JSON` being true/false. 183 | } 184 | 185 | func (resp *GetTableRowsResp) JSONToStructs(v interface{}) error { 186 | return json.Unmarshal(resp.Rows, v) 187 | } 188 | 189 | func (resp *GetTableRowsResp) BinaryToStructs(v interface{}) error { 190 | var rows []string 191 | 192 | err := json.Unmarshal(resp.Rows, &rows) 193 | if err != nil { 194 | return err 195 | } 196 | 197 | outSlice := reflect.ValueOf(v).Elem() 198 | structType := reflect.TypeOf(v).Elem().Elem() 199 | 200 | for _, row := range rows { 201 | bin, err := hex.DecodeString(row) 202 | if err != nil { 203 | return err 204 | } 205 | 206 | // access the type of the `Slice`, create a bunch of them.. 207 | newStruct := reflect.New(structType) 208 | 209 | decoder := NewDecoder(bin) 210 | if err := decoder.Decode(newStruct.Interface()); err != nil { 211 | return err 212 | } 213 | 214 | outSlice = reflect.Append(outSlice, reflect.Indirect(newStruct)) 215 | } 216 | 217 | reflect.ValueOf(v).Elem().Set(outSlice) 218 | 219 | return nil 220 | } 221 | 222 | type Currency struct { 223 | Precision uint8 224 | Name CurrencyName 225 | } 226 | 227 | type GetRequiredKeysResp struct { 228 | RequiredKeys []ecc.PublicKey `json:"required_keys"` 229 | } 230 | 231 | // PushTransactionFullResp unwraps the responses from a successful `push_transaction`. 232 | // FIXME: REVIEW the actual output, things have moved here. 233 | type PushTransactionFullResp struct { 234 | StatusCode string 235 | TransactionID string `json:"transaction_id"` 236 | Processed TransactionProcessed `json:"processed"` // WARN: is an `fc::variant` in server.. 237 | } 238 | 239 | type TransactionProcessed struct { 240 | Status string `json:"status"` 241 | ID SHA256Bytes `json:"id"` 242 | ActionTraces []ActionTrace `json:"action_traces"` 243 | DeferredTransactions []string `json:"deferred_transactions"` // that's not right... dig to find what's there.. 244 | } 245 | 246 | type ActionTrace struct { 247 | Receiver AccountName `json:"receiver"` 248 | // Action Action `json:"act"` // FIXME: how do we unpack that ? what's on the other side anyway? 249 | Console string `json:"console"` 250 | DataAccess []DataAccess `json:"data_access"` 251 | } 252 | 253 | type DataAccess struct { 254 | Type string `json:"type"` // "write", "read"? 255 | Code AccountName `json:"code"` 256 | Scope AccountName `json:"scope"` 257 | Sequence int `json:"sequence"` 258 | } 259 | 260 | type PushTransactionShortResp struct { 261 | TransactionID string `json:"transaction_id"` 262 | Processed bool `json:"processed"` // WARN: is an `fc::variant` in server.. 263 | } 264 | 265 | // 266 | 267 | type WalletSignTransactionResp struct { 268 | // Ignore the rest of the transaction, so the wallet server 269 | // doesn't forge some transactions on your behalf, and you send it 270 | // to the network.. ... although.. it's better if you can trust 271 | // your wallet ! 272 | 273 | Signatures []ecc.Signature `json:"signatures"` 274 | } 275 | 276 | type MyStruct struct { 277 | Currency 278 | Balance uint64 279 | } 280 | 281 | // NetConnectionResp 282 | type NetConnectionsResp struct { 283 | Peer string `json:"peer"` 284 | Connecting bool `json:"connecting"` 285 | Syncing bool `json:"syncing"` 286 | LastHandshake HandshakeMessage `json:"last_handshake"` 287 | } 288 | 289 | type NetStatusResp struct { 290 | } 291 | 292 | type NetConnectResp string 293 | 294 | type NetDisconnectResp string 295 | 296 | type Global struct { 297 | MaxBlockNetUsage int `json:"max_block_net_usage"` 298 | TargetBlockNetUsagePct int `json:"target_block_net_usage_pct"` 299 | MaxTransactionNetUsage int `json:"max_transaction_net_usage"` 300 | BasePerTransactionNetUsage int `json:"base_per_transaction_net_usage"` 301 | NetUsageLeeway int `json:"net_usage_leeway"` 302 | ContextFreeDiscountNetUsageNum int `json:"context_free_discount_net_usage_num"` 303 | ContextFreeDiscountNetUsageDen int `json:"context_free_discount_net_usage_den"` 304 | MaxBlockCPUUsage int `json:"max_block_cpu_usage"` 305 | TargetBlockCPUUsagePct int `json:"target_block_cpu_usage_pct"` 306 | MaxTransactionCPUUsage int `json:"max_transaction_cpu_usage"` 307 | MinTransactionCPUUsage int `json:"min_transaction_cpu_usage"` 308 | MaxTransactionLifetime int `json:"max_transaction_lifetime"` 309 | DeferredTrxExpirationWindow int `json:"deferred_trx_expiration_window"` 310 | MaxTransactionDelay int `json:"max_transaction_delay"` 311 | MaxInlineActionSize int `json:"max_inline_action_size"` 312 | MaxInlineActionDepth int `json:"max_inline_action_depth"` 313 | MaxAuthorityDepth int `json:"max_authority_depth"` 314 | MaxRAMSize string `json:"max_ram_size"` 315 | TotalRAMBytesReserved JSONInt64 `json:"total_ram_bytes_reserved"` 316 | TotalRAMStake JSONInt64 `json:"total_ram_stake"` 317 | LastProducerScheduleUpdate string `json:"last_producer_schedule_update"` 318 | LastPervoteBucketFill int64 `json:"last_pervote_bucket_fill,string"` 319 | PervoteBucket int `json:"pervote_bucket"` 320 | PerblockBucket int `json:"perblock_bucket"` 321 | TotalUnpaidBlocks int `json:"total_unpaid_blocks"` 322 | TotalActivatedStake float64 `json:"total_activated_stake,string"` 323 | ThreshActivatedStakeTime int64 `json:"thresh_activated_stake_time,string"` 324 | LastProducerScheduleSize int `json:"last_producer_schedule_size"` 325 | TotalProducerVoteWeight float64 `json:"total_producer_vote_weight,string"` 326 | LastNameClose string `json:"last_name_close"` 327 | } 328 | 329 | type Producer struct { 330 | Owner string `json:"owner"` 331 | TotalVotes float64 `json:"total_votes,string"` 332 | ProducerKey string `json:"producer_key"` 333 | IsActive int `json:"is_active"` 334 | URL string `json:"url"` 335 | UnpaidBlocks int `json:"unpaid_blocks"` 336 | LastClaimTime JSONFloat64 `json:"last_claim_time"` 337 | Location int `json:"location"` 338 | } 339 | type ProducersResp struct { 340 | Producers []Producer `json:"producers"` 341 | } 342 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/signer.go: -------------------------------------------------------------------------------- 1 | package eos 2 | 3 | import ( 4 | "crypto/sha256" 5 | "fmt" 6 | 7 | "os" 8 | 9 | "bufio" 10 | 11 | "strings" 12 | 13 | "github.com/eoscanada/eos-go/ecc" 14 | ) 15 | 16 | type Signer interface { 17 | AvailableKeys() (out []ecc.PublicKey, err error) 18 | 19 | // Sign signs a `tx` transaction. It gets passed a 20 | // SignedTransaction because it is possible that it holds a few 21 | // signatures and requests this wallet only to add one or more 22 | // signatures it requires. 23 | Sign(tx *SignedTransaction, chainID []byte, requiredKeys ...ecc.PublicKey) (*SignedTransaction, error) 24 | 25 | ImportPrivateKey(wifPrivKey string) error 26 | } 27 | 28 | // `eosiowd` wallet-based signer 29 | type WalletSigner struct { 30 | api *API 31 | walletName string 32 | } 33 | 34 | // NewWalletSigner takes an `api`, because often the wallet will be a 35 | // second endpoint, and not the server node with whom you're pushing 36 | // transactions to. 37 | func NewWalletSigner(api *API, walletName string) *WalletSigner { 38 | return &WalletSigner{api, walletName} 39 | } 40 | 41 | func (s *WalletSigner) ImportPrivateKey(wifKey string) (err error) { 42 | return s.api.WalletImportKey(s.walletName, wifKey) 43 | } 44 | 45 | func (s *WalletSigner) AvailableKeys() (out []ecc.PublicKey, err error) { 46 | return s.api.WalletPublicKeys() 47 | } 48 | 49 | func (s *WalletSigner) Sign(tx *SignedTransaction, chainID []byte, requiredKeys ...ecc.PublicKey) (*SignedTransaction, error) { 50 | // Fetch the available keys over there... and ask this wallet 51 | // provider to sign with the keys he has.. 52 | 53 | // TODO: If there's not a full overlap between the required keys 54 | // and the available keys, return something about 55 | // `SignatureIncomplete`. 56 | 57 | resp, err := s.api.WalletSignTransaction(tx, chainID, requiredKeys...) 58 | if err != nil { 59 | return nil, err 60 | } 61 | 62 | tx.Signatures = resp.Signatures 63 | 64 | return tx, nil 65 | } 66 | 67 | // KeyBag, local signing - NOT COMPLETE 68 | 69 | // KeyBag holds private keys in memory, for signing transactions. 70 | type KeyBag struct { 71 | Keys []*ecc.PrivateKey `json:"keys"` 72 | } 73 | 74 | func NewKeyBag() *KeyBag { 75 | return &KeyBag{ 76 | Keys: make([]*ecc.PrivateKey, 0), 77 | } 78 | } 79 | 80 | func (b *KeyBag) Add(wifKey string) error { 81 | privKey, err := ecc.NewPrivateKey(wifKey) 82 | if err != nil { 83 | return err 84 | } 85 | b.Keys = append(b.Keys, privKey) 86 | return nil 87 | } 88 | 89 | func (b *KeyBag) ImportFromFile(path string) error { 90 | inFile, err := os.Open(path) 91 | if err != nil { 92 | return fmt.Errorf("import keys from file [%s], %s", path, err) 93 | } 94 | defer inFile.Close() 95 | scanner := bufio.NewScanner(inFile) 96 | scanner.Split(bufio.ScanLines) 97 | 98 | for scanner.Scan() { 99 | key := strings.TrimSpace(strings.Split(scanner.Text(), " ")[0]) 100 | 101 | if strings.Contains(key, "/") || strings.Contains(key, "#") || strings.Contains(key, ";") { 102 | return fmt.Errorf("lines should consist of a private key on each line, with an optional whitespace and comment") 103 | } 104 | 105 | if err := b.Add(key); err != nil { 106 | return err 107 | } 108 | } 109 | return nil 110 | } 111 | 112 | func (b *KeyBag) AvailableKeys() (out []ecc.PublicKey, err error) { 113 | for _, k := range b.Keys { 114 | out = append(out, k.PublicKey()) 115 | } 116 | return 117 | } 118 | 119 | func (b *KeyBag) ImportPrivateKey(wifPrivKey string) (err error) { 120 | return b.Add(wifPrivKey) 121 | } 122 | 123 | func (b *KeyBag) SignDigest(digest []byte, requiredKey ecc.PublicKey) (ecc.Signature, error) { 124 | 125 | privateKey := b.keyMap()[requiredKey.String()] 126 | if privateKey == nil { 127 | return ecc.Signature{}, fmt.Errorf("private key not found for public key [%s]", requiredKey.String()) 128 | } 129 | 130 | return privateKey.Sign(digest) 131 | } 132 | 133 | func (b *KeyBag) Sign(tx *SignedTransaction, chainID []byte, requiredKeys ...ecc.PublicKey) (*SignedTransaction, error) { 134 | // TODO: probably want to use `tx.packed` and hash the ContextFreeData also. 135 | txdata, cfd, err := tx.PackedTransactionAndCFD() 136 | if err != nil { 137 | return nil, err 138 | } 139 | 140 | sigDigest := SigDigest(chainID, txdata, cfd) 141 | 142 | keyMap := b.keyMap() 143 | for _, key := range requiredKeys { 144 | privKey := keyMap[key.String()] 145 | if privKey == nil { 146 | return nil, fmt.Errorf("private key for %q not in keybag", key) 147 | } 148 | 149 | // fmt.Println("Signing with", key.String(), privKey.String()) 150 | // fmt.Println("SIGNING THIS DIGEST:", hex.EncodeToString(sigDigest)) 151 | // fmt.Println("SIGNING THIS payload:", hex.EncodeToString(txdata)) 152 | // fmt.Println("SIGNING THIS chainID:", hex.EncodeToString(chainID)) 153 | // fmt.Println("SIGNING THIS cfd:", hex.EncodeToString(cfd)) 154 | sig, err := privKey.Sign(sigDigest) 155 | if err != nil { 156 | return nil, err 157 | } 158 | 159 | tx.Signatures = append(tx.Signatures, sig) 160 | } 161 | 162 | // tmpcnt, _ := json.Marshal(tx) 163 | // var newTx *SignedTransaction 164 | // _ = json.Unmarshal(tmpcnt, &newTx) 165 | 166 | return tx, nil 167 | } 168 | 169 | func (b *KeyBag) keyMap() map[string]*ecc.PrivateKey { 170 | out := map[string]*ecc.PrivateKey{} 171 | for _, key := range b.Keys { 172 | out[key.PublicKey().String()] = key 173 | } 174 | return out 175 | } 176 | 177 | func SigDigest(chainID, payload, contextFreeData []byte) []byte { 178 | h := sha256.New() 179 | if len(chainID) == 0 { 180 | _, _ = h.Write(make([]byte, 32, 32)) 181 | } else { 182 | _, _ = h.Write(chainID) 183 | } 184 | _, _ = h.Write(payload) 185 | 186 | if len(contextFreeData) > 0 { 187 | h2 := sha256.New() 188 | _, _ = h2.Write(contextFreeData) 189 | _, _ = h.Write(h2.Sum(nil)) // add the hash of CFD to the payload 190 | } else { 191 | _, _ = h.Write(make([]byte, 32, 32)) 192 | } 193 | return h.Sum(nil) 194 | } 195 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/system/bidname.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import ( 4 | eos "github.com/eoscanada/eos-go" 5 | ) 6 | 7 | func NewBidname(bidder, newname eos.AccountName, bid eos.Asset) *eos.Action { 8 | a := &eos.Action{ 9 | Account: AN("eosio"), 10 | Name: ActN("bidname"), 11 | Authorization: []eos.PermissionLevel{ 12 | {Actor: bidder, Permission: PN("active")}, 13 | }, 14 | ActionData: eos.NewActionData(Bidname{ 15 | Bidder: bidder, 16 | Newname: newname, 17 | Bid: bid, 18 | }), 19 | } 20 | return a 21 | } 22 | 23 | // Bidname represents the `eosio.system_contract::bidname` action. 24 | type Bidname struct { 25 | Bidder eos.AccountName `json:"bidder"` 26 | Newname eos.AccountName `json:"newname"` 27 | Bid eos.Asset `json:"bid"` // specified in EOS 28 | } 29 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/system/buyram.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import ( 4 | eos "github.com/eoscanada/eos-go" 5 | ) 6 | 7 | func NewBuyRAM(payer, receiver eos.AccountName, eosQuantity uint64) *eos.Action { 8 | a := &eos.Action{ 9 | Account: AN("eosio"), 10 | Name: ActN("buyram"), 11 | Authorization: []eos.PermissionLevel{ 12 | {Actor: payer, Permission: PN("active")}, 13 | }, 14 | ActionData: eos.NewActionData(BuyRAM{ 15 | Payer: payer, 16 | Receiver: receiver, 17 | Quantity: eos.NewEOSAsset(int64(eosQuantity)), 18 | }), 19 | } 20 | return a 21 | } 22 | 23 | // BuyRAM represents the `eosio.system::buyram` action. 24 | type BuyRAM struct { 25 | Payer eos.AccountName `json:"payer"` 26 | Receiver eos.AccountName `json:"receiver"` 27 | Quantity eos.Asset `json:"quant"` // specified in EOS 28 | } 29 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/system/buyrambytes.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import ( 4 | eos "github.com/eoscanada/eos-go" 5 | ) 6 | 7 | // NewBuyRAMBytes will buy at current market price a given number of 8 | // bytes of RAM, and grant them to the `receiver` account. 9 | func NewBuyRAMBytes(payer, receiver eos.AccountName, bytes uint32) *eos.Action { 10 | a := &eos.Action{ 11 | Account: AN("eosio"), 12 | Name: ActN("buyrambytes"), 13 | Authorization: []eos.PermissionLevel{ 14 | {Actor: payer, Permission: eos.PermissionName("active")}, 15 | }, 16 | ActionData: eos.NewActionData(BuyRAMBytes{ 17 | Payer: payer, 18 | Receiver: receiver, 19 | Bytes: bytes, 20 | }), 21 | } 22 | return a 23 | } 24 | 25 | // BuyRAMBytes represents the `eosio.system::buyrambytes` action. 26 | type BuyRAMBytes struct { 27 | Payer eos.AccountName `json:"payer"` 28 | Receiver eos.AccountName `json:"receiver"` 29 | Bytes uint32 `json:"bytes"` 30 | } 31 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/system/claimrewards.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import ( 4 | eos "github.com/eoscanada/eos-go" 5 | ) 6 | 7 | // NewClaimRewards will buy at current market price a given number of 8 | // bytes of RAM, and grant them to the `receiver` account. 9 | func NewClaimRewards(owner eos.AccountName) *eos.Action { 10 | a := &eos.Action{ 11 | Account: AN("eosio"), 12 | Name: ActN("claimrewards"), 13 | Authorization: []eos.PermissionLevel{ 14 | {Actor: owner, Permission: eos.PermissionName("active")}, 15 | }, 16 | ActionData: eos.NewActionData(ClaimRewards{ 17 | Owner: owner, 18 | }), 19 | } 20 | return a 21 | } 22 | 23 | // ClaimRewards represents the `eosio.system::claimrewards` action. 24 | type ClaimRewards struct { 25 | Owner eos.AccountName `json:"owner"` 26 | } 27 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/system/delegatebw.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import ( 4 | eos "github.com/eoscanada/eos-go" 5 | ) 6 | 7 | // NewDelegateBW returns a `delegatebw` action that lives on the 8 | // `eosio.system` contract. 9 | func NewDelegateBW(from, receiver eos.AccountName, stakeCPU, stakeNet eos.Asset, transfer bool) *eos.Action { 10 | return &eos.Action{ 11 | Account: AN("eosio"), 12 | Name: ActN("delegatebw"), 13 | Authorization: []eos.PermissionLevel{ 14 | {Actor: from, Permission: PN("active")}, 15 | }, 16 | ActionData: eos.NewActionData(DelegateBW{ 17 | From: from, 18 | Receiver: receiver, 19 | StakeNet: stakeNet, 20 | StakeCPU: stakeCPU, 21 | Transfer: eos.Bool(transfer), 22 | }), 23 | } 24 | } 25 | 26 | // DelegateBW represents the `eosio.system::delegatebw` action. 27 | type DelegateBW struct { 28 | From eos.AccountName `json:"from"` 29 | Receiver eos.AccountName `json:"receiver"` 30 | StakeNet eos.Asset `json:"stake_net"` 31 | StakeCPU eos.Asset `json:"stake_cpu"` 32 | Transfer eos.Bool `json:"transfer"` 33 | } 34 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/system/init.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import ( 4 | "github.com/eoscanada/eos-go" 5 | ) 6 | 7 | func init() { 8 | eos.RegisterAction(AN("eosio"), ActN("setcode"), SetCode{}) 9 | eos.RegisterAction(AN("eosio"), ActN("setabi"), SetABI{}) 10 | eos.RegisterAction(AN("eosio"), ActN("newaccount"), NewAccount{}) 11 | eos.RegisterAction(AN("eosio"), ActN("delegatebw"), DelegateBW{}) 12 | eos.RegisterAction(AN("eosio"), ActN("undelegatebw"), UndelegateBW{}) 13 | eos.RegisterAction(AN("eosio"), ActN("refund"), Refund{}) 14 | eos.RegisterAction(AN("eosio"), ActN("regproducer"), RegProducer{}) 15 | eos.RegisterAction(AN("eosio"), ActN("unregprod"), UnregProducer{}) 16 | eos.RegisterAction(AN("eosio"), ActN("regproxy"), RegProxy{}) 17 | eos.RegisterAction(AN("eosio"), ActN("unregproxy"), UnregProxy{}) 18 | eos.RegisterAction(AN("eosio"), ActN("voteproducer"), VoteProducer{}) 19 | eos.RegisterAction(AN("eosio"), ActN("claimrewards"), ClaimRewards{}) 20 | eos.RegisterAction(AN("eosio"), ActN("buyram"), BuyRAM{}) 21 | eos.RegisterAction(AN("eosio"), ActN("buyrambytes"), BuyRAMBytes{}) 22 | // eos.RegisterAction(AN("eosio"), ActN("nonce"), &Nonce{}) 23 | } 24 | 25 | var AN = eos.AN 26 | var PN = eos.PN 27 | var ActN = eos.ActN 28 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/system/newaccount.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import ( 4 | "github.com/eoscanada/eos-go" 5 | "github.com/eoscanada/eos-go/ecc" 6 | ) 7 | 8 | // NewNewAccount returns a `newaccount` action that lives on the 9 | // `eosio.system` contract. 10 | func NewNewAccount(creator, newAccount eos.AccountName, publicKey ecc.PublicKey) *eos.Action { 11 | return &eos.Action{ 12 | Account: AN("eosio"), 13 | Name: ActN("newaccount"), 14 | Authorization: []eos.PermissionLevel{ 15 | {Actor: creator, Permission: PN("active")}, 16 | }, 17 | ActionData: eos.NewActionData(NewAccount{ 18 | Creator: creator, 19 | Name: newAccount, 20 | Owner: eos.Authority{ 21 | Threshold: 1, 22 | Keys: []eos.KeyWeight{ 23 | { 24 | PublicKey: publicKey, 25 | Weight: 1, 26 | }, 27 | }, 28 | Accounts: []eos.PermissionLevelWeight{}, 29 | }, 30 | Active: eos.Authority{ 31 | Threshold: 1, 32 | Keys: []eos.KeyWeight{ 33 | { 34 | PublicKey: publicKey, 35 | Weight: 1, 36 | }, 37 | }, 38 | Accounts: []eos.PermissionLevelWeight{}, 39 | }, 40 | }), 41 | } 42 | } 43 | 44 | // NewDelegatedNewAccount returns a `newaccount` action that lives on the 45 | // `eosio.system` contract. It is filled with an authority structure that 46 | // delegates full control of the new account to an already existing account. 47 | func NewDelegatedNewAccount(creator, newAccount eos.AccountName, delegatedTo eos.AccountName) *eos.Action { 48 | return &eos.Action{ 49 | Account: AN("eosio"), 50 | Name: ActN("newaccount"), 51 | Authorization: []eos.PermissionLevel{ 52 | {Actor: creator, Permission: PN("active")}, 53 | }, 54 | ActionData: eos.NewActionData(NewAccount{ 55 | Creator: creator, 56 | Name: newAccount, 57 | Owner: eos.Authority{ 58 | Threshold: 1, 59 | Keys: []eos.KeyWeight{}, 60 | Accounts: []eos.PermissionLevelWeight{ 61 | eos.PermissionLevelWeight{ 62 | Permission: eos.PermissionLevel{ 63 | Actor: delegatedTo, 64 | Permission: PN("active"), 65 | }, 66 | Weight: 1, 67 | }, 68 | }, 69 | }, 70 | Active: eos.Authority{ 71 | Threshold: 1, 72 | Keys: []eos.KeyWeight{}, 73 | Accounts: []eos.PermissionLevelWeight{ 74 | eos.PermissionLevelWeight{ 75 | Permission: eos.PermissionLevel{ 76 | Actor: delegatedTo, 77 | Permission: PN("active"), 78 | }, 79 | Weight: 1, 80 | }, 81 | }, 82 | }, 83 | }), 84 | } 85 | } 86 | 87 | // NewCustomNewAccount returns a `newaccount` action that lives on the 88 | // `eosio.system` contract. You can specify your own `owner` and 89 | // `active` permissions. 90 | func NewCustomNewAccount(creator, newAccount eos.AccountName, owner, active eos.Authority) *eos.Action { 91 | return &eos.Action{ 92 | Account: AN("eosio"), 93 | Name: ActN("newaccount"), 94 | Authorization: []eos.PermissionLevel{ 95 | {Actor: creator, Permission: PN("active")}, 96 | }, 97 | ActionData: eos.NewActionData(NewAccount{ 98 | Creator: creator, 99 | Name: newAccount, 100 | Owner: owner, 101 | Active: active, 102 | }), 103 | } 104 | } 105 | 106 | // NewAccount represents a `newaccount` action on the `eosio.system` 107 | // contract. It is one of the rare ones to be hard-coded into the 108 | // blockchain. 109 | type NewAccount struct { 110 | Creator eos.AccountName `json:"creator"` 111 | Name eos.AccountName `json:"name"` 112 | Owner eos.Authority `json:"owner"` 113 | Active eos.Authority `json:"active"` 114 | } 115 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/system/nonce.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import "github.com/eoscanada/eos-go" 4 | 5 | // NewNonce returns a `nonce` action that lives on the 6 | // `eosio.bios` contract. It should exist only when booting a new 7 | // network, as it is replaced using the `eos-bios` boot process by the 8 | // `eosio.system` contract. 9 | func NewNonce(nonce string) *eos.Action { 10 | a := &eos.Action{ 11 | Account: AN("eosio"), 12 | Name: ActN("nonce"), 13 | Authorization: []eos.PermissionLevel{ 14 | //{Actor: AN("eosio"), Permission: PN("active")}, 15 | }, 16 | ActionData: eos.NewActionData(Nonce{ 17 | Value: nonce, 18 | }), 19 | } 20 | return a 21 | } 22 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/system/refund.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import ( 4 | eos "github.com/eoscanada/eos-go" 5 | ) 6 | 7 | // NewRefund returns a `refund` action that lives on the 8 | // `eosio.system` contract. 9 | func NewRefund(owner eos.AccountName) *eos.Action { 10 | return &eos.Action{ 11 | Account: AN("eosio"), 12 | Name: ActN("refund"), 13 | Authorization: []eos.PermissionLevel{ 14 | {Actor: owner, Permission: PN("active")}, 15 | }, 16 | ActionData: eos.NewActionData(Refund{ 17 | Owner: owner, 18 | }), 19 | } 20 | } 21 | 22 | // Refund represents the `eosio.system::refund` action 23 | type Refund struct { 24 | Owner eos.AccountName `json:"owner"` 25 | } 26 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/system/regproducer.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import ( 4 | eos "github.com/eoscanada/eos-go" 5 | "github.com/eoscanada/eos-go/ecc" 6 | ) 7 | 8 | // NewRegProducer returns a `regproducer` action that lives on the 9 | // `eosio.system` contract. 10 | func NewRegProducer(producer eos.AccountName, producerKey ecc.PublicKey, url string) *eos.Action { 11 | return &eos.Action{ 12 | Account: AN("eosio"), 13 | Name: ActN("regproducer"), 14 | Authorization: []eos.PermissionLevel{ 15 | {Actor: producer, Permission: PN("active")}, 16 | }, 17 | ActionData: eos.NewActionData(RegProducer{ 18 | Producer: producer, 19 | ProducerKey: producerKey, 20 | URL: url, 21 | Location: 0, 22 | }), 23 | } 24 | } 25 | 26 | // RegProducer represents the `eosio.system::regproducer` action 27 | type RegProducer struct { 28 | Producer eos.AccountName `json:"producer"` 29 | ProducerKey ecc.PublicKey `json:"producer_key"` 30 | URL string `json:"url"` 31 | Location uint16 `json:"location"` // what,s the meaning of that anyway ? 32 | } 33 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/system/regproxy.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import ( 4 | eos "github.com/eoscanada/eos-go" 5 | ) 6 | 7 | // NewRegProxy returns a `regproxy` action that lives on the 8 | // `eosio.system` contract. 9 | func NewRegProxy(proxy eos.AccountName, isProxy bool) *eos.Action { 10 | return &eos.Action{ 11 | Account: AN("eosio"), 12 | Name: ActN("regproxy"), 13 | Authorization: []eos.PermissionLevel{ 14 | {Actor: proxy, Permission: PN("active")}, 15 | }, 16 | ActionData: eos.NewActionData(RegProxy{ 17 | Proxy: proxy, 18 | IsProxy: isProxy, 19 | }), 20 | } 21 | } 22 | 23 | // RegProxy represents the `eosio.system::regproxy` action 24 | type RegProxy struct { 25 | Proxy eos.AccountName `json:"proxy"` 26 | IsProxy bool `json:"isproxy"` 27 | } 28 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/system/rmvproducer.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import ( 4 | eos "github.com/eoscanada/eos-go" 5 | ) 6 | 7 | // NewRemoveProducer returns a `rmvproducer` action that lives on the 8 | // `eosio.system` contract. This is to be called by the consortium of 9 | // BPs, to oust a BP from its place. If you want to unregister 10 | // yourself as a BP, use `unregprod`. 11 | func NewRemoveProducer(producer eos.AccountName) *eos.Action { 12 | return &eos.Action{ 13 | Account: AN("eosio"), 14 | Name: ActN("rmvproducer"), 15 | Authorization: []eos.PermissionLevel{ 16 | {Actor: AN("eosio"), Permission: PN("active")}, 17 | }, 18 | ActionData: eos.NewActionData(RemoveProducer{ 19 | Producer: producer, 20 | }), 21 | } 22 | } 23 | 24 | // RemoveProducer represents the `eosio.system::rmvproducer` action 25 | type RemoveProducer struct { 26 | Producer eos.AccountName `json:"producer"` 27 | } 28 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/system/setcode.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io/ioutil" 7 | 8 | eos "github.com/eoscanada/eos-go" 9 | ) 10 | 11 | func NewSetCodeTx(account eos.AccountName, wasmPath, abiPath string) (out *eos.Transaction, err error) { 12 | codeContent, err := ioutil.ReadFile(wasmPath) 13 | if err != nil { 14 | return nil, err 15 | } 16 | 17 | abiContent, err := ioutil.ReadFile(abiPath) 18 | if err != nil { 19 | return nil, err 20 | } 21 | 22 | var abiDef eos.ABI 23 | if err := json.Unmarshal(abiContent, &abiDef); err != nil { 24 | return nil, fmt.Errorf("unmarshal ABI file: %s", err) 25 | } 26 | 27 | abiPacked, err := eos.MarshalBinary(abiDef) 28 | if err != nil { 29 | return nil, fmt.Errorf("packing ABI: %s", err) 30 | } 31 | 32 | actions := []*eos.Action{ 33 | { 34 | Account: AN("eosio"), 35 | Name: ActN("setcode"), 36 | Authorization: []eos.PermissionLevel{ 37 | {account, eos.PermissionName("active")}, 38 | }, 39 | ActionData: eos.NewActionData(SetCode{ 40 | Account: account, 41 | VMType: 0, 42 | VMVersion: 0, 43 | Code: eos.HexBytes(codeContent), 44 | }), 45 | }, 46 | { 47 | Account: AN("eosio"), 48 | Name: ActN("setabi"), 49 | Authorization: []eos.PermissionLevel{ 50 | {account, eos.PermissionName("active")}, 51 | }, 52 | ActionData: eos.NewActionData(SetABI{ 53 | Account: account, 54 | ABI: eos.HexBytes(abiPacked), 55 | }), 56 | }, 57 | } 58 | return &eos.Transaction{Actions: actions}, nil 59 | } 60 | 61 | // SetCode represents the hard-coded `setcode` action. 62 | type SetCode struct { 63 | Account eos.AccountName `json:"account"` 64 | VMType byte `json:"vmtype"` 65 | VMVersion byte `json:"vmversion"` 66 | Code eos.HexBytes `json:"code"` 67 | } 68 | 69 | // SetABI represents the hard-coded `setabi` action. 70 | type SetABI struct { 71 | Account eos.AccountName `json:"account"` 72 | ABI eos.HexBytes `json:"abi"` 73 | } 74 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/system/setpriv.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import eos "github.com/eoscanada/eos-go" 4 | 5 | // NewSetPriv returns a `setpriv` action that lives on the 6 | // `eosio.bios` contract. It should exist only when booting a new 7 | // network, as it is replaced using the `eos-bios` boot process by the 8 | // `eosio.system` contract. 9 | func NewSetPriv(account eos.AccountName) *eos.Action { 10 | a := &eos.Action{ 11 | Account: AN("eosio"), 12 | Name: ActN("setpriv"), 13 | Authorization: []eos.PermissionLevel{ 14 | {Actor: AN("eosio"), Permission: PN("active")}, 15 | }, 16 | ActionData: eos.NewActionData(SetPriv{ 17 | Account: account, 18 | IsPriv: true, 19 | }), 20 | } 21 | return a 22 | } 23 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/system/setprods.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import eos "github.com/eoscanada/eos-go" 4 | 5 | // NewSetPriv returns a `setpriv` action that lives on the 6 | // `eosio.bios` contract. It should exist only when booting a new 7 | // network, as it is replaced using the `eos-bios` boot process by the 8 | // `eosio.system` contract. 9 | func NewSetProds(producers []ProducerKey) *eos.Action { 10 | a := &eos.Action{ 11 | Account: AN("eosio"), 12 | Name: ActN("setprods"), 13 | Authorization: []eos.PermissionLevel{ 14 | {Actor: AN("eosio"), Permission: PN("active")}, 15 | }, 16 | ActionData: eos.NewActionData(SetProds{ 17 | Schedule: producers, 18 | }), 19 | } 20 | return a 21 | } 22 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/system/setram.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import ( 4 | eos "github.com/eoscanada/eos-go" 5 | ) 6 | 7 | func NewSetRAM(maxRAMSize uint64) *eos.Action { 8 | a := &eos.Action{ 9 | Account: AN("eosio"), 10 | Name: ActN("setram"), 11 | Authorization: []eos.PermissionLevel{ 12 | {AN("eosio"), eos.PermissionName("active")}, 13 | }, 14 | ActionData: eos.NewActionData(SetRAM{ 15 | MaxRAMSize: maxRAMSize, 16 | }), 17 | } 18 | return a 19 | } 20 | 21 | // SetRAM represents the hard-coded `setram` action. 22 | type SetRAM struct { 23 | MaxRAMSize uint64 `json:"max_ram_size"` 24 | } 25 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/system/types.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import ( 4 | eos "github.com/eoscanada/eos-go" 5 | "github.com/eoscanada/eos-go/ecc" 6 | ) 7 | 8 | // SetPriv sets privileged account status. Used in the bios boot mechanism. 9 | type SetPriv struct { 10 | Account eos.AccountName `json:"account"` 11 | IsPriv bool `json:"is_priv"` 12 | } 13 | 14 | // SetProds is present in `eosio.bios` contract. Used only at boot time. 15 | type SetProds struct { 16 | Schedule []ProducerKey `json:"schedule"` 17 | } 18 | 19 | type ProducerKey struct { 20 | ProducerName eos.AccountName `json:"producer_name"` 21 | BlockSigningKey ecc.PublicKey `json:"block_signing_key"` 22 | } 23 | 24 | // BlockchainParameters are all the params we can set through `setparams`. 25 | type BlockchainParameters struct { 26 | MaxBlockNetUsage uint64 `json:"max_block_net_usage"` 27 | TargetBlockNetUsagePct uint32 `json:"target_block_net_usage_pct"` 28 | MaxTransactionNetUsage uint32 `json:"max_transaction_net_usage"` 29 | BasePerTransactionNetUsage uint32 `json:"base_per_transaction_net_usage"` 30 | NetUsageLeeway uint32 `json:"net_usage_leeway"` 31 | ContextFreeDiscountNetUsageNum uint32 `json:"context_free_discount_net_usage_num"` 32 | ContextFreeDiscountNetUsageDen uint32 `json:"context_free_discount_net_usage_den"` 33 | MaxBlockCPUUsage uint32 `json:"max_block_cpu_usage"` 34 | TargetBlockCPUUsagePct uint32 `json:"target_block_cpu_usage_pct"` 35 | MaxTransactionCPUUsage uint32 `json:"max_transaction_cpu_usage"` 36 | MinTransactionCPUUsage uint32 `json:"min_transaction_cpu_usage"` 37 | MaxTransactionLifetime uint32 `json:"max_transaction_lifetime"` 38 | DeferredTrxExpirationWindow uint32 `json:"deferred_trx_expiration_window"` 39 | MaxTransactionDelay uint32 `json:"max_transaction_delay"` 40 | MaxInlineActionSize uint32 `json:"max_inline_action_size"` 41 | MaxInlineActionDepth uint16 `json:"max_inline_action_depth"` 42 | MaxAuthorityDepth uint16 `json:"max_authority_depth"` 43 | MaxGeneratedTransactionCount uint32 `json:"max_generated_transaction_count"` 44 | 45 | // replace-regexp \(\w\)_\(\w\) -> \1\,(upcase \2) 46 | // then Cpu -> CPU 47 | } 48 | 49 | type EOSIOGlobalState struct { 50 | BlockchainParameters 51 | TotalStorageBytesReserved uint64 `json:"total_storage_bytes_reserved"` 52 | TotalStorageStake uint64 `json:"total_storage_stake"` 53 | PaymentPerBlock uint64 `json:"payment_per_block"` 54 | } 55 | 56 | // UnregProxy represents the `eosio.system::unregproxy` action 57 | type UnregProxy struct { 58 | Proxy eos.AccountName `json:"proxy"` 59 | } 60 | 61 | // Nonce represents the `eosio.system::nonce` action. It is used to 62 | // add variability in a transaction, so you can send the same many 63 | // times in the same block, without it having the same Tx hash. 64 | type Nonce struct { 65 | Value string `json:"value"` 66 | } 67 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/system/undelegatebw.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import ( 4 | eos "github.com/eoscanada/eos-go" 5 | ) 6 | 7 | // NewUndelegateBW returns a `undelegatebw` action that lives on the 8 | // `eosio.system` contract. 9 | func NewUndelegateBW(from, receiver eos.AccountName, unstakeCPU, unstakeNet eos.Asset) *eos.Action { 10 | return &eos.Action{ 11 | Account: AN("eosio"), 12 | Name: ActN("undelegatebw"), 13 | Authorization: []eos.PermissionLevel{ 14 | {Actor: from, Permission: PN("active")}, 15 | }, 16 | ActionData: eos.NewActionData(UndelegateBW{ 17 | From: from, 18 | Receiver: receiver, 19 | UnstakeNet: unstakeNet, 20 | UnstakeCPU: unstakeCPU, 21 | }), 22 | } 23 | } 24 | 25 | // UndelegateBW represents the `eosio.system::undelegatebw` action. 26 | type UndelegateBW struct { 27 | From eos.AccountName `json:"from"` 28 | Receiver eos.AccountName `json:"receiver"` 29 | UnstakeNet eos.Asset `json:"unstake_net_quantity"` 30 | UnstakeCPU eos.Asset `json:"unstake_cpu_quantity"` 31 | } 32 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/system/unregprod.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import ( 4 | eos "github.com/eoscanada/eos-go" 5 | ) 6 | 7 | // NewUnregProducer returns a `unregprod` action that lives on the 8 | // `eosio.system` contract. 9 | func NewUnregProducer(producer eos.AccountName) *eos.Action { 10 | return &eos.Action{ 11 | Account: AN("eosio"), 12 | Name: ActN("unregprod"), 13 | Authorization: []eos.PermissionLevel{ 14 | {Actor: producer, Permission: PN("active")}, 15 | }, 16 | ActionData: eos.NewActionData(UnregProducer{ 17 | Producer: producer, 18 | }), 19 | } 20 | } 21 | 22 | // UnregProducer represents the `eosio.system::unregprod` action 23 | type UnregProducer struct { 24 | Producer eos.AccountName `json:"producer"` 25 | } 26 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/system/updateauth.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import "github.com/eoscanada/eos-go" 4 | 5 | // NewUpdateAuth creates an action from the `eosio.system` contract 6 | // called `updateauth`. 7 | // 8 | // usingPermission needs to be `owner` if you want to modify the 9 | // `owner` authorization, otherwise `active` will do for the rest. 10 | func NewUpdateAuth(account eos.AccountName, permission, parent eos.PermissionName, authority eos.Authority, usingPermission eos.PermissionName) *eos.Action { 11 | a := &eos.Action{ 12 | Account: AN("eosio"), 13 | Name: ActN("updateauth"), 14 | Authorization: []eos.PermissionLevel{ 15 | {account, usingPermission}, 16 | }, 17 | ActionData: eos.NewActionData(UpdateAuth{ 18 | Account: account, 19 | Permission: permission, 20 | Parent: parent, 21 | Auth: authority, 22 | }), 23 | } 24 | 25 | return a 26 | } 27 | 28 | // UpdateAuth represents the hard-coded `updateauth` action. 29 | // 30 | // If you change the `active` permission, `owner` is the required parent. 31 | // 32 | // If you change the `owner` permission, there should be no parent. 33 | type UpdateAuth struct { 34 | Account eos.AccountName `json:"account"` 35 | Permission eos.PermissionName `json:"permission"` 36 | Parent eos.PermissionName `json:"parent"` 37 | Auth eos.Authority `json:"auth"` 38 | } 39 | 40 | /** 41 | 42 | 42a3be5a00000100e543ae35 43 | 0000 44 | 0000 45 | 00 46 | 02 47 | 48 | ACTION 1 49 | 0000000000ea3055 eosio 50 | 0040cbdaa86c52d5 updateauth 51 | 01 52 | 0000000000ea3055 eosio 53 | 00000000a8ed3232 active 54 | 1e len 55 | 0000000000ea3055 eosio 56 | 00000000a8ed3232 active 57 | 0000000080ab26a7 owner 58 | 00000000 threshold 59 | 00 60 | 00 61 | 62 | ACTION 2 63 | 0000000000ea3055 eosio 64 | 0040cbdaa86c52d5 updateauth 65 | 01 66 | 0000000000ea3055 67 | 00000000a8ed3232 68 | 1e len 69 | 0000000000ea3055 eosio 70 | 0000000080ab26a7 owner 71 | 0000000000000000 NONE (parent empty) 72 | 00000000 73 | 00 74 | 00 75 | 76 | 77 | 0000000000ea3055 eosio 78 | 00000000a8ed3232 active 79 | 0000000080ab26a7 owner 80 | 00000000 81 | 00 82 | 00 83 | */ 84 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/system/voteproducer.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import "github.com/eoscanada/eos-go" 4 | 5 | // NewNonce returns a `nonce` action that lives on the 6 | // `eosio.bios` contract. It should exist only when booting a new 7 | // network, as it is replaced using the `eos-bios` boot process by the 8 | // `eosio.system` contract. 9 | func NewVoteProducer(voter eos.AccountName, proxy eos.AccountName, producers ...eos.AccountName) *eos.Action { 10 | a := &eos.Action{ 11 | Account: AN("eosio"), 12 | Name: ActN("voteproducer"), 13 | Authorization: []eos.PermissionLevel{ 14 | {Actor: voter, Permission: PN("active")}, 15 | }, 16 | ActionData: eos.NewActionData( 17 | VoteProducer{ 18 | Voter: voter, 19 | Proxy: proxy, 20 | Producers: producers, 21 | }, 22 | ), 23 | } 24 | return a 25 | } 26 | 27 | // VoteProducer represents the `eosio.system::voteproducer` action 28 | type VoteProducer struct { 29 | Voter eos.AccountName `json:"voter"` 30 | Proxy eos.AccountName `json:"proxy"` 31 | Producers []eos.AccountName `json:"producers"` 32 | } 33 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/transaction.go: -------------------------------------------------------------------------------- 1 | package eos 2 | 3 | import ( 4 | "bytes" 5 | "compress/flate" 6 | "compress/zlib" 7 | "crypto/sha256" 8 | "encoding/binary" 9 | "errors" 10 | "fmt" 11 | "time" 12 | 13 | "io" 14 | 15 | "encoding/json" 16 | 17 | "io/ioutil" 18 | 19 | "github.com/eoscanada/eos-go/ecc" 20 | ) 21 | 22 | type TransactionHeader struct { 23 | Expiration JSONTime `json:"expiration"` 24 | RefBlockNum uint16 `json:"ref_block_num"` 25 | RefBlockPrefix uint32 `json:"ref_block_prefix"` 26 | 27 | MaxNetUsageWords Varuint32 `json:"max_net_usage_words"` 28 | MaxCPUUsageMS uint8 `json:"max_cpu_usage_ms"` 29 | DelaySec Varuint32 `json:"delay_sec"` // number of secs to delay, making it cancellable for that duration 30 | } 31 | 32 | type Transaction struct { // WARN: is a `variant` in C++, can be a SignedTransaction or a Transaction. 33 | TransactionHeader 34 | 35 | ContextFreeActions []*Action `json:"context_free_actions"` 36 | Actions []*Action `json:"actions"` 37 | Extensions []*Extension `json:"transaction_extensions"` 38 | } 39 | 40 | // NewTransaction creates a transaction. Unless you plan on adding HeadBlockID later, to be complete, opts should contain it. Sign 41 | func NewTransaction(actions []*Action, opts *TxOptions) *Transaction { 42 | if opts == nil { 43 | opts = &TxOptions{} 44 | } 45 | 46 | tx := &Transaction{Actions: actions} 47 | tx.Fill(opts.HeadBlockID, opts.DelaySecs, opts.MaxNetUsageWords, opts.MaxCPUUsageMS) 48 | return tx 49 | } 50 | 51 | type Extension struct { 52 | Type uint16 `json:"type"` 53 | Data HexBytes `json:"data"` 54 | } 55 | 56 | // Fill sets the fields on a transaction. If you pass `headBlockID`, then `api` can be nil. If you don't pass `headBlockID`, then the `api` is going to be called to fetch 57 | func (tx *Transaction) Fill(headBlockID SHA256Bytes, delaySecs, maxNetUsageWords uint32, maxCPUUsageMS uint8) { 58 | tx.setRefBlock(headBlockID) 59 | 60 | if tx.ContextFreeActions == nil { 61 | tx.ContextFreeActions = make([]*Action, 0, 0) 62 | } 63 | if tx.Extensions == nil { 64 | tx.Extensions = make([]*Extension, 0, 0) 65 | } 66 | 67 | tx.MaxNetUsageWords = Varuint32(maxNetUsageWords) 68 | tx.MaxCPUUsageMS = maxCPUUsageMS 69 | tx.DelaySec = Varuint32(delaySecs) 70 | 71 | tx.Expiration = JSONTime{time.Now().UTC().Add(30 * time.Second)} 72 | } 73 | 74 | func (tx *Transaction) setRefBlock(blockID []byte) { 75 | tx.RefBlockNum = uint16(binary.BigEndian.Uint32(blockID[:4])) 76 | tx.RefBlockPrefix = binary.LittleEndian.Uint32(blockID[8:16]) 77 | } 78 | 79 | type SignedTransaction struct { 80 | *Transaction 81 | 82 | Signatures []ecc.Signature `json:"signatures"` 83 | ContextFreeData []HexBytes `json:"context_free_data"` 84 | 85 | packed *PackedTransaction 86 | } 87 | 88 | func NewSignedTransaction(tx *Transaction) *SignedTransaction { 89 | return &SignedTransaction{ 90 | Transaction: tx, 91 | Signatures: make([]ecc.Signature, 0), 92 | ContextFreeData: make([]HexBytes, 0), 93 | } 94 | } 95 | 96 | func (s *SignedTransaction) String() string { 97 | 98 | data, err := json.Marshal(s) 99 | if err != nil { 100 | return err.Error() 101 | } 102 | return string(data) 103 | } 104 | 105 | func (s *SignedTransaction) SignedByKeys(chainID SHA256Bytes) (out []ecc.PublicKey, err error) { 106 | trx, cfd, err := s.PackedTransactionAndCFD() 107 | if err != nil { 108 | return 109 | } 110 | 111 | for _, sig := range s.Signatures { 112 | pubKey, err := sig.PublicKey(SigDigest(chainID, trx, cfd)) 113 | if err != nil { 114 | return nil, err 115 | } 116 | 117 | out = append(out, pubKey) 118 | } 119 | 120 | return 121 | } 122 | 123 | func (s *SignedTransaction) PackedTransactionAndCFD() ([]byte, []byte, error) { 124 | rawtrx, err := MarshalBinary(s.Transaction) 125 | if err != nil { 126 | return nil, nil, err 127 | } 128 | 129 | rawcfd := []byte{} 130 | if len(s.ContextFreeData) > 0 { 131 | rawcfd, err = MarshalBinary(s.ContextFreeData) 132 | if err != nil { 133 | return nil, nil, err 134 | } 135 | } 136 | 137 | return rawtrx, rawcfd, nil 138 | } 139 | 140 | func (tx *Transaction) ID() string { 141 | return "ID here" //todo 142 | } 143 | 144 | func (s *SignedTransaction) Pack(compression CompressionType) (*PackedTransaction, error) { 145 | rawtrx, rawcfd, err := s.PackedTransactionAndCFD() 146 | if err != nil { 147 | return nil, err 148 | } 149 | 150 | switch compression { 151 | case CompressionZlib: 152 | var trx bytes.Buffer 153 | var cfd bytes.Buffer 154 | 155 | // Compress Trx 156 | writer, _ := zlib.NewWriterLevel(&trx, flate.BestCompression) // can only fail if invalid `level`.. 157 | writer.Write(rawtrx) // ignore error, could only bust memory 158 | rawtrx = trx.Bytes() 159 | 160 | // Compress ContextFreeData 161 | writer, _ = zlib.NewWriterLevel(&cfd, flate.BestCompression) // can only fail if invalid `level`.. 162 | writer.Write(rawcfd) // ignore errors, memory errors only 163 | rawcfd = cfd.Bytes() 164 | 165 | } 166 | 167 | packed := &PackedTransaction{ 168 | Signatures: s.Signatures, 169 | Compression: compression, 170 | PackedContextFreeData: rawcfd, 171 | PackedTransaction: rawtrx, 172 | } 173 | 174 | return packed, nil 175 | } 176 | 177 | // PackedTransaction represents a fully packed transaction, with 178 | // signatures, and all. They circulate like that on the P2P net, and 179 | // that's how they are stored. 180 | type PackedTransaction struct { 181 | Signatures []ecc.Signature `json:"signatures"` 182 | Compression CompressionType `json:"compression"` // in C++, it's an enum, not sure how it Binary-marshals.. 183 | PackedContextFreeData HexBytes `json:"packed_context_free_data"` 184 | PackedTransaction HexBytes `json:"packed_trx"` 185 | } 186 | 187 | func (p *PackedTransaction) ID() SHA256Bytes { 188 | h := sha256.New() 189 | _, _ = h.Write(p.PackedTransaction) 190 | return h.Sum(nil) 191 | } 192 | 193 | func (p *PackedTransaction) Unpack() (signedTx *SignedTransaction, err error) { 194 | var txReader io.Reader 195 | txReader = bytes.NewBuffer(p.PackedTransaction) 196 | 197 | var freeDataReader io.Reader 198 | freeDataReader = bytes.NewBuffer(p.PackedContextFreeData) 199 | 200 | switch p.Compression { 201 | case CompressionZlib: 202 | txReader, err = zlib.NewReader(txReader) 203 | if err != nil { 204 | return 205 | } 206 | 207 | freeDataReader, err = zlib.NewReader(freeDataReader) 208 | if err != nil { 209 | return 210 | } 211 | } 212 | 213 | data, err := ioutil.ReadAll(txReader) 214 | if err != nil { 215 | return 216 | } 217 | decoder := NewDecoder(data) 218 | 219 | var tx Transaction 220 | err = decoder.Decode(&tx) 221 | if err != nil { 222 | return nil, fmt.Errorf("unpacking Transaction, %s", err) 223 | } 224 | 225 | // TODO: wire that in 226 | //decoder = NewDecoder(freeDataReader) 227 | //var contextFreeData []HexBytes 228 | //err = decoder.Decode(&contextFreeData) 229 | //if err != nil { 230 | // fmt.Println("PackedTransaction@freedata err: ", err) 231 | // return 232 | //} 233 | 234 | signedTx = NewSignedTransaction(&tx) 235 | //signedTx.ContextFreeData = contextFreeData 236 | signedTx.Signatures = p.Signatures 237 | signedTx.packed = p 238 | 239 | return 240 | } 241 | 242 | type DeferredTransaction struct { 243 | *Transaction 244 | 245 | SenderID uint32 `json:"sender_id"` 246 | Sender AccountName `json:"sender"` 247 | DelayUntil JSONTime `json:"delay_until"` 248 | } 249 | 250 | // TxOptions represents options you want to pass to the transaction 251 | // you're sending. 252 | type TxOptions struct { 253 | ChainID SHA256Bytes // If specified, we won't hit the API to fetch it 254 | HeadBlockID SHA256Bytes // If provided, don't hit API to fetch it. This allows offline transaction signing. 255 | MaxNetUsageWords uint32 256 | DelaySecs uint32 257 | MaxCPUUsageMS uint8 // If you want to override the CPU usage (in counts of 1024) 258 | //ExtraKCPUUsage uint32 // If you want to *add* some CPU usage to the estimated amount (in counts of 1024) 259 | Compress CompressionType 260 | } 261 | 262 | // FillFromChain will load ChainID (for signing transactions) and 263 | // HeadBlockID (to fill transaction with TaPoS data). 264 | func (opts *TxOptions) FillFromChain(api *API) error { 265 | if opts == nil { 266 | return errors.New("TxOptions should not be nil, send an object") 267 | } 268 | 269 | if opts.HeadBlockID == nil || opts.ChainID == nil { 270 | info, err := api.cachedGetInfo() 271 | if err != nil { 272 | return err 273 | } 274 | 275 | if opts.HeadBlockID == nil { 276 | opts.HeadBlockID = info.HeadBlockID 277 | } 278 | if opts.ChainID == nil { 279 | opts.ChainID = info.ChainID 280 | } 281 | } 282 | 283 | return nil 284 | } 285 | -------------------------------------------------------------------------------- /vendor/github.com/eoscanada/eos-go/types.go: -------------------------------------------------------------------------------- 1 | package eos 2 | 3 | import ( 4 | "encoding/hex" 5 | "encoding/json" 6 | "errors" 7 | "fmt" 8 | "math" 9 | "strconv" 10 | "strings" 11 | "time" 12 | 13 | "github.com/eoscanada/eos-go/ecc" 14 | ) 15 | 16 | // For reference: 17 | // https://github.com/mithrilcoin-io/EosCommander/blob/master/app/src/main/java/io/mithrilcoin/eoscommander/data/remote/model/types/EosByteWriter.java 18 | 19 | type Name string 20 | type AccountName Name 21 | type PermissionName Name 22 | type ActionName Name 23 | type TableName Name 24 | type ScopeName Name 25 | 26 | func AN(in string) AccountName { return AccountName(in) } 27 | func ActN(in string) ActionName { return ActionName(in) } 28 | func PN(in string) PermissionName { return PermissionName(in) } 29 | 30 | type AccountResourceLimit struct { 31 | Used JSONInt64 `json:"used"` 32 | Available JSONInt64 `json:"available"` 33 | Max JSONInt64 `json:"max"` 34 | } 35 | 36 | type DelegatedBandwidth struct { 37 | From AccountName `json:"from"` 38 | To AccountName `json:"to"` 39 | NetWeight Asset `json:"net_weight"` 40 | CPUWeight Asset `json:"cpu_weight"` 41 | } 42 | 43 | type TotalResources struct { 44 | Owner AccountName `json:"owner"` 45 | NetWeight Asset `json:"net_weight"` 46 | CPUWeight Asset `json:"cpu_weight"` 47 | RAMBytes JSONInt64 `json:"ram_bytes"` 48 | } 49 | 50 | type VoterInfo struct { 51 | Owner AccountName `json:"owner"` 52 | Proxy AccountName `json:"proxy"` 53 | Producers []AccountName `json:"producers"` 54 | Staked JSONInt64 `json:"staked"` 55 | LastVoteWeight JSONFloat64 `json:"last_vote_weight"` 56 | ProxiedVoteWeight JSONFloat64 `json:"proxied_vote_weight"` 57 | IsProxy byte `json:"is_proxy"` 58 | DeferredTrxID uint32 `json:"deferred_trx_id"` 59 | LastUnstakeTime BlockTimestamp `json:"last_unstake_time"` 60 | Unstaking Asset `json:"unstaking"` 61 | } 62 | 63 | type CompressionType uint8 64 | 65 | const ( 66 | CompressionNone = CompressionType(iota) 67 | CompressionZlib 68 | ) 69 | 70 | func (c CompressionType) String() string { 71 | switch c { 72 | case CompressionNone: 73 | return "none" 74 | case CompressionZlib: 75 | return "zlib" 76 | default: 77 | return "" 78 | } 79 | } 80 | 81 | func (c CompressionType) MarshalJSON() ([]byte, error) { 82 | return json.Marshal(c.String()) 83 | } 84 | 85 | func (c *CompressionType) UnmarshalJSON(data []byte) error { 86 | switch string(data) { 87 | case "zlib": 88 | *c = CompressionZlib 89 | default: 90 | *c = CompressionNone 91 | } 92 | return nil 93 | } 94 | 95 | // CurrencyName 96 | 97 | type CurrencyName string 98 | 99 | type Bool bool 100 | 101 | func (b *Bool) UnmarshalJSON(data []byte) error { 102 | var num int 103 | err := json.Unmarshal(data, &num) 104 | if err == nil { 105 | *b = Bool(num != 0) 106 | return nil 107 | } 108 | 109 | var boolVal bool 110 | if err := json.Unmarshal(data, &boolVal); err != nil { 111 | return fmt.Errorf("couldn't unmarshal bool as int or true/false: %s", err) 112 | } 113 | 114 | *b = Bool(boolVal) 115 | return nil 116 | } 117 | 118 | // Asset 119 | 120 | // NOTE: there's also ExtendedAsset which is a quantity with the attached contract (AccountName) 121 | type Asset struct { 122 | Amount int64 123 | Symbol 124 | } 125 | 126 | func (a Asset) Add(other Asset) Asset { 127 | if a.Symbol != other.Symbol { 128 | panic("Add applies only to assets with the same symbol") 129 | } 130 | return Asset{Amount: a.Amount + other.Amount, Symbol: a.Symbol} 131 | } 132 | 133 | func (a Asset) Sub(other Asset) Asset { 134 | if a.Symbol != other.Symbol { 135 | panic("Sub applies only to assets with the same symbol") 136 | } 137 | return Asset{Amount: a.Amount - other.Amount, Symbol: a.Symbol} 138 | } 139 | 140 | func (a Asset) String() string { 141 | strInt := fmt.Sprintf("%d", a.Amount) 142 | if len(strInt) < int(a.Symbol.Precision+1) { 143 | // prepend `0` for the difference: 144 | strInt = strings.Repeat("0", int(a.Symbol.Precision+uint8(1))-len(strInt)) + strInt 145 | } 146 | 147 | var result string 148 | if a.Symbol.Precision == 0 { 149 | result = strInt 150 | } else { 151 | result = strInt[:len(strInt)-int(a.Symbol.Precision)] + "." + strInt[len(strInt)-int(a.Symbol.Precision):] 152 | } 153 | 154 | return fmt.Sprintf("%s %s", result, a.Symbol.Symbol) 155 | } 156 | 157 | // NOTE: there's also a new ExtendedSymbol (which includes the contract (as AccountName) on which it is) 158 | type Symbol struct { 159 | Precision uint8 160 | Symbol string 161 | } 162 | 163 | // EOSSymbol represents the standard EOS symbol on the chain. It's 164 | // here just to speed up things. 165 | var EOSSymbol = Symbol{Precision: 4, Symbol: "EOS"} 166 | 167 | func NewEOSAssetFromString(amount string) (out Asset, err error) { 168 | if len(amount) == 0 { 169 | return out, fmt.Errorf("cannot be an empty string") 170 | } 171 | 172 | if strings.Contains(amount, " EOS") { 173 | amount = strings.Replace(amount, " EOS", "", 1) 174 | } 175 | if !strings.Contains(amount, ".") { 176 | val, err := strconv.ParseInt(amount, 10, 64) 177 | if err != nil { 178 | return out, err 179 | } 180 | return NewEOSAsset(val * 10000), nil 181 | } 182 | 183 | parts := strings.Split(amount, ".") 184 | if len(parts) != 2 { 185 | return out, fmt.Errorf("cannot have two . in amount") 186 | } 187 | 188 | if len(parts[1]) > 4 { 189 | return out, fmt.Errorf("EOS has only 4 decimals") 190 | } 191 | 192 | val, err := strconv.ParseInt(strings.Replace(amount, ".", "", 1), 10, 64) 193 | if err != nil { 194 | return out, err 195 | } 196 | return NewEOSAsset(val * int64(math.Pow10(4-len(parts[1])))), nil 197 | } 198 | 199 | func NewEOSAsset(amount int64) Asset { 200 | return Asset{Amount: amount, Symbol: EOSSymbol} 201 | } 202 | 203 | // NewAsset parses a string like `1000.0000 EOS` into a properly setup Asset 204 | func NewAsset(in string) (out Asset, err error) { 205 | sec := strings.SplitN(in, " ", 2) 206 | if len(sec) != 2 { 207 | return out, fmt.Errorf("invalid format %q, expected an amount and a currency symbol", in) 208 | } 209 | 210 | if len(sec[1]) > 7 { 211 | return out, fmt.Errorf("currency symbol %q too long", sec[1]) 212 | } 213 | 214 | out.Symbol.Symbol = sec[1] 215 | amount := sec[0] 216 | amountSec := strings.SplitN(amount, ".", 2) 217 | 218 | if len(amountSec) == 2 { 219 | out.Symbol.Precision = uint8(len(amountSec[1])) 220 | } 221 | 222 | val, err := strconv.ParseInt(strings.Replace(amount, ".", "", 1), 10, 64) 223 | if err != nil { 224 | return out, err 225 | } 226 | 227 | out.Amount = val 228 | 229 | return 230 | } 231 | 232 | func (a *Asset) UnmarshalJSON(data []byte) error { 233 | var s string 234 | err := json.Unmarshal(data, &s) 235 | if err != nil { 236 | return err 237 | } 238 | 239 | asset, err := NewAsset(s) 240 | if err != nil { 241 | return err 242 | } 243 | 244 | *a = asset 245 | 246 | return nil 247 | } 248 | 249 | type Permission struct { 250 | PermName string `json:"perm_name"` 251 | Parent string `json:"parent"` 252 | RequiredAuth Authority `json:"required_auth"` 253 | } 254 | 255 | type PermissionLevel struct { 256 | Actor AccountName `json:"actor"` 257 | Permission PermissionName `json:"permission"` 258 | } 259 | 260 | // NewPermissionLevel parses strings like `account@active`, 261 | // `otheraccount@owner` and builds a PermissionLevel struct. It 262 | // validates that there is a single optional @ (where permission 263 | // defaults to 'active'), and validates length of account and 264 | // permission names. 265 | func NewPermissionLevel(in string) (out PermissionLevel, err error) { 266 | parts := strings.Split(in, "@") 267 | if len(parts) > 2 { 268 | return out, fmt.Errorf("permission %q invalid, use account[@permission]", in) 269 | } 270 | 271 | if len(parts[0]) > 12 { 272 | return out, fmt.Errorf("account name %q too long", parts[0]) 273 | } 274 | 275 | out.Actor = AccountName(parts[0]) 276 | out.Permission = PermissionName("active") 277 | if len(parts) == 2 { 278 | if len(parts[1]) > 12 { 279 | return out, fmt.Errorf("permission %q name too long", parts[1]) 280 | } 281 | 282 | out.Permission = PermissionName(parts[1]) 283 | } 284 | 285 | return 286 | } 287 | 288 | type PermissionLevelWeight struct { 289 | Permission PermissionLevel `json:"permission"` 290 | Weight uint16 `json:"weight"` // weight_type 291 | } 292 | 293 | type Authority struct { 294 | Threshold uint32 `json:"threshold"` 295 | Keys []KeyWeight `json:"keys,omitempty"` 296 | Accounts []PermissionLevelWeight `json:"accounts,omitempty"` 297 | Waits []WaitWeight `json:"waits,omitempty"` 298 | } 299 | 300 | type KeyWeight struct { 301 | PublicKey ecc.PublicKey `json:"key"` 302 | Weight uint16 `json:"weight"` // weight_type 303 | } 304 | 305 | type WaitWeight struct { 306 | WaitSec uint32 `json:"wait_sec"` 307 | Weight uint16 `json:"weight"` // weight_type 308 | } 309 | 310 | type GetCodeResp struct { 311 | AccountName AccountName `json:"account_name"` 312 | CodeHash string `json:"code_hash"` 313 | WASM string `json:"wasm"` 314 | ABI ABI `json:"abi"` 315 | } 316 | 317 | type GetABIResp struct { 318 | AccountName AccountName `json:"account_name"` 319 | ABI ABI `json:"abi"` 320 | } 321 | 322 | // JSONTime 323 | 324 | type JSONTime struct { 325 | time.Time 326 | } 327 | 328 | const JSONTimeFormat = "2006-01-02T15:04:05" 329 | 330 | func (t JSONTime) MarshalJSON() ([]byte, error) { 331 | return []byte(fmt.Sprintf("%q", t.Format(JSONTimeFormat))), nil 332 | } 333 | 334 | func (t *JSONTime) UnmarshalJSON(data []byte) (err error) { 335 | if string(data) == "null" { 336 | return nil 337 | } 338 | 339 | t.Time, err = time.Parse(`"`+JSONTimeFormat+`"`, string(data)) 340 | return err 341 | } 342 | 343 | // HexBytes 344 | 345 | type HexBytes []byte 346 | 347 | func (t HexBytes) MarshalJSON() ([]byte, error) { 348 | return json.Marshal(hex.EncodeToString(t)) 349 | } 350 | 351 | func (t *HexBytes) UnmarshalJSON(data []byte) (err error) { 352 | var s string 353 | err = json.Unmarshal(data, &s) 354 | if err != nil { 355 | return 356 | } 357 | 358 | *t, err = hex.DecodeString(s) 359 | return 360 | } 361 | 362 | // SHA256Bytes 363 | 364 | type SHA256Bytes []byte // should always be 32 bytes 365 | 366 | func (t SHA256Bytes) MarshalJSON() ([]byte, error) { 367 | return json.Marshal(hex.EncodeToString(t)) 368 | } 369 | 370 | func (t *SHA256Bytes) UnmarshalJSON(data []byte) (err error) { 371 | var s string 372 | err = json.Unmarshal(data, &s) 373 | if err != nil { 374 | return 375 | } 376 | 377 | *t, err = hex.DecodeString(s) 378 | return 379 | } 380 | 381 | type Varuint32 uint32 382 | 383 | // Tstamp 384 | 385 | type Tstamp struct { 386 | time.Time 387 | } 388 | 389 | func (t Tstamp) MarshalJSON() ([]byte, error) { 390 | return json.Marshal(fmt.Sprintf("%d", t.UnixNano())) 391 | } 392 | 393 | func (t *Tstamp) UnmarshalJSON(data []byte) (err error) { 394 | var unixNano int64 395 | if data[0] == '"' { 396 | var s string 397 | if err = json.Unmarshal(data, &s); err != nil { 398 | return 399 | } 400 | 401 | unixNano, err = strconv.ParseInt(s, 10, 64) 402 | if err != nil { 403 | return err 404 | } 405 | 406 | } else { 407 | unixNano, err = strconv.ParseInt(string(data), 10, 64) 408 | if err != nil { 409 | return err 410 | } 411 | } 412 | 413 | *t = Tstamp{time.Unix(0, unixNano)} 414 | 415 | return nil 416 | } 417 | 418 | type BlockTimestamp struct { 419 | time.Time 420 | } 421 | 422 | const BlockTimestampFormat = "2006-01-02T15:04:05" 423 | 424 | func (t BlockTimestamp) MarshalJSON() ([]byte, error) { 425 | return []byte(fmt.Sprintf("%q", t.Format(BlockTimestampFormat))), nil 426 | } 427 | 428 | func (t *BlockTimestamp) UnmarshalJSON(data []byte) (err error) { 429 | if string(data) == "null" { 430 | return nil 431 | } 432 | 433 | t.Time, err = time.Parse(`"`+BlockTimestampFormat+`"`, string(data)) 434 | if err != nil { 435 | t.Time, err = time.Parse(`"`+BlockTimestampFormat+`Z07:00"`, string(data)) 436 | } 437 | return err 438 | } 439 | 440 | type JSONFloat64 float64 441 | 442 | func (f *JSONFloat64) UnmarshalJSON(data []byte) error { 443 | if len(data) == 0 { 444 | return errors.New("empty value") 445 | } 446 | 447 | if data[0] == '"' { 448 | var s string 449 | if err := json.Unmarshal(data, &s); err != nil { 450 | return err 451 | } 452 | 453 | val, err := strconv.ParseFloat(s, 64) 454 | if err != nil { 455 | return err 456 | } 457 | 458 | *f = JSONFloat64(val) 459 | 460 | return nil 461 | } 462 | 463 | var fl float64 464 | if err := json.Unmarshal(data, &fl); err != nil { 465 | return err 466 | } 467 | 468 | *f = JSONFloat64(fl) 469 | 470 | return nil 471 | } 472 | 473 | type JSONInt64 int64 474 | 475 | func (i *JSONInt64) UnmarshalJSON(data []byte) error { 476 | if len(data) == 0 { 477 | return errors.New("empty value") 478 | } 479 | 480 | if data[0] == '"' { 481 | var s string 482 | if err := json.Unmarshal(data, &s); err != nil { 483 | return err 484 | } 485 | 486 | val, err := strconv.ParseInt(s, 10, 64) 487 | if err != nil { 488 | return err 489 | } 490 | 491 | *i = JSONInt64(val) 492 | 493 | return nil 494 | } 495 | 496 | var v int64 497 | if err := json.Unmarshal(data, &v); err != nil { 498 | return err 499 | } 500 | 501 | *i = JSONInt64(v) 502 | 503 | return nil 504 | } 505 | -------------------------------------------------------------------------------- /vendor/golang.org/x/crypto/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2009 The Go Authors. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google Inc. nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /vendor/golang.org/x/crypto/PATENTS: -------------------------------------------------------------------------------- 1 | Additional IP Rights Grant (Patents) 2 | 3 | "This implementation" means the copyrightable works distributed by 4 | Google as part of the Go project. 5 | 6 | Google hereby grants to You a perpetual, worldwide, non-exclusive, 7 | no-charge, royalty-free, irrevocable (except as stated in this section) 8 | patent license to make, have made, use, offer to sell, sell, import, 9 | transfer and otherwise run, modify and propagate the contents of this 10 | implementation of Go, where such license applies only to those patent 11 | claims, both currently owned or controlled by Google and acquired in 12 | the future, licensable by Google that are necessarily infringed by this 13 | implementation of Go. This grant does not include claims that would be 14 | infringed only as a consequence of further modification of this 15 | implementation. If you or your agent or exclusive licensee institute or 16 | order or agree to the institution of patent litigation against any 17 | entity (including a cross-claim or counterclaim in a lawsuit) alleging 18 | that this implementation of Go or any code incorporated within this 19 | implementation of Go constitutes direct or contributory patent 20 | infringement, or inducement of patent infringement, then any patent 21 | rights granted to you under this License for this implementation of Go 22 | shall terminate as of the date such litigation is filed. 23 | -------------------------------------------------------------------------------- /vendor/golang.org/x/crypto/ripemd160/ripemd160.go: -------------------------------------------------------------------------------- 1 | // Copyright 2010 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package ripemd160 implements the RIPEMD-160 hash algorithm. 6 | package ripemd160 // import "golang.org/x/crypto/ripemd160" 7 | 8 | // RIPEMD-160 is designed by by Hans Dobbertin, Antoon Bosselaers, and Bart 9 | // Preneel with specifications available at: 10 | // http://homes.esat.kuleuven.be/~cosicart/pdf/AB-9601/AB-9601.pdf. 11 | 12 | import ( 13 | "crypto" 14 | "hash" 15 | ) 16 | 17 | func init() { 18 | crypto.RegisterHash(crypto.RIPEMD160, New) 19 | } 20 | 21 | // The size of the checksum in bytes. 22 | const Size = 20 23 | 24 | // The block size of the hash algorithm in bytes. 25 | const BlockSize = 64 26 | 27 | const ( 28 | _s0 = 0x67452301 29 | _s1 = 0xefcdab89 30 | _s2 = 0x98badcfe 31 | _s3 = 0x10325476 32 | _s4 = 0xc3d2e1f0 33 | ) 34 | 35 | // digest represents the partial evaluation of a checksum. 36 | type digest struct { 37 | s [5]uint32 // running context 38 | x [BlockSize]byte // temporary buffer 39 | nx int // index into x 40 | tc uint64 // total count of bytes processed 41 | } 42 | 43 | func (d *digest) Reset() { 44 | d.s[0], d.s[1], d.s[2], d.s[3], d.s[4] = _s0, _s1, _s2, _s3, _s4 45 | d.nx = 0 46 | d.tc = 0 47 | } 48 | 49 | // New returns a new hash.Hash computing the checksum. 50 | func New() hash.Hash { 51 | result := new(digest) 52 | result.Reset() 53 | return result 54 | } 55 | 56 | func (d *digest) Size() int { return Size } 57 | 58 | func (d *digest) BlockSize() int { return BlockSize } 59 | 60 | func (d *digest) Write(p []byte) (nn int, err error) { 61 | nn = len(p) 62 | d.tc += uint64(nn) 63 | if d.nx > 0 { 64 | n := len(p) 65 | if n > BlockSize-d.nx { 66 | n = BlockSize - d.nx 67 | } 68 | for i := 0; i < n; i++ { 69 | d.x[d.nx+i] = p[i] 70 | } 71 | d.nx += n 72 | if d.nx == BlockSize { 73 | _Block(d, d.x[0:]) 74 | d.nx = 0 75 | } 76 | p = p[n:] 77 | } 78 | n := _Block(d, p) 79 | p = p[n:] 80 | if len(p) > 0 { 81 | d.nx = copy(d.x[:], p) 82 | } 83 | return 84 | } 85 | 86 | func (d0 *digest) Sum(in []byte) []byte { 87 | // Make a copy of d0 so that caller can keep writing and summing. 88 | d := *d0 89 | 90 | // Padding. Add a 1 bit and 0 bits until 56 bytes mod 64. 91 | tc := d.tc 92 | var tmp [64]byte 93 | tmp[0] = 0x80 94 | if tc%64 < 56 { 95 | d.Write(tmp[0 : 56-tc%64]) 96 | } else { 97 | d.Write(tmp[0 : 64+56-tc%64]) 98 | } 99 | 100 | // Length in bits. 101 | tc <<= 3 102 | for i := uint(0); i < 8; i++ { 103 | tmp[i] = byte(tc >> (8 * i)) 104 | } 105 | d.Write(tmp[0:8]) 106 | 107 | if d.nx != 0 { 108 | panic("d.nx != 0") 109 | } 110 | 111 | var digest [Size]byte 112 | for i, s := range d.s { 113 | digest[i*4] = byte(s) 114 | digest[i*4+1] = byte(s >> 8) 115 | digest[i*4+2] = byte(s >> 16) 116 | digest[i*4+3] = byte(s >> 24) 117 | } 118 | 119 | return append(in, digest[:]...) 120 | } 121 | -------------------------------------------------------------------------------- /vendor/golang.org/x/crypto/ripemd160/ripemd160block.go: -------------------------------------------------------------------------------- 1 | // Copyright 2010 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // RIPEMD-160 block step. 6 | // In its own file so that a faster assembly or C version 7 | // can be substituted easily. 8 | 9 | package ripemd160 10 | 11 | import ( 12 | "math/bits" 13 | ) 14 | 15 | // work buffer indices and roll amounts for one line 16 | var _n = [80]uint{ 17 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18 | 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 19 | 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 20 | 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 21 | 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13, 22 | } 23 | 24 | var _r = [80]uint{ 25 | 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 26 | 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 27 | 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 28 | 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 29 | 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6, 30 | } 31 | 32 | // same for the other parallel one 33 | var n_ = [80]uint{ 34 | 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 35 | 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 36 | 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 37 | 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 38 | 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11, 39 | } 40 | 41 | var r_ = [80]uint{ 42 | 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 43 | 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 44 | 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 45 | 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 46 | 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11, 47 | } 48 | 49 | func _Block(md *digest, p []byte) int { 50 | n := 0 51 | var x [16]uint32 52 | var alpha, beta uint32 53 | for len(p) >= BlockSize { 54 | a, b, c, d, e := md.s[0], md.s[1], md.s[2], md.s[3], md.s[4] 55 | aa, bb, cc, dd, ee := a, b, c, d, e 56 | j := 0 57 | for i := 0; i < 16; i++ { 58 | x[i] = uint32(p[j]) | uint32(p[j+1])<<8 | uint32(p[j+2])<<16 | uint32(p[j+3])<<24 59 | j += 4 60 | } 61 | 62 | // round 1 63 | i := 0 64 | for i < 16 { 65 | alpha = a + (b ^ c ^ d) + x[_n[i]] 66 | s := int(_r[i]) 67 | alpha = bits.RotateLeft32(alpha, s) + e 68 | beta = bits.RotateLeft32(c, 10) 69 | a, b, c, d, e = e, alpha, b, beta, d 70 | 71 | // parallel line 72 | alpha = aa + (bb ^ (cc | ^dd)) + x[n_[i]] + 0x50a28be6 73 | s = int(r_[i]) 74 | alpha = bits.RotateLeft32(alpha, s) + ee 75 | beta = bits.RotateLeft32(cc, 10) 76 | aa, bb, cc, dd, ee = ee, alpha, bb, beta, dd 77 | 78 | i++ 79 | } 80 | 81 | // round 2 82 | for i < 32 { 83 | alpha = a + (b&c | ^b&d) + x[_n[i]] + 0x5a827999 84 | s := int(_r[i]) 85 | alpha = bits.RotateLeft32(alpha, s) + e 86 | beta = bits.RotateLeft32(c, 10) 87 | a, b, c, d, e = e, alpha, b, beta, d 88 | 89 | // parallel line 90 | alpha = aa + (bb&dd | cc&^dd) + x[n_[i]] + 0x5c4dd124 91 | s = int(r_[i]) 92 | alpha = bits.RotateLeft32(alpha, s) + ee 93 | beta = bits.RotateLeft32(cc, 10) 94 | aa, bb, cc, dd, ee = ee, alpha, bb, beta, dd 95 | 96 | i++ 97 | } 98 | 99 | // round 3 100 | for i < 48 { 101 | alpha = a + (b | ^c ^ d) + x[_n[i]] + 0x6ed9eba1 102 | s := int(_r[i]) 103 | alpha = bits.RotateLeft32(alpha, s) + e 104 | beta = bits.RotateLeft32(c, 10) 105 | a, b, c, d, e = e, alpha, b, beta, d 106 | 107 | // parallel line 108 | alpha = aa + (bb | ^cc ^ dd) + x[n_[i]] + 0x6d703ef3 109 | s = int(r_[i]) 110 | alpha = bits.RotateLeft32(alpha, s) + ee 111 | beta = bits.RotateLeft32(cc, 10) 112 | aa, bb, cc, dd, ee = ee, alpha, bb, beta, dd 113 | 114 | i++ 115 | } 116 | 117 | // round 4 118 | for i < 64 { 119 | alpha = a + (b&d | c&^d) + x[_n[i]] + 0x8f1bbcdc 120 | s := int(_r[i]) 121 | alpha = bits.RotateLeft32(alpha, s) + e 122 | beta = bits.RotateLeft32(c, 10) 123 | a, b, c, d, e = e, alpha, b, beta, d 124 | 125 | // parallel line 126 | alpha = aa + (bb&cc | ^bb&dd) + x[n_[i]] + 0x7a6d76e9 127 | s = int(r_[i]) 128 | alpha = bits.RotateLeft32(alpha, s) + ee 129 | beta = bits.RotateLeft32(cc, 10) 130 | aa, bb, cc, dd, ee = ee, alpha, bb, beta, dd 131 | 132 | i++ 133 | } 134 | 135 | // round 5 136 | for i < 80 { 137 | alpha = a + (b ^ (c | ^d)) + x[_n[i]] + 0xa953fd4e 138 | s := int(_r[i]) 139 | alpha = bits.RotateLeft32(alpha, s) + e 140 | beta = bits.RotateLeft32(c, 10) 141 | a, b, c, d, e = e, alpha, b, beta, d 142 | 143 | // parallel line 144 | alpha = aa + (bb ^ cc ^ dd) + x[n_[i]] 145 | s = int(r_[i]) 146 | alpha = bits.RotateLeft32(alpha, s) + ee 147 | beta = bits.RotateLeft32(cc, 10) 148 | aa, bb, cc, dd, ee = ee, alpha, bb, beta, dd 149 | 150 | i++ 151 | } 152 | 153 | // combine results 154 | dd += c + md.s[1] 155 | md.s[1] = md.s[2] + d + ee 156 | md.s[2] = md.s[3] + e + aa 157 | md.s[3] = md.s[4] + a + bb 158 | md.s[4] = md.s[0] + b + cc 159 | md.s[0] = dd 160 | 161 | p = p[BlockSize:] 162 | n += BlockSize 163 | } 164 | return n 165 | } 166 | -------------------------------------------------------------------------------- /vendor/vendor.json: -------------------------------------------------------------------------------- 1 | { 2 | "comment": "", 3 | "ignore": "test", 4 | "package": [ 5 | { 6 | "checksumSHA1": "d1AVWZxDEEp4ZtMVZsq5cse3fh0=", 7 | "path": "github.com/eoscanada/eos-go", 8 | "revision": "41f3b757e924be72775089cf7ee5ff63d40f1daa", 9 | "revisionTime": "2018-07-06T03:44:21Z" 10 | }, 11 | { 12 | "checksumSHA1": "mbdurDenl8bhRVVu8ixJw70fi5E=", 13 | "path": "github.com/eoscanada/eos-go/btcsuite/btcd/btcec", 14 | "revision": "41f3b757e924be72775089cf7ee5ff63d40f1daa", 15 | "revisionTime": "2018-07-06T03:44:21Z" 16 | }, 17 | { 18 | "checksumSHA1": "9CdGdJ/+qjIwCfyoxoB3JxNtdyg=", 19 | "path": "github.com/eoscanada/eos-go/btcsuite/btcutil", 20 | "revision": "41f3b757e924be72775089cf7ee5ff63d40f1daa", 21 | "revisionTime": "2018-07-06T03:44:21Z" 22 | }, 23 | { 24 | "checksumSHA1": "VkjW+vswsv7J0PX2UFqqg+/RVgs=", 25 | "path": "github.com/eoscanada/eos-go/btcsuite/btcutil/base58", 26 | "revision": "41f3b757e924be72775089cf7ee5ff63d40f1daa", 27 | "revisionTime": "2018-07-06T03:44:21Z" 28 | }, 29 | { 30 | "checksumSHA1": "Prj/mEIP4L5aX+Kwis+lhBklBOE=", 31 | "path": "github.com/eoscanada/eos-go/ecc", 32 | "revision": "41f3b757e924be72775089cf7ee5ff63d40f1daa", 33 | "revisionTime": "2018-07-06T03:44:21Z" 34 | }, 35 | { 36 | "checksumSHA1": "IzWsV4CUd3OIZ5fS5SIMNgbGhQM=", 37 | "path": "github.com/eoscanada/eos-go/system", 38 | "revision": "41f3b757e924be72775089cf7ee5ff63d40f1daa", 39 | "revisionTime": "2018-07-06T03:44:21Z" 40 | }, 41 | { 42 | "checksumSHA1": "TQoVgHqUD72/5ALzi9p5W3oyaug=", 43 | "path": "golang.org/x/crypto/ripemd160", 44 | "revision": "ae8bce0030810cf999bb2b9868ae5c7c58e6343b", 45 | "revisionTime": "2018-04-30T17:54:52Z" 46 | } 47 | ], 48 | "rootPath": "github.com/eoscanada/eos-claimer" 49 | } 50 | --------------------------------------------------------------------------------