From 935de8d471681c504892e86dd059bba288927e6d Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Tue, 26 Jun 2018 22:38:50 +0100 Subject: [PATCH 01/28] Don't panic on nil Bounds Signed-off-by: Silas Davis --- execution/events/pbevents/blocks.go | 3 +++ execution/events/pbevents/blocks_test.go | 17 +++++++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 execution/events/pbevents/blocks_test.go diff --git a/execution/events/pbevents/blocks.go b/execution/events/pbevents/blocks.go index 5856e64b9..5513ec34c 100644 --- a/execution/events/pbevents/blocks.go +++ b/execution/events/pbevents/blocks.go @@ -12,6 +12,9 @@ func (b *Bound) Key(latestBlockHeight uint64) events.Key { } func (b *Bound) Bound(latestBlockHeight uint64) uint64 { + if b == nil { + return latestBlockHeight + } switch b.Type { case Bound_ABSOLUTE: return b.GetIndex() diff --git a/execution/events/pbevents/blocks_test.go b/execution/events/pbevents/blocks_test.go new file mode 100644 index 000000000..62641f876 --- /dev/null +++ b/execution/events/pbevents/blocks_test.go @@ -0,0 +1,17 @@ +package pbevents + +import ( + "testing" + + "github.com/hyperledger/burrow/execution/events" + "github.com/stretchr/testify/assert" +) + +func TestBlockRange_Bounds(t *testing.T) { + latestHeight := uint64(2344) + br := &BlockRange{} + start, end, streaming := br.Bounds(latestHeight) + assert.Equal(t, events.NewKey(latestHeight, 0), start) + assert.Equal(t, events.NewKey(latestHeight, 0), end) + assert.False(t, streaming) +} From 9e0e078b99b0b4352b745a776a8e9fa4c644e4e7 Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Wed, 27 Jun 2018 12:02:51 +0100 Subject: [PATCH 02/28] Improve event test Signed-off-by: Silas Davis --- Makefile | 3 +++ rpc/rpcevents/integration/events_server_test.go | 8 +++++--- rpc/test/strange_loop.go | 2 +- rpc/test/strange_loop.sol | 2 +- 4 files changed, 10 insertions(+), 5 deletions(-) diff --git a/Makefile b/Makefile index 2a40f335c..fb80bce1f 100644 --- a/Makefile +++ b/Makefile @@ -173,6 +173,9 @@ test: check test_keys: build_db burrow_bin="${REPO}/bin/burrow" keys/test.sh +rpc/test/strange_loop.go: rpc/test/strange_loop.sol + @rpc/test/strange_loop.sh + .PHONY: test_integration test_integration: test_keys @go test -tags integration ./rpc/rpcevents/integration diff --git a/rpc/rpcevents/integration/events_server_test.go b/rpc/rpcevents/integration/events_server_test.go index 4d2e31520..0e8aebb14 100644 --- a/rpc/rpcevents/integration/events_server_test.go +++ b/rpc/rpcevents/integration/events_server_test.go @@ -24,6 +24,8 @@ import ( "encoding/json" + "strings" + "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/execution/events" @@ -80,10 +82,10 @@ func TestEventSubscribeLog(t *testing.T) { func(evs []*pbevents.Event) { require.Len(t, evs, test.UpsieDownsieCallCount-2) log := evs[0].GetExecutionEvent().GetEventDataLog() - depth := binary.Int64FromWord256(binary.LeftPadWord256(log.Topics[1])) - payload := string(log.Data) + depth := binary.Int64FromWord256(binary.LeftPadWord256(log.Topics[2])) + direction := strings.TrimRight(string(log.Topics[1]), "\x00") assert.Equal(t, int64(18), depth) - assert.Contains(t, payload, "Upsie!") + assert.Equal(t, "Upsie!", direction) }) } diff --git a/rpc/test/strange_loop.go b/rpc/test/strange_loop.go index 10590c4fc..230de1cc2 100644 --- a/rpc/test/strange_loop.go +++ b/rpc/test/strange_loop.go @@ -1,3 +1,3 @@ package test -const strangeLoopBytecodeHex = "60606040526017600055602260015560116002556001600360006101000a81548160ff021916908315150217905550341561003957600080fd5b61039f806100486000396000f300606060405260043610610041576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063ebb384dd14610046575b600080fd5b341561005157600080fd5b61005961006f565b6040518082815260200191505060405180910390f35b60006002549050600360009054906101000a900460ff161561023a576001546002541215610199576002600081548092919060010191905055506002547f6488c53a044f5cc88f6f830b84ae7a701762a11b40a91eb0451a870b0f560a4b6040518080602001828103825260068152602001807f557073696521000000000000000000000000000000000000000000000000000081525060200191505060405180910390a260025490503073ffffffffffffffffffffffffffffffffffffffff1663ebb384dd6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b151561017c57600080fd5b5af1151561018957600080fd5b5050506040518051905050610235565b6000600360006101000a81548160ff02191690831515021790555060025490503073ffffffffffffffffffffffffffffffffffffffff1663ebb384dd6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b151561021c57600080fd5b5af1151561022957600080fd5b50505060405180519050505b61036f565b600054600254131561034957600260008154809291906001900391905055506002547f6488c53a044f5cc88f6f830b84ae7a701762a11b40a91eb0451a870b0f560a4b6040518080602001828103825260088152602001807f446f776e7369652100000000000000000000000000000000000000000000000081525060200191505060405180910390a260025490503073ffffffffffffffffffffffffffffffffffffffff1663ebb384dd6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b151561032c57600080fd5b5af1151561033957600080fd5b505050604051805190505061036e565b6001600360006101000a81548160ff0219169083151502179055506002549050610370565b5b5b905600a165627a7a7230582052e0533ea43cd4d1a18ebcfb80ad6d09e217a7615d9faf935ce110c467f7c0b80029" +const strangeLoopBytecodeHex = "60606040526017600055602260015560116002556001600360006101000a81548160ff021916908315150217905550341561003957600080fd5b610369806100486000396000f300606060405260043610610041576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063ebb384dd14610046575b600080fd5b341561005157600080fd5b61005961006f565b6040518082815260200191505060405180910390f35b60006002549050600360009054906101000a900460ff161561021f57600154600254121561017e576002600081548092919060010191905055506002547f55707369652100000000000000000000000000000000000000000000000000007f3ff0b1eac80ecf8e93d1a2d7982a9230f8ea7693439fd548687b08a5e292b09760405160405180910390a360025490503073ffffffffffffffffffffffffffffffffffffffff1663ebb384dd6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b151561016157600080fd5b5af1151561016e57600080fd5b505050604051805190505061021a565b6000600360006101000a81548160ff02191690831515021790555060025490503073ffffffffffffffffffffffffffffffffffffffff1663ebb384dd6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b151561020157600080fd5b5af1151561020e57600080fd5b50505060405180519050505b610339565b600054600254131561031357600260008154809291906001900391905055506002547f446f776e736965210000000000000000000000000000000000000000000000007f3ff0b1eac80ecf8e93d1a2d7982a9230f8ea7693439fd548687b08a5e292b09760405160405180910390a360025490503073ffffffffffffffffffffffffffffffffffffffff1663ebb384dd6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15156102f657600080fd5b5af1151561030357600080fd5b5050506040518051905050610338565b6001600360006101000a81548160ff021916908315150217905550600254905061033a565b5b5b905600a165627a7a723058204852911519ec7080301770f04ea7bf39ba1e2d71b4988eb1df310378ac767f350029" diff --git a/rpc/test/strange_loop.sol b/rpc/test/strange_loop.sol index 5c2d0bc4d..33726d0b9 100644 --- a/rpc/test/strange_loop.sol +++ b/rpc/test/strange_loop.sol @@ -7,7 +7,7 @@ contract StrangeLoop { bool down = true; // indexed puts it in topic event ChangeLevel( - string direction, + bytes32 indexed direction, int indexed newDepth); function UpsieDownsie() public returns (int i) { From 1aae07cee4271af02e2fe1e730006ba71e7eb601 Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Wed, 27 Jun 2018 20:56:54 +0200 Subject: [PATCH 03/28] Improve solidity fixture handling Signed-off-by: Silas Davis --- Makefile | 18 +++++++++++++++--- .../integration/transactor_server_test.go | 4 ++-- rpc/test/helpers.go | 5 +---- rpc/test/strange_loop.go | 3 --- rpc/test/strange_loop.sh | 5 ----- rpc/test/strange_loop.sol.go | 5 +++++ rpc/v0/integration/v0_test.go | 6 +++--- scripts/solc_compile_go.sh | 17 +++++++++++++++++ 8 files changed, 43 insertions(+), 20 deletions(-) delete mode 100644 rpc/test/strange_loop.go delete mode 100755 rpc/test/strange_loop.sh create mode 100644 rpc/test/strange_loop.sol.go create mode 100755 scripts/solc_compile_go.sh diff --git a/Makefile b/Makefile index fb80bce1f..86ad8624a 100644 --- a/Makefile +++ b/Makefile @@ -16,9 +16,14 @@ BOSMARMOT_PROJECT := github.com/monax/bosmarmot BOSMARMOT_GOPATH := ${REPO}/.gopath_bos BOSMARMOT_CHECKOUT := ${BOSMARMOT_GOPATH}/src/${BOSMARMOT_PROJECT} -PROTO_FILES = $(shell find . -type f -name '*.proto') +# Protobuf generated go files +PROTO_FILES = $(shell find . -path ./vendor -prune -o -type f -name '*.proto') PROTO_GO_FILES = $(patsubst %.proto, %.pb.go, $(PROTO_FILES)) +# Our own Go files containing the compiled bytecode of solidity files as a constant +SOLIDITY_FILES = $(shell find . -path ./vendor -prune -o -type f -name '*.sol') +SOLIDITY_GO_FILES = $(patsubst %.sol, %.sol.go, $(SOLIDITY_FILES)) + ### Formatting, linting and vetting # check the code for style standards; currently enforces go formatting. @@ -146,7 +151,6 @@ build_race_db: build_race_client: go build -race -o ${REPO}/bin/burrow-client ./client/cmd/burrow-client - # Get the Bosmarmot code .PHONY: bos bos: ./scripts/deps/bos.sh @@ -164,7 +168,15 @@ docker_build: check commit_hash ### Testing github.com/hyperledger/burrow -# test burrow +# Solidity fixtures +%.sol.go: %.sol scripts/solc_compile_go.sh + scripts/solc_compile_go.sh $< $@ + +.PHONY: solidity +solidity: $(SOLIDITY_GO_FILES) + +# Test + .PHONY: test test: check @go test ${PACKAGES_NOVENDOR} diff --git a/rpc/rpctransactor/integration/transactor_server_test.go b/rpc/rpctransactor/integration/transactor_server_test.go index c48cb128a..80c79df92 100644 --- a/rpc/rpctransactor/integration/transactor_server_test.go +++ b/rpc/rpctransactor/integration/transactor_server_test.go @@ -67,7 +67,7 @@ func TestTransactCreate(t *testing.T) { create, err := cli.Transact(context.Background(), &pbtransactor.TransactParam{ InputAccount: inputAccount(i), Address: nil, - Data: test.StrangeLoopBytecode, + Data: test.Bytecode_strange_loop, Fee: 2, GasLimit: 10000, }) @@ -89,7 +89,7 @@ func BenchmarkTransactCreateContract(b *testing.B) { create, err := cli.Transact(context.Background(), &pbtransactor.TransactParam{ InputAccount: inputAccount(i), Address: nil, - Data: test.StrangeLoopBytecode, + Data: test.Bytecode_strange_loop, Fee: 2, GasLimit: 10000, }) diff --git a/rpc/test/helpers.go b/rpc/test/helpers.go index 18ded24e2..e994045b4 100644 --- a/rpc/test/helpers.go +++ b/rpc/test/helpers.go @@ -12,12 +12,9 @@ import ( "github.com/hyperledger/burrow/rpc" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tmthrgd/go-hex" "google.golang.org/grpc" ) -var StrangeLoopBytecode = hex.MustDecodeString(strangeLoopBytecodeHex) - // Recursive call count for UpsieDownsie() function call from strange_loop.sol // Equals initial call, then depth from 17 -> 34, one for the bounce, then depth from 34 -> 23, // so... (I didn't say it had to make sense): @@ -75,7 +72,7 @@ func CreateContract(t testing.TB, cli pbtransactor.TransactorClient, create, err := cli.TransactAndHold(context.Background(), &pbtransactor.TransactParam{ InputAccount: inputAccount, Address: nil, - Data: StrangeLoopBytecode, + Data: Bytecode_strange_loop, Fee: 2, GasLimit: 10000, }) diff --git a/rpc/test/strange_loop.go b/rpc/test/strange_loop.go deleted file mode 100644 index 230de1cc2..000000000 --- a/rpc/test/strange_loop.go +++ /dev/null @@ -1,3 +0,0 @@ -package test - -const strangeLoopBytecodeHex = "60606040526017600055602260015560116002556001600360006101000a81548160ff021916908315150217905550341561003957600080fd5b610369806100486000396000f300606060405260043610610041576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063ebb384dd14610046575b600080fd5b341561005157600080fd5b61005961006f565b6040518082815260200191505060405180910390f35b60006002549050600360009054906101000a900460ff161561021f57600154600254121561017e576002600081548092919060010191905055506002547f55707369652100000000000000000000000000000000000000000000000000007f3ff0b1eac80ecf8e93d1a2d7982a9230f8ea7693439fd548687b08a5e292b09760405160405180910390a360025490503073ffffffffffffffffffffffffffffffffffffffff1663ebb384dd6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b151561016157600080fd5b5af1151561016e57600080fd5b505050604051805190505061021a565b6000600360006101000a81548160ff02191690831515021790555060025490503073ffffffffffffffffffffffffffffffffffffffff1663ebb384dd6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b151561020157600080fd5b5af1151561020e57600080fd5b50505060405180519050505b610339565b600054600254131561031357600260008154809291906001900391905055506002547f446f776e736965210000000000000000000000000000000000000000000000007f3ff0b1eac80ecf8e93d1a2d7982a9230f8ea7693439fd548687b08a5e292b09760405160405180910390a360025490503073ffffffffffffffffffffffffffffffffffffffff1663ebb384dd6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15156102f657600080fd5b5af1151561030357600080fd5b5050506040518051905050610338565b6001600360006101000a81548160ff021916908315150217905550600254905061033a565b5b5b905600a165627a7a723058204852911519ec7080301770f04ea7bf39ba1e2d71b4988eb1df310378ac767f350029" diff --git a/rpc/test/strange_loop.sh b/rpc/test/strange_loop.sh deleted file mode 100755 index edbdf044b..000000000 --- a/rpc/test/strange_loop.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env bash - -script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" - -echo -e "package test\n\nconst strangeLoopBytecodeHex = \"$(solc --bin "$script_dir/strange_loop.sol" | tail -1)\"" > "${script_dir}/strange_loop.go" diff --git a/rpc/test/strange_loop.sol.go b/rpc/test/strange_loop.sol.go new file mode 100644 index 000000000..57a1f061f --- /dev/null +++ b/rpc/test/strange_loop.sol.go @@ -0,0 +1,5 @@ +package test + +import "github.com/tmthrgd/go-hex" + +var Bytecode_strange_loop = hex.MustDecodeString("60606040526017600055602260015560116002556001600360006101000a81548160ff021916908315150217905550341561003957600080fd5b610369806100486000396000f300606060405260043610610041576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063ebb384dd14610046575b600080fd5b341561005157600080fd5b61005961006f565b6040518082815260200191505060405180910390f35b60006002549050600360009054906101000a900460ff161561021f57600154600254121561017e576002600081548092919060010191905055506002547f55707369652100000000000000000000000000000000000000000000000000007f3ff0b1eac80ecf8e93d1a2d7982a9230f8ea7693439fd548687b08a5e292b09760405160405180910390a360025490503073ffffffffffffffffffffffffffffffffffffffff1663ebb384dd6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b151561016157600080fd5b5af1151561016e57600080fd5b505050604051805190505061021a565b6000600360006101000a81548160ff02191690831515021790555060025490503073ffffffffffffffffffffffffffffffffffffffff1663ebb384dd6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b151561020157600080fd5b5af1151561020e57600080fd5b50505060405180519050505b610339565b600054600254131561031357600260008154809291906001900391905055506002547f446f776e736965210000000000000000000000000000000000000000000000007f3ff0b1eac80ecf8e93d1a2d7982a9230f8ea7693439fd548687b08a5e292b09760405160405180910390a360025490503073ffffffffffffffffffffffffffffffffffffffff1663ebb384dd6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15156102f657600080fd5b5af1151561030357600080fd5b5050506040518051905050610338565b6001600360006101000a81548160ff021916908315150217905550600254905061033a565b5b5b905600a165627a7a723058202906ff200f065bf0b9e4f4d744be14a519f74f794b53a0ea5993280b38eeaf210029") diff --git a/rpc/v0/integration/v0_test.go b/rpc/v0/integration/v0_test.go index 3e57114cc..563512eb7 100644 --- a/rpc/v0/integration/v0_test.go +++ b/rpc/v0/integration/v0_test.go @@ -66,7 +66,7 @@ func TestTransactCreate(t *testing.T) { create, err := cli.Transact(v0.TransactParam{ InputAccount: inputAccount(i), Address: nil, - Data: test.StrangeLoopBytecode, + Data: test.Bytecode_strange_loop, Fee: 2, GasLimit: 10000, }) @@ -89,7 +89,7 @@ func BenchmarkTransactCreateContract(b *testing.B) { create, err := cli.Transact(v0.TransactParam{ InputAccount: inputAccount(i), Address: nil, - Data: test.StrangeLoopBytecode, + Data: test.Bytecode_strange_loop, Fee: 2, GasLimit: 10000, }) @@ -109,7 +109,7 @@ func TestTransactAndHold(t *testing.T) { create, err := cli.TransactAndHold(v0.TransactParam{ InputAccount: inputAccount(i), Address: nil, - Data: test.StrangeLoopBytecode, + Data: test.Bytecode_strange_loop, Fee: 2, GasLimit: 10000, }) diff --git a/scripts/solc_compile_go.sh b/scripts/solc_compile_go.sh new file mode 100755 index 000000000..997b7b08b --- /dev/null +++ b/scripts/solc_compile_go.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash + +script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +solidity_file="$1" +solidity_name=$(basename $1) +go_file="$2" +package=$(basename $(dirname "$go_file")) +solidity_bin=$(solc --bin "$solidity_file" | tail -1) + +cat << GOFILE > "$go_file" +package ${package} + +import "github.com/tmthrgd/go-hex" + +var Bytecode_${solidity_name%%.sol} = hex.MustDecodeString("${solidity_bin}") +GOFILE + From c6c232bee6bf58f79b25af0b266af11388fbce4f Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Thu, 28 Jun 2018 12:46:52 +0200 Subject: [PATCH 04/28] Fix latest bound off by one since end is exclusive Signed-off-by: Silas Davis --- execution/events/event.go | 1 + execution/events/key.go | 4 ++++ execution/events/pbevents/blocks.go | 4 +++- execution/events/pbevents/blocks_test.go | 2 +- 4 files changed, 9 insertions(+), 2 deletions(-) diff --git a/execution/events/event.go b/execution/events/event.go index 5830a1298..508c96776 100644 --- a/execution/events/event.go +++ b/execution/events/event.go @@ -14,6 +14,7 @@ var cdc = txs.NewAminoCodec() var eventMessageTag = event.TagMap{event.MessageTypeKey: reflect.TypeOf(&Event{}).String()} type Provider interface { + // Get events between startKey (inclusive) and endKey (exclusive) - i.e. the half open interval [start, end) GetEvents(startKey, endKey Key, consumer func(*Event) (stop bool)) (stopped bool, err error) LatestEventKey() Key } diff --git a/execution/events/key.go b/execution/events/key.go index f78463e16..52371518f 100644 --- a/execution/events/key.go +++ b/execution/events/key.go @@ -36,6 +36,10 @@ func (k Key) IsSuccessorOf(p Key) bool { return ph == kh && pi+1 == ki || ph < kh && ki == 0 } +func (k Key) IncHeight() Key { + return NewKey(k.Height()+1, k.Index()) +} + func (k Key) Bytes() []byte { return k } diff --git a/execution/events/pbevents/blocks.go b/execution/events/pbevents/blocks.go index 5513ec34c..b2df626d2 100644 --- a/execution/events/pbevents/blocks.go +++ b/execution/events/pbevents/blocks.go @@ -2,8 +2,10 @@ package pbevents import "github.com/hyperledger/burrow/execution/events" +// Get bounds suitable for events.Provider func (br *BlockRange) Bounds(latestBlockHeight uint64) (startKey, endKey events.Key, streaming bool) { - return br.GetStart().Key(latestBlockHeight), br.GetEnd().Key(latestBlockHeight), + // End bound is exclusive in state.GetEvents so we increment the height + return br.GetStart().Key(latestBlockHeight), br.GetEnd().Key(latestBlockHeight).IncHeight(), br.GetEnd().GetType() == Bound_STREAM } diff --git a/execution/events/pbevents/blocks_test.go b/execution/events/pbevents/blocks_test.go index 62641f876..a7a05b47e 100644 --- a/execution/events/pbevents/blocks_test.go +++ b/execution/events/pbevents/blocks_test.go @@ -12,6 +12,6 @@ func TestBlockRange_Bounds(t *testing.T) { br := &BlockRange{} start, end, streaming := br.Bounds(latestHeight) assert.Equal(t, events.NewKey(latestHeight, 0), start) - assert.Equal(t, events.NewKey(latestHeight, 0), end) + assert.Equal(t, events.NewKey(latestHeight+1, 0), end) assert.False(t, streaming) } From bd1d3e17004134c9218e31951e4ca78457ceeb76 Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Mon, 2 Jul 2018 13:16:10 +0200 Subject: [PATCH 05/28] Provide ability to set value to transfer in Transact* methods Signed-off-by: Silas Davis --- execution/pbtransactor/transactor.pb.go | 157 ++-- execution/pbtransactor/transactor.proto | 17 +- execution/transactor.go | 20 +- .../integration/transactor_server_test.go | 3 + rpc/rpctransactor/transactor_server.go | 6 +- rpc/test/helpers.go | 2 + rpc/v0/methods.go | 7 +- .../spf13/cobra/cobra/cmd/license_agpl.go | 683 ----------------- .../spf13/cobra/cobra/cmd/license_apache_2.go | 238 ------ .../cobra/cobra/cmd/license_bsd_clause_2.go | 71 -- .../cobra/cobra/cmd/license_bsd_clause_3.go | 78 -- .../spf13/cobra/cobra/cmd/license_gpl_2.go | 376 --------- .../spf13/cobra/cobra/cmd/license_gpl_3.go | 711 ------------------ .../spf13/cobra/cobra/cmd/license_lgpl.go | 186 ----- .../spf13/cobra/cobra/cmd/license_mit.go | 63 -- .../spf13/cobra/cobra/cmd/licenses.go | 118 --- 16 files changed, 135 insertions(+), 2601 deletions(-) delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_agpl.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_apache_2.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_2.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_3.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_2.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_3.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_lgpl.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_mit.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/licenses.go diff --git a/execution/pbtransactor/transactor.pb.go b/execution/pbtransactor/transactor.pb.go index b6f10a44c..e5c7a8934 100644 --- a/execution/pbtransactor/transactor.pb.go +++ b/execution/pbtransactor/transactor.pb.go @@ -38,7 +38,7 @@ func (m *CallParam) Reset() { *m = CallParam{} } func (m *CallParam) String() string { return proto.CompactTextString(m) } func (*CallParam) ProtoMessage() {} func (*CallParam) Descriptor() ([]byte, []int) { - return fileDescriptor_transactor_abf3bfc7b34ac7c7, []int{0} + return fileDescriptor_transactor_97142763aca9e238, []int{0} } func (m *CallParam) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_CallParam.Unmarshal(m, b) @@ -92,7 +92,7 @@ func (m *CallCodeParam) Reset() { *m = CallCodeParam{} } func (m *CallCodeParam) String() string { return proto.CompactTextString(m) } func (*CallCodeParam) ProtoMessage() {} func (*CallCodeParam) Descriptor() ([]byte, []int) { - return fileDescriptor_transactor_abf3bfc7b34ac7c7, []int{1} + return fileDescriptor_transactor_97142763aca9e238, []int{1} } func (m *CallCodeParam) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_CallCodeParam.Unmarshal(m, b) @@ -134,21 +134,28 @@ func (m *CallCodeParam) GetData() []byte { } type TransactParam struct { - InputAccount *InputAccount `protobuf:"bytes,1,opt,name=inputAccount,proto3" json:"inputAccount,omitempty"` - Address []byte `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` - Data []byte `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"` - GasLimit uint64 `protobuf:"varint,4,opt,name=gasLimit,proto3" json:"gasLimit,omitempty"` - Fee uint64 `protobuf:"varint,5,opt,name=fee,proto3" json:"fee,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + // The input account to sign with + InputAccount *InputAccount `protobuf:"bytes,1,opt,name=inputAccount,proto3" json:"inputAccount,omitempty"` + // The address of the contract to call, or omitted if creating a new contract + Address []byte `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` + // EVM bytecode payload to deliver + Data []byte `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"` + // The maximum gas to provide to the EVM when running any code - provided in order to bound the computation time + GasLimit uint64 `protobuf:"varint,4,opt,name=gasLimit,proto3" json:"gasLimit,omitempty"` + // Value to transfer, where amount = value + fee + Value uint64 `protobuf:"varint,5,opt,name=value,proto3" json:"value,omitempty"` + // Fee to offer validators for processing transaction + Fee uint64 `protobuf:"varint,6,opt,name=fee,proto3" json:"fee,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *TransactParam) Reset() { *m = TransactParam{} } func (m *TransactParam) String() string { return proto.CompactTextString(m) } func (*TransactParam) ProtoMessage() {} func (*TransactParam) Descriptor() ([]byte, []int) { - return fileDescriptor_transactor_abf3bfc7b34ac7c7, []int{2} + return fileDescriptor_transactor_97142763aca9e238, []int{2} } func (m *TransactParam) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_TransactParam.Unmarshal(m, b) @@ -196,6 +203,13 @@ func (m *TransactParam) GetGasLimit() uint64 { return 0 } +func (m *TransactParam) GetValue() uint64 { + if m != nil { + return m.Value + } + return 0 +} + func (m *TransactParam) GetFee() uint64 { if m != nil { return m.Fee @@ -216,7 +230,7 @@ func (m *SendParam) Reset() { *m = SendParam{} } func (m *SendParam) String() string { return proto.CompactTextString(m) } func (*SendParam) ProtoMessage() {} func (*SendParam) Descriptor() ([]byte, []int) { - return fileDescriptor_transactor_abf3bfc7b34ac7c7, []int{3} + return fileDescriptor_transactor_97142763aca9e238, []int{3} } func (m *SendParam) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_SendParam.Unmarshal(m, b) @@ -268,7 +282,7 @@ func (m *TxParam) Reset() { *m = TxParam{} } func (m *TxParam) String() string { return proto.CompactTextString(m) } func (*TxParam) ProtoMessage() {} func (*TxParam) Descriptor() ([]byte, []int) { - return fileDescriptor_transactor_abf3bfc7b34ac7c7, []int{4} + return fileDescriptor_transactor_97142763aca9e238, []int{4} } func (m *TxParam) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_TxParam.Unmarshal(m, b) @@ -307,7 +321,7 @@ func (m *SignTxParam) Reset() { *m = SignTxParam{} } func (m *SignTxParam) String() string { return proto.CompactTextString(m) } func (*SignTxParam) ProtoMessage() {} func (*SignTxParam) Descriptor() ([]byte, []int) { - return fileDescriptor_transactor_abf3bfc7b34ac7c7, []int{5} + return fileDescriptor_transactor_97142763aca9e238, []int{5} } func (m *SignTxParam) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_SignTxParam.Unmarshal(m, b) @@ -353,7 +367,7 @@ func (m *SignedTx) Reset() { *m = SignedTx{} } func (m *SignedTx) String() string { return proto.CompactTextString(m) } func (*SignedTx) ProtoMessage() {} func (*SignedTx) Descriptor() ([]byte, []int) { - return fileDescriptor_transactor_abf3bfc7b34ac7c7, []int{6} + return fileDescriptor_transactor_97142763aca9e238, []int{6} } func (m *SignedTx) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_SignedTx.Unmarshal(m, b) @@ -392,7 +406,7 @@ func (m *CallResult) Reset() { *m = CallResult{} } func (m *CallResult) String() string { return proto.CompactTextString(m) } func (*CallResult) ProtoMessage() {} func (*CallResult) Descriptor() ([]byte, []int) { - return fileDescriptor_transactor_abf3bfc7b34ac7c7, []int{7} + return fileDescriptor_transactor_97142763aca9e238, []int{7} } func (m *CallResult) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_CallResult.Unmarshal(m, b) @@ -439,7 +453,7 @@ func (m *TxReceipt) Reset() { *m = TxReceipt{} } func (m *TxReceipt) String() string { return proto.CompactTextString(m) } func (*TxReceipt) ProtoMessage() {} func (*TxReceipt) Descriptor() ([]byte, []int) { - return fileDescriptor_transactor_abf3bfc7b34ac7c7, []int{8} + return fileDescriptor_transactor_97142763aca9e238, []int{8} } func (m *TxReceipt) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_TxReceipt.Unmarshal(m, b) @@ -492,7 +506,7 @@ func (m *InputAccount) Reset() { *m = InputAccount{} } func (m *InputAccount) String() string { return proto.CompactTextString(m) } func (*InputAccount) ProtoMessage() {} func (*InputAccount) Descriptor() ([]byte, []int) { - return fileDescriptor_transactor_abf3bfc7b34ac7c7, []int{9} + return fileDescriptor_transactor_97142763aca9e238, []int{9} } func (m *InputAccount) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_InputAccount.Unmarshal(m, b) @@ -537,7 +551,7 @@ func (m *PrivateAccount) Reset() { *m = PrivateAccount{} } func (m *PrivateAccount) String() string { return proto.CompactTextString(m) } func (*PrivateAccount) ProtoMessage() {} func (*PrivateAccount) Descriptor() ([]byte, []int) { - return fileDescriptor_transactor_abf3bfc7b34ac7c7, []int{10} + return fileDescriptor_transactor_97142763aca9e238, []int{10} } func (m *PrivateAccount) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_PrivateAccount.Unmarshal(m, b) @@ -590,13 +604,21 @@ const _ = grpc.SupportPackageIsVersion4 // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type TransactorClient interface { + // Broadcast a signed and serialised transaction to the mempool BroadcastTx(ctx context.Context, in *TxParam, opts ...grpc.CallOption) (*TxReceipt, error) + // Perform a 'simulated' call of a contract against the current committed EVM state without any changes been saved Call(ctx context.Context, in *CallParam, opts ...grpc.CallOption) (*CallResult, error) + // Perform a 'simulated' execution of provided code against the current committed EVM state without any changes been saved CallCode(ctx context.Context, in *CallCodeParam, opts ...grpc.CallOption) (*CallResult, error) + // Formulate a CallTx transaction signed server-side Transact(ctx context.Context, in *TransactParam, opts ...grpc.CallOption) (*TxReceipt, error) + // Formulate a CallTx transaction signed server-side and wait for it to be included in a block, retrieving response TransactAndHold(ctx context.Context, in *TransactParam, opts ...grpc.CallOption) (*pbevents.EventDataCall, error) + // Formulate a SendTx transaction signed server-side Send(ctx context.Context, in *SendParam, opts ...grpc.CallOption) (*TxReceipt, error) + // Formulate a SendTx transaction signed server-side and wait for it to be included in a block, retrieving response SendAndHold(ctx context.Context, in *SendParam, opts ...grpc.CallOption) (*TxReceipt, error) + // Sign a transaction server-side SignTx(ctx context.Context, in *SignTxParam, opts ...grpc.CallOption) (*SignedTx, error) } @@ -682,13 +704,21 @@ func (c *transactorClient) SignTx(ctx context.Context, in *SignTxParam, opts ... // TransactorServer is the server API for Transactor service. type TransactorServer interface { + // Broadcast a signed and serialised transaction to the mempool BroadcastTx(context.Context, *TxParam) (*TxReceipt, error) + // Perform a 'simulated' call of a contract against the current committed EVM state without any changes been saved Call(context.Context, *CallParam) (*CallResult, error) + // Perform a 'simulated' execution of provided code against the current committed EVM state without any changes been saved CallCode(context.Context, *CallCodeParam) (*CallResult, error) + // Formulate a CallTx transaction signed server-side Transact(context.Context, *TransactParam) (*TxReceipt, error) + // Formulate a CallTx transaction signed server-side and wait for it to be included in a block, retrieving response TransactAndHold(context.Context, *TransactParam) (*pbevents.EventDataCall, error) + // Formulate a SendTx transaction signed server-side Send(context.Context, *SendParam) (*TxReceipt, error) + // Formulate a SendTx transaction signed server-side and wait for it to be included in a block, retrieving response SendAndHold(context.Context, *SendParam) (*TxReceipt, error) + // Sign a transaction server-side SignTx(context.Context, *SignTxParam) (*SignedTx, error) } @@ -882,48 +912,49 @@ var _Transactor_serviceDesc = grpc.ServiceDesc{ } func init() { - proto.RegisterFile("github.com/hyperledger/burrow/execution/pbtransactor/transactor.proto", fileDescriptor_transactor_abf3bfc7b34ac7c7) -} - -var fileDescriptor_transactor_abf3bfc7b34ac7c7 = []byte{ - // 614 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x55, 0x51, 0x6f, 0xd3, 0x30, - 0x10, 0x56, 0xd7, 0xb0, 0xb5, 0xd7, 0x6e, 0x43, 0x96, 0x18, 0x59, 0x98, 0xd0, 0x94, 0xa7, 0x3e, - 0x35, 0x68, 0x20, 0x04, 0x42, 0x0c, 0xba, 0x6e, 0x6c, 0x68, 0x20, 0x4d, 0x59, 0x78, 0xe1, 0xcd, - 0x8d, 0x6f, 0x5d, 0xa4, 0x36, 0x8e, 0x1c, 0x67, 0xcb, 0x1e, 0x79, 0xe7, 0x9f, 0xf0, 0x27, 0x91, - 0x1d, 0xa7, 0x6d, 0x52, 0x0a, 0x0c, 0xf1, 0x94, 0xbb, 0xf3, 0xe7, 0xcf, 0xdf, 0xdd, 0xf9, 0x1c, - 0x38, 0x19, 0x47, 0xf2, 0x3a, 0x1b, 0xf5, 0x43, 0x3e, 0xf5, 0xae, 0xef, 0x12, 0x14, 0x13, 0x64, - 0x63, 0x14, 0xde, 0x28, 0x13, 0x82, 0xdf, 0x7a, 0x98, 0x63, 0x98, 0xc9, 0x88, 0xc7, 0x5e, 0x32, - 0x92, 0x82, 0xc6, 0x29, 0x0d, 0x25, 0x17, 0xde, 0xdc, 0xec, 0x27, 0x82, 0x4b, 0x4e, 0xba, 0x8b, - 0xcb, 0xce, 0xf1, 0xdf, 0x92, 0xe2, 0x0d, 0xc6, 0x32, 0xf5, 0x92, 0x91, 0x31, 0x8a, 0x4f, 0xc1, - 0xe9, 0x7e, 0x86, 0xf6, 0x90, 0x4e, 0x26, 0x17, 0x54, 0xd0, 0x29, 0x21, 0x60, 0x5d, 0x09, 0x3e, - 0xb5, 0x1b, 0xfb, 0x8d, 0x5e, 0xd7, 0xd7, 0x36, 0xb1, 0x61, 0x83, 0x32, 0x26, 0x30, 0x4d, 0xed, - 0x35, 0x1d, 0x2e, 0x5d, 0x85, 0x66, 0x54, 0x52, 0xbb, 0x59, 0xa0, 0x95, 0xed, 0x9e, 0xc3, 0xa6, - 0xa2, 0x1b, 0x72, 0x86, 0xab, 0x29, 0x09, 0x58, 0x21, 0x67, 0x68, 0xf8, 0xb4, 0xfd, 0x4b, 0xb2, - 0x1f, 0x0d, 0xd8, 0x0c, 0x4c, 0xc2, 0x05, 0xdb, 0x21, 0x74, 0xa3, 0x38, 0xc9, 0xe4, 0x20, 0x0c, - 0x79, 0x16, 0x4b, 0xcd, 0xda, 0x39, 0x70, 0xfa, 0x8b, 0x85, 0xe9, 0x7f, 0x5c, 0x40, 0xf8, 0x15, - 0xfc, 0xfd, 0x92, 0x21, 0x0e, 0xb4, 0xc6, 0x34, 0xfd, 0x14, 0x4d, 0x23, 0x69, 0x5b, 0xfb, 0x8d, - 0x9e, 0xe5, 0xcf, 0x7c, 0xf2, 0x10, 0x9a, 0x57, 0x88, 0xf6, 0x03, 0x1d, 0x56, 0xa6, 0xfb, 0xad, - 0x01, 0xed, 0x4b, 0x8c, 0xd9, 0xff, 0x51, 0xba, 0x07, 0x6d, 0xc9, 0x07, 0x15, 0xad, 0xf3, 0x00, - 0xd9, 0x81, 0x75, 0x3a, 0xd5, 0xbc, 0x4d, 0x2d, 0xc0, 0x78, 0xee, 0x2e, 0x6c, 0x04, 0x79, 0x21, - 0x60, 0x0b, 0xd6, 0x64, 0x6e, 0xca, 0xbe, 0x26, 0x73, 0x17, 0xa1, 0x73, 0x19, 0x8d, 0xe3, 0x15, - 0xcb, 0xe4, 0x03, 0x6c, 0x27, 0x22, 0xba, 0xa1, 0x12, 0x8d, 0x02, 0x75, 0x6a, 0xb3, 0xd7, 0x39, - 0xd8, 0xab, 0x4a, 0xbe, 0xa8, 0x80, 0xfc, 0xfa, 0x26, 0xd7, 0x81, 0x96, 0x3a, 0x06, 0x59, 0x90, - 0x2f, 0x49, 0x38, 0x04, 0x50, 0x97, 0xc3, 0xc7, 0x34, 0x9b, 0x48, 0x95, 0x83, 0x8f, 0x32, 0x13, - 0xb1, 0x41, 0x18, 0x4f, 0xf5, 0xe8, 0x94, 0xa6, 0x5f, 0x52, 0x64, 0x3a, 0x6f, 0xcb, 0x2f, 0x5d, - 0xf7, 0x16, 0xda, 0x41, 0xee, 0x63, 0x88, 0x51, 0xa2, 0xb7, 0x07, 0xf9, 0x19, 0x4d, 0xaf, 0xcb, - 0xed, 0x85, 0x47, 0x7a, 0xb0, 0x3d, 0x14, 0x48, 0x25, 0xa6, 0x43, 0x1e, 0x4b, 0x41, 0x43, 0xa9, - 0x69, 0x5a, 0x7e, 0x3d, 0xac, 0x91, 0xc6, 0x2e, 0x0b, 0x5d, 0x74, 0xbf, 0x1e, 0x76, 0xcf, 0xa0, - 0xbb, 0xd8, 0x2a, 0xf2, 0x14, 0xc0, 0xe4, 0x7d, 0x8e, 0x77, 0xe6, 0xfc, 0x85, 0xc8, 0xea, 0x6b, - 0xe6, 0x3e, 0x83, 0xad, 0x6a, 0x05, 0x15, 0xd7, 0xc5, 0x12, 0xd7, 0x3c, 0x72, 0xf0, 0xdd, 0x02, - 0x08, 0x66, 0xf5, 0x27, 0x6f, 0xa1, 0x73, 0x24, 0x38, 0x65, 0x21, 0x4d, 0x65, 0x90, 0x93, 0x47, - 0xd5, 0xee, 0x98, 0xee, 0x3a, 0x8f, 0xeb, 0xe1, 0xb2, 0x6a, 0xaf, 0xc1, 0x52, 0x2d, 0x20, 0x35, - 0xc0, 0xec, 0x09, 0x70, 0xec, 0xe5, 0x05, 0xd3, 0xaf, 0x01, 0xb4, 0xca, 0xd1, 0x26, 0x4f, 0x96, - 0x51, 0xb3, 0x91, 0xff, 0x0d, 0xc5, 0x7b, 0x68, 0x95, 0xa9, 0xd4, 0x29, 0x2a, 0x73, 0xbe, 0x5a, - 0xff, 0x29, 0x6c, 0x97, 0xc8, 0x41, 0xcc, 0xce, 0xf8, 0x84, 0xfd, 0x99, 0xc8, 0xbc, 0x77, 0x27, - 0xea, 0x73, 0x4c, 0x25, 0xd5, 0x05, 0x78, 0x05, 0x96, 0x1a, 0xd6, 0x7a, 0x21, 0x66, 0x03, 0xbc, - 0x5a, 0xc2, 0x3b, 0xe8, 0x28, 0x54, 0x79, 0xfc, 0xfd, 0x09, 0xde, 0xc0, 0x7a, 0x31, 0x89, 0x64, - 0xb7, 0xb6, 0x77, 0x3e, 0x9f, 0xce, 0xce, 0xf2, 0x92, 0x9a, 0xa9, 0xa3, 0x97, 0x5f, 0x5f, 0xfc, - 0xcb, 0xcf, 0x64, 0xb4, 0xae, 0x9f, 0xfb, 0xe7, 0x3f, 0x03, 0x00, 0x00, 0xff, 0xff, 0xe0, 0x16, - 0x56, 0xc5, 0x8b, 0x06, 0x00, 0x00, + proto.RegisterFile("github.com/hyperledger/burrow/execution/pbtransactor/transactor.proto", fileDescriptor_transactor_97142763aca9e238) +} + +var fileDescriptor_transactor_97142763aca9e238 = []byte{ + // 625 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x55, 0x4f, 0x6f, 0xd3, 0x30, + 0x14, 0x57, 0xd7, 0xac, 0x6b, 0x5f, 0xbb, 0x0d, 0x59, 0x30, 0xb2, 0x30, 0xa1, 0x29, 0xa7, 0x9e, + 0x5a, 0x34, 0x10, 0x02, 0x21, 0x06, 0x5d, 0x37, 0x36, 0x34, 0x90, 0xa6, 0x2c, 0x5c, 0xb8, 0xb9, + 0xf1, 0x5b, 0x17, 0xa9, 0x8d, 0x23, 0xc7, 0xd9, 0xb2, 0x23, 0x77, 0xbe, 0x14, 0xdf, 0x0c, 0xd9, + 0x71, 0xda, 0x26, 0xa5, 0xc0, 0x10, 0xa7, 0xbc, 0x3f, 0x3f, 0xff, 0xde, 0x3f, 0x3f, 0x07, 0x4e, + 0xc6, 0xa1, 0xbc, 0x4e, 0x47, 0xbd, 0x80, 0x4f, 0xfb, 0xd7, 0x77, 0x31, 0x8a, 0x09, 0xb2, 0x31, + 0x8a, 0xfe, 0x28, 0x15, 0x82, 0xdf, 0xf6, 0x31, 0xc3, 0x20, 0x95, 0x21, 0x8f, 0xfa, 0xf1, 0x48, + 0x0a, 0x1a, 0x25, 0x34, 0x90, 0x5c, 0xf4, 0xe7, 0x62, 0x2f, 0x16, 0x5c, 0x72, 0xd2, 0x59, 0x74, + 0x3b, 0xc7, 0x7f, 0x4b, 0x8a, 0x37, 0x18, 0xc9, 0xa4, 0x1f, 0x8f, 0x8c, 0x90, 0x7f, 0x72, 0x4e, + 0xf7, 0x33, 0xb4, 0x86, 0x74, 0x32, 0xb9, 0xa0, 0x82, 0x4e, 0x09, 0x01, 0xeb, 0x4a, 0xf0, 0xa9, + 0x5d, 0xdb, 0xaf, 0x75, 0x3b, 0x9e, 0x96, 0x89, 0x0d, 0x1b, 0x94, 0x31, 0x81, 0x49, 0x62, 0xaf, + 0x69, 0x73, 0xa1, 0x2a, 0x34, 0xa3, 0x92, 0xda, 0xf5, 0x1c, 0xad, 0x64, 0xf7, 0x1c, 0x36, 0x15, + 0xdd, 0x90, 0x33, 0x5c, 0x4d, 0x49, 0xc0, 0x0a, 0x38, 0x43, 0xc3, 0xa7, 0xe5, 0x5f, 0x92, 0xfd, + 0xa8, 0xc1, 0xa6, 0x6f, 0x0a, 0xce, 0xd9, 0x0e, 0xa1, 0x13, 0x46, 0x71, 0x2a, 0x07, 0x41, 0xc0, + 0xd3, 0x48, 0x6a, 0xd6, 0xf6, 0x81, 0xd3, 0x5b, 0x6c, 0x4c, 0xef, 0xe3, 0x02, 0xc2, 0x2b, 0xe1, + 0xef, 0x57, 0x0c, 0x71, 0xa0, 0x39, 0xa6, 0xc9, 0xa7, 0x70, 0x1a, 0x4a, 0xdb, 0xda, 0xaf, 0x75, + 0x2d, 0x6f, 0xa6, 0x93, 0x87, 0xb0, 0x7e, 0x43, 0x27, 0x29, 0xda, 0xeb, 0xda, 0x91, 0x2b, 0xe4, + 0x01, 0xd4, 0xaf, 0x10, 0xed, 0x86, 0xb6, 0x29, 0xd1, 0xfd, 0x56, 0x83, 0xd6, 0x25, 0x46, 0xec, + 0xff, 0xe4, 0xbf, 0x07, 0x2d, 0xc9, 0x07, 0xa5, 0x0a, 0xe6, 0x06, 0xb2, 0x03, 0x0d, 0x3a, 0xd5, + 0xbc, 0x75, 0x9d, 0x80, 0xd1, 0xdc, 0x5d, 0xd8, 0xf0, 0xb3, 0x3c, 0x81, 0x2d, 0x58, 0x93, 0x99, + 0x19, 0xc6, 0x9a, 0xcc, 0x5c, 0x84, 0xf6, 0x65, 0x38, 0x8e, 0x56, 0xb8, 0xc9, 0x07, 0xd8, 0x8e, + 0x45, 0x78, 0x43, 0x25, 0x9a, 0x0c, 0x54, 0xd4, 0x7a, 0xb7, 0x7d, 0xb0, 0x57, 0x4e, 0xf9, 0xa2, + 0x04, 0xf2, 0xaa, 0x87, 0x5c, 0x07, 0x9a, 0x2a, 0x0c, 0x32, 0x3f, 0x5b, 0x4a, 0xe1, 0x10, 0x40, + 0x5d, 0x19, 0x0f, 0x93, 0x74, 0x22, 0x55, 0x0d, 0x1e, 0xca, 0x54, 0x44, 0x06, 0x61, 0x34, 0x35, + 0xb9, 0x53, 0x9a, 0x7c, 0x49, 0x90, 0xe9, 0xba, 0x2d, 0xaf, 0x50, 0xdd, 0x5b, 0x68, 0xf9, 0x99, + 0x87, 0x01, 0x86, 0xb1, 0x3e, 0xee, 0x67, 0x67, 0x34, 0xb9, 0x2e, 0x8e, 0xe7, 0x1a, 0xe9, 0xc2, + 0xf6, 0x50, 0x20, 0x95, 0x98, 0x0c, 0x79, 0x24, 0x05, 0x0d, 0xa4, 0xa6, 0x69, 0x7a, 0x55, 0xb3, + 0x46, 0x1a, 0xb9, 0x68, 0x74, 0x7e, 0x27, 0xaa, 0x66, 0xf7, 0x0c, 0x3a, 0x8b, 0xa3, 0x22, 0x4f, + 0x01, 0x4c, 0xdd, 0xe7, 0x78, 0x67, 0xe2, 0x2f, 0x58, 0x56, 0x5f, 0x3e, 0xf7, 0x19, 0x6c, 0x95, + 0x3b, 0xa8, 0xb8, 0x2e, 0x96, 0xb8, 0xe6, 0x96, 0x83, 0xef, 0x16, 0x80, 0x3f, 0xeb, 0x3f, 0x79, + 0x0b, 0xed, 0x23, 0xc1, 0x29, 0x0b, 0x68, 0x22, 0xfd, 0x8c, 0x3c, 0x2a, 0x4f, 0xc7, 0x4c, 0xd7, + 0x79, 0x5c, 0x35, 0x17, 0x5d, 0x7b, 0x0d, 0x96, 0x1a, 0x01, 0xa9, 0x00, 0x66, 0x0f, 0x83, 0x63, + 0x2f, 0x3b, 0xcc, 0xbc, 0x06, 0xd0, 0x2c, 0x16, 0x9e, 0x3c, 0x59, 0x46, 0xcd, 0x1e, 0x82, 0xdf, + 0x50, 0xbc, 0x87, 0x66, 0x51, 0x4a, 0x95, 0xa2, 0xb4, 0xfd, 0xab, 0xf3, 0x3f, 0x85, 0xed, 0x02, + 0x39, 0x88, 0xd8, 0x19, 0x9f, 0xb0, 0x3f, 0x13, 0x99, 0x57, 0xf0, 0x44, 0x7d, 0x8e, 0xa9, 0xa4, + 0xba, 0x01, 0xaf, 0xc0, 0x52, 0xcb, 0x5a, 0x6d, 0xc4, 0x6c, 0x81, 0x57, 0xa7, 0xf0, 0x0e, 0xda, + 0x0a, 0x55, 0x84, 0xbf, 0x3f, 0xc1, 0x1b, 0x68, 0xe4, 0x9b, 0x48, 0x76, 0x2b, 0x67, 0xe7, 0xfb, + 0xe9, 0xec, 0x2c, 0xbb, 0xd4, 0x4e, 0x1d, 0xbd, 0xfc, 0xfa, 0xe2, 0x5f, 0x7e, 0x31, 0xa3, 0x86, + 0xfe, 0x09, 0x3c, 0xff, 0x19, 0x00, 0x00, 0xff, 0xff, 0x51, 0xbd, 0x3d, 0xf0, 0xa1, 0x06, 0x00, + 0x00, } diff --git a/execution/pbtransactor/transactor.proto b/execution/pbtransactor/transactor.proto index 07679018b..dd058388d 100644 --- a/execution/pbtransactor/transactor.proto +++ b/execution/pbtransactor/transactor.proto @@ -8,13 +8,21 @@ import "github.com/hyperledger/burrow/execution/events/pbevents/events.proto"; // Transaction Service Definition service Transactor { + // Broadcast a signed and serialised transaction to the mempool rpc BroadcastTx (TxParam) returns (TxReceipt); + // Perform a 'simulated' call of a contract against the current committed EVM state without any changes been saved rpc Call (CallParam) returns (CallResult); + // Perform a 'simulated' execution of provided code against the current committed EVM state without any changes been saved rpc CallCode (CallCodeParam) returns (CallResult); + // Formulate a CallTx transaction signed server-side rpc Transact (TransactParam) returns (TxReceipt); + // Formulate a CallTx transaction signed server-side and wait for it to be included in a block, retrieving response rpc TransactAndHold (TransactParam) returns (pbevents.EventDataCall); + // Formulate a SendTx transaction signed server-side rpc Send (SendParam) returns (TxReceipt); + // Formulate a SendTx transaction signed server-side and wait for it to be included in a block, retrieving response rpc SendAndHold (SendParam) returns (TxReceipt); + // Sign a transaction server-side rpc SignTx (SignTxParam) returns (SignedTx); } @@ -32,11 +40,18 @@ message CallCodeParam { } message TransactParam { + // The input account to sign with InputAccount inputAccount = 1; + // The address of the contract to call, or omitted if creating a new contract bytes address = 2; + // EVM bytecode payload to deliver bytes data = 3; + // The maximum gas to provide to the EVM when running any code - provided in order to bound the computation time uint64 gasLimit = 4; - uint64 fee = 5; + // Value to transfer, where amount = value + fee + uint64 value = 5; + // Fee to offer validators for processing transaction + uint64 fee = 6; } message SendParam { diff --git a/execution/transactor.go b/execution/transactor.go index b620d481d..c4d57bba1 100644 --- a/execution/transactor.go +++ b/execution/transactor.go @@ -192,7 +192,7 @@ func (trans *Transactor) BroadcastTxRaw(txBytes []byte) (*txs.Receipt, error) { // Orders calls to BroadcastTx using lock (waits for response from core before releasing) func (trans *Transactor) Transact(sequentialSigningAccount *SequentialSigningAccount, address *crypto.Address, data []byte, - gasLimit, fee uint64) (*txs.Receipt, error) { + gasLimit, value, fee uint64) (*txs.Receipt, error) { // Use the get the freshest sequence numbers from mempool state and hold the lock until we get a response from // CheckTx @@ -201,8 +201,10 @@ func (trans *Transactor) Transact(sequentialSigningAccount *SequentialSigningAcc return nil, err } defer unlock() - - txEnv, err := trans.formulateCallTx(inputAccount, address, data, gasLimit, fee) + if binary.IsUint64SumOverflow(value, fee) { + return nil, fmt.Errorf("amount to transfer overflows uint64 amount = %v (value) + %v (fee)", value, fee) + } + txEnv, err := trans.formulateCallTx(inputAccount, address, data, gasLimit, value+fee, fee) if err != nil { return nil, err } @@ -210,15 +212,17 @@ func (trans *Transactor) Transact(sequentialSigningAccount *SequentialSigningAcc } func (trans *Transactor) TransactAndHold(ctx context.Context, sequentialSigningAccount *SequentialSigningAccount, - address *crypto.Address, data []byte, gasLimit, fee uint64) (*events.EventDataCall, error) { + address *crypto.Address, data []byte, gasLimit, value, fee uint64) (*events.EventDataCall, error) { inputAccount, unlock, err := sequentialSigningAccount.Lock() if err != nil { return nil, err } defer unlock() - - callTxEnv, err := trans.formulateCallTx(inputAccount, address, data, gasLimit, fee) + if binary.IsUint64SumOverflow(value, fee) { + return nil, fmt.Errorf("amount to transfer overflows uint64 amount = %v (value) + %v (fee)", value, fee) + } + callTxEnv, err := trans.formulateCallTx(inputAccount, address, data, gasLimit, value+fee, fee) if err != nil { return nil, err } @@ -268,11 +272,11 @@ func (trans *Transactor) TransactAndHold(ctx context.Context, sequentialSigningA } } func (trans *Transactor) formulateCallTx(inputAccount *SigningAccount, address *crypto.Address, data []byte, - gasLimit, fee uint64) (*txs.Envelope, error) { + gasLimit, amount, fee uint64) (*txs.Envelope, error) { txInput := &payload.TxInput{ Address: inputAccount.Address(), - Amount: fee, + Amount: amount, Sequence: inputAccount.Sequence() + 1, } tx := &payload.CallTx{ diff --git a/rpc/rpctransactor/integration/transactor_server_test.go b/rpc/rpctransactor/integration/transactor_server_test.go index 80c79df92..cbb1a1c75 100644 --- a/rpc/rpctransactor/integration/transactor_server_test.go +++ b/rpc/rpctransactor/integration/transactor_server_test.go @@ -44,6 +44,7 @@ func TestTransactCallNoCode(t *testing.T) { InputAccount: inputAccount(i), Address: toAddress.Bytes(), Data: []byte{}, + Value: 0, Fee: 2, GasLimit: 10000 + uint64(i), }) @@ -68,6 +69,7 @@ func TestTransactCreate(t *testing.T) { InputAccount: inputAccount(i), Address: nil, Data: test.Bytecode_strange_loop, + Value: 0, Fee: 2, GasLimit: 10000, }) @@ -90,6 +92,7 @@ func BenchmarkTransactCreateContract(b *testing.B) { InputAccount: inputAccount(i), Address: nil, Data: test.Bytecode_strange_loop, + Value: 0, Fee: 2, GasLimit: 10000, }) diff --git a/rpc/rpctransactor/transactor_server.go b/rpc/rpctransactor/transactor_server.go index 53c973fd0..aeed1c4b0 100644 --- a/rpc/rpctransactor/transactor_server.go +++ b/rpc/rpctransactor/transactor_server.go @@ -73,7 +73,7 @@ func (ts *transactorServer) Transact(ctx context.Context, param *pbtransactor.Tr if err != nil { return nil, err } - receipt, err := ts.transactor.Transact(inputAccount, address, param.GetData(), param.GetGasLimit(), + receipt, err := ts.transactor.Transact(inputAccount, address, param.GetData(), param.GetGasLimit(), param.GetValue(), param.GetFee()) if err != nil { return nil, err @@ -90,8 +90,8 @@ func (ts *transactorServer) TransactAndHold(ctx context.Context, param *pbtransa if err != nil { return nil, err } - edt, err := ts.transactor.TransactAndHold(ctx, inputAccount, address, param.GetData(), - param.GetGasLimit(), param.GetFee()) + edt, err := ts.transactor.TransactAndHold(ctx, inputAccount, address, param.GetData(), param.GetGasLimit(), + param.GetValue(), param.GetFee()) if err != nil { return nil, err } diff --git a/rpc/test/helpers.go b/rpc/test/helpers.go index e994045b4..0e7d934f5 100644 --- a/rpc/test/helpers.go +++ b/rpc/test/helpers.go @@ -73,6 +73,7 @@ func CreateContract(t testing.TB, cli pbtransactor.TransactorClient, InputAccount: inputAccount, Address: nil, Data: Bytecode_strange_loop, + Value: 0, Fee: 2, GasLimit: 10000, }) @@ -89,6 +90,7 @@ func CallContract(t testing.TB, cli pbtransactor.TransactorClient, InputAccount: inputAccount, Address: contractAddress, Data: functionID[:], + Value: 0, Fee: 2, GasLimit: 10000, }) diff --git a/rpc/v0/methods.go b/rpc/v0/methods.go index 224ce798d..7b510f23c 100644 --- a/rpc/v0/methods.go +++ b/rpc/v0/methods.go @@ -238,7 +238,9 @@ func GetMethods(codec rpc.Codec, service *rpc.Service, logger *logging.Logger) m if err != nil { return nil, rpc.INVALID_PARAMS, err } - receipt, err := service.Transactor().Transact(inputAccount, address, param.Data, param.GasLimit, param.Fee) + // We ensure zero value transfer for legacy compatibility reason (i.e. we always have) + receipt, err := service.Transactor().Transact(inputAccount, address, param.Data, param.GasLimit, 0, + param.Fee) if err != nil { return nil, rpc.INTERNAL_ERROR, err } @@ -259,8 +261,9 @@ func GetMethods(codec rpc.Codec, service *rpc.Service, logger *logging.Logger) m if err != nil { return nil, rpc.INVALID_PARAMS, err } + // We ensure zero value transfer for legacy compatibility reason (i.e. we always have) eventDataCall, err := service.Transactor().TransactAndHold(context.Background(), inputAccount, address, - param.Data, param.GasLimit, param.Fee) + param.Data, param.GasLimit, 0, param.Fee) if err != nil { return nil, rpc.INTERNAL_ERROR, err } diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/license_agpl.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_agpl.go deleted file mode 100644 index bc22e9732..000000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/license_agpl.go +++ /dev/null @@ -1,683 +0,0 @@ -package cmd - -func initAgpl() { - Licenses["agpl"] = License{ - Name: "GNU Affero General Public License", - PossibleMatches: []string{"agpl", "affero gpl", "gnu agpl"}, - Header: ` -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see .`, - Text: ` GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU Affero General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU Affero General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU AGPL, see -. -`, - } -} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/license_apache_2.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_apache_2.go deleted file mode 100644 index 38393d541..000000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/license_apache_2.go +++ /dev/null @@ -1,238 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Parts inspired by https://github.com/ryanuber/go-license - -package cmd - -func initApache2() { - Licenses["apache"] = License{ - Name: "Apache 2.0", - PossibleMatches: []string{"apache", "apache20", "apache 2.0", "apache2.0", "apache-2.0"}, - Header: ` -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License.`, - Text: ` - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -`, - } -} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_2.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_2.go deleted file mode 100644 index 4a847e04a..000000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_2.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Parts inspired by https://github.com/ryanuber/go-license - -package cmd - -func initBsdClause2() { - Licenses["freebsd"] = License{ - Name: "Simplified BSD License", - PossibleMatches: []string{"freebsd", "simpbsd", "simple bsd", "2-clause bsd", - "2 clause bsd", "simplified bsd license"}, - Header: `All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE.`, - Text: `{{ .copyright }} -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -`, - } -} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_3.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_3.go deleted file mode 100644 index c7476b31f..000000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_3.go +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Parts inspired by https://github.com/ryanuber/go-license - -package cmd - -func initBsdClause3() { - Licenses["bsd"] = License{ - Name: "NewBSD", - PossibleMatches: []string{"bsd", "newbsd", "3 clause bsd", "3-clause bsd"}, - Header: `All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors - may be used to endorse or promote products derived from this software - without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE.`, - Text: `{{ .copyright }} -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors - may be used to endorse or promote products derived from this software - without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -`, - } -} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_2.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_2.go deleted file mode 100644 index 03e05b3a7..000000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_2.go +++ /dev/null @@ -1,376 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Parts inspired by https://github.com/ryanuber/go-license - -package cmd - -func initGpl2() { - Licenses["gpl2"] = License{ - Name: "GNU General Public License 2.0", - PossibleMatches: []string{"gpl2", "gnu gpl2", "gplv2"}, - Header: ` -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU Lesser General Public License -along with this program. If not, see .`, - Text: ` GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type 'show c' for details. - -The hypothetical commands 'show w' and 'show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than 'show w' and 'show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - 'Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. -`, - } -} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_3.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_3.go deleted file mode 100644 index ce07679c7..000000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_3.go +++ /dev/null @@ -1,711 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Parts inspired by https://github.com/ryanuber/go-license - -package cmd - -func initGpl3() { - Licenses["gpl3"] = License{ - Name: "GNU General Public License 3.0", - PossibleMatches: []string{"gpl3", "gplv3", "gpl", "gnu gpl3", "gnu gpl"}, - Header: ` -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see .`, - Text: ` GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type 'show c' for details. - -The hypothetical commands 'show w' and 'show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. -`, - } -} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/license_lgpl.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_lgpl.go deleted file mode 100644 index 0f8b96cad..000000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/license_lgpl.go +++ /dev/null @@ -1,186 +0,0 @@ -package cmd - -func initLgpl() { - Licenses["lgpl"] = License{ - Name: "GNU Lesser General Public License", - PossibleMatches: []string{"lgpl", "lesser gpl", "gnu lgpl"}, - Header: ` -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Lesser General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public License -along with this program. If not, see .`, - Text: ` GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library.`, - } -} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/license_mit.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_mit.go deleted file mode 100644 index bd2d0c4fa..000000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/license_mit.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Parts inspired by https://github.com/ryanuber/go-license - -package cmd - -func initMit() { - Licenses["mit"] = License{ - Name: "MIT License", - PossibleMatches: []string{"mit"}, - Header: ` -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE.`, - Text: `The MIT License (MIT) - -{{ .copyright }} - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -`, - } -} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/licenses.go b/vendor/github.com/spf13/cobra/cobra/cmd/licenses.go deleted file mode 100644 index a070134dd..000000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/licenses.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Parts inspired by https://github.com/ryanuber/go-license - -package cmd - -import ( - "strings" - "time" - - "github.com/spf13/viper" -) - -// Licenses contains all possible licenses a user can choose from. -var Licenses = make(map[string]License) - -// License represents a software license agreement, containing the Name of -// the license, its possible matches (on the command line as given to cobra), -// the header to be used with each file on the file's creating, and the text -// of the license -type License struct { - Name string // The type of license in use - PossibleMatches []string // Similar names to guess - Text string // License text data - Header string // License header for source files -} - -func init() { - // Allows a user to not use a license. - Licenses["none"] = License{"None", []string{"none", "false"}, "", ""} - - initApache2() - initMit() - initBsdClause3() - initBsdClause2() - initGpl2() - initGpl3() - initLgpl() - initAgpl() -} - -// getLicense returns license specified by user in flag or in config. -// If user didn't specify the license, it returns Apache License 2.0. -// -// TODO: Inspect project for existing license -func getLicense() License { - // If explicitly flagged, use that. - if userLicense != "" { - return findLicense(userLicense) - } - - // If user wants to have custom license, use that. - if viper.IsSet("license.header") || viper.IsSet("license.text") { - return License{Header: viper.GetString("license.header"), - Text: viper.GetString("license.text")} - } - - // If user wants to have built-in license, use that. - if viper.IsSet("license") { - return findLicense(viper.GetString("license")) - } - - // If user didn't set any license, use Apache 2.0 by default. - return Licenses["apache"] -} - -func copyrightLine() string { - author := viper.GetString("author") - - year := viper.GetString("year") // For tests. - if year == "" { - year = time.Now().Format("2006") - } - - return "Copyright © " + year + " " + author -} - -// findLicense looks for License object of built-in licenses. -// If it didn't find license, then the app will be terminated and -// error will be printed. -func findLicense(name string) License { - found := matchLicense(name) - if found == "" { - er("unknown license: " + name) - } - return Licenses[found] -} - -// matchLicense compares the given a license name -// to PossibleMatches of all built-in licenses. -// It returns blank string, if name is blank string or it didn't find -// then appropriate match to name. -func matchLicense(name string) string { - if name == "" { - return "" - } - - for key, lic := range Licenses { - for _, match := range lic.PossibleMatches { - if strings.EqualFold(name, match) { - return key - } - } - } - - return "" -} From 070d01e5bd833d393927b1dd863da92a630e9bfb Mon Sep 17 00:00:00 2001 From: Casey Kuhlman Date: Mon, 2 Jul 2018 23:36:27 +0100 Subject: [PATCH 06/28] move dockerfile Signed-off-by: Casey Kuhlman --- .circleci/Dockerfile | 6 +++--- .circleci/config.yml | 3 +-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/.circleci/Dockerfile b/.circleci/Dockerfile index 072232c14..62926585e 100644 --- a/.circleci/Dockerfile +++ b/.circleci/Dockerfile @@ -1,10 +1,10 @@ -# docker build -t quay.io/monax/burrow:ci . +# docker build -t quay.io/monax/build:burrow-ci . FROM golang:1.10.1-alpine3.7 MAINTAINER Monax ENV DOCKER_VERSION "17.12.1-ce" # This is the image used by the Circle CI config in this directory pushed to quay.io/monax/bosmarmot:ci -# docker build -t quay.io/monax/burrow:ci -f ./.circleci/Dockerfile . +# docker build -t quay.io/monax/build:burrow-ci -f ./.circleci/Dockerfile . RUN apk add --update --no-cache nodejs netcat-openbsd git openssh-client openssl make bash gcc g++ jq curl # get docker client RUN curl -L -o /tmp/docker-$DOCKER_VERSION.tgz https://download.docker.com/linux/static/stable/x86_64/docker-$DOCKER_VERSION.tgz \ @@ -14,4 +14,4 @@ RUN curl -L -o /tmp/docker-$DOCKER_VERSION.tgz https://download.docker.com/linux RUN go get github.com/jstemmer/go-junit-report RUN go get -u github.com/golang/dep/cmd/dep RUN npm install -g mocha -RUN npm install -g mocha-circleci-reporter \ No newline at end of file +RUN npm install -g mocha-circleci-reporter diff --git a/.circleci/config.yml b/.circleci/config.yml index e062f4238..3f8b04082 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -4,7 +4,7 @@ defaults: &defaults working_directory: /go/src/github.com/hyperledger/burrow docker: - - image: quay.io/monax/burrow:ci + - image: quay.io/monax/build:burrow-ci tag_filters: &tags_filters tags: @@ -130,4 +130,3 @@ workflows: <<: *tags_filters branches: only: develop - From 22905a034f7588e8ef5e250893006db6d53c93e9 Mon Sep 17 00:00:00 2001 From: Sean Young Date: Wed, 4 Jul 2018 14:34:47 +0100 Subject: [PATCH 07/28] Add new yaml function to burrow configure templating Now the the genesis spec can be generated as yaml or json. << yaml .Config >> << json .Config >> Since the return value of yaml is string, json can also be used to double quote and string escape the yaml. << json (yaml .Config) >> Signed-off-by: Sean Young --- Gopkg.lock | 12 ++++++------ deployment/config.go | 9 +++++++++ genesis/genesis.go | 2 +- vendor/github.com/prometheus/procfs/xfrm.go | 2 +- vendor/golang.org/x/net/http2/flow.go | 10 +++++----- vendor/golang.org/x/net/http2/server.go | 13 +++++++++++++ vendor/golang.org/x/sys/unix/fcntl.go | 6 +++++- .../golang.org/x/sys/unix/syscall_solaris.go | 6 +++++- vendor/golang.org/x/sys/windows/service.go | 18 ++++++++++++++++++ 9 files changed, 63 insertions(+), 15 deletions(-) diff --git a/Gopkg.lock b/Gopkg.lock index 04895d2aa..6a5ce6ba6 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -210,7 +210,7 @@ branch = "master" name = "github.com/prometheus/client_golang" packages = ["prometheus"] - revision = "77e8f2ddcfed59ece3a8151879efb2304b5cbbcf" + revision = "d6a9817c4afc94d51115e4a30d449056a3fbf547" [[projects]] branch = "master" @@ -237,7 +237,7 @@ "nfs", "xfs" ] - revision = "7d6f385de8bea29190f15ba9931442a0eaef9af7" + revision = "40f013a808ec4fa79def444a1a56de4d1727efcb" [[projects]] branch = "master" @@ -440,7 +440,7 @@ "internal/timeseries", "trace" ] - revision = "afe8f62b1d6bbd81f31868121a50b06d8188e1f9" + revision = "ed29d75add3d7c4bf7ca65aac0c6df3d1420216f" [[projects]] branch = "master" @@ -450,7 +450,7 @@ "unix", "windows" ] - revision = "a200a19cb90b19de298170992778b1fda7217bd6" + revision = "151529c776cdc58ddbe7963ba9af779f3577b419" [[projects]] name = "golang.org/x/text" @@ -477,7 +477,7 @@ branch = "master" name = "google.golang.org/genproto" packages = ["googleapis/rpc/status"] - revision = "80063a038e333bbe006c878e4c5ce4c74d055498" + revision = "ff3583edef7de132f219f0efc00e097cabcc0ec0" [[projects]] name = "google.golang.org/grpc" @@ -533,6 +533,6 @@ [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "ab60dfe224ea60fe247e9585bba9cd57e37f1e03a1fca0eb368291e28cfb71df" + inputs-digest = "7b9b17cb4d553647a445b9cefe47cea819dac89f8787efc9ed2992ef585c9948" solver-name = "gps-cdcl" solver-version = 1 diff --git a/deployment/config.go b/deployment/config.go index a9bab141b..dc70796d6 100644 --- a/deployment/config.go +++ b/deployment/config.go @@ -12,6 +12,7 @@ import ( "github.com/hyperledger/burrow/genesis" "github.com/pkg/errors" "github.com/tmthrgd/go-hex" + "gopkg.in/yaml.v2" ) type Validator struct { @@ -45,6 +46,14 @@ var templateFuncs template.FuncMap = map[string]interface{}{ "hex": func(rv reflect.Value) string { return encode(rv, hex.EncodeUpperToString) }, + "yaml": func(rv interface{}) string { + a, _ := yaml.Marshal(rv) + return string(a) + }, + "json": func(rv interface{}) string { + b, _ := json.Marshal(rv) + return string(b) + }, } const DefaultKeysExportFormat = `{ diff --git a/genesis/genesis.go b/genesis/genesis.go index 5a6e07603..d60564415 100644 --- a/genesis/genesis.go +++ b/genesis/genesis.go @@ -50,7 +50,7 @@ type Account struct { type Validator struct { BasicAccount - NodeAddress *crypto.Address `json:",omitempty" toml:",omitempty"` + NodeAddress *crypto.Address `json:",omitempty" toml:",omitempty" yaml:",omitempty"` Name string UnbondTo []BasicAccount } diff --git a/vendor/github.com/prometheus/procfs/xfrm.go b/vendor/github.com/prometheus/procfs/xfrm.go index ffe9df50d..8f1508f0f 100644 --- a/vendor/github.com/prometheus/procfs/xfrm.go +++ b/vendor/github.com/prometheus/procfs/xfrm.go @@ -113,7 +113,7 @@ func (fs FS) NewXfrmStat() (XfrmStat, error) { if len(fields) != 2 { return XfrmStat{}, fmt.Errorf( - "couldnt parse %s line %s", file.Name(), s.Text()) + "couldn't parse %s line %s", file.Name(), s.Text()) } name := fields[0] diff --git a/vendor/golang.org/x/net/http2/flow.go b/vendor/golang.org/x/net/http2/flow.go index 957de2542..cea601fcd 100644 --- a/vendor/golang.org/x/net/http2/flow.go +++ b/vendor/golang.org/x/net/http2/flow.go @@ -41,10 +41,10 @@ func (f *flow) take(n int32) { // add adds n bytes (positive or negative) to the flow control window. // It returns false if the sum would exceed 2^31-1. func (f *flow) add(n int32) bool { - remain := (1<<31 - 1) - f.n - if n > remain { - return false + sum := f.n + n + if (sum > n) == (f.n > 0) { + f.n = sum + return true } - f.n += n - return true + return false } diff --git a/vendor/golang.org/x/net/http2/server.go b/vendor/golang.org/x/net/http2/server.go index 769c0fe5e..793899169 100644 --- a/vendor/golang.org/x/net/http2/server.go +++ b/vendor/golang.org/x/net/http2/server.go @@ -2347,6 +2347,19 @@ func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) { foreachHeaderElement(v, rws.declareTrailer) } + // "Connection" headers aren't allowed in HTTP/2 (RFC 7540, 8.1.2.2), + // but respect "Connection" == "close" to mean sending a GOAWAY and tearing + // down the TCP connection when idle, like we do for HTTP/1. + // TODO: remove more Connection-specific header fields here, in addition + // to "Connection". + if _, ok := rws.snapHeader["Connection"]; ok { + v := rws.snapHeader.Get("Connection") + delete(rws.snapHeader, "Connection") + if v == "close" { + rws.conn.startGracefulShutdown() + } + } + endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{ streamID: rws.stream.id, diff --git a/vendor/golang.org/x/sys/unix/fcntl.go b/vendor/golang.org/x/sys/unix/fcntl.go index 0c58c7e1e..9379ba9ce 100644 --- a/vendor/golang.org/x/sys/unix/fcntl.go +++ b/vendor/golang.org/x/sys/unix/fcntl.go @@ -14,7 +14,11 @@ var fcntl64Syscall uintptr = SYS_FCNTL // FcntlInt performs a fcntl syscall on fd with the provided command and argument. func FcntlInt(fd uintptr, cmd, arg int) (int, error) { - valptr, _, err := Syscall(fcntl64Syscall, fd, uintptr(cmd), uintptr(arg)) + valptr, _, errno := Syscall(fcntl64Syscall, fd, uintptr(cmd), uintptr(arg)) + var err error + if errno != 0 { + err = errno + } return int(valptr), err } diff --git a/vendor/golang.org/x/sys/unix/syscall_solaris.go b/vendor/golang.org/x/sys/unix/syscall_solaris.go index 4d7efbc27..820ef77af 100644 --- a/vendor/golang.org/x/sys/unix/syscall_solaris.go +++ b/vendor/golang.org/x/sys/unix/syscall_solaris.go @@ -314,7 +314,11 @@ func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error { // FcntlInt performs a fcntl syscall on fd with the provided command and argument. func FcntlInt(fd uintptr, cmd, arg int) (int, error) { - valptr, _, err := sysvicall6(uintptr(unsafe.Pointer(&procfcntl)), 3, uintptr(fd), uintptr(cmd), uintptr(arg), 0, 0, 0) + valptr, _, errno := sysvicall6(uintptr(unsafe.Pointer(&procfcntl)), 3, uintptr(fd), uintptr(cmd), uintptr(arg), 0, 0, 0) + var err error + if errno != 0 { + err = errno + } return int(valptr), err } diff --git a/vendor/golang.org/x/sys/windows/service.go b/vendor/golang.org/x/sys/windows/service.go index 24aa90bbb..62fc31b40 100644 --- a/vendor/golang.org/x/sys/windows/service.go +++ b/vendor/golang.org/x/sys/windows/service.go @@ -43,6 +43,11 @@ const ( SC_STATUS_PROCESS_INFO = 0 + SC_ACTION_NONE = 0 + SC_ACTION_RESTART = 1 + SC_ACTION_REBOOT = 2 + SC_ACTION_RUN_COMMAND = 3 + SERVICE_STOPPED = 1 SERVICE_START_PENDING = 2 SERVICE_STOP_PENDING = 3 @@ -148,6 +153,19 @@ type ENUM_SERVICE_STATUS_PROCESS struct { ServiceStatusProcess SERVICE_STATUS_PROCESS } +type SERVICE_FAILURE_ACTIONS struct { + ResetPeriod uint32 + RebootMsg *uint16 + Command *uint16 + ActionsCount uint32 + Actions *SC_ACTION +} + +type SC_ACTION struct { + Type uint32 + Delay uint32 +} + //sys CloseServiceHandle(handle Handle) (err error) = advapi32.CloseServiceHandle //sys CreateService(mgr Handle, serviceName *uint16, displayName *uint16, access uint32, srvType uint32, startType uint32, errCtl uint32, pathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16) (handle Handle, err error) [failretval==0] = advapi32.CreateServiceW //sys OpenService(mgr Handle, serviceName *uint16, access uint32) (handle Handle, err error) [failretval==0] = advapi32.OpenServiceW From fa40f57847f424fde4f140390ba64dfe30fc3d6b Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Wed, 18 Jul 2018 17:26:25 +0100 Subject: [PATCH 08/28] Update dep and vendor Signed-off-by: Silas Davis --- Gopkg.lock | 262 +- Gopkg.toml | 16 +- vendor/github.com/gin-contrib/sse/LICENSE | 21 - .../github.com/gin-contrib/sse/sse-decoder.go | 116 - .../github.com/gin-contrib/sse/sse-encoder.go | 110 - vendor/github.com/gin-contrib/sse/writer.go | 24 - vendor/github.com/gin-gonic/gin/AUTHORS.md | 227 - vendor/github.com/gin-gonic/gin/LICENSE | 21 - vendor/github.com/gin-gonic/gin/auth.go | 92 - .../gin-gonic/gin/binding/binding.go | 72 - .../gin/binding/default_validator.go | 45 - .../github.com/gin-gonic/gin/binding/form.go | 54 - .../gin-gonic/gin/binding/form_mapping.go | 182 - .../github.com/gin-gonic/gin/binding/json.go | 24 - .../gin-gonic/gin/binding/msgpack.go | 28 - .../gin-gonic/gin/binding/protobuf.go | 35 - .../github.com/gin-gonic/gin/binding/xml.go | 24 - vendor/github.com/gin-gonic/gin/context.go | 766 - .../gin-gonic/gin/context_appengine.go | 11 - vendor/github.com/gin-gonic/gin/debug.go | 71 - vendor/github.com/gin-gonic/gin/deprecated.go | 25 - vendor/github.com/gin-gonic/gin/errors.go | 159 - vendor/github.com/gin-gonic/gin/fs.go | 46 - vendor/github.com/gin-gonic/gin/gin.go | 418 - vendor/github.com/gin-gonic/gin/logger.go | 142 - vendor/github.com/gin-gonic/gin/mode.go | 69 - vendor/github.com/gin-gonic/gin/path.go | 123 - vendor/github.com/gin-gonic/gin/recovery.go | 108 - .../github.com/gin-gonic/gin/render/data.go | 23 - .../github.com/gin-gonic/gin/render/html.go | 82 - .../github.com/gin-gonic/gin/render/json.go | 57 - .../gin-gonic/gin/render/msgpack.go | 31 - .../gin-gonic/gin/render/redirect.go | 26 - .../github.com/gin-gonic/gin/render/render.go | 34 - .../github.com/gin-gonic/gin/render/text.go | 36 - vendor/github.com/gin-gonic/gin/render/xml.go | 25 - .../github.com/gin-gonic/gin/render/yaml.go | 33 - .../gin-gonic/gin/response_writer.go | 116 - .../github.com/gin-gonic/gin/routergroup.go | 215 - .../github.com/gin-gonic/gin/test_helpers.go | 17 - vendor/github.com/gin-gonic/gin/tree.go | 622 - vendor/github.com/gin-gonic/gin/utils.go | 154 - .../gogo/protobuf/gogoproto/Makefile | 37 + .../gogo/protobuf/gogoproto/gogo.pb.go | 333 +- .../gogo/protobuf/gogoproto/gogo.pb.golden | 45 + .../gogo/protobuf/gogoproto/gogo.proto | 136 + .../gogo/protobuf/gogoproto/helper.go | 7 +- .../github.com/gogo/protobuf/jsonpb/jsonpb.go | 188 +- .../github.com/gogo/protobuf/proto/Makefile | 43 + .../github.com/gogo/protobuf/proto/clone.go | 46 +- .../gogo/protobuf/proto/custom_gogo.go | 39 + .../github.com/gogo/protobuf/proto/decode.go | 676 +- .../gogo/protobuf/proto/decode_gogo.go | 172 - .../github.com/gogo/protobuf/proto/discard.go | 201 +- .../gogo/protobuf/proto/duration_gogo.go | 154 - .../github.com/gogo/protobuf/proto/encode.go | 1191 +- .../gogo/protobuf/proto/encode_gogo.go | 317 - .../github.com/gogo/protobuf/proto/equal.go | 30 +- .../gogo/protobuf/proto/extensions.go | 283 +- .../gogo/protobuf/proto/extensions_gogo.go | 162 +- vendor/github.com/gogo/protobuf/proto/lib.go | 70 +- .../gogo/protobuf/proto/lib_gogo.go | 8 + .../gogo/protobuf/proto/message_set.go | 81 +- .../gogo/protobuf/proto/pointer_reflect.go | 595 +- .../protobuf/proto/pointer_reflect_gogo.go | 64 +- .../gogo/protobuf/proto/pointer_unsafe.go | 366 +- .../protobuf/proto/pointer_unsafe_gogo.go | 100 +- .../gogo/protobuf/proto/properties.go | 469 +- .../gogo/protobuf/proto/properties_gogo.go | 81 +- .../gogo/protobuf/proto/table_marshal.go | 2799 ++ .../gogo/protobuf/proto/table_marshal_gogo.go | 388 + .../gogo/protobuf/proto/table_merge.go | 657 + .../gogo/protobuf/proto/table_unmarshal.go | 2048 + .../protobuf/proto/table_unmarshal_gogo.go | 385 + vendor/github.com/gogo/protobuf/proto/text.go | 61 +- .../gogo/protobuf/proto/text_parser.go | 77 +- .../gogo/protobuf/proto/timestamp_gogo.go | 180 - .../protoc-gen-gogo/descriptor/Makefile | 36 + .../descriptor/descriptor.pb.go | 878 +- .../descriptor/descriptor_gostring.gen.go | 36 +- vendor/github.com/gogo/protobuf/types/any.go | 10 +- .../github.com/gogo/protobuf/types/any.pb.go | 127 +- .../github.com/gogo/protobuf/types/api.pb.go | 2058 + .../gogo/protobuf/types/duration.pb.go | 108 +- .../gogo/protobuf/types/empty.pb.go | 102 +- .../gogo/protobuf/types/field_mask.pb.go | 113 +- .../gogo/protobuf/types/source_context.pb.go | 535 + .../gogo/protobuf/types/struct.pb.go | 286 +- .../gogo/protobuf/types/timestamp.pb.go | 116 +- .../github.com/gogo/protobuf/types/type.pb.go | 3228 ++ .../gogo/protobuf/types/wrappers.pb.go | 644 +- .../protoc-gen-go/descriptor/descriptor.pb.go | 2812 -- .../inconshreveable/mousetrap/LICENSE | 13 - .../inconshreveable/mousetrap/trap_others.go | 15 - .../inconshreveable/mousetrap/trap_windows.go | 98 - .../mousetrap/trap_windows_1.4.go | 46 - vendor/github.com/mattn/go-isatty/LICENSE | 9 - vendor/github.com/mattn/go-isatty/doc.go | 2 - .../mattn/go-isatty/isatty_appengine.go | 15 - .../github.com/mattn/go-isatty/isatty_bsd.go | 18 - .../mattn/go-isatty/isatty_linux.go | 18 - .../mattn/go-isatty/isatty_linux_ppc64x.go | 19 - .../mattn/go-isatty/isatty_others.go | 10 - .../mattn/go-isatty/isatty_solaris.go | 16 - .../mattn/go-isatty/isatty_windows.go | 94 - vendor/github.com/spf13/cobra/LICENSE.txt | 174 - vendor/github.com/spf13/cobra/args.go | 89 - .../spf13/cobra/bash_completions.go | 584 - vendor/github.com/spf13/cobra/cobra.go | 200 - .../cobra/cobra/cmd/testdata/LICENSE.golden | 202 - vendor/github.com/spf13/cobra/command.go | 1517 - .../github.com/spf13/cobra/command_notwin.go | 5 - vendor/github.com/spf13/cobra/command_win.go | 20 - .../github.com/spf13/cobra/zsh_completions.go | 126 - vendor/github.com/spf13/pflag/LICENSE | 28 - vendor/github.com/spf13/pflag/bool.go | 94 - vendor/github.com/spf13/pflag/bool_slice.go | 147 - vendor/github.com/spf13/pflag/bytes.go | 105 - vendor/github.com/spf13/pflag/count.go | 96 - vendor/github.com/spf13/pflag/duration.go | 86 - .../github.com/spf13/pflag/duration_slice.go | 128 - vendor/github.com/spf13/pflag/flag.go | 1223 - vendor/github.com/spf13/pflag/float32.go | 88 - vendor/github.com/spf13/pflag/float64.go | 84 - vendor/github.com/spf13/pflag/golangflag.go | 105 - vendor/github.com/spf13/pflag/int.go | 84 - vendor/github.com/spf13/pflag/int16.go | 88 - vendor/github.com/spf13/pflag/int32.go | 88 - vendor/github.com/spf13/pflag/int64.go | 84 - vendor/github.com/spf13/pflag/int8.go | 88 - vendor/github.com/spf13/pflag/int_slice.go | 128 - vendor/github.com/spf13/pflag/ip.go | 94 - vendor/github.com/spf13/pflag/ip_slice.go | 148 - vendor/github.com/spf13/pflag/ipmask.go | 122 - vendor/github.com/spf13/pflag/ipnet.go | 98 - vendor/github.com/spf13/pflag/string.go | 80 - vendor/github.com/spf13/pflag/string_array.go | 103 - vendor/github.com/spf13/pflag/string_slice.go | 149 - vendor/github.com/spf13/pflag/uint.go | 88 - vendor/github.com/spf13/pflag/uint16.go | 88 - vendor/github.com/spf13/pflag/uint32.go | 88 - vendor/github.com/spf13/pflag/uint64.go | 88 - vendor/github.com/spf13/pflag/uint8.go | 88 - vendor/github.com/spf13/pflag/uint_slice.go | 126 - .../github.com/stretchr/testify/suite/doc.go | 65 - .../stretchr/testify/suite/interfaces.go | 46 - .../stretchr/testify/suite/suite.go | 136 - .../tendermint/abci/example/kvstore/README.md | 31 + .../tendermint/abci/types/types.proto | 282 + .../tendermint/tmlibs/autofile/README.md | 1 + .../tendermint/tmlibs/common/types.proto | 24 + .../github.com/tendermint/tmlibs/db/README.md | 1 + .../tendermint/tmlibs/flowrate/README.md | 10 + .../tendermint/tmlibs/merkle/README.md | 4 + vendor/github.com/tommy351/gin-cors/LICENSE | 20 - vendor/github.com/tommy351/gin-cors/cors.go | 80 - vendor/github.com/ugorji/go/LICENSE | 22 - vendor/github.com/ugorji/go/codec/0doc.go | 264 - vendor/github.com/ugorji/go/codec/binc.go | 1168 - vendor/github.com/ugorji/go/codec/cbor.go | 756 - vendor/github.com/ugorji/go/codec/decode.go | 2552 -- vendor/github.com/ugorji/go/codec/encode.go | 1375 - .../ugorji/go/codec/fast-path.generated.go | 34522 ---------------- .../ugorji/go/codec/fast-path.not.go | 47 - .../ugorji/go/codec/gen-helper.generated.go | 335 - .../ugorji/go/codec/gen.generated.go | 164 - vendor/github.com/ugorji/go/codec/gen.go | 2139 - .../go/codec/goversion_arrayof_gte_go15.go | 14 - .../go/codec/goversion_arrayof_lt_go15.go | 14 - .../go/codec/goversion_makemap_gte_go19.go | 15 - .../go/codec/goversion_makemap_lt_go19.go | 12 - ...version_unexportedembeddedptr_gte_go110.go | 8 - ...oversion_unexportedembeddedptr_lt_go110.go | 8 - .../go/codec/goversion_unsupported_lt_go14.go | 17 - .../go/codec/goversion_vendor_eq_go15.go | 10 - .../go/codec/goversion_vendor_eq_go16.go | 10 - .../go/codec/goversion_vendor_gte_go17.go | 8 - .../go/codec/goversion_vendor_lt_go15.go | 8 - vendor/github.com/ugorji/go/codec/helper.go | 2414 -- .../ugorji/go/codec/helper_internal.go | 121 - .../ugorji/go/codec/helper_not_unsafe.go | 272 - .../ugorji/go/codec/helper_unsafe.go | 639 - vendor/github.com/ugorji/go/codec/json.go | 1423 - vendor/github.com/ugorji/go/codec/msgpack.go | 1092 - vendor/github.com/ugorji/go/codec/rpc.go | 232 - vendor/github.com/ugorji/go/codec/simple.go | 652 - vendor/github.com/ugorji/go/codec/xml.go | 508 - vendor/google.golang.org/grpc/backoff.go | 66 +- .../grpc/balancer/balancer.go | 42 + .../grpc/balancer_v1_wrapper.go | 56 +- vendor/google.golang.org/grpc/clientconn.go | 33 +- vendor/google.golang.org/grpc/codes/codes.go | 13 + vendor/google.golang.org/grpc/grpclb.go | 341 - .../grpclb/grpc_lb_v1/messages/messages.pb.go | 799 - .../google.golang.org/grpc/grpclb_picker.go | 159 - .../grpc/grpclb_remote_balancer.go | 266 - vendor/google.golang.org/grpc/grpclb_util.go | 214 - .../grpc/internal/backoff/backoff.go | 78 + .../grpc/{ => internal}/channelz/funcs.go | 0 .../grpc/{ => internal}/channelz/types.go | 0 .../grpc/internal/grpcrand/grpcrand.go | 56 + .../grpc/internal/internal.go | 25 +- .../google.golang.org/grpc/picker_wrapper.go | 21 +- .../grpc_reflection_v1alpha/reflection.pb.go | 925 - .../grpc/reflection/serverreflection.go | 454 - .../grpc/resolver/dns/dns_resolver.go | 8 +- .../grpc/resolver_conn_wrapper.go | 6 +- vendor/google.golang.org/grpc/rpc_util.go | 124 +- vendor/google.golang.org/grpc/server.go | 28 +- vendor/google.golang.org/grpc/status/go16.go | 42 + vendor/google.golang.org/grpc/status/go17.go | 44 + .../grpc/stickiness_linkedmap.go | 97 + vendor/google.golang.org/grpc/stream.go | 66 +- .../grpc/transport/controlbuf.go | 101 +- .../grpc/transport/flowcontrol.go | 10 +- .../grpc/transport/http2_client.go | 36 +- .../grpc/transport/http2_server.go | 25 +- .../grpc/transport/http_util.go | 42 +- vendor/google.golang.org/grpc/version.go | 22 + .../go-playground/validator.v8/LICENSE | 22 - .../go-playground/validator.v8/baked_in.go | 1410 - .../go-playground/validator.v8/cache.go | 263 - .../go-playground/validator.v8/doc.go | 852 - .../go-playground/validator.v8/regexes.go | 59 - .../go-playground/validator.v8/util.go | 252 - .../go-playground/validator.v8/validator.go | 782 - vendor/gopkg.in/tylerb/graceful.v1/LICENSE | 21 - .../gopkg.in/tylerb/graceful.v1/graceful.go | 489 - .../tylerb/graceful.v1/keepalive_listener.go | 32 - .../tylerb/graceful.v1/limit_listen.go | 77 - vendor/gopkg.in/tylerb/graceful.v1/signal.go | 17 - .../tylerb/graceful.v1/signal_appengine.go | 13 - 232 files changed, 17161 insertions(+), 78582 deletions(-) delete mode 100644 vendor/github.com/gin-contrib/sse/LICENSE delete mode 100644 vendor/github.com/gin-contrib/sse/sse-decoder.go delete mode 100644 vendor/github.com/gin-contrib/sse/sse-encoder.go delete mode 100644 vendor/github.com/gin-contrib/sse/writer.go delete mode 100644 vendor/github.com/gin-gonic/gin/AUTHORS.md delete mode 100644 vendor/github.com/gin-gonic/gin/LICENSE delete mode 100644 vendor/github.com/gin-gonic/gin/auth.go delete mode 100644 vendor/github.com/gin-gonic/gin/binding/binding.go delete mode 100644 vendor/github.com/gin-gonic/gin/binding/default_validator.go delete mode 100644 vendor/github.com/gin-gonic/gin/binding/form.go delete mode 100644 vendor/github.com/gin-gonic/gin/binding/form_mapping.go delete mode 100644 vendor/github.com/gin-gonic/gin/binding/json.go delete mode 100644 vendor/github.com/gin-gonic/gin/binding/msgpack.go delete mode 100644 vendor/github.com/gin-gonic/gin/binding/protobuf.go delete mode 100644 vendor/github.com/gin-gonic/gin/binding/xml.go delete mode 100644 vendor/github.com/gin-gonic/gin/context.go delete mode 100644 vendor/github.com/gin-gonic/gin/context_appengine.go delete mode 100644 vendor/github.com/gin-gonic/gin/debug.go delete mode 100644 vendor/github.com/gin-gonic/gin/deprecated.go delete mode 100644 vendor/github.com/gin-gonic/gin/errors.go delete mode 100644 vendor/github.com/gin-gonic/gin/fs.go delete mode 100644 vendor/github.com/gin-gonic/gin/gin.go delete mode 100644 vendor/github.com/gin-gonic/gin/logger.go delete mode 100644 vendor/github.com/gin-gonic/gin/mode.go delete mode 100644 vendor/github.com/gin-gonic/gin/path.go delete mode 100644 vendor/github.com/gin-gonic/gin/recovery.go delete mode 100644 vendor/github.com/gin-gonic/gin/render/data.go delete mode 100644 vendor/github.com/gin-gonic/gin/render/html.go delete mode 100644 vendor/github.com/gin-gonic/gin/render/json.go delete mode 100644 vendor/github.com/gin-gonic/gin/render/msgpack.go delete mode 100644 vendor/github.com/gin-gonic/gin/render/redirect.go delete mode 100644 vendor/github.com/gin-gonic/gin/render/render.go delete mode 100644 vendor/github.com/gin-gonic/gin/render/text.go delete mode 100644 vendor/github.com/gin-gonic/gin/render/xml.go delete mode 100644 vendor/github.com/gin-gonic/gin/render/yaml.go delete mode 100644 vendor/github.com/gin-gonic/gin/response_writer.go delete mode 100644 vendor/github.com/gin-gonic/gin/routergroup.go delete mode 100644 vendor/github.com/gin-gonic/gin/test_helpers.go delete mode 100644 vendor/github.com/gin-gonic/gin/tree.go delete mode 100644 vendor/github.com/gin-gonic/gin/utils.go create mode 100644 vendor/github.com/gogo/protobuf/gogoproto/Makefile create mode 100644 vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.golden create mode 100644 vendor/github.com/gogo/protobuf/gogoproto/gogo.proto create mode 100644 vendor/github.com/gogo/protobuf/proto/Makefile create mode 100644 vendor/github.com/gogo/protobuf/proto/custom_gogo.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/decode_gogo.go create mode 100644 vendor/github.com/gogo/protobuf/proto/table_marshal.go create mode 100644 vendor/github.com/gogo/protobuf/proto/table_marshal_gogo.go create mode 100644 vendor/github.com/gogo/protobuf/proto/table_merge.go create mode 100644 vendor/github.com/gogo/protobuf/proto/table_unmarshal.go create mode 100644 vendor/github.com/gogo/protobuf/proto/table_unmarshal_gogo.go create mode 100644 vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/Makefile create mode 100644 vendor/github.com/gogo/protobuf/types/api.pb.go create mode 100644 vendor/github.com/gogo/protobuf/types/source_context.pb.go create mode 100644 vendor/github.com/gogo/protobuf/types/type.pb.go delete mode 100644 vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go delete mode 100644 vendor/github.com/inconshreveable/mousetrap/LICENSE delete mode 100644 vendor/github.com/inconshreveable/mousetrap/trap_others.go delete mode 100644 vendor/github.com/inconshreveable/mousetrap/trap_windows.go delete mode 100644 vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go delete mode 100644 vendor/github.com/mattn/go-isatty/LICENSE delete mode 100644 vendor/github.com/mattn/go-isatty/doc.go delete mode 100644 vendor/github.com/mattn/go-isatty/isatty_appengine.go delete mode 100644 vendor/github.com/mattn/go-isatty/isatty_bsd.go delete mode 100644 vendor/github.com/mattn/go-isatty/isatty_linux.go delete mode 100644 vendor/github.com/mattn/go-isatty/isatty_linux_ppc64x.go delete mode 100644 vendor/github.com/mattn/go-isatty/isatty_others.go delete mode 100644 vendor/github.com/mattn/go-isatty/isatty_solaris.go delete mode 100644 vendor/github.com/mattn/go-isatty/isatty_windows.go delete mode 100644 vendor/github.com/spf13/cobra/LICENSE.txt delete mode 100644 vendor/github.com/spf13/cobra/args.go delete mode 100644 vendor/github.com/spf13/cobra/bash_completions.go delete mode 100644 vendor/github.com/spf13/cobra/cobra.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/testdata/LICENSE.golden delete mode 100644 vendor/github.com/spf13/cobra/command.go delete mode 100644 vendor/github.com/spf13/cobra/command_notwin.go delete mode 100644 vendor/github.com/spf13/cobra/command_win.go delete mode 100644 vendor/github.com/spf13/cobra/zsh_completions.go delete mode 100644 vendor/github.com/spf13/pflag/LICENSE delete mode 100644 vendor/github.com/spf13/pflag/bool.go delete mode 100644 vendor/github.com/spf13/pflag/bool_slice.go delete mode 100644 vendor/github.com/spf13/pflag/bytes.go delete mode 100644 vendor/github.com/spf13/pflag/count.go delete mode 100644 vendor/github.com/spf13/pflag/duration.go delete mode 100644 vendor/github.com/spf13/pflag/duration_slice.go delete mode 100644 vendor/github.com/spf13/pflag/flag.go delete mode 100644 vendor/github.com/spf13/pflag/float32.go delete mode 100644 vendor/github.com/spf13/pflag/float64.go delete mode 100644 vendor/github.com/spf13/pflag/golangflag.go delete mode 100644 vendor/github.com/spf13/pflag/int.go delete mode 100644 vendor/github.com/spf13/pflag/int16.go delete mode 100644 vendor/github.com/spf13/pflag/int32.go delete mode 100644 vendor/github.com/spf13/pflag/int64.go delete mode 100644 vendor/github.com/spf13/pflag/int8.go delete mode 100644 vendor/github.com/spf13/pflag/int_slice.go delete mode 100644 vendor/github.com/spf13/pflag/ip.go delete mode 100644 vendor/github.com/spf13/pflag/ip_slice.go delete mode 100644 vendor/github.com/spf13/pflag/ipmask.go delete mode 100644 vendor/github.com/spf13/pflag/ipnet.go delete mode 100644 vendor/github.com/spf13/pflag/string.go delete mode 100644 vendor/github.com/spf13/pflag/string_array.go delete mode 100644 vendor/github.com/spf13/pflag/string_slice.go delete mode 100644 vendor/github.com/spf13/pflag/uint.go delete mode 100644 vendor/github.com/spf13/pflag/uint16.go delete mode 100644 vendor/github.com/spf13/pflag/uint32.go delete mode 100644 vendor/github.com/spf13/pflag/uint64.go delete mode 100644 vendor/github.com/spf13/pflag/uint8.go delete mode 100644 vendor/github.com/spf13/pflag/uint_slice.go delete mode 100644 vendor/github.com/stretchr/testify/suite/doc.go delete mode 100644 vendor/github.com/stretchr/testify/suite/interfaces.go delete mode 100644 vendor/github.com/stretchr/testify/suite/suite.go create mode 100644 vendor/github.com/tendermint/abci/example/kvstore/README.md create mode 100644 vendor/github.com/tendermint/abci/types/types.proto create mode 100644 vendor/github.com/tendermint/tmlibs/autofile/README.md create mode 100644 vendor/github.com/tendermint/tmlibs/common/types.proto create mode 100644 vendor/github.com/tendermint/tmlibs/db/README.md create mode 100644 vendor/github.com/tendermint/tmlibs/flowrate/README.md create mode 100644 vendor/github.com/tendermint/tmlibs/merkle/README.md delete mode 100644 vendor/github.com/tommy351/gin-cors/LICENSE delete mode 100644 vendor/github.com/tommy351/gin-cors/cors.go delete mode 100644 vendor/github.com/ugorji/go/LICENSE delete mode 100644 vendor/github.com/ugorji/go/codec/0doc.go delete mode 100644 vendor/github.com/ugorji/go/codec/binc.go delete mode 100644 vendor/github.com/ugorji/go/codec/cbor.go delete mode 100644 vendor/github.com/ugorji/go/codec/decode.go delete mode 100644 vendor/github.com/ugorji/go/codec/encode.go delete mode 100644 vendor/github.com/ugorji/go/codec/fast-path.generated.go delete mode 100644 vendor/github.com/ugorji/go/codec/fast-path.not.go delete mode 100644 vendor/github.com/ugorji/go/codec/gen-helper.generated.go delete mode 100644 vendor/github.com/ugorji/go/codec/gen.generated.go delete mode 100644 vendor/github.com/ugorji/go/codec/gen.go delete mode 100644 vendor/github.com/ugorji/go/codec/goversion_arrayof_gte_go15.go delete mode 100644 vendor/github.com/ugorji/go/codec/goversion_arrayof_lt_go15.go delete mode 100644 vendor/github.com/ugorji/go/codec/goversion_makemap_gte_go19.go delete mode 100644 vendor/github.com/ugorji/go/codec/goversion_makemap_lt_go19.go delete mode 100644 vendor/github.com/ugorji/go/codec/goversion_unexportedembeddedptr_gte_go110.go delete mode 100644 vendor/github.com/ugorji/go/codec/goversion_unexportedembeddedptr_lt_go110.go delete mode 100644 vendor/github.com/ugorji/go/codec/goversion_unsupported_lt_go14.go delete mode 100644 vendor/github.com/ugorji/go/codec/goversion_vendor_eq_go15.go delete mode 100644 vendor/github.com/ugorji/go/codec/goversion_vendor_eq_go16.go delete mode 100644 vendor/github.com/ugorji/go/codec/goversion_vendor_gte_go17.go delete mode 100644 vendor/github.com/ugorji/go/codec/goversion_vendor_lt_go15.go delete mode 100644 vendor/github.com/ugorji/go/codec/helper.go delete mode 100644 vendor/github.com/ugorji/go/codec/helper_internal.go delete mode 100644 vendor/github.com/ugorji/go/codec/helper_not_unsafe.go delete mode 100644 vendor/github.com/ugorji/go/codec/helper_unsafe.go delete mode 100644 vendor/github.com/ugorji/go/codec/json.go delete mode 100644 vendor/github.com/ugorji/go/codec/msgpack.go delete mode 100644 vendor/github.com/ugorji/go/codec/rpc.go delete mode 100644 vendor/github.com/ugorji/go/codec/simple.go delete mode 100644 vendor/github.com/ugorji/go/codec/xml.go delete mode 100644 vendor/google.golang.org/grpc/grpclb.go delete mode 100644 vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.pb.go delete mode 100644 vendor/google.golang.org/grpc/grpclb_picker.go delete mode 100644 vendor/google.golang.org/grpc/grpclb_remote_balancer.go delete mode 100644 vendor/google.golang.org/grpc/grpclb_util.go create mode 100644 vendor/google.golang.org/grpc/internal/backoff/backoff.go rename vendor/google.golang.org/grpc/{ => internal}/channelz/funcs.go (100%) rename vendor/google.golang.org/grpc/{ => internal}/channelz/types.go (100%) create mode 100644 vendor/google.golang.org/grpc/internal/grpcrand/grpcrand.go delete mode 100644 vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.pb.go delete mode 100644 vendor/google.golang.org/grpc/reflection/serverreflection.go create mode 100644 vendor/google.golang.org/grpc/status/go16.go create mode 100644 vendor/google.golang.org/grpc/status/go17.go create mode 100644 vendor/google.golang.org/grpc/stickiness_linkedmap.go create mode 100644 vendor/google.golang.org/grpc/version.go delete mode 100644 vendor/gopkg.in/go-playground/validator.v8/LICENSE delete mode 100644 vendor/gopkg.in/go-playground/validator.v8/baked_in.go delete mode 100644 vendor/gopkg.in/go-playground/validator.v8/cache.go delete mode 100644 vendor/gopkg.in/go-playground/validator.v8/doc.go delete mode 100644 vendor/gopkg.in/go-playground/validator.v8/regexes.go delete mode 100644 vendor/gopkg.in/go-playground/validator.v8/util.go delete mode 100644 vendor/gopkg.in/go-playground/validator.v8/validator.go delete mode 100644 vendor/gopkg.in/tylerb/graceful.v1/LICENSE delete mode 100644 vendor/gopkg.in/tylerb/graceful.v1/graceful.go delete mode 100644 vendor/gopkg.in/tylerb/graceful.v1/keepalive_listener.go delete mode 100644 vendor/gopkg.in/tylerb/graceful.v1/limit_listen.go delete mode 100644 vendor/gopkg.in/tylerb/graceful.v1/signal.go delete mode 100644 vendor/gopkg.in/tylerb/graceful.v1/signal_appengine.go diff --git a/Gopkg.lock b/Gopkg.lock index 6a5ce6ba6..30b89e8a5 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -2,98 +2,107 @@ [[projects]] + digest = "1:e0499b93857a1b91efbdc0c21e26f1130685de98035008f3b01eeeb0713798cb" name = "github.com/BurntSushi/toml" packages = ["."] + pruneopts = "NUT" revision = "b26d9c308763d68093482582cea63d69be07a0f0" version = "v0.3.0" [[projects]] + digest = "1:40948327b6631b9b5c7bb55acb55bd1cad78ffbfa9d81642e90ffdcb1d487443" name = "github.com/OneOfOne/xxhash" packages = ["."] + pruneopts = "NUT" revision = "6def279d2ce6c81a79dd1c1be580f03bb216fb8a" version = "v1.2.2" [[projects]] branch = "master" + digest = "1:707ebe952a8b3d00b343c01536c79c73771d100f63ec6babeaed5c79e2b8a8dd" name = "github.com/beorn7/perks" packages = ["quantile"] + pruneopts = "NUT" revision = "3a771d992973f24aa725d07868b467d1ddfceafb" [[projects]] branch = "master" + digest = "1:8bd66090a4fc1d422f0cb065a3023bf98f07f44920c3f87da5c3107f990434e4" name = "github.com/btcsuite/btcd" packages = ["btcec"] + pruneopts = "NUT" revision = "86fed781132ac890ee03e906e4ecd5d6fa180c64" [[projects]] branch = "master" + digest = "1:96f90d432e58964e281f5e4d4683699a472b39517d5b38b39df422523ebb5bd2" name = "github.com/cep21/xdgbasedir" packages = ["."] + pruneopts = "NUT" revision = "21470bfc93b9903bce0beaebb037b1d04d0be523" [[projects]] + digest = "1:a2c1d0e43bd3baaa071d1b9ed72c27d78169b2b269f71c105ac4ba34b1be4a39" name = "github.com/davecgh/go-spew" packages = ["spew"] + pruneopts = "NUT" revision = "346938d642f2ec3594ed81d874461961cd0faa76" version = "v1.1.0" [[projects]] + digest = "1:4f0ac2a7cc350b14c72a9de0de046b908482d6f16183c8570ee4d6e17adc6a94" name = "github.com/eapache/channels" packages = ["."] + pruneopts = "NUT" revision = "47238d5aae8c0fefd518ef2bee46290909cf8263" version = "v1.1.0" [[projects]] + digest = "1:0d36a2b325b9e75f8057f7f9fbe778d348d70ba652cb9335485b69d1a5c4e038" name = "github.com/eapache/queue" packages = ["."] + pruneopts = "NUT" revision = "44cc805cf13205b55f69e14bcb69867d1ae92f98" version = "v1.1.0" [[projects]] branch = "master" + digest = "1:294576320c5093015ca9130ed928c84b2fdc8b9db6d136505a513795f3a64e3e" name = "github.com/ebuchman/fail-test" packages = ["."] + pruneopts = "NUT" revision = "95f809107225be108efcf10a3509e4ea6ceef3c4" [[projects]] - branch = "master" - name = "github.com/gin-contrib/sse" - packages = ["."] - revision = "22d885f9ecc78bf4ee5d72b937e4bbcdc58e8cae" - -[[projects]] - name = "github.com/gin-gonic/gin" - packages = [ - ".", - "binding", - "render" - ] - revision = "d459835d2b077e44f7c9b453505ee29881d5d12d" - version = "v1.2" - -[[projects]] + digest = "1:5a6f43bb19bea1e7894542a80c6e95bab099c380dd90abebd76d3938e8c66567" name = "github.com/go-kit/kit" packages = [ "log", "log/level", - "log/term" + "log/term", ] + pruneopts = "NUT" revision = "4dc7be5d2d12881735283bcab7352178e190fc71" version = "v0.6.0" [[projects]] + digest = "1:341a7df38da99fe91ed40e4008c13cc5d02dcc98ed1a094360cb7d5df26d6d26" name = "github.com/go-logfmt/logfmt" packages = ["."] + pruneopts = "NUT" revision = "390ab7935ee28ec6b286364bba9b4dd6410cb3d5" version = "v0.3.0" [[projects]] + digest = "1:a1efdbc2762667c8a41cbf02b19a0549c846bf2c1d08cad4f445e3344089f1f0" name = "github.com/go-stack/stack" packages = ["."] + pruneopts = "NUT" revision = "259ab82a6cad3992b4e21ff5cac294ccb06474bc" version = "v1.7.0" [[projects]] + digest = "1:212285efb97b9ec2e20550d81f0446cb7897e57cbdfd7301b1363ab113d8be45" name = "github.com/gogo/protobuf" packages = [ "gogoproto", @@ -101,55 +110,60 @@ "proto", "protoc-gen-gogo/descriptor", "sortkeys", - "types" + "types", ] - revision = "1adfc126b41513cc696b209667c8656ea7aac67c" - version = "v1.0.0" + pruneopts = "UT" + revision = "7d68e886eac4f7e34d0d82241a6273d6c304c5cf" + version = "v1.1.0" [[projects]] + digest = "1:713cc7628304d027a7e9edcb52da888a8912d6405250a8d9c8eff6f41dd54398" name = "github.com/golang/protobuf" packages = [ "proto", - "protoc-gen-go/descriptor", "ptypes", "ptypes/any", "ptypes/duration", - "ptypes/timestamp" + "ptypes/timestamp", ] + pruneopts = "NUT" revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265" version = "v1.1.0" [[projects]] branch = "master" + digest = "1:7f114b78210bf5b75f307fc97cff293633c835bab1e0ea8a744a44b39c042dfe" name = "github.com/golang/snappy" packages = ["."] + pruneopts = "NUT" revision = "2e65f85255dbc3072edf28d6b5b8efc472979f5a" [[projects]] + digest = "1:3b708ebf63bfa9ba3313bedb8526bc0bb284e51474e65e958481476a9d4a12aa" name = "github.com/gorilla/websocket" packages = ["."] + pruneopts = "NUT" revision = "ea4d1f681babbce9545c9c5f3d5194a789c89f5b" version = "v1.2.0" [[projects]] branch = "master" + digest = "1:b7f860847a1d71f925ba9385ed95f1ebc0abfeb418a78e219ab61f48fdfeffad" name = "github.com/howeyc/gopass" packages = ["."] + pruneopts = "NUT" revision = "bf9dde6d0d2c004a008c27aaee91170c786f6db8" [[projects]] + digest = "1:65300ccc4bcb38b107b868155c303312978981e56bca707c81efec57575b5e06" name = "github.com/imdario/mergo" packages = ["."] + pruneopts = "NUT" revision = "9316a62528ac99aaecb4e47eadd6dc8aa6533d58" version = "v0.3.5" [[projects]] - name = "github.com/inconshreveable/mousetrap" - packages = ["."] - revision = "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75" - version = "v1.0" - -[[projects]] + digest = "1:fa8175fc1639f717d9462d6c507d92b174662db600997f1b4a92aae0571c23de" name = "github.com/jawher/mow.cli" packages = [ ".", @@ -159,122 +173,131 @@ "internal/lexer", "internal/matcher", "internal/parser", - "internal/values" + "internal/values", ] + pruneopts = "NUT" revision = "2f22195f169da29d54624afd9eb83ada5c9e4ee9" version = "v1.0.4" [[projects]] branch = "master" + digest = "1:3d24306f696fc55f4773ba2ea288be218ca725b572e714483e65de169c731845" name = "github.com/jmhodges/levigo" packages = ["."] + pruneopts = "NUT" revision = "c42d9e0ca023e2198120196f842701bb4c55d7b9" [[projects]] branch = "master" + digest = "1:f91bb67d051a94cf6ab2cf07eee0550432afc31655838d42cdec258db4b348f0" name = "github.com/kr/logfmt" packages = ["."] + pruneopts = "NUT" revision = "b84e30acd515aadc4b783ad4ff83aff3299bdfe0" [[projects]] - name = "github.com/mattn/go-isatty" - packages = ["."] - revision = "0360b2af4f38e8d38c7fce2a9f4e702702d73a39" - version = "v0.0.3" - -[[projects]] + digest = "1:5985ef4caf91ece5d54817c11ea25f182697534f8ae6521eadcd628c142ac4b6" name = "github.com/matttproud/golang_protobuf_extensions" packages = ["pbutil"] + pruneopts = "NUT" revision = "c12348ce28de40eed0136aa2b644d0ee0650e56c" version = "v1.0.1" [[projects]] + digest = "1:0392287f4fcbbd32a8352f82044dd0b644284d8a979897810abfa246a080adec" name = "github.com/monax/relic" packages = ["."] + pruneopts = "NUT" revision = "f24b36b5f6f7f5c6034c89a6a47de1bfbbf7787e" version = "v1.1.0" [[projects]] + digest = "1:5cf3f025cbee5951a4ee961de067c8a89fc95a5adabead774f82822efabab121" name = "github.com/pkg/errors" packages = ["."] + pruneopts = "NUT" revision = "645ef00459ed84a119197bfb8d8205042c6df63d" version = "v0.8.0" [[projects]] + digest = "1:0028cb19b2e4c3112225cd871870f2d9cf49b9b4276531f03438a88e94be86fe" name = "github.com/pmezard/go-difflib" packages = ["difflib"] + pruneopts = "NUT" revision = "792786c7400a136282c1664665ae0a8db921c6c2" version = "v1.0.0" [[projects]] branch = "master" + digest = "1:22deec4bab258f99bf1e4394c51d976e04ddf9a52f55b0e2912d9cdd503dff16" name = "github.com/prometheus/client_golang" packages = ["prometheus"] + pruneopts = "NUT" revision = "d6a9817c4afc94d51115e4a30d449056a3fbf547" [[projects]] branch = "master" + digest = "1:53a76eb11bdc815fcf0c757a9648fda0ab6887da13f07587181ff2223b67956c" name = "github.com/prometheus/client_model" packages = ["go"] + pruneopts = "NUT" revision = "99fa1f4be8e564e8a6b613da7fa6f46c9edafc6c" [[projects]] branch = "master" + digest = "1:3bbebf77a04cda10bd07834d1686141608aca01c1aeb400d504d8aa026793b5a" name = "github.com/prometheus/common" packages = [ "expfmt", "internal/bitbucket.org/ww/goautoneg", - "model" + "model", ] + pruneopts = "NUT" revision = "7600349dcfe1abd18d72d3a1770870d9800a7801" [[projects]] branch = "master" + digest = "1:b161534d0cce842f1e1eaf087e2c5f28191f0bac0c3070fc9a7e1b6269238d88" name = "github.com/prometheus/procfs" packages = [ ".", "internal/util", "nfs", - "xfs" + "xfs", ] + pruneopts = "NUT" revision = "40f013a808ec4fa79def444a1a56de4d1727efcb" [[projects]] branch = "master" + digest = "1:7c522337040d4ec9a136cd9d64fe4677ee1d3eae4a7f8831c2108f9bec43fa48" name = "github.com/rcrowley/go-metrics" packages = ["."] + pruneopts = "NUT" revision = "e2704e165165ec55d062f5919b4b29494e9fa790" -[[projects]] - name = "github.com/spf13/cobra" - packages = ["."] - revision = "ef82de70bb3f60c65fb8eebacbb2d122ef517385" - version = "v0.0.3" - -[[projects]] - name = "github.com/spf13/pflag" - packages = ["."] - revision = "583c0c0531f06d5278b7d917446061adc344b5cd" - version = "v1.0.1" - [[projects]] branch = "master" + digest = "1:47201ae9986674849b91deb7eb8c5625d84b387ff1ae161a4ae3eb62779217cb" name = "github.com/streadway/simpleuuid" packages = ["."] + pruneopts = "NUT" revision = "6617b501e485b77e61b98cd533aefff9e258b5a7" [[projects]] + digest = "1:a7cb71e7cef4a320ae6d91424df8f991ed4161aede6dea7ba8d8f3af1b589a6c" name = "github.com/stretchr/testify" packages = [ "assert", "require", - "suite" ] + pruneopts = "NUT" revision = "f35b8ab0b5a2cef36673838d662e249dd9c94686" version = "v1.2.2" [[projects]] branch = "master" + digest = "1:bd62f27525a36697564991b8e6071ff56afa99d3235261924a0212db5ce780bd" name = "github.com/syndtr/goleveldb" packages = [ "leveldb", @@ -288,53 +311,65 @@ "leveldb/opt", "leveldb/storage", "leveldb/table", - "leveldb/util" + "leveldb/util", ] + pruneopts = "NUT" revision = "0d5a0ceb10cf9ab89fdd744cc8c50a83134f6697" [[projects]] + digest = "1:b8a05190f9aa37b0ab5b29b480797306b221709ffcb4a0ed9946cc7110849c07" name = "github.com/tendermint/abci" packages = [ "client", "example/code", "example/kvstore", - "types" + "types", ] + pruneopts = "UT" revision = "198dccf0ddfd1bb176f87657e3286a05a6ed9540" version = "v0.12.0" [[projects]] branch = "master" + digest = "1:203b409c21115233a576f99e8f13d8e07ad82b25500491f7e1cca12588fb3232" name = "github.com/tendermint/ed25519" packages = [ ".", "edwards25519", - "extra25519" + "extra25519", ] + pruneopts = "NUT" revision = "d8387025d2b9d158cf4efb07e7ebf814bcce2057" [[projects]] + digest = "1:0457834dfbe7dfd39c9e2d99147bde666094819e85728eb235a122943660256c" name = "github.com/tendermint/go-amino" packages = ["."] + pruneopts = "NUT" revision = "ed62928576cfcaf887209dc96142cd79cdfff389" version = "0.9.9" [[projects]] + digest = "1:9b0716c497677d6404499b2931cbfac90943d20302b90128b2979b5e1fcb09f5" name = "github.com/tendermint/go-crypto" packages = ["."] + pruneopts = "NUT" revision = "915416979bf70efa4bcbf1c6cd5d64c5fff9fc19" version = "v0.6.2" [[projects]] + digest = "1:91de33917aa98c06cb0f32867908071dd6992fff80347c37fc592165051957a0" name = "github.com/tendermint/iavl" packages = [ ".", - "sha256truncated" + "sha256truncated", ] + pruneopts = "NUT" revision = "c9206995e8f948e99927f5084a88a7e94ca256da" version = "v0.8.0-rc0" [[projects]] + digest = "1:0bde6563ae9ebe48770735120ee223a8761e8ec23fde4f36995bbbb4ea69d1ca" name = "github.com/tendermint/tendermint" packages = [ "blockchain", @@ -364,12 +399,14 @@ "state/txindex/kv", "state/txindex/null", "types", - "version" + "version", ] + pruneopts = "NUT" revision = "46369a1ab76f274ab47179c4176221842b8207b4" version = "v0.21.0" [[projects]] + digest = "1:1e17077c52b3c68e5ec1059ed078210e8b1030eb30ad23a69b924e7f30bd0132" name = "github.com/tendermint/tmlibs" packages = [ "autofile", @@ -378,37 +415,31 @@ "db", "flowrate", "log", - "merkle" + "merkle", ] + pruneopts = "UT" revision = "692f1d86a6e2c0efa698fd1e4541b68c74ffaf38" version = "v0.8.4" [[projects]] branch = "master" + digest = "1:ac0a19060bcaafa2abdeebbc9a40cdca961039cd01e639a0b728fdb7b8d2200a" name = "github.com/tmthrgd/asm" packages = ["."] + pruneopts = "NUT" revision = "e7da50cc23089806f643a8a72d1e6e2b4daefe91" [[projects]] branch = "master" + digest = "1:cca27d0506f054ec7cef0eb1e60dd770e60337b83f4534e6316921bd288c4340" name = "github.com/tmthrgd/go-hex" packages = ["."] + pruneopts = "NUT" revision = "a82aa03cedda71045967f5cc69c22cada26f4e6c" [[projects]] branch = "master" - name = "github.com/tommy351/gin-cors" - packages = ["."] - revision = "dc91dec6313ae4db53481bf3b29cf6b94bf80357" - -[[projects]] - name = "github.com/ugorji/go" - packages = ["codec"] - revision = "b4c50a2b199d93b13dc15e78929cfb23bfdf21ab" - version = "v1.1.1" - -[[projects]] - branch = "master" + digest = "1:acfa60b5755859faec71ac0f34d2ffd16113334fa6350aad536b4207e5b5193f" name = "golang.org/x/crypto" packages = [ "curve25519", @@ -424,12 +455,14 @@ "ripemd160", "salsa20/salsa", "scrypt", - "ssh/terminal" + "ssh/terminal", ] + pruneopts = "NUT" revision = "a49355c7e3f8fe157a85be2f77e6e269a0f89602" [[projects]] branch = "master" + digest = "1:cdc8cc9377bcb05ff97816bf398120c0a242f502b5eb2bb27d1d650b523e67e1" name = "golang.org/x/net" packages = [ "context", @@ -438,21 +471,25 @@ "http2/hpack", "idna", "internal/timeseries", - "trace" + "trace", ] + pruneopts = "NUT" revision = "ed29d75add3d7c4bf7ca65aac0c6df3d1420216f" [[projects]] branch = "master" + digest = "1:569e1719852f85b01939e6040b3eee417913c9e6d0368d3d1460d0af4eb702bc" name = "golang.org/x/sys" packages = [ "cpu", "unix", - "windows" + "windows", ] + pruneopts = "NUT" revision = "151529c776cdc58ddbe7963ba9af779f3577b419" [[projects]] + digest = "1:a0f29009397dc27c9dc8440f0945d49e5cbb9b72d0b0fc745474d9bfdea2d9f8" name = "golang.org/x/text" packages = [ "collate", @@ -468,71 +505,112 @@ "unicode/bidi", "unicode/cldr", "unicode/norm", - "unicode/rangetable" + "unicode/rangetable", ] + pruneopts = "NUT" revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" version = "v0.3.0" [[projects]] branch = "master" + digest = "1:601e63e7d4577f907118bec825902505291918859d223bce015539e79f1160e3" name = "google.golang.org/genproto" packages = ["googleapis/rpc/status"] + pruneopts = "NUT" revision = "ff3583edef7de132f219f0efc00e097cabcc0ec0" [[projects]] + digest = "1:f778941d5c2e46da5e0f5d553d3e80bf70eb40d2e80bb4c649b625b9133f3d5f" name = "google.golang.org/grpc" packages = [ ".", "balancer", "balancer/base", "balancer/roundrobin", - "channelz", "codes", "connectivity", "credentials", "encoding", "encoding/proto", - "grpclb/grpc_lb_v1/messages", "grpclog", "internal", + "internal/backoff", + "internal/channelz", + "internal/grpcrand", "keepalive", "metadata", "naming", "peer", - "reflection", - "reflection/grpc_reflection_v1alpha", "resolver", "resolver/dns", "resolver/passthrough", "stats", "status", "tap", - "transport" + "transport", ] - revision = "7a6a684ca69eb4cae85ad0a484f2e531598c047b" - version = "v1.12.2" - -[[projects]] - name = "gopkg.in/go-playground/validator.v8" - packages = ["."] - revision = "5f1438d3fca68893a817e4a66806cea46a9e4ebf" - version = "v8.18.2" - -[[projects]] - name = "gopkg.in/tylerb/graceful.v1" - packages = ["."] - revision = "4654dfbb6ad53cb5e27f37d99b02e16c1872fbbb" - version = "v1.2.15" + pruneopts = "NUT" + revision = "168a6198bcb0ef175f7dacec0b8691fc141dc9b8" + version = "v1.13.0" [[projects]] + digest = "1:7c95b35057a0ff2e19f707173cc1a947fa43a6eb5c4d300d196ece0334046082" name = "gopkg.in/yaml.v2" packages = ["."] + pruneopts = "NUT" revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183" version = "v2.2.1" [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "7b9b17cb4d553647a445b9cefe47cea819dac89f8787efc9ed2992ef585c9948" + input-imports = [ + "github.com/BurntSushi/toml", + "github.com/OneOfOne/xxhash", + "github.com/btcsuite/btcd/btcec", + "github.com/cep21/xdgbasedir", + "github.com/eapache/channels", + "github.com/go-kit/kit/log", + "github.com/go-kit/kit/log/term", + "github.com/gogo/protobuf/gogoproto", + "github.com/gogo/protobuf/proto", + "github.com/golang/protobuf/proto", + "github.com/gorilla/websocket", + "github.com/howeyc/gopass", + "github.com/imdario/mergo", + "github.com/jawher/mow.cli", + "github.com/monax/relic", + "github.com/pkg/errors", + "github.com/prometheus/client_golang/prometheus", + "github.com/rcrowley/go-metrics", + "github.com/streadway/simpleuuid", + "github.com/stretchr/testify/assert", + "github.com/stretchr/testify/require", + "github.com/tendermint/abci/types", + "github.com/tendermint/go-amino", + "github.com/tendermint/go-crypto", + "github.com/tendermint/iavl", + "github.com/tendermint/tendermint/blockchain", + "github.com/tendermint/tendermint/config", + "github.com/tendermint/tendermint/consensus", + "github.com/tendermint/tendermint/consensus/types", + "github.com/tendermint/tendermint/libs/pubsub", + "github.com/tendermint/tendermint/node", + "github.com/tendermint/tendermint/p2p", + "github.com/tendermint/tendermint/proxy", + "github.com/tendermint/tendermint/rpc/core/types", + "github.com/tendermint/tendermint/state", + "github.com/tendermint/tendermint/types", + "github.com/tendermint/tmlibs/common", + "github.com/tendermint/tmlibs/db", + "github.com/tendermint/tmlibs/log", + "github.com/tmthrgd/go-hex", + "golang.org/x/crypto/ed25519", + "golang.org/x/crypto/ripemd160", + "golang.org/x/crypto/scrypt", + "golang.org/x/net/context", + "google.golang.org/grpc", + "gopkg.in/yaml.v2", + ] solver-name = "gps-cdcl" solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml index 26c1310ac..d96822fe2 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -2,6 +2,16 @@ go-tests = true unused-packages = true non-go = true + # For proto files + [[prune.project]] + name = "github.com/gogo/protobuf" + non-go = false + [[prune.project]] + name = "github.com/tendermint/abci" + non-go = false + [[prune.project]] + name = "github.com/tendermint/tmlibs" + non-go = false # From Tendermint [[constraint]] @@ -25,10 +35,14 @@ version = "~0.8.4" # We don't care which version Tendermint wants +[[override]] + name = "github.com/gogo/protobuf" + version = "~1.1.0" + [[override]] name = "github.com/golang/protobuf" version = "~1.1.0" [[override]] name = "google.golang.org/grpc" - version = "~1.12.2" + version = "~1.13.0" diff --git a/vendor/github.com/gin-contrib/sse/LICENSE b/vendor/github.com/gin-contrib/sse/LICENSE deleted file mode 100644 index 1ff7f3706..000000000 --- a/vendor/github.com/gin-contrib/sse/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Manuel Martínez-Almeida - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/gin-contrib/sse/sse-decoder.go b/vendor/github.com/gin-contrib/sse/sse-decoder.go deleted file mode 100644 index fd49b9c37..000000000 --- a/vendor/github.com/gin-contrib/sse/sse-decoder.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package sse - -import ( - "bytes" - "io" - "io/ioutil" -) - -type decoder struct { - events []Event -} - -func Decode(r io.Reader) ([]Event, error) { - var dec decoder - return dec.decode(r) -} - -func (d *decoder) dispatchEvent(event Event, data string) { - dataLength := len(data) - if dataLength > 0 { - //If the data buffer's last character is a U+000A LINE FEED (LF) character, then remove the last character from the data buffer. - data = data[:dataLength-1] - dataLength-- - } - if dataLength == 0 && event.Event == "" { - return - } - if event.Event == "" { - event.Event = "message" - } - event.Data = data - d.events = append(d.events, event) -} - -func (d *decoder) decode(r io.Reader) ([]Event, error) { - buf, err := ioutil.ReadAll(r) - if err != nil { - return nil, err - } - - var currentEvent Event - var dataBuffer *bytes.Buffer = new(bytes.Buffer) - // TODO (and unit tests) - // Lines must be separated by either a U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair, - // a single U+000A LINE FEED (LF) character, - // or a single U+000D CARRIAGE RETURN (CR) character. - lines := bytes.Split(buf, []byte{'\n'}) - for _, line := range lines { - if len(line) == 0 { - // If the line is empty (a blank line). Dispatch the event. - d.dispatchEvent(currentEvent, dataBuffer.String()) - - // reset current event and data buffer - currentEvent = Event{} - dataBuffer.Reset() - continue - } - if line[0] == byte(':') { - // If the line starts with a U+003A COLON character (:), ignore the line. - continue - } - - var field, value []byte - colonIndex := bytes.IndexRune(line, ':') - if colonIndex != -1 { - // If the line contains a U+003A COLON character character (:) - // Collect the characters on the line before the first U+003A COLON character (:), - // and let field be that string. - field = line[:colonIndex] - // Collect the characters on the line after the first U+003A COLON character (:), - // and let value be that string. - value = line[colonIndex+1:] - // If value starts with a single U+0020 SPACE character, remove it from value. - if len(value) > 0 && value[0] == ' ' { - value = value[1:] - } - } else { - // Otherwise, the string is not empty but does not contain a U+003A COLON character character (:) - // Use the whole line as the field name, and the empty string as the field value. - field = line - value = []byte{} - } - // The steps to process the field given a field name and a field value depend on the field name, - // as given in the following list. Field names must be compared literally, - // with no case folding performed. - switch string(field) { - case "event": - // Set the event name buffer to field value. - currentEvent.Event = string(value) - case "id": - // Set the event stream's last event ID to the field value. - currentEvent.Id = string(value) - case "retry": - // If the field value consists of only characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), - // then interpret the field value as an integer in base ten, and set the event stream's reconnection time to that integer. - // Otherwise, ignore the field. - currentEvent.Id = string(value) - case "data": - // Append the field value to the data buffer, - dataBuffer.Write(value) - // then append a single U+000A LINE FEED (LF) character to the data buffer. - dataBuffer.WriteString("\n") - default: - //Otherwise. The field is ignored. - continue - } - } - // Once the end of the file is reached, the user agent must dispatch the event one final time. - d.dispatchEvent(currentEvent, dataBuffer.String()) - - return d.events, nil -} diff --git a/vendor/github.com/gin-contrib/sse/sse-encoder.go b/vendor/github.com/gin-contrib/sse/sse-encoder.go deleted file mode 100644 index f9c808750..000000000 --- a/vendor/github.com/gin-contrib/sse/sse-encoder.go +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package sse - -import ( - "encoding/json" - "fmt" - "io" - "net/http" - "reflect" - "strconv" - "strings" -) - -// Server-Sent Events -// W3C Working Draft 29 October 2009 -// http://www.w3.org/TR/2009/WD-eventsource-20091029/ - -const ContentType = "text/event-stream" - -var contentType = []string{ContentType} -var noCache = []string{"no-cache"} - -var fieldReplacer = strings.NewReplacer( - "\n", "\\n", - "\r", "\\r") - -var dataReplacer = strings.NewReplacer( - "\n", "\ndata:", - "\r", "\\r") - -type Event struct { - Event string - Id string - Retry uint - Data interface{} -} - -func Encode(writer io.Writer, event Event) error { - w := checkWriter(writer) - writeId(w, event.Id) - writeEvent(w, event.Event) - writeRetry(w, event.Retry) - return writeData(w, event.Data) -} - -func writeId(w stringWriter, id string) { - if len(id) > 0 { - w.WriteString("id:") - fieldReplacer.WriteString(w, id) - w.WriteString("\n") - } -} - -func writeEvent(w stringWriter, event string) { - if len(event) > 0 { - w.WriteString("event:") - fieldReplacer.WriteString(w, event) - w.WriteString("\n") - } -} - -func writeRetry(w stringWriter, retry uint) { - if retry > 0 { - w.WriteString("retry:") - w.WriteString(strconv.FormatUint(uint64(retry), 10)) - w.WriteString("\n") - } -} - -func writeData(w stringWriter, data interface{}) error { - w.WriteString("data:") - switch kindOfData(data) { - case reflect.Struct, reflect.Slice, reflect.Map: - err := json.NewEncoder(w).Encode(data) - if err != nil { - return err - } - w.WriteString("\n") - default: - dataReplacer.WriteString(w, fmt.Sprint(data)) - w.WriteString("\n\n") - } - return nil -} - -func (r Event) Render(w http.ResponseWriter) error { - r.WriteContentType(w) - return Encode(w, r) -} - -func (r Event) WriteContentType(w http.ResponseWriter) { - header := w.Header() - header["Content-Type"] = contentType - - if _, exist := header["Cache-Control"]; !exist { - header["Cache-Control"] = noCache - } -} - -func kindOfData(data interface{}) reflect.Kind { - value := reflect.ValueOf(data) - valueType := value.Kind() - if valueType == reflect.Ptr { - valueType = value.Elem().Kind() - } - return valueType -} diff --git a/vendor/github.com/gin-contrib/sse/writer.go b/vendor/github.com/gin-contrib/sse/writer.go deleted file mode 100644 index 6f9806c55..000000000 --- a/vendor/github.com/gin-contrib/sse/writer.go +++ /dev/null @@ -1,24 +0,0 @@ -package sse - -import "io" - -type stringWriter interface { - io.Writer - WriteString(string) (int, error) -} - -type stringWrapper struct { - io.Writer -} - -func (w stringWrapper) WriteString(str string) (int, error) { - return w.Writer.Write([]byte(str)) -} - -func checkWriter(writer io.Writer) stringWriter { - if w, ok := writer.(stringWriter); ok { - return w - } else { - return stringWrapper{writer} - } -} diff --git a/vendor/github.com/gin-gonic/gin/AUTHORS.md b/vendor/github.com/gin-gonic/gin/AUTHORS.md deleted file mode 100644 index 7ab7213d9..000000000 --- a/vendor/github.com/gin-gonic/gin/AUTHORS.md +++ /dev/null @@ -1,227 +0,0 @@ -List of all the awesome people working to make Gin the best Web Framework in Go. - -## gin 0.x series authors - -**Maintainer:** Manu Martinez-Almeida (@manucorporat), Javier Provecho (@javierprovecho) - -People and companies, who have contributed, in alphabetical order. - -**@858806258 (杰哥)** -- Fix typo in example - - -**@achedeuzot (Klemen Sever)** -- Fix newline debug printing - - -**@adammck (Adam Mckaig)** -- Add MIT license - - -**@AlexanderChen1989 (Alexander)** -- Typos in README - - -**@alexanderdidenko (Aleksandr Didenko)** -- Add support multipart/form-data - - -**@alexandernyquist (Alexander Nyquist)** -- Using template.Must to fix multiple return issue -- ★ Added support for OPTIONS verb -- ★ Setting response headers before calling WriteHeader -- Improved documentation for model binding -- ★ Added Content.Redirect() -- ★ Added tons of Unit tests - - -**@austinheap (Austin Heap)** -- Added travis CI integration - - -**@andredublin (Andre Dublin)** -- Fix typo in comment - - -**@bredov (Ludwig Valda Vasquez)** -- Fix html templating in debug mode - - -**@bluele (Jun Kimura)** -- Fixes code examples in README - - -**@chad-russell** -- ★ Support for serializing gin.H into XML - - -**@dickeyxxx (Jeff Dickey)** -- Typos in README -- Add example about serving static files - - -**@donileo (Adonis)** -- Add NoMethod handler - - -**@dutchcoders (DutchCoders)** -- ★ Fix security bug that allows client to spoof ip -- Fix typo. r.HTMLTemplates -> SetHTMLTemplate - - -**@el3ctro- (Joshua Loper)** -- Fix typo in example - - -**@ethankan (Ethan Kan)** -- Unsigned integers in binding - - -**(Evgeny Persienko)** -- Validate sub structures - - -**@frankbille (Frank Bille)** -- Add support for HTTP Realm Auth - - -**@fmd (Fareed Dudhia)** -- Fix typo. SetHTTPTemplate -> SetHTMLTemplate - - -**@ironiridis (Christopher Harrington)** -- Remove old reference - - -**@jammie-stackhouse (Jamie Stackhouse)** -- Add more shortcuts for router methods - - -**@jasonrhansen** -- Fix spelling and grammar errors in documentation - - -**@JasonSoft (Jason Lee)** -- Fix typo in comment - - -**@joiggama (Ignacio Galindo)** -- Add utf-8 charset header on renders - - -**@julienschmidt (Julien Schmidt)** -- gofmt the code examples - - -**@kelcecil (Kel Cecil)** -- Fix readme typo - - -**@kyledinh (Kyle Dinh)** -- Adds RunTLS() - - -**@LinusU (Linus Unnebäck)** -- Small fixes in README - - -**@loongmxbt (Saint Asky)** -- Fix typo in example - - -**@lucas-clemente (Lucas Clemente)** -- ★ work around path.Join removing trailing slashes from routes - - -**@mattn (Yasuhiro Matsumoto)** -- Improve color logger - - -**@mdigger (Dmitry Sedykh)** -- Fixes Form binding when content-type is x-www-form-urlencoded -- No repeat call c.Writer.Status() in gin.Logger -- Fixes Content-Type for json render - - -**@mirzac (Mirza Ceric)** -- Fix debug printing - - -**@mopemope (Yutaka Matsubara)** -- ★ Adds Godep support (Dependencies Manager) -- Fix variadic parameter in the flexible render API -- Fix Corrupted plain render -- Add Pluggable View Renderer Example - - -**@msemenistyi (Mykyta Semenistyi)** -- update Readme.md. Add code to String method - - -**@msoedov (Sasha Myasoedov)** -- ★ Adds tons of unit tests. - - -**@ngerakines (Nick Gerakines)** -- ★ Improves API, c.GET() doesn't panic -- Adds MustGet() method - - -**@r8k (Rajiv Kilaparti)** -- Fix Port usage in README. - - -**@rayrod2030 (Ray Rodriguez)** -- Fix typo in example - - -**@rns** -- Fix typo in example - - -**@RobAWilkinson (Robert Wilkinson)** -- Add example of forms and params - - -**@rogierlommers (Rogier Lommers)** -- Add updated static serve example - - -**@se77en (Damon Zhao)** -- Improve color logging - - -**@silasb (Silas Baronda)** -- Fixing quotes in README - - -**@SkuliOskarsson (Skuli Oskarsson)** -- Fixes some texts in README II - - -**@slimmy (Jimmy Pettersson)** -- Added messages for required bindings - - -**@smira (Andrey Smirnov)** -- Add support for ignored/unexported fields in binding - - -**@superalsrk (SRK.Lyu)** -- Update httprouter godeps - - -**@tebeka (Miki Tebeka)** -- Use net/http constants instead of numeric values - - -**@techjanitor** -- Update context.go reserved IPs - - -**@yosssi (Keiji Yoshida)** -- Fix link in README - - -**@yuyabee** -- Fixed README diff --git a/vendor/github.com/gin-gonic/gin/LICENSE b/vendor/github.com/gin-gonic/gin/LICENSE deleted file mode 100644 index 1ff7f3706..000000000 --- a/vendor/github.com/gin-gonic/gin/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Manuel Martínez-Almeida - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/gin-gonic/gin/auth.go b/vendor/github.com/gin-gonic/gin/auth.go deleted file mode 100644 index 125e659f2..000000000 --- a/vendor/github.com/gin-gonic/gin/auth.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "crypto/subtle" - "encoding/base64" - "strconv" -) - -const AuthUserKey = "user" - -type ( - Accounts map[string]string - authPair struct { - Value string - User string - } - authPairs []authPair -) - -func (a authPairs) searchCredential(authValue string) (string, bool) { - if len(authValue) == 0 { - return "", false - } - for _, pair := range a { - if pair.Value == authValue { - return pair.User, true - } - } - return "", false -} - -// BasicAuthForRealm returns a Basic HTTP Authorization middleware. It takes as arguments a map[string]string where -// the key is the user name and the value is the password, as well as the name of the Realm. -// If the realm is empty, "Authorization Required" will be used by default. -// (see http://tools.ietf.org/html/rfc2617#section-1.2) -func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc { - if realm == "" { - realm = "Authorization Required" - } - realm = "Basic realm=" + strconv.Quote(realm) - pairs := processAccounts(accounts) - return func(c *Context) { - // Search user in the slice of allowed credentials - user, found := pairs.searchCredential(c.Request.Header.Get("Authorization")) - if !found { - // Credentials doesn't match, we return 401 and abort handlers chain. - c.Header("WWW-Authenticate", realm) - c.AbortWithStatus(401) - } else { - // The user credentials was found, set user's id to key AuthUserKey in this context, the userId can be read later using - // c.MustGet(gin.AuthUserKey) - c.Set(AuthUserKey, user) - } - } -} - -// BasicAuth returns a Basic HTTP Authorization middleware. It takes as argument a map[string]string where -// the key is the user name and the value is the password. -func BasicAuth(accounts Accounts) HandlerFunc { - return BasicAuthForRealm(accounts, "") -} - -func processAccounts(accounts Accounts) authPairs { - assert1(len(accounts) > 0, "Empty list of authorized credentials") - pairs := make(authPairs, 0, len(accounts)) - for user, password := range accounts { - assert1(len(user) > 0, "User can not be empty") - value := authorizationHeader(user, password) - pairs = append(pairs, authPair{ - Value: value, - User: user, - }) - } - return pairs -} - -func authorizationHeader(user, password string) string { - base := user + ":" + password - return "Basic " + base64.StdEncoding.EncodeToString([]byte(base)) -} - -func secureCompare(given, actual string) bool { - if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 { - return subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 1 - } - /* Securely compare actual to itself to keep constant time, but always return false */ - return subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 && false -} diff --git a/vendor/github.com/gin-gonic/gin/binding/binding.go b/vendor/github.com/gin-gonic/gin/binding/binding.go deleted file mode 100644 index 1dbf2460a..000000000 --- a/vendor/github.com/gin-gonic/gin/binding/binding.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package binding - -import "net/http" - -const ( - MIMEJSON = "application/json" - MIMEHTML = "text/html" - MIMEXML = "application/xml" - MIMEXML2 = "text/xml" - MIMEPlain = "text/plain" - MIMEPOSTForm = "application/x-www-form-urlencoded" - MIMEMultipartPOSTForm = "multipart/form-data" - MIMEPROTOBUF = "application/x-protobuf" - MIMEMSGPACK = "application/x-msgpack" - MIMEMSGPACK2 = "application/msgpack" -) - -type Binding interface { - Name() string - Bind(*http.Request, interface{}) error -} - -type StructValidator interface { - // ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right. - // If the received type is not a struct, any validation should be skipped and nil must be returned. - // If the received type is a struct or pointer to a struct, the validation should be performed. - // If the struct is not valid or the validation itself fails, a descriptive error should be returned. - // Otherwise nil must be returned. - ValidateStruct(interface{}) error -} - -var Validator StructValidator = &defaultValidator{} - -var ( - JSON = jsonBinding{} - XML = xmlBinding{} - Form = formBinding{} - FormPost = formPostBinding{} - FormMultipart = formMultipartBinding{} - ProtoBuf = protobufBinding{} - MsgPack = msgpackBinding{} -) - -func Default(method, contentType string) Binding { - if method == "GET" { - return Form - } - - switch contentType { - case MIMEJSON: - return JSON - case MIMEXML, MIMEXML2: - return XML - case MIMEPROTOBUF: - return ProtoBuf - case MIMEMSGPACK, MIMEMSGPACK2: - return MsgPack - default: //case MIMEPOSTForm, MIMEMultipartPOSTForm: - return Form - } -} - -func validate(obj interface{}) error { - if Validator == nil { - return nil - } - return Validator.ValidateStruct(obj) -} diff --git a/vendor/github.com/gin-gonic/gin/binding/default_validator.go b/vendor/github.com/gin-gonic/gin/binding/default_validator.go deleted file mode 100644 index 19885f164..000000000 --- a/vendor/github.com/gin-gonic/gin/binding/default_validator.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2017 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package binding - -import ( - "reflect" - "sync" - - "gopkg.in/go-playground/validator.v8" -) - -type defaultValidator struct { - once sync.Once - validate *validator.Validate -} - -var _ StructValidator = &defaultValidator{} - -func (v *defaultValidator) ValidateStruct(obj interface{}) error { - if kindOfData(obj) == reflect.Struct { - v.lazyinit() - if err := v.validate.Struct(obj); err != nil { - return error(err) - } - } - return nil -} - -func (v *defaultValidator) lazyinit() { - v.once.Do(func() { - config := &validator.Config{TagName: "binding"} - v.validate = validator.New(config) - }) -} - -func kindOfData(data interface{}) reflect.Kind { - value := reflect.ValueOf(data) - valueType := value.Kind() - if valueType == reflect.Ptr { - valueType = value.Elem().Kind() - } - return valueType -} diff --git a/vendor/github.com/gin-gonic/gin/binding/form.go b/vendor/github.com/gin-gonic/gin/binding/form.go deleted file mode 100644 index 557333e6f..000000000 --- a/vendor/github.com/gin-gonic/gin/binding/form.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package binding - -import "net/http" - -type formBinding struct{} -type formPostBinding struct{} -type formMultipartBinding struct{} - -func (formBinding) Name() string { - return "form" -} - -func (formBinding) Bind(req *http.Request, obj interface{}) error { - if err := req.ParseForm(); err != nil { - return err - } - req.ParseMultipartForm(32 << 10) // 32 MB - if err := mapForm(obj, req.Form); err != nil { - return err - } - return validate(obj) -} - -func (formPostBinding) Name() string { - return "form-urlencoded" -} - -func (formPostBinding) Bind(req *http.Request, obj interface{}) error { - if err := req.ParseForm(); err != nil { - return err - } - if err := mapForm(obj, req.PostForm); err != nil { - return err - } - return validate(obj) -} - -func (formMultipartBinding) Name() string { - return "multipart/form-data" -} - -func (formMultipartBinding) Bind(req *http.Request, obj interface{}) error { - if err := req.ParseMultipartForm(32 << 10); err != nil { - return err - } - if err := mapForm(obj, req.MultipartForm.Value); err != nil { - return err - } - return validate(obj) -} diff --git a/vendor/github.com/gin-gonic/gin/binding/form_mapping.go b/vendor/github.com/gin-gonic/gin/binding/form_mapping.go deleted file mode 100644 index 34f126781..000000000 --- a/vendor/github.com/gin-gonic/gin/binding/form_mapping.go +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package binding - -import ( - "errors" - "reflect" - "strconv" - "time" -) - -func mapForm(ptr interface{}, form map[string][]string) error { - typ := reflect.TypeOf(ptr).Elem() - val := reflect.ValueOf(ptr).Elem() - for i := 0; i < typ.NumField(); i++ { - typeField := typ.Field(i) - structField := val.Field(i) - if !structField.CanSet() { - continue - } - - structFieldKind := structField.Kind() - inputFieldName := typeField.Tag.Get("form") - if inputFieldName == "" { - inputFieldName = typeField.Name - - // if "form" tag is nil, we inspect if the field is a struct. - // this would not make sense for JSON parsing but it does for a form - // since data is flatten - if structFieldKind == reflect.Struct { - err := mapForm(structField.Addr().Interface(), form) - if err != nil { - return err - } - continue - } - } - inputValue, exists := form[inputFieldName] - if !exists { - continue - } - - numElems := len(inputValue) - if structFieldKind == reflect.Slice && numElems > 0 { - sliceOf := structField.Type().Elem().Kind() - slice := reflect.MakeSlice(structField.Type(), numElems, numElems) - for i := 0; i < numElems; i++ { - if err := setWithProperType(sliceOf, inputValue[i], slice.Index(i)); err != nil { - return err - } - } - val.Field(i).Set(slice) - } else { - if _, isTime := structField.Interface().(time.Time); isTime { - if err := setTimeField(inputValue[0], typeField, structField); err != nil { - return err - } - continue - } - if err := setWithProperType(typeField.Type.Kind(), inputValue[0], structField); err != nil { - return err - } - } - } - return nil -} - -func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value) error { - switch valueKind { - case reflect.Int: - return setIntField(val, 0, structField) - case reflect.Int8: - return setIntField(val, 8, structField) - case reflect.Int16: - return setIntField(val, 16, structField) - case reflect.Int32: - return setIntField(val, 32, structField) - case reflect.Int64: - return setIntField(val, 64, structField) - case reflect.Uint: - return setUintField(val, 0, structField) - case reflect.Uint8: - return setUintField(val, 8, structField) - case reflect.Uint16: - return setUintField(val, 16, structField) - case reflect.Uint32: - return setUintField(val, 32, structField) - case reflect.Uint64: - return setUintField(val, 64, structField) - case reflect.Bool: - return setBoolField(val, structField) - case reflect.Float32: - return setFloatField(val, 32, structField) - case reflect.Float64: - return setFloatField(val, 64, structField) - case reflect.String: - structField.SetString(val) - default: - return errors.New("Unknown type") - } - return nil -} - -func setIntField(val string, bitSize int, field reflect.Value) error { - if val == "" { - val = "0" - } - intVal, err := strconv.ParseInt(val, 10, bitSize) - if err == nil { - field.SetInt(intVal) - } - return err -} - -func setUintField(val string, bitSize int, field reflect.Value) error { - if val == "" { - val = "0" - } - uintVal, err := strconv.ParseUint(val, 10, bitSize) - if err == nil { - field.SetUint(uintVal) - } - return err -} - -func setBoolField(val string, field reflect.Value) error { - if val == "" { - val = "false" - } - boolVal, err := strconv.ParseBool(val) - if err == nil { - field.SetBool(boolVal) - } - return nil -} - -func setFloatField(val string, bitSize int, field reflect.Value) error { - if val == "" { - val = "0.0" - } - floatVal, err := strconv.ParseFloat(val, bitSize) - if err == nil { - field.SetFloat(floatVal) - } - return err -} - -func setTimeField(val string, structField reflect.StructField, value reflect.Value) error { - timeFormat := structField.Tag.Get("time_format") - if timeFormat == "" { - return errors.New("Blank time format") - } - - if val == "" { - value.Set(reflect.ValueOf(time.Time{})) - return nil - } - - l := time.Local - if isUTC, _ := strconv.ParseBool(structField.Tag.Get("time_utc")); isUTC { - l = time.UTC - } - - t, err := time.ParseInLocation(timeFormat, val, l) - if err != nil { - return err - } - - value.Set(reflect.ValueOf(t)) - return nil -} - -// Don't pass in pointers to bind to. Can lead to bugs. See: -// https://github.com/codegangsta/martini-contrib/issues/40 -// https://github.com/codegangsta/martini-contrib/pull/34#issuecomment-29683659 -func ensureNotPointer(obj interface{}) { - if reflect.TypeOf(obj).Kind() == reflect.Ptr { - panic("Pointers are not accepted as binding models") - } -} diff --git a/vendor/github.com/gin-gonic/gin/binding/json.go b/vendor/github.com/gin-gonic/gin/binding/json.go deleted file mode 100644 index 486b9733b..000000000 --- a/vendor/github.com/gin-gonic/gin/binding/json.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package binding - -import ( - "encoding/json" - "net/http" -) - -type jsonBinding struct{} - -func (jsonBinding) Name() string { - return "json" -} - -func (jsonBinding) Bind(req *http.Request, obj interface{}) error { - decoder := json.NewDecoder(req.Body) - if err := decoder.Decode(obj); err != nil { - return err - } - return validate(obj) -} diff --git a/vendor/github.com/gin-gonic/gin/binding/msgpack.go b/vendor/github.com/gin-gonic/gin/binding/msgpack.go deleted file mode 100644 index 69367175b..000000000 --- a/vendor/github.com/gin-gonic/gin/binding/msgpack.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2017 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package binding - -import ( - "net/http" - - "github.com/ugorji/go/codec" -) - -type msgpackBinding struct{} - -func (msgpackBinding) Name() string { - return "msgpack" -} - -func (msgpackBinding) Bind(req *http.Request, obj interface{}) error { - - if err := codec.NewDecoder(req.Body, new(codec.MsgpackHandle)).Decode(&obj); err != nil { - //var decoder *codec.Decoder = codec.NewDecoder(req.Body, &codec.MsgpackHandle) - //if err := decoder.Decode(&obj); err != nil { - return err - } - return validate(obj) - -} diff --git a/vendor/github.com/gin-gonic/gin/binding/protobuf.go b/vendor/github.com/gin-gonic/gin/binding/protobuf.go deleted file mode 100644 index c7eb84e9b..000000000 --- a/vendor/github.com/gin-gonic/gin/binding/protobuf.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package binding - -import ( - "io/ioutil" - "net/http" - - "github.com/golang/protobuf/proto" -) - -type protobufBinding struct{} - -func (protobufBinding) Name() string { - return "protobuf" -} - -func (protobufBinding) Bind(req *http.Request, obj interface{}) error { - - buf, err := ioutil.ReadAll(req.Body) - if err != nil { - return err - } - - if err = proto.Unmarshal(buf, obj.(proto.Message)); err != nil { - return err - } - - //Here it's same to return validate(obj), but util now we cann't add `binding:""` to the struct - //which automatically generate by gen-proto - return nil - //return validate(obj) -} diff --git a/vendor/github.com/gin-gonic/gin/binding/xml.go b/vendor/github.com/gin-gonic/gin/binding/xml.go deleted file mode 100644 index f84a6b7f1..000000000 --- a/vendor/github.com/gin-gonic/gin/binding/xml.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package binding - -import ( - "encoding/xml" - "net/http" -) - -type xmlBinding struct{} - -func (xmlBinding) Name() string { - return "xml" -} - -func (xmlBinding) Bind(req *http.Request, obj interface{}) error { - decoder := xml.NewDecoder(req.Body) - if err := decoder.Decode(obj); err != nil { - return err - } - return validate(obj) -} diff --git a/vendor/github.com/gin-gonic/gin/context.go b/vendor/github.com/gin-gonic/gin/context.go deleted file mode 100644 index 5c4d27dca..000000000 --- a/vendor/github.com/gin-gonic/gin/context.go +++ /dev/null @@ -1,766 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "errors" - "io" - "io/ioutil" - "math" - "mime/multipart" - "net" - "net/http" - "net/url" - "strings" - "time" - - "github.com/gin-contrib/sse" - "github.com/gin-gonic/gin/binding" - "github.com/gin-gonic/gin/render" -) - -// Content-Type MIME of the most common data formats -const ( - MIMEJSON = binding.MIMEJSON - MIMEHTML = binding.MIMEHTML - MIMEXML = binding.MIMEXML - MIMEXML2 = binding.MIMEXML2 - MIMEPlain = binding.MIMEPlain - MIMEPOSTForm = binding.MIMEPOSTForm - MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm -) - -const ( - defaultMemory = 32 << 20 // 32 MB - abortIndex int8 = math.MaxInt8 / 2 -) - -// Context is the most important part of gin. It allows us to pass variables between middleware, -// manage the flow, validate the JSON of a request and render a JSON response for example. -type Context struct { - writermem responseWriter - Request *http.Request - Writer ResponseWriter - - Params Params - handlers HandlersChain - index int8 - - engine *Engine - Keys map[string]interface{} - Errors errorMsgs - Accepted []string -} - -/************************************/ -/********** CONTEXT CREATION ********/ -/************************************/ - -func (c *Context) reset() { - c.Writer = &c.writermem - c.Params = c.Params[0:0] - c.handlers = nil - c.index = -1 - c.Keys = nil - c.Errors = c.Errors[0:0] - c.Accepted = nil -} - -// Copy returns a copy of the current context that can be safely used outside the request's scope. -// This has to be used when the context has to be passed to a goroutine. -func (c *Context) Copy() *Context { - var cp = *c - cp.writermem.ResponseWriter = nil - cp.Writer = &cp.writermem - cp.index = abortIndex - cp.handlers = nil - return &cp -} - -// HandlerName returns the main handler's name. For example if the handler is "handleGetUsers()", this -// function will return "main.handleGetUsers" -func (c *Context) HandlerName() string { - return nameOfFunction(c.handlers.Last()) -} - -// Handler returns the main handler. -func (c *Context) Handler() HandlerFunc { - return c.handlers.Last() -} - -/************************************/ -/*********** FLOW CONTROL ***********/ -/************************************/ - -// Next should be used only inside middleware. -// It executes the pending handlers in the chain inside the calling handler. -// See example in GitHub. -func (c *Context) Next() { - c.index++ - s := int8(len(c.handlers)) - for ; c.index < s; c.index++ { - c.handlers[c.index](c) - } -} - -// IsAborted returns true if the current context was aborted. -func (c *Context) IsAborted() bool { - return c.index >= abortIndex -} - -// Abort prevents pending handlers from being called. Note that this will not stop the current handler. -// Let's say you have an authorization middleware that validates that the current request is authorized. If the -// authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers -// for this request are not called. -func (c *Context) Abort() { - c.index = abortIndex -} - -// AbortWithStatus calls `Abort()` and writes the headers with the specified status code. -// For example, a failed attempt to authenticate a request could use: context.AbortWithStatus(401). -func (c *Context) AbortWithStatus(code int) { - c.Status(code) - c.Writer.WriteHeaderNow() - c.Abort() -} - -// AbortWithStatusJSON calls `Abort()` and then `JSON` internally. This method stops the chain, writes the status code and return a JSON body -// It also sets the Content-Type as "application/json". -func (c *Context) AbortWithStatusJSON(code int, jsonObj interface{}) { - c.Abort() - c.JSON(code, jsonObj) -} - -// AbortWithError calls `AbortWithStatus()` and `Error()` internally. This method stops the chain, writes the status code and -// pushes the specified error to `c.Errors`. -// See Context.Error() for more details. -func (c *Context) AbortWithError(code int, err error) *Error { - c.AbortWithStatus(code) - return c.Error(err) -} - -/************************************/ -/********* ERROR MANAGEMENT *********/ -/************************************/ - -// Attaches an error to the current context. The error is pushed to a list of errors. -// It's a good idea to call Error for each error that occurred during the resolution of a request. -// A middleware can be used to collect all the errors -// and push them to a database together, print a log, or append it in the HTTP response. -func (c *Context) Error(err error) *Error { - var parsedError *Error - switch err.(type) { - case *Error: - parsedError = err.(*Error) - default: - parsedError = &Error{ - Err: err, - Type: ErrorTypePrivate, - } - } - c.Errors = append(c.Errors, parsedError) - return parsedError -} - -/************************************/ -/******** METADATA MANAGEMENT********/ -/************************************/ - -// Set is used to store a new key/value pair exclusively for this context. -// It also lazy initializes c.Keys if it was not used previously. -func (c *Context) Set(key string, value interface{}) { - if c.Keys == nil { - c.Keys = make(map[string]interface{}) - } - c.Keys[key] = value -} - -// Get returns the value for the given key, ie: (value, true). -// If the value does not exists it returns (nil, false) -func (c *Context) Get(key string) (value interface{}, exists bool) { - value, exists = c.Keys[key] - return -} - -// MustGet returns the value for the given key if it exists, otherwise it panics. -func (c *Context) MustGet(key string) interface{} { - if value, exists := c.Get(key); exists { - return value - } - panic("Key \"" + key + "\" does not exist") -} - -// GetString returns the value associated with the key as a string. -func (c *Context) GetString(key string) (s string) { - if val, ok := c.Get(key); ok && val != nil { - s, _ = val.(string) - } - return -} - -// GetBool returns the value associated with the key as a boolean. -func (c *Context) GetBool(key string) (b bool) { - if val, ok := c.Get(key); ok && val != nil { - b, _ = val.(bool) - } - return -} - -// GetInt returns the value associated with the key as an integer. -func (c *Context) GetInt(key string) (i int) { - if val, ok := c.Get(key); ok && val != nil { - i, _ = val.(int) - } - return -} - -// GetInt64 returns the value associated with the key as an integer. -func (c *Context) GetInt64(key string) (i64 int64) { - if val, ok := c.Get(key); ok && val != nil { - i64, _ = val.(int64) - } - return -} - -// GetFloat64 returns the value associated with the key as a float64. -func (c *Context) GetFloat64(key string) (f64 float64) { - if val, ok := c.Get(key); ok && val != nil { - f64, _ = val.(float64) - } - return -} - -// GetTime returns the value associated with the key as time. -func (c *Context) GetTime(key string) (t time.Time) { - if val, ok := c.Get(key); ok && val != nil { - t, _ = val.(time.Time) - } - return -} - -// GetDuration returns the value associated with the key as a duration. -func (c *Context) GetDuration(key string) (d time.Duration) { - if val, ok := c.Get(key); ok && val != nil { - d, _ = val.(time.Duration) - } - return -} - -// GetStringSlice returns the value associated with the key as a slice of strings. -func (c *Context) GetStringSlice(key string) (ss []string) { - if val, ok := c.Get(key); ok && val != nil { - ss, _ = val.([]string) - } - return -} - -// GetStringMap returns the value associated with the key as a map of interfaces. -func (c *Context) GetStringMap(key string) (sm map[string]interface{}) { - if val, ok := c.Get(key); ok && val != nil { - sm, _ = val.(map[string]interface{}) - } - return -} - -// GetStringMapString returns the value associated with the key as a map of strings. -func (c *Context) GetStringMapString(key string) (sms map[string]string) { - if val, ok := c.Get(key); ok && val != nil { - sms, _ = val.(map[string]string) - } - return -} - -// GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings. -func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string) { - if val, ok := c.Get(key); ok && val != nil { - smss, _ = val.(map[string][]string) - } - return -} - -/************************************/ -/************ INPUT DATA ************/ -/************************************/ - -// Param returns the value of the URL param. -// It is a shortcut for c.Params.ByName(key) -// router.GET("/user/:id", func(c *gin.Context) { -// // a GET request to /user/john -// id := c.Param("id") // id == "john" -// }) -func (c *Context) Param(key string) string { - return c.Params.ByName(key) -} - -// Query returns the keyed url query value if it exists, -// otherwise it returns an empty string `("")`. -// It is shortcut for `c.Request.URL.Query().Get(key)` -// GET /path?id=1234&name=Manu&value= -// c.Query("id") == "1234" -// c.Query("name") == "Manu" -// c.Query("value") == "" -// c.Query("wtf") == "" -func (c *Context) Query(key string) string { - value, _ := c.GetQuery(key) - return value -} - -// DefaultQuery returns the keyed url query value if it exists, -// otherwise it returns the specified defaultValue string. -// See: Query() and GetQuery() for further information. -// GET /?name=Manu&lastname= -// c.DefaultQuery("name", "unknown") == "Manu" -// c.DefaultQuery("id", "none") == "none" -// c.DefaultQuery("lastname", "none") == "" -func (c *Context) DefaultQuery(key, defaultValue string) string { - if value, ok := c.GetQuery(key); ok { - return value - } - return defaultValue -} - -// GetQuery is like Query(), it returns the keyed url query value -// if it exists `(value, true)` (even when the value is an empty string), -// otherwise it returns `("", false)`. -// It is shortcut for `c.Request.URL.Query().Get(key)` -// GET /?name=Manu&lastname= -// ("Manu", true) == c.GetQuery("name") -// ("", false) == c.GetQuery("id") -// ("", true) == c.GetQuery("lastname") -func (c *Context) GetQuery(key string) (string, bool) { - if values, ok := c.GetQueryArray(key); ok { - return values[0], ok - } - return "", false -} - -// QueryArray returns a slice of strings for a given query key. -// The length of the slice depends on the number of params with the given key. -func (c *Context) QueryArray(key string) []string { - values, _ := c.GetQueryArray(key) - return values -} - -// GetQueryArray returns a slice of strings for a given query key, plus -// a boolean value whether at least one value exists for the given key. -func (c *Context) GetQueryArray(key string) ([]string, bool) { - req := c.Request - if values, ok := req.URL.Query()[key]; ok && len(values) > 0 { - return values, true - } - return []string{}, false -} - -// PostForm returns the specified key from a POST urlencoded form or multipart form -// when it exists, otherwise it returns an empty string `("")`. -func (c *Context) PostForm(key string) string { - value, _ := c.GetPostForm(key) - return value -} - -// DefaultPostForm returns the specified key from a POST urlencoded form or multipart form -// when it exists, otherwise it returns the specified defaultValue string. -// See: PostForm() and GetPostForm() for further information. -func (c *Context) DefaultPostForm(key, defaultValue string) string { - if value, ok := c.GetPostForm(key); ok { - return value - } - return defaultValue -} - -// GetPostForm is like PostForm(key). It returns the specified key from a POST urlencoded -// form or multipart form when it exists `(value, true)` (even when the value is an empty string), -// otherwise it returns ("", false). -// For example, during a PATCH request to update the user's email: -// email=mail@example.com --> ("mail@example.com", true) := GetPostForm("email") // set email to "mail@example.com" -// email= --> ("", true) := GetPostForm("email") // set email to "" -// --> ("", false) := GetPostForm("email") // do nothing with email -func (c *Context) GetPostForm(key string) (string, bool) { - if values, ok := c.GetPostFormArray(key); ok { - return values[0], ok - } - return "", false -} - -// PostFormArray returns a slice of strings for a given form key. -// The length of the slice depends on the number of params with the given key. -func (c *Context) PostFormArray(key string) []string { - values, _ := c.GetPostFormArray(key) - return values -} - -// GetPostFormArray returns a slice of strings for a given form key, plus -// a boolean value whether at least one value exists for the given key. -func (c *Context) GetPostFormArray(key string) ([]string, bool) { - req := c.Request - req.ParseForm() - req.ParseMultipartForm(defaultMemory) - if values := req.PostForm[key]; len(values) > 0 { - return values, true - } - if req.MultipartForm != nil && req.MultipartForm.File != nil { - if values := req.MultipartForm.Value[key]; len(values) > 0 { - return values, true - } - } - return []string{}, false -} - -// FormFile returns the first file for the provided form key. -func (c *Context) FormFile(name string) (*multipart.FileHeader, error) { - _, fh, err := c.Request.FormFile(name) - return fh, err -} - -// MultipartForm is the parsed multipart form, including file uploads. -func (c *Context) MultipartForm() (*multipart.Form, error) { - err := c.Request.ParseMultipartForm(defaultMemory) - return c.Request.MultipartForm, err -} - -// Bind checks the Content-Type to select a binding engine automatically, -// Depending the "Content-Type" header different bindings are used: -// "application/json" --> JSON binding -// "application/xml" --> XML binding -// otherwise --> returns an error -// It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. -// It decodes the json payload into the struct specified as a pointer. -// Like ParseBody() but this method also writes a 400 error if the json is not valid. -func (c *Context) Bind(obj interface{}) error { - b := binding.Default(c.Request.Method, c.ContentType()) - return c.MustBindWith(obj, b) -} - -// BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON) -func (c *Context) BindJSON(obj interface{}) error { - return c.MustBindWith(obj, binding.JSON) -} - -// MustBindWith binds the passed struct pointer using the specified binding -// engine. It will abort the request with HTTP 400 if any error ocurrs. -// See the binding package. -func (c *Context) MustBindWith(obj interface{}, b binding.Binding) (err error) { - if err = c.ShouldBindWith(obj, b); err != nil { - c.AbortWithError(400, err).SetType(ErrorTypeBind) - } - - return -} - -// ShouldBindWith binds the passed struct pointer using the specified binding -// engine. -// See the binding package. -func (c *Context) ShouldBindWith(obj interface{}, b binding.Binding) error { - return b.Bind(c.Request, obj) -} - -// ClientIP implements a best effort algorithm to return the real client IP, it parses -// X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy. -// Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP. -func (c *Context) ClientIP() string { - if c.engine.ForwardedByClientIP { - clientIP := c.requestHeader("X-Forwarded-For") - if index := strings.IndexByte(clientIP, ','); index >= 0 { - clientIP = clientIP[0:index] - } - clientIP = strings.TrimSpace(clientIP) - if len(clientIP) > 0 { - return clientIP - } - clientIP = strings.TrimSpace(c.requestHeader("X-Real-Ip")) - if len(clientIP) > 0 { - return clientIP - } - } - - if c.engine.AppEngine { - if addr := c.Request.Header.Get("X-Appengine-Remote-Addr"); addr != "" { - return addr - } - } - - if ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)); err == nil { - return ip - } - - return "" -} - -// ContentType returns the Content-Type header of the request. -func (c *Context) ContentType() string { - return filterFlags(c.requestHeader("Content-Type")) -} - -// IsWebsocket returns true if the request headers indicate that a websocket -// handshake is being initiated by the client. -func (c *Context) IsWebsocket() bool { - if strings.Contains(strings.ToLower(c.requestHeader("Connection")), "upgrade") && - strings.ToLower(c.requestHeader("Upgrade")) == "websocket" { - return true - } - return false -} - -func (c *Context) requestHeader(key string) string { - if values, _ := c.Request.Header[key]; len(values) > 0 { - return values[0] - } - return "" -} - -/************************************/ -/******** RESPONSE RENDERING ********/ -/************************************/ - -// bodyAllowedForStatus is a copy of http.bodyAllowedForStatus non-exported function -func bodyAllowedForStatus(status int) bool { - switch { - case status >= 100 && status <= 199: - return false - case status == 204: - return false - case status == 304: - return false - } - return true -} - -func (c *Context) Status(code int) { - c.writermem.WriteHeader(code) -} - -// Header is a intelligent shortcut for c.Writer.Header().Set(key, value) -// It writes a header in the response. -// If value == "", this method removes the header `c.Writer.Header().Del(key)` -func (c *Context) Header(key, value string) { - if len(value) == 0 { - c.Writer.Header().Del(key) - } else { - c.Writer.Header().Set(key, value) - } -} - -// GetHeader returns value from request headers -func (c *Context) GetHeader(key string) string { - return c.requestHeader(key) -} - -// GetRawData return stream data -func (c *Context) GetRawData() ([]byte, error) { - return ioutil.ReadAll(c.Request.Body) -} - -func (c *Context) SetCookie( - name string, - value string, - maxAge int, - path string, - domain string, - secure bool, - httpOnly bool, -) { - if path == "" { - path = "/" - } - http.SetCookie(c.Writer, &http.Cookie{ - Name: name, - Value: url.QueryEscape(value), - MaxAge: maxAge, - Path: path, - Domain: domain, - Secure: secure, - HttpOnly: httpOnly, - }) -} - -func (c *Context) Cookie(name string) (string, error) { - cookie, err := c.Request.Cookie(name) - if err != nil { - return "", err - } - val, _ := url.QueryUnescape(cookie.Value) - return val, nil -} - -func (c *Context) Render(code int, r render.Render) { - c.Status(code) - - if !bodyAllowedForStatus(code) { - r.WriteContentType(c.Writer) - c.Writer.WriteHeaderNow() - return - } - - if err := r.Render(c.Writer); err != nil { - panic(err) - } -} - -// HTML renders the HTTP template specified by its file name. -// It also updates the HTTP code and sets the Content-Type as "text/html". -// See http://golang.org/doc/articles/wiki/ -func (c *Context) HTML(code int, name string, obj interface{}) { - instance := c.engine.HTMLRender.Instance(name, obj) - c.Render(code, instance) -} - -// IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body. -// It also sets the Content-Type as "application/json". -// WARNING: we recommend to use this only for development purposes since printing pretty JSON is -// more CPU and bandwidth consuming. Use Context.JSON() instead. -func (c *Context) IndentedJSON(code int, obj interface{}) { - c.Render(code, render.IndentedJSON{Data: obj}) -} - -// JSON serializes the given struct as JSON into the response body. -// It also sets the Content-Type as "application/json". -func (c *Context) JSON(code int, obj interface{}) { - c.Render(code, render.JSON{Data: obj}) -} - -// XML serializes the given struct as XML into the response body. -// It also sets the Content-Type as "application/xml". -func (c *Context) XML(code int, obj interface{}) { - c.Render(code, render.XML{Data: obj}) -} - -// YAML serializes the given struct as YAML into the response body. -func (c *Context) YAML(code int, obj interface{}) { - c.Render(code, render.YAML{Data: obj}) -} - -// String writes the given string into the response body. -func (c *Context) String(code int, format string, values ...interface{}) { - c.Render(code, render.String{Format: format, Data: values}) -} - -// Redirect returns a HTTP redirect to the specific location. -func (c *Context) Redirect(code int, location string) { - c.Render(-1, render.Redirect{ - Code: code, - Location: location, - Request: c.Request, - }) -} - -// Data writes some data into the body stream and updates the HTTP code. -func (c *Context) Data(code int, contentType string, data []byte) { - c.Render(code, render.Data{ - ContentType: contentType, - Data: data, - }) -} - -// File writes the specified file into the body stream in a efficient way. -func (c *Context) File(filepath string) { - http.ServeFile(c.Writer, c.Request, filepath) -} - -// SSEvent writes a Server-Sent Event into the body stream. -func (c *Context) SSEvent(name string, message interface{}) { - c.Render(-1, sse.Event{ - Event: name, - Data: message, - }) -} - -func (c *Context) Stream(step func(w io.Writer) bool) { - w := c.Writer - clientGone := w.CloseNotify() - for { - select { - case <-clientGone: - return - default: - keepOpen := step(w) - w.Flush() - if !keepOpen { - return - } - } - } -} - -/************************************/ -/******** CONTENT NEGOTIATION *******/ -/************************************/ - -type Negotiate struct { - Offered []string - HTMLName string - HTMLData interface{} - JSONData interface{} - XMLData interface{} - Data interface{} -} - -func (c *Context) Negotiate(code int, config Negotiate) { - switch c.NegotiateFormat(config.Offered...) { - case binding.MIMEJSON: - data := chooseData(config.JSONData, config.Data) - c.JSON(code, data) - - case binding.MIMEHTML: - data := chooseData(config.HTMLData, config.Data) - c.HTML(code, config.HTMLName, data) - - case binding.MIMEXML: - data := chooseData(config.XMLData, config.Data) - c.XML(code, data) - - default: - c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server")) - } -} - -func (c *Context) NegotiateFormat(offered ...string) string { - assert1(len(offered) > 0, "you must provide at least one offer") - - if c.Accepted == nil { - c.Accepted = parseAccept(c.requestHeader("Accept")) - } - if len(c.Accepted) == 0 { - return offered[0] - } - for _, accepted := range c.Accepted { - for _, offert := range offered { - if accepted == offert { - return offert - } - } - } - return "" -} - -func (c *Context) SetAccepted(formats ...string) { - c.Accepted = formats -} - -/************************************/ -/***** GOLANG.ORG/X/NET/CONTEXT *****/ -/************************************/ - -func (c *Context) Deadline() (deadline time.Time, ok bool) { - return -} - -func (c *Context) Done() <-chan struct{} { - return nil -} - -func (c *Context) Err() error { - return nil -} - -func (c *Context) Value(key interface{}) interface{} { - if key == 0 { - return c.Request - } - if keyAsString, ok := key.(string); ok { - val, _ := c.Get(keyAsString) - return val - } - return nil -} diff --git a/vendor/github.com/gin-gonic/gin/context_appengine.go b/vendor/github.com/gin-gonic/gin/context_appengine.go deleted file mode 100644 index 38c189a0b..000000000 --- a/vendor/github.com/gin-gonic/gin/context_appengine.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build appengine - -// Copyright 2017 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -func init() { - defaultAppEngine = true -} diff --git a/vendor/github.com/gin-gonic/gin/debug.go b/vendor/github.com/gin-gonic/gin/debug.go deleted file mode 100644 index a121591a8..000000000 --- a/vendor/github.com/gin-gonic/gin/debug.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "bytes" - "html/template" - "log" -) - -func init() { - log.SetFlags(0) -} - -// IsDebugging returns true if the framework is running in debug mode. -// Use SetMode(gin.Release) to switch to disable the debug mode. -func IsDebugging() bool { - return ginMode == debugCode -} - -func debugPrintRoute(httpMethod, absolutePath string, handlers HandlersChain) { - if IsDebugging() { - nuHandlers := len(handlers) - handlerName := nameOfFunction(handlers.Last()) - debugPrint("%-6s %-25s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers) - } -} - -func debugPrintLoadTemplate(tmpl *template.Template) { - if IsDebugging() { - var buf bytes.Buffer - for _, tmpl := range tmpl.Templates() { - buf.WriteString("\t- ") - buf.WriteString(tmpl.Name()) - buf.WriteString("\n") - } - debugPrint("Loaded HTML Templates (%d): \n%s\n", len(tmpl.Templates()), buf.String()) - } -} - -func debugPrint(format string, values ...interface{}) { - if IsDebugging() { - log.Printf("[GIN-debug] "+format, values...) - } -} - -func debugPrintWARNINGNew() { - debugPrint(`[WARNING] Running in "debug" mode. Switch to "release" mode in production. - - using env: export GIN_MODE=release - - using code: gin.SetMode(gin.ReleaseMode) - -`) -} - -func debugPrintWARNINGSetHTMLTemplate() { - debugPrint(`[WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called -at initialization. ie. before any route is registered or the router is listening in a socket: - - router := gin.Default() - router.SetHTMLTemplate(template) // << good place - -`) -} - -func debugPrintError(err error) { - if err != nil { - debugPrint("[ERROR] %v\n", err) - } -} diff --git a/vendor/github.com/gin-gonic/gin/deprecated.go b/vendor/github.com/gin-gonic/gin/deprecated.go deleted file mode 100644 index 27e8f5583..000000000 --- a/vendor/github.com/gin-gonic/gin/deprecated.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "github.com/gin-gonic/gin/binding" - "log" -) - -func (c *Context) GetCookie(name string) (string, error) { - log.Println("GetCookie() method is deprecated. Use Cookie() instead.") - return c.Cookie(name) -} - -// BindWith binds the passed struct pointer using the specified binding engine. -// See the binding package. -func (c *Context) BindWith(obj interface{}, b binding.Binding) error { - log.Println(`BindWith(\"interface{}, binding.Binding\") error is going to - be deprecated, please check issue #662 and either use MustBindWith() if you - want HTTP 400 to be automatically returned if any error occur, of use - ShouldBindWith() if you need to manage the error.`) - return c.MustBindWith(obj, b) -} diff --git a/vendor/github.com/gin-gonic/gin/errors.go b/vendor/github.com/gin-gonic/gin/errors.go deleted file mode 100644 index 896af6fc2..000000000 --- a/vendor/github.com/gin-gonic/gin/errors.go +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" -) - -type ErrorType uint64 - -const ( - ErrorTypeBind ErrorType = 1 << 63 // used when c.Bind() fails - ErrorTypeRender ErrorType = 1 << 62 // used when c.Render() fails - ErrorTypePrivate ErrorType = 1 << 0 - ErrorTypePublic ErrorType = 1 << 1 - - ErrorTypeAny ErrorType = 1<<64 - 1 - ErrorTypeNu = 2 -) - -type ( - Error struct { - Err error - Type ErrorType - Meta interface{} - } - - errorMsgs []*Error -) - -var _ error = &Error{} - -func (msg *Error) SetType(flags ErrorType) *Error { - msg.Type = flags - return msg -} - -func (msg *Error) SetMeta(data interface{}) *Error { - msg.Meta = data - return msg -} - -func (msg *Error) JSON() interface{} { - json := H{} - if msg.Meta != nil { - value := reflect.ValueOf(msg.Meta) - switch value.Kind() { - case reflect.Struct: - return msg.Meta - case reflect.Map: - for _, key := range value.MapKeys() { - json[key.String()] = value.MapIndex(key).Interface() - } - default: - json["meta"] = msg.Meta - } - } - if _, ok := json["error"]; !ok { - json["error"] = msg.Error() - } - return json -} - -// MarshalJSON implements the json.Marshaller interface -func (msg *Error) MarshalJSON() ([]byte, error) { - return json.Marshal(msg.JSON()) -} - -// Implements the error interface -func (msg Error) Error() string { - return msg.Err.Error() -} - -func (msg *Error) IsType(flags ErrorType) bool { - return (msg.Type & flags) > 0 -} - -// Returns a readonly copy filtered the byte. -// ie ByType(gin.ErrorTypePublic) returns a slice of errors with type=ErrorTypePublic -func (a errorMsgs) ByType(typ ErrorType) errorMsgs { - if len(a) == 0 { - return nil - } - if typ == ErrorTypeAny { - return a - } - var result errorMsgs - for _, msg := range a { - if msg.IsType(typ) { - result = append(result, msg) - } - } - return result -} - -// Returns the last error in the slice. It returns nil if the array is empty. -// Shortcut for errors[len(errors)-1] -func (a errorMsgs) Last() *Error { - length := len(a) - if length > 0 { - return a[length-1] - } - return nil -} - -// Returns an array will all the error messages. -// Example: -// c.Error(errors.New("first")) -// c.Error(errors.New("second")) -// c.Error(errors.New("third")) -// c.Errors.Errors() // == []string{"first", "second", "third"} -func (a errorMsgs) Errors() []string { - if len(a) == 0 { - return nil - } - errorStrings := make([]string, len(a)) - for i, err := range a { - errorStrings[i] = err.Error() - } - return errorStrings -} - -func (a errorMsgs) JSON() interface{} { - switch len(a) { - case 0: - return nil - case 1: - return a.Last().JSON() - default: - json := make([]interface{}, len(a)) - for i, err := range a { - json[i] = err.JSON() - } - return json - } -} - -func (a errorMsgs) MarshalJSON() ([]byte, error) { - return json.Marshal(a.JSON()) -} - -func (a errorMsgs) String() string { - if len(a) == 0 { - return "" - } - var buffer bytes.Buffer - for i, msg := range a { - fmt.Fprintf(&buffer, "Error #%02d: %s\n", (i + 1), msg.Err) - if msg.Meta != nil { - fmt.Fprintf(&buffer, " Meta: %v\n", msg.Meta) - } - } - return buffer.String() -} diff --git a/vendor/github.com/gin-gonic/gin/fs.go b/vendor/github.com/gin-gonic/gin/fs.go deleted file mode 100644 index 12645826a..000000000 --- a/vendor/github.com/gin-gonic/gin/fs.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2017 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "net/http" - "os" -) - -type ( - onlyfilesFS struct { - fs http.FileSystem - } - neuteredReaddirFile struct { - http.File - } -) - -// Dir returns a http.Filesystem that can be used by http.FileServer(). It is used internally -// in router.Static(). -// if listDirectory == true, then it works the same as http.Dir() otherwise it returns -// a filesystem that prevents http.FileServer() to list the directory files. -func Dir(root string, listDirectory bool) http.FileSystem { - fs := http.Dir(root) - if listDirectory { - return fs - } - return &onlyfilesFS{fs} -} - -// Conforms to http.Filesystem -func (fs onlyfilesFS) Open(name string) (http.File, error) { - f, err := fs.fs.Open(name) - if err != nil { - return nil, err - } - return neuteredReaddirFile{f}, nil -} - -// Overrides the http.File default implementation -func (f neuteredReaddirFile) Readdir(count int) ([]os.FileInfo, error) { - // this disables directory listing - return nil, nil -} diff --git a/vendor/github.com/gin-gonic/gin/gin.go b/vendor/github.com/gin-gonic/gin/gin.go deleted file mode 100644 index c4118a4ef..000000000 --- a/vendor/github.com/gin-gonic/gin/gin.go +++ /dev/null @@ -1,418 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "html/template" - "net" - "net/http" - "os" - "sync" - - "github.com/gin-gonic/gin/render" -) - -// Version is Framework's version -const Version = "v1.2" - -var default404Body = []byte("404 page not found") -var default405Body = []byte("405 method not allowed") -var defaultAppEngine bool - -type HandlerFunc func(*Context) -type HandlersChain []HandlerFunc - -// Last returns the last handler in the chain. ie. the last handler is the main own. -func (c HandlersChain) Last() HandlerFunc { - length := len(c) - if length > 0 { - return c[length-1] - } - return nil -} - -type ( - RoutesInfo []RouteInfo - RouteInfo struct { - Method string - Path string - Handler string - } - - // Engine is the framework's instance, it contains the muxer, middleware and configuration settings. - // Create an instance of Engine, by using New() or Default() - Engine struct { - RouterGroup - delims render.Delims - HTMLRender render.HTMLRender - FuncMap template.FuncMap - allNoRoute HandlersChain - allNoMethod HandlersChain - noRoute HandlersChain - noMethod HandlersChain - pool sync.Pool - trees methodTrees - - // Enables automatic redirection if the current route can't be matched but a - // handler for the path with (without) the trailing slash exists. - // For example if /foo/ is requested but a route only exists for /foo, the - // client is redirected to /foo with http status code 301 for GET requests - // and 307 for all other request methods. - RedirectTrailingSlash bool - - // If enabled, the router tries to fix the current request path, if no - // handle is registered for it. - // First superfluous path elements like ../ or // are removed. - // Afterwards the router does a case-insensitive lookup of the cleaned path. - // If a handle can be found for this route, the router makes a redirection - // to the corrected path with status code 301 for GET requests and 307 for - // all other request methods. - // For example /FOO and /..//Foo could be redirected to /foo. - // RedirectTrailingSlash is independent of this option. - RedirectFixedPath bool - - // If enabled, the router checks if another method is allowed for the - // current route, if the current request can not be routed. - // If this is the case, the request is answered with 'Method Not Allowed' - // and HTTP status code 405. - // If no other Method is allowed, the request is delegated to the NotFound - // handler. - HandleMethodNotAllowed bool - ForwardedByClientIP bool - - // #726 #755 If enabled, it will thrust some headers starting with - // 'X-AppEngine...' for better integration with that PaaS. - AppEngine bool - - // If enabled, the url.RawPath will be used to find parameters. - UseRawPath bool - // If true, the path value will be unescaped. - // If UseRawPath is false (by default), the UnescapePathValues effectively is true, - // as url.Path gonna be used, which is already unescaped. - UnescapePathValues bool - } -) - -var _ IRouter = &Engine{} - -// New returns a new blank Engine instance without any middleware attached. -// By default the configuration is: -// - RedirectTrailingSlash: true -// - RedirectFixedPath: false -// - HandleMethodNotAllowed: false -// - ForwardedByClientIP: true -// - UseRawPath: false -// - UnescapePathValues: true -func New() *Engine { - debugPrintWARNINGNew() - engine := &Engine{ - RouterGroup: RouterGroup{ - Handlers: nil, - basePath: "/", - root: true, - }, - FuncMap: template.FuncMap{}, - RedirectTrailingSlash: true, - RedirectFixedPath: false, - HandleMethodNotAllowed: false, - ForwardedByClientIP: true, - AppEngine: defaultAppEngine, - UseRawPath: false, - UnescapePathValues: true, - trees: make(methodTrees, 0, 9), - delims: render.Delims{"{{", "}}"}, - } - engine.RouterGroup.engine = engine - engine.pool.New = func() interface{} { - return engine.allocateContext() - } - return engine -} - -// Default returns an Engine instance with the Logger and Recovery middleware already attached. -func Default() *Engine { - engine := New() - engine.Use(Logger(), Recovery()) - return engine -} - -func (engine *Engine) allocateContext() *Context { - return &Context{engine: engine} -} - -func (engine *Engine) Delims(left, right string) *Engine { - engine.delims = render.Delims{left, right} - return engine -} - -func (engine *Engine) LoadHTMLGlob(pattern string) { - if IsDebugging() { - debugPrintLoadTemplate(template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseGlob(pattern))) - engine.HTMLRender = render.HTMLDebug{Glob: pattern, FuncMap: engine.FuncMap, Delims: engine.delims} - } else { - templ := template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseGlob(pattern)) - engine.SetHTMLTemplate(templ) - } -} - -func (engine *Engine) LoadHTMLFiles(files ...string) { - if IsDebugging() { - engine.HTMLRender = render.HTMLDebug{Files: files, FuncMap: engine.FuncMap, Delims: engine.delims} - } else { - templ := template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseFiles(files...)) - engine.SetHTMLTemplate(templ) - } -} - -func (engine *Engine) SetHTMLTemplate(templ *template.Template) { - if len(engine.trees) > 0 { - debugPrintWARNINGSetHTMLTemplate() - } - - engine.HTMLRender = render.HTMLProduction{Template: templ.Funcs(engine.FuncMap)} -} - -func (engine *Engine) SetFuncMap(funcMap template.FuncMap) { - engine.FuncMap = funcMap -} - -// NoRoute adds handlers for NoRoute. It return a 404 code by default. -func (engine *Engine) NoRoute(handlers ...HandlerFunc) { - engine.noRoute = handlers - engine.rebuild404Handlers() -} - -// NoMethod sets the handlers called when... TODO -func (engine *Engine) NoMethod(handlers ...HandlerFunc) { - engine.noMethod = handlers - engine.rebuild405Handlers() -} - -// Use attachs a global middleware to the router. ie. the middleware attached though Use() will be -// included in the handlers chain for every single request. Even 404, 405, static files... -// For example, this is the right place for a logger or error management middleware. -func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes { - engine.RouterGroup.Use(middleware...) - engine.rebuild404Handlers() - engine.rebuild405Handlers() - return engine -} - -func (engine *Engine) rebuild404Handlers() { - engine.allNoRoute = engine.combineHandlers(engine.noRoute) -} - -func (engine *Engine) rebuild405Handlers() { - engine.allNoMethod = engine.combineHandlers(engine.noMethod) -} - -func (engine *Engine) addRoute(method, path string, handlers HandlersChain) { - assert1(path[0] == '/', "path must begin with '/'") - assert1(len(method) > 0, "HTTP method can not be empty") - assert1(len(handlers) > 0, "there must be at least one handler") - - debugPrintRoute(method, path, handlers) - root := engine.trees.get(method) - if root == nil { - root = new(node) - engine.trees = append(engine.trees, methodTree{method: method, root: root}) - } - root.addRoute(path, handlers) -} - -// Routes returns a slice of registered routes, including some useful information, such as: -// the http method, path and the handler name. -func (engine *Engine) Routes() (routes RoutesInfo) { - for _, tree := range engine.trees { - routes = iterate("", tree.method, routes, tree.root) - } - return routes -} - -func iterate(path, method string, routes RoutesInfo, root *node) RoutesInfo { - path += root.path - if len(root.handlers) > 0 { - routes = append(routes, RouteInfo{ - Method: method, - Path: path, - Handler: nameOfFunction(root.handlers.Last()), - }) - } - for _, child := range root.children { - routes = iterate(path, method, routes, child) - } - return routes -} - -// Run attaches the router to a http.Server and starts listening and serving HTTP requests. -// It is a shortcut for http.ListenAndServe(addr, router) -// Note: this method will block the calling goroutine indefinitely unless an error happens. -func (engine *Engine) Run(addr ...string) (err error) { - defer func() { debugPrintError(err) }() - - address := resolveAddress(addr) - debugPrint("Listening and serving HTTP on %s\n", address) - err = http.ListenAndServe(address, engine) - return -} - -// RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests. -// It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) -// Note: this method will block the calling goroutine indefinitely unless an error happens. -func (engine *Engine) RunTLS(addr string, certFile string, keyFile string) (err error) { - debugPrint("Listening and serving HTTPS on %s\n", addr) - defer func() { debugPrintError(err) }() - - err = http.ListenAndServeTLS(addr, certFile, keyFile, engine) - return -} - -// RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests -// through the specified unix socket (ie. a file). -// Note: this method will block the calling goroutine indefinitely unless an error happens. -func (engine *Engine) RunUnix(file string) (err error) { - debugPrint("Listening and serving HTTP on unix:/%s", file) - defer func() { debugPrintError(err) }() - - os.Remove(file) - listener, err := net.Listen("unix", file) - if err != nil { - return - } - defer listener.Close() - err = http.Serve(listener, engine) - return -} - -// Conforms to the http.Handler interface. -func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) { - c := engine.pool.Get().(*Context) - c.writermem.reset(w) - c.Request = req - c.reset() - - engine.handleHTTPRequest(c) - - engine.pool.Put(c) -} - -// Re-enter a context that has been rewritten. -// This can be done by setting c.Request.Path to your new target. -// Disclaimer: You can loop yourself to death with this, use wisely. -func (engine *Engine) HandleContext(c *Context) { - c.reset() - engine.handleHTTPRequest(c) - engine.pool.Put(c) -} - -func (engine *Engine) handleHTTPRequest(context *Context) { - httpMethod := context.Request.Method - var path string - var unescape bool - if engine.UseRawPath && len(context.Request.URL.RawPath) > 0 { - path = context.Request.URL.RawPath - unescape = engine.UnescapePathValues - } else { - path = context.Request.URL.Path - unescape = false - } - - // Find root of the tree for the given HTTP method - t := engine.trees - for i, tl := 0, len(t); i < tl; i++ { - if t[i].method == httpMethod { - root := t[i].root - // Find route in tree - handlers, params, tsr := root.getValue(path, context.Params, unescape) - if handlers != nil { - context.handlers = handlers - context.Params = params - context.Next() - context.writermem.WriteHeaderNow() - return - } - if httpMethod != "CONNECT" && path != "/" { - if tsr && engine.RedirectTrailingSlash { - redirectTrailingSlash(context) - return - } - if engine.RedirectFixedPath && redirectFixedPath(context, root, engine.RedirectFixedPath) { - return - } - } - break - } - } - - // TODO: unit test - if engine.HandleMethodNotAllowed { - for _, tree := range engine.trees { - if tree.method != httpMethod { - if handlers, _, _ := tree.root.getValue(path, nil, unescape); handlers != nil { - context.handlers = engine.allNoMethod - serveError(context, 405, default405Body) - return - } - } - } - } - context.handlers = engine.allNoRoute - serveError(context, 404, default404Body) -} - -var mimePlain = []string{MIMEPlain} - -func serveError(c *Context, code int, defaultMessage []byte) { - c.writermem.status = code - c.Next() - if !c.writermem.Written() { - if c.writermem.Status() == code { - c.writermem.Header()["Content-Type"] = mimePlain - c.Writer.Write(defaultMessage) - } else { - c.writermem.WriteHeaderNow() - } - } -} - -func redirectTrailingSlash(c *Context) { - req := c.Request - path := req.URL.Path - code := 301 // Permanent redirect, request with GET method - if req.Method != "GET" { - code = 307 - } - - if len(path) > 1 && path[len(path)-1] == '/' { - req.URL.Path = path[:len(path)-1] - } else { - req.URL.Path = path + "/" - } - debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String()) - http.Redirect(c.Writer, req, req.URL.String(), code) - c.writermem.WriteHeaderNow() -} - -func redirectFixedPath(c *Context, root *node, trailingSlash bool) bool { - req := c.Request - path := req.URL.Path - - fixedPath, found := root.findCaseInsensitivePath( - cleanPath(path), - trailingSlash, - ) - if found { - code := 301 // Permanent redirect, request with GET method - if req.Method != "GET" { - code = 307 - } - req.URL.Path = string(fixedPath) - debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String()) - http.Redirect(c.Writer, req, req.URL.String(), code) - c.writermem.WriteHeaderNow() - return true - } - return false -} diff --git a/vendor/github.com/gin-gonic/gin/logger.go b/vendor/github.com/gin-gonic/gin/logger.go deleted file mode 100644 index dc6f14154..000000000 --- a/vendor/github.com/gin-gonic/gin/logger.go +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "fmt" - "io" - "os" - "time" - - "github.com/mattn/go-isatty" -) - -var ( - green = string([]byte{27, 91, 57, 55, 59, 52, 50, 109}) - white = string([]byte{27, 91, 57, 48, 59, 52, 55, 109}) - yellow = string([]byte{27, 91, 57, 55, 59, 52, 51, 109}) - red = string([]byte{27, 91, 57, 55, 59, 52, 49, 109}) - blue = string([]byte{27, 91, 57, 55, 59, 52, 52, 109}) - magenta = string([]byte{27, 91, 57, 55, 59, 52, 53, 109}) - cyan = string([]byte{27, 91, 57, 55, 59, 52, 54, 109}) - reset = string([]byte{27, 91, 48, 109}) - disableColor = false -) - -func DisableConsoleColor() { - disableColor = true -} - -func ErrorLogger() HandlerFunc { - return ErrorLoggerT(ErrorTypeAny) -} - -func ErrorLoggerT(typ ErrorType) HandlerFunc { - return func(c *Context) { - c.Next() - errors := c.Errors.ByType(typ) - if len(errors) > 0 { - c.JSON(-1, errors) - } - } -} - -// Logger instances a Logger middleware that will write the logs to gin.DefaultWriter -// By default gin.DefaultWriter = os.Stdout -func Logger() HandlerFunc { - return LoggerWithWriter(DefaultWriter) -} - -// LoggerWithWriter instance a Logger middleware with the specified writter buffer. -// Example: os.Stdout, a file opened in write mode, a socket... -func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc { - isTerm := true - - if w, ok := out.(*os.File); !ok || - (os.Getenv("TERM") == "dumb" || (!isatty.IsTerminal(w.Fd()) && !isatty.IsCygwinTerminal(w.Fd()))) || - disableColor { - isTerm = false - } - - var skip map[string]struct{} - - if length := len(notlogged); length > 0 { - skip = make(map[string]struct{}, length) - - for _, path := range notlogged { - skip[path] = struct{}{} - } - } - - return func(c *Context) { - // Start timer - start := time.Now() - path := c.Request.URL.Path - - // Process request - c.Next() - - // Log only when path is not being skipped - if _, ok := skip[path]; !ok { - // Stop timer - end := time.Now() - latency := end.Sub(start) - - clientIP := c.ClientIP() - method := c.Request.Method - statusCode := c.Writer.Status() - var statusColor, methodColor string - if isTerm { - statusColor = colorForStatus(statusCode) - methodColor = colorForMethod(method) - } - comment := c.Errors.ByType(ErrorTypePrivate).String() - - fmt.Fprintf(out, "[GIN] %v |%s %3d %s| %13v | %15s |%s %s %-7s %s\n%s", - end.Format("2006/01/02 - 15:04:05"), - statusColor, statusCode, reset, - latency, - clientIP, - methodColor, method, reset, - path, - comment, - ) - } - } -} - -func colorForStatus(code int) string { - switch { - case code >= 200 && code < 300: - return green - case code >= 300 && code < 400: - return white - case code >= 400 && code < 500: - return yellow - default: - return red - } -} - -func colorForMethod(method string) string { - switch method { - case "GET": - return blue - case "POST": - return cyan - case "PUT": - return yellow - case "DELETE": - return red - case "PATCH": - return green - case "HEAD": - return magenta - case "OPTIONS": - return white - default: - return reset - } -} diff --git a/vendor/github.com/gin-gonic/gin/mode.go b/vendor/github.com/gin-gonic/gin/mode.go deleted file mode 100644 index e24dbdc2c..000000000 --- a/vendor/github.com/gin-gonic/gin/mode.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "io" - "os" - - "github.com/gin-gonic/gin/binding" -) - -const ENV_GIN_MODE = "GIN_MODE" - -const ( - DebugMode string = "debug" - ReleaseMode string = "release" - TestMode string = "test" -) -const ( - debugCode = iota - releaseCode - testCode -) - -// DefaultWriter is the default io.Writer used the Gin for debug output and -// middleware output like Logger() or Recovery(). -// Note that both Logger and Recovery provides custom ways to configure their -// output io.Writer. -// To support coloring in Windows use: -// import "github.com/mattn/go-colorable" -// gin.DefaultWriter = colorable.NewColorableStdout() -var DefaultWriter io.Writer = os.Stdout -var DefaultErrorWriter io.Writer = os.Stderr - -var ginMode = debugCode -var modeName = DebugMode - -func init() { - mode := os.Getenv(ENV_GIN_MODE) - if len(mode) == 0 { - SetMode(DebugMode) - } else { - SetMode(mode) - } -} - -func SetMode(value string) { - switch value { - case DebugMode: - ginMode = debugCode - case ReleaseMode: - ginMode = releaseCode - case TestMode: - ginMode = testCode - default: - panic("gin mode unknown: " + value) - } - modeName = value -} - -func DisableBindValidation() { - binding.Validator = nil -} - -func Mode() string { - return modeName -} diff --git a/vendor/github.com/gin-gonic/gin/path.go b/vendor/github.com/gin-gonic/gin/path.go deleted file mode 100644 index d7e7458b5..000000000 --- a/vendor/github.com/gin-gonic/gin/path.go +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2013 Julien Schmidt. All rights reserved. -// Based on the path package, Copyright 2009 The Go Authors. -// Use of this source code is governed by a BSD-style license that can be found -// at https://github.com/julienschmidt/httprouter/blob/master/LICENSE. - -package gin - -// CleanPath is the URL version of path.Clean, it returns a canonical URL path -// for p, eliminating . and .. elements. -// -// The following rules are applied iteratively until no further processing can -// be done: -// 1. Replace multiple slashes with a single slash. -// 2. Eliminate each . path name element (the current directory). -// 3. Eliminate each inner .. path name element (the parent directory) -// along with the non-.. element that precedes it. -// 4. Eliminate .. elements that begin a rooted path: -// that is, replace "/.." by "/" at the beginning of a path. -// -// If the result of this process is an empty string, "/" is returned -func cleanPath(p string) string { - // Turn empty string into "/" - if p == "" { - return "/" - } - - n := len(p) - var buf []byte - - // Invariants: - // reading from path; r is index of next byte to process. - // writing to buf; w is index of next byte to write. - - // path must start with '/' - r := 1 - w := 1 - - if p[0] != '/' { - r = 0 - buf = make([]byte, n+1) - buf[0] = '/' - } - - trailing := n > 2 && p[n-1] == '/' - - // A bit more clunky without a 'lazybuf' like the path package, but the loop - // gets completely inlined (bufApp). So in contrast to the path package this - // loop has no expensive function calls (except 1x make) - - for r < n { - switch { - case p[r] == '/': - // empty path element, trailing slash is added after the end - r++ - - case p[r] == '.' && r+1 == n: - trailing = true - r++ - - case p[r] == '.' && p[r+1] == '/': - // . element - r++ - - case p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'): - // .. element: remove to last / - r += 2 - - if w > 1 { - // can backtrack - w-- - - if buf == nil { - for w > 1 && p[w] != '/' { - w-- - } - } else { - for w > 1 && buf[w] != '/' { - w-- - } - } - } - - default: - // real path element. - // add slash if needed - if w > 1 { - bufApp(&buf, p, w, '/') - w++ - } - - // copy element - for r < n && p[r] != '/' { - bufApp(&buf, p, w, p[r]) - w++ - r++ - } - } - } - - // re-append trailing slash - if trailing && w > 1 { - bufApp(&buf, p, w, '/') - w++ - } - - if buf == nil { - return p[:w] - } - return string(buf[:w]) -} - -// internal helper to lazily create a buffer if necessary -func bufApp(buf *[]byte, s string, w int, c byte) { - if *buf == nil { - if s[w] == c { - return - } - - *buf = make([]byte, len(s)) - copy(*buf, s[:w]) - } - (*buf)[w] = c -} diff --git a/vendor/github.com/gin-gonic/gin/recovery.go b/vendor/github.com/gin-gonic/gin/recovery.go deleted file mode 100644 index c502f3553..000000000 --- a/vendor/github.com/gin-gonic/gin/recovery.go +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "log" - "net/http/httputil" - "runtime" -) - -var ( - dunno = []byte("???") - centerDot = []byte("·") - dot = []byte(".") - slash = []byte("/") -) - -// Recovery returns a middleware that recovers from any panics and writes a 500 if there was one. -func Recovery() HandlerFunc { - return RecoveryWithWriter(DefaultErrorWriter) -} - -func RecoveryWithWriter(out io.Writer) HandlerFunc { - var logger *log.Logger - if out != nil { - logger = log.New(out, "\n\n\x1b[31m", log.LstdFlags) - } - return func(c *Context) { - defer func() { - if err := recover(); err != nil { - if logger != nil { - stack := stack(3) - httprequest, _ := httputil.DumpRequest(c.Request, false) - logger.Printf("[Recovery] panic recovered:\n%s\n%s\n%s%s", string(httprequest), err, stack, reset) - } - c.AbortWithStatus(500) - } - }() - c.Next() - } -} - -// stack returns a nicely formated stack frame, skipping skip frames -func stack(skip int) []byte { - buf := new(bytes.Buffer) // the returned data - // As we loop, we open files and read them. These variables record the currently - // loaded file. - var lines [][]byte - var lastFile string - for i := skip; ; i++ { // Skip the expected number of frames - pc, file, line, ok := runtime.Caller(i) - if !ok { - break - } - // Print this much at least. If we can't find the source, it won't show. - fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc) - if file != lastFile { - data, err := ioutil.ReadFile(file) - if err != nil { - continue - } - lines = bytes.Split(data, []byte{'\n'}) - lastFile = file - } - fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line)) - } - return buf.Bytes() -} - -// source returns a space-trimmed slice of the n'th line. -func source(lines [][]byte, n int) []byte { - n-- // in stack trace, lines are 1-indexed but our array is 0-indexed - if n < 0 || n >= len(lines) { - return dunno - } - return bytes.TrimSpace(lines[n]) -} - -// function returns, if possible, the name of the function containing the PC. -func function(pc uintptr) []byte { - fn := runtime.FuncForPC(pc) - if fn == nil { - return dunno - } - name := []byte(fn.Name()) - // The name includes the path name to the package, which is unnecessary - // since the file name is already included. Plus, it has center dots. - // That is, we see - // runtime/debug.*T·ptrmethod - // and want - // *T.ptrmethod - // Also the package path might contains dot (e.g. code.google.com/...), - // so first eliminate the path prefix - if lastslash := bytes.LastIndex(name, slash); lastslash >= 0 { - name = name[lastslash+1:] - } - if period := bytes.Index(name, dot); period >= 0 { - name = name[period+1:] - } - name = bytes.Replace(name, centerDot, dot, -1) - return name -} diff --git a/vendor/github.com/gin-gonic/gin/render/data.go b/vendor/github.com/gin-gonic/gin/render/data.go deleted file mode 100644 index c296042c9..000000000 --- a/vendor/github.com/gin-gonic/gin/render/data.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package render - -import "net/http" - -type Data struct { - ContentType string - Data []byte -} - -// Render (Data) writes data with custom ContentType -func (r Data) Render(w http.ResponseWriter) (err error) { - r.WriteContentType(w) - _, err = w.Write(r.Data) - return -} - -func (r Data) WriteContentType(w http.ResponseWriter) { - writeContentType(w, []string{r.ContentType}) -} diff --git a/vendor/github.com/gin-gonic/gin/render/html.go b/vendor/github.com/gin-gonic/gin/render/html.go deleted file mode 100644 index cf91219cc..000000000 --- a/vendor/github.com/gin-gonic/gin/render/html.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package render - -import ( - "html/template" - "net/http" -) - -type ( - Delims struct { - Left string - Right string - } - - HTMLRender interface { - Instance(string, interface{}) Render - } - - HTMLProduction struct { - Template *template.Template - Delims Delims - } - - HTMLDebug struct { - Files []string - Glob string - Delims Delims - FuncMap template.FuncMap - } - - HTML struct { - Template *template.Template - Name string - Data interface{} - } -) - -var htmlContentType = []string{"text/html; charset=utf-8"} - -func (r HTMLProduction) Instance(name string, data interface{}) Render { - return HTML{ - Template: r.Template, - Name: name, - Data: data, - } -} - -func (r HTMLDebug) Instance(name string, data interface{}) Render { - return HTML{ - Template: r.loadTemplate(), - Name: name, - Data: data, - } -} -func (r HTMLDebug) loadTemplate() *template.Template { - if r.FuncMap == nil { - r.FuncMap = template.FuncMap{} - } - if len(r.Files) > 0 { - return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseFiles(r.Files...)) - } - if len(r.Glob) > 0 { - return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseGlob(r.Glob)) - } - panic("the HTML debug render was created without files or glob pattern") -} - -func (r HTML) Render(w http.ResponseWriter) error { - r.WriteContentType(w) - - if len(r.Name) == 0 { - return r.Template.Execute(w, r.Data) - } - return r.Template.ExecuteTemplate(w, r.Name, r.Data) -} - -func (r HTML) WriteContentType(w http.ResponseWriter) { - writeContentType(w, htmlContentType) -} diff --git a/vendor/github.com/gin-gonic/gin/render/json.go b/vendor/github.com/gin-gonic/gin/render/json.go deleted file mode 100644 index 3ee8b1326..000000000 --- a/vendor/github.com/gin-gonic/gin/render/json.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package render - -import ( - "encoding/json" - "net/http" -) - -type ( - JSON struct { - Data interface{} - } - - IndentedJSON struct { - Data interface{} - } -) - -var jsonContentType = []string{"application/json; charset=utf-8"} - -func (r JSON) Render(w http.ResponseWriter) (err error) { - if err = WriteJSON(w, r.Data); err != nil { - panic(err) - } - return -} - -func (r JSON) WriteContentType(w http.ResponseWriter) { - writeContentType(w, jsonContentType) -} - -func WriteJSON(w http.ResponseWriter, obj interface{}) error { - writeContentType(w, jsonContentType) - jsonBytes, err := json.Marshal(obj) - if err != nil { - return err - } - w.Write(jsonBytes) - return nil -} - -func (r IndentedJSON) Render(w http.ResponseWriter) error { - r.WriteContentType(w) - jsonBytes, err := json.MarshalIndent(r.Data, "", " ") - if err != nil { - return err - } - w.Write(jsonBytes) - return nil -} - -func (r IndentedJSON) WriteContentType(w http.ResponseWriter) { - writeContentType(w, jsonContentType) -} diff --git a/vendor/github.com/gin-gonic/gin/render/msgpack.go b/vendor/github.com/gin-gonic/gin/render/msgpack.go deleted file mode 100644 index e6c13e588..000000000 --- a/vendor/github.com/gin-gonic/gin/render/msgpack.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2017 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package render - -import ( - "net/http" - - "github.com/ugorji/go/codec" -) - -type MsgPack struct { - Data interface{} -} - -var msgpackContentType = []string{"application/msgpack; charset=utf-8"} - -func (r MsgPack) WriteContentType(w http.ResponseWriter) { - writeContentType(w, msgpackContentType) -} - -func (r MsgPack) Render(w http.ResponseWriter) error { - return WriteMsgPack(w, r.Data) -} - -func WriteMsgPack(w http.ResponseWriter, obj interface{}) error { - writeContentType(w, msgpackContentType) - var h codec.Handle = new(codec.MsgpackHandle) - return codec.NewEncoder(w, h).Encode(obj) -} diff --git a/vendor/github.com/gin-gonic/gin/render/redirect.go b/vendor/github.com/gin-gonic/gin/render/redirect.go deleted file mode 100644 index f874a3515..000000000 --- a/vendor/github.com/gin-gonic/gin/render/redirect.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package render - -import ( - "fmt" - "net/http" -) - -type Redirect struct { - Code int - Request *http.Request - Location string -} - -func (r Redirect) Render(w http.ResponseWriter) error { - if (r.Code < 300 || r.Code > 308) && r.Code != 201 { - panic(fmt.Sprintf("Cannot redirect with status code %d", r.Code)) - } - http.Redirect(w, r.Request, r.Location, r.Code) - return nil -} - -func (r Redirect) WriteContentType(http.ResponseWriter) {} diff --git a/vendor/github.com/gin-gonic/gin/render/render.go b/vendor/github.com/gin-gonic/gin/render/render.go deleted file mode 100644 index 462914214..000000000 --- a/vendor/github.com/gin-gonic/gin/render/render.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package render - -import "net/http" - -type Render interface { - Render(http.ResponseWriter) error - WriteContentType(w http.ResponseWriter) -} - -var ( - _ Render = JSON{} - _ Render = IndentedJSON{} - _ Render = XML{} - _ Render = String{} - _ Render = Redirect{} - _ Render = Data{} - _ Render = HTML{} - _ HTMLRender = HTMLDebug{} - _ HTMLRender = HTMLProduction{} - _ Render = YAML{} - _ Render = MsgPack{} - _ Render = MsgPack{} -) - -func writeContentType(w http.ResponseWriter, value []string) { - header := w.Header() - if val := header["Content-Type"]; len(val) == 0 { - header["Content-Type"] = value - } -} diff --git a/vendor/github.com/gin-gonic/gin/render/text.go b/vendor/github.com/gin-gonic/gin/render/text.go deleted file mode 100644 index 74cd26bee..000000000 --- a/vendor/github.com/gin-gonic/gin/render/text.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package render - -import ( - "fmt" - "io" - "net/http" -) - -type String struct { - Format string - Data []interface{} -} - -var plainContentType = []string{"text/plain; charset=utf-8"} - -func (r String) Render(w http.ResponseWriter) error { - WriteString(w, r.Format, r.Data) - return nil -} - -func (r String) WriteContentType(w http.ResponseWriter) { - writeContentType(w, plainContentType) -} - -func WriteString(w http.ResponseWriter, format string, data []interface{}) { - writeContentType(w, plainContentType) - if len(data) > 0 { - fmt.Fprintf(w, format, data...) - } else { - io.WriteString(w, format) - } -} diff --git a/vendor/github.com/gin-gonic/gin/render/xml.go b/vendor/github.com/gin-gonic/gin/render/xml.go deleted file mode 100644 index cff1ac3e8..000000000 --- a/vendor/github.com/gin-gonic/gin/render/xml.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package render - -import ( - "encoding/xml" - "net/http" -) - -type XML struct { - Data interface{} -} - -var xmlContentType = []string{"application/xml; charset=utf-8"} - -func (r XML) Render(w http.ResponseWriter) error { - r.WriteContentType(w) - return xml.NewEncoder(w).Encode(r.Data) -} - -func (r XML) WriteContentType(w http.ResponseWriter) { - writeContentType(w, xmlContentType) -} diff --git a/vendor/github.com/gin-gonic/gin/render/yaml.go b/vendor/github.com/gin-gonic/gin/render/yaml.go deleted file mode 100644 index 25d0ebd47..000000000 --- a/vendor/github.com/gin-gonic/gin/render/yaml.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package render - -import ( - "net/http" - - "gopkg.in/yaml.v2" -) - -type YAML struct { - Data interface{} -} - -var yamlContentType = []string{"application/x-yaml; charset=utf-8"} - -func (r YAML) Render(w http.ResponseWriter) error { - r.WriteContentType(w) - - bytes, err := yaml.Marshal(r.Data) - if err != nil { - return err - } - - w.Write(bytes) - return nil -} - -func (r YAML) WriteContentType(w http.ResponseWriter) { - writeContentType(w, yamlContentType) -} diff --git a/vendor/github.com/gin-gonic/gin/response_writer.go b/vendor/github.com/gin-gonic/gin/response_writer.go deleted file mode 100644 index fcbe230d0..000000000 --- a/vendor/github.com/gin-gonic/gin/response_writer.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "bufio" - "io" - "net" - "net/http" -) - -const ( - noWritten = -1 - defaultStatus = 200 -) - -type ( - ResponseWriter interface { - http.ResponseWriter - http.Hijacker - http.Flusher - http.CloseNotifier - - // Returns the HTTP response status code of the current request. - Status() int - - // Returns the number of bytes already written into the response http body. - // See Written() - Size() int - - // Writes the string into the response body. - WriteString(string) (int, error) - - // Returns true if the response body was already written. - Written() bool - - // Forces to write the http header (status code + headers). - WriteHeaderNow() - } - - responseWriter struct { - http.ResponseWriter - size int - status int - } -) - -var _ ResponseWriter = &responseWriter{} - -func (w *responseWriter) reset(writer http.ResponseWriter) { - w.ResponseWriter = writer - w.size = noWritten - w.status = defaultStatus -} - -func (w *responseWriter) WriteHeader(code int) { - if code > 0 && w.status != code { - if w.Written() { - debugPrint("[WARNING] Headers were already written. Wanted to override status code %d with %d", w.status, code) - } - w.status = code - } -} - -func (w *responseWriter) WriteHeaderNow() { - if !w.Written() { - w.size = 0 - w.ResponseWriter.WriteHeader(w.status) - } -} - -func (w *responseWriter) Write(data []byte) (n int, err error) { - w.WriteHeaderNow() - n, err = w.ResponseWriter.Write(data) - w.size += n - return -} - -func (w *responseWriter) WriteString(s string) (n int, err error) { - w.WriteHeaderNow() - n, err = io.WriteString(w.ResponseWriter, s) - w.size += n - return -} - -func (w *responseWriter) Status() int { - return w.status -} - -func (w *responseWriter) Size() int { - return w.size -} - -func (w *responseWriter) Written() bool { - return w.size != noWritten -} - -// Implements the http.Hijacker interface -func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { - if w.size < 0 { - w.size = 0 - } - return w.ResponseWriter.(http.Hijacker).Hijack() -} - -// Implements the http.CloseNotify interface -func (w *responseWriter) CloseNotify() <-chan bool { - return w.ResponseWriter.(http.CloseNotifier).CloseNotify() -} - -// Implements the http.Flush interface -func (w *responseWriter) Flush() { - w.ResponseWriter.(http.Flusher).Flush() -} diff --git a/vendor/github.com/gin-gonic/gin/routergroup.go b/vendor/github.com/gin-gonic/gin/routergroup.go deleted file mode 100644 index f22729bbd..000000000 --- a/vendor/github.com/gin-gonic/gin/routergroup.go +++ /dev/null @@ -1,215 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "net/http" - "path" - "regexp" - "strings" -) - -type ( - IRouter interface { - IRoutes - Group(string, ...HandlerFunc) *RouterGroup - } - - IRoutes interface { - Use(...HandlerFunc) IRoutes - - Handle(string, string, ...HandlerFunc) IRoutes - Any(string, ...HandlerFunc) IRoutes - GET(string, ...HandlerFunc) IRoutes - POST(string, ...HandlerFunc) IRoutes - DELETE(string, ...HandlerFunc) IRoutes - PATCH(string, ...HandlerFunc) IRoutes - PUT(string, ...HandlerFunc) IRoutes - OPTIONS(string, ...HandlerFunc) IRoutes - HEAD(string, ...HandlerFunc) IRoutes - - StaticFile(string, string) IRoutes - Static(string, string) IRoutes - StaticFS(string, http.FileSystem) IRoutes - } - - // RouterGroup is used internally to configure router, a RouterGroup is associated with a prefix - // and an array of handlers (middleware) - RouterGroup struct { - Handlers HandlersChain - basePath string - engine *Engine - root bool - } -) - -var _ IRouter = &RouterGroup{} - -// Use adds middleware to the group, see example code in github. -func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes { - group.Handlers = append(group.Handlers, middleware...) - return group.returnObj() -} - -// Group creates a new router group. You should add all the routes that have common middlwares or the same path prefix. -// For example, all the routes that use a common middlware for authorization could be grouped. -func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup { - return &RouterGroup{ - Handlers: group.combineHandlers(handlers), - basePath: group.calculateAbsolutePath(relativePath), - engine: group.engine, - } -} - -func (group *RouterGroup) BasePath() string { - return group.basePath -} - -func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes { - absolutePath := group.calculateAbsolutePath(relativePath) - handlers = group.combineHandlers(handlers) - group.engine.addRoute(httpMethod, absolutePath, handlers) - return group.returnObj() -} - -// Handle registers a new request handle and middleware with the given path and method. -// The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes. -// See the example code in github. -// -// For GET, POST, PUT, PATCH and DELETE requests the respective shortcut -// functions can be used. -// -// This function is intended for bulk loading and to allow the usage of less -// frequently used, non-standardized or custom methods (e.g. for internal -// communication with a proxy). -func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes { - if matches, err := regexp.MatchString("^[A-Z]+$", httpMethod); !matches || err != nil { - panic("http method " + httpMethod + " is not valid") - } - return group.handle(httpMethod, relativePath, handlers) -} - -// POST is a shortcut for router.Handle("POST", path, handle) -func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes { - return group.handle("POST", relativePath, handlers) -} - -// GET is a shortcut for router.Handle("GET", path, handle) -func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes { - return group.handle("GET", relativePath, handlers) -} - -// DELETE is a shortcut for router.Handle("DELETE", path, handle) -func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes { - return group.handle("DELETE", relativePath, handlers) -} - -// PATCH is a shortcut for router.Handle("PATCH", path, handle) -func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes { - return group.handle("PATCH", relativePath, handlers) -} - -// PUT is a shortcut for router.Handle("PUT", path, handle) -func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes { - return group.handle("PUT", relativePath, handlers) -} - -// OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle) -func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes { - return group.handle("OPTIONS", relativePath, handlers) -} - -// HEAD is a shortcut for router.Handle("HEAD", path, handle) -func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes { - return group.handle("HEAD", relativePath, handlers) -} - -// Any registers a route that matches all the HTTP methods. -// GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE -func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes { - group.handle("GET", relativePath, handlers) - group.handle("POST", relativePath, handlers) - group.handle("PUT", relativePath, handlers) - group.handle("PATCH", relativePath, handlers) - group.handle("HEAD", relativePath, handlers) - group.handle("OPTIONS", relativePath, handlers) - group.handle("DELETE", relativePath, handlers) - group.handle("CONNECT", relativePath, handlers) - group.handle("TRACE", relativePath, handlers) - return group.returnObj() -} - -// StaticFile registers a single route in order to server a single file of the local filesystem. -// router.StaticFile("favicon.ico", "./resources/favicon.ico") -func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes { - if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") { - panic("URL parameters can not be used when serving a static file") - } - handler := func(c *Context) { - c.File(filepath) - } - group.GET(relativePath, handler) - group.HEAD(relativePath, handler) - return group.returnObj() -} - -// Static serves files from the given file system root. -// Internally a http.FileServer is used, therefore http.NotFound is used instead -// of the Router's NotFound handler. -// To use the operating system's file system implementation, -// use : -// router.Static("/static", "/var/www") -func (group *RouterGroup) Static(relativePath, root string) IRoutes { - return group.StaticFS(relativePath, Dir(root, false)) -} - -// StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead. -// Gin by default user: gin.Dir() -func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes { - if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") { - panic("URL parameters can not be used when serving a static folder") - } - handler := group.createStaticHandler(relativePath, fs) - urlPattern := path.Join(relativePath, "/*filepath") - - // Register GET and HEAD handlers - group.GET(urlPattern, handler) - group.HEAD(urlPattern, handler) - return group.returnObj() -} - -func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem) HandlerFunc { - absolutePath := group.calculateAbsolutePath(relativePath) - fileServer := http.StripPrefix(absolutePath, http.FileServer(fs)) - _, nolisting := fs.(*onlyfilesFS) - return func(c *Context) { - if nolisting { - c.Writer.WriteHeader(404) - } - fileServer.ServeHTTP(c.Writer, c.Request) - } -} - -func (group *RouterGroup) combineHandlers(handlers HandlersChain) HandlersChain { - finalSize := len(group.Handlers) + len(handlers) - if finalSize >= int(abortIndex) { - panic("too many handlers") - } - mergedHandlers := make(HandlersChain, finalSize) - copy(mergedHandlers, group.Handlers) - copy(mergedHandlers[len(group.Handlers):], handlers) - return mergedHandlers -} - -func (group *RouterGroup) calculateAbsolutePath(relativePath string) string { - return joinPaths(group.basePath, relativePath) -} - -func (group *RouterGroup) returnObj() IRoutes { - if group.root { - return group.engine - } - return group -} diff --git a/vendor/github.com/gin-gonic/gin/test_helpers.go b/vendor/github.com/gin-gonic/gin/test_helpers.go deleted file mode 100644 index e7dd55f77..000000000 --- a/vendor/github.com/gin-gonic/gin/test_helpers.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2017 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "net/http" -) - -func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine) { - r = New() - c = r.allocateContext() - c.reset() - c.writermem.reset(w) - return -} diff --git a/vendor/github.com/gin-gonic/gin/tree.go b/vendor/github.com/gin-gonic/gin/tree.go deleted file mode 100644 index a39f43bf2..000000000 --- a/vendor/github.com/gin-gonic/gin/tree.go +++ /dev/null @@ -1,622 +0,0 @@ -// Copyright 2013 Julien Schmidt. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be found -// at https://github.com/julienschmidt/httprouter/blob/master/LICENSE - -package gin - -import ( - "net/url" - "strings" - "unicode" -) - -// Param is a single URL parameter, consisting of a key and a value. -type Param struct { - Key string - Value string -} - -// Params is a Param-slice, as returned by the router. -// The slice is ordered, the first URL parameter is also the first slice value. -// It is therefore safe to read values by the index. -type Params []Param - -// Get returns the value of the first Param which key matches the given name. -// If no matching Param is found, an empty string is returned. -func (ps Params) Get(name string) (string, bool) { - for _, entry := range ps { - if entry.Key == name { - return entry.Value, true - } - } - return "", false -} - -// ByName returns the value of the first Param which key matches the given name. -// If no matching Param is found, an empty string is returned. -func (ps Params) ByName(name string) (va string) { - va, _ = ps.Get(name) - return -} - -type methodTree struct { - method string - root *node -} - -type methodTrees []methodTree - -func (trees methodTrees) get(method string) *node { - for _, tree := range trees { - if tree.method == method { - return tree.root - } - } - return nil -} - -func min(a, b int) int { - if a <= b { - return a - } - return b -} - -func countParams(path string) uint8 { - var n uint - for i := 0; i < len(path); i++ { - if path[i] != ':' && path[i] != '*' { - continue - } - n++ - } - if n >= 255 { - return 255 - } - return uint8(n) -} - -type nodeType uint8 - -const ( - static nodeType = iota // default - root - param - catchAll -) - -type node struct { - path string - wildChild bool - nType nodeType - maxParams uint8 - indices string - children []*node - handlers HandlersChain - priority uint32 -} - -// increments priority of the given child and reorders if necessary -func (n *node) incrementChildPrio(pos int) int { - n.children[pos].priority++ - prio := n.children[pos].priority - - // adjust position (move to front) - newPos := pos - for newPos > 0 && n.children[newPos-1].priority < prio { - // swap node positions - tmpN := n.children[newPos-1] - n.children[newPos-1] = n.children[newPos] - n.children[newPos] = tmpN - - newPos-- - } - - // build new index char string - if newPos != pos { - n.indices = n.indices[:newPos] + // unchanged prefix, might be empty - n.indices[pos:pos+1] + // the index char we move - n.indices[newPos:pos] + n.indices[pos+1:] // rest without char at 'pos' - } - - return newPos -} - -// addRoute adds a node with the given handle to the path. -// Not concurrency-safe! -func (n *node) addRoute(path string, handlers HandlersChain) { - fullPath := path - n.priority++ - numParams := countParams(path) - - // non-empty tree - if len(n.path) > 0 || len(n.children) > 0 { - walk: - for { - // Update maxParams of the current node - if numParams > n.maxParams { - n.maxParams = numParams - } - - // Find the longest common prefix. - // This also implies that the common prefix contains no ':' or '*' - // since the existing key can't contain those chars. - i := 0 - max := min(len(path), len(n.path)) - for i < max && path[i] == n.path[i] { - i++ - } - - // Split edge - if i < len(n.path) { - child := node{ - path: n.path[i:], - wildChild: n.wildChild, - indices: n.indices, - children: n.children, - handlers: n.handlers, - priority: n.priority - 1, - } - - // Update maxParams (max of all children) - for i := range child.children { - if child.children[i].maxParams > child.maxParams { - child.maxParams = child.children[i].maxParams - } - } - - n.children = []*node{&child} - // []byte for proper unicode char conversion, see #65 - n.indices = string([]byte{n.path[i]}) - n.path = path[:i] - n.handlers = nil - n.wildChild = false - } - - // Make new node a child of this node - if i < len(path) { - path = path[i:] - - if n.wildChild { - n = n.children[0] - n.priority++ - - // Update maxParams of the child node - if numParams > n.maxParams { - n.maxParams = numParams - } - numParams-- - - // Check if the wildcard matches - if len(path) >= len(n.path) && n.path == path[:len(n.path)] { - // check for longer wildcard, e.g. :name and :names - if len(n.path) >= len(path) || path[len(n.path)] == '/' { - continue walk - } - } - - panic("path segment '" + path + - "' conflicts with existing wildcard '" + n.path + - "' in path '" + fullPath + "'") - } - - c := path[0] - - // slash after param - if n.nType == param && c == '/' && len(n.children) == 1 { - n = n.children[0] - n.priority++ - continue walk - } - - // Check if a child with the next path byte exists - for i := 0; i < len(n.indices); i++ { - if c == n.indices[i] { - i = n.incrementChildPrio(i) - n = n.children[i] - continue walk - } - } - - // Otherwise insert it - if c != ':' && c != '*' { - // []byte for proper unicode char conversion, see #65 - n.indices += string([]byte{c}) - child := &node{ - maxParams: numParams, - } - n.children = append(n.children, child) - n.incrementChildPrio(len(n.indices) - 1) - n = child - } - n.insertChild(numParams, path, fullPath, handlers) - return - - } else if i == len(path) { // Make node a (in-path) leaf - if n.handlers != nil { - panic("handlers are already registered for path ''" + fullPath + "'") - } - n.handlers = handlers - } - return - } - } else { // Empty tree - n.insertChild(numParams, path, fullPath, handlers) - n.nType = root - } -} - -func (n *node) insertChild(numParams uint8, path string, fullPath string, handlers HandlersChain) { - var offset int // already handled bytes of the path - - // find prefix until first wildcard (beginning with ':'' or '*'') - for i, max := 0, len(path); numParams > 0; i++ { - c := path[i] - if c != ':' && c != '*' { - continue - } - - // find wildcard end (either '/' or path end) - end := i + 1 - for end < max && path[end] != '/' { - switch path[end] { - // the wildcard name must not contain ':' and '*' - case ':', '*': - panic("only one wildcard per path segment is allowed, has: '" + - path[i:] + "' in path '" + fullPath + "'") - default: - end++ - } - } - - // check if this Node existing children which would be - // unreachable if we insert the wildcard here - if len(n.children) > 0 { - panic("wildcard route '" + path[i:end] + - "' conflicts with existing children in path '" + fullPath + "'") - } - - // check if the wildcard has a name - if end-i < 2 { - panic("wildcards must be named with a non-empty name in path '" + fullPath + "'") - } - - if c == ':' { // param - // split path at the beginning of the wildcard - if i > 0 { - n.path = path[offset:i] - offset = i - } - - child := &node{ - nType: param, - maxParams: numParams, - } - n.children = []*node{child} - n.wildChild = true - n = child - n.priority++ - numParams-- - - // if the path doesn't end with the wildcard, then there - // will be another non-wildcard subpath starting with '/' - if end < max { - n.path = path[offset:end] - offset = end - - child := &node{ - maxParams: numParams, - priority: 1, - } - n.children = []*node{child} - n = child - } - - } else { // catchAll - if end != max || numParams > 1 { - panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'") - } - - if len(n.path) > 0 && n.path[len(n.path)-1] == '/' { - panic("catch-all conflicts with existing handle for the path segment root in path '" + fullPath + "'") - } - - // currently fixed width 1 for '/' - i-- - if path[i] != '/' { - panic("no / before catch-all in path '" + fullPath + "'") - } - - n.path = path[offset:i] - - // first node: catchAll node with empty path - child := &node{ - wildChild: true, - nType: catchAll, - maxParams: 1, - } - n.children = []*node{child} - n.indices = string(path[i]) - n = child - n.priority++ - - // second node: node holding the variable - child = &node{ - path: path[i:], - nType: catchAll, - maxParams: 1, - handlers: handlers, - priority: 1, - } - n.children = []*node{child} - - return - } - } - - // insert remaining path part and handle to the leaf - n.path = path[offset:] - n.handlers = handlers -} - -// Returns the handle registered with the given path (key). The values of -// wildcards are saved to a map. -// If no handle can be found, a TSR (trailing slash redirect) recommendation is -// made if a handle exists with an extra (without the) trailing slash for the -// given path. -func (n *node) getValue(path string, po Params, unescape bool) (handlers HandlersChain, p Params, tsr bool) { - p = po -walk: // Outer loop for walking the tree - for { - if len(path) > len(n.path) { - if path[:len(n.path)] == n.path { - path = path[len(n.path):] - // If this node does not have a wildcard (param or catchAll) - // child, we can just look up the next child node and continue - // to walk down the tree - if !n.wildChild { - c := path[0] - for i := 0; i < len(n.indices); i++ { - if c == n.indices[i] { - n = n.children[i] - continue walk - } - } - - // Nothing found. - // We can recommend to redirect to the same URL without a - // trailing slash if a leaf exists for that path. - tsr = (path == "/" && n.handlers != nil) - return - } - - // handle wildcard child - n = n.children[0] - switch n.nType { - case param: - // find param end (either '/' or path end) - end := 0 - for end < len(path) && path[end] != '/' { - end++ - } - - // save param value - if cap(p) < int(n.maxParams) { - p = make(Params, 0, n.maxParams) - } - i := len(p) - p = p[:i+1] // expand slice within preallocated capacity - p[i].Key = n.path[1:] - val := path[:end] - if unescape { - var err error - if p[i].Value, err = url.QueryUnescape(val); err != nil { - p[i].Value = val // fallback, in case of error - } - } else { - p[i].Value = val - } - - // we need to go deeper! - if end < len(path) { - if len(n.children) > 0 { - path = path[end:] - n = n.children[0] - continue walk - } - - // ... but we can't - tsr = (len(path) == end+1) - return - } - - if handlers = n.handlers; handlers != nil { - return - } - if len(n.children) == 1 { - // No handle found. Check if a handle for this path + a - // trailing slash exists for TSR recommendation - n = n.children[0] - tsr = (n.path == "/" && n.handlers != nil) - } - - return - - case catchAll: - // save param value - if cap(p) < int(n.maxParams) { - p = make(Params, 0, n.maxParams) - } - i := len(p) - p = p[:i+1] // expand slice within preallocated capacity - p[i].Key = n.path[2:] - if unescape { - var err error - if p[i].Value, err = url.QueryUnescape(path); err != nil { - p[i].Value = path // fallback, in case of error - } - } else { - p[i].Value = path - } - - handlers = n.handlers - return - - default: - panic("invalid node type") - } - } - } else if path == n.path { - // We should have reached the node containing the handle. - // Check if this node has a handle registered. - if handlers = n.handlers; handlers != nil { - return - } - - if path == "/" && n.wildChild && n.nType != root { - tsr = true - return - } - - // No handle found. Check if a handle for this path + a - // trailing slash exists for trailing slash recommendation - for i := 0; i < len(n.indices); i++ { - if n.indices[i] == '/' { - n = n.children[i] - tsr = (len(n.path) == 1 && n.handlers != nil) || - (n.nType == catchAll && n.children[0].handlers != nil) - return - } - } - - return - } - - // Nothing found. We can recommend to redirect to the same URL with an - // extra trailing slash if a leaf exists for that path - tsr = (path == "/") || - (len(n.path) == len(path)+1 && n.path[len(path)] == '/' && - path == n.path[:len(n.path)-1] && n.handlers != nil) - return - } -} - -// Makes a case-insensitive lookup of the given path and tries to find a handler. -// It can optionally also fix trailing slashes. -// It returns the case-corrected path and a bool indicating whether the lookup -// was successful. -func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) (ciPath []byte, found bool) { - ciPath = make([]byte, 0, len(path)+1) // preallocate enough memory - - // Outer loop for walking the tree - for len(path) >= len(n.path) && strings.ToLower(path[:len(n.path)]) == strings.ToLower(n.path) { - path = path[len(n.path):] - ciPath = append(ciPath, n.path...) - - if len(path) > 0 { - // If this node does not have a wildcard (param or catchAll) child, - // we can just look up the next child node and continue to walk down - // the tree - if !n.wildChild { - r := unicode.ToLower(rune(path[0])) - for i, index := range n.indices { - // must use recursive approach since both index and - // ToLower(index) could exist. We must check both. - if r == unicode.ToLower(index) { - out, found := n.children[i].findCaseInsensitivePath(path, fixTrailingSlash) - if found { - return append(ciPath, out...), true - } - } - } - - // Nothing found. We can recommend to redirect to the same URL - // without a trailing slash if a leaf exists for that path - found = (fixTrailingSlash && path == "/" && n.handlers != nil) - return - } - - n = n.children[0] - switch n.nType { - case param: - // find param end (either '/' or path end) - k := 0 - for k < len(path) && path[k] != '/' { - k++ - } - - // add param value to case insensitive path - ciPath = append(ciPath, path[:k]...) - - // we need to go deeper! - if k < len(path) { - if len(n.children) > 0 { - path = path[k:] - n = n.children[0] - continue - } - - // ... but we can't - if fixTrailingSlash && len(path) == k+1 { - return ciPath, true - } - return - } - - if n.handlers != nil { - return ciPath, true - } else if fixTrailingSlash && len(n.children) == 1 { - // No handle found. Check if a handle for this path + a - // trailing slash exists - n = n.children[0] - if n.path == "/" && n.handlers != nil { - return append(ciPath, '/'), true - } - } - return - - case catchAll: - return append(ciPath, path...), true - - default: - panic("invalid node type") - } - } else { - // We should have reached the node containing the handle. - // Check if this node has a handle registered. - if n.handlers != nil { - return ciPath, true - } - - // No handle found. - // Try to fix the path by adding a trailing slash - if fixTrailingSlash { - for i := 0; i < len(n.indices); i++ { - if n.indices[i] == '/' { - n = n.children[i] - if (len(n.path) == 1 && n.handlers != nil) || - (n.nType == catchAll && n.children[0].handlers != nil) { - return append(ciPath, '/'), true - } - return - } - } - } - return - } - } - - // Nothing found. - // Try to fix the path by adding / removing a trailing slash - if fixTrailingSlash { - if path == "/" { - return ciPath, true - } - if len(path)+1 == len(n.path) && n.path[len(path)] == '/' && - strings.ToLower(path) == strings.ToLower(n.path[:len(path)]) && - n.handlers != nil { - return append(ciPath, n.path...), true - } - } - return -} diff --git a/vendor/github.com/gin-gonic/gin/utils.go b/vendor/github.com/gin-gonic/gin/utils.go deleted file mode 100644 index 18064fb53..000000000 --- a/vendor/github.com/gin-gonic/gin/utils.go +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "encoding/xml" - "net/http" - "os" - "path" - "reflect" - "runtime" - "strings" -) - -const BindKey = "_gin-gonic/gin/bindkey" - -func Bind(val interface{}) HandlerFunc { - value := reflect.ValueOf(val) - if value.Kind() == reflect.Ptr { - panic(`Bind struct can not be a pointer. Example: - Use: gin.Bind(Struct{}) instead of gin.Bind(&Struct{}) -`) - } - typ := value.Type() - - return func(c *Context) { - obj := reflect.New(typ).Interface() - if c.Bind(obj) == nil { - c.Set(BindKey, obj) - } - } -} - -func WrapF(f http.HandlerFunc) HandlerFunc { - return func(c *Context) { - f(c.Writer, c.Request) - } -} - -func WrapH(h http.Handler) HandlerFunc { - return func(c *Context) { - h.ServeHTTP(c.Writer, c.Request) - } -} - -type H map[string]interface{} - -// MarshalXML allows type H to be used with xml.Marshal -func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error { - start.Name = xml.Name{ - Space: "", - Local: "map", - } - if err := e.EncodeToken(start); err != nil { - return err - } - for key, value := range h { - elem := xml.StartElement{ - Name: xml.Name{Space: "", Local: key}, - Attr: []xml.Attr{}, - } - if err := e.EncodeElement(value, elem); err != nil { - return err - } - } - if err := e.EncodeToken(xml.EndElement{Name: start.Name}); err != nil { - return err - } - return nil -} - -func assert1(guard bool, text string) { - if !guard { - panic(text) - } -} - -func filterFlags(content string) string { - for i, char := range content { - if char == ' ' || char == ';' { - return content[:i] - } - } - return content -} - -func chooseData(custom, wildcard interface{}) interface{} { - if custom == nil { - if wildcard == nil { - panic("negotiation config is invalid") - } - return wildcard - } - return custom -} - -func parseAccept(acceptHeader string) []string { - parts := strings.Split(acceptHeader, ",") - out := make([]string, 0, len(parts)) - for _, part := range parts { - index := strings.IndexByte(part, ';') - if index >= 0 { - part = part[0:index] - } - part = strings.TrimSpace(part) - if len(part) > 0 { - out = append(out, part) - } - } - return out -} - -func lastChar(str string) uint8 { - size := len(str) - if size == 0 { - panic("The length of the string can't be 0") - } - return str[size-1] -} - -func nameOfFunction(f interface{}) string { - return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name() -} - -func joinPaths(absolutePath, relativePath string) string { - if len(relativePath) == 0 { - return absolutePath - } - - finalPath := path.Join(absolutePath, relativePath) - appendSlash := lastChar(relativePath) == '/' && lastChar(finalPath) != '/' - if appendSlash { - return finalPath + "/" - } - return finalPath -} - -func resolveAddress(addr []string) string { - switch len(addr) { - case 0: - if port := os.Getenv("PORT"); len(port) > 0 { - debugPrint("Environment variable PORT=\"%s\"", port) - return ":" + port - } - debugPrint("Environment variable PORT is undefined. Using port :8080 by default") - return ":8080" - case 1: - return addr[0] - default: - panic("too much parameters") - } -} diff --git a/vendor/github.com/gogo/protobuf/gogoproto/Makefile b/vendor/github.com/gogo/protobuf/gogoproto/Makefile new file mode 100644 index 000000000..0b4659b73 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/gogoproto/Makefile @@ -0,0 +1,37 @@ +# Protocol Buffers for Go with Gadgets +# +# Copyright (c) 2013, The GoGo Authors. All rights reserved. +# http://github.com/gogo/protobuf +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +regenerate: + go install github.com/gogo/protobuf/protoc-gen-gogo + protoc --gogo_out=Mgoogle/protobuf/descriptor.proto=github.com/gogo/protobuf/protoc-gen-gogo/descriptor:../../../../ --proto_path=../../../../:../protobuf/:. *.proto + +restore: + cp gogo.pb.golden gogo.pb.go + +preserve: + cp gogo.pb.go gogo.pb.golden diff --git a/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.go b/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.go index 5765acb15..97843b244 100644 --- a/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.go +++ b/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.go @@ -1,20 +1,12 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: gogo.proto -/* -Package gogoproto is a generated protocol buffer package. - -It is generated from these files: - gogo.proto - -It has these top-level messages: -*/ -package gogoproto +package gogoproto // import "github.com/gogo/protobuf/gogoproto" import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" -import google_protobuf "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" +import descriptor "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal @@ -28,7 +20,7 @@ var _ = math.Inf const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package var E_GoprotoEnumPrefix = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.EnumOptions)(nil), + ExtendedType: (*descriptor.EnumOptions)(nil), ExtensionType: (*bool)(nil), Field: 62001, Name: "gogoproto.goproto_enum_prefix", @@ -37,7 +29,7 @@ var E_GoprotoEnumPrefix = &proto.ExtensionDesc{ } var E_GoprotoEnumStringer = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.EnumOptions)(nil), + ExtendedType: (*descriptor.EnumOptions)(nil), ExtensionType: (*bool)(nil), Field: 62021, Name: "gogoproto.goproto_enum_stringer", @@ -46,7 +38,7 @@ var E_GoprotoEnumStringer = &proto.ExtensionDesc{ } var E_EnumStringer = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.EnumOptions)(nil), + ExtendedType: (*descriptor.EnumOptions)(nil), ExtensionType: (*bool)(nil), Field: 62022, Name: "gogoproto.enum_stringer", @@ -55,7 +47,7 @@ var E_EnumStringer = &proto.ExtensionDesc{ } var E_EnumCustomname = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.EnumOptions)(nil), + ExtendedType: (*descriptor.EnumOptions)(nil), ExtensionType: (*string)(nil), Field: 62023, Name: "gogoproto.enum_customname", @@ -64,7 +56,7 @@ var E_EnumCustomname = &proto.ExtensionDesc{ } var E_Enumdecl = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.EnumOptions)(nil), + ExtendedType: (*descriptor.EnumOptions)(nil), ExtensionType: (*bool)(nil), Field: 62024, Name: "gogoproto.enumdecl", @@ -73,7 +65,7 @@ var E_Enumdecl = &proto.ExtensionDesc{ } var E_EnumvalueCustomname = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.EnumValueOptions)(nil), + ExtendedType: (*descriptor.EnumValueOptions)(nil), ExtensionType: (*string)(nil), Field: 66001, Name: "gogoproto.enumvalue_customname", @@ -82,7 +74,7 @@ var E_EnumvalueCustomname = &proto.ExtensionDesc{ } var E_GoprotoGettersAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63001, Name: "gogoproto.goproto_getters_all", @@ -91,7 +83,7 @@ var E_GoprotoGettersAll = &proto.ExtensionDesc{ } var E_GoprotoEnumPrefixAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63002, Name: "gogoproto.goproto_enum_prefix_all", @@ -100,7 +92,7 @@ var E_GoprotoEnumPrefixAll = &proto.ExtensionDesc{ } var E_GoprotoStringerAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63003, Name: "gogoproto.goproto_stringer_all", @@ -109,7 +101,7 @@ var E_GoprotoStringerAll = &proto.ExtensionDesc{ } var E_VerboseEqualAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63004, Name: "gogoproto.verbose_equal_all", @@ -118,7 +110,7 @@ var E_VerboseEqualAll = &proto.ExtensionDesc{ } var E_FaceAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63005, Name: "gogoproto.face_all", @@ -127,7 +119,7 @@ var E_FaceAll = &proto.ExtensionDesc{ } var E_GostringAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63006, Name: "gogoproto.gostring_all", @@ -136,7 +128,7 @@ var E_GostringAll = &proto.ExtensionDesc{ } var E_PopulateAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63007, Name: "gogoproto.populate_all", @@ -145,7 +137,7 @@ var E_PopulateAll = &proto.ExtensionDesc{ } var E_StringerAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63008, Name: "gogoproto.stringer_all", @@ -154,7 +146,7 @@ var E_StringerAll = &proto.ExtensionDesc{ } var E_OnlyoneAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63009, Name: "gogoproto.onlyone_all", @@ -163,7 +155,7 @@ var E_OnlyoneAll = &proto.ExtensionDesc{ } var E_EqualAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63013, Name: "gogoproto.equal_all", @@ -172,7 +164,7 @@ var E_EqualAll = &proto.ExtensionDesc{ } var E_DescriptionAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63014, Name: "gogoproto.description_all", @@ -181,7 +173,7 @@ var E_DescriptionAll = &proto.ExtensionDesc{ } var E_TestgenAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63015, Name: "gogoproto.testgen_all", @@ -190,7 +182,7 @@ var E_TestgenAll = &proto.ExtensionDesc{ } var E_BenchgenAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63016, Name: "gogoproto.benchgen_all", @@ -199,7 +191,7 @@ var E_BenchgenAll = &proto.ExtensionDesc{ } var E_MarshalerAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63017, Name: "gogoproto.marshaler_all", @@ -208,7 +200,7 @@ var E_MarshalerAll = &proto.ExtensionDesc{ } var E_UnmarshalerAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63018, Name: "gogoproto.unmarshaler_all", @@ -217,7 +209,7 @@ var E_UnmarshalerAll = &proto.ExtensionDesc{ } var E_StableMarshalerAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63019, Name: "gogoproto.stable_marshaler_all", @@ -226,7 +218,7 @@ var E_StableMarshalerAll = &proto.ExtensionDesc{ } var E_SizerAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63020, Name: "gogoproto.sizer_all", @@ -235,7 +227,7 @@ var E_SizerAll = &proto.ExtensionDesc{ } var E_GoprotoEnumStringerAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63021, Name: "gogoproto.goproto_enum_stringer_all", @@ -244,7 +236,7 @@ var E_GoprotoEnumStringerAll = &proto.ExtensionDesc{ } var E_EnumStringerAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63022, Name: "gogoproto.enum_stringer_all", @@ -253,7 +245,7 @@ var E_EnumStringerAll = &proto.ExtensionDesc{ } var E_UnsafeMarshalerAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63023, Name: "gogoproto.unsafe_marshaler_all", @@ -262,7 +254,7 @@ var E_UnsafeMarshalerAll = &proto.ExtensionDesc{ } var E_UnsafeUnmarshalerAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63024, Name: "gogoproto.unsafe_unmarshaler_all", @@ -271,7 +263,7 @@ var E_UnsafeUnmarshalerAll = &proto.ExtensionDesc{ } var E_GoprotoExtensionsMapAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63025, Name: "gogoproto.goproto_extensions_map_all", @@ -280,7 +272,7 @@ var E_GoprotoExtensionsMapAll = &proto.ExtensionDesc{ } var E_GoprotoUnrecognizedAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63026, Name: "gogoproto.goproto_unrecognized_all", @@ -289,7 +281,7 @@ var E_GoprotoUnrecognizedAll = &proto.ExtensionDesc{ } var E_GogoprotoImport = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63027, Name: "gogoproto.gogoproto_import", @@ -298,7 +290,7 @@ var E_GogoprotoImport = &proto.ExtensionDesc{ } var E_ProtosizerAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63028, Name: "gogoproto.protosizer_all", @@ -307,7 +299,7 @@ var E_ProtosizerAll = &proto.ExtensionDesc{ } var E_CompareAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63029, Name: "gogoproto.compare_all", @@ -316,7 +308,7 @@ var E_CompareAll = &proto.ExtensionDesc{ } var E_TypedeclAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63030, Name: "gogoproto.typedecl_all", @@ -325,7 +317,7 @@ var E_TypedeclAll = &proto.ExtensionDesc{ } var E_EnumdeclAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63031, Name: "gogoproto.enumdecl_all", @@ -334,7 +326,7 @@ var E_EnumdeclAll = &proto.ExtensionDesc{ } var E_GoprotoRegistration = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), + ExtendedType: (*descriptor.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63032, Name: "gogoproto.goproto_registration", @@ -342,8 +334,17 @@ var E_GoprotoRegistration = &proto.ExtensionDesc{ Filename: "gogo.proto", } +var E_MessagenameAll = &proto.ExtensionDesc{ + ExtendedType: (*descriptor.FileOptions)(nil), + ExtensionType: (*bool)(nil), + Field: 63033, + Name: "gogoproto.messagename_all", + Tag: "varint,63033,opt,name=messagename_all,json=messagenameAll", + Filename: "gogo.proto", +} + var E_GoprotoGetters = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64001, Name: "gogoproto.goproto_getters", @@ -352,7 +353,7 @@ var E_GoprotoGetters = &proto.ExtensionDesc{ } var E_GoprotoStringer = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64003, Name: "gogoproto.goproto_stringer", @@ -361,7 +362,7 @@ var E_GoprotoStringer = &proto.ExtensionDesc{ } var E_VerboseEqual = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64004, Name: "gogoproto.verbose_equal", @@ -370,7 +371,7 @@ var E_VerboseEqual = &proto.ExtensionDesc{ } var E_Face = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64005, Name: "gogoproto.face", @@ -379,7 +380,7 @@ var E_Face = &proto.ExtensionDesc{ } var E_Gostring = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64006, Name: "gogoproto.gostring", @@ -388,7 +389,7 @@ var E_Gostring = &proto.ExtensionDesc{ } var E_Populate = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64007, Name: "gogoproto.populate", @@ -397,7 +398,7 @@ var E_Populate = &proto.ExtensionDesc{ } var E_Stringer = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 67008, Name: "gogoproto.stringer", @@ -406,7 +407,7 @@ var E_Stringer = &proto.ExtensionDesc{ } var E_Onlyone = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64009, Name: "gogoproto.onlyone", @@ -415,7 +416,7 @@ var E_Onlyone = &proto.ExtensionDesc{ } var E_Equal = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64013, Name: "gogoproto.equal", @@ -424,7 +425,7 @@ var E_Equal = &proto.ExtensionDesc{ } var E_Description = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64014, Name: "gogoproto.description", @@ -433,7 +434,7 @@ var E_Description = &proto.ExtensionDesc{ } var E_Testgen = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64015, Name: "gogoproto.testgen", @@ -442,7 +443,7 @@ var E_Testgen = &proto.ExtensionDesc{ } var E_Benchgen = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64016, Name: "gogoproto.benchgen", @@ -451,7 +452,7 @@ var E_Benchgen = &proto.ExtensionDesc{ } var E_Marshaler = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64017, Name: "gogoproto.marshaler", @@ -460,7 +461,7 @@ var E_Marshaler = &proto.ExtensionDesc{ } var E_Unmarshaler = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64018, Name: "gogoproto.unmarshaler", @@ -469,7 +470,7 @@ var E_Unmarshaler = &proto.ExtensionDesc{ } var E_StableMarshaler = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64019, Name: "gogoproto.stable_marshaler", @@ -478,7 +479,7 @@ var E_StableMarshaler = &proto.ExtensionDesc{ } var E_Sizer = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64020, Name: "gogoproto.sizer", @@ -487,7 +488,7 @@ var E_Sizer = &proto.ExtensionDesc{ } var E_UnsafeMarshaler = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64023, Name: "gogoproto.unsafe_marshaler", @@ -496,7 +497,7 @@ var E_UnsafeMarshaler = &proto.ExtensionDesc{ } var E_UnsafeUnmarshaler = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64024, Name: "gogoproto.unsafe_unmarshaler", @@ -505,7 +506,7 @@ var E_UnsafeUnmarshaler = &proto.ExtensionDesc{ } var E_GoprotoExtensionsMap = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64025, Name: "gogoproto.goproto_extensions_map", @@ -514,7 +515,7 @@ var E_GoprotoExtensionsMap = &proto.ExtensionDesc{ } var E_GoprotoUnrecognized = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64026, Name: "gogoproto.goproto_unrecognized", @@ -523,7 +524,7 @@ var E_GoprotoUnrecognized = &proto.ExtensionDesc{ } var E_Protosizer = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64028, Name: "gogoproto.protosizer", @@ -532,7 +533,7 @@ var E_Protosizer = &proto.ExtensionDesc{ } var E_Compare = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64029, Name: "gogoproto.compare", @@ -541,7 +542,7 @@ var E_Compare = &proto.ExtensionDesc{ } var E_Typedecl = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), + ExtendedType: (*descriptor.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64030, Name: "gogoproto.typedecl", @@ -549,8 +550,17 @@ var E_Typedecl = &proto.ExtensionDesc{ Filename: "gogo.proto", } +var E_Messagename = &proto.ExtensionDesc{ + ExtendedType: (*descriptor.MessageOptions)(nil), + ExtensionType: (*bool)(nil), + Field: 64033, + Name: "gogoproto.messagename", + Tag: "varint,64033,opt,name=messagename", + Filename: "gogo.proto", +} + var E_Nullable = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), + ExtendedType: (*descriptor.FieldOptions)(nil), ExtensionType: (*bool)(nil), Field: 65001, Name: "gogoproto.nullable", @@ -559,7 +569,7 @@ var E_Nullable = &proto.ExtensionDesc{ } var E_Embed = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), + ExtendedType: (*descriptor.FieldOptions)(nil), ExtensionType: (*bool)(nil), Field: 65002, Name: "gogoproto.embed", @@ -568,7 +578,7 @@ var E_Embed = &proto.ExtensionDesc{ } var E_Customtype = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), + ExtendedType: (*descriptor.FieldOptions)(nil), ExtensionType: (*string)(nil), Field: 65003, Name: "gogoproto.customtype", @@ -577,7 +587,7 @@ var E_Customtype = &proto.ExtensionDesc{ } var E_Customname = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), + ExtendedType: (*descriptor.FieldOptions)(nil), ExtensionType: (*string)(nil), Field: 65004, Name: "gogoproto.customname", @@ -586,7 +596,7 @@ var E_Customname = &proto.ExtensionDesc{ } var E_Jsontag = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), + ExtendedType: (*descriptor.FieldOptions)(nil), ExtensionType: (*string)(nil), Field: 65005, Name: "gogoproto.jsontag", @@ -595,7 +605,7 @@ var E_Jsontag = &proto.ExtensionDesc{ } var E_Moretags = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), + ExtendedType: (*descriptor.FieldOptions)(nil), ExtensionType: (*string)(nil), Field: 65006, Name: "gogoproto.moretags", @@ -604,7 +614,7 @@ var E_Moretags = &proto.ExtensionDesc{ } var E_Casttype = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), + ExtendedType: (*descriptor.FieldOptions)(nil), ExtensionType: (*string)(nil), Field: 65007, Name: "gogoproto.casttype", @@ -613,7 +623,7 @@ var E_Casttype = &proto.ExtensionDesc{ } var E_Castkey = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), + ExtendedType: (*descriptor.FieldOptions)(nil), ExtensionType: (*string)(nil), Field: 65008, Name: "gogoproto.castkey", @@ -622,7 +632,7 @@ var E_Castkey = &proto.ExtensionDesc{ } var E_Castvalue = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), + ExtendedType: (*descriptor.FieldOptions)(nil), ExtensionType: (*string)(nil), Field: 65009, Name: "gogoproto.castvalue", @@ -631,7 +641,7 @@ var E_Castvalue = &proto.ExtensionDesc{ } var E_Stdtime = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), + ExtendedType: (*descriptor.FieldOptions)(nil), ExtensionType: (*bool)(nil), Field: 65010, Name: "gogoproto.stdtime", @@ -640,7 +650,7 @@ var E_Stdtime = &proto.ExtensionDesc{ } var E_Stdduration = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), + ExtendedType: (*descriptor.FieldOptions)(nil), ExtensionType: (*bool)(nil), Field: 65011, Name: "gogoproto.stdduration", @@ -684,6 +694,7 @@ func init() { proto.RegisterExtension(E_TypedeclAll) proto.RegisterExtension(E_EnumdeclAll) proto.RegisterExtension(E_GoprotoRegistration) + proto.RegisterExtension(E_MessagenameAll) proto.RegisterExtension(E_GoprotoGetters) proto.RegisterExtension(E_GoprotoStringer) proto.RegisterExtension(E_VerboseEqual) @@ -707,6 +718,7 @@ func init() { proto.RegisterExtension(E_Protosizer) proto.RegisterExtension(E_Compare) proto.RegisterExtension(E_Typedecl) + proto.RegisterExtension(E_Messagename) proto.RegisterExtension(E_Nullable) proto.RegisterExtension(E_Embed) proto.RegisterExtension(E_Customtype) @@ -720,85 +732,86 @@ func init() { proto.RegisterExtension(E_Stdduration) } -func init() { proto.RegisterFile("gogo.proto", fileDescriptorGogo) } - -var fileDescriptorGogo = []byte{ - // 1220 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x98, 0x4b, 0x6f, 0x1c, 0x45, - 0x10, 0x80, 0x85, 0x48, 0x14, 0x6f, 0xd9, 0x8e, 0xf1, 0xda, 0x98, 0x10, 0x81, 0x08, 0x9c, 0x38, - 0xd9, 0xa7, 0x08, 0xa5, 0xad, 0xc8, 0x72, 0x2c, 0xc7, 0x4a, 0x84, 0xc1, 0x98, 0x38, 0xbc, 0x0e, - 0xab, 0xd9, 0xdd, 0xf6, 0x78, 0x60, 0x66, 0x7a, 0x98, 0xe9, 0x89, 0xe2, 0xdc, 0x50, 0x78, 0x08, - 0x21, 0xde, 0x48, 0x90, 0x90, 0x04, 0x38, 0xf0, 0x7e, 0x86, 0xf7, 0x91, 0x0b, 0x8f, 0x2b, 0xff, - 0x81, 0x0b, 0x60, 0xde, 0xbe, 0xf9, 0x82, 0x6a, 0xb6, 0x6a, 0xb6, 0x67, 0xbd, 0x52, 0xf7, 0xde, - 0xc6, 0xeb, 0xfe, 0xbe, 0xad, 0xa9, 0x9a, 0xae, 0xea, 0x59, 0x00, 0x5f, 0xf9, 0x6a, 0x3a, 0x49, - 0x95, 0x56, 0xf5, 0x1a, 0x5e, 0x17, 0x97, 0x07, 0x0f, 0xf9, 0x4a, 0xf9, 0xa1, 0x9c, 0x29, 0xfe, - 0x6a, 0xe6, 0xeb, 0x33, 0x6d, 0x99, 0xb5, 0xd2, 0x20, 0xd1, 0x2a, 0xed, 0x2c, 0x16, 0x77, 0xc1, - 0x04, 0x2d, 0x6e, 0xc8, 0x38, 0x8f, 0x1a, 0x49, 0x2a, 0xd7, 0x83, 0xb3, 0xf5, 0x9b, 0xa6, 0x3b, - 0xe4, 0x34, 0x93, 0xd3, 0x8b, 0x71, 0x1e, 0xdd, 0x9d, 0xe8, 0x40, 0xc5, 0xd9, 0x81, 0xab, 0xbf, - 0x5c, 0x7b, 0xe8, 0x9a, 0xdb, 0x87, 0x56, 0xc7, 0x09, 0xc5, 0xff, 0xad, 0x14, 0xa0, 0x58, 0x85, - 0xeb, 0x2b, 0xbe, 0x4c, 0xa7, 0x41, 0xec, 0xcb, 0xd4, 0x62, 0xfc, 0x9e, 0x8c, 0x13, 0x86, 0xf1, - 0x5e, 0x42, 0xc5, 0x02, 0x8c, 0x0e, 0xe2, 0xfa, 0x81, 0x5c, 0x23, 0xd2, 0x94, 0x2c, 0xc1, 0x58, - 0x21, 0x69, 0xe5, 0x99, 0x56, 0x51, 0xec, 0x45, 0xd2, 0xa2, 0xf9, 0xb1, 0xd0, 0xd4, 0x56, 0xf7, - 0x23, 0xb6, 0x50, 0x52, 0x42, 0xc0, 0x10, 0x7e, 0xd2, 0x96, 0xad, 0xd0, 0x62, 0xf8, 0x89, 0x02, - 0x29, 0xd7, 0x8b, 0xd3, 0x30, 0x89, 0xd7, 0x67, 0xbc, 0x30, 0x97, 0x66, 0x24, 0xb7, 0xf6, 0xf5, - 0x9c, 0xc6, 0x65, 0x2c, 0xfb, 0xf9, 0xfc, 0x9e, 0x22, 0x9c, 0x89, 0x52, 0x60, 0xc4, 0x64, 0x54, - 0xd1, 0x97, 0x5a, 0xcb, 0x34, 0x6b, 0x78, 0x61, 0xbf, 0xf0, 0x8e, 0x07, 0x61, 0x69, 0xbc, 0xb0, - 0x55, 0xad, 0xe2, 0x52, 0x87, 0x9c, 0x0f, 0x43, 0xb1, 0x06, 0x37, 0xf4, 0x79, 0x2a, 0x1c, 0x9c, - 0x17, 0xc9, 0x39, 0xb9, 0xeb, 0xc9, 0x40, 0xed, 0x0a, 0xf0, 0xe7, 0x65, 0x2d, 0x1d, 0x9c, 0xaf, - 0x93, 0xb3, 0x4e, 0x2c, 0x97, 0x14, 0x8d, 0x27, 0x61, 0xfc, 0x8c, 0x4c, 0x9b, 0x2a, 0x93, 0x0d, - 0xf9, 0x68, 0xee, 0x85, 0x0e, 0xba, 0x4b, 0xa4, 0x1b, 0x23, 0x70, 0x11, 0x39, 0x74, 0x1d, 0x81, - 0xa1, 0x75, 0xaf, 0x25, 0x1d, 0x14, 0x97, 0x49, 0xb1, 0x0f, 0xd7, 0x23, 0x3a, 0x0f, 0x23, 0xbe, - 0xea, 0xdc, 0x92, 0x03, 0x7e, 0x85, 0xf0, 0x61, 0x66, 0x48, 0x91, 0xa8, 0x24, 0x0f, 0x3d, 0xed, - 0x12, 0xc1, 0x1b, 0xac, 0x60, 0x86, 0x14, 0x03, 0xa4, 0xf5, 0x4d, 0x56, 0x64, 0x46, 0x3e, 0xe7, - 0x60, 0x58, 0xc5, 0xe1, 0xa6, 0x8a, 0x5d, 0x82, 0x78, 0x8b, 0x0c, 0x40, 0x08, 0x0a, 0x66, 0xa1, - 0xe6, 0x5a, 0x88, 0xb7, 0xb7, 0x78, 0x7b, 0x70, 0x05, 0x96, 0x60, 0x8c, 0x1b, 0x54, 0xa0, 0x62, - 0x07, 0xc5, 0x3b, 0xa4, 0xd8, 0x6f, 0x60, 0x74, 0x1b, 0x5a, 0x66, 0xda, 0x97, 0x2e, 0x92, 0x77, - 0xf9, 0x36, 0x08, 0xa1, 0x54, 0x36, 0x65, 0xdc, 0xda, 0x70, 0x33, 0xbc, 0xc7, 0xa9, 0x64, 0x06, - 0x15, 0x0b, 0x30, 0x1a, 0x79, 0x69, 0xb6, 0xe1, 0x85, 0x4e, 0xe5, 0x78, 0x9f, 0x1c, 0x23, 0x25, - 0x44, 0x19, 0xc9, 0xe3, 0x41, 0x34, 0x1f, 0x70, 0x46, 0x0c, 0x8c, 0xb6, 0x5e, 0xa6, 0xbd, 0x66, - 0x28, 0x1b, 0x83, 0xd8, 0x3e, 0xe4, 0xad, 0xd7, 0x61, 0x97, 0x4d, 0xe3, 0x2c, 0xd4, 0xb2, 0xe0, - 0x9c, 0x93, 0xe6, 0x23, 0xae, 0x74, 0x01, 0x20, 0xfc, 0x00, 0xdc, 0xd8, 0x77, 0x4c, 0x38, 0xc8, - 0x3e, 0x26, 0xd9, 0x54, 0x9f, 0x51, 0x41, 0x2d, 0x61, 0x50, 0xe5, 0x27, 0xdc, 0x12, 0x64, 0x8f, - 0x6b, 0x05, 0x26, 0xf3, 0x38, 0xf3, 0xd6, 0x07, 0xcb, 0xda, 0xa7, 0x9c, 0xb5, 0x0e, 0x5b, 0xc9, - 0xda, 0x29, 0x98, 0x22, 0xe3, 0x60, 0x75, 0xfd, 0x8c, 0x1b, 0x6b, 0x87, 0x5e, 0xab, 0x56, 0xf7, - 0x21, 0x38, 0x58, 0xa6, 0xf3, 0xac, 0x96, 0x71, 0x86, 0x4c, 0x23, 0xf2, 0x12, 0x07, 0xf3, 0x55, - 0x32, 0x73, 0xc7, 0x5f, 0x2c, 0x05, 0xcb, 0x5e, 0x82, 0xf2, 0xfb, 0xe1, 0x00, 0xcb, 0xf3, 0x38, - 0x95, 0x2d, 0xe5, 0xc7, 0xc1, 0x39, 0xd9, 0x76, 0x50, 0x7f, 0xde, 0x53, 0xaa, 0x35, 0x03, 0x47, - 0xf3, 0x09, 0xb8, 0xae, 0x3c, 0xab, 0x34, 0x82, 0x28, 0x51, 0xa9, 0xb6, 0x18, 0xbf, 0xe0, 0x4a, - 0x95, 0xdc, 0x89, 0x02, 0x13, 0x8b, 0xb0, 0xbf, 0xf8, 0xd3, 0xf5, 0x91, 0xfc, 0x92, 0x44, 0xa3, - 0x5d, 0x8a, 0x1a, 0x47, 0x4b, 0x45, 0x89, 0x97, 0xba, 0xf4, 0xbf, 0xaf, 0xb8, 0x71, 0x10, 0x42, - 0x8d, 0x43, 0x6f, 0x26, 0x12, 0xa7, 0xbd, 0x83, 0xe1, 0x6b, 0x6e, 0x1c, 0xcc, 0x90, 0x82, 0x0f, - 0x0c, 0x0e, 0x8a, 0x6f, 0x58, 0xc1, 0x0c, 0x2a, 0xee, 0xe9, 0x0e, 0xda, 0x54, 0xfa, 0x41, 0xa6, - 0x53, 0x0f, 0x57, 0x5b, 0x54, 0xdf, 0x6e, 0x55, 0x0f, 0x61, 0xab, 0x06, 0x2a, 0x4e, 0xc2, 0x58, - 0xcf, 0x11, 0xa3, 0x7e, 0xcb, 0x2e, 0xdb, 0xb2, 0xcc, 0x32, 0xcf, 0x2f, 0x85, 0x8f, 0x6d, 0x53, - 0x33, 0xaa, 0x9e, 0x30, 0xc4, 0x9d, 0x58, 0xf7, 0xea, 0x39, 0xc0, 0x2e, 0x3b, 0xbf, 0x5d, 0x96, - 0xbe, 0x72, 0x0c, 0x10, 0xc7, 0x61, 0xb4, 0x72, 0x06, 0xb0, 0xab, 0x1e, 0x27, 0xd5, 0x88, 0x79, - 0x04, 0x10, 0x87, 0x61, 0x0f, 0xce, 0x73, 0x3b, 0xfe, 0x04, 0xe1, 0xc5, 0x72, 0x71, 0x14, 0x86, - 0x78, 0x8e, 0xdb, 0xd1, 0x27, 0x09, 0x2d, 0x11, 0xc4, 0x79, 0x86, 0xdb, 0xf1, 0xa7, 0x18, 0x67, - 0x04, 0x71, 0xf7, 0x14, 0x7e, 0xf7, 0xcc, 0x1e, 0xea, 0xc3, 0x9c, 0xbb, 0x59, 0xd8, 0x47, 0xc3, - 0xdb, 0x4e, 0x3f, 0x4d, 0x5f, 0xce, 0x84, 0xb8, 0x03, 0xf6, 0x3a, 0x26, 0xfc, 0x59, 0x42, 0x3b, - 0xeb, 0xc5, 0x02, 0x0c, 0x1b, 0x03, 0xdb, 0x8e, 0x3f, 0x47, 0xb8, 0x49, 0x61, 0xe8, 0x34, 0xb0, - 0xed, 0x82, 0xe7, 0x39, 0x74, 0x22, 0x30, 0x6d, 0x3c, 0xab, 0xed, 0xf4, 0x0b, 0x9c, 0x75, 0x46, - 0xc4, 0x1c, 0xd4, 0xca, 0xfe, 0x6b, 0xe7, 0x5f, 0x24, 0xbe, 0xcb, 0x60, 0x06, 0x8c, 0xfe, 0x6f, - 0x57, 0xbc, 0xc4, 0x19, 0x30, 0x28, 0xdc, 0x46, 0xbd, 0x33, 0xdd, 0x6e, 0x7a, 0x99, 0xb7, 0x51, - 0xcf, 0x48, 0xc7, 0x6a, 0x16, 0x6d, 0xd0, 0xae, 0x78, 0x85, 0xab, 0x59, 0xac, 0xc7, 0x30, 0x7a, - 0x87, 0xa4, 0xdd, 0xf1, 0x2a, 0x87, 0xd1, 0x33, 0x23, 0xc5, 0x0a, 0xd4, 0x77, 0x0f, 0x48, 0xbb, - 0xef, 0x35, 0xf2, 0x8d, 0xef, 0x9a, 0x8f, 0xe2, 0x3e, 0x98, 0xea, 0x3f, 0x1c, 0xed, 0xd6, 0x0b, - 0xdb, 0x3d, 0xaf, 0x33, 0xe6, 0x6c, 0x14, 0xa7, 0xba, 0x5d, 0xd6, 0x1c, 0x8c, 0x76, 0xed, 0xc5, - 0xed, 0x6a, 0xa3, 0x35, 0xe7, 0xa2, 0x98, 0x07, 0xe8, 0xce, 0x24, 0xbb, 0xeb, 0x12, 0xb9, 0x0c, - 0x08, 0xb7, 0x06, 0x8d, 0x24, 0x3b, 0x7f, 0x99, 0xb7, 0x06, 0x11, 0xb8, 0x35, 0x78, 0x1a, 0xd9, - 0xe9, 0x2b, 0xbc, 0x35, 0x18, 0x11, 0xb3, 0x30, 0x14, 0xe7, 0x61, 0x88, 0xcf, 0x56, 0xfd, 0xe6, - 0x3e, 0xe3, 0x46, 0x86, 0x6d, 0x86, 0x7f, 0xdd, 0x21, 0x98, 0x01, 0x71, 0x18, 0xf6, 0xca, 0xa8, - 0x29, 0xdb, 0x36, 0xf2, 0xb7, 0x1d, 0xee, 0x27, 0xb8, 0x5a, 0xcc, 0x01, 0x74, 0x5e, 0xa6, 0x31, - 0x0a, 0x1b, 0xfb, 0xfb, 0x4e, 0xe7, 0xbd, 0xde, 0x40, 0xba, 0x82, 0xe2, 0x6d, 0xdc, 0x22, 0xd8, - 0xaa, 0x0a, 0x8a, 0x17, 0xf0, 0x23, 0xb0, 0xef, 0xe1, 0x4c, 0xc5, 0xda, 0xf3, 0x6d, 0xf4, 0x1f, - 0x44, 0xf3, 0x7a, 0x4c, 0x58, 0xa4, 0x52, 0xa9, 0x3d, 0x3f, 0xb3, 0xb1, 0x7f, 0x12, 0x5b, 0x02, - 0x08, 0xb7, 0xbc, 0x4c, 0xbb, 0xdc, 0xf7, 0x5f, 0x0c, 0x33, 0x80, 0x41, 0xe3, 0xf5, 0x23, 0x72, - 0xd3, 0xc6, 0xfe, 0xcd, 0x41, 0xd3, 0x7a, 0x71, 0x14, 0x6a, 0x78, 0x59, 0xfc, 0x0e, 0x61, 0x83, - 0xff, 0x21, 0xb8, 0x4b, 0xe0, 0x37, 0x67, 0xba, 0xad, 0x03, 0x7b, 0xb2, 0xff, 0xa5, 0x4a, 0xf3, - 0x7a, 0x31, 0x0f, 0xc3, 0x99, 0x6e, 0xb7, 0x73, 0x3a, 0xd1, 0x58, 0xf0, 0xff, 0x76, 0xca, 0x97, - 0xdc, 0x92, 0x39, 0xb6, 0x08, 0x13, 0x2d, 0x15, 0xf5, 0x82, 0xc7, 0x60, 0x49, 0x2d, 0xa9, 0x95, - 0x62, 0x17, 0x3d, 0x78, 0x9b, 0x1f, 0xe8, 0x8d, 0xbc, 0x39, 0xdd, 0x52, 0xd1, 0x0c, 0x1e, 0x35, - 0xbb, 0xbf, 0xa0, 0x95, 0x07, 0xcf, 0xff, 0x03, 0x00, 0x00, 0xff, 0xff, 0xed, 0x5f, 0x6c, 0x20, - 0x74, 0x13, 0x00, 0x00, +func init() { proto.RegisterFile("gogo.proto", fileDescriptor_gogo_68790841c0f79064) } + +var fileDescriptor_gogo_68790841c0f79064 = []byte{ + // 1246 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x98, 0x49, 0x6f, 0x1c, 0x45, + 0x14, 0x80, 0x85, 0x70, 0x64, 0xcf, 0xf3, 0x86, 0xc7, 0xc6, 0x84, 0x08, 0x44, 0xe0, 0xc4, 0xc9, + 0x3e, 0x45, 0x28, 0x65, 0x45, 0x96, 0x63, 0x39, 0x56, 0x10, 0x06, 0x63, 0xe2, 0xb0, 0x1d, 0x46, + 0x3d, 0x33, 0xe5, 0x76, 0x43, 0x77, 0xd7, 0xd0, 0x5d, 0x1d, 0xc5, 0xb9, 0xa1, 0xb0, 0x08, 0x21, + 0x76, 0x24, 0x48, 0x48, 0x02, 0x39, 0xb0, 0xaf, 0x61, 0xe7, 0xc6, 0x85, 0xe5, 0xca, 0x7f, 0xe0, + 0x02, 0x98, 0xdd, 0x37, 0x5f, 0xa2, 0xd7, 0xfd, 0x5e, 0x4f, 0xcd, 0x78, 0xa4, 0xaa, 0xb9, 0xb5, + 0xed, 0xfa, 0x3e, 0x57, 0xbf, 0x57, 0xf5, 0xde, 0x9b, 0x01, 0xf0, 0x95, 0xaf, 0x66, 0x5a, 0x89, + 0xd2, 0xaa, 0x5a, 0xc1, 0xe7, 0xfc, 0xf1, 0xc0, 0x41, 0x5f, 0x29, 0x3f, 0x94, 0xb3, 0xf9, 0x4f, + 0xf5, 0x6c, 0x63, 0xb6, 0x29, 0xd3, 0x46, 0x12, 0xb4, 0xb4, 0x4a, 0x8a, 0xc5, 0xe2, 0x6e, 0x98, + 0xa4, 0xc5, 0x35, 0x19, 0x67, 0x51, 0xad, 0x95, 0xc8, 0x8d, 0xe0, 0x74, 0xf5, 0xa6, 0x99, 0x82, + 0x9c, 0x61, 0x72, 0x66, 0x29, 0xce, 0xa2, 0x7b, 0x5a, 0x3a, 0x50, 0x71, 0xba, 0xff, 0xca, 0xaf, + 0xd7, 0x1e, 0xbc, 0xe6, 0xf6, 0xa1, 0xb5, 0x09, 0x42, 0xf1, 0x6f, 0xab, 0x39, 0x28, 0xd6, 0xe0, + 0xfa, 0x0e, 0x5f, 0xaa, 0x93, 0x20, 0xf6, 0x65, 0x62, 0x31, 0xfe, 0x40, 0xc6, 0x49, 0xc3, 0x78, + 0x1f, 0xa1, 0x62, 0x11, 0x46, 0xfb, 0x71, 0xfd, 0x48, 0xae, 0x11, 0x69, 0x4a, 0x96, 0x61, 0x3c, + 0x97, 0x34, 0xb2, 0x54, 0xab, 0x28, 0xf6, 0x22, 0x69, 0xd1, 0xfc, 0x94, 0x6b, 0x2a, 0x6b, 0x63, + 0x88, 0x2d, 0x96, 0x94, 0x10, 0x30, 0x84, 0xbf, 0x69, 0xca, 0x46, 0x68, 0x31, 0xfc, 0x4c, 0x1b, + 0x29, 0xd7, 0x8b, 0x93, 0x30, 0x85, 0xcf, 0xa7, 0xbc, 0x30, 0x93, 0xe6, 0x4e, 0x6e, 0xed, 0xe9, + 0x39, 0x89, 0xcb, 0x58, 0xf6, 0xcb, 0xd9, 0x81, 0x7c, 0x3b, 0x93, 0xa5, 0xc0, 0xd8, 0x93, 0x91, + 0x45, 0x5f, 0x6a, 0x2d, 0x93, 0xb4, 0xe6, 0x85, 0xbd, 0xb6, 0x77, 0x2c, 0x08, 0x4b, 0xe3, 0xb9, + 0xed, 0xce, 0x2c, 0x2e, 0x17, 0xe4, 0x42, 0x18, 0x8a, 0x75, 0xb8, 0xa1, 0xc7, 0xa9, 0x70, 0x70, + 0x9e, 0x27, 0xe7, 0xd4, 0x9e, 0x93, 0x81, 0xda, 0x55, 0xe0, 0xdf, 0x97, 0xb9, 0x74, 0x70, 0xbe, + 0x41, 0xce, 0x2a, 0xb1, 0x9c, 0x52, 0x34, 0xde, 0x09, 0x13, 0xa7, 0x64, 0x52, 0x57, 0xa9, 0xac, + 0xc9, 0xc7, 0x32, 0x2f, 0x74, 0xd0, 0x5d, 0x20, 0xdd, 0x38, 0x81, 0x4b, 0xc8, 0xa1, 0xeb, 0x30, + 0x0c, 0x6d, 0x78, 0x0d, 0xe9, 0xa0, 0xb8, 0x48, 0x8a, 0x41, 0x5c, 0x8f, 0xe8, 0x02, 0x8c, 0xf8, + 0xaa, 0x78, 0x25, 0x07, 0xfc, 0x12, 0xe1, 0xc3, 0xcc, 0x90, 0xa2, 0xa5, 0x5a, 0x59, 0xe8, 0x69, + 0x97, 0x1d, 0xbc, 0xc9, 0x0a, 0x66, 0x48, 0xd1, 0x47, 0x58, 0xdf, 0x62, 0x45, 0x6a, 0xc4, 0x73, + 0x1e, 0x86, 0x55, 0x1c, 0x6e, 0xa9, 0xd8, 0x65, 0x13, 0x97, 0xc9, 0x00, 0x84, 0xa0, 0x60, 0x0e, + 0x2a, 0xae, 0x89, 0x78, 0x7b, 0x9b, 0xaf, 0x07, 0x67, 0x60, 0x19, 0xc6, 0xb9, 0x40, 0x05, 0x2a, + 0x76, 0x50, 0xbc, 0x43, 0x8a, 0x31, 0x03, 0xa3, 0xd7, 0xd0, 0x32, 0xd5, 0xbe, 0x74, 0x91, 0xbc, + 0xcb, 0xaf, 0x41, 0x08, 0x85, 0xb2, 0x2e, 0xe3, 0xc6, 0xa6, 0x9b, 0xe1, 0x3d, 0x0e, 0x25, 0x33, + 0xa8, 0x58, 0x84, 0xd1, 0xc8, 0x4b, 0xd2, 0x4d, 0x2f, 0x74, 0x4a, 0xc7, 0xfb, 0xe4, 0x18, 0x29, + 0x21, 0x8a, 0x48, 0x16, 0xf7, 0xa3, 0xf9, 0x80, 0x23, 0x62, 0x60, 0x74, 0xf5, 0x52, 0xed, 0xd5, + 0x43, 0x59, 0xeb, 0xc7, 0xf6, 0x21, 0x5f, 0xbd, 0x82, 0x5d, 0x31, 0x8d, 0x73, 0x50, 0x49, 0x83, + 0x33, 0x4e, 0x9a, 0x8f, 0x38, 0xd3, 0x39, 0x80, 0xf0, 0x83, 0x70, 0x63, 0xcf, 0x36, 0xe1, 0x20, + 0xfb, 0x98, 0x64, 0xd3, 0x3d, 0x5a, 0x05, 0x95, 0x84, 0x7e, 0x95, 0x9f, 0x70, 0x49, 0x90, 0x5d, + 0xae, 0x55, 0x98, 0xca, 0xe2, 0xd4, 0xdb, 0xe8, 0x2f, 0x6a, 0x9f, 0x72, 0xd4, 0x0a, 0xb6, 0x23, + 0x6a, 0x27, 0x60, 0x9a, 0x8c, 0xfd, 0xe5, 0xf5, 0x33, 0x2e, 0xac, 0x05, 0xbd, 0xde, 0x99, 0xdd, + 0x87, 0xe1, 0x40, 0x19, 0xce, 0xd3, 0x5a, 0xc6, 0x29, 0x32, 0xb5, 0xc8, 0x6b, 0x39, 0x98, 0xaf, + 0x90, 0x99, 0x2b, 0xfe, 0x52, 0x29, 0x58, 0xf1, 0x5a, 0x28, 0x7f, 0x00, 0xf6, 0xb3, 0x3c, 0x8b, + 0x13, 0xd9, 0x50, 0x7e, 0x1c, 0x9c, 0x91, 0x4d, 0x07, 0xf5, 0xe7, 0x5d, 0xa9, 0x5a, 0x37, 0x70, + 0x34, 0x1f, 0x87, 0xeb, 0xca, 0x59, 0xa5, 0x16, 0x44, 0x2d, 0x95, 0x68, 0x8b, 0xf1, 0x0b, 0xce, + 0x54, 0xc9, 0x1d, 0xcf, 0x31, 0xb1, 0x04, 0x63, 0xf9, 0x8f, 0xae, 0x47, 0xf2, 0x4b, 0x12, 0x8d, + 0xb6, 0x29, 0x2a, 0x1c, 0x0d, 0x15, 0xb5, 0xbc, 0xc4, 0xa5, 0xfe, 0x7d, 0xc5, 0x85, 0x83, 0x10, + 0x2a, 0x1c, 0x7a, 0xab, 0x25, 0xb1, 0xdb, 0x3b, 0x18, 0xbe, 0xe6, 0xc2, 0xc1, 0x0c, 0x29, 0x78, + 0x60, 0x70, 0x50, 0x7c, 0xc3, 0x0a, 0x66, 0x50, 0x71, 0x6f, 0xbb, 0xd1, 0x26, 0xd2, 0x0f, 0x52, + 0x9d, 0x78, 0xb8, 0xda, 0xa2, 0xfa, 0x76, 0xbb, 0x73, 0x08, 0x5b, 0x33, 0x50, 0xac, 0x44, 0x91, + 0x4c, 0x53, 0xcf, 0x97, 0x38, 0x71, 0x38, 0x6c, 0xec, 0x3b, 0xae, 0x44, 0x06, 0x56, 0xdc, 0xcf, + 0xf1, 0xae, 0x59, 0xa5, 0x7a, 0xcb, 0x1e, 0xd1, 0x4a, 0xc1, 0xb0, 0xeb, 0xf1, 0x1d, 0x72, 0x75, + 0x8e, 0x2a, 0xe2, 0x2e, 0x3c, 0x40, 0x9d, 0x03, 0x85, 0x5d, 0x76, 0x76, 0xa7, 0x3c, 0x43, 0x1d, + 0xf3, 0x84, 0x38, 0x06, 0xa3, 0x1d, 0xc3, 0x84, 0x5d, 0xf5, 0x04, 0xa9, 0x46, 0xcc, 0x59, 0x42, + 0x1c, 0x82, 0x01, 0x1c, 0x0c, 0xec, 0xf8, 0x93, 0x84, 0xe7, 0xcb, 0xc5, 0x11, 0x18, 0xe2, 0x81, + 0xc0, 0x8e, 0x3e, 0x45, 0x68, 0x89, 0x20, 0xce, 0xc3, 0x80, 0x1d, 0x7f, 0x9a, 0x71, 0x46, 0x10, + 0x77, 0x0f, 0xe1, 0xf7, 0xcf, 0x0e, 0x50, 0x41, 0xe7, 0xd8, 0xcd, 0xc1, 0x20, 0x4d, 0x01, 0x76, + 0xfa, 0x19, 0xfa, 0xe7, 0x4c, 0x88, 0x3b, 0x60, 0x9f, 0x63, 0xc0, 0x9f, 0x23, 0xb4, 0x58, 0x2f, + 0x16, 0x61, 0xd8, 0xe8, 0xfc, 0x76, 0xfc, 0x79, 0xc2, 0x4d, 0x0a, 0xb7, 0x4e, 0x9d, 0xdf, 0x2e, + 0x78, 0x81, 0xb7, 0x4e, 0x04, 0x86, 0x8d, 0x9b, 0xbe, 0x9d, 0x7e, 0x91, 0xa3, 0xce, 0x88, 0x98, + 0x87, 0x4a, 0x59, 0xc8, 0xed, 0xfc, 0x4b, 0xc4, 0xb7, 0x19, 0x8c, 0x80, 0xd1, 0x48, 0xec, 0x8a, + 0x97, 0x39, 0x02, 0x06, 0x85, 0xd7, 0xa8, 0x7b, 0x38, 0xb0, 0x9b, 0x5e, 0xe1, 0x6b, 0xd4, 0x35, + 0x1b, 0x60, 0x36, 0xf3, 0x7a, 0x6a, 0x57, 0xbc, 0xca, 0xd9, 0xcc, 0xd7, 0xe3, 0x36, 0xba, 0xbb, + 0xad, 0xdd, 0xf1, 0x1a, 0x6f, 0xa3, 0xab, 0xd9, 0x8a, 0x55, 0xa8, 0xee, 0xed, 0xb4, 0x76, 0xdf, + 0xeb, 0xe4, 0x9b, 0xd8, 0xd3, 0x68, 0xc5, 0xfd, 0x30, 0xdd, 0xbb, 0xcb, 0xda, 0xad, 0xe7, 0x76, + 0xba, 0x3e, 0x17, 0x99, 0x4d, 0x56, 0x9c, 0x68, 0x97, 0x6b, 0xb3, 0xc3, 0xda, 0xb5, 0xe7, 0x77, + 0x3a, 0x2b, 0xb6, 0xd9, 0x60, 0xc5, 0x02, 0x40, 0xbb, 0xb9, 0xd9, 0x5d, 0x17, 0xc8, 0x65, 0x40, + 0x78, 0x35, 0xa8, 0xb7, 0xd9, 0xf9, 0x8b, 0x7c, 0x35, 0x88, 0xc0, 0xab, 0xc1, 0x6d, 0xcd, 0x4e, + 0x5f, 0xe2, 0xab, 0xc1, 0x08, 0x9e, 0x6c, 0xa3, 0x73, 0xd8, 0x0d, 0x97, 0xf9, 0x64, 0x1b, 0x94, + 0x98, 0x83, 0xa1, 0x38, 0x0b, 0x43, 0x3c, 0xa0, 0xd5, 0x9b, 0x7b, 0xb4, 0x2b, 0x19, 0x36, 0x99, + 0xff, 0x6d, 0x97, 0x76, 0xc0, 0x80, 0x38, 0x04, 0xfb, 0x64, 0x54, 0x97, 0x4d, 0x1b, 0xf9, 0xfb, + 0x2e, 0x17, 0x25, 0x5c, 0x2d, 0xe6, 0x01, 0x8a, 0x8f, 0xf6, 0xf8, 0x2a, 0x36, 0xf6, 0x8f, 0xdd, + 0xe2, 0x5b, 0x06, 0x03, 0x69, 0x0b, 0xf2, 0x17, 0xb7, 0x08, 0xb6, 0x3b, 0x05, 0xf9, 0x5b, 0x1f, + 0x86, 0xc1, 0x47, 0x52, 0x15, 0x6b, 0xcf, 0xb7, 0xd1, 0x7f, 0x12, 0xcd, 0xeb, 0x31, 0x60, 0x91, + 0x4a, 0xa4, 0xf6, 0xfc, 0xd4, 0xc6, 0xfe, 0x45, 0x6c, 0x09, 0x20, 0xdc, 0xf0, 0x52, 0xed, 0xf2, + 0xde, 0x7f, 0x33, 0xcc, 0x00, 0x6e, 0x1a, 0x9f, 0x1f, 0x95, 0x5b, 0x36, 0xf6, 0x1f, 0xde, 0x34, + 0xad, 0x17, 0x47, 0xa0, 0x82, 0x8f, 0xf9, 0xb7, 0x22, 0x36, 0xf8, 0x5f, 0x82, 0xdb, 0x04, 0xfe, + 0xe7, 0x54, 0x37, 0x75, 0x60, 0x0f, 0xf6, 0x7f, 0x94, 0x69, 0x5e, 0x2f, 0x16, 0x60, 0x38, 0xd5, + 0xcd, 0x66, 0x46, 0xf3, 0x95, 0x05, 0xff, 0x7f, 0xb7, 0xfc, 0xc8, 0x5d, 0x32, 0x47, 0x97, 0x60, + 0xb2, 0xa1, 0xa2, 0x6e, 0xf0, 0x28, 0x2c, 0xab, 0x65, 0xb5, 0x9a, 0x5f, 0xc5, 0x87, 0x6e, 0xf3, + 0x03, 0xbd, 0x99, 0xd5, 0x67, 0x1a, 0x2a, 0x9a, 0xc5, 0xc1, 0xb7, 0xfd, 0x7d, 0x5e, 0x39, 0x06, + 0x5f, 0x0d, 0x00, 0x00, 0xff, 0xff, 0x51, 0xf0, 0xa5, 0x95, 0x02, 0x14, 0x00, 0x00, } diff --git a/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.golden b/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.golden new file mode 100644 index 000000000..f6502e4b9 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.golden @@ -0,0 +1,45 @@ +// Code generated by protoc-gen-go. +// source: gogo.proto +// DO NOT EDIT! + +package gogoproto + +import proto "github.com/gogo/protobuf/proto" +import json "encoding/json" +import math "math" +import google_protobuf "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" + +// Reference proto, json, and math imports to suppress error if they are not otherwise used. +var _ = proto.Marshal +var _ = &json.SyntaxError{} +var _ = math.Inf + +var E_Nullable = &proto.ExtensionDesc{ + ExtendedType: (*google_protobuf.FieldOptions)(nil), + ExtensionType: (*bool)(nil), + Field: 51235, + Name: "gogoproto.nullable", + Tag: "varint,51235,opt,name=nullable", +} + +var E_Embed = &proto.ExtensionDesc{ + ExtendedType: (*google_protobuf.FieldOptions)(nil), + ExtensionType: (*bool)(nil), + Field: 51236, + Name: "gogoproto.embed", + Tag: "varint,51236,opt,name=embed", +} + +var E_Customtype = &proto.ExtensionDesc{ + ExtendedType: (*google_protobuf.FieldOptions)(nil), + ExtensionType: (*string)(nil), + Field: 51237, + Name: "gogoproto.customtype", + Tag: "bytes,51237,opt,name=customtype", +} + +func init() { + proto.RegisterExtension(E_Nullable) + proto.RegisterExtension(E_Embed) + proto.RegisterExtension(E_Customtype) +} diff --git a/vendor/github.com/gogo/protobuf/gogoproto/gogo.proto b/vendor/github.com/gogo/protobuf/gogoproto/gogo.proto new file mode 100644 index 000000000..bc8d889f1 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/gogoproto/gogo.proto @@ -0,0 +1,136 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2013, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto2"; +package gogoproto; + +import "google/protobuf/descriptor.proto"; + +option java_package = "com.google.protobuf"; +option java_outer_classname = "GoGoProtos"; +option go_package = "github.com/gogo/protobuf/gogoproto"; + +extend google.protobuf.EnumOptions { + optional bool goproto_enum_prefix = 62001; + optional bool goproto_enum_stringer = 62021; + optional bool enum_stringer = 62022; + optional string enum_customname = 62023; + optional bool enumdecl = 62024; +} + +extend google.protobuf.EnumValueOptions { + optional string enumvalue_customname = 66001; +} + +extend google.protobuf.FileOptions { + optional bool goproto_getters_all = 63001; + optional bool goproto_enum_prefix_all = 63002; + optional bool goproto_stringer_all = 63003; + optional bool verbose_equal_all = 63004; + optional bool face_all = 63005; + optional bool gostring_all = 63006; + optional bool populate_all = 63007; + optional bool stringer_all = 63008; + optional bool onlyone_all = 63009; + + optional bool equal_all = 63013; + optional bool description_all = 63014; + optional bool testgen_all = 63015; + optional bool benchgen_all = 63016; + optional bool marshaler_all = 63017; + optional bool unmarshaler_all = 63018; + optional bool stable_marshaler_all = 63019; + + optional bool sizer_all = 63020; + + optional bool goproto_enum_stringer_all = 63021; + optional bool enum_stringer_all = 63022; + + optional bool unsafe_marshaler_all = 63023; + optional bool unsafe_unmarshaler_all = 63024; + + optional bool goproto_extensions_map_all = 63025; + optional bool goproto_unrecognized_all = 63026; + optional bool gogoproto_import = 63027; + optional bool protosizer_all = 63028; + optional bool compare_all = 63029; + optional bool typedecl_all = 63030; + optional bool enumdecl_all = 63031; + + optional bool goproto_registration = 63032; + optional bool messagename_all = 63033; +} + +extend google.protobuf.MessageOptions { + optional bool goproto_getters = 64001; + optional bool goproto_stringer = 64003; + optional bool verbose_equal = 64004; + optional bool face = 64005; + optional bool gostring = 64006; + optional bool populate = 64007; + optional bool stringer = 67008; + optional bool onlyone = 64009; + + optional bool equal = 64013; + optional bool description = 64014; + optional bool testgen = 64015; + optional bool benchgen = 64016; + optional bool marshaler = 64017; + optional bool unmarshaler = 64018; + optional bool stable_marshaler = 64019; + + optional bool sizer = 64020; + + optional bool unsafe_marshaler = 64023; + optional bool unsafe_unmarshaler = 64024; + + optional bool goproto_extensions_map = 64025; + optional bool goproto_unrecognized = 64026; + + optional bool protosizer = 64028; + optional bool compare = 64029; + + optional bool typedecl = 64030; + + optional bool messagename = 64033; +} + +extend google.protobuf.FieldOptions { + optional bool nullable = 65001; + optional bool embed = 65002; + optional string customtype = 65003; + optional string customname = 65004; + optional string jsontag = 65005; + optional string moretags = 65006; + optional string casttype = 65007; + optional string castkey = 65008; + optional string castvalue = 65009; + + optional bool stdtime = 65010; + optional bool stdduration = 65011; +} diff --git a/vendor/github.com/gogo/protobuf/gogoproto/helper.go b/vendor/github.com/gogo/protobuf/gogoproto/helper.go index 6b851c562..22910c6d4 100644 --- a/vendor/github.com/gogo/protobuf/gogoproto/helper.go +++ b/vendor/github.com/gogo/protobuf/gogoproto/helper.go @@ -334,9 +334,6 @@ func HasExtensionsMap(file *google_protobuf.FileDescriptorProto, message *google } func HasUnrecognized(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - if IsProto3(file) { - return false - } return proto.GetBoolExtension(message.Options, E_GoprotoUnrecognized, proto.GetBoolExtension(file.Options, E_GoprotoUnrecognizedAll, true)) } @@ -355,3 +352,7 @@ func HasCompare(file *google_protobuf.FileDescriptorProto, message *google_proto func RegistersGolangProto(file *google_protobuf.FileDescriptorProto) bool { return proto.GetBoolExtension(file.Options, E_GoprotoRegistration, false) } + +func HasMessageName(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { + return proto.GetBoolExtension(message.Options, E_Messagename, proto.GetBoolExtension(file.Options, E_MessagenameAll, false)) +} diff --git a/vendor/github.com/gogo/protobuf/jsonpb/jsonpb.go b/vendor/github.com/gogo/protobuf/jsonpb/jsonpb.go index 57a3a9147..cd0f66863 100644 --- a/vendor/github.com/gogo/protobuf/jsonpb/jsonpb.go +++ b/vendor/github.com/gogo/protobuf/jsonpb/jsonpb.go @@ -55,6 +55,8 @@ import ( "github.com/gogo/protobuf/types" ) +const secondInNanos = int64(time.Second / time.Nanosecond) + // Marshaler is a configurable object for converting between // protocol buffer objects and a JSON representation for them. type Marshaler struct { @@ -117,6 +119,14 @@ type JSONPBUnmarshaler interface { // Marshal marshals a protocol buffer into JSON. func (m *Marshaler) Marshal(out io.Writer, pb proto.Message) error { + v := reflect.ValueOf(pb) + if pb == nil || (v.Kind() == reflect.Ptr && v.IsNil()) { + return errors.New("Marshal called with nil") + } + // Check for unset required fields first. + if err := checkRequiredFields(pb); err != nil { + return err + } writer := &errWriter{writer: out} return m.marshalObject(writer, pb, "", "") } @@ -189,13 +199,22 @@ func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent, typeU // Any is a bit more involved. return m.marshalAny(out, v, indent) case "Duration": - // "Generated output always contains 3, 6, or 9 fractional digits, + // "Generated output always contains 0, 3, 6, or 9 fractional digits, // depending on required precision." s, ns := s.Field(0).Int(), s.Field(1).Int() - d := time.Duration(s)*time.Second + time.Duration(ns)*time.Nanosecond - x := fmt.Sprintf("%.9f", d.Seconds()) + if ns <= -secondInNanos || ns >= secondInNanos { + return fmt.Errorf("ns out of range (%v, %v)", -secondInNanos, secondInNanos) + } + if (s > 0 && ns < 0) || (s < 0 && ns > 0) { + return errors.New("signs of seconds and nanos do not match") + } + if s < 0 { + ns = -ns + } + x := fmt.Sprintf("%d.%09d", s, ns) x = strings.TrimSuffix(x, "000") x = strings.TrimSuffix(x, "000") + x = strings.TrimSuffix(x, ".000") out.write(`"`) out.write(x) out.write(`s"`) @@ -206,13 +225,17 @@ func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent, typeU return m.marshalValue(out, &proto.Properties{}, s.Field(0), indent) case "Timestamp": // "RFC 3339, where generated output will always be Z-normalized - // and uses 3, 6 or 9 fractional digits." + // and uses 0, 3, 6 or 9 fractional digits." s, ns := s.Field(0).Int(), s.Field(1).Int() + if ns < 0 || ns >= secondInNanos { + return fmt.Errorf("ns out of range [0, %v)", secondInNanos) + } t := time.Unix(s, ns).UTC() // time.RFC3339Nano isn't exactly right (we need to get 3/6/9 fractional digits). x := t.Format("2006-01-02T15:04:05.000000000") x = strings.TrimSuffix(x, "000") x = strings.TrimSuffix(x, "000") + x = strings.TrimSuffix(x, ".000") out.write(`"`) out.write(x) out.write(`Z"`) @@ -716,7 +739,10 @@ func (u *Unmarshaler) UnmarshalNext(dec *json.Decoder, pb proto.Message) error { if err := dec.Decode(&inputValue); err != nil { return err } - return u.unmarshalValue(reflect.ValueOf(pb).Elem(), inputValue, nil) + if err := u.unmarshalValue(reflect.ValueOf(pb).Elem(), inputValue, nil); err != nil { + return err + } + return checkRequiredFields(pb) } // Unmarshal unmarshals a JSON object stream into a protocol @@ -886,7 +912,7 @@ func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMe return fmt.Errorf("bad ListValue: %v", err) } - target.Field(0).Set(reflect.ValueOf(make([]*types.Value, len(s), len(s)))) + target.Field(0).Set(reflect.ValueOf(make([]*types.Value, len(s)))) for i, sv := range s { if err := u.unmarshalValue(target.Field(0).Index(i), sv, prop); err != nil { return err @@ -1114,13 +1140,6 @@ func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMe } if mp != nil { target.Set(reflect.MakeMap(targetType)) - var keyprop, valprop *proto.Properties - if prop != nil { - // These could still be nil if the protobuf metadata is broken somehow. - // TODO: This won't work because the fields are unexported. - // We should probably just reparse them. - //keyprop, valprop = prop.mkeyprop, prop.mvalprop - } for ks, raw := range mp { // Unmarshal map key. The core json library already decoded the key into a // string, so we handle that specially. Other types were quoted post-serialization. @@ -1129,7 +1148,8 @@ func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMe k = reflect.ValueOf(ks) } else { k = reflect.New(targetType.Key()).Elem() - if err := u.unmarshalValue(k, json.RawMessage(ks), keyprop); err != nil { + // TODO: pass the correct Properties if needed. + if err := u.unmarshalValue(k, json.RawMessage(ks), nil); err != nil { return err } } @@ -1140,7 +1160,8 @@ func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMe // Unmarshal map value. v := reflect.New(targetType.Elem()).Elem() - if err := u.unmarshalValue(v, raw, valprop); err != nil { + // TODO: pass the correct Properties if needed. + if err := u.unmarshalValue(v, raw, nil); err != nil { return err } target.SetMapIndex(k, v) @@ -1226,3 +1247,140 @@ func (s mapKeys) Less(i, j int) bool { } return fmt.Sprint(s[i].Interface()) < fmt.Sprint(s[j].Interface()) } + +// checkRequiredFields returns an error if any required field in the given proto message is not set. +// This function is used by both Marshal and Unmarshal. While required fields only exist in a +// proto2 message, a proto3 message can contain proto2 message(s). +func checkRequiredFields(pb proto.Message) error { + // Most well-known type messages do not contain required fields. The "Any" type may contain + // a message that has required fields. + // + // When an Any message is being marshaled, the code will invoked proto.Unmarshal on Any.Value + // field in order to transform that into JSON, and that should have returned an error if a + // required field is not set in the embedded message. + // + // When an Any message is being unmarshaled, the code will have invoked proto.Marshal on the + // embedded message to store the serialized message in Any.Value field, and that should have + // returned an error if a required field is not set. + if _, ok := pb.(isWkt); ok { + return nil + } + + v := reflect.ValueOf(pb) + // Skip message if it is not a struct pointer. + if v.Kind() != reflect.Ptr { + return nil + } + v = v.Elem() + if v.Kind() != reflect.Struct { + return nil + } + + for i := 0; i < v.NumField(); i++ { + field := v.Field(i) + sfield := v.Type().Field(i) + + if sfield.PkgPath != "" { + // blank PkgPath means the field is exported; skip if not exported + continue + } + + if strings.HasPrefix(sfield.Name, "XXX_") { + continue + } + + // Oneof field is an interface implemented by wrapper structs containing the actual oneof + // field, i.e. an interface containing &T{real_value}. + if sfield.Tag.Get("protobuf_oneof") != "" { + if field.Kind() != reflect.Interface { + continue + } + v := field.Elem() + if v.Kind() != reflect.Ptr || v.IsNil() { + continue + } + v = v.Elem() + if v.Kind() != reflect.Struct || v.NumField() < 1 { + continue + } + field = v.Field(0) + sfield = v.Type().Field(0) + } + + protoTag := sfield.Tag.Get("protobuf") + if protoTag == "" { + continue + } + var prop proto.Properties + prop.Init(sfield.Type, sfield.Name, protoTag, &sfield) + + switch field.Kind() { + case reflect.Map: + if field.IsNil() { + continue + } + // Check each map value. + keys := field.MapKeys() + for _, k := range keys { + v := field.MapIndex(k) + if err := checkRequiredFieldsInValue(v); err != nil { + return err + } + } + case reflect.Slice: + // Handle non-repeated type, e.g. bytes. + if !prop.Repeated { + if prop.Required && field.IsNil() { + return fmt.Errorf("required field %q is not set", prop.Name) + } + continue + } + + // Handle repeated type. + if field.IsNil() { + continue + } + // Check each slice item. + for i := 0; i < field.Len(); i++ { + v := field.Index(i) + if err := checkRequiredFieldsInValue(v); err != nil { + return err + } + } + case reflect.Ptr: + if field.IsNil() { + if prop.Required { + return fmt.Errorf("required field %q is not set", prop.Name) + } + continue + } + if err := checkRequiredFieldsInValue(field); err != nil { + return err + } + } + } + + // Handle proto2 extensions. + for _, ext := range proto.RegisteredExtensions(pb) { + if !proto.HasExtension(pb, ext) { + continue + } + ep, err := proto.GetExtension(pb, ext) + if err != nil { + return err + } + err = checkRequiredFieldsInValue(reflect.ValueOf(ep)) + if err != nil { + return err + } + } + + return nil +} + +func checkRequiredFieldsInValue(v reflect.Value) error { + if pm, ok := v.Interface().(proto.Message); ok { + return checkRequiredFields(pm) + } + return nil +} diff --git a/vendor/github.com/gogo/protobuf/proto/Makefile b/vendor/github.com/gogo/protobuf/proto/Makefile new file mode 100644 index 000000000..00d65f327 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/Makefile @@ -0,0 +1,43 @@ +# Go support for Protocol Buffers - Google's data interchange format +# +# Copyright 2010 The Go Authors. All rights reserved. +# https://github.com/golang/protobuf +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +install: + go install + +test: install generate-test-pbs + go test + + +generate-test-pbs: + make install + make -C test_proto + make -C proto3_proto + make diff --git a/vendor/github.com/gogo/protobuf/proto/clone.go b/vendor/github.com/gogo/protobuf/proto/clone.go index 5d4cba4b5..a26b046d9 100644 --- a/vendor/github.com/gogo/protobuf/proto/clone.go +++ b/vendor/github.com/gogo/protobuf/proto/clone.go @@ -35,22 +35,39 @@ package proto import ( + "fmt" "log" "reflect" "strings" ) // Clone returns a deep copy of a protocol buffer. -func Clone(pb Message) Message { - in := reflect.ValueOf(pb) +func Clone(src Message) Message { + in := reflect.ValueOf(src) if in.IsNil() { - return pb + return src } - out := reflect.New(in.Type().Elem()) - // out is empty so a merge is a deep copy. - mergeStruct(out.Elem(), in.Elem()) - return out.Interface().(Message) + dst := out.Interface().(Message) + Merge(dst, src) + return dst +} + +// Merger is the interface representing objects that can merge messages of the same type. +type Merger interface { + // Merge merges src into this message. + // Required and optional fields that are set in src will be set to that value in dst. + // Elements of repeated fields will be appended. + // + // Merge may panic if called with a different argument type than the receiver. + Merge(src Message) +} + +// generatedMerger is the custom merge method that generated protos will have. +// We must add this method since a generate Merge method will conflict with +// many existing protos that have a Merge data field already defined. +type generatedMerger interface { + XXX_Merge(src Message) } // Merge merges src into dst. @@ -58,17 +75,24 @@ func Clone(pb Message) Message { // Elements of repeated fields will be appended. // Merge panics if src and dst are not the same type, or if dst is nil. func Merge(dst, src Message) { + if m, ok := dst.(Merger); ok { + m.Merge(src) + return + } + in := reflect.ValueOf(src) out := reflect.ValueOf(dst) if out.IsNil() { panic("proto: nil destination") } if in.Type() != out.Type() { - // Explicit test prior to mergeStruct so that mistyped nils will fail - panic("proto: type mismatch") + panic(fmt.Sprintf("proto.Merge(%T, %T) type mismatch", dst, src)) } if in.IsNil() { - // Merging nil into non-nil is a quiet no-op + return // Merge from nil src is a noop + } + if m, ok := dst.(generatedMerger); ok { + m.XXX_Merge(src) return } mergeStruct(out.Elem(), in.Elem()) @@ -89,7 +113,7 @@ func mergeStruct(out, in reflect.Value) { bIn := emIn.GetExtensions() bOut := emOut.GetExtensions() *bOut = append(*bOut, *bIn...) - } else if emIn, ok := extendable(in.Addr().Interface()); ok { + } else if emIn, err := extendable(in.Addr().Interface()); err == nil { emOut, _ := extendable(out.Addr().Interface()) mIn, muIn := emIn.extensionsRead() if mIn != nil { diff --git a/vendor/github.com/gogo/protobuf/proto/custom_gogo.go b/vendor/github.com/gogo/protobuf/proto/custom_gogo.go new file mode 100644 index 000000000..24552483c --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/custom_gogo.go @@ -0,0 +1,39 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2018, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import "reflect" + +type custom interface { + Marshal() ([]byte, error) + Unmarshal(data []byte) error + Size() int +} + +var customType = reflect.TypeOf((*custom)(nil)).Elem() diff --git a/vendor/github.com/gogo/protobuf/proto/decode.go b/vendor/github.com/gogo/protobuf/proto/decode.go index 737f2731d..d9aa3c42d 100644 --- a/vendor/github.com/gogo/protobuf/proto/decode.go +++ b/vendor/github.com/gogo/protobuf/proto/decode.go @@ -39,8 +39,6 @@ import ( "errors" "fmt" "io" - "os" - "reflect" ) // errOverflow is returned when an integer is too large to be represented. @@ -50,10 +48,6 @@ var errOverflow = errors.New("proto: integer overflow") // wire type is encountered. It does not get returned to user code. var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof") -// The fundamental decoders that interpret bytes on the wire. -// Those that take integer types all return uint64 and are -// therefore of type valueDecoder. - // DecodeVarint reads a varint-encoded integer from the slice. // It returns the integer and the number of bytes consumed, or // zero if there is not enough. @@ -267,9 +261,6 @@ func (p *Buffer) DecodeZigzag32() (x uint64, err error) { return } -// These are not ValueDecoders: they produce an array of bytes or a string. -// bytes, embedded messages - // DecodeRawBytes reads a count-delimited byte buffer from the Buffer. // This is the format used for the bytes protocol buffer // type and for embedded messages. @@ -311,81 +302,29 @@ func (p *Buffer) DecodeStringBytes() (s string, err error) { return string(buf), nil } -// Skip the next item in the buffer. Its wire type is decoded and presented as an argument. -// If the protocol buffer has extensions, and the field matches, add it as an extension. -// Otherwise, if the XXX_unrecognized field exists, append the skipped data there. -func (o *Buffer) skipAndSave(t reflect.Type, tag, wire int, base structPointer, unrecField field) error { - oi := o.index - - err := o.skip(t, tag, wire) - if err != nil { - return err - } - - if !unrecField.IsValid() { - return nil - } - - ptr := structPointer_Bytes(base, unrecField) - - // Add the skipped field to struct field - obuf := o.buf - - o.buf = *ptr - o.EncodeVarint(uint64(tag<<3 | wire)) - *ptr = append(o.buf, obuf[oi:o.index]...) - - o.buf = obuf - - return nil -} - -// Skip the next item in the buffer. Its wire type is decoded and presented as an argument. -func (o *Buffer) skip(t reflect.Type, tag, wire int) error { - - var u uint64 - var err error - - switch wire { - case WireVarint: - _, err = o.DecodeVarint() - case WireFixed64: - _, err = o.DecodeFixed64() - case WireBytes: - _, err = o.DecodeRawBytes(false) - case WireFixed32: - _, err = o.DecodeFixed32() - case WireStartGroup: - for { - u, err = o.DecodeVarint() - if err != nil { - break - } - fwire := int(u & 0x7) - if fwire == WireEndGroup { - break - } - ftag := int(u >> 3) - err = o.skip(t, ftag, fwire) - if err != nil { - break - } - } - default: - err = fmt.Errorf("proto: can't skip unknown wire type %d for %s", wire, t) - } - return err -} - // Unmarshaler is the interface representing objects that can -// unmarshal themselves. The method should reset the receiver before -// decoding starts. The argument points to data that may be +// unmarshal themselves. The argument points to data that may be // overwritten, so implementations should not keep references to the // buffer. +// Unmarshal implementations should not clear the receiver. +// Any unmarshaled data should be merged into the receiver. +// Callers of Unmarshal that do not want to retain existing data +// should Reset the receiver before calling Unmarshal. type Unmarshaler interface { Unmarshal([]byte) error } +// newUnmarshaler is the interface representing objects that can +// unmarshal themselves. The semantics are identical to Unmarshaler. +// +// This exists to support protoc-gen-go generated messages. +// The proto package will stop type-asserting to this interface in the future. +// +// DO NOT DEPEND ON THIS. +type newUnmarshaler interface { + XXX_Unmarshal([]byte) error +} + // Unmarshal parses the protocol buffer representation in buf and places the // decoded result in pb. If the struct underlying pb does not match // the data in buf, the results can be unpredictable. @@ -395,7 +334,13 @@ type Unmarshaler interface { // to preserve and append to existing data. func Unmarshal(buf []byte, pb Message) error { pb.Reset() - return UnmarshalMerge(buf, pb) + if u, ok := pb.(newUnmarshaler); ok { + return u.XXX_Unmarshal(buf) + } + if u, ok := pb.(Unmarshaler); ok { + return u.Unmarshal(buf) + } + return NewBuffer(buf).Unmarshal(pb) } // UnmarshalMerge parses the protocol buffer representation in buf and @@ -405,8 +350,16 @@ func Unmarshal(buf []byte, pb Message) error { // UnmarshalMerge merges into existing data in pb. // Most code should use Unmarshal instead. func UnmarshalMerge(buf []byte, pb Message) error { - // If the object can unmarshal itself, let it. + if u, ok := pb.(newUnmarshaler); ok { + return u.XXX_Unmarshal(buf) + } if u, ok := pb.(Unmarshaler); ok { + // NOTE: The history of proto have unfortunately been inconsistent + // whether Unmarshaler should or should not implicitly clear itself. + // Some implementations do, most do not. + // Thus, calling this here may or may not do what people want. + // + // See https://github.com/golang/protobuf/issues/424 return u.Unmarshal(buf) } return NewBuffer(buf).Unmarshal(pb) @@ -422,12 +375,17 @@ func (p *Buffer) DecodeMessage(pb Message) error { } // DecodeGroup reads a tag-delimited group from the Buffer. +// StartGroup tag is already consumed. This function consumes +// EndGroup tag. func (p *Buffer) DecodeGroup(pb Message) error { - typ, base, err := getbase(pb) - if err != nil { - return err + b := p.buf[p.index:] + x, y := findEndGroup(b) + if x < 0 { + return io.ErrUnexpectedEOF } - return p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), true, base) + err := Unmarshal(b[:x], pb) + p.index += y + return err } // Unmarshal parses the protocol buffer representation in the @@ -438,541 +396,33 @@ func (p *Buffer) DecodeGroup(pb Message) error { // Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal. func (p *Buffer) Unmarshal(pb Message) error { // If the object can unmarshal itself, let it. - if u, ok := pb.(Unmarshaler); ok { - err := u.Unmarshal(p.buf[p.index:]) + if u, ok := pb.(newUnmarshaler); ok { + err := u.XXX_Unmarshal(p.buf[p.index:]) p.index = len(p.buf) return err } - - typ, base, err := getbase(pb) - if err != nil { - return err - } - - err = p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), false, base) - - if collectStats { - stats.Decode++ - } - - return err -} - -// unmarshalType does the work of unmarshaling a structure. -func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group bool, base structPointer) error { - var state errorState - required, reqFields := prop.reqCount, uint64(0) - - var err error - for err == nil && o.index < len(o.buf) { - oi := o.index - var u uint64 - u, err = o.DecodeVarint() - if err != nil { - break - } - wire := int(u & 0x7) - if wire == WireEndGroup { - if is_group { - if required > 0 { - // Not enough information to determine the exact field. - // (See below.) - return &RequiredNotSetError{"{Unknown}"} - } - return nil // input is satisfied - } - return fmt.Errorf("proto: %s: wiretype end group for non-group", st) - } - tag := int(u >> 3) - if tag <= 0 { - return fmt.Errorf("proto: %s: illegal tag %d (wire type %d)", st, tag, wire) - } - fieldnum, ok := prop.decoderTags.get(tag) - if !ok { - // Maybe it's an extension? - if prop.extendable { - if e, eok := structPointer_Interface(base, st).(extensionsBytes); eok { - if isExtensionField(e, int32(tag)) { - if err = o.skip(st, tag, wire); err == nil { - ext := e.GetExtensions() - *ext = append(*ext, o.buf[oi:o.index]...) - } - continue - } - } else if e, _ := extendable(structPointer_Interface(base, st)); isExtensionField(e, int32(tag)) { - if err = o.skip(st, tag, wire); err == nil { - extmap := e.extensionsWrite() - ext := extmap[int32(tag)] // may be missing - ext.enc = append(ext.enc, o.buf[oi:o.index]...) - extmap[int32(tag)] = ext - } - continue - } - } - // Maybe it's a oneof? - if prop.oneofUnmarshaler != nil { - m := structPointer_Interface(base, st).(Message) - // First return value indicates whether tag is a oneof field. - ok, err = prop.oneofUnmarshaler(m, tag, wire, o) - if err == ErrInternalBadWireType { - // Map the error to something more descriptive. - // Do the formatting here to save generated code space. - err = fmt.Errorf("bad wiretype for oneof field in %T", m) - } - if ok { - continue - } - } - err = o.skipAndSave(st, tag, wire, base, prop.unrecField) - continue - } - p := prop.Prop[fieldnum] - - if p.dec == nil { - fmt.Fprintf(os.Stderr, "proto: no protobuf decoder for %s.%s\n", st, st.Field(fieldnum).Name) - continue - } - dec := p.dec - if wire != WireStartGroup && wire != p.WireType { - if wire == WireBytes && p.packedDec != nil { - // a packable field - dec = p.packedDec - } else { - err = fmt.Errorf("proto: bad wiretype for field %s.%s: got wiretype %d, want %d", st, st.Field(fieldnum).Name, wire, p.WireType) - continue - } - } - decErr := dec(o, p, base) - if decErr != nil && !state.shouldContinue(decErr, p) { - err = decErr - } - if err == nil && p.Required { - // Successfully decoded a required field. - if tag <= 64 { - // use bitmap for fields 1-64 to catch field reuse. - var mask uint64 = 1 << uint64(tag-1) - if reqFields&mask == 0 { - // new required field - reqFields |= mask - required-- - } - } else { - // This is imprecise. It can be fooled by a required field - // with a tag > 64 that is encoded twice; that's very rare. - // A fully correct implementation would require allocating - // a data structure, which we would like to avoid. - required-- - } - } - } - if err == nil { - if is_group { - return io.ErrUnexpectedEOF - } - if state.err != nil { - return state.err - } - if required > 0 { - // Not enough information to determine the exact field. If we use extra - // CPU, we could determine the field only if the missing required field - // has a tag <= 64 and we check reqFields. - return &RequiredNotSetError{"{Unknown}"} - } - } - return err -} - -// Individual type decoders -// For each, -// u is the decoded value, -// v is a pointer to the field (pointer) in the struct - -// Sizes of the pools to allocate inside the Buffer. -// The goal is modest amortization and allocation -// on at least 16-byte boundaries. -const ( - boolPoolSize = 16 - uint32PoolSize = 8 - uint64PoolSize = 4 -) - -// Decode a bool. -func (o *Buffer) dec_bool(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - if len(o.bools) == 0 { - o.bools = make([]bool, boolPoolSize) - } - o.bools[0] = u != 0 - *structPointer_Bool(base, p.field) = &o.bools[0] - o.bools = o.bools[1:] - return nil -} - -func (o *Buffer) dec_proto3_bool(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - *structPointer_BoolVal(base, p.field) = u != 0 - return nil -} - -// Decode an int32. -func (o *Buffer) dec_int32(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - word32_Set(structPointer_Word32(base, p.field), o, uint32(u)) - return nil -} - -func (o *Buffer) dec_proto3_int32(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - word32Val_Set(structPointer_Word32Val(base, p.field), uint32(u)) - return nil -} - -// Decode an int64. -func (o *Buffer) dec_int64(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - word64_Set(structPointer_Word64(base, p.field), o, u) - return nil -} - -func (o *Buffer) dec_proto3_int64(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - word64Val_Set(structPointer_Word64Val(base, p.field), o, u) - return nil -} - -// Decode a string. -func (o *Buffer) dec_string(p *Properties, base structPointer) error { - s, err := o.DecodeStringBytes() - if err != nil { - return err - } - *structPointer_String(base, p.field) = &s - return nil -} - -func (o *Buffer) dec_proto3_string(p *Properties, base structPointer) error { - s, err := o.DecodeStringBytes() - if err != nil { - return err - } - *structPointer_StringVal(base, p.field) = s - return nil -} - -// Decode a slice of bytes ([]byte). -func (o *Buffer) dec_slice_byte(p *Properties, base structPointer) error { - b, err := o.DecodeRawBytes(true) - if err != nil { - return err - } - *structPointer_Bytes(base, p.field) = b - return nil -} - -// Decode a slice of bools ([]bool). -func (o *Buffer) dec_slice_bool(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - v := structPointer_BoolSlice(base, p.field) - *v = append(*v, u != 0) - return nil -} - -// Decode a slice of bools ([]bool) in packed format. -func (o *Buffer) dec_slice_packed_bool(p *Properties, base structPointer) error { - v := structPointer_BoolSlice(base, p.field) - - nn, err := o.DecodeVarint() - if err != nil { - return err - } - nb := int(nn) // number of bytes of encoded bools - fin := o.index + nb - if fin < o.index { - return errOverflow - } - - y := *v - for o.index < fin { - u, err := p.valDec(o) - if err != nil { - return err - } - y = append(y, u != 0) - } - - *v = y - return nil -} - -// Decode a slice of int32s ([]int32). -func (o *Buffer) dec_slice_int32(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - structPointer_Word32Slice(base, p.field).Append(uint32(u)) - return nil -} - -// Decode a slice of int32s ([]int32) in packed format. -func (o *Buffer) dec_slice_packed_int32(p *Properties, base structPointer) error { - v := structPointer_Word32Slice(base, p.field) - - nn, err := o.DecodeVarint() - if err != nil { - return err - } - nb := int(nn) // number of bytes of encoded int32s - - fin := o.index + nb - if fin < o.index { - return errOverflow - } - for o.index < fin { - u, err := p.valDec(o) - if err != nil { - return err - } - v.Append(uint32(u)) - } - return nil -} - -// Decode a slice of int64s ([]int64). -func (o *Buffer) dec_slice_int64(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - - structPointer_Word64Slice(base, p.field).Append(u) - return nil -} - -// Decode a slice of int64s ([]int64) in packed format. -func (o *Buffer) dec_slice_packed_int64(p *Properties, base structPointer) error { - v := structPointer_Word64Slice(base, p.field) - - nn, err := o.DecodeVarint() - if err != nil { - return err - } - nb := int(nn) // number of bytes of encoded int64s - - fin := o.index + nb - if fin < o.index { - return errOverflow - } - for o.index < fin { - u, err := p.valDec(o) - if err != nil { - return err - } - v.Append(u) - } - return nil -} - -// Decode a slice of strings ([]string). -func (o *Buffer) dec_slice_string(p *Properties, base structPointer) error { - s, err := o.DecodeStringBytes() - if err != nil { - return err - } - v := structPointer_StringSlice(base, p.field) - *v = append(*v, s) - return nil -} - -// Decode a slice of slice of bytes ([][]byte). -func (o *Buffer) dec_slice_slice_byte(p *Properties, base structPointer) error { - b, err := o.DecodeRawBytes(true) - if err != nil { - return err - } - v := structPointer_BytesSlice(base, p.field) - *v = append(*v, b) - return nil -} - -// Decode a map field. -func (o *Buffer) dec_new_map(p *Properties, base structPointer) error { - raw, err := o.DecodeRawBytes(false) - if err != nil { - return err - } - oi := o.index // index at the end of this map entry - o.index -= len(raw) // move buffer back to start of map entry - - mptr := structPointer_NewAt(base, p.field, p.mtype) // *map[K]V - if mptr.Elem().IsNil() { - mptr.Elem().Set(reflect.MakeMap(mptr.Type().Elem())) - } - v := mptr.Elem() // map[K]V - - // Prepare addressable doubly-indirect placeholders for the key and value types. - // See enc_new_map for why. - keyptr := reflect.New(reflect.PtrTo(p.mtype.Key())).Elem() // addressable *K - keybase := toStructPointer(keyptr.Addr()) // **K - - var valbase structPointer - var valptr reflect.Value - switch p.mtype.Elem().Kind() { - case reflect.Slice: - // []byte - var dummy []byte - valptr = reflect.ValueOf(&dummy) // *[]byte - valbase = toStructPointer(valptr) // *[]byte - case reflect.Ptr: - // message; valptr is **Msg; need to allocate the intermediate pointer - valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V - valptr.Set(reflect.New(valptr.Type().Elem())) - valbase = toStructPointer(valptr) - default: - // everything else - valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V - valbase = toStructPointer(valptr.Addr()) // **V - } - - // Decode. - // This parses a restricted wire format, namely the encoding of a message - // with two fields. See enc_new_map for the format. - for o.index < oi { - // tagcode for key and value properties are always a single byte - // because they have tags 1 and 2. - tagcode := o.buf[o.index] - o.index++ - switch tagcode { - case p.mkeyprop.tagcode[0]: - if err := p.mkeyprop.dec(o, p.mkeyprop, keybase); err != nil { - return err - } - case p.mvalprop.tagcode[0]: - if err := p.mvalprop.dec(o, p.mvalprop, valbase); err != nil { - return err - } - default: - // TODO: Should we silently skip this instead? - return fmt.Errorf("proto: bad map data tag %d", raw[0]) - } - } - keyelem, valelem := keyptr.Elem(), valptr.Elem() - if !keyelem.IsValid() { - keyelem = reflect.Zero(p.mtype.Key()) - } - if !valelem.IsValid() { - valelem = reflect.Zero(p.mtype.Elem()) - } - - v.SetMapIndex(keyelem, valelem) - return nil -} - -// Decode a group. -func (o *Buffer) dec_struct_group(p *Properties, base structPointer) error { - bas := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(bas) { - // allocate new nested message - bas = toStructPointer(reflect.New(p.stype)) - structPointer_SetStructPointer(base, p.field, bas) - } - return o.unmarshalType(p.stype, p.sprop, true, bas) -} - -// Decode an embedded message. -func (o *Buffer) dec_struct_message(p *Properties, base structPointer) (err error) { - raw, e := o.DecodeRawBytes(false) - if e != nil { - return e - } - - bas := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(bas) { - // allocate new nested message - bas = toStructPointer(reflect.New(p.stype)) - structPointer_SetStructPointer(base, p.field, bas) - } - - // If the object can unmarshal itself, let it. - if p.isUnmarshaler { - iv := structPointer_Interface(bas, p.stype) - return iv.(Unmarshaler).Unmarshal(raw) - } - - obuf := o.buf - oi := o.index - o.buf = raw - o.index = 0 - - err = o.unmarshalType(p.stype, p.sprop, false, bas) - o.buf = obuf - o.index = oi - - return err -} - -// Decode a slice of embedded messages. -func (o *Buffer) dec_slice_struct_message(p *Properties, base structPointer) error { - return o.dec_slice_struct(p, false, base) -} - -// Decode a slice of embedded groups. -func (o *Buffer) dec_slice_struct_group(p *Properties, base structPointer) error { - return o.dec_slice_struct(p, true, base) -} - -// Decode a slice of structs ([]*struct). -func (o *Buffer) dec_slice_struct(p *Properties, is_group bool, base structPointer) error { - v := reflect.New(p.stype) - bas := toStructPointer(v) - structPointer_StructPointerSlice(base, p.field).Append(bas) - - if is_group { - err := o.unmarshalType(p.stype, p.sprop, is_group, bas) - return err - } - - raw, err := o.DecodeRawBytes(false) - if err != nil { + if u, ok := pb.(Unmarshaler); ok { + // NOTE: The history of proto have unfortunately been inconsistent + // whether Unmarshaler should or should not implicitly clear itself. + // Some implementations do, most do not. + // Thus, calling this here may or may not do what people want. + // + // See https://github.com/golang/protobuf/issues/424 + err := u.Unmarshal(p.buf[p.index:]) + p.index = len(p.buf) return err } - // If the object can unmarshal itself, let it. - if p.isUnmarshaler { - iv := v.Interface() - return iv.(Unmarshaler).Unmarshal(raw) - } - - obuf := o.buf - oi := o.index - o.buf = raw - o.index = 0 - - err = o.unmarshalType(p.stype, p.sprop, is_group, bas) - - o.buf = obuf - o.index = oi - + // Slow workaround for messages that aren't Unmarshalers. + // This includes some hand-coded .pb.go files and + // bootstrap protos. + // TODO: fix all of those and then add Unmarshal to + // the Message interface. Then: + // The cast above and code below can be deleted. + // The old unmarshaler can be deleted. + // Clients can call Unmarshal directly (can already do that, actually). + var info InternalMessageInfo + err := info.Unmarshal(pb, p.buf[p.index:]) + p.index = len(p.buf) return err } diff --git a/vendor/github.com/gogo/protobuf/proto/decode_gogo.go b/vendor/github.com/gogo/protobuf/proto/decode_gogo.go deleted file mode 100644 index 6fb74de4c..000000000 --- a/vendor/github.com/gogo/protobuf/proto/decode_gogo.go +++ /dev/null @@ -1,172 +0,0 @@ -// Protocol Buffers for Go with Gadgets -// -// Copyright (c) 2013, The GoGo Authors. All rights reserved. -// http://github.com/gogo/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "reflect" -) - -// Decode a reference to a struct pointer. -func (o *Buffer) dec_ref_struct_message(p *Properties, base structPointer) (err error) { - raw, e := o.DecodeRawBytes(false) - if e != nil { - return e - } - - // If the object can unmarshal itself, let it. - if p.isUnmarshaler { - panic("not supported, since this is a pointer receiver") - } - - obuf := o.buf - oi := o.index - o.buf = raw - o.index = 0 - - bas := structPointer_FieldPointer(base, p.field) - - err = o.unmarshalType(p.stype, p.sprop, false, bas) - o.buf = obuf - o.index = oi - - return err -} - -// Decode a slice of references to struct pointers ([]struct). -func (o *Buffer) dec_slice_ref_struct(p *Properties, is_group bool, base structPointer) error { - newBas := appendStructPointer(base, p.field, p.sstype) - - if is_group { - panic("not supported, maybe in future, if requested.") - } - - raw, err := o.DecodeRawBytes(false) - if err != nil { - return err - } - - // If the object can unmarshal itself, let it. - if p.isUnmarshaler { - panic("not supported, since this is not a pointer receiver.") - } - - obuf := o.buf - oi := o.index - o.buf = raw - o.index = 0 - - err = o.unmarshalType(p.stype, p.sprop, is_group, newBas) - - o.buf = obuf - o.index = oi - - return err -} - -// Decode a slice of references to struct pointers. -func (o *Buffer) dec_slice_ref_struct_message(p *Properties, base structPointer) error { - return o.dec_slice_ref_struct(p, false, base) -} - -func setPtrCustomType(base structPointer, f field, v interface{}) { - if v == nil { - return - } - structPointer_SetStructPointer(base, f, toStructPointer(reflect.ValueOf(v))) -} - -func setCustomType(base structPointer, f field, value interface{}) { - if value == nil { - return - } - v := reflect.ValueOf(value).Elem() - t := reflect.TypeOf(value).Elem() - kind := t.Kind() - switch kind { - case reflect.Slice: - slice := reflect.MakeSlice(t, v.Len(), v.Cap()) - reflect.Copy(slice, v) - oldHeader := structPointer_GetSliceHeader(base, f) - oldHeader.Data = slice.Pointer() - oldHeader.Len = v.Len() - oldHeader.Cap = v.Cap() - default: - size := reflect.TypeOf(value).Elem().Size() - structPointer_Copy(toStructPointer(reflect.ValueOf(value)), structPointer_Add(base, f), int(size)) - } -} - -func (o *Buffer) dec_custom_bytes(p *Properties, base structPointer) error { - b, err := o.DecodeRawBytes(true) - if err != nil { - return err - } - i := reflect.New(p.ctype.Elem()).Interface() - custom := (i).(Unmarshaler) - if err := custom.Unmarshal(b); err != nil { - return err - } - setPtrCustomType(base, p.field, custom) - return nil -} - -func (o *Buffer) dec_custom_ref_bytes(p *Properties, base structPointer) error { - b, err := o.DecodeRawBytes(true) - if err != nil { - return err - } - i := reflect.New(p.ctype).Interface() - custom := (i).(Unmarshaler) - if err := custom.Unmarshal(b); err != nil { - return err - } - if custom != nil { - setCustomType(base, p.field, custom) - } - return nil -} - -// Decode a slice of bytes ([]byte) into a slice of custom types. -func (o *Buffer) dec_custom_slice_bytes(p *Properties, base structPointer) error { - b, err := o.DecodeRawBytes(true) - if err != nil { - return err - } - i := reflect.New(p.ctype.Elem()).Interface() - custom := (i).(Unmarshaler) - if err := custom.Unmarshal(b); err != nil { - return err - } - newBas := appendStructPointer(base, p.field, p.ctype) - - var zero field - setCustomType(newBas, zero, custom) - - return nil -} diff --git a/vendor/github.com/gogo/protobuf/proto/discard.go b/vendor/github.com/gogo/protobuf/proto/discard.go index bd0e3bb4c..fe1bd7d90 100644 --- a/vendor/github.com/gogo/protobuf/proto/discard.go +++ b/vendor/github.com/gogo/protobuf/proto/discard.go @@ -35,8 +35,14 @@ import ( "fmt" "reflect" "strings" + "sync" + "sync/atomic" ) +type generatedDiscarder interface { + XXX_DiscardUnknown() +} + // DiscardUnknown recursively discards all unknown fields from this message // and all embedded messages. // @@ -49,9 +55,202 @@ import ( // For proto2 messages, the unknown fields of message extensions are only // discarded from messages that have been accessed via GetExtension. func DiscardUnknown(m Message) { + if m, ok := m.(generatedDiscarder); ok { + m.XXX_DiscardUnknown() + return + } + // TODO: Dynamically populate a InternalMessageInfo for legacy messages, + // but the master branch has no implementation for InternalMessageInfo, + // so it would be more work to replicate that approach. discardLegacy(m) } +// DiscardUnknown recursively discards all unknown fields. +func (a *InternalMessageInfo) DiscardUnknown(m Message) { + di := atomicLoadDiscardInfo(&a.discard) + if di == nil { + di = getDiscardInfo(reflect.TypeOf(m).Elem()) + atomicStoreDiscardInfo(&a.discard, di) + } + di.discard(toPointer(&m)) +} + +type discardInfo struct { + typ reflect.Type + + initialized int32 // 0: only typ is valid, 1: everything is valid + lock sync.Mutex + + fields []discardFieldInfo + unrecognized field +} + +type discardFieldInfo struct { + field field // Offset of field, guaranteed to be valid + discard func(src pointer) +} + +var ( + discardInfoMap = map[reflect.Type]*discardInfo{} + discardInfoLock sync.Mutex +) + +func getDiscardInfo(t reflect.Type) *discardInfo { + discardInfoLock.Lock() + defer discardInfoLock.Unlock() + di := discardInfoMap[t] + if di == nil { + di = &discardInfo{typ: t} + discardInfoMap[t] = di + } + return di +} + +func (di *discardInfo) discard(src pointer) { + if src.isNil() { + return // Nothing to do. + } + + if atomic.LoadInt32(&di.initialized) == 0 { + di.computeDiscardInfo() + } + + for _, fi := range di.fields { + sfp := src.offset(fi.field) + fi.discard(sfp) + } + + // For proto2 messages, only discard unknown fields in message extensions + // that have been accessed via GetExtension. + if em, err := extendable(src.asPointerTo(di.typ).Interface()); err == nil { + // Ignore lock since DiscardUnknown is not concurrency safe. + emm, _ := em.extensionsRead() + for _, mx := range emm { + if m, ok := mx.value.(Message); ok { + DiscardUnknown(m) + } + } + } + + if di.unrecognized.IsValid() { + *src.offset(di.unrecognized).toBytes() = nil + } +} + +func (di *discardInfo) computeDiscardInfo() { + di.lock.Lock() + defer di.lock.Unlock() + if di.initialized != 0 { + return + } + t := di.typ + n := t.NumField() + + for i := 0; i < n; i++ { + f := t.Field(i) + if strings.HasPrefix(f.Name, "XXX_") { + continue + } + + dfi := discardFieldInfo{field: toField(&f)} + tf := f.Type + + // Unwrap tf to get its most basic type. + var isPointer, isSlice bool + if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { + isSlice = true + tf = tf.Elem() + } + if tf.Kind() == reflect.Ptr { + isPointer = true + tf = tf.Elem() + } + if isPointer && isSlice && tf.Kind() != reflect.Struct { + panic(fmt.Sprintf("%v.%s cannot be a slice of pointers to primitive types", t, f.Name)) + } + + switch tf.Kind() { + case reflect.Struct: + switch { + case !isPointer: + panic(fmt.Sprintf("%v.%s cannot be a direct struct value", t, f.Name)) + case isSlice: // E.g., []*pb.T + discardInfo := getDiscardInfo(tf) + dfi.discard = func(src pointer) { + sps := src.getPointerSlice() + for _, sp := range sps { + if !sp.isNil() { + discardInfo.discard(sp) + } + } + } + default: // E.g., *pb.T + discardInfo := getDiscardInfo(tf) + dfi.discard = func(src pointer) { + sp := src.getPointer() + if !sp.isNil() { + discardInfo.discard(sp) + } + } + } + case reflect.Map: + switch { + case isPointer || isSlice: + panic(fmt.Sprintf("%v.%s cannot be a pointer to a map or a slice of map values", t, f.Name)) + default: // E.g., map[K]V + if tf.Elem().Kind() == reflect.Ptr { // Proto struct (e.g., *T) + dfi.discard = func(src pointer) { + sm := src.asPointerTo(tf).Elem() + if sm.Len() == 0 { + return + } + for _, key := range sm.MapKeys() { + val := sm.MapIndex(key) + DiscardUnknown(val.Interface().(Message)) + } + } + } else { + dfi.discard = func(pointer) {} // Noop + } + } + case reflect.Interface: + // Must be oneof field. + switch { + case isPointer || isSlice: + panic(fmt.Sprintf("%v.%s cannot be a pointer to a interface or a slice of interface values", t, f.Name)) + default: // E.g., interface{} + // TODO: Make this faster? + dfi.discard = func(src pointer) { + su := src.asPointerTo(tf).Elem() + if !su.IsNil() { + sv := su.Elem().Elem().Field(0) + if sv.Kind() == reflect.Ptr && sv.IsNil() { + return + } + switch sv.Type().Kind() { + case reflect.Ptr: // Proto struct (e.g., *T) + DiscardUnknown(sv.Interface().(Message)) + } + } + } + } + default: + continue + } + di.fields = append(di.fields, dfi) + } + + di.unrecognized = invalidField + if f, ok := t.FieldByName("XXX_unrecognized"); ok { + if f.Type != reflect.TypeOf([]byte{}) { + panic("expected XXX_unrecognized to be of type []byte") + } + di.unrecognized = toField(&f) + } + + atomic.StoreInt32(&di.initialized, 1) +} + func discardLegacy(m Message) { v := reflect.ValueOf(m) if v.Kind() != reflect.Ptr || v.IsNil() { @@ -139,7 +338,7 @@ func discardLegacy(m Message) { // For proto2 messages, only discard unknown fields in message extensions // that have been accessed via GetExtension. - if em, ok := extendable(m); ok { + if em, err := extendable(m); err == nil { // Ignore lock since discardLegacy is not concurrency safe. emm, _ := em.extensionsRead() for _, mx := range emm { diff --git a/vendor/github.com/gogo/protobuf/proto/duration_gogo.go b/vendor/github.com/gogo/protobuf/proto/duration_gogo.go index 18e2a5f77..e748e1730 100644 --- a/vendor/github.com/gogo/protobuf/proto/duration_gogo.go +++ b/vendor/github.com/gogo/protobuf/proto/duration_gogo.go @@ -47,157 +47,3 @@ func (*duration) String() string { return "duration" } func init() { RegisterType((*duration)(nil), "gogo.protobuf.proto.duration") } - -func (o *Buffer) decDuration() (time.Duration, error) { - b, err := o.DecodeRawBytes(true) - if err != nil { - return 0, err - } - dproto := &duration{} - if err := Unmarshal(b, dproto); err != nil { - return 0, err - } - return durationFromProto(dproto) -} - -func (o *Buffer) dec_duration(p *Properties, base structPointer) error { - d, err := o.decDuration() - if err != nil { - return err - } - word64_Set(structPointer_Word64(base, p.field), o, uint64(d)) - return nil -} - -func (o *Buffer) dec_ref_duration(p *Properties, base structPointer) error { - d, err := o.decDuration() - if err != nil { - return err - } - word64Val_Set(structPointer_Word64Val(base, p.field), o, uint64(d)) - return nil -} - -func (o *Buffer) dec_slice_duration(p *Properties, base structPointer) error { - d, err := o.decDuration() - if err != nil { - return err - } - newBas := appendStructPointer(base, p.field, reflect.SliceOf(reflect.PtrTo(durationType))) - var zero field - setPtrCustomType(newBas, zero, &d) - return nil -} - -func (o *Buffer) dec_slice_ref_duration(p *Properties, base structPointer) error { - d, err := o.decDuration() - if err != nil { - return err - } - structPointer_Word64Slice(base, p.field).Append(uint64(d)) - return nil -} - -func size_duration(p *Properties, base structPointer) (n int) { - structp := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(structp) { - return 0 - } - dur := structPointer_Interface(structp, durationType).(*time.Duration) - d := durationProto(*dur) - size := Size(d) - return size + sizeVarint(uint64(size)) + len(p.tagcode) -} - -func (o *Buffer) enc_duration(p *Properties, base structPointer) error { - structp := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(structp) { - return ErrNil - } - dur := structPointer_Interface(structp, durationType).(*time.Duration) - d := durationProto(*dur) - data, err := Marshal(d) - if err != nil { - return err - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - return nil -} - -func size_ref_duration(p *Properties, base structPointer) (n int) { - dur := structPointer_InterfaceAt(base, p.field, durationType).(*time.Duration) - d := durationProto(*dur) - size := Size(d) - return size + sizeVarint(uint64(size)) + len(p.tagcode) -} - -func (o *Buffer) enc_ref_duration(p *Properties, base structPointer) error { - dur := structPointer_InterfaceAt(base, p.field, durationType).(*time.Duration) - d := durationProto(*dur) - data, err := Marshal(d) - if err != nil { - return err - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - return nil -} - -func size_slice_duration(p *Properties, base structPointer) (n int) { - pdurs := structPointer_InterfaceAt(base, p.field, reflect.SliceOf(reflect.PtrTo(durationType))).(*[]*time.Duration) - durs := *pdurs - for i := 0; i < len(durs); i++ { - if durs[i] == nil { - return 0 - } - dproto := durationProto(*durs[i]) - size := Size(dproto) - n += len(p.tagcode) + size + sizeVarint(uint64(size)) - } - return n -} - -func (o *Buffer) enc_slice_duration(p *Properties, base structPointer) error { - pdurs := structPointer_InterfaceAt(base, p.field, reflect.SliceOf(reflect.PtrTo(durationType))).(*[]*time.Duration) - durs := *pdurs - for i := 0; i < len(durs); i++ { - if durs[i] == nil { - return errRepeatedHasNil - } - dproto := durationProto(*durs[i]) - data, err := Marshal(dproto) - if err != nil { - return err - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - } - return nil -} - -func size_slice_ref_duration(p *Properties, base structPointer) (n int) { - pdurs := structPointer_InterfaceAt(base, p.field, reflect.SliceOf(durationType)).(*[]time.Duration) - durs := *pdurs - for i := 0; i < len(durs); i++ { - dproto := durationProto(durs[i]) - size := Size(dproto) - n += len(p.tagcode) + size + sizeVarint(uint64(size)) - } - return n -} - -func (o *Buffer) enc_slice_ref_duration(p *Properties, base structPointer) error { - pdurs := structPointer_InterfaceAt(base, p.field, reflect.SliceOf(durationType)).(*[]time.Duration) - durs := *pdurs - for i := 0; i < len(durs); i++ { - dproto := durationProto(durs[i]) - data, err := Marshal(dproto) - if err != nil { - return err - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - } - return nil -} diff --git a/vendor/github.com/gogo/protobuf/proto/encode.go b/vendor/github.com/gogo/protobuf/proto/encode.go index 8b84d1b22..c27d35f86 100644 --- a/vendor/github.com/gogo/protobuf/proto/encode.go +++ b/vendor/github.com/gogo/protobuf/proto/encode.go @@ -39,7 +39,6 @@ import ( "errors" "fmt" "reflect" - "sort" ) // RequiredNotSetError is the error returned if Marshal is called with @@ -82,10 +81,6 @@ var ( const maxVarintBytes = 10 // maximum length of a varint -// maxMarshalSize is the largest allowed size of an encoded protobuf, -// since C++ and Java use signed int32s for the size. -const maxMarshalSize = 1<<31 - 1 - // EncodeVarint returns the varint encoding of x. // This is the format for the // int32, int64, uint32, uint64, bool, and enum @@ -119,18 +114,27 @@ func (p *Buffer) EncodeVarint(x uint64) error { // SizeVarint returns the varint encoding size of an integer. func SizeVarint(x uint64) int { - return sizeVarint(x) -} - -func sizeVarint(x uint64) (n int) { - for { - n++ - x >>= 7 - if x == 0 { - break - } - } - return n + switch { + case x < 1<<7: + return 1 + case x < 1<<14: + return 2 + case x < 1<<21: + return 3 + case x < 1<<28: + return 4 + case x < 1<<35: + return 5 + case x < 1<<42: + return 6 + case x < 1<<49: + return 7 + case x < 1<<56: + return 8 + case x < 1<<63: + return 9 + } + return 10 } // EncodeFixed64 writes a 64-bit integer to the Buffer. @@ -149,10 +153,6 @@ func (p *Buffer) EncodeFixed64(x uint64) error { return nil } -func sizeFixed64(x uint64) int { - return 8 -} - // EncodeFixed32 writes a 32-bit integer to the Buffer. // This is the format for the // fixed32, sfixed32, and float protocol buffer types. @@ -165,20 +165,12 @@ func (p *Buffer) EncodeFixed32(x uint64) error { return nil } -func sizeFixed32(x uint64) int { - return 4 -} - // EncodeZigzag64 writes a zigzag-encoded 64-bit integer // to the Buffer. // This is the format used for the sint64 protocol buffer type. func (p *Buffer) EncodeZigzag64(x uint64) error { // use signed number to get arithmetic right shift. - return p.EncodeVarint((x << 1) ^ uint64((int64(x) >> 63))) -} - -func sizeZigzag64(x uint64) int { - return sizeVarint((x << 1) ^ uint64((int64(x) >> 63))) + return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } // EncodeZigzag32 writes a zigzag-encoded 32-bit integer @@ -189,10 +181,6 @@ func (p *Buffer) EncodeZigzag32(x uint64) error { return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) } -func sizeZigzag32(x uint64) int { - return sizeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) -} - // EncodeRawBytes writes a count-delimited byte buffer to the Buffer. // This is the format used for the bytes protocol buffer // type and for embedded messages. @@ -202,11 +190,6 @@ func (p *Buffer) EncodeRawBytes(b []byte) error { return nil } -func sizeRawBytes(b []byte) int { - return sizeVarint(uint64(len(b))) + - len(b) -} - // EncodeStringBytes writes an encoded string to the Buffer. // This is the format used for the proto2 string type. func (p *Buffer) EncodeStringBytes(s string) error { @@ -215,319 +198,17 @@ func (p *Buffer) EncodeStringBytes(s string) error { return nil } -func sizeStringBytes(s string) int { - return sizeVarint(uint64(len(s))) + - len(s) -} - // Marshaler is the interface representing objects that can marshal themselves. type Marshaler interface { Marshal() ([]byte, error) } -// Marshal takes the protocol buffer -// and encodes it into the wire format, returning the data. -func Marshal(pb Message) ([]byte, error) { - // Can the object marshal itself? - if m, ok := pb.(Marshaler); ok { - return m.Marshal() - } - p := NewBuffer(nil) - err := p.Marshal(pb) - if p.buf == nil && err == nil { - // Return a non-nil slice on success. - return []byte{}, nil - } - return p.buf, err -} - // EncodeMessage writes the protocol buffer to the Buffer, // prefixed by a varint-encoded length. func (p *Buffer) EncodeMessage(pb Message) error { - t, base, err := getbase(pb) - if structPointer_IsNil(base) { - return ErrNil - } - if err == nil { - var state errorState - err = p.enc_len_struct(GetProperties(t.Elem()), base, &state) - } - return err -} - -// Marshal takes the protocol buffer -// and encodes it into the wire format, writing the result to the -// Buffer. -func (p *Buffer) Marshal(pb Message) error { - // Can the object marshal itself? - if m, ok := pb.(Marshaler); ok { - data, err := m.Marshal() - p.buf = append(p.buf, data...) - return err - } - - t, base, err := getbase(pb) - if structPointer_IsNil(base) { - return ErrNil - } - if err == nil { - err = p.enc_struct(GetProperties(t.Elem()), base) - } - - if collectStats { - (stats).Encode++ // Parens are to work around a goimports bug. - } - - if len(p.buf) > maxMarshalSize { - return ErrTooLarge - } - return err -} - -// Size returns the encoded size of a protocol buffer. -func Size(pb Message) (n int) { - // Can the object marshal itself? If so, Size is slow. - // TODO: add Size to Marshaler, or add a Sizer interface. - if m, ok := pb.(Marshaler); ok { - b, _ := m.Marshal() - return len(b) - } - - t, base, err := getbase(pb) - if structPointer_IsNil(base) { - return 0 - } - if err == nil { - n = size_struct(GetProperties(t.Elem()), base) - } - - if collectStats { - (stats).Size++ // Parens are to work around a goimports bug. - } - - return -} - -// Individual type encoders. - -// Encode a bool. -func (o *Buffer) enc_bool(p *Properties, base structPointer) error { - v := *structPointer_Bool(base, p.field) - if v == nil { - return ErrNil - } - x := 0 - if *v { - x = 1 - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func (o *Buffer) enc_proto3_bool(p *Properties, base structPointer) error { - v := *structPointer_BoolVal(base, p.field) - if !v { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, 1) - return nil -} - -func size_bool(p *Properties, base structPointer) int { - v := *structPointer_Bool(base, p.field) - if v == nil { - return 0 - } - return len(p.tagcode) + 1 // each bool takes exactly one byte -} - -func size_proto3_bool(p *Properties, base structPointer) int { - v := *structPointer_BoolVal(base, p.field) - if !v && !p.oneof { - return 0 - } - return len(p.tagcode) + 1 // each bool takes exactly one byte -} - -// Encode an int32. -func (o *Buffer) enc_int32(p *Properties, base structPointer) error { - v := structPointer_Word32(base, p.field) - if word32_IsNil(v) { - return ErrNil - } - x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func (o *Buffer) enc_proto3_int32(p *Properties, base structPointer) error { - v := structPointer_Word32Val(base, p.field) - x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range - if x == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func size_int32(p *Properties, base structPointer) (n int) { - v := structPointer_Word32(base, p.field) - if word32_IsNil(v) { - return 0 - } - x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range - n += len(p.tagcode) - n += p.valSize(uint64(x)) - return -} - -func size_proto3_int32(p *Properties, base structPointer) (n int) { - v := structPointer_Word32Val(base, p.field) - x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range - if x == 0 && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += p.valSize(uint64(x)) - return -} - -// Encode a uint32. -// Exactly the same as int32, except for no sign extension. -func (o *Buffer) enc_uint32(p *Properties, base structPointer) error { - v := structPointer_Word32(base, p.field) - if word32_IsNil(v) { - return ErrNil - } - x := word32_Get(v) - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func (o *Buffer) enc_proto3_uint32(p *Properties, base structPointer) error { - v := structPointer_Word32Val(base, p.field) - x := word32Val_Get(v) - if x == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func size_uint32(p *Properties, base structPointer) (n int) { - v := structPointer_Word32(base, p.field) - if word32_IsNil(v) { - return 0 - } - x := word32_Get(v) - n += len(p.tagcode) - n += p.valSize(uint64(x)) - return -} - -func size_proto3_uint32(p *Properties, base structPointer) (n int) { - v := structPointer_Word32Val(base, p.field) - x := word32Val_Get(v) - if x == 0 && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += p.valSize(uint64(x)) - return -} - -// Encode an int64. -func (o *Buffer) enc_int64(p *Properties, base structPointer) error { - v := structPointer_Word64(base, p.field) - if word64_IsNil(v) { - return ErrNil - } - x := word64_Get(v) - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, x) - return nil -} - -func (o *Buffer) enc_proto3_int64(p *Properties, base structPointer) error { - v := structPointer_Word64Val(base, p.field) - x := word64Val_Get(v) - if x == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, x) - return nil -} - -func size_int64(p *Properties, base structPointer) (n int) { - v := structPointer_Word64(base, p.field) - if word64_IsNil(v) { - return 0 - } - x := word64_Get(v) - n += len(p.tagcode) - n += p.valSize(x) - return -} - -func size_proto3_int64(p *Properties, base structPointer) (n int) { - v := structPointer_Word64Val(base, p.field) - x := word64Val_Get(v) - if x == 0 && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += p.valSize(x) - return -} - -// Encode a string. -func (o *Buffer) enc_string(p *Properties, base structPointer) error { - v := *structPointer_String(base, p.field) - if v == nil { - return ErrNil - } - x := *v - o.buf = append(o.buf, p.tagcode...) - o.EncodeStringBytes(x) - return nil -} - -func (o *Buffer) enc_proto3_string(p *Properties, base structPointer) error { - v := *structPointer_StringVal(base, p.field) - if v == "" { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeStringBytes(v) - return nil -} - -func size_string(p *Properties, base structPointer) (n int) { - v := *structPointer_String(base, p.field) - if v == nil { - return 0 - } - x := *v - n += len(p.tagcode) - n += sizeStringBytes(x) - return -} - -func size_proto3_string(p *Properties, base structPointer) (n int) { - v := *structPointer_StringVal(base, p.field) - if v == "" && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += sizeStringBytes(v) - return + siz := Size(pb) + p.EncodeVarint(uint64(siz)) + return p.Marshal(pb) } // All protocol buffer fields are nillable, but be careful. @@ -538,825 +219,3 @@ func isNil(v reflect.Value) bool { } return false } - -// Encode a message struct. -func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error { - var state errorState - structp := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(structp) { - return ErrNil - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, err := m.Marshal() - if err != nil && !state.shouldContinue(err, nil) { - return err - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - return state.err - } - - o.buf = append(o.buf, p.tagcode...) - return o.enc_len_struct(p.sprop, structp, &state) -} - -func size_struct_message(p *Properties, base structPointer) int { - structp := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(structp) { - return 0 - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, _ := m.Marshal() - n0 := len(p.tagcode) - n1 := sizeRawBytes(data) - return n0 + n1 - } - - n0 := len(p.tagcode) - n1 := size_struct(p.sprop, structp) - n2 := sizeVarint(uint64(n1)) // size of encoded length - return n0 + n1 + n2 -} - -// Encode a group struct. -func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error { - var state errorState - b := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(b) { - return ErrNil - } - - o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup)) - err := o.enc_struct(p.sprop, b) - if err != nil && !state.shouldContinue(err, nil) { - return err - } - o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup)) - return state.err -} - -func size_struct_group(p *Properties, base structPointer) (n int) { - b := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(b) { - return 0 - } - - n += sizeVarint(uint64((p.Tag << 3) | WireStartGroup)) - n += size_struct(p.sprop, b) - n += sizeVarint(uint64((p.Tag << 3) | WireEndGroup)) - return -} - -// Encode a slice of bools ([]bool). -func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error { - s := *structPointer_BoolSlice(base, p.field) - l := len(s) - if l == 0 { - return ErrNil - } - for _, x := range s { - o.buf = append(o.buf, p.tagcode...) - v := uint64(0) - if x { - v = 1 - } - p.valEnc(o, v) - } - return nil -} - -func size_slice_bool(p *Properties, base structPointer) int { - s := *structPointer_BoolSlice(base, p.field) - l := len(s) - if l == 0 { - return 0 - } - return l * (len(p.tagcode) + 1) // each bool takes exactly one byte -} - -// Encode a slice of bools ([]bool) in packed format. -func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error { - s := *structPointer_BoolSlice(base, p.field) - l := len(s) - if l == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeVarint(uint64(l)) // each bool takes exactly one byte - for _, x := range s { - v := uint64(0) - if x { - v = 1 - } - p.valEnc(o, v) - } - return nil -} - -func size_slice_packed_bool(p *Properties, base structPointer) (n int) { - s := *structPointer_BoolSlice(base, p.field) - l := len(s) - if l == 0 { - return 0 - } - n += len(p.tagcode) - n += sizeVarint(uint64(l)) - n += l // each bool takes exactly one byte - return -} - -// Encode a slice of bytes ([]byte). -func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error { - s := *structPointer_Bytes(base, p.field) - if s == nil { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(s) - return nil -} - -func (o *Buffer) enc_proto3_slice_byte(p *Properties, base structPointer) error { - s := *structPointer_Bytes(base, p.field) - if len(s) == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(s) - return nil -} - -func size_slice_byte(p *Properties, base structPointer) (n int) { - s := *structPointer_Bytes(base, p.field) - if s == nil && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += sizeRawBytes(s) - return -} - -func size_proto3_slice_byte(p *Properties, base structPointer) (n int) { - s := *structPointer_Bytes(base, p.field) - if len(s) == 0 && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += sizeRawBytes(s) - return -} - -// Encode a slice of int32s ([]int32). -func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - x := int32(s.Index(i)) // permit sign extension to use full 64-bit range - p.valEnc(o, uint64(x)) - } - return nil -} - -func size_slice_int32(p *Properties, base structPointer) (n int) { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - for i := 0; i < l; i++ { - n += len(p.tagcode) - x := int32(s.Index(i)) // permit sign extension to use full 64-bit range - n += p.valSize(uint64(x)) - } - return -} - -// Encode a slice of int32s ([]int32) in packed format. -func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - // TODO: Reuse a Buffer. - buf := NewBuffer(nil) - for i := 0; i < l; i++ { - x := int32(s.Index(i)) // permit sign extension to use full 64-bit range - p.valEnc(buf, uint64(x)) - } - - o.buf = append(o.buf, p.tagcode...) - o.EncodeVarint(uint64(len(buf.buf))) - o.buf = append(o.buf, buf.buf...) - return nil -} - -func size_slice_packed_int32(p *Properties, base structPointer) (n int) { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - var bufSize int - for i := 0; i < l; i++ { - x := int32(s.Index(i)) // permit sign extension to use full 64-bit range - bufSize += p.valSize(uint64(x)) - } - - n += len(p.tagcode) - n += sizeVarint(uint64(bufSize)) - n += bufSize - return -} - -// Encode a slice of uint32s ([]uint32). -// Exactly the same as int32, except for no sign extension. -func (o *Buffer) enc_slice_uint32(p *Properties, base structPointer) error { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - x := s.Index(i) - p.valEnc(o, uint64(x)) - } - return nil -} - -func size_slice_uint32(p *Properties, base structPointer) (n int) { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - for i := 0; i < l; i++ { - n += len(p.tagcode) - x := s.Index(i) - n += p.valSize(uint64(x)) - } - return -} - -// Encode a slice of uint32s ([]uint32) in packed format. -// Exactly the same as int32, except for no sign extension. -func (o *Buffer) enc_slice_packed_uint32(p *Properties, base structPointer) error { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - // TODO: Reuse a Buffer. - buf := NewBuffer(nil) - for i := 0; i < l; i++ { - p.valEnc(buf, uint64(s.Index(i))) - } - - o.buf = append(o.buf, p.tagcode...) - o.EncodeVarint(uint64(len(buf.buf))) - o.buf = append(o.buf, buf.buf...) - return nil -} - -func size_slice_packed_uint32(p *Properties, base structPointer) (n int) { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - var bufSize int - for i := 0; i < l; i++ { - bufSize += p.valSize(uint64(s.Index(i))) - } - - n += len(p.tagcode) - n += sizeVarint(uint64(bufSize)) - n += bufSize - return -} - -// Encode a slice of int64s ([]int64). -func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error { - s := structPointer_Word64Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, s.Index(i)) - } - return nil -} - -func size_slice_int64(p *Properties, base structPointer) (n int) { - s := structPointer_Word64Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - for i := 0; i < l; i++ { - n += len(p.tagcode) - n += p.valSize(s.Index(i)) - } - return -} - -// Encode a slice of int64s ([]int64) in packed format. -func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error { - s := structPointer_Word64Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - // TODO: Reuse a Buffer. - buf := NewBuffer(nil) - for i := 0; i < l; i++ { - p.valEnc(buf, s.Index(i)) - } - - o.buf = append(o.buf, p.tagcode...) - o.EncodeVarint(uint64(len(buf.buf))) - o.buf = append(o.buf, buf.buf...) - return nil -} - -func size_slice_packed_int64(p *Properties, base structPointer) (n int) { - s := structPointer_Word64Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - var bufSize int - for i := 0; i < l; i++ { - bufSize += p.valSize(s.Index(i)) - } - - n += len(p.tagcode) - n += sizeVarint(uint64(bufSize)) - n += bufSize - return -} - -// Encode a slice of slice of bytes ([][]byte). -func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error { - ss := *structPointer_BytesSlice(base, p.field) - l := len(ss) - if l == 0 { - return ErrNil - } - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(ss[i]) - } - return nil -} - -func size_slice_slice_byte(p *Properties, base structPointer) (n int) { - ss := *structPointer_BytesSlice(base, p.field) - l := len(ss) - if l == 0 { - return 0 - } - n += l * len(p.tagcode) - for i := 0; i < l; i++ { - n += sizeRawBytes(ss[i]) - } - return -} - -// Encode a slice of strings ([]string). -func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error { - ss := *structPointer_StringSlice(base, p.field) - l := len(ss) - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - o.EncodeStringBytes(ss[i]) - } - return nil -} - -func size_slice_string(p *Properties, base structPointer) (n int) { - ss := *structPointer_StringSlice(base, p.field) - l := len(ss) - n += l * len(p.tagcode) - for i := 0; i < l; i++ { - n += sizeStringBytes(ss[i]) - } - return -} - -// Encode a slice of message structs ([]*struct). -func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error { - var state errorState - s := structPointer_StructPointerSlice(base, p.field) - l := s.Len() - - for i := 0; i < l; i++ { - structp := s.Index(i) - if structPointer_IsNil(structp) { - return errRepeatedHasNil - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, err := m.Marshal() - if err != nil && !state.shouldContinue(err, nil) { - return err - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - continue - } - - o.buf = append(o.buf, p.tagcode...) - err := o.enc_len_struct(p.sprop, structp, &state) - if err != nil && !state.shouldContinue(err, nil) { - if err == ErrNil { - return errRepeatedHasNil - } - return err - } - } - return state.err -} - -func size_slice_struct_message(p *Properties, base structPointer) (n int) { - s := structPointer_StructPointerSlice(base, p.field) - l := s.Len() - n += l * len(p.tagcode) - for i := 0; i < l; i++ { - structp := s.Index(i) - if structPointer_IsNil(structp) { - return // return the size up to this point - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, _ := m.Marshal() - n += sizeRawBytes(data) - continue - } - - n0 := size_struct(p.sprop, structp) - n1 := sizeVarint(uint64(n0)) // size of encoded length - n += n0 + n1 - } - return -} - -// Encode a slice of group structs ([]*struct). -func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error { - var state errorState - s := structPointer_StructPointerSlice(base, p.field) - l := s.Len() - - for i := 0; i < l; i++ { - b := s.Index(i) - if structPointer_IsNil(b) { - return errRepeatedHasNil - } - - o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup)) - - err := o.enc_struct(p.sprop, b) - - if err != nil && !state.shouldContinue(err, nil) { - if err == ErrNil { - return errRepeatedHasNil - } - return err - } - - o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup)) - } - return state.err -} - -func size_slice_struct_group(p *Properties, base structPointer) (n int) { - s := structPointer_StructPointerSlice(base, p.field) - l := s.Len() - - n += l * sizeVarint(uint64((p.Tag<<3)|WireStartGroup)) - n += l * sizeVarint(uint64((p.Tag<<3)|WireEndGroup)) - for i := 0; i < l; i++ { - b := s.Index(i) - if structPointer_IsNil(b) { - return // return size up to this point - } - - n += size_struct(p.sprop, b) - } - return -} - -// Encode an extension map. -func (o *Buffer) enc_map(p *Properties, base structPointer) error { - exts := structPointer_ExtMap(base, p.field) - if err := encodeExtensionsMap(*exts); err != nil { - return err - } - - return o.enc_map_body(*exts) -} - -func (o *Buffer) enc_exts(p *Properties, base structPointer) error { - exts := structPointer_Extensions(base, p.field) - - v, mu := exts.extensionsRead() - if v == nil { - return nil - } - - mu.Lock() - defer mu.Unlock() - if err := encodeExtensionsMap(v); err != nil { - return err - } - - return o.enc_map_body(v) -} - -func (o *Buffer) enc_map_body(v map[int32]Extension) error { - // Fast-path for common cases: zero or one extensions. - if len(v) <= 1 { - for _, e := range v { - o.buf = append(o.buf, e.enc...) - } - return nil - } - - // Sort keys to provide a deterministic encoding. - keys := make([]int, 0, len(v)) - for k := range v { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - for _, k := range keys { - o.buf = append(o.buf, v[int32(k)].enc...) - } - return nil -} - -func size_map(p *Properties, base structPointer) int { - v := structPointer_ExtMap(base, p.field) - return extensionsMapSize(*v) -} - -func size_exts(p *Properties, base structPointer) int { - v := structPointer_Extensions(base, p.field) - return extensionsSize(v) -} - -// Encode a map field. -func (o *Buffer) enc_new_map(p *Properties, base structPointer) error { - var state errorState // XXX: or do we need to plumb this through? - - /* - A map defined as - map map_field = N; - is encoded in the same way as - message MapFieldEntry { - key_type key = 1; - value_type value = 2; - } - repeated MapFieldEntry map_field = N; - */ - - v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V - if v.Len() == 0 { - return nil - } - - keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype) - - enc := func() error { - if err := p.mkeyprop.enc(o, p.mkeyprop, keybase); err != nil { - return err - } - if err := p.mvalprop.enc(o, p.mvalprop, valbase); err != nil && err != ErrNil { - return err - } - return nil - } - - // Don't sort map keys. It is not required by the spec, and C++ doesn't do it. - for _, key := range v.MapKeys() { - val := v.MapIndex(key) - - keycopy.Set(key) - valcopy.Set(val) - - o.buf = append(o.buf, p.tagcode...) - if err := o.enc_len_thing(enc, &state); err != nil { - return err - } - } - return nil -} - -func size_new_map(p *Properties, base structPointer) int { - v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V - - keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype) - - n := 0 - for _, key := range v.MapKeys() { - val := v.MapIndex(key) - keycopy.Set(key) - valcopy.Set(val) - - // Tag codes for key and val are the responsibility of the sub-sizer. - keysize := p.mkeyprop.size(p.mkeyprop, keybase) - valsize := p.mvalprop.size(p.mvalprop, valbase) - entry := keysize + valsize - // Add on tag code and length of map entry itself. - n += len(p.tagcode) + sizeVarint(uint64(entry)) + entry - } - return n -} - -// mapEncodeScratch returns a new reflect.Value matching the map's value type, -// and a structPointer suitable for passing to an encoder or sizer. -func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) { - // Prepare addressable doubly-indirect placeholders for the key and value types. - // This is needed because the element-type encoders expect **T, but the map iteration produces T. - - keycopy = reflect.New(mapType.Key()).Elem() // addressable K - keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K - keyptr.Set(keycopy.Addr()) // - keybase = toStructPointer(keyptr.Addr()) // **K - - // Value types are more varied and require special handling. - switch mapType.Elem().Kind() { - case reflect.Slice: - // []byte - var dummy []byte - valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte - valbase = toStructPointer(valcopy.Addr()) - case reflect.Ptr: - // message; the generated field type is map[K]*Msg (so V is *Msg), - // so we only need one level of indirection. - valcopy = reflect.New(mapType.Elem()).Elem() // addressable V - valbase = toStructPointer(valcopy.Addr()) - default: - // everything else - valcopy = reflect.New(mapType.Elem()).Elem() // addressable V - valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V - valptr.Set(valcopy.Addr()) // - valbase = toStructPointer(valptr.Addr()) // **V - } - return -} - -// Encode a struct. -func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error { - var state errorState - // Encode fields in tag order so that decoders may use optimizations - // that depend on the ordering. - // https://developers.google.com/protocol-buffers/docs/encoding#order - for _, i := range prop.order { - p := prop.Prop[i] - if p.enc != nil { - err := p.enc(o, p, base) - if err != nil { - if err == ErrNil { - if p.Required && state.err == nil { - state.err = &RequiredNotSetError{p.Name} - } - } else if err == errRepeatedHasNil { - // Give more context to nil values in repeated fields. - return errors.New("repeated field " + p.OrigName + " has nil element") - } else if !state.shouldContinue(err, p) { - return err - } - } - if len(o.buf) > maxMarshalSize { - return ErrTooLarge - } - } - } - - // Do oneof fields. - if prop.oneofMarshaler != nil { - m := structPointer_Interface(base, prop.stype).(Message) - if err := prop.oneofMarshaler(m, o); err == ErrNil { - return errOneofHasNil - } else if err != nil { - return err - } - } - - // Add unrecognized fields at the end. - if prop.unrecField.IsValid() { - v := *structPointer_Bytes(base, prop.unrecField) - if len(o.buf)+len(v) > maxMarshalSize { - return ErrTooLarge - } - if len(v) > 0 { - o.buf = append(o.buf, v...) - } - } - - return state.err -} - -func size_struct(prop *StructProperties, base structPointer) (n int) { - for _, i := range prop.order { - p := prop.Prop[i] - if p.size != nil { - n += p.size(p, base) - } - } - - // Add unrecognized fields at the end. - if prop.unrecField.IsValid() { - v := *structPointer_Bytes(base, prop.unrecField) - n += len(v) - } - - // Factor in any oneof fields. - if prop.oneofSizer != nil { - m := structPointer_Interface(base, prop.stype).(Message) - n += prop.oneofSizer(m) - } - - return -} - -var zeroes [20]byte // longer than any conceivable sizeVarint - -// Encode a struct, preceded by its encoded length (as a varint). -func (o *Buffer) enc_len_struct(prop *StructProperties, base structPointer, state *errorState) error { - return o.enc_len_thing(func() error { return o.enc_struct(prop, base) }, state) -} - -// Encode something, preceded by its encoded length (as a varint). -func (o *Buffer) enc_len_thing(enc func() error, state *errorState) error { - iLen := len(o.buf) - o.buf = append(o.buf, 0, 0, 0, 0) // reserve four bytes for length - iMsg := len(o.buf) - err := enc() - if err != nil && !state.shouldContinue(err, nil) { - return err - } - lMsg := len(o.buf) - iMsg - lLen := sizeVarint(uint64(lMsg)) - switch x := lLen - (iMsg - iLen); { - case x > 0: // actual length is x bytes larger than the space we reserved - // Move msg x bytes right. - o.buf = append(o.buf, zeroes[:x]...) - copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg]) - case x < 0: // actual length is x bytes smaller than the space we reserved - // Move msg x bytes left. - copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg]) - o.buf = o.buf[:len(o.buf)+x] // x is negative - } - // Encode the length in the reserved space. - o.buf = o.buf[:iLen] - o.EncodeVarint(uint64(lMsg)) - o.buf = o.buf[:len(o.buf)+lMsg] - return state.err -} - -// errorState maintains the first error that occurs and updates that error -// with additional context. -type errorState struct { - err error -} - -// shouldContinue reports whether encoding should continue upon encountering the -// given error. If the error is RequiredNotSetError, shouldContinue returns true -// and, if this is the first appearance of that error, remembers it for future -// reporting. -// -// If prop is not nil, it may update any error with additional context about the -// field with the error. -func (s *errorState) shouldContinue(err error, prop *Properties) bool { - // Ignore unset required fields. - reqNotSet, ok := err.(*RequiredNotSetError) - if !ok { - return false - } - if s.err == nil { - if prop != nil { - err = &RequiredNotSetError{prop.Name + "." + reqNotSet.field} - } - s.err = err - } - return true -} diff --git a/vendor/github.com/gogo/protobuf/proto/encode_gogo.go b/vendor/github.com/gogo/protobuf/proto/encode_gogo.go index 32111b7f4..0f5fb173e 100644 --- a/vendor/github.com/gogo/protobuf/proto/encode_gogo.go +++ b/vendor/github.com/gogo/protobuf/proto/encode_gogo.go @@ -3,11 +3,6 @@ // Copyright (c) 2013, The GoGo Authors. All rights reserved. // http://github.com/gogo/protobuf // -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// http://github.com/golang/protobuf/ -// // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: @@ -18,9 +13,6 @@ // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT @@ -36,315 +28,6 @@ package proto -import ( - "reflect" -) - func NewRequiredNotSetError(field string) *RequiredNotSetError { return &RequiredNotSetError{field} } - -type Sizer interface { - Size() int -} - -func (o *Buffer) enc_ext_slice_byte(p *Properties, base structPointer) error { - s := *structPointer_Bytes(base, p.field) - if s == nil { - return ErrNil - } - o.buf = append(o.buf, s...) - return nil -} - -func size_ext_slice_byte(p *Properties, base structPointer) (n int) { - s := *structPointer_Bytes(base, p.field) - if s == nil { - return 0 - } - n += len(s) - return -} - -// Encode a reference to bool pointer. -func (o *Buffer) enc_ref_bool(p *Properties, base structPointer) error { - v := *structPointer_BoolVal(base, p.field) - x := 0 - if v { - x = 1 - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func size_ref_bool(p *Properties, base structPointer) int { - return len(p.tagcode) + 1 // each bool takes exactly one byte -} - -// Encode a reference to int32 pointer. -func (o *Buffer) enc_ref_int32(p *Properties, base structPointer) error { - v := structPointer_Word32Val(base, p.field) - x := int32(word32Val_Get(v)) - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func size_ref_int32(p *Properties, base structPointer) (n int) { - v := structPointer_Word32Val(base, p.field) - x := int32(word32Val_Get(v)) - n += len(p.tagcode) - n += p.valSize(uint64(x)) - return -} - -func (o *Buffer) enc_ref_uint32(p *Properties, base structPointer) error { - v := structPointer_Word32Val(base, p.field) - x := word32Val_Get(v) - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func size_ref_uint32(p *Properties, base structPointer) (n int) { - v := structPointer_Word32Val(base, p.field) - x := word32Val_Get(v) - n += len(p.tagcode) - n += p.valSize(uint64(x)) - return -} - -// Encode a reference to an int64 pointer. -func (o *Buffer) enc_ref_int64(p *Properties, base structPointer) error { - v := structPointer_Word64Val(base, p.field) - x := word64Val_Get(v) - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, x) - return nil -} - -func size_ref_int64(p *Properties, base structPointer) (n int) { - v := structPointer_Word64Val(base, p.field) - x := word64Val_Get(v) - n += len(p.tagcode) - n += p.valSize(x) - return -} - -// Encode a reference to a string pointer. -func (o *Buffer) enc_ref_string(p *Properties, base structPointer) error { - v := *structPointer_StringVal(base, p.field) - o.buf = append(o.buf, p.tagcode...) - o.EncodeStringBytes(v) - return nil -} - -func size_ref_string(p *Properties, base structPointer) (n int) { - v := *structPointer_StringVal(base, p.field) - n += len(p.tagcode) - n += sizeStringBytes(v) - return -} - -// Encode a reference to a message struct. -func (o *Buffer) enc_ref_struct_message(p *Properties, base structPointer) error { - var state errorState - structp := structPointer_GetRefStructPointer(base, p.field) - if structPointer_IsNil(structp) { - return ErrNil - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, err := m.Marshal() - if err != nil && !state.shouldContinue(err, nil) { - return err - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - return nil - } - - o.buf = append(o.buf, p.tagcode...) - return o.enc_len_struct(p.sprop, structp, &state) -} - -//TODO this is only copied, please fix this -func size_ref_struct_message(p *Properties, base structPointer) int { - structp := structPointer_GetRefStructPointer(base, p.field) - if structPointer_IsNil(structp) { - return 0 - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, _ := m.Marshal() - n0 := len(p.tagcode) - n1 := sizeRawBytes(data) - return n0 + n1 - } - - n0 := len(p.tagcode) - n1 := size_struct(p.sprop, structp) - n2 := sizeVarint(uint64(n1)) // size of encoded length - return n0 + n1 + n2 -} - -// Encode a slice of references to message struct pointers ([]struct). -func (o *Buffer) enc_slice_ref_struct_message(p *Properties, base structPointer) error { - var state errorState - ss := structPointer_StructRefSlice(base, p.field, p.stype.Size()) - l := ss.Len() - for i := 0; i < l; i++ { - structp := ss.Index(i) - if structPointer_IsNil(structp) { - return errRepeatedHasNil - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, err := m.Marshal() - if err != nil && !state.shouldContinue(err, nil) { - return err - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - continue - } - - o.buf = append(o.buf, p.tagcode...) - err := o.enc_len_struct(p.sprop, structp, &state) - if err != nil && !state.shouldContinue(err, nil) { - if err == ErrNil { - return errRepeatedHasNil - } - return err - } - - } - return state.err -} - -//TODO this is only copied, please fix this -func size_slice_ref_struct_message(p *Properties, base structPointer) (n int) { - ss := structPointer_StructRefSlice(base, p.field, p.stype.Size()) - l := ss.Len() - n += l * len(p.tagcode) - for i := 0; i < l; i++ { - structp := ss.Index(i) - if structPointer_IsNil(structp) { - return // return the size up to this point - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, _ := m.Marshal() - n += len(p.tagcode) - n += sizeRawBytes(data) - continue - } - - n0 := size_struct(p.sprop, structp) - n1 := sizeVarint(uint64(n0)) // size of encoded length - n += n0 + n1 - } - return -} - -func (o *Buffer) enc_custom_bytes(p *Properties, base structPointer) error { - i := structPointer_InterfaceRef(base, p.field, p.ctype) - if i == nil { - return ErrNil - } - custom := i.(Marshaler) - data, err := custom.Marshal() - if err != nil { - return err - } - if data == nil { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - return nil -} - -func size_custom_bytes(p *Properties, base structPointer) (n int) { - n += len(p.tagcode) - i := structPointer_InterfaceRef(base, p.field, p.ctype) - if i == nil { - return 0 - } - custom := i.(Marshaler) - data, _ := custom.Marshal() - n += sizeRawBytes(data) - return -} - -func (o *Buffer) enc_custom_ref_bytes(p *Properties, base structPointer) error { - custom := structPointer_InterfaceAt(base, p.field, p.ctype).(Marshaler) - data, err := custom.Marshal() - if err != nil { - return err - } - if data == nil { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - return nil -} - -func size_custom_ref_bytes(p *Properties, base structPointer) (n int) { - n += len(p.tagcode) - i := structPointer_InterfaceAt(base, p.field, p.ctype) - if i == nil { - return 0 - } - custom := i.(Marshaler) - data, _ := custom.Marshal() - n += sizeRawBytes(data) - return -} - -func (o *Buffer) enc_custom_slice_bytes(p *Properties, base structPointer) error { - inter := structPointer_InterfaceRef(base, p.field, p.ctype) - if inter == nil { - return ErrNil - } - slice := reflect.ValueOf(inter) - l := slice.Len() - for i := 0; i < l; i++ { - v := slice.Index(i) - custom := v.Interface().(Marshaler) - data, err := custom.Marshal() - if err != nil { - return err - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - } - return nil -} - -func size_custom_slice_bytes(p *Properties, base structPointer) (n int) { - inter := structPointer_InterfaceRef(base, p.field, p.ctype) - if inter == nil { - return 0 - } - slice := reflect.ValueOf(inter) - l := slice.Len() - n += l * len(p.tagcode) - for i := 0; i < l; i++ { - v := slice.Index(i) - custom := v.Interface().(Marshaler) - data, _ := custom.Marshal() - n += sizeRawBytes(data) - } - return -} diff --git a/vendor/github.com/gogo/protobuf/proto/equal.go b/vendor/github.com/gogo/protobuf/proto/equal.go index 2ed1cf596..d4db5a1c1 100644 --- a/vendor/github.com/gogo/protobuf/proto/equal.go +++ b/vendor/github.com/gogo/protobuf/proto/equal.go @@ -109,15 +109,6 @@ func equalStruct(v1, v2 reflect.Value) bool { // set/unset mismatch return false } - b1, ok := f1.Interface().(raw) - if ok { - b2 := f2.Interface().(raw) - // RawMessage - if !bytes.Equal(b1.Bytes(), b2.Bytes()) { - return false - } - continue - } f1, f2 = f1.Elem(), f2.Elem() } if !equalAny(f1, f2, sprop.Prop[i]) { @@ -146,11 +137,7 @@ func equalStruct(v1, v2 reflect.Value) bool { u1 := uf.Bytes() u2 := v2.FieldByName("XXX_unrecognized").Bytes() - if !bytes.Equal(u1, u2) { - return false - } - - return true + return bytes.Equal(u1, u2) } // v1 and v2 are known to have the same type. @@ -261,6 +248,15 @@ func equalExtMap(base reflect.Type, em1, em2 map[int32]Extension) bool { m1, m2 := e1.value, e2.value + if m1 == nil && m2 == nil { + // Both have only encoded form. + if bytes.Equal(e1.enc, e2.enc) { + continue + } + // The bytes are different, but the extensions might still be + // equal. We need to decode them to compare. + } + if m1 != nil && m2 != nil { // Both are unencoded. if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { @@ -276,8 +272,12 @@ func equalExtMap(base reflect.Type, em1, em2 map[int32]Extension) bool { desc = m[extNum] } if desc == nil { + // If both have only encoded form and the bytes are the same, + // it is handled above. We get here when the bytes are different. + // We don't know how to decode it, so just compare them as byte + // slices. log.Printf("proto: don't know how to compare extension %d of %v", extNum, base) - continue + return false } var err error if m1 == nil { diff --git a/vendor/github.com/gogo/protobuf/proto/extensions.go b/vendor/github.com/gogo/protobuf/proto/extensions.go index 0dfcb538e..44ebd457c 100644 --- a/vendor/github.com/gogo/protobuf/proto/extensions.go +++ b/vendor/github.com/gogo/protobuf/proto/extensions.go @@ -38,6 +38,7 @@ package proto import ( "errors" "fmt" + "io" "reflect" "strconv" "sync" @@ -69,12 +70,6 @@ type extendableProtoV1 interface { ExtensionMap() map[int32]Extension } -type extensionsBytes interface { - Message - ExtensionRangeArray() []ExtensionRange - GetExtensions() *[]byte -} - // extensionAdapter is a wrapper around extendableProtoV1 that implements extendableProto. type extensionAdapter struct { extendableProtoV1 @@ -97,14 +92,31 @@ func (n notLocker) Unlock() {} // extendable returns the extendableProto interface for the given generated proto message. // If the proto message has the old extension format, it returns a wrapper that implements // the extendableProto interface. -func extendable(p interface{}) (extendableProto, bool) { - if ep, ok := p.(extendableProto); ok { - return ep, ok - } - if ep, ok := p.(extendableProtoV1); ok { - return extensionAdapter{ep}, ok +func extendable(p interface{}) (extendableProto, error) { + switch p := p.(type) { + case extendableProto: + if isNilPtr(p) { + return nil, fmt.Errorf("proto: nil %T is not extendable", p) + } + return p, nil + case extendableProtoV1: + if isNilPtr(p) { + return nil, fmt.Errorf("proto: nil %T is not extendable", p) + } + return extensionAdapter{p}, nil + case extensionsBytes: + return slowExtensionAdapter{p}, nil } - return nil, false + // Don't allocate a specific error containing %T: + // this is the hot path for Clone and MarshalText. + return nil, errNotExtendable +} + +var errNotExtendable = errors.New("proto: not an extendable proto.Message") + +func isNilPtr(x interface{}) bool { + v := reflect.ValueOf(x) + return v.Kind() == reflect.Ptr && v.IsNil() } // XXX_InternalExtensions is an internal representation of proto extensions. @@ -149,16 +161,6 @@ func (e *XXX_InternalExtensions) extensionsRead() (map[int32]Extension, sync.Loc return e.p.extensionMap, &e.p.mu } -type extensionRange interface { - Message - ExtensionRangeArray() []ExtensionRange -} - -var extendableProtoType = reflect.TypeOf((*extendableProto)(nil)).Elem() -var extendableProtoV1Type = reflect.TypeOf((*extendableProtoV1)(nil)).Elem() -var extendableBytesType = reflect.TypeOf((*extensionsBytes)(nil)).Elem() -var extensionRangeType = reflect.TypeOf((*extensionRange)(nil)).Elem() - // ExtensionDesc represents an extension specification. // Used in generated code from the protocol compiler. type ExtensionDesc struct { @@ -198,8 +200,8 @@ func SetRawExtension(base Message, id int32, b []byte) { *ext = append(*ext, b...) return } - epb, ok := extendable(base) - if !ok { + epb, err := extendable(base) + if err != nil { return } extmap := epb.extensionsWrite() @@ -207,7 +209,7 @@ func SetRawExtension(base Message, id int32, b []byte) { } // isExtensionField returns true iff the given field number is in an extension range. -func isExtensionField(pb extensionRange, field int32) bool { +func isExtensionField(pb extendableProto, field int32) bool { for _, er := range pb.ExtensionRangeArray() { if er.Start <= field && field <= er.End { return true @@ -223,8 +225,11 @@ func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error { if ea, ok := pbi.(extensionAdapter); ok { pbi = ea.extendableProtoV1 } + if ea, ok := pbi.(slowExtensionAdapter); ok { + pbi = ea.extensionsBytes + } if a, b := reflect.TypeOf(pbi), reflect.TypeOf(extension.ExtendedType); a != b { - return errors.New("proto: bad extended type; " + b.String() + " does not extend " + a.String()) + return fmt.Errorf("proto: bad extended type; %v does not extend %v", b, a) } // Check the range. if !isExtensionField(pb, extension.Field) { @@ -269,80 +274,6 @@ func extensionProperties(ed *ExtensionDesc) *Properties { return prop } -// encode encodes any unmarshaled (unencoded) extensions in e. -func encodeExtensions(e *XXX_InternalExtensions) error { - m, mu := e.extensionsRead() - if m == nil { - return nil // fast path - } - mu.Lock() - defer mu.Unlock() - return encodeExtensionsMap(m) -} - -// encode encodes any unmarshaled (unencoded) extensions in e. -func encodeExtensionsMap(m map[int32]Extension) error { - for k, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - et := reflect.TypeOf(e.desc.ExtensionType) - props := extensionProperties(e.desc) - - p := NewBuffer(nil) - // If e.value has type T, the encoder expects a *struct{ X T }. - // Pass a *T with a zero field and hope it all works out. - x := reflect.New(et) - x.Elem().Set(reflect.ValueOf(e.value)) - if err := props.enc(p, props, toStructPointer(x)); err != nil { - return err - } - e.enc = p.buf - m[k] = e - } - return nil -} - -func extensionsSize(e *XXX_InternalExtensions) (n int) { - m, mu := e.extensionsRead() - if m == nil { - return 0 - } - mu.Lock() - defer mu.Unlock() - return extensionsMapSize(m) -} - -func extensionsMapSize(m map[int32]Extension) (n int) { - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - n += len(e.enc) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - et := reflect.TypeOf(e.desc.ExtensionType) - props := extensionProperties(e.desc) - - // If e.value has type T, the encoder expects a *struct{ X T }. - // Pass a *T with a zero field and hope it all works out. - x := reflect.New(et) - x.Elem().Set(reflect.ValueOf(e.value)) - n += props.size(props, toStructPointer(x)) - } - return -} - // HasExtension returns whether the given extension is present in pb. func HasExtension(pb Message, extension *ExtensionDesc) bool { if epb, doki := pb.(extensionsBytes); doki { @@ -366,8 +297,8 @@ func HasExtension(pb Message, extension *ExtensionDesc) bool { return false } // TODO: Check types, field numbers, etc.? - epb, ok := extendable(pb) - if !ok { + epb, err := extendable(pb) + if err != nil { return false } extmap, mu := epb.extensionsRead() @@ -375,46 +306,26 @@ func HasExtension(pb Message, extension *ExtensionDesc) bool { return false } mu.Lock() - _, ok = extmap[extension.Field] + _, ok := extmap[extension.Field] mu.Unlock() return ok } -func deleteExtension(pb extensionsBytes, theFieldNum int32, offset int) int { - ext := pb.GetExtensions() - for offset < len(*ext) { - tag, n1 := DecodeVarint((*ext)[offset:]) - fieldNum := int32(tag >> 3) - wireType := int(tag & 0x7) - n2, err := size((*ext)[offset+n1:], wireType) - if err != nil { - panic(err) - } - newOffset := offset + n1 + n2 - if fieldNum == theFieldNum { - *ext = append((*ext)[:offset], (*ext)[newOffset:]...) - return offset - } - offset = newOffset - } - return -1 -} - // ClearExtension removes the given extension from pb. func ClearExtension(pb Message, extension *ExtensionDesc) { clearExtension(pb, extension.Field) } func clearExtension(pb Message, fieldNum int32) { - if epb, doki := pb.(extensionsBytes); doki { + if epb, ok := pb.(extensionsBytes); ok { offset := 0 for offset != -1 { offset = deleteExtension(epb, fieldNum, offset) } return } - epb, ok := extendable(pb) - if !ok { + epb, err := extendable(pb) + if err != nil { return } // TODO: Check types, field numbers, etc.? @@ -422,39 +333,33 @@ func clearExtension(pb Message, fieldNum int32) { delete(extmap, fieldNum) } -// GetExtension parses and returns the given extension of pb. -// If the extension is not present and has no default value it returns ErrMissingExtension. +// GetExtension retrieves a proto2 extended field from pb. +// +// If the descriptor is type complete (i.e., ExtensionDesc.ExtensionType is non-nil), +// then GetExtension parses the encoded field and returns a Go value of the specified type. +// If the field is not present, then the default value is returned (if one is specified), +// otherwise ErrMissingExtension is reported. +// +// If the descriptor is not type complete (i.e., ExtensionDesc.ExtensionType is nil), +// then GetExtension returns the raw encoded bytes of the field extension. func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) { if epb, doki := pb.(extensionsBytes); doki { ext := epb.GetExtensions() - o := 0 - for o < len(*ext) { - tag, n := DecodeVarint((*ext)[o:]) - fieldNum := int32(tag >> 3) - wireType := int(tag & 0x7) - l, err := size((*ext)[o+n:], wireType) - if err != nil { - return nil, err - } - if int32(fieldNum) == extension.Field { - v, err := decodeExtension((*ext)[o:o+n+l], extension) - if err != nil { - return nil, err - } - return v, nil - } - o += n + l - } - return defaultExtensionValue(extension) + return decodeExtensionFromBytes(extension, *ext) } - epb, ok := extendable(pb) - if !ok { - return nil, errors.New("proto: not an extendable proto") - } - if err := checkExtensionTypes(epb, extension); err != nil { + + epb, err := extendable(pb) + if err != nil { return nil, err } + if extension.ExtendedType != nil { + // can only check type if this is a complete descriptor + if cerr := checkExtensionTypes(epb, extension); cerr != nil { + return nil, cerr + } + } + emap, mu := epb.extensionsRead() if emap == nil { return defaultExtensionValue(extension) @@ -479,6 +384,11 @@ func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) { return e.value, nil } + if extension.ExtensionType == nil { + // incomplete descriptor + return e.enc, nil + } + v, err := decodeExtension(e.enc, extension) if err != nil { return nil, err @@ -496,6 +406,11 @@ func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) { // defaultExtensionValue returns the default value for extension. // If no default for an extension is defined ErrMissingExtension is returned. func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) { + if extension.ExtensionType == nil { + // incomplete descriptor, so no default + return nil, ErrMissingExtension + } + t := reflect.TypeOf(extension.ExtensionType) props := extensionProperties(extension) @@ -530,31 +445,28 @@ func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) { // decodeExtension decodes an extension encoded in b. func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) { - o := NewBuffer(b) - t := reflect.TypeOf(extension.ExtensionType) - - props := extensionProperties(extension) + unmarshal := typeUnmarshaler(t, extension.Tag) // t is a pointer to a struct, pointer to basic type or a slice. - // Allocate a "field" to store the pointer/slice itself; the - // pointer/slice will be stored here. We pass - // the address of this field to props.dec. - // This passes a zero field and a *t and lets props.dec - // interpret it as a *struct{ x t }. + // Allocate space to store the pointer/slice. value := reflect.New(t).Elem() + var err error for { - // Discard wire type and field number varint. It isn't needed. - if _, err := o.DecodeVarint(); err != nil { - return nil, err + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF } + b = b[n:] + wire := int(x) & 7 - if err := props.dec(o, props, toStructPointer(value.Addr())); err != nil { + b, err = unmarshal(b, valToPointer(value.Addr()), wire) + if err != nil { return nil, err } - if o.index >= len(o.buf) { + if len(b) == 0 { break } } @@ -564,9 +476,13 @@ func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) { // GetExtensions returns a slice of the extensions present in pb that are also listed in es. // The returned slice has the same length as es; missing extensions will appear as nil elements. func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) { + epb, err := extendable(pb) + if err != nil { + return nil, err + } extensions = make([]interface{}, len(es)) for i, e := range es { - extensions[i], err = GetExtension(pb, e) + extensions[i], err = GetExtension(epb, e) if err == ErrMissingExtension { err = nil } @@ -581,9 +497,9 @@ func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, e // For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing // just the Field field, which defines the extension's field number. func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) { - epb, ok := extendable(pb) - if !ok { - return nil, fmt.Errorf("proto: %T is not an extendable proto.Message", pb) + epb, err := extendable(pb) + if err != nil { + return nil, err } registeredExtensions := RegisteredExtensions(pb) @@ -610,23 +526,18 @@ func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) { // SetExtension sets the specified extension of pb to the specified value. func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error { - if epb, doki := pb.(extensionsBytes); doki { - ClearExtension(pb, extension) - ext := epb.GetExtensions() - et := reflect.TypeOf(extension.ExtensionType) - props := extensionProperties(extension) - p := NewBuffer(nil) - x := reflect.New(et) - x.Elem().Set(reflect.ValueOf(value)) - if err := props.enc(p, props, toStructPointer(x)); err != nil { + if epb, ok := pb.(extensionsBytes); ok { + newb, err := encodeExtension(extension, value) + if err != nil { return err } - *ext = append(*ext, p.buf...) + bb := epb.GetExtensions() + *bb = append(*bb, newb...) return nil } - epb, ok := extendable(pb) - if !ok { - return errors.New("proto: not an extendable proto") + epb, err := extendable(pb) + if err != nil { + return err } if err := checkExtensionTypes(epb, extension); err != nil { return err @@ -656,8 +567,8 @@ func ClearAllExtensions(pb Message) { *ext = []byte{} return } - epb, ok := extendable(pb) - if !ok { + epb, err := extendable(pb) + if err != nil { return } m := epb.extensionsWrite() diff --git a/vendor/github.com/gogo/protobuf/proto/extensions_gogo.go b/vendor/github.com/gogo/protobuf/proto/extensions_gogo.go index ea6478f00..53ebd8cca 100644 --- a/vendor/github.com/gogo/protobuf/proto/extensions_gogo.go +++ b/vendor/github.com/gogo/protobuf/proto/extensions_gogo.go @@ -32,12 +32,36 @@ import ( "bytes" "errors" "fmt" + "io" "reflect" "sort" "strings" "sync" ) +type extensionsBytes interface { + Message + ExtensionRangeArray() []ExtensionRange + GetExtensions() *[]byte +} + +type slowExtensionAdapter struct { + extensionsBytes +} + +func (s slowExtensionAdapter) extensionsWrite() map[int32]Extension { + panic("Please report a bug to github.com/gogo/protobuf if you see this message: Writing extensions is not supported for extensions stored in a byte slice field.") +} + +func (s slowExtensionAdapter) extensionsRead() (map[int32]Extension, sync.Locker) { + b := s.GetExtensions() + m, err := BytesToExtensionsMap(*b) + if err != nil { + panic(err) + } + return m, notLocker{} +} + func GetBoolExtension(pb Message, extension *ExtensionDesc, ifnotset bool) bool { if reflect.ValueOf(pb).IsNil() { return ifnotset @@ -56,19 +80,28 @@ func GetBoolExtension(pb Message, extension *ExtensionDesc, ifnotset bool) bool } func (this *Extension) Equal(that *Extension) bool { + if err := this.Encode(); err != nil { + return false + } + if err := that.Encode(); err != nil { + return false + } return bytes.Equal(this.enc, that.enc) } func (this *Extension) Compare(that *Extension) int { + if err := this.Encode(); err != nil { + return 1 + } + if err := that.Encode(); err != nil { + return -1 + } return bytes.Compare(this.enc, that.enc) } func SizeOfInternalExtension(m extendableProto) (n int) { - return SizeOfExtensionMap(m.extensionsWrite()) -} - -func SizeOfExtensionMap(m map[int32]Extension) (n int) { - return extensionsMapSize(m) + info := getMarshalInfo(reflect.TypeOf(m)) + return info.sizeV1Extensions(m.extensionsWrite()) } type sortableMapElem struct { @@ -122,28 +155,26 @@ func EncodeInternalExtension(m extendableProto, data []byte) (n int, err error) } func EncodeExtensionMap(m map[int32]Extension, data []byte) (n int, err error) { - if err := encodeExtensionsMap(m); err != nil { - return 0, err - } - keys := make([]int, 0, len(m)) - for k := range m { - keys = append(keys, int(k)) - } - sort.Ints(keys) - for _, k := range keys { - n += copy(data[n:], m[int32(k)].enc) + o := 0 + for _, e := range m { + if err := e.Encode(); err != nil { + return 0, err + } + n := copy(data[o:], e.enc) + if n != len(e.enc) { + return 0, io.ErrShortBuffer + } + o += n } - return n, nil + return o, nil } func GetRawExtension(m map[int32]Extension, id int32) ([]byte, error) { - if m[id].value == nil || m[id].desc == nil { - return m[id].enc, nil - } - if err := encodeExtensionsMap(m); err != nil { + e := m[id] + if err := e.Encode(); err != nil { return nil, err } - return m[id].enc, nil + return e.enc, nil } func size(buf []byte, wire int) (int, error) { @@ -218,35 +249,58 @@ func AppendExtension(e Message, tag int32, buf []byte) { } } -func encodeExtension(e *Extension) error { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - return nil +func encodeExtension(extension *ExtensionDesc, value interface{}) ([]byte, error) { + u := getMarshalInfo(reflect.TypeOf(extension.ExtendedType)) + ei := u.getExtElemInfo(extension) + v := value + p := toAddrPointer(&v, ei.isptr) + siz := ei.sizer(p, SizeVarint(ei.wiretag)) + buf := make([]byte, 0, siz) + return ei.marshaler(buf, p, ei.wiretag, false) +} + +func decodeExtensionFromBytes(extension *ExtensionDesc, buf []byte) (interface{}, error) { + o := 0 + for o < len(buf) { + tag, n := DecodeVarint((buf)[o:]) + fieldNum := int32(tag >> 3) + wireType := int(tag & 0x7) + if o+n > len(buf) { + return nil, fmt.Errorf("unable to decode extension") + } + l, err := size((buf)[o+n:], wireType) + if err != nil { + return nil, err + } + if int32(fieldNum) == extension.Field { + if o+n+l > len(buf) { + return nil, fmt.Errorf("unable to decode extension") + } + v, err := decodeExtension((buf)[o:o+n+l], extension) + if err != nil { + return nil, err + } + return v, nil + } + o += n + l } - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - et := reflect.TypeOf(e.desc.ExtensionType) - props := extensionProperties(e.desc) - - p := NewBuffer(nil) - // If e.value has type T, the encoder expects a *struct{ X T }. - // Pass a *T with a zero field and hope it all works out. - x := reflect.New(et) - x.Elem().Set(reflect.ValueOf(e.value)) - if err := props.enc(p, props, toStructPointer(x)); err != nil { - return err + return defaultExtensionValue(extension) +} + +func (this *Extension) Encode() error { + if this.enc == nil { + var err error + this.enc, err = encodeExtension(this.desc, this.value) + if err != nil { + return err + } } - e.enc = p.buf return nil } func (this Extension) GoString() string { - if this.enc == nil { - if err := encodeExtension(&this); err != nil { - panic(err) - } + if err := this.Encode(); err != nil { + return fmt.Sprintf("error encoding extension: %v", err) } return fmt.Sprintf("proto.NewExtension(%#v)", this.enc) } @@ -292,3 +346,23 @@ func GetUnsafeExtensionsMap(extendable Message) map[int32]Extension { pb := extendable.(extendableProto) return pb.extensionsWrite() } + +func deleteExtension(pb extensionsBytes, theFieldNum int32, offset int) int { + ext := pb.GetExtensions() + for offset < len(*ext) { + tag, n1 := DecodeVarint((*ext)[offset:]) + fieldNum := int32(tag >> 3) + wireType := int(tag & 0x7) + n2, err := size((*ext)[offset+n1:], wireType) + if err != nil { + panic(err) + } + newOffset := offset + n1 + n2 + if fieldNum == theFieldNum { + *ext = append((*ext)[:offset], (*ext)[newOffset:]...) + return offset + } + offset = newOffset + } + return -1 +} diff --git a/vendor/github.com/gogo/protobuf/proto/lib.go b/vendor/github.com/gogo/protobuf/proto/lib.go index c98d73da4..0f1950c67 100644 --- a/vendor/github.com/gogo/protobuf/proto/lib.go +++ b/vendor/github.com/gogo/protobuf/proto/lib.go @@ -265,6 +265,7 @@ package proto import ( "encoding/json" + "errors" "fmt" "log" "reflect" @@ -273,6 +274,8 @@ import ( "sync" ) +var errInvalidUTF8 = errors.New("proto: invalid UTF-8 string") + // Message is implemented by generated protocol buffer messages. type Message interface { Reset() @@ -309,16 +312,7 @@ type Buffer struct { buf []byte // encode/decode byte stream index int // read point - // pools of basic types to amortize allocation. - bools []bool - uint32s []uint32 - uint64s []uint64 - - // extra pools, only used with pointer_reflect.go - int32s []int32 - int64s []int64 - float32s []float32 - float64s []float64 + deterministic bool } // NewBuffer allocates a new Buffer and initializes its internal data to @@ -343,6 +337,30 @@ func (p *Buffer) SetBuf(s []byte) { // Bytes returns the contents of the Buffer. func (p *Buffer) Bytes() []byte { return p.buf } +// SetDeterministic sets whether to use deterministic serialization. +// +// Deterministic serialization guarantees that for a given binary, equal +// messages will always be serialized to the same bytes. This implies: +// +// - Repeated serialization of a message will return the same bytes. +// - Different processes of the same binary (which may be executing on +// different machines) will serialize equal messages to the same bytes. +// +// Note that the deterministic serialization is NOT canonical across +// languages. It is not guaranteed to remain stable over time. It is unstable +// across different builds with schema changes due to unknown fields. +// Users who need canonical serialization (e.g., persistent storage in a +// canonical form, fingerprinting, etc.) should define their own +// canonicalization specification and implement their own serializer rather +// than relying on this API. +// +// If deterministic serialization is requested, map entries will be sorted +// by keys in lexographical order. This is an implementation detail and +// subject to change. +func (p *Buffer) SetDeterministic(deterministic bool) { + p.deterministic = deterministic +} + /* * Helper routines for simplifying the creation of optional fields of basic type. */ @@ -831,22 +849,12 @@ func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMes return sf, false, nil } +// mapKeys returns a sort.Interface to be used for sorting the map keys. // Map fields may have key types of non-float scalars, strings and enums. -// The easiest way to sort them in some deterministic order is to use fmt. -// If this turns out to be inefficient we can always consider other options, -// such as doing a Schwartzian transform. - func mapKeys(vs []reflect.Value) sort.Interface { - s := mapKeySorter{ - vs: vs, - // default Less function: textual comparison - less: func(a, b reflect.Value) bool { - return fmt.Sprint(a.Interface()) < fmt.Sprint(b.Interface()) - }, - } + s := mapKeySorter{vs: vs} - // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps; - // numeric keys are sorted numerically. + // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps. if len(vs) == 0 { return s } @@ -855,6 +863,12 @@ func mapKeys(vs []reflect.Value) sort.Interface { s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() } case reflect.Uint32, reflect.Uint64: s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() } + case reflect.Bool: + s.less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() } // false < true + case reflect.String: + s.less = func(a, b reflect.Value) bool { return a.String() < b.String() } + default: + panic(fmt.Sprintf("unsupported map key type: %v", vs[0].Kind())) } return s @@ -895,3 +909,13 @@ const GoGoProtoPackageIsVersion2 = true // ProtoPackageIsVersion1 is referenced from generated protocol buffer files // to assert that that code is compatible with this version of the proto package. const GoGoProtoPackageIsVersion1 = true + +// InternalMessageInfo is a type used internally by generated .pb.go files. +// This type is not intended to be used by non-generated code. +// This type is not subject to any compatibility guarantee. +type InternalMessageInfo struct { + marshal *marshalInfo + unmarshal *unmarshalInfo + merge *mergeInfo + discard *discardInfo +} diff --git a/vendor/github.com/gogo/protobuf/proto/lib_gogo.go b/vendor/github.com/gogo/protobuf/proto/lib_gogo.go index 4b4f7c909..b3aa39190 100644 --- a/vendor/github.com/gogo/protobuf/proto/lib_gogo.go +++ b/vendor/github.com/gogo/protobuf/proto/lib_gogo.go @@ -33,6 +33,14 @@ import ( "strconv" ) +type Sizer interface { + Size() int +} + +type ProtoSizer interface { + ProtoSize() int +} + func MarshalJSONEnum(m map[int32]string, value int32) ([]byte, error) { s, ok := m[value] if !ok { diff --git a/vendor/github.com/gogo/protobuf/proto/message_set.go b/vendor/github.com/gogo/protobuf/proto/message_set.go index fd982decd..3b6ca41d5 100644 --- a/vendor/github.com/gogo/protobuf/proto/message_set.go +++ b/vendor/github.com/gogo/protobuf/proto/message_set.go @@ -42,6 +42,7 @@ import ( "fmt" "reflect" "sort" + "sync" ) // errNoMessageTypeID occurs when a protocol buffer does not have a message type ID. @@ -94,10 +95,7 @@ func (ms *messageSet) find(pb Message) *_MessageSet_Item { } func (ms *messageSet) Has(pb Message) bool { - if ms.find(pb) != nil { - return true - } - return false + return ms.find(pb) != nil } func (ms *messageSet) Unmarshal(pb Message) error { @@ -150,46 +148,42 @@ func skipVarint(buf []byte) []byte { // MarshalMessageSet encodes the extension map represented by m in the message set wire format. // It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option. func MarshalMessageSet(exts interface{}) ([]byte, error) { - var m map[int32]Extension + return marshalMessageSet(exts, false) +} + +// marshaMessageSet implements above function, with the opt to turn on / off deterministic during Marshal. +func marshalMessageSet(exts interface{}, deterministic bool) ([]byte, error) { switch exts := exts.(type) { case *XXX_InternalExtensions: - if err := encodeExtensions(exts); err != nil { - return nil, err - } - m, _ = exts.extensionsRead() + var u marshalInfo + siz := u.sizeMessageSet(exts) + b := make([]byte, 0, siz) + return u.appendMessageSet(b, exts, deterministic) + case map[int32]Extension: - if err := encodeExtensionsMap(exts); err != nil { - return nil, err + // This is an old-style extension map. + // Wrap it in a new-style XXX_InternalExtensions. + ie := XXX_InternalExtensions{ + p: &struct { + mu sync.Mutex + extensionMap map[int32]Extension + }{ + extensionMap: exts, + }, } - m = exts + + var u marshalInfo + siz := u.sizeMessageSet(&ie) + b := make([]byte, 0, siz) + return u.appendMessageSet(b, &ie, deterministic) + default: return nil, errors.New("proto: not an extension map") } - - // Sort extension IDs to provide a deterministic encoding. - // See also enc_map in encode.go. - ids := make([]int, 0, len(m)) - for id := range m { - ids = append(ids, int(id)) - } - sort.Ints(ids) - - ms := &messageSet{Item: make([]*_MessageSet_Item, 0, len(m))} - for _, id := range ids { - e := m[int32(id)] - // Remove the wire type and field number varint, as well as the length varint. - msg := skipVarint(skipVarint(e.enc)) - - ms.Item = append(ms.Item, &_MessageSet_Item{ - TypeId: Int32(int32(id)), - Message: msg, - }) - } - return Marshal(ms) } // UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. -// It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option. +// It is called by Unmarshal methods on protocol buffer messages with the message_set_wire_format option. func UnmarshalMessageSet(buf []byte, exts interface{}) error { var m map[int32]Extension switch exts := exts.(type) { @@ -235,7 +229,15 @@ func MarshalMessageSetJSON(exts interface{}) ([]byte, error) { var m map[int32]Extension switch exts := exts.(type) { case *XXX_InternalExtensions: - m, _ = exts.extensionsRead() + var mu sync.Locker + m, mu = exts.extensionsRead() + if m != nil { + // Keep the extensions map locked until we're done marshaling to prevent + // races between marshaling and unmarshaling the lazily-{en,de}coded + // values. + mu.Lock() + defer mu.Unlock() + } case map[int32]Extension: m = exts default: @@ -253,15 +255,16 @@ func MarshalMessageSetJSON(exts interface{}) ([]byte, error) { for i, id := range ids { ext := m[id] - if i > 0 { - b.WriteByte(',') - } - msd, ok := messageSetMap[id] if !ok { // Unknown type; we can't render it, so skip it. continue } + + if i > 0 && b.Len() > 1 { + b.WriteByte(',') + } + fmt.Fprintf(&b, `"[%s]":`, msd.name) x := ext.value diff --git a/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go b/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go index fb512e2e1..b6cad9083 100644 --- a/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go +++ b/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go @@ -29,7 +29,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// +build appengine js +// +build purego appengine js // This file contains an implementation of proto field accesses using package reflect. // It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can @@ -38,32 +38,13 @@ package proto import ( - "math" "reflect" + "sync" ) -// A structPointer is a pointer to a struct. -type structPointer struct { - v reflect.Value -} - -// toStructPointer returns a structPointer equivalent to the given reflect value. -// The reflect value must itself be a pointer to a struct. -func toStructPointer(v reflect.Value) structPointer { - return structPointer{v} -} - -// IsNil reports whether p is nil. -func structPointer_IsNil(p structPointer) bool { - return p.v.IsNil() -} +const unsafeAllowed = false -// Interface returns the struct pointer as an interface value. -func structPointer_Interface(p structPointer, _ reflect.Type) interface{} { - return p.v.Interface() -} - -// A field identifies a field in a struct, accessible from a structPointer. +// A field identifies a field in a struct, accessible from a pointer. // In this implementation, a field is identified by the sequence of field indices // passed to reflect's FieldByIndex. type field []int @@ -76,409 +57,301 @@ func toField(f *reflect.StructField) field { // invalidField is an invalid field identifier. var invalidField = field(nil) +// zeroField is a noop when calling pointer.offset. +var zeroField = field([]int{}) + // IsValid reports whether the field identifier is valid. func (f field) IsValid() bool { return f != nil } -// field returns the given field in the struct as a reflect value. -func structPointer_field(p structPointer, f field) reflect.Value { - // Special case: an extension map entry with a value of type T - // passes a *T to the struct-handling code with a zero field, - // expecting that it will be treated as equivalent to *struct{ X T }, - // which has the same memory layout. We have to handle that case - // specially, because reflect will panic if we call FieldByIndex on a - // non-struct. - if f == nil { - return p.v.Elem() - } - - return p.v.Elem().FieldByIndex(f) +// The pointer type is for the table-driven decoder. +// The implementation here uses a reflect.Value of pointer type to +// create a generic pointer. In pointer_unsafe.go we use unsafe +// instead of reflect to implement the same (but faster) interface. +type pointer struct { + v reflect.Value } -// ifield returns the given field in the struct as an interface value. -func structPointer_ifield(p structPointer, f field) interface{} { - return structPointer_field(p, f).Addr().Interface() +// toPointer converts an interface of pointer type to a pointer +// that points to the same target. +func toPointer(i *Message) pointer { + return pointer{v: reflect.ValueOf(*i)} } -// Bytes returns the address of a []byte field in the struct. -func structPointer_Bytes(p structPointer, f field) *[]byte { - return structPointer_ifield(p, f).(*[]byte) +// toAddrPointer converts an interface to a pointer that points to +// the interface data. +func toAddrPointer(i *interface{}, isptr bool) pointer { + v := reflect.ValueOf(*i) + u := reflect.New(v.Type()) + u.Elem().Set(v) + return pointer{v: u} } -// BytesSlice returns the address of a [][]byte field in the struct. -func structPointer_BytesSlice(p structPointer, f field) *[][]byte { - return structPointer_ifield(p, f).(*[][]byte) +// valToPointer converts v to a pointer. v must be of pointer type. +func valToPointer(v reflect.Value) pointer { + return pointer{v: v} } -// Bool returns the address of a *bool field in the struct. -func structPointer_Bool(p structPointer, f field) **bool { - return structPointer_ifield(p, f).(**bool) +// offset converts from a pointer to a structure to a pointer to +// one of its fields. +func (p pointer) offset(f field) pointer { + return pointer{v: p.v.Elem().FieldByIndex(f).Addr()} } -// BoolVal returns the address of a bool field in the struct. -func structPointer_BoolVal(p structPointer, f field) *bool { - return structPointer_ifield(p, f).(*bool) +func (p pointer) isNil() bool { + return p.v.IsNil() } -// BoolSlice returns the address of a []bool field in the struct. -func structPointer_BoolSlice(p structPointer, f field) *[]bool { - return structPointer_ifield(p, f).(*[]bool) +// grow updates the slice s in place to make it one element longer. +// s must be addressable. +// Returns the (addressable) new element. +func grow(s reflect.Value) reflect.Value { + n, m := s.Len(), s.Cap() + if n < m { + s.SetLen(n + 1) + } else { + s.Set(reflect.Append(s, reflect.Zero(s.Type().Elem()))) + } + return s.Index(n) } -// String returns the address of a *string field in the struct. -func structPointer_String(p structPointer, f field) **string { - return structPointer_ifield(p, f).(**string) +func (p pointer) toInt64() *int64 { + return p.v.Interface().(*int64) } - -// StringVal returns the address of a string field in the struct. -func structPointer_StringVal(p structPointer, f field) *string { - return structPointer_ifield(p, f).(*string) +func (p pointer) toInt64Ptr() **int64 { + return p.v.Interface().(**int64) } - -// StringSlice returns the address of a []string field in the struct. -func structPointer_StringSlice(p structPointer, f field) *[]string { - return structPointer_ifield(p, f).(*[]string) +func (p pointer) toInt64Slice() *[]int64 { + return p.v.Interface().(*[]int64) } -// Extensions returns the address of an extension map field in the struct. -func structPointer_Extensions(p structPointer, f field) *XXX_InternalExtensions { - return structPointer_ifield(p, f).(*XXX_InternalExtensions) -} +var int32ptr = reflect.TypeOf((*int32)(nil)) -// ExtMap returns the address of an extension map field in the struct. -func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension { - return structPointer_ifield(p, f).(*map[int32]Extension) +func (p pointer) toInt32() *int32 { + return p.v.Convert(int32ptr).Interface().(*int32) } -// NewAt returns the reflect.Value for a pointer to a field in the struct. -func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value { - return structPointer_field(p, f).Addr() +// The toInt32Ptr/Slice methods don't work because of enums. +// Instead, we must use set/get methods for the int32ptr/slice case. +/* + func (p pointer) toInt32Ptr() **int32 { + return p.v.Interface().(**int32) } - -// SetStructPointer writes a *struct field in the struct. -func structPointer_SetStructPointer(p structPointer, f field, q structPointer) { - structPointer_field(p, f).Set(q.v) + func (p pointer) toInt32Slice() *[]int32 { + return p.v.Interface().(*[]int32) } - -// GetStructPointer reads a *struct field in the struct. -func structPointer_GetStructPointer(p structPointer, f field) structPointer { - return structPointer{structPointer_field(p, f)} +*/ +func (p pointer) getInt32Ptr() *int32 { + if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { + // raw int32 type + return p.v.Elem().Interface().(*int32) + } + // an enum + return p.v.Elem().Convert(int32PtrType).Interface().(*int32) +} +func (p pointer) setInt32Ptr(v int32) { + // Allocate value in a *int32. Possibly convert that to a *enum. + // Then assign it to a **int32 or **enum. + // Note: we can convert *int32 to *enum, but we can't convert + // **int32 to **enum! + p.v.Elem().Set(reflect.ValueOf(&v).Convert(p.v.Type().Elem())) +} + +// getInt32Slice copies []int32 from p as a new slice. +// This behavior differs from the implementation in pointer_unsafe.go. +func (p pointer) getInt32Slice() []int32 { + if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { + // raw int32 type + return p.v.Elem().Interface().([]int32) + } + // an enum + // Allocate a []int32, then assign []enum's values into it. + // Note: we can't convert []enum to []int32. + slice := p.v.Elem() + s := make([]int32, slice.Len()) + for i := 0; i < slice.Len(); i++ { + s[i] = int32(slice.Index(i).Int()) + } + return s } -// StructPointerSlice the address of a []*struct field in the struct. -func structPointer_StructPointerSlice(p structPointer, f field) structPointerSlice { - return structPointerSlice{structPointer_field(p, f)} +// setInt32Slice copies []int32 into p as a new slice. +// This behavior differs from the implementation in pointer_unsafe.go. +func (p pointer) setInt32Slice(v []int32) { + if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { + // raw int32 type + p.v.Elem().Set(reflect.ValueOf(v)) + return + } + // an enum + // Allocate a []enum, then assign []int32's values into it. + // Note: we can't convert []enum to []int32. + slice := reflect.MakeSlice(p.v.Type().Elem(), len(v), cap(v)) + for i, x := range v { + slice.Index(i).SetInt(int64(x)) + } + p.v.Elem().Set(slice) } - -// A structPointerSlice represents the address of a slice of pointers to structs -// (themselves messages or groups). That is, v.Type() is *[]*struct{...}. -type structPointerSlice struct { - v reflect.Value +func (p pointer) appendInt32Slice(v int32) { + grow(p.v.Elem()).SetInt(int64(v)) } -func (p structPointerSlice) Len() int { return p.v.Len() } -func (p structPointerSlice) Index(i int) structPointer { return structPointer{p.v.Index(i)} } -func (p structPointerSlice) Append(q structPointer) { - p.v.Set(reflect.Append(p.v, q.v)) +func (p pointer) toUint64() *uint64 { + return p.v.Interface().(*uint64) } - -var ( - int32Type = reflect.TypeOf(int32(0)) - uint32Type = reflect.TypeOf(uint32(0)) - float32Type = reflect.TypeOf(float32(0)) - int64Type = reflect.TypeOf(int64(0)) - uint64Type = reflect.TypeOf(uint64(0)) - float64Type = reflect.TypeOf(float64(0)) -) - -// A word32 represents a field of type *int32, *uint32, *float32, or *enum. -// That is, v.Type() is *int32, *uint32, *float32, or *enum and v is assignable. -type word32 struct { - v reflect.Value +func (p pointer) toUint64Ptr() **uint64 { + return p.v.Interface().(**uint64) } - -// IsNil reports whether p is nil. -func word32_IsNil(p word32) bool { - return p.v.IsNil() +func (p pointer) toUint64Slice() *[]uint64 { + return p.v.Interface().(*[]uint64) } - -// Set sets p to point at a newly allocated word with bits set to x. -func word32_Set(p word32, o *Buffer, x uint32) { - t := p.v.Type().Elem() - switch t { - case int32Type: - if len(o.int32s) == 0 { - o.int32s = make([]int32, uint32PoolSize) - } - o.int32s[0] = int32(x) - p.v.Set(reflect.ValueOf(&o.int32s[0])) - o.int32s = o.int32s[1:] - return - case uint32Type: - if len(o.uint32s) == 0 { - o.uint32s = make([]uint32, uint32PoolSize) - } - o.uint32s[0] = x - p.v.Set(reflect.ValueOf(&o.uint32s[0])) - o.uint32s = o.uint32s[1:] - return - case float32Type: - if len(o.float32s) == 0 { - o.float32s = make([]float32, uint32PoolSize) - } - o.float32s[0] = math.Float32frombits(x) - p.v.Set(reflect.ValueOf(&o.float32s[0])) - o.float32s = o.float32s[1:] - return - } - - // must be enum - p.v.Set(reflect.New(t)) - p.v.Elem().SetInt(int64(int32(x))) +func (p pointer) toUint32() *uint32 { + return p.v.Interface().(*uint32) } - -// Get gets the bits pointed at by p, as a uint32. -func word32_Get(p word32) uint32 { - elem := p.v.Elem() - switch elem.Kind() { - case reflect.Int32: - return uint32(elem.Int()) - case reflect.Uint32: - return uint32(elem.Uint()) - case reflect.Float32: - return math.Float32bits(float32(elem.Float())) - } - panic("unreachable") +func (p pointer) toUint32Ptr() **uint32 { + return p.v.Interface().(**uint32) } - -// Word32 returns a reference to a *int32, *uint32, *float32, or *enum field in the struct. -func structPointer_Word32(p structPointer, f field) word32 { - return word32{structPointer_field(p, f)} +func (p pointer) toUint32Slice() *[]uint32 { + return p.v.Interface().(*[]uint32) } - -// A word32Val represents a field of type int32, uint32, float32, or enum. -// That is, v.Type() is int32, uint32, float32, or enum and v is assignable. -type word32Val struct { - v reflect.Value +func (p pointer) toBool() *bool { + return p.v.Interface().(*bool) } - -// Set sets *p to x. -func word32Val_Set(p word32Val, x uint32) { - switch p.v.Type() { - case int32Type: - p.v.SetInt(int64(x)) - return - case uint32Type: - p.v.SetUint(uint64(x)) - return - case float32Type: - p.v.SetFloat(float64(math.Float32frombits(x))) - return - } - - // must be enum - p.v.SetInt(int64(int32(x))) +func (p pointer) toBoolPtr() **bool { + return p.v.Interface().(**bool) } - -// Get gets the bits pointed at by p, as a uint32. -func word32Val_Get(p word32Val) uint32 { - elem := p.v - switch elem.Kind() { - case reflect.Int32: - return uint32(elem.Int()) - case reflect.Uint32: - return uint32(elem.Uint()) - case reflect.Float32: - return math.Float32bits(float32(elem.Float())) - } - panic("unreachable") +func (p pointer) toBoolSlice() *[]bool { + return p.v.Interface().(*[]bool) } - -// Word32Val returns a reference to a int32, uint32, float32, or enum field in the struct. -func structPointer_Word32Val(p structPointer, f field) word32Val { - return word32Val{structPointer_field(p, f)} +func (p pointer) toFloat64() *float64 { + return p.v.Interface().(*float64) } - -// A word32Slice is a slice of 32-bit values. -// That is, v.Type() is []int32, []uint32, []float32, or []enum. -type word32Slice struct { - v reflect.Value +func (p pointer) toFloat64Ptr() **float64 { + return p.v.Interface().(**float64) } - -func (p word32Slice) Append(x uint32) { - n, m := p.v.Len(), p.v.Cap() - if n < m { - p.v.SetLen(n + 1) - } else { - t := p.v.Type().Elem() - p.v.Set(reflect.Append(p.v, reflect.Zero(t))) - } - elem := p.v.Index(n) - switch elem.Kind() { - case reflect.Int32: - elem.SetInt(int64(int32(x))) - case reflect.Uint32: - elem.SetUint(uint64(x)) - case reflect.Float32: - elem.SetFloat(float64(math.Float32frombits(x))) - } +func (p pointer) toFloat64Slice() *[]float64 { + return p.v.Interface().(*[]float64) } - -func (p word32Slice) Len() int { - return p.v.Len() +func (p pointer) toFloat32() *float32 { + return p.v.Interface().(*float32) } - -func (p word32Slice) Index(i int) uint32 { - elem := p.v.Index(i) - switch elem.Kind() { - case reflect.Int32: - return uint32(elem.Int()) - case reflect.Uint32: - return uint32(elem.Uint()) - case reflect.Float32: - return math.Float32bits(float32(elem.Float())) - } - panic("unreachable") +func (p pointer) toFloat32Ptr() **float32 { + return p.v.Interface().(**float32) } - -// Word32Slice returns a reference to a []int32, []uint32, []float32, or []enum field in the struct. -func structPointer_Word32Slice(p structPointer, f field) word32Slice { - return word32Slice{structPointer_field(p, f)} +func (p pointer) toFloat32Slice() *[]float32 { + return p.v.Interface().(*[]float32) } - -// word64 is like word32 but for 64-bit values. -type word64 struct { - v reflect.Value +func (p pointer) toString() *string { + return p.v.Interface().(*string) } - -func word64_Set(p word64, o *Buffer, x uint64) { - t := p.v.Type().Elem() - switch t { - case int64Type: - if len(o.int64s) == 0 { - o.int64s = make([]int64, uint64PoolSize) - } - o.int64s[0] = int64(x) - p.v.Set(reflect.ValueOf(&o.int64s[0])) - o.int64s = o.int64s[1:] - return - case uint64Type: - if len(o.uint64s) == 0 { - o.uint64s = make([]uint64, uint64PoolSize) - } - o.uint64s[0] = x - p.v.Set(reflect.ValueOf(&o.uint64s[0])) - o.uint64s = o.uint64s[1:] - return - case float64Type: - if len(o.float64s) == 0 { - o.float64s = make([]float64, uint64PoolSize) - } - o.float64s[0] = math.Float64frombits(x) - p.v.Set(reflect.ValueOf(&o.float64s[0])) - o.float64s = o.float64s[1:] - return - } - panic("unreachable") +func (p pointer) toStringPtr() **string { + return p.v.Interface().(**string) } - -func word64_IsNil(p word64) bool { - return p.v.IsNil() +func (p pointer) toStringSlice() *[]string { + return p.v.Interface().(*[]string) } - -func word64_Get(p word64) uint64 { - elem := p.v.Elem() - switch elem.Kind() { - case reflect.Int64: - return uint64(elem.Int()) - case reflect.Uint64: - return elem.Uint() - case reflect.Float64: - return math.Float64bits(elem.Float()) - } - panic("unreachable") +func (p pointer) toBytes() *[]byte { + return p.v.Interface().(*[]byte) } - -func structPointer_Word64(p structPointer, f field) word64 { - return word64{structPointer_field(p, f)} +func (p pointer) toBytesSlice() *[][]byte { + return p.v.Interface().(*[][]byte) +} +func (p pointer) toExtensions() *XXX_InternalExtensions { + return p.v.Interface().(*XXX_InternalExtensions) +} +func (p pointer) toOldExtensions() *map[int32]Extension { + return p.v.Interface().(*map[int32]Extension) +} +func (p pointer) getPointer() pointer { + return pointer{v: p.v.Elem()} +} +func (p pointer) setPointer(q pointer) { + p.v.Elem().Set(q.v) +} +func (p pointer) appendPointer(q pointer) { + grow(p.v.Elem()).Set(q.v) } -// word64Val is like word32Val but for 64-bit values. -type word64Val struct { - v reflect.Value +// getPointerSlice copies []*T from p as a new []pointer. +// This behavior differs from the implementation in pointer_unsafe.go. +func (p pointer) getPointerSlice() []pointer { + if p.v.IsNil() { + return nil + } + n := p.v.Elem().Len() + s := make([]pointer, n) + for i := 0; i < n; i++ { + s[i] = pointer{v: p.v.Elem().Index(i)} + } + return s } -func word64Val_Set(p word64Val, o *Buffer, x uint64) { - switch p.v.Type() { - case int64Type: - p.v.SetInt(int64(x)) - return - case uint64Type: - p.v.SetUint(x) - return - case float64Type: - p.v.SetFloat(math.Float64frombits(x)) +// setPointerSlice copies []pointer into p as a new []*T. +// This behavior differs from the implementation in pointer_unsafe.go. +func (p pointer) setPointerSlice(v []pointer) { + if v == nil { + p.v.Elem().Set(reflect.New(p.v.Elem().Type()).Elem()) return } - panic("unreachable") + s := reflect.MakeSlice(p.v.Elem().Type(), 0, len(v)) + for _, p := range v { + s = reflect.Append(s, p.v) + } + p.v.Elem().Set(s) } -func word64Val_Get(p word64Val) uint64 { - elem := p.v - switch elem.Kind() { - case reflect.Int64: - return uint64(elem.Int()) - case reflect.Uint64: - return elem.Uint() - case reflect.Float64: - return math.Float64bits(elem.Float()) +// getInterfacePointer returns a pointer that points to the +// interface data of the interface pointed by p. +func (p pointer) getInterfacePointer() pointer { + if p.v.Elem().IsNil() { + return pointer{v: p.v.Elem()} } - panic("unreachable") + return pointer{v: p.v.Elem().Elem().Elem().Field(0).Addr()} // *interface -> interface -> *struct -> struct } -func structPointer_Word64Val(p structPointer, f field) word64Val { - return word64Val{structPointer_field(p, f)} +func (p pointer) asPointerTo(t reflect.Type) reflect.Value { + // TODO: check that p.v.Type().Elem() == t? + return p.v } -type word64Slice struct { - v reflect.Value +func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo { + atomicLock.Lock() + defer atomicLock.Unlock() + return *p } - -func (p word64Slice) Append(x uint64) { - n, m := p.v.Len(), p.v.Cap() - if n < m { - p.v.SetLen(n + 1) - } else { - t := p.v.Type().Elem() - p.v.Set(reflect.Append(p.v, reflect.Zero(t))) - } - elem := p.v.Index(n) - switch elem.Kind() { - case reflect.Int64: - elem.SetInt(int64(int64(x))) - case reflect.Uint64: - elem.SetUint(uint64(x)) - case reflect.Float64: - elem.SetFloat(float64(math.Float64frombits(x))) - } +func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) { + atomicLock.Lock() + defer atomicLock.Unlock() + *p = v } - -func (p word64Slice) Len() int { - return p.v.Len() +func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo { + atomicLock.Lock() + defer atomicLock.Unlock() + return *p } - -func (p word64Slice) Index(i int) uint64 { - elem := p.v.Index(i) - switch elem.Kind() { - case reflect.Int64: - return uint64(elem.Int()) - case reflect.Uint64: - return uint64(elem.Uint()) - case reflect.Float64: - return math.Float64bits(float64(elem.Float())) - } - panic("unreachable") +func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) { + atomicLock.Lock() + defer atomicLock.Unlock() + *p = v } - -func structPointer_Word64Slice(p structPointer, f field) word64Slice { - return word64Slice{structPointer_field(p, f)} +func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo { + atomicLock.Lock() + defer atomicLock.Unlock() + return *p +} +func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) { + atomicLock.Lock() + defer atomicLock.Unlock() + *p = v } +func atomicLoadDiscardInfo(p **discardInfo) *discardInfo { + atomicLock.Lock() + defer atomicLock.Unlock() + return *p +} +func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) { + atomicLock.Lock() + defer atomicLock.Unlock() + *p = v +} + +var atomicLock sync.Mutex diff --git a/vendor/github.com/gogo/protobuf/proto/pointer_reflect_gogo.go b/vendor/github.com/gogo/protobuf/proto/pointer_reflect_gogo.go index 1763a5f22..7ffd3c29d 100644 --- a/vendor/github.com/gogo/protobuf/proto/pointer_reflect_gogo.go +++ b/vendor/github.com/gogo/protobuf/proto/pointer_reflect_gogo.go @@ -1,6 +1,6 @@ // Protocol Buffers for Go with Gadgets // -// Copyright (c) 2016, The GoGo Authors. All rights reserved. +// Copyright (c) 2018, The GoGo Authors. All rights reserved. // http://github.com/gogo/protobuf // // Redistribution and use in source and binary forms, with or without @@ -26,7 +26,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// +build appengine js +// +build purego appengine js + +// This file contains an implementation of proto field accesses using package reflect. +// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can +// be used on App Engine. package proto @@ -34,52 +38,22 @@ import ( "reflect" ) -func structPointer_FieldPointer(p structPointer, f field) structPointer { - panic("not implemented") -} - -func appendStructPointer(base structPointer, f field, typ reflect.Type) structPointer { - panic("not implemented") -} - -func structPointer_InterfaceAt(p structPointer, f field, t reflect.Type) interface{} { - panic("not implemented") -} - -func structPointer_InterfaceRef(p structPointer, f field, t reflect.Type) interface{} { - panic("not implemented") -} - -func structPointer_GetRefStructPointer(p structPointer, f field) structPointer { - panic("not implemented") -} +// TODO: untested, so probably incorrect. -func structPointer_Add(p structPointer, size field) structPointer { - panic("not implemented") +func (p pointer) getRef() pointer { + return pointer{v: p.v.Addr()} } -func structPointer_Len(p structPointer, f field) int { - panic("not implemented") -} - -func structPointer_GetSliceHeader(p structPointer, f field) *reflect.SliceHeader { - panic("not implemented") -} - -func structPointer_Copy(oldptr structPointer, newptr structPointer, size int) { - panic("not implemented") -} - -func structPointer_StructRefSlice(p structPointer, f field, size uintptr) *structRefSlice { - panic("not implemented") -} - -type structRefSlice struct{} - -func (v *structRefSlice) Len() int { - panic("not implemented") +func (p pointer) appendRef(v pointer, typ reflect.Type) { + slice := p.getSlice(typ) + elem := v.asPointerTo(typ).Elem() + newSlice := reflect.Append(slice, elem) + slice.Set(newSlice) } -func (v *structRefSlice) Index(i int) structPointer { - panic("not implemented") +func (p pointer) getSlice(typ reflect.Type) reflect.Value { + sliceTyp := reflect.SliceOf(typ) + slice := p.asPointerTo(sliceTyp) + slice = slice.Elem() + return slice } diff --git a/vendor/github.com/gogo/protobuf/proto/pointer_unsafe.go b/vendor/github.com/gogo/protobuf/proto/pointer_unsafe.go index 6b5567d47..d55a335d9 100644 --- a/vendor/github.com/gogo/protobuf/proto/pointer_unsafe.go +++ b/vendor/github.com/gogo/protobuf/proto/pointer_unsafe.go @@ -29,7 +29,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// +build !appengine,!js +// +build !purego,!appengine,!js // This file contains the implementation of the proto field accesses using package unsafe. @@ -37,38 +37,13 @@ package proto import ( "reflect" + "sync/atomic" "unsafe" ) -// NOTE: These type_Foo functions would more idiomatically be methods, -// but Go does not allow methods on pointer types, and we must preserve -// some pointer type for the garbage collector. We use these -// funcs with clunky names as our poor approximation to methods. -// -// An alternative would be -// type structPointer struct { p unsafe.Pointer } -// but that does not registerize as well. - -// A structPointer is a pointer to a struct. -type structPointer unsafe.Pointer - -// toStructPointer returns a structPointer equivalent to the given reflect value. -func toStructPointer(v reflect.Value) structPointer { - return structPointer(unsafe.Pointer(v.Pointer())) -} - -// IsNil reports whether p is nil. -func structPointer_IsNil(p structPointer) bool { - return p == nil -} - -// Interface returns the struct pointer, assumed to have element type t, -// as an interface value. -func structPointer_Interface(p structPointer, t reflect.Type) interface{} { - return reflect.NewAt(t, unsafe.Pointer(p)).Interface() -} +const unsafeAllowed = true -// A field identifies a field in a struct, accessible from a structPointer. +// A field identifies a field in a struct, accessible from a pointer. // In this implementation, a field is identified by its byte offset from the start of the struct. type field uintptr @@ -80,191 +55,254 @@ func toField(f *reflect.StructField) field { // invalidField is an invalid field identifier. const invalidField = ^field(0) +// zeroField is a noop when calling pointer.offset. +const zeroField = field(0) + // IsValid reports whether the field identifier is valid. func (f field) IsValid() bool { - return f != ^field(0) + return f != invalidField } -// Bytes returns the address of a []byte field in the struct. -func structPointer_Bytes(p structPointer, f field) *[]byte { - return (*[]byte)(unsafe.Pointer(uintptr(p) + uintptr(f))) +// The pointer type below is for the new table-driven encoder/decoder. +// The implementation here uses unsafe.Pointer to create a generic pointer. +// In pointer_reflect.go we use reflect instead of unsafe to implement +// the same (but slower) interface. +type pointer struct { + p unsafe.Pointer } -// BytesSlice returns the address of a [][]byte field in the struct. -func structPointer_BytesSlice(p structPointer, f field) *[][]byte { - return (*[][]byte)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} +// size of pointer +var ptrSize = unsafe.Sizeof(uintptr(0)) -// Bool returns the address of a *bool field in the struct. -func structPointer_Bool(p structPointer, f field) **bool { - return (**bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) +// toPointer converts an interface of pointer type to a pointer +// that points to the same target. +func toPointer(i *Message) pointer { + // Super-tricky - read pointer out of data word of interface value. + // Saves ~25ns over the equivalent: + // return valToPointer(reflect.ValueOf(*i)) + return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]} } -// BoolVal returns the address of a bool field in the struct. -func structPointer_BoolVal(p structPointer, f field) *bool { - return (*bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) +// toAddrPointer converts an interface to a pointer that points to +// the interface data. +func toAddrPointer(i *interface{}, isptr bool) pointer { + // Super-tricky - read or get the address of data word of interface value. + if isptr { + // The interface is of pointer type, thus it is a direct interface. + // The data word is the pointer data itself. We take its address. + return pointer{p: unsafe.Pointer(uintptr(unsafe.Pointer(i)) + ptrSize)} + } + // The interface is not of pointer type. The data word is the pointer + // to the data. + return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]} } -// BoolSlice returns the address of a []bool field in the struct. -func structPointer_BoolSlice(p structPointer, f field) *[]bool { - return (*[]bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) +// valToPointer converts v to a pointer. v must be of pointer type. +func valToPointer(v reflect.Value) pointer { + return pointer{p: unsafe.Pointer(v.Pointer())} } -// String returns the address of a *string field in the struct. -func structPointer_String(p structPointer, f field) **string { - return (**string)(unsafe.Pointer(uintptr(p) + uintptr(f))) +// offset converts from a pointer to a structure to a pointer to +// one of its fields. +func (p pointer) offset(f field) pointer { + // For safety, we should panic if !f.IsValid, however calling panic causes + // this to no longer be inlineable, which is a serious performance cost. + /* + if !f.IsValid() { + panic("invalid field") + } + */ + return pointer{p: unsafe.Pointer(uintptr(p.p) + uintptr(f))} } -// StringVal returns the address of a string field in the struct. -func structPointer_StringVal(p structPointer, f field) *string { - return (*string)(unsafe.Pointer(uintptr(p) + uintptr(f))) +func (p pointer) isNil() bool { + return p.p == nil } -// StringSlice returns the address of a []string field in the struct. -func structPointer_StringSlice(p structPointer, f field) *[]string { - return (*[]string)(unsafe.Pointer(uintptr(p) + uintptr(f))) +func (p pointer) toInt64() *int64 { + return (*int64)(p.p) } - -// ExtMap returns the address of an extension map field in the struct. -func structPointer_Extensions(p structPointer, f field) *XXX_InternalExtensions { - return (*XXX_InternalExtensions)(unsafe.Pointer(uintptr(p) + uintptr(f))) +func (p pointer) toInt64Ptr() **int64 { + return (**int64)(p.p) } - -func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension { - return (*map[int32]Extension)(unsafe.Pointer(uintptr(p) + uintptr(f))) +func (p pointer) toInt64Slice() *[]int64 { + return (*[]int64)(p.p) } - -// NewAt returns the reflect.Value for a pointer to a field in the struct. -func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value { - return reflect.NewAt(typ, unsafe.Pointer(uintptr(p)+uintptr(f))) +func (p pointer) toInt32() *int32 { + return (*int32)(p.p) } -// SetStructPointer writes a *struct field in the struct. -func structPointer_SetStructPointer(p structPointer, f field, q structPointer) { - *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) = q +// See pointer_reflect.go for why toInt32Ptr/Slice doesn't exist. +/* + func (p pointer) toInt32Ptr() **int32 { + return (**int32)(p.p) + } + func (p pointer) toInt32Slice() *[]int32 { + return (*[]int32)(p.p) + } +*/ +func (p pointer) getInt32Ptr() *int32 { + return *(**int32)(p.p) } - -// GetStructPointer reads a *struct field in the struct. -func structPointer_GetStructPointer(p structPointer, f field) structPointer { - return *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) +func (p pointer) setInt32Ptr(v int32) { + *(**int32)(p.p) = &v } -// StructPointerSlice the address of a []*struct field in the struct. -func structPointer_StructPointerSlice(p structPointer, f field) *structPointerSlice { - return (*structPointerSlice)(unsafe.Pointer(uintptr(p) + uintptr(f))) +// getInt32Slice loads a []int32 from p. +// The value returned is aliased with the original slice. +// This behavior differs from the implementation in pointer_reflect.go. +func (p pointer) getInt32Slice() []int32 { + return *(*[]int32)(p.p) } -// A structPointerSlice represents a slice of pointers to structs (themselves submessages or groups). -type structPointerSlice []structPointer - -func (v *structPointerSlice) Len() int { return len(*v) } -func (v *structPointerSlice) Index(i int) structPointer { return (*v)[i] } -func (v *structPointerSlice) Append(p structPointer) { *v = append(*v, p) } - -// A word32 is the address of a "pointer to 32-bit value" field. -type word32 **uint32 - -// IsNil reports whether *v is nil. -func word32_IsNil(p word32) bool { - return *p == nil +// setInt32Slice stores a []int32 to p. +// The value set is aliased with the input slice. +// This behavior differs from the implementation in pointer_reflect.go. +func (p pointer) setInt32Slice(v []int32) { + *(*[]int32)(p.p) = v } -// Set sets *v to point at a newly allocated word set to x. -func word32_Set(p word32, o *Buffer, x uint32) { - if len(o.uint32s) == 0 { - o.uint32s = make([]uint32, uint32PoolSize) - } - o.uint32s[0] = x - *p = &o.uint32s[0] - o.uint32s = o.uint32s[1:] +// TODO: Can we get rid of appendInt32Slice and use setInt32Slice instead? +func (p pointer) appendInt32Slice(v int32) { + s := (*[]int32)(p.p) + *s = append(*s, v) } -// Get gets the value pointed at by *v. -func word32_Get(p word32) uint32 { - return **p +func (p pointer) toUint64() *uint64 { + return (*uint64)(p.p) } - -// Word32 returns the address of a *int32, *uint32, *float32, or *enum field in the struct. -func structPointer_Word32(p structPointer, f field) word32 { - return word32((**uint32)(unsafe.Pointer(uintptr(p) + uintptr(f)))) +func (p pointer) toUint64Ptr() **uint64 { + return (**uint64)(p.p) } - -// A word32Val is the address of a 32-bit value field. -type word32Val *uint32 - -// Set sets *p to x. -func word32Val_Set(p word32Val, x uint32) { - *p = x +func (p pointer) toUint64Slice() *[]uint64 { + return (*[]uint64)(p.p) } - -// Get gets the value pointed at by p. -func word32Val_Get(p word32Val) uint32 { - return *p +func (p pointer) toUint32() *uint32 { + return (*uint32)(p.p) } - -// Word32Val returns the address of a *int32, *uint32, *float32, or *enum field in the struct. -func structPointer_Word32Val(p structPointer, f field) word32Val { - return word32Val((*uint32)(unsafe.Pointer(uintptr(p) + uintptr(f)))) +func (p pointer) toUint32Ptr() **uint32 { + return (**uint32)(p.p) } - -// A word32Slice is a slice of 32-bit values. -type word32Slice []uint32 - -func (v *word32Slice) Append(x uint32) { *v = append(*v, x) } -func (v *word32Slice) Len() int { return len(*v) } -func (v *word32Slice) Index(i int) uint32 { return (*v)[i] } - -// Word32Slice returns the address of a []int32, []uint32, []float32, or []enum field in the struct. -func structPointer_Word32Slice(p structPointer, f field) *word32Slice { - return (*word32Slice)(unsafe.Pointer(uintptr(p) + uintptr(f))) +func (p pointer) toUint32Slice() *[]uint32 { + return (*[]uint32)(p.p) } - -// word64 is like word32 but for 64-bit values. -type word64 **uint64 - -func word64_Set(p word64, o *Buffer, x uint64) { - if len(o.uint64s) == 0 { - o.uint64s = make([]uint64, uint64PoolSize) - } - o.uint64s[0] = x - *p = &o.uint64s[0] - o.uint64s = o.uint64s[1:] +func (p pointer) toBool() *bool { + return (*bool)(p.p) } - -func word64_IsNil(p word64) bool { - return *p == nil +func (p pointer) toBoolPtr() **bool { + return (**bool)(p.p) } - -func word64_Get(p word64) uint64 { - return **p +func (p pointer) toBoolSlice() *[]bool { + return (*[]bool)(p.p) +} +func (p pointer) toFloat64() *float64 { + return (*float64)(p.p) +} +func (p pointer) toFloat64Ptr() **float64 { + return (**float64)(p.p) +} +func (p pointer) toFloat64Slice() *[]float64 { + return (*[]float64)(p.p) +} +func (p pointer) toFloat32() *float32 { + return (*float32)(p.p) +} +func (p pointer) toFloat32Ptr() **float32 { + return (**float32)(p.p) +} +func (p pointer) toFloat32Slice() *[]float32 { + return (*[]float32)(p.p) +} +func (p pointer) toString() *string { + return (*string)(p.p) +} +func (p pointer) toStringPtr() **string { + return (**string)(p.p) +} +func (p pointer) toStringSlice() *[]string { + return (*[]string)(p.p) +} +func (p pointer) toBytes() *[]byte { + return (*[]byte)(p.p) +} +func (p pointer) toBytesSlice() *[][]byte { + return (*[][]byte)(p.p) +} +func (p pointer) toExtensions() *XXX_InternalExtensions { + return (*XXX_InternalExtensions)(p.p) +} +func (p pointer) toOldExtensions() *map[int32]Extension { + return (*map[int32]Extension)(p.p) } -func structPointer_Word64(p structPointer, f field) word64 { - return word64((**uint64)(unsafe.Pointer(uintptr(p) + uintptr(f)))) +// getPointerSlice loads []*T from p as a []pointer. +// The value returned is aliased with the original slice. +// This behavior differs from the implementation in pointer_reflect.go. +func (p pointer) getPointerSlice() []pointer { + // Super-tricky - p should point to a []*T where T is a + // message type. We load it as []pointer. + return *(*[]pointer)(p.p) } -// word64Val is like word32Val but for 64-bit values. -type word64Val *uint64 +// setPointerSlice stores []pointer into p as a []*T. +// The value set is aliased with the input slice. +// This behavior differs from the implementation in pointer_reflect.go. +func (p pointer) setPointerSlice(v []pointer) { + // Super-tricky - p should point to a []*T where T is a + // message type. We store it as []pointer. + *(*[]pointer)(p.p) = v +} -func word64Val_Set(p word64Val, o *Buffer, x uint64) { - *p = x +// getPointer loads the pointer at p and returns it. +func (p pointer) getPointer() pointer { + return pointer{p: *(*unsafe.Pointer)(p.p)} } -func word64Val_Get(p word64Val) uint64 { - return *p +// setPointer stores the pointer q at p. +func (p pointer) setPointer(q pointer) { + *(*unsafe.Pointer)(p.p) = q.p } -func structPointer_Word64Val(p structPointer, f field) word64Val { - return word64Val((*uint64)(unsafe.Pointer(uintptr(p) + uintptr(f)))) +// append q to the slice pointed to by p. +func (p pointer) appendPointer(q pointer) { + s := (*[]unsafe.Pointer)(p.p) + *s = append(*s, q.p) } -// word64Slice is like word32Slice but for 64-bit values. -type word64Slice []uint64 +// getInterfacePointer returns a pointer that points to the +// interface data of the interface pointed by p. +func (p pointer) getInterfacePointer() pointer { + // Super-tricky - read pointer out of data word of interface value. + return pointer{p: (*(*[2]unsafe.Pointer)(p.p))[1]} +} -func (v *word64Slice) Append(x uint64) { *v = append(*v, x) } -func (v *word64Slice) Len() int { return len(*v) } -func (v *word64Slice) Index(i int) uint64 { return (*v)[i] } +// asPointerTo returns a reflect.Value that is a pointer to an +// object of type t stored at p. +func (p pointer) asPointerTo(t reflect.Type) reflect.Value { + return reflect.NewAt(t, p.p) +} -func structPointer_Word64Slice(p structPointer, f field) *word64Slice { - return (*word64Slice)(unsafe.Pointer(uintptr(p) + uintptr(f))) +func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo { + return (*unmarshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) +} +func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) { + atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) +} +func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo { + return (*marshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) +} +func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) { + atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) +} +func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo { + return (*mergeInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) +} +func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) { + atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) +} +func atomicLoadDiscardInfo(p **discardInfo) *discardInfo { + return (*discardInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) +} +func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) { + atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) } diff --git a/vendor/github.com/gogo/protobuf/proto/pointer_unsafe_gogo.go b/vendor/github.com/gogo/protobuf/proto/pointer_unsafe_gogo.go index f156a29f0..b354101b9 100644 --- a/vendor/github.com/gogo/protobuf/proto/pointer_unsafe_gogo.go +++ b/vendor/github.com/gogo/protobuf/proto/pointer_unsafe_gogo.go @@ -1,6 +1,6 @@ // Protocol Buffers for Go with Gadgets // -// Copyright (c) 2013, The GoGo Authors. All rights reserved. +// Copyright (c) 2018, The GoGo Authors. All rights reserved. // http://github.com/gogo/protobuf // // Redistribution and use in source and binary forms, with or without @@ -26,7 +26,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// +build !appengine,!js +// +build !purego !appengine,!js // This file contains the implementation of the proto field accesses using package unsafe. @@ -37,92 +37,20 @@ import ( "unsafe" ) -func structPointer_InterfaceAt(p structPointer, f field, t reflect.Type) interface{} { - point := unsafe.Pointer(uintptr(p) + uintptr(f)) - r := reflect.NewAt(t, point) - return r.Interface() +func (p pointer) getRef() pointer { + return pointer{p: (unsafe.Pointer)(&p.p)} } -func structPointer_InterfaceRef(p structPointer, f field, t reflect.Type) interface{} { - point := unsafe.Pointer(uintptr(p) + uintptr(f)) - r := reflect.NewAt(t, point) - if r.Elem().IsNil() { - return nil - } - return r.Elem().Interface() +func (p pointer) appendRef(v pointer, typ reflect.Type) { + slice := p.getSlice(typ) + elem := v.asPointerTo(typ).Elem() + newSlice := reflect.Append(slice, elem) + slice.Set(newSlice) } -func copyUintPtr(oldptr, newptr uintptr, size int) { - oldbytes := make([]byte, 0) - oldslice := (*reflect.SliceHeader)(unsafe.Pointer(&oldbytes)) - oldslice.Data = oldptr - oldslice.Len = size - oldslice.Cap = size - newbytes := make([]byte, 0) - newslice := (*reflect.SliceHeader)(unsafe.Pointer(&newbytes)) - newslice.Data = newptr - newslice.Len = size - newslice.Cap = size - copy(newbytes, oldbytes) -} - -func structPointer_Copy(oldptr structPointer, newptr structPointer, size int) { - copyUintPtr(uintptr(oldptr), uintptr(newptr), size) -} - -func appendStructPointer(base structPointer, f field, typ reflect.Type) structPointer { - size := typ.Elem().Size() - - oldHeader := structPointer_GetSliceHeader(base, f) - oldSlice := reflect.NewAt(typ, unsafe.Pointer(oldHeader)).Elem() - newLen := oldHeader.Len + 1 - newSlice := reflect.MakeSlice(typ, newLen, newLen) - reflect.Copy(newSlice, oldSlice) - bas := toStructPointer(newSlice) - oldHeader.Data = uintptr(bas) - oldHeader.Len = newLen - oldHeader.Cap = newLen - - return structPointer(unsafe.Pointer(uintptr(unsafe.Pointer(bas)) + uintptr(uintptr(newLen-1)*size))) -} - -func structPointer_FieldPointer(p structPointer, f field) structPointer { - return structPointer(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -func structPointer_GetRefStructPointer(p structPointer, f field) structPointer { - return structPointer((*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f)))) -} - -func structPointer_GetSliceHeader(p structPointer, f field) *reflect.SliceHeader { - return (*reflect.SliceHeader)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -func structPointer_Add(p structPointer, size field) structPointer { - return structPointer(unsafe.Pointer(uintptr(p) + uintptr(size))) -} - -func structPointer_Len(p structPointer, f field) int { - return len(*(*[]interface{})(unsafe.Pointer(structPointer_GetRefStructPointer(p, f)))) -} - -func structPointer_StructRefSlice(p structPointer, f field, size uintptr) *structRefSlice { - return &structRefSlice{p: p, f: f, size: size} -} - -// A structRefSlice represents a slice of structs (themselves submessages or groups). -type structRefSlice struct { - p structPointer - f field - size uintptr -} - -func (v *structRefSlice) Len() int { - return structPointer_Len(v.p, v.f) -} - -func (v *structRefSlice) Index(i int) structPointer { - ss := structPointer_GetStructPointer(v.p, v.f) - ss1 := structPointer_GetRefStructPointer(ss, 0) - return structPointer_Add(ss1, field(uintptr(i)*v.size)) +func (p pointer) getSlice(typ reflect.Type) reflect.Value { + sliceTyp := reflect.SliceOf(typ) + slice := p.asPointerTo(sliceTyp) + slice = slice.Elem() + return slice } diff --git a/vendor/github.com/gogo/protobuf/proto/properties.go b/vendor/github.com/gogo/protobuf/proto/properties.go index 2a69e8862..7a5e28efe 100644 --- a/vendor/github.com/gogo/protobuf/proto/properties.go +++ b/vendor/github.com/gogo/protobuf/proto/properties.go @@ -63,42 +63,6 @@ const ( WireFixed32 = 5 ) -const startSize = 10 // initial slice/string sizes - -// Encoders are defined in encode.go -// An encoder outputs the full representation of a field, including its -// tag and encoder type. -type encoder func(p *Buffer, prop *Properties, base structPointer) error - -// A valueEncoder encodes a single integer in a particular encoding. -type valueEncoder func(o *Buffer, x uint64) error - -// Sizers are defined in encode.go -// A sizer returns the encoded size of a field, including its tag and encoder -// type. -type sizer func(prop *Properties, base structPointer) int - -// A valueSizer returns the encoded size of a single integer in a particular -// encoding. -type valueSizer func(x uint64) int - -// Decoders are defined in decode.go -// A decoder creates a value from its wire representation. -// Unrecognized subelements are saved in unrec. -type decoder func(p *Buffer, prop *Properties, base structPointer) error - -// A valueDecoder decodes a single integer in a particular encoding. -type valueDecoder func(o *Buffer) (x uint64, err error) - -// A oneofMarshaler does the marshaling for all oneof fields in a message. -type oneofMarshaler func(Message, *Buffer) error - -// A oneofUnmarshaler does the unmarshaling for a oneof field in a message. -type oneofUnmarshaler func(Message, int, int, *Buffer) (bool, error) - -// A oneofSizer does the sizing for all oneof fields in a message. -type oneofSizer func(Message) int - // tagMap is an optimization over map[int]int for typical protocol buffer // use-cases. Encoded protocol buffers are often in tag order with small tag // numbers. @@ -145,13 +109,6 @@ type StructProperties struct { decoderTags tagMap // map from proto tag to struct field number decoderOrigNames map[string]int // map from original name to struct field number order []int // list of struct field numbers in tag order - unrecField field // field id of the XXX_unrecognized []byte field - extendable bool // is this an extendable proto - - oneofMarshaler oneofMarshaler - oneofUnmarshaler oneofUnmarshaler - oneofSizer oneofSizer - stype reflect.Type // OneofTypes contains information about the oneof fields in this message. // It is keyed by the original name of a field. @@ -197,36 +154,19 @@ type Properties struct { StdTime bool StdDuration bool - enc encoder - valEnc valueEncoder // set for bool and numeric types only - field field - tagcode []byte // encoding of EncodeVarint((Tag<<3)|WireType) - tagbuf [8]byte - stype reflect.Type // set for struct types only - sstype reflect.Type // set for slices of structs types only - ctype reflect.Type // set for custom types only - sprop *StructProperties // set for struct types only - isMarshaler bool - isUnmarshaler bool + stype reflect.Type // set for struct types only + ctype reflect.Type // set for custom types only + sprop *StructProperties // set for struct types only mtype reflect.Type // set for map types only mkeyprop *Properties // set for map types only mvalprop *Properties // set for map types only - - size sizer - valSize valueSizer // set for bool and numeric types only - - dec decoder - valDec valueDecoder // set for bool and numeric types only - - // If this is a packable field, this will be the decoder for the packed version of the field. - packedDec decoder } // String formats the properties in the protobuf struct field tag style. func (p *Properties) String() string { s := p.Wire - s = "," + s += "," s += strconv.Itoa(p.Tag) if p.Required { s += ",req" @@ -272,29 +212,14 @@ func (p *Properties) Parse(s string) { switch p.Wire { case "varint": p.WireType = WireVarint - p.valEnc = (*Buffer).EncodeVarint - p.valDec = (*Buffer).DecodeVarint - p.valSize = sizeVarint case "fixed32": p.WireType = WireFixed32 - p.valEnc = (*Buffer).EncodeFixed32 - p.valDec = (*Buffer).DecodeFixed32 - p.valSize = sizeFixed32 case "fixed64": p.WireType = WireFixed64 - p.valEnc = (*Buffer).EncodeFixed64 - p.valDec = (*Buffer).DecodeFixed64 - p.valSize = sizeFixed64 case "zigzag32": p.WireType = WireVarint - p.valEnc = (*Buffer).EncodeZigzag32 - p.valDec = (*Buffer).DecodeZigzag32 - p.valSize = sizeZigzag32 case "zigzag64": p.WireType = WireVarint - p.valEnc = (*Buffer).EncodeZigzag64 - p.valDec = (*Buffer).DecodeZigzag64 - p.valSize = sizeZigzag64 case "bytes", "group": p.WireType = WireBytes // no numeric converter for non-numeric types @@ -309,6 +234,7 @@ func (p *Properties) Parse(s string) { return } +outer: for i := 2; i < len(fields); i++ { f := fields[i] switch { @@ -336,7 +262,7 @@ func (p *Properties) Parse(s string) { if i+1 < len(fields) { // Commas aren't escaped, and def is always last. p.Default += "," + strings.Join(fields[i+1:], ",") - break + break outer } case strings.HasPrefix(f, "embedded="): p.OrigName = strings.Split(f, "=")[1] @@ -352,292 +278,43 @@ func (p *Properties) Parse(s string) { } } -func logNoSliceEnc(t1, t2 reflect.Type) { - fmt.Fprintf(os.Stderr, "proto: no slice oenc for %T = []%T\n", t1, t2) -} - var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem() -// Initialize the fields for encoding and decoding. -func (p *Properties) setEncAndDec(typ reflect.Type, f *reflect.StructField, lockGetProp bool) { - p.enc = nil - p.dec = nil - p.size = nil +// setFieldProps initializes the field properties for submessages and maps. +func (p *Properties) setFieldProps(typ reflect.Type, f *reflect.StructField, lockGetProp bool) { isMap := typ.Kind() == reflect.Map if len(p.CustomType) > 0 && !isMap { - p.setCustomEncAndDec(typ) + p.ctype = typ p.setTag(lockGetProp) return } if p.StdTime && !isMap { - p.setTimeEncAndDec(typ) p.setTag(lockGetProp) return } if p.StdDuration && !isMap { - p.setDurationEncAndDec(typ) p.setTag(lockGetProp) return } switch t1 := typ; t1.Kind() { - default: - fmt.Fprintf(os.Stderr, "proto: no coders for %v\n", t1) - - // proto3 scalar types - - case reflect.Bool: - if p.proto3 { - p.enc = (*Buffer).enc_proto3_bool - p.dec = (*Buffer).dec_proto3_bool - p.size = size_proto3_bool - } else { - p.enc = (*Buffer).enc_ref_bool - p.dec = (*Buffer).dec_proto3_bool - p.size = size_ref_bool - } - case reflect.Int32: - if p.proto3 { - p.enc = (*Buffer).enc_proto3_int32 - p.dec = (*Buffer).dec_proto3_int32 - p.size = size_proto3_int32 - } else { - p.enc = (*Buffer).enc_ref_int32 - p.dec = (*Buffer).dec_proto3_int32 - p.size = size_ref_int32 - } - case reflect.Uint32: - if p.proto3 { - p.enc = (*Buffer).enc_proto3_uint32 - p.dec = (*Buffer).dec_proto3_int32 // can reuse - p.size = size_proto3_uint32 - } else { - p.enc = (*Buffer).enc_ref_uint32 - p.dec = (*Buffer).dec_proto3_int32 // can reuse - p.size = size_ref_uint32 - } - case reflect.Int64, reflect.Uint64: - if p.proto3 { - p.enc = (*Buffer).enc_proto3_int64 - p.dec = (*Buffer).dec_proto3_int64 - p.size = size_proto3_int64 - } else { - p.enc = (*Buffer).enc_ref_int64 - p.dec = (*Buffer).dec_proto3_int64 - p.size = size_ref_int64 - } - case reflect.Float32: - if p.proto3 { - p.enc = (*Buffer).enc_proto3_uint32 // can just treat them as bits - p.dec = (*Buffer).dec_proto3_int32 - p.size = size_proto3_uint32 - } else { - p.enc = (*Buffer).enc_ref_uint32 // can just treat them as bits - p.dec = (*Buffer).dec_proto3_int32 - p.size = size_ref_uint32 - } - case reflect.Float64: - if p.proto3 { - p.enc = (*Buffer).enc_proto3_int64 // can just treat them as bits - p.dec = (*Buffer).dec_proto3_int64 - p.size = size_proto3_int64 - } else { - p.enc = (*Buffer).enc_ref_int64 // can just treat them as bits - p.dec = (*Buffer).dec_proto3_int64 - p.size = size_ref_int64 - } - case reflect.String: - if p.proto3 { - p.enc = (*Buffer).enc_proto3_string - p.dec = (*Buffer).dec_proto3_string - p.size = size_proto3_string - } else { - p.enc = (*Buffer).enc_ref_string - p.dec = (*Buffer).dec_proto3_string - p.size = size_ref_string - } case reflect.Struct: p.stype = typ - p.isMarshaler = isMarshaler(typ) - p.isUnmarshaler = isUnmarshaler(typ) - if p.Wire == "bytes" { - p.enc = (*Buffer).enc_ref_struct_message - p.dec = (*Buffer).dec_ref_struct_message - p.size = size_ref_struct_message - } else { - fmt.Fprintf(os.Stderr, "proto: no coders for struct %T\n", typ) - } - case reflect.Ptr: - switch t2 := t1.Elem(); t2.Kind() { - default: - fmt.Fprintf(os.Stderr, "proto: no encoder function for %v -> %v\n", t1, t2) - break - case reflect.Bool: - p.enc = (*Buffer).enc_bool - p.dec = (*Buffer).dec_bool - p.size = size_bool - case reflect.Int32: - p.enc = (*Buffer).enc_int32 - p.dec = (*Buffer).dec_int32 - p.size = size_int32 - case reflect.Uint32: - p.enc = (*Buffer).enc_uint32 - p.dec = (*Buffer).dec_int32 // can reuse - p.size = size_uint32 - case reflect.Int64, reflect.Uint64: - p.enc = (*Buffer).enc_int64 - p.dec = (*Buffer).dec_int64 - p.size = size_int64 - case reflect.Float32: - p.enc = (*Buffer).enc_uint32 // can just treat them as bits - p.dec = (*Buffer).dec_int32 - p.size = size_uint32 - case reflect.Float64: - p.enc = (*Buffer).enc_int64 // can just treat them as bits - p.dec = (*Buffer).dec_int64 - p.size = size_int64 - case reflect.String: - p.enc = (*Buffer).enc_string - p.dec = (*Buffer).dec_string - p.size = size_string - case reflect.Struct: + if t1.Elem().Kind() == reflect.Struct { p.stype = t1.Elem() - p.isMarshaler = isMarshaler(t1) - p.isUnmarshaler = isUnmarshaler(t1) - if p.Wire == "bytes" { - p.enc = (*Buffer).enc_struct_message - p.dec = (*Buffer).dec_struct_message - p.size = size_struct_message - } else { - p.enc = (*Buffer).enc_struct_group - p.dec = (*Buffer).dec_struct_group - p.size = size_struct_group - } } - case reflect.Slice: switch t2 := t1.Elem(); t2.Kind() { - default: - logNoSliceEnc(t1, t2) - break - case reflect.Bool: - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_bool - p.size = size_slice_packed_bool - } else { - p.enc = (*Buffer).enc_slice_bool - p.size = size_slice_bool - } - p.dec = (*Buffer).dec_slice_bool - p.packedDec = (*Buffer).dec_slice_packed_bool - case reflect.Int32: - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_int32 - p.size = size_slice_packed_int32 - } else { - p.enc = (*Buffer).enc_slice_int32 - p.size = size_slice_int32 - } - p.dec = (*Buffer).dec_slice_int32 - p.packedDec = (*Buffer).dec_slice_packed_int32 - case reflect.Uint32: - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_uint32 - p.size = size_slice_packed_uint32 - } else { - p.enc = (*Buffer).enc_slice_uint32 - p.size = size_slice_uint32 - } - p.dec = (*Buffer).dec_slice_int32 - p.packedDec = (*Buffer).dec_slice_packed_int32 - case reflect.Int64, reflect.Uint64: - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_int64 - p.size = size_slice_packed_int64 - } else { - p.enc = (*Buffer).enc_slice_int64 - p.size = size_slice_int64 - } - p.dec = (*Buffer).dec_slice_int64 - p.packedDec = (*Buffer).dec_slice_packed_int64 - case reflect.Uint8: - p.dec = (*Buffer).dec_slice_byte - if p.proto3 { - p.enc = (*Buffer).enc_proto3_slice_byte - p.size = size_proto3_slice_byte - } else { - p.enc = (*Buffer).enc_slice_byte - p.size = size_slice_byte - } - case reflect.Float32, reflect.Float64: - switch t2.Bits() { - case 32: - // can just treat them as bits - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_uint32 - p.size = size_slice_packed_uint32 - } else { - p.enc = (*Buffer).enc_slice_uint32 - p.size = size_slice_uint32 - } - p.dec = (*Buffer).dec_slice_int32 - p.packedDec = (*Buffer).dec_slice_packed_int32 - case 64: - // can just treat them as bits - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_int64 - p.size = size_slice_packed_int64 - } else { - p.enc = (*Buffer).enc_slice_int64 - p.size = size_slice_int64 - } - p.dec = (*Buffer).dec_slice_int64 - p.packedDec = (*Buffer).dec_slice_packed_int64 - default: - logNoSliceEnc(t1, t2) - break - } - case reflect.String: - p.enc = (*Buffer).enc_slice_string - p.dec = (*Buffer).dec_slice_string - p.size = size_slice_string case reflect.Ptr: switch t3 := t2.Elem(); t3.Kind() { - default: - fmt.Fprintf(os.Stderr, "proto: no ptr oenc for %T -> %T -> %T\n", t1, t2, t3) - break case reflect.Struct: - p.stype = t2.Elem() - p.isMarshaler = isMarshaler(t2) - p.isUnmarshaler = isUnmarshaler(t2) - if p.Wire == "bytes" { - p.enc = (*Buffer).enc_slice_struct_message - p.dec = (*Buffer).dec_slice_struct_message - p.size = size_slice_struct_message - } else { - p.enc = (*Buffer).enc_slice_struct_group - p.dec = (*Buffer).dec_slice_struct_group - p.size = size_slice_struct_group - } - } - case reflect.Slice: - switch t2.Elem().Kind() { - default: - fmt.Fprintf(os.Stderr, "proto: no slice elem oenc for %T -> %T -> %T\n", t1, t2, t2.Elem()) - break - case reflect.Uint8: - p.enc = (*Buffer).enc_slice_slice_byte - p.dec = (*Buffer).dec_slice_slice_byte - p.size = size_slice_slice_byte + p.stype = t3 } case reflect.Struct: - p.setSliceOfNonPointerStructs(t1) + p.stype = t2 } case reflect.Map: - p.enc = (*Buffer).enc_new_map - p.dec = (*Buffer).dec_new_map - p.size = size_new_map p.mtype = t1 p.mkeyprop = &Properties{} @@ -659,20 +336,6 @@ func (p *Properties) setEncAndDec(typ reflect.Type, f *reflect.StructField, lock } func (p *Properties) setTag(lockGetProp bool) { - // precalculate tag code - wire := p.WireType - if p.Packed { - wire = WireBytes - } - x := uint32(p.Tag)<<3 | uint32(wire) - i := 0 - for i = 0; x > 127; i++ { - p.tagbuf[i] = 0x80 | uint8(x&0x7F) - x >>= 7 - } - p.tagbuf[i] = uint8(x) - p.tagcode = p.tagbuf[0 : i+1] - if p.stype != nil { if lockGetProp { p.sprop = GetProperties(p.stype) @@ -683,20 +346,9 @@ func (p *Properties) setTag(lockGetProp bool) { } var ( - marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() - unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem() + marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() ) -// isMarshaler reports whether type t implements Marshaler. -func isMarshaler(t reflect.Type) bool { - return t.Implements(marshalerType) -} - -// isUnmarshaler reports whether type t implements Unmarshaler. -func isUnmarshaler(t reflect.Type) bool { - return t.Implements(unmarshalerType) -} - // Init populates the properties from a protocol buffer struct tag. func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) { p.init(typ, name, tag, f, true) @@ -706,14 +358,11 @@ func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructF // "bytes,49,opt,def=hello!" p.Name = name p.OrigName = name - if f != nil { - p.field = toField(f) - } if tag == "" { return } p.Parse(tag) - p.setEncAndDec(typ, f, lockGetProp) + p.setFieldProps(typ, f, lockGetProp) } var ( @@ -763,10 +412,6 @@ func getPropertiesLocked(t reflect.Type) *StructProperties { propertiesMap[t] = prop // build properties - prop.extendable = reflect.PtrTo(t).Implements(extendableProtoType) || - reflect.PtrTo(t).Implements(extendableProtoV1Type) || - reflect.PtrTo(t).Implements(extendableBytesType) - prop.unrecField = invalidField prop.Prop = make([]*Properties, t.NumField()) prop.order = make([]int, t.NumField()) @@ -777,23 +422,6 @@ func getPropertiesLocked(t reflect.Type) *StructProperties { name := f.Name p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false) - if f.Name == "XXX_InternalExtensions" { // special case - p.enc = (*Buffer).enc_exts - p.dec = nil // not needed - p.size = size_exts - } else if f.Name == "XXX_extensions" { // special case - if len(f.Tag.Get("protobuf")) > 0 { - p.enc = (*Buffer).enc_ext_slice_byte - p.dec = nil // not needed - p.size = size_ext_slice_byte - } else { - p.enc = (*Buffer).enc_map - p.dec = nil // not needed - p.size = size_map - } - } else if f.Name == "XXX_unrecognized" { // special case - prop.unrecField = toField(&f) - } oneof := f.Tag.Get("protobuf_oneof") // special case if oneof != "" { isOneofMessage = true @@ -809,9 +437,6 @@ func getPropertiesLocked(t reflect.Type) *StructProperties { } print("\n") } - if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") && oneof == "" { - fmt.Fprintln(os.Stderr, "proto: no encoder for", f.Name, f.Type.String(), "[GetProperties]") - } } // Re-order prop.order. @@ -822,8 +447,7 @@ func getPropertiesLocked(t reflect.Type) *StructProperties { } if om, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); isOneofMessage && ok { var oots []interface{} - prop.oneofMarshaler, prop.oneofUnmarshaler, prop.oneofSizer, oots = om.XXX_OneofFuncs() - prop.stype = t + _, _, _, oots = om.XXX_OneofFuncs() // Interpret oneof metadata. prop.OneofTypes = make(map[string]*OneofProperties) @@ -873,30 +497,6 @@ func getPropertiesLocked(t reflect.Type) *StructProperties { return prop } -// Return the Properties object for the x[0]'th field of the structure. -func propByIndex(t reflect.Type, x []int) *Properties { - if len(x) != 1 { - fmt.Fprintf(os.Stderr, "proto: field index dimension %d (not 1) for type %s\n", len(x), t) - return nil - } - prop := GetProperties(t) - return prop.Prop[x[0]] -} - -// Get the address and type of a pointer to a struct from an interface. -func getbase(pb Message) (t reflect.Type, b structPointer, err error) { - if pb == nil { - err = ErrNil - return - } - // get the reflect type of the pointer to the struct. - t = reflect.TypeOf(pb) - // get the address of the struct. - value := reflect.ValueOf(pb) - b = toStructPointer(value) - return -} - // A global registry of enum types. // The generated code will register the generated maps by calling RegisterEnum. @@ -925,20 +525,42 @@ func EnumValueMap(enumType string) map[string]int32 { // A registry of all linked message types. // The string is a fully-qualified proto name ("pkg.Message"). var ( - protoTypes = make(map[string]reflect.Type) - revProtoTypes = make(map[reflect.Type]string) + protoTypedNils = make(map[string]Message) // a map from proto names to typed nil pointers + protoMapTypes = make(map[string]reflect.Type) // a map from proto names to map types + revProtoTypes = make(map[reflect.Type]string) ) // RegisterType is called from generated code and maps from the fully qualified // proto name to the type (pointer to struct) of the protocol buffer. func RegisterType(x Message, name string) { - if _, ok := protoTypes[name]; ok { + if _, ok := protoTypedNils[name]; ok { // TODO: Some day, make this a panic. log.Printf("proto: duplicate proto type registered: %s", name) return } t := reflect.TypeOf(x) - protoTypes[name] = t + if v := reflect.ValueOf(x); v.Kind() == reflect.Ptr && v.Pointer() == 0 { + // Generated code always calls RegisterType with nil x. + // This check is just for extra safety. + protoTypedNils[name] = x + } else { + protoTypedNils[name] = reflect.Zero(t).Interface().(Message) + } + revProtoTypes[t] = name +} + +// RegisterMapType is called from generated code and maps from the fully qualified +// proto name to the native map type of the proto map definition. +func RegisterMapType(x interface{}, name string) { + if reflect.TypeOf(x).Kind() != reflect.Map { + panic(fmt.Sprintf("RegisterMapType(%T, %q); want map", x, name)) + } + if _, ok := protoMapTypes[name]; ok { + log.Printf("proto: duplicate proto type registered: %s", name) + return + } + t := reflect.TypeOf(x) + protoMapTypes[name] = t revProtoTypes[t] = name } @@ -954,7 +576,14 @@ func MessageName(x Message) string { } // MessageType returns the message type (pointer to struct) for a named message. -func MessageType(name string) reflect.Type { return protoTypes[name] } +// The type is not guaranteed to implement proto.Message if the name refers to a +// map entry. +func MessageType(name string) reflect.Type { + if t, ok := protoTypedNils[name]; ok { + return reflect.TypeOf(t) + } + return protoMapTypes[name] +} // A registry of all linked proto files. var ( diff --git a/vendor/github.com/gogo/protobuf/proto/properties_gogo.go b/vendor/github.com/gogo/protobuf/proto/properties_gogo.go index b6b7176c5..40ea3dd93 100644 --- a/vendor/github.com/gogo/protobuf/proto/properties_gogo.go +++ b/vendor/github.com/gogo/protobuf/proto/properties_gogo.go @@ -1,6 +1,6 @@ // Protocol Buffers for Go with Gadgets // -// Copyright (c) 2013, The GoGo Authors. All rights reserved. +// Copyright (c) 2018, The GoGo Authors. All rights reserved. // http://github.com/gogo/protobuf // // Redistribution and use in source and binary forms, with or without @@ -29,83 +29,8 @@ package proto import ( - "fmt" - "os" "reflect" ) -func (p *Properties) setCustomEncAndDec(typ reflect.Type) { - p.ctype = typ - if p.Repeated { - p.enc = (*Buffer).enc_custom_slice_bytes - p.dec = (*Buffer).dec_custom_slice_bytes - p.size = size_custom_slice_bytes - } else if typ.Kind() == reflect.Ptr { - p.enc = (*Buffer).enc_custom_bytes - p.dec = (*Buffer).dec_custom_bytes - p.size = size_custom_bytes - } else { - p.enc = (*Buffer).enc_custom_ref_bytes - p.dec = (*Buffer).dec_custom_ref_bytes - p.size = size_custom_ref_bytes - } -} - -func (p *Properties) setDurationEncAndDec(typ reflect.Type) { - if p.Repeated { - if typ.Elem().Kind() == reflect.Ptr { - p.enc = (*Buffer).enc_slice_duration - p.dec = (*Buffer).dec_slice_duration - p.size = size_slice_duration - } else { - p.enc = (*Buffer).enc_slice_ref_duration - p.dec = (*Buffer).dec_slice_ref_duration - p.size = size_slice_ref_duration - } - } else if typ.Kind() == reflect.Ptr { - p.enc = (*Buffer).enc_duration - p.dec = (*Buffer).dec_duration - p.size = size_duration - } else { - p.enc = (*Buffer).enc_ref_duration - p.dec = (*Buffer).dec_ref_duration - p.size = size_ref_duration - } -} - -func (p *Properties) setTimeEncAndDec(typ reflect.Type) { - if p.Repeated { - if typ.Elem().Kind() == reflect.Ptr { - p.enc = (*Buffer).enc_slice_time - p.dec = (*Buffer).dec_slice_time - p.size = size_slice_time - } else { - p.enc = (*Buffer).enc_slice_ref_time - p.dec = (*Buffer).dec_slice_ref_time - p.size = size_slice_ref_time - } - } else if typ.Kind() == reflect.Ptr { - p.enc = (*Buffer).enc_time - p.dec = (*Buffer).dec_time - p.size = size_time - } else { - p.enc = (*Buffer).enc_ref_time - p.dec = (*Buffer).dec_ref_time - p.size = size_ref_time - } - -} - -func (p *Properties) setSliceOfNonPointerStructs(typ reflect.Type) { - t2 := typ.Elem() - p.sstype = typ - p.stype = t2 - p.isMarshaler = isMarshaler(t2) - p.isUnmarshaler = isUnmarshaler(t2) - p.enc = (*Buffer).enc_slice_ref_struct_message - p.dec = (*Buffer).dec_slice_ref_struct_message - p.size = size_slice_ref_struct_message - if p.Wire != "bytes" { - fmt.Fprintf(os.Stderr, "proto: no ptr oenc for %T -> %T \n", typ, t2) - } -} +var sizerType = reflect.TypeOf((*Sizer)(nil)).Elem() +var protosizerType = reflect.TypeOf((*ProtoSizer)(nil)).Elem() diff --git a/vendor/github.com/gogo/protobuf/proto/table_marshal.go b/vendor/github.com/gogo/protobuf/proto/table_marshal.go new file mode 100644 index 000000000..255e7b508 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/table_marshal.go @@ -0,0 +1,2799 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2016 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import ( + "errors" + "fmt" + "math" + "reflect" + "sort" + "strconv" + "strings" + "sync" + "sync/atomic" + "unicode/utf8" +) + +// a sizer takes a pointer to a field and the size of its tag, computes the size of +// the encoded data. +type sizer func(pointer, int) int + +// a marshaler takes a byte slice, a pointer to a field, and its tag (in wire format), +// marshals the field to the end of the slice, returns the slice and error (if any). +type marshaler func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) + +// marshalInfo is the information used for marshaling a message. +type marshalInfo struct { + typ reflect.Type + fields []*marshalFieldInfo + unrecognized field // offset of XXX_unrecognized + extensions field // offset of XXX_InternalExtensions + v1extensions field // offset of XXX_extensions + sizecache field // offset of XXX_sizecache + initialized int32 // 0 -- only typ is set, 1 -- fully initialized + messageset bool // uses message set wire format + hasmarshaler bool // has custom marshaler + sync.RWMutex // protect extElems map, also for initialization + extElems map[int32]*marshalElemInfo // info of extension elements + + hassizer bool // has custom sizer + hasprotosizer bool // has custom protosizer + + bytesExtensions field // offset of XXX_extensions where the field type is []byte +} + +// marshalFieldInfo is the information used for marshaling a field of a message. +type marshalFieldInfo struct { + field field + wiretag uint64 // tag in wire format + tagsize int // size of tag in wire format + sizer sizer + marshaler marshaler + isPointer bool + required bool // field is required + name string // name of the field, for error reporting + oneofElems map[reflect.Type]*marshalElemInfo // info of oneof elements +} + +// marshalElemInfo is the information used for marshaling an extension or oneof element. +type marshalElemInfo struct { + wiretag uint64 // tag in wire format + tagsize int // size of tag in wire format + sizer sizer + marshaler marshaler + isptr bool // elem is pointer typed, thus interface of this type is a direct interface (extension only) +} + +var ( + marshalInfoMap = map[reflect.Type]*marshalInfo{} + marshalInfoLock sync.Mutex +) + +// getMarshalInfo returns the information to marshal a given type of message. +// The info it returns may not necessarily initialized. +// t is the type of the message (NOT the pointer to it). +func getMarshalInfo(t reflect.Type) *marshalInfo { + marshalInfoLock.Lock() + u, ok := marshalInfoMap[t] + if !ok { + u = &marshalInfo{typ: t} + marshalInfoMap[t] = u + } + marshalInfoLock.Unlock() + return u +} + +// Size is the entry point from generated code, +// and should be ONLY called by generated code. +// It computes the size of encoded data of msg. +// a is a pointer to a place to store cached marshal info. +func (a *InternalMessageInfo) Size(msg Message) int { + u := getMessageMarshalInfo(msg, a) + ptr := toPointer(&msg) + if ptr.isNil() { + // We get here if msg is a typed nil ((*SomeMessage)(nil)), + // so it satisfies the interface, and msg == nil wouldn't + // catch it. We don't want crash in this case. + return 0 + } + return u.size(ptr) +} + +// Marshal is the entry point from generated code, +// and should be ONLY called by generated code. +// It marshals msg to the end of b. +// a is a pointer to a place to store cached marshal info. +func (a *InternalMessageInfo) Marshal(b []byte, msg Message, deterministic bool) ([]byte, error) { + u := getMessageMarshalInfo(msg, a) + ptr := toPointer(&msg) + if ptr.isNil() { + // We get here if msg is a typed nil ((*SomeMessage)(nil)), + // so it satisfies the interface, and msg == nil wouldn't + // catch it. We don't want crash in this case. + return b, ErrNil + } + return u.marshal(b, ptr, deterministic) +} + +func getMessageMarshalInfo(msg interface{}, a *InternalMessageInfo) *marshalInfo { + // u := a.marshal, but atomically. + // We use an atomic here to ensure memory consistency. + u := atomicLoadMarshalInfo(&a.marshal) + if u == nil { + // Get marshal information from type of message. + t := reflect.ValueOf(msg).Type() + if t.Kind() != reflect.Ptr { + panic(fmt.Sprintf("cannot handle non-pointer message type %v", t)) + } + u = getMarshalInfo(t.Elem()) + // Store it in the cache for later users. + // a.marshal = u, but atomically. + atomicStoreMarshalInfo(&a.marshal, u) + } + return u +} + +// size is the main function to compute the size of the encoded data of a message. +// ptr is the pointer to the message. +func (u *marshalInfo) size(ptr pointer) int { + if atomic.LoadInt32(&u.initialized) == 0 { + u.computeMarshalInfo() + } + + // If the message can marshal itself, let it do it, for compatibility. + // NOTE: This is not efficient. + if u.hasmarshaler { + // Uses the message's Size method if available + if u.hassizer { + s := ptr.asPointerTo(u.typ).Interface().(Sizer) + return s.Size() + } + // Uses the message's ProtoSize method if available + if u.hasprotosizer { + s := ptr.asPointerTo(u.typ).Interface().(ProtoSizer) + return s.ProtoSize() + } + + m := ptr.asPointerTo(u.typ).Interface().(Marshaler) + b, _ := m.Marshal() + return len(b) + } + + n := 0 + for _, f := range u.fields { + if f.isPointer && ptr.offset(f.field).getPointer().isNil() { + // nil pointer always marshals to nothing + continue + } + n += f.sizer(ptr.offset(f.field), f.tagsize) + } + if u.extensions.IsValid() { + e := ptr.offset(u.extensions).toExtensions() + if u.messageset { + n += u.sizeMessageSet(e) + } else { + n += u.sizeExtensions(e) + } + } + if u.v1extensions.IsValid() { + m := *ptr.offset(u.v1extensions).toOldExtensions() + n += u.sizeV1Extensions(m) + } + if u.bytesExtensions.IsValid() { + s := *ptr.offset(u.bytesExtensions).toBytes() + n += len(s) + } + if u.unrecognized.IsValid() { + s := *ptr.offset(u.unrecognized).toBytes() + n += len(s) + } + + // cache the result for use in marshal + if u.sizecache.IsValid() { + atomic.StoreInt32(ptr.offset(u.sizecache).toInt32(), int32(n)) + } + return n +} + +// cachedsize gets the size from cache. If there is no cache (i.e. message is not generated), +// fall back to compute the size. +func (u *marshalInfo) cachedsize(ptr pointer) int { + if u.sizecache.IsValid() { + return int(atomic.LoadInt32(ptr.offset(u.sizecache).toInt32())) + } + return u.size(ptr) +} + +// marshal is the main function to marshal a message. It takes a byte slice and appends +// the encoded data to the end of the slice, returns the slice and error (if any). +// ptr is the pointer to the message. +// If deterministic is true, map is marshaled in deterministic order. +func (u *marshalInfo) marshal(b []byte, ptr pointer, deterministic bool) ([]byte, error) { + if atomic.LoadInt32(&u.initialized) == 0 { + u.computeMarshalInfo() + } + + // If the message can marshal itself, let it do it, for compatibility. + // NOTE: This is not efficient. + if u.hasmarshaler { + if deterministic { + return nil, errors.New("proto: deterministic not supported by the Marshal method of " + u.typ.String()) + } + m := ptr.asPointerTo(u.typ).Interface().(Marshaler) + b1, err := m.Marshal() + b = append(b, b1...) + return b, err + } + + var err, errreq error + // The old marshaler encodes extensions at beginning. + if u.extensions.IsValid() { + e := ptr.offset(u.extensions).toExtensions() + if u.messageset { + b, err = u.appendMessageSet(b, e, deterministic) + } else { + b, err = u.appendExtensions(b, e, deterministic) + } + if err != nil { + return b, err + } + } + if u.v1extensions.IsValid() { + m := *ptr.offset(u.v1extensions).toOldExtensions() + b, err = u.appendV1Extensions(b, m, deterministic) + if err != nil { + return b, err + } + } + if u.bytesExtensions.IsValid() { + s := *ptr.offset(u.bytesExtensions).toBytes() + b = append(b, s...) + } + for _, f := range u.fields { + if f.required && errreq == nil { + if ptr.offset(f.field).getPointer().isNil() { + // Required field is not set. + // We record the error but keep going, to give a complete marshaling. + errreq = &RequiredNotSetError{f.name} + continue + } + } + if f.isPointer && ptr.offset(f.field).getPointer().isNil() { + // nil pointer always marshals to nothing + continue + } + b, err = f.marshaler(b, ptr.offset(f.field), f.wiretag, deterministic) + if err != nil { + if err1, ok := err.(*RequiredNotSetError); ok { + // Required field in submessage is not set. + // We record the error but keep going, to give a complete marshaling. + if errreq == nil { + errreq = &RequiredNotSetError{f.name + "." + err1.field} + } + continue + } + if err == errRepeatedHasNil { + err = errors.New("proto: repeated field " + f.name + " has nil element") + } + return b, err + } + } + if u.unrecognized.IsValid() { + s := *ptr.offset(u.unrecognized).toBytes() + b = append(b, s...) + } + return b, errreq +} + +// computeMarshalInfo initializes the marshal info. +func (u *marshalInfo) computeMarshalInfo() { + u.Lock() + defer u.Unlock() + if u.initialized != 0 { // non-atomic read is ok as it is protected by the lock + return + } + + t := u.typ + u.unrecognized = invalidField + u.extensions = invalidField + u.v1extensions = invalidField + u.bytesExtensions = invalidField + u.sizecache = invalidField + isOneofMessage := false + + if reflect.PtrTo(t).Implements(sizerType) { + u.hassizer = true + } + if reflect.PtrTo(t).Implements(protosizerType) { + u.hasprotosizer = true + } + // If the message can marshal itself, let it do it, for compatibility. + // NOTE: This is not efficient. + if reflect.PtrTo(t).Implements(marshalerType) { + u.hasmarshaler = true + atomic.StoreInt32(&u.initialized, 1) + return + } + + n := t.NumField() + + // deal with XXX fields first + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if f.Tag.Get("protobuf_oneof") != "" { + isOneofMessage = true + } + if !strings.HasPrefix(f.Name, "XXX_") { + continue + } + switch f.Name { + case "XXX_sizecache": + u.sizecache = toField(&f) + case "XXX_unrecognized": + u.unrecognized = toField(&f) + case "XXX_InternalExtensions": + u.extensions = toField(&f) + u.messageset = f.Tag.Get("protobuf_messageset") == "1" + case "XXX_extensions": + if f.Type.Kind() == reflect.Map { + u.v1extensions = toField(&f) + } else { + u.bytesExtensions = toField(&f) + } + case "XXX_NoUnkeyedLiteral": + // nothing to do + default: + panic("unknown XXX field: " + f.Name) + } + n-- + } + + // get oneof implementers + var oneofImplementers []interface{} + // gogo: isOneofMessage is needed for embedded oneof messages, without a marshaler and unmarshaler + if m, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok && isOneofMessage { + _, _, _, oneofImplementers = m.XXX_OneofFuncs() + } + + // normal fields + fields := make([]marshalFieldInfo, n) // batch allocation + u.fields = make([]*marshalFieldInfo, 0, n) + for i, j := 0, 0; i < t.NumField(); i++ { + f := t.Field(i) + + if strings.HasPrefix(f.Name, "XXX_") { + continue + } + field := &fields[j] + j++ + field.name = f.Name + u.fields = append(u.fields, field) + if f.Tag.Get("protobuf_oneof") != "" { + field.computeOneofFieldInfo(&f, oneofImplementers) + continue + } + if f.Tag.Get("protobuf") == "" { + // field has no tag (not in generated message), ignore it + u.fields = u.fields[:len(u.fields)-1] + j-- + continue + } + field.computeMarshalFieldInfo(&f) + } + + // fields are marshaled in tag order on the wire. + sort.Sort(byTag(u.fields)) + + atomic.StoreInt32(&u.initialized, 1) +} + +// helper for sorting fields by tag +type byTag []*marshalFieldInfo + +func (a byTag) Len() int { return len(a) } +func (a byTag) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a byTag) Less(i, j int) bool { return a[i].wiretag < a[j].wiretag } + +// getExtElemInfo returns the information to marshal an extension element. +// The info it returns is initialized. +func (u *marshalInfo) getExtElemInfo(desc *ExtensionDesc) *marshalElemInfo { + // get from cache first + u.RLock() + e, ok := u.extElems[desc.Field] + u.RUnlock() + if ok { + return e + } + + t := reflect.TypeOf(desc.ExtensionType) // pointer or slice to basic type or struct + tags := strings.Split(desc.Tag, ",") + tag, err := strconv.Atoi(tags[1]) + if err != nil { + panic("tag is not an integer") + } + wt := wiretype(tags[0]) + sizr, marshalr := typeMarshaler(t, tags, false, false) + e = &marshalElemInfo{ + wiretag: uint64(tag)<<3 | wt, + tagsize: SizeVarint(uint64(tag) << 3), + sizer: sizr, + marshaler: marshalr, + isptr: t.Kind() == reflect.Ptr, + } + + // update cache + u.Lock() + if u.extElems == nil { + u.extElems = make(map[int32]*marshalElemInfo) + } + u.extElems[desc.Field] = e + u.Unlock() + return e +} + +// computeMarshalFieldInfo fills up the information to marshal a field. +func (fi *marshalFieldInfo) computeMarshalFieldInfo(f *reflect.StructField) { + // parse protobuf tag of the field. + // tag has format of "bytes,49,opt,name=foo,def=hello!" + tags := strings.Split(f.Tag.Get("protobuf"), ",") + if tags[0] == "" { + return + } + tag, err := strconv.Atoi(tags[1]) + if err != nil { + panic("tag is not an integer") + } + wt := wiretype(tags[0]) + if tags[2] == "req" { + fi.required = true + } + fi.setTag(f, tag, wt) + fi.setMarshaler(f, tags) +} + +func (fi *marshalFieldInfo) computeOneofFieldInfo(f *reflect.StructField, oneofImplementers []interface{}) { + fi.field = toField(f) + fi.wiretag = 1<<31 - 1 // Use a large tag number, make oneofs sorted at the end. This tag will not appear on the wire. + fi.isPointer = true + fi.sizer, fi.marshaler = makeOneOfMarshaler(fi, f) + fi.oneofElems = make(map[reflect.Type]*marshalElemInfo) + + ityp := f.Type // interface type + for _, o := range oneofImplementers { + t := reflect.TypeOf(o) + if !t.Implements(ityp) { + continue + } + sf := t.Elem().Field(0) // oneof implementer is a struct with a single field + tags := strings.Split(sf.Tag.Get("protobuf"), ",") + tag, err := strconv.Atoi(tags[1]) + if err != nil { + panic("tag is not an integer") + } + wt := wiretype(tags[0]) + sizr, marshalr := typeMarshaler(sf.Type, tags, false, true) // oneof should not omit any zero value + fi.oneofElems[t.Elem()] = &marshalElemInfo{ + wiretag: uint64(tag)<<3 | wt, + tagsize: SizeVarint(uint64(tag) << 3), + sizer: sizr, + marshaler: marshalr, + } + } +} + +type oneofMessage interface { + XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{}) +} + +// wiretype returns the wire encoding of the type. +func wiretype(encoding string) uint64 { + switch encoding { + case "fixed32": + return WireFixed32 + case "fixed64": + return WireFixed64 + case "varint", "zigzag32", "zigzag64": + return WireVarint + case "bytes": + return WireBytes + case "group": + return WireStartGroup + } + panic("unknown wire type " + encoding) +} + +// setTag fills up the tag (in wire format) and its size in the info of a field. +func (fi *marshalFieldInfo) setTag(f *reflect.StructField, tag int, wt uint64) { + fi.field = toField(f) + fi.wiretag = uint64(tag)<<3 | wt + fi.tagsize = SizeVarint(uint64(tag) << 3) +} + +// setMarshaler fills up the sizer and marshaler in the info of a field. +func (fi *marshalFieldInfo) setMarshaler(f *reflect.StructField, tags []string) { + switch f.Type.Kind() { + case reflect.Map: + // map field + fi.isPointer = true + fi.sizer, fi.marshaler = makeMapMarshaler(f) + return + case reflect.Ptr, reflect.Slice: + fi.isPointer = true + } + fi.sizer, fi.marshaler = typeMarshaler(f.Type, tags, true, false) +} + +// typeMarshaler returns the sizer and marshaler of a given field. +// t is the type of the field. +// tags is the generated "protobuf" tag of the field. +// If nozero is true, zero value is not marshaled to the wire. +// If oneof is true, it is a oneof field. +func typeMarshaler(t reflect.Type, tags []string, nozero, oneof bool) (sizer, marshaler) { + encoding := tags[0] + + pointer := false + slice := false + if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { + slice = true + t = t.Elem() + } + if t.Kind() == reflect.Ptr { + pointer = true + t = t.Elem() + } + + packed := false + proto3 := false + ctype := false + isTime := false + isDuration := false + for i := 2; i < len(tags); i++ { + if tags[i] == "packed" { + packed = true + } + if tags[i] == "proto3" { + proto3 = true + } + if strings.HasPrefix(tags[i], "customtype=") { + ctype = true + } + if tags[i] == "stdtime" { + isTime = true + } + if tags[i] == "stdduration" { + isDuration = true + } + } + if !proto3 && !pointer && !slice { + nozero = false + } + + if ctype { + if reflect.PtrTo(t).Implements(customType) { + if slice { + return makeMessageRefSliceMarshaler(getMarshalInfo(t)) + } + if pointer { + return makeCustomPtrMarshaler(getMarshalInfo(t)) + } + return makeCustomMarshaler(getMarshalInfo(t)) + } else { + panic(fmt.Sprintf("custom type: type: %v, does not implement the proto.custom interface", t)) + } + } + + if isTime { + if pointer { + if slice { + return makeTimePtrSliceMarshaler(getMarshalInfo(t)) + } + return makeTimePtrMarshaler(getMarshalInfo(t)) + } + if slice { + return makeTimeSliceMarshaler(getMarshalInfo(t)) + } + return makeTimeMarshaler(getMarshalInfo(t)) + } + + if isDuration { + if pointer { + if slice { + return makeDurationPtrSliceMarshaler(getMarshalInfo(t)) + } + return makeDurationPtrMarshaler(getMarshalInfo(t)) + } + if slice { + return makeDurationSliceMarshaler(getMarshalInfo(t)) + } + return makeDurationMarshaler(getMarshalInfo(t)) + } + + switch t.Kind() { + case reflect.Bool: + if pointer { + return sizeBoolPtr, appendBoolPtr + } + if slice { + if packed { + return sizeBoolPackedSlice, appendBoolPackedSlice + } + return sizeBoolSlice, appendBoolSlice + } + if nozero { + return sizeBoolValueNoZero, appendBoolValueNoZero + } + return sizeBoolValue, appendBoolValue + case reflect.Uint32: + switch encoding { + case "fixed32": + if pointer { + return sizeFixed32Ptr, appendFixed32Ptr + } + if slice { + if packed { + return sizeFixed32PackedSlice, appendFixed32PackedSlice + } + return sizeFixed32Slice, appendFixed32Slice + } + if nozero { + return sizeFixed32ValueNoZero, appendFixed32ValueNoZero + } + return sizeFixed32Value, appendFixed32Value + case "varint": + if pointer { + return sizeVarint32Ptr, appendVarint32Ptr + } + if slice { + if packed { + return sizeVarint32PackedSlice, appendVarint32PackedSlice + } + return sizeVarint32Slice, appendVarint32Slice + } + if nozero { + return sizeVarint32ValueNoZero, appendVarint32ValueNoZero + } + return sizeVarint32Value, appendVarint32Value + } + case reflect.Int32: + switch encoding { + case "fixed32": + if pointer { + return sizeFixedS32Ptr, appendFixedS32Ptr + } + if slice { + if packed { + return sizeFixedS32PackedSlice, appendFixedS32PackedSlice + } + return sizeFixedS32Slice, appendFixedS32Slice + } + if nozero { + return sizeFixedS32ValueNoZero, appendFixedS32ValueNoZero + } + return sizeFixedS32Value, appendFixedS32Value + case "varint": + if pointer { + return sizeVarintS32Ptr, appendVarintS32Ptr + } + if slice { + if packed { + return sizeVarintS32PackedSlice, appendVarintS32PackedSlice + } + return sizeVarintS32Slice, appendVarintS32Slice + } + if nozero { + return sizeVarintS32ValueNoZero, appendVarintS32ValueNoZero + } + return sizeVarintS32Value, appendVarintS32Value + case "zigzag32": + if pointer { + return sizeZigzag32Ptr, appendZigzag32Ptr + } + if slice { + if packed { + return sizeZigzag32PackedSlice, appendZigzag32PackedSlice + } + return sizeZigzag32Slice, appendZigzag32Slice + } + if nozero { + return sizeZigzag32ValueNoZero, appendZigzag32ValueNoZero + } + return sizeZigzag32Value, appendZigzag32Value + } + case reflect.Uint64: + switch encoding { + case "fixed64": + if pointer { + return sizeFixed64Ptr, appendFixed64Ptr + } + if slice { + if packed { + return sizeFixed64PackedSlice, appendFixed64PackedSlice + } + return sizeFixed64Slice, appendFixed64Slice + } + if nozero { + return sizeFixed64ValueNoZero, appendFixed64ValueNoZero + } + return sizeFixed64Value, appendFixed64Value + case "varint": + if pointer { + return sizeVarint64Ptr, appendVarint64Ptr + } + if slice { + if packed { + return sizeVarint64PackedSlice, appendVarint64PackedSlice + } + return sizeVarint64Slice, appendVarint64Slice + } + if nozero { + return sizeVarint64ValueNoZero, appendVarint64ValueNoZero + } + return sizeVarint64Value, appendVarint64Value + } + case reflect.Int64: + switch encoding { + case "fixed64": + if pointer { + return sizeFixedS64Ptr, appendFixedS64Ptr + } + if slice { + if packed { + return sizeFixedS64PackedSlice, appendFixedS64PackedSlice + } + return sizeFixedS64Slice, appendFixedS64Slice + } + if nozero { + return sizeFixedS64ValueNoZero, appendFixedS64ValueNoZero + } + return sizeFixedS64Value, appendFixedS64Value + case "varint": + if pointer { + return sizeVarintS64Ptr, appendVarintS64Ptr + } + if slice { + if packed { + return sizeVarintS64PackedSlice, appendVarintS64PackedSlice + } + return sizeVarintS64Slice, appendVarintS64Slice + } + if nozero { + return sizeVarintS64ValueNoZero, appendVarintS64ValueNoZero + } + return sizeVarintS64Value, appendVarintS64Value + case "zigzag64": + if pointer { + return sizeZigzag64Ptr, appendZigzag64Ptr + } + if slice { + if packed { + return sizeZigzag64PackedSlice, appendZigzag64PackedSlice + } + return sizeZigzag64Slice, appendZigzag64Slice + } + if nozero { + return sizeZigzag64ValueNoZero, appendZigzag64ValueNoZero + } + return sizeZigzag64Value, appendZigzag64Value + } + case reflect.Float32: + if pointer { + return sizeFloat32Ptr, appendFloat32Ptr + } + if slice { + if packed { + return sizeFloat32PackedSlice, appendFloat32PackedSlice + } + return sizeFloat32Slice, appendFloat32Slice + } + if nozero { + return sizeFloat32ValueNoZero, appendFloat32ValueNoZero + } + return sizeFloat32Value, appendFloat32Value + case reflect.Float64: + if pointer { + return sizeFloat64Ptr, appendFloat64Ptr + } + if slice { + if packed { + return sizeFloat64PackedSlice, appendFloat64PackedSlice + } + return sizeFloat64Slice, appendFloat64Slice + } + if nozero { + return sizeFloat64ValueNoZero, appendFloat64ValueNoZero + } + return sizeFloat64Value, appendFloat64Value + case reflect.String: + if pointer { + return sizeStringPtr, appendStringPtr + } + if slice { + return sizeStringSlice, appendStringSlice + } + if nozero { + return sizeStringValueNoZero, appendStringValueNoZero + } + return sizeStringValue, appendStringValue + case reflect.Slice: + if slice { + return sizeBytesSlice, appendBytesSlice + } + if oneof { + // Oneof bytes field may also have "proto3" tag. + // We want to marshal it as a oneof field. Do this + // check before the proto3 check. + return sizeBytesOneof, appendBytesOneof + } + if proto3 { + return sizeBytes3, appendBytes3 + } + return sizeBytes, appendBytes + case reflect.Struct: + switch encoding { + case "group": + if slice { + return makeGroupSliceMarshaler(getMarshalInfo(t)) + } + return makeGroupMarshaler(getMarshalInfo(t)) + case "bytes": + if pointer { + if slice { + return makeMessageSliceMarshaler(getMarshalInfo(t)) + } + return makeMessageMarshaler(getMarshalInfo(t)) + } else { + if slice { + return makeMessageRefSliceMarshaler(getMarshalInfo(t)) + } + return makeMessageRefMarshaler(getMarshalInfo(t)) + } + } + } + panic(fmt.Sprintf("unknown or mismatched type: type: %v, wire type: %v", t, encoding)) +} + +// Below are functions to size/marshal a specific type of a field. +// They are stored in the field's info, and called by function pointers. +// They have type sizer or marshaler. + +func sizeFixed32Value(_ pointer, tagsize int) int { + return 4 + tagsize +} +func sizeFixed32ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toUint32() + if v == 0 { + return 0 + } + return 4 + tagsize +} +func sizeFixed32Ptr(ptr pointer, tagsize int) int { + p := *ptr.toUint32Ptr() + if p == nil { + return 0 + } + return 4 + tagsize +} +func sizeFixed32Slice(ptr pointer, tagsize int) int { + s := *ptr.toUint32Slice() + return (4 + tagsize) * len(s) +} +func sizeFixed32PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toUint32Slice() + if len(s) == 0 { + return 0 + } + return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize +} +func sizeFixedS32Value(_ pointer, tagsize int) int { + return 4 + tagsize +} +func sizeFixedS32ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toInt32() + if v == 0 { + return 0 + } + return 4 + tagsize +} +func sizeFixedS32Ptr(ptr pointer, tagsize int) int { + p := ptr.getInt32Ptr() + if p == nil { + return 0 + } + return 4 + tagsize +} +func sizeFixedS32Slice(ptr pointer, tagsize int) int { + s := ptr.getInt32Slice() + return (4 + tagsize) * len(s) +} +func sizeFixedS32PackedSlice(ptr pointer, tagsize int) int { + s := ptr.getInt32Slice() + if len(s) == 0 { + return 0 + } + return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize +} +func sizeFloat32Value(_ pointer, tagsize int) int { + return 4 + tagsize +} +func sizeFloat32ValueNoZero(ptr pointer, tagsize int) int { + v := math.Float32bits(*ptr.toFloat32()) + if v == 0 { + return 0 + } + return 4 + tagsize +} +func sizeFloat32Ptr(ptr pointer, tagsize int) int { + p := *ptr.toFloat32Ptr() + if p == nil { + return 0 + } + return 4 + tagsize +} +func sizeFloat32Slice(ptr pointer, tagsize int) int { + s := *ptr.toFloat32Slice() + return (4 + tagsize) * len(s) +} +func sizeFloat32PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toFloat32Slice() + if len(s) == 0 { + return 0 + } + return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize +} +func sizeFixed64Value(_ pointer, tagsize int) int { + return 8 + tagsize +} +func sizeFixed64ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toUint64() + if v == 0 { + return 0 + } + return 8 + tagsize +} +func sizeFixed64Ptr(ptr pointer, tagsize int) int { + p := *ptr.toUint64Ptr() + if p == nil { + return 0 + } + return 8 + tagsize +} +func sizeFixed64Slice(ptr pointer, tagsize int) int { + s := *ptr.toUint64Slice() + return (8 + tagsize) * len(s) +} +func sizeFixed64PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toUint64Slice() + if len(s) == 0 { + return 0 + } + return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize +} +func sizeFixedS64Value(_ pointer, tagsize int) int { + return 8 + tagsize +} +func sizeFixedS64ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toInt64() + if v == 0 { + return 0 + } + return 8 + tagsize +} +func sizeFixedS64Ptr(ptr pointer, tagsize int) int { + p := *ptr.toInt64Ptr() + if p == nil { + return 0 + } + return 8 + tagsize +} +func sizeFixedS64Slice(ptr pointer, tagsize int) int { + s := *ptr.toInt64Slice() + return (8 + tagsize) * len(s) +} +func sizeFixedS64PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toInt64Slice() + if len(s) == 0 { + return 0 + } + return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize +} +func sizeFloat64Value(_ pointer, tagsize int) int { + return 8 + tagsize +} +func sizeFloat64ValueNoZero(ptr pointer, tagsize int) int { + v := math.Float64bits(*ptr.toFloat64()) + if v == 0 { + return 0 + } + return 8 + tagsize +} +func sizeFloat64Ptr(ptr pointer, tagsize int) int { + p := *ptr.toFloat64Ptr() + if p == nil { + return 0 + } + return 8 + tagsize +} +func sizeFloat64Slice(ptr pointer, tagsize int) int { + s := *ptr.toFloat64Slice() + return (8 + tagsize) * len(s) +} +func sizeFloat64PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toFloat64Slice() + if len(s) == 0 { + return 0 + } + return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize +} +func sizeVarint32Value(ptr pointer, tagsize int) int { + v := *ptr.toUint32() + return SizeVarint(uint64(v)) + tagsize +} +func sizeVarint32ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toUint32() + if v == 0 { + return 0 + } + return SizeVarint(uint64(v)) + tagsize +} +func sizeVarint32Ptr(ptr pointer, tagsize int) int { + p := *ptr.toUint32Ptr() + if p == nil { + return 0 + } + return SizeVarint(uint64(*p)) + tagsize +} +func sizeVarint32Slice(ptr pointer, tagsize int) int { + s := *ptr.toUint32Slice() + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + tagsize + } + return n +} +func sizeVarint32PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toUint32Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + } + return n + SizeVarint(uint64(n)) + tagsize +} +func sizeVarintS32Value(ptr pointer, tagsize int) int { + v := *ptr.toInt32() + return SizeVarint(uint64(v)) + tagsize +} +func sizeVarintS32ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toInt32() + if v == 0 { + return 0 + } + return SizeVarint(uint64(v)) + tagsize +} +func sizeVarintS32Ptr(ptr pointer, tagsize int) int { + p := ptr.getInt32Ptr() + if p == nil { + return 0 + } + return SizeVarint(uint64(*p)) + tagsize +} +func sizeVarintS32Slice(ptr pointer, tagsize int) int { + s := ptr.getInt32Slice() + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + tagsize + } + return n +} +func sizeVarintS32PackedSlice(ptr pointer, tagsize int) int { + s := ptr.getInt32Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + } + return n + SizeVarint(uint64(n)) + tagsize +} +func sizeVarint64Value(ptr pointer, tagsize int) int { + v := *ptr.toUint64() + return SizeVarint(v) + tagsize +} +func sizeVarint64ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toUint64() + if v == 0 { + return 0 + } + return SizeVarint(v) + tagsize +} +func sizeVarint64Ptr(ptr pointer, tagsize int) int { + p := *ptr.toUint64Ptr() + if p == nil { + return 0 + } + return SizeVarint(*p) + tagsize +} +func sizeVarint64Slice(ptr pointer, tagsize int) int { + s := *ptr.toUint64Slice() + n := 0 + for _, v := range s { + n += SizeVarint(v) + tagsize + } + return n +} +func sizeVarint64PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toUint64Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += SizeVarint(v) + } + return n + SizeVarint(uint64(n)) + tagsize +} +func sizeVarintS64Value(ptr pointer, tagsize int) int { + v := *ptr.toInt64() + return SizeVarint(uint64(v)) + tagsize +} +func sizeVarintS64ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toInt64() + if v == 0 { + return 0 + } + return SizeVarint(uint64(v)) + tagsize +} +func sizeVarintS64Ptr(ptr pointer, tagsize int) int { + p := *ptr.toInt64Ptr() + if p == nil { + return 0 + } + return SizeVarint(uint64(*p)) + tagsize +} +func sizeVarintS64Slice(ptr pointer, tagsize int) int { + s := *ptr.toInt64Slice() + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + tagsize + } + return n +} +func sizeVarintS64PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toInt64Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + } + return n + SizeVarint(uint64(n)) + tagsize +} +func sizeZigzag32Value(ptr pointer, tagsize int) int { + v := *ptr.toInt32() + return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize +} +func sizeZigzag32ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toInt32() + if v == 0 { + return 0 + } + return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize +} +func sizeZigzag32Ptr(ptr pointer, tagsize int) int { + p := ptr.getInt32Ptr() + if p == nil { + return 0 + } + v := *p + return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize +} +func sizeZigzag32Slice(ptr pointer, tagsize int) int { + s := ptr.getInt32Slice() + n := 0 + for _, v := range s { + n += SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize + } + return n +} +func sizeZigzag32PackedSlice(ptr pointer, tagsize int) int { + s := ptr.getInt32Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) + } + return n + SizeVarint(uint64(n)) + tagsize +} +func sizeZigzag64Value(ptr pointer, tagsize int) int { + v := *ptr.toInt64() + return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize +} +func sizeZigzag64ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toInt64() + if v == 0 { + return 0 + } + return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize +} +func sizeZigzag64Ptr(ptr pointer, tagsize int) int { + p := *ptr.toInt64Ptr() + if p == nil { + return 0 + } + v := *p + return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize +} +func sizeZigzag64Slice(ptr pointer, tagsize int) int { + s := *ptr.toInt64Slice() + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize + } + return n +} +func sizeZigzag64PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toInt64Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63))) + } + return n + SizeVarint(uint64(n)) + tagsize +} +func sizeBoolValue(_ pointer, tagsize int) int { + return 1 + tagsize +} +func sizeBoolValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toBool() + if !v { + return 0 + } + return 1 + tagsize +} +func sizeBoolPtr(ptr pointer, tagsize int) int { + p := *ptr.toBoolPtr() + if p == nil { + return 0 + } + return 1 + tagsize +} +func sizeBoolSlice(ptr pointer, tagsize int) int { + s := *ptr.toBoolSlice() + return (1 + tagsize) * len(s) +} +func sizeBoolPackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toBoolSlice() + if len(s) == 0 { + return 0 + } + return len(s) + SizeVarint(uint64(len(s))) + tagsize +} +func sizeStringValue(ptr pointer, tagsize int) int { + v := *ptr.toString() + return len(v) + SizeVarint(uint64(len(v))) + tagsize +} +func sizeStringValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toString() + if v == "" { + return 0 + } + return len(v) + SizeVarint(uint64(len(v))) + tagsize +} +func sizeStringPtr(ptr pointer, tagsize int) int { + p := *ptr.toStringPtr() + if p == nil { + return 0 + } + v := *p + return len(v) + SizeVarint(uint64(len(v))) + tagsize +} +func sizeStringSlice(ptr pointer, tagsize int) int { + s := *ptr.toStringSlice() + n := 0 + for _, v := range s { + n += len(v) + SizeVarint(uint64(len(v))) + tagsize + } + return n +} +func sizeBytes(ptr pointer, tagsize int) int { + v := *ptr.toBytes() + if v == nil { + return 0 + } + return len(v) + SizeVarint(uint64(len(v))) + tagsize +} +func sizeBytes3(ptr pointer, tagsize int) int { + v := *ptr.toBytes() + if len(v) == 0 { + return 0 + } + return len(v) + SizeVarint(uint64(len(v))) + tagsize +} +func sizeBytesOneof(ptr pointer, tagsize int) int { + v := *ptr.toBytes() + return len(v) + SizeVarint(uint64(len(v))) + tagsize +} +func sizeBytesSlice(ptr pointer, tagsize int) int { + s := *ptr.toBytesSlice() + n := 0 + for _, v := range s { + n += len(v) + SizeVarint(uint64(len(v))) + tagsize + } + return n +} + +// appendFixed32 appends an encoded fixed32 to b. +func appendFixed32(b []byte, v uint32) []byte { + b = append(b, + byte(v), + byte(v>>8), + byte(v>>16), + byte(v>>24)) + return b +} + +// appendFixed64 appends an encoded fixed64 to b. +func appendFixed64(b []byte, v uint64) []byte { + b = append(b, + byte(v), + byte(v>>8), + byte(v>>16), + byte(v>>24), + byte(v>>32), + byte(v>>40), + byte(v>>48), + byte(v>>56)) + return b +} + +// appendVarint appends an encoded varint to b. +func appendVarint(b []byte, v uint64) []byte { + // TODO: make 1-byte (maybe 2-byte) case inline-able, once we + // have non-leaf inliner. + switch { + case v < 1<<7: + b = append(b, byte(v)) + case v < 1<<14: + b = append(b, + byte(v&0x7f|0x80), + byte(v>>7)) + case v < 1<<21: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte(v>>14)) + case v < 1<<28: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte(v>>21)) + case v < 1<<35: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte(v>>28)) + case v < 1<<42: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte((v>>28)&0x7f|0x80), + byte(v>>35)) + case v < 1<<49: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte((v>>28)&0x7f|0x80), + byte((v>>35)&0x7f|0x80), + byte(v>>42)) + case v < 1<<56: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte((v>>28)&0x7f|0x80), + byte((v>>35)&0x7f|0x80), + byte((v>>42)&0x7f|0x80), + byte(v>>49)) + case v < 1<<63: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte((v>>28)&0x7f|0x80), + byte((v>>35)&0x7f|0x80), + byte((v>>42)&0x7f|0x80), + byte((v>>49)&0x7f|0x80), + byte(v>>56)) + default: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte((v>>28)&0x7f|0x80), + byte((v>>35)&0x7f|0x80), + byte((v>>42)&0x7f|0x80), + byte((v>>49)&0x7f|0x80), + byte((v>>56)&0x7f|0x80), + 1) + } + return b +} + +func appendFixed32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint32() + b = appendVarint(b, wiretag) + b = appendFixed32(b, v) + return b, nil +} +func appendFixed32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint32() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed32(b, v) + return b, nil +} +func appendFixed32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toUint32Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed32(b, *p) + return b, nil +} +func appendFixed32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint32Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendFixed32(b, v) + } + return b, nil +} +func appendFixed32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint32Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + b = appendVarint(b, uint64(4*len(s))) + for _, v := range s { + b = appendFixed32(b, v) + } + return b, nil +} +func appendFixedS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt32() + b = appendVarint(b, wiretag) + b = appendFixed32(b, uint32(v)) + return b, nil +} +func appendFixedS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt32() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed32(b, uint32(v)) + return b, nil +} +func appendFixedS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := ptr.getInt32Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed32(b, uint32(*p)) + return b, nil +} +func appendFixedS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := ptr.getInt32Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendFixed32(b, uint32(v)) + } + return b, nil +} +func appendFixedS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := ptr.getInt32Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + b = appendVarint(b, uint64(4*len(s))) + for _, v := range s { + b = appendFixed32(b, uint32(v)) + } + return b, nil +} +func appendFloat32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := math.Float32bits(*ptr.toFloat32()) + b = appendVarint(b, wiretag) + b = appendFixed32(b, v) + return b, nil +} +func appendFloat32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := math.Float32bits(*ptr.toFloat32()) + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed32(b, v) + return b, nil +} +func appendFloat32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toFloat32Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed32(b, math.Float32bits(*p)) + return b, nil +} +func appendFloat32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toFloat32Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendFixed32(b, math.Float32bits(v)) + } + return b, nil +} +func appendFloat32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toFloat32Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + b = appendVarint(b, uint64(4*len(s))) + for _, v := range s { + b = appendFixed32(b, math.Float32bits(v)) + } + return b, nil +} +func appendFixed64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint64() + b = appendVarint(b, wiretag) + b = appendFixed64(b, v) + return b, nil +} +func appendFixed64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint64() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed64(b, v) + return b, nil +} +func appendFixed64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toUint64Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed64(b, *p) + return b, nil +} +func appendFixed64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint64Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendFixed64(b, v) + } + return b, nil +} +func appendFixed64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint64Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + b = appendVarint(b, uint64(8*len(s))) + for _, v := range s { + b = appendFixed64(b, v) + } + return b, nil +} +func appendFixedS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt64() + b = appendVarint(b, wiretag) + b = appendFixed64(b, uint64(v)) + return b, nil +} +func appendFixedS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt64() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed64(b, uint64(v)) + return b, nil +} +func appendFixedS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toInt64Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed64(b, uint64(*p)) + return b, nil +} +func appendFixedS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toInt64Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendFixed64(b, uint64(v)) + } + return b, nil +} +func appendFixedS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toInt64Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + b = appendVarint(b, uint64(8*len(s))) + for _, v := range s { + b = appendFixed64(b, uint64(v)) + } + return b, nil +} +func appendFloat64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := math.Float64bits(*ptr.toFloat64()) + b = appendVarint(b, wiretag) + b = appendFixed64(b, v) + return b, nil +} +func appendFloat64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := math.Float64bits(*ptr.toFloat64()) + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed64(b, v) + return b, nil +} +func appendFloat64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toFloat64Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed64(b, math.Float64bits(*p)) + return b, nil +} +func appendFloat64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toFloat64Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendFixed64(b, math.Float64bits(v)) + } + return b, nil +} +func appendFloat64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toFloat64Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + b = appendVarint(b, uint64(8*len(s))) + for _, v := range s { + b = appendFixed64(b, math.Float64bits(v)) + } + return b, nil +} +func appendVarint32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint32() + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + return b, nil +} +func appendVarint32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint32() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + return b, nil +} +func appendVarint32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toUint32Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(*p)) + return b, nil +} +func appendVarint32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint32Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + } + return b, nil +} +func appendVarint32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint32Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + // compute size + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + } + b = appendVarint(b, uint64(n)) + for _, v := range s { + b = appendVarint(b, uint64(v)) + } + return b, nil +} +func appendVarintS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt32() + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + return b, nil +} +func appendVarintS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt32() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + return b, nil +} +func appendVarintS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := ptr.getInt32Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(*p)) + return b, nil +} +func appendVarintS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := ptr.getInt32Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + } + return b, nil +} +func appendVarintS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := ptr.getInt32Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + // compute size + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + } + b = appendVarint(b, uint64(n)) + for _, v := range s { + b = appendVarint(b, uint64(v)) + } + return b, nil +} +func appendVarint64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint64() + b = appendVarint(b, wiretag) + b = appendVarint(b, v) + return b, nil +} +func appendVarint64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint64() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, v) + return b, nil +} +func appendVarint64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toUint64Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, *p) + return b, nil +} +func appendVarint64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint64Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendVarint(b, v) + } + return b, nil +} +func appendVarint64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint64Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + // compute size + n := 0 + for _, v := range s { + n += SizeVarint(v) + } + b = appendVarint(b, uint64(n)) + for _, v := range s { + b = appendVarint(b, v) + } + return b, nil +} +func appendVarintS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt64() + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + return b, nil +} +func appendVarintS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt64() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + return b, nil +} +func appendVarintS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toInt64Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(*p)) + return b, nil +} +func appendVarintS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toInt64Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + } + return b, nil +} +func appendVarintS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toInt64Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + // compute size + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + } + b = appendVarint(b, uint64(n)) + for _, v := range s { + b = appendVarint(b, uint64(v)) + } + return b, nil +} +func appendZigzag32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt32() + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + return b, nil +} +func appendZigzag32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt32() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + return b, nil +} +func appendZigzag32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := ptr.getInt32Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + v := *p + b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + return b, nil +} +func appendZigzag32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := ptr.getInt32Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + } + return b, nil +} +func appendZigzag32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := ptr.getInt32Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + // compute size + n := 0 + for _, v := range s { + n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) + } + b = appendVarint(b, uint64(n)) + for _, v := range s { + b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + } + return b, nil +} +func appendZigzag64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt64() + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) + return b, nil +} +func appendZigzag64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt64() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) + return b, nil +} +func appendZigzag64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toInt64Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + v := *p + b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) + return b, nil +} +func appendZigzag64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toInt64Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) + } + return b, nil +} +func appendZigzag64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toInt64Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + // compute size + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63))) + } + b = appendVarint(b, uint64(n)) + for _, v := range s { + b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) + } + return b, nil +} +func appendBoolValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toBool() + b = appendVarint(b, wiretag) + if v { + b = append(b, 1) + } else { + b = append(b, 0) + } + return b, nil +} +func appendBoolValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toBool() + if !v { + return b, nil + } + b = appendVarint(b, wiretag) + b = append(b, 1) + return b, nil +} + +func appendBoolPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toBoolPtr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + if *p { + b = append(b, 1) + } else { + b = append(b, 0) + } + return b, nil +} +func appendBoolSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toBoolSlice() + for _, v := range s { + b = appendVarint(b, wiretag) + if v { + b = append(b, 1) + } else { + b = append(b, 0) + } + } + return b, nil +} +func appendBoolPackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toBoolSlice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + b = appendVarint(b, uint64(len(s))) + for _, v := range s { + if v { + b = append(b, 1) + } else { + b = append(b, 0) + } + } + return b, nil +} +func appendStringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toString() + if !utf8.ValidString(v) { + return nil, errInvalidUTF8 + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + return b, nil +} +func appendStringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toString() + if v == "" { + return b, nil + } + if !utf8.ValidString(v) { + return nil, errInvalidUTF8 + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + return b, nil +} +func appendStringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toStringPtr() + if p == nil { + return b, nil + } + v := *p + if !utf8.ValidString(v) { + return nil, errInvalidUTF8 + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + return b, nil +} +func appendStringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toStringSlice() + for _, v := range s { + if !utf8.ValidString(v) { + return nil, errInvalidUTF8 + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + } + return b, nil +} +func appendBytes(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toBytes() + if v == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + return b, nil +} +func appendBytes3(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toBytes() + if len(v) == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + return b, nil +} +func appendBytesOneof(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toBytes() + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + return b, nil +} +func appendBytesSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toBytesSlice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + } + return b, nil +} + +// makeGroupMarshaler returns the sizer and marshaler for a group. +// u is the marshal info of the underlying message. +func makeGroupMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + p := ptr.getPointer() + if p.isNil() { + return 0 + } + return u.size(p) + 2*tagsize + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + p := ptr.getPointer() + if p.isNil() { + return b, nil + } + var err error + b = appendVarint(b, wiretag) // start group + b, err = u.marshal(b, p, deterministic) + b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group + return b, err + } +} + +// makeGroupSliceMarshaler returns the sizer and marshaler for a group slice. +// u is the marshal info of the underlying message. +func makeGroupSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getPointerSlice() + n := 0 + for _, v := range s { + if v.isNil() { + continue + } + n += u.size(v) + 2*tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getPointerSlice() + var err, errreq error + for _, v := range s { + if v.isNil() { + return b, errRepeatedHasNil + } + b = appendVarint(b, wiretag) // start group + b, err = u.marshal(b, v, deterministic) + b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group + if err != nil { + if _, ok := err.(*RequiredNotSetError); ok { + // Required field in submessage is not set. + // We record the error but keep going, to give a complete marshaling. + if errreq == nil { + errreq = err + } + continue + } + if err == ErrNil { + err = errRepeatedHasNil + } + return b, err + } + } + return b, errreq + } +} + +// makeMessageMarshaler returns the sizer and marshaler for a message field. +// u is the marshal info of the message. +func makeMessageMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + p := ptr.getPointer() + if p.isNil() { + return 0 + } + siz := u.size(p) + return siz + SizeVarint(uint64(siz)) + tagsize + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + p := ptr.getPointer() + if p.isNil() { + return b, nil + } + b = appendVarint(b, wiretag) + siz := u.cachedsize(p) + b = appendVarint(b, uint64(siz)) + return u.marshal(b, p, deterministic) + } +} + +// makeMessageSliceMarshaler returns the sizer and marshaler for a message slice. +// u is the marshal info of the message. +func makeMessageSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getPointerSlice() + n := 0 + for _, v := range s { + if v.isNil() { + continue + } + siz := u.size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getPointerSlice() + var err, errreq error + for _, v := range s { + if v.isNil() { + return b, errRepeatedHasNil + } + b = appendVarint(b, wiretag) + siz := u.cachedsize(v) + b = appendVarint(b, uint64(siz)) + b, err = u.marshal(b, v, deterministic) + if err != nil { + if _, ok := err.(*RequiredNotSetError); ok { + // Required field in submessage is not set. + // We record the error but keep going, to give a complete marshaling. + if errreq == nil { + errreq = err + } + continue + } + if err == ErrNil { + err = errRepeatedHasNil + } + return b, err + } + } + return b, errreq + } +} + +// makeMapMarshaler returns the sizer and marshaler for a map field. +// f is the pointer to the reflect data structure of the field. +func makeMapMarshaler(f *reflect.StructField) (sizer, marshaler) { + // figure out key and value type + t := f.Type + keyType := t.Key() + valType := t.Elem() + tags := strings.Split(f.Tag.Get("protobuf"), ",") + keyTags := strings.Split(f.Tag.Get("protobuf_key"), ",") + valTags := strings.Split(f.Tag.Get("protobuf_val"), ",") + for _, t := range tags { + if strings.HasPrefix(t, "customtype=") { + valTags = append(valTags, t) + } + if t == "stdtime" { + valTags = append(valTags, t) + } + if t == "stdduration" { + valTags = append(valTags, t) + } + } + keySizer, keyMarshaler := typeMarshaler(keyType, keyTags, false, false) // don't omit zero value in map + valSizer, valMarshaler := typeMarshaler(valType, valTags, false, false) // don't omit zero value in map + keyWireTag := 1<<3 | wiretype(keyTags[0]) + valWireTag := 2<<3 | wiretype(valTags[0]) + + // We create an interface to get the addresses of the map key and value. + // If value is pointer-typed, the interface is a direct interface, the + // idata itself is the value. Otherwise, the idata is the pointer to the + // value. + // Key cannot be pointer-typed. + valIsPtr := valType.Kind() == reflect.Ptr + return func(ptr pointer, tagsize int) int { + m := ptr.asPointerTo(t).Elem() // the map + n := 0 + for _, k := range m.MapKeys() { + ki := k.Interface() + vi := m.MapIndex(k).Interface() + kaddr := toAddrPointer(&ki, false) // pointer to key + vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value + siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, tag uint64, deterministic bool) ([]byte, error) { + m := ptr.asPointerTo(t).Elem() // the map + var err error + keys := m.MapKeys() + if len(keys) > 1 && deterministic { + sort.Sort(mapKeys(keys)) + } + for _, k := range keys { + ki := k.Interface() + vi := m.MapIndex(k).Interface() + kaddr := toAddrPointer(&ki, false) // pointer to key + vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value + b = appendVarint(b, tag) + siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1) + b = appendVarint(b, uint64(siz)) + b, err = keyMarshaler(b, kaddr, keyWireTag, deterministic) + if err != nil { + return b, err + } + b, err = valMarshaler(b, vaddr, valWireTag, deterministic) + if err != nil && err != ErrNil { // allow nil value in map + return b, err + } + } + return b, nil + } +} + +// makeOneOfMarshaler returns the sizer and marshaler for a oneof field. +// fi is the marshal info of the field. +// f is the pointer to the reflect data structure of the field. +func makeOneOfMarshaler(fi *marshalFieldInfo, f *reflect.StructField) (sizer, marshaler) { + // Oneof field is an interface. We need to get the actual data type on the fly. + t := f.Type + return func(ptr pointer, _ int) int { + p := ptr.getInterfacePointer() + if p.isNil() { + return 0 + } + v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct + telem := v.Type() + e := fi.oneofElems[telem] + return e.sizer(p, e.tagsize) + }, + func(b []byte, ptr pointer, _ uint64, deterministic bool) ([]byte, error) { + p := ptr.getInterfacePointer() + if p.isNil() { + return b, nil + } + v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct + telem := v.Type() + if telem.Field(0).Type.Kind() == reflect.Ptr && p.getPointer().isNil() { + return b, errOneofHasNil + } + e := fi.oneofElems[telem] + return e.marshaler(b, p, e.wiretag, deterministic) + } +} + +// sizeExtensions computes the size of encoded data for a XXX_InternalExtensions field. +func (u *marshalInfo) sizeExtensions(ext *XXX_InternalExtensions) int { + m, mu := ext.extensionsRead() + if m == nil { + return 0 + } + mu.Lock() + + n := 0 + for _, e := range m { + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + n += len(e.enc) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + n += ei.sizer(p, ei.tagsize) + } + mu.Unlock() + return n +} + +// appendExtensions marshals a XXX_InternalExtensions field to the end of byte slice b. +func (u *marshalInfo) appendExtensions(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) { + m, mu := ext.extensionsRead() + if m == nil { + return b, nil + } + mu.Lock() + defer mu.Unlock() + + var err error + + // Fast-path for common cases: zero or one extensions. + // Don't bother sorting the keys. + if len(m) <= 1 { + for _, e := range m { + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + b = append(b, e.enc...) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + b, err = ei.marshaler(b, p, ei.wiretag, deterministic) + if err != nil { + return b, err + } + } + return b, nil + } + + // Sort the keys to provide a deterministic encoding. + // Not sure this is required, but the old code does it. + keys := make([]int, 0, len(m)) + for k := range m { + keys = append(keys, int(k)) + } + sort.Ints(keys) + + for _, k := range keys { + e := m[int32(k)] + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + b = append(b, e.enc...) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + b, err = ei.marshaler(b, p, ei.wiretag, deterministic) + if err != nil { + return b, err + } + } + return b, nil +} + +// message set format is: +// message MessageSet { +// repeated group Item = 1 { +// required int32 type_id = 2; +// required string message = 3; +// }; +// } + +// sizeMessageSet computes the size of encoded data for a XXX_InternalExtensions field +// in message set format (above). +func (u *marshalInfo) sizeMessageSet(ext *XXX_InternalExtensions) int { + m, mu := ext.extensionsRead() + if m == nil { + return 0 + } + mu.Lock() + + n := 0 + for id, e := range m { + n += 2 // start group, end group. tag = 1 (size=1) + n += SizeVarint(uint64(id)) + 1 // type_id, tag = 2 (size=1) + + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint + siz := len(msgWithLen) + n += siz + 1 // message, tag = 3 (size=1) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + n += ei.sizer(p, 1) // message, tag = 3 (size=1) + } + mu.Unlock() + return n +} + +// appendMessageSet marshals a XXX_InternalExtensions field in message set format (above) +// to the end of byte slice b. +func (u *marshalInfo) appendMessageSet(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) { + m, mu := ext.extensionsRead() + if m == nil { + return b, nil + } + mu.Lock() + defer mu.Unlock() + + var err error + + // Fast-path for common cases: zero or one extensions. + // Don't bother sorting the keys. + if len(m) <= 1 { + for id, e := range m { + b = append(b, 1<<3|WireStartGroup) + b = append(b, 2<<3|WireVarint) + b = appendVarint(b, uint64(id)) + + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint + b = append(b, 3<<3|WireBytes) + b = append(b, msgWithLen...) + b = append(b, 1<<3|WireEndGroup) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic) + if err != nil { + return b, err + } + b = append(b, 1<<3|WireEndGroup) + } + return b, nil + } + + // Sort the keys to provide a deterministic encoding. + keys := make([]int, 0, len(m)) + for k := range m { + keys = append(keys, int(k)) + } + sort.Ints(keys) + + for _, id := range keys { + e := m[int32(id)] + b = append(b, 1<<3|WireStartGroup) + b = append(b, 2<<3|WireVarint) + b = appendVarint(b, uint64(id)) + + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint + b = append(b, 3<<3|WireBytes) + b = append(b, msgWithLen...) + b = append(b, 1<<3|WireEndGroup) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic) + b = append(b, 1<<3|WireEndGroup) + if err != nil { + return b, err + } + } + return b, nil +} + +// sizeV1Extensions computes the size of encoded data for a V1-API extension field. +func (u *marshalInfo) sizeV1Extensions(m map[int32]Extension) int { + if m == nil { + return 0 + } + + n := 0 + for _, e := range m { + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + n += len(e.enc) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + n += ei.sizer(p, ei.tagsize) + } + return n +} + +// appendV1Extensions marshals a V1-API extension field to the end of byte slice b. +func (u *marshalInfo) appendV1Extensions(b []byte, m map[int32]Extension, deterministic bool) ([]byte, error) { + if m == nil { + return b, nil + } + + // Sort the keys to provide a deterministic encoding. + keys := make([]int, 0, len(m)) + for k := range m { + keys = append(keys, int(k)) + } + sort.Ints(keys) + + var err error + for _, k := range keys { + e := m[int32(k)] + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + b = append(b, e.enc...) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + b, err = ei.marshaler(b, p, ei.wiretag, deterministic) + if err != nil { + return b, err + } + } + return b, nil +} + +// newMarshaler is the interface representing objects that can marshal themselves. +// +// This exists to support protoc-gen-go generated messages. +// The proto package will stop type-asserting to this interface in the future. +// +// DO NOT DEPEND ON THIS. +type newMarshaler interface { + XXX_Size() int + XXX_Marshal(b []byte, deterministic bool) ([]byte, error) +} + +// Size returns the encoded size of a protocol buffer message. +// This is the main entry point. +func Size(pb Message) int { + if m, ok := pb.(newMarshaler); ok { + return m.XXX_Size() + } + if m, ok := pb.(Marshaler); ok { + // If the message can marshal itself, let it do it, for compatibility. + // NOTE: This is not efficient. + b, _ := m.Marshal() + return len(b) + } + // in case somehow we didn't generate the wrapper + if pb == nil { + return 0 + } + var info InternalMessageInfo + return info.Size(pb) +} + +// Marshal takes a protocol buffer message +// and encodes it into the wire format, returning the data. +// This is the main entry point. +func Marshal(pb Message) ([]byte, error) { + if m, ok := pb.(newMarshaler); ok { + siz := m.XXX_Size() + b := make([]byte, 0, siz) + return m.XXX_Marshal(b, false) + } + if m, ok := pb.(Marshaler); ok { + // If the message can marshal itself, let it do it, for compatibility. + // NOTE: This is not efficient. + return m.Marshal() + } + // in case somehow we didn't generate the wrapper + if pb == nil { + return nil, ErrNil + } + var info InternalMessageInfo + siz := info.Size(pb) + b := make([]byte, 0, siz) + return info.Marshal(b, pb, false) +} + +// Marshal takes a protocol buffer message +// and encodes it into the wire format, writing the result to the +// Buffer. +// This is an alternative entry point. It is not necessary to use +// a Buffer for most applications. +func (p *Buffer) Marshal(pb Message) error { + var err error + if m, ok := pb.(newMarshaler); ok { + siz := m.XXX_Size() + p.grow(siz) // make sure buf has enough capacity + p.buf, err = m.XXX_Marshal(p.buf, p.deterministic) + return err + } + if m, ok := pb.(Marshaler); ok { + // If the message can marshal itself, let it do it, for compatibility. + // NOTE: This is not efficient. + var b []byte + b, err = m.Marshal() + p.buf = append(p.buf, b...) + return err + } + // in case somehow we didn't generate the wrapper + if pb == nil { + return ErrNil + } + var info InternalMessageInfo + siz := info.Size(pb) + p.grow(siz) // make sure buf has enough capacity + p.buf, err = info.Marshal(p.buf, pb, p.deterministic) + return err +} + +// grow grows the buffer's capacity, if necessary, to guarantee space for +// another n bytes. After grow(n), at least n bytes can be written to the +// buffer without another allocation. +func (p *Buffer) grow(n int) { + need := len(p.buf) + n + if need <= cap(p.buf) { + return + } + newCap := len(p.buf) * 2 + if newCap < need { + newCap = need + } + p.buf = append(make([]byte, 0, newCap), p.buf...) +} diff --git a/vendor/github.com/gogo/protobuf/proto/table_marshal_gogo.go b/vendor/github.com/gogo/protobuf/proto/table_marshal_gogo.go new file mode 100644 index 000000000..997f57c1e --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/table_marshal_gogo.go @@ -0,0 +1,388 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2018, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import ( + "reflect" + "time" +) + +// makeMessageRefMarshaler differs a bit from makeMessageMarshaler +// It marshal a message T instead of a *T +func makeMessageRefMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + siz := u.size(ptr) + return siz + SizeVarint(uint64(siz)) + tagsize + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + b = appendVarint(b, wiretag) + siz := u.cachedsize(ptr) + b = appendVarint(b, uint64(siz)) + return u.marshal(b, ptr, deterministic) + } +} + +// makeMessageRefSliceMarshaler differs quite a lot from makeMessageSliceMarshaler +// It marshals a slice of messages []T instead of []*T +func makeMessageRefSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(u.typ) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + e := elem.Interface() + v := toAddrPointer(&e, false) + siz := u.size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(u.typ) + var err, errreq error + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + e := elem.Interface() + v := toAddrPointer(&e, false) + b = appendVarint(b, wiretag) + siz := u.size(v) + b = appendVarint(b, uint64(siz)) + b, err = u.marshal(b, v, deterministic) + + if err != nil { + if _, ok := err.(*RequiredNotSetError); ok { + // Required field in submessage is not set. + // We record the error but keep going, to give a complete marshaling. + if errreq == nil { + errreq = err + } + continue + } + if err == ErrNil { + err = errRepeatedHasNil + } + return b, err + } + } + + return b, errreq + } +} + +func makeCustomPtrMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + if ptr.isNil() { + return 0 + } + m := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(custom) + siz := m.Size() + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + if ptr.isNil() { + return b, nil + } + m := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(custom) + siz := m.Size() + buf, err := m.Marshal() + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + return b, nil + } +} + +func makeCustomMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + m := ptr.asPointerTo(u.typ).Interface().(custom) + siz := m.Size() + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + m := ptr.asPointerTo(u.typ).Interface().(custom) + siz := m.Size() + buf, err := m.Marshal() + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + return b, nil + } +} + +func makeTimeMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + t := ptr.asPointerTo(u.typ).Interface().(*time.Time) + ts, err := timestampProto(*t) + if err != nil { + return 0 + } + siz := Size(ts) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + t := ptr.asPointerTo(u.typ).Interface().(*time.Time) + ts, err := timestampProto(*t) + if err != nil { + return nil, err + } + buf, err := Marshal(ts) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeTimePtrMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + if ptr.isNil() { + return 0 + } + t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*time.Time) + ts, err := timestampProto(*t) + if err != nil { + return 0 + } + siz := Size(ts) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + if ptr.isNil() { + return b, nil + } + t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*time.Time) + ts, err := timestampProto(*t) + if err != nil { + return nil, err + } + buf, err := Marshal(ts) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeTimeSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(u.typ) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(time.Time) + ts, err := timestampProto(t) + if err != nil { + return 0 + } + siz := Size(ts) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(u.typ) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(time.Time) + ts, err := timestampProto(t) + if err != nil { + return nil, err + } + siz := Size(ts) + buf, err := Marshal(ts) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeTimePtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(*time.Time) + ts, err := timestampProto(*t) + if err != nil { + return 0 + } + siz := Size(ts) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + t := elem.Interface().(*time.Time) + ts, err := timestampProto(*t) + if err != nil { + return nil, err + } + siz := Size(ts) + buf, err := Marshal(ts) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeDurationMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + d := ptr.asPointerTo(u.typ).Interface().(*time.Duration) + dur := durationProto(*d) + siz := Size(dur) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + d := ptr.asPointerTo(u.typ).Interface().(*time.Duration) + dur := durationProto(*d) + buf, err := Marshal(dur) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeDurationPtrMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + if ptr.isNil() { + return 0 + } + d := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*time.Duration) + dur := durationProto(*d) + siz := Size(dur) + return tagsize + SizeVarint(uint64(siz)) + siz + }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + if ptr.isNil() { + return b, nil + } + d := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*time.Duration) + dur := durationProto(*d) + buf, err := Marshal(dur) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(buf))) + b = append(b, buf...) + return b, nil + } +} + +func makeDurationSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(u.typ) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + d := elem.Interface().(time.Duration) + dur := durationProto(d) + siz := Size(dur) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(u.typ) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + d := elem.Interface().(time.Duration) + dur := durationProto(d) + siz := Size(dur) + buf, err := Marshal(dur) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} + +func makeDurationPtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + n := 0 + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + d := elem.Interface().(*time.Duration) + dur := durationProto(*d) + siz := Size(dur) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getSlice(reflect.PtrTo(u.typ)) + for i := 0; i < s.Len(); i++ { + elem := s.Index(i) + d := elem.Interface().(*time.Duration) + dur := durationProto(*d) + siz := Size(dur) + buf, err := Marshal(dur) + if err != nil { + return nil, err + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(siz)) + b = append(b, buf...) + } + + return b, nil + } +} diff --git a/vendor/github.com/gogo/protobuf/proto/table_merge.go b/vendor/github.com/gogo/protobuf/proto/table_merge.go new file mode 100644 index 000000000..f520106e0 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/table_merge.go @@ -0,0 +1,657 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2016 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import ( + "fmt" + "reflect" + "strings" + "sync" + "sync/atomic" +) + +// Merge merges the src message into dst. +// This assumes that dst and src of the same type and are non-nil. +func (a *InternalMessageInfo) Merge(dst, src Message) { + mi := atomicLoadMergeInfo(&a.merge) + if mi == nil { + mi = getMergeInfo(reflect.TypeOf(dst).Elem()) + atomicStoreMergeInfo(&a.merge, mi) + } + mi.merge(toPointer(&dst), toPointer(&src)) +} + +type mergeInfo struct { + typ reflect.Type + + initialized int32 // 0: only typ is valid, 1: everything is valid + lock sync.Mutex + + fields []mergeFieldInfo + unrecognized field // Offset of XXX_unrecognized +} + +type mergeFieldInfo struct { + field field // Offset of field, guaranteed to be valid + + // isPointer reports whether the value in the field is a pointer. + // This is true for the following situations: + // * Pointer to struct + // * Pointer to basic type (proto2 only) + // * Slice (first value in slice header is a pointer) + // * String (first value in string header is a pointer) + isPointer bool + + // basicWidth reports the width of the field assuming that it is directly + // embedded in the struct (as is the case for basic types in proto3). + // The possible values are: + // 0: invalid + // 1: bool + // 4: int32, uint32, float32 + // 8: int64, uint64, float64 + basicWidth int + + // Where dst and src are pointers to the types being merged. + merge func(dst, src pointer) +} + +var ( + mergeInfoMap = map[reflect.Type]*mergeInfo{} + mergeInfoLock sync.Mutex +) + +func getMergeInfo(t reflect.Type) *mergeInfo { + mergeInfoLock.Lock() + defer mergeInfoLock.Unlock() + mi := mergeInfoMap[t] + if mi == nil { + mi = &mergeInfo{typ: t} + mergeInfoMap[t] = mi + } + return mi +} + +// merge merges src into dst assuming they are both of type *mi.typ. +func (mi *mergeInfo) merge(dst, src pointer) { + if dst.isNil() { + panic("proto: nil destination") + } + if src.isNil() { + return // Nothing to do. + } + + if atomic.LoadInt32(&mi.initialized) == 0 { + mi.computeMergeInfo() + } + + for _, fi := range mi.fields { + sfp := src.offset(fi.field) + + // As an optimization, we can avoid the merge function call cost + // if we know for sure that the source will have no effect + // by checking if it is the zero value. + if unsafeAllowed { + if fi.isPointer && sfp.getPointer().isNil() { // Could be slice or string + continue + } + if fi.basicWidth > 0 { + switch { + case fi.basicWidth == 1 && !*sfp.toBool(): + continue + case fi.basicWidth == 4 && *sfp.toUint32() == 0: + continue + case fi.basicWidth == 8 && *sfp.toUint64() == 0: + continue + } + } + } + + dfp := dst.offset(fi.field) + fi.merge(dfp, sfp) + } + + // TODO: Make this faster? + out := dst.asPointerTo(mi.typ).Elem() + in := src.asPointerTo(mi.typ).Elem() + if emIn, err := extendable(in.Addr().Interface()); err == nil { + emOut, _ := extendable(out.Addr().Interface()) + mIn, muIn := emIn.extensionsRead() + if mIn != nil { + mOut := emOut.extensionsWrite() + muIn.Lock() + mergeExtension(mOut, mIn) + muIn.Unlock() + } + } + + if mi.unrecognized.IsValid() { + if b := *src.offset(mi.unrecognized).toBytes(); len(b) > 0 { + *dst.offset(mi.unrecognized).toBytes() = append([]byte(nil), b...) + } + } +} + +func (mi *mergeInfo) computeMergeInfo() { + mi.lock.Lock() + defer mi.lock.Unlock() + if mi.initialized != 0 { + return + } + t := mi.typ + n := t.NumField() + + props := GetProperties(t) + for i := 0; i < n; i++ { + f := t.Field(i) + if strings.HasPrefix(f.Name, "XXX_") { + continue + } + + mfi := mergeFieldInfo{field: toField(&f)} + tf := f.Type + + // As an optimization, we can avoid the merge function call cost + // if we know for sure that the source will have no effect + // by checking if it is the zero value. + if unsafeAllowed { + switch tf.Kind() { + case reflect.Ptr, reflect.Slice, reflect.String: + // As a special case, we assume slices and strings are pointers + // since we know that the first field in the SliceSlice or + // StringHeader is a data pointer. + mfi.isPointer = true + case reflect.Bool: + mfi.basicWidth = 1 + case reflect.Int32, reflect.Uint32, reflect.Float32: + mfi.basicWidth = 4 + case reflect.Int64, reflect.Uint64, reflect.Float64: + mfi.basicWidth = 8 + } + } + + // Unwrap tf to get at its most basic type. + var isPointer, isSlice bool + if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { + isSlice = true + tf = tf.Elem() + } + if tf.Kind() == reflect.Ptr { + isPointer = true + tf = tf.Elem() + } + if isPointer && isSlice && tf.Kind() != reflect.Struct { + panic("both pointer and slice for basic type in " + tf.Name()) + } + + switch tf.Kind() { + case reflect.Int32: + switch { + case isSlice: // E.g., []int32 + mfi.merge = func(dst, src pointer) { + // NOTE: toInt32Slice is not defined (see pointer_reflect.go). + /* + sfsp := src.toInt32Slice() + if *sfsp != nil { + dfsp := dst.toInt32Slice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []int64{} + } + } + */ + sfs := src.getInt32Slice() + if sfs != nil { + dfs := dst.getInt32Slice() + dfs = append(dfs, sfs...) + if dfs == nil { + dfs = []int32{} + } + dst.setInt32Slice(dfs) + } + } + case isPointer: // E.g., *int32 + mfi.merge = func(dst, src pointer) { + // NOTE: toInt32Ptr is not defined (see pointer_reflect.go). + /* + sfpp := src.toInt32Ptr() + if *sfpp != nil { + dfpp := dst.toInt32Ptr() + if *dfpp == nil { + *dfpp = Int32(**sfpp) + } else { + **dfpp = **sfpp + } + } + */ + sfp := src.getInt32Ptr() + if sfp != nil { + dfp := dst.getInt32Ptr() + if dfp == nil { + dst.setInt32Ptr(*sfp) + } else { + *dfp = *sfp + } + } + } + default: // E.g., int32 + mfi.merge = func(dst, src pointer) { + if v := *src.toInt32(); v != 0 { + *dst.toInt32() = v + } + } + } + case reflect.Int64: + switch { + case isSlice: // E.g., []int64 + mfi.merge = func(dst, src pointer) { + sfsp := src.toInt64Slice() + if *sfsp != nil { + dfsp := dst.toInt64Slice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []int64{} + } + } + } + case isPointer: // E.g., *int64 + mfi.merge = func(dst, src pointer) { + sfpp := src.toInt64Ptr() + if *sfpp != nil { + dfpp := dst.toInt64Ptr() + if *dfpp == nil { + *dfpp = Int64(**sfpp) + } else { + **dfpp = **sfpp + } + } + } + default: // E.g., int64 + mfi.merge = func(dst, src pointer) { + if v := *src.toInt64(); v != 0 { + *dst.toInt64() = v + } + } + } + case reflect.Uint32: + switch { + case isSlice: // E.g., []uint32 + mfi.merge = func(dst, src pointer) { + sfsp := src.toUint32Slice() + if *sfsp != nil { + dfsp := dst.toUint32Slice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []uint32{} + } + } + } + case isPointer: // E.g., *uint32 + mfi.merge = func(dst, src pointer) { + sfpp := src.toUint32Ptr() + if *sfpp != nil { + dfpp := dst.toUint32Ptr() + if *dfpp == nil { + *dfpp = Uint32(**sfpp) + } else { + **dfpp = **sfpp + } + } + } + default: // E.g., uint32 + mfi.merge = func(dst, src pointer) { + if v := *src.toUint32(); v != 0 { + *dst.toUint32() = v + } + } + } + case reflect.Uint64: + switch { + case isSlice: // E.g., []uint64 + mfi.merge = func(dst, src pointer) { + sfsp := src.toUint64Slice() + if *sfsp != nil { + dfsp := dst.toUint64Slice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []uint64{} + } + } + } + case isPointer: // E.g., *uint64 + mfi.merge = func(dst, src pointer) { + sfpp := src.toUint64Ptr() + if *sfpp != nil { + dfpp := dst.toUint64Ptr() + if *dfpp == nil { + *dfpp = Uint64(**sfpp) + } else { + **dfpp = **sfpp + } + } + } + default: // E.g., uint64 + mfi.merge = func(dst, src pointer) { + if v := *src.toUint64(); v != 0 { + *dst.toUint64() = v + } + } + } + case reflect.Float32: + switch { + case isSlice: // E.g., []float32 + mfi.merge = func(dst, src pointer) { + sfsp := src.toFloat32Slice() + if *sfsp != nil { + dfsp := dst.toFloat32Slice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []float32{} + } + } + } + case isPointer: // E.g., *float32 + mfi.merge = func(dst, src pointer) { + sfpp := src.toFloat32Ptr() + if *sfpp != nil { + dfpp := dst.toFloat32Ptr() + if *dfpp == nil { + *dfpp = Float32(**sfpp) + } else { + **dfpp = **sfpp + } + } + } + default: // E.g., float32 + mfi.merge = func(dst, src pointer) { + if v := *src.toFloat32(); v != 0 { + *dst.toFloat32() = v + } + } + } + case reflect.Float64: + switch { + case isSlice: // E.g., []float64 + mfi.merge = func(dst, src pointer) { + sfsp := src.toFloat64Slice() + if *sfsp != nil { + dfsp := dst.toFloat64Slice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []float64{} + } + } + } + case isPointer: // E.g., *float64 + mfi.merge = func(dst, src pointer) { + sfpp := src.toFloat64Ptr() + if *sfpp != nil { + dfpp := dst.toFloat64Ptr() + if *dfpp == nil { + *dfpp = Float64(**sfpp) + } else { + **dfpp = **sfpp + } + } + } + default: // E.g., float64 + mfi.merge = func(dst, src pointer) { + if v := *src.toFloat64(); v != 0 { + *dst.toFloat64() = v + } + } + } + case reflect.Bool: + switch { + case isSlice: // E.g., []bool + mfi.merge = func(dst, src pointer) { + sfsp := src.toBoolSlice() + if *sfsp != nil { + dfsp := dst.toBoolSlice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []bool{} + } + } + } + case isPointer: // E.g., *bool + mfi.merge = func(dst, src pointer) { + sfpp := src.toBoolPtr() + if *sfpp != nil { + dfpp := dst.toBoolPtr() + if *dfpp == nil { + *dfpp = Bool(**sfpp) + } else { + **dfpp = **sfpp + } + } + } + default: // E.g., bool + mfi.merge = func(dst, src pointer) { + if v := *src.toBool(); v { + *dst.toBool() = v + } + } + } + case reflect.String: + switch { + case isSlice: // E.g., []string + mfi.merge = func(dst, src pointer) { + sfsp := src.toStringSlice() + if *sfsp != nil { + dfsp := dst.toStringSlice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []string{} + } + } + } + case isPointer: // E.g., *string + mfi.merge = func(dst, src pointer) { + sfpp := src.toStringPtr() + if *sfpp != nil { + dfpp := dst.toStringPtr() + if *dfpp == nil { + *dfpp = String(**sfpp) + } else { + **dfpp = **sfpp + } + } + } + default: // E.g., string + mfi.merge = func(dst, src pointer) { + if v := *src.toString(); v != "" { + *dst.toString() = v + } + } + } + case reflect.Slice: + isProto3 := props.Prop[i].proto3 + switch { + case isPointer: + panic("bad pointer in byte slice case in " + tf.Name()) + case tf.Elem().Kind() != reflect.Uint8: + panic("bad element kind in byte slice case in " + tf.Name()) + case isSlice: // E.g., [][]byte + mfi.merge = func(dst, src pointer) { + sbsp := src.toBytesSlice() + if *sbsp != nil { + dbsp := dst.toBytesSlice() + for _, sb := range *sbsp { + if sb == nil { + *dbsp = append(*dbsp, nil) + } else { + *dbsp = append(*dbsp, append([]byte{}, sb...)) + } + } + if *dbsp == nil { + *dbsp = [][]byte{} + } + } + } + default: // E.g., []byte + mfi.merge = func(dst, src pointer) { + sbp := src.toBytes() + if *sbp != nil { + dbp := dst.toBytes() + if !isProto3 || len(*sbp) > 0 { + *dbp = append([]byte{}, *sbp...) + } + } + } + } + case reflect.Struct: + switch { + case !isPointer: + mergeInfo := getMergeInfo(tf) + mfi.merge = func(dst, src pointer) { + mergeInfo.merge(dst, src) + } + case isSlice: // E.g., []*pb.T + mergeInfo := getMergeInfo(tf) + mfi.merge = func(dst, src pointer) { + sps := src.getPointerSlice() + if sps != nil { + dps := dst.getPointerSlice() + for _, sp := range sps { + var dp pointer + if !sp.isNil() { + dp = valToPointer(reflect.New(tf)) + mergeInfo.merge(dp, sp) + } + dps = append(dps, dp) + } + if dps == nil { + dps = []pointer{} + } + dst.setPointerSlice(dps) + } + } + default: // E.g., *pb.T + mergeInfo := getMergeInfo(tf) + mfi.merge = func(dst, src pointer) { + sp := src.getPointer() + if !sp.isNil() { + dp := dst.getPointer() + if dp.isNil() { + dp = valToPointer(reflect.New(tf)) + dst.setPointer(dp) + } + mergeInfo.merge(dp, sp) + } + } + } + case reflect.Map: + switch { + case isPointer || isSlice: + panic("bad pointer or slice in map case in " + tf.Name()) + default: // E.g., map[K]V + mfi.merge = func(dst, src pointer) { + sm := src.asPointerTo(tf).Elem() + if sm.Len() == 0 { + return + } + dm := dst.asPointerTo(tf).Elem() + if dm.IsNil() { + dm.Set(reflect.MakeMap(tf)) + } + + switch tf.Elem().Kind() { + case reflect.Ptr: // Proto struct (e.g., *T) + for _, key := range sm.MapKeys() { + val := sm.MapIndex(key) + val = reflect.ValueOf(Clone(val.Interface().(Message))) + dm.SetMapIndex(key, val) + } + case reflect.Slice: // E.g. Bytes type (e.g., []byte) + for _, key := range sm.MapKeys() { + val := sm.MapIndex(key) + val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) + dm.SetMapIndex(key, val) + } + default: // Basic type (e.g., string) + for _, key := range sm.MapKeys() { + val := sm.MapIndex(key) + dm.SetMapIndex(key, val) + } + } + } + } + case reflect.Interface: + // Must be oneof field. + switch { + case isPointer || isSlice: + panic("bad pointer or slice in interface case in " + tf.Name()) + default: // E.g., interface{} + // TODO: Make this faster? + mfi.merge = func(dst, src pointer) { + su := src.asPointerTo(tf).Elem() + if !su.IsNil() { + du := dst.asPointerTo(tf).Elem() + typ := su.Elem().Type() + if du.IsNil() || du.Elem().Type() != typ { + du.Set(reflect.New(typ.Elem())) // Initialize interface if empty + } + sv := su.Elem().Elem().Field(0) + if sv.Kind() == reflect.Ptr && sv.IsNil() { + return + } + dv := du.Elem().Elem().Field(0) + if dv.Kind() == reflect.Ptr && dv.IsNil() { + dv.Set(reflect.New(sv.Type().Elem())) // Initialize proto message if empty + } + switch sv.Type().Kind() { + case reflect.Ptr: // Proto struct (e.g., *T) + Merge(dv.Interface().(Message), sv.Interface().(Message)) + case reflect.Slice: // E.g. Bytes type (e.g., []byte) + dv.Set(reflect.ValueOf(append([]byte{}, sv.Bytes()...))) + default: // Basic type (e.g., string) + dv.Set(sv) + } + } + } + } + default: + panic(fmt.Sprintf("merger not found for type:%s", tf)) + } + mi.fields = append(mi.fields, mfi) + } + + mi.unrecognized = invalidField + if f, ok := t.FieldByName("XXX_unrecognized"); ok { + if f.Type != reflect.TypeOf([]byte{}) { + panic("expected XXX_unrecognized to be of type []byte") + } + mi.unrecognized = toField(&f) + } + + atomic.StoreInt32(&mi.initialized, 1) +} diff --git a/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go b/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go new file mode 100644 index 000000000..910e2dd6a --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go @@ -0,0 +1,2048 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2016 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import ( + "errors" + "fmt" + "io" + "math" + "reflect" + "strconv" + "strings" + "sync" + "sync/atomic" + "unicode/utf8" +) + +// Unmarshal is the entry point from the generated .pb.go files. +// This function is not intended to be used by non-generated code. +// This function is not subject to any compatibility guarantee. +// msg contains a pointer to a protocol buffer struct. +// b is the data to be unmarshaled into the protocol buffer. +// a is a pointer to a place to store cached unmarshal information. +func (a *InternalMessageInfo) Unmarshal(msg Message, b []byte) error { + // Load the unmarshal information for this message type. + // The atomic load ensures memory consistency. + u := atomicLoadUnmarshalInfo(&a.unmarshal) + if u == nil { + // Slow path: find unmarshal info for msg, update a with it. + u = getUnmarshalInfo(reflect.TypeOf(msg).Elem()) + atomicStoreUnmarshalInfo(&a.unmarshal, u) + } + // Then do the unmarshaling. + err := u.unmarshal(toPointer(&msg), b) + return err +} + +type unmarshalInfo struct { + typ reflect.Type // type of the protobuf struct + + // 0 = only typ field is initialized + // 1 = completely initialized + initialized int32 + lock sync.Mutex // prevents double initialization + dense []unmarshalFieldInfo // fields indexed by tag # + sparse map[uint64]unmarshalFieldInfo // fields indexed by tag # + reqFields []string // names of required fields + reqMask uint64 // 1< 0 { + // Read tag and wire type. + // Special case 1 and 2 byte varints. + var x uint64 + if b[0] < 128 { + x = uint64(b[0]) + b = b[1:] + } else if len(b) >= 2 && b[1] < 128 { + x = uint64(b[0]&0x7f) + uint64(b[1])<<7 + b = b[2:] + } else { + var n int + x, n = decodeVarint(b) + if n == 0 { + return io.ErrUnexpectedEOF + } + b = b[n:] + } + tag := x >> 3 + wire := int(x) & 7 + + // Dispatch on the tag to one of the unmarshal* functions below. + var f unmarshalFieldInfo + if tag < uint64(len(u.dense)) { + f = u.dense[tag] + } else { + f = u.sparse[tag] + } + if fn := f.unmarshal; fn != nil { + var err error + b, err = fn(b, m.offset(f.field), wire) + if err == nil { + reqMask |= f.reqMask + continue + } + if r, ok := err.(*RequiredNotSetError); ok { + // Remember this error, but keep parsing. We need to produce + // a full parse even if a required field is missing. + rnse = r + reqMask |= f.reqMask + continue + } + if err != errInternalBadWireType { + return err + } + // Fragments with bad wire type are treated as unknown fields. + } + + // Unknown tag. + if !u.unrecognized.IsValid() { + // Don't keep unrecognized data; just skip it. + var err error + b, err = skipField(b, wire) + if err != nil { + return err + } + continue + } + // Keep unrecognized data around. + // maybe in extensions, maybe in the unrecognized field. + z := m.offset(u.unrecognized).toBytes() + var emap map[int32]Extension + var e Extension + for _, r := range u.extensionRanges { + if uint64(r.Start) <= tag && tag <= uint64(r.End) { + if u.extensions.IsValid() { + mp := m.offset(u.extensions).toExtensions() + emap = mp.extensionsWrite() + e = emap[int32(tag)] + z = &e.enc + break + } + if u.oldExtensions.IsValid() { + p := m.offset(u.oldExtensions).toOldExtensions() + emap = *p + if emap == nil { + emap = map[int32]Extension{} + *p = emap + } + e = emap[int32(tag)] + z = &e.enc + break + } + if u.bytesExtensions.IsValid() { + z = m.offset(u.bytesExtensions).toBytes() + break + } + panic("no extensions field available") + } + } + // Use wire type to skip data. + var err error + b0 := b + b, err = skipField(b, wire) + if err != nil { + return err + } + *z = encodeVarint(*z, tag<<3|uint64(wire)) + *z = append(*z, b0[:len(b0)-len(b)]...) + + if emap != nil { + emap[int32(tag)] = e + } + } + if rnse != nil { + // A required field of a submessage/group is missing. Return that error. + return rnse + } + if reqMask != u.reqMask { + // A required field of this message is missing. + for _, n := range u.reqFields { + if reqMask&1 == 0 { + return &RequiredNotSetError{n} + } + reqMask >>= 1 + } + } + return nil +} + +// computeUnmarshalInfo fills in u with information for use +// in unmarshaling protocol buffers of type u.typ. +func (u *unmarshalInfo) computeUnmarshalInfo() { + u.lock.Lock() + defer u.lock.Unlock() + if u.initialized != 0 { + return + } + t := u.typ + n := t.NumField() + + // Set up the "not found" value for the unrecognized byte buffer. + // This is the default for proto3. + u.unrecognized = invalidField + u.extensions = invalidField + u.oldExtensions = invalidField + u.bytesExtensions = invalidField + + // List of the generated type and offset for each oneof field. + type oneofField struct { + ityp reflect.Type // interface type of oneof field + field field // offset in containing message + } + var oneofFields []oneofField + + for i := 0; i < n; i++ { + f := t.Field(i) + if f.Name == "XXX_unrecognized" { + // The byte slice used to hold unrecognized input is special. + if f.Type != reflect.TypeOf(([]byte)(nil)) { + panic("bad type for XXX_unrecognized field: " + f.Type.Name()) + } + u.unrecognized = toField(&f) + continue + } + if f.Name == "XXX_InternalExtensions" { + // Ditto here. + if f.Type != reflect.TypeOf(XXX_InternalExtensions{}) { + panic("bad type for XXX_InternalExtensions field: " + f.Type.Name()) + } + u.extensions = toField(&f) + if f.Tag.Get("protobuf_messageset") == "1" { + u.isMessageSet = true + } + continue + } + if f.Name == "XXX_extensions" { + // An older form of the extensions field. + if f.Type == reflect.TypeOf((map[int32]Extension)(nil)) { + u.oldExtensions = toField(&f) + continue + } else if f.Type == reflect.TypeOf(([]byte)(nil)) { + u.bytesExtensions = toField(&f) + continue + } + panic("bad type for XXX_extensions field: " + f.Type.Name()) + } + if f.Name == "XXX_NoUnkeyedLiteral" || f.Name == "XXX_sizecache" { + continue + } + + oneof := f.Tag.Get("protobuf_oneof") + if oneof != "" { + oneofFields = append(oneofFields, oneofField{f.Type, toField(&f)}) + // The rest of oneof processing happens below. + continue + } + + tags := f.Tag.Get("protobuf") + tagArray := strings.Split(tags, ",") + if len(tagArray) < 2 { + panic("protobuf tag not enough fields in " + t.Name() + "." + f.Name + ": " + tags) + } + tag, err := strconv.Atoi(tagArray[1]) + if err != nil { + panic("protobuf tag field not an integer: " + tagArray[1]) + } + + name := "" + for _, tag := range tagArray[3:] { + if strings.HasPrefix(tag, "name=") { + name = tag[5:] + } + } + + // Extract unmarshaling function from the field (its type and tags). + unmarshal := fieldUnmarshaler(&f) + + // Required field? + var reqMask uint64 + if tagArray[2] == "req" { + bit := len(u.reqFields) + u.reqFields = append(u.reqFields, name) + reqMask = uint64(1) << uint(bit) + // TODO: if we have more than 64 required fields, we end up + // not verifying that all required fields are present. + // Fix this, perhaps using a count of required fields? + } + + // Store the info in the correct slot in the message. + u.setTag(tag, toField(&f), unmarshal, reqMask) + } + + // Find any types associated with oneof fields. + // TODO: XXX_OneofFuncs returns more info than we need. Get rid of some of it? + fn := reflect.Zero(reflect.PtrTo(t)).MethodByName("XXX_OneofFuncs") + // gogo: len(oneofFields) > 0 is needed for embedded oneof messages, without a marshaler and unmarshaler + if fn.IsValid() && len(oneofFields) > 0 { + res := fn.Call(nil)[3] // last return value from XXX_OneofFuncs: []interface{} + for i := res.Len() - 1; i >= 0; i-- { + v := res.Index(i) // interface{} + tptr := reflect.ValueOf(v.Interface()).Type() // *Msg_X + typ := tptr.Elem() // Msg_X + + f := typ.Field(0) // oneof implementers have one field + baseUnmarshal := fieldUnmarshaler(&f) + tagstr := strings.Split(f.Tag.Get("protobuf"), ",")[1] + tag, err := strconv.Atoi(tagstr) + if err != nil { + panic("protobuf tag field not an integer: " + tagstr) + } + + // Find the oneof field that this struct implements. + // Might take O(n^2) to process all of the oneofs, but who cares. + for _, of := range oneofFields { + if tptr.Implements(of.ityp) { + // We have found the corresponding interface for this struct. + // That lets us know where this struct should be stored + // when we encounter it during unmarshaling. + unmarshal := makeUnmarshalOneof(typ, of.ityp, baseUnmarshal) + u.setTag(tag, of.field, unmarshal, 0) + } + } + } + } + + // Get extension ranges, if any. + fn = reflect.Zero(reflect.PtrTo(t)).MethodByName("ExtensionRangeArray") + if fn.IsValid() { + if !u.extensions.IsValid() && !u.oldExtensions.IsValid() && !u.bytesExtensions.IsValid() { + panic("a message with extensions, but no extensions field in " + t.Name()) + } + u.extensionRanges = fn.Call(nil)[0].Interface().([]ExtensionRange) + } + + // Explicitly disallow tag 0. This will ensure we flag an error + // when decoding a buffer of all zeros. Without this code, we + // would decode and skip an all-zero buffer of even length. + // [0 0] is [tag=0/wiretype=varint varint-encoded-0]. + u.setTag(0, zeroField, func(b []byte, f pointer, w int) ([]byte, error) { + return nil, fmt.Errorf("proto: %s: illegal tag 0 (wire type %d)", t, w) + }, 0) + + // Set mask for required field check. + u.reqMask = uint64(1)<= 0 && (tag < 16 || tag < 2*n) { // TODO: what are the right numbers here? + for len(u.dense) <= tag { + u.dense = append(u.dense, unmarshalFieldInfo{}) + } + u.dense[tag] = i + return + } + if u.sparse == nil { + u.sparse = map[uint64]unmarshalFieldInfo{} + } + u.sparse[uint64(tag)] = i +} + +// fieldUnmarshaler returns an unmarshaler for the given field. +func fieldUnmarshaler(f *reflect.StructField) unmarshaler { + if f.Type.Kind() == reflect.Map { + return makeUnmarshalMap(f) + } + return typeUnmarshaler(f.Type, f.Tag.Get("protobuf")) +} + +// typeUnmarshaler returns an unmarshaler for the given field type / field tag pair. +func typeUnmarshaler(t reflect.Type, tags string) unmarshaler { + tagArray := strings.Split(tags, ",") + encoding := tagArray[0] + name := "unknown" + ctype := false + isTime := false + isDuration := false + for _, tag := range tagArray[3:] { + if strings.HasPrefix(tag, "name=") { + name = tag[5:] + } + if strings.HasPrefix(tag, "customtype=") { + ctype = true + } + if tag == "stdtime" { + isTime = true + } + if tag == "stdduration" { + isDuration = true + } + } + + // Figure out packaging (pointer, slice, or both) + slice := false + pointer := false + if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { + slice = true + t = t.Elem() + } + if t.Kind() == reflect.Ptr { + pointer = true + t = t.Elem() + } + + if ctype { + if reflect.PtrTo(t).Implements(customType) { + if slice { + return makeUnmarshalCustomSlice(getUnmarshalInfo(t), name) + } + if pointer { + return makeUnmarshalCustomPtr(getUnmarshalInfo(t), name) + } + return makeUnmarshalCustom(getUnmarshalInfo(t), name) + } else { + panic(fmt.Sprintf("custom type: type: %v, does not implement the proto.custom interface", t)) + } + } + + if isTime { + if pointer { + if slice { + return makeUnmarshalTimePtrSlice(getUnmarshalInfo(t), name) + } + return makeUnmarshalTimePtr(getUnmarshalInfo(t), name) + } + if slice { + return makeUnmarshalTimeSlice(getUnmarshalInfo(t), name) + } + return makeUnmarshalTime(getUnmarshalInfo(t), name) + } + + if isDuration { + if pointer { + if slice { + return makeUnmarshalDurationPtrSlice(getUnmarshalInfo(t), name) + } + return makeUnmarshalDurationPtr(getUnmarshalInfo(t), name) + } + if slice { + return makeUnmarshalDurationSlice(getUnmarshalInfo(t), name) + } + return makeUnmarshalDuration(getUnmarshalInfo(t), name) + } + + // We'll never have both pointer and slice for basic types. + if pointer && slice && t.Kind() != reflect.Struct { + panic("both pointer and slice for basic type in " + t.Name()) + } + + switch t.Kind() { + case reflect.Bool: + if pointer { + return unmarshalBoolPtr + } + if slice { + return unmarshalBoolSlice + } + return unmarshalBoolValue + case reflect.Int32: + switch encoding { + case "fixed32": + if pointer { + return unmarshalFixedS32Ptr + } + if slice { + return unmarshalFixedS32Slice + } + return unmarshalFixedS32Value + case "varint": + // this could be int32 or enum + if pointer { + return unmarshalInt32Ptr + } + if slice { + return unmarshalInt32Slice + } + return unmarshalInt32Value + case "zigzag32": + if pointer { + return unmarshalSint32Ptr + } + if slice { + return unmarshalSint32Slice + } + return unmarshalSint32Value + } + case reflect.Int64: + switch encoding { + case "fixed64": + if pointer { + return unmarshalFixedS64Ptr + } + if slice { + return unmarshalFixedS64Slice + } + return unmarshalFixedS64Value + case "varint": + if pointer { + return unmarshalInt64Ptr + } + if slice { + return unmarshalInt64Slice + } + return unmarshalInt64Value + case "zigzag64": + if pointer { + return unmarshalSint64Ptr + } + if slice { + return unmarshalSint64Slice + } + return unmarshalSint64Value + } + case reflect.Uint32: + switch encoding { + case "fixed32": + if pointer { + return unmarshalFixed32Ptr + } + if slice { + return unmarshalFixed32Slice + } + return unmarshalFixed32Value + case "varint": + if pointer { + return unmarshalUint32Ptr + } + if slice { + return unmarshalUint32Slice + } + return unmarshalUint32Value + } + case reflect.Uint64: + switch encoding { + case "fixed64": + if pointer { + return unmarshalFixed64Ptr + } + if slice { + return unmarshalFixed64Slice + } + return unmarshalFixed64Value + case "varint": + if pointer { + return unmarshalUint64Ptr + } + if slice { + return unmarshalUint64Slice + } + return unmarshalUint64Value + } + case reflect.Float32: + if pointer { + return unmarshalFloat32Ptr + } + if slice { + return unmarshalFloat32Slice + } + return unmarshalFloat32Value + case reflect.Float64: + if pointer { + return unmarshalFloat64Ptr + } + if slice { + return unmarshalFloat64Slice + } + return unmarshalFloat64Value + case reflect.Map: + panic("map type in typeUnmarshaler in " + t.Name()) + case reflect.Slice: + if pointer { + panic("bad pointer in slice case in " + t.Name()) + } + if slice { + return unmarshalBytesSlice + } + return unmarshalBytesValue + case reflect.String: + if pointer { + return unmarshalStringPtr + } + if slice { + return unmarshalStringSlice + } + return unmarshalStringValue + case reflect.Struct: + // message or group field + if !pointer { + switch encoding { + case "bytes": + if slice { + return makeUnmarshalMessageSlice(getUnmarshalInfo(t), name) + } + return makeUnmarshalMessage(getUnmarshalInfo(t), name) + } + } + switch encoding { + case "bytes": + if slice { + return makeUnmarshalMessageSlicePtr(getUnmarshalInfo(t), name) + } + return makeUnmarshalMessagePtr(getUnmarshalInfo(t), name) + case "group": + if slice { + return makeUnmarshalGroupSlicePtr(getUnmarshalInfo(t), name) + } + return makeUnmarshalGroupPtr(getUnmarshalInfo(t), name) + } + } + panic(fmt.Sprintf("unmarshaler not found type:%s encoding:%s", t, encoding)) +} + +// Below are all the unmarshalers for individual fields of various types. + +func unmarshalInt64Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x) + *f.toInt64() = v + return b, nil +} + +func unmarshalInt64Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x) + *f.toInt64Ptr() = &v + return b, nil +} + +func unmarshalInt64Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + x, n = decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x) + s := f.toInt64Slice() + *s = append(*s, v) + } + return res, nil + } + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x) + s := f.toInt64Slice() + *s = append(*s, v) + return b, nil +} + +func unmarshalSint64Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x>>1) ^ int64(x)<<63>>63 + *f.toInt64() = v + return b, nil +} + +func unmarshalSint64Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x>>1) ^ int64(x)<<63>>63 + *f.toInt64Ptr() = &v + return b, nil +} + +func unmarshalSint64Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + x, n = decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x>>1) ^ int64(x)<<63>>63 + s := f.toInt64Slice() + *s = append(*s, v) + } + return res, nil + } + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x>>1) ^ int64(x)<<63>>63 + s := f.toInt64Slice() + *s = append(*s, v) + return b, nil +} + +func unmarshalUint64Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint64(x) + *f.toUint64() = v + return b, nil +} + +func unmarshalUint64Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint64(x) + *f.toUint64Ptr() = &v + return b, nil +} + +func unmarshalUint64Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + x, n = decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint64(x) + s := f.toUint64Slice() + *s = append(*s, v) + } + return res, nil + } + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint64(x) + s := f.toUint64Slice() + *s = append(*s, v) + return b, nil +} + +func unmarshalInt32Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x) + *f.toInt32() = v + return b, nil +} + +func unmarshalInt32Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x) + f.setInt32Ptr(v) + return b, nil +} + +func unmarshalInt32Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + x, n = decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x) + f.appendInt32Slice(v) + } + return res, nil + } + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x) + f.appendInt32Slice(v) + return b, nil +} + +func unmarshalSint32Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x>>1) ^ int32(x)<<31>>31 + *f.toInt32() = v + return b, nil +} + +func unmarshalSint32Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x>>1) ^ int32(x)<<31>>31 + f.setInt32Ptr(v) + return b, nil +} + +func unmarshalSint32Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + x, n = decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x>>1) ^ int32(x)<<31>>31 + f.appendInt32Slice(v) + } + return res, nil + } + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x>>1) ^ int32(x)<<31>>31 + f.appendInt32Slice(v) + return b, nil +} + +func unmarshalUint32Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint32(x) + *f.toUint32() = v + return b, nil +} + +func unmarshalUint32Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint32(x) + *f.toUint32Ptr() = &v + return b, nil +} + +func unmarshalUint32Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + x, n = decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint32(x) + s := f.toUint32Slice() + *s = append(*s, v) + } + return res, nil + } + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint32(x) + s := f.toUint32Slice() + *s = append(*s, v) + return b, nil +} + +func unmarshalFixed64Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 + *f.toUint64() = v + return b[8:], nil +} + +func unmarshalFixed64Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 + *f.toUint64Ptr() = &v + return b[8:], nil +} + +func unmarshalFixed64Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 + s := f.toUint64Slice() + *s = append(*s, v) + b = b[8:] + } + return res, nil + } + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 + s := f.toUint64Slice() + *s = append(*s, v) + return b[8:], nil +} + +func unmarshalFixedS64Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 + *f.toInt64() = v + return b[8:], nil +} + +func unmarshalFixedS64Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 + *f.toInt64Ptr() = &v + return b[8:], nil +} + +func unmarshalFixedS64Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 + s := f.toInt64Slice() + *s = append(*s, v) + b = b[8:] + } + return res, nil + } + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 + s := f.toInt64Slice() + *s = append(*s, v) + return b[8:], nil +} + +func unmarshalFixed32Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 + *f.toUint32() = v + return b[4:], nil +} + +func unmarshalFixed32Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 + *f.toUint32Ptr() = &v + return b[4:], nil +} + +func unmarshalFixed32Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 + s := f.toUint32Slice() + *s = append(*s, v) + b = b[4:] + } + return res, nil + } + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 + s := f.toUint32Slice() + *s = append(*s, v) + return b[4:], nil +} + +func unmarshalFixedS32Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 + *f.toInt32() = v + return b[4:], nil +} + +func unmarshalFixedS32Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 + f.setInt32Ptr(v) + return b[4:], nil +} + +func unmarshalFixedS32Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 + f.appendInt32Slice(v) + b = b[4:] + } + return res, nil + } + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 + f.appendInt32Slice(v) + return b[4:], nil +} + +func unmarshalBoolValue(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + // Note: any length varint is allowed, even though any sane + // encoder will use one byte. + // See https://github.com/golang/protobuf/issues/76 + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + // TODO: check if x>1? Tests seem to indicate no. + v := x != 0 + *f.toBool() = v + return b[n:], nil +} + +func unmarshalBoolPtr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + v := x != 0 + *f.toBoolPtr() = &v + return b[n:], nil +} + +func unmarshalBoolSlice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + x, n = decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + v := x != 0 + s := f.toBoolSlice() + *s = append(*s, v) + b = b[n:] + } + return res, nil + } + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + v := x != 0 + s := f.toBoolSlice() + *s = append(*s, v) + return b[n:], nil +} + +func unmarshalFloat64Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) + *f.toFloat64() = v + return b[8:], nil +} + +func unmarshalFloat64Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) + *f.toFloat64Ptr() = &v + return b[8:], nil +} + +func unmarshalFloat64Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) + s := f.toFloat64Slice() + *s = append(*s, v) + b = b[8:] + } + return res, nil + } + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) + s := f.toFloat64Slice() + *s = append(*s, v) + return b[8:], nil +} + +func unmarshalFloat32Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) + *f.toFloat32() = v + return b[4:], nil +} + +func unmarshalFloat32Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) + *f.toFloat32Ptr() = &v + return b[4:], nil +} + +func unmarshalFloat32Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) + s := f.toFloat32Slice() + *s = append(*s, v) + b = b[4:] + } + return res, nil + } + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) + s := f.toFloat32Slice() + *s = append(*s, v) + return b[4:], nil +} + +func unmarshalStringValue(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + v := string(b[:x]) + if !utf8.ValidString(v) { + return nil, errInvalidUTF8 + } + *f.toString() = v + return b[x:], nil +} + +func unmarshalStringPtr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + v := string(b[:x]) + if !utf8.ValidString(v) { + return nil, errInvalidUTF8 + } + *f.toStringPtr() = &v + return b[x:], nil +} + +func unmarshalStringSlice(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + v := string(b[:x]) + if !utf8.ValidString(v) { + return nil, errInvalidUTF8 + } + s := f.toStringSlice() + *s = append(*s, v) + return b[x:], nil +} + +var emptyBuf [0]byte + +func unmarshalBytesValue(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + // The use of append here is a trick which avoids the zeroing + // that would be required if we used a make/copy pair. + // We append to emptyBuf instead of nil because we want + // a non-nil result even when the length is 0. + v := append(emptyBuf[:], b[:x]...) + *f.toBytes() = v + return b[x:], nil +} + +func unmarshalBytesSlice(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + v := append(emptyBuf[:], b[:x]...) + s := f.toBytesSlice() + *s = append(*s, v) + return b[x:], nil +} + +func makeUnmarshalMessagePtr(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + // First read the message field to see if something is there. + // The semantics of multiple submessages are weird. Instead of + // the last one winning (as it is for all other fields), multiple + // submessages are merged. + v := f.getPointer() + if v.isNil() { + v = valToPointer(reflect.New(sub.typ)) + f.setPointer(v) + } + err := sub.unmarshal(v, b[:x]) + if err != nil { + if r, ok := err.(*RequiredNotSetError); ok { + r.field = name + "." + r.field + } else { + return nil, err + } + } + return b[x:], err + } +} + +func makeUnmarshalMessageSlicePtr(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + v := valToPointer(reflect.New(sub.typ)) + err := sub.unmarshal(v, b[:x]) + if err != nil { + if r, ok := err.(*RequiredNotSetError); ok { + r.field = name + "." + r.field + } else { + return nil, err + } + } + f.appendPointer(v) + return b[x:], err + } +} + +func makeUnmarshalGroupPtr(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireStartGroup { + return b, errInternalBadWireType + } + x, y := findEndGroup(b) + if x < 0 { + return nil, io.ErrUnexpectedEOF + } + v := f.getPointer() + if v.isNil() { + v = valToPointer(reflect.New(sub.typ)) + f.setPointer(v) + } + err := sub.unmarshal(v, b[:x]) + if err != nil { + if r, ok := err.(*RequiredNotSetError); ok { + r.field = name + "." + r.field + } else { + return nil, err + } + } + return b[y:], err + } +} + +func makeUnmarshalGroupSlicePtr(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireStartGroup { + return b, errInternalBadWireType + } + x, y := findEndGroup(b) + if x < 0 { + return nil, io.ErrUnexpectedEOF + } + v := valToPointer(reflect.New(sub.typ)) + err := sub.unmarshal(v, b[:x]) + if err != nil { + if r, ok := err.(*RequiredNotSetError); ok { + r.field = name + "." + r.field + } else { + return nil, err + } + } + f.appendPointer(v) + return b[y:], err + } +} + +func makeUnmarshalMap(f *reflect.StructField) unmarshaler { + t := f.Type + kt := t.Key() + vt := t.Elem() + tagArray := strings.Split(f.Tag.Get("protobuf"), ",") + valTags := strings.Split(f.Tag.Get("protobuf_val"), ",") + for _, t := range tagArray { + if strings.HasPrefix(t, "customtype=") { + valTags = append(valTags, t) + } + if t == "stdtime" { + valTags = append(valTags, t) + } + if t == "stdduration" { + valTags = append(valTags, t) + } + } + unmarshalKey := typeUnmarshaler(kt, f.Tag.Get("protobuf_key")) + unmarshalVal := typeUnmarshaler(vt, strings.Join(valTags, ",")) + return func(b []byte, f pointer, w int) ([]byte, error) { + // The map entry is a submessage. Figure out how big it is. + if w != WireBytes { + return nil, fmt.Errorf("proto: bad wiretype for map field: got %d want %d", w, WireBytes) + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + r := b[x:] // unused data to return + b = b[:x] // data for map entry + + // Note: we could use #keys * #values ~= 200 functions + // to do map decoding without reflection. Probably not worth it. + // Maps will be somewhat slow. Oh well. + + // Read key and value from data. + k := reflect.New(kt) + v := reflect.New(vt) + for len(b) > 0 { + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + wire := int(x) & 7 + b = b[n:] + + var err error + switch x >> 3 { + case 1: + b, err = unmarshalKey(b, valToPointer(k), wire) + case 2: + b, err = unmarshalVal(b, valToPointer(v), wire) + default: + err = errInternalBadWireType // skip unknown tag + } + + if err == nil { + continue + } + if err != errInternalBadWireType { + return nil, err + } + + // Skip past unknown fields. + b, err = skipField(b, wire) + if err != nil { + return nil, err + } + } + + // Get map, allocate if needed. + m := f.asPointerTo(t).Elem() // an addressable map[K]T + if m.IsNil() { + m.Set(reflect.MakeMap(t)) + } + + // Insert into map. + m.SetMapIndex(k.Elem(), v.Elem()) + + return r, nil + } +} + +// makeUnmarshalOneof makes an unmarshaler for oneof fields. +// for: +// message Msg { +// oneof F { +// int64 X = 1; +// float64 Y = 2; +// } +// } +// typ is the type of the concrete entry for a oneof case (e.g. Msg_X). +// ityp is the interface type of the oneof field (e.g. isMsg_F). +// unmarshal is the unmarshaler for the base type of the oneof case (e.g. int64). +// Note that this function will be called once for each case in the oneof. +func makeUnmarshalOneof(typ, ityp reflect.Type, unmarshal unmarshaler) unmarshaler { + sf := typ.Field(0) + field0 := toField(&sf) + return func(b []byte, f pointer, w int) ([]byte, error) { + // Allocate holder for value. + v := reflect.New(typ) + + // Unmarshal data into holder. + // We unmarshal into the first field of the holder object. + var err error + b, err = unmarshal(b, valToPointer(v).offset(field0), w) + if err != nil { + return nil, err + } + + // Write pointer to holder into target field. + f.asPointerTo(ityp).Elem().Set(v) + + return b, nil + } +} + +// Error used by decode internally. +var errInternalBadWireType = errors.New("proto: internal error: bad wiretype") + +// skipField skips past a field of type wire and returns the remaining bytes. +func skipField(b []byte, wire int) ([]byte, error) { + switch wire { + case WireVarint: + _, k := decodeVarint(b) + if k == 0 { + return b, io.ErrUnexpectedEOF + } + b = b[k:] + case WireFixed32: + if len(b) < 4 { + return b, io.ErrUnexpectedEOF + } + b = b[4:] + case WireFixed64: + if len(b) < 8 { + return b, io.ErrUnexpectedEOF + } + b = b[8:] + case WireBytes: + m, k := decodeVarint(b) + if k == 0 || uint64(len(b)-k) < m { + return b, io.ErrUnexpectedEOF + } + b = b[uint64(k)+m:] + case WireStartGroup: + _, i := findEndGroup(b) + if i == -1 { + return b, io.ErrUnexpectedEOF + } + b = b[i:] + default: + return b, fmt.Errorf("proto: can't skip unknown wire type %d", wire) + } + return b, nil +} + +// findEndGroup finds the index of the next EndGroup tag. +// Groups may be nested, so the "next" EndGroup tag is the first +// unpaired EndGroup. +// findEndGroup returns the indexes of the start and end of the EndGroup tag. +// Returns (-1,-1) if it can't find one. +func findEndGroup(b []byte) (int, int) { + depth := 1 + i := 0 + for { + x, n := decodeVarint(b[i:]) + if n == 0 { + return -1, -1 + } + j := i + i += n + switch x & 7 { + case WireVarint: + _, k := decodeVarint(b[i:]) + if k == 0 { + return -1, -1 + } + i += k + case WireFixed32: + if len(b)-4 < i { + return -1, -1 + } + i += 4 + case WireFixed64: + if len(b)-8 < i { + return -1, -1 + } + i += 8 + case WireBytes: + m, k := decodeVarint(b[i:]) + if k == 0 { + return -1, -1 + } + i += k + if uint64(len(b)-i) < m { + return -1, -1 + } + i += int(m) + case WireStartGroup: + depth++ + case WireEndGroup: + depth-- + if depth == 0 { + return j, i + } + default: + return -1, -1 + } + } +} + +// encodeVarint appends a varint-encoded integer to b and returns the result. +func encodeVarint(b []byte, x uint64) []byte { + for x >= 1<<7 { + b = append(b, byte(x&0x7f|0x80)) + x >>= 7 + } + return append(b, byte(x)) +} + +// decodeVarint reads a varint-encoded integer from b. +// Returns the decoded integer and the number of bytes read. +// If there is an error, it returns 0,0. +func decodeVarint(b []byte) (uint64, int) { + var x, y uint64 + if len(b) <= 0 { + goto bad + } + x = uint64(b[0]) + if x < 0x80 { + return x, 1 + } + x -= 0x80 + + if len(b) <= 1 { + goto bad + } + y = uint64(b[1]) + x += y << 7 + if y < 0x80 { + return x, 2 + } + x -= 0x80 << 7 + + if len(b) <= 2 { + goto bad + } + y = uint64(b[2]) + x += y << 14 + if y < 0x80 { + return x, 3 + } + x -= 0x80 << 14 + + if len(b) <= 3 { + goto bad + } + y = uint64(b[3]) + x += y << 21 + if y < 0x80 { + return x, 4 + } + x -= 0x80 << 21 + + if len(b) <= 4 { + goto bad + } + y = uint64(b[4]) + x += y << 28 + if y < 0x80 { + return x, 5 + } + x -= 0x80 << 28 + + if len(b) <= 5 { + goto bad + } + y = uint64(b[5]) + x += y << 35 + if y < 0x80 { + return x, 6 + } + x -= 0x80 << 35 + + if len(b) <= 6 { + goto bad + } + y = uint64(b[6]) + x += y << 42 + if y < 0x80 { + return x, 7 + } + x -= 0x80 << 42 + + if len(b) <= 7 { + goto bad + } + y = uint64(b[7]) + x += y << 49 + if y < 0x80 { + return x, 8 + } + x -= 0x80 << 49 + + if len(b) <= 8 { + goto bad + } + y = uint64(b[8]) + x += y << 56 + if y < 0x80 { + return x, 9 + } + x -= 0x80 << 56 + + if len(b) <= 9 { + goto bad + } + y = uint64(b[9]) + x += y << 63 + if y < 2 { + return x, 10 + } + +bad: + return 0, 0 +} diff --git a/vendor/github.com/gogo/protobuf/proto/table_unmarshal_gogo.go b/vendor/github.com/gogo/protobuf/proto/table_unmarshal_gogo.go new file mode 100644 index 000000000..00d6c7ad9 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/proto/table_unmarshal_gogo.go @@ -0,0 +1,385 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2018, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +import ( + "io" + "reflect" +) + +func makeUnmarshalMessage(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + // First read the message field to see if something is there. + // The semantics of multiple submessages are weird. Instead of + // the last one winning (as it is for all other fields), multiple + // submessages are merged. + v := f // gogo: changed from v := f.getPointer() + if v.isNil() { + v = valToPointer(reflect.New(sub.typ)) + f.setPointer(v) + } + err := sub.unmarshal(v, b[:x]) + if err != nil { + if r, ok := err.(*RequiredNotSetError); ok { + r.field = name + "." + r.field + } else { + return nil, err + } + } + return b[x:], err + } +} + +func makeUnmarshalMessageSlice(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + v := valToPointer(reflect.New(sub.typ)) + err := sub.unmarshal(v, b[:x]) + if err != nil { + if r, ok := err.(*RequiredNotSetError); ok { + r.field = name + "." + r.field + } else { + return nil, err + } + } + f.appendRef(v, sub.typ) // gogo: changed from f.appendPointer(v) + return b[x:], err + } +} + +func makeUnmarshalCustomPtr(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + + s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem() + s.Set(reflect.New(sub.typ)) + m := s.Interface().(custom) + if err := m.Unmarshal(b[:x]); err != nil { + return nil, err + } + return b[x:], nil + } +} + +func makeUnmarshalCustomSlice(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := reflect.New(sub.typ) + c := m.Interface().(custom) + if err := c.Unmarshal(b[:x]); err != nil { + return nil, err + } + v := valToPointer(m) + f.appendRef(v, sub.typ) + return b[x:], nil + } +} + +func makeUnmarshalCustom(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + + m := f.asPointerTo(sub.typ).Interface().(custom) + if err := m.Unmarshal(b[:x]); err != nil { + return nil, err + } + return b[x:], nil + } +} + +func makeUnmarshalTime(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := ×tamp{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + t, err := timestampFromProto(m) + if err != nil { + return nil, err + } + s := f.asPointerTo(sub.typ).Elem() + s.Set(reflect.ValueOf(t)) + return b[x:], nil + } +} + +func makeUnmarshalTimePtr(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := ×tamp{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + t, err := timestampFromProto(m) + if err != nil { + return nil, err + } + s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem() + s.Set(reflect.ValueOf(&t)) + return b[x:], nil + } +} + +func makeUnmarshalTimePtrSlice(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := ×tamp{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + t, err := timestampFromProto(m) + if err != nil { + return nil, err + } + slice := f.getSlice(reflect.PtrTo(sub.typ)) + newSlice := reflect.Append(slice, reflect.ValueOf(&t)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeUnmarshalTimeSlice(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := ×tamp{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + t, err := timestampFromProto(m) + if err != nil { + return nil, err + } + slice := f.getSlice(sub.typ) + newSlice := reflect.Append(slice, reflect.ValueOf(t)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeUnmarshalDurationPtr(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &duration{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + d, err := durationFromProto(m) + if err != nil { + return nil, err + } + s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem() + s.Set(reflect.ValueOf(&d)) + return b[x:], nil + } +} + +func makeUnmarshalDuration(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &duration{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + d, err := durationFromProto(m) + if err != nil { + return nil, err + } + s := f.asPointerTo(sub.typ).Elem() + s.Set(reflect.ValueOf(d)) + return b[x:], nil + } +} + +func makeUnmarshalDurationPtrSlice(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &duration{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + d, err := durationFromProto(m) + if err != nil { + return nil, err + } + slice := f.getSlice(reflect.PtrTo(sub.typ)) + newSlice := reflect.Append(slice, reflect.ValueOf(&d)) + slice.Set(newSlice) + return b[x:], nil + } +} + +func makeUnmarshalDurationSlice(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return nil, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + m := &duration{} + if err := Unmarshal(b[:x], m); err != nil { + return nil, err + } + d, err := durationFromProto(m) + if err != nil { + return nil, err + } + slice := f.getSlice(sub.typ) + newSlice := reflect.Append(slice, reflect.ValueOf(d)) + slice.Set(newSlice) + return b[x:], nil + } +} diff --git a/vendor/github.com/gogo/protobuf/proto/text.go b/vendor/github.com/gogo/protobuf/proto/text.go index f609d1d45..4f5706dc5 100644 --- a/vendor/github.com/gogo/protobuf/proto/text.go +++ b/vendor/github.com/gogo/protobuf/proto/text.go @@ -57,7 +57,6 @@ import ( var ( newline = []byte("\n") spaces = []byte(" ") - gtNewline = []byte(">\n") endBraceNewline = []byte("}\n") backslashN = []byte{'\\', 'n'} backslashR = []byte{'\\', 'r'} @@ -177,11 +176,6 @@ func writeName(w *textWriter, props *Properties) error { return nil } -// raw is the interface satisfied by RawMessage. -type raw interface { - Bytes() []byte -} - func requiresQuotes(u string) bool { // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted. for _, ch := range u { @@ -276,6 +270,10 @@ func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error { props := sprops.Prop[i] name := st.Field(i).Name + if name == "XXX_NoUnkeyedLiteral" { + continue + } + if strings.HasPrefix(name, "XXX_") { // There are two XXX_ fields: // XXX_unrecognized []byte @@ -447,12 +445,6 @@ func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error { return err } } - if b, ok := fv.Interface().(raw); ok { - if err := writeRaw(w, b.Bytes()); err != nil { - return err - } - continue - } if len(props.Enum) > 0 { if err := tm.writeEnum(w, fv, props); err != nil { @@ -475,7 +467,7 @@ func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error { pv = reflect.New(sv.Type()) pv.Elem().Set(sv) } - if pv.Type().Implements(extensionRangeType) { + if _, err := extendable(pv.Interface()); err == nil { if err := tm.writeExtensions(w, pv); err != nil { return err } @@ -484,27 +476,6 @@ func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error { return nil } -// writeRaw writes an uninterpreted raw message. -func writeRaw(w *textWriter, b []byte) error { - if err := w.WriteByte('<'); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - if err := writeUnknownStruct(w, b); err != nil { - return err - } - w.unindent() - if err := w.WriteByte('>'); err != nil { - return err - } - return nil -} - // writeAny writes an arbitrary field. func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error { v = reflect.Indirect(v) @@ -605,6 +576,19 @@ func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Propert } } w.indent() + if v.CanAddr() { + // Calling v.Interface on a struct causes the reflect package to + // copy the entire struct. This is racy with the new Marshaler + // since we atomically update the XXX_sizecache. + // + // Thus, we retrieve a pointer to the struct if possible to avoid + // a race since v.Interface on the pointer doesn't copy the struct. + // + // If v is not addressable, then we are not worried about a race + // since it implies that the binary Marshaler cannot possibly be + // mutating this value. + v = v.Addr() + } if etm, ok := v.Interface().(encoding.TextMarshaler); ok { text, err := etm.MarshalText() if err != nil { @@ -613,8 +597,13 @@ func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Propert if _, err = w.Write(text); err != nil { return err } - } else if err := tm.writeStruct(w, v); err != nil { - return err + } else { + if v.Kind() == reflect.Ptr { + v = v.Elem() + } + if err := tm.writeStruct(w, v); err != nil { + return err + } } w.unindent() if err := w.WriteByte(ket); err != nil { diff --git a/vendor/github.com/gogo/protobuf/proto/text_parser.go b/vendor/github.com/gogo/protobuf/proto/text_parser.go index f1276729a..fbb000d37 100644 --- a/vendor/github.com/gogo/protobuf/proto/text_parser.go +++ b/vendor/github.com/gogo/protobuf/proto/text_parser.go @@ -212,7 +212,6 @@ func (p *textParser) advance() { var ( errBadUTF8 = errors.New("proto: bad UTF-8") - errBadHex = errors.New("proto: bad hexadecimal") ) func unquoteC(s string, quote rune) (string, error) { @@ -283,60 +282,47 @@ func unescape(s string) (ch string, tail string, err error) { return "?", s, nil // trigraph workaround case '\'', '"', '\\': return string(r), s, nil - case '0', '1', '2', '3', '4', '5', '6', '7', 'x', 'X': + case '0', '1', '2', '3', '4', '5', '6', '7': if len(s) < 2 { return "", "", fmt.Errorf(`\%c requires 2 following digits`, r) } - base := 8 - ss := s[:2] + ss := string(r) + s[:2] s = s[2:] - if r == 'x' || r == 'X' { - base = 16 - } else { - ss = string(r) + ss - } - i, err := strconv.ParseUint(ss, base, 8) + i, err := strconv.ParseUint(ss, 8, 8) if err != nil { - return "", "", err + return "", "", fmt.Errorf(`\%s contains non-octal digits`, ss) } return string([]byte{byte(i)}), s, nil - case 'u', 'U': - n := 4 - if r == 'U' { + case 'x', 'X', 'u', 'U': + var n int + switch r { + case 'x', 'X': + n = 2 + case 'u': + n = 4 + case 'U': n = 8 } if len(s) < n { - return "", "", fmt.Errorf(`\%c requires %d digits`, r, n) - } - - bs := make([]byte, n/2) - for i := 0; i < n; i += 2 { - a, ok1 := unhex(s[i]) - b, ok2 := unhex(s[i+1]) - if !ok1 || !ok2 { - return "", "", errBadHex - } - bs[i/2] = a<<4 | b + return "", "", fmt.Errorf(`\%c requires %d following digits`, r, n) } + ss := s[:n] s = s[n:] - return string(bs), s, nil + i, err := strconv.ParseUint(ss, 16, 64) + if err != nil { + return "", "", fmt.Errorf(`\%c%s contains non-hexadecimal digits`, r, ss) + } + if r == 'x' || r == 'X' { + return string([]byte{byte(i)}), s, nil + } + if i > utf8.MaxRune { + return "", "", fmt.Errorf(`\%c%s is not a valid Unicode code point`, r, ss) + } + return string(i), s, nil } return "", "", fmt.Errorf(`unknown escape \%c`, r) } -// Adapted from src/pkg/strconv/quote.go. -func unhex(b byte) (v byte, ok bool) { - switch { - case '0' <= b && b <= '9': - return b - '0', true - case 'a' <= b && b <= 'f': - return b - 'a' + 10, true - case 'A' <= b && b <= 'F': - return b - 'A' + 10, true - } - return 0, false -} - // Back off the parser by one token. Can only be done between calls to next(). // It makes the next advance() a no-op. func (p *textParser) back() { p.backed = true } @@ -734,6 +720,9 @@ func (p *textParser) consumeExtName() (string, error) { if tok.err != nil { return "", p.errorf("unrecognized type_url or extension name: %s", tok.err) } + if p.done && tok.value != "]" { + return "", p.errorf("unclosed type_url or extension name") + } } return strings.Join(parts, ""), nil } @@ -983,7 +972,7 @@ func (p *textParser) readAny(v reflect.Value, props *Properties) error { return p.readStruct(fv, terminator) case reflect.Uint32: if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { - fv.SetUint(x) + fv.SetUint(uint64(x)) return nil } case reflect.Uint64: @@ -1001,13 +990,9 @@ func (p *textParser) readAny(v reflect.Value, props *Properties) error { // UnmarshalText returns *RequiredNotSetError. func UnmarshalText(s string, pb Message) error { if um, ok := pb.(encoding.TextUnmarshaler); ok { - err := um.UnmarshalText([]byte(s)) - return err + return um.UnmarshalText([]byte(s)) } pb.Reset() v := reflect.ValueOf(pb) - if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil { - return pe - } - return nil + return newTextParser(s).readStruct(v.Elem(), "") } diff --git a/vendor/github.com/gogo/protobuf/proto/timestamp_gogo.go b/vendor/github.com/gogo/protobuf/proto/timestamp_gogo.go index d42764743..38439fa99 100644 --- a/vendor/github.com/gogo/protobuf/proto/timestamp_gogo.go +++ b/vendor/github.com/gogo/protobuf/proto/timestamp_gogo.go @@ -47,183 +47,3 @@ func (*timestamp) String() string { return "timestamp" } func init() { RegisterType((*timestamp)(nil), "gogo.protobuf.proto.timestamp") } - -func (o *Buffer) decTimestamp() (time.Time, error) { - b, err := o.DecodeRawBytes(true) - if err != nil { - return time.Time{}, err - } - tproto := ×tamp{} - if err := Unmarshal(b, tproto); err != nil { - return time.Time{}, err - } - return timestampFromProto(tproto) -} - -func (o *Buffer) dec_time(p *Properties, base structPointer) error { - t, err := o.decTimestamp() - if err != nil { - return err - } - setPtrCustomType(base, p.field, &t) - return nil -} - -func (o *Buffer) dec_ref_time(p *Properties, base structPointer) error { - t, err := o.decTimestamp() - if err != nil { - return err - } - setCustomType(base, p.field, &t) - return nil -} - -func (o *Buffer) dec_slice_time(p *Properties, base structPointer) error { - t, err := o.decTimestamp() - if err != nil { - return err - } - newBas := appendStructPointer(base, p.field, reflect.SliceOf(reflect.PtrTo(timeType))) - var zero field - setPtrCustomType(newBas, zero, &t) - return nil -} - -func (o *Buffer) dec_slice_ref_time(p *Properties, base structPointer) error { - t, err := o.decTimestamp() - if err != nil { - return err - } - newBas := appendStructPointer(base, p.field, reflect.SliceOf(timeType)) - var zero field - setCustomType(newBas, zero, &t) - return nil -} - -func size_time(p *Properties, base structPointer) (n int) { - structp := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(structp) { - return 0 - } - tim := structPointer_Interface(structp, timeType).(*time.Time) - t, err := timestampProto(*tim) - if err != nil { - return 0 - } - size := Size(t) - return size + sizeVarint(uint64(size)) + len(p.tagcode) -} - -func (o *Buffer) enc_time(p *Properties, base structPointer) error { - structp := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(structp) { - return ErrNil - } - tim := structPointer_Interface(structp, timeType).(*time.Time) - t, err := timestampProto(*tim) - if err != nil { - return err - } - data, err := Marshal(t) - if err != nil { - return err - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - return nil -} - -func size_ref_time(p *Properties, base structPointer) (n int) { - tim := structPointer_InterfaceAt(base, p.field, timeType).(*time.Time) - t, err := timestampProto(*tim) - if err != nil { - return 0 - } - size := Size(t) - return size + sizeVarint(uint64(size)) + len(p.tagcode) -} - -func (o *Buffer) enc_ref_time(p *Properties, base structPointer) error { - tim := structPointer_InterfaceAt(base, p.field, timeType).(*time.Time) - t, err := timestampProto(*tim) - if err != nil { - return err - } - data, err := Marshal(t) - if err != nil { - return err - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - return nil -} - -func size_slice_time(p *Properties, base structPointer) (n int) { - ptims := structPointer_InterfaceAt(base, p.field, reflect.SliceOf(reflect.PtrTo(timeType))).(*[]*time.Time) - tims := *ptims - for i := 0; i < len(tims); i++ { - if tims[i] == nil { - return 0 - } - tproto, err := timestampProto(*tims[i]) - if err != nil { - return 0 - } - size := Size(tproto) - n += len(p.tagcode) + size + sizeVarint(uint64(size)) - } - return n -} - -func (o *Buffer) enc_slice_time(p *Properties, base structPointer) error { - ptims := structPointer_InterfaceAt(base, p.field, reflect.SliceOf(reflect.PtrTo(timeType))).(*[]*time.Time) - tims := *ptims - for i := 0; i < len(tims); i++ { - if tims[i] == nil { - return errRepeatedHasNil - } - tproto, err := timestampProto(*tims[i]) - if err != nil { - return err - } - data, err := Marshal(tproto) - if err != nil { - return err - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - } - return nil -} - -func size_slice_ref_time(p *Properties, base structPointer) (n int) { - ptims := structPointer_InterfaceAt(base, p.field, reflect.SliceOf(timeType)).(*[]time.Time) - tims := *ptims - for i := 0; i < len(tims); i++ { - tproto, err := timestampProto(tims[i]) - if err != nil { - return 0 - } - size := Size(tproto) - n += len(p.tagcode) + size + sizeVarint(uint64(size)) - } - return n -} - -func (o *Buffer) enc_slice_ref_time(p *Properties, base structPointer) error { - ptims := structPointer_InterfaceAt(base, p.field, reflect.SliceOf(timeType)).(*[]time.Time) - tims := *ptims - for i := 0; i < len(tims); i++ { - tproto, err := timestampProto(tims[i]) - if err != nil { - return err - } - data, err := Marshal(tproto) - if err != nil { - return err - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - } - return nil -} diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/Makefile b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/Makefile new file mode 100644 index 000000000..3496dc99d --- /dev/null +++ b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/Makefile @@ -0,0 +1,36 @@ +# Go support for Protocol Buffers - Google's data interchange format +# +# Copyright 2010 The Go Authors. All rights reserved. +# https://github.com/golang/protobuf +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +regenerate: + go install github.com/gogo/protobuf/protoc-gen-gogo + go install github.com/gogo/protobuf/protoc-gen-gostring + protoc --gogo_out=. -I=../../protobuf/google/protobuf ../../protobuf/google/protobuf/descriptor.proto + protoc --gostring_out=. -I=../../protobuf/google/protobuf ../../protobuf/google/protobuf/descriptor.proto diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.pb.go b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.pb.go index 4174cbd9f..44f893b77 100644 --- a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.pb.go +++ b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.pb.go @@ -1,35 +1,6 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: descriptor.proto -/* -Package descriptor is a generated protocol buffer package. - -It is generated from these files: - descriptor.proto - -It has these top-level messages: - FileDescriptorSet - FileDescriptorProto - DescriptorProto - ExtensionRangeOptions - FieldDescriptorProto - OneofDescriptorProto - EnumDescriptorProto - EnumValueDescriptorProto - ServiceDescriptorProto - MethodDescriptorProto - FileOptions - MessageOptions - FieldOptions - OneofOptions - EnumOptions - EnumValueOptions - ServiceOptions - MethodOptions - UninterpretedOption - SourceCodeInfo - GeneratedCodeInfo -*/ package descriptor import proto "github.com/gogo/protobuf/proto" @@ -139,7 +110,7 @@ func (x *FieldDescriptorProto_Type) UnmarshalJSON(data []byte) error { return nil } func (FieldDescriptorProto_Type) EnumDescriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{4, 0} + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{4, 0} } type FieldDescriptorProto_Label int32 @@ -179,7 +150,7 @@ func (x *FieldDescriptorProto_Label) UnmarshalJSON(data []byte) error { return nil } func (FieldDescriptorProto_Label) EnumDescriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{4, 1} + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{4, 1} } // Generated classes can be optimized for speed or code size. @@ -220,7 +191,7 @@ func (x *FileOptions_OptimizeMode) UnmarshalJSON(data []byte) error { return nil } func (FileOptions_OptimizeMode) EnumDescriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{10, 0} + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{10, 0} } type FieldOptions_CType int32 @@ -260,7 +231,7 @@ func (x *FieldOptions_CType) UnmarshalJSON(data []byte) error { return nil } func (FieldOptions_CType) EnumDescriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{12, 0} + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{12, 0} } type FieldOptions_JSType int32 @@ -302,7 +273,7 @@ func (x *FieldOptions_JSType) UnmarshalJSON(data []byte) error { return nil } func (FieldOptions_JSType) EnumDescriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{12, 1} + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{12, 1} } // Is this method side-effect-free (or safe in HTTP parlance), or idempotent, @@ -344,20 +315,41 @@ func (x *MethodOptions_IdempotencyLevel) UnmarshalJSON(data []byte) error { return nil } func (MethodOptions_IdempotencyLevel) EnumDescriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{17, 0} + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{17, 0} } // The protocol compiler can output a FileDescriptorSet containing the .proto // files it parses. type FileDescriptorSet struct { - File []*FileDescriptorProto `protobuf:"bytes,1,rep,name=file" json:"file,omitempty"` - XXX_unrecognized []byte `json:"-"` + File []*FileDescriptorProto `protobuf:"bytes,1,rep,name=file" json:"file,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *FileDescriptorSet) Reset() { *m = FileDescriptorSet{} } -func (m *FileDescriptorSet) String() string { return proto.CompactTextString(m) } -func (*FileDescriptorSet) ProtoMessage() {} -func (*FileDescriptorSet) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{0} } +func (m *FileDescriptorSet) Reset() { *m = FileDescriptorSet{} } +func (m *FileDescriptorSet) String() string { return proto.CompactTextString(m) } +func (*FileDescriptorSet) ProtoMessage() {} +func (*FileDescriptorSet) Descriptor() ([]byte, []int) { + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{0} +} +func (m *FileDescriptorSet) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_FileDescriptorSet.Unmarshal(m, b) +} +func (m *FileDescriptorSet) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_FileDescriptorSet.Marshal(b, m, deterministic) +} +func (dst *FileDescriptorSet) XXX_Merge(src proto.Message) { + xxx_messageInfo_FileDescriptorSet.Merge(dst, src) +} +func (m *FileDescriptorSet) XXX_Size() int { + return xxx_messageInfo_FileDescriptorSet.Size(m) +} +func (m *FileDescriptorSet) XXX_DiscardUnknown() { + xxx_messageInfo_FileDescriptorSet.DiscardUnknown(m) +} + +var xxx_messageInfo_FileDescriptorSet proto.InternalMessageInfo func (m *FileDescriptorSet) GetFile() []*FileDescriptorProto { if m != nil { @@ -390,14 +382,35 @@ type FileDescriptorProto struct { SourceCodeInfo *SourceCodeInfo `protobuf:"bytes,9,opt,name=source_code_info,json=sourceCodeInfo" json:"source_code_info,omitempty"` // The syntax of the proto file. // The supported values are "proto2" and "proto3". - Syntax *string `protobuf:"bytes,12,opt,name=syntax" json:"syntax,omitempty"` - XXX_unrecognized []byte `json:"-"` + Syntax *string `protobuf:"bytes,12,opt,name=syntax" json:"syntax,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *FileDescriptorProto) Reset() { *m = FileDescriptorProto{} } -func (m *FileDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*FileDescriptorProto) ProtoMessage() {} -func (*FileDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{1} } +func (m *FileDescriptorProto) Reset() { *m = FileDescriptorProto{} } +func (m *FileDescriptorProto) String() string { return proto.CompactTextString(m) } +func (*FileDescriptorProto) ProtoMessage() {} +func (*FileDescriptorProto) Descriptor() ([]byte, []int) { + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{1} +} +func (m *FileDescriptorProto) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_FileDescriptorProto.Unmarshal(m, b) +} +func (m *FileDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_FileDescriptorProto.Marshal(b, m, deterministic) +} +func (dst *FileDescriptorProto) XXX_Merge(src proto.Message) { + xxx_messageInfo_FileDescriptorProto.Merge(dst, src) +} +func (m *FileDescriptorProto) XXX_Size() int { + return xxx_messageInfo_FileDescriptorProto.Size(m) +} +func (m *FileDescriptorProto) XXX_DiscardUnknown() { + xxx_messageInfo_FileDescriptorProto.DiscardUnknown(m) +} + +var xxx_messageInfo_FileDescriptorProto proto.InternalMessageInfo func (m *FileDescriptorProto) GetName() string { if m != nil && m.Name != nil { @@ -496,14 +509,35 @@ type DescriptorProto struct { ReservedRange []*DescriptorProto_ReservedRange `protobuf:"bytes,9,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"` // Reserved field names, which may not be used by fields in the same message. // A given name may only be reserved once. - ReservedName []string `protobuf:"bytes,10,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"` - XXX_unrecognized []byte `json:"-"` + ReservedName []string `protobuf:"bytes,10,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *DescriptorProto) Reset() { *m = DescriptorProto{} } -func (m *DescriptorProto) String() string { return proto.CompactTextString(m) } -func (*DescriptorProto) ProtoMessage() {} -func (*DescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{2} } +func (m *DescriptorProto) Reset() { *m = DescriptorProto{} } +func (m *DescriptorProto) String() string { return proto.CompactTextString(m) } +func (*DescriptorProto) ProtoMessage() {} +func (*DescriptorProto) Descriptor() ([]byte, []int) { + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{2} +} +func (m *DescriptorProto) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_DescriptorProto.Unmarshal(m, b) +} +func (m *DescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_DescriptorProto.Marshal(b, m, deterministic) +} +func (dst *DescriptorProto) XXX_Merge(src proto.Message) { + xxx_messageInfo_DescriptorProto.Merge(dst, src) +} +func (m *DescriptorProto) XXX_Size() int { + return xxx_messageInfo_DescriptorProto.Size(m) +} +func (m *DescriptorProto) XXX_DiscardUnknown() { + xxx_messageInfo_DescriptorProto.DiscardUnknown(m) +} + +var xxx_messageInfo_DescriptorProto proto.InternalMessageInfo func (m *DescriptorProto) GetName() string { if m != nil && m.Name != nil { @@ -576,19 +610,38 @@ func (m *DescriptorProto) GetReservedName() []string { } type DescriptorProto_ExtensionRange struct { - Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` - End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` - Options *ExtensionRangeOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_unrecognized []byte `json:"-"` + Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` + End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` + Options *ExtensionRangeOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *DescriptorProto_ExtensionRange) Reset() { *m = DescriptorProto_ExtensionRange{} } func (m *DescriptorProto_ExtensionRange) String() string { return proto.CompactTextString(m) } func (*DescriptorProto_ExtensionRange) ProtoMessage() {} func (*DescriptorProto_ExtensionRange) Descriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{2, 0} + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{2, 0} +} +func (m *DescriptorProto_ExtensionRange) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_DescriptorProto_ExtensionRange.Unmarshal(m, b) +} +func (m *DescriptorProto_ExtensionRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_DescriptorProto_ExtensionRange.Marshal(b, m, deterministic) +} +func (dst *DescriptorProto_ExtensionRange) XXX_Merge(src proto.Message) { + xxx_messageInfo_DescriptorProto_ExtensionRange.Merge(dst, src) +} +func (m *DescriptorProto_ExtensionRange) XXX_Size() int { + return xxx_messageInfo_DescriptorProto_ExtensionRange.Size(m) +} +func (m *DescriptorProto_ExtensionRange) XXX_DiscardUnknown() { + xxx_messageInfo_DescriptorProto_ExtensionRange.DiscardUnknown(m) } +var xxx_messageInfo_DescriptorProto_ExtensionRange proto.InternalMessageInfo + func (m *DescriptorProto_ExtensionRange) GetStart() int32 { if m != nil && m.Start != nil { return *m.Start @@ -614,18 +667,37 @@ func (m *DescriptorProto_ExtensionRange) GetOptions() *ExtensionRangeOptions { // fields or extension ranges in the same message. Reserved ranges may // not overlap. type DescriptorProto_ReservedRange struct { - Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` - End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` - XXX_unrecognized []byte `json:"-"` + Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` + End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *DescriptorProto_ReservedRange) Reset() { *m = DescriptorProto_ReservedRange{} } func (m *DescriptorProto_ReservedRange) String() string { return proto.CompactTextString(m) } func (*DescriptorProto_ReservedRange) ProtoMessage() {} func (*DescriptorProto_ReservedRange) Descriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{2, 1} + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{2, 1} +} +func (m *DescriptorProto_ReservedRange) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_DescriptorProto_ReservedRange.Unmarshal(m, b) +} +func (m *DescriptorProto_ReservedRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_DescriptorProto_ReservedRange.Marshal(b, m, deterministic) +} +func (dst *DescriptorProto_ReservedRange) XXX_Merge(src proto.Message) { + xxx_messageInfo_DescriptorProto_ReservedRange.Merge(dst, src) +} +func (m *DescriptorProto_ReservedRange) XXX_Size() int { + return xxx_messageInfo_DescriptorProto_ReservedRange.Size(m) +} +func (m *DescriptorProto_ReservedRange) XXX_DiscardUnknown() { + xxx_messageInfo_DescriptorProto_ReservedRange.DiscardUnknown(m) } +var xxx_messageInfo_DescriptorProto_ReservedRange proto.InternalMessageInfo + func (m *DescriptorProto_ReservedRange) GetStart() int32 { if m != nil && m.Start != nil { return *m.Start @@ -643,14 +715,18 @@ func (m *DescriptorProto_ReservedRange) GetEnd() int32 { type ExtensionRangeOptions struct { // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *ExtensionRangeOptions) Reset() { *m = ExtensionRangeOptions{} } -func (m *ExtensionRangeOptions) String() string { return proto.CompactTextString(m) } -func (*ExtensionRangeOptions) ProtoMessage() {} -func (*ExtensionRangeOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{3} } +func (m *ExtensionRangeOptions) Reset() { *m = ExtensionRangeOptions{} } +func (m *ExtensionRangeOptions) String() string { return proto.CompactTextString(m) } +func (*ExtensionRangeOptions) ProtoMessage() {} +func (*ExtensionRangeOptions) Descriptor() ([]byte, []int) { + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{3} +} var extRange_ExtensionRangeOptions = []proto.ExtensionRange{ {Start: 1000, End: 536870911}, @@ -659,6 +735,23 @@ var extRange_ExtensionRangeOptions = []proto.ExtensionRange{ func (*ExtensionRangeOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_ExtensionRangeOptions } +func (m *ExtensionRangeOptions) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ExtensionRangeOptions.Unmarshal(m, b) +} +func (m *ExtensionRangeOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ExtensionRangeOptions.Marshal(b, m, deterministic) +} +func (dst *ExtensionRangeOptions) XXX_Merge(src proto.Message) { + xxx_messageInfo_ExtensionRangeOptions.Merge(dst, src) +} +func (m *ExtensionRangeOptions) XXX_Size() int { + return xxx_messageInfo_ExtensionRangeOptions.Size(m) +} +func (m *ExtensionRangeOptions) XXX_DiscardUnknown() { + xxx_messageInfo_ExtensionRangeOptions.DiscardUnknown(m) +} + +var xxx_messageInfo_ExtensionRangeOptions proto.InternalMessageInfo func (m *ExtensionRangeOptions) GetUninterpretedOption() []*UninterpretedOption { if m != nil { @@ -697,15 +790,36 @@ type FieldDescriptorProto struct { // user has set a "json_name" option on this field, that option's value // will be used. Otherwise, it's deduced from the field's name by converting // it to camelCase. - JsonName *string `protobuf:"bytes,10,opt,name=json_name,json=jsonName" json:"json_name,omitempty"` - Options *FieldOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"` - XXX_unrecognized []byte `json:"-"` + JsonName *string `protobuf:"bytes,10,opt,name=json_name,json=jsonName" json:"json_name,omitempty"` + Options *FieldOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *FieldDescriptorProto) Reset() { *m = FieldDescriptorProto{} } +func (m *FieldDescriptorProto) String() string { return proto.CompactTextString(m) } +func (*FieldDescriptorProto) ProtoMessage() {} +func (*FieldDescriptorProto) Descriptor() ([]byte, []int) { + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{4} +} +func (m *FieldDescriptorProto) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_FieldDescriptorProto.Unmarshal(m, b) +} +func (m *FieldDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_FieldDescriptorProto.Marshal(b, m, deterministic) +} +func (dst *FieldDescriptorProto) XXX_Merge(src proto.Message) { + xxx_messageInfo_FieldDescriptorProto.Merge(dst, src) +} +func (m *FieldDescriptorProto) XXX_Size() int { + return xxx_messageInfo_FieldDescriptorProto.Size(m) +} +func (m *FieldDescriptorProto) XXX_DiscardUnknown() { + xxx_messageInfo_FieldDescriptorProto.DiscardUnknown(m) } -func (m *FieldDescriptorProto) Reset() { *m = FieldDescriptorProto{} } -func (m *FieldDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*FieldDescriptorProto) ProtoMessage() {} -func (*FieldDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{4} } +var xxx_messageInfo_FieldDescriptorProto proto.InternalMessageInfo func (m *FieldDescriptorProto) GetName() string { if m != nil && m.Name != nil { @@ -779,15 +893,36 @@ func (m *FieldDescriptorProto) GetOptions() *FieldOptions { // Describes a oneof. type OneofDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Options *OneofOptions `protobuf:"bytes,2,opt,name=options" json:"options,omitempty"` - XXX_unrecognized []byte `json:"-"` + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Options *OneofOptions `protobuf:"bytes,2,opt,name=options" json:"options,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *OneofDescriptorProto) Reset() { *m = OneofDescriptorProto{} } +func (m *OneofDescriptorProto) String() string { return proto.CompactTextString(m) } +func (*OneofDescriptorProto) ProtoMessage() {} +func (*OneofDescriptorProto) Descriptor() ([]byte, []int) { + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{5} +} +func (m *OneofDescriptorProto) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_OneofDescriptorProto.Unmarshal(m, b) +} +func (m *OneofDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_OneofDescriptorProto.Marshal(b, m, deterministic) +} +func (dst *OneofDescriptorProto) XXX_Merge(src proto.Message) { + xxx_messageInfo_OneofDescriptorProto.Merge(dst, src) +} +func (m *OneofDescriptorProto) XXX_Size() int { + return xxx_messageInfo_OneofDescriptorProto.Size(m) +} +func (m *OneofDescriptorProto) XXX_DiscardUnknown() { + xxx_messageInfo_OneofDescriptorProto.DiscardUnknown(m) } -func (m *OneofDescriptorProto) Reset() { *m = OneofDescriptorProto{} } -func (m *OneofDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*OneofDescriptorProto) ProtoMessage() {} -func (*OneofDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{5} } +var xxx_messageInfo_OneofDescriptorProto proto.InternalMessageInfo func (m *OneofDescriptorProto) GetName() string { if m != nil && m.Name != nil { @@ -814,14 +949,35 @@ type EnumDescriptorProto struct { ReservedRange []*EnumDescriptorProto_EnumReservedRange `protobuf:"bytes,4,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"` // Reserved enum value names, which may not be reused. A given name may only // be reserved once. - ReservedName []string `protobuf:"bytes,5,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"` - XXX_unrecognized []byte `json:"-"` + ReservedName []string `protobuf:"bytes,5,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *EnumDescriptorProto) Reset() { *m = EnumDescriptorProto{} } -func (m *EnumDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*EnumDescriptorProto) ProtoMessage() {} -func (*EnumDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{6} } +func (m *EnumDescriptorProto) Reset() { *m = EnumDescriptorProto{} } +func (m *EnumDescriptorProto) String() string { return proto.CompactTextString(m) } +func (*EnumDescriptorProto) ProtoMessage() {} +func (*EnumDescriptorProto) Descriptor() ([]byte, []int) { + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{6} +} +func (m *EnumDescriptorProto) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_EnumDescriptorProto.Unmarshal(m, b) +} +func (m *EnumDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_EnumDescriptorProto.Marshal(b, m, deterministic) +} +func (dst *EnumDescriptorProto) XXX_Merge(src proto.Message) { + xxx_messageInfo_EnumDescriptorProto.Merge(dst, src) +} +func (m *EnumDescriptorProto) XXX_Size() int { + return xxx_messageInfo_EnumDescriptorProto.Size(m) +} +func (m *EnumDescriptorProto) XXX_DiscardUnknown() { + xxx_messageInfo_EnumDescriptorProto.DiscardUnknown(m) +} + +var xxx_messageInfo_EnumDescriptorProto proto.InternalMessageInfo func (m *EnumDescriptorProto) GetName() string { if m != nil && m.Name != nil { @@ -865,17 +1021,36 @@ func (m *EnumDescriptorProto) GetReservedName() []string { // is inclusive such that it can appropriately represent the entire int32 // domain. type EnumDescriptorProto_EnumReservedRange struct { - Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` - End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` - XXX_unrecognized []byte `json:"-"` + Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` + End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *EnumDescriptorProto_EnumReservedRange) Reset() { *m = EnumDescriptorProto_EnumReservedRange{} } func (m *EnumDescriptorProto_EnumReservedRange) String() string { return proto.CompactTextString(m) } func (*EnumDescriptorProto_EnumReservedRange) ProtoMessage() {} func (*EnumDescriptorProto_EnumReservedRange) Descriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{6, 0} + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{6, 0} +} +func (m *EnumDescriptorProto_EnumReservedRange) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Unmarshal(m, b) +} +func (m *EnumDescriptorProto_EnumReservedRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Marshal(b, m, deterministic) +} +func (dst *EnumDescriptorProto_EnumReservedRange) XXX_Merge(src proto.Message) { + xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Merge(dst, src) } +func (m *EnumDescriptorProto_EnumReservedRange) XXX_Size() int { + return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Size(m) +} +func (m *EnumDescriptorProto_EnumReservedRange) XXX_DiscardUnknown() { + xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.DiscardUnknown(m) +} + +var xxx_messageInfo_EnumDescriptorProto_EnumReservedRange proto.InternalMessageInfo func (m *EnumDescriptorProto_EnumReservedRange) GetStart() int32 { if m != nil && m.Start != nil { @@ -893,19 +1068,38 @@ func (m *EnumDescriptorProto_EnumReservedRange) GetEnd() int32 { // Describes a value within an enum. type EnumValueDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Number *int32 `protobuf:"varint,2,opt,name=number" json:"number,omitempty"` - Options *EnumValueOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_unrecognized []byte `json:"-"` + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Number *int32 `protobuf:"varint,2,opt,name=number" json:"number,omitempty"` + Options *EnumValueOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *EnumValueDescriptorProto) Reset() { *m = EnumValueDescriptorProto{} } func (m *EnumValueDescriptorProto) String() string { return proto.CompactTextString(m) } func (*EnumValueDescriptorProto) ProtoMessage() {} func (*EnumValueDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{7} + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{7} +} +func (m *EnumValueDescriptorProto) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_EnumValueDescriptorProto.Unmarshal(m, b) +} +func (m *EnumValueDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_EnumValueDescriptorProto.Marshal(b, m, deterministic) +} +func (dst *EnumValueDescriptorProto) XXX_Merge(src proto.Message) { + xxx_messageInfo_EnumValueDescriptorProto.Merge(dst, src) +} +func (m *EnumValueDescriptorProto) XXX_Size() int { + return xxx_messageInfo_EnumValueDescriptorProto.Size(m) +} +func (m *EnumValueDescriptorProto) XXX_DiscardUnknown() { + xxx_messageInfo_EnumValueDescriptorProto.DiscardUnknown(m) } +var xxx_messageInfo_EnumValueDescriptorProto proto.InternalMessageInfo + func (m *EnumValueDescriptorProto) GetName() string { if m != nil && m.Name != nil { return *m.Name @@ -929,16 +1123,37 @@ func (m *EnumValueDescriptorProto) GetOptions() *EnumValueOptions { // Describes a service. type ServiceDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Method []*MethodDescriptorProto `protobuf:"bytes,2,rep,name=method" json:"method,omitempty"` - Options *ServiceOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_unrecognized []byte `json:"-"` + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Method []*MethodDescriptorProto `protobuf:"bytes,2,rep,name=method" json:"method,omitempty"` + Options *ServiceOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *ServiceDescriptorProto) Reset() { *m = ServiceDescriptorProto{} } +func (m *ServiceDescriptorProto) String() string { return proto.CompactTextString(m) } +func (*ServiceDescriptorProto) ProtoMessage() {} +func (*ServiceDescriptorProto) Descriptor() ([]byte, []int) { + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{8} +} +func (m *ServiceDescriptorProto) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ServiceDescriptorProto.Unmarshal(m, b) +} +func (m *ServiceDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ServiceDescriptorProto.Marshal(b, m, deterministic) +} +func (dst *ServiceDescriptorProto) XXX_Merge(src proto.Message) { + xxx_messageInfo_ServiceDescriptorProto.Merge(dst, src) +} +func (m *ServiceDescriptorProto) XXX_Size() int { + return xxx_messageInfo_ServiceDescriptorProto.Size(m) +} +func (m *ServiceDescriptorProto) XXX_DiscardUnknown() { + xxx_messageInfo_ServiceDescriptorProto.DiscardUnknown(m) } -func (m *ServiceDescriptorProto) Reset() { *m = ServiceDescriptorProto{} } -func (m *ServiceDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*ServiceDescriptorProto) ProtoMessage() {} -func (*ServiceDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{8} } +var xxx_messageInfo_ServiceDescriptorProto proto.InternalMessageInfo func (m *ServiceDescriptorProto) GetName() string { if m != nil && m.Name != nil { @@ -972,14 +1187,35 @@ type MethodDescriptorProto struct { // Identifies if client streams multiple client messages ClientStreaming *bool `protobuf:"varint,5,opt,name=client_streaming,json=clientStreaming,def=0" json:"client_streaming,omitempty"` // Identifies if server streams multiple server messages - ServerStreaming *bool `protobuf:"varint,6,opt,name=server_streaming,json=serverStreaming,def=0" json:"server_streaming,omitempty"` - XXX_unrecognized []byte `json:"-"` + ServerStreaming *bool `protobuf:"varint,6,opt,name=server_streaming,json=serverStreaming,def=0" json:"server_streaming,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *MethodDescriptorProto) Reset() { *m = MethodDescriptorProto{} } -func (m *MethodDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*MethodDescriptorProto) ProtoMessage() {} -func (*MethodDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{9} } +func (m *MethodDescriptorProto) Reset() { *m = MethodDescriptorProto{} } +func (m *MethodDescriptorProto) String() string { return proto.CompactTextString(m) } +func (*MethodDescriptorProto) ProtoMessage() {} +func (*MethodDescriptorProto) Descriptor() ([]byte, []int) { + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{9} +} +func (m *MethodDescriptorProto) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_MethodDescriptorProto.Unmarshal(m, b) +} +func (m *MethodDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_MethodDescriptorProto.Marshal(b, m, deterministic) +} +func (dst *MethodDescriptorProto) XXX_Merge(src proto.Message) { + xxx_messageInfo_MethodDescriptorProto.Merge(dst, src) +} +func (m *MethodDescriptorProto) XXX_Size() int { + return xxx_messageInfo_MethodDescriptorProto.Size(m) +} +func (m *MethodDescriptorProto) XXX_DiscardUnknown() { + xxx_messageInfo_MethodDescriptorProto.DiscardUnknown(m) +} + +var xxx_messageInfo_MethodDescriptorProto proto.InternalMessageInfo const Default_MethodDescriptorProto_ClientStreaming bool = false const Default_MethodDescriptorProto_ServerStreaming bool = false @@ -1046,7 +1282,7 @@ type FileOptions struct { // top-level extensions defined in the file. JavaMultipleFiles *bool `protobuf:"varint,10,opt,name=java_multiple_files,json=javaMultipleFiles,def=0" json:"java_multiple_files,omitempty"` // This option does nothing. - JavaGenerateEqualsAndHash *bool `protobuf:"varint,20,opt,name=java_generate_equals_and_hash,json=javaGenerateEqualsAndHash" json:"java_generate_equals_and_hash,omitempty"` + JavaGenerateEqualsAndHash *bool `protobuf:"varint,20,opt,name=java_generate_equals_and_hash,json=javaGenerateEqualsAndHash" json:"java_generate_equals_and_hash,omitempty"` // Deprecated: Do not use. // If set true, then the Java2 code generator will generate code that // throws an exception whenever an attempt is made to assign a non-UTF-8 // byte sequence to a string field. @@ -1100,16 +1336,21 @@ type FileOptions struct { // is empty. When this option is empty, the package name will be used for // determining the namespace. PhpNamespace *string `protobuf:"bytes,41,opt,name=php_namespace,json=phpNamespace" json:"php_namespace,omitempty"` - // The parser stores options it doesn't recognize here. See above. + // The parser stores options it doesn't recognize here. + // See the documentation for the "Options" section above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *FileOptions) Reset() { *m = FileOptions{} } -func (m *FileOptions) String() string { return proto.CompactTextString(m) } -func (*FileOptions) ProtoMessage() {} -func (*FileOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{10} } +func (m *FileOptions) Reset() { *m = FileOptions{} } +func (m *FileOptions) String() string { return proto.CompactTextString(m) } +func (*FileOptions) ProtoMessage() {} +func (*FileOptions) Descriptor() ([]byte, []int) { + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{10} +} var extRange_FileOptions = []proto.ExtensionRange{ {Start: 1000, End: 536870911}, @@ -1118,6 +1359,23 @@ var extRange_FileOptions = []proto.ExtensionRange{ func (*FileOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_FileOptions } +func (m *FileOptions) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_FileOptions.Unmarshal(m, b) +} +func (m *FileOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_FileOptions.Marshal(b, m, deterministic) +} +func (dst *FileOptions) XXX_Merge(src proto.Message) { + xxx_messageInfo_FileOptions.Merge(dst, src) +} +func (m *FileOptions) XXX_Size() int { + return xxx_messageInfo_FileOptions.Size(m) +} +func (m *FileOptions) XXX_DiscardUnknown() { + xxx_messageInfo_FileOptions.DiscardUnknown(m) +} + +var xxx_messageInfo_FileOptions proto.InternalMessageInfo const Default_FileOptions_JavaMultipleFiles bool = false const Default_FileOptions_JavaStringCheckUtf8 bool = false @@ -1150,6 +1408,7 @@ func (m *FileOptions) GetJavaMultipleFiles() bool { return Default_FileOptions_JavaMultipleFiles } +// Deprecated: Do not use. func (m *FileOptions) GetJavaGenerateEqualsAndHash() bool { if m != nil && m.JavaGenerateEqualsAndHash != nil { return *m.JavaGenerateEqualsAndHash @@ -1315,14 +1574,18 @@ type MessageOptions struct { MapEntry *bool `protobuf:"varint,7,opt,name=map_entry,json=mapEntry" json:"map_entry,omitempty"` // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *MessageOptions) Reset() { *m = MessageOptions{} } -func (m *MessageOptions) String() string { return proto.CompactTextString(m) } -func (*MessageOptions) ProtoMessage() {} -func (*MessageOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{11} } +func (m *MessageOptions) Reset() { *m = MessageOptions{} } +func (m *MessageOptions) String() string { return proto.CompactTextString(m) } +func (*MessageOptions) ProtoMessage() {} +func (*MessageOptions) Descriptor() ([]byte, []int) { + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{11} +} var extRange_MessageOptions = []proto.ExtensionRange{ {Start: 1000, End: 536870911}, @@ -1331,6 +1594,23 @@ var extRange_MessageOptions = []proto.ExtensionRange{ func (*MessageOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_MessageOptions } +func (m *MessageOptions) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_MessageOptions.Unmarshal(m, b) +} +func (m *MessageOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_MessageOptions.Marshal(b, m, deterministic) +} +func (dst *MessageOptions) XXX_Merge(src proto.Message) { + xxx_messageInfo_MessageOptions.Merge(dst, src) +} +func (m *MessageOptions) XXX_Size() int { + return xxx_messageInfo_MessageOptions.Size(m) +} +func (m *MessageOptions) XXX_DiscardUnknown() { + xxx_messageInfo_MessageOptions.DiscardUnknown(m) +} + +var xxx_messageInfo_MessageOptions proto.InternalMessageInfo const Default_MessageOptions_MessageSetWireFormat bool = false const Default_MessageOptions_NoStandardDescriptorAccessor bool = false @@ -1433,14 +1713,18 @@ type FieldOptions struct { Weak *bool `protobuf:"varint,10,opt,name=weak,def=0" json:"weak,omitempty"` // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *FieldOptions) Reset() { *m = FieldOptions{} } -func (m *FieldOptions) String() string { return proto.CompactTextString(m) } -func (*FieldOptions) ProtoMessage() {} -func (*FieldOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{12} } +func (m *FieldOptions) Reset() { *m = FieldOptions{} } +func (m *FieldOptions) String() string { return proto.CompactTextString(m) } +func (*FieldOptions) ProtoMessage() {} +func (*FieldOptions) Descriptor() ([]byte, []int) { + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{12} +} var extRange_FieldOptions = []proto.ExtensionRange{ {Start: 1000, End: 536870911}, @@ -1449,6 +1733,23 @@ var extRange_FieldOptions = []proto.ExtensionRange{ func (*FieldOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_FieldOptions } +func (m *FieldOptions) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_FieldOptions.Unmarshal(m, b) +} +func (m *FieldOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_FieldOptions.Marshal(b, m, deterministic) +} +func (dst *FieldOptions) XXX_Merge(src proto.Message) { + xxx_messageInfo_FieldOptions.Merge(dst, src) +} +func (m *FieldOptions) XXX_Size() int { + return xxx_messageInfo_FieldOptions.Size(m) +} +func (m *FieldOptions) XXX_DiscardUnknown() { + xxx_messageInfo_FieldOptions.DiscardUnknown(m) +} + +var xxx_messageInfo_FieldOptions proto.InternalMessageInfo const Default_FieldOptions_Ctype FieldOptions_CType = FieldOptions_STRING const Default_FieldOptions_Jstype FieldOptions_JSType = FieldOptions_JS_NORMAL @@ -1508,14 +1809,18 @@ func (m *FieldOptions) GetUninterpretedOption() []*UninterpretedOption { type OneofOptions struct { // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *OneofOptions) Reset() { *m = OneofOptions{} } -func (m *OneofOptions) String() string { return proto.CompactTextString(m) } -func (*OneofOptions) ProtoMessage() {} -func (*OneofOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{13} } +func (m *OneofOptions) Reset() { *m = OneofOptions{} } +func (m *OneofOptions) String() string { return proto.CompactTextString(m) } +func (*OneofOptions) ProtoMessage() {} +func (*OneofOptions) Descriptor() ([]byte, []int) { + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{13} +} var extRange_OneofOptions = []proto.ExtensionRange{ {Start: 1000, End: 536870911}, @@ -1524,6 +1829,23 @@ var extRange_OneofOptions = []proto.ExtensionRange{ func (*OneofOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_OneofOptions } +func (m *OneofOptions) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_OneofOptions.Unmarshal(m, b) +} +func (m *OneofOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_OneofOptions.Marshal(b, m, deterministic) +} +func (dst *OneofOptions) XXX_Merge(src proto.Message) { + xxx_messageInfo_OneofOptions.Merge(dst, src) +} +func (m *OneofOptions) XXX_Size() int { + return xxx_messageInfo_OneofOptions.Size(m) +} +func (m *OneofOptions) XXX_DiscardUnknown() { + xxx_messageInfo_OneofOptions.DiscardUnknown(m) +} + +var xxx_messageInfo_OneofOptions proto.InternalMessageInfo func (m *OneofOptions) GetUninterpretedOption() []*UninterpretedOption { if m != nil { @@ -1543,14 +1865,18 @@ type EnumOptions struct { Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *EnumOptions) Reset() { *m = EnumOptions{} } -func (m *EnumOptions) String() string { return proto.CompactTextString(m) } -func (*EnumOptions) ProtoMessage() {} -func (*EnumOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{14} } +func (m *EnumOptions) Reset() { *m = EnumOptions{} } +func (m *EnumOptions) String() string { return proto.CompactTextString(m) } +func (*EnumOptions) ProtoMessage() {} +func (*EnumOptions) Descriptor() ([]byte, []int) { + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{14} +} var extRange_EnumOptions = []proto.ExtensionRange{ {Start: 1000, End: 536870911}, @@ -1559,6 +1885,23 @@ var extRange_EnumOptions = []proto.ExtensionRange{ func (*EnumOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_EnumOptions } +func (m *EnumOptions) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_EnumOptions.Unmarshal(m, b) +} +func (m *EnumOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_EnumOptions.Marshal(b, m, deterministic) +} +func (dst *EnumOptions) XXX_Merge(src proto.Message) { + xxx_messageInfo_EnumOptions.Merge(dst, src) +} +func (m *EnumOptions) XXX_Size() int { + return xxx_messageInfo_EnumOptions.Size(m) +} +func (m *EnumOptions) XXX_DiscardUnknown() { + xxx_messageInfo_EnumOptions.DiscardUnknown(m) +} + +var xxx_messageInfo_EnumOptions proto.InternalMessageInfo const Default_EnumOptions_Deprecated bool = false @@ -1591,14 +1934,18 @@ type EnumValueOptions struct { Deprecated *bool `protobuf:"varint,1,opt,name=deprecated,def=0" json:"deprecated,omitempty"` // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *EnumValueOptions) Reset() { *m = EnumValueOptions{} } -func (m *EnumValueOptions) String() string { return proto.CompactTextString(m) } -func (*EnumValueOptions) ProtoMessage() {} -func (*EnumValueOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{15} } +func (m *EnumValueOptions) Reset() { *m = EnumValueOptions{} } +func (m *EnumValueOptions) String() string { return proto.CompactTextString(m) } +func (*EnumValueOptions) ProtoMessage() {} +func (*EnumValueOptions) Descriptor() ([]byte, []int) { + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{15} +} var extRange_EnumValueOptions = []proto.ExtensionRange{ {Start: 1000, End: 536870911}, @@ -1607,6 +1954,23 @@ var extRange_EnumValueOptions = []proto.ExtensionRange{ func (*EnumValueOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_EnumValueOptions } +func (m *EnumValueOptions) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_EnumValueOptions.Unmarshal(m, b) +} +func (m *EnumValueOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_EnumValueOptions.Marshal(b, m, deterministic) +} +func (dst *EnumValueOptions) XXX_Merge(src proto.Message) { + xxx_messageInfo_EnumValueOptions.Merge(dst, src) +} +func (m *EnumValueOptions) XXX_Size() int { + return xxx_messageInfo_EnumValueOptions.Size(m) +} +func (m *EnumValueOptions) XXX_DiscardUnknown() { + xxx_messageInfo_EnumValueOptions.DiscardUnknown(m) +} + +var xxx_messageInfo_EnumValueOptions proto.InternalMessageInfo const Default_EnumValueOptions_Deprecated bool = false @@ -1632,14 +1996,18 @@ type ServiceOptions struct { Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"` // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *ServiceOptions) Reset() { *m = ServiceOptions{} } -func (m *ServiceOptions) String() string { return proto.CompactTextString(m) } -func (*ServiceOptions) ProtoMessage() {} -func (*ServiceOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{16} } +func (m *ServiceOptions) Reset() { *m = ServiceOptions{} } +func (m *ServiceOptions) String() string { return proto.CompactTextString(m) } +func (*ServiceOptions) ProtoMessage() {} +func (*ServiceOptions) Descriptor() ([]byte, []int) { + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{16} +} var extRange_ServiceOptions = []proto.ExtensionRange{ {Start: 1000, End: 536870911}, @@ -1648,6 +2016,23 @@ var extRange_ServiceOptions = []proto.ExtensionRange{ func (*ServiceOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_ServiceOptions } +func (m *ServiceOptions) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ServiceOptions.Unmarshal(m, b) +} +func (m *ServiceOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ServiceOptions.Marshal(b, m, deterministic) +} +func (dst *ServiceOptions) XXX_Merge(src proto.Message) { + xxx_messageInfo_ServiceOptions.Merge(dst, src) +} +func (m *ServiceOptions) XXX_Size() int { + return xxx_messageInfo_ServiceOptions.Size(m) +} +func (m *ServiceOptions) XXX_DiscardUnknown() { + xxx_messageInfo_ServiceOptions.DiscardUnknown(m) +} + +var xxx_messageInfo_ServiceOptions proto.InternalMessageInfo const Default_ServiceOptions_Deprecated bool = false @@ -1674,14 +2059,18 @@ type MethodOptions struct { IdempotencyLevel *MethodOptions_IdempotencyLevel `protobuf:"varint,34,opt,name=idempotency_level,json=idempotencyLevel,enum=google.protobuf.MethodOptions_IdempotencyLevel,def=0" json:"idempotency_level,omitempty"` // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *MethodOptions) Reset() { *m = MethodOptions{} } -func (m *MethodOptions) String() string { return proto.CompactTextString(m) } -func (*MethodOptions) ProtoMessage() {} -func (*MethodOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{17} } +func (m *MethodOptions) Reset() { *m = MethodOptions{} } +func (m *MethodOptions) String() string { return proto.CompactTextString(m) } +func (*MethodOptions) ProtoMessage() {} +func (*MethodOptions) Descriptor() ([]byte, []int) { + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{17} +} var extRange_MethodOptions = []proto.ExtensionRange{ {Start: 1000, End: 536870911}, @@ -1690,6 +2079,23 @@ var extRange_MethodOptions = []proto.ExtensionRange{ func (*MethodOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_MethodOptions } +func (m *MethodOptions) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_MethodOptions.Unmarshal(m, b) +} +func (m *MethodOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_MethodOptions.Marshal(b, m, deterministic) +} +func (dst *MethodOptions) XXX_Merge(src proto.Message) { + xxx_messageInfo_MethodOptions.Merge(dst, src) +} +func (m *MethodOptions) XXX_Size() int { + return xxx_messageInfo_MethodOptions.Size(m) +} +func (m *MethodOptions) XXX_DiscardUnknown() { + xxx_messageInfo_MethodOptions.DiscardUnknown(m) +} + +var xxx_messageInfo_MethodOptions proto.InternalMessageInfo const Default_MethodOptions_Deprecated bool = false const Default_MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel = MethodOptions_IDEMPOTENCY_UNKNOWN @@ -1725,19 +2131,40 @@ type UninterpretedOption struct { Name []*UninterpretedOption_NamePart `protobuf:"bytes,2,rep,name=name" json:"name,omitempty"` // The value of the uninterpreted option, in whatever type the tokenizer // identified it as during parsing. Exactly one of these should be set. - IdentifierValue *string `protobuf:"bytes,3,opt,name=identifier_value,json=identifierValue" json:"identifier_value,omitempty"` - PositiveIntValue *uint64 `protobuf:"varint,4,opt,name=positive_int_value,json=positiveIntValue" json:"positive_int_value,omitempty"` - NegativeIntValue *int64 `protobuf:"varint,5,opt,name=negative_int_value,json=negativeIntValue" json:"negative_int_value,omitempty"` - DoubleValue *float64 `protobuf:"fixed64,6,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"` - StringValue []byte `protobuf:"bytes,7,opt,name=string_value,json=stringValue" json:"string_value,omitempty"` - AggregateValue *string `protobuf:"bytes,8,opt,name=aggregate_value,json=aggregateValue" json:"aggregate_value,omitempty"` - XXX_unrecognized []byte `json:"-"` + IdentifierValue *string `protobuf:"bytes,3,opt,name=identifier_value,json=identifierValue" json:"identifier_value,omitempty"` + PositiveIntValue *uint64 `protobuf:"varint,4,opt,name=positive_int_value,json=positiveIntValue" json:"positive_int_value,omitempty"` + NegativeIntValue *int64 `protobuf:"varint,5,opt,name=negative_int_value,json=negativeIntValue" json:"negative_int_value,omitempty"` + DoubleValue *float64 `protobuf:"fixed64,6,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"` + StringValue []byte `protobuf:"bytes,7,opt,name=string_value,json=stringValue" json:"string_value,omitempty"` + AggregateValue *string `protobuf:"bytes,8,opt,name=aggregate_value,json=aggregateValue" json:"aggregate_value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *UninterpretedOption) Reset() { *m = UninterpretedOption{} } -func (m *UninterpretedOption) String() string { return proto.CompactTextString(m) } -func (*UninterpretedOption) ProtoMessage() {} -func (*UninterpretedOption) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{18} } +func (m *UninterpretedOption) Reset() { *m = UninterpretedOption{} } +func (m *UninterpretedOption) String() string { return proto.CompactTextString(m) } +func (*UninterpretedOption) ProtoMessage() {} +func (*UninterpretedOption) Descriptor() ([]byte, []int) { + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{18} +} +func (m *UninterpretedOption) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_UninterpretedOption.Unmarshal(m, b) +} +func (m *UninterpretedOption) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_UninterpretedOption.Marshal(b, m, deterministic) +} +func (dst *UninterpretedOption) XXX_Merge(src proto.Message) { + xxx_messageInfo_UninterpretedOption.Merge(dst, src) +} +func (m *UninterpretedOption) XXX_Size() int { + return xxx_messageInfo_UninterpretedOption.Size(m) +} +func (m *UninterpretedOption) XXX_DiscardUnknown() { + xxx_messageInfo_UninterpretedOption.DiscardUnknown(m) +} + +var xxx_messageInfo_UninterpretedOption proto.InternalMessageInfo func (m *UninterpretedOption) GetName() []*UninterpretedOption_NamePart { if m != nil { @@ -1794,18 +2221,37 @@ func (m *UninterpretedOption) GetAggregateValue() string { // E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents // "foo.(bar.baz).qux". type UninterpretedOption_NamePart struct { - NamePart *string `protobuf:"bytes,1,req,name=name_part,json=namePart" json:"name_part,omitempty"` - IsExtension *bool `protobuf:"varint,2,req,name=is_extension,json=isExtension" json:"is_extension,omitempty"` - XXX_unrecognized []byte `json:"-"` + NamePart *string `protobuf:"bytes,1,req,name=name_part,json=namePart" json:"name_part,omitempty"` + IsExtension *bool `protobuf:"varint,2,req,name=is_extension,json=isExtension" json:"is_extension,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *UninterpretedOption_NamePart) Reset() { *m = UninterpretedOption_NamePart{} } func (m *UninterpretedOption_NamePart) String() string { return proto.CompactTextString(m) } func (*UninterpretedOption_NamePart) ProtoMessage() {} func (*UninterpretedOption_NamePart) Descriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{18, 0} + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{18, 0} +} +func (m *UninterpretedOption_NamePart) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_UninterpretedOption_NamePart.Unmarshal(m, b) +} +func (m *UninterpretedOption_NamePart) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_UninterpretedOption_NamePart.Marshal(b, m, deterministic) +} +func (dst *UninterpretedOption_NamePart) XXX_Merge(src proto.Message) { + xxx_messageInfo_UninterpretedOption_NamePart.Merge(dst, src) +} +func (m *UninterpretedOption_NamePart) XXX_Size() int { + return xxx_messageInfo_UninterpretedOption_NamePart.Size(m) +} +func (m *UninterpretedOption_NamePart) XXX_DiscardUnknown() { + xxx_messageInfo_UninterpretedOption_NamePart.DiscardUnknown(m) } +var xxx_messageInfo_UninterpretedOption_NamePart proto.InternalMessageInfo + func (m *UninterpretedOption_NamePart) GetNamePart() string { if m != nil && m.NamePart != nil { return *m.NamePart @@ -1866,14 +2312,35 @@ type SourceCodeInfo struct { // - Code which tries to interpret locations should probably be designed to // ignore those that it doesn't understand, as more types of locations could // be recorded in the future. - Location []*SourceCodeInfo_Location `protobuf:"bytes,1,rep,name=location" json:"location,omitempty"` - XXX_unrecognized []byte `json:"-"` + Location []*SourceCodeInfo_Location `protobuf:"bytes,1,rep,name=location" json:"location,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *SourceCodeInfo) Reset() { *m = SourceCodeInfo{} } -func (m *SourceCodeInfo) String() string { return proto.CompactTextString(m) } -func (*SourceCodeInfo) ProtoMessage() {} -func (*SourceCodeInfo) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{19} } +func (m *SourceCodeInfo) Reset() { *m = SourceCodeInfo{} } +func (m *SourceCodeInfo) String() string { return proto.CompactTextString(m) } +func (*SourceCodeInfo) ProtoMessage() {} +func (*SourceCodeInfo) Descriptor() ([]byte, []int) { + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{19} +} +func (m *SourceCodeInfo) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_SourceCodeInfo.Unmarshal(m, b) +} +func (m *SourceCodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_SourceCodeInfo.Marshal(b, m, deterministic) +} +func (dst *SourceCodeInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_SourceCodeInfo.Merge(dst, src) +} +func (m *SourceCodeInfo) XXX_Size() int { + return xxx_messageInfo_SourceCodeInfo.Size(m) +} +func (m *SourceCodeInfo) XXX_DiscardUnknown() { + xxx_messageInfo_SourceCodeInfo.DiscardUnknown(m) +} + +var xxx_messageInfo_SourceCodeInfo proto.InternalMessageInfo func (m *SourceCodeInfo) GetLocation() []*SourceCodeInfo_Location { if m != nil { @@ -1963,15 +2430,34 @@ type SourceCodeInfo_Location struct { LeadingComments *string `protobuf:"bytes,3,opt,name=leading_comments,json=leadingComments" json:"leading_comments,omitempty"` TrailingComments *string `protobuf:"bytes,4,opt,name=trailing_comments,json=trailingComments" json:"trailing_comments,omitempty"` LeadingDetachedComments []string `protobuf:"bytes,6,rep,name=leading_detached_comments,json=leadingDetachedComments" json:"leading_detached_comments,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *SourceCodeInfo_Location) Reset() { *m = SourceCodeInfo_Location{} } func (m *SourceCodeInfo_Location) String() string { return proto.CompactTextString(m) } func (*SourceCodeInfo_Location) ProtoMessage() {} func (*SourceCodeInfo_Location) Descriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{19, 0} + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{19, 0} +} +func (m *SourceCodeInfo_Location) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_SourceCodeInfo_Location.Unmarshal(m, b) +} +func (m *SourceCodeInfo_Location) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_SourceCodeInfo_Location.Marshal(b, m, deterministic) +} +func (dst *SourceCodeInfo_Location) XXX_Merge(src proto.Message) { + xxx_messageInfo_SourceCodeInfo_Location.Merge(dst, src) } +func (m *SourceCodeInfo_Location) XXX_Size() int { + return xxx_messageInfo_SourceCodeInfo_Location.Size(m) +} +func (m *SourceCodeInfo_Location) XXX_DiscardUnknown() { + xxx_messageInfo_SourceCodeInfo_Location.DiscardUnknown(m) +} + +var xxx_messageInfo_SourceCodeInfo_Location proto.InternalMessageInfo func (m *SourceCodeInfo_Location) GetPath() []int32 { if m != nil { @@ -2014,14 +2500,35 @@ func (m *SourceCodeInfo_Location) GetLeadingDetachedComments() []string { type GeneratedCodeInfo struct { // An Annotation connects some span of text in generated code to an element // of its generating .proto file. - Annotation []*GeneratedCodeInfo_Annotation `protobuf:"bytes,1,rep,name=annotation" json:"annotation,omitempty"` - XXX_unrecognized []byte `json:"-"` + Annotation []*GeneratedCodeInfo_Annotation `protobuf:"bytes,1,rep,name=annotation" json:"annotation,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GeneratedCodeInfo) Reset() { *m = GeneratedCodeInfo{} } +func (m *GeneratedCodeInfo) String() string { return proto.CompactTextString(m) } +func (*GeneratedCodeInfo) ProtoMessage() {} +func (*GeneratedCodeInfo) Descriptor() ([]byte, []int) { + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{20} +} +func (m *GeneratedCodeInfo) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GeneratedCodeInfo.Unmarshal(m, b) +} +func (m *GeneratedCodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GeneratedCodeInfo.Marshal(b, m, deterministic) +} +func (dst *GeneratedCodeInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_GeneratedCodeInfo.Merge(dst, src) +} +func (m *GeneratedCodeInfo) XXX_Size() int { + return xxx_messageInfo_GeneratedCodeInfo.Size(m) +} +func (m *GeneratedCodeInfo) XXX_DiscardUnknown() { + xxx_messageInfo_GeneratedCodeInfo.DiscardUnknown(m) } -func (m *GeneratedCodeInfo) Reset() { *m = GeneratedCodeInfo{} } -func (m *GeneratedCodeInfo) String() string { return proto.CompactTextString(m) } -func (*GeneratedCodeInfo) ProtoMessage() {} -func (*GeneratedCodeInfo) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{20} } +var xxx_messageInfo_GeneratedCodeInfo proto.InternalMessageInfo func (m *GeneratedCodeInfo) GetAnnotation() []*GeneratedCodeInfo_Annotation { if m != nil { @@ -2042,16 +2549,35 @@ type GeneratedCodeInfo_Annotation struct { // Identifies the ending offset in bytes in the generated code that // relates to the identified offset. The end offset should be one past // the last relevant byte (so the length of the text = end - begin). - End *int32 `protobuf:"varint,4,opt,name=end" json:"end,omitempty"` - XXX_unrecognized []byte `json:"-"` + End *int32 `protobuf:"varint,4,opt,name=end" json:"end,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *GeneratedCodeInfo_Annotation) Reset() { *m = GeneratedCodeInfo_Annotation{} } func (m *GeneratedCodeInfo_Annotation) String() string { return proto.CompactTextString(m) } func (*GeneratedCodeInfo_Annotation) ProtoMessage() {} func (*GeneratedCodeInfo_Annotation) Descriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{20, 0} + return fileDescriptor_descriptor_9588782fb9cbecd6, []int{20, 0} +} +func (m *GeneratedCodeInfo_Annotation) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GeneratedCodeInfo_Annotation.Unmarshal(m, b) } +func (m *GeneratedCodeInfo_Annotation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GeneratedCodeInfo_Annotation.Marshal(b, m, deterministic) +} +func (dst *GeneratedCodeInfo_Annotation) XXX_Merge(src proto.Message) { + xxx_messageInfo_GeneratedCodeInfo_Annotation.Merge(dst, src) +} +func (m *GeneratedCodeInfo_Annotation) XXX_Size() int { + return xxx_messageInfo_GeneratedCodeInfo_Annotation.Size(m) +} +func (m *GeneratedCodeInfo_Annotation) XXX_DiscardUnknown() { + xxx_messageInfo_GeneratedCodeInfo_Annotation.DiscardUnknown(m) +} + +var xxx_messageInfo_GeneratedCodeInfo_Annotation proto.InternalMessageInfo func (m *GeneratedCodeInfo_Annotation) GetPath() []int32 { if m != nil { @@ -2117,9 +2643,9 @@ func init() { proto.RegisterEnum("google.protobuf.MethodOptions_IdempotencyLevel", MethodOptions_IdempotencyLevel_name, MethodOptions_IdempotencyLevel_value) } -func init() { proto.RegisterFile("descriptor.proto", fileDescriptorDescriptor) } +func init() { proto.RegisterFile("descriptor.proto", fileDescriptor_descriptor_9588782fb9cbecd6) } -var fileDescriptorDescriptor = []byte{ +var fileDescriptor_descriptor_9588782fb9cbecd6 = []byte{ // 2487 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x59, 0xcd, 0x6f, 0xdb, 0xc8, 0x15, 0x5f, 0x7d, 0x5a, 0x7a, 0x92, 0xe5, 0xf1, 0xd8, 0x9b, 0x30, 0xde, 0x8f, 0x38, 0xda, 0x8f, diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_gostring.gen.go b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_gostring.gen.go index 3b95a7757..ec6eb168d 100644 --- a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_gostring.gen.go +++ b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_gostring.gen.go @@ -1,43 +1,15 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: descriptor.proto -/* -Package descriptor is a generated protocol buffer package. - -It is generated from these files: - descriptor.proto - -It has these top-level messages: - FileDescriptorSet - FileDescriptorProto - DescriptorProto - ExtensionRangeOptions - FieldDescriptorProto - OneofDescriptorProto - EnumDescriptorProto - EnumValueDescriptorProto - ServiceDescriptorProto - MethodDescriptorProto - FileOptions - MessageOptions - FieldOptions - OneofOptions - EnumOptions - EnumValueOptions - ServiceOptions - MethodOptions - UninterpretedOption - SourceCodeInfo - GeneratedCodeInfo -*/ package descriptor import fmt "fmt" import strings "strings" -import proto "github.com/gogo/protobuf/proto" +import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto" import sort "sort" import strconv "strconv" import reflect "reflect" +import proto "github.com/gogo/protobuf/proto" import math "math" // Reference imports to suppress errors if they are not otherwise used. @@ -752,8 +724,8 @@ func valueToGoStringDescriptor(v interface{}, typ string) string { pv := reflect.Indirect(rv).Interface() return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv) } -func extensionToGoStringDescriptor(m proto.Message) string { - e := proto.GetUnsafeExtensionsMap(m) +func extensionToGoStringDescriptor(m github_com_gogo_protobuf_proto.Message) string { + e := github_com_gogo_protobuf_proto.GetUnsafeExtensionsMap(m) if e == nil { return "nil" } diff --git a/vendor/github.com/gogo/protobuf/types/any.go b/vendor/github.com/gogo/protobuf/types/any.go index d83c3ad00..df4787de3 100644 --- a/vendor/github.com/gogo/protobuf/types/any.go +++ b/vendor/github.com/gogo/protobuf/types/any.go @@ -129,10 +129,12 @@ func UnmarshalAny(any *Any, pb proto.Message) error { // Is returns true if any value contains a given message type. func Is(any *Any, pb proto.Message) bool { - aname, err := AnyMessageName(any) - if err != nil { + // The following is equivalent to AnyMessageName(any) == proto.MessageName(pb), + // but it avoids scanning TypeUrl for the slash. + if any == nil { return false } - - return aname == proto.MessageName(pb) + name := proto.MessageName(pb) + prefix := len(any.TypeUrl) - len(name) + return prefix >= 1 && any.TypeUrl[prefix-1] == '/' && any.TypeUrl[prefix:] == name } diff --git a/vendor/github.com/gogo/protobuf/types/any.pb.go b/vendor/github.com/gogo/protobuf/types/any.pb.go index 4b5f5705a..b9918238b 100644 --- a/vendor/github.com/gogo/protobuf/types/any.pb.go +++ b/vendor/github.com/gogo/protobuf/types/any.pb.go @@ -1,15 +1,6 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: any.proto +// source: google/protobuf/any.proto -/* - Package types is a generated protocol buffer package. - - It is generated from these files: - any.proto - - It has these top-level messages: - Any -*/ package types import proto "github.com/gogo/protobuf/proto" @@ -115,17 +106,18 @@ const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package // } // type Any struct { - // A URL/resource name whose content describes the type of the - // serialized protocol buffer message. + // A URL/resource name that uniquely identifies the type of the serialized + // protocol buffer message. The last segment of the URL's path must represent + // the fully qualified name of the type (as in + // `path/google.protobuf.Duration`). The name should be in a canonical form + // (e.g., leading "." is not accepted). // - // For URLs which use the scheme `http`, `https`, or no scheme, the - // following restrictions and interpretations apply: + // In practice, teams usually precompile into the binary all types that they + // expect it to use in the context of Any. However, for URLs which use the + // scheme `http`, `https`, or no scheme, one can optionally set up a type + // server that maps type URLs to message definitions as follows: // // * If no scheme is provided, `https` is assumed. - // * The last segment of the URL's path must represent the fully - // qualified name of the type (as in `path/google.protobuf.Duration`). - // The name should be in a canonical form (e.g., leading "." is - // not accepted). // * An HTTP GET on the URL must yield a [google.protobuf.Type][] // value in binary format, or produce an error. // * Applications are allowed to cache lookup results based on the @@ -134,18 +126,53 @@ type Any struct { // on changes to types. (Use versioned type names to manage // breaking changes.) // + // Note: this functionality is not currently available in the official + // protobuf release, and it is not used for type URLs beginning with + // type.googleapis.com. + // // Schemes other than `http`, `https` (or the empty scheme) might be // used with implementation specific semantics. // TypeUrl string `protobuf:"bytes,1,opt,name=type_url,json=typeUrl,proto3" json:"type_url,omitempty"` // Must be a valid serialized protocol buffer of the above specified type. - Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` + Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Any) Reset() { *m = Any{} } +func (*Any) ProtoMessage() {} +func (*Any) Descriptor() ([]byte, []int) { + return fileDescriptor_any_8eec716d227a06dd, []int{0} +} +func (*Any) XXX_WellKnownType() string { return "Any" } +func (m *Any) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Any) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Any.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *Any) XXX_Merge(src proto.Message) { + xxx_messageInfo_Any.Merge(dst, src) +} +func (m *Any) XXX_Size() int { + return m.Size() +} +func (m *Any) XXX_DiscardUnknown() { + xxx_messageInfo_Any.DiscardUnknown(m) } -func (m *Any) Reset() { *m = Any{} } -func (*Any) ProtoMessage() {} -func (*Any) Descriptor() ([]byte, []int) { return fileDescriptorAny, []int{0} } -func (*Any) XXX_WellKnownType() string { return "Any" } +var xxx_messageInfo_Any proto.InternalMessageInfo func (m *Any) GetTypeUrl() string { if m != nil { @@ -161,6 +188,9 @@ func (m *Any) GetValue() []byte { return nil } +func (*Any) XXX_MessageName() string { + return "google.protobuf.Any" +} func init() { proto.RegisterType((*Any)(nil), "google.protobuf.Any") } @@ -198,6 +228,9 @@ func (this *Any) Compare(that interface{}) int { if c := bytes.Compare(this.Value, that1.Value); c != 0 { return c } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } return 0 } func (this *Any) Equal(that interface{}) bool { @@ -225,6 +258,9 @@ func (this *Any) Equal(that interface{}) bool { if !bytes.Equal(this.Value, that1.Value) { return false } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } return true } func (this *Any) GoString() string { @@ -235,6 +271,9 @@ func (this *Any) GoString() string { s = append(s, "&types.Any{") s = append(s, "TypeUrl: "+fmt.Sprintf("%#v", this.TypeUrl)+",\n") s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n") + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } s = append(s, "}") return strings.Join(s, "") } @@ -273,6 +312,9 @@ func (m *Any) MarshalTo(dAtA []byte) (int, error) { i = encodeVarintAny(dAtA, i, uint64(len(m.Value))) i += copy(dAtA[i:], m.Value) } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } return i, nil } @@ -294,6 +336,7 @@ func NewPopulatedAny(r randyAny, easy bool) *Any { this.Value[i] = byte(r.Intn(256)) } if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedAny(r, 3) } return this } @@ -381,6 +424,9 @@ func (m *Any) Size() (n int) { if l > 0 { n += 1 + l + sovAny(uint64(l)) } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } return n } @@ -404,6 +450,7 @@ func (this *Any) String() string { s := strings.Join([]string{`&Any{`, `TypeUrl:` + fmt.Sprintf("%v", this.TypeUrl) + `,`, `Value:` + fmt.Sprintf("%v", this.Value) + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s @@ -517,6 +564,7 @@ func (m *Any) Unmarshal(dAtA []byte) error { if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } @@ -631,21 +679,22 @@ var ( ErrIntOverflowAny = fmt.Errorf("proto: integer overflow") ) -func init() { proto.RegisterFile("any.proto", fileDescriptorAny) } +func init() { proto.RegisterFile("google/protobuf/any.proto", fileDescriptor_any_8eec716d227a06dd) } -var fileDescriptorAny = []byte{ - // 204 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x4c, 0xcc, 0xab, 0xd4, - 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x4f, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0x85, 0xf0, 0x92, - 0x4a, 0xd3, 0x94, 0xcc, 0xb8, 0x98, 0x1d, 0xf3, 0x2a, 0x85, 0x24, 0xb9, 0x38, 0x4a, 0x2a, 0x0b, - 0x52, 0xe3, 0x4b, 0x8b, 0x72, 0x24, 0x18, 0x15, 0x18, 0x35, 0x38, 0x83, 0xd8, 0x41, 0xfc, 0xd0, - 0xa2, 0x1c, 0x21, 0x11, 0x2e, 0xd6, 0xb2, 0xc4, 0x9c, 0xd2, 0x54, 0x09, 0x26, 0x05, 0x46, 0x0d, - 0x9e, 0x20, 0x08, 0xc7, 0xa9, 0xfe, 0xc2, 0x43, 0x39, 0x86, 0x1b, 0x0f, 0xe5, 0x18, 0x3e, 0x3c, - 0x94, 0x63, 0xfc, 0xf1, 0x50, 0x8e, 0xb1, 0xe1, 0x91, 0x1c, 0xe3, 0x8a, 0x47, 0x72, 0x8c, 0x27, - 0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x8b, 0x47, 0x72, 0x0c, - 0x1f, 0x40, 0xe2, 0x8f, 0xe5, 0x18, 0xb9, 0x84, 0x93, 0xf3, 0x73, 0xf5, 0xd0, 0xac, 0x77, 0xe2, - 0x70, 0xcc, 0xab, 0x0c, 0x00, 0x71, 0x02, 0x18, 0xa3, 0x58, 0x41, 0x36, 0x16, 0x2f, 0x62, 0x62, - 0x76, 0x0f, 0x70, 0x5a, 0xc5, 0x24, 0xe7, 0x0e, 0x51, 0x1a, 0x00, 0x55, 0xaa, 0x17, 0x9e, 0x9a, - 0x93, 0xe3, 0x9d, 0x97, 0x5f, 0x9e, 0x17, 0x02, 0x52, 0x96, 0xc4, 0x06, 0x36, 0xc3, 0x18, 0x10, - 0x00, 0x00, 0xff, 0xff, 0xb7, 0x39, 0x2f, 0x89, 0xdd, 0x00, 0x00, 0x00, +var fileDescriptor_any_8eec716d227a06dd = []byte{ + // 216 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4c, 0xcf, 0xcf, 0x4f, + 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcc, 0xab, 0xd4, + 0x03, 0x73, 0x84, 0xf8, 0x21, 0x52, 0x7a, 0x30, 0x29, 0x25, 0x33, 0x2e, 0x66, 0xc7, 0xbc, 0x4a, + 0x21, 0x49, 0x2e, 0x8e, 0x92, 0xca, 0x82, 0xd4, 0xf8, 0xd2, 0xa2, 0x1c, 0x09, 0x46, 0x05, 0x46, + 0x0d, 0xce, 0x20, 0x76, 0x10, 0x3f, 0xb4, 0x28, 0x47, 0x48, 0x84, 0x8b, 0xb5, 0x2c, 0x31, 0xa7, + 0x34, 0x55, 0x82, 0x49, 0x81, 0x51, 0x83, 0x27, 0x08, 0xc2, 0x71, 0x6a, 0x66, 0xbc, 0xf0, 0x50, + 0x8e, 0xe1, 0xc6, 0x43, 0x39, 0x86, 0x0f, 0x0f, 0xe5, 0x18, 0x7f, 0x3c, 0x94, 0x63, 0x6c, 0x78, + 0x24, 0xc7, 0xb8, 0xe2, 0x91, 0x1c, 0xe3, 0x89, 0x47, 0x72, 0x8c, 0x17, 0x1e, 0xc9, 0x31, 0x3e, + 0x78, 0x24, 0xc7, 0xf8, 0xe2, 0x91, 0x1c, 0xc3, 0x07, 0x90, 0xf8, 0x63, 0x39, 0xc6, 0x13, 0x8f, + 0xe5, 0x18, 0xb9, 0x84, 0x93, 0xf3, 0x73, 0xf5, 0xd0, 0xdc, 0xe0, 0xc4, 0xe1, 0x98, 0x57, 0x19, + 0x00, 0xe2, 0x04, 0x30, 0x46, 0xb1, 0x82, 0xac, 0x2d, 0x5e, 0xc4, 0xc4, 0xec, 0x1e, 0xe0, 0xb4, + 0x8a, 0x49, 0xce, 0x1d, 0xa2, 0x34, 0x00, 0xaa, 0x54, 0x2f, 0x3c, 0x35, 0x27, 0xc7, 0x3b, 0x2f, + 0xbf, 0x3c, 0x2f, 0x04, 0xa4, 0x2c, 0x89, 0x0d, 0x6c, 0x86, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, + 0x19, 0x7c, 0x7c, 0x94, 0xf2, 0x00, 0x00, 0x00, } diff --git a/vendor/github.com/gogo/protobuf/types/api.pb.go b/vendor/github.com/gogo/protobuf/types/api.pb.go new file mode 100644 index 000000000..395c9b6b4 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/types/api.pb.go @@ -0,0 +1,2058 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: google/protobuf/api.proto + +package types + +import proto "github.com/gogo/protobuf/proto" +import fmt "fmt" +import math "math" + +import bytes "bytes" + +import strings "strings" +import reflect "reflect" + +import io "io" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package + +// Api is a light-weight descriptor for an API Interface. +// +// Interfaces are also described as "protocol buffer services" in some contexts, +// such as by the "service" keyword in a .proto file, but they are different +// from API Services, which represent a concrete implementation of an interface +// as opposed to simply a description of methods and bindings. They are also +// sometimes simply referred to as "APIs" in other contexts, such as the name of +// this message itself. See https://cloud.google.com/apis/design/glossary for +// detailed terminology. +type Api struct { + // The fully qualified name of this interface, including package name + // followed by the interface's simple name. + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + // The methods of this interface, in unspecified order. + Methods []*Method `protobuf:"bytes,2,rep,name=methods" json:"methods,omitempty"` + // Any metadata attached to the interface. + Options []*Option `protobuf:"bytes,3,rep,name=options" json:"options,omitempty"` + // A version string for this interface. If specified, must have the form + // `major-version.minor-version`, as in `1.10`. If the minor version is + // omitted, it defaults to zero. If the entire version field is empty, the + // major version is derived from the package name, as outlined below. If the + // field is not empty, the version in the package name will be verified to be + // consistent with what is provided here. + // + // The versioning schema uses [semantic + // versioning](http://semver.org) where the major version number + // indicates a breaking change and the minor version an additive, + // non-breaking change. Both version numbers are signals to users + // what to expect from different versions, and should be carefully + // chosen based on the product plan. + // + // The major version is also reflected in the package name of the + // interface, which must end in `v`, as in + // `google.feature.v1`. For major versions 0 and 1, the suffix can + // be omitted. Zero major versions must only be used for + // experimental, non-GA interfaces. + // + // + Version string `protobuf:"bytes,4,opt,name=version,proto3" json:"version,omitempty"` + // Source context for the protocol buffer service represented by this + // message. + SourceContext *SourceContext `protobuf:"bytes,5,opt,name=source_context,json=sourceContext" json:"source_context,omitempty"` + // Included interfaces. See [Mixin][]. + Mixins []*Mixin `protobuf:"bytes,6,rep,name=mixins" json:"mixins,omitempty"` + // The source syntax of the service. + Syntax Syntax `protobuf:"varint,7,opt,name=syntax,proto3,enum=google.protobuf.Syntax" json:"syntax,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Api) Reset() { *m = Api{} } +func (*Api) ProtoMessage() {} +func (*Api) Descriptor() ([]byte, []int) { + return fileDescriptor_api_658bf9e68d9b66a3, []int{0} +} +func (m *Api) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Api) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Api.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *Api) XXX_Merge(src proto.Message) { + xxx_messageInfo_Api.Merge(dst, src) +} +func (m *Api) XXX_Size() int { + return m.Size() +} +func (m *Api) XXX_DiscardUnknown() { + xxx_messageInfo_Api.DiscardUnknown(m) +} + +var xxx_messageInfo_Api proto.InternalMessageInfo + +func (m *Api) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *Api) GetMethods() []*Method { + if m != nil { + return m.Methods + } + return nil +} + +func (m *Api) GetOptions() []*Option { + if m != nil { + return m.Options + } + return nil +} + +func (m *Api) GetVersion() string { + if m != nil { + return m.Version + } + return "" +} + +func (m *Api) GetSourceContext() *SourceContext { + if m != nil { + return m.SourceContext + } + return nil +} + +func (m *Api) GetMixins() []*Mixin { + if m != nil { + return m.Mixins + } + return nil +} + +func (m *Api) GetSyntax() Syntax { + if m != nil { + return m.Syntax + } + return SYNTAX_PROTO2 +} + +func (*Api) XXX_MessageName() string { + return "google.protobuf.Api" +} + +// Method represents a method of an API interface. +type Method struct { + // The simple name of this method. + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + // A URL of the input message type. + RequestTypeUrl string `protobuf:"bytes,2,opt,name=request_type_url,json=requestTypeUrl,proto3" json:"request_type_url,omitempty"` + // If true, the request is streamed. + RequestStreaming bool `protobuf:"varint,3,opt,name=request_streaming,json=requestStreaming,proto3" json:"request_streaming,omitempty"` + // The URL of the output message type. + ResponseTypeUrl string `protobuf:"bytes,4,opt,name=response_type_url,json=responseTypeUrl,proto3" json:"response_type_url,omitempty"` + // If true, the response is streamed. + ResponseStreaming bool `protobuf:"varint,5,opt,name=response_streaming,json=responseStreaming,proto3" json:"response_streaming,omitempty"` + // Any metadata attached to the method. + Options []*Option `protobuf:"bytes,6,rep,name=options" json:"options,omitempty"` + // The source syntax of this method. + Syntax Syntax `protobuf:"varint,7,opt,name=syntax,proto3,enum=google.protobuf.Syntax" json:"syntax,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Method) Reset() { *m = Method{} } +func (*Method) ProtoMessage() {} +func (*Method) Descriptor() ([]byte, []int) { + return fileDescriptor_api_658bf9e68d9b66a3, []int{1} +} +func (m *Method) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Method) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Method.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *Method) XXX_Merge(src proto.Message) { + xxx_messageInfo_Method.Merge(dst, src) +} +func (m *Method) XXX_Size() int { + return m.Size() +} +func (m *Method) XXX_DiscardUnknown() { + xxx_messageInfo_Method.DiscardUnknown(m) +} + +var xxx_messageInfo_Method proto.InternalMessageInfo + +func (m *Method) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *Method) GetRequestTypeUrl() string { + if m != nil { + return m.RequestTypeUrl + } + return "" +} + +func (m *Method) GetRequestStreaming() bool { + if m != nil { + return m.RequestStreaming + } + return false +} + +func (m *Method) GetResponseTypeUrl() string { + if m != nil { + return m.ResponseTypeUrl + } + return "" +} + +func (m *Method) GetResponseStreaming() bool { + if m != nil { + return m.ResponseStreaming + } + return false +} + +func (m *Method) GetOptions() []*Option { + if m != nil { + return m.Options + } + return nil +} + +func (m *Method) GetSyntax() Syntax { + if m != nil { + return m.Syntax + } + return SYNTAX_PROTO2 +} + +func (*Method) XXX_MessageName() string { + return "google.protobuf.Method" +} + +// Declares an API Interface to be included in this interface. The including +// interface must redeclare all the methods from the included interface, but +// documentation and options are inherited as follows: +// +// - If after comment and whitespace stripping, the documentation +// string of the redeclared method is empty, it will be inherited +// from the original method. +// +// - Each annotation belonging to the service config (http, +// visibility) which is not set in the redeclared method will be +// inherited. +// +// - If an http annotation is inherited, the path pattern will be +// modified as follows. Any version prefix will be replaced by the +// version of the including interface plus the [root][] path if +// specified. +// +// Example of a simple mixin: +// +// package google.acl.v1; +// service AccessControl { +// // Get the underlying ACL object. +// rpc GetAcl(GetAclRequest) returns (Acl) { +// option (google.api.http).get = "/v1/{resource=**}:getAcl"; +// } +// } +// +// package google.storage.v2; +// service Storage { +// rpc GetAcl(GetAclRequest) returns (Acl); +// +// // Get a data record. +// rpc GetData(GetDataRequest) returns (Data) { +// option (google.api.http).get = "/v2/{resource=**}"; +// } +// } +// +// Example of a mixin configuration: +// +// apis: +// - name: google.storage.v2.Storage +// mixins: +// - name: google.acl.v1.AccessControl +// +// The mixin construct implies that all methods in `AccessControl` are +// also declared with same name and request/response types in +// `Storage`. A documentation generator or annotation processor will +// see the effective `Storage.GetAcl` method after inherting +// documentation and annotations as follows: +// +// service Storage { +// // Get the underlying ACL object. +// rpc GetAcl(GetAclRequest) returns (Acl) { +// option (google.api.http).get = "/v2/{resource=**}:getAcl"; +// } +// ... +// } +// +// Note how the version in the path pattern changed from `v1` to `v2`. +// +// If the `root` field in the mixin is specified, it should be a +// relative path under which inherited HTTP paths are placed. Example: +// +// apis: +// - name: google.storage.v2.Storage +// mixins: +// - name: google.acl.v1.AccessControl +// root: acls +// +// This implies the following inherited HTTP annotation: +// +// service Storage { +// // Get the underlying ACL object. +// rpc GetAcl(GetAclRequest) returns (Acl) { +// option (google.api.http).get = "/v2/acls/{resource=**}:getAcl"; +// } +// ... +// } +type Mixin struct { + // The fully qualified name of the interface which is included. + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + // If non-empty specifies a path under which inherited HTTP paths + // are rooted. + Root string `protobuf:"bytes,2,opt,name=root,proto3" json:"root,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Mixin) Reset() { *m = Mixin{} } +func (*Mixin) ProtoMessage() {} +func (*Mixin) Descriptor() ([]byte, []int) { + return fileDescriptor_api_658bf9e68d9b66a3, []int{2} +} +func (m *Mixin) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Mixin) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Mixin.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *Mixin) XXX_Merge(src proto.Message) { + xxx_messageInfo_Mixin.Merge(dst, src) +} +func (m *Mixin) XXX_Size() int { + return m.Size() +} +func (m *Mixin) XXX_DiscardUnknown() { + xxx_messageInfo_Mixin.DiscardUnknown(m) +} + +var xxx_messageInfo_Mixin proto.InternalMessageInfo + +func (m *Mixin) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *Mixin) GetRoot() string { + if m != nil { + return m.Root + } + return "" +} + +func (*Mixin) XXX_MessageName() string { + return "google.protobuf.Mixin" +} +func init() { + proto.RegisterType((*Api)(nil), "google.protobuf.Api") + proto.RegisterType((*Method)(nil), "google.protobuf.Method") + proto.RegisterType((*Mixin)(nil), "google.protobuf.Mixin") +} +func (this *Api) Compare(that interface{}) int { + if that == nil { + if this == nil { + return 0 + } + return 1 + } + + that1, ok := that.(*Api) + if !ok { + that2, ok := that.(Api) + if ok { + that1 = &that2 + } else { + return 1 + } + } + if that1 == nil { + if this == nil { + return 0 + } + return 1 + } else if this == nil { + return -1 + } + if this.Name != that1.Name { + if this.Name < that1.Name { + return -1 + } + return 1 + } + if len(this.Methods) != len(that1.Methods) { + if len(this.Methods) < len(that1.Methods) { + return -1 + } + return 1 + } + for i := range this.Methods { + if c := this.Methods[i].Compare(that1.Methods[i]); c != 0 { + return c + } + } + if len(this.Options) != len(that1.Options) { + if len(this.Options) < len(that1.Options) { + return -1 + } + return 1 + } + for i := range this.Options { + if c := this.Options[i].Compare(that1.Options[i]); c != 0 { + return c + } + } + if this.Version != that1.Version { + if this.Version < that1.Version { + return -1 + } + return 1 + } + if c := this.SourceContext.Compare(that1.SourceContext); c != 0 { + return c + } + if len(this.Mixins) != len(that1.Mixins) { + if len(this.Mixins) < len(that1.Mixins) { + return -1 + } + return 1 + } + for i := range this.Mixins { + if c := this.Mixins[i].Compare(that1.Mixins[i]); c != 0 { + return c + } + } + if this.Syntax != that1.Syntax { + if this.Syntax < that1.Syntax { + return -1 + } + return 1 + } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } + return 0 +} +func (this *Method) Compare(that interface{}) int { + if that == nil { + if this == nil { + return 0 + } + return 1 + } + + that1, ok := that.(*Method) + if !ok { + that2, ok := that.(Method) + if ok { + that1 = &that2 + } else { + return 1 + } + } + if that1 == nil { + if this == nil { + return 0 + } + return 1 + } else if this == nil { + return -1 + } + if this.Name != that1.Name { + if this.Name < that1.Name { + return -1 + } + return 1 + } + if this.RequestTypeUrl != that1.RequestTypeUrl { + if this.RequestTypeUrl < that1.RequestTypeUrl { + return -1 + } + return 1 + } + if this.RequestStreaming != that1.RequestStreaming { + if !this.RequestStreaming { + return -1 + } + return 1 + } + if this.ResponseTypeUrl != that1.ResponseTypeUrl { + if this.ResponseTypeUrl < that1.ResponseTypeUrl { + return -1 + } + return 1 + } + if this.ResponseStreaming != that1.ResponseStreaming { + if !this.ResponseStreaming { + return -1 + } + return 1 + } + if len(this.Options) != len(that1.Options) { + if len(this.Options) < len(that1.Options) { + return -1 + } + return 1 + } + for i := range this.Options { + if c := this.Options[i].Compare(that1.Options[i]); c != 0 { + return c + } + } + if this.Syntax != that1.Syntax { + if this.Syntax < that1.Syntax { + return -1 + } + return 1 + } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } + return 0 +} +func (this *Mixin) Compare(that interface{}) int { + if that == nil { + if this == nil { + return 0 + } + return 1 + } + + that1, ok := that.(*Mixin) + if !ok { + that2, ok := that.(Mixin) + if ok { + that1 = &that2 + } else { + return 1 + } + } + if that1 == nil { + if this == nil { + return 0 + } + return 1 + } else if this == nil { + return -1 + } + if this.Name != that1.Name { + if this.Name < that1.Name { + return -1 + } + return 1 + } + if this.Root != that1.Root { + if this.Root < that1.Root { + return -1 + } + return 1 + } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } + return 0 +} +func (this *Api) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*Api) + if !ok { + that2, ok := that.(Api) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Name != that1.Name { + return false + } + if len(this.Methods) != len(that1.Methods) { + return false + } + for i := range this.Methods { + if !this.Methods[i].Equal(that1.Methods[i]) { + return false + } + } + if len(this.Options) != len(that1.Options) { + return false + } + for i := range this.Options { + if !this.Options[i].Equal(that1.Options[i]) { + return false + } + } + if this.Version != that1.Version { + return false + } + if !this.SourceContext.Equal(that1.SourceContext) { + return false + } + if len(this.Mixins) != len(that1.Mixins) { + return false + } + for i := range this.Mixins { + if !this.Mixins[i].Equal(that1.Mixins[i]) { + return false + } + } + if this.Syntax != that1.Syntax { + return false + } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } + return true +} +func (this *Method) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*Method) + if !ok { + that2, ok := that.(Method) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Name != that1.Name { + return false + } + if this.RequestTypeUrl != that1.RequestTypeUrl { + return false + } + if this.RequestStreaming != that1.RequestStreaming { + return false + } + if this.ResponseTypeUrl != that1.ResponseTypeUrl { + return false + } + if this.ResponseStreaming != that1.ResponseStreaming { + return false + } + if len(this.Options) != len(that1.Options) { + return false + } + for i := range this.Options { + if !this.Options[i].Equal(that1.Options[i]) { + return false + } + } + if this.Syntax != that1.Syntax { + return false + } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } + return true +} +func (this *Mixin) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*Mixin) + if !ok { + that2, ok := that.(Mixin) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Name != that1.Name { + return false + } + if this.Root != that1.Root { + return false + } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } + return true +} +func (this *Api) GoString() string { + if this == nil { + return "nil" + } + s := make([]string, 0, 11) + s = append(s, "&types.Api{") + s = append(s, "Name: "+fmt.Sprintf("%#v", this.Name)+",\n") + if this.Methods != nil { + s = append(s, "Methods: "+fmt.Sprintf("%#v", this.Methods)+",\n") + } + if this.Options != nil { + s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n") + } + s = append(s, "Version: "+fmt.Sprintf("%#v", this.Version)+",\n") + if this.SourceContext != nil { + s = append(s, "SourceContext: "+fmt.Sprintf("%#v", this.SourceContext)+",\n") + } + if this.Mixins != nil { + s = append(s, "Mixins: "+fmt.Sprintf("%#v", this.Mixins)+",\n") + } + s = append(s, "Syntax: "+fmt.Sprintf("%#v", this.Syntax)+",\n") + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } + s = append(s, "}") + return strings.Join(s, "") +} +func (this *Method) GoString() string { + if this == nil { + return "nil" + } + s := make([]string, 0, 11) + s = append(s, "&types.Method{") + s = append(s, "Name: "+fmt.Sprintf("%#v", this.Name)+",\n") + s = append(s, "RequestTypeUrl: "+fmt.Sprintf("%#v", this.RequestTypeUrl)+",\n") + s = append(s, "RequestStreaming: "+fmt.Sprintf("%#v", this.RequestStreaming)+",\n") + s = append(s, "ResponseTypeUrl: "+fmt.Sprintf("%#v", this.ResponseTypeUrl)+",\n") + s = append(s, "ResponseStreaming: "+fmt.Sprintf("%#v", this.ResponseStreaming)+",\n") + if this.Options != nil { + s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n") + } + s = append(s, "Syntax: "+fmt.Sprintf("%#v", this.Syntax)+",\n") + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } + s = append(s, "}") + return strings.Join(s, "") +} +func (this *Mixin) GoString() string { + if this == nil { + return "nil" + } + s := make([]string, 0, 6) + s = append(s, "&types.Mixin{") + s = append(s, "Name: "+fmt.Sprintf("%#v", this.Name)+",\n") + s = append(s, "Root: "+fmt.Sprintf("%#v", this.Root)+",\n") + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } + s = append(s, "}") + return strings.Join(s, "") +} +func valueToGoStringApi(v interface{}, typ string) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv) +} +func (m *Api) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Api) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Name) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintApi(dAtA, i, uint64(len(m.Name))) + i += copy(dAtA[i:], m.Name) + } + if len(m.Methods) > 0 { + for _, msg := range m.Methods { + dAtA[i] = 0x12 + i++ + i = encodeVarintApi(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + if len(m.Options) > 0 { + for _, msg := range m.Options { + dAtA[i] = 0x1a + i++ + i = encodeVarintApi(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + if len(m.Version) > 0 { + dAtA[i] = 0x22 + i++ + i = encodeVarintApi(dAtA, i, uint64(len(m.Version))) + i += copy(dAtA[i:], m.Version) + } + if m.SourceContext != nil { + dAtA[i] = 0x2a + i++ + i = encodeVarintApi(dAtA, i, uint64(m.SourceContext.Size())) + n1, err := m.SourceContext.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n1 + } + if len(m.Mixins) > 0 { + for _, msg := range m.Mixins { + dAtA[i] = 0x32 + i++ + i = encodeVarintApi(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + if m.Syntax != 0 { + dAtA[i] = 0x38 + i++ + i = encodeVarintApi(dAtA, i, uint64(m.Syntax)) + } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } + return i, nil +} + +func (m *Method) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Method) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Name) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintApi(dAtA, i, uint64(len(m.Name))) + i += copy(dAtA[i:], m.Name) + } + if len(m.RequestTypeUrl) > 0 { + dAtA[i] = 0x12 + i++ + i = encodeVarintApi(dAtA, i, uint64(len(m.RequestTypeUrl))) + i += copy(dAtA[i:], m.RequestTypeUrl) + } + if m.RequestStreaming { + dAtA[i] = 0x18 + i++ + if m.RequestStreaming { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i++ + } + if len(m.ResponseTypeUrl) > 0 { + dAtA[i] = 0x22 + i++ + i = encodeVarintApi(dAtA, i, uint64(len(m.ResponseTypeUrl))) + i += copy(dAtA[i:], m.ResponseTypeUrl) + } + if m.ResponseStreaming { + dAtA[i] = 0x28 + i++ + if m.ResponseStreaming { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i++ + } + if len(m.Options) > 0 { + for _, msg := range m.Options { + dAtA[i] = 0x32 + i++ + i = encodeVarintApi(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + if m.Syntax != 0 { + dAtA[i] = 0x38 + i++ + i = encodeVarintApi(dAtA, i, uint64(m.Syntax)) + } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } + return i, nil +} + +func (m *Mixin) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Mixin) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Name) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintApi(dAtA, i, uint64(len(m.Name))) + i += copy(dAtA[i:], m.Name) + } + if len(m.Root) > 0 { + dAtA[i] = 0x12 + i++ + i = encodeVarintApi(dAtA, i, uint64(len(m.Root))) + i += copy(dAtA[i:], m.Root) + } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } + return i, nil +} + +func encodeVarintApi(dAtA []byte, offset int, v uint64) int { + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return offset + 1 +} +func NewPopulatedApi(r randyApi, easy bool) *Api { + this := &Api{} + this.Name = string(randStringApi(r)) + if r.Intn(10) != 0 { + v1 := r.Intn(5) + this.Methods = make([]*Method, v1) + for i := 0; i < v1; i++ { + this.Methods[i] = NewPopulatedMethod(r, easy) + } + } + if r.Intn(10) != 0 { + v2 := r.Intn(5) + this.Options = make([]*Option, v2) + for i := 0; i < v2; i++ { + this.Options[i] = NewPopulatedOption(r, easy) + } + } + this.Version = string(randStringApi(r)) + if r.Intn(10) != 0 { + this.SourceContext = NewPopulatedSourceContext(r, easy) + } + if r.Intn(10) != 0 { + v3 := r.Intn(5) + this.Mixins = make([]*Mixin, v3) + for i := 0; i < v3; i++ { + this.Mixins[i] = NewPopulatedMixin(r, easy) + } + } + this.Syntax = Syntax([]int32{0, 1}[r.Intn(2)]) + if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedApi(r, 8) + } + return this +} + +func NewPopulatedMethod(r randyApi, easy bool) *Method { + this := &Method{} + this.Name = string(randStringApi(r)) + this.RequestTypeUrl = string(randStringApi(r)) + this.RequestStreaming = bool(bool(r.Intn(2) == 0)) + this.ResponseTypeUrl = string(randStringApi(r)) + this.ResponseStreaming = bool(bool(r.Intn(2) == 0)) + if r.Intn(10) != 0 { + v4 := r.Intn(5) + this.Options = make([]*Option, v4) + for i := 0; i < v4; i++ { + this.Options[i] = NewPopulatedOption(r, easy) + } + } + this.Syntax = Syntax([]int32{0, 1}[r.Intn(2)]) + if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedApi(r, 8) + } + return this +} + +func NewPopulatedMixin(r randyApi, easy bool) *Mixin { + this := &Mixin{} + this.Name = string(randStringApi(r)) + this.Root = string(randStringApi(r)) + if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedApi(r, 3) + } + return this +} + +type randyApi interface { + Float32() float32 + Float64() float64 + Int63() int64 + Int31() int32 + Uint32() uint32 + Intn(n int) int +} + +func randUTF8RuneApi(r randyApi) rune { + ru := r.Intn(62) + if ru < 10 { + return rune(ru + 48) + } else if ru < 36 { + return rune(ru + 55) + } + return rune(ru + 61) +} +func randStringApi(r randyApi) string { + v5 := r.Intn(100) + tmps := make([]rune, v5) + for i := 0; i < v5; i++ { + tmps[i] = randUTF8RuneApi(r) + } + return string(tmps) +} +func randUnrecognizedApi(r randyApi, maxFieldNumber int) (dAtA []byte) { + l := r.Intn(5) + for i := 0; i < l; i++ { + wire := r.Intn(4) + if wire == 3 { + wire = 5 + } + fieldNumber := maxFieldNumber + r.Intn(100) + dAtA = randFieldApi(dAtA, r, fieldNumber, wire) + } + return dAtA +} +func randFieldApi(dAtA []byte, r randyApi, fieldNumber int, wire int) []byte { + key := uint32(fieldNumber)<<3 | uint32(wire) + switch wire { + case 0: + dAtA = encodeVarintPopulateApi(dAtA, uint64(key)) + v6 := r.Int63() + if r.Intn(2) == 0 { + v6 *= -1 + } + dAtA = encodeVarintPopulateApi(dAtA, uint64(v6)) + case 1: + dAtA = encodeVarintPopulateApi(dAtA, uint64(key)) + dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) + case 2: + dAtA = encodeVarintPopulateApi(dAtA, uint64(key)) + ll := r.Intn(100) + dAtA = encodeVarintPopulateApi(dAtA, uint64(ll)) + for j := 0; j < ll; j++ { + dAtA = append(dAtA, byte(r.Intn(256))) + } + default: + dAtA = encodeVarintPopulateApi(dAtA, uint64(key)) + dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) + } + return dAtA +} +func encodeVarintPopulateApi(dAtA []byte, v uint64) []byte { + for v >= 1<<7 { + dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80)) + v >>= 7 + } + dAtA = append(dAtA, uint8(v)) + return dAtA +} +func (m *Api) Size() (n int) { + var l int + _ = l + l = len(m.Name) + if l > 0 { + n += 1 + l + sovApi(uint64(l)) + } + if len(m.Methods) > 0 { + for _, e := range m.Methods { + l = e.Size() + n += 1 + l + sovApi(uint64(l)) + } + } + if len(m.Options) > 0 { + for _, e := range m.Options { + l = e.Size() + n += 1 + l + sovApi(uint64(l)) + } + } + l = len(m.Version) + if l > 0 { + n += 1 + l + sovApi(uint64(l)) + } + if m.SourceContext != nil { + l = m.SourceContext.Size() + n += 1 + l + sovApi(uint64(l)) + } + if len(m.Mixins) > 0 { + for _, e := range m.Mixins { + l = e.Size() + n += 1 + l + sovApi(uint64(l)) + } + } + if m.Syntax != 0 { + n += 1 + sovApi(uint64(m.Syntax)) + } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } + return n +} + +func (m *Method) Size() (n int) { + var l int + _ = l + l = len(m.Name) + if l > 0 { + n += 1 + l + sovApi(uint64(l)) + } + l = len(m.RequestTypeUrl) + if l > 0 { + n += 1 + l + sovApi(uint64(l)) + } + if m.RequestStreaming { + n += 2 + } + l = len(m.ResponseTypeUrl) + if l > 0 { + n += 1 + l + sovApi(uint64(l)) + } + if m.ResponseStreaming { + n += 2 + } + if len(m.Options) > 0 { + for _, e := range m.Options { + l = e.Size() + n += 1 + l + sovApi(uint64(l)) + } + } + if m.Syntax != 0 { + n += 1 + sovApi(uint64(m.Syntax)) + } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } + return n +} + +func (m *Mixin) Size() (n int) { + var l int + _ = l + l = len(m.Name) + if l > 0 { + n += 1 + l + sovApi(uint64(l)) + } + l = len(m.Root) + if l > 0 { + n += 1 + l + sovApi(uint64(l)) + } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } + return n +} + +func sovApi(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n +} +func sozApi(x uint64) (n int) { + return sovApi(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (this *Api) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Api{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Methods:` + strings.Replace(fmt.Sprintf("%v", this.Methods), "Method", "Method", 1) + `,`, + `Options:` + strings.Replace(fmt.Sprintf("%v", this.Options), "Option", "Option", 1) + `,`, + `Version:` + fmt.Sprintf("%v", this.Version) + `,`, + `SourceContext:` + strings.Replace(fmt.Sprintf("%v", this.SourceContext), "SourceContext", "SourceContext", 1) + `,`, + `Mixins:` + strings.Replace(fmt.Sprintf("%v", this.Mixins), "Mixin", "Mixin", 1) + `,`, + `Syntax:` + fmt.Sprintf("%v", this.Syntax) + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, + `}`, + }, "") + return s +} +func (this *Method) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Method{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `RequestTypeUrl:` + fmt.Sprintf("%v", this.RequestTypeUrl) + `,`, + `RequestStreaming:` + fmt.Sprintf("%v", this.RequestStreaming) + `,`, + `ResponseTypeUrl:` + fmt.Sprintf("%v", this.ResponseTypeUrl) + `,`, + `ResponseStreaming:` + fmt.Sprintf("%v", this.ResponseStreaming) + `,`, + `Options:` + strings.Replace(fmt.Sprintf("%v", this.Options), "Option", "Option", 1) + `,`, + `Syntax:` + fmt.Sprintf("%v", this.Syntax) + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, + `}`, + }, "") + return s +} +func (this *Mixin) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Mixin{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Root:` + fmt.Sprintf("%v", this.Root) + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, + `}`, + }, "") + return s +} +func valueToStringApi(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} +func (m *Api) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowApi + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Api: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Api: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowApi + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthApi + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Methods", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowApi + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthApi + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Methods = append(m.Methods, &Method{}) + if err := m.Methods[len(m.Methods)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Options", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowApi + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthApi + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Options = append(m.Options, &Option{}) + if err := m.Options[len(m.Options)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowApi + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthApi + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Version = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SourceContext", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowApi + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthApi + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.SourceContext == nil { + m.SourceContext = &SourceContext{} + } + if err := m.SourceContext.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Mixins", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowApi + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthApi + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Mixins = append(m.Mixins, &Mixin{}) + if err := m.Mixins[len(m.Mixins)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 7: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Syntax", wireType) + } + m.Syntax = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowApi + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Syntax |= (Syntax(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipApi(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthApi + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Method) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowApi + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Method: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Method: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowApi + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthApi + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field RequestTypeUrl", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowApi + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthApi + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.RequestTypeUrl = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field RequestStreaming", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowApi + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + m.RequestStreaming = bool(v != 0) + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ResponseTypeUrl", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowApi + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthApi + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ResponseTypeUrl = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ResponseStreaming", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowApi + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + m.ResponseStreaming = bool(v != 0) + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Options", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowApi + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthApi + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Options = append(m.Options, &Option{}) + if err := m.Options[len(m.Options)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 7: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Syntax", wireType) + } + m.Syntax = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowApi + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Syntax |= (Syntax(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipApi(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthApi + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Mixin) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowApi + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Mixin: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Mixin: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowApi + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthApi + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Root", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowApi + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthApi + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Root = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipApi(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthApi + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipApi(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowApi + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowApi + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowApi + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + iNdEx += length + if length < 0 { + return 0, ErrInvalidLengthApi + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowApi + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipApi(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} + +var ( + ErrInvalidLengthApi = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowApi = fmt.Errorf("proto: integer overflow") +) + +func init() { proto.RegisterFile("google/protobuf/api.proto", fileDescriptor_api_658bf9e68d9b66a3) } + +var fileDescriptor_api_658bf9e68d9b66a3 = []byte{ + // 472 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x91, 0x31, 0x6f, 0x13, 0x31, + 0x14, 0xc7, 0xf3, 0xee, 0x92, 0x4b, 0x71, 0x45, 0x0a, 0x46, 0x02, 0x93, 0xc1, 0x3a, 0x55, 0x0c, + 0x27, 0x10, 0x17, 0x51, 0x3e, 0x41, 0x83, 0x50, 0x07, 0x84, 0x88, 0x2e, 0x20, 0x24, 0x96, 0x28, + 0x0d, 0x26, 0x9c, 0x74, 0x67, 0x1f, 0xb6, 0x03, 0xc9, 0x86, 0xc4, 0x37, 0x61, 0x42, 0x8c, 0x7c, + 0x03, 0xb6, 0x8e, 0x1d, 0x19, 0xc9, 0x75, 0x61, 0xec, 0xc8, 0x88, 0xec, 0x3b, 0x37, 0x25, 0x0d, + 0x12, 0xdd, 0xfc, 0xde, 0xff, 0xe7, 0xbf, 0xdf, 0xfb, 0x1b, 0xdd, 0x9e, 0x0a, 0x31, 0xcd, 0x58, + 0xaf, 0x90, 0x42, 0x8b, 0xc3, 0xd9, 0x9b, 0xde, 0xb8, 0x48, 0x63, 0x5b, 0xe0, 0x9d, 0x4a, 0x8a, + 0x9d, 0xd4, 0xbd, 0xb3, 0xce, 0x2a, 0x31, 0x93, 0x13, 0x36, 0x9a, 0x08, 0xae, 0xd9, 0x5c, 0x57, + 0x60, 0xb7, 0xbb, 0x4e, 0xe9, 0x45, 0x51, 0x9b, 0xec, 0x7e, 0xf7, 0x90, 0xbf, 0x5f, 0xa4, 0x18, + 0xa3, 0x26, 0x1f, 0xe7, 0x8c, 0x40, 0x08, 0xd1, 0x95, 0xc4, 0x9e, 0xf1, 0x03, 0xd4, 0xce, 0x99, + 0x7e, 0x2b, 0x5e, 0x2b, 0xe2, 0x85, 0x7e, 0xb4, 0xbd, 0x77, 0x2b, 0x5e, 0x1b, 0x20, 0x7e, 0x6a, + 0xf5, 0xc4, 0x71, 0xe6, 0x8a, 0x28, 0x74, 0x2a, 0xb8, 0x22, 0xfe, 0x3f, 0xae, 0x3c, 0xb3, 0x7a, + 0xe2, 0x38, 0x4c, 0x50, 0xfb, 0x3d, 0x93, 0x2a, 0x15, 0x9c, 0x34, 0xed, 0xe3, 0xae, 0xc4, 0x8f, + 0x51, 0xe7, 0xef, 0x7d, 0x48, 0x2b, 0x84, 0x68, 0x7b, 0x8f, 0x5e, 0xf0, 0x1c, 0x5a, 0xec, 0x51, + 0x45, 0x25, 0x57, 0xd5, 0xf9, 0x12, 0xc7, 0x28, 0xc8, 0xd3, 0x79, 0xca, 0x15, 0x09, 0xec, 0x48, + 0x37, 0x2f, 0x6e, 0x61, 0xe4, 0xa4, 0xa6, 0x70, 0x0f, 0x05, 0x6a, 0xc1, 0xf5, 0x78, 0x4e, 0xda, + 0x21, 0x44, 0x9d, 0x0d, 0x2b, 0x0c, 0xad, 0x9c, 0xd4, 0xd8, 0xee, 0x37, 0x0f, 0x05, 0x55, 0x10, + 0x1b, 0x63, 0x8c, 0xd0, 0x35, 0xc9, 0xde, 0xcd, 0x98, 0xd2, 0x23, 0x13, 0xfc, 0x68, 0x26, 0x33, + 0xe2, 0x59, 0xbd, 0x53, 0xf7, 0x9f, 0x2f, 0x0a, 0xf6, 0x42, 0x66, 0xf8, 0x1e, 0xba, 0xee, 0x48, + 0xa5, 0x25, 0x1b, 0xe7, 0x29, 0x9f, 0x12, 0x3f, 0x84, 0x68, 0x2b, 0x71, 0x16, 0x43, 0xd7, 0xc7, + 0x77, 0x0d, 0xac, 0x0a, 0xc1, 0x15, 0x5b, 0xf9, 0x56, 0x09, 0xee, 0x38, 0xc1, 0x19, 0xdf, 0x47, + 0xf8, 0x8c, 0x5d, 0x39, 0xb7, 0xac, 0xf3, 0x99, 0xcb, 0xca, 0xfa, 0xdc, 0x2f, 0x06, 0xff, 0xf9, + 0x8b, 0x97, 0x0e, 0xad, 0x87, 0x5a, 0x36, 0xf6, 0x8d, 0x91, 0x61, 0xd4, 0x94, 0x42, 0xe8, 0x3a, + 0x26, 0x7b, 0xee, 0x7f, 0x82, 0xe3, 0x25, 0x6d, 0xfc, 0x58, 0xd2, 0xc6, 0xe9, 0x92, 0xc2, 0xef, + 0x25, 0x85, 0x8f, 0x25, 0x85, 0x2f, 0x25, 0x85, 0xa3, 0x92, 0xc2, 0x71, 0x49, 0xe1, 0x67, 0x49, + 0xe1, 0x57, 0x49, 0x1b, 0xa7, 0xa6, 0x7f, 0x42, 0xe1, 0xe8, 0x84, 0x02, 0xba, 0x31, 0x11, 0xf9, + 0xfa, 0x2c, 0xfd, 0xad, 0xfd, 0x22, 0x1d, 0x98, 0x62, 0x00, 0xaf, 0x5a, 0x26, 0x3c, 0xf5, 0xd9, + 0xf3, 0x0f, 0x06, 0xfd, 0xaf, 0x1e, 0x3d, 0xa8, 0xd0, 0x81, 0x1b, 0xfb, 0x25, 0xcb, 0xb2, 0x27, + 0x5c, 0x7c, 0xe0, 0x26, 0x4b, 0x75, 0x18, 0x58, 0x8f, 0x87, 0x7f, 0x02, 0x00, 0x00, 0xff, 0xff, + 0x20, 0x4e, 0x03, 0x8e, 0xa6, 0x03, 0x00, 0x00, +} diff --git a/vendor/github.com/gogo/protobuf/types/duration.pb.go b/vendor/github.com/gogo/protobuf/types/duration.pb.go index ee9deacfd..39bb7a2da 100644 --- a/vendor/github.com/gogo/protobuf/types/duration.pb.go +++ b/vendor/github.com/gogo/protobuf/types/duration.pb.go @@ -1,21 +1,14 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: duration.proto +// source: google/protobuf/duration.proto -/* - Package types is a generated protocol buffer package. - - It is generated from these files: - duration.proto - - It has these top-level messages: - Duration -*/ package types import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" +import bytes "bytes" + import strings "strings" import reflect "reflect" @@ -103,13 +96,44 @@ type Duration struct { // of one second or more, a non-zero value for the `nanos` field must be // of the same sign as the `seconds` field. Must be from -999,999,999 // to +999,999,999 inclusive. - Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"` + Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *Duration) Reset() { *m = Duration{} } -func (*Duration) ProtoMessage() {} -func (*Duration) Descriptor() ([]byte, []int) { return fileDescriptorDuration, []int{0} } -func (*Duration) XXX_WellKnownType() string { return "Duration" } +func (m *Duration) Reset() { *m = Duration{} } +func (*Duration) ProtoMessage() {} +func (*Duration) Descriptor() ([]byte, []int) { + return fileDescriptor_duration_7f04bf66a647e6f6, []int{0} +} +func (*Duration) XXX_WellKnownType() string { return "Duration" } +func (m *Duration) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Duration) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Duration.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *Duration) XXX_Merge(src proto.Message) { + xxx_messageInfo_Duration.Merge(dst, src) +} +func (m *Duration) XXX_Size() int { + return m.Size() +} +func (m *Duration) XXX_DiscardUnknown() { + xxx_messageInfo_Duration.DiscardUnknown(m) +} + +var xxx_messageInfo_Duration proto.InternalMessageInfo func (m *Duration) GetSeconds() int64 { if m != nil { @@ -125,6 +149,9 @@ func (m *Duration) GetNanos() int32 { return 0 } +func (*Duration) XXX_MessageName() string { + return "google.protobuf.Duration" +} func init() { proto.RegisterType((*Duration)(nil), "google.protobuf.Duration") } @@ -165,6 +192,9 @@ func (this *Duration) Compare(that interface{}) int { } return 1 } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } return 0 } func (this *Duration) Equal(that interface{}) bool { @@ -192,6 +222,9 @@ func (this *Duration) Equal(that interface{}) bool { if this.Nanos != that1.Nanos { return false } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } return true } func (this *Duration) GoString() string { @@ -202,6 +235,9 @@ func (this *Duration) GoString() string { s = append(s, "&types.Duration{") s = append(s, "Seconds: "+fmt.Sprintf("%#v", this.Seconds)+",\n") s = append(s, "Nanos: "+fmt.Sprintf("%#v", this.Nanos)+",\n") + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } s = append(s, "}") return strings.Join(s, "") } @@ -238,6 +274,9 @@ func (m *Duration) MarshalTo(dAtA []byte) (int, error) { i++ i = encodeVarintDuration(dAtA, i, uint64(m.Nanos)) } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } return i, nil } @@ -259,6 +298,9 @@ func (m *Duration) Size() (n int) { if m.Nanos != 0 { n += 1 + sovDuration(uint64(m.Nanos)) } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } return n } @@ -354,6 +396,7 @@ func (m *Duration) Unmarshal(dAtA []byte) error { if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } @@ -468,21 +511,24 @@ var ( ErrIntOverflowDuration = fmt.Errorf("proto: integer overflow") ) -func init() { proto.RegisterFile("duration.proto", fileDescriptorDuration) } +func init() { + proto.RegisterFile("google/protobuf/duration.proto", fileDescriptor_duration_7f04bf66a647e6f6) +} -var fileDescriptorDuration = []byte{ - // 203 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x4b, 0x29, 0x2d, 0x4a, - 0x2c, 0xc9, 0xcc, 0xcf, 0xd3, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x4f, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0x85, 0xf0, 0x92, 0x4a, 0xd3, 0x94, 0xac, 0xb8, 0x38, 0x5c, 0xa0, 0x4a, 0x84, 0x24, - 0xb8, 0xd8, 0x8b, 0x53, 0x93, 0xf3, 0xf3, 0x52, 0x8a, 0x25, 0x18, 0x15, 0x18, 0x35, 0x98, 0x83, - 0x60, 0x5c, 0x21, 0x11, 0x2e, 0xd6, 0xbc, 0xc4, 0xbc, 0xfc, 0x62, 0x09, 0x26, 0x05, 0x46, 0x0d, - 0xd6, 0x20, 0x08, 0xc7, 0xa9, 0xfe, 0xc2, 0x43, 0x39, 0x86, 0x1b, 0x0f, 0xe5, 0x18, 0x3e, 0x3c, - 0x94, 0x63, 0x5c, 0xf1, 0x48, 0x8e, 0xf1, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, - 0x3c, 0x92, 0x63, 0x7c, 0xf1, 0x48, 0x8e, 0xe1, 0xc3, 0x23, 0x39, 0xc6, 0x15, 0x8f, 0xe5, 0x18, - 0xb9, 0x84, 0x93, 0xf3, 0x73, 0xf5, 0xd0, 0xac, 0x76, 0xe2, 0x85, 0x59, 0x1c, 0x00, 0x12, 0x09, - 0x60, 0x8c, 0x62, 0x2d, 0xa9, 0x2c, 0x48, 0x2d, 0xfe, 0xc1, 0xc8, 0xb8, 0x88, 0x89, 0xd9, 0x3d, - 0xc0, 0x69, 0x15, 0x93, 0x9c, 0x3b, 0x44, 0x4b, 0x00, 0x54, 0x8b, 0x5e, 0x78, 0x6a, 0x4e, 0x8e, - 0x77, 0x5e, 0x7e, 0x79, 0x5e, 0x08, 0x48, 0x65, 0x12, 0x1b, 0xd8, 0x2c, 0x63, 0x40, 0x00, 0x00, - 0x00, 0xff, 0xff, 0x9d, 0x5a, 0x25, 0xa5, 0xe6, 0x00, 0x00, 0x00, +var fileDescriptor_duration_7f04bf66a647e6f6 = []byte{ + // 215 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4b, 0xcf, 0xcf, 0x4f, + 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0x29, 0x2d, 0x4a, + 0x2c, 0xc9, 0xcc, 0xcf, 0xd3, 0x03, 0x8b, 0x08, 0xf1, 0x43, 0xe4, 0xf5, 0x60, 0xf2, 0x4a, 0x56, + 0x5c, 0x1c, 0x2e, 0x50, 0x25, 0x42, 0x12, 0x5c, 0xec, 0xc5, 0xa9, 0xc9, 0xf9, 0x79, 0x29, 0xc5, + 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0xcc, 0x41, 0x30, 0xae, 0x90, 0x08, 0x17, 0x6b, 0x5e, 0x62, 0x5e, + 0x7e, 0xb1, 0x04, 0x93, 0x02, 0xa3, 0x06, 0x6b, 0x10, 0x84, 0xe3, 0xd4, 0xcc, 0x78, 0xe1, 0xa1, + 0x1c, 0xc3, 0x8d, 0x87, 0x72, 0x0c, 0x1f, 0x1e, 0xca, 0x31, 0xae, 0x78, 0x24, 0xc7, 0x78, 0xe2, + 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0xbe, 0x78, 0x24, 0xc7, 0xf0, + 0xe1, 0x91, 0x1c, 0xe3, 0x8a, 0xc7, 0x72, 0x8c, 0x27, 0x1e, 0xcb, 0x31, 0x72, 0x09, 0x27, 0xe7, + 0xe7, 0xea, 0xa1, 0xd9, 0xef, 0xc4, 0x0b, 0xb3, 0x3d, 0x00, 0x24, 0x12, 0xc0, 0x18, 0xc5, 0x5a, + 0x52, 0x59, 0x90, 0x5a, 0xfc, 0x83, 0x91, 0x71, 0x11, 0x13, 0xb3, 0x7b, 0x80, 0xd3, 0x2a, 0x26, + 0x39, 0x77, 0x88, 0x96, 0x00, 0xa8, 0x16, 0xbd, 0xf0, 0xd4, 0x9c, 0x1c, 0xef, 0xbc, 0xfc, 0xf2, + 0xbc, 0x10, 0x90, 0xca, 0x24, 0x36, 0xb0, 0x59, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x7d, + 0xb1, 0xa3, 0x66, 0xfb, 0x00, 0x00, 0x00, } diff --git a/vendor/github.com/gogo/protobuf/types/empty.pb.go b/vendor/github.com/gogo/protobuf/types/empty.pb.go index e7018b905..db58ac670 100644 --- a/vendor/github.com/gogo/protobuf/types/empty.pb.go +++ b/vendor/github.com/gogo/protobuf/types/empty.pb.go @@ -1,21 +1,14 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: empty.proto +// source: google/protobuf/empty.proto -/* -Package types is a generated protocol buffer package. - -It is generated from these files: - empty.proto - -It has these top-level messages: - Empty -*/ package types import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" +import bytes "bytes" + import strings "strings" import reflect "reflect" @@ -42,13 +35,47 @@ const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package // // The JSON representation for `Empty` is empty JSON object `{}`. type Empty struct { + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *Empty) Reset() { *m = Empty{} } -func (*Empty) ProtoMessage() {} -func (*Empty) Descriptor() ([]byte, []int) { return fileDescriptorEmpty, []int{0} } -func (*Empty) XXX_WellKnownType() string { return "Empty" } +func (m *Empty) Reset() { *m = Empty{} } +func (*Empty) ProtoMessage() {} +func (*Empty) Descriptor() ([]byte, []int) { + return fileDescriptor_empty_fa64318be3e23895, []int{0} +} +func (*Empty) XXX_WellKnownType() string { return "Empty" } +func (m *Empty) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Empty) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Empty.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *Empty) XXX_Merge(src proto.Message) { + xxx_messageInfo_Empty.Merge(dst, src) +} +func (m *Empty) XXX_Size() int { + return m.Size() +} +func (m *Empty) XXX_DiscardUnknown() { + xxx_messageInfo_Empty.DiscardUnknown(m) +} + +var xxx_messageInfo_Empty proto.InternalMessageInfo +func (*Empty) XXX_MessageName() string { + return "google.protobuf.Empty" +} func init() { proto.RegisterType((*Empty)(nil), "google.protobuf.Empty") } @@ -77,6 +104,9 @@ func (this *Empty) Compare(that interface{}) int { } else if this == nil { return -1 } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } return 0 } func (this *Empty) Equal(that interface{}) bool { @@ -98,6 +128,9 @@ func (this *Empty) Equal(that interface{}) bool { } else if this == nil { return false } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } return true } func (this *Empty) GoString() string { @@ -106,6 +139,9 @@ func (this *Empty) GoString() string { } s := make([]string, 0, 4) s = append(s, "&types.Empty{") + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } s = append(s, "}") return strings.Join(s, "") } @@ -132,6 +168,9 @@ func (m *Empty) MarshalTo(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } return i, nil } @@ -147,6 +186,7 @@ func encodeVarintEmpty(dAtA []byte, offset int, v uint64) int { func NewPopulatedEmpty(r randyEmpty, easy bool) *Empty { this := &Empty{} if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedEmpty(r, 1) } return this } @@ -226,6 +266,9 @@ func encodeVarintPopulateEmpty(dAtA []byte, v uint64) []byte { func (m *Empty) Size() (n int) { var l int _ = l + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } return n } @@ -247,6 +290,7 @@ func (this *Empty) String() string { return "nil" } s := strings.Join([]string{`&Empty{`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s @@ -300,6 +344,7 @@ func (m *Empty) Unmarshal(dAtA []byte) error { if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } @@ -414,19 +459,20 @@ var ( ErrIntOverflowEmpty = fmt.Errorf("proto: integer overflow") ) -func init() { proto.RegisterFile("empty.proto", fileDescriptorEmpty) } +func init() { proto.RegisterFile("google/protobuf/empty.proto", fileDescriptor_empty_fa64318be3e23895) } -var fileDescriptorEmpty = []byte{ - // 169 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x4e, 0xcd, 0x2d, 0x28, - 0xa9, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x4f, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0x85, - 0xf0, 0x92, 0x4a, 0xd3, 0x94, 0xd8, 0xb9, 0x58, 0x5d, 0x41, 0xf2, 0x4e, 0x2d, 0x8c, 0x17, 0x1e, - 0xca, 0x31, 0xdc, 0x78, 0x28, 0xc7, 0xf0, 0xe1, 0xa1, 0x1c, 0xe3, 0x8f, 0x87, 0x72, 0x8c, 0x0d, - 0x8f, 0xe4, 0x18, 0x57, 0x3c, 0x92, 0x63, 0x3c, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, - 0x07, 0x8f, 0xe4, 0x18, 0x5f, 0x3c, 0x92, 0x63, 0xf8, 0x00, 0x12, 0x7f, 0x2c, 0xc7, 0xc8, 0x25, - 0x9c, 0x9c, 0x9f, 0xab, 0x87, 0x66, 0xa0, 0x13, 0x17, 0xd8, 0xb8, 0x00, 0x10, 0x37, 0x80, 0x31, - 0x8a, 0xb5, 0xa4, 0xb2, 0x20, 0xb5, 0xf8, 0x07, 0x23, 0xe3, 0x22, 0x26, 0x66, 0xf7, 0x00, 0xa7, - 0x55, 0x4c, 0x72, 0xee, 0x10, 0xf5, 0x01, 0x50, 0xf5, 0x7a, 0xe1, 0xa9, 0x39, 0x39, 0xde, 0x79, - 0xf9, 0xe5, 0x79, 0x21, 0x20, 0x95, 0x49, 0x6c, 0x60, 0x83, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, - 0xff, 0x7c, 0xa8, 0xf0, 0xc4, 0xb6, 0x00, 0x00, 0x00, +var fileDescriptor_empty_fa64318be3e23895 = []byte{ + // 180 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4e, 0xcf, 0xcf, 0x4f, + 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcd, 0x2d, 0x28, + 0xa9, 0xd4, 0x03, 0x73, 0x85, 0xf8, 0x21, 0x92, 0x7a, 0x30, 0x49, 0x25, 0x76, 0x2e, 0x56, 0x57, + 0x90, 0xbc, 0x53, 0x07, 0xe3, 0x85, 0x87, 0x72, 0x0c, 0x37, 0x1e, 0xca, 0x31, 0x7c, 0x78, 0x28, + 0xc7, 0xf8, 0xe3, 0xa1, 0x1c, 0x63, 0xc3, 0x23, 0x39, 0xc6, 0x15, 0x8f, 0xe4, 0x18, 0x4f, 0x3c, + 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x17, 0x8f, 0xe4, 0x18, 0x3e, + 0x80, 0xc4, 0x1f, 0xcb, 0x31, 0x9e, 0x78, 0x2c, 0xc7, 0xc8, 0x25, 0x9c, 0x9c, 0x9f, 0xab, 0x87, + 0x66, 0xa8, 0x13, 0x17, 0xd8, 0xc8, 0x00, 0x10, 0x37, 0x80, 0x31, 0x8a, 0xb5, 0xa4, 0xb2, 0x20, + 0xb5, 0xf8, 0x07, 0x23, 0xe3, 0x22, 0x26, 0x66, 0xf7, 0x00, 0xa7, 0x55, 0x4c, 0x72, 0xee, 0x10, + 0xf5, 0x01, 0x50, 0xf5, 0x7a, 0xe1, 0xa9, 0x39, 0x39, 0xde, 0x79, 0xf9, 0xe5, 0x79, 0x21, 0x20, + 0x95, 0x49, 0x6c, 0x60, 0x83, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0x07, 0x8c, 0xf8, 0x26, + 0xca, 0x00, 0x00, 0x00, } diff --git a/vendor/github.com/gogo/protobuf/types/field_mask.pb.go b/vendor/github.com/gogo/protobuf/types/field_mask.pb.go index 22e8b4f0d..13d61762e 100644 --- a/vendor/github.com/gogo/protobuf/types/field_mask.pb.go +++ b/vendor/github.com/gogo/protobuf/types/field_mask.pb.go @@ -1,21 +1,14 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: field_mask.proto +// source: google/protobuf/field_mask.proto -/* -Package types is a generated protocol buffer package. - -It is generated from these files: - field_mask.proto - -It has these top-level messages: - FieldMask -*/ package types import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" +import bytes "bytes" + import strings "strings" import reflect "reflect" @@ -233,14 +226,51 @@ const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package // // Note that oneof type names ("test_oneof" in this case) cannot be used in // paths. +// +// ## Field Mask Verification +// +// The implementation of the all the API methods, which have any FieldMask type +// field in the request, should verify the included field paths, and return +// `INVALID_ARGUMENT` error if any path is duplicated or unmappable. type FieldMask struct { // The set of field mask paths. - Paths []string `protobuf:"bytes,1,rep,name=paths" json:"paths,omitempty"` + Paths []string `protobuf:"bytes,1,rep,name=paths" json:"paths,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *FieldMask) Reset() { *m = FieldMask{} } -func (*FieldMask) ProtoMessage() {} -func (*FieldMask) Descriptor() ([]byte, []int) { return fileDescriptorFieldMask, []int{0} } +func (m *FieldMask) Reset() { *m = FieldMask{} } +func (*FieldMask) ProtoMessage() {} +func (*FieldMask) Descriptor() ([]byte, []int) { + return fileDescriptor_field_mask_3abe20b2f0d4cb1c, []int{0} +} +func (m *FieldMask) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *FieldMask) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_FieldMask.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *FieldMask) XXX_Merge(src proto.Message) { + xxx_messageInfo_FieldMask.Merge(dst, src) +} +func (m *FieldMask) XXX_Size() int { + return m.Size() +} +func (m *FieldMask) XXX_DiscardUnknown() { + xxx_messageInfo_FieldMask.DiscardUnknown(m) +} + +var xxx_messageInfo_FieldMask proto.InternalMessageInfo func (m *FieldMask) GetPaths() []string { if m != nil { @@ -249,6 +279,9 @@ func (m *FieldMask) GetPaths() []string { return nil } +func (*FieldMask) XXX_MessageName() string { + return "google.protobuf.FieldMask" +} func init() { proto.RegisterType((*FieldMask)(nil), "google.protobuf.FieldMask") } @@ -291,6 +324,9 @@ func (this *FieldMask) Compare(that interface{}) int { return 1 } } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } return 0 } func (this *FieldMask) Equal(that interface{}) bool { @@ -320,6 +356,9 @@ func (this *FieldMask) Equal(that interface{}) bool { return false } } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } return true } func (this *FieldMask) GoString() string { @@ -329,6 +368,9 @@ func (this *FieldMask) GoString() string { s := make([]string, 0, 5) s = append(s, "&types.FieldMask{") s = append(s, "Paths: "+fmt.Sprintf("%#v", this.Paths)+",\n") + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } s = append(s, "}") return strings.Join(s, "") } @@ -370,6 +412,9 @@ func (m *FieldMask) MarshalTo(dAtA []byte) (int, error) { i += copy(dAtA[i:], s) } } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } return i, nil } @@ -390,6 +435,7 @@ func NewPopulatedFieldMask(r randyFieldMask, easy bool) *FieldMask { this.Paths[i] = string(randStringFieldMask(r)) } if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedFieldMask(r, 2) } return this } @@ -475,6 +521,9 @@ func (m *FieldMask) Size() (n int) { n += 1 + l + sovFieldMask(uint64(l)) } } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } return n } @@ -497,6 +546,7 @@ func (this *FieldMask) String() string { } s := strings.Join([]string{`&FieldMask{`, `Paths:` + fmt.Sprintf("%v", this.Paths) + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s @@ -579,6 +629,7 @@ func (m *FieldMask) Unmarshal(dAtA []byte) error { if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } @@ -693,21 +744,23 @@ var ( ErrIntOverflowFieldMask = fmt.Errorf("proto: integer overflow") ) -func init() { proto.RegisterFile("field_mask.proto", fileDescriptorFieldMask) } +func init() { + proto.RegisterFile("google/protobuf/field_mask.proto", fileDescriptor_field_mask_3abe20b2f0d4cb1c) +} -var fileDescriptorFieldMask = []byte{ - // 193 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x48, 0xcb, 0x4c, 0xcd, - 0x49, 0x89, 0xcf, 0x4d, 0x2c, 0xce, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x4f, 0xcf, - 0xcf, 0x4f, 0xcf, 0x49, 0x85, 0xf0, 0x92, 0x4a, 0xd3, 0x94, 0x14, 0xb9, 0x38, 0xdd, 0x40, 0x8a, - 0x7c, 0x13, 0x8b, 0xb3, 0x85, 0x44, 0xb8, 0x58, 0x0b, 0x12, 0x4b, 0x32, 0x8a, 0x25, 0x18, 0x15, - 0x98, 0x35, 0x38, 0x83, 0x20, 0x1c, 0xa7, 0x56, 0xc6, 0x0b, 0x0f, 0xe5, 0x18, 0x6e, 0x3c, 0x94, - 0x63, 0xf8, 0xf0, 0x50, 0x8e, 0xf1, 0xc7, 0x43, 0x39, 0xc6, 0x86, 0x47, 0x72, 0x8c, 0x2b, 0x1e, - 0xc9, 0x31, 0x9e, 0x78, 0x24, 0xc7, 0x78, 0xe1, 0x91, 0x1c, 0xe3, 0x83, 0x47, 0x72, 0x8c, 0x2f, - 0x1e, 0xc9, 0x31, 0x7c, 0x00, 0x89, 0x3f, 0x96, 0x63, 0xe4, 0x12, 0x4e, 0xce, 0xcf, 0xd5, 0x43, - 0xb3, 0xca, 0x89, 0x0f, 0x6e, 0x51, 0x00, 0x48, 0x28, 0x80, 0x31, 0x8a, 0xb5, 0xa4, 0xb2, 0x20, - 0xb5, 0x78, 0x11, 0x13, 0xb3, 0x7b, 0x80, 0xd3, 0x2a, 0x26, 0x39, 0x77, 0x88, 0x86, 0x00, 0xa8, - 0x06, 0xbd, 0xf0, 0xd4, 0x9c, 0x1c, 0xef, 0xbc, 0xfc, 0xf2, 0xbc, 0x10, 0x90, 0xb2, 0x24, 0x36, - 0xb0, 0x49, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x51, 0x31, 0x89, 0xb5, 0xd6, 0x00, 0x00, - 0x00, +var fileDescriptor_field_mask_3abe20b2f0d4cb1c = []byte{ + // 204 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x48, 0xcf, 0xcf, 0x4f, + 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcb, 0x4c, 0xcd, + 0x49, 0x89, 0xcf, 0x4d, 0x2c, 0xce, 0xd6, 0x03, 0x8b, 0x09, 0xf1, 0x43, 0x54, 0xe8, 0xc1, 0x54, + 0x28, 0x29, 0x72, 0x71, 0xba, 0x81, 0x14, 0xf9, 0x26, 0x16, 0x67, 0x0b, 0x89, 0x70, 0xb1, 0x16, + 0x24, 0x96, 0x64, 0x14, 0x4b, 0x30, 0x2a, 0x30, 0x6b, 0x70, 0x06, 0x41, 0x38, 0x4e, 0x9d, 0x8c, + 0x17, 0x1e, 0xca, 0x31, 0xdc, 0x78, 0x28, 0xc7, 0xf0, 0xe1, 0xa1, 0x1c, 0xe3, 0x8f, 0x87, 0x72, + 0x8c, 0x0d, 0x8f, 0xe4, 0x18, 0x57, 0x3c, 0x92, 0x63, 0x3c, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, + 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x5f, 0x3c, 0x92, 0x63, 0xf8, 0x00, 0x12, 0x7f, 0x2c, 0xc7, + 0x78, 0xe2, 0xb1, 0x1c, 0x23, 0x97, 0x70, 0x72, 0x7e, 0xae, 0x1e, 0x9a, 0x75, 0x4e, 0x7c, 0x70, + 0xcb, 0x02, 0x40, 0x42, 0x01, 0x8c, 0x51, 0xac, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x8b, 0x98, 0x98, + 0xdd, 0x03, 0x9c, 0x56, 0x31, 0xc9, 0xb9, 0x43, 0x34, 0x04, 0x40, 0x35, 0xe8, 0x85, 0xa7, 0xe6, + 0xe4, 0x78, 0xe7, 0xe5, 0x97, 0xe7, 0x85, 0x80, 0x94, 0x25, 0xb1, 0x81, 0x4d, 0x32, 0x06, 0x04, + 0x00, 0x00, 0xff, 0xff, 0xea, 0xa6, 0x08, 0xbf, 0xea, 0x00, 0x00, 0x00, } diff --git a/vendor/github.com/gogo/protobuf/types/source_context.pb.go b/vendor/github.com/gogo/protobuf/types/source_context.pb.go new file mode 100644 index 000000000..0c1daf729 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/types/source_context.pb.go @@ -0,0 +1,535 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: google/protobuf/source_context.proto + +package types + +import proto "github.com/gogo/protobuf/proto" +import fmt "fmt" +import math "math" + +import bytes "bytes" + +import strings "strings" +import reflect "reflect" + +import io "io" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package + +// `SourceContext` represents information about the source of a +// protobuf element, like the file in which it is defined. +type SourceContext struct { + // The path-qualified name of the .proto file that contained the associated + // protobuf element. For example: `"google/protobuf/source_context.proto"`. + FileName string `protobuf:"bytes,1,opt,name=file_name,json=fileName,proto3" json:"file_name,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *SourceContext) Reset() { *m = SourceContext{} } +func (*SourceContext) ProtoMessage() {} +func (*SourceContext) Descriptor() ([]byte, []int) { + return fileDescriptor_source_context_d25fd312302631f7, []int{0} +} +func (m *SourceContext) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *SourceContext) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_SourceContext.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *SourceContext) XXX_Merge(src proto.Message) { + xxx_messageInfo_SourceContext.Merge(dst, src) +} +func (m *SourceContext) XXX_Size() int { + return m.Size() +} +func (m *SourceContext) XXX_DiscardUnknown() { + xxx_messageInfo_SourceContext.DiscardUnknown(m) +} + +var xxx_messageInfo_SourceContext proto.InternalMessageInfo + +func (m *SourceContext) GetFileName() string { + if m != nil { + return m.FileName + } + return "" +} + +func (*SourceContext) XXX_MessageName() string { + return "google.protobuf.SourceContext" +} +func init() { + proto.RegisterType((*SourceContext)(nil), "google.protobuf.SourceContext") +} +func (this *SourceContext) Compare(that interface{}) int { + if that == nil { + if this == nil { + return 0 + } + return 1 + } + + that1, ok := that.(*SourceContext) + if !ok { + that2, ok := that.(SourceContext) + if ok { + that1 = &that2 + } else { + return 1 + } + } + if that1 == nil { + if this == nil { + return 0 + } + return 1 + } else if this == nil { + return -1 + } + if this.FileName != that1.FileName { + if this.FileName < that1.FileName { + return -1 + } + return 1 + } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } + return 0 +} +func (this *SourceContext) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*SourceContext) + if !ok { + that2, ok := that.(SourceContext) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.FileName != that1.FileName { + return false + } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } + return true +} +func (this *SourceContext) GoString() string { + if this == nil { + return "nil" + } + s := make([]string, 0, 5) + s = append(s, "&types.SourceContext{") + s = append(s, "FileName: "+fmt.Sprintf("%#v", this.FileName)+",\n") + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } + s = append(s, "}") + return strings.Join(s, "") +} +func valueToGoStringSourceContext(v interface{}, typ string) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv) +} +func (m *SourceContext) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *SourceContext) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.FileName) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintSourceContext(dAtA, i, uint64(len(m.FileName))) + i += copy(dAtA[i:], m.FileName) + } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } + return i, nil +} + +func encodeVarintSourceContext(dAtA []byte, offset int, v uint64) int { + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return offset + 1 +} +func NewPopulatedSourceContext(r randySourceContext, easy bool) *SourceContext { + this := &SourceContext{} + this.FileName = string(randStringSourceContext(r)) + if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedSourceContext(r, 2) + } + return this +} + +type randySourceContext interface { + Float32() float32 + Float64() float64 + Int63() int64 + Int31() int32 + Uint32() uint32 + Intn(n int) int +} + +func randUTF8RuneSourceContext(r randySourceContext) rune { + ru := r.Intn(62) + if ru < 10 { + return rune(ru + 48) + } else if ru < 36 { + return rune(ru + 55) + } + return rune(ru + 61) +} +func randStringSourceContext(r randySourceContext) string { + v1 := r.Intn(100) + tmps := make([]rune, v1) + for i := 0; i < v1; i++ { + tmps[i] = randUTF8RuneSourceContext(r) + } + return string(tmps) +} +func randUnrecognizedSourceContext(r randySourceContext, maxFieldNumber int) (dAtA []byte) { + l := r.Intn(5) + for i := 0; i < l; i++ { + wire := r.Intn(4) + if wire == 3 { + wire = 5 + } + fieldNumber := maxFieldNumber + r.Intn(100) + dAtA = randFieldSourceContext(dAtA, r, fieldNumber, wire) + } + return dAtA +} +func randFieldSourceContext(dAtA []byte, r randySourceContext, fieldNumber int, wire int) []byte { + key := uint32(fieldNumber)<<3 | uint32(wire) + switch wire { + case 0: + dAtA = encodeVarintPopulateSourceContext(dAtA, uint64(key)) + v2 := r.Int63() + if r.Intn(2) == 0 { + v2 *= -1 + } + dAtA = encodeVarintPopulateSourceContext(dAtA, uint64(v2)) + case 1: + dAtA = encodeVarintPopulateSourceContext(dAtA, uint64(key)) + dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) + case 2: + dAtA = encodeVarintPopulateSourceContext(dAtA, uint64(key)) + ll := r.Intn(100) + dAtA = encodeVarintPopulateSourceContext(dAtA, uint64(ll)) + for j := 0; j < ll; j++ { + dAtA = append(dAtA, byte(r.Intn(256))) + } + default: + dAtA = encodeVarintPopulateSourceContext(dAtA, uint64(key)) + dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) + } + return dAtA +} +func encodeVarintPopulateSourceContext(dAtA []byte, v uint64) []byte { + for v >= 1<<7 { + dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80)) + v >>= 7 + } + dAtA = append(dAtA, uint8(v)) + return dAtA +} +func (m *SourceContext) Size() (n int) { + var l int + _ = l + l = len(m.FileName) + if l > 0 { + n += 1 + l + sovSourceContext(uint64(l)) + } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } + return n +} + +func sovSourceContext(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n +} +func sozSourceContext(x uint64) (n int) { + return sovSourceContext(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (this *SourceContext) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&SourceContext{`, + `FileName:` + fmt.Sprintf("%v", this.FileName) + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, + `}`, + }, "") + return s +} +func valueToStringSourceContext(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} +func (m *SourceContext) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowSourceContext + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: SourceContext: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SourceContext: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field FileName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowSourceContext + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthSourceContext + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.FileName = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipSourceContext(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthSourceContext + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipSourceContext(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowSourceContext + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowSourceContext + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowSourceContext + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + iNdEx += length + if length < 0 { + return 0, ErrInvalidLengthSourceContext + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowSourceContext + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipSourceContext(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} + +var ( + ErrInvalidLengthSourceContext = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowSourceContext = fmt.Errorf("proto: integer overflow") +) + +func init() { + proto.RegisterFile("google/protobuf/source_context.proto", fileDescriptor_source_context_d25fd312302631f7) +} + +var fileDescriptor_source_context_d25fd312302631f7 = []byte{ + // 216 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x49, 0xcf, 0xcf, 0x4f, + 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0xce, 0x2f, 0x2d, + 0x4a, 0x4e, 0x8d, 0x4f, 0xce, 0xcf, 0x2b, 0x49, 0xad, 0x28, 0xd1, 0x03, 0x8b, 0x0b, 0xf1, 0x43, + 0x54, 0xe9, 0xc1, 0x54, 0x29, 0xe9, 0x70, 0xf1, 0x06, 0x83, 0x15, 0x3a, 0x43, 0xd4, 0x09, 0x49, + 0x73, 0x71, 0xa6, 0x65, 0xe6, 0xa4, 0xc6, 0xe7, 0x25, 0xe6, 0xa6, 0x4a, 0x30, 0x2a, 0x30, 0x6a, + 0x70, 0x06, 0x71, 0x80, 0x04, 0xfc, 0x12, 0x73, 0x53, 0x9d, 0x7a, 0x19, 0x2f, 0x3c, 0x94, 0x63, + 0xb8, 0xf1, 0x50, 0x8e, 0xe1, 0xc3, 0x43, 0x39, 0xc6, 0x1f, 0x0f, 0xe5, 0x18, 0x1b, 0x1e, 0xc9, + 0x31, 0xae, 0x78, 0x24, 0xc7, 0x78, 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, + 0xc9, 0x31, 0xbe, 0x78, 0x24, 0xc7, 0xf0, 0x01, 0x24, 0xfe, 0x58, 0x8e, 0xf1, 0xc4, 0x63, 0x39, + 0x46, 0x2e, 0xe1, 0xe4, 0xfc, 0x5c, 0x3d, 0x34, 0x9b, 0x9d, 0x84, 0x50, 0xec, 0x0d, 0x00, 0x09, + 0x07, 0x30, 0x46, 0xb1, 0x96, 0x54, 0x16, 0xa4, 0x16, 0x2f, 0x62, 0x62, 0x76, 0x0f, 0x70, 0x5a, + 0xc5, 0x24, 0xe7, 0x0e, 0xd1, 0x14, 0x00, 0xd5, 0xa4, 0x17, 0x9e, 0x9a, 0x93, 0xe3, 0x9d, 0x97, + 0x5f, 0x9e, 0x17, 0x02, 0x52, 0x96, 0xc4, 0x06, 0x36, 0xcd, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, + 0x86, 0x8b, 0x02, 0xb9, 0xfd, 0x00, 0x00, 0x00, +} diff --git a/vendor/github.com/gogo/protobuf/types/struct.pb.go b/vendor/github.com/gogo/protobuf/types/struct.pb.go index 7d5372b03..659f2e5e8 100644 --- a/vendor/github.com/gogo/protobuf/types/struct.pb.go +++ b/vendor/github.com/gogo/protobuf/types/struct.pb.go @@ -1,17 +1,6 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: struct.proto +// source: google/protobuf/struct.proto -/* - Package types is a generated protocol buffer package. - - It is generated from these files: - struct.proto - - It has these top-level messages: - Struct - Value - ListValue -*/ package types import proto "github.com/gogo/protobuf/proto" @@ -20,11 +9,13 @@ import math "math" import strconv "strconv" +import bytes "bytes" + import strings "strings" import reflect "reflect" -import sortkeys "github.com/gogo/protobuf/sortkeys" +import github_com_gogo_protobuf_sortkeys "github.com/gogo/protobuf/sortkeys" -import binary "encoding/binary" +import encoding_binary "encoding/binary" import io "io" @@ -57,8 +48,10 @@ var NullValue_value = map[string]int32{ "NULL_VALUE": 0, } -func (NullValue) EnumDescriptor() ([]byte, []int) { return fileDescriptorStruct, []int{0} } -func (NullValue) XXX_WellKnownType() string { return "NullValue" } +func (NullValue) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_struct_e8dc68d36b73896c, []int{0} +} +func (NullValue) XXX_WellKnownType() string { return "NullValue" } // `Struct` represents a structured data value, consisting of fields // which map to dynamically typed values. In some languages, `Struct` @@ -70,13 +63,44 @@ func (NullValue) XXX_WellKnownType() string { return "NullValue" } // The JSON representation for `Struct` is JSON object. type Struct struct { // Unordered map of dynamically typed values. - Fields map[string]*Value `protobuf:"bytes,1,rep,name=fields" json:"fields,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value"` + Fields map[string]*Value `protobuf:"bytes,1,rep,name=fields" json:"fields,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Struct) Reset() { *m = Struct{} } +func (*Struct) ProtoMessage() {} +func (*Struct) Descriptor() ([]byte, []int) { + return fileDescriptor_struct_e8dc68d36b73896c, []int{0} +} +func (*Struct) XXX_WellKnownType() string { return "Struct" } +func (m *Struct) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Struct) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Struct.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *Struct) XXX_Merge(src proto.Message) { + xxx_messageInfo_Struct.Merge(dst, src) +} +func (m *Struct) XXX_Size() int { + return m.Size() +} +func (m *Struct) XXX_DiscardUnknown() { + xxx_messageInfo_Struct.DiscardUnknown(m) } -func (m *Struct) Reset() { *m = Struct{} } -func (*Struct) ProtoMessage() {} -func (*Struct) Descriptor() ([]byte, []int) { return fileDescriptorStruct, []int{0} } -func (*Struct) XXX_WellKnownType() string { return "Struct" } +var xxx_messageInfo_Struct proto.InternalMessageInfo func (m *Struct) GetFields() map[string]*Value { if m != nil { @@ -85,6 +109,10 @@ func (m *Struct) GetFields() map[string]*Value { return nil } +func (*Struct) XXX_MessageName() string { + return "google.protobuf.Struct" +} + // `Value` represents a dynamically typed value which can be either // null, a number, a string, a boolean, a recursive struct value, or a // list of values. A producer of value is expected to set one of that @@ -101,13 +129,44 @@ type Value struct { // *Value_BoolValue // *Value_StructValue // *Value_ListValue - Kind isValue_Kind `protobuf_oneof:"kind"` + Kind isValue_Kind `protobuf_oneof:"kind"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *Value) Reset() { *m = Value{} } -func (*Value) ProtoMessage() {} -func (*Value) Descriptor() ([]byte, []int) { return fileDescriptorStruct, []int{1} } -func (*Value) XXX_WellKnownType() string { return "Value" } +func (m *Value) Reset() { *m = Value{} } +func (*Value) ProtoMessage() {} +func (*Value) Descriptor() ([]byte, []int) { + return fileDescriptor_struct_e8dc68d36b73896c, []int{1} +} +func (*Value) XXX_WellKnownType() string { return "Value" } +func (m *Value) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Value) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Value.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *Value) XXX_Merge(src proto.Message) { + xxx_messageInfo_Value.Merge(dst, src) +} +func (m *Value) XXX_Size() int { + return m.Size() +} +func (m *Value) XXX_DiscardUnknown() { + xxx_messageInfo_Value.DiscardUnknown(m) +} + +var xxx_messageInfo_Value proto.InternalMessageInfo type isValue_Kind interface { isValue_Kind() @@ -297,26 +356,26 @@ func _Value_OneofSizer(msg proto.Message) (n int) { // kind switch x := m.Kind.(type) { case *Value_NullValue: - n += proto.SizeVarint(1<<3 | proto.WireVarint) + n += 1 // tag and wire n += proto.SizeVarint(uint64(x.NullValue)) case *Value_NumberValue: - n += proto.SizeVarint(2<<3 | proto.WireFixed64) + n += 1 // tag and wire n += 8 case *Value_StringValue: - n += proto.SizeVarint(3<<3 | proto.WireBytes) + n += 1 // tag and wire n += proto.SizeVarint(uint64(len(x.StringValue))) n += len(x.StringValue) case *Value_BoolValue: - n += proto.SizeVarint(4<<3 | proto.WireVarint) + n += 1 // tag and wire n += 1 case *Value_StructValue: s := proto.Size(x.StructValue) - n += proto.SizeVarint(5<<3 | proto.WireBytes) + n += 1 // tag and wire n += proto.SizeVarint(uint64(s)) n += s case *Value_ListValue: s := proto.Size(x.ListValue) - n += proto.SizeVarint(6<<3 | proto.WireBytes) + n += 1 // tag and wire n += proto.SizeVarint(uint64(s)) n += s case nil: @@ -326,18 +385,53 @@ func _Value_OneofSizer(msg proto.Message) (n int) { return n } +func (*Value) XXX_MessageName() string { + return "google.protobuf.Value" +} + // `ListValue` is a wrapper around a repeated field of values. // // The JSON representation for `ListValue` is JSON array. type ListValue struct { // Repeated field of dynamically typed values. - Values []*Value `protobuf:"bytes,1,rep,name=values" json:"values,omitempty"` + Values []*Value `protobuf:"bytes,1,rep,name=values" json:"values,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *ListValue) Reset() { *m = ListValue{} } -func (*ListValue) ProtoMessage() {} -func (*ListValue) Descriptor() ([]byte, []int) { return fileDescriptorStruct, []int{2} } -func (*ListValue) XXX_WellKnownType() string { return "ListValue" } +func (m *ListValue) Reset() { *m = ListValue{} } +func (*ListValue) ProtoMessage() {} +func (*ListValue) Descriptor() ([]byte, []int) { + return fileDescriptor_struct_e8dc68d36b73896c, []int{2} +} +func (*ListValue) XXX_WellKnownType() string { return "ListValue" } +func (m *ListValue) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ListValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ListValue.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *ListValue) XXX_Merge(src proto.Message) { + xxx_messageInfo_ListValue.Merge(dst, src) +} +func (m *ListValue) XXX_Size() int { + return m.Size() +} +func (m *ListValue) XXX_DiscardUnknown() { + xxx_messageInfo_ListValue.DiscardUnknown(m) +} + +var xxx_messageInfo_ListValue proto.InternalMessageInfo func (m *ListValue) GetValues() []*Value { if m != nil { @@ -346,8 +440,12 @@ func (m *ListValue) GetValues() []*Value { return nil } +func (*ListValue) XXX_MessageName() string { + return "google.protobuf.ListValue" +} func init() { proto.RegisterType((*Struct)(nil), "google.protobuf.Struct") + proto.RegisterMapType((map[string]*Value)(nil), "google.protobuf.Struct.FieldsEntry") proto.RegisterType((*Value)(nil), "google.protobuf.Value") proto.RegisterType((*ListValue)(nil), "google.protobuf.ListValue") proto.RegisterEnum("google.protobuf.NullValue", NullValue_name, NullValue_value) @@ -386,6 +484,9 @@ func (this *Struct) Equal(that interface{}) bool { return false } } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } return true } func (this *Value) Equal(that interface{}) bool { @@ -416,6 +517,9 @@ func (this *Value) Equal(that interface{}) bool { } else if !this.Kind.Equal(that1.Kind) { return false } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } return true } func (this *Value_NullValue) Equal(that interface{}) bool { @@ -589,6 +693,9 @@ func (this *ListValue) Equal(that interface{}) bool { return false } } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } return true } func (this *Struct) GoString() string { @@ -601,7 +708,7 @@ func (this *Struct) GoString() string { for k := range this.Fields { keysForFields = append(keysForFields, k) } - sortkeys.Strings(keysForFields) + github_com_gogo_protobuf_sortkeys.Strings(keysForFields) mapStringForFields := "map[string]*Value{" for _, k := range keysForFields { mapStringForFields += fmt.Sprintf("%#v: %#v,", k, this.Fields[k]) @@ -610,6 +717,9 @@ func (this *Struct) GoString() string { if this.Fields != nil { s = append(s, "Fields: "+mapStringForFields+",\n") } + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } s = append(s, "}") return strings.Join(s, "") } @@ -622,6 +732,9 @@ func (this *Value) GoString() string { if this.Kind != nil { s = append(s, "Kind: "+fmt.Sprintf("%#v", this.Kind)+",\n") } + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } s = append(s, "}") return strings.Join(s, "") } @@ -682,6 +795,9 @@ func (this *ListValue) GoString() string { if this.Values != nil { s = append(s, "Values: "+fmt.Sprintf("%#v", this.Values)+",\n") } + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } s = append(s, "}") return strings.Join(s, "") } @@ -736,6 +852,9 @@ func (m *Struct) MarshalTo(dAtA []byte) (int, error) { } } } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } return i, nil } @@ -761,6 +880,9 @@ func (m *Value) MarshalTo(dAtA []byte) (int, error) { } i += nn2 } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } return i, nil } @@ -775,7 +897,7 @@ func (m *Value_NumberValue) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x11 i++ - binary.LittleEndian.PutUint64(dAtA[i:], uint64(math.Float64bits(float64(m.NumberValue)))) + encoding_binary.LittleEndian.PutUint64(dAtA[i:], uint64(math.Float64bits(float64(m.NumberValue)))) i += 8 return i, nil } @@ -854,6 +976,9 @@ func (m *ListValue) MarshalTo(dAtA []byte) (int, error) { i += n } } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } return i, nil } @@ -876,6 +1001,7 @@ func NewPopulatedStruct(r randyStruct, easy bool) *Struct { } } if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedStruct(r, 2) } return this } @@ -898,6 +1024,7 @@ func NewPopulatedValue(r randyStruct, easy bool) *Value { this.Kind = NewPopulatedValue_ListValue(r, easy) } if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedStruct(r, 7) } return this } @@ -945,6 +1072,7 @@ func NewPopulatedListValue(r randyStruct, easy bool) *ListValue { } } if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedStruct(r, 2) } return this } @@ -1037,6 +1165,9 @@ func (m *Struct) Size() (n int) { n += mapEntrySize + 1 + sovStruct(uint64(mapEntrySize)) } } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } return n } @@ -1046,6 +1177,9 @@ func (m *Value) Size() (n int) { if m.Kind != nil { n += m.Kind.Size() } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } return n } @@ -1101,6 +1235,9 @@ func (m *ListValue) Size() (n int) { n += 1 + l + sovStruct(uint64(l)) } } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } return n } @@ -1125,7 +1262,7 @@ func (this *Struct) String() string { for k := range this.Fields { keysForFields = append(keysForFields, k) } - sortkeys.Strings(keysForFields) + github_com_gogo_protobuf_sortkeys.Strings(keysForFields) mapStringForFields := "map[string]*Value{" for _, k := range keysForFields { mapStringForFields += fmt.Sprintf("%v: %v,", k, this.Fields[k]) @@ -1133,6 +1270,7 @@ func (this *Struct) String() string { mapStringForFields += "}" s := strings.Join([]string{`&Struct{`, `Fields:` + mapStringForFields + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s @@ -1143,6 +1281,7 @@ func (this *Value) String() string { } s := strings.Join([]string{`&Value{`, `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s @@ -1213,6 +1352,7 @@ func (this *ListValue) String() string { } s := strings.Join([]string{`&ListValue{`, `Values:` + strings.Replace(fmt.Sprintf("%v", this.Values), "Value", "Value", 1) + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s @@ -1389,6 +1529,7 @@ func (m *Struct) Unmarshal(dAtA []byte) error { if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } @@ -1455,7 +1596,7 @@ func (m *Value) Unmarshal(dAtA []byte) error { if (iNdEx + 8) > l { return io.ErrUnexpectedEOF } - v = uint64(binary.LittleEndian.Uint64(dAtA[iNdEx:])) + v = uint64(encoding_binary.LittleEndian.Uint64(dAtA[iNdEx:])) iNdEx += 8 m.Kind = &Value_NumberValue{float64(math.Float64frombits(v))} case 3: @@ -1584,6 +1725,7 @@ func (m *Value) Unmarshal(dAtA []byte) error { if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } @@ -1665,6 +1807,7 @@ func (m *ListValue) Unmarshal(dAtA []byte) error { if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } @@ -1779,35 +1922,38 @@ var ( ErrIntOverflowStruct = fmt.Errorf("proto: integer overflow") ) -func init() { proto.RegisterFile("struct.proto", fileDescriptorStruct) } +func init() { + proto.RegisterFile("google/protobuf/struct.proto", fileDescriptor_struct_e8dc68d36b73896c) +} -var fileDescriptorStruct = []byte{ - // 432 bytes of a gzipped FileDescriptorProto +var fileDescriptor_struct_e8dc68d36b73896c = []byte{ + // 443 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x91, 0xb1, 0x6f, 0xd3, 0x40, - 0x14, 0xc6, 0xfd, 0x9c, 0xc6, 0x22, 0xcf, 0x55, 0xa9, 0x0e, 0x09, 0xa2, 0x22, 0x1d, 0x51, 0xba, - 0x58, 0x08, 0x79, 0x08, 0x0b, 0x22, 0x2c, 0x58, 0x2a, 0xad, 0x84, 0x55, 0x19, 0x43, 0x8b, 0xc4, - 0x12, 0xe1, 0xd4, 0x8d, 0xac, 0x5e, 0xef, 0x2a, 0xfb, 0x0c, 0xca, 0x06, 0xff, 0x05, 0x33, 0x13, - 0x62, 0xe4, 0xaf, 0x60, 0xec, 0xc8, 0x88, 0x3d, 0x31, 0x76, 0xec, 0x88, 0xee, 0xce, 0x36, 0xa8, - 0x51, 0x36, 0xbf, 0xcf, 0xbf, 0xf7, 0xbd, 0xf7, 0xbd, 0xc3, 0xcd, 0x42, 0xe6, 0xe5, 0x5c, 0xfa, - 0x17, 0xb9, 0x90, 0x82, 0xdc, 0x5e, 0x08, 0xb1, 0x60, 0xa9, 0xa9, 0x92, 0xf2, 0x74, 0xfc, 0x05, - 0xd0, 0x79, 0xad, 0x09, 0x32, 0x45, 0xe7, 0x34, 0x4b, 0xd9, 0x49, 0x31, 0x84, 0x51, 0xcf, 0x73, - 0x27, 0xbb, 0xfe, 0x0d, 0xd8, 0x37, 0xa0, 0xff, 0x42, 0x53, 0x7b, 0x5c, 0xe6, 0xcb, 0xb8, 0x69, - 0xd9, 0x79, 0x85, 0xee, 0x7f, 0x32, 0xd9, 0xc6, 0xde, 0x59, 0xba, 0x1c, 0xc2, 0x08, 0xbc, 0x41, - 0xac, 0x3e, 0xc9, 0x23, 0xec, 0x7f, 0x78, 0xcf, 0xca, 0x74, 0x68, 0x8f, 0xc0, 0x73, 0x27, 0x77, - 0x57, 0xcc, 0x8f, 0xd5, 0xdf, 0xd8, 0x40, 0x4f, 0xed, 0x27, 0x30, 0xfe, 0x61, 0x63, 0x5f, 0x8b, - 0x64, 0x8a, 0xc8, 0x4b, 0xc6, 0x66, 0xc6, 0x40, 0x99, 0x6e, 0x4d, 0x76, 0x56, 0x0c, 0x0e, 0x4b, - 0xc6, 0x34, 0x7f, 0x60, 0xc5, 0x03, 0xde, 0x16, 0x64, 0x17, 0x37, 0x79, 0x79, 0x9e, 0xa4, 0xf9, - 0xec, 0xdf, 0x7c, 0x38, 0xb0, 0x62, 0xd7, 0xa8, 0x1d, 0x54, 0xc8, 0x3c, 0xe3, 0x8b, 0x06, 0xea, - 0xa9, 0xc5, 0x15, 0x64, 0x54, 0x03, 0x3d, 0x40, 0x4c, 0x84, 0x68, 0xd7, 0xd8, 0x18, 0x81, 0x77, - 0x4b, 0x8d, 0x52, 0x9a, 0x01, 0x9e, 0xb5, 0xd7, 0x6e, 0x90, 0xbe, 0x8e, 0x7a, 0x6f, 0xcd, 0x1d, - 0x1b, 0xfb, 0x72, 0x2e, 0xbb, 0x94, 0x2c, 0x2b, 0xda, 0x5e, 0x47, 0xf7, 0xae, 0xa6, 0x0c, 0xb3, - 0x42, 0x76, 0x29, 0x59, 0x5b, 0x04, 0x0e, 0x6e, 0x9c, 0x65, 0xfc, 0x64, 0x3c, 0xc5, 0x41, 0x47, - 0x10, 0x1f, 0x1d, 0x6d, 0xd6, 0xbe, 0xe8, 0xba, 0xa3, 0x37, 0xd4, 0xc3, 0xfb, 0x38, 0xe8, 0x8e, - 0x48, 0xb6, 0x10, 0x0f, 0x8f, 0xc2, 0x70, 0x76, 0xfc, 0x3c, 0x3c, 0xda, 0xdb, 0xb6, 0x82, 0xcf, - 0x70, 0x59, 0x51, 0xeb, 0x57, 0x45, 0xad, 0xab, 0x8a, 0xc2, 0x75, 0x45, 0xe1, 0x53, 0x4d, 0xe1, - 0x5b, 0x4d, 0xe1, 0x67, 0x4d, 0xe1, 0xb2, 0xa6, 0xf0, 0xbb, 0xa6, 0xf0, 0xa7, 0xa6, 0xd6, 0x55, - 0x4d, 0x01, 0xef, 0xcc, 0xc5, 0xf9, 0xcd, 0x71, 0x81, 0x6b, 0x92, 0x47, 0xaa, 0x8e, 0xe0, 0x5d, - 0x5f, 0x2e, 0x2f, 0xd2, 0xe2, 0x1a, 0xe0, 0xab, 0xdd, 0xdb, 0x8f, 0x82, 0xef, 0x36, 0xdd, 0x37, - 0x0d, 0x51, 0xbb, 0xdf, 0xdb, 0x94, 0xb1, 0x97, 0x5c, 0x7c, 0xe4, 0x6f, 0x14, 0x99, 0x38, 0xda, - 0xe9, 0xf1, 0xdf, 0x00, 0x00, 0x00, 0xff, 0xff, 0x75, 0xc5, 0x1c, 0x3b, 0xd5, 0x02, 0x00, 0x00, + 0x14, 0xc6, 0xfd, 0x9c, 0xc6, 0x22, 0xcf, 0xa8, 0x54, 0x87, 0x04, 0x51, 0x41, 0x47, 0x94, 0x2e, + 0x11, 0x42, 0xae, 0x14, 0x16, 0x44, 0x58, 0x88, 0x54, 0x5a, 0x89, 0xa8, 0x0a, 0x86, 0x16, 0x89, + 0x25, 0xc2, 0xae, 0x1b, 0x59, 0xbd, 0xde, 0x55, 0xf6, 0x1d, 0x28, 0x1b, 0x0b, 0xff, 0x03, 0x33, + 0x13, 0x62, 0xe4, 0xaf, 0x60, 0xec, 0xc8, 0x88, 0xcd, 0xc2, 0xd8, 0xb1, 0x23, 0xba, 0x3b, 0xdb, + 0x54, 0x8d, 0xb2, 0xf9, 0x7d, 0xf7, 0x7b, 0xdf, 0x7b, 0xdf, 0x33, 0xde, 0x9f, 0x0b, 0x31, 0x67, + 0xc9, 0xf6, 0x59, 0x26, 0xa4, 0x88, 0xd4, 0xf1, 0x76, 0x2e, 0x33, 0x15, 0xcb, 0xc0, 0xd4, 0xe4, + 0x96, 0x7d, 0x0d, 0xea, 0xd7, 0xfe, 0x17, 0x40, 0xef, 0xb5, 0x21, 0xc8, 0x08, 0xbd, 0xe3, 0x34, + 0x61, 0x47, 0x79, 0x17, 0x7a, 0xad, 0x81, 0x3f, 0xdc, 0x0a, 0xae, 0xc1, 0x81, 0x05, 0x83, 0x17, + 0x86, 0xda, 0xe1, 0x32, 0x5b, 0x84, 0x55, 0xcb, 0xe6, 0x2b, 0xf4, 0xaf, 0xc8, 0x64, 0x03, 0x5b, + 0x27, 0xc9, 0xa2, 0x0b, 0x3d, 0x18, 0x74, 0x42, 0xfd, 0x49, 0x1e, 0x61, 0xfb, 0xc3, 0x7b, 0xa6, + 0x92, 0xae, 0xdb, 0x83, 0x81, 0x3f, 0xbc, 0xb3, 0x64, 0x7e, 0xa8, 0x5f, 0x43, 0x0b, 0x3d, 0x75, + 0x9f, 0x40, 0xff, 0x87, 0x8b, 0x6d, 0x23, 0x92, 0x11, 0x22, 0x57, 0x8c, 0xcd, 0xac, 0x81, 0x36, + 0x5d, 0x1f, 0x6e, 0x2e, 0x19, 0xec, 0x2b, 0xc6, 0x0c, 0xbf, 0xe7, 0x84, 0x1d, 0x5e, 0x17, 0x64, + 0x0b, 0x6f, 0x72, 0x75, 0x1a, 0x25, 0xd9, 0xec, 0xff, 0x7c, 0xd8, 0x73, 0x42, 0xdf, 0xaa, 0x0d, + 0x94, 0xcb, 0x2c, 0xe5, 0xf3, 0x0a, 0x6a, 0xe9, 0xc5, 0x35, 0x64, 0x55, 0x0b, 0x3d, 0x40, 0x8c, + 0x84, 0xa8, 0xd7, 0x58, 0xeb, 0xc1, 0xe0, 0x86, 0x1e, 0xa5, 0x35, 0x0b, 0x3c, 0x33, 0x2e, 0x2a, + 0x96, 0x15, 0xd2, 0x36, 0x51, 0xef, 0xae, 0xb8, 0x63, 0x65, 0xaf, 0x62, 0xd9, 0xa4, 0x64, 0x69, + 0x5e, 0xf7, 0x7a, 0xa6, 0x77, 0x39, 0xe5, 0x24, 0xcd, 0x65, 0x93, 0x92, 0xd5, 0xc5, 0xd8, 0xc3, + 0xb5, 0x93, 0x94, 0x1f, 0xf5, 0x47, 0xd8, 0x69, 0x08, 0x12, 0xa0, 0x67, 0xcc, 0xea, 0x3f, 0xba, + 0xea, 0xe8, 0x15, 0xf5, 0xf0, 0x1e, 0x76, 0x9a, 0x23, 0x92, 0x75, 0xc4, 0xfd, 0x83, 0xc9, 0x64, + 0x76, 0xf8, 0x7c, 0x72, 0xb0, 0xb3, 0xe1, 0x8c, 0x3f, 0xc3, 0x79, 0x41, 0x9d, 0x5f, 0x05, 0x75, + 0x2e, 0x0a, 0x0a, 0x97, 0x05, 0x85, 0x4f, 0x25, 0x85, 0x6f, 0x25, 0x85, 0x9f, 0x25, 0x85, 0xf3, + 0x92, 0xc2, 0xef, 0x92, 0xc2, 0xdf, 0x92, 0x3a, 0x17, 0x5a, 0xfb, 0x43, 0x01, 0x6f, 0xc7, 0xe2, + 0xf4, 0xfa, 0xc8, 0xb1, 0x6f, 0xd3, 0x4f, 0x75, 0x3d, 0x85, 0x77, 0x6d, 0xb9, 0x38, 0x4b, 0xf2, + 0x4b, 0x80, 0xaf, 0x6e, 0x6b, 0x77, 0x3a, 0xfe, 0xee, 0xd2, 0x5d, 0xdb, 0x30, 0xad, 0x77, 0x7c, + 0x9b, 0x30, 0xf6, 0x92, 0x8b, 0x8f, 0xfc, 0x8d, 0x26, 0x23, 0xcf, 0x38, 0x3d, 0xfe, 0x17, 0x00, + 0x00, 0xff, 0xff, 0x9f, 0x67, 0xad, 0xcf, 0xe9, 0x02, 0x00, 0x00, } diff --git a/vendor/github.com/gogo/protobuf/types/timestamp.pb.go b/vendor/github.com/gogo/protobuf/types/timestamp.pb.go index 41b18f941..e0476675e 100644 --- a/vendor/github.com/gogo/protobuf/types/timestamp.pb.go +++ b/vendor/github.com/gogo/protobuf/types/timestamp.pb.go @@ -1,21 +1,14 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: timestamp.proto +// source: google/protobuf/timestamp.proto -/* - Package types is a generated protocol buffer package. - - It is generated from these files: - timestamp.proto - - It has these top-level messages: - Timestamp -*/ package types import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" +import bytes "bytes" + import strings "strings" import reflect "reflect" @@ -95,7 +88,9 @@ const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package // {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional // seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), // are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone -// is required, though only UTC (as indicated by "Z") is presently supported. +// is required. A proto3 JSON serializer should always use UTC (as indicated by +// "Z") when printing the Timestamp type and a proto3 JSON parser should be +// able to accept both UTC and other timezones (as indicated by an offset). // // For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past // 01:30 UTC on January 15, 2017. @@ -106,8 +101,8 @@ const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package // to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) // with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one // can use the Joda Time's [`ISODateTimeFormat.dateTime()`]( -// http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime()) -// to obtain a formatter capable of generating timestamps in this format. +// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime-- +// ) to obtain a formatter capable of generating timestamps in this format. // // type Timestamp struct { @@ -119,13 +114,44 @@ type Timestamp struct { // second values with fractions must still have non-negative nanos values // that count forward in time. Must be from 0 to 999,999,999 // inclusive. - Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"` + Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *Timestamp) Reset() { *m = Timestamp{} } -func (*Timestamp) ProtoMessage() {} -func (*Timestamp) Descriptor() ([]byte, []int) { return fileDescriptorTimestamp, []int{0} } -func (*Timestamp) XXX_WellKnownType() string { return "Timestamp" } +func (m *Timestamp) Reset() { *m = Timestamp{} } +func (*Timestamp) ProtoMessage() {} +func (*Timestamp) Descriptor() ([]byte, []int) { + return fileDescriptor_timestamp_0a0a9bc758317e91, []int{0} +} +func (*Timestamp) XXX_WellKnownType() string { return "Timestamp" } +func (m *Timestamp) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Timestamp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Timestamp.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *Timestamp) XXX_Merge(src proto.Message) { + xxx_messageInfo_Timestamp.Merge(dst, src) +} +func (m *Timestamp) XXX_Size() int { + return m.Size() +} +func (m *Timestamp) XXX_DiscardUnknown() { + xxx_messageInfo_Timestamp.DiscardUnknown(m) +} + +var xxx_messageInfo_Timestamp proto.InternalMessageInfo func (m *Timestamp) GetSeconds() int64 { if m != nil { @@ -141,6 +167,9 @@ func (m *Timestamp) GetNanos() int32 { return 0 } +func (*Timestamp) XXX_MessageName() string { + return "google.protobuf.Timestamp" +} func init() { proto.RegisterType((*Timestamp)(nil), "google.protobuf.Timestamp") } @@ -181,6 +210,9 @@ func (this *Timestamp) Compare(that interface{}) int { } return 1 } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } return 0 } func (this *Timestamp) Equal(that interface{}) bool { @@ -208,6 +240,9 @@ func (this *Timestamp) Equal(that interface{}) bool { if this.Nanos != that1.Nanos { return false } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } return true } func (this *Timestamp) GoString() string { @@ -218,6 +253,9 @@ func (this *Timestamp) GoString() string { s = append(s, "&types.Timestamp{") s = append(s, "Seconds: "+fmt.Sprintf("%#v", this.Seconds)+",\n") s = append(s, "Nanos: "+fmt.Sprintf("%#v", this.Nanos)+",\n") + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } s = append(s, "}") return strings.Join(s, "") } @@ -254,6 +292,9 @@ func (m *Timestamp) MarshalTo(dAtA []byte) (int, error) { i++ i = encodeVarintTimestamp(dAtA, i, uint64(m.Nanos)) } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } return i, nil } @@ -275,6 +316,9 @@ func (m *Timestamp) Size() (n int) { if m.Nanos != 0 { n += 1 + sovTimestamp(uint64(m.Nanos)) } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } return n } @@ -370,6 +414,7 @@ func (m *Timestamp) Unmarshal(dAtA []byte) error { if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } @@ -484,21 +529,24 @@ var ( ErrIntOverflowTimestamp = fmt.Errorf("proto: integer overflow") ) -func init() { proto.RegisterFile("timestamp.proto", fileDescriptorTimestamp) } +func init() { + proto.RegisterFile("google/protobuf/timestamp.proto", fileDescriptor_timestamp_0a0a9bc758317e91) +} -var fileDescriptorTimestamp = []byte{ - // 205 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x2f, 0xc9, 0xcc, 0x4d, - 0x2d, 0x2e, 0x49, 0xcc, 0x2d, 0xd0, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x4f, 0xcf, 0xcf, - 0x4f, 0xcf, 0x49, 0x85, 0xf0, 0x92, 0x4a, 0xd3, 0x94, 0xac, 0xb9, 0x38, 0x43, 0x60, 0x6a, 0x84, - 0x24, 0xb8, 0xd8, 0x8b, 0x53, 0x93, 0xf3, 0xf3, 0x52, 0x8a, 0x25, 0x18, 0x15, 0x18, 0x35, 0x98, - 0x83, 0x60, 0x5c, 0x21, 0x11, 0x2e, 0xd6, 0xbc, 0xc4, 0xbc, 0xfc, 0x62, 0x09, 0x26, 0x05, 0x46, - 0x0d, 0xd6, 0x20, 0x08, 0xc7, 0xa9, 0x81, 0xf1, 0xc2, 0x43, 0x39, 0x86, 0x1b, 0x0f, 0xe5, 0x18, - 0x3e, 0x3c, 0x94, 0x63, 0x5c, 0xf1, 0x48, 0x8e, 0xf1, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, - 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x7c, 0xf1, 0x48, 0x8e, 0xe1, 0xc3, 0x23, 0x39, 0xc6, 0x15, 0x8f, - 0xe5, 0x18, 0xb9, 0x84, 0x93, 0xf3, 0x73, 0xf5, 0xd0, 0x2c, 0x77, 0xe2, 0x83, 0x5b, 0x1d, 0x00, - 0x12, 0x0a, 0x60, 0x8c, 0x62, 0x2d, 0xa9, 0x2c, 0x48, 0x2d, 0xfe, 0xc1, 0xc8, 0xb8, 0x88, 0x89, - 0xd9, 0x3d, 0xc0, 0x69, 0x15, 0x93, 0x9c, 0x3b, 0x44, 0x4f, 0x00, 0x54, 0x8f, 0x5e, 0x78, 0x6a, - 0x4e, 0x8e, 0x77, 0x5e, 0x7e, 0x79, 0x5e, 0x08, 0x48, 0x65, 0x12, 0x1b, 0xd8, 0x30, 0x63, 0x40, - 0x00, 0x00, 0x00, 0xff, 0xff, 0x9b, 0xa2, 0x42, 0xda, 0xea, 0x00, 0x00, 0x00, +var fileDescriptor_timestamp_0a0a9bc758317e91 = []byte{ + // 216 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4f, 0xcf, 0xcf, 0x4f, + 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0xc9, 0xcc, 0x4d, + 0x2d, 0x2e, 0x49, 0xcc, 0x2d, 0xd0, 0x03, 0x0b, 0x09, 0xf1, 0x43, 0x14, 0xe8, 0xc1, 0x14, 0x28, + 0x59, 0x73, 0x71, 0x86, 0xc0, 0xd4, 0x08, 0x49, 0x70, 0xb1, 0x17, 0xa7, 0x26, 0xe7, 0xe7, 0xa5, + 0x14, 0x4b, 0x30, 0x2a, 0x30, 0x6a, 0x30, 0x07, 0xc1, 0xb8, 0x42, 0x22, 0x5c, 0xac, 0x79, 0x89, + 0x79, 0xf9, 0xc5, 0x12, 0x4c, 0x0a, 0x8c, 0x1a, 0xac, 0x41, 0x10, 0x8e, 0x53, 0x0b, 0xe3, 0x85, + 0x87, 0x72, 0x0c, 0x37, 0x1e, 0xca, 0x31, 0x7c, 0x78, 0x28, 0xc7, 0xb8, 0xe2, 0x91, 0x1c, 0xe3, + 0x89, 0x47, 0x72, 0x8c, 0x17, 0x1e, 0xc9, 0x31, 0x3e, 0x78, 0x24, 0xc7, 0xf8, 0xe2, 0x91, 0x1c, + 0xc3, 0x87, 0x47, 0x72, 0x8c, 0x2b, 0x1e, 0xcb, 0x31, 0x9e, 0x78, 0x2c, 0xc7, 0xc8, 0x25, 0x9c, + 0x9c, 0x9f, 0xab, 0x87, 0xe6, 0x00, 0x27, 0x3e, 0xb8, 0xf5, 0x01, 0x20, 0xa1, 0x00, 0xc6, 0x28, + 0xd6, 0x92, 0xca, 0x82, 0xd4, 0xe2, 0x1f, 0x8c, 0x8c, 0x8b, 0x98, 0x98, 0xdd, 0x03, 0x9c, 0x56, + 0x31, 0xc9, 0xb9, 0x43, 0xf4, 0x04, 0x40, 0xf5, 0xe8, 0x85, 0xa7, 0xe6, 0xe4, 0x78, 0xe7, 0xe5, + 0x97, 0xe7, 0x85, 0x80, 0x54, 0x26, 0xb1, 0x81, 0x0d, 0x33, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, + 0x40, 0xae, 0xf1, 0x42, 0xfe, 0x00, 0x00, 0x00, } diff --git a/vendor/github.com/gogo/protobuf/types/type.pb.go b/vendor/github.com/gogo/protobuf/types/type.pb.go new file mode 100644 index 000000000..5f406e041 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/types/type.pb.go @@ -0,0 +1,3228 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: google/protobuf/type.proto + +package types + +import proto "github.com/gogo/protobuf/proto" +import fmt "fmt" +import math "math" + +import bytes "bytes" + +import strconv "strconv" + +import strings "strings" +import reflect "reflect" + +import io "io" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package + +// The syntax in which a protocol buffer element is defined. +type Syntax int32 + +const ( + // Syntax `proto2`. + SYNTAX_PROTO2 Syntax = 0 + // Syntax `proto3`. + SYNTAX_PROTO3 Syntax = 1 +) + +var Syntax_name = map[int32]string{ + 0: "SYNTAX_PROTO2", + 1: "SYNTAX_PROTO3", +} +var Syntax_value = map[string]int32{ + "SYNTAX_PROTO2": 0, + "SYNTAX_PROTO3": 1, +} + +func (Syntax) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_type_345e3aff58b7b252, []int{0} +} + +// Basic field types. +type Field_Kind int32 + +const ( + // Field type unknown. + TYPE_UNKNOWN Field_Kind = 0 + // Field type double. + TYPE_DOUBLE Field_Kind = 1 + // Field type float. + TYPE_FLOAT Field_Kind = 2 + // Field type int64. + TYPE_INT64 Field_Kind = 3 + // Field type uint64. + TYPE_UINT64 Field_Kind = 4 + // Field type int32. + TYPE_INT32 Field_Kind = 5 + // Field type fixed64. + TYPE_FIXED64 Field_Kind = 6 + // Field type fixed32. + TYPE_FIXED32 Field_Kind = 7 + // Field type bool. + TYPE_BOOL Field_Kind = 8 + // Field type string. + TYPE_STRING Field_Kind = 9 + // Field type group. Proto2 syntax only, and deprecated. + TYPE_GROUP Field_Kind = 10 + // Field type message. + TYPE_MESSAGE Field_Kind = 11 + // Field type bytes. + TYPE_BYTES Field_Kind = 12 + // Field type uint32. + TYPE_UINT32 Field_Kind = 13 + // Field type enum. + TYPE_ENUM Field_Kind = 14 + // Field type sfixed32. + TYPE_SFIXED32 Field_Kind = 15 + // Field type sfixed64. + TYPE_SFIXED64 Field_Kind = 16 + // Field type sint32. + TYPE_SINT32 Field_Kind = 17 + // Field type sint64. + TYPE_SINT64 Field_Kind = 18 +) + +var Field_Kind_name = map[int32]string{ + 0: "TYPE_UNKNOWN", + 1: "TYPE_DOUBLE", + 2: "TYPE_FLOAT", + 3: "TYPE_INT64", + 4: "TYPE_UINT64", + 5: "TYPE_INT32", + 6: "TYPE_FIXED64", + 7: "TYPE_FIXED32", + 8: "TYPE_BOOL", + 9: "TYPE_STRING", + 10: "TYPE_GROUP", + 11: "TYPE_MESSAGE", + 12: "TYPE_BYTES", + 13: "TYPE_UINT32", + 14: "TYPE_ENUM", + 15: "TYPE_SFIXED32", + 16: "TYPE_SFIXED64", + 17: "TYPE_SINT32", + 18: "TYPE_SINT64", +} +var Field_Kind_value = map[string]int32{ + "TYPE_UNKNOWN": 0, + "TYPE_DOUBLE": 1, + "TYPE_FLOAT": 2, + "TYPE_INT64": 3, + "TYPE_UINT64": 4, + "TYPE_INT32": 5, + "TYPE_FIXED64": 6, + "TYPE_FIXED32": 7, + "TYPE_BOOL": 8, + "TYPE_STRING": 9, + "TYPE_GROUP": 10, + "TYPE_MESSAGE": 11, + "TYPE_BYTES": 12, + "TYPE_UINT32": 13, + "TYPE_ENUM": 14, + "TYPE_SFIXED32": 15, + "TYPE_SFIXED64": 16, + "TYPE_SINT32": 17, + "TYPE_SINT64": 18, +} + +func (Field_Kind) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_type_345e3aff58b7b252, []int{1, 0} +} + +// Whether a field is optional, required, or repeated. +type Field_Cardinality int32 + +const ( + // For fields with unknown cardinality. + CARDINALITY_UNKNOWN Field_Cardinality = 0 + // For optional fields. + CARDINALITY_OPTIONAL Field_Cardinality = 1 + // For required fields. Proto2 syntax only. + CARDINALITY_REQUIRED Field_Cardinality = 2 + // For repeated fields. + CARDINALITY_REPEATED Field_Cardinality = 3 +) + +var Field_Cardinality_name = map[int32]string{ + 0: "CARDINALITY_UNKNOWN", + 1: "CARDINALITY_OPTIONAL", + 2: "CARDINALITY_REQUIRED", + 3: "CARDINALITY_REPEATED", +} +var Field_Cardinality_value = map[string]int32{ + "CARDINALITY_UNKNOWN": 0, + "CARDINALITY_OPTIONAL": 1, + "CARDINALITY_REQUIRED": 2, + "CARDINALITY_REPEATED": 3, +} + +func (Field_Cardinality) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_type_345e3aff58b7b252, []int{1, 1} +} + +// A protocol buffer message type. +type Type struct { + // The fully qualified message name. + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + // The list of fields. + Fields []*Field `protobuf:"bytes,2,rep,name=fields" json:"fields,omitempty"` + // The list of types appearing in `oneof` definitions in this type. + Oneofs []string `protobuf:"bytes,3,rep,name=oneofs" json:"oneofs,omitempty"` + // The protocol buffer options. + Options []*Option `protobuf:"bytes,4,rep,name=options" json:"options,omitempty"` + // The source context. + SourceContext *SourceContext `protobuf:"bytes,5,opt,name=source_context,json=sourceContext" json:"source_context,omitempty"` + // The source syntax. + Syntax Syntax `protobuf:"varint,6,opt,name=syntax,proto3,enum=google.protobuf.Syntax" json:"syntax,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Type) Reset() { *m = Type{} } +func (*Type) ProtoMessage() {} +func (*Type) Descriptor() ([]byte, []int) { + return fileDescriptor_type_345e3aff58b7b252, []int{0} +} +func (m *Type) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Type) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Type.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *Type) XXX_Merge(src proto.Message) { + xxx_messageInfo_Type.Merge(dst, src) +} +func (m *Type) XXX_Size() int { + return m.Size() +} +func (m *Type) XXX_DiscardUnknown() { + xxx_messageInfo_Type.DiscardUnknown(m) +} + +var xxx_messageInfo_Type proto.InternalMessageInfo + +func (m *Type) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *Type) GetFields() []*Field { + if m != nil { + return m.Fields + } + return nil +} + +func (m *Type) GetOneofs() []string { + if m != nil { + return m.Oneofs + } + return nil +} + +func (m *Type) GetOptions() []*Option { + if m != nil { + return m.Options + } + return nil +} + +func (m *Type) GetSourceContext() *SourceContext { + if m != nil { + return m.SourceContext + } + return nil +} + +func (m *Type) GetSyntax() Syntax { + if m != nil { + return m.Syntax + } + return SYNTAX_PROTO2 +} + +func (*Type) XXX_MessageName() string { + return "google.protobuf.Type" +} + +// A single field of a message type. +type Field struct { + // The field type. + Kind Field_Kind `protobuf:"varint,1,opt,name=kind,proto3,enum=google.protobuf.Field_Kind" json:"kind,omitempty"` + // The field cardinality. + Cardinality Field_Cardinality `protobuf:"varint,2,opt,name=cardinality,proto3,enum=google.protobuf.Field_Cardinality" json:"cardinality,omitempty"` + // The field number. + Number int32 `protobuf:"varint,3,opt,name=number,proto3" json:"number,omitempty"` + // The field name. + Name string `protobuf:"bytes,4,opt,name=name,proto3" json:"name,omitempty"` + // The field type URL, without the scheme, for message or enumeration + // types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`. + TypeUrl string `protobuf:"bytes,6,opt,name=type_url,json=typeUrl,proto3" json:"type_url,omitempty"` + // The index of the field type in `Type.oneofs`, for message or enumeration + // types. The first type has index 1; zero means the type is not in the list. + OneofIndex int32 `protobuf:"varint,7,opt,name=oneof_index,json=oneofIndex,proto3" json:"oneof_index,omitempty"` + // Whether to use alternative packed wire representation. + Packed bool `protobuf:"varint,8,opt,name=packed,proto3" json:"packed,omitempty"` + // The protocol buffer options. + Options []*Option `protobuf:"bytes,9,rep,name=options" json:"options,omitempty"` + // The field JSON name. + JsonName string `protobuf:"bytes,10,opt,name=json_name,json=jsonName,proto3" json:"json_name,omitempty"` + // The string value of the default value of this field. Proto2 syntax only. + DefaultValue string `protobuf:"bytes,11,opt,name=default_value,json=defaultValue,proto3" json:"default_value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Field) Reset() { *m = Field{} } +func (*Field) ProtoMessage() {} +func (*Field) Descriptor() ([]byte, []int) { + return fileDescriptor_type_345e3aff58b7b252, []int{1} +} +func (m *Field) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Field) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Field.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *Field) XXX_Merge(src proto.Message) { + xxx_messageInfo_Field.Merge(dst, src) +} +func (m *Field) XXX_Size() int { + return m.Size() +} +func (m *Field) XXX_DiscardUnknown() { + xxx_messageInfo_Field.DiscardUnknown(m) +} + +var xxx_messageInfo_Field proto.InternalMessageInfo + +func (m *Field) GetKind() Field_Kind { + if m != nil { + return m.Kind + } + return TYPE_UNKNOWN +} + +func (m *Field) GetCardinality() Field_Cardinality { + if m != nil { + return m.Cardinality + } + return CARDINALITY_UNKNOWN +} + +func (m *Field) GetNumber() int32 { + if m != nil { + return m.Number + } + return 0 +} + +func (m *Field) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *Field) GetTypeUrl() string { + if m != nil { + return m.TypeUrl + } + return "" +} + +func (m *Field) GetOneofIndex() int32 { + if m != nil { + return m.OneofIndex + } + return 0 +} + +func (m *Field) GetPacked() bool { + if m != nil { + return m.Packed + } + return false +} + +func (m *Field) GetOptions() []*Option { + if m != nil { + return m.Options + } + return nil +} + +func (m *Field) GetJsonName() string { + if m != nil { + return m.JsonName + } + return "" +} + +func (m *Field) GetDefaultValue() string { + if m != nil { + return m.DefaultValue + } + return "" +} + +func (*Field) XXX_MessageName() string { + return "google.protobuf.Field" +} + +// Enum type definition. +type Enum struct { + // Enum type name. + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + // Enum value definitions. + Enumvalue []*EnumValue `protobuf:"bytes,2,rep,name=enumvalue" json:"enumvalue,omitempty"` + // Protocol buffer options. + Options []*Option `protobuf:"bytes,3,rep,name=options" json:"options,omitempty"` + // The source context. + SourceContext *SourceContext `protobuf:"bytes,4,opt,name=source_context,json=sourceContext" json:"source_context,omitempty"` + // The source syntax. + Syntax Syntax `protobuf:"varint,5,opt,name=syntax,proto3,enum=google.protobuf.Syntax" json:"syntax,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Enum) Reset() { *m = Enum{} } +func (*Enum) ProtoMessage() {} +func (*Enum) Descriptor() ([]byte, []int) { + return fileDescriptor_type_345e3aff58b7b252, []int{2} +} +func (m *Enum) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Enum) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Enum.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *Enum) XXX_Merge(src proto.Message) { + xxx_messageInfo_Enum.Merge(dst, src) +} +func (m *Enum) XXX_Size() int { + return m.Size() +} +func (m *Enum) XXX_DiscardUnknown() { + xxx_messageInfo_Enum.DiscardUnknown(m) +} + +var xxx_messageInfo_Enum proto.InternalMessageInfo + +func (m *Enum) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *Enum) GetEnumvalue() []*EnumValue { + if m != nil { + return m.Enumvalue + } + return nil +} + +func (m *Enum) GetOptions() []*Option { + if m != nil { + return m.Options + } + return nil +} + +func (m *Enum) GetSourceContext() *SourceContext { + if m != nil { + return m.SourceContext + } + return nil +} + +func (m *Enum) GetSyntax() Syntax { + if m != nil { + return m.Syntax + } + return SYNTAX_PROTO2 +} + +func (*Enum) XXX_MessageName() string { + return "google.protobuf.Enum" +} + +// Enum value definition. +type EnumValue struct { + // Enum value name. + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + // Enum value number. + Number int32 `protobuf:"varint,2,opt,name=number,proto3" json:"number,omitempty"` + // Protocol buffer options. + Options []*Option `protobuf:"bytes,3,rep,name=options" json:"options,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *EnumValue) Reset() { *m = EnumValue{} } +func (*EnumValue) ProtoMessage() {} +func (*EnumValue) Descriptor() ([]byte, []int) { + return fileDescriptor_type_345e3aff58b7b252, []int{3} +} +func (m *EnumValue) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *EnumValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_EnumValue.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *EnumValue) XXX_Merge(src proto.Message) { + xxx_messageInfo_EnumValue.Merge(dst, src) +} +func (m *EnumValue) XXX_Size() int { + return m.Size() +} +func (m *EnumValue) XXX_DiscardUnknown() { + xxx_messageInfo_EnumValue.DiscardUnknown(m) +} + +var xxx_messageInfo_EnumValue proto.InternalMessageInfo + +func (m *EnumValue) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *EnumValue) GetNumber() int32 { + if m != nil { + return m.Number + } + return 0 +} + +func (m *EnumValue) GetOptions() []*Option { + if m != nil { + return m.Options + } + return nil +} + +func (*EnumValue) XXX_MessageName() string { + return "google.protobuf.EnumValue" +} + +// A protocol buffer option, which can be attached to a message, field, +// enumeration, etc. +type Option struct { + // The option's name. For protobuf built-in options (options defined in + // descriptor.proto), this is the short name. For example, `"map_entry"`. + // For custom options, it should be the fully-qualified name. For example, + // `"google.api.http"`. + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + // The option's value packed in an Any message. If the value is a primitive, + // the corresponding wrapper type defined in google/protobuf/wrappers.proto + // should be used. If the value is an enum, it should be stored as an int32 + // value using the google.protobuf.Int32Value type. + Value *Any `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Option) Reset() { *m = Option{} } +func (*Option) ProtoMessage() {} +func (*Option) Descriptor() ([]byte, []int) { + return fileDescriptor_type_345e3aff58b7b252, []int{4} +} +func (m *Option) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Option) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Option.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *Option) XXX_Merge(src proto.Message) { + xxx_messageInfo_Option.Merge(dst, src) +} +func (m *Option) XXX_Size() int { + return m.Size() +} +func (m *Option) XXX_DiscardUnknown() { + xxx_messageInfo_Option.DiscardUnknown(m) +} + +var xxx_messageInfo_Option proto.InternalMessageInfo + +func (m *Option) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *Option) GetValue() *Any { + if m != nil { + return m.Value + } + return nil +} + +func (*Option) XXX_MessageName() string { + return "google.protobuf.Option" +} +func init() { + proto.RegisterType((*Type)(nil), "google.protobuf.Type") + proto.RegisterType((*Field)(nil), "google.protobuf.Field") + proto.RegisterType((*Enum)(nil), "google.protobuf.Enum") + proto.RegisterType((*EnumValue)(nil), "google.protobuf.EnumValue") + proto.RegisterType((*Option)(nil), "google.protobuf.Option") + proto.RegisterEnum("google.protobuf.Syntax", Syntax_name, Syntax_value) + proto.RegisterEnum("google.protobuf.Field_Kind", Field_Kind_name, Field_Kind_value) + proto.RegisterEnum("google.protobuf.Field_Cardinality", Field_Cardinality_name, Field_Cardinality_value) +} +func (this *Type) Compare(that interface{}) int { + if that == nil { + if this == nil { + return 0 + } + return 1 + } + + that1, ok := that.(*Type) + if !ok { + that2, ok := that.(Type) + if ok { + that1 = &that2 + } else { + return 1 + } + } + if that1 == nil { + if this == nil { + return 0 + } + return 1 + } else if this == nil { + return -1 + } + if this.Name != that1.Name { + if this.Name < that1.Name { + return -1 + } + return 1 + } + if len(this.Fields) != len(that1.Fields) { + if len(this.Fields) < len(that1.Fields) { + return -1 + } + return 1 + } + for i := range this.Fields { + if c := this.Fields[i].Compare(that1.Fields[i]); c != 0 { + return c + } + } + if len(this.Oneofs) != len(that1.Oneofs) { + if len(this.Oneofs) < len(that1.Oneofs) { + return -1 + } + return 1 + } + for i := range this.Oneofs { + if this.Oneofs[i] != that1.Oneofs[i] { + if this.Oneofs[i] < that1.Oneofs[i] { + return -1 + } + return 1 + } + } + if len(this.Options) != len(that1.Options) { + if len(this.Options) < len(that1.Options) { + return -1 + } + return 1 + } + for i := range this.Options { + if c := this.Options[i].Compare(that1.Options[i]); c != 0 { + return c + } + } + if c := this.SourceContext.Compare(that1.SourceContext); c != 0 { + return c + } + if this.Syntax != that1.Syntax { + if this.Syntax < that1.Syntax { + return -1 + } + return 1 + } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } + return 0 +} +func (this *Field) Compare(that interface{}) int { + if that == nil { + if this == nil { + return 0 + } + return 1 + } + + that1, ok := that.(*Field) + if !ok { + that2, ok := that.(Field) + if ok { + that1 = &that2 + } else { + return 1 + } + } + if that1 == nil { + if this == nil { + return 0 + } + return 1 + } else if this == nil { + return -1 + } + if this.Kind != that1.Kind { + if this.Kind < that1.Kind { + return -1 + } + return 1 + } + if this.Cardinality != that1.Cardinality { + if this.Cardinality < that1.Cardinality { + return -1 + } + return 1 + } + if this.Number != that1.Number { + if this.Number < that1.Number { + return -1 + } + return 1 + } + if this.Name != that1.Name { + if this.Name < that1.Name { + return -1 + } + return 1 + } + if this.TypeUrl != that1.TypeUrl { + if this.TypeUrl < that1.TypeUrl { + return -1 + } + return 1 + } + if this.OneofIndex != that1.OneofIndex { + if this.OneofIndex < that1.OneofIndex { + return -1 + } + return 1 + } + if this.Packed != that1.Packed { + if !this.Packed { + return -1 + } + return 1 + } + if len(this.Options) != len(that1.Options) { + if len(this.Options) < len(that1.Options) { + return -1 + } + return 1 + } + for i := range this.Options { + if c := this.Options[i].Compare(that1.Options[i]); c != 0 { + return c + } + } + if this.JsonName != that1.JsonName { + if this.JsonName < that1.JsonName { + return -1 + } + return 1 + } + if this.DefaultValue != that1.DefaultValue { + if this.DefaultValue < that1.DefaultValue { + return -1 + } + return 1 + } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } + return 0 +} +func (this *Enum) Compare(that interface{}) int { + if that == nil { + if this == nil { + return 0 + } + return 1 + } + + that1, ok := that.(*Enum) + if !ok { + that2, ok := that.(Enum) + if ok { + that1 = &that2 + } else { + return 1 + } + } + if that1 == nil { + if this == nil { + return 0 + } + return 1 + } else if this == nil { + return -1 + } + if this.Name != that1.Name { + if this.Name < that1.Name { + return -1 + } + return 1 + } + if len(this.Enumvalue) != len(that1.Enumvalue) { + if len(this.Enumvalue) < len(that1.Enumvalue) { + return -1 + } + return 1 + } + for i := range this.Enumvalue { + if c := this.Enumvalue[i].Compare(that1.Enumvalue[i]); c != 0 { + return c + } + } + if len(this.Options) != len(that1.Options) { + if len(this.Options) < len(that1.Options) { + return -1 + } + return 1 + } + for i := range this.Options { + if c := this.Options[i].Compare(that1.Options[i]); c != 0 { + return c + } + } + if c := this.SourceContext.Compare(that1.SourceContext); c != 0 { + return c + } + if this.Syntax != that1.Syntax { + if this.Syntax < that1.Syntax { + return -1 + } + return 1 + } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } + return 0 +} +func (this *EnumValue) Compare(that interface{}) int { + if that == nil { + if this == nil { + return 0 + } + return 1 + } + + that1, ok := that.(*EnumValue) + if !ok { + that2, ok := that.(EnumValue) + if ok { + that1 = &that2 + } else { + return 1 + } + } + if that1 == nil { + if this == nil { + return 0 + } + return 1 + } else if this == nil { + return -1 + } + if this.Name != that1.Name { + if this.Name < that1.Name { + return -1 + } + return 1 + } + if this.Number != that1.Number { + if this.Number < that1.Number { + return -1 + } + return 1 + } + if len(this.Options) != len(that1.Options) { + if len(this.Options) < len(that1.Options) { + return -1 + } + return 1 + } + for i := range this.Options { + if c := this.Options[i].Compare(that1.Options[i]); c != 0 { + return c + } + } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } + return 0 +} +func (this *Option) Compare(that interface{}) int { + if that == nil { + if this == nil { + return 0 + } + return 1 + } + + that1, ok := that.(*Option) + if !ok { + that2, ok := that.(Option) + if ok { + that1 = &that2 + } else { + return 1 + } + } + if that1 == nil { + if this == nil { + return 0 + } + return 1 + } else if this == nil { + return -1 + } + if this.Name != that1.Name { + if this.Name < that1.Name { + return -1 + } + return 1 + } + if c := this.Value.Compare(that1.Value); c != 0 { + return c + } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } + return 0 +} +func (x Syntax) String() string { + s, ok := Syntax_name[int32(x)] + if ok { + return s + } + return strconv.Itoa(int(x)) +} +func (x Field_Kind) String() string { + s, ok := Field_Kind_name[int32(x)] + if ok { + return s + } + return strconv.Itoa(int(x)) +} +func (x Field_Cardinality) String() string { + s, ok := Field_Cardinality_name[int32(x)] + if ok { + return s + } + return strconv.Itoa(int(x)) +} +func (this *Type) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*Type) + if !ok { + that2, ok := that.(Type) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Name != that1.Name { + return false + } + if len(this.Fields) != len(that1.Fields) { + return false + } + for i := range this.Fields { + if !this.Fields[i].Equal(that1.Fields[i]) { + return false + } + } + if len(this.Oneofs) != len(that1.Oneofs) { + return false + } + for i := range this.Oneofs { + if this.Oneofs[i] != that1.Oneofs[i] { + return false + } + } + if len(this.Options) != len(that1.Options) { + return false + } + for i := range this.Options { + if !this.Options[i].Equal(that1.Options[i]) { + return false + } + } + if !this.SourceContext.Equal(that1.SourceContext) { + return false + } + if this.Syntax != that1.Syntax { + return false + } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } + return true +} +func (this *Field) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*Field) + if !ok { + that2, ok := that.(Field) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Kind != that1.Kind { + return false + } + if this.Cardinality != that1.Cardinality { + return false + } + if this.Number != that1.Number { + return false + } + if this.Name != that1.Name { + return false + } + if this.TypeUrl != that1.TypeUrl { + return false + } + if this.OneofIndex != that1.OneofIndex { + return false + } + if this.Packed != that1.Packed { + return false + } + if len(this.Options) != len(that1.Options) { + return false + } + for i := range this.Options { + if !this.Options[i].Equal(that1.Options[i]) { + return false + } + } + if this.JsonName != that1.JsonName { + return false + } + if this.DefaultValue != that1.DefaultValue { + return false + } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } + return true +} +func (this *Enum) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*Enum) + if !ok { + that2, ok := that.(Enum) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Name != that1.Name { + return false + } + if len(this.Enumvalue) != len(that1.Enumvalue) { + return false + } + for i := range this.Enumvalue { + if !this.Enumvalue[i].Equal(that1.Enumvalue[i]) { + return false + } + } + if len(this.Options) != len(that1.Options) { + return false + } + for i := range this.Options { + if !this.Options[i].Equal(that1.Options[i]) { + return false + } + } + if !this.SourceContext.Equal(that1.SourceContext) { + return false + } + if this.Syntax != that1.Syntax { + return false + } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } + return true +} +func (this *EnumValue) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*EnumValue) + if !ok { + that2, ok := that.(EnumValue) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Name != that1.Name { + return false + } + if this.Number != that1.Number { + return false + } + if len(this.Options) != len(that1.Options) { + return false + } + for i := range this.Options { + if !this.Options[i].Equal(that1.Options[i]) { + return false + } + } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } + return true +} +func (this *Option) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*Option) + if !ok { + that2, ok := that.(Option) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Name != that1.Name { + return false + } + if !this.Value.Equal(that1.Value) { + return false + } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } + return true +} +func (this *Type) GoString() string { + if this == nil { + return "nil" + } + s := make([]string, 0, 10) + s = append(s, "&types.Type{") + s = append(s, "Name: "+fmt.Sprintf("%#v", this.Name)+",\n") + if this.Fields != nil { + s = append(s, "Fields: "+fmt.Sprintf("%#v", this.Fields)+",\n") + } + s = append(s, "Oneofs: "+fmt.Sprintf("%#v", this.Oneofs)+",\n") + if this.Options != nil { + s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n") + } + if this.SourceContext != nil { + s = append(s, "SourceContext: "+fmt.Sprintf("%#v", this.SourceContext)+",\n") + } + s = append(s, "Syntax: "+fmt.Sprintf("%#v", this.Syntax)+",\n") + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } + s = append(s, "}") + return strings.Join(s, "") +} +func (this *Field) GoString() string { + if this == nil { + return "nil" + } + s := make([]string, 0, 14) + s = append(s, "&types.Field{") + s = append(s, "Kind: "+fmt.Sprintf("%#v", this.Kind)+",\n") + s = append(s, "Cardinality: "+fmt.Sprintf("%#v", this.Cardinality)+",\n") + s = append(s, "Number: "+fmt.Sprintf("%#v", this.Number)+",\n") + s = append(s, "Name: "+fmt.Sprintf("%#v", this.Name)+",\n") + s = append(s, "TypeUrl: "+fmt.Sprintf("%#v", this.TypeUrl)+",\n") + s = append(s, "OneofIndex: "+fmt.Sprintf("%#v", this.OneofIndex)+",\n") + s = append(s, "Packed: "+fmt.Sprintf("%#v", this.Packed)+",\n") + if this.Options != nil { + s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n") + } + s = append(s, "JsonName: "+fmt.Sprintf("%#v", this.JsonName)+",\n") + s = append(s, "DefaultValue: "+fmt.Sprintf("%#v", this.DefaultValue)+",\n") + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } + s = append(s, "}") + return strings.Join(s, "") +} +func (this *Enum) GoString() string { + if this == nil { + return "nil" + } + s := make([]string, 0, 9) + s = append(s, "&types.Enum{") + s = append(s, "Name: "+fmt.Sprintf("%#v", this.Name)+",\n") + if this.Enumvalue != nil { + s = append(s, "Enumvalue: "+fmt.Sprintf("%#v", this.Enumvalue)+",\n") + } + if this.Options != nil { + s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n") + } + if this.SourceContext != nil { + s = append(s, "SourceContext: "+fmt.Sprintf("%#v", this.SourceContext)+",\n") + } + s = append(s, "Syntax: "+fmt.Sprintf("%#v", this.Syntax)+",\n") + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } + s = append(s, "}") + return strings.Join(s, "") +} +func (this *EnumValue) GoString() string { + if this == nil { + return "nil" + } + s := make([]string, 0, 7) + s = append(s, "&types.EnumValue{") + s = append(s, "Name: "+fmt.Sprintf("%#v", this.Name)+",\n") + s = append(s, "Number: "+fmt.Sprintf("%#v", this.Number)+",\n") + if this.Options != nil { + s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n") + } + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } + s = append(s, "}") + return strings.Join(s, "") +} +func (this *Option) GoString() string { + if this == nil { + return "nil" + } + s := make([]string, 0, 6) + s = append(s, "&types.Option{") + s = append(s, "Name: "+fmt.Sprintf("%#v", this.Name)+",\n") + if this.Value != nil { + s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n") + } + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } + s = append(s, "}") + return strings.Join(s, "") +} +func valueToGoStringType(v interface{}, typ string) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv) +} +func (m *Type) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Type) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Name) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintType(dAtA, i, uint64(len(m.Name))) + i += copy(dAtA[i:], m.Name) + } + if len(m.Fields) > 0 { + for _, msg := range m.Fields { + dAtA[i] = 0x12 + i++ + i = encodeVarintType(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + if len(m.Oneofs) > 0 { + for _, s := range m.Oneofs { + dAtA[i] = 0x1a + i++ + l = len(s) + for l >= 1<<7 { + dAtA[i] = uint8(uint64(l)&0x7f | 0x80) + l >>= 7 + i++ + } + dAtA[i] = uint8(l) + i++ + i += copy(dAtA[i:], s) + } + } + if len(m.Options) > 0 { + for _, msg := range m.Options { + dAtA[i] = 0x22 + i++ + i = encodeVarintType(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + if m.SourceContext != nil { + dAtA[i] = 0x2a + i++ + i = encodeVarintType(dAtA, i, uint64(m.SourceContext.Size())) + n1, err := m.SourceContext.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n1 + } + if m.Syntax != 0 { + dAtA[i] = 0x30 + i++ + i = encodeVarintType(dAtA, i, uint64(m.Syntax)) + } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } + return i, nil +} + +func (m *Field) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Field) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.Kind != 0 { + dAtA[i] = 0x8 + i++ + i = encodeVarintType(dAtA, i, uint64(m.Kind)) + } + if m.Cardinality != 0 { + dAtA[i] = 0x10 + i++ + i = encodeVarintType(dAtA, i, uint64(m.Cardinality)) + } + if m.Number != 0 { + dAtA[i] = 0x18 + i++ + i = encodeVarintType(dAtA, i, uint64(m.Number)) + } + if len(m.Name) > 0 { + dAtA[i] = 0x22 + i++ + i = encodeVarintType(dAtA, i, uint64(len(m.Name))) + i += copy(dAtA[i:], m.Name) + } + if len(m.TypeUrl) > 0 { + dAtA[i] = 0x32 + i++ + i = encodeVarintType(dAtA, i, uint64(len(m.TypeUrl))) + i += copy(dAtA[i:], m.TypeUrl) + } + if m.OneofIndex != 0 { + dAtA[i] = 0x38 + i++ + i = encodeVarintType(dAtA, i, uint64(m.OneofIndex)) + } + if m.Packed { + dAtA[i] = 0x40 + i++ + if m.Packed { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i++ + } + if len(m.Options) > 0 { + for _, msg := range m.Options { + dAtA[i] = 0x4a + i++ + i = encodeVarintType(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + if len(m.JsonName) > 0 { + dAtA[i] = 0x52 + i++ + i = encodeVarintType(dAtA, i, uint64(len(m.JsonName))) + i += copy(dAtA[i:], m.JsonName) + } + if len(m.DefaultValue) > 0 { + dAtA[i] = 0x5a + i++ + i = encodeVarintType(dAtA, i, uint64(len(m.DefaultValue))) + i += copy(dAtA[i:], m.DefaultValue) + } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } + return i, nil +} + +func (m *Enum) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Enum) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Name) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintType(dAtA, i, uint64(len(m.Name))) + i += copy(dAtA[i:], m.Name) + } + if len(m.Enumvalue) > 0 { + for _, msg := range m.Enumvalue { + dAtA[i] = 0x12 + i++ + i = encodeVarintType(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + if len(m.Options) > 0 { + for _, msg := range m.Options { + dAtA[i] = 0x1a + i++ + i = encodeVarintType(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + if m.SourceContext != nil { + dAtA[i] = 0x22 + i++ + i = encodeVarintType(dAtA, i, uint64(m.SourceContext.Size())) + n2, err := m.SourceContext.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n2 + } + if m.Syntax != 0 { + dAtA[i] = 0x28 + i++ + i = encodeVarintType(dAtA, i, uint64(m.Syntax)) + } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } + return i, nil +} + +func (m *EnumValue) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *EnumValue) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Name) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintType(dAtA, i, uint64(len(m.Name))) + i += copy(dAtA[i:], m.Name) + } + if m.Number != 0 { + dAtA[i] = 0x10 + i++ + i = encodeVarintType(dAtA, i, uint64(m.Number)) + } + if len(m.Options) > 0 { + for _, msg := range m.Options { + dAtA[i] = 0x1a + i++ + i = encodeVarintType(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } + return i, nil +} + +func (m *Option) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Option) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Name) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintType(dAtA, i, uint64(len(m.Name))) + i += copy(dAtA[i:], m.Name) + } + if m.Value != nil { + dAtA[i] = 0x12 + i++ + i = encodeVarintType(dAtA, i, uint64(m.Value.Size())) + n3, err := m.Value.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n3 + } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } + return i, nil +} + +func encodeVarintType(dAtA []byte, offset int, v uint64) int { + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return offset + 1 +} +func NewPopulatedType(r randyType, easy bool) *Type { + this := &Type{} + this.Name = string(randStringType(r)) + if r.Intn(10) != 0 { + v1 := r.Intn(5) + this.Fields = make([]*Field, v1) + for i := 0; i < v1; i++ { + this.Fields[i] = NewPopulatedField(r, easy) + } + } + v2 := r.Intn(10) + this.Oneofs = make([]string, v2) + for i := 0; i < v2; i++ { + this.Oneofs[i] = string(randStringType(r)) + } + if r.Intn(10) != 0 { + v3 := r.Intn(5) + this.Options = make([]*Option, v3) + for i := 0; i < v3; i++ { + this.Options[i] = NewPopulatedOption(r, easy) + } + } + if r.Intn(10) != 0 { + this.SourceContext = NewPopulatedSourceContext(r, easy) + } + this.Syntax = Syntax([]int32{0, 1}[r.Intn(2)]) + if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedType(r, 7) + } + return this +} + +func NewPopulatedField(r randyType, easy bool) *Field { + this := &Field{} + this.Kind = Field_Kind([]int32{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}[r.Intn(19)]) + this.Cardinality = Field_Cardinality([]int32{0, 1, 2, 3}[r.Intn(4)]) + this.Number = int32(r.Int31()) + if r.Intn(2) == 0 { + this.Number *= -1 + } + this.Name = string(randStringType(r)) + this.TypeUrl = string(randStringType(r)) + this.OneofIndex = int32(r.Int31()) + if r.Intn(2) == 0 { + this.OneofIndex *= -1 + } + this.Packed = bool(bool(r.Intn(2) == 0)) + if r.Intn(10) != 0 { + v4 := r.Intn(5) + this.Options = make([]*Option, v4) + for i := 0; i < v4; i++ { + this.Options[i] = NewPopulatedOption(r, easy) + } + } + this.JsonName = string(randStringType(r)) + this.DefaultValue = string(randStringType(r)) + if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedType(r, 12) + } + return this +} + +func NewPopulatedEnum(r randyType, easy bool) *Enum { + this := &Enum{} + this.Name = string(randStringType(r)) + if r.Intn(10) != 0 { + v5 := r.Intn(5) + this.Enumvalue = make([]*EnumValue, v5) + for i := 0; i < v5; i++ { + this.Enumvalue[i] = NewPopulatedEnumValue(r, easy) + } + } + if r.Intn(10) != 0 { + v6 := r.Intn(5) + this.Options = make([]*Option, v6) + for i := 0; i < v6; i++ { + this.Options[i] = NewPopulatedOption(r, easy) + } + } + if r.Intn(10) != 0 { + this.SourceContext = NewPopulatedSourceContext(r, easy) + } + this.Syntax = Syntax([]int32{0, 1}[r.Intn(2)]) + if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedType(r, 6) + } + return this +} + +func NewPopulatedEnumValue(r randyType, easy bool) *EnumValue { + this := &EnumValue{} + this.Name = string(randStringType(r)) + this.Number = int32(r.Int31()) + if r.Intn(2) == 0 { + this.Number *= -1 + } + if r.Intn(10) != 0 { + v7 := r.Intn(5) + this.Options = make([]*Option, v7) + for i := 0; i < v7; i++ { + this.Options[i] = NewPopulatedOption(r, easy) + } + } + if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedType(r, 4) + } + return this +} + +func NewPopulatedOption(r randyType, easy bool) *Option { + this := &Option{} + this.Name = string(randStringType(r)) + if r.Intn(10) != 0 { + this.Value = NewPopulatedAny(r, easy) + } + if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedType(r, 3) + } + return this +} + +type randyType interface { + Float32() float32 + Float64() float64 + Int63() int64 + Int31() int32 + Uint32() uint32 + Intn(n int) int +} + +func randUTF8RuneType(r randyType) rune { + ru := r.Intn(62) + if ru < 10 { + return rune(ru + 48) + } else if ru < 36 { + return rune(ru + 55) + } + return rune(ru + 61) +} +func randStringType(r randyType) string { + v8 := r.Intn(100) + tmps := make([]rune, v8) + for i := 0; i < v8; i++ { + tmps[i] = randUTF8RuneType(r) + } + return string(tmps) +} +func randUnrecognizedType(r randyType, maxFieldNumber int) (dAtA []byte) { + l := r.Intn(5) + for i := 0; i < l; i++ { + wire := r.Intn(4) + if wire == 3 { + wire = 5 + } + fieldNumber := maxFieldNumber + r.Intn(100) + dAtA = randFieldType(dAtA, r, fieldNumber, wire) + } + return dAtA +} +func randFieldType(dAtA []byte, r randyType, fieldNumber int, wire int) []byte { + key := uint32(fieldNumber)<<3 | uint32(wire) + switch wire { + case 0: + dAtA = encodeVarintPopulateType(dAtA, uint64(key)) + v9 := r.Int63() + if r.Intn(2) == 0 { + v9 *= -1 + } + dAtA = encodeVarintPopulateType(dAtA, uint64(v9)) + case 1: + dAtA = encodeVarintPopulateType(dAtA, uint64(key)) + dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) + case 2: + dAtA = encodeVarintPopulateType(dAtA, uint64(key)) + ll := r.Intn(100) + dAtA = encodeVarintPopulateType(dAtA, uint64(ll)) + for j := 0; j < ll; j++ { + dAtA = append(dAtA, byte(r.Intn(256))) + } + default: + dAtA = encodeVarintPopulateType(dAtA, uint64(key)) + dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) + } + return dAtA +} +func encodeVarintPopulateType(dAtA []byte, v uint64) []byte { + for v >= 1<<7 { + dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80)) + v >>= 7 + } + dAtA = append(dAtA, uint8(v)) + return dAtA +} +func (m *Type) Size() (n int) { + var l int + _ = l + l = len(m.Name) + if l > 0 { + n += 1 + l + sovType(uint64(l)) + } + if len(m.Fields) > 0 { + for _, e := range m.Fields { + l = e.Size() + n += 1 + l + sovType(uint64(l)) + } + } + if len(m.Oneofs) > 0 { + for _, s := range m.Oneofs { + l = len(s) + n += 1 + l + sovType(uint64(l)) + } + } + if len(m.Options) > 0 { + for _, e := range m.Options { + l = e.Size() + n += 1 + l + sovType(uint64(l)) + } + } + if m.SourceContext != nil { + l = m.SourceContext.Size() + n += 1 + l + sovType(uint64(l)) + } + if m.Syntax != 0 { + n += 1 + sovType(uint64(m.Syntax)) + } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } + return n +} + +func (m *Field) Size() (n int) { + var l int + _ = l + if m.Kind != 0 { + n += 1 + sovType(uint64(m.Kind)) + } + if m.Cardinality != 0 { + n += 1 + sovType(uint64(m.Cardinality)) + } + if m.Number != 0 { + n += 1 + sovType(uint64(m.Number)) + } + l = len(m.Name) + if l > 0 { + n += 1 + l + sovType(uint64(l)) + } + l = len(m.TypeUrl) + if l > 0 { + n += 1 + l + sovType(uint64(l)) + } + if m.OneofIndex != 0 { + n += 1 + sovType(uint64(m.OneofIndex)) + } + if m.Packed { + n += 2 + } + if len(m.Options) > 0 { + for _, e := range m.Options { + l = e.Size() + n += 1 + l + sovType(uint64(l)) + } + } + l = len(m.JsonName) + if l > 0 { + n += 1 + l + sovType(uint64(l)) + } + l = len(m.DefaultValue) + if l > 0 { + n += 1 + l + sovType(uint64(l)) + } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } + return n +} + +func (m *Enum) Size() (n int) { + var l int + _ = l + l = len(m.Name) + if l > 0 { + n += 1 + l + sovType(uint64(l)) + } + if len(m.Enumvalue) > 0 { + for _, e := range m.Enumvalue { + l = e.Size() + n += 1 + l + sovType(uint64(l)) + } + } + if len(m.Options) > 0 { + for _, e := range m.Options { + l = e.Size() + n += 1 + l + sovType(uint64(l)) + } + } + if m.SourceContext != nil { + l = m.SourceContext.Size() + n += 1 + l + sovType(uint64(l)) + } + if m.Syntax != 0 { + n += 1 + sovType(uint64(m.Syntax)) + } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } + return n +} + +func (m *EnumValue) Size() (n int) { + var l int + _ = l + l = len(m.Name) + if l > 0 { + n += 1 + l + sovType(uint64(l)) + } + if m.Number != 0 { + n += 1 + sovType(uint64(m.Number)) + } + if len(m.Options) > 0 { + for _, e := range m.Options { + l = e.Size() + n += 1 + l + sovType(uint64(l)) + } + } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } + return n +} + +func (m *Option) Size() (n int) { + var l int + _ = l + l = len(m.Name) + if l > 0 { + n += 1 + l + sovType(uint64(l)) + } + if m.Value != nil { + l = m.Value.Size() + n += 1 + l + sovType(uint64(l)) + } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } + return n +} + +func sovType(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n +} +func sozType(x uint64) (n int) { + return sovType(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (this *Type) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Type{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Fields:` + strings.Replace(fmt.Sprintf("%v", this.Fields), "Field", "Field", 1) + `,`, + `Oneofs:` + fmt.Sprintf("%v", this.Oneofs) + `,`, + `Options:` + strings.Replace(fmt.Sprintf("%v", this.Options), "Option", "Option", 1) + `,`, + `SourceContext:` + strings.Replace(fmt.Sprintf("%v", this.SourceContext), "SourceContext", "SourceContext", 1) + `,`, + `Syntax:` + fmt.Sprintf("%v", this.Syntax) + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, + `}`, + }, "") + return s +} +func (this *Field) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Field{`, + `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`, + `Cardinality:` + fmt.Sprintf("%v", this.Cardinality) + `,`, + `Number:` + fmt.Sprintf("%v", this.Number) + `,`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `TypeUrl:` + fmt.Sprintf("%v", this.TypeUrl) + `,`, + `OneofIndex:` + fmt.Sprintf("%v", this.OneofIndex) + `,`, + `Packed:` + fmt.Sprintf("%v", this.Packed) + `,`, + `Options:` + strings.Replace(fmt.Sprintf("%v", this.Options), "Option", "Option", 1) + `,`, + `JsonName:` + fmt.Sprintf("%v", this.JsonName) + `,`, + `DefaultValue:` + fmt.Sprintf("%v", this.DefaultValue) + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, + `}`, + }, "") + return s +} +func (this *Enum) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Enum{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Enumvalue:` + strings.Replace(fmt.Sprintf("%v", this.Enumvalue), "EnumValue", "EnumValue", 1) + `,`, + `Options:` + strings.Replace(fmt.Sprintf("%v", this.Options), "Option", "Option", 1) + `,`, + `SourceContext:` + strings.Replace(fmt.Sprintf("%v", this.SourceContext), "SourceContext", "SourceContext", 1) + `,`, + `Syntax:` + fmt.Sprintf("%v", this.Syntax) + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, + `}`, + }, "") + return s +} +func (this *EnumValue) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&EnumValue{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Number:` + fmt.Sprintf("%v", this.Number) + `,`, + `Options:` + strings.Replace(fmt.Sprintf("%v", this.Options), "Option", "Option", 1) + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, + `}`, + }, "") + return s +} +func (this *Option) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Option{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Value:` + strings.Replace(fmt.Sprintf("%v", this.Value), "Any", "Any", 1) + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, + `}`, + }, "") + return s +} +func valueToStringType(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} +func (m *Type) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Type: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Type: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthType + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Fields", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthType + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Fields = append(m.Fields, &Field{}) + if err := m.Fields[len(m.Fields)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Oneofs", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthType + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Oneofs = append(m.Oneofs, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Options", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthType + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Options = append(m.Options, &Option{}) + if err := m.Options[len(m.Options)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SourceContext", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthType + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.SourceContext == nil { + m.SourceContext = &SourceContext{} + } + if err := m.SourceContext.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Syntax", wireType) + } + m.Syntax = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Syntax |= (Syntax(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipType(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthType + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Field) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Field: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Field: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Kind", wireType) + } + m.Kind = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Kind |= (Field_Kind(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Cardinality", wireType) + } + m.Cardinality = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Cardinality |= (Field_Cardinality(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Number", wireType) + } + m.Number = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Number |= (int32(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthType + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TypeUrl", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthType + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.TypeUrl = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 7: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field OneofIndex", wireType) + } + m.OneofIndex = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.OneofIndex |= (int32(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 8: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Packed", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + m.Packed = bool(v != 0) + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Options", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthType + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Options = append(m.Options, &Option{}) + if err := m.Options[len(m.Options)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 10: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field JsonName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthType + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.JsonName = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 11: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DefaultValue", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthType + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.DefaultValue = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipType(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthType + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Enum) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Enum: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Enum: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthType + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Enumvalue", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthType + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Enumvalue = append(m.Enumvalue, &EnumValue{}) + if err := m.Enumvalue[len(m.Enumvalue)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Options", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthType + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Options = append(m.Options, &Option{}) + if err := m.Options[len(m.Options)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SourceContext", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthType + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.SourceContext == nil { + m.SourceContext = &SourceContext{} + } + if err := m.SourceContext.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Syntax", wireType) + } + m.Syntax = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Syntax |= (Syntax(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipType(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthType + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *EnumValue) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: EnumValue: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: EnumValue: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthType + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Number", wireType) + } + m.Number = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Number |= (int32(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Options", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthType + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Options = append(m.Options, &Option{}) + if err := m.Options[len(m.Options)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipType(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthType + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Option) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Option: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Option: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthType + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowType + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthType + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Value == nil { + m.Value = &Any{} + } + if err := m.Value.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipType(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthType + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipType(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowType + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowType + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowType + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + iNdEx += length + if length < 0 { + return 0, ErrInvalidLengthType + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowType + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipType(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} + +var ( + ErrInvalidLengthType = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowType = fmt.Errorf("proto: integer overflow") +) + +func init() { proto.RegisterFile("google/protobuf/type.proto", fileDescriptor_type_345e3aff58b7b252) } + +var fileDescriptor_type_345e3aff58b7b252 = []byte{ + // 844 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x55, 0xcf, 0x73, 0xda, 0x46, + 0x14, 0x66, 0x41, 0xc8, 0xe8, 0x61, 0xf0, 0x66, 0x93, 0x49, 0x14, 0x67, 0x46, 0x65, 0x68, 0x0f, + 0x4c, 0x0e, 0x78, 0x0a, 0x1e, 0x4f, 0xaf, 0x60, 0x64, 0xca, 0x98, 0x48, 0xea, 0x22, 0x9a, 0xb8, + 0x17, 0x06, 0x83, 0x9c, 0x21, 0x11, 0x2b, 0x06, 0x89, 0xd6, 0xdc, 0x7a, 0xeb, 0xa9, 0xff, 0x44, + 0x4f, 0x9d, 0x9e, 0xfb, 0x47, 0xf8, 0x98, 0x63, 0x8f, 0x35, 0xb9, 0xf4, 0x98, 0x63, 0x6e, 0xed, + 0xec, 0x0a, 0x64, 0xf1, 0xa3, 0x33, 0x6e, 0x73, 0xe3, 0x7d, 0xdf, 0xf7, 0x7e, 0xee, 0xd3, 0x03, + 0x0e, 0x5f, 0x7b, 0xde, 0x6b, 0xd7, 0x39, 0x9a, 0x4c, 0xbd, 0xc0, 0xbb, 0x9c, 0x5d, 0x1d, 0x05, + 0xf3, 0x89, 0x53, 0x16, 0x16, 0x39, 0x08, 0xb9, 0xf2, 0x8a, 0x3b, 0x7c, 0xba, 0x29, 0xee, 0xb3, + 0x79, 0xc8, 0x1e, 0x7e, 0xb1, 0x49, 0xf9, 0xde, 0x6c, 0x3a, 0x70, 0x7a, 0x03, 0x8f, 0x05, 0xce, + 0x75, 0x10, 0xaa, 0x8a, 0x3f, 0x27, 0x41, 0xb2, 0xe7, 0x13, 0x87, 0x10, 0x90, 0x58, 0x7f, 0xec, + 0xa8, 0xa8, 0x80, 0x4a, 0x0a, 0x15, 0xbf, 0x49, 0x19, 0xe4, 0xab, 0x91, 0xe3, 0x0e, 0x7d, 0x35, + 0x59, 0x48, 0x95, 0xb2, 0x95, 0xc7, 0xe5, 0x8d, 0xfc, 0xe5, 0x33, 0x4e, 0xd3, 0xa5, 0x8a, 0x3c, + 0x06, 0xd9, 0x63, 0x8e, 0x77, 0xe5, 0xab, 0xa9, 0x42, 0xaa, 0xa4, 0xd0, 0xa5, 0x45, 0xbe, 0x84, + 0x3d, 0x6f, 0x12, 0x8c, 0x3c, 0xe6, 0xab, 0x92, 0x08, 0xf4, 0x64, 0x2b, 0x90, 0x29, 0x78, 0xba, + 0xd2, 0x11, 0x1d, 0xf2, 0xeb, 0xf5, 0xaa, 0xe9, 0x02, 0x2a, 0x65, 0x2b, 0xda, 0x96, 0x67, 0x47, + 0xc8, 0x4e, 0x43, 0x15, 0xcd, 0xf9, 0x71, 0x93, 0x1c, 0x81, 0xec, 0xcf, 0x59, 0xd0, 0xbf, 0x56, + 0xe5, 0x02, 0x2a, 0xe5, 0x77, 0x24, 0xee, 0x08, 0x9a, 0x2e, 0x65, 0xc5, 0xdf, 0x65, 0x48, 0x8b, + 0xa6, 0xc8, 0x11, 0x48, 0x6f, 0x47, 0x6c, 0x28, 0x06, 0x92, 0xaf, 0x3c, 0xdb, 0xdd, 0x7a, 0xf9, + 0x7c, 0xc4, 0x86, 0x54, 0x08, 0x49, 0x03, 0xb2, 0x83, 0xfe, 0x74, 0x38, 0x62, 0x7d, 0x77, 0x14, + 0xcc, 0xd5, 0xa4, 0xf0, 0x2b, 0xfe, 0x8b, 0xdf, 0xe9, 0x9d, 0x92, 0xc6, 0xdd, 0xf8, 0x0c, 0xd9, + 0x6c, 0x7c, 0xe9, 0x4c, 0xd5, 0x54, 0x01, 0x95, 0xd2, 0x74, 0x69, 0x45, 0xef, 0x23, 0xc5, 0xde, + 0xe7, 0x29, 0x64, 0xf8, 0x72, 0xf4, 0x66, 0x53, 0x57, 0xf4, 0xa7, 0xd0, 0x3d, 0x6e, 0x77, 0xa7, + 0x2e, 0xf9, 0x0c, 0xb2, 0x62, 0xf8, 0xbd, 0x11, 0x1b, 0x3a, 0xd7, 0xea, 0x9e, 0x88, 0x05, 0x02, + 0x6a, 0x71, 0x84, 0xe7, 0x99, 0xf4, 0x07, 0x6f, 0x9d, 0xa1, 0x9a, 0x29, 0xa0, 0x52, 0x86, 0x2e, + 0xad, 0xf8, 0x5b, 0x29, 0xf7, 0x7c, 0xab, 0x67, 0xa0, 0xbc, 0xf1, 0x3d, 0xd6, 0x13, 0xf5, 0x81, + 0xa8, 0x23, 0xc3, 0x01, 0x83, 0xd7, 0xf8, 0x39, 0xe4, 0x86, 0xce, 0x55, 0x7f, 0xe6, 0x06, 0xbd, + 0xef, 0xfb, 0xee, 0xcc, 0x51, 0xb3, 0x42, 0xb0, 0xbf, 0x04, 0xbf, 0xe5, 0x58, 0xf1, 0x26, 0x09, + 0x12, 0x9f, 0x24, 0xc1, 0xb0, 0x6f, 0x5f, 0x58, 0x7a, 0xaf, 0x6b, 0x9c, 0x1b, 0xe6, 0x4b, 0x03, + 0x27, 0xc8, 0x01, 0x64, 0x05, 0xd2, 0x30, 0xbb, 0xf5, 0xb6, 0x8e, 0x11, 0xc9, 0x03, 0x08, 0xe0, + 0xac, 0x6d, 0xd6, 0x6c, 0x9c, 0x8c, 0xec, 0x96, 0x61, 0x9f, 0x1c, 0xe3, 0x54, 0xe4, 0xd0, 0x0d, + 0x01, 0x29, 0x2e, 0xa8, 0x56, 0x70, 0x3a, 0xca, 0x71, 0xd6, 0x7a, 0xa5, 0x37, 0x4e, 0x8e, 0xb1, + 0xbc, 0x8e, 0x54, 0x2b, 0x78, 0x8f, 0xe4, 0x40, 0x11, 0x48, 0xdd, 0x34, 0xdb, 0x38, 0x13, 0xc5, + 0xec, 0xd8, 0xb4, 0x65, 0x34, 0xb1, 0x12, 0xc5, 0x6c, 0x52, 0xb3, 0x6b, 0x61, 0x88, 0x22, 0xbc, + 0xd0, 0x3b, 0x9d, 0x5a, 0x53, 0xc7, 0xd9, 0x48, 0x51, 0xbf, 0xb0, 0xf5, 0x0e, 0xde, 0x5f, 0x2b, + 0xab, 0x5a, 0xc1, 0xb9, 0x28, 0x85, 0x6e, 0x74, 0x5f, 0xe0, 0x3c, 0x79, 0x00, 0xb9, 0x30, 0xc5, + 0xaa, 0x88, 0x83, 0x0d, 0xe8, 0xe4, 0x18, 0xe3, 0xbb, 0x42, 0xc2, 0x28, 0x0f, 0xd6, 0x80, 0x93, + 0x63, 0x4c, 0x8a, 0x01, 0x64, 0x63, 0xbb, 0x45, 0x9e, 0xc0, 0xc3, 0xd3, 0x1a, 0x6d, 0xb4, 0x8c, + 0x5a, 0xbb, 0x65, 0x5f, 0xc4, 0xe6, 0xaa, 0xc2, 0xa3, 0x38, 0x61, 0x5a, 0x76, 0xcb, 0x34, 0x6a, + 0x6d, 0x8c, 0x36, 0x19, 0xaa, 0x7f, 0xd3, 0x6d, 0x51, 0xbd, 0x81, 0x93, 0xdb, 0x8c, 0xa5, 0xd7, + 0x6c, 0xbd, 0x81, 0x53, 0xc5, 0xbf, 0x11, 0x48, 0x3a, 0x9b, 0x8d, 0x77, 0x9e, 0x91, 0xaf, 0x40, + 0x71, 0xd8, 0x6c, 0x1c, 0x3e, 0x7f, 0x78, 0x49, 0x0e, 0xb7, 0x96, 0x8a, 0x7b, 0x8b, 0x65, 0xa0, + 0x77, 0xe2, 0xf8, 0x32, 0xa6, 0xfe, 0xf7, 0xe1, 0x90, 0x3e, 0xed, 0x70, 0xa4, 0xef, 0x77, 0x38, + 0xde, 0x80, 0x12, 0xb5, 0xb0, 0x73, 0x0a, 0x77, 0x1f, 0x76, 0x72, 0xed, 0xc3, 0xfe, 0xef, 0x3d, + 0x16, 0xbf, 0x06, 0x39, 0x84, 0x76, 0x26, 0x7a, 0x0e, 0xe9, 0xd5, 0xa8, 0x79, 0xe3, 0x8f, 0xb6, + 0xc2, 0xd5, 0xd8, 0x9c, 0x86, 0x92, 0xe7, 0x65, 0x90, 0xc3, 0x3e, 0xf8, 0xb2, 0x75, 0x2e, 0x0c, + 0xbb, 0xf6, 0xaa, 0x67, 0x51, 0xd3, 0x36, 0x2b, 0x38, 0xb1, 0x09, 0x55, 0x31, 0xaa, 0xff, 0x84, + 0xde, 0xdd, 0x6a, 0x89, 0x3f, 0x6e, 0xb5, 0xc4, 0x87, 0x5b, 0x0d, 0x7d, 0xbc, 0xd5, 0xd0, 0x8f, + 0x0b, 0x0d, 0xfd, 0xba, 0xd0, 0xd0, 0xcd, 0x42, 0x43, 0xef, 0x16, 0x1a, 0xfa, 0x73, 0xa1, 0xa1, + 0xbf, 0x16, 0x5a, 0xe2, 0x03, 0xc7, 0xdf, 0x6b, 0xe8, 0xe6, 0xbd, 0x86, 0xe0, 0xe1, 0xc0, 0x1b, + 0x6f, 0x96, 0x51, 0x57, 0xf8, 0xff, 0x8e, 0xc5, 0x2d, 0x0b, 0x7d, 0x97, 0xe6, 0x87, 0xcb, 0xff, + 0x88, 0xd0, 0x2f, 0xc9, 0x54, 0xd3, 0xaa, 0xff, 0x96, 0xd4, 0x9a, 0xa1, 0xdc, 0x5a, 0x55, 0xfd, + 0xd2, 0x71, 0xdd, 0x73, 0xe6, 0xfd, 0xc0, 0xb8, 0x9b, 0x7f, 0x29, 0x8b, 0x38, 0xd5, 0x7f, 0x02, + 0x00, 0x00, 0xff, 0xff, 0x74, 0x97, 0x69, 0x12, 0x2f, 0x07, 0x00, 0x00, +} diff --git a/vendor/github.com/gogo/protobuf/types/wrappers.pb.go b/vendor/github.com/gogo/protobuf/types/wrappers.pb.go index 18b384ea3..9ec3c54c4 100644 --- a/vendor/github.com/gogo/protobuf/types/wrappers.pb.go +++ b/vendor/github.com/gogo/protobuf/types/wrappers.pb.go @@ -1,23 +1,6 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: wrappers.proto - -/* -Package types is a generated protocol buffer package. - -It is generated from these files: - wrappers.proto - -It has these top-level messages: - DoubleValue - FloatValue - Int64Value - UInt64Value - Int32Value - UInt32Value - BoolValue - StringValue - BytesValue -*/ +// source: google/protobuf/wrappers.proto + package types import proto "github.com/gogo/protobuf/proto" @@ -29,7 +12,7 @@ import bytes "bytes" import strings "strings" import reflect "reflect" -import binary "encoding/binary" +import encoding_binary "encoding/binary" import io "io" @@ -49,13 +32,44 @@ const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package // The JSON representation for `DoubleValue` is JSON number. type DoubleValue struct { // The double value. - Value float64 `protobuf:"fixed64,1,opt,name=value,proto3" json:"value,omitempty"` + Value float64 `protobuf:"fixed64,1,opt,name=value,proto3" json:"value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *DoubleValue) Reset() { *m = DoubleValue{} } -func (*DoubleValue) ProtoMessage() {} -func (*DoubleValue) Descriptor() ([]byte, []int) { return fileDescriptorWrappers, []int{0} } -func (*DoubleValue) XXX_WellKnownType() string { return "DoubleValue" } +func (m *DoubleValue) Reset() { *m = DoubleValue{} } +func (*DoubleValue) ProtoMessage() {} +func (*DoubleValue) Descriptor() ([]byte, []int) { + return fileDescriptor_wrappers_b0966e4a6118a07f, []int{0} +} +func (*DoubleValue) XXX_WellKnownType() string { return "DoubleValue" } +func (m *DoubleValue) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *DoubleValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_DoubleValue.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *DoubleValue) XXX_Merge(src proto.Message) { + xxx_messageInfo_DoubleValue.Merge(dst, src) +} +func (m *DoubleValue) XXX_Size() int { + return m.Size() +} +func (m *DoubleValue) XXX_DiscardUnknown() { + xxx_messageInfo_DoubleValue.DiscardUnknown(m) +} + +var xxx_messageInfo_DoubleValue proto.InternalMessageInfo func (m *DoubleValue) GetValue() float64 { if m != nil { @@ -64,18 +78,53 @@ func (m *DoubleValue) GetValue() float64 { return 0 } +func (*DoubleValue) XXX_MessageName() string { + return "google.protobuf.DoubleValue" +} + // Wrapper message for `float`. // // The JSON representation for `FloatValue` is JSON number. type FloatValue struct { // The float value. - Value float32 `protobuf:"fixed32,1,opt,name=value,proto3" json:"value,omitempty"` + Value float32 `protobuf:"fixed32,1,opt,name=value,proto3" json:"value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *FloatValue) Reset() { *m = FloatValue{} } +func (*FloatValue) ProtoMessage() {} +func (*FloatValue) Descriptor() ([]byte, []int) { + return fileDescriptor_wrappers_b0966e4a6118a07f, []int{1} +} +func (*FloatValue) XXX_WellKnownType() string { return "FloatValue" } +func (m *FloatValue) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *FloatValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_FloatValue.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *FloatValue) XXX_Merge(src proto.Message) { + xxx_messageInfo_FloatValue.Merge(dst, src) +} +func (m *FloatValue) XXX_Size() int { + return m.Size() +} +func (m *FloatValue) XXX_DiscardUnknown() { + xxx_messageInfo_FloatValue.DiscardUnknown(m) } -func (m *FloatValue) Reset() { *m = FloatValue{} } -func (*FloatValue) ProtoMessage() {} -func (*FloatValue) Descriptor() ([]byte, []int) { return fileDescriptorWrappers, []int{1} } -func (*FloatValue) XXX_WellKnownType() string { return "FloatValue" } +var xxx_messageInfo_FloatValue proto.InternalMessageInfo func (m *FloatValue) GetValue() float32 { if m != nil { @@ -84,18 +133,53 @@ func (m *FloatValue) GetValue() float32 { return 0 } +func (*FloatValue) XXX_MessageName() string { + return "google.protobuf.FloatValue" +} + // Wrapper message for `int64`. // // The JSON representation for `Int64Value` is JSON string. type Int64Value struct { // The int64 value. - Value int64 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` + Value int64 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Int64Value) Reset() { *m = Int64Value{} } +func (*Int64Value) ProtoMessage() {} +func (*Int64Value) Descriptor() ([]byte, []int) { + return fileDescriptor_wrappers_b0966e4a6118a07f, []int{2} +} +func (*Int64Value) XXX_WellKnownType() string { return "Int64Value" } +func (m *Int64Value) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Int64Value) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Int64Value.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *Int64Value) XXX_Merge(src proto.Message) { + xxx_messageInfo_Int64Value.Merge(dst, src) +} +func (m *Int64Value) XXX_Size() int { + return m.Size() +} +func (m *Int64Value) XXX_DiscardUnknown() { + xxx_messageInfo_Int64Value.DiscardUnknown(m) } -func (m *Int64Value) Reset() { *m = Int64Value{} } -func (*Int64Value) ProtoMessage() {} -func (*Int64Value) Descriptor() ([]byte, []int) { return fileDescriptorWrappers, []int{2} } -func (*Int64Value) XXX_WellKnownType() string { return "Int64Value" } +var xxx_messageInfo_Int64Value proto.InternalMessageInfo func (m *Int64Value) GetValue() int64 { if m != nil { @@ -104,18 +188,53 @@ func (m *Int64Value) GetValue() int64 { return 0 } +func (*Int64Value) XXX_MessageName() string { + return "google.protobuf.Int64Value" +} + // Wrapper message for `uint64`. // // The JSON representation for `UInt64Value` is JSON string. type UInt64Value struct { // The uint64 value. - Value uint64 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` + Value uint64 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *UInt64Value) Reset() { *m = UInt64Value{} } +func (*UInt64Value) ProtoMessage() {} +func (*UInt64Value) Descriptor() ([]byte, []int) { + return fileDescriptor_wrappers_b0966e4a6118a07f, []int{3} +} +func (*UInt64Value) XXX_WellKnownType() string { return "UInt64Value" } +func (m *UInt64Value) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *UInt64Value) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_UInt64Value.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *UInt64Value) XXX_Merge(src proto.Message) { + xxx_messageInfo_UInt64Value.Merge(dst, src) +} +func (m *UInt64Value) XXX_Size() int { + return m.Size() +} +func (m *UInt64Value) XXX_DiscardUnknown() { + xxx_messageInfo_UInt64Value.DiscardUnknown(m) } -func (m *UInt64Value) Reset() { *m = UInt64Value{} } -func (*UInt64Value) ProtoMessage() {} -func (*UInt64Value) Descriptor() ([]byte, []int) { return fileDescriptorWrappers, []int{3} } -func (*UInt64Value) XXX_WellKnownType() string { return "UInt64Value" } +var xxx_messageInfo_UInt64Value proto.InternalMessageInfo func (m *UInt64Value) GetValue() uint64 { if m != nil { @@ -124,18 +243,53 @@ func (m *UInt64Value) GetValue() uint64 { return 0 } +func (*UInt64Value) XXX_MessageName() string { + return "google.protobuf.UInt64Value" +} + // Wrapper message for `int32`. // // The JSON representation for `Int32Value` is JSON number. type Int32Value struct { // The int32 value. - Value int32 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` + Value int32 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *Int32Value) Reset() { *m = Int32Value{} } -func (*Int32Value) ProtoMessage() {} -func (*Int32Value) Descriptor() ([]byte, []int) { return fileDescriptorWrappers, []int{4} } -func (*Int32Value) XXX_WellKnownType() string { return "Int32Value" } +func (m *Int32Value) Reset() { *m = Int32Value{} } +func (*Int32Value) ProtoMessage() {} +func (*Int32Value) Descriptor() ([]byte, []int) { + return fileDescriptor_wrappers_b0966e4a6118a07f, []int{4} +} +func (*Int32Value) XXX_WellKnownType() string { return "Int32Value" } +func (m *Int32Value) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Int32Value) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Int32Value.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *Int32Value) XXX_Merge(src proto.Message) { + xxx_messageInfo_Int32Value.Merge(dst, src) +} +func (m *Int32Value) XXX_Size() int { + return m.Size() +} +func (m *Int32Value) XXX_DiscardUnknown() { + xxx_messageInfo_Int32Value.DiscardUnknown(m) +} + +var xxx_messageInfo_Int32Value proto.InternalMessageInfo func (m *Int32Value) GetValue() int32 { if m != nil { @@ -144,18 +298,53 @@ func (m *Int32Value) GetValue() int32 { return 0 } +func (*Int32Value) XXX_MessageName() string { + return "google.protobuf.Int32Value" +} + // Wrapper message for `uint32`. // // The JSON representation for `UInt32Value` is JSON number. type UInt32Value struct { // The uint32 value. - Value uint32 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` + Value uint32 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *UInt32Value) Reset() { *m = UInt32Value{} } -func (*UInt32Value) ProtoMessage() {} -func (*UInt32Value) Descriptor() ([]byte, []int) { return fileDescriptorWrappers, []int{5} } -func (*UInt32Value) XXX_WellKnownType() string { return "UInt32Value" } +func (m *UInt32Value) Reset() { *m = UInt32Value{} } +func (*UInt32Value) ProtoMessage() {} +func (*UInt32Value) Descriptor() ([]byte, []int) { + return fileDescriptor_wrappers_b0966e4a6118a07f, []int{5} +} +func (*UInt32Value) XXX_WellKnownType() string { return "UInt32Value" } +func (m *UInt32Value) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *UInt32Value) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_UInt32Value.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *UInt32Value) XXX_Merge(src proto.Message) { + xxx_messageInfo_UInt32Value.Merge(dst, src) +} +func (m *UInt32Value) XXX_Size() int { + return m.Size() +} +func (m *UInt32Value) XXX_DiscardUnknown() { + xxx_messageInfo_UInt32Value.DiscardUnknown(m) +} + +var xxx_messageInfo_UInt32Value proto.InternalMessageInfo func (m *UInt32Value) GetValue() uint32 { if m != nil { @@ -164,18 +353,53 @@ func (m *UInt32Value) GetValue() uint32 { return 0 } +func (*UInt32Value) XXX_MessageName() string { + return "google.protobuf.UInt32Value" +} + // Wrapper message for `bool`. // // The JSON representation for `BoolValue` is JSON `true` and `false`. type BoolValue struct { // The bool value. - Value bool `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` + Value bool `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *BoolValue) Reset() { *m = BoolValue{} } +func (*BoolValue) ProtoMessage() {} +func (*BoolValue) Descriptor() ([]byte, []int) { + return fileDescriptor_wrappers_b0966e4a6118a07f, []int{6} +} +func (*BoolValue) XXX_WellKnownType() string { return "BoolValue" } +func (m *BoolValue) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *BoolValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_BoolValue.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *BoolValue) XXX_Merge(src proto.Message) { + xxx_messageInfo_BoolValue.Merge(dst, src) +} +func (m *BoolValue) XXX_Size() int { + return m.Size() +} +func (m *BoolValue) XXX_DiscardUnknown() { + xxx_messageInfo_BoolValue.DiscardUnknown(m) } -func (m *BoolValue) Reset() { *m = BoolValue{} } -func (*BoolValue) ProtoMessage() {} -func (*BoolValue) Descriptor() ([]byte, []int) { return fileDescriptorWrappers, []int{6} } -func (*BoolValue) XXX_WellKnownType() string { return "BoolValue" } +var xxx_messageInfo_BoolValue proto.InternalMessageInfo func (m *BoolValue) GetValue() bool { if m != nil { @@ -184,18 +408,53 @@ func (m *BoolValue) GetValue() bool { return false } +func (*BoolValue) XXX_MessageName() string { + return "google.protobuf.BoolValue" +} + // Wrapper message for `string`. // // The JSON representation for `StringValue` is JSON string. type StringValue struct { // The string value. - Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` + Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *StringValue) Reset() { *m = StringValue{} } -func (*StringValue) ProtoMessage() {} -func (*StringValue) Descriptor() ([]byte, []int) { return fileDescriptorWrappers, []int{7} } -func (*StringValue) XXX_WellKnownType() string { return "StringValue" } +func (m *StringValue) Reset() { *m = StringValue{} } +func (*StringValue) ProtoMessage() {} +func (*StringValue) Descriptor() ([]byte, []int) { + return fileDescriptor_wrappers_b0966e4a6118a07f, []int{7} +} +func (*StringValue) XXX_WellKnownType() string { return "StringValue" } +func (m *StringValue) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *StringValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_StringValue.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *StringValue) XXX_Merge(src proto.Message) { + xxx_messageInfo_StringValue.Merge(dst, src) +} +func (m *StringValue) XXX_Size() int { + return m.Size() +} +func (m *StringValue) XXX_DiscardUnknown() { + xxx_messageInfo_StringValue.DiscardUnknown(m) +} + +var xxx_messageInfo_StringValue proto.InternalMessageInfo func (m *StringValue) GetValue() string { if m != nil { @@ -204,18 +463,53 @@ func (m *StringValue) GetValue() string { return "" } +func (*StringValue) XXX_MessageName() string { + return "google.protobuf.StringValue" +} + // Wrapper message for `bytes`. // // The JSON representation for `BytesValue` is JSON string. type BytesValue struct { // The bytes value. - Value []byte `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` + Value []byte `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *BytesValue) Reset() { *m = BytesValue{} } -func (*BytesValue) ProtoMessage() {} -func (*BytesValue) Descriptor() ([]byte, []int) { return fileDescriptorWrappers, []int{8} } -func (*BytesValue) XXX_WellKnownType() string { return "BytesValue" } +func (m *BytesValue) Reset() { *m = BytesValue{} } +func (*BytesValue) ProtoMessage() {} +func (*BytesValue) Descriptor() ([]byte, []int) { + return fileDescriptor_wrappers_b0966e4a6118a07f, []int{8} +} +func (*BytesValue) XXX_WellKnownType() string { return "BytesValue" } +func (m *BytesValue) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *BytesValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_BytesValue.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalTo(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (dst *BytesValue) XXX_Merge(src proto.Message) { + xxx_messageInfo_BytesValue.Merge(dst, src) +} +func (m *BytesValue) XXX_Size() int { + return m.Size() +} +func (m *BytesValue) XXX_DiscardUnknown() { + xxx_messageInfo_BytesValue.DiscardUnknown(m) +} + +var xxx_messageInfo_BytesValue proto.InternalMessageInfo func (m *BytesValue) GetValue() []byte { if m != nil { @@ -224,6 +518,9 @@ func (m *BytesValue) GetValue() []byte { return nil } +func (*BytesValue) XXX_MessageName() string { + return "google.protobuf.BytesValue" +} func init() { proto.RegisterType((*DoubleValue)(nil), "google.protobuf.DoubleValue") proto.RegisterType((*FloatValue)(nil), "google.protobuf.FloatValue") @@ -266,6 +563,9 @@ func (this *DoubleValue) Compare(that interface{}) int { } return 1 } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } return 0 } func (this *FloatValue) Compare(that interface{}) int { @@ -299,6 +599,9 @@ func (this *FloatValue) Compare(that interface{}) int { } return 1 } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } return 0 } func (this *Int64Value) Compare(that interface{}) int { @@ -332,6 +635,9 @@ func (this *Int64Value) Compare(that interface{}) int { } return 1 } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } return 0 } func (this *UInt64Value) Compare(that interface{}) int { @@ -365,6 +671,9 @@ func (this *UInt64Value) Compare(that interface{}) int { } return 1 } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } return 0 } func (this *Int32Value) Compare(that interface{}) int { @@ -398,6 +707,9 @@ func (this *Int32Value) Compare(that interface{}) int { } return 1 } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } return 0 } func (this *UInt32Value) Compare(that interface{}) int { @@ -431,6 +743,9 @@ func (this *UInt32Value) Compare(that interface{}) int { } return 1 } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } return 0 } func (this *BoolValue) Compare(that interface{}) int { @@ -464,6 +779,9 @@ func (this *BoolValue) Compare(that interface{}) int { } return 1 } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } return 0 } func (this *StringValue) Compare(that interface{}) int { @@ -497,6 +815,9 @@ func (this *StringValue) Compare(that interface{}) int { } return 1 } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } return 0 } func (this *BytesValue) Compare(that interface{}) int { @@ -527,6 +848,9 @@ func (this *BytesValue) Compare(that interface{}) int { if c := bytes.Compare(this.Value, that1.Value); c != 0 { return c } + if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { + return c + } return 0 } func (this *DoubleValue) Equal(that interface{}) bool { @@ -551,6 +875,9 @@ func (this *DoubleValue) Equal(that interface{}) bool { if this.Value != that1.Value { return false } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } return true } func (this *FloatValue) Equal(that interface{}) bool { @@ -575,6 +902,9 @@ func (this *FloatValue) Equal(that interface{}) bool { if this.Value != that1.Value { return false } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } return true } func (this *Int64Value) Equal(that interface{}) bool { @@ -599,6 +929,9 @@ func (this *Int64Value) Equal(that interface{}) bool { if this.Value != that1.Value { return false } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } return true } func (this *UInt64Value) Equal(that interface{}) bool { @@ -623,6 +956,9 @@ func (this *UInt64Value) Equal(that interface{}) bool { if this.Value != that1.Value { return false } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } return true } func (this *Int32Value) Equal(that interface{}) bool { @@ -647,6 +983,9 @@ func (this *Int32Value) Equal(that interface{}) bool { if this.Value != that1.Value { return false } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } return true } func (this *UInt32Value) Equal(that interface{}) bool { @@ -671,6 +1010,9 @@ func (this *UInt32Value) Equal(that interface{}) bool { if this.Value != that1.Value { return false } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } return true } func (this *BoolValue) Equal(that interface{}) bool { @@ -695,6 +1037,9 @@ func (this *BoolValue) Equal(that interface{}) bool { if this.Value != that1.Value { return false } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } return true } func (this *StringValue) Equal(that interface{}) bool { @@ -719,6 +1064,9 @@ func (this *StringValue) Equal(that interface{}) bool { if this.Value != that1.Value { return false } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } return true } func (this *BytesValue) Equal(that interface{}) bool { @@ -743,6 +1091,9 @@ func (this *BytesValue) Equal(that interface{}) bool { if !bytes.Equal(this.Value, that1.Value) { return false } + if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { + return false + } return true } func (this *DoubleValue) GoString() string { @@ -752,6 +1103,9 @@ func (this *DoubleValue) GoString() string { s := make([]string, 0, 5) s = append(s, "&types.DoubleValue{") s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n") + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } s = append(s, "}") return strings.Join(s, "") } @@ -762,6 +1116,9 @@ func (this *FloatValue) GoString() string { s := make([]string, 0, 5) s = append(s, "&types.FloatValue{") s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n") + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } s = append(s, "}") return strings.Join(s, "") } @@ -772,6 +1129,9 @@ func (this *Int64Value) GoString() string { s := make([]string, 0, 5) s = append(s, "&types.Int64Value{") s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n") + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } s = append(s, "}") return strings.Join(s, "") } @@ -782,6 +1142,9 @@ func (this *UInt64Value) GoString() string { s := make([]string, 0, 5) s = append(s, "&types.UInt64Value{") s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n") + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } s = append(s, "}") return strings.Join(s, "") } @@ -792,6 +1155,9 @@ func (this *Int32Value) GoString() string { s := make([]string, 0, 5) s = append(s, "&types.Int32Value{") s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n") + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } s = append(s, "}") return strings.Join(s, "") } @@ -802,6 +1168,9 @@ func (this *UInt32Value) GoString() string { s := make([]string, 0, 5) s = append(s, "&types.UInt32Value{") s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n") + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } s = append(s, "}") return strings.Join(s, "") } @@ -812,6 +1181,9 @@ func (this *BoolValue) GoString() string { s := make([]string, 0, 5) s = append(s, "&types.BoolValue{") s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n") + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } s = append(s, "}") return strings.Join(s, "") } @@ -822,6 +1194,9 @@ func (this *StringValue) GoString() string { s := make([]string, 0, 5) s = append(s, "&types.StringValue{") s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n") + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } s = append(s, "}") return strings.Join(s, "") } @@ -832,6 +1207,9 @@ func (this *BytesValue) GoString() string { s := make([]string, 0, 5) s = append(s, "&types.BytesValue{") s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n") + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } s = append(s, "}") return strings.Join(s, "") } @@ -861,9 +1239,12 @@ func (m *DoubleValue) MarshalTo(dAtA []byte) (int, error) { if m.Value != 0 { dAtA[i] = 0x9 i++ - binary.LittleEndian.PutUint64(dAtA[i:], uint64(math.Float64bits(float64(m.Value)))) + encoding_binary.LittleEndian.PutUint64(dAtA[i:], uint64(math.Float64bits(float64(m.Value)))) i += 8 } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } return i, nil } @@ -885,9 +1266,12 @@ func (m *FloatValue) MarshalTo(dAtA []byte) (int, error) { if m.Value != 0 { dAtA[i] = 0xd i++ - binary.LittleEndian.PutUint32(dAtA[i:], uint32(math.Float32bits(float32(m.Value)))) + encoding_binary.LittleEndian.PutUint32(dAtA[i:], uint32(math.Float32bits(float32(m.Value)))) i += 4 } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } return i, nil } @@ -911,6 +1295,9 @@ func (m *Int64Value) MarshalTo(dAtA []byte) (int, error) { i++ i = encodeVarintWrappers(dAtA, i, uint64(m.Value)) } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } return i, nil } @@ -934,6 +1321,9 @@ func (m *UInt64Value) MarshalTo(dAtA []byte) (int, error) { i++ i = encodeVarintWrappers(dAtA, i, uint64(m.Value)) } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } return i, nil } @@ -957,6 +1347,9 @@ func (m *Int32Value) MarshalTo(dAtA []byte) (int, error) { i++ i = encodeVarintWrappers(dAtA, i, uint64(m.Value)) } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } return i, nil } @@ -980,6 +1373,9 @@ func (m *UInt32Value) MarshalTo(dAtA []byte) (int, error) { i++ i = encodeVarintWrappers(dAtA, i, uint64(m.Value)) } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } return i, nil } @@ -1008,6 +1404,9 @@ func (m *BoolValue) MarshalTo(dAtA []byte) (int, error) { } i++ } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } return i, nil } @@ -1032,6 +1431,9 @@ func (m *StringValue) MarshalTo(dAtA []byte) (int, error) { i = encodeVarintWrappers(dAtA, i, uint64(len(m.Value))) i += copy(dAtA[i:], m.Value) } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } return i, nil } @@ -1056,6 +1458,9 @@ func (m *BytesValue) MarshalTo(dAtA []byte) (int, error) { i = encodeVarintWrappers(dAtA, i, uint64(len(m.Value))) i += copy(dAtA[i:], m.Value) } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } return i, nil } @@ -1075,6 +1480,7 @@ func NewPopulatedDoubleValue(r randyWrappers, easy bool) *DoubleValue { this.Value *= -1 } if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedWrappers(r, 2) } return this } @@ -1086,6 +1492,7 @@ func NewPopulatedFloatValue(r randyWrappers, easy bool) *FloatValue { this.Value *= -1 } if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedWrappers(r, 2) } return this } @@ -1097,6 +1504,7 @@ func NewPopulatedInt64Value(r randyWrappers, easy bool) *Int64Value { this.Value *= -1 } if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedWrappers(r, 2) } return this } @@ -1105,6 +1513,7 @@ func NewPopulatedUInt64Value(r randyWrappers, easy bool) *UInt64Value { this := &UInt64Value{} this.Value = uint64(uint64(r.Uint32())) if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedWrappers(r, 2) } return this } @@ -1116,6 +1525,7 @@ func NewPopulatedInt32Value(r randyWrappers, easy bool) *Int32Value { this.Value *= -1 } if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedWrappers(r, 2) } return this } @@ -1124,6 +1534,7 @@ func NewPopulatedUInt32Value(r randyWrappers, easy bool) *UInt32Value { this := &UInt32Value{} this.Value = uint32(r.Uint32()) if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedWrappers(r, 2) } return this } @@ -1132,6 +1543,7 @@ func NewPopulatedBoolValue(r randyWrappers, easy bool) *BoolValue { this := &BoolValue{} this.Value = bool(bool(r.Intn(2) == 0)) if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedWrappers(r, 2) } return this } @@ -1140,6 +1552,7 @@ func NewPopulatedStringValue(r randyWrappers, easy bool) *StringValue { this := &StringValue{} this.Value = string(randStringWrappers(r)) if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedWrappers(r, 2) } return this } @@ -1152,6 +1565,7 @@ func NewPopulatedBytesValue(r randyWrappers, easy bool) *BytesValue { this.Value[i] = byte(r.Intn(256)) } if !easy && r.Intn(10) != 0 { + this.XXX_unrecognized = randUnrecognizedWrappers(r, 2) } return this } @@ -1234,6 +1648,9 @@ func (m *DoubleValue) Size() (n int) { if m.Value != 0 { n += 9 } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } return n } @@ -1243,6 +1660,9 @@ func (m *FloatValue) Size() (n int) { if m.Value != 0 { n += 5 } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } return n } @@ -1252,6 +1672,9 @@ func (m *Int64Value) Size() (n int) { if m.Value != 0 { n += 1 + sovWrappers(uint64(m.Value)) } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } return n } @@ -1261,6 +1684,9 @@ func (m *UInt64Value) Size() (n int) { if m.Value != 0 { n += 1 + sovWrappers(uint64(m.Value)) } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } return n } @@ -1270,6 +1696,9 @@ func (m *Int32Value) Size() (n int) { if m.Value != 0 { n += 1 + sovWrappers(uint64(m.Value)) } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } return n } @@ -1279,6 +1708,9 @@ func (m *UInt32Value) Size() (n int) { if m.Value != 0 { n += 1 + sovWrappers(uint64(m.Value)) } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } return n } @@ -1288,6 +1720,9 @@ func (m *BoolValue) Size() (n int) { if m.Value { n += 2 } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } return n } @@ -1298,6 +1733,9 @@ func (m *StringValue) Size() (n int) { if l > 0 { n += 1 + l + sovWrappers(uint64(l)) } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } return n } @@ -1308,6 +1746,9 @@ func (m *BytesValue) Size() (n int) { if l > 0 { n += 1 + l + sovWrappers(uint64(l)) } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } return n } @@ -1330,6 +1771,7 @@ func (this *DoubleValue) String() string { } s := strings.Join([]string{`&DoubleValue{`, `Value:` + fmt.Sprintf("%v", this.Value) + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s @@ -1340,6 +1782,7 @@ func (this *FloatValue) String() string { } s := strings.Join([]string{`&FloatValue{`, `Value:` + fmt.Sprintf("%v", this.Value) + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s @@ -1350,6 +1793,7 @@ func (this *Int64Value) String() string { } s := strings.Join([]string{`&Int64Value{`, `Value:` + fmt.Sprintf("%v", this.Value) + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s @@ -1360,6 +1804,7 @@ func (this *UInt64Value) String() string { } s := strings.Join([]string{`&UInt64Value{`, `Value:` + fmt.Sprintf("%v", this.Value) + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s @@ -1370,6 +1815,7 @@ func (this *Int32Value) String() string { } s := strings.Join([]string{`&Int32Value{`, `Value:` + fmt.Sprintf("%v", this.Value) + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s @@ -1380,6 +1826,7 @@ func (this *UInt32Value) String() string { } s := strings.Join([]string{`&UInt32Value{`, `Value:` + fmt.Sprintf("%v", this.Value) + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s @@ -1390,6 +1837,7 @@ func (this *BoolValue) String() string { } s := strings.Join([]string{`&BoolValue{`, `Value:` + fmt.Sprintf("%v", this.Value) + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s @@ -1400,6 +1848,7 @@ func (this *StringValue) String() string { } s := strings.Join([]string{`&StringValue{`, `Value:` + fmt.Sprintf("%v", this.Value) + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s @@ -1410,6 +1859,7 @@ func (this *BytesValue) String() string { } s := strings.Join([]string{`&BytesValue{`, `Value:` + fmt.Sprintf("%v", this.Value) + `,`, + `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s @@ -1459,7 +1909,7 @@ func (m *DoubleValue) Unmarshal(dAtA []byte) error { if (iNdEx + 8) > l { return io.ErrUnexpectedEOF } - v = uint64(binary.LittleEndian.Uint64(dAtA[iNdEx:])) + v = uint64(encoding_binary.LittleEndian.Uint64(dAtA[iNdEx:])) iNdEx += 8 m.Value = float64(math.Float64frombits(v)) default: @@ -1474,6 +1924,7 @@ func (m *DoubleValue) Unmarshal(dAtA []byte) error { if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } @@ -1520,7 +1971,7 @@ func (m *FloatValue) Unmarshal(dAtA []byte) error { if (iNdEx + 4) > l { return io.ErrUnexpectedEOF } - v = uint32(binary.LittleEndian.Uint32(dAtA[iNdEx:])) + v = uint32(encoding_binary.LittleEndian.Uint32(dAtA[iNdEx:])) iNdEx += 4 m.Value = float32(math.Float32frombits(v)) default: @@ -1535,6 +1986,7 @@ func (m *FloatValue) Unmarshal(dAtA []byte) error { if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } @@ -1604,6 +2056,7 @@ func (m *Int64Value) Unmarshal(dAtA []byte) error { if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } @@ -1673,6 +2126,7 @@ func (m *UInt64Value) Unmarshal(dAtA []byte) error { if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } @@ -1742,6 +2196,7 @@ func (m *Int32Value) Unmarshal(dAtA []byte) error { if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } @@ -1811,6 +2266,7 @@ func (m *UInt32Value) Unmarshal(dAtA []byte) error { if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } @@ -1881,6 +2337,7 @@ func (m *BoolValue) Unmarshal(dAtA []byte) error { if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } @@ -1960,6 +2417,7 @@ func (m *StringValue) Unmarshal(dAtA []byte) error { if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } @@ -2041,6 +2499,7 @@ func (m *BytesValue) Unmarshal(dAtA []byte) error { if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } @@ -2155,26 +2614,29 @@ var ( ErrIntOverflowWrappers = fmt.Errorf("proto: integer overflow") ) -func init() { proto.RegisterFile("wrappers.proto", fileDescriptorWrappers) } - -var fileDescriptorWrappers = []byte{ - // 278 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x2b, 0x2f, 0x4a, 0x2c, - 0x28, 0x48, 0x2d, 0x2a, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x4f, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0x85, 0xf0, 0x92, 0x4a, 0xd3, 0x94, 0x94, 0xb9, 0xb8, 0x5d, 0xf2, 0x4b, 0x93, 0x72, - 0x52, 0xc3, 0x12, 0x73, 0x4a, 0x53, 0x85, 0x44, 0xb8, 0x58, 0xcb, 0x40, 0x0c, 0x09, 0x46, 0x05, - 0x46, 0x0d, 0xc6, 0x20, 0x08, 0x47, 0x49, 0x89, 0x8b, 0xcb, 0x2d, 0x27, 0x3f, 0xb1, 0x04, 0x8b, - 0x1a, 0x26, 0x24, 0x35, 0x9e, 0x79, 0x25, 0x66, 0x26, 0x58, 0xd4, 0x30, 0xc3, 0xd4, 0x28, 0x73, - 0x71, 0x87, 0xe2, 0x52, 0xc4, 0x82, 0x6a, 0x90, 0xb1, 0x11, 0x16, 0x35, 0xac, 0x68, 0x06, 0x61, - 0x55, 0xc4, 0x0b, 0x53, 0xa4, 0xc8, 0xc5, 0xe9, 0x94, 0x9f, 0x9f, 0x83, 0x45, 0x09, 0x07, 0x92, - 0x39, 0xc1, 0x25, 0x45, 0x99, 0x79, 0xe9, 0x58, 0x14, 0x71, 0x22, 0x39, 0xc8, 0xa9, 0xb2, 0x24, - 0xb5, 0x18, 0x8b, 0x1a, 0x1e, 0xa8, 0x1a, 0xa7, 0x76, 0xc6, 0x0b, 0x0f, 0xe5, 0x18, 0x6e, 0x3c, - 0x94, 0x63, 0xf8, 0xf0, 0x50, 0x8e, 0xf1, 0xc7, 0x43, 0x39, 0xc6, 0x86, 0x47, 0x72, 0x8c, 0x2b, - 0x1e, 0xc9, 0x31, 0x9e, 0x78, 0x24, 0xc7, 0x78, 0xe1, 0x91, 0x1c, 0xe3, 0x83, 0x47, 0x72, 0x8c, - 0x2f, 0x1e, 0xc9, 0x31, 0x7c, 0x00, 0x89, 0x3f, 0x96, 0x63, 0xe4, 0x12, 0x4e, 0xce, 0xcf, 0xd5, - 0x43, 0x8b, 0x0e, 0x27, 0xde, 0x70, 0x68, 0x7c, 0x05, 0x80, 0x44, 0x02, 0x18, 0xa3, 0x58, 0x4b, - 0x2a, 0x0b, 0x52, 0x8b, 0x7f, 0x30, 0x32, 0x2e, 0x62, 0x62, 0x76, 0x0f, 0x70, 0x5a, 0xc5, 0x24, - 0xe7, 0x0e, 0xd1, 0x12, 0x00, 0xd5, 0xa2, 0x17, 0x9e, 0x9a, 0x93, 0xe3, 0x9d, 0x97, 0x5f, 0x9e, - 0x17, 0x02, 0x52, 0x99, 0xc4, 0x06, 0x36, 0xcb, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0x23, 0x27, - 0x6c, 0x5f, 0xfa, 0x01, 0x00, 0x00, +func init() { + proto.RegisterFile("google/protobuf/wrappers.proto", fileDescriptor_wrappers_b0966e4a6118a07f) +} + +var fileDescriptor_wrappers_b0966e4a6118a07f = []byte{ + // 289 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4b, 0xcf, 0xcf, 0x4f, + 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0x2f, 0x4a, 0x2c, + 0x28, 0x48, 0x2d, 0x2a, 0xd6, 0x03, 0x8b, 0x08, 0xf1, 0x43, 0xe4, 0xf5, 0x60, 0xf2, 0x4a, 0xca, + 0x5c, 0xdc, 0x2e, 0xf9, 0xa5, 0x49, 0x39, 0xa9, 0x61, 0x89, 0x39, 0xa5, 0xa9, 0x42, 0x22, 0x5c, + 0xac, 0x65, 0x20, 0x86, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0x63, 0x10, 0x84, 0xa3, 0xa4, 0xc4, 0xc5, + 0xe5, 0x96, 0x93, 0x9f, 0x58, 0x82, 0x45, 0x0d, 0x13, 0x92, 0x1a, 0xcf, 0xbc, 0x12, 0x33, 0x13, + 0x2c, 0x6a, 0x98, 0x61, 0x6a, 0x94, 0xb9, 0xb8, 0x43, 0x71, 0x29, 0x62, 0x41, 0x35, 0xc8, 0xd8, + 0x08, 0x8b, 0x1a, 0x56, 0x34, 0x83, 0xb0, 0x2a, 0xe2, 0x85, 0x29, 0x52, 0xe4, 0xe2, 0x74, 0xca, + 0xcf, 0xcf, 0xc1, 0xa2, 0x84, 0x03, 0xc9, 0x9c, 0xe0, 0x92, 0xa2, 0xcc, 0xbc, 0x74, 0x2c, 0x8a, + 0x38, 0x91, 0x1c, 0xe4, 0x54, 0x59, 0x92, 0x5a, 0x8c, 0x45, 0x0d, 0x0f, 0x54, 0x8d, 0x53, 0x37, + 0xe3, 0x85, 0x87, 0x72, 0x0c, 0x37, 0x1e, 0xca, 0x31, 0x7c, 0x78, 0x28, 0xc7, 0xf8, 0xe3, 0xa1, + 0x1c, 0x63, 0xc3, 0x23, 0x39, 0xc6, 0x15, 0x8f, 0xe4, 0x18, 0x4f, 0x3c, 0x92, 0x63, 0xbc, 0xf0, + 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x17, 0x8f, 0xe4, 0x18, 0x3e, 0x80, 0xc4, 0x1f, 0xcb, + 0x31, 0x9e, 0x78, 0x2c, 0xc7, 0xc8, 0x25, 0x9c, 0x9c, 0x9f, 0xab, 0x87, 0x16, 0x25, 0x4e, 0xbc, + 0xe1, 0xd0, 0x38, 0x0b, 0x00, 0x89, 0x04, 0x30, 0x46, 0xb1, 0x96, 0x54, 0x16, 0xa4, 0x16, 0xff, + 0x60, 0x64, 0x5c, 0xc4, 0xc4, 0xec, 0x1e, 0xe0, 0xb4, 0x8a, 0x49, 0xce, 0x1d, 0xa2, 0x25, 0x00, + 0xaa, 0x45, 0x2f, 0x3c, 0x35, 0x27, 0xc7, 0x3b, 0x2f, 0xbf, 0x3c, 0x2f, 0x04, 0xa4, 0x32, 0x89, + 0x0d, 0x6c, 0x96, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0xff, 0xc7, 0xfe, 0x37, 0x0e, 0x02, 0x00, + 0x00, } diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go deleted file mode 100644 index e855b1f5c..000000000 --- a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go +++ /dev/null @@ -1,2812 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/descriptor.proto - -package descriptor // import "github.com/golang/protobuf/protoc-gen-go/descriptor" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type FieldDescriptorProto_Type int32 - -const ( - // 0 is reserved for errors. - // Order is weird for historical reasons. - FieldDescriptorProto_TYPE_DOUBLE FieldDescriptorProto_Type = 1 - FieldDescriptorProto_TYPE_FLOAT FieldDescriptorProto_Type = 2 - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if - // negative values are likely. - FieldDescriptorProto_TYPE_INT64 FieldDescriptorProto_Type = 3 - FieldDescriptorProto_TYPE_UINT64 FieldDescriptorProto_Type = 4 - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if - // negative values are likely. - FieldDescriptorProto_TYPE_INT32 FieldDescriptorProto_Type = 5 - FieldDescriptorProto_TYPE_FIXED64 FieldDescriptorProto_Type = 6 - FieldDescriptorProto_TYPE_FIXED32 FieldDescriptorProto_Type = 7 - FieldDescriptorProto_TYPE_BOOL FieldDescriptorProto_Type = 8 - FieldDescriptorProto_TYPE_STRING FieldDescriptorProto_Type = 9 - // Tag-delimited aggregate. - // Group type is deprecated and not supported in proto3. However, Proto3 - // implementations should still be able to parse the group wire format and - // treat group fields as unknown fields. - FieldDescriptorProto_TYPE_GROUP FieldDescriptorProto_Type = 10 - FieldDescriptorProto_TYPE_MESSAGE FieldDescriptorProto_Type = 11 - // New in version 2. - FieldDescriptorProto_TYPE_BYTES FieldDescriptorProto_Type = 12 - FieldDescriptorProto_TYPE_UINT32 FieldDescriptorProto_Type = 13 - FieldDescriptorProto_TYPE_ENUM FieldDescriptorProto_Type = 14 - FieldDescriptorProto_TYPE_SFIXED32 FieldDescriptorProto_Type = 15 - FieldDescriptorProto_TYPE_SFIXED64 FieldDescriptorProto_Type = 16 - FieldDescriptorProto_TYPE_SINT32 FieldDescriptorProto_Type = 17 - FieldDescriptorProto_TYPE_SINT64 FieldDescriptorProto_Type = 18 -) - -var FieldDescriptorProto_Type_name = map[int32]string{ - 1: "TYPE_DOUBLE", - 2: "TYPE_FLOAT", - 3: "TYPE_INT64", - 4: "TYPE_UINT64", - 5: "TYPE_INT32", - 6: "TYPE_FIXED64", - 7: "TYPE_FIXED32", - 8: "TYPE_BOOL", - 9: "TYPE_STRING", - 10: "TYPE_GROUP", - 11: "TYPE_MESSAGE", - 12: "TYPE_BYTES", - 13: "TYPE_UINT32", - 14: "TYPE_ENUM", - 15: "TYPE_SFIXED32", - 16: "TYPE_SFIXED64", - 17: "TYPE_SINT32", - 18: "TYPE_SINT64", -} -var FieldDescriptorProto_Type_value = map[string]int32{ - "TYPE_DOUBLE": 1, - "TYPE_FLOAT": 2, - "TYPE_INT64": 3, - "TYPE_UINT64": 4, - "TYPE_INT32": 5, - "TYPE_FIXED64": 6, - "TYPE_FIXED32": 7, - "TYPE_BOOL": 8, - "TYPE_STRING": 9, - "TYPE_GROUP": 10, - "TYPE_MESSAGE": 11, - "TYPE_BYTES": 12, - "TYPE_UINT32": 13, - "TYPE_ENUM": 14, - "TYPE_SFIXED32": 15, - "TYPE_SFIXED64": 16, - "TYPE_SINT32": 17, - "TYPE_SINT64": 18, -} - -func (x FieldDescriptorProto_Type) Enum() *FieldDescriptorProto_Type { - p := new(FieldDescriptorProto_Type) - *p = x - return p -} -func (x FieldDescriptorProto_Type) String() string { - return proto.EnumName(FieldDescriptorProto_Type_name, int32(x)) -} -func (x *FieldDescriptorProto_Type) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Type_value, data, "FieldDescriptorProto_Type") - if err != nil { - return err - } - *x = FieldDescriptorProto_Type(value) - return nil -} -func (FieldDescriptorProto_Type) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{4, 0} -} - -type FieldDescriptorProto_Label int32 - -const ( - // 0 is reserved for errors - FieldDescriptorProto_LABEL_OPTIONAL FieldDescriptorProto_Label = 1 - FieldDescriptorProto_LABEL_REQUIRED FieldDescriptorProto_Label = 2 - FieldDescriptorProto_LABEL_REPEATED FieldDescriptorProto_Label = 3 -) - -var FieldDescriptorProto_Label_name = map[int32]string{ - 1: "LABEL_OPTIONAL", - 2: "LABEL_REQUIRED", - 3: "LABEL_REPEATED", -} -var FieldDescriptorProto_Label_value = map[string]int32{ - "LABEL_OPTIONAL": 1, - "LABEL_REQUIRED": 2, - "LABEL_REPEATED": 3, -} - -func (x FieldDescriptorProto_Label) Enum() *FieldDescriptorProto_Label { - p := new(FieldDescriptorProto_Label) - *p = x - return p -} -func (x FieldDescriptorProto_Label) String() string { - return proto.EnumName(FieldDescriptorProto_Label_name, int32(x)) -} -func (x *FieldDescriptorProto_Label) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Label_value, data, "FieldDescriptorProto_Label") - if err != nil { - return err - } - *x = FieldDescriptorProto_Label(value) - return nil -} -func (FieldDescriptorProto_Label) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{4, 1} -} - -// Generated classes can be optimized for speed or code size. -type FileOptions_OptimizeMode int32 - -const ( - FileOptions_SPEED FileOptions_OptimizeMode = 1 - // etc. - FileOptions_CODE_SIZE FileOptions_OptimizeMode = 2 - FileOptions_LITE_RUNTIME FileOptions_OptimizeMode = 3 -) - -var FileOptions_OptimizeMode_name = map[int32]string{ - 1: "SPEED", - 2: "CODE_SIZE", - 3: "LITE_RUNTIME", -} -var FileOptions_OptimizeMode_value = map[string]int32{ - "SPEED": 1, - "CODE_SIZE": 2, - "LITE_RUNTIME": 3, -} - -func (x FileOptions_OptimizeMode) Enum() *FileOptions_OptimizeMode { - p := new(FileOptions_OptimizeMode) - *p = x - return p -} -func (x FileOptions_OptimizeMode) String() string { - return proto.EnumName(FileOptions_OptimizeMode_name, int32(x)) -} -func (x *FileOptions_OptimizeMode) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FileOptions_OptimizeMode_value, data, "FileOptions_OptimizeMode") - if err != nil { - return err - } - *x = FileOptions_OptimizeMode(value) - return nil -} -func (FileOptions_OptimizeMode) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{10, 0} -} - -type FieldOptions_CType int32 - -const ( - // Default mode. - FieldOptions_STRING FieldOptions_CType = 0 - FieldOptions_CORD FieldOptions_CType = 1 - FieldOptions_STRING_PIECE FieldOptions_CType = 2 -) - -var FieldOptions_CType_name = map[int32]string{ - 0: "STRING", - 1: "CORD", - 2: "STRING_PIECE", -} -var FieldOptions_CType_value = map[string]int32{ - "STRING": 0, - "CORD": 1, - "STRING_PIECE": 2, -} - -func (x FieldOptions_CType) Enum() *FieldOptions_CType { - p := new(FieldOptions_CType) - *p = x - return p -} -func (x FieldOptions_CType) String() string { - return proto.EnumName(FieldOptions_CType_name, int32(x)) -} -func (x *FieldOptions_CType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldOptions_CType_value, data, "FieldOptions_CType") - if err != nil { - return err - } - *x = FieldOptions_CType(value) - return nil -} -func (FieldOptions_CType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{12, 0} -} - -type FieldOptions_JSType int32 - -const ( - // Use the default type. - FieldOptions_JS_NORMAL FieldOptions_JSType = 0 - // Use JavaScript strings. - FieldOptions_JS_STRING FieldOptions_JSType = 1 - // Use JavaScript numbers. - FieldOptions_JS_NUMBER FieldOptions_JSType = 2 -) - -var FieldOptions_JSType_name = map[int32]string{ - 0: "JS_NORMAL", - 1: "JS_STRING", - 2: "JS_NUMBER", -} -var FieldOptions_JSType_value = map[string]int32{ - "JS_NORMAL": 0, - "JS_STRING": 1, - "JS_NUMBER": 2, -} - -func (x FieldOptions_JSType) Enum() *FieldOptions_JSType { - p := new(FieldOptions_JSType) - *p = x - return p -} -func (x FieldOptions_JSType) String() string { - return proto.EnumName(FieldOptions_JSType_name, int32(x)) -} -func (x *FieldOptions_JSType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldOptions_JSType_value, data, "FieldOptions_JSType") - if err != nil { - return err - } - *x = FieldOptions_JSType(value) - return nil -} -func (FieldOptions_JSType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{12, 1} -} - -// Is this method side-effect-free (or safe in HTTP parlance), or idempotent, -// or neither? HTTP based RPC implementation may choose GET verb for safe -// methods, and PUT verb for idempotent methods instead of the default POST. -type MethodOptions_IdempotencyLevel int32 - -const ( - MethodOptions_IDEMPOTENCY_UNKNOWN MethodOptions_IdempotencyLevel = 0 - MethodOptions_NO_SIDE_EFFECTS MethodOptions_IdempotencyLevel = 1 - MethodOptions_IDEMPOTENT MethodOptions_IdempotencyLevel = 2 -) - -var MethodOptions_IdempotencyLevel_name = map[int32]string{ - 0: "IDEMPOTENCY_UNKNOWN", - 1: "NO_SIDE_EFFECTS", - 2: "IDEMPOTENT", -} -var MethodOptions_IdempotencyLevel_value = map[string]int32{ - "IDEMPOTENCY_UNKNOWN": 0, - "NO_SIDE_EFFECTS": 1, - "IDEMPOTENT": 2, -} - -func (x MethodOptions_IdempotencyLevel) Enum() *MethodOptions_IdempotencyLevel { - p := new(MethodOptions_IdempotencyLevel) - *p = x - return p -} -func (x MethodOptions_IdempotencyLevel) String() string { - return proto.EnumName(MethodOptions_IdempotencyLevel_name, int32(x)) -} -func (x *MethodOptions_IdempotencyLevel) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(MethodOptions_IdempotencyLevel_value, data, "MethodOptions_IdempotencyLevel") - if err != nil { - return err - } - *x = MethodOptions_IdempotencyLevel(value) - return nil -} -func (MethodOptions_IdempotencyLevel) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{17, 0} -} - -// The protocol compiler can output a FileDescriptorSet containing the .proto -// files it parses. -type FileDescriptorSet struct { - File []*FileDescriptorProto `protobuf:"bytes,1,rep,name=file" json:"file,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FileDescriptorSet) Reset() { *m = FileDescriptorSet{} } -func (m *FileDescriptorSet) String() string { return proto.CompactTextString(m) } -func (*FileDescriptorSet) ProtoMessage() {} -func (*FileDescriptorSet) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{0} -} -func (m *FileDescriptorSet) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FileDescriptorSet.Unmarshal(m, b) -} -func (m *FileDescriptorSet) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FileDescriptorSet.Marshal(b, m, deterministic) -} -func (dst *FileDescriptorSet) XXX_Merge(src proto.Message) { - xxx_messageInfo_FileDescriptorSet.Merge(dst, src) -} -func (m *FileDescriptorSet) XXX_Size() int { - return xxx_messageInfo_FileDescriptorSet.Size(m) -} -func (m *FileDescriptorSet) XXX_DiscardUnknown() { - xxx_messageInfo_FileDescriptorSet.DiscardUnknown(m) -} - -var xxx_messageInfo_FileDescriptorSet proto.InternalMessageInfo - -func (m *FileDescriptorSet) GetFile() []*FileDescriptorProto { - if m != nil { - return m.File - } - return nil -} - -// Describes a complete .proto file. -type FileDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Package *string `protobuf:"bytes,2,opt,name=package" json:"package,omitempty"` - // Names of files imported by this file. - Dependency []string `protobuf:"bytes,3,rep,name=dependency" json:"dependency,omitempty"` - // Indexes of the public imported files in the dependency list above. - PublicDependency []int32 `protobuf:"varint,10,rep,name=public_dependency,json=publicDependency" json:"public_dependency,omitempty"` - // Indexes of the weak imported files in the dependency list. - // For Google-internal migration only. Do not use. - WeakDependency []int32 `protobuf:"varint,11,rep,name=weak_dependency,json=weakDependency" json:"weak_dependency,omitempty"` - // All top-level definitions in this file. - MessageType []*DescriptorProto `protobuf:"bytes,4,rep,name=message_type,json=messageType" json:"message_type,omitempty"` - EnumType []*EnumDescriptorProto `protobuf:"bytes,5,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"` - Service []*ServiceDescriptorProto `protobuf:"bytes,6,rep,name=service" json:"service,omitempty"` - Extension []*FieldDescriptorProto `protobuf:"bytes,7,rep,name=extension" json:"extension,omitempty"` - Options *FileOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"` - // This field contains optional information about the original source code. - // You may safely remove this entire field without harming runtime - // functionality of the descriptors -- the information is needed only by - // development tools. - SourceCodeInfo *SourceCodeInfo `protobuf:"bytes,9,opt,name=source_code_info,json=sourceCodeInfo" json:"source_code_info,omitempty"` - // The syntax of the proto file. - // The supported values are "proto2" and "proto3". - Syntax *string `protobuf:"bytes,12,opt,name=syntax" json:"syntax,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FileDescriptorProto) Reset() { *m = FileDescriptorProto{} } -func (m *FileDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*FileDescriptorProto) ProtoMessage() {} -func (*FileDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{1} -} -func (m *FileDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FileDescriptorProto.Unmarshal(m, b) -} -func (m *FileDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FileDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *FileDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_FileDescriptorProto.Merge(dst, src) -} -func (m *FileDescriptorProto) XXX_Size() int { - return xxx_messageInfo_FileDescriptorProto.Size(m) -} -func (m *FileDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_FileDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_FileDescriptorProto proto.InternalMessageInfo - -func (m *FileDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *FileDescriptorProto) GetPackage() string { - if m != nil && m.Package != nil { - return *m.Package - } - return "" -} - -func (m *FileDescriptorProto) GetDependency() []string { - if m != nil { - return m.Dependency - } - return nil -} - -func (m *FileDescriptorProto) GetPublicDependency() []int32 { - if m != nil { - return m.PublicDependency - } - return nil -} - -func (m *FileDescriptorProto) GetWeakDependency() []int32 { - if m != nil { - return m.WeakDependency - } - return nil -} - -func (m *FileDescriptorProto) GetMessageType() []*DescriptorProto { - if m != nil { - return m.MessageType - } - return nil -} - -func (m *FileDescriptorProto) GetEnumType() []*EnumDescriptorProto { - if m != nil { - return m.EnumType - } - return nil -} - -func (m *FileDescriptorProto) GetService() []*ServiceDescriptorProto { - if m != nil { - return m.Service - } - return nil -} - -func (m *FileDescriptorProto) GetExtension() []*FieldDescriptorProto { - if m != nil { - return m.Extension - } - return nil -} - -func (m *FileDescriptorProto) GetOptions() *FileOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *FileDescriptorProto) GetSourceCodeInfo() *SourceCodeInfo { - if m != nil { - return m.SourceCodeInfo - } - return nil -} - -func (m *FileDescriptorProto) GetSyntax() string { - if m != nil && m.Syntax != nil { - return *m.Syntax - } - return "" -} - -// Describes a message type. -type DescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Field []*FieldDescriptorProto `protobuf:"bytes,2,rep,name=field" json:"field,omitempty"` - Extension []*FieldDescriptorProto `protobuf:"bytes,6,rep,name=extension" json:"extension,omitempty"` - NestedType []*DescriptorProto `protobuf:"bytes,3,rep,name=nested_type,json=nestedType" json:"nested_type,omitempty"` - EnumType []*EnumDescriptorProto `protobuf:"bytes,4,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"` - ExtensionRange []*DescriptorProto_ExtensionRange `protobuf:"bytes,5,rep,name=extension_range,json=extensionRange" json:"extension_range,omitempty"` - OneofDecl []*OneofDescriptorProto `protobuf:"bytes,8,rep,name=oneof_decl,json=oneofDecl" json:"oneof_decl,omitempty"` - Options *MessageOptions `protobuf:"bytes,7,opt,name=options" json:"options,omitempty"` - ReservedRange []*DescriptorProto_ReservedRange `protobuf:"bytes,9,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"` - // Reserved field names, which may not be used by fields in the same message. - // A given name may only be reserved once. - ReservedName []string `protobuf:"bytes,10,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DescriptorProto) Reset() { *m = DescriptorProto{} } -func (m *DescriptorProto) String() string { return proto.CompactTextString(m) } -func (*DescriptorProto) ProtoMessage() {} -func (*DescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{2} -} -func (m *DescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DescriptorProto.Unmarshal(m, b) -} -func (m *DescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DescriptorProto.Marshal(b, m, deterministic) -} -func (dst *DescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_DescriptorProto.Merge(dst, src) -} -func (m *DescriptorProto) XXX_Size() int { - return xxx_messageInfo_DescriptorProto.Size(m) -} -func (m *DescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_DescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_DescriptorProto proto.InternalMessageInfo - -func (m *DescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *DescriptorProto) GetField() []*FieldDescriptorProto { - if m != nil { - return m.Field - } - return nil -} - -func (m *DescriptorProto) GetExtension() []*FieldDescriptorProto { - if m != nil { - return m.Extension - } - return nil -} - -func (m *DescriptorProto) GetNestedType() []*DescriptorProto { - if m != nil { - return m.NestedType - } - return nil -} - -func (m *DescriptorProto) GetEnumType() []*EnumDescriptorProto { - if m != nil { - return m.EnumType - } - return nil -} - -func (m *DescriptorProto) GetExtensionRange() []*DescriptorProto_ExtensionRange { - if m != nil { - return m.ExtensionRange - } - return nil -} - -func (m *DescriptorProto) GetOneofDecl() []*OneofDescriptorProto { - if m != nil { - return m.OneofDecl - } - return nil -} - -func (m *DescriptorProto) GetOptions() *MessageOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *DescriptorProto) GetReservedRange() []*DescriptorProto_ReservedRange { - if m != nil { - return m.ReservedRange - } - return nil -} - -func (m *DescriptorProto) GetReservedName() []string { - if m != nil { - return m.ReservedName - } - return nil -} - -type DescriptorProto_ExtensionRange struct { - Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` - End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` - Options *ExtensionRangeOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DescriptorProto_ExtensionRange) Reset() { *m = DescriptorProto_ExtensionRange{} } -func (m *DescriptorProto_ExtensionRange) String() string { return proto.CompactTextString(m) } -func (*DescriptorProto_ExtensionRange) ProtoMessage() {} -func (*DescriptorProto_ExtensionRange) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{2, 0} -} -func (m *DescriptorProto_ExtensionRange) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DescriptorProto_ExtensionRange.Unmarshal(m, b) -} -func (m *DescriptorProto_ExtensionRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DescriptorProto_ExtensionRange.Marshal(b, m, deterministic) -} -func (dst *DescriptorProto_ExtensionRange) XXX_Merge(src proto.Message) { - xxx_messageInfo_DescriptorProto_ExtensionRange.Merge(dst, src) -} -func (m *DescriptorProto_ExtensionRange) XXX_Size() int { - return xxx_messageInfo_DescriptorProto_ExtensionRange.Size(m) -} -func (m *DescriptorProto_ExtensionRange) XXX_DiscardUnknown() { - xxx_messageInfo_DescriptorProto_ExtensionRange.DiscardUnknown(m) -} - -var xxx_messageInfo_DescriptorProto_ExtensionRange proto.InternalMessageInfo - -func (m *DescriptorProto_ExtensionRange) GetStart() int32 { - if m != nil && m.Start != nil { - return *m.Start - } - return 0 -} - -func (m *DescriptorProto_ExtensionRange) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -func (m *DescriptorProto_ExtensionRange) GetOptions() *ExtensionRangeOptions { - if m != nil { - return m.Options - } - return nil -} - -// Range of reserved tag numbers. Reserved tag numbers may not be used by -// fields or extension ranges in the same message. Reserved ranges may -// not overlap. -type DescriptorProto_ReservedRange struct { - Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` - End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DescriptorProto_ReservedRange) Reset() { *m = DescriptorProto_ReservedRange{} } -func (m *DescriptorProto_ReservedRange) String() string { return proto.CompactTextString(m) } -func (*DescriptorProto_ReservedRange) ProtoMessage() {} -func (*DescriptorProto_ReservedRange) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{2, 1} -} -func (m *DescriptorProto_ReservedRange) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DescriptorProto_ReservedRange.Unmarshal(m, b) -} -func (m *DescriptorProto_ReservedRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DescriptorProto_ReservedRange.Marshal(b, m, deterministic) -} -func (dst *DescriptorProto_ReservedRange) XXX_Merge(src proto.Message) { - xxx_messageInfo_DescriptorProto_ReservedRange.Merge(dst, src) -} -func (m *DescriptorProto_ReservedRange) XXX_Size() int { - return xxx_messageInfo_DescriptorProto_ReservedRange.Size(m) -} -func (m *DescriptorProto_ReservedRange) XXX_DiscardUnknown() { - xxx_messageInfo_DescriptorProto_ReservedRange.DiscardUnknown(m) -} - -var xxx_messageInfo_DescriptorProto_ReservedRange proto.InternalMessageInfo - -func (m *DescriptorProto_ReservedRange) GetStart() int32 { - if m != nil && m.Start != nil { - return *m.Start - } - return 0 -} - -func (m *DescriptorProto_ReservedRange) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -type ExtensionRangeOptions struct { - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ExtensionRangeOptions) Reset() { *m = ExtensionRangeOptions{} } -func (m *ExtensionRangeOptions) String() string { return proto.CompactTextString(m) } -func (*ExtensionRangeOptions) ProtoMessage() {} -func (*ExtensionRangeOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{3} -} - -var extRange_ExtensionRangeOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*ExtensionRangeOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_ExtensionRangeOptions -} -func (m *ExtensionRangeOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ExtensionRangeOptions.Unmarshal(m, b) -} -func (m *ExtensionRangeOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ExtensionRangeOptions.Marshal(b, m, deterministic) -} -func (dst *ExtensionRangeOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_ExtensionRangeOptions.Merge(dst, src) -} -func (m *ExtensionRangeOptions) XXX_Size() int { - return xxx_messageInfo_ExtensionRangeOptions.Size(m) -} -func (m *ExtensionRangeOptions) XXX_DiscardUnknown() { - xxx_messageInfo_ExtensionRangeOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_ExtensionRangeOptions proto.InternalMessageInfo - -func (m *ExtensionRangeOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -// Describes a field within a message. -type FieldDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Number *int32 `protobuf:"varint,3,opt,name=number" json:"number,omitempty"` - Label *FieldDescriptorProto_Label `protobuf:"varint,4,opt,name=label,enum=google.protobuf.FieldDescriptorProto_Label" json:"label,omitempty"` - // If type_name is set, this need not be set. If both this and type_name - // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. - Type *FieldDescriptorProto_Type `protobuf:"varint,5,opt,name=type,enum=google.protobuf.FieldDescriptorProto_Type" json:"type,omitempty"` - // For message and enum types, this is the name of the type. If the name - // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping - // rules are used to find the type (i.e. first the nested types within this - // message are searched, then within the parent, on up to the root - // namespace). - TypeName *string `protobuf:"bytes,6,opt,name=type_name,json=typeName" json:"type_name,omitempty"` - // For extensions, this is the name of the type being extended. It is - // resolved in the same manner as type_name. - Extendee *string `protobuf:"bytes,2,opt,name=extendee" json:"extendee,omitempty"` - // For numeric types, contains the original text representation of the value. - // For booleans, "true" or "false". - // For strings, contains the default text contents (not escaped in any way). - // For bytes, contains the C escaped value. All bytes >= 128 are escaped. - // TODO(kenton): Base-64 encode? - DefaultValue *string `protobuf:"bytes,7,opt,name=default_value,json=defaultValue" json:"default_value,omitempty"` - // If set, gives the index of a oneof in the containing type's oneof_decl - // list. This field is a member of that oneof. - OneofIndex *int32 `protobuf:"varint,9,opt,name=oneof_index,json=oneofIndex" json:"oneof_index,omitempty"` - // JSON name of this field. The value is set by protocol compiler. If the - // user has set a "json_name" option on this field, that option's value - // will be used. Otherwise, it's deduced from the field's name by converting - // it to camelCase. - JsonName *string `protobuf:"bytes,10,opt,name=json_name,json=jsonName" json:"json_name,omitempty"` - Options *FieldOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FieldDescriptorProto) Reset() { *m = FieldDescriptorProto{} } -func (m *FieldDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*FieldDescriptorProto) ProtoMessage() {} -func (*FieldDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{4} -} -func (m *FieldDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FieldDescriptorProto.Unmarshal(m, b) -} -func (m *FieldDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FieldDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *FieldDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_FieldDescriptorProto.Merge(dst, src) -} -func (m *FieldDescriptorProto) XXX_Size() int { - return xxx_messageInfo_FieldDescriptorProto.Size(m) -} -func (m *FieldDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_FieldDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_FieldDescriptorProto proto.InternalMessageInfo - -func (m *FieldDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *FieldDescriptorProto) GetNumber() int32 { - if m != nil && m.Number != nil { - return *m.Number - } - return 0 -} - -func (m *FieldDescriptorProto) GetLabel() FieldDescriptorProto_Label { - if m != nil && m.Label != nil { - return *m.Label - } - return FieldDescriptorProto_LABEL_OPTIONAL -} - -func (m *FieldDescriptorProto) GetType() FieldDescriptorProto_Type { - if m != nil && m.Type != nil { - return *m.Type - } - return FieldDescriptorProto_TYPE_DOUBLE -} - -func (m *FieldDescriptorProto) GetTypeName() string { - if m != nil && m.TypeName != nil { - return *m.TypeName - } - return "" -} - -func (m *FieldDescriptorProto) GetExtendee() string { - if m != nil && m.Extendee != nil { - return *m.Extendee - } - return "" -} - -func (m *FieldDescriptorProto) GetDefaultValue() string { - if m != nil && m.DefaultValue != nil { - return *m.DefaultValue - } - return "" -} - -func (m *FieldDescriptorProto) GetOneofIndex() int32 { - if m != nil && m.OneofIndex != nil { - return *m.OneofIndex - } - return 0 -} - -func (m *FieldDescriptorProto) GetJsonName() string { - if m != nil && m.JsonName != nil { - return *m.JsonName - } - return "" -} - -func (m *FieldDescriptorProto) GetOptions() *FieldOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes a oneof. -type OneofDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Options *OneofOptions `protobuf:"bytes,2,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *OneofDescriptorProto) Reset() { *m = OneofDescriptorProto{} } -func (m *OneofDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*OneofDescriptorProto) ProtoMessage() {} -func (*OneofDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{5} -} -func (m *OneofDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_OneofDescriptorProto.Unmarshal(m, b) -} -func (m *OneofDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_OneofDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *OneofDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_OneofDescriptorProto.Merge(dst, src) -} -func (m *OneofDescriptorProto) XXX_Size() int { - return xxx_messageInfo_OneofDescriptorProto.Size(m) -} -func (m *OneofDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_OneofDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_OneofDescriptorProto proto.InternalMessageInfo - -func (m *OneofDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *OneofDescriptorProto) GetOptions() *OneofOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes an enum type. -type EnumDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Value []*EnumValueDescriptorProto `protobuf:"bytes,2,rep,name=value" json:"value,omitempty"` - Options *EnumOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - // Range of reserved numeric values. Reserved numeric values may not be used - // by enum values in the same enum declaration. Reserved ranges may not - // overlap. - ReservedRange []*EnumDescriptorProto_EnumReservedRange `protobuf:"bytes,4,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"` - // Reserved enum value names, which may not be reused. A given name may only - // be reserved once. - ReservedName []string `protobuf:"bytes,5,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumDescriptorProto) Reset() { *m = EnumDescriptorProto{} } -func (m *EnumDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*EnumDescriptorProto) ProtoMessage() {} -func (*EnumDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{6} -} -func (m *EnumDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumDescriptorProto.Unmarshal(m, b) -} -func (m *EnumDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *EnumDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumDescriptorProto.Merge(dst, src) -} -func (m *EnumDescriptorProto) XXX_Size() int { - return xxx_messageInfo_EnumDescriptorProto.Size(m) -} -func (m *EnumDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_EnumDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumDescriptorProto proto.InternalMessageInfo - -func (m *EnumDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *EnumDescriptorProto) GetValue() []*EnumValueDescriptorProto { - if m != nil { - return m.Value - } - return nil -} - -func (m *EnumDescriptorProto) GetOptions() *EnumOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *EnumDescriptorProto) GetReservedRange() []*EnumDescriptorProto_EnumReservedRange { - if m != nil { - return m.ReservedRange - } - return nil -} - -func (m *EnumDescriptorProto) GetReservedName() []string { - if m != nil { - return m.ReservedName - } - return nil -} - -// Range of reserved numeric values. Reserved values may not be used by -// entries in the same enum. Reserved ranges may not overlap. -// -// Note that this is distinct from DescriptorProto.ReservedRange in that it -// is inclusive such that it can appropriately represent the entire int32 -// domain. -type EnumDescriptorProto_EnumReservedRange struct { - Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` - End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumDescriptorProto_EnumReservedRange) Reset() { *m = EnumDescriptorProto_EnumReservedRange{} } -func (m *EnumDescriptorProto_EnumReservedRange) String() string { return proto.CompactTextString(m) } -func (*EnumDescriptorProto_EnumReservedRange) ProtoMessage() {} -func (*EnumDescriptorProto_EnumReservedRange) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{6, 0} -} -func (m *EnumDescriptorProto_EnumReservedRange) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Unmarshal(m, b) -} -func (m *EnumDescriptorProto_EnumReservedRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Marshal(b, m, deterministic) -} -func (dst *EnumDescriptorProto_EnumReservedRange) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Merge(dst, src) -} -func (m *EnumDescriptorProto_EnumReservedRange) XXX_Size() int { - return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Size(m) -} -func (m *EnumDescriptorProto_EnumReservedRange) XXX_DiscardUnknown() { - xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumDescriptorProto_EnumReservedRange proto.InternalMessageInfo - -func (m *EnumDescriptorProto_EnumReservedRange) GetStart() int32 { - if m != nil && m.Start != nil { - return *m.Start - } - return 0 -} - -func (m *EnumDescriptorProto_EnumReservedRange) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -// Describes a value within an enum. -type EnumValueDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Number *int32 `protobuf:"varint,2,opt,name=number" json:"number,omitempty"` - Options *EnumValueOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumValueDescriptorProto) Reset() { *m = EnumValueDescriptorProto{} } -func (m *EnumValueDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*EnumValueDescriptorProto) ProtoMessage() {} -func (*EnumValueDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{7} -} -func (m *EnumValueDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumValueDescriptorProto.Unmarshal(m, b) -} -func (m *EnumValueDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumValueDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *EnumValueDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumValueDescriptorProto.Merge(dst, src) -} -func (m *EnumValueDescriptorProto) XXX_Size() int { - return xxx_messageInfo_EnumValueDescriptorProto.Size(m) -} -func (m *EnumValueDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_EnumValueDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumValueDescriptorProto proto.InternalMessageInfo - -func (m *EnumValueDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *EnumValueDescriptorProto) GetNumber() int32 { - if m != nil && m.Number != nil { - return *m.Number - } - return 0 -} - -func (m *EnumValueDescriptorProto) GetOptions() *EnumValueOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes a service. -type ServiceDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Method []*MethodDescriptorProto `protobuf:"bytes,2,rep,name=method" json:"method,omitempty"` - Options *ServiceOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServiceDescriptorProto) Reset() { *m = ServiceDescriptorProto{} } -func (m *ServiceDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*ServiceDescriptorProto) ProtoMessage() {} -func (*ServiceDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{8} -} -func (m *ServiceDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServiceDescriptorProto.Unmarshal(m, b) -} -func (m *ServiceDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServiceDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *ServiceDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServiceDescriptorProto.Merge(dst, src) -} -func (m *ServiceDescriptorProto) XXX_Size() int { - return xxx_messageInfo_ServiceDescriptorProto.Size(m) -} -func (m *ServiceDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_ServiceDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_ServiceDescriptorProto proto.InternalMessageInfo - -func (m *ServiceDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *ServiceDescriptorProto) GetMethod() []*MethodDescriptorProto { - if m != nil { - return m.Method - } - return nil -} - -func (m *ServiceDescriptorProto) GetOptions() *ServiceOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes a method of a service. -type MethodDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - // Input and output type names. These are resolved in the same way as - // FieldDescriptorProto.type_name, but must refer to a message type. - InputType *string `protobuf:"bytes,2,opt,name=input_type,json=inputType" json:"input_type,omitempty"` - OutputType *string `protobuf:"bytes,3,opt,name=output_type,json=outputType" json:"output_type,omitempty"` - Options *MethodOptions `protobuf:"bytes,4,opt,name=options" json:"options,omitempty"` - // Identifies if client streams multiple client messages - ClientStreaming *bool `protobuf:"varint,5,opt,name=client_streaming,json=clientStreaming,def=0" json:"client_streaming,omitempty"` - // Identifies if server streams multiple server messages - ServerStreaming *bool `protobuf:"varint,6,opt,name=server_streaming,json=serverStreaming,def=0" json:"server_streaming,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MethodDescriptorProto) Reset() { *m = MethodDescriptorProto{} } -func (m *MethodDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*MethodDescriptorProto) ProtoMessage() {} -func (*MethodDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{9} -} -func (m *MethodDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MethodDescriptorProto.Unmarshal(m, b) -} -func (m *MethodDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MethodDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *MethodDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_MethodDescriptorProto.Merge(dst, src) -} -func (m *MethodDescriptorProto) XXX_Size() int { - return xxx_messageInfo_MethodDescriptorProto.Size(m) -} -func (m *MethodDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_MethodDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_MethodDescriptorProto proto.InternalMessageInfo - -const Default_MethodDescriptorProto_ClientStreaming bool = false -const Default_MethodDescriptorProto_ServerStreaming bool = false - -func (m *MethodDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *MethodDescriptorProto) GetInputType() string { - if m != nil && m.InputType != nil { - return *m.InputType - } - return "" -} - -func (m *MethodDescriptorProto) GetOutputType() string { - if m != nil && m.OutputType != nil { - return *m.OutputType - } - return "" -} - -func (m *MethodDescriptorProto) GetOptions() *MethodOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *MethodDescriptorProto) GetClientStreaming() bool { - if m != nil && m.ClientStreaming != nil { - return *m.ClientStreaming - } - return Default_MethodDescriptorProto_ClientStreaming -} - -func (m *MethodDescriptorProto) GetServerStreaming() bool { - if m != nil && m.ServerStreaming != nil { - return *m.ServerStreaming - } - return Default_MethodDescriptorProto_ServerStreaming -} - -type FileOptions struct { - // Sets the Java package where classes generated from this .proto will be - // placed. By default, the proto package is used, but this is often - // inappropriate because proto packages do not normally start with backwards - // domain names. - JavaPackage *string `protobuf:"bytes,1,opt,name=java_package,json=javaPackage" json:"java_package,omitempty"` - // If set, all the classes from the .proto file are wrapped in a single - // outer class with the given name. This applies to both Proto1 - // (equivalent to the old "--one_java_file" option) and Proto2 (where - // a .proto always translates to a single class, but you may want to - // explicitly choose the class name). - JavaOuterClassname *string `protobuf:"bytes,8,opt,name=java_outer_classname,json=javaOuterClassname" json:"java_outer_classname,omitempty"` - // If set true, then the Java code generator will generate a separate .java - // file for each top-level message, enum, and service defined in the .proto - // file. Thus, these types will *not* be nested inside the outer class - // named by java_outer_classname. However, the outer class will still be - // generated to contain the file's getDescriptor() method as well as any - // top-level extensions defined in the file. - JavaMultipleFiles *bool `protobuf:"varint,10,opt,name=java_multiple_files,json=javaMultipleFiles,def=0" json:"java_multiple_files,omitempty"` - // This option does nothing. - JavaGenerateEqualsAndHash *bool `protobuf:"varint,20,opt,name=java_generate_equals_and_hash,json=javaGenerateEqualsAndHash" json:"java_generate_equals_and_hash,omitempty"` // Deprecated: Do not use. - // If set true, then the Java2 code generator will generate code that - // throws an exception whenever an attempt is made to assign a non-UTF-8 - // byte sequence to a string field. - // Message reflection will do the same. - // However, an extension field still accepts non-UTF-8 byte sequences. - // This option has no effect on when used with the lite runtime. - JavaStringCheckUtf8 *bool `protobuf:"varint,27,opt,name=java_string_check_utf8,json=javaStringCheckUtf8,def=0" json:"java_string_check_utf8,omitempty"` - OptimizeFor *FileOptions_OptimizeMode `protobuf:"varint,9,opt,name=optimize_for,json=optimizeFor,enum=google.protobuf.FileOptions_OptimizeMode,def=1" json:"optimize_for,omitempty"` - // Sets the Go package where structs generated from this .proto will be - // placed. If omitted, the Go package will be derived from the following: - // - The basename of the package import path, if provided. - // - Otherwise, the package statement in the .proto file, if present. - // - Otherwise, the basename of the .proto file, without extension. - GoPackage *string `protobuf:"bytes,11,opt,name=go_package,json=goPackage" json:"go_package,omitempty"` - // Should generic services be generated in each language? "Generic" services - // are not specific to any particular RPC system. They are generated by the - // main code generators in each language (without additional plugins). - // Generic services were the only kind of service generation supported by - // early versions of google.protobuf. - // - // Generic services are now considered deprecated in favor of using plugins - // that generate code specific to your particular RPC system. Therefore, - // these default to false. Old code which depends on generic services should - // explicitly set them to true. - CcGenericServices *bool `protobuf:"varint,16,opt,name=cc_generic_services,json=ccGenericServices,def=0" json:"cc_generic_services,omitempty"` - JavaGenericServices *bool `protobuf:"varint,17,opt,name=java_generic_services,json=javaGenericServices,def=0" json:"java_generic_services,omitempty"` - PyGenericServices *bool `protobuf:"varint,18,opt,name=py_generic_services,json=pyGenericServices,def=0" json:"py_generic_services,omitempty"` - PhpGenericServices *bool `protobuf:"varint,42,opt,name=php_generic_services,json=phpGenericServices,def=0" json:"php_generic_services,omitempty"` - // Is this file deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for everything in the file, or it will be completely ignored; in the very - // least, this is a formalization for deprecating files. - Deprecated *bool `protobuf:"varint,23,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // Enables the use of arenas for the proto messages in this file. This applies - // only to generated classes for C++. - CcEnableArenas *bool `protobuf:"varint,31,opt,name=cc_enable_arenas,json=ccEnableArenas,def=0" json:"cc_enable_arenas,omitempty"` - // Sets the objective c class prefix which is prepended to all objective c - // generated classes from this .proto. There is no default. - ObjcClassPrefix *string `protobuf:"bytes,36,opt,name=objc_class_prefix,json=objcClassPrefix" json:"objc_class_prefix,omitempty"` - // Namespace for generated classes; defaults to the package. - CsharpNamespace *string `protobuf:"bytes,37,opt,name=csharp_namespace,json=csharpNamespace" json:"csharp_namespace,omitempty"` - // By default Swift generators will take the proto package and CamelCase it - // replacing '.' with underscore and use that to prefix the types/symbols - // defined. When this options is provided, they will use this value instead - // to prefix the types/symbols defined. - SwiftPrefix *string `protobuf:"bytes,39,opt,name=swift_prefix,json=swiftPrefix" json:"swift_prefix,omitempty"` - // Sets the php class prefix which is prepended to all php generated classes - // from this .proto. Default is empty. - PhpClassPrefix *string `protobuf:"bytes,40,opt,name=php_class_prefix,json=phpClassPrefix" json:"php_class_prefix,omitempty"` - // Use this option to change the namespace of php generated classes. Default - // is empty. When this option is empty, the package name will be used for - // determining the namespace. - PhpNamespace *string `protobuf:"bytes,41,opt,name=php_namespace,json=phpNamespace" json:"php_namespace,omitempty"` - // The parser stores options it doesn't recognize here. - // See the documentation for the "Options" section above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FileOptions) Reset() { *m = FileOptions{} } -func (m *FileOptions) String() string { return proto.CompactTextString(m) } -func (*FileOptions) ProtoMessage() {} -func (*FileOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{10} -} - -var extRange_FileOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*FileOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_FileOptions -} -func (m *FileOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FileOptions.Unmarshal(m, b) -} -func (m *FileOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FileOptions.Marshal(b, m, deterministic) -} -func (dst *FileOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_FileOptions.Merge(dst, src) -} -func (m *FileOptions) XXX_Size() int { - return xxx_messageInfo_FileOptions.Size(m) -} -func (m *FileOptions) XXX_DiscardUnknown() { - xxx_messageInfo_FileOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_FileOptions proto.InternalMessageInfo - -const Default_FileOptions_JavaMultipleFiles bool = false -const Default_FileOptions_JavaStringCheckUtf8 bool = false -const Default_FileOptions_OptimizeFor FileOptions_OptimizeMode = FileOptions_SPEED -const Default_FileOptions_CcGenericServices bool = false -const Default_FileOptions_JavaGenericServices bool = false -const Default_FileOptions_PyGenericServices bool = false -const Default_FileOptions_PhpGenericServices bool = false -const Default_FileOptions_Deprecated bool = false -const Default_FileOptions_CcEnableArenas bool = false - -func (m *FileOptions) GetJavaPackage() string { - if m != nil && m.JavaPackage != nil { - return *m.JavaPackage - } - return "" -} - -func (m *FileOptions) GetJavaOuterClassname() string { - if m != nil && m.JavaOuterClassname != nil { - return *m.JavaOuterClassname - } - return "" -} - -func (m *FileOptions) GetJavaMultipleFiles() bool { - if m != nil && m.JavaMultipleFiles != nil { - return *m.JavaMultipleFiles - } - return Default_FileOptions_JavaMultipleFiles -} - -// Deprecated: Do not use. -func (m *FileOptions) GetJavaGenerateEqualsAndHash() bool { - if m != nil && m.JavaGenerateEqualsAndHash != nil { - return *m.JavaGenerateEqualsAndHash - } - return false -} - -func (m *FileOptions) GetJavaStringCheckUtf8() bool { - if m != nil && m.JavaStringCheckUtf8 != nil { - return *m.JavaStringCheckUtf8 - } - return Default_FileOptions_JavaStringCheckUtf8 -} - -func (m *FileOptions) GetOptimizeFor() FileOptions_OptimizeMode { - if m != nil && m.OptimizeFor != nil { - return *m.OptimizeFor - } - return Default_FileOptions_OptimizeFor -} - -func (m *FileOptions) GetGoPackage() string { - if m != nil && m.GoPackage != nil { - return *m.GoPackage - } - return "" -} - -func (m *FileOptions) GetCcGenericServices() bool { - if m != nil && m.CcGenericServices != nil { - return *m.CcGenericServices - } - return Default_FileOptions_CcGenericServices -} - -func (m *FileOptions) GetJavaGenericServices() bool { - if m != nil && m.JavaGenericServices != nil { - return *m.JavaGenericServices - } - return Default_FileOptions_JavaGenericServices -} - -func (m *FileOptions) GetPyGenericServices() bool { - if m != nil && m.PyGenericServices != nil { - return *m.PyGenericServices - } - return Default_FileOptions_PyGenericServices -} - -func (m *FileOptions) GetPhpGenericServices() bool { - if m != nil && m.PhpGenericServices != nil { - return *m.PhpGenericServices - } - return Default_FileOptions_PhpGenericServices -} - -func (m *FileOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_FileOptions_Deprecated -} - -func (m *FileOptions) GetCcEnableArenas() bool { - if m != nil && m.CcEnableArenas != nil { - return *m.CcEnableArenas - } - return Default_FileOptions_CcEnableArenas -} - -func (m *FileOptions) GetObjcClassPrefix() string { - if m != nil && m.ObjcClassPrefix != nil { - return *m.ObjcClassPrefix - } - return "" -} - -func (m *FileOptions) GetCsharpNamespace() string { - if m != nil && m.CsharpNamespace != nil { - return *m.CsharpNamespace - } - return "" -} - -func (m *FileOptions) GetSwiftPrefix() string { - if m != nil && m.SwiftPrefix != nil { - return *m.SwiftPrefix - } - return "" -} - -func (m *FileOptions) GetPhpClassPrefix() string { - if m != nil && m.PhpClassPrefix != nil { - return *m.PhpClassPrefix - } - return "" -} - -func (m *FileOptions) GetPhpNamespace() string { - if m != nil && m.PhpNamespace != nil { - return *m.PhpNamespace - } - return "" -} - -func (m *FileOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type MessageOptions struct { - // Set true to use the old proto1 MessageSet wire format for extensions. - // This is provided for backwards-compatibility with the MessageSet wire - // format. You should not use this for any other reason: It's less - // efficient, has fewer features, and is more complicated. - // - // The message must be defined exactly as follows: - // message Foo { - // option message_set_wire_format = true; - // extensions 4 to max; - // } - // Note that the message cannot have any defined fields; MessageSets only - // have extensions. - // - // All extensions of your type must be singular messages; e.g. they cannot - // be int32s, enums, or repeated messages. - // - // Because this is an option, the above two restrictions are not enforced by - // the protocol compiler. - MessageSetWireFormat *bool `protobuf:"varint,1,opt,name=message_set_wire_format,json=messageSetWireFormat,def=0" json:"message_set_wire_format,omitempty"` - // Disables the generation of the standard "descriptor()" accessor, which can - // conflict with a field of the same name. This is meant to make migration - // from proto1 easier; new code should avoid fields named "descriptor". - NoStandardDescriptorAccessor *bool `protobuf:"varint,2,opt,name=no_standard_descriptor_accessor,json=noStandardDescriptorAccessor,def=0" json:"no_standard_descriptor_accessor,omitempty"` - // Is this message deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the message, or it will be completely ignored; in the very least, - // this is a formalization for deprecating messages. - Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // Whether the message is an automatically generated map entry type for the - // maps field. - // - // For maps fields: - // map map_field = 1; - // The parsed descriptor looks like: - // message MapFieldEntry { - // option map_entry = true; - // optional KeyType key = 1; - // optional ValueType value = 2; - // } - // repeated MapFieldEntry map_field = 1; - // - // Implementations may choose not to generate the map_entry=true message, but - // use a native map in the target language to hold the keys and values. - // The reflection APIs in such implementions still need to work as - // if the field is a repeated message field. - // - // NOTE: Do not set the option in .proto files. Always use the maps syntax - // instead. The option should only be implicitly set by the proto compiler - // parser. - MapEntry *bool `protobuf:"varint,7,opt,name=map_entry,json=mapEntry" json:"map_entry,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MessageOptions) Reset() { *m = MessageOptions{} } -func (m *MessageOptions) String() string { return proto.CompactTextString(m) } -func (*MessageOptions) ProtoMessage() {} -func (*MessageOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{11} -} - -var extRange_MessageOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*MessageOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MessageOptions -} -func (m *MessageOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MessageOptions.Unmarshal(m, b) -} -func (m *MessageOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MessageOptions.Marshal(b, m, deterministic) -} -func (dst *MessageOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_MessageOptions.Merge(dst, src) -} -func (m *MessageOptions) XXX_Size() int { - return xxx_messageInfo_MessageOptions.Size(m) -} -func (m *MessageOptions) XXX_DiscardUnknown() { - xxx_messageInfo_MessageOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_MessageOptions proto.InternalMessageInfo - -const Default_MessageOptions_MessageSetWireFormat bool = false -const Default_MessageOptions_NoStandardDescriptorAccessor bool = false -const Default_MessageOptions_Deprecated bool = false - -func (m *MessageOptions) GetMessageSetWireFormat() bool { - if m != nil && m.MessageSetWireFormat != nil { - return *m.MessageSetWireFormat - } - return Default_MessageOptions_MessageSetWireFormat -} - -func (m *MessageOptions) GetNoStandardDescriptorAccessor() bool { - if m != nil && m.NoStandardDescriptorAccessor != nil { - return *m.NoStandardDescriptorAccessor - } - return Default_MessageOptions_NoStandardDescriptorAccessor -} - -func (m *MessageOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_MessageOptions_Deprecated -} - -func (m *MessageOptions) GetMapEntry() bool { - if m != nil && m.MapEntry != nil { - return *m.MapEntry - } - return false -} - -func (m *MessageOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type FieldOptions struct { - // The ctype option instructs the C++ code generator to use a different - // representation of the field than it normally would. See the specific - // options below. This option is not yet implemented in the open source - // release -- sorry, we'll try to include it in a future version! - Ctype *FieldOptions_CType `protobuf:"varint,1,opt,name=ctype,enum=google.protobuf.FieldOptions_CType,def=0" json:"ctype,omitempty"` - // The packed option can be enabled for repeated primitive fields to enable - // a more efficient representation on the wire. Rather than repeatedly - // writing the tag and type for each element, the entire array is encoded as - // a single length-delimited blob. In proto3, only explicit setting it to - // false will avoid using packed encoding. - Packed *bool `protobuf:"varint,2,opt,name=packed" json:"packed,omitempty"` - // The jstype option determines the JavaScript type used for values of the - // field. The option is permitted only for 64 bit integral and fixed types - // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING - // is represented as JavaScript string, which avoids loss of precision that - // can happen when a large value is converted to a floating point JavaScript. - // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to - // use the JavaScript "number" type. The behavior of the default option - // JS_NORMAL is implementation dependent. - // - // This option is an enum to permit additional types to be added, e.g. - // goog.math.Integer. - Jstype *FieldOptions_JSType `protobuf:"varint,6,opt,name=jstype,enum=google.protobuf.FieldOptions_JSType,def=0" json:"jstype,omitempty"` - // Should this field be parsed lazily? Lazy applies only to message-type - // fields. It means that when the outer message is initially parsed, the - // inner message's contents will not be parsed but instead stored in encoded - // form. The inner message will actually be parsed when it is first accessed. - // - // This is only a hint. Implementations are free to choose whether to use - // eager or lazy parsing regardless of the value of this option. However, - // setting this option true suggests that the protocol author believes that - // using lazy parsing on this field is worth the additional bookkeeping - // overhead typically needed to implement it. - // - // This option does not affect the public interface of any generated code; - // all method signatures remain the same. Furthermore, thread-safety of the - // interface is not affected by this option; const methods remain safe to - // call from multiple threads concurrently, while non-const methods continue - // to require exclusive access. - // - // - // Note that implementations may choose not to check required fields within - // a lazy sub-message. That is, calling IsInitialized() on the outer message - // may return true even if the inner message has missing required fields. - // This is necessary because otherwise the inner message would have to be - // parsed in order to perform the check, defeating the purpose of lazy - // parsing. An implementation which chooses not to check required fields - // must be consistent about it. That is, for any particular sub-message, the - // implementation must either *always* check its required fields, or *never* - // check its required fields, regardless of whether or not the message has - // been parsed. - Lazy *bool `protobuf:"varint,5,opt,name=lazy,def=0" json:"lazy,omitempty"` - // Is this field deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for accessors, or it will be completely ignored; in the very least, this - // is a formalization for deprecating fields. - Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // For Google-internal migration only. Do not use. - Weak *bool `protobuf:"varint,10,opt,name=weak,def=0" json:"weak,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FieldOptions) Reset() { *m = FieldOptions{} } -func (m *FieldOptions) String() string { return proto.CompactTextString(m) } -func (*FieldOptions) ProtoMessage() {} -func (*FieldOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{12} -} - -var extRange_FieldOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*FieldOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_FieldOptions -} -func (m *FieldOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FieldOptions.Unmarshal(m, b) -} -func (m *FieldOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FieldOptions.Marshal(b, m, deterministic) -} -func (dst *FieldOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_FieldOptions.Merge(dst, src) -} -func (m *FieldOptions) XXX_Size() int { - return xxx_messageInfo_FieldOptions.Size(m) -} -func (m *FieldOptions) XXX_DiscardUnknown() { - xxx_messageInfo_FieldOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_FieldOptions proto.InternalMessageInfo - -const Default_FieldOptions_Ctype FieldOptions_CType = FieldOptions_STRING -const Default_FieldOptions_Jstype FieldOptions_JSType = FieldOptions_JS_NORMAL -const Default_FieldOptions_Lazy bool = false -const Default_FieldOptions_Deprecated bool = false -const Default_FieldOptions_Weak bool = false - -func (m *FieldOptions) GetCtype() FieldOptions_CType { - if m != nil && m.Ctype != nil { - return *m.Ctype - } - return Default_FieldOptions_Ctype -} - -func (m *FieldOptions) GetPacked() bool { - if m != nil && m.Packed != nil { - return *m.Packed - } - return false -} - -func (m *FieldOptions) GetJstype() FieldOptions_JSType { - if m != nil && m.Jstype != nil { - return *m.Jstype - } - return Default_FieldOptions_Jstype -} - -func (m *FieldOptions) GetLazy() bool { - if m != nil && m.Lazy != nil { - return *m.Lazy - } - return Default_FieldOptions_Lazy -} - -func (m *FieldOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_FieldOptions_Deprecated -} - -func (m *FieldOptions) GetWeak() bool { - if m != nil && m.Weak != nil { - return *m.Weak - } - return Default_FieldOptions_Weak -} - -func (m *FieldOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type OneofOptions struct { - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *OneofOptions) Reset() { *m = OneofOptions{} } -func (m *OneofOptions) String() string { return proto.CompactTextString(m) } -func (*OneofOptions) ProtoMessage() {} -func (*OneofOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{13} -} - -var extRange_OneofOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*OneofOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_OneofOptions -} -func (m *OneofOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_OneofOptions.Unmarshal(m, b) -} -func (m *OneofOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_OneofOptions.Marshal(b, m, deterministic) -} -func (dst *OneofOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_OneofOptions.Merge(dst, src) -} -func (m *OneofOptions) XXX_Size() int { - return xxx_messageInfo_OneofOptions.Size(m) -} -func (m *OneofOptions) XXX_DiscardUnknown() { - xxx_messageInfo_OneofOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_OneofOptions proto.InternalMessageInfo - -func (m *OneofOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type EnumOptions struct { - // Set this option to true to allow mapping different tag names to the same - // value. - AllowAlias *bool `protobuf:"varint,2,opt,name=allow_alias,json=allowAlias" json:"allow_alias,omitempty"` - // Is this enum deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the enum, or it will be completely ignored; in the very least, this - // is a formalization for deprecating enums. - Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumOptions) Reset() { *m = EnumOptions{} } -func (m *EnumOptions) String() string { return proto.CompactTextString(m) } -func (*EnumOptions) ProtoMessage() {} -func (*EnumOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{14} -} - -var extRange_EnumOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*EnumOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_EnumOptions -} -func (m *EnumOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumOptions.Unmarshal(m, b) -} -func (m *EnumOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumOptions.Marshal(b, m, deterministic) -} -func (dst *EnumOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumOptions.Merge(dst, src) -} -func (m *EnumOptions) XXX_Size() int { - return xxx_messageInfo_EnumOptions.Size(m) -} -func (m *EnumOptions) XXX_DiscardUnknown() { - xxx_messageInfo_EnumOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumOptions proto.InternalMessageInfo - -const Default_EnumOptions_Deprecated bool = false - -func (m *EnumOptions) GetAllowAlias() bool { - if m != nil && m.AllowAlias != nil { - return *m.AllowAlias - } - return false -} - -func (m *EnumOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_EnumOptions_Deprecated -} - -func (m *EnumOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type EnumValueOptions struct { - // Is this enum value deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the enum value, or it will be completely ignored; in the very least, - // this is a formalization for deprecating enum values. - Deprecated *bool `protobuf:"varint,1,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumValueOptions) Reset() { *m = EnumValueOptions{} } -func (m *EnumValueOptions) String() string { return proto.CompactTextString(m) } -func (*EnumValueOptions) ProtoMessage() {} -func (*EnumValueOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{15} -} - -var extRange_EnumValueOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*EnumValueOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_EnumValueOptions -} -func (m *EnumValueOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumValueOptions.Unmarshal(m, b) -} -func (m *EnumValueOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumValueOptions.Marshal(b, m, deterministic) -} -func (dst *EnumValueOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumValueOptions.Merge(dst, src) -} -func (m *EnumValueOptions) XXX_Size() int { - return xxx_messageInfo_EnumValueOptions.Size(m) -} -func (m *EnumValueOptions) XXX_DiscardUnknown() { - xxx_messageInfo_EnumValueOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumValueOptions proto.InternalMessageInfo - -const Default_EnumValueOptions_Deprecated bool = false - -func (m *EnumValueOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_EnumValueOptions_Deprecated -} - -func (m *EnumValueOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type ServiceOptions struct { - // Is this service deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the service, or it will be completely ignored; in the very least, - // this is a formalization for deprecating services. - Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServiceOptions) Reset() { *m = ServiceOptions{} } -func (m *ServiceOptions) String() string { return proto.CompactTextString(m) } -func (*ServiceOptions) ProtoMessage() {} -func (*ServiceOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{16} -} - -var extRange_ServiceOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*ServiceOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_ServiceOptions -} -func (m *ServiceOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServiceOptions.Unmarshal(m, b) -} -func (m *ServiceOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServiceOptions.Marshal(b, m, deterministic) -} -func (dst *ServiceOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServiceOptions.Merge(dst, src) -} -func (m *ServiceOptions) XXX_Size() int { - return xxx_messageInfo_ServiceOptions.Size(m) -} -func (m *ServiceOptions) XXX_DiscardUnknown() { - xxx_messageInfo_ServiceOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_ServiceOptions proto.InternalMessageInfo - -const Default_ServiceOptions_Deprecated bool = false - -func (m *ServiceOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_ServiceOptions_Deprecated -} - -func (m *ServiceOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type MethodOptions struct { - // Is this method deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the method, or it will be completely ignored; in the very least, - // this is a formalization for deprecating methods. - Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - IdempotencyLevel *MethodOptions_IdempotencyLevel `protobuf:"varint,34,opt,name=idempotency_level,json=idempotencyLevel,enum=google.protobuf.MethodOptions_IdempotencyLevel,def=0" json:"idempotency_level,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MethodOptions) Reset() { *m = MethodOptions{} } -func (m *MethodOptions) String() string { return proto.CompactTextString(m) } -func (*MethodOptions) ProtoMessage() {} -func (*MethodOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{17} -} - -var extRange_MethodOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*MethodOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MethodOptions -} -func (m *MethodOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MethodOptions.Unmarshal(m, b) -} -func (m *MethodOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MethodOptions.Marshal(b, m, deterministic) -} -func (dst *MethodOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_MethodOptions.Merge(dst, src) -} -func (m *MethodOptions) XXX_Size() int { - return xxx_messageInfo_MethodOptions.Size(m) -} -func (m *MethodOptions) XXX_DiscardUnknown() { - xxx_messageInfo_MethodOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_MethodOptions proto.InternalMessageInfo - -const Default_MethodOptions_Deprecated bool = false -const Default_MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel = MethodOptions_IDEMPOTENCY_UNKNOWN - -func (m *MethodOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_MethodOptions_Deprecated -} - -func (m *MethodOptions) GetIdempotencyLevel() MethodOptions_IdempotencyLevel { - if m != nil && m.IdempotencyLevel != nil { - return *m.IdempotencyLevel - } - return Default_MethodOptions_IdempotencyLevel -} - -func (m *MethodOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -// A message representing a option the parser does not recognize. This only -// appears in options protos created by the compiler::Parser class. -// DescriptorPool resolves these when building Descriptor objects. Therefore, -// options protos in descriptor objects (e.g. returned by Descriptor::options(), -// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions -// in them. -type UninterpretedOption struct { - Name []*UninterpretedOption_NamePart `protobuf:"bytes,2,rep,name=name" json:"name,omitempty"` - // The value of the uninterpreted option, in whatever type the tokenizer - // identified it as during parsing. Exactly one of these should be set. - IdentifierValue *string `protobuf:"bytes,3,opt,name=identifier_value,json=identifierValue" json:"identifier_value,omitempty"` - PositiveIntValue *uint64 `protobuf:"varint,4,opt,name=positive_int_value,json=positiveIntValue" json:"positive_int_value,omitempty"` - NegativeIntValue *int64 `protobuf:"varint,5,opt,name=negative_int_value,json=negativeIntValue" json:"negative_int_value,omitempty"` - DoubleValue *float64 `protobuf:"fixed64,6,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"` - StringValue []byte `protobuf:"bytes,7,opt,name=string_value,json=stringValue" json:"string_value,omitempty"` - AggregateValue *string `protobuf:"bytes,8,opt,name=aggregate_value,json=aggregateValue" json:"aggregate_value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UninterpretedOption) Reset() { *m = UninterpretedOption{} } -func (m *UninterpretedOption) String() string { return proto.CompactTextString(m) } -func (*UninterpretedOption) ProtoMessage() {} -func (*UninterpretedOption) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{18} -} -func (m *UninterpretedOption) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UninterpretedOption.Unmarshal(m, b) -} -func (m *UninterpretedOption) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UninterpretedOption.Marshal(b, m, deterministic) -} -func (dst *UninterpretedOption) XXX_Merge(src proto.Message) { - xxx_messageInfo_UninterpretedOption.Merge(dst, src) -} -func (m *UninterpretedOption) XXX_Size() int { - return xxx_messageInfo_UninterpretedOption.Size(m) -} -func (m *UninterpretedOption) XXX_DiscardUnknown() { - xxx_messageInfo_UninterpretedOption.DiscardUnknown(m) -} - -var xxx_messageInfo_UninterpretedOption proto.InternalMessageInfo - -func (m *UninterpretedOption) GetName() []*UninterpretedOption_NamePart { - if m != nil { - return m.Name - } - return nil -} - -func (m *UninterpretedOption) GetIdentifierValue() string { - if m != nil && m.IdentifierValue != nil { - return *m.IdentifierValue - } - return "" -} - -func (m *UninterpretedOption) GetPositiveIntValue() uint64 { - if m != nil && m.PositiveIntValue != nil { - return *m.PositiveIntValue - } - return 0 -} - -func (m *UninterpretedOption) GetNegativeIntValue() int64 { - if m != nil && m.NegativeIntValue != nil { - return *m.NegativeIntValue - } - return 0 -} - -func (m *UninterpretedOption) GetDoubleValue() float64 { - if m != nil && m.DoubleValue != nil { - return *m.DoubleValue - } - return 0 -} - -func (m *UninterpretedOption) GetStringValue() []byte { - if m != nil { - return m.StringValue - } - return nil -} - -func (m *UninterpretedOption) GetAggregateValue() string { - if m != nil && m.AggregateValue != nil { - return *m.AggregateValue - } - return "" -} - -// The name of the uninterpreted option. Each string represents a segment in -// a dot-separated name. is_extension is true iff a segment represents an -// extension (denoted with parentheses in options specs in .proto files). -// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents -// "foo.(bar.baz).qux". -type UninterpretedOption_NamePart struct { - NamePart *string `protobuf:"bytes,1,req,name=name_part,json=namePart" json:"name_part,omitempty"` - IsExtension *bool `protobuf:"varint,2,req,name=is_extension,json=isExtension" json:"is_extension,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UninterpretedOption_NamePart) Reset() { *m = UninterpretedOption_NamePart{} } -func (m *UninterpretedOption_NamePart) String() string { return proto.CompactTextString(m) } -func (*UninterpretedOption_NamePart) ProtoMessage() {} -func (*UninterpretedOption_NamePart) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{18, 0} -} -func (m *UninterpretedOption_NamePart) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UninterpretedOption_NamePart.Unmarshal(m, b) -} -func (m *UninterpretedOption_NamePart) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UninterpretedOption_NamePart.Marshal(b, m, deterministic) -} -func (dst *UninterpretedOption_NamePart) XXX_Merge(src proto.Message) { - xxx_messageInfo_UninterpretedOption_NamePart.Merge(dst, src) -} -func (m *UninterpretedOption_NamePart) XXX_Size() int { - return xxx_messageInfo_UninterpretedOption_NamePart.Size(m) -} -func (m *UninterpretedOption_NamePart) XXX_DiscardUnknown() { - xxx_messageInfo_UninterpretedOption_NamePart.DiscardUnknown(m) -} - -var xxx_messageInfo_UninterpretedOption_NamePart proto.InternalMessageInfo - -func (m *UninterpretedOption_NamePart) GetNamePart() string { - if m != nil && m.NamePart != nil { - return *m.NamePart - } - return "" -} - -func (m *UninterpretedOption_NamePart) GetIsExtension() bool { - if m != nil && m.IsExtension != nil { - return *m.IsExtension - } - return false -} - -// Encapsulates information about the original source file from which a -// FileDescriptorProto was generated. -type SourceCodeInfo struct { - // A Location identifies a piece of source code in a .proto file which - // corresponds to a particular definition. This information is intended - // to be useful to IDEs, code indexers, documentation generators, and similar - // tools. - // - // For example, say we have a file like: - // message Foo { - // optional string foo = 1; - // } - // Let's look at just the field definition: - // optional string foo = 1; - // ^ ^^ ^^ ^ ^^^ - // a bc de f ghi - // We have the following locations: - // span path represents - // [a,i) [ 4, 0, 2, 0 ] The whole field definition. - // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). - // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). - // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). - // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). - // - // Notes: - // - A location may refer to a repeated field itself (i.e. not to any - // particular index within it). This is used whenever a set of elements are - // logically enclosed in a single code segment. For example, an entire - // extend block (possibly containing multiple extension definitions) will - // have an outer location whose path refers to the "extensions" repeated - // field without an index. - // - Multiple locations may have the same path. This happens when a single - // logical declaration is spread out across multiple places. The most - // obvious example is the "extend" block again -- there may be multiple - // extend blocks in the same scope, each of which will have the same path. - // - A location's span is not always a subset of its parent's span. For - // example, the "extendee" of an extension declaration appears at the - // beginning of the "extend" block and is shared by all extensions within - // the block. - // - Just because a location's span is a subset of some other location's span - // does not mean that it is a descendent. For example, a "group" defines - // both a type and a field in a single declaration. Thus, the locations - // corresponding to the type and field and their components will overlap. - // - Code which tries to interpret locations should probably be designed to - // ignore those that it doesn't understand, as more types of locations could - // be recorded in the future. - Location []*SourceCodeInfo_Location `protobuf:"bytes,1,rep,name=location" json:"location,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SourceCodeInfo) Reset() { *m = SourceCodeInfo{} } -func (m *SourceCodeInfo) String() string { return proto.CompactTextString(m) } -func (*SourceCodeInfo) ProtoMessage() {} -func (*SourceCodeInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{19} -} -func (m *SourceCodeInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SourceCodeInfo.Unmarshal(m, b) -} -func (m *SourceCodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SourceCodeInfo.Marshal(b, m, deterministic) -} -func (dst *SourceCodeInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_SourceCodeInfo.Merge(dst, src) -} -func (m *SourceCodeInfo) XXX_Size() int { - return xxx_messageInfo_SourceCodeInfo.Size(m) -} -func (m *SourceCodeInfo) XXX_DiscardUnknown() { - xxx_messageInfo_SourceCodeInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_SourceCodeInfo proto.InternalMessageInfo - -func (m *SourceCodeInfo) GetLocation() []*SourceCodeInfo_Location { - if m != nil { - return m.Location - } - return nil -} - -type SourceCodeInfo_Location struct { - // Identifies which part of the FileDescriptorProto was defined at this - // location. - // - // Each element is a field number or an index. They form a path from - // the root FileDescriptorProto to the place where the definition. For - // example, this path: - // [ 4, 3, 2, 7, 1 ] - // refers to: - // file.message_type(3) // 4, 3 - // .field(7) // 2, 7 - // .name() // 1 - // This is because FileDescriptorProto.message_type has field number 4: - // repeated DescriptorProto message_type = 4; - // and DescriptorProto.field has field number 2: - // repeated FieldDescriptorProto field = 2; - // and FieldDescriptorProto.name has field number 1: - // optional string name = 1; - // - // Thus, the above path gives the location of a field name. If we removed - // the last element: - // [ 4, 3, 2, 7 ] - // this path refers to the whole field declaration (from the beginning - // of the label to the terminating semicolon). - Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"` - // Always has exactly three or four elements: start line, start column, - // end line (optional, otherwise assumed same as start line), end column. - // These are packed into a single field for efficiency. Note that line - // and column numbers are zero-based -- typically you will want to add - // 1 to each before displaying to a user. - Span []int32 `protobuf:"varint,2,rep,packed,name=span" json:"span,omitempty"` - // If this SourceCodeInfo represents a complete declaration, these are any - // comments appearing before and after the declaration which appear to be - // attached to the declaration. - // - // A series of line comments appearing on consecutive lines, with no other - // tokens appearing on those lines, will be treated as a single comment. - // - // leading_detached_comments will keep paragraphs of comments that appear - // before (but not connected to) the current element. Each paragraph, - // separated by empty lines, will be one comment element in the repeated - // field. - // - // Only the comment content is provided; comment markers (e.g. //) are - // stripped out. For block comments, leading whitespace and an asterisk - // will be stripped from the beginning of each line other than the first. - // Newlines are included in the output. - // - // Examples: - // - // optional int32 foo = 1; // Comment attached to foo. - // // Comment attached to bar. - // optional int32 bar = 2; - // - // optional string baz = 3; - // // Comment attached to baz. - // // Another line attached to baz. - // - // // Comment attached to qux. - // // - // // Another line attached to qux. - // optional double qux = 4; - // - // // Detached comment for corge. This is not leading or trailing comments - // // to qux or corge because there are blank lines separating it from - // // both. - // - // // Detached comment for corge paragraph 2. - // - // optional string corge = 5; - // /* Block comment attached - // * to corge. Leading asterisks - // * will be removed. */ - // /* Block comment attached to - // * grault. */ - // optional int32 grault = 6; - // - // // ignored detached comments. - LeadingComments *string `protobuf:"bytes,3,opt,name=leading_comments,json=leadingComments" json:"leading_comments,omitempty"` - TrailingComments *string `protobuf:"bytes,4,opt,name=trailing_comments,json=trailingComments" json:"trailing_comments,omitempty"` - LeadingDetachedComments []string `protobuf:"bytes,6,rep,name=leading_detached_comments,json=leadingDetachedComments" json:"leading_detached_comments,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SourceCodeInfo_Location) Reset() { *m = SourceCodeInfo_Location{} } -func (m *SourceCodeInfo_Location) String() string { return proto.CompactTextString(m) } -func (*SourceCodeInfo_Location) ProtoMessage() {} -func (*SourceCodeInfo_Location) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{19, 0} -} -func (m *SourceCodeInfo_Location) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SourceCodeInfo_Location.Unmarshal(m, b) -} -func (m *SourceCodeInfo_Location) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SourceCodeInfo_Location.Marshal(b, m, deterministic) -} -func (dst *SourceCodeInfo_Location) XXX_Merge(src proto.Message) { - xxx_messageInfo_SourceCodeInfo_Location.Merge(dst, src) -} -func (m *SourceCodeInfo_Location) XXX_Size() int { - return xxx_messageInfo_SourceCodeInfo_Location.Size(m) -} -func (m *SourceCodeInfo_Location) XXX_DiscardUnknown() { - xxx_messageInfo_SourceCodeInfo_Location.DiscardUnknown(m) -} - -var xxx_messageInfo_SourceCodeInfo_Location proto.InternalMessageInfo - -func (m *SourceCodeInfo_Location) GetPath() []int32 { - if m != nil { - return m.Path - } - return nil -} - -func (m *SourceCodeInfo_Location) GetSpan() []int32 { - if m != nil { - return m.Span - } - return nil -} - -func (m *SourceCodeInfo_Location) GetLeadingComments() string { - if m != nil && m.LeadingComments != nil { - return *m.LeadingComments - } - return "" -} - -func (m *SourceCodeInfo_Location) GetTrailingComments() string { - if m != nil && m.TrailingComments != nil { - return *m.TrailingComments - } - return "" -} - -func (m *SourceCodeInfo_Location) GetLeadingDetachedComments() []string { - if m != nil { - return m.LeadingDetachedComments - } - return nil -} - -// Describes the relationship between generated code and its original source -// file. A GeneratedCodeInfo message is associated with only one generated -// source file, but may contain references to different source .proto files. -type GeneratedCodeInfo struct { - // An Annotation connects some span of text in generated code to an element - // of its generating .proto file. - Annotation []*GeneratedCodeInfo_Annotation `protobuf:"bytes,1,rep,name=annotation" json:"annotation,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GeneratedCodeInfo) Reset() { *m = GeneratedCodeInfo{} } -func (m *GeneratedCodeInfo) String() string { return proto.CompactTextString(m) } -func (*GeneratedCodeInfo) ProtoMessage() {} -func (*GeneratedCodeInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{20} -} -func (m *GeneratedCodeInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GeneratedCodeInfo.Unmarshal(m, b) -} -func (m *GeneratedCodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GeneratedCodeInfo.Marshal(b, m, deterministic) -} -func (dst *GeneratedCodeInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_GeneratedCodeInfo.Merge(dst, src) -} -func (m *GeneratedCodeInfo) XXX_Size() int { - return xxx_messageInfo_GeneratedCodeInfo.Size(m) -} -func (m *GeneratedCodeInfo) XXX_DiscardUnknown() { - xxx_messageInfo_GeneratedCodeInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_GeneratedCodeInfo proto.InternalMessageInfo - -func (m *GeneratedCodeInfo) GetAnnotation() []*GeneratedCodeInfo_Annotation { - if m != nil { - return m.Annotation - } - return nil -} - -type GeneratedCodeInfo_Annotation struct { - // Identifies the element in the original source .proto file. This field - // is formatted the same as SourceCodeInfo.Location.path. - Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"` - // Identifies the filesystem path to the original source .proto. - SourceFile *string `protobuf:"bytes,2,opt,name=source_file,json=sourceFile" json:"source_file,omitempty"` - // Identifies the starting offset in bytes in the generated code - // that relates to the identified object. - Begin *int32 `protobuf:"varint,3,opt,name=begin" json:"begin,omitempty"` - // Identifies the ending offset in bytes in the generated code that - // relates to the identified offset. The end offset should be one past - // the last relevant byte (so the length of the text = end - begin). - End *int32 `protobuf:"varint,4,opt,name=end" json:"end,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GeneratedCodeInfo_Annotation) Reset() { *m = GeneratedCodeInfo_Annotation{} } -func (m *GeneratedCodeInfo_Annotation) String() string { return proto.CompactTextString(m) } -func (*GeneratedCodeInfo_Annotation) ProtoMessage() {} -func (*GeneratedCodeInfo_Annotation) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{20, 0} -} -func (m *GeneratedCodeInfo_Annotation) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GeneratedCodeInfo_Annotation.Unmarshal(m, b) -} -func (m *GeneratedCodeInfo_Annotation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GeneratedCodeInfo_Annotation.Marshal(b, m, deterministic) -} -func (dst *GeneratedCodeInfo_Annotation) XXX_Merge(src proto.Message) { - xxx_messageInfo_GeneratedCodeInfo_Annotation.Merge(dst, src) -} -func (m *GeneratedCodeInfo_Annotation) XXX_Size() int { - return xxx_messageInfo_GeneratedCodeInfo_Annotation.Size(m) -} -func (m *GeneratedCodeInfo_Annotation) XXX_DiscardUnknown() { - xxx_messageInfo_GeneratedCodeInfo_Annotation.DiscardUnknown(m) -} - -var xxx_messageInfo_GeneratedCodeInfo_Annotation proto.InternalMessageInfo - -func (m *GeneratedCodeInfo_Annotation) GetPath() []int32 { - if m != nil { - return m.Path - } - return nil -} - -func (m *GeneratedCodeInfo_Annotation) GetSourceFile() string { - if m != nil && m.SourceFile != nil { - return *m.SourceFile - } - return "" -} - -func (m *GeneratedCodeInfo_Annotation) GetBegin() int32 { - if m != nil && m.Begin != nil { - return *m.Begin - } - return 0 -} - -func (m *GeneratedCodeInfo_Annotation) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -func init() { - proto.RegisterType((*FileDescriptorSet)(nil), "google.protobuf.FileDescriptorSet") - proto.RegisterType((*FileDescriptorProto)(nil), "google.protobuf.FileDescriptorProto") - proto.RegisterType((*DescriptorProto)(nil), "google.protobuf.DescriptorProto") - proto.RegisterType((*DescriptorProto_ExtensionRange)(nil), "google.protobuf.DescriptorProto.ExtensionRange") - proto.RegisterType((*DescriptorProto_ReservedRange)(nil), "google.protobuf.DescriptorProto.ReservedRange") - proto.RegisterType((*ExtensionRangeOptions)(nil), "google.protobuf.ExtensionRangeOptions") - proto.RegisterType((*FieldDescriptorProto)(nil), "google.protobuf.FieldDescriptorProto") - proto.RegisterType((*OneofDescriptorProto)(nil), "google.protobuf.OneofDescriptorProto") - proto.RegisterType((*EnumDescriptorProto)(nil), "google.protobuf.EnumDescriptorProto") - proto.RegisterType((*EnumDescriptorProto_EnumReservedRange)(nil), "google.protobuf.EnumDescriptorProto.EnumReservedRange") - proto.RegisterType((*EnumValueDescriptorProto)(nil), "google.protobuf.EnumValueDescriptorProto") - proto.RegisterType((*ServiceDescriptorProto)(nil), "google.protobuf.ServiceDescriptorProto") - proto.RegisterType((*MethodDescriptorProto)(nil), "google.protobuf.MethodDescriptorProto") - proto.RegisterType((*FileOptions)(nil), "google.protobuf.FileOptions") - proto.RegisterType((*MessageOptions)(nil), "google.protobuf.MessageOptions") - proto.RegisterType((*FieldOptions)(nil), "google.protobuf.FieldOptions") - proto.RegisterType((*OneofOptions)(nil), "google.protobuf.OneofOptions") - proto.RegisterType((*EnumOptions)(nil), "google.protobuf.EnumOptions") - proto.RegisterType((*EnumValueOptions)(nil), "google.protobuf.EnumValueOptions") - proto.RegisterType((*ServiceOptions)(nil), "google.protobuf.ServiceOptions") - proto.RegisterType((*MethodOptions)(nil), "google.protobuf.MethodOptions") - proto.RegisterType((*UninterpretedOption)(nil), "google.protobuf.UninterpretedOption") - proto.RegisterType((*UninterpretedOption_NamePart)(nil), "google.protobuf.UninterpretedOption.NamePart") - proto.RegisterType((*SourceCodeInfo)(nil), "google.protobuf.SourceCodeInfo") - proto.RegisterType((*SourceCodeInfo_Location)(nil), "google.protobuf.SourceCodeInfo.Location") - proto.RegisterType((*GeneratedCodeInfo)(nil), "google.protobuf.GeneratedCodeInfo") - proto.RegisterType((*GeneratedCodeInfo_Annotation)(nil), "google.protobuf.GeneratedCodeInfo.Annotation") - proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Type", FieldDescriptorProto_Type_name, FieldDescriptorProto_Type_value) - proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Label", FieldDescriptorProto_Label_name, FieldDescriptorProto_Label_value) - proto.RegisterEnum("google.protobuf.FileOptions_OptimizeMode", FileOptions_OptimizeMode_name, FileOptions_OptimizeMode_value) - proto.RegisterEnum("google.protobuf.FieldOptions_CType", FieldOptions_CType_name, FieldOptions_CType_value) - proto.RegisterEnum("google.protobuf.FieldOptions_JSType", FieldOptions_JSType_name, FieldOptions_JSType_value) - proto.RegisterEnum("google.protobuf.MethodOptions_IdempotencyLevel", MethodOptions_IdempotencyLevel_name, MethodOptions_IdempotencyLevel_value) -} - -func init() { - proto.RegisterFile("google/protobuf/descriptor.proto", fileDescriptor_descriptor_4df4cb5f42392df6) -} - -var fileDescriptor_descriptor_4df4cb5f42392df6 = []byte{ - // 2555 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x59, 0xdd, 0x6e, 0x1b, 0xc7, - 0xf5, 0xcf, 0xf2, 0x4b, 0xe4, 0x21, 0x45, 0x8d, 0x46, 0x8a, 0xbd, 0x56, 0x3e, 0x2c, 0x33, 0x1f, - 0x96, 0x9d, 0x7f, 0xa8, 0xc0, 0xb1, 0x1d, 0x47, 0xfe, 0x23, 0x2d, 0x45, 0xae, 0x15, 0xaa, 0x12, - 0xc9, 0x2e, 0xa9, 0xe6, 0x03, 0x28, 0x16, 0xa3, 0xdd, 0x21, 0xb9, 0xf6, 0x72, 0x77, 0xb3, 0xbb, - 0xb4, 0xad, 0xa0, 0x17, 0x06, 0x7a, 0xd5, 0xab, 0xde, 0x16, 0x45, 0xd1, 0x8b, 0xde, 0x04, 0xe8, - 0x03, 0x14, 0xc8, 0x5d, 0x9f, 0xa0, 0x40, 0xde, 0xa0, 0x68, 0x0b, 0xb4, 0x8f, 0xd0, 0xcb, 0x62, - 0x66, 0x76, 0x97, 0xbb, 0x24, 0x15, 0x2b, 0x01, 0xe2, 0x5c, 0x91, 0xf3, 0x9b, 0xdf, 0x39, 0x73, - 0xe6, 0xcc, 0x99, 0x33, 0x67, 0x66, 0x61, 0x7b, 0xe4, 0x38, 0x23, 0x8b, 0xee, 0xba, 0x9e, 0x13, - 0x38, 0xa7, 0xd3, 0xe1, 0xae, 0x41, 0x7d, 0xdd, 0x33, 0xdd, 0xc0, 0xf1, 0xea, 0x1c, 0xc3, 0x6b, - 0x82, 0x51, 0x8f, 0x18, 0xb5, 0x63, 0x58, 0x7f, 0x60, 0x5a, 0xb4, 0x15, 0x13, 0xfb, 0x34, 0xc0, - 0xf7, 0x20, 0x37, 0x34, 0x2d, 0x2a, 0x4b, 0xdb, 0xd9, 0x9d, 0xf2, 0xad, 0x37, 0xeb, 0x73, 0x42, - 0xf5, 0xb4, 0x44, 0x8f, 0xc1, 0x2a, 0x97, 0xa8, 0xfd, 0x2b, 0x07, 0x1b, 0x4b, 0x7a, 0x31, 0x86, - 0x9c, 0x4d, 0x26, 0x4c, 0xa3, 0xb4, 0x53, 0x52, 0xf9, 0x7f, 0x2c, 0xc3, 0x8a, 0x4b, 0xf4, 0x47, - 0x64, 0x44, 0xe5, 0x0c, 0x87, 0xa3, 0x26, 0x7e, 0x1d, 0xc0, 0xa0, 0x2e, 0xb5, 0x0d, 0x6a, 0xeb, - 0x67, 0x72, 0x76, 0x3b, 0xbb, 0x53, 0x52, 0x13, 0x08, 0x7e, 0x07, 0xd6, 0xdd, 0xe9, 0xa9, 0x65, - 0xea, 0x5a, 0x82, 0x06, 0xdb, 0xd9, 0x9d, 0xbc, 0x8a, 0x44, 0x47, 0x6b, 0x46, 0xbe, 0x0e, 0x6b, - 0x4f, 0x28, 0x79, 0x94, 0xa4, 0x96, 0x39, 0xb5, 0xca, 0xe0, 0x04, 0xb1, 0x09, 0x95, 0x09, 0xf5, - 0x7d, 0x32, 0xa2, 0x5a, 0x70, 0xe6, 0x52, 0x39, 0xc7, 0x67, 0xbf, 0xbd, 0x30, 0xfb, 0xf9, 0x99, - 0x97, 0x43, 0xa9, 0xc1, 0x99, 0x4b, 0x71, 0x03, 0x4a, 0xd4, 0x9e, 0x4e, 0x84, 0x86, 0xfc, 0x39, - 0xfe, 0x53, 0xec, 0xe9, 0x64, 0x5e, 0x4b, 0x91, 0x89, 0x85, 0x2a, 0x56, 0x7c, 0xea, 0x3d, 0x36, - 0x75, 0x2a, 0x17, 0xb8, 0x82, 0xeb, 0x0b, 0x0a, 0xfa, 0xa2, 0x7f, 0x5e, 0x47, 0x24, 0x87, 0x9b, - 0x50, 0xa2, 0x4f, 0x03, 0x6a, 0xfb, 0xa6, 0x63, 0xcb, 0x2b, 0x5c, 0xc9, 0x5b, 0x4b, 0x56, 0x91, - 0x5a, 0xc6, 0xbc, 0x8a, 0x99, 0x1c, 0xbe, 0x0b, 0x2b, 0x8e, 0x1b, 0x98, 0x8e, 0xed, 0xcb, 0xc5, - 0x6d, 0x69, 0xa7, 0x7c, 0xeb, 0xd5, 0xa5, 0x81, 0xd0, 0x15, 0x1c, 0x35, 0x22, 0xe3, 0x36, 0x20, - 0xdf, 0x99, 0x7a, 0x3a, 0xd5, 0x74, 0xc7, 0xa0, 0x9a, 0x69, 0x0f, 0x1d, 0xb9, 0xc4, 0x15, 0x5c, - 0x5d, 0x9c, 0x08, 0x27, 0x36, 0x1d, 0x83, 0xb6, 0xed, 0xa1, 0xa3, 0x56, 0xfd, 0x54, 0x1b, 0x5f, - 0x82, 0x82, 0x7f, 0x66, 0x07, 0xe4, 0xa9, 0x5c, 0xe1, 0x11, 0x12, 0xb6, 0x6a, 0x5f, 0x17, 0x60, - 0xed, 0x22, 0x21, 0x76, 0x1f, 0xf2, 0x43, 0x36, 0x4b, 0x39, 0xf3, 0x5d, 0x7c, 0x20, 0x64, 0xd2, - 0x4e, 0x2c, 0x7c, 0x4f, 0x27, 0x36, 0xa0, 0x6c, 0x53, 0x3f, 0xa0, 0x86, 0x88, 0x88, 0xec, 0x05, - 0x63, 0x0a, 0x84, 0xd0, 0x62, 0x48, 0xe5, 0xbe, 0x57, 0x48, 0x7d, 0x0a, 0x6b, 0xb1, 0x49, 0x9a, - 0x47, 0xec, 0x51, 0x14, 0x9b, 0xbb, 0xcf, 0xb3, 0xa4, 0xae, 0x44, 0x72, 0x2a, 0x13, 0x53, 0xab, - 0x34, 0xd5, 0xc6, 0x2d, 0x00, 0xc7, 0xa6, 0xce, 0x50, 0x33, 0xa8, 0x6e, 0xc9, 0xc5, 0x73, 0xbc, - 0xd4, 0x65, 0x94, 0x05, 0x2f, 0x39, 0x02, 0xd5, 0x2d, 0xfc, 0xe1, 0x2c, 0xd4, 0x56, 0xce, 0x89, - 0x94, 0x63, 0xb1, 0xc9, 0x16, 0xa2, 0xed, 0x04, 0xaa, 0x1e, 0x65, 0x71, 0x4f, 0x8d, 0x70, 0x66, - 0x25, 0x6e, 0x44, 0xfd, 0xb9, 0x33, 0x53, 0x43, 0x31, 0x31, 0xb1, 0x55, 0x2f, 0xd9, 0xc4, 0x6f, - 0x40, 0x0c, 0x68, 0x3c, 0xac, 0x80, 0x67, 0xa1, 0x4a, 0x04, 0x76, 0xc8, 0x84, 0x6e, 0x7d, 0x09, - 0xd5, 0xb4, 0x7b, 0xf0, 0x26, 0xe4, 0xfd, 0x80, 0x78, 0x01, 0x8f, 0xc2, 0xbc, 0x2a, 0x1a, 0x18, - 0x41, 0x96, 0xda, 0x06, 0xcf, 0x72, 0x79, 0x95, 0xfd, 0xc5, 0x3f, 0x9d, 0x4d, 0x38, 0xcb, 0x27, - 0xfc, 0xf6, 0xe2, 0x8a, 0xa6, 0x34, 0xcf, 0xcf, 0x7b, 0xeb, 0x03, 0x58, 0x4d, 0x4d, 0xe0, 0xa2, - 0x43, 0xd7, 0x7e, 0x05, 0x2f, 0x2f, 0x55, 0x8d, 0x3f, 0x85, 0xcd, 0xa9, 0x6d, 0xda, 0x01, 0xf5, - 0x5c, 0x8f, 0xb2, 0x88, 0x15, 0x43, 0xc9, 0xff, 0x5e, 0x39, 0x27, 0xe6, 0x4e, 0x92, 0x6c, 0xa1, - 0x45, 0xdd, 0x98, 0x2e, 0x82, 0x37, 0x4b, 0xc5, 0xff, 0xac, 0xa0, 0x67, 0xcf, 0x9e, 0x3d, 0xcb, - 0xd4, 0x7e, 0x57, 0x80, 0xcd, 0x65, 0x7b, 0x66, 0xe9, 0xf6, 0xbd, 0x04, 0x05, 0x7b, 0x3a, 0x39, - 0xa5, 0x1e, 0x77, 0x52, 0x5e, 0x0d, 0x5b, 0xb8, 0x01, 0x79, 0x8b, 0x9c, 0x52, 0x4b, 0xce, 0x6d, - 0x4b, 0x3b, 0xd5, 0x5b, 0xef, 0x5c, 0x68, 0x57, 0xd6, 0x8f, 0x98, 0x88, 0x2a, 0x24, 0xf1, 0x47, - 0x90, 0x0b, 0x53, 0x34, 0xd3, 0x70, 0xf3, 0x62, 0x1a, 0xd8, 0x5e, 0x52, 0xb9, 0x1c, 0x7e, 0x05, - 0x4a, 0xec, 0x57, 0xc4, 0x46, 0x81, 0xdb, 0x5c, 0x64, 0x00, 0x8b, 0x0b, 0xbc, 0x05, 0x45, 0xbe, - 0x4d, 0x0c, 0x1a, 0x1d, 0x6d, 0x71, 0x9b, 0x05, 0x96, 0x41, 0x87, 0x64, 0x6a, 0x05, 0xda, 0x63, - 0x62, 0x4d, 0x29, 0x0f, 0xf8, 0x92, 0x5a, 0x09, 0xc1, 0x5f, 0x30, 0x0c, 0x5f, 0x85, 0xb2, 0xd8, - 0x55, 0xa6, 0x6d, 0xd0, 0xa7, 0x3c, 0x7b, 0xe6, 0x55, 0xb1, 0xd1, 0xda, 0x0c, 0x61, 0xc3, 0x3f, - 0xf4, 0x1d, 0x3b, 0x0a, 0x4d, 0x3e, 0x04, 0x03, 0xf8, 0xf0, 0x1f, 0xcc, 0x27, 0xee, 0xd7, 0x96, - 0x4f, 0x6f, 0x3e, 0xa6, 0x6a, 0x7f, 0xc9, 0x40, 0x8e, 0xe7, 0x8b, 0x35, 0x28, 0x0f, 0x3e, 0xeb, - 0x29, 0x5a, 0xab, 0x7b, 0xb2, 0x7f, 0xa4, 0x20, 0x09, 0x57, 0x01, 0x38, 0xf0, 0xe0, 0xa8, 0xdb, - 0x18, 0xa0, 0x4c, 0xdc, 0x6e, 0x77, 0x06, 0x77, 0x6f, 0xa3, 0x6c, 0x2c, 0x70, 0x22, 0x80, 0x5c, - 0x92, 0xf0, 0xfe, 0x2d, 0x94, 0xc7, 0x08, 0x2a, 0x42, 0x41, 0xfb, 0x53, 0xa5, 0x75, 0xf7, 0x36, - 0x2a, 0xa4, 0x91, 0xf7, 0x6f, 0xa1, 0x15, 0xbc, 0x0a, 0x25, 0x8e, 0xec, 0x77, 0xbb, 0x47, 0xa8, - 0x18, 0xeb, 0xec, 0x0f, 0xd4, 0x76, 0xe7, 0x00, 0x95, 0x62, 0x9d, 0x07, 0x6a, 0xf7, 0xa4, 0x87, - 0x20, 0xd6, 0x70, 0xac, 0xf4, 0xfb, 0x8d, 0x03, 0x05, 0x95, 0x63, 0xc6, 0xfe, 0x67, 0x03, 0xa5, - 0x8f, 0x2a, 0x29, 0xb3, 0xde, 0xbf, 0x85, 0x56, 0xe3, 0x21, 0x94, 0xce, 0xc9, 0x31, 0xaa, 0xe2, - 0x75, 0x58, 0x15, 0x43, 0x44, 0x46, 0xac, 0xcd, 0x41, 0x77, 0x6f, 0x23, 0x34, 0x33, 0x44, 0x68, - 0x59, 0x4f, 0x01, 0x77, 0x6f, 0x23, 0x5c, 0x6b, 0x42, 0x9e, 0x47, 0x17, 0xc6, 0x50, 0x3d, 0x6a, - 0xec, 0x2b, 0x47, 0x5a, 0xb7, 0x37, 0x68, 0x77, 0x3b, 0x8d, 0x23, 0x24, 0xcd, 0x30, 0x55, 0xf9, - 0xf9, 0x49, 0x5b, 0x55, 0x5a, 0x28, 0x93, 0xc4, 0x7a, 0x4a, 0x63, 0xa0, 0xb4, 0x50, 0xb6, 0xa6, - 0xc3, 0xe6, 0xb2, 0x3c, 0xb9, 0x74, 0x67, 0x24, 0x96, 0x38, 0x73, 0xce, 0x12, 0x73, 0x5d, 0x0b, - 0x4b, 0xfc, 0xcf, 0x0c, 0x6c, 0x2c, 0x39, 0x2b, 0x96, 0x0e, 0xf2, 0x13, 0xc8, 0x8b, 0x10, 0x15, - 0xa7, 0xe7, 0x8d, 0xa5, 0x87, 0x0e, 0x0f, 0xd8, 0x85, 0x13, 0x94, 0xcb, 0x25, 0x2b, 0x88, 0xec, - 0x39, 0x15, 0x04, 0x53, 0xb1, 0x90, 0xd3, 0x7f, 0xb9, 0x90, 0xd3, 0xc5, 0xb1, 0x77, 0xf7, 0x22, - 0xc7, 0x1e, 0xc7, 0xbe, 0x5b, 0x6e, 0xcf, 0x2f, 0xc9, 0xed, 0xf7, 0x61, 0x7d, 0x41, 0xd1, 0x85, - 0x73, 0xec, 0xaf, 0x25, 0x90, 0xcf, 0x73, 0xce, 0x73, 0x32, 0x5d, 0x26, 0x95, 0xe9, 0xee, 0xcf, - 0x7b, 0xf0, 0xda, 0xf9, 0x8b, 0xb0, 0xb0, 0xd6, 0x5f, 0x49, 0x70, 0x69, 0x79, 0xa5, 0xb8, 0xd4, - 0x86, 0x8f, 0xa0, 0x30, 0xa1, 0xc1, 0xd8, 0x89, 0xaa, 0xa5, 0xb7, 0x97, 0x9c, 0xc1, 0xac, 0x7b, - 0x7e, 0xb1, 0x43, 0xa9, 0xe4, 0x21, 0x9e, 0x3d, 0xaf, 0xdc, 0x13, 0xd6, 0x2c, 0x58, 0xfa, 0x9b, - 0x0c, 0xbc, 0xbc, 0x54, 0xf9, 0x52, 0x43, 0x5f, 0x03, 0x30, 0x6d, 0x77, 0x1a, 0x88, 0x8a, 0x48, - 0x24, 0xd8, 0x12, 0x47, 0x78, 0xf2, 0x62, 0xc9, 0x73, 0x1a, 0xc4, 0xfd, 0x59, 0xde, 0x0f, 0x02, - 0xe2, 0x84, 0x7b, 0x33, 0x43, 0x73, 0xdc, 0xd0, 0xd7, 0xcf, 0x99, 0xe9, 0x42, 0x60, 0xbe, 0x07, - 0x48, 0xb7, 0x4c, 0x6a, 0x07, 0x9a, 0x1f, 0x78, 0x94, 0x4c, 0x4c, 0x7b, 0xc4, 0x4f, 0x90, 0xe2, - 0x5e, 0x7e, 0x48, 0x2c, 0x9f, 0xaa, 0x6b, 0xa2, 0xbb, 0x1f, 0xf5, 0x32, 0x09, 0x1e, 0x40, 0x5e, - 0x42, 0xa2, 0x90, 0x92, 0x10, 0xdd, 0xb1, 0x44, 0xed, 0xeb, 0x22, 0x94, 0x13, 0x75, 0x35, 0xbe, - 0x06, 0x95, 0x87, 0xe4, 0x31, 0xd1, 0xa2, 0xbb, 0x92, 0xf0, 0x44, 0x99, 0x61, 0xbd, 0xf0, 0xbe, - 0xf4, 0x1e, 0x6c, 0x72, 0x8a, 0x33, 0x0d, 0xa8, 0xa7, 0xe9, 0x16, 0xf1, 0x7d, 0xee, 0xb4, 0x22, - 0xa7, 0x62, 0xd6, 0xd7, 0x65, 0x5d, 0xcd, 0xa8, 0x07, 0xdf, 0x81, 0x0d, 0x2e, 0x31, 0x99, 0x5a, - 0x81, 0xe9, 0x5a, 0x54, 0x63, 0xb7, 0x37, 0x9f, 0x9f, 0x24, 0xb1, 0x65, 0xeb, 0x8c, 0x71, 0x1c, - 0x12, 0x98, 0x45, 0x3e, 0x6e, 0xc1, 0x6b, 0x5c, 0x6c, 0x44, 0x6d, 0xea, 0x91, 0x80, 0x6a, 0xf4, - 0x8b, 0x29, 0xb1, 0x7c, 0x8d, 0xd8, 0x86, 0x36, 0x26, 0xfe, 0x58, 0xde, 0x64, 0x0a, 0xf6, 0x33, - 0xb2, 0xa4, 0x5e, 0x61, 0xc4, 0x83, 0x90, 0xa7, 0x70, 0x5a, 0xc3, 0x36, 0x3e, 0x26, 0xfe, 0x18, - 0xef, 0xc1, 0x25, 0xae, 0xc5, 0x0f, 0x3c, 0xd3, 0x1e, 0x69, 0xfa, 0x98, 0xea, 0x8f, 0xb4, 0x69, - 0x30, 0xbc, 0x27, 0xbf, 0x92, 0x1c, 0x9f, 0x5b, 0xd8, 0xe7, 0x9c, 0x26, 0xa3, 0x9c, 0x04, 0xc3, - 0x7b, 0xb8, 0x0f, 0x15, 0xb6, 0x18, 0x13, 0xf3, 0x4b, 0xaa, 0x0d, 0x1d, 0x8f, 0x1f, 0x8d, 0xd5, - 0x25, 0xa9, 0x29, 0xe1, 0xc1, 0x7a, 0x37, 0x14, 0x38, 0x76, 0x0c, 0xba, 0x97, 0xef, 0xf7, 0x14, - 0xa5, 0xa5, 0x96, 0x23, 0x2d, 0x0f, 0x1c, 0x8f, 0x05, 0xd4, 0xc8, 0x89, 0x1d, 0x5c, 0x16, 0x01, - 0x35, 0x72, 0x22, 0xf7, 0xde, 0x81, 0x0d, 0x5d, 0x17, 0x73, 0x36, 0x75, 0x2d, 0xbc, 0x63, 0xf9, - 0x32, 0x4a, 0x39, 0x4b, 0xd7, 0x0f, 0x04, 0x21, 0x8c, 0x71, 0x1f, 0x7f, 0x08, 0x2f, 0xcf, 0x9c, - 0x95, 0x14, 0x5c, 0x5f, 0x98, 0xe5, 0xbc, 0xe8, 0x1d, 0xd8, 0x70, 0xcf, 0x16, 0x05, 0x71, 0x6a, - 0x44, 0xf7, 0x6c, 0x5e, 0xec, 0x03, 0xd8, 0x74, 0xc7, 0xee, 0xa2, 0xdc, 0xcd, 0xa4, 0x1c, 0x76, - 0xc7, 0xee, 0xbc, 0xe0, 0x5b, 0xfc, 0xc2, 0xed, 0x51, 0x9d, 0x04, 0xd4, 0x90, 0x2f, 0x27, 0xe9, - 0x89, 0x0e, 0xbc, 0x0b, 0x48, 0xd7, 0x35, 0x6a, 0x93, 0x53, 0x8b, 0x6a, 0xc4, 0xa3, 0x36, 0xf1, - 0xe5, 0xab, 0x49, 0x72, 0x55, 0xd7, 0x15, 0xde, 0xdb, 0xe0, 0x9d, 0xf8, 0x26, 0xac, 0x3b, 0xa7, - 0x0f, 0x75, 0x11, 0x92, 0x9a, 0xeb, 0xd1, 0xa1, 0xf9, 0x54, 0x7e, 0x93, 0xfb, 0x77, 0x8d, 0x75, - 0xf0, 0x80, 0xec, 0x71, 0x18, 0xdf, 0x00, 0xa4, 0xfb, 0x63, 0xe2, 0xb9, 0x3c, 0x27, 0xfb, 0x2e, - 0xd1, 0xa9, 0xfc, 0x96, 0xa0, 0x0a, 0xbc, 0x13, 0xc1, 0x6c, 0x4b, 0xf8, 0x4f, 0xcc, 0x61, 0x10, - 0x69, 0xbc, 0x2e, 0xb6, 0x04, 0xc7, 0x42, 0x6d, 0x3b, 0x80, 0x98, 0x2b, 0x52, 0x03, 0xef, 0x70, - 0x5a, 0xd5, 0x1d, 0xbb, 0xc9, 0x71, 0xdf, 0x80, 0x55, 0xc6, 0x9c, 0x0d, 0x7a, 0x43, 0x14, 0x64, - 0xee, 0x38, 0x31, 0xe2, 0x0f, 0x56, 0x1b, 0xd7, 0xf6, 0xa0, 0x92, 0x8c, 0x4f, 0x5c, 0x02, 0x11, - 0xa1, 0x48, 0x62, 0xc5, 0x4a, 0xb3, 0xdb, 0x62, 0x65, 0xc6, 0xe7, 0x0a, 0xca, 0xb0, 0x72, 0xe7, - 0xa8, 0x3d, 0x50, 0x34, 0xf5, 0xa4, 0x33, 0x68, 0x1f, 0x2b, 0x28, 0x9b, 0xa8, 0xab, 0x0f, 0x73, - 0xc5, 0xb7, 0xd1, 0xf5, 0xda, 0x37, 0x19, 0xa8, 0xa6, 0x2f, 0x4a, 0xf8, 0xff, 0xe1, 0x72, 0xf4, - 0xaa, 0xe1, 0xd3, 0x40, 0x7b, 0x62, 0x7a, 0x7c, 0xe3, 0x4c, 0x88, 0x38, 0xc4, 0xe2, 0xa5, 0xdb, - 0x0c, 0x59, 0x7d, 0x1a, 0x7c, 0x62, 0x7a, 0x6c, 0x5b, 0x4c, 0x48, 0x80, 0x8f, 0xe0, 0xaa, 0xed, - 0x68, 0x7e, 0x40, 0x6c, 0x83, 0x78, 0x86, 0x36, 0x7b, 0x4f, 0xd2, 0x88, 0xae, 0x53, 0xdf, 0x77, - 0xc4, 0x81, 0x15, 0x6b, 0x79, 0xd5, 0x76, 0xfa, 0x21, 0x79, 0x96, 0xc9, 0x1b, 0x21, 0x75, 0x2e, - 0xcc, 0xb2, 0xe7, 0x85, 0xd9, 0x2b, 0x50, 0x9a, 0x10, 0x57, 0xa3, 0x76, 0xe0, 0x9d, 0xf1, 0xf2, - 0xb8, 0xa8, 0x16, 0x27, 0xc4, 0x55, 0x58, 0xfb, 0x85, 0xdc, 0x52, 0x0e, 0x73, 0xc5, 0x22, 0x2a, - 0x1d, 0xe6, 0x8a, 0x25, 0x04, 0xb5, 0x7f, 0x64, 0xa1, 0x92, 0x2c, 0x97, 0xd9, 0xed, 0x43, 0xe7, - 0x27, 0x8b, 0xc4, 0x73, 0xcf, 0x1b, 0xdf, 0x5a, 0x5c, 0xd7, 0x9b, 0xec, 0xc8, 0xd9, 0x2b, 0x88, - 0x22, 0x56, 0x15, 0x92, 0xec, 0xb8, 0x67, 0xd9, 0x86, 0x8a, 0xa2, 0xa1, 0xa8, 0x86, 0x2d, 0x7c, - 0x00, 0x85, 0x87, 0x3e, 0xd7, 0x5d, 0xe0, 0xba, 0xdf, 0xfc, 0x76, 0xdd, 0x87, 0x7d, 0xae, 0xbc, - 0x74, 0xd8, 0xd7, 0x3a, 0x5d, 0xf5, 0xb8, 0x71, 0xa4, 0x86, 0xe2, 0xf8, 0x0a, 0xe4, 0x2c, 0xf2, - 0xe5, 0x59, 0xfa, 0x70, 0xe2, 0xd0, 0x45, 0x17, 0xe1, 0x0a, 0xe4, 0x9e, 0x50, 0xf2, 0x28, 0x7d, - 0x24, 0x70, 0xe8, 0x07, 0xdc, 0x0c, 0xbb, 0x90, 0xe7, 0xfe, 0xc2, 0x00, 0xa1, 0xc7, 0xd0, 0x4b, - 0xb8, 0x08, 0xb9, 0x66, 0x57, 0x65, 0x1b, 0x02, 0x41, 0x45, 0xa0, 0x5a, 0xaf, 0xad, 0x34, 0x15, - 0x94, 0xa9, 0xdd, 0x81, 0x82, 0x70, 0x02, 0xdb, 0x2c, 0xb1, 0x1b, 0xd0, 0x4b, 0x61, 0x33, 0xd4, - 0x21, 0x45, 0xbd, 0x27, 0xc7, 0xfb, 0x8a, 0x8a, 0x32, 0xe9, 0xa5, 0xce, 0xa1, 0x7c, 0xcd, 0x87, - 0x4a, 0xb2, 0x5e, 0x7e, 0x31, 0x77, 0xe1, 0xbf, 0x4a, 0x50, 0x4e, 0xd4, 0xbf, 0xac, 0x70, 0x21, - 0x96, 0xe5, 0x3c, 0xd1, 0x88, 0x65, 0x12, 0x3f, 0x0c, 0x0d, 0xe0, 0x50, 0x83, 0x21, 0x17, 0x5d, - 0xba, 0x17, 0xb4, 0x45, 0xf2, 0xa8, 0x50, 0xfb, 0xa3, 0x04, 0x68, 0xbe, 0x00, 0x9d, 0x33, 0x53, - 0xfa, 0x31, 0xcd, 0xac, 0xfd, 0x41, 0x82, 0x6a, 0xba, 0xea, 0x9c, 0x33, 0xef, 0xda, 0x8f, 0x6a, - 0xde, 0xdf, 0x33, 0xb0, 0x9a, 0xaa, 0x35, 0x2f, 0x6a, 0xdd, 0x17, 0xb0, 0x6e, 0x1a, 0x74, 0xe2, - 0x3a, 0x01, 0xb5, 0xf5, 0x33, 0xcd, 0xa2, 0x8f, 0xa9, 0x25, 0xd7, 0x78, 0xd2, 0xd8, 0xfd, 0xf6, - 0x6a, 0xb6, 0xde, 0x9e, 0xc9, 0x1d, 0x31, 0xb1, 0xbd, 0x8d, 0x76, 0x4b, 0x39, 0xee, 0x75, 0x07, - 0x4a, 0xa7, 0xf9, 0x99, 0x76, 0xd2, 0xf9, 0x59, 0xa7, 0xfb, 0x49, 0x47, 0x45, 0xe6, 0x1c, 0xed, - 0x07, 0xdc, 0xf6, 0x3d, 0x40, 0xf3, 0x46, 0xe1, 0xcb, 0xb0, 0xcc, 0x2c, 0xf4, 0x12, 0xde, 0x80, - 0xb5, 0x4e, 0x57, 0xeb, 0xb7, 0x5b, 0x8a, 0xa6, 0x3c, 0x78, 0xa0, 0x34, 0x07, 0x7d, 0xf1, 0x3e, - 0x11, 0xb3, 0x07, 0xa9, 0x0d, 0x5e, 0xfb, 0x7d, 0x16, 0x36, 0x96, 0x58, 0x82, 0x1b, 0xe1, 0xcd, - 0x42, 0x5c, 0x76, 0xde, 0xbd, 0x88, 0xf5, 0x75, 0x56, 0x10, 0xf4, 0x88, 0x17, 0x84, 0x17, 0x91, - 0x1b, 0xc0, 0xbc, 0x64, 0x07, 0xe6, 0xd0, 0xa4, 0x5e, 0xf8, 0x9c, 0x23, 0xae, 0x1b, 0x6b, 0x33, - 0x5c, 0xbc, 0xe8, 0xfc, 0x1f, 0x60, 0xd7, 0xf1, 0xcd, 0xc0, 0x7c, 0x4c, 0x35, 0xd3, 0x8e, 0xde, - 0x7e, 0xd8, 0xf5, 0x23, 0xa7, 0xa2, 0xa8, 0xa7, 0x6d, 0x07, 0x31, 0xdb, 0xa6, 0x23, 0x32, 0xc7, - 0x66, 0xc9, 0x3c, 0xab, 0xa2, 0xa8, 0x27, 0x66, 0x5f, 0x83, 0x8a, 0xe1, 0x4c, 0x59, 0x4d, 0x26, - 0x78, 0xec, 0xec, 0x90, 0xd4, 0xb2, 0xc0, 0x62, 0x4a, 0x58, 0x6d, 0xcf, 0x1e, 0x9d, 0x2a, 0x6a, - 0x59, 0x60, 0x82, 0x72, 0x1d, 0xd6, 0xc8, 0x68, 0xe4, 0x31, 0xe5, 0x91, 0x22, 0x71, 0x7f, 0xa8, - 0xc6, 0x30, 0x27, 0x6e, 0x1d, 0x42, 0x31, 0xf2, 0x03, 0x3b, 0xaa, 0x99, 0x27, 0x34, 0x57, 0x5c, - 0x8a, 0x33, 0x3b, 0x25, 0xb5, 0x68, 0x47, 0x9d, 0xd7, 0xa0, 0x62, 0xfa, 0xda, 0xec, 0x0d, 0x3d, - 0xb3, 0x9d, 0xd9, 0x29, 0xaa, 0x65, 0xd3, 0x8f, 0xdf, 0x1f, 0x6b, 0x5f, 0x65, 0xa0, 0x9a, 0xfe, - 0x06, 0x80, 0x5b, 0x50, 0xb4, 0x1c, 0x9d, 0xf0, 0xd0, 0x12, 0x1f, 0xa0, 0x76, 0x9e, 0xf3, 0xd9, - 0xa0, 0x7e, 0x14, 0xf2, 0xd5, 0x58, 0x72, 0xeb, 0x6f, 0x12, 0x14, 0x23, 0x18, 0x5f, 0x82, 0x9c, - 0x4b, 0x82, 0x31, 0x57, 0x97, 0xdf, 0xcf, 0x20, 0x49, 0xe5, 0x6d, 0x86, 0xfb, 0x2e, 0xb1, 0x79, - 0x08, 0x84, 0x38, 0x6b, 0xb3, 0x75, 0xb5, 0x28, 0x31, 0xf8, 0xe5, 0xc4, 0x99, 0x4c, 0xa8, 0x1d, - 0xf8, 0xd1, 0xba, 0x86, 0x78, 0x33, 0x84, 0xf1, 0x3b, 0xb0, 0x1e, 0x78, 0xc4, 0xb4, 0x52, 0xdc, - 0x1c, 0xe7, 0xa2, 0xa8, 0x23, 0x26, 0xef, 0xc1, 0x95, 0x48, 0xaf, 0x41, 0x03, 0xa2, 0x8f, 0xa9, - 0x31, 0x13, 0x2a, 0xf0, 0x47, 0x88, 0xcb, 0x21, 0xa1, 0x15, 0xf6, 0x47, 0xb2, 0xb5, 0x6f, 0x24, - 0x58, 0x8f, 0xae, 0x53, 0x46, 0xec, 0xac, 0x63, 0x00, 0x62, 0xdb, 0x4e, 0x90, 0x74, 0xd7, 0x62, - 0x28, 0x2f, 0xc8, 0xd5, 0x1b, 0xb1, 0x90, 0x9a, 0x50, 0xb0, 0x35, 0x01, 0x98, 0xf5, 0x9c, 0xeb, - 0xb6, 0xab, 0x50, 0x0e, 0x3f, 0xf0, 0xf0, 0xaf, 0x84, 0xe2, 0x02, 0x0e, 0x02, 0x62, 0xf7, 0x2e, - 0xbc, 0x09, 0xf9, 0x53, 0x3a, 0x32, 0xed, 0xf0, 0xd9, 0x56, 0x34, 0xa2, 0x67, 0x92, 0x5c, 0xfc, - 0x4c, 0xb2, 0xff, 0x5b, 0x09, 0x36, 0x74, 0x67, 0x32, 0x6f, 0xef, 0x3e, 0x9a, 0x7b, 0x05, 0xf0, - 0x3f, 0x96, 0x3e, 0xff, 0x68, 0x64, 0x06, 0xe3, 0xe9, 0x69, 0x5d, 0x77, 0x26, 0xbb, 0x23, 0xc7, - 0x22, 0xf6, 0x68, 0xf6, 0x99, 0x93, 0xff, 0xd1, 0xdf, 0x1d, 0x51, 0xfb, 0xdd, 0x91, 0x93, 0xf8, - 0xe8, 0x79, 0x7f, 0xf6, 0xf7, 0xbf, 0x92, 0xf4, 0xa7, 0x4c, 0xf6, 0xa0, 0xb7, 0xff, 0xe7, 0xcc, - 0xd6, 0x81, 0x18, 0xae, 0x17, 0xb9, 0x47, 0xa5, 0x43, 0x8b, 0xea, 0x6c, 0xca, 0xff, 0x0b, 0x00, - 0x00, 0xff, 0xff, 0x1a, 0x28, 0x25, 0x79, 0x42, 0x1d, 0x00, 0x00, -} diff --git a/vendor/github.com/inconshreveable/mousetrap/LICENSE b/vendor/github.com/inconshreveable/mousetrap/LICENSE deleted file mode 100644 index 5f0d1fb6a..000000000 --- a/vendor/github.com/inconshreveable/mousetrap/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2014 Alan Shreve - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_others.go b/vendor/github.com/inconshreveable/mousetrap/trap_others.go deleted file mode 100644 index 9d2d8a4ba..000000000 --- a/vendor/github.com/inconshreveable/mousetrap/trap_others.go +++ /dev/null @@ -1,15 +0,0 @@ -// +build !windows - -package mousetrap - -// StartedByExplorer returns true if the program was invoked by the user -// double-clicking on the executable from explorer.exe -// -// It is conservative and returns false if any of the internal calls fail. -// It does not guarantee that the program was run from a terminal. It only can tell you -// whether it was launched from explorer.exe -// -// On non-Windows platforms, it always returns false. -func StartedByExplorer() bool { - return false -} diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_windows.go b/vendor/github.com/inconshreveable/mousetrap/trap_windows.go deleted file mode 100644 index 336142a5e..000000000 --- a/vendor/github.com/inconshreveable/mousetrap/trap_windows.go +++ /dev/null @@ -1,98 +0,0 @@ -// +build windows -// +build !go1.4 - -package mousetrap - -import ( - "fmt" - "os" - "syscall" - "unsafe" -) - -const ( - // defined by the Win32 API - th32cs_snapprocess uintptr = 0x2 -) - -var ( - kernel = syscall.MustLoadDLL("kernel32.dll") - CreateToolhelp32Snapshot = kernel.MustFindProc("CreateToolhelp32Snapshot") - Process32First = kernel.MustFindProc("Process32FirstW") - Process32Next = kernel.MustFindProc("Process32NextW") -) - -// ProcessEntry32 structure defined by the Win32 API -type processEntry32 struct { - dwSize uint32 - cntUsage uint32 - th32ProcessID uint32 - th32DefaultHeapID int - th32ModuleID uint32 - cntThreads uint32 - th32ParentProcessID uint32 - pcPriClassBase int32 - dwFlags uint32 - szExeFile [syscall.MAX_PATH]uint16 -} - -func getProcessEntry(pid int) (pe *processEntry32, err error) { - snapshot, _, e1 := CreateToolhelp32Snapshot.Call(th32cs_snapprocess, uintptr(0)) - if snapshot == uintptr(syscall.InvalidHandle) { - err = fmt.Errorf("CreateToolhelp32Snapshot: %v", e1) - return - } - defer syscall.CloseHandle(syscall.Handle(snapshot)) - - var processEntry processEntry32 - processEntry.dwSize = uint32(unsafe.Sizeof(processEntry)) - ok, _, e1 := Process32First.Call(snapshot, uintptr(unsafe.Pointer(&processEntry))) - if ok == 0 { - err = fmt.Errorf("Process32First: %v", e1) - return - } - - for { - if processEntry.th32ProcessID == uint32(pid) { - pe = &processEntry - return - } - - ok, _, e1 = Process32Next.Call(snapshot, uintptr(unsafe.Pointer(&processEntry))) - if ok == 0 { - err = fmt.Errorf("Process32Next: %v", e1) - return - } - } -} - -func getppid() (pid int, err error) { - pe, err := getProcessEntry(os.Getpid()) - if err != nil { - return - } - - pid = int(pe.th32ParentProcessID) - return -} - -// StartedByExplorer returns true if the program was invoked by the user double-clicking -// on the executable from explorer.exe -// -// It is conservative and returns false if any of the internal calls fail. -// It does not guarantee that the program was run from a terminal. It only can tell you -// whether it was launched from explorer.exe -func StartedByExplorer() bool { - ppid, err := getppid() - if err != nil { - return false - } - - pe, err := getProcessEntry(ppid) - if err != nil { - return false - } - - name := syscall.UTF16ToString(pe.szExeFile[:]) - return name == "explorer.exe" -} diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go b/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go deleted file mode 100644 index 9a28e57c3..000000000 --- a/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go +++ /dev/null @@ -1,46 +0,0 @@ -// +build windows -// +build go1.4 - -package mousetrap - -import ( - "os" - "syscall" - "unsafe" -) - -func getProcessEntry(pid int) (*syscall.ProcessEntry32, error) { - snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0) - if err != nil { - return nil, err - } - defer syscall.CloseHandle(snapshot) - var procEntry syscall.ProcessEntry32 - procEntry.Size = uint32(unsafe.Sizeof(procEntry)) - if err = syscall.Process32First(snapshot, &procEntry); err != nil { - return nil, err - } - for { - if procEntry.ProcessID == uint32(pid) { - return &procEntry, nil - } - err = syscall.Process32Next(snapshot, &procEntry) - if err != nil { - return nil, err - } - } -} - -// StartedByExplorer returns true if the program was invoked by the user double-clicking -// on the executable from explorer.exe -// -// It is conservative and returns false if any of the internal calls fail. -// It does not guarantee that the program was run from a terminal. It only can tell you -// whether it was launched from explorer.exe -func StartedByExplorer() bool { - pe, err := getProcessEntry(os.Getppid()) - if err != nil { - return false - } - return "explorer.exe" == syscall.UTF16ToString(pe.ExeFile[:]) -} diff --git a/vendor/github.com/mattn/go-isatty/LICENSE b/vendor/github.com/mattn/go-isatty/LICENSE deleted file mode 100644 index 65dc692b6..000000000 --- a/vendor/github.com/mattn/go-isatty/LICENSE +++ /dev/null @@ -1,9 +0,0 @@ -Copyright (c) Yasuhiro MATSUMOTO - -MIT License (Expat) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/mattn/go-isatty/doc.go b/vendor/github.com/mattn/go-isatty/doc.go deleted file mode 100644 index 17d4f90eb..000000000 --- a/vendor/github.com/mattn/go-isatty/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package isatty implements interface to isatty -package isatty diff --git a/vendor/github.com/mattn/go-isatty/isatty_appengine.go b/vendor/github.com/mattn/go-isatty/isatty_appengine.go deleted file mode 100644 index 9584a9884..000000000 --- a/vendor/github.com/mattn/go-isatty/isatty_appengine.go +++ /dev/null @@ -1,15 +0,0 @@ -// +build appengine - -package isatty - -// IsTerminal returns true if the file descriptor is terminal which -// is always false on on appengine classic which is a sandboxed PaaS. -func IsTerminal(fd uintptr) bool { - return false -} - -// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2 -// terminal. This is also always false on this environment. -func IsCygwinTerminal(fd uintptr) bool { - return false -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_bsd.go b/vendor/github.com/mattn/go-isatty/isatty_bsd.go deleted file mode 100644 index 42f2514d1..000000000 --- a/vendor/github.com/mattn/go-isatty/isatty_bsd.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build darwin freebsd openbsd netbsd dragonfly -// +build !appengine - -package isatty - -import ( - "syscall" - "unsafe" -) - -const ioctlReadTermios = syscall.TIOCGETA - -// IsTerminal return true if the file descriptor is terminal. -func IsTerminal(fd uintptr) bool { - var termios syscall.Termios - _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) - return err == 0 -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_linux.go b/vendor/github.com/mattn/go-isatty/isatty_linux.go deleted file mode 100644 index 7384cf991..000000000 --- a/vendor/github.com/mattn/go-isatty/isatty_linux.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build linux -// +build !appengine,!ppc64,!ppc64le - -package isatty - -import ( - "syscall" - "unsafe" -) - -const ioctlReadTermios = syscall.TCGETS - -// IsTerminal return true if the file descriptor is terminal. -func IsTerminal(fd uintptr) bool { - var termios syscall.Termios - _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) - return err == 0 -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_linux_ppc64x.go b/vendor/github.com/mattn/go-isatty/isatty_linux_ppc64x.go deleted file mode 100644 index 44e5d2130..000000000 --- a/vendor/github.com/mattn/go-isatty/isatty_linux_ppc64x.go +++ /dev/null @@ -1,19 +0,0 @@ -// +build linux -// +build ppc64 ppc64le - -package isatty - -import ( - "unsafe" - - syscall "golang.org/x/sys/unix" -) - -const ioctlReadTermios = syscall.TCGETS - -// IsTerminal return true if the file descriptor is terminal. -func IsTerminal(fd uintptr) bool { - var termios syscall.Termios - _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) - return err == 0 -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_others.go b/vendor/github.com/mattn/go-isatty/isatty_others.go deleted file mode 100644 index ff4de3d9a..000000000 --- a/vendor/github.com/mattn/go-isatty/isatty_others.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build !windows -// +build !appengine - -package isatty - -// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2 -// terminal. This is also always false on this environment. -func IsCygwinTerminal(fd uintptr) bool { - return false -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_solaris.go b/vendor/github.com/mattn/go-isatty/isatty_solaris.go deleted file mode 100644 index 1f0c6bf53..000000000 --- a/vendor/github.com/mattn/go-isatty/isatty_solaris.go +++ /dev/null @@ -1,16 +0,0 @@ -// +build solaris -// +build !appengine - -package isatty - -import ( - "golang.org/x/sys/unix" -) - -// IsTerminal returns true if the given file descriptor is a terminal. -// see: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libbc/libc/gen/common/isatty.c -func IsTerminal(fd uintptr) bool { - var termio unix.Termio - err := unix.IoctlSetTermio(int(fd), unix.TCGETA, &termio) - return err == nil -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_windows.go b/vendor/github.com/mattn/go-isatty/isatty_windows.go deleted file mode 100644 index af51cbcaa..000000000 --- a/vendor/github.com/mattn/go-isatty/isatty_windows.go +++ /dev/null @@ -1,94 +0,0 @@ -// +build windows -// +build !appengine - -package isatty - -import ( - "strings" - "syscall" - "unicode/utf16" - "unsafe" -) - -const ( - fileNameInfo uintptr = 2 - fileTypePipe = 3 -) - -var ( - kernel32 = syscall.NewLazyDLL("kernel32.dll") - procGetConsoleMode = kernel32.NewProc("GetConsoleMode") - procGetFileInformationByHandleEx = kernel32.NewProc("GetFileInformationByHandleEx") - procGetFileType = kernel32.NewProc("GetFileType") -) - -func init() { - // Check if GetFileInformationByHandleEx is available. - if procGetFileInformationByHandleEx.Find() != nil { - procGetFileInformationByHandleEx = nil - } -} - -// IsTerminal return true if the file descriptor is terminal. -func IsTerminal(fd uintptr) bool { - var st uint32 - r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, fd, uintptr(unsafe.Pointer(&st)), 0) - return r != 0 && e == 0 -} - -// Check pipe name is used for cygwin/msys2 pty. -// Cygwin/MSYS2 PTY has a name like: -// \{cygwin,msys}-XXXXXXXXXXXXXXXX-ptyN-{from,to}-master -func isCygwinPipeName(name string) bool { - token := strings.Split(name, "-") - if len(token) < 5 { - return false - } - - if token[0] != `\msys` && token[0] != `\cygwin` { - return false - } - - if token[1] == "" { - return false - } - - if !strings.HasPrefix(token[2], "pty") { - return false - } - - if token[3] != `from` && token[3] != `to` { - return false - } - - if token[4] != "master" { - return false - } - - return true -} - -// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2 -// terminal. -func IsCygwinTerminal(fd uintptr) bool { - if procGetFileInformationByHandleEx == nil { - return false - } - - // Cygwin/msys's pty is a pipe. - ft, _, e := syscall.Syscall(procGetFileType.Addr(), 1, fd, 0, 0) - if ft != fileTypePipe || e != 0 { - return false - } - - var buf [2 + syscall.MAX_PATH]uint16 - r, _, e := syscall.Syscall6(procGetFileInformationByHandleEx.Addr(), - 4, fd, fileNameInfo, uintptr(unsafe.Pointer(&buf)), - uintptr(len(buf)*2), 0, 0) - if r == 0 || e != 0 { - return false - } - - l := *(*uint32)(unsafe.Pointer(&buf)) - return isCygwinPipeName(string(utf16.Decode(buf[2 : 2+l/2]))) -} diff --git a/vendor/github.com/spf13/cobra/LICENSE.txt b/vendor/github.com/spf13/cobra/LICENSE.txt deleted file mode 100644 index 298f0e266..000000000 --- a/vendor/github.com/spf13/cobra/LICENSE.txt +++ /dev/null @@ -1,174 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. diff --git a/vendor/github.com/spf13/cobra/args.go b/vendor/github.com/spf13/cobra/args.go deleted file mode 100644 index a5d8a9273..000000000 --- a/vendor/github.com/spf13/cobra/args.go +++ /dev/null @@ -1,89 +0,0 @@ -package cobra - -import ( - "fmt" -) - -type PositionalArgs func(cmd *Command, args []string) error - -// Legacy arg validation has the following behaviour: -// - root commands with no subcommands can take arbitrary arguments -// - root commands with subcommands will do subcommand validity checking -// - subcommands will always accept arbitrary arguments -func legacyArgs(cmd *Command, args []string) error { - // no subcommand, always take args - if !cmd.HasSubCommands() { - return nil - } - - // root command with subcommands, do subcommand checking. - if !cmd.HasParent() && len(args) > 0 { - return fmt.Errorf("unknown command %q for %q%s", args[0], cmd.CommandPath(), cmd.findSuggestions(args[0])) - } - return nil -} - -// NoArgs returns an error if any args are included. -func NoArgs(cmd *Command, args []string) error { - if len(args) > 0 { - return fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath()) - } - return nil -} - -// OnlyValidArgs returns an error if any args are not in the list of ValidArgs. -func OnlyValidArgs(cmd *Command, args []string) error { - if len(cmd.ValidArgs) > 0 { - for _, v := range args { - if !stringInSlice(v, cmd.ValidArgs) { - return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0])) - } - } - } - return nil -} - -// ArbitraryArgs never returns an error. -func ArbitraryArgs(cmd *Command, args []string) error { - return nil -} - -// MinimumNArgs returns an error if there is not at least N args. -func MinimumNArgs(n int) PositionalArgs { - return func(cmd *Command, args []string) error { - if len(args) < n { - return fmt.Errorf("requires at least %d arg(s), only received %d", n, len(args)) - } - return nil - } -} - -// MaximumNArgs returns an error if there are more than N args. -func MaximumNArgs(n int) PositionalArgs { - return func(cmd *Command, args []string) error { - if len(args) > n { - return fmt.Errorf("accepts at most %d arg(s), received %d", n, len(args)) - } - return nil - } -} - -// ExactArgs returns an error if there are not exactly n args. -func ExactArgs(n int) PositionalArgs { - return func(cmd *Command, args []string) error { - if len(args) != n { - return fmt.Errorf("accepts %d arg(s), received %d", n, len(args)) - } - return nil - } -} - -// RangeArgs returns an error if the number of args is not within the expected range. -func RangeArgs(min int, max int) PositionalArgs { - return func(cmd *Command, args []string) error { - if len(args) < min || len(args) > max { - return fmt.Errorf("accepts between %d and %d arg(s), received %d", min, max, len(args)) - } - return nil - } -} diff --git a/vendor/github.com/spf13/cobra/bash_completions.go b/vendor/github.com/spf13/cobra/bash_completions.go deleted file mode 100644 index 8fa8f486f..000000000 --- a/vendor/github.com/spf13/cobra/bash_completions.go +++ /dev/null @@ -1,584 +0,0 @@ -package cobra - -import ( - "bytes" - "fmt" - "io" - "os" - "sort" - "strings" - - "github.com/spf13/pflag" -) - -// Annotations for Bash completion. -const ( - BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extensions" - BashCompCustom = "cobra_annotation_bash_completion_custom" - BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag" - BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir" -) - -func writePreamble(buf *bytes.Buffer, name string) { - buf.WriteString(fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name)) - buf.WriteString(fmt.Sprintf(` -__%[1]s_debug() -{ - if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then - echo "$*" >> "${BASH_COMP_DEBUG_FILE}" - fi -} - -# Homebrew on Macs have version 1.3 of bash-completion which doesn't include -# _init_completion. This is a very minimal version of that function. -__%[1]s_init_completion() -{ - COMPREPLY=() - _get_comp_words_by_ref "$@" cur prev words cword -} - -__%[1]s_index_of_word() -{ - local w word=$1 - shift - index=0 - for w in "$@"; do - [[ $w = "$word" ]] && return - index=$((index+1)) - done - index=-1 -} - -__%[1]s_contains_word() -{ - local w word=$1; shift - for w in "$@"; do - [[ $w = "$word" ]] && return - done - return 1 -} - -__%[1]s_handle_reply() -{ - __%[1]s_debug "${FUNCNAME[0]}" - case $cur in - -*) - if [[ $(type -t compopt) = "builtin" ]]; then - compopt -o nospace - fi - local allflags - if [ ${#must_have_one_flag[@]} -ne 0 ]; then - allflags=("${must_have_one_flag[@]}") - else - allflags=("${flags[*]} ${two_word_flags[*]}") - fi - COMPREPLY=( $(compgen -W "${allflags[*]}" -- "$cur") ) - if [[ $(type -t compopt) = "builtin" ]]; then - [[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace - fi - - # complete after --flag=abc - if [[ $cur == *=* ]]; then - if [[ $(type -t compopt) = "builtin" ]]; then - compopt +o nospace - fi - - local index flag - flag="${cur%%=*}" - __%[1]s_index_of_word "${flag}" "${flags_with_completion[@]}" - COMPREPLY=() - if [[ ${index} -ge 0 ]]; then - PREFIX="" - cur="${cur#*=}" - ${flags_completion[${index}]} - if [ -n "${ZSH_VERSION}" ]; then - # zsh completion needs --flag= prefix - eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )" - fi - fi - fi - return 0; - ;; - esac - - # check if we are handling a flag with special work handling - local index - __%[1]s_index_of_word "${prev}" "${flags_with_completion[@]}" - if [[ ${index} -ge 0 ]]; then - ${flags_completion[${index}]} - return - fi - - # we are parsing a flag and don't have a special handler, no completion - if [[ ${cur} != "${words[cword]}" ]]; then - return - fi - - local completions - completions=("${commands[@]}") - if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then - completions=("${must_have_one_noun[@]}") - fi - if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then - completions+=("${must_have_one_flag[@]}") - fi - COMPREPLY=( $(compgen -W "${completions[*]}" -- "$cur") ) - - if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then - COMPREPLY=( $(compgen -W "${noun_aliases[*]}" -- "$cur") ) - fi - - if [[ ${#COMPREPLY[@]} -eq 0 ]]; then - declare -F __custom_func >/dev/null && __custom_func - fi - - # available in bash-completion >= 2, not always present on macOS - if declare -F __ltrim_colon_completions >/dev/null; then - __ltrim_colon_completions "$cur" - fi - - # If there is only 1 completion and it is a flag with an = it will be completed - # but we don't want a space after the = - if [[ "${#COMPREPLY[@]}" -eq "1" ]] && [[ $(type -t compopt) = "builtin" ]] && [[ "${COMPREPLY[0]}" == --*= ]]; then - compopt -o nospace - fi -} - -# The arguments should be in the form "ext1|ext2|extn" -__%[1]s_handle_filename_extension_flag() -{ - local ext="$1" - _filedir "@(${ext})" -} - -__%[1]s_handle_subdirs_in_dir_flag() -{ - local dir="$1" - pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 -} - -__%[1]s_handle_flag() -{ - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - - # if a command required a flag, and we found it, unset must_have_one_flag() - local flagname=${words[c]} - local flagvalue - # if the word contained an = - if [[ ${words[c]} == *"="* ]]; then - flagvalue=${flagname#*=} # take in as flagvalue after the = - flagname=${flagname%%=*} # strip everything after the = - flagname="${flagname}=" # but put the = back - fi - __%[1]s_debug "${FUNCNAME[0]}: looking for ${flagname}" - if __%[1]s_contains_word "${flagname}" "${must_have_one_flag[@]}"; then - must_have_one_flag=() - fi - - # if you set a flag which only applies to this command, don't show subcommands - if __%[1]s_contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then - commands=() - fi - - # keep flag value with flagname as flaghash - # flaghash variable is an associative array which is only supported in bash > 3. - if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then - if [ -n "${flagvalue}" ] ; then - flaghash[${flagname}]=${flagvalue} - elif [ -n "${words[ $((c+1)) ]}" ] ; then - flaghash[${flagname}]=${words[ $((c+1)) ]} - else - flaghash[${flagname}]="true" # pad "true" for bool flag - fi - fi - - # skip the argument to a two word flag - if __%[1]s_contains_word "${words[c]}" "${two_word_flags[@]}"; then - c=$((c+1)) - # if we are looking for a flags value, don't show commands - if [[ $c -eq $cword ]]; then - commands=() - fi - fi - - c=$((c+1)) - -} - -__%[1]s_handle_noun() -{ - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - - if __%[1]s_contains_word "${words[c]}" "${must_have_one_noun[@]}"; then - must_have_one_noun=() - elif __%[1]s_contains_word "${words[c]}" "${noun_aliases[@]}"; then - must_have_one_noun=() - fi - - nouns+=("${words[c]}") - c=$((c+1)) -} - -__%[1]s_handle_command() -{ - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - - local next_command - if [[ -n ${last_command} ]]; then - next_command="_${last_command}_${words[c]//:/__}" - else - if [[ $c -eq 0 ]]; then - next_command="_%[1]s_root_command" - else - next_command="_${words[c]//:/__}" - fi - fi - c=$((c+1)) - __%[1]s_debug "${FUNCNAME[0]}: looking for ${next_command}" - declare -F "$next_command" >/dev/null && $next_command -} - -__%[1]s_handle_word() -{ - if [[ $c -ge $cword ]]; then - __%[1]s_handle_reply - return - fi - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - if [[ "${words[c]}" == -* ]]; then - __%[1]s_handle_flag - elif __%[1]s_contains_word "${words[c]}" "${commands[@]}"; then - __%[1]s_handle_command - elif [[ $c -eq 0 ]]; then - __%[1]s_handle_command - elif __%[1]s_contains_word "${words[c]}" "${command_aliases[@]}"; then - # aliashash variable is an associative array which is only supported in bash > 3. - if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then - words[c]=${aliashash[${words[c]}]} - __%[1]s_handle_command - else - __%[1]s_handle_noun - fi - else - __%[1]s_handle_noun - fi - __%[1]s_handle_word -} - -`, name)) -} - -func writePostscript(buf *bytes.Buffer, name string) { - name = strings.Replace(name, ":", "__", -1) - buf.WriteString(fmt.Sprintf("__start_%s()\n", name)) - buf.WriteString(fmt.Sprintf(`{ - local cur prev words cword - declare -A flaghash 2>/dev/null || : - declare -A aliashash 2>/dev/null || : - if declare -F _init_completion >/dev/null 2>&1; then - _init_completion -s || return - else - __%[1]s_init_completion -n "=" || return - fi - - local c=0 - local flags=() - local two_word_flags=() - local local_nonpersistent_flags=() - local flags_with_completion=() - local flags_completion=() - local commands=("%[1]s") - local must_have_one_flag=() - local must_have_one_noun=() - local last_command - local nouns=() - - __%[1]s_handle_word -} - -`, name)) - buf.WriteString(fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then - complete -o default -F __start_%s %s -else - complete -o default -o nospace -F __start_%s %s -fi - -`, name, name, name, name)) - buf.WriteString("# ex: ts=4 sw=4 et filetype=sh\n") -} - -func writeCommands(buf *bytes.Buffer, cmd *Command) { - buf.WriteString(" commands=()\n") - for _, c := range cmd.Commands() { - if !c.IsAvailableCommand() || c == cmd.helpCommand { - continue - } - buf.WriteString(fmt.Sprintf(" commands+=(%q)\n", c.Name())) - writeCmdAliases(buf, c) - } - buf.WriteString("\n") -} - -func writeFlagHandler(buf *bytes.Buffer, name string, annotations map[string][]string, cmd *Command) { - for key, value := range annotations { - switch key { - case BashCompFilenameExt: - buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) - - var ext string - if len(value) > 0 { - ext = fmt.Sprintf("__%s_handle_filename_extension_flag ", cmd.Root().Name()) + strings.Join(value, "|") - } else { - ext = "_filedir" - } - buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext)) - case BashCompCustom: - buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) - if len(value) > 0 { - handlers := strings.Join(value, "; ") - buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", handlers)) - } else { - buf.WriteString(" flags_completion+=(:)\n") - } - case BashCompSubdirsInDir: - buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) - - var ext string - if len(value) == 1 { - ext = fmt.Sprintf("__%s_handle_subdirs_in_dir_flag ", cmd.Root().Name()) + value[0] - } else { - ext = "_filedir -d" - } - buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext)) - } - } -} - -func writeShortFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) { - name := flag.Shorthand - format := " " - if len(flag.NoOptDefVal) == 0 { - format += "two_word_" - } - format += "flags+=(\"-%s\")\n" - buf.WriteString(fmt.Sprintf(format, name)) - writeFlagHandler(buf, "-"+name, flag.Annotations, cmd) -} - -func writeFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) { - name := flag.Name - format := " flags+=(\"--%s" - if len(flag.NoOptDefVal) == 0 { - format += "=" - } - format += "\")\n" - buf.WriteString(fmt.Sprintf(format, name)) - writeFlagHandler(buf, "--"+name, flag.Annotations, cmd) -} - -func writeLocalNonPersistentFlag(buf *bytes.Buffer, flag *pflag.Flag) { - name := flag.Name - format := " local_nonpersistent_flags+=(\"--%s" - if len(flag.NoOptDefVal) == 0 { - format += "=" - } - format += "\")\n" - buf.WriteString(fmt.Sprintf(format, name)) -} - -func writeFlags(buf *bytes.Buffer, cmd *Command) { - buf.WriteString(` flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - -`) - localNonPersistentFlags := cmd.LocalNonPersistentFlags() - cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { - if nonCompletableFlag(flag) { - return - } - writeFlag(buf, flag, cmd) - if len(flag.Shorthand) > 0 { - writeShortFlag(buf, flag, cmd) - } - if localNonPersistentFlags.Lookup(flag.Name) != nil { - writeLocalNonPersistentFlag(buf, flag) - } - }) - cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { - if nonCompletableFlag(flag) { - return - } - writeFlag(buf, flag, cmd) - if len(flag.Shorthand) > 0 { - writeShortFlag(buf, flag, cmd) - } - }) - - buf.WriteString("\n") -} - -func writeRequiredFlag(buf *bytes.Buffer, cmd *Command) { - buf.WriteString(" must_have_one_flag=()\n") - flags := cmd.NonInheritedFlags() - flags.VisitAll(func(flag *pflag.Flag) { - if nonCompletableFlag(flag) { - return - } - for key := range flag.Annotations { - switch key { - case BashCompOneRequiredFlag: - format := " must_have_one_flag+=(\"--%s" - if flag.Value.Type() != "bool" { - format += "=" - } - format += "\")\n" - buf.WriteString(fmt.Sprintf(format, flag.Name)) - - if len(flag.Shorthand) > 0 { - buf.WriteString(fmt.Sprintf(" must_have_one_flag+=(\"-%s\")\n", flag.Shorthand)) - } - } - } - }) -} - -func writeRequiredNouns(buf *bytes.Buffer, cmd *Command) { - buf.WriteString(" must_have_one_noun=()\n") - sort.Sort(sort.StringSlice(cmd.ValidArgs)) - for _, value := range cmd.ValidArgs { - buf.WriteString(fmt.Sprintf(" must_have_one_noun+=(%q)\n", value)) - } -} - -func writeCmdAliases(buf *bytes.Buffer, cmd *Command) { - if len(cmd.Aliases) == 0 { - return - } - - sort.Sort(sort.StringSlice(cmd.Aliases)) - - buf.WriteString(fmt.Sprint(` if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then`, "\n")) - for _, value := range cmd.Aliases { - buf.WriteString(fmt.Sprintf(" command_aliases+=(%q)\n", value)) - buf.WriteString(fmt.Sprintf(" aliashash[%q]=%q\n", value, cmd.Name())) - } - buf.WriteString(` fi`) - buf.WriteString("\n") -} -func writeArgAliases(buf *bytes.Buffer, cmd *Command) { - buf.WriteString(" noun_aliases=()\n") - sort.Sort(sort.StringSlice(cmd.ArgAliases)) - for _, value := range cmd.ArgAliases { - buf.WriteString(fmt.Sprintf(" noun_aliases+=(%q)\n", value)) - } -} - -func gen(buf *bytes.Buffer, cmd *Command) { - for _, c := range cmd.Commands() { - if !c.IsAvailableCommand() || c == cmd.helpCommand { - continue - } - gen(buf, c) - } - commandName := cmd.CommandPath() - commandName = strings.Replace(commandName, " ", "_", -1) - commandName = strings.Replace(commandName, ":", "__", -1) - - if cmd.Root() == cmd { - buf.WriteString(fmt.Sprintf("_%s_root_command()\n{\n", commandName)) - } else { - buf.WriteString(fmt.Sprintf("_%s()\n{\n", commandName)) - } - - buf.WriteString(fmt.Sprintf(" last_command=%q\n", commandName)) - buf.WriteString("\n") - buf.WriteString(" command_aliases=()\n") - buf.WriteString("\n") - - writeCommands(buf, cmd) - writeFlags(buf, cmd) - writeRequiredFlag(buf, cmd) - writeRequiredNouns(buf, cmd) - writeArgAliases(buf, cmd) - buf.WriteString("}\n\n") -} - -// GenBashCompletion generates bash completion file and writes to the passed writer. -func (c *Command) GenBashCompletion(w io.Writer) error { - buf := new(bytes.Buffer) - writePreamble(buf, c.Name()) - if len(c.BashCompletionFunction) > 0 { - buf.WriteString(c.BashCompletionFunction + "\n") - } - gen(buf, c) - writePostscript(buf, c.Name()) - - _, err := buf.WriteTo(w) - return err -} - -func nonCompletableFlag(flag *pflag.Flag) bool { - return flag.Hidden || len(flag.Deprecated) > 0 -} - -// GenBashCompletionFile generates bash completion file. -func (c *Command) GenBashCompletionFile(filename string) error { - outFile, err := os.Create(filename) - if err != nil { - return err - } - defer outFile.Close() - - return c.GenBashCompletion(outFile) -} - -// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag if it exists, -// and causes your command to report an error if invoked without the flag. -func (c *Command) MarkFlagRequired(name string) error { - return MarkFlagRequired(c.Flags(), name) -} - -// MarkPersistentFlagRequired adds the BashCompOneRequiredFlag annotation to the named persistent flag if it exists, -// and causes your command to report an error if invoked without the flag. -func (c *Command) MarkPersistentFlagRequired(name string) error { - return MarkFlagRequired(c.PersistentFlags(), name) -} - -// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag if it exists, -// and causes your command to report an error if invoked without the flag. -func MarkFlagRequired(flags *pflag.FlagSet, name string) error { - return flags.SetAnnotation(name, BashCompOneRequiredFlag, []string{"true"}) -} - -// MarkFlagFilename adds the BashCompFilenameExt annotation to the named flag, if it exists. -// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided. -func (c *Command) MarkFlagFilename(name string, extensions ...string) error { - return MarkFlagFilename(c.Flags(), name, extensions...) -} - -// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists. -// Generated bash autocompletion will call the bash function f for the flag. -func (c *Command) MarkFlagCustom(name string, f string) error { - return MarkFlagCustom(c.Flags(), name, f) -} - -// MarkPersistentFlagFilename adds the BashCompFilenameExt annotation to the named persistent flag, if it exists. -// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided. -func (c *Command) MarkPersistentFlagFilename(name string, extensions ...string) error { - return MarkFlagFilename(c.PersistentFlags(), name, extensions...) -} - -// MarkFlagFilename adds the BashCompFilenameExt annotation to the named flag in the flag set, if it exists. -// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided. -func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error { - return flags.SetAnnotation(name, BashCompFilenameExt, extensions) -} - -// MarkFlagCustom adds the BashCompCustom annotation to the named flag in the flag set, if it exists. -// Generated bash autocompletion will call the bash function f for the flag. -func MarkFlagCustom(flags *pflag.FlagSet, name string, f string) error { - return flags.SetAnnotation(name, BashCompCustom, []string{f}) -} diff --git a/vendor/github.com/spf13/cobra/cobra.go b/vendor/github.com/spf13/cobra/cobra.go deleted file mode 100644 index 7010fd15b..000000000 --- a/vendor/github.com/spf13/cobra/cobra.go +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright © 2013 Steve Francia . -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Commands similar to git, go tools and other modern CLI tools -// inspired by go, go-Commander, gh and subcommand - -package cobra - -import ( - "fmt" - "io" - "reflect" - "strconv" - "strings" - "text/template" - "unicode" -) - -var templateFuncs = template.FuncMap{ - "trim": strings.TrimSpace, - "trimRightSpace": trimRightSpace, - "trimTrailingWhitespaces": trimRightSpace, - "appendIfNotPresent": appendIfNotPresent, - "rpad": rpad, - "gt": Gt, - "eq": Eq, -} - -var initializers []func() - -// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing -// to automatically enable in CLI tools. -// Set this to true to enable it. -var EnablePrefixMatching = false - -// EnableCommandSorting controls sorting of the slice of commands, which is turned on by default. -// To disable sorting, set it to false. -var EnableCommandSorting = true - -// MousetrapHelpText enables an information splash screen on Windows -// if the CLI is started from explorer.exe. -// To disable the mousetrap, just set this variable to blank string (""). -// Works only on Microsoft Windows. -var MousetrapHelpText string = `This is a command line tool. - -You need to open cmd.exe and run it from there. -` - -// AddTemplateFunc adds a template function that's available to Usage and Help -// template generation. -func AddTemplateFunc(name string, tmplFunc interface{}) { - templateFuncs[name] = tmplFunc -} - -// AddTemplateFuncs adds multiple template functions that are available to Usage and -// Help template generation. -func AddTemplateFuncs(tmplFuncs template.FuncMap) { - for k, v := range tmplFuncs { - templateFuncs[k] = v - } -} - -// OnInitialize sets the passed functions to be run when each command's -// Execute method is called. -func OnInitialize(y ...func()) { - initializers = append(initializers, y...) -} - -// FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra. - -// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans, -// Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as -// ints and then compared. -func Gt(a interface{}, b interface{}) bool { - var left, right int64 - av := reflect.ValueOf(a) - - switch av.Kind() { - case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: - left = int64(av.Len()) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - left = av.Int() - case reflect.String: - left, _ = strconv.ParseInt(av.String(), 10, 64) - } - - bv := reflect.ValueOf(b) - - switch bv.Kind() { - case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: - right = int64(bv.Len()) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - right = bv.Int() - case reflect.String: - right, _ = strconv.ParseInt(bv.String(), 10, 64) - } - - return left > right -} - -// FIXME Eq is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra. - -// Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic. -func Eq(a interface{}, b interface{}) bool { - av := reflect.ValueOf(a) - bv := reflect.ValueOf(b) - - switch av.Kind() { - case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: - panic("Eq called on unsupported type") - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return av.Int() == bv.Int() - case reflect.String: - return av.String() == bv.String() - } - return false -} - -func trimRightSpace(s string) string { - return strings.TrimRightFunc(s, unicode.IsSpace) -} - -// FIXME appendIfNotPresent is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra. - -// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s. -func appendIfNotPresent(s, stringToAppend string) string { - if strings.Contains(s, stringToAppend) { - return s - } - return s + " " + stringToAppend -} - -// rpad adds padding to the right of a string. -func rpad(s string, padding int) string { - template := fmt.Sprintf("%%-%ds", padding) - return fmt.Sprintf(template, s) -} - -// tmpl executes the given template text on data, writing the result to w. -func tmpl(w io.Writer, text string, data interface{}) error { - t := template.New("top") - t.Funcs(templateFuncs) - template.Must(t.Parse(text)) - return t.Execute(w, data) -} - -// ld compares two strings and returns the levenshtein distance between them. -func ld(s, t string, ignoreCase bool) int { - if ignoreCase { - s = strings.ToLower(s) - t = strings.ToLower(t) - } - d := make([][]int, len(s)+1) - for i := range d { - d[i] = make([]int, len(t)+1) - } - for i := range d { - d[i][0] = i - } - for j := range d[0] { - d[0][j] = j - } - for j := 1; j <= len(t); j++ { - for i := 1; i <= len(s); i++ { - if s[i-1] == t[j-1] { - d[i][j] = d[i-1][j-1] - } else { - min := d[i-1][j] - if d[i][j-1] < min { - min = d[i][j-1] - } - if d[i-1][j-1] < min { - min = d[i-1][j-1] - } - d[i][j] = min + 1 - } - } - - } - return d[len(s)][len(t)] -} - -func stringInSlice(a string, list []string) bool { - for _, b := range list { - if b == a { - return true - } - } - return false -} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/testdata/LICENSE.golden b/vendor/github.com/spf13/cobra/cobra/cmd/testdata/LICENSE.golden deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/testdata/LICENSE.golden +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go deleted file mode 100644 index 34d1bf367..000000000 --- a/vendor/github.com/spf13/cobra/command.go +++ /dev/null @@ -1,1517 +0,0 @@ -// Copyright © 2013 Steve Francia . -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces. -// In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code. -package cobra - -import ( - "bytes" - "fmt" - "io" - "os" - "path/filepath" - "sort" - "strings" - - flag "github.com/spf13/pflag" -) - -// FParseErrWhitelist configures Flag parse errors to be ignored -type FParseErrWhitelist flag.ParseErrorsWhitelist - -// Command is just that, a command for your application. -// E.g. 'go run ...' - 'run' is the command. Cobra requires -// you to define the usage and description as part of your command -// definition to ensure usability. -type Command struct { - // Use is the one-line usage message. - Use string - - // Aliases is an array of aliases that can be used instead of the first word in Use. - Aliases []string - - // SuggestFor is an array of command names for which this command will be suggested - - // similar to aliases but only suggests. - SuggestFor []string - - // Short is the short description shown in the 'help' output. - Short string - - // Long is the long message shown in the 'help ' output. - Long string - - // Example is examples of how to use the command. - Example string - - // ValidArgs is list of all valid non-flag arguments that are accepted in bash completions - ValidArgs []string - - // Expected arguments - Args PositionalArgs - - // ArgAliases is List of aliases for ValidArgs. - // These are not suggested to the user in the bash completion, - // but accepted if entered manually. - ArgAliases []string - - // BashCompletionFunction is custom functions used by the bash autocompletion generator. - BashCompletionFunction string - - // Deprecated defines, if this command is deprecated and should print this string when used. - Deprecated string - - // Hidden defines, if this command is hidden and should NOT show up in the list of available commands. - Hidden bool - - // Annotations are key/value pairs that can be used by applications to identify or - // group commands. - Annotations map[string]string - - // Version defines the version for this command. If this value is non-empty and the command does not - // define a "version" flag, a "version" boolean flag will be added to the command and, if specified, - // will print content of the "Version" variable. - Version string - - // The *Run functions are executed in the following order: - // * PersistentPreRun() - // * PreRun() - // * Run() - // * PostRun() - // * PersistentPostRun() - // All functions get the same args, the arguments after the command name. - // - // PersistentPreRun: children of this command will inherit and execute. - PersistentPreRun func(cmd *Command, args []string) - // PersistentPreRunE: PersistentPreRun but returns an error. - PersistentPreRunE func(cmd *Command, args []string) error - // PreRun: children of this command will not inherit. - PreRun func(cmd *Command, args []string) - // PreRunE: PreRun but returns an error. - PreRunE func(cmd *Command, args []string) error - // Run: Typically the actual work function. Most commands will only implement this. - Run func(cmd *Command, args []string) - // RunE: Run but returns an error. - RunE func(cmd *Command, args []string) error - // PostRun: run after the Run command. - PostRun func(cmd *Command, args []string) - // PostRunE: PostRun but returns an error. - PostRunE func(cmd *Command, args []string) error - // PersistentPostRun: children of this command will inherit and execute after PostRun. - PersistentPostRun func(cmd *Command, args []string) - // PersistentPostRunE: PersistentPostRun but returns an error. - PersistentPostRunE func(cmd *Command, args []string) error - - // SilenceErrors is an option to quiet errors down stream. - SilenceErrors bool - - // SilenceUsage is an option to silence usage when an error occurs. - SilenceUsage bool - - // DisableFlagParsing disables the flag parsing. - // If this is true all flags will be passed to the command as arguments. - DisableFlagParsing bool - - // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...") - // will be printed by generating docs for this command. - DisableAutoGenTag bool - - // DisableFlagsInUseLine will disable the addition of [flags] to the usage - // line of a command when printing help or generating docs - DisableFlagsInUseLine bool - - // DisableSuggestions disables the suggestions based on Levenshtein distance - // that go along with 'unknown command' messages. - DisableSuggestions bool - // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions. - // Must be > 0. - SuggestionsMinimumDistance int - - // TraverseChildren parses flags on all parents before executing child command. - TraverseChildren bool - - //FParseErrWhitelist flag parse errors to be ignored - FParseErrWhitelist FParseErrWhitelist - - // commands is the list of commands supported by this program. - commands []*Command - // parent is a parent command for this command. - parent *Command - // Max lengths of commands' string lengths for use in padding. - commandsMaxUseLen int - commandsMaxCommandPathLen int - commandsMaxNameLen int - // commandsAreSorted defines, if command slice are sorted or not. - commandsAreSorted bool - // commandCalledAs is the name or alias value used to call this command. - commandCalledAs struct { - name string - called bool - } - - // args is actual args parsed from flags. - args []string - // flagErrorBuf contains all error messages from pflag. - flagErrorBuf *bytes.Buffer - // flags is full set of flags. - flags *flag.FlagSet - // pflags contains persistent flags. - pflags *flag.FlagSet - // lflags contains local flags. - lflags *flag.FlagSet - // iflags contains inherited flags. - iflags *flag.FlagSet - // parentsPflags is all persistent flags of cmd's parents. - parentsPflags *flag.FlagSet - // globNormFunc is the global normalization function - // that we can use on every pflag set and children commands - globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName - - // output is an output writer defined by user. - output io.Writer - // usageFunc is usage func defined by user. - usageFunc func(*Command) error - // usageTemplate is usage template defined by user. - usageTemplate string - // flagErrorFunc is func defined by user and it's called when the parsing of - // flags returns an error. - flagErrorFunc func(*Command, error) error - // helpTemplate is help template defined by user. - helpTemplate string - // helpFunc is help func defined by user. - helpFunc func(*Command, []string) - // helpCommand is command with usage 'help'. If it's not defined by user, - // cobra uses default help command. - helpCommand *Command - // versionTemplate is the version template defined by user. - versionTemplate string -} - -// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden -// particularly useful when testing. -func (c *Command) SetArgs(a []string) { - c.args = a -} - -// SetOutput sets the destination for usage and error messages. -// If output is nil, os.Stderr is used. -func (c *Command) SetOutput(output io.Writer) { - c.output = output -} - -// SetUsageFunc sets usage function. Usage can be defined by application. -func (c *Command) SetUsageFunc(f func(*Command) error) { - c.usageFunc = f -} - -// SetUsageTemplate sets usage template. Can be defined by Application. -func (c *Command) SetUsageTemplate(s string) { - c.usageTemplate = s -} - -// SetFlagErrorFunc sets a function to generate an error when flag parsing -// fails. -func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) { - c.flagErrorFunc = f -} - -// SetHelpFunc sets help function. Can be defined by Application. -func (c *Command) SetHelpFunc(f func(*Command, []string)) { - c.helpFunc = f -} - -// SetHelpCommand sets help command. -func (c *Command) SetHelpCommand(cmd *Command) { - c.helpCommand = cmd -} - -// SetHelpTemplate sets help template to be used. Application can use it to set custom template. -func (c *Command) SetHelpTemplate(s string) { - c.helpTemplate = s -} - -// SetVersionTemplate sets version template to be used. Application can use it to set custom template. -func (c *Command) SetVersionTemplate(s string) { - c.versionTemplate = s -} - -// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands. -// The user should not have a cyclic dependency on commands. -func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) { - c.Flags().SetNormalizeFunc(n) - c.PersistentFlags().SetNormalizeFunc(n) - c.globNormFunc = n - - for _, command := range c.commands { - command.SetGlobalNormalizationFunc(n) - } -} - -// OutOrStdout returns output to stdout. -func (c *Command) OutOrStdout() io.Writer { - return c.getOut(os.Stdout) -} - -// OutOrStderr returns output to stderr -func (c *Command) OutOrStderr() io.Writer { - return c.getOut(os.Stderr) -} - -func (c *Command) getOut(def io.Writer) io.Writer { - if c.output != nil { - return c.output - } - if c.HasParent() { - return c.parent.getOut(def) - } - return def -} - -// UsageFunc returns either the function set by SetUsageFunc for this command -// or a parent, or it returns a default usage function. -func (c *Command) UsageFunc() (f func(*Command) error) { - if c.usageFunc != nil { - return c.usageFunc - } - if c.HasParent() { - return c.Parent().UsageFunc() - } - return func(c *Command) error { - c.mergePersistentFlags() - err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c) - if err != nil { - c.Println(err) - } - return err - } -} - -// Usage puts out the usage for the command. -// Used when a user provides invalid input. -// Can be defined by user by overriding UsageFunc. -func (c *Command) Usage() error { - return c.UsageFunc()(c) -} - -// HelpFunc returns either the function set by SetHelpFunc for this command -// or a parent, or it returns a function with default help behavior. -func (c *Command) HelpFunc() func(*Command, []string) { - if c.helpFunc != nil { - return c.helpFunc - } - if c.HasParent() { - return c.Parent().HelpFunc() - } - return func(c *Command, a []string) { - c.mergePersistentFlags() - err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c) - if err != nil { - c.Println(err) - } - } -} - -// Help puts out the help for the command. -// Used when a user calls help [command]. -// Can be defined by user by overriding HelpFunc. -func (c *Command) Help() error { - c.HelpFunc()(c, []string{}) - return nil -} - -// UsageString return usage string. -func (c *Command) UsageString() string { - tmpOutput := c.output - bb := new(bytes.Buffer) - c.SetOutput(bb) - c.Usage() - c.output = tmpOutput - return bb.String() -} - -// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this -// command or a parent, or it returns a function which returns the original -// error. -func (c *Command) FlagErrorFunc() (f func(*Command, error) error) { - if c.flagErrorFunc != nil { - return c.flagErrorFunc - } - - if c.HasParent() { - return c.parent.FlagErrorFunc() - } - return func(c *Command, err error) error { - return err - } -} - -var minUsagePadding = 25 - -// UsagePadding return padding for the usage. -func (c *Command) UsagePadding() int { - if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen { - return minUsagePadding - } - return c.parent.commandsMaxUseLen -} - -var minCommandPathPadding = 11 - -// CommandPathPadding return padding for the command path. -func (c *Command) CommandPathPadding() int { - if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen { - return minCommandPathPadding - } - return c.parent.commandsMaxCommandPathLen -} - -var minNamePadding = 11 - -// NamePadding returns padding for the name. -func (c *Command) NamePadding() int { - if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen { - return minNamePadding - } - return c.parent.commandsMaxNameLen -} - -// UsageTemplate returns usage template for the command. -func (c *Command) UsageTemplate() string { - if c.usageTemplate != "" { - return c.usageTemplate - } - - if c.HasParent() { - return c.parent.UsageTemplate() - } - return `Usage:{{if .Runnable}} - {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}} - {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}} - -Aliases: - {{.NameAndAliases}}{{end}}{{if .HasExample}} - -Examples: -{{.Example}}{{end}}{{if .HasAvailableSubCommands}} - -Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}} - {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}} - -Flags: -{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}} - -Global Flags: -{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}} - -Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}} - {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}} - -Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}} -` -} - -// HelpTemplate return help template for the command. -func (c *Command) HelpTemplate() string { - if c.helpTemplate != "" { - return c.helpTemplate - } - - if c.HasParent() { - return c.parent.HelpTemplate() - } - return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}} - -{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}` -} - -// VersionTemplate return version template for the command. -func (c *Command) VersionTemplate() string { - if c.versionTemplate != "" { - return c.versionTemplate - } - - if c.HasParent() { - return c.parent.VersionTemplate() - } - return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}} -` -} - -func hasNoOptDefVal(name string, fs *flag.FlagSet) bool { - flag := fs.Lookup(name) - if flag == nil { - return false - } - return flag.NoOptDefVal != "" -} - -func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool { - if len(name) == 0 { - return false - } - - flag := fs.ShorthandLookup(name[:1]) - if flag == nil { - return false - } - return flag.NoOptDefVal != "" -} - -func stripFlags(args []string, c *Command) []string { - if len(args) == 0 { - return args - } - c.mergePersistentFlags() - - commands := []string{} - flags := c.Flags() - -Loop: - for len(args) > 0 { - s := args[0] - args = args[1:] - switch { - case s == "--": - // "--" terminates the flags - break Loop - case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags): - // If '--flag arg' then - // delete arg from args. - fallthrough // (do the same as below) - case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags): - // If '-f arg' then - // delete 'arg' from args or break the loop if len(args) <= 1. - if len(args) <= 1 { - break Loop - } else { - args = args[1:] - continue - } - case s != "" && !strings.HasPrefix(s, "-"): - commands = append(commands, s) - } - } - - return commands -} - -// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like -// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]). -func argsMinusFirstX(args []string, x string) []string { - for i, y := range args { - if x == y { - ret := []string{} - ret = append(ret, args[:i]...) - ret = append(ret, args[i+1:]...) - return ret - } - } - return args -} - -func isFlagArg(arg string) bool { - return ((len(arg) >= 3 && arg[1] == '-') || - (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-')) -} - -// Find the target command given the args and command tree -// Meant to be run on the highest node. Only searches down. -func (c *Command) Find(args []string) (*Command, []string, error) { - var innerfind func(*Command, []string) (*Command, []string) - - innerfind = func(c *Command, innerArgs []string) (*Command, []string) { - argsWOflags := stripFlags(innerArgs, c) - if len(argsWOflags) == 0 { - return c, innerArgs - } - nextSubCmd := argsWOflags[0] - - cmd := c.findNext(nextSubCmd) - if cmd != nil { - return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd)) - } - return c, innerArgs - } - - commandFound, a := innerfind(c, args) - if commandFound.Args == nil { - return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound)) - } - return commandFound, a, nil -} - -func (c *Command) findSuggestions(arg string) string { - if c.DisableSuggestions { - return "" - } - if c.SuggestionsMinimumDistance <= 0 { - c.SuggestionsMinimumDistance = 2 - } - suggestionsString := "" - if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 { - suggestionsString += "\n\nDid you mean this?\n" - for _, s := range suggestions { - suggestionsString += fmt.Sprintf("\t%v\n", s) - } - } - return suggestionsString -} - -func (c *Command) findNext(next string) *Command { - matches := make([]*Command, 0) - for _, cmd := range c.commands { - if cmd.Name() == next || cmd.HasAlias(next) { - cmd.commandCalledAs.name = next - return cmd - } - if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) { - matches = append(matches, cmd) - } - } - - if len(matches) == 1 { - return matches[0] - } - - return nil -} - -// Traverse the command tree to find the command, and parse args for -// each parent. -func (c *Command) Traverse(args []string) (*Command, []string, error) { - flags := []string{} - inFlag := false - - for i, arg := range args { - switch { - // A long flag with a space separated value - case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="): - // TODO: this isn't quite right, we should really check ahead for 'true' or 'false' - inFlag = !hasNoOptDefVal(arg[2:], c.Flags()) - flags = append(flags, arg) - continue - // A short flag with a space separated value - case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()): - inFlag = true - flags = append(flags, arg) - continue - // The value for a flag - case inFlag: - inFlag = false - flags = append(flags, arg) - continue - // A flag without a value, or with an `=` separated value - case isFlagArg(arg): - flags = append(flags, arg) - continue - } - - cmd := c.findNext(arg) - if cmd == nil { - return c, args, nil - } - - if err := c.ParseFlags(flags); err != nil { - return nil, args, err - } - return cmd.Traverse(args[i+1:]) - } - return c, args, nil -} - -// SuggestionsFor provides suggestions for the typedName. -func (c *Command) SuggestionsFor(typedName string) []string { - suggestions := []string{} - for _, cmd := range c.commands { - if cmd.IsAvailableCommand() { - levenshteinDistance := ld(typedName, cmd.Name(), true) - suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance - suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName)) - if suggestByLevenshtein || suggestByPrefix { - suggestions = append(suggestions, cmd.Name()) - } - for _, explicitSuggestion := range cmd.SuggestFor { - if strings.EqualFold(typedName, explicitSuggestion) { - suggestions = append(suggestions, cmd.Name()) - } - } - } - } - return suggestions -} - -// VisitParents visits all parents of the command and invokes fn on each parent. -func (c *Command) VisitParents(fn func(*Command)) { - if c.HasParent() { - fn(c.Parent()) - c.Parent().VisitParents(fn) - } -} - -// Root finds root command. -func (c *Command) Root() *Command { - if c.HasParent() { - return c.Parent().Root() - } - return c -} - -// ArgsLenAtDash will return the length of c.Flags().Args at the moment -// when a -- was found during args parsing. -func (c *Command) ArgsLenAtDash() int { - return c.Flags().ArgsLenAtDash() -} - -func (c *Command) execute(a []string) (err error) { - if c == nil { - return fmt.Errorf("Called Execute() on a nil Command") - } - - if len(c.Deprecated) > 0 { - c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated) - } - - // initialize help and version flag at the last point possible to allow for user - // overriding - c.InitDefaultHelpFlag() - c.InitDefaultVersionFlag() - - err = c.ParseFlags(a) - if err != nil { - return c.FlagErrorFunc()(c, err) - } - - // If help is called, regardless of other flags, return we want help. - // Also say we need help if the command isn't runnable. - helpVal, err := c.Flags().GetBool("help") - if err != nil { - // should be impossible to get here as we always declare a help - // flag in InitDefaultHelpFlag() - c.Println("\"help\" flag declared as non-bool. Please correct your code") - return err - } - - if helpVal { - return flag.ErrHelp - } - - // for back-compat, only add version flag behavior if version is defined - if c.Version != "" { - versionVal, err := c.Flags().GetBool("version") - if err != nil { - c.Println("\"version\" flag declared as non-bool. Please correct your code") - return err - } - if versionVal { - err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c) - if err != nil { - c.Println(err) - } - return err - } - } - - if !c.Runnable() { - return flag.ErrHelp - } - - c.preRun() - - argWoFlags := c.Flags().Args() - if c.DisableFlagParsing { - argWoFlags = a - } - - if err := c.ValidateArgs(argWoFlags); err != nil { - return err - } - - for p := c; p != nil; p = p.Parent() { - if p.PersistentPreRunE != nil { - if err := p.PersistentPreRunE(c, argWoFlags); err != nil { - return err - } - break - } else if p.PersistentPreRun != nil { - p.PersistentPreRun(c, argWoFlags) - break - } - } - if c.PreRunE != nil { - if err := c.PreRunE(c, argWoFlags); err != nil { - return err - } - } else if c.PreRun != nil { - c.PreRun(c, argWoFlags) - } - - if err := c.validateRequiredFlags(); err != nil { - return err - } - if c.RunE != nil { - if err := c.RunE(c, argWoFlags); err != nil { - return err - } - } else { - c.Run(c, argWoFlags) - } - if c.PostRunE != nil { - if err := c.PostRunE(c, argWoFlags); err != nil { - return err - } - } else if c.PostRun != nil { - c.PostRun(c, argWoFlags) - } - for p := c; p != nil; p = p.Parent() { - if p.PersistentPostRunE != nil { - if err := p.PersistentPostRunE(c, argWoFlags); err != nil { - return err - } - break - } else if p.PersistentPostRun != nil { - p.PersistentPostRun(c, argWoFlags) - break - } - } - - return nil -} - -func (c *Command) preRun() { - for _, x := range initializers { - x() - } -} - -// Execute uses the args (os.Args[1:] by default) -// and run through the command tree finding appropriate matches -// for commands and then corresponding flags. -func (c *Command) Execute() error { - _, err := c.ExecuteC() - return err -} - -// ExecuteC executes the command. -func (c *Command) ExecuteC() (cmd *Command, err error) { - // Regardless of what command execute is called on, run on Root only - if c.HasParent() { - return c.Root().ExecuteC() - } - - // windows hook - if preExecHookFn != nil { - preExecHookFn(c) - } - - // initialize help as the last point possible to allow for user - // overriding - c.InitDefaultHelpCmd() - - var args []string - - // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155 - if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" { - args = os.Args[1:] - } else { - args = c.args - } - - var flags []string - if c.TraverseChildren { - cmd, flags, err = c.Traverse(args) - } else { - cmd, flags, err = c.Find(args) - } - if err != nil { - // If found parse to a subcommand and then failed, talk about the subcommand - if cmd != nil { - c = cmd - } - if !c.SilenceErrors { - c.Println("Error:", err.Error()) - c.Printf("Run '%v --help' for usage.\n", c.CommandPath()) - } - return c, err - } - - cmd.commandCalledAs.called = true - if cmd.commandCalledAs.name == "" { - cmd.commandCalledAs.name = cmd.Name() - } - - err = cmd.execute(flags) - if err != nil { - // Always show help if requested, even if SilenceErrors is in - // effect - if err == flag.ErrHelp { - cmd.HelpFunc()(cmd, args) - return cmd, nil - } - - // If root command has SilentErrors flagged, - // all subcommands should respect it - if !cmd.SilenceErrors && !c.SilenceErrors { - c.Println("Error:", err.Error()) - } - - // If root command has SilentUsage flagged, - // all subcommands should respect it - if !cmd.SilenceUsage && !c.SilenceUsage { - c.Println(cmd.UsageString()) - } - } - return cmd, err -} - -func (c *Command) ValidateArgs(args []string) error { - if c.Args == nil { - return nil - } - return c.Args(c, args) -} - -func (c *Command) validateRequiredFlags() error { - flags := c.Flags() - missingFlagNames := []string{} - flags.VisitAll(func(pflag *flag.Flag) { - requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag] - if !found { - return - } - if (requiredAnnotation[0] == "true") && !pflag.Changed { - missingFlagNames = append(missingFlagNames, pflag.Name) - } - }) - - if len(missingFlagNames) > 0 { - return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`)) - } - return nil -} - -// InitDefaultHelpFlag adds default help flag to c. -// It is called automatically by executing the c or by calling help and usage. -// If c already has help flag, it will do nothing. -func (c *Command) InitDefaultHelpFlag() { - c.mergePersistentFlags() - if c.Flags().Lookup("help") == nil { - usage := "help for " - if c.Name() == "" { - usage += "this command" - } else { - usage += c.Name() - } - c.Flags().BoolP("help", "h", false, usage) - } -} - -// InitDefaultVersionFlag adds default version flag to c. -// It is called automatically by executing the c. -// If c already has a version flag, it will do nothing. -// If c.Version is empty, it will do nothing. -func (c *Command) InitDefaultVersionFlag() { - if c.Version == "" { - return - } - - c.mergePersistentFlags() - if c.Flags().Lookup("version") == nil { - usage := "version for " - if c.Name() == "" { - usage += "this command" - } else { - usage += c.Name() - } - c.Flags().Bool("version", false, usage) - } -} - -// InitDefaultHelpCmd adds default help command to c. -// It is called automatically by executing the c or by calling help and usage. -// If c already has help command or c has no subcommands, it will do nothing. -func (c *Command) InitDefaultHelpCmd() { - if !c.HasSubCommands() { - return - } - - if c.helpCommand == nil { - c.helpCommand = &Command{ - Use: "help [command]", - Short: "Help about any command", - Long: `Help provides help for any command in the application. -Simply type ` + c.Name() + ` help [path to command] for full details.`, - - Run: func(c *Command, args []string) { - cmd, _, e := c.Root().Find(args) - if cmd == nil || e != nil { - c.Printf("Unknown help topic %#q\n", args) - c.Root().Usage() - } else { - cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown - cmd.Help() - } - }, - } - } - c.RemoveCommand(c.helpCommand) - c.AddCommand(c.helpCommand) -} - -// ResetCommands delete parent, subcommand and help command from c. -func (c *Command) ResetCommands() { - c.parent = nil - c.commands = nil - c.helpCommand = nil - c.parentsPflags = nil -} - -// Sorts commands by their names. -type commandSorterByName []*Command - -func (c commandSorterByName) Len() int { return len(c) } -func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] } -func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() } - -// Commands returns a sorted slice of child commands. -func (c *Command) Commands() []*Command { - // do not sort commands if it already sorted or sorting was disabled - if EnableCommandSorting && !c.commandsAreSorted { - sort.Sort(commandSorterByName(c.commands)) - c.commandsAreSorted = true - } - return c.commands -} - -// AddCommand adds one or more commands to this parent command. -func (c *Command) AddCommand(cmds ...*Command) { - for i, x := range cmds { - if cmds[i] == c { - panic("Command can't be a child of itself") - } - cmds[i].parent = c - // update max lengths - usageLen := len(x.Use) - if usageLen > c.commandsMaxUseLen { - c.commandsMaxUseLen = usageLen - } - commandPathLen := len(x.CommandPath()) - if commandPathLen > c.commandsMaxCommandPathLen { - c.commandsMaxCommandPathLen = commandPathLen - } - nameLen := len(x.Name()) - if nameLen > c.commandsMaxNameLen { - c.commandsMaxNameLen = nameLen - } - // If global normalization function exists, update all children - if c.globNormFunc != nil { - x.SetGlobalNormalizationFunc(c.globNormFunc) - } - c.commands = append(c.commands, x) - c.commandsAreSorted = false - } -} - -// RemoveCommand removes one or more commands from a parent command. -func (c *Command) RemoveCommand(cmds ...*Command) { - commands := []*Command{} -main: - for _, command := range c.commands { - for _, cmd := range cmds { - if command == cmd { - command.parent = nil - continue main - } - } - commands = append(commands, command) - } - c.commands = commands - // recompute all lengths - c.commandsMaxUseLen = 0 - c.commandsMaxCommandPathLen = 0 - c.commandsMaxNameLen = 0 - for _, command := range c.commands { - usageLen := len(command.Use) - if usageLen > c.commandsMaxUseLen { - c.commandsMaxUseLen = usageLen - } - commandPathLen := len(command.CommandPath()) - if commandPathLen > c.commandsMaxCommandPathLen { - c.commandsMaxCommandPathLen = commandPathLen - } - nameLen := len(command.Name()) - if nameLen > c.commandsMaxNameLen { - c.commandsMaxNameLen = nameLen - } - } -} - -// Print is a convenience method to Print to the defined output, fallback to Stderr if not set. -func (c *Command) Print(i ...interface{}) { - fmt.Fprint(c.OutOrStderr(), i...) -} - -// Println is a convenience method to Println to the defined output, fallback to Stderr if not set. -func (c *Command) Println(i ...interface{}) { - c.Print(fmt.Sprintln(i...)) -} - -// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set. -func (c *Command) Printf(format string, i ...interface{}) { - c.Print(fmt.Sprintf(format, i...)) -} - -// CommandPath returns the full path to this command. -func (c *Command) CommandPath() string { - if c.HasParent() { - return c.Parent().CommandPath() + " " + c.Name() - } - return c.Name() -} - -// UseLine puts out the full usage for a given command (including parents). -func (c *Command) UseLine() string { - var useline string - if c.HasParent() { - useline = c.parent.CommandPath() + " " + c.Use - } else { - useline = c.Use - } - if c.DisableFlagsInUseLine { - return useline - } - if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") { - useline += " [flags]" - } - return useline -} - -// DebugFlags used to determine which flags have been assigned to which commands -// and which persist. -func (c *Command) DebugFlags() { - c.Println("DebugFlags called on", c.Name()) - var debugflags func(*Command) - - debugflags = func(x *Command) { - if x.HasFlags() || x.HasPersistentFlags() { - c.Println(x.Name()) - } - if x.HasFlags() { - x.flags.VisitAll(func(f *flag.Flag) { - if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil { - c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]") - } else { - c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]") - } - }) - } - if x.HasPersistentFlags() { - x.pflags.VisitAll(func(f *flag.Flag) { - if x.HasFlags() { - if x.flags.Lookup(f.Name) == nil { - c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]") - } - } else { - c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]") - } - }) - } - c.Println(x.flagErrorBuf) - if x.HasSubCommands() { - for _, y := range x.commands { - debugflags(y) - } - } - } - - debugflags(c) -} - -// Name returns the command's name: the first word in the use line. -func (c *Command) Name() string { - name := c.Use - i := strings.Index(name, " ") - if i >= 0 { - name = name[:i] - } - return name -} - -// HasAlias determines if a given string is an alias of the command. -func (c *Command) HasAlias(s string) bool { - for _, a := range c.Aliases { - if a == s { - return true - } - } - return false -} - -// CalledAs returns the command name or alias that was used to invoke -// this command or an empty string if the command has not been called. -func (c *Command) CalledAs() string { - if c.commandCalledAs.called { - return c.commandCalledAs.name - } - return "" -} - -// hasNameOrAliasPrefix returns true if the Name or any of aliases start -// with prefix -func (c *Command) hasNameOrAliasPrefix(prefix string) bool { - if strings.HasPrefix(c.Name(), prefix) { - c.commandCalledAs.name = c.Name() - return true - } - for _, alias := range c.Aliases { - if strings.HasPrefix(alias, prefix) { - c.commandCalledAs.name = alias - return true - } - } - return false -} - -// NameAndAliases returns a list of the command name and all aliases -func (c *Command) NameAndAliases() string { - return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ") -} - -// HasExample determines if the command has example. -func (c *Command) HasExample() bool { - return len(c.Example) > 0 -} - -// Runnable determines if the command is itself runnable. -func (c *Command) Runnable() bool { - return c.Run != nil || c.RunE != nil -} - -// HasSubCommands determines if the command has children commands. -func (c *Command) HasSubCommands() bool { - return len(c.commands) > 0 -} - -// IsAvailableCommand determines if a command is available as a non-help command -// (this includes all non deprecated/hidden commands). -func (c *Command) IsAvailableCommand() bool { - if len(c.Deprecated) != 0 || c.Hidden { - return false - } - - if c.HasParent() && c.Parent().helpCommand == c { - return false - } - - if c.Runnable() || c.HasAvailableSubCommands() { - return true - } - - return false -} - -// IsAdditionalHelpTopicCommand determines if a command is an additional -// help topic command; additional help topic command is determined by the -// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that -// are runnable/hidden/deprecated. -// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924. -func (c *Command) IsAdditionalHelpTopicCommand() bool { - // if a command is runnable, deprecated, or hidden it is not a 'help' command - if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden { - return false - } - - // if any non-help sub commands are found, the command is not a 'help' command - for _, sub := range c.commands { - if !sub.IsAdditionalHelpTopicCommand() { - return false - } - } - - // the command either has no sub commands, or no non-help sub commands - return true -} - -// HasHelpSubCommands determines if a command has any available 'help' sub commands -// that need to be shown in the usage/help default template under 'additional help -// topics'. -func (c *Command) HasHelpSubCommands() bool { - // return true on the first found available 'help' sub command - for _, sub := range c.commands { - if sub.IsAdditionalHelpTopicCommand() { - return true - } - } - - // the command either has no sub commands, or no available 'help' sub commands - return false -} - -// HasAvailableSubCommands determines if a command has available sub commands that -// need to be shown in the usage/help default template under 'available commands'. -func (c *Command) HasAvailableSubCommands() bool { - // return true on the first found available (non deprecated/help/hidden) - // sub command - for _, sub := range c.commands { - if sub.IsAvailableCommand() { - return true - } - } - - // the command either has no sub commands, or no available (non deprecated/help/hidden) - // sub commands - return false -} - -// HasParent determines if the command is a child command. -func (c *Command) HasParent() bool { - return c.parent != nil -} - -// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist. -func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName { - return c.globNormFunc -} - -// Flags returns the complete FlagSet that applies -// to this command (local and persistent declared here and by all parents). -func (c *Command) Flags() *flag.FlagSet { - if c.flags == nil { - c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - c.flags.SetOutput(c.flagErrorBuf) - } - - return c.flags -} - -// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands. -func (c *Command) LocalNonPersistentFlags() *flag.FlagSet { - persistentFlags := c.PersistentFlags() - - out := flag.NewFlagSet(c.Name(), flag.ContinueOnError) - c.LocalFlags().VisitAll(func(f *flag.Flag) { - if persistentFlags.Lookup(f.Name) == nil { - out.AddFlag(f) - } - }) - return out -} - -// LocalFlags returns the local FlagSet specifically set in the current command. -func (c *Command) LocalFlags() *flag.FlagSet { - c.mergePersistentFlags() - - if c.lflags == nil { - c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - c.lflags.SetOutput(c.flagErrorBuf) - } - c.lflags.SortFlags = c.Flags().SortFlags - if c.globNormFunc != nil { - c.lflags.SetNormalizeFunc(c.globNormFunc) - } - - addToLocal := func(f *flag.Flag) { - if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil { - c.lflags.AddFlag(f) - } - } - c.Flags().VisitAll(addToLocal) - c.PersistentFlags().VisitAll(addToLocal) - return c.lflags -} - -// InheritedFlags returns all flags which were inherited from parents commands. -func (c *Command) InheritedFlags() *flag.FlagSet { - c.mergePersistentFlags() - - if c.iflags == nil { - c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - c.iflags.SetOutput(c.flagErrorBuf) - } - - local := c.LocalFlags() - if c.globNormFunc != nil { - c.iflags.SetNormalizeFunc(c.globNormFunc) - } - - c.parentsPflags.VisitAll(func(f *flag.Flag) { - if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil { - c.iflags.AddFlag(f) - } - }) - return c.iflags -} - -// NonInheritedFlags returns all flags which were not inherited from parent commands. -func (c *Command) NonInheritedFlags() *flag.FlagSet { - return c.LocalFlags() -} - -// PersistentFlags returns the persistent FlagSet specifically set in the current command. -func (c *Command) PersistentFlags() *flag.FlagSet { - if c.pflags == nil { - c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - c.pflags.SetOutput(c.flagErrorBuf) - } - return c.pflags -} - -// ResetFlags deletes all flags from command. -func (c *Command) ResetFlags() { - c.flagErrorBuf = new(bytes.Buffer) - c.flagErrorBuf.Reset() - c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - c.flags.SetOutput(c.flagErrorBuf) - c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - c.pflags.SetOutput(c.flagErrorBuf) - - c.lflags = nil - c.iflags = nil - c.parentsPflags = nil -} - -// HasFlags checks if the command contains any flags (local plus persistent from the entire structure). -func (c *Command) HasFlags() bool { - return c.Flags().HasFlags() -} - -// HasPersistentFlags checks if the command contains persistent flags. -func (c *Command) HasPersistentFlags() bool { - return c.PersistentFlags().HasFlags() -} - -// HasLocalFlags checks if the command has flags specifically declared locally. -func (c *Command) HasLocalFlags() bool { - return c.LocalFlags().HasFlags() -} - -// HasInheritedFlags checks if the command has flags inherited from its parent command. -func (c *Command) HasInheritedFlags() bool { - return c.InheritedFlags().HasFlags() -} - -// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire -// structure) which are not hidden or deprecated. -func (c *Command) HasAvailableFlags() bool { - return c.Flags().HasAvailableFlags() -} - -// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated. -func (c *Command) HasAvailablePersistentFlags() bool { - return c.PersistentFlags().HasAvailableFlags() -} - -// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden -// or deprecated. -func (c *Command) HasAvailableLocalFlags() bool { - return c.LocalFlags().HasAvailableFlags() -} - -// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are -// not hidden or deprecated. -func (c *Command) HasAvailableInheritedFlags() bool { - return c.InheritedFlags().HasAvailableFlags() -} - -// Flag climbs up the command tree looking for matching flag. -func (c *Command) Flag(name string) (flag *flag.Flag) { - flag = c.Flags().Lookup(name) - - if flag == nil { - flag = c.persistentFlag(name) - } - - return -} - -// Recursively find matching persistent flag. -func (c *Command) persistentFlag(name string) (flag *flag.Flag) { - if c.HasPersistentFlags() { - flag = c.PersistentFlags().Lookup(name) - } - - if flag == nil { - c.updateParentsPflags() - flag = c.parentsPflags.Lookup(name) - } - return -} - -// ParseFlags parses persistent flag tree and local flags. -func (c *Command) ParseFlags(args []string) error { - if c.DisableFlagParsing { - return nil - } - - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - beforeErrorBufLen := c.flagErrorBuf.Len() - c.mergePersistentFlags() - - //do it here after merging all flags and just before parse - c.Flags().ParseErrorsWhitelist = flag.ParseErrorsWhitelist(c.FParseErrWhitelist) - - err := c.Flags().Parse(args) - // Print warnings if they occurred (e.g. deprecated flag messages). - if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil { - c.Print(c.flagErrorBuf.String()) - } - - return err -} - -// Parent returns a commands parent command. -func (c *Command) Parent() *Command { - return c.parent -} - -// mergePersistentFlags merges c.PersistentFlags() to c.Flags() -// and adds missing persistent flags of all parents. -func (c *Command) mergePersistentFlags() { - c.updateParentsPflags() - c.Flags().AddFlagSet(c.PersistentFlags()) - c.Flags().AddFlagSet(c.parentsPflags) -} - -// updateParentsPflags updates c.parentsPflags by adding -// new persistent flags of all parents. -// If c.parentsPflags == nil, it makes new. -func (c *Command) updateParentsPflags() { - if c.parentsPflags == nil { - c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - c.parentsPflags.SetOutput(c.flagErrorBuf) - c.parentsPflags.SortFlags = false - } - - if c.globNormFunc != nil { - c.parentsPflags.SetNormalizeFunc(c.globNormFunc) - } - - c.Root().PersistentFlags().AddFlagSet(flag.CommandLine) - - c.VisitParents(func(parent *Command) { - c.parentsPflags.AddFlagSet(parent.PersistentFlags()) - }) -} diff --git a/vendor/github.com/spf13/cobra/command_notwin.go b/vendor/github.com/spf13/cobra/command_notwin.go deleted file mode 100644 index 6159c1cc1..000000000 --- a/vendor/github.com/spf13/cobra/command_notwin.go +++ /dev/null @@ -1,5 +0,0 @@ -// +build !windows - -package cobra - -var preExecHookFn func(*Command) diff --git a/vendor/github.com/spf13/cobra/command_win.go b/vendor/github.com/spf13/cobra/command_win.go deleted file mode 100644 index edec728e4..000000000 --- a/vendor/github.com/spf13/cobra/command_win.go +++ /dev/null @@ -1,20 +0,0 @@ -// +build windows - -package cobra - -import ( - "os" - "time" - - "github.com/inconshreveable/mousetrap" -) - -var preExecHookFn = preExecHook - -func preExecHook(c *Command) { - if MousetrapHelpText != "" && mousetrap.StartedByExplorer() { - c.Print(MousetrapHelpText) - time.Sleep(5 * time.Second) - os.Exit(1) - } -} diff --git a/vendor/github.com/spf13/cobra/zsh_completions.go b/vendor/github.com/spf13/cobra/zsh_completions.go deleted file mode 100644 index 889c22e27..000000000 --- a/vendor/github.com/spf13/cobra/zsh_completions.go +++ /dev/null @@ -1,126 +0,0 @@ -package cobra - -import ( - "bytes" - "fmt" - "io" - "os" - "strings" -) - -// GenZshCompletionFile generates zsh completion file. -func (c *Command) GenZshCompletionFile(filename string) error { - outFile, err := os.Create(filename) - if err != nil { - return err - } - defer outFile.Close() - - return c.GenZshCompletion(outFile) -} - -// GenZshCompletion generates a zsh completion file and writes to the passed writer. -func (c *Command) GenZshCompletion(w io.Writer) error { - buf := new(bytes.Buffer) - - writeHeader(buf, c) - maxDepth := maxDepth(c) - writeLevelMapping(buf, maxDepth) - writeLevelCases(buf, maxDepth, c) - - _, err := buf.WriteTo(w) - return err -} - -func writeHeader(w io.Writer, cmd *Command) { - fmt.Fprintf(w, "#compdef %s\n\n", cmd.Name()) -} - -func maxDepth(c *Command) int { - if len(c.Commands()) == 0 { - return 0 - } - maxDepthSub := 0 - for _, s := range c.Commands() { - subDepth := maxDepth(s) - if subDepth > maxDepthSub { - maxDepthSub = subDepth - } - } - return 1 + maxDepthSub -} - -func writeLevelMapping(w io.Writer, numLevels int) { - fmt.Fprintln(w, `_arguments \`) - for i := 1; i <= numLevels; i++ { - fmt.Fprintf(w, ` '%d: :->level%d' \`, i, i) - fmt.Fprintln(w) - } - fmt.Fprintf(w, ` '%d: :%s'`, numLevels+1, "_files") - fmt.Fprintln(w) -} - -func writeLevelCases(w io.Writer, maxDepth int, root *Command) { - fmt.Fprintln(w, "case $state in") - defer fmt.Fprintln(w, "esac") - - for i := 1; i <= maxDepth; i++ { - fmt.Fprintf(w, " level%d)\n", i) - writeLevel(w, root, i) - fmt.Fprintln(w, " ;;") - } - fmt.Fprintln(w, " *)") - fmt.Fprintln(w, " _arguments '*: :_files'") - fmt.Fprintln(w, " ;;") -} - -func writeLevel(w io.Writer, root *Command, i int) { - fmt.Fprintf(w, " case $words[%d] in\n", i) - defer fmt.Fprintln(w, " esac") - - commands := filterByLevel(root, i) - byParent := groupByParent(commands) - - for p, c := range byParent { - names := names(c) - fmt.Fprintf(w, " %s)\n", p) - fmt.Fprintf(w, " _arguments '%d: :(%s)'\n", i, strings.Join(names, " ")) - fmt.Fprintln(w, " ;;") - } - fmt.Fprintln(w, " *)") - fmt.Fprintln(w, " _arguments '*: :_files'") - fmt.Fprintln(w, " ;;") - -} - -func filterByLevel(c *Command, l int) []*Command { - cs := make([]*Command, 0) - if l == 0 { - cs = append(cs, c) - return cs - } - for _, s := range c.Commands() { - cs = append(cs, filterByLevel(s, l-1)...) - } - return cs -} - -func groupByParent(commands []*Command) map[string][]*Command { - m := make(map[string][]*Command) - for _, c := range commands { - parent := c.Parent() - if parent == nil { - continue - } - m[parent.Name()] = append(m[parent.Name()], c) - } - return m -} - -func names(commands []*Command) []string { - ns := make([]string, len(commands)) - for i, c := range commands { - ns[i] = c.Name() - } - return ns -} diff --git a/vendor/github.com/spf13/pflag/LICENSE b/vendor/github.com/spf13/pflag/LICENSE deleted file mode 100644 index 63ed1cfea..000000000 --- a/vendor/github.com/spf13/pflag/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright (c) 2012 Alex Ogier. All rights reserved. -Copyright (c) 2012 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/spf13/pflag/bool.go b/vendor/github.com/spf13/pflag/bool.go deleted file mode 100644 index c4c5c0bfd..000000000 --- a/vendor/github.com/spf13/pflag/bool.go +++ /dev/null @@ -1,94 +0,0 @@ -package pflag - -import "strconv" - -// optional interface to indicate boolean flags that can be -// supplied without "=value" text -type boolFlag interface { - Value - IsBoolFlag() bool -} - -// -- bool Value -type boolValue bool - -func newBoolValue(val bool, p *bool) *boolValue { - *p = val - return (*boolValue)(p) -} - -func (b *boolValue) Set(s string) error { - v, err := strconv.ParseBool(s) - *b = boolValue(v) - return err -} - -func (b *boolValue) Type() string { - return "bool" -} - -func (b *boolValue) String() string { return strconv.FormatBool(bool(*b)) } - -func (b *boolValue) IsBoolFlag() bool { return true } - -func boolConv(sval string) (interface{}, error) { - return strconv.ParseBool(sval) -} - -// GetBool return the bool value of a flag with the given name -func (f *FlagSet) GetBool(name string) (bool, error) { - val, err := f.getFlagType(name, "bool", boolConv) - if err != nil { - return false, err - } - return val.(bool), nil -} - -// BoolVar defines a bool flag with specified name, default value, and usage string. -// The argument p points to a bool variable in which to store the value of the flag. -func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) { - f.BoolVarP(p, name, "", value, usage) -} - -// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) { - flag := f.VarPF(newBoolValue(value, p), name, shorthand, usage) - flag.NoOptDefVal = "true" -} - -// BoolVar defines a bool flag with specified name, default value, and usage string. -// The argument p points to a bool variable in which to store the value of the flag. -func BoolVar(p *bool, name string, value bool, usage string) { - BoolVarP(p, name, "", value, usage) -} - -// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash. -func BoolVarP(p *bool, name, shorthand string, value bool, usage string) { - flag := CommandLine.VarPF(newBoolValue(value, p), name, shorthand, usage) - flag.NoOptDefVal = "true" -} - -// Bool defines a bool flag with specified name, default value, and usage string. -// The return value is the address of a bool variable that stores the value of the flag. -func (f *FlagSet) Bool(name string, value bool, usage string) *bool { - return f.BoolP(name, "", value, usage) -} - -// BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool { - p := new(bool) - f.BoolVarP(p, name, shorthand, value, usage) - return p -} - -// Bool defines a bool flag with specified name, default value, and usage string. -// The return value is the address of a bool variable that stores the value of the flag. -func Bool(name string, value bool, usage string) *bool { - return BoolP(name, "", value, usage) -} - -// BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash. -func BoolP(name, shorthand string, value bool, usage string) *bool { - b := CommandLine.BoolP(name, shorthand, value, usage) - return b -} diff --git a/vendor/github.com/spf13/pflag/bool_slice.go b/vendor/github.com/spf13/pflag/bool_slice.go deleted file mode 100644 index 5af02f1a7..000000000 --- a/vendor/github.com/spf13/pflag/bool_slice.go +++ /dev/null @@ -1,147 +0,0 @@ -package pflag - -import ( - "io" - "strconv" - "strings" -) - -// -- boolSlice Value -type boolSliceValue struct { - value *[]bool - changed bool -} - -func newBoolSliceValue(val []bool, p *[]bool) *boolSliceValue { - bsv := new(boolSliceValue) - bsv.value = p - *bsv.value = val - return bsv -} - -// Set converts, and assigns, the comma-separated boolean argument string representation as the []bool value of this flag. -// If Set is called on a flag that already has a []bool assigned, the newly converted values will be appended. -func (s *boolSliceValue) Set(val string) error { - - // remove all quote characters - rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "") - - // read flag arguments with CSV parser - boolStrSlice, err := readAsCSV(rmQuote.Replace(val)) - if err != nil && err != io.EOF { - return err - } - - // parse boolean values into slice - out := make([]bool, 0, len(boolStrSlice)) - for _, boolStr := range boolStrSlice { - b, err := strconv.ParseBool(strings.TrimSpace(boolStr)) - if err != nil { - return err - } - out = append(out, b) - } - - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - - s.changed = true - - return nil -} - -// Type returns a string that uniquely represents this flag's type. -func (s *boolSliceValue) Type() string { - return "boolSlice" -} - -// String defines a "native" format for this boolean slice flag value. -func (s *boolSliceValue) String() string { - - boolStrSlice := make([]string, len(*s.value)) - for i, b := range *s.value { - boolStrSlice[i] = strconv.FormatBool(b) - } - - out, _ := writeAsCSV(boolStrSlice) - - return "[" + out + "]" -} - -func boolSliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Empty string would cause a slice with one (empty) entry - if len(val) == 0 { - return []bool{}, nil - } - ss := strings.Split(val, ",") - out := make([]bool, len(ss)) - for i, t := range ss { - var err error - out[i], err = strconv.ParseBool(t) - if err != nil { - return nil, err - } - } - return out, nil -} - -// GetBoolSlice returns the []bool value of a flag with the given name. -func (f *FlagSet) GetBoolSlice(name string) ([]bool, error) { - val, err := f.getFlagType(name, "boolSlice", boolSliceConv) - if err != nil { - return []bool{}, err - } - return val.([]bool), nil -} - -// BoolSliceVar defines a boolSlice flag with specified name, default value, and usage string. -// The argument p points to a []bool variable in which to store the value of the flag. -func (f *FlagSet) BoolSliceVar(p *[]bool, name string, value []bool, usage string) { - f.VarP(newBoolSliceValue(value, p), name, "", usage) -} - -// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) { - f.VarP(newBoolSliceValue(value, p), name, shorthand, usage) -} - -// BoolSliceVar defines a []bool flag with specified name, default value, and usage string. -// The argument p points to a []bool variable in which to store the value of the flag. -func BoolSliceVar(p *[]bool, name string, value []bool, usage string) { - CommandLine.VarP(newBoolSliceValue(value, p), name, "", usage) -} - -// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash. -func BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) { - CommandLine.VarP(newBoolSliceValue(value, p), name, shorthand, usage) -} - -// BoolSlice defines a []bool flag with specified name, default value, and usage string. -// The return value is the address of a []bool variable that stores the value of the flag. -func (f *FlagSet) BoolSlice(name string, value []bool, usage string) *[]bool { - p := []bool{} - f.BoolSliceVarP(&p, name, "", value, usage) - return &p -} - -// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool { - p := []bool{} - f.BoolSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// BoolSlice defines a []bool flag with specified name, default value, and usage string. -// The return value is the address of a []bool variable that stores the value of the flag. -func BoolSlice(name string, value []bool, usage string) *[]bool { - return CommandLine.BoolSliceP(name, "", value, usage) -} - -// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash. -func BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool { - return CommandLine.BoolSliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/bytes.go b/vendor/github.com/spf13/pflag/bytes.go deleted file mode 100644 index 12c58db9f..000000000 --- a/vendor/github.com/spf13/pflag/bytes.go +++ /dev/null @@ -1,105 +0,0 @@ -package pflag - -import ( - "encoding/hex" - "fmt" - "strings" -) - -// BytesHex adapts []byte for use as a flag. Value of flag is HEX encoded -type bytesHexValue []byte - -func (bytesHex bytesHexValue) String() string { - return fmt.Sprintf("%X", []byte(bytesHex)) -} - -func (bytesHex *bytesHexValue) Set(value string) error { - bin, err := hex.DecodeString(strings.TrimSpace(value)) - - if err != nil { - return err - } - - *bytesHex = bin - - return nil -} - -func (*bytesHexValue) Type() string { - return "bytesHex" -} - -func newBytesHexValue(val []byte, p *[]byte) *bytesHexValue { - *p = val - return (*bytesHexValue)(p) -} - -func bytesHexConv(sval string) (interface{}, error) { - - bin, err := hex.DecodeString(sval) - - if err == nil { - return bin, nil - } - - return nil, fmt.Errorf("invalid string being converted to Bytes: %s %s", sval, err) -} - -// GetBytesHex return the []byte value of a flag with the given name -func (f *FlagSet) GetBytesHex(name string) ([]byte, error) { - val, err := f.getFlagType(name, "bytesHex", bytesHexConv) - - if err != nil { - return []byte{}, err - } - - return val.([]byte), nil -} - -// BytesHexVar defines an []byte flag with specified name, default value, and usage string. -// The argument p points to an []byte variable in which to store the value of the flag. -func (f *FlagSet) BytesHexVar(p *[]byte, name string, value []byte, usage string) { - f.VarP(newBytesHexValue(value, p), name, "", usage) -} - -// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) { - f.VarP(newBytesHexValue(value, p), name, shorthand, usage) -} - -// BytesHexVar defines an []byte flag with specified name, default value, and usage string. -// The argument p points to an []byte variable in which to store the value of the flag. -func BytesHexVar(p *[]byte, name string, value []byte, usage string) { - CommandLine.VarP(newBytesHexValue(value, p), name, "", usage) -} - -// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash. -func BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) { - CommandLine.VarP(newBytesHexValue(value, p), name, shorthand, usage) -} - -// BytesHex defines an []byte flag with specified name, default value, and usage string. -// The return value is the address of an []byte variable that stores the value of the flag. -func (f *FlagSet) BytesHex(name string, value []byte, usage string) *[]byte { - p := new([]byte) - f.BytesHexVarP(p, name, "", value, usage) - return p -} - -// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BytesHexP(name, shorthand string, value []byte, usage string) *[]byte { - p := new([]byte) - f.BytesHexVarP(p, name, shorthand, value, usage) - return p -} - -// BytesHex defines an []byte flag with specified name, default value, and usage string. -// The return value is the address of an []byte variable that stores the value of the flag. -func BytesHex(name string, value []byte, usage string) *[]byte { - return CommandLine.BytesHexP(name, "", value, usage) -} - -// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash. -func BytesHexP(name, shorthand string, value []byte, usage string) *[]byte { - return CommandLine.BytesHexP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/count.go b/vendor/github.com/spf13/pflag/count.go deleted file mode 100644 index aa126e44d..000000000 --- a/vendor/github.com/spf13/pflag/count.go +++ /dev/null @@ -1,96 +0,0 @@ -package pflag - -import "strconv" - -// -- count Value -type countValue int - -func newCountValue(val int, p *int) *countValue { - *p = val - return (*countValue)(p) -} - -func (i *countValue) Set(s string) error { - // "+1" means that no specific value was passed, so increment - if s == "+1" { - *i = countValue(*i + 1) - return nil - } - v, err := strconv.ParseInt(s, 0, 0) - *i = countValue(v) - return err -} - -func (i *countValue) Type() string { - return "count" -} - -func (i *countValue) String() string { return strconv.Itoa(int(*i)) } - -func countConv(sval string) (interface{}, error) { - i, err := strconv.Atoi(sval) - if err != nil { - return nil, err - } - return i, nil -} - -// GetCount return the int value of a flag with the given name -func (f *FlagSet) GetCount(name string) (int, error) { - val, err := f.getFlagType(name, "count", countConv) - if err != nil { - return 0, err - } - return val.(int), nil -} - -// CountVar defines a count flag with specified name, default value, and usage string. -// The argument p points to an int variable in which to store the value of the flag. -// A count flag will add 1 to its value evey time it is found on the command line -func (f *FlagSet) CountVar(p *int, name string, usage string) { - f.CountVarP(p, name, "", usage) -} - -// CountVarP is like CountVar only take a shorthand for the flag name. -func (f *FlagSet) CountVarP(p *int, name, shorthand string, usage string) { - flag := f.VarPF(newCountValue(0, p), name, shorthand, usage) - flag.NoOptDefVal = "+1" -} - -// CountVar like CountVar only the flag is placed on the CommandLine instead of a given flag set -func CountVar(p *int, name string, usage string) { - CommandLine.CountVar(p, name, usage) -} - -// CountVarP is like CountVar only take a shorthand for the flag name. -func CountVarP(p *int, name, shorthand string, usage string) { - CommandLine.CountVarP(p, name, shorthand, usage) -} - -// Count defines a count flag with specified name, default value, and usage string. -// The return value is the address of an int variable that stores the value of the flag. -// A count flag will add 1 to its value evey time it is found on the command line -func (f *FlagSet) Count(name string, usage string) *int { - p := new(int) - f.CountVarP(p, name, "", usage) - return p -} - -// CountP is like Count only takes a shorthand for the flag name. -func (f *FlagSet) CountP(name, shorthand string, usage string) *int { - p := new(int) - f.CountVarP(p, name, shorthand, usage) - return p -} - -// Count defines a count flag with specified name, default value, and usage string. -// The return value is the address of an int variable that stores the value of the flag. -// A count flag will add 1 to its value evey time it is found on the command line -func Count(name string, usage string) *int { - return CommandLine.CountP(name, "", usage) -} - -// CountP is like Count only takes a shorthand for the flag name. -func CountP(name, shorthand string, usage string) *int { - return CommandLine.CountP(name, shorthand, usage) -} diff --git a/vendor/github.com/spf13/pflag/duration.go b/vendor/github.com/spf13/pflag/duration.go deleted file mode 100644 index e9debef88..000000000 --- a/vendor/github.com/spf13/pflag/duration.go +++ /dev/null @@ -1,86 +0,0 @@ -package pflag - -import ( - "time" -) - -// -- time.Duration Value -type durationValue time.Duration - -func newDurationValue(val time.Duration, p *time.Duration) *durationValue { - *p = val - return (*durationValue)(p) -} - -func (d *durationValue) Set(s string) error { - v, err := time.ParseDuration(s) - *d = durationValue(v) - return err -} - -func (d *durationValue) Type() string { - return "duration" -} - -func (d *durationValue) String() string { return (*time.Duration)(d).String() } - -func durationConv(sval string) (interface{}, error) { - return time.ParseDuration(sval) -} - -// GetDuration return the duration value of a flag with the given name -func (f *FlagSet) GetDuration(name string) (time.Duration, error) { - val, err := f.getFlagType(name, "duration", durationConv) - if err != nil { - return 0, err - } - return val.(time.Duration), nil -} - -// DurationVar defines a time.Duration flag with specified name, default value, and usage string. -// The argument p points to a time.Duration variable in which to store the value of the flag. -func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) { - f.VarP(newDurationValue(value, p), name, "", usage) -} - -// DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) { - f.VarP(newDurationValue(value, p), name, shorthand, usage) -} - -// DurationVar defines a time.Duration flag with specified name, default value, and usage string. -// The argument p points to a time.Duration variable in which to store the value of the flag. -func DurationVar(p *time.Duration, name string, value time.Duration, usage string) { - CommandLine.VarP(newDurationValue(value, p), name, "", usage) -} - -// DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash. -func DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) { - CommandLine.VarP(newDurationValue(value, p), name, shorthand, usage) -} - -// Duration defines a time.Duration flag with specified name, default value, and usage string. -// The return value is the address of a time.Duration variable that stores the value of the flag. -func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration { - p := new(time.Duration) - f.DurationVarP(p, name, "", value, usage) - return p -} - -// DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration { - p := new(time.Duration) - f.DurationVarP(p, name, shorthand, value, usage) - return p -} - -// Duration defines a time.Duration flag with specified name, default value, and usage string. -// The return value is the address of a time.Duration variable that stores the value of the flag. -func Duration(name string, value time.Duration, usage string) *time.Duration { - return CommandLine.DurationP(name, "", value, usage) -} - -// DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash. -func DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration { - return CommandLine.DurationP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/duration_slice.go b/vendor/github.com/spf13/pflag/duration_slice.go deleted file mode 100644 index 52c6b6dc1..000000000 --- a/vendor/github.com/spf13/pflag/duration_slice.go +++ /dev/null @@ -1,128 +0,0 @@ -package pflag - -import ( - "fmt" - "strings" - "time" -) - -// -- durationSlice Value -type durationSliceValue struct { - value *[]time.Duration - changed bool -} - -func newDurationSliceValue(val []time.Duration, p *[]time.Duration) *durationSliceValue { - dsv := new(durationSliceValue) - dsv.value = p - *dsv.value = val - return dsv -} - -func (s *durationSliceValue) Set(val string) error { - ss := strings.Split(val, ",") - out := make([]time.Duration, len(ss)) - for i, d := range ss { - var err error - out[i], err = time.ParseDuration(d) - if err != nil { - return err - } - - } - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - s.changed = true - return nil -} - -func (s *durationSliceValue) Type() string { - return "durationSlice" -} - -func (s *durationSliceValue) String() string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = fmt.Sprintf("%s", d) - } - return "[" + strings.Join(out, ",") + "]" -} - -func durationSliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Empty string would cause a slice with one (empty) entry - if len(val) == 0 { - return []time.Duration{}, nil - } - ss := strings.Split(val, ",") - out := make([]time.Duration, len(ss)) - for i, d := range ss { - var err error - out[i], err = time.ParseDuration(d) - if err != nil { - return nil, err - } - - } - return out, nil -} - -// GetDurationSlice returns the []time.Duration value of a flag with the given name -func (f *FlagSet) GetDurationSlice(name string) ([]time.Duration, error) { - val, err := f.getFlagType(name, "durationSlice", durationSliceConv) - if err != nil { - return []time.Duration{}, err - } - return val.([]time.Duration), nil -} - -// DurationSliceVar defines a durationSlice flag with specified name, default value, and usage string. -// The argument p points to a []time.Duration variable in which to store the value of the flag. -func (f *FlagSet) DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string) { - f.VarP(newDurationSliceValue(value, p), name, "", usage) -} - -// DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) DurationSliceVarP(p *[]time.Duration, name, shorthand string, value []time.Duration, usage string) { - f.VarP(newDurationSliceValue(value, p), name, shorthand, usage) -} - -// DurationSliceVar defines a duration[] flag with specified name, default value, and usage string. -// The argument p points to a duration[] variable in which to store the value of the flag. -func DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string) { - CommandLine.VarP(newDurationSliceValue(value, p), name, "", usage) -} - -// DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash. -func DurationSliceVarP(p *[]time.Duration, name, shorthand string, value []time.Duration, usage string) { - CommandLine.VarP(newDurationSliceValue(value, p), name, shorthand, usage) -} - -// DurationSlice defines a []time.Duration flag with specified name, default value, and usage string. -// The return value is the address of a []time.Duration variable that stores the value of the flag. -func (f *FlagSet) DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration { - p := []time.Duration{} - f.DurationSliceVarP(&p, name, "", value, usage) - return &p -} - -// DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) DurationSliceP(name, shorthand string, value []time.Duration, usage string) *[]time.Duration { - p := []time.Duration{} - f.DurationSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// DurationSlice defines a []time.Duration flag with specified name, default value, and usage string. -// The return value is the address of a []time.Duration variable that stores the value of the flag. -func DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration { - return CommandLine.DurationSliceP(name, "", value, usage) -} - -// DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash. -func DurationSliceP(name, shorthand string, value []time.Duration, usage string) *[]time.Duration { - return CommandLine.DurationSliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/flag.go b/vendor/github.com/spf13/pflag/flag.go deleted file mode 100644 index 5eadc84e3..000000000 --- a/vendor/github.com/spf13/pflag/flag.go +++ /dev/null @@ -1,1223 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* -Package pflag is a drop-in replacement for Go's flag package, implementing -POSIX/GNU-style --flags. - -pflag is compatible with the GNU extensions to the POSIX recommendations -for command-line options. See -http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html - -Usage: - -pflag is a drop-in replacement of Go's native flag package. If you import -pflag under the name "flag" then all code should continue to function -with no changes. - - import flag "github.com/spf13/pflag" - -There is one exception to this: if you directly instantiate the Flag struct -there is one more field "Shorthand" that you will need to set. -Most code never instantiates this struct directly, and instead uses -functions such as String(), BoolVar(), and Var(), and is therefore -unaffected. - -Define flags using flag.String(), Bool(), Int(), etc. - -This declares an integer flag, -flagname, stored in the pointer ip, with type *int. - var ip = flag.Int("flagname", 1234, "help message for flagname") -If you like, you can bind the flag to a variable using the Var() functions. - var flagvar int - func init() { - flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") - } -Or you can create custom flags that satisfy the Value interface (with -pointer receivers) and couple them to flag parsing by - flag.Var(&flagVal, "name", "help message for flagname") -For such flags, the default value is just the initial value of the variable. - -After all flags are defined, call - flag.Parse() -to parse the command line into the defined flags. - -Flags may then be used directly. If you're using the flags themselves, -they are all pointers; if you bind to variables, they're values. - fmt.Println("ip has value ", *ip) - fmt.Println("flagvar has value ", flagvar) - -After parsing, the arguments after the flag are available as the -slice flag.Args() or individually as flag.Arg(i). -The arguments are indexed from 0 through flag.NArg()-1. - -The pflag package also defines some new functions that are not in flag, -that give one-letter shorthands for flags. You can use these by appending -'P' to the name of any function that defines a flag. - var ip = flag.IntP("flagname", "f", 1234, "help message") - var flagvar bool - func init() { - flag.BoolVarP("boolname", "b", true, "help message") - } - flag.VarP(&flagVar, "varname", "v", 1234, "help message") -Shorthand letters can be used with single dashes on the command line. -Boolean shorthand flags can be combined with other shorthand flags. - -Command line flag syntax: - --flag // boolean flags only - --flag=x - -Unlike the flag package, a single dash before an option means something -different than a double dash. Single dashes signify a series of shorthand -letters for flags. All but the last shorthand letter must be boolean flags. - // boolean flags - -f - -abc - // non-boolean flags - -n 1234 - -Ifile - // mixed - -abcs "hello" - -abcn1234 - -Flag parsing stops after the terminator "--". Unlike the flag package, -flags can be interspersed with arguments anywhere on the command line -before this terminator. - -Integer flags accept 1234, 0664, 0x1234 and may be negative. -Boolean flags (in their long form) accept 1, 0, t, f, true, false, -TRUE, FALSE, True, False. -Duration flags accept any input valid for time.ParseDuration. - -The default set of command-line flags is controlled by -top-level functions. The FlagSet type allows one to define -independent sets of flags, such as to implement subcommands -in a command-line interface. The methods of FlagSet are -analogous to the top-level functions for the command-line -flag set. -*/ -package pflag - -import ( - "bytes" - "errors" - goflag "flag" - "fmt" - "io" - "os" - "sort" - "strings" -) - -// ErrHelp is the error returned if the flag -help is invoked but no such flag is defined. -var ErrHelp = errors.New("pflag: help requested") - -// ErrorHandling defines how to handle flag parsing errors. -type ErrorHandling int - -const ( - // ContinueOnError will return an err from Parse() if an error is found - ContinueOnError ErrorHandling = iota - // ExitOnError will call os.Exit(2) if an error is found when parsing - ExitOnError - // PanicOnError will panic() if an error is found when parsing flags - PanicOnError -) - -// ParseErrorsWhitelist defines the parsing errors that can be ignored -type ParseErrorsWhitelist struct { - // UnknownFlags will ignore unknown flags errors and continue parsing rest of the flags - UnknownFlags bool -} - -// NormalizedName is a flag name that has been normalized according to rules -// for the FlagSet (e.g. making '-' and '_' equivalent). -type NormalizedName string - -// A FlagSet represents a set of defined flags. -type FlagSet struct { - // Usage is the function called when an error occurs while parsing flags. - // The field is a function (not a method) that may be changed to point to - // a custom error handler. - Usage func() - - // SortFlags is used to indicate, if user wants to have sorted flags in - // help/usage messages. - SortFlags bool - - // ParseErrorsWhitelist is used to configure a whitelist of errors - ParseErrorsWhitelist ParseErrorsWhitelist - - name string - parsed bool - actual map[NormalizedName]*Flag - orderedActual []*Flag - sortedActual []*Flag - formal map[NormalizedName]*Flag - orderedFormal []*Flag - sortedFormal []*Flag - shorthands map[byte]*Flag - args []string // arguments after flags - argsLenAtDash int // len(args) when a '--' was located when parsing, or -1 if no -- - errorHandling ErrorHandling - output io.Writer // nil means stderr; use out() accessor - interspersed bool // allow interspersed option/non-option args - normalizeNameFunc func(f *FlagSet, name string) NormalizedName - - addedGoFlagSets []*goflag.FlagSet -} - -// A Flag represents the state of a flag. -type Flag struct { - Name string // name as it appears on command line - Shorthand string // one-letter abbreviated flag - Usage string // help message - Value Value // value as set - DefValue string // default value (as text); for usage message - Changed bool // If the user set the value (or if left to default) - NoOptDefVal string // default value (as text); if the flag is on the command line without any options - Deprecated string // If this flag is deprecated, this string is the new or now thing to use - Hidden bool // used by cobra.Command to allow flags to be hidden from help/usage text - ShorthandDeprecated string // If the shorthand of this flag is deprecated, this string is the new or now thing to use - Annotations map[string][]string // used by cobra.Command bash autocomple code -} - -// Value is the interface to the dynamic value stored in a flag. -// (The default value is represented as a string.) -type Value interface { - String() string - Set(string) error - Type() string -} - -// sortFlags returns the flags as a slice in lexicographical sorted order. -func sortFlags(flags map[NormalizedName]*Flag) []*Flag { - list := make(sort.StringSlice, len(flags)) - i := 0 - for k := range flags { - list[i] = string(k) - i++ - } - list.Sort() - result := make([]*Flag, len(list)) - for i, name := range list { - result[i] = flags[NormalizedName(name)] - } - return result -} - -// SetNormalizeFunc allows you to add a function which can translate flag names. -// Flags added to the FlagSet will be translated and then when anything tries to -// look up the flag that will also be translated. So it would be possible to create -// a flag named "getURL" and have it translated to "geturl". A user could then pass -// "--getUrl" which may also be translated to "geturl" and everything will work. -func (f *FlagSet) SetNormalizeFunc(n func(f *FlagSet, name string) NormalizedName) { - f.normalizeNameFunc = n - f.sortedFormal = f.sortedFormal[:0] - for fname, flag := range f.formal { - nname := f.normalizeFlagName(flag.Name) - if fname == nname { - continue - } - flag.Name = string(nname) - delete(f.formal, fname) - f.formal[nname] = flag - if _, set := f.actual[fname]; set { - delete(f.actual, fname) - f.actual[nname] = flag - } - } -} - -// GetNormalizeFunc returns the previously set NormalizeFunc of a function which -// does no translation, if not set previously. -func (f *FlagSet) GetNormalizeFunc() func(f *FlagSet, name string) NormalizedName { - if f.normalizeNameFunc != nil { - return f.normalizeNameFunc - } - return func(f *FlagSet, name string) NormalizedName { return NormalizedName(name) } -} - -func (f *FlagSet) normalizeFlagName(name string) NormalizedName { - n := f.GetNormalizeFunc() - return n(f, name) -} - -func (f *FlagSet) out() io.Writer { - if f.output == nil { - return os.Stderr - } - return f.output -} - -// SetOutput sets the destination for usage and error messages. -// If output is nil, os.Stderr is used. -func (f *FlagSet) SetOutput(output io.Writer) { - f.output = output -} - -// VisitAll visits the flags in lexicographical order or -// in primordial order if f.SortFlags is false, calling fn for each. -// It visits all flags, even those not set. -func (f *FlagSet) VisitAll(fn func(*Flag)) { - if len(f.formal) == 0 { - return - } - - var flags []*Flag - if f.SortFlags { - if len(f.formal) != len(f.sortedFormal) { - f.sortedFormal = sortFlags(f.formal) - } - flags = f.sortedFormal - } else { - flags = f.orderedFormal - } - - for _, flag := range flags { - fn(flag) - } -} - -// HasFlags returns a bool to indicate if the FlagSet has any flags defined. -func (f *FlagSet) HasFlags() bool { - return len(f.formal) > 0 -} - -// HasAvailableFlags returns a bool to indicate if the FlagSet has any flags -// that are not hidden. -func (f *FlagSet) HasAvailableFlags() bool { - for _, flag := range f.formal { - if !flag.Hidden { - return true - } - } - return false -} - -// VisitAll visits the command-line flags in lexicographical order or -// in primordial order if f.SortFlags is false, calling fn for each. -// It visits all flags, even those not set. -func VisitAll(fn func(*Flag)) { - CommandLine.VisitAll(fn) -} - -// Visit visits the flags in lexicographical order or -// in primordial order if f.SortFlags is false, calling fn for each. -// It visits only those flags that have been set. -func (f *FlagSet) Visit(fn func(*Flag)) { - if len(f.actual) == 0 { - return - } - - var flags []*Flag - if f.SortFlags { - if len(f.actual) != len(f.sortedActual) { - f.sortedActual = sortFlags(f.actual) - } - flags = f.sortedActual - } else { - flags = f.orderedActual - } - - for _, flag := range flags { - fn(flag) - } -} - -// Visit visits the command-line flags in lexicographical order or -// in primordial order if f.SortFlags is false, calling fn for each. -// It visits only those flags that have been set. -func Visit(fn func(*Flag)) { - CommandLine.Visit(fn) -} - -// Lookup returns the Flag structure of the named flag, returning nil if none exists. -func (f *FlagSet) Lookup(name string) *Flag { - return f.lookup(f.normalizeFlagName(name)) -} - -// ShorthandLookup returns the Flag structure of the short handed flag, -// returning nil if none exists. -// It panics, if len(name) > 1. -func (f *FlagSet) ShorthandLookup(name string) *Flag { - if name == "" { - return nil - } - if len(name) > 1 { - msg := fmt.Sprintf("can not look up shorthand which is more than one ASCII character: %q", name) - fmt.Fprintf(f.out(), msg) - panic(msg) - } - c := name[0] - return f.shorthands[c] -} - -// lookup returns the Flag structure of the named flag, returning nil if none exists. -func (f *FlagSet) lookup(name NormalizedName) *Flag { - return f.formal[name] -} - -// func to return a given type for a given flag name -func (f *FlagSet) getFlagType(name string, ftype string, convFunc func(sval string) (interface{}, error)) (interface{}, error) { - flag := f.Lookup(name) - if flag == nil { - err := fmt.Errorf("flag accessed but not defined: %s", name) - return nil, err - } - - if flag.Value.Type() != ftype { - err := fmt.Errorf("trying to get %s value of flag of type %s", ftype, flag.Value.Type()) - return nil, err - } - - sval := flag.Value.String() - result, err := convFunc(sval) - if err != nil { - return nil, err - } - return result, nil -} - -// ArgsLenAtDash will return the length of f.Args at the moment when a -- was -// found during arg parsing. This allows your program to know which args were -// before the -- and which came after. -func (f *FlagSet) ArgsLenAtDash() int { - return f.argsLenAtDash -} - -// MarkDeprecated indicated that a flag is deprecated in your program. It will -// continue to function but will not show up in help or usage messages. Using -// this flag will also print the given usageMessage. -func (f *FlagSet) MarkDeprecated(name string, usageMessage string) error { - flag := f.Lookup(name) - if flag == nil { - return fmt.Errorf("flag %q does not exist", name) - } - if usageMessage == "" { - return fmt.Errorf("deprecated message for flag %q must be set", name) - } - flag.Deprecated = usageMessage - flag.Hidden = true - return nil -} - -// MarkShorthandDeprecated will mark the shorthand of a flag deprecated in your -// program. It will continue to function but will not show up in help or usage -// messages. Using this flag will also print the given usageMessage. -func (f *FlagSet) MarkShorthandDeprecated(name string, usageMessage string) error { - flag := f.Lookup(name) - if flag == nil { - return fmt.Errorf("flag %q does not exist", name) - } - if usageMessage == "" { - return fmt.Errorf("deprecated message for flag %q must be set", name) - } - flag.ShorthandDeprecated = usageMessage - return nil -} - -// MarkHidden sets a flag to 'hidden' in your program. It will continue to -// function but will not show up in help or usage messages. -func (f *FlagSet) MarkHidden(name string) error { - flag := f.Lookup(name) - if flag == nil { - return fmt.Errorf("flag %q does not exist", name) - } - flag.Hidden = true - return nil -} - -// Lookup returns the Flag structure of the named command-line flag, -// returning nil if none exists. -func Lookup(name string) *Flag { - return CommandLine.Lookup(name) -} - -// ShorthandLookup returns the Flag structure of the short handed flag, -// returning nil if none exists. -func ShorthandLookup(name string) *Flag { - return CommandLine.ShorthandLookup(name) -} - -// Set sets the value of the named flag. -func (f *FlagSet) Set(name, value string) error { - normalName := f.normalizeFlagName(name) - flag, ok := f.formal[normalName] - if !ok { - return fmt.Errorf("no such flag -%v", name) - } - - err := flag.Value.Set(value) - if err != nil { - var flagName string - if flag.Shorthand != "" && flag.ShorthandDeprecated == "" { - flagName = fmt.Sprintf("-%s, --%s", flag.Shorthand, flag.Name) - } else { - flagName = fmt.Sprintf("--%s", flag.Name) - } - return fmt.Errorf("invalid argument %q for %q flag: %v", value, flagName, err) - } - - if !flag.Changed { - if f.actual == nil { - f.actual = make(map[NormalizedName]*Flag) - } - f.actual[normalName] = flag - f.orderedActual = append(f.orderedActual, flag) - - flag.Changed = true - } - - if flag.Deprecated != "" { - fmt.Fprintf(f.out(), "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated) - } - return nil -} - -// SetAnnotation allows one to set arbitrary annotations on a flag in the FlagSet. -// This is sometimes used by spf13/cobra programs which want to generate additional -// bash completion information. -func (f *FlagSet) SetAnnotation(name, key string, values []string) error { - normalName := f.normalizeFlagName(name) - flag, ok := f.formal[normalName] - if !ok { - return fmt.Errorf("no such flag -%v", name) - } - if flag.Annotations == nil { - flag.Annotations = map[string][]string{} - } - flag.Annotations[key] = values - return nil -} - -// Changed returns true if the flag was explicitly set during Parse() and false -// otherwise -func (f *FlagSet) Changed(name string) bool { - flag := f.Lookup(name) - // If a flag doesn't exist, it wasn't changed.... - if flag == nil { - return false - } - return flag.Changed -} - -// Set sets the value of the named command-line flag. -func Set(name, value string) error { - return CommandLine.Set(name, value) -} - -// PrintDefaults prints, to standard error unless configured -// otherwise, the default values of all defined flags in the set. -func (f *FlagSet) PrintDefaults() { - usages := f.FlagUsages() - fmt.Fprint(f.out(), usages) -} - -// defaultIsZeroValue returns true if the default value for this flag represents -// a zero value. -func (f *Flag) defaultIsZeroValue() bool { - switch f.Value.(type) { - case boolFlag: - return f.DefValue == "false" - case *durationValue: - // Beginning in Go 1.7, duration zero values are "0s" - return f.DefValue == "0" || f.DefValue == "0s" - case *intValue, *int8Value, *int32Value, *int64Value, *uintValue, *uint8Value, *uint16Value, *uint32Value, *uint64Value, *countValue, *float32Value, *float64Value: - return f.DefValue == "0" - case *stringValue: - return f.DefValue == "" - case *ipValue, *ipMaskValue, *ipNetValue: - return f.DefValue == "" - case *intSliceValue, *stringSliceValue, *stringArrayValue: - return f.DefValue == "[]" - default: - switch f.Value.String() { - case "false": - return true - case "": - return true - case "": - return true - case "0": - return true - } - return false - } -} - -// UnquoteUsage extracts a back-quoted name from the usage -// string for a flag and returns it and the un-quoted usage. -// Given "a `name` to show" it returns ("name", "a name to show"). -// If there are no back quotes, the name is an educated guess of the -// type of the flag's value, or the empty string if the flag is boolean. -func UnquoteUsage(flag *Flag) (name string, usage string) { - // Look for a back-quoted name, but avoid the strings package. - usage = flag.Usage - for i := 0; i < len(usage); i++ { - if usage[i] == '`' { - for j := i + 1; j < len(usage); j++ { - if usage[j] == '`' { - name = usage[i+1 : j] - usage = usage[:i] + name + usage[j+1:] - return name, usage - } - } - break // Only one back quote; use type name. - } - } - - name = flag.Value.Type() - switch name { - case "bool": - name = "" - case "float64": - name = "float" - case "int64": - name = "int" - case "uint64": - name = "uint" - case "stringSlice": - name = "strings" - case "intSlice": - name = "ints" - case "uintSlice": - name = "uints" - case "boolSlice": - name = "bools" - } - - return -} - -// Splits the string `s` on whitespace into an initial substring up to -// `i` runes in length and the remainder. Will go `slop` over `i` if -// that encompasses the entire string (which allows the caller to -// avoid short orphan words on the final line). -func wrapN(i, slop int, s string) (string, string) { - if i+slop > len(s) { - return s, "" - } - - w := strings.LastIndexAny(s[:i], " \t\n") - if w <= 0 { - return s, "" - } - nlPos := strings.LastIndex(s[:i], "\n") - if nlPos > 0 && nlPos < w { - return s[:nlPos], s[nlPos+1:] - } - return s[:w], s[w+1:] -} - -// Wraps the string `s` to a maximum width `w` with leading indent -// `i`. The first line is not indented (this is assumed to be done by -// caller). Pass `w` == 0 to do no wrapping -func wrap(i, w int, s string) string { - if w == 0 { - return strings.Replace(s, "\n", "\n"+strings.Repeat(" ", i), -1) - } - - // space between indent i and end of line width w into which - // we should wrap the text. - wrap := w - i - - var r, l string - - // Not enough space for sensible wrapping. Wrap as a block on - // the next line instead. - if wrap < 24 { - i = 16 - wrap = w - i - r += "\n" + strings.Repeat(" ", i) - } - // If still not enough space then don't even try to wrap. - if wrap < 24 { - return strings.Replace(s, "\n", r, -1) - } - - // Try to avoid short orphan words on the final line, by - // allowing wrapN to go a bit over if that would fit in the - // remainder of the line. - slop := 5 - wrap = wrap - slop - - // Handle first line, which is indented by the caller (or the - // special case above) - l, s = wrapN(wrap, slop, s) - r = r + strings.Replace(l, "\n", "\n"+strings.Repeat(" ", i), -1) - - // Now wrap the rest - for s != "" { - var t string - - t, s = wrapN(wrap, slop, s) - r = r + "\n" + strings.Repeat(" ", i) + strings.Replace(t, "\n", "\n"+strings.Repeat(" ", i), -1) - } - - return r - -} - -// FlagUsagesWrapped returns a string containing the usage information -// for all flags in the FlagSet. Wrapped to `cols` columns (0 for no -// wrapping) -func (f *FlagSet) FlagUsagesWrapped(cols int) string { - buf := new(bytes.Buffer) - - lines := make([]string, 0, len(f.formal)) - - maxlen := 0 - f.VisitAll(func(flag *Flag) { - if flag.Hidden { - return - } - - line := "" - if flag.Shorthand != "" && flag.ShorthandDeprecated == "" { - line = fmt.Sprintf(" -%s, --%s", flag.Shorthand, flag.Name) - } else { - line = fmt.Sprintf(" --%s", flag.Name) - } - - varname, usage := UnquoteUsage(flag) - if varname != "" { - line += " " + varname - } - if flag.NoOptDefVal != "" { - switch flag.Value.Type() { - case "string": - line += fmt.Sprintf("[=\"%s\"]", flag.NoOptDefVal) - case "bool": - if flag.NoOptDefVal != "true" { - line += fmt.Sprintf("[=%s]", flag.NoOptDefVal) - } - case "count": - if flag.NoOptDefVal != "+1" { - line += fmt.Sprintf("[=%s]", flag.NoOptDefVal) - } - default: - line += fmt.Sprintf("[=%s]", flag.NoOptDefVal) - } - } - - // This special character will be replaced with spacing once the - // correct alignment is calculated - line += "\x00" - if len(line) > maxlen { - maxlen = len(line) - } - - line += usage - if !flag.defaultIsZeroValue() { - if flag.Value.Type() == "string" { - line += fmt.Sprintf(" (default %q)", flag.DefValue) - } else { - line += fmt.Sprintf(" (default %s)", flag.DefValue) - } - } - if len(flag.Deprecated) != 0 { - line += fmt.Sprintf(" (DEPRECATED: %s)", flag.Deprecated) - } - - lines = append(lines, line) - }) - - for _, line := range lines { - sidx := strings.Index(line, "\x00") - spacing := strings.Repeat(" ", maxlen-sidx) - // maxlen + 2 comes from + 1 for the \x00 and + 1 for the (deliberate) off-by-one in maxlen-sidx - fmt.Fprintln(buf, line[:sidx], spacing, wrap(maxlen+2, cols, line[sidx+1:])) - } - - return buf.String() -} - -// FlagUsages returns a string containing the usage information for all flags in -// the FlagSet -func (f *FlagSet) FlagUsages() string { - return f.FlagUsagesWrapped(0) -} - -// PrintDefaults prints to standard error the default values of all defined command-line flags. -func PrintDefaults() { - CommandLine.PrintDefaults() -} - -// defaultUsage is the default function to print a usage message. -func defaultUsage(f *FlagSet) { - fmt.Fprintf(f.out(), "Usage of %s:\n", f.name) - f.PrintDefaults() -} - -// NOTE: Usage is not just defaultUsage(CommandLine) -// because it serves (via godoc flag Usage) as the example -// for how to write your own usage function. - -// Usage prints to standard error a usage message documenting all defined command-line flags. -// The function is a variable that may be changed to point to a custom function. -// By default it prints a simple header and calls PrintDefaults; for details about the -// format of the output and how to control it, see the documentation for PrintDefaults. -var Usage = func() { - fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) - PrintDefaults() -} - -// NFlag returns the number of flags that have been set. -func (f *FlagSet) NFlag() int { return len(f.actual) } - -// NFlag returns the number of command-line flags that have been set. -func NFlag() int { return len(CommandLine.actual) } - -// Arg returns the i'th argument. Arg(0) is the first remaining argument -// after flags have been processed. -func (f *FlagSet) Arg(i int) string { - if i < 0 || i >= len(f.args) { - return "" - } - return f.args[i] -} - -// Arg returns the i'th command-line argument. Arg(0) is the first remaining argument -// after flags have been processed. -func Arg(i int) string { - return CommandLine.Arg(i) -} - -// NArg is the number of arguments remaining after flags have been processed. -func (f *FlagSet) NArg() int { return len(f.args) } - -// NArg is the number of arguments remaining after flags have been processed. -func NArg() int { return len(CommandLine.args) } - -// Args returns the non-flag arguments. -func (f *FlagSet) Args() []string { return f.args } - -// Args returns the non-flag command-line arguments. -func Args() []string { return CommandLine.args } - -// Var defines a flag with the specified name and usage string. The type and -// value of the flag are represented by the first argument, of type Value, which -// typically holds a user-defined implementation of Value. For instance, the -// caller could create a flag that turns a comma-separated string into a slice -// of strings by giving the slice the methods of Value; in particular, Set would -// decompose the comma-separated string into the slice. -func (f *FlagSet) Var(value Value, name string, usage string) { - f.VarP(value, name, "", usage) -} - -// VarPF is like VarP, but returns the flag created -func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag { - // Remember the default value as a string; it won't change. - flag := &Flag{ - Name: name, - Shorthand: shorthand, - Usage: usage, - Value: value, - DefValue: value.String(), - } - f.AddFlag(flag) - return flag -} - -// VarP is like Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) VarP(value Value, name, shorthand, usage string) { - f.VarPF(value, name, shorthand, usage) -} - -// AddFlag will add the flag to the FlagSet -func (f *FlagSet) AddFlag(flag *Flag) { - normalizedFlagName := f.normalizeFlagName(flag.Name) - - _, alreadyThere := f.formal[normalizedFlagName] - if alreadyThere { - msg := fmt.Sprintf("%s flag redefined: %s", f.name, flag.Name) - fmt.Fprintln(f.out(), msg) - panic(msg) // Happens only if flags are declared with identical names - } - if f.formal == nil { - f.formal = make(map[NormalizedName]*Flag) - } - - flag.Name = string(normalizedFlagName) - f.formal[normalizedFlagName] = flag - f.orderedFormal = append(f.orderedFormal, flag) - - if flag.Shorthand == "" { - return - } - if len(flag.Shorthand) > 1 { - msg := fmt.Sprintf("%q shorthand is more than one ASCII character", flag.Shorthand) - fmt.Fprintf(f.out(), msg) - panic(msg) - } - if f.shorthands == nil { - f.shorthands = make(map[byte]*Flag) - } - c := flag.Shorthand[0] - used, alreadyThere := f.shorthands[c] - if alreadyThere { - msg := fmt.Sprintf("unable to redefine %q shorthand in %q flagset: it's already used for %q flag", c, f.name, used.Name) - fmt.Fprintf(f.out(), msg) - panic(msg) - } - f.shorthands[c] = flag -} - -// AddFlagSet adds one FlagSet to another. If a flag is already present in f -// the flag from newSet will be ignored. -func (f *FlagSet) AddFlagSet(newSet *FlagSet) { - if newSet == nil { - return - } - newSet.VisitAll(func(flag *Flag) { - if f.Lookup(flag.Name) == nil { - f.AddFlag(flag) - } - }) -} - -// Var defines a flag with the specified name and usage string. The type and -// value of the flag are represented by the first argument, of type Value, which -// typically holds a user-defined implementation of Value. For instance, the -// caller could create a flag that turns a comma-separated string into a slice -// of strings by giving the slice the methods of Value; in particular, Set would -// decompose the comma-separated string into the slice. -func Var(value Value, name string, usage string) { - CommandLine.VarP(value, name, "", usage) -} - -// VarP is like Var, but accepts a shorthand letter that can be used after a single dash. -func VarP(value Value, name, shorthand, usage string) { - CommandLine.VarP(value, name, shorthand, usage) -} - -// failf prints to standard error a formatted error and usage message and -// returns the error. -func (f *FlagSet) failf(format string, a ...interface{}) error { - err := fmt.Errorf(format, a...) - if f.errorHandling != ContinueOnError { - fmt.Fprintln(f.out(), err) - f.usage() - } - return err -} - -// usage calls the Usage method for the flag set, or the usage function if -// the flag set is CommandLine. -func (f *FlagSet) usage() { - if f == CommandLine { - Usage() - } else if f.Usage == nil { - defaultUsage(f) - } else { - f.Usage() - } -} - -//--unknown (args will be empty) -//--unknown --next-flag ... (args will be --next-flag ...) -//--unknown arg ... (args will be arg ...) -func stripUnknownFlagValue(args []string) []string { - if len(args) == 0 { - //--unknown - return args - } - - first := args[0] - if first[0] == '-' { - //--unknown --next-flag ... - return args - } - - //--unknown arg ... (args will be arg ...) - return args[1:] -} - -func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []string, err error) { - a = args - name := s[2:] - if len(name) == 0 || name[0] == '-' || name[0] == '=' { - err = f.failf("bad flag syntax: %s", s) - return - } - - split := strings.SplitN(name, "=", 2) - name = split[0] - flag, exists := f.formal[f.normalizeFlagName(name)] - - if !exists { - switch { - case name == "help": - f.usage() - return a, ErrHelp - case f.ParseErrorsWhitelist.UnknownFlags: - // --unknown=unknownval arg ... - // we do not want to lose arg in this case - if len(split) >= 2 { - return a, nil - } - - return stripUnknownFlagValue(a), nil - default: - err = f.failf("unknown flag: --%s", name) - return - } - } - - var value string - if len(split) == 2 { - // '--flag=arg' - value = split[1] - } else if flag.NoOptDefVal != "" { - // '--flag' (arg was optional) - value = flag.NoOptDefVal - } else if len(a) > 0 { - // '--flag arg' - value = a[0] - a = a[1:] - } else { - // '--flag' (arg was required) - err = f.failf("flag needs an argument: %s", s) - return - } - - err = fn(flag, value) - if err != nil { - f.failf(err.Error()) - } - return -} - -func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parseFunc) (outShorts string, outArgs []string, err error) { - if strings.HasPrefix(shorthands, "test.") { - return - } - - outArgs = args - outShorts = shorthands[1:] - c := shorthands[0] - - flag, exists := f.shorthands[c] - if !exists { - switch { - case c == 'h': - f.usage() - err = ErrHelp - return - case f.ParseErrorsWhitelist.UnknownFlags: - // '-f=arg arg ...' - // we do not want to lose arg in this case - if len(shorthands) > 2 && shorthands[1] == '=' { - outShorts = "" - return - } - - outArgs = stripUnknownFlagValue(outArgs) - return - default: - err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands) - return - } - } - - var value string - if len(shorthands) > 2 && shorthands[1] == '=' { - // '-f=arg' - value = shorthands[2:] - outShorts = "" - } else if flag.NoOptDefVal != "" { - // '-f' (arg was optional) - value = flag.NoOptDefVal - } else if len(shorthands) > 1 { - // '-farg' - value = shorthands[1:] - outShorts = "" - } else if len(args) > 0 { - // '-f arg' - value = args[0] - outArgs = args[1:] - } else { - // '-f' (arg was required) - err = f.failf("flag needs an argument: %q in -%s", c, shorthands) - return - } - - if flag.ShorthandDeprecated != "" { - fmt.Fprintf(f.out(), "Flag shorthand -%s has been deprecated, %s\n", flag.Shorthand, flag.ShorthandDeprecated) - } - - err = fn(flag, value) - if err != nil { - f.failf(err.Error()) - } - return -} - -func (f *FlagSet) parseShortArg(s string, args []string, fn parseFunc) (a []string, err error) { - a = args - shorthands := s[1:] - - // "shorthands" can be a series of shorthand letters of flags (e.g. "-vvv"). - for len(shorthands) > 0 { - shorthands, a, err = f.parseSingleShortArg(shorthands, args, fn) - if err != nil { - return - } - } - - return -} - -func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) { - for len(args) > 0 { - s := args[0] - args = args[1:] - if len(s) == 0 || s[0] != '-' || len(s) == 1 { - if !f.interspersed { - f.args = append(f.args, s) - f.args = append(f.args, args...) - return nil - } - f.args = append(f.args, s) - continue - } - - if s[1] == '-' { - if len(s) == 2 { // "--" terminates the flags - f.argsLenAtDash = len(f.args) - f.args = append(f.args, args...) - break - } - args, err = f.parseLongArg(s, args, fn) - } else { - args, err = f.parseShortArg(s, args, fn) - } - if err != nil { - return - } - } - return -} - -// Parse parses flag definitions from the argument list, which should not -// include the command name. Must be called after all flags in the FlagSet -// are defined and before flags are accessed by the program. -// The return value will be ErrHelp if -help was set but not defined. -func (f *FlagSet) Parse(arguments []string) error { - if f.addedGoFlagSets != nil { - for _, goFlagSet := range f.addedGoFlagSets { - goFlagSet.Parse(nil) - } - } - f.parsed = true - - if len(arguments) < 0 { - return nil - } - - f.args = make([]string, 0, len(arguments)) - - set := func(flag *Flag, value string) error { - return f.Set(flag.Name, value) - } - - err := f.parseArgs(arguments, set) - if err != nil { - switch f.errorHandling { - case ContinueOnError: - return err - case ExitOnError: - fmt.Println(err) - os.Exit(2) - case PanicOnError: - panic(err) - } - } - return nil -} - -type parseFunc func(flag *Flag, value string) error - -// ParseAll parses flag definitions from the argument list, which should not -// include the command name. The arguments for fn are flag and value. Must be -// called after all flags in the FlagSet are defined and before flags are -// accessed by the program. The return value will be ErrHelp if -help was set -// but not defined. -func (f *FlagSet) ParseAll(arguments []string, fn func(flag *Flag, value string) error) error { - f.parsed = true - f.args = make([]string, 0, len(arguments)) - - err := f.parseArgs(arguments, fn) - if err != nil { - switch f.errorHandling { - case ContinueOnError: - return err - case ExitOnError: - os.Exit(2) - case PanicOnError: - panic(err) - } - } - return nil -} - -// Parsed reports whether f.Parse has been called. -func (f *FlagSet) Parsed() bool { - return f.parsed -} - -// Parse parses the command-line flags from os.Args[1:]. Must be called -// after all flags are defined and before flags are accessed by the program. -func Parse() { - // Ignore errors; CommandLine is set for ExitOnError. - CommandLine.Parse(os.Args[1:]) -} - -// ParseAll parses the command-line flags from os.Args[1:] and called fn for each. -// The arguments for fn are flag and value. Must be called after all flags are -// defined and before flags are accessed by the program. -func ParseAll(fn func(flag *Flag, value string) error) { - // Ignore errors; CommandLine is set for ExitOnError. - CommandLine.ParseAll(os.Args[1:], fn) -} - -// SetInterspersed sets whether to support interspersed option/non-option arguments. -func SetInterspersed(interspersed bool) { - CommandLine.SetInterspersed(interspersed) -} - -// Parsed returns true if the command-line flags have been parsed. -func Parsed() bool { - return CommandLine.Parsed() -} - -// CommandLine is the default set of command-line flags, parsed from os.Args. -var CommandLine = NewFlagSet(os.Args[0], ExitOnError) - -// NewFlagSet returns a new, empty flag set with the specified name, -// error handling property and SortFlags set to true. -func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet { - f := &FlagSet{ - name: name, - errorHandling: errorHandling, - argsLenAtDash: -1, - interspersed: true, - SortFlags: true, - } - return f -} - -// SetInterspersed sets whether to support interspersed option/non-option arguments. -func (f *FlagSet) SetInterspersed(interspersed bool) { - f.interspersed = interspersed -} - -// Init sets the name and error handling property for a flag set. -// By default, the zero FlagSet uses an empty name and the -// ContinueOnError error handling policy. -func (f *FlagSet) Init(name string, errorHandling ErrorHandling) { - f.name = name - f.errorHandling = errorHandling - f.argsLenAtDash = -1 -} diff --git a/vendor/github.com/spf13/pflag/float32.go b/vendor/github.com/spf13/pflag/float32.go deleted file mode 100644 index a243f81f7..000000000 --- a/vendor/github.com/spf13/pflag/float32.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- float32 Value -type float32Value float32 - -func newFloat32Value(val float32, p *float32) *float32Value { - *p = val - return (*float32Value)(p) -} - -func (f *float32Value) Set(s string) error { - v, err := strconv.ParseFloat(s, 32) - *f = float32Value(v) - return err -} - -func (f *float32Value) Type() string { - return "float32" -} - -func (f *float32Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 32) } - -func float32Conv(sval string) (interface{}, error) { - v, err := strconv.ParseFloat(sval, 32) - if err != nil { - return 0, err - } - return float32(v), nil -} - -// GetFloat32 return the float32 value of a flag with the given name -func (f *FlagSet) GetFloat32(name string) (float32, error) { - val, err := f.getFlagType(name, "float32", float32Conv) - if err != nil { - return 0, err - } - return val.(float32), nil -} - -// Float32Var defines a float32 flag with specified name, default value, and usage string. -// The argument p points to a float32 variable in which to store the value of the flag. -func (f *FlagSet) Float32Var(p *float32, name string, value float32, usage string) { - f.VarP(newFloat32Value(value, p), name, "", usage) -} - -// Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Float32VarP(p *float32, name, shorthand string, value float32, usage string) { - f.VarP(newFloat32Value(value, p), name, shorthand, usage) -} - -// Float32Var defines a float32 flag with specified name, default value, and usage string. -// The argument p points to a float32 variable in which to store the value of the flag. -func Float32Var(p *float32, name string, value float32, usage string) { - CommandLine.VarP(newFloat32Value(value, p), name, "", usage) -} - -// Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash. -func Float32VarP(p *float32, name, shorthand string, value float32, usage string) { - CommandLine.VarP(newFloat32Value(value, p), name, shorthand, usage) -} - -// Float32 defines a float32 flag with specified name, default value, and usage string. -// The return value is the address of a float32 variable that stores the value of the flag. -func (f *FlagSet) Float32(name string, value float32, usage string) *float32 { - p := new(float32) - f.Float32VarP(p, name, "", value, usage) - return p -} - -// Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Float32P(name, shorthand string, value float32, usage string) *float32 { - p := new(float32) - f.Float32VarP(p, name, shorthand, value, usage) - return p -} - -// Float32 defines a float32 flag with specified name, default value, and usage string. -// The return value is the address of a float32 variable that stores the value of the flag. -func Float32(name string, value float32, usage string) *float32 { - return CommandLine.Float32P(name, "", value, usage) -} - -// Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash. -func Float32P(name, shorthand string, value float32, usage string) *float32 { - return CommandLine.Float32P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/float64.go b/vendor/github.com/spf13/pflag/float64.go deleted file mode 100644 index 04b5492a7..000000000 --- a/vendor/github.com/spf13/pflag/float64.go +++ /dev/null @@ -1,84 +0,0 @@ -package pflag - -import "strconv" - -// -- float64 Value -type float64Value float64 - -func newFloat64Value(val float64, p *float64) *float64Value { - *p = val - return (*float64Value)(p) -} - -func (f *float64Value) Set(s string) error { - v, err := strconv.ParseFloat(s, 64) - *f = float64Value(v) - return err -} - -func (f *float64Value) Type() string { - return "float64" -} - -func (f *float64Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 64) } - -func float64Conv(sval string) (interface{}, error) { - return strconv.ParseFloat(sval, 64) -} - -// GetFloat64 return the float64 value of a flag with the given name -func (f *FlagSet) GetFloat64(name string) (float64, error) { - val, err := f.getFlagType(name, "float64", float64Conv) - if err != nil { - return 0, err - } - return val.(float64), nil -} - -// Float64Var defines a float64 flag with specified name, default value, and usage string. -// The argument p points to a float64 variable in which to store the value of the flag. -func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) { - f.VarP(newFloat64Value(value, p), name, "", usage) -} - -// Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Float64VarP(p *float64, name, shorthand string, value float64, usage string) { - f.VarP(newFloat64Value(value, p), name, shorthand, usage) -} - -// Float64Var defines a float64 flag with specified name, default value, and usage string. -// The argument p points to a float64 variable in which to store the value of the flag. -func Float64Var(p *float64, name string, value float64, usage string) { - CommandLine.VarP(newFloat64Value(value, p), name, "", usage) -} - -// Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash. -func Float64VarP(p *float64, name, shorthand string, value float64, usage string) { - CommandLine.VarP(newFloat64Value(value, p), name, shorthand, usage) -} - -// Float64 defines a float64 flag with specified name, default value, and usage string. -// The return value is the address of a float64 variable that stores the value of the flag. -func (f *FlagSet) Float64(name string, value float64, usage string) *float64 { - p := new(float64) - f.Float64VarP(p, name, "", value, usage) - return p -} - -// Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Float64P(name, shorthand string, value float64, usage string) *float64 { - p := new(float64) - f.Float64VarP(p, name, shorthand, value, usage) - return p -} - -// Float64 defines a float64 flag with specified name, default value, and usage string. -// The return value is the address of a float64 variable that stores the value of the flag. -func Float64(name string, value float64, usage string) *float64 { - return CommandLine.Float64P(name, "", value, usage) -} - -// Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash. -func Float64P(name, shorthand string, value float64, usage string) *float64 { - return CommandLine.Float64P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/golangflag.go b/vendor/github.com/spf13/pflag/golangflag.go deleted file mode 100644 index d3dd72b7f..000000000 --- a/vendor/github.com/spf13/pflag/golangflag.go +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pflag - -import ( - goflag "flag" - "reflect" - "strings" -) - -// flagValueWrapper implements pflag.Value around a flag.Value. The main -// difference here is the addition of the Type method that returns a string -// name of the type. As this is generally unknown, we approximate that with -// reflection. -type flagValueWrapper struct { - inner goflag.Value - flagType string -} - -// We are just copying the boolFlag interface out of goflag as that is what -// they use to decide if a flag should get "true" when no arg is given. -type goBoolFlag interface { - goflag.Value - IsBoolFlag() bool -} - -func wrapFlagValue(v goflag.Value) Value { - // If the flag.Value happens to also be a pflag.Value, just use it directly. - if pv, ok := v.(Value); ok { - return pv - } - - pv := &flagValueWrapper{ - inner: v, - } - - t := reflect.TypeOf(v) - if t.Kind() == reflect.Interface || t.Kind() == reflect.Ptr { - t = t.Elem() - } - - pv.flagType = strings.TrimSuffix(t.Name(), "Value") - return pv -} - -func (v *flagValueWrapper) String() string { - return v.inner.String() -} - -func (v *flagValueWrapper) Set(s string) error { - return v.inner.Set(s) -} - -func (v *flagValueWrapper) Type() string { - return v.flagType -} - -// PFlagFromGoFlag will return a *pflag.Flag given a *flag.Flag -// If the *flag.Flag.Name was a single character (ex: `v`) it will be accessiblei -// with both `-v` and `--v` in flags. If the golang flag was more than a single -// character (ex: `verbose`) it will only be accessible via `--verbose` -func PFlagFromGoFlag(goflag *goflag.Flag) *Flag { - // Remember the default value as a string; it won't change. - flag := &Flag{ - Name: goflag.Name, - Usage: goflag.Usage, - Value: wrapFlagValue(goflag.Value), - // Looks like golang flags don't set DefValue correctly :-( - //DefValue: goflag.DefValue, - DefValue: goflag.Value.String(), - } - // Ex: if the golang flag was -v, allow both -v and --v to work - if len(flag.Name) == 1 { - flag.Shorthand = flag.Name - } - if fv, ok := goflag.Value.(goBoolFlag); ok && fv.IsBoolFlag() { - flag.NoOptDefVal = "true" - } - return flag -} - -// AddGoFlag will add the given *flag.Flag to the pflag.FlagSet -func (f *FlagSet) AddGoFlag(goflag *goflag.Flag) { - if f.Lookup(goflag.Name) != nil { - return - } - newflag := PFlagFromGoFlag(goflag) - f.AddFlag(newflag) -} - -// AddGoFlagSet will add the given *flag.FlagSet to the pflag.FlagSet -func (f *FlagSet) AddGoFlagSet(newSet *goflag.FlagSet) { - if newSet == nil { - return - } - newSet.VisitAll(func(goflag *goflag.Flag) { - f.AddGoFlag(goflag) - }) - if f.addedGoFlagSets == nil { - f.addedGoFlagSets = make([]*goflag.FlagSet, 0) - } - f.addedGoFlagSets = append(f.addedGoFlagSets, newSet) -} diff --git a/vendor/github.com/spf13/pflag/int.go b/vendor/github.com/spf13/pflag/int.go deleted file mode 100644 index 1474b89df..000000000 --- a/vendor/github.com/spf13/pflag/int.go +++ /dev/null @@ -1,84 +0,0 @@ -package pflag - -import "strconv" - -// -- int Value -type intValue int - -func newIntValue(val int, p *int) *intValue { - *p = val - return (*intValue)(p) -} - -func (i *intValue) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 64) - *i = intValue(v) - return err -} - -func (i *intValue) Type() string { - return "int" -} - -func (i *intValue) String() string { return strconv.Itoa(int(*i)) } - -func intConv(sval string) (interface{}, error) { - return strconv.Atoi(sval) -} - -// GetInt return the int value of a flag with the given name -func (f *FlagSet) GetInt(name string) (int, error) { - val, err := f.getFlagType(name, "int", intConv) - if err != nil { - return 0, err - } - return val.(int), nil -} - -// IntVar defines an int flag with specified name, default value, and usage string. -// The argument p points to an int variable in which to store the value of the flag. -func (f *FlagSet) IntVar(p *int, name string, value int, usage string) { - f.VarP(newIntValue(value, p), name, "", usage) -} - -// IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IntVarP(p *int, name, shorthand string, value int, usage string) { - f.VarP(newIntValue(value, p), name, shorthand, usage) -} - -// IntVar defines an int flag with specified name, default value, and usage string. -// The argument p points to an int variable in which to store the value of the flag. -func IntVar(p *int, name string, value int, usage string) { - CommandLine.VarP(newIntValue(value, p), name, "", usage) -} - -// IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash. -func IntVarP(p *int, name, shorthand string, value int, usage string) { - CommandLine.VarP(newIntValue(value, p), name, shorthand, usage) -} - -// Int defines an int flag with specified name, default value, and usage string. -// The return value is the address of an int variable that stores the value of the flag. -func (f *FlagSet) Int(name string, value int, usage string) *int { - p := new(int) - f.IntVarP(p, name, "", value, usage) - return p -} - -// IntP is like Int, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IntP(name, shorthand string, value int, usage string) *int { - p := new(int) - f.IntVarP(p, name, shorthand, value, usage) - return p -} - -// Int defines an int flag with specified name, default value, and usage string. -// The return value is the address of an int variable that stores the value of the flag. -func Int(name string, value int, usage string) *int { - return CommandLine.IntP(name, "", value, usage) -} - -// IntP is like Int, but accepts a shorthand letter that can be used after a single dash. -func IntP(name, shorthand string, value int, usage string) *int { - return CommandLine.IntP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/int16.go b/vendor/github.com/spf13/pflag/int16.go deleted file mode 100644 index f1a01d05e..000000000 --- a/vendor/github.com/spf13/pflag/int16.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- int16 Value -type int16Value int16 - -func newInt16Value(val int16, p *int16) *int16Value { - *p = val - return (*int16Value)(p) -} - -func (i *int16Value) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 16) - *i = int16Value(v) - return err -} - -func (i *int16Value) Type() string { - return "int16" -} - -func (i *int16Value) String() string { return strconv.FormatInt(int64(*i), 10) } - -func int16Conv(sval string) (interface{}, error) { - v, err := strconv.ParseInt(sval, 0, 16) - if err != nil { - return 0, err - } - return int16(v), nil -} - -// GetInt16 returns the int16 value of a flag with the given name -func (f *FlagSet) GetInt16(name string) (int16, error) { - val, err := f.getFlagType(name, "int16", int16Conv) - if err != nil { - return 0, err - } - return val.(int16), nil -} - -// Int16Var defines an int16 flag with specified name, default value, and usage string. -// The argument p points to an int16 variable in which to store the value of the flag. -func (f *FlagSet) Int16Var(p *int16, name string, value int16, usage string) { - f.VarP(newInt16Value(value, p), name, "", usage) -} - -// Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int16VarP(p *int16, name, shorthand string, value int16, usage string) { - f.VarP(newInt16Value(value, p), name, shorthand, usage) -} - -// Int16Var defines an int16 flag with specified name, default value, and usage string. -// The argument p points to an int16 variable in which to store the value of the flag. -func Int16Var(p *int16, name string, value int16, usage string) { - CommandLine.VarP(newInt16Value(value, p), name, "", usage) -} - -// Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash. -func Int16VarP(p *int16, name, shorthand string, value int16, usage string) { - CommandLine.VarP(newInt16Value(value, p), name, shorthand, usage) -} - -// Int16 defines an int16 flag with specified name, default value, and usage string. -// The return value is the address of an int16 variable that stores the value of the flag. -func (f *FlagSet) Int16(name string, value int16, usage string) *int16 { - p := new(int16) - f.Int16VarP(p, name, "", value, usage) - return p -} - -// Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int16P(name, shorthand string, value int16, usage string) *int16 { - p := new(int16) - f.Int16VarP(p, name, shorthand, value, usage) - return p -} - -// Int16 defines an int16 flag with specified name, default value, and usage string. -// The return value is the address of an int16 variable that stores the value of the flag. -func Int16(name string, value int16, usage string) *int16 { - return CommandLine.Int16P(name, "", value, usage) -} - -// Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash. -func Int16P(name, shorthand string, value int16, usage string) *int16 { - return CommandLine.Int16P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/int32.go b/vendor/github.com/spf13/pflag/int32.go deleted file mode 100644 index 9b95944f0..000000000 --- a/vendor/github.com/spf13/pflag/int32.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- int32 Value -type int32Value int32 - -func newInt32Value(val int32, p *int32) *int32Value { - *p = val - return (*int32Value)(p) -} - -func (i *int32Value) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 32) - *i = int32Value(v) - return err -} - -func (i *int32Value) Type() string { - return "int32" -} - -func (i *int32Value) String() string { return strconv.FormatInt(int64(*i), 10) } - -func int32Conv(sval string) (interface{}, error) { - v, err := strconv.ParseInt(sval, 0, 32) - if err != nil { - return 0, err - } - return int32(v), nil -} - -// GetInt32 return the int32 value of a flag with the given name -func (f *FlagSet) GetInt32(name string) (int32, error) { - val, err := f.getFlagType(name, "int32", int32Conv) - if err != nil { - return 0, err - } - return val.(int32), nil -} - -// Int32Var defines an int32 flag with specified name, default value, and usage string. -// The argument p points to an int32 variable in which to store the value of the flag. -func (f *FlagSet) Int32Var(p *int32, name string, value int32, usage string) { - f.VarP(newInt32Value(value, p), name, "", usage) -} - -// Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int32VarP(p *int32, name, shorthand string, value int32, usage string) { - f.VarP(newInt32Value(value, p), name, shorthand, usage) -} - -// Int32Var defines an int32 flag with specified name, default value, and usage string. -// The argument p points to an int32 variable in which to store the value of the flag. -func Int32Var(p *int32, name string, value int32, usage string) { - CommandLine.VarP(newInt32Value(value, p), name, "", usage) -} - -// Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash. -func Int32VarP(p *int32, name, shorthand string, value int32, usage string) { - CommandLine.VarP(newInt32Value(value, p), name, shorthand, usage) -} - -// Int32 defines an int32 flag with specified name, default value, and usage string. -// The return value is the address of an int32 variable that stores the value of the flag. -func (f *FlagSet) Int32(name string, value int32, usage string) *int32 { - p := new(int32) - f.Int32VarP(p, name, "", value, usage) - return p -} - -// Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int32P(name, shorthand string, value int32, usage string) *int32 { - p := new(int32) - f.Int32VarP(p, name, shorthand, value, usage) - return p -} - -// Int32 defines an int32 flag with specified name, default value, and usage string. -// The return value is the address of an int32 variable that stores the value of the flag. -func Int32(name string, value int32, usage string) *int32 { - return CommandLine.Int32P(name, "", value, usage) -} - -// Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash. -func Int32P(name, shorthand string, value int32, usage string) *int32 { - return CommandLine.Int32P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/int64.go b/vendor/github.com/spf13/pflag/int64.go deleted file mode 100644 index 0026d781d..000000000 --- a/vendor/github.com/spf13/pflag/int64.go +++ /dev/null @@ -1,84 +0,0 @@ -package pflag - -import "strconv" - -// -- int64 Value -type int64Value int64 - -func newInt64Value(val int64, p *int64) *int64Value { - *p = val - return (*int64Value)(p) -} - -func (i *int64Value) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 64) - *i = int64Value(v) - return err -} - -func (i *int64Value) Type() string { - return "int64" -} - -func (i *int64Value) String() string { return strconv.FormatInt(int64(*i), 10) } - -func int64Conv(sval string) (interface{}, error) { - return strconv.ParseInt(sval, 0, 64) -} - -// GetInt64 return the int64 value of a flag with the given name -func (f *FlagSet) GetInt64(name string) (int64, error) { - val, err := f.getFlagType(name, "int64", int64Conv) - if err != nil { - return 0, err - } - return val.(int64), nil -} - -// Int64Var defines an int64 flag with specified name, default value, and usage string. -// The argument p points to an int64 variable in which to store the value of the flag. -func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) { - f.VarP(newInt64Value(value, p), name, "", usage) -} - -// Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int64VarP(p *int64, name, shorthand string, value int64, usage string) { - f.VarP(newInt64Value(value, p), name, shorthand, usage) -} - -// Int64Var defines an int64 flag with specified name, default value, and usage string. -// The argument p points to an int64 variable in which to store the value of the flag. -func Int64Var(p *int64, name string, value int64, usage string) { - CommandLine.VarP(newInt64Value(value, p), name, "", usage) -} - -// Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash. -func Int64VarP(p *int64, name, shorthand string, value int64, usage string) { - CommandLine.VarP(newInt64Value(value, p), name, shorthand, usage) -} - -// Int64 defines an int64 flag with specified name, default value, and usage string. -// The return value is the address of an int64 variable that stores the value of the flag. -func (f *FlagSet) Int64(name string, value int64, usage string) *int64 { - p := new(int64) - f.Int64VarP(p, name, "", value, usage) - return p -} - -// Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int64P(name, shorthand string, value int64, usage string) *int64 { - p := new(int64) - f.Int64VarP(p, name, shorthand, value, usage) - return p -} - -// Int64 defines an int64 flag with specified name, default value, and usage string. -// The return value is the address of an int64 variable that stores the value of the flag. -func Int64(name string, value int64, usage string) *int64 { - return CommandLine.Int64P(name, "", value, usage) -} - -// Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash. -func Int64P(name, shorthand string, value int64, usage string) *int64 { - return CommandLine.Int64P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/int8.go b/vendor/github.com/spf13/pflag/int8.go deleted file mode 100644 index 4da92228e..000000000 --- a/vendor/github.com/spf13/pflag/int8.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- int8 Value -type int8Value int8 - -func newInt8Value(val int8, p *int8) *int8Value { - *p = val - return (*int8Value)(p) -} - -func (i *int8Value) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 8) - *i = int8Value(v) - return err -} - -func (i *int8Value) Type() string { - return "int8" -} - -func (i *int8Value) String() string { return strconv.FormatInt(int64(*i), 10) } - -func int8Conv(sval string) (interface{}, error) { - v, err := strconv.ParseInt(sval, 0, 8) - if err != nil { - return 0, err - } - return int8(v), nil -} - -// GetInt8 return the int8 value of a flag with the given name -func (f *FlagSet) GetInt8(name string) (int8, error) { - val, err := f.getFlagType(name, "int8", int8Conv) - if err != nil { - return 0, err - } - return val.(int8), nil -} - -// Int8Var defines an int8 flag with specified name, default value, and usage string. -// The argument p points to an int8 variable in which to store the value of the flag. -func (f *FlagSet) Int8Var(p *int8, name string, value int8, usage string) { - f.VarP(newInt8Value(value, p), name, "", usage) -} - -// Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int8VarP(p *int8, name, shorthand string, value int8, usage string) { - f.VarP(newInt8Value(value, p), name, shorthand, usage) -} - -// Int8Var defines an int8 flag with specified name, default value, and usage string. -// The argument p points to an int8 variable in which to store the value of the flag. -func Int8Var(p *int8, name string, value int8, usage string) { - CommandLine.VarP(newInt8Value(value, p), name, "", usage) -} - -// Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash. -func Int8VarP(p *int8, name, shorthand string, value int8, usage string) { - CommandLine.VarP(newInt8Value(value, p), name, shorthand, usage) -} - -// Int8 defines an int8 flag with specified name, default value, and usage string. -// The return value is the address of an int8 variable that stores the value of the flag. -func (f *FlagSet) Int8(name string, value int8, usage string) *int8 { - p := new(int8) - f.Int8VarP(p, name, "", value, usage) - return p -} - -// Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int8P(name, shorthand string, value int8, usage string) *int8 { - p := new(int8) - f.Int8VarP(p, name, shorthand, value, usage) - return p -} - -// Int8 defines an int8 flag with specified name, default value, and usage string. -// The return value is the address of an int8 variable that stores the value of the flag. -func Int8(name string, value int8, usage string) *int8 { - return CommandLine.Int8P(name, "", value, usage) -} - -// Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash. -func Int8P(name, shorthand string, value int8, usage string) *int8 { - return CommandLine.Int8P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/int_slice.go b/vendor/github.com/spf13/pflag/int_slice.go deleted file mode 100644 index 1e7c9edde..000000000 --- a/vendor/github.com/spf13/pflag/int_slice.go +++ /dev/null @@ -1,128 +0,0 @@ -package pflag - -import ( - "fmt" - "strconv" - "strings" -) - -// -- intSlice Value -type intSliceValue struct { - value *[]int - changed bool -} - -func newIntSliceValue(val []int, p *[]int) *intSliceValue { - isv := new(intSliceValue) - isv.value = p - *isv.value = val - return isv -} - -func (s *intSliceValue) Set(val string) error { - ss := strings.Split(val, ",") - out := make([]int, len(ss)) - for i, d := range ss { - var err error - out[i], err = strconv.Atoi(d) - if err != nil { - return err - } - - } - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - s.changed = true - return nil -} - -func (s *intSliceValue) Type() string { - return "intSlice" -} - -func (s *intSliceValue) String() string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = fmt.Sprintf("%d", d) - } - return "[" + strings.Join(out, ",") + "]" -} - -func intSliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Empty string would cause a slice with one (empty) entry - if len(val) == 0 { - return []int{}, nil - } - ss := strings.Split(val, ",") - out := make([]int, len(ss)) - for i, d := range ss { - var err error - out[i], err = strconv.Atoi(d) - if err != nil { - return nil, err - } - - } - return out, nil -} - -// GetIntSlice return the []int value of a flag with the given name -func (f *FlagSet) GetIntSlice(name string) ([]int, error) { - val, err := f.getFlagType(name, "intSlice", intSliceConv) - if err != nil { - return []int{}, err - } - return val.([]int), nil -} - -// IntSliceVar defines a intSlice flag with specified name, default value, and usage string. -// The argument p points to a []int variable in which to store the value of the flag. -func (f *FlagSet) IntSliceVar(p *[]int, name string, value []int, usage string) { - f.VarP(newIntSliceValue(value, p), name, "", usage) -} - -// IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IntSliceVarP(p *[]int, name, shorthand string, value []int, usage string) { - f.VarP(newIntSliceValue(value, p), name, shorthand, usage) -} - -// IntSliceVar defines a int[] flag with specified name, default value, and usage string. -// The argument p points to a int[] variable in which to store the value of the flag. -func IntSliceVar(p *[]int, name string, value []int, usage string) { - CommandLine.VarP(newIntSliceValue(value, p), name, "", usage) -} - -// IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash. -func IntSliceVarP(p *[]int, name, shorthand string, value []int, usage string) { - CommandLine.VarP(newIntSliceValue(value, p), name, shorthand, usage) -} - -// IntSlice defines a []int flag with specified name, default value, and usage string. -// The return value is the address of a []int variable that stores the value of the flag. -func (f *FlagSet) IntSlice(name string, value []int, usage string) *[]int { - p := []int{} - f.IntSliceVarP(&p, name, "", value, usage) - return &p -} - -// IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IntSliceP(name, shorthand string, value []int, usage string) *[]int { - p := []int{} - f.IntSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// IntSlice defines a []int flag with specified name, default value, and usage string. -// The return value is the address of a []int variable that stores the value of the flag. -func IntSlice(name string, value []int, usage string) *[]int { - return CommandLine.IntSliceP(name, "", value, usage) -} - -// IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash. -func IntSliceP(name, shorthand string, value []int, usage string) *[]int { - return CommandLine.IntSliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/ip.go b/vendor/github.com/spf13/pflag/ip.go deleted file mode 100644 index 3d414ba69..000000000 --- a/vendor/github.com/spf13/pflag/ip.go +++ /dev/null @@ -1,94 +0,0 @@ -package pflag - -import ( - "fmt" - "net" - "strings" -) - -// -- net.IP value -type ipValue net.IP - -func newIPValue(val net.IP, p *net.IP) *ipValue { - *p = val - return (*ipValue)(p) -} - -func (i *ipValue) String() string { return net.IP(*i).String() } -func (i *ipValue) Set(s string) error { - ip := net.ParseIP(strings.TrimSpace(s)) - if ip == nil { - return fmt.Errorf("failed to parse IP: %q", s) - } - *i = ipValue(ip) - return nil -} - -func (i *ipValue) Type() string { - return "ip" -} - -func ipConv(sval string) (interface{}, error) { - ip := net.ParseIP(sval) - if ip != nil { - return ip, nil - } - return nil, fmt.Errorf("invalid string being converted to IP address: %s", sval) -} - -// GetIP return the net.IP value of a flag with the given name -func (f *FlagSet) GetIP(name string) (net.IP, error) { - val, err := f.getFlagType(name, "ip", ipConv) - if err != nil { - return nil, err - } - return val.(net.IP), nil -} - -// IPVar defines an net.IP flag with specified name, default value, and usage string. -// The argument p points to an net.IP variable in which to store the value of the flag. -func (f *FlagSet) IPVar(p *net.IP, name string, value net.IP, usage string) { - f.VarP(newIPValue(value, p), name, "", usage) -} - -// IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) { - f.VarP(newIPValue(value, p), name, shorthand, usage) -} - -// IPVar defines an net.IP flag with specified name, default value, and usage string. -// The argument p points to an net.IP variable in which to store the value of the flag. -func IPVar(p *net.IP, name string, value net.IP, usage string) { - CommandLine.VarP(newIPValue(value, p), name, "", usage) -} - -// IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash. -func IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) { - CommandLine.VarP(newIPValue(value, p), name, shorthand, usage) -} - -// IP defines an net.IP flag with specified name, default value, and usage string. -// The return value is the address of an net.IP variable that stores the value of the flag. -func (f *FlagSet) IP(name string, value net.IP, usage string) *net.IP { - p := new(net.IP) - f.IPVarP(p, name, "", value, usage) - return p -} - -// IPP is like IP, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPP(name, shorthand string, value net.IP, usage string) *net.IP { - p := new(net.IP) - f.IPVarP(p, name, shorthand, value, usage) - return p -} - -// IP defines an net.IP flag with specified name, default value, and usage string. -// The return value is the address of an net.IP variable that stores the value of the flag. -func IP(name string, value net.IP, usage string) *net.IP { - return CommandLine.IPP(name, "", value, usage) -} - -// IPP is like IP, but accepts a shorthand letter that can be used after a single dash. -func IPP(name, shorthand string, value net.IP, usage string) *net.IP { - return CommandLine.IPP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/ip_slice.go b/vendor/github.com/spf13/pflag/ip_slice.go deleted file mode 100644 index 7dd196fe3..000000000 --- a/vendor/github.com/spf13/pflag/ip_slice.go +++ /dev/null @@ -1,148 +0,0 @@ -package pflag - -import ( - "fmt" - "io" - "net" - "strings" -) - -// -- ipSlice Value -type ipSliceValue struct { - value *[]net.IP - changed bool -} - -func newIPSliceValue(val []net.IP, p *[]net.IP) *ipSliceValue { - ipsv := new(ipSliceValue) - ipsv.value = p - *ipsv.value = val - return ipsv -} - -// Set converts, and assigns, the comma-separated IP argument string representation as the []net.IP value of this flag. -// If Set is called on a flag that already has a []net.IP assigned, the newly converted values will be appended. -func (s *ipSliceValue) Set(val string) error { - - // remove all quote characters - rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "") - - // read flag arguments with CSV parser - ipStrSlice, err := readAsCSV(rmQuote.Replace(val)) - if err != nil && err != io.EOF { - return err - } - - // parse ip values into slice - out := make([]net.IP, 0, len(ipStrSlice)) - for _, ipStr := range ipStrSlice { - ip := net.ParseIP(strings.TrimSpace(ipStr)) - if ip == nil { - return fmt.Errorf("invalid string being converted to IP address: %s", ipStr) - } - out = append(out, ip) - } - - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - - s.changed = true - - return nil -} - -// Type returns a string that uniquely represents this flag's type. -func (s *ipSliceValue) Type() string { - return "ipSlice" -} - -// String defines a "native" format for this net.IP slice flag value. -func (s *ipSliceValue) String() string { - - ipStrSlice := make([]string, len(*s.value)) - for i, ip := range *s.value { - ipStrSlice[i] = ip.String() - } - - out, _ := writeAsCSV(ipStrSlice) - - return "[" + out + "]" -} - -func ipSliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Emtpy string would cause a slice with one (empty) entry - if len(val) == 0 { - return []net.IP{}, nil - } - ss := strings.Split(val, ",") - out := make([]net.IP, len(ss)) - for i, sval := range ss { - ip := net.ParseIP(strings.TrimSpace(sval)) - if ip == nil { - return nil, fmt.Errorf("invalid string being converted to IP address: %s", sval) - } - out[i] = ip - } - return out, nil -} - -// GetIPSlice returns the []net.IP value of a flag with the given name -func (f *FlagSet) GetIPSlice(name string) ([]net.IP, error) { - val, err := f.getFlagType(name, "ipSlice", ipSliceConv) - if err != nil { - return []net.IP{}, err - } - return val.([]net.IP), nil -} - -// IPSliceVar defines a ipSlice flag with specified name, default value, and usage string. -// The argument p points to a []net.IP variable in which to store the value of the flag. -func (f *FlagSet) IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) { - f.VarP(newIPSliceValue(value, p), name, "", usage) -} - -// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) { - f.VarP(newIPSliceValue(value, p), name, shorthand, usage) -} - -// IPSliceVar defines a []net.IP flag with specified name, default value, and usage string. -// The argument p points to a []net.IP variable in which to store the value of the flag. -func IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) { - CommandLine.VarP(newIPSliceValue(value, p), name, "", usage) -} - -// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash. -func IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) { - CommandLine.VarP(newIPSliceValue(value, p), name, shorthand, usage) -} - -// IPSlice defines a []net.IP flag with specified name, default value, and usage string. -// The return value is the address of a []net.IP variable that stores the value of that flag. -func (f *FlagSet) IPSlice(name string, value []net.IP, usage string) *[]net.IP { - p := []net.IP{} - f.IPSliceVarP(&p, name, "", value, usage) - return &p -} - -// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP { - p := []net.IP{} - f.IPSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// IPSlice defines a []net.IP flag with specified name, default value, and usage string. -// The return value is the address of a []net.IP variable that stores the value of the flag. -func IPSlice(name string, value []net.IP, usage string) *[]net.IP { - return CommandLine.IPSliceP(name, "", value, usage) -} - -// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash. -func IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP { - return CommandLine.IPSliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/ipmask.go b/vendor/github.com/spf13/pflag/ipmask.go deleted file mode 100644 index 5bd44bd21..000000000 --- a/vendor/github.com/spf13/pflag/ipmask.go +++ /dev/null @@ -1,122 +0,0 @@ -package pflag - -import ( - "fmt" - "net" - "strconv" -) - -// -- net.IPMask value -type ipMaskValue net.IPMask - -func newIPMaskValue(val net.IPMask, p *net.IPMask) *ipMaskValue { - *p = val - return (*ipMaskValue)(p) -} - -func (i *ipMaskValue) String() string { return net.IPMask(*i).String() } -func (i *ipMaskValue) Set(s string) error { - ip := ParseIPv4Mask(s) - if ip == nil { - return fmt.Errorf("failed to parse IP mask: %q", s) - } - *i = ipMaskValue(ip) - return nil -} - -func (i *ipMaskValue) Type() string { - return "ipMask" -} - -// ParseIPv4Mask written in IP form (e.g. 255.255.255.0). -// This function should really belong to the net package. -func ParseIPv4Mask(s string) net.IPMask { - mask := net.ParseIP(s) - if mask == nil { - if len(s) != 8 { - return nil - } - // net.IPMask.String() actually outputs things like ffffff00 - // so write a horrible parser for that as well :-( - m := []int{} - for i := 0; i < 4; i++ { - b := "0x" + s[2*i:2*i+2] - d, err := strconv.ParseInt(b, 0, 0) - if err != nil { - return nil - } - m = append(m, int(d)) - } - s := fmt.Sprintf("%d.%d.%d.%d", m[0], m[1], m[2], m[3]) - mask = net.ParseIP(s) - if mask == nil { - return nil - } - } - return net.IPv4Mask(mask[12], mask[13], mask[14], mask[15]) -} - -func parseIPv4Mask(sval string) (interface{}, error) { - mask := ParseIPv4Mask(sval) - if mask == nil { - return nil, fmt.Errorf("unable to parse %s as net.IPMask", sval) - } - return mask, nil -} - -// GetIPv4Mask return the net.IPv4Mask value of a flag with the given name -func (f *FlagSet) GetIPv4Mask(name string) (net.IPMask, error) { - val, err := f.getFlagType(name, "ipMask", parseIPv4Mask) - if err != nil { - return nil, err - } - return val.(net.IPMask), nil -} - -// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string. -// The argument p points to an net.IPMask variable in which to store the value of the flag. -func (f *FlagSet) IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) { - f.VarP(newIPMaskValue(value, p), name, "", usage) -} - -// IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) { - f.VarP(newIPMaskValue(value, p), name, shorthand, usage) -} - -// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string. -// The argument p points to an net.IPMask variable in which to store the value of the flag. -func IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) { - CommandLine.VarP(newIPMaskValue(value, p), name, "", usage) -} - -// IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash. -func IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) { - CommandLine.VarP(newIPMaskValue(value, p), name, shorthand, usage) -} - -// IPMask defines an net.IPMask flag with specified name, default value, and usage string. -// The return value is the address of an net.IPMask variable that stores the value of the flag. -func (f *FlagSet) IPMask(name string, value net.IPMask, usage string) *net.IPMask { - p := new(net.IPMask) - f.IPMaskVarP(p, name, "", value, usage) - return p -} - -// IPMaskP is like IPMask, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask { - p := new(net.IPMask) - f.IPMaskVarP(p, name, shorthand, value, usage) - return p -} - -// IPMask defines an net.IPMask flag with specified name, default value, and usage string. -// The return value is the address of an net.IPMask variable that stores the value of the flag. -func IPMask(name string, value net.IPMask, usage string) *net.IPMask { - return CommandLine.IPMaskP(name, "", value, usage) -} - -// IPMaskP is like IP, but accepts a shorthand letter that can be used after a single dash. -func IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask { - return CommandLine.IPMaskP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/ipnet.go b/vendor/github.com/spf13/pflag/ipnet.go deleted file mode 100644 index e2c1b8bcd..000000000 --- a/vendor/github.com/spf13/pflag/ipnet.go +++ /dev/null @@ -1,98 +0,0 @@ -package pflag - -import ( - "fmt" - "net" - "strings" -) - -// IPNet adapts net.IPNet for use as a flag. -type ipNetValue net.IPNet - -func (ipnet ipNetValue) String() string { - n := net.IPNet(ipnet) - return n.String() -} - -func (ipnet *ipNetValue) Set(value string) error { - _, n, err := net.ParseCIDR(strings.TrimSpace(value)) - if err != nil { - return err - } - *ipnet = ipNetValue(*n) - return nil -} - -func (*ipNetValue) Type() string { - return "ipNet" -} - -func newIPNetValue(val net.IPNet, p *net.IPNet) *ipNetValue { - *p = val - return (*ipNetValue)(p) -} - -func ipNetConv(sval string) (interface{}, error) { - _, n, err := net.ParseCIDR(strings.TrimSpace(sval)) - if err == nil { - return *n, nil - } - return nil, fmt.Errorf("invalid string being converted to IPNet: %s", sval) -} - -// GetIPNet return the net.IPNet value of a flag with the given name -func (f *FlagSet) GetIPNet(name string) (net.IPNet, error) { - val, err := f.getFlagType(name, "ipNet", ipNetConv) - if err != nil { - return net.IPNet{}, err - } - return val.(net.IPNet), nil -} - -// IPNetVar defines an net.IPNet flag with specified name, default value, and usage string. -// The argument p points to an net.IPNet variable in which to store the value of the flag. -func (f *FlagSet) IPNetVar(p *net.IPNet, name string, value net.IPNet, usage string) { - f.VarP(newIPNetValue(value, p), name, "", usage) -} - -// IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPNetVarP(p *net.IPNet, name, shorthand string, value net.IPNet, usage string) { - f.VarP(newIPNetValue(value, p), name, shorthand, usage) -} - -// IPNetVar defines an net.IPNet flag with specified name, default value, and usage string. -// The argument p points to an net.IPNet variable in which to store the value of the flag. -func IPNetVar(p *net.IPNet, name string, value net.IPNet, usage string) { - CommandLine.VarP(newIPNetValue(value, p), name, "", usage) -} - -// IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash. -func IPNetVarP(p *net.IPNet, name, shorthand string, value net.IPNet, usage string) { - CommandLine.VarP(newIPNetValue(value, p), name, shorthand, usage) -} - -// IPNet defines an net.IPNet flag with specified name, default value, and usage string. -// The return value is the address of an net.IPNet variable that stores the value of the flag. -func (f *FlagSet) IPNet(name string, value net.IPNet, usage string) *net.IPNet { - p := new(net.IPNet) - f.IPNetVarP(p, name, "", value, usage) - return p -} - -// IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPNetP(name, shorthand string, value net.IPNet, usage string) *net.IPNet { - p := new(net.IPNet) - f.IPNetVarP(p, name, shorthand, value, usage) - return p -} - -// IPNet defines an net.IPNet flag with specified name, default value, and usage string. -// The return value is the address of an net.IPNet variable that stores the value of the flag. -func IPNet(name string, value net.IPNet, usage string) *net.IPNet { - return CommandLine.IPNetP(name, "", value, usage) -} - -// IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash. -func IPNetP(name, shorthand string, value net.IPNet, usage string) *net.IPNet { - return CommandLine.IPNetP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/string.go b/vendor/github.com/spf13/pflag/string.go deleted file mode 100644 index 04e0a26ff..000000000 --- a/vendor/github.com/spf13/pflag/string.go +++ /dev/null @@ -1,80 +0,0 @@ -package pflag - -// -- string Value -type stringValue string - -func newStringValue(val string, p *string) *stringValue { - *p = val - return (*stringValue)(p) -} - -func (s *stringValue) Set(val string) error { - *s = stringValue(val) - return nil -} -func (s *stringValue) Type() string { - return "string" -} - -func (s *stringValue) String() string { return string(*s) } - -func stringConv(sval string) (interface{}, error) { - return sval, nil -} - -// GetString return the string value of a flag with the given name -func (f *FlagSet) GetString(name string) (string, error) { - val, err := f.getFlagType(name, "string", stringConv) - if err != nil { - return "", err - } - return val.(string), nil -} - -// StringVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a string variable in which to store the value of the flag. -func (f *FlagSet) StringVar(p *string, name string, value string, usage string) { - f.VarP(newStringValue(value, p), name, "", usage) -} - -// StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringVarP(p *string, name, shorthand string, value string, usage string) { - f.VarP(newStringValue(value, p), name, shorthand, usage) -} - -// StringVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a string variable in which to store the value of the flag. -func StringVar(p *string, name string, value string, usage string) { - CommandLine.VarP(newStringValue(value, p), name, "", usage) -} - -// StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash. -func StringVarP(p *string, name, shorthand string, value string, usage string) { - CommandLine.VarP(newStringValue(value, p), name, shorthand, usage) -} - -// String defines a string flag with specified name, default value, and usage string. -// The return value is the address of a string variable that stores the value of the flag. -func (f *FlagSet) String(name string, value string, usage string) *string { - p := new(string) - f.StringVarP(p, name, "", value, usage) - return p -} - -// StringP is like String, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringP(name, shorthand string, value string, usage string) *string { - p := new(string) - f.StringVarP(p, name, shorthand, value, usage) - return p -} - -// String defines a string flag with specified name, default value, and usage string. -// The return value is the address of a string variable that stores the value of the flag. -func String(name string, value string, usage string) *string { - return CommandLine.StringP(name, "", value, usage) -} - -// StringP is like String, but accepts a shorthand letter that can be used after a single dash. -func StringP(name, shorthand string, value string, usage string) *string { - return CommandLine.StringP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/string_array.go b/vendor/github.com/spf13/pflag/string_array.go deleted file mode 100644 index fa7bc6018..000000000 --- a/vendor/github.com/spf13/pflag/string_array.go +++ /dev/null @@ -1,103 +0,0 @@ -package pflag - -// -- stringArray Value -type stringArrayValue struct { - value *[]string - changed bool -} - -func newStringArrayValue(val []string, p *[]string) *stringArrayValue { - ssv := new(stringArrayValue) - ssv.value = p - *ssv.value = val - return ssv -} - -func (s *stringArrayValue) Set(val string) error { - if !s.changed { - *s.value = []string{val} - s.changed = true - } else { - *s.value = append(*s.value, val) - } - return nil -} - -func (s *stringArrayValue) Type() string { - return "stringArray" -} - -func (s *stringArrayValue) String() string { - str, _ := writeAsCSV(*s.value) - return "[" + str + "]" -} - -func stringArrayConv(sval string) (interface{}, error) { - sval = sval[1 : len(sval)-1] - // An empty string would cause a array with one (empty) string - if len(sval) == 0 { - return []string{}, nil - } - return readAsCSV(sval) -} - -// GetStringArray return the []string value of a flag with the given name -func (f *FlagSet) GetStringArray(name string) ([]string, error) { - val, err := f.getFlagType(name, "stringArray", stringArrayConv) - if err != nil { - return []string{}, err - } - return val.([]string), nil -} - -// StringArrayVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a []string variable in which to store the values of the multiple flags. -// The value of each argument will not try to be separated by comma. Use a StringSlice for that. -func (f *FlagSet) StringArrayVar(p *[]string, name string, value []string, usage string) { - f.VarP(newStringArrayValue(value, p), name, "", usage) -} - -// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) { - f.VarP(newStringArrayValue(value, p), name, shorthand, usage) -} - -// StringArrayVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a []string variable in which to store the value of the flag. -// The value of each argument will not try to be separated by comma. Use a StringSlice for that. -func StringArrayVar(p *[]string, name string, value []string, usage string) { - CommandLine.VarP(newStringArrayValue(value, p), name, "", usage) -} - -// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash. -func StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) { - CommandLine.VarP(newStringArrayValue(value, p), name, shorthand, usage) -} - -// StringArray defines a string flag with specified name, default value, and usage string. -// The return value is the address of a []string variable that stores the value of the flag. -// The value of each argument will not try to be separated by comma. Use a StringSlice for that. -func (f *FlagSet) StringArray(name string, value []string, usage string) *[]string { - p := []string{} - f.StringArrayVarP(&p, name, "", value, usage) - return &p -} - -// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringArrayP(name, shorthand string, value []string, usage string) *[]string { - p := []string{} - f.StringArrayVarP(&p, name, shorthand, value, usage) - return &p -} - -// StringArray defines a string flag with specified name, default value, and usage string. -// The return value is the address of a []string variable that stores the value of the flag. -// The value of each argument will not try to be separated by comma. Use a StringSlice for that. -func StringArray(name string, value []string, usage string) *[]string { - return CommandLine.StringArrayP(name, "", value, usage) -} - -// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash. -func StringArrayP(name, shorthand string, value []string, usage string) *[]string { - return CommandLine.StringArrayP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/string_slice.go b/vendor/github.com/spf13/pflag/string_slice.go deleted file mode 100644 index 0cd3ccc08..000000000 --- a/vendor/github.com/spf13/pflag/string_slice.go +++ /dev/null @@ -1,149 +0,0 @@ -package pflag - -import ( - "bytes" - "encoding/csv" - "strings" -) - -// -- stringSlice Value -type stringSliceValue struct { - value *[]string - changed bool -} - -func newStringSliceValue(val []string, p *[]string) *stringSliceValue { - ssv := new(stringSliceValue) - ssv.value = p - *ssv.value = val - return ssv -} - -func readAsCSV(val string) ([]string, error) { - if val == "" { - return []string{}, nil - } - stringReader := strings.NewReader(val) - csvReader := csv.NewReader(stringReader) - return csvReader.Read() -} - -func writeAsCSV(vals []string) (string, error) { - b := &bytes.Buffer{} - w := csv.NewWriter(b) - err := w.Write(vals) - if err != nil { - return "", err - } - w.Flush() - return strings.TrimSuffix(b.String(), "\n"), nil -} - -func (s *stringSliceValue) Set(val string) error { - v, err := readAsCSV(val) - if err != nil { - return err - } - if !s.changed { - *s.value = v - } else { - *s.value = append(*s.value, v...) - } - s.changed = true - return nil -} - -func (s *stringSliceValue) Type() string { - return "stringSlice" -} - -func (s *stringSliceValue) String() string { - str, _ := writeAsCSV(*s.value) - return "[" + str + "]" -} - -func stringSliceConv(sval string) (interface{}, error) { - sval = sval[1 : len(sval)-1] - // An empty string would cause a slice with one (empty) string - if len(sval) == 0 { - return []string{}, nil - } - return readAsCSV(sval) -} - -// GetStringSlice return the []string value of a flag with the given name -func (f *FlagSet) GetStringSlice(name string) ([]string, error) { - val, err := f.getFlagType(name, "stringSlice", stringSliceConv) - if err != nil { - return []string{}, err - } - return val.([]string), nil -} - -// StringSliceVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a []string variable in which to store the value of the flag. -// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. -// For example: -// --ss="v1,v2" -ss="v3" -// will result in -// []string{"v1", "v2", "v3"} -func (f *FlagSet) StringSliceVar(p *[]string, name string, value []string, usage string) { - f.VarP(newStringSliceValue(value, p), name, "", usage) -} - -// StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringSliceVarP(p *[]string, name, shorthand string, value []string, usage string) { - f.VarP(newStringSliceValue(value, p), name, shorthand, usage) -} - -// StringSliceVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a []string variable in which to store the value of the flag. -// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. -// For example: -// --ss="v1,v2" -ss="v3" -// will result in -// []string{"v1", "v2", "v3"} -func StringSliceVar(p *[]string, name string, value []string, usage string) { - CommandLine.VarP(newStringSliceValue(value, p), name, "", usage) -} - -// StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash. -func StringSliceVarP(p *[]string, name, shorthand string, value []string, usage string) { - CommandLine.VarP(newStringSliceValue(value, p), name, shorthand, usage) -} - -// StringSlice defines a string flag with specified name, default value, and usage string. -// The return value is the address of a []string variable that stores the value of the flag. -// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. -// For example: -// --ss="v1,v2" -ss="v3" -// will result in -// []string{"v1", "v2", "v3"} -func (f *FlagSet) StringSlice(name string, value []string, usage string) *[]string { - p := []string{} - f.StringSliceVarP(&p, name, "", value, usage) - return &p -} - -// StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringSliceP(name, shorthand string, value []string, usage string) *[]string { - p := []string{} - f.StringSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// StringSlice defines a string flag with specified name, default value, and usage string. -// The return value is the address of a []string variable that stores the value of the flag. -// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. -// For example: -// --ss="v1,v2" -ss="v3" -// will result in -// []string{"v1", "v2", "v3"} -func StringSlice(name string, value []string, usage string) *[]string { - return CommandLine.StringSliceP(name, "", value, usage) -} - -// StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash. -func StringSliceP(name, shorthand string, value []string, usage string) *[]string { - return CommandLine.StringSliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/uint.go b/vendor/github.com/spf13/pflag/uint.go deleted file mode 100644 index dcbc2b758..000000000 --- a/vendor/github.com/spf13/pflag/uint.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- uint Value -type uintValue uint - -func newUintValue(val uint, p *uint) *uintValue { - *p = val - return (*uintValue)(p) -} - -func (i *uintValue) Set(s string) error { - v, err := strconv.ParseUint(s, 0, 64) - *i = uintValue(v) - return err -} - -func (i *uintValue) Type() string { - return "uint" -} - -func (i *uintValue) String() string { return strconv.FormatUint(uint64(*i), 10) } - -func uintConv(sval string) (interface{}, error) { - v, err := strconv.ParseUint(sval, 0, 0) - if err != nil { - return 0, err - } - return uint(v), nil -} - -// GetUint return the uint value of a flag with the given name -func (f *FlagSet) GetUint(name string) (uint, error) { - val, err := f.getFlagType(name, "uint", uintConv) - if err != nil { - return 0, err - } - return val.(uint), nil -} - -// UintVar defines a uint flag with specified name, default value, and usage string. -// The argument p points to a uint variable in which to store the value of the flag. -func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) { - f.VarP(newUintValue(value, p), name, "", usage) -} - -// UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) UintVarP(p *uint, name, shorthand string, value uint, usage string) { - f.VarP(newUintValue(value, p), name, shorthand, usage) -} - -// UintVar defines a uint flag with specified name, default value, and usage string. -// The argument p points to a uint variable in which to store the value of the flag. -func UintVar(p *uint, name string, value uint, usage string) { - CommandLine.VarP(newUintValue(value, p), name, "", usage) -} - -// UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash. -func UintVarP(p *uint, name, shorthand string, value uint, usage string) { - CommandLine.VarP(newUintValue(value, p), name, shorthand, usage) -} - -// Uint defines a uint flag with specified name, default value, and usage string. -// The return value is the address of a uint variable that stores the value of the flag. -func (f *FlagSet) Uint(name string, value uint, usage string) *uint { - p := new(uint) - f.UintVarP(p, name, "", value, usage) - return p -} - -// UintP is like Uint, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) UintP(name, shorthand string, value uint, usage string) *uint { - p := new(uint) - f.UintVarP(p, name, shorthand, value, usage) - return p -} - -// Uint defines a uint flag with specified name, default value, and usage string. -// The return value is the address of a uint variable that stores the value of the flag. -func Uint(name string, value uint, usage string) *uint { - return CommandLine.UintP(name, "", value, usage) -} - -// UintP is like Uint, but accepts a shorthand letter that can be used after a single dash. -func UintP(name, shorthand string, value uint, usage string) *uint { - return CommandLine.UintP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/uint16.go b/vendor/github.com/spf13/pflag/uint16.go deleted file mode 100644 index 7e9914edd..000000000 --- a/vendor/github.com/spf13/pflag/uint16.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- uint16 value -type uint16Value uint16 - -func newUint16Value(val uint16, p *uint16) *uint16Value { - *p = val - return (*uint16Value)(p) -} - -func (i *uint16Value) Set(s string) error { - v, err := strconv.ParseUint(s, 0, 16) - *i = uint16Value(v) - return err -} - -func (i *uint16Value) Type() string { - return "uint16" -} - -func (i *uint16Value) String() string { return strconv.FormatUint(uint64(*i), 10) } - -func uint16Conv(sval string) (interface{}, error) { - v, err := strconv.ParseUint(sval, 0, 16) - if err != nil { - return 0, err - } - return uint16(v), nil -} - -// GetUint16 return the uint16 value of a flag with the given name -func (f *FlagSet) GetUint16(name string) (uint16, error) { - val, err := f.getFlagType(name, "uint16", uint16Conv) - if err != nil { - return 0, err - } - return val.(uint16), nil -} - -// Uint16Var defines a uint flag with specified name, default value, and usage string. -// The argument p points to a uint variable in which to store the value of the flag. -func (f *FlagSet) Uint16Var(p *uint16, name string, value uint16, usage string) { - f.VarP(newUint16Value(value, p), name, "", usage) -} - -// Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) { - f.VarP(newUint16Value(value, p), name, shorthand, usage) -} - -// Uint16Var defines a uint flag with specified name, default value, and usage string. -// The argument p points to a uint variable in which to store the value of the flag. -func Uint16Var(p *uint16, name string, value uint16, usage string) { - CommandLine.VarP(newUint16Value(value, p), name, "", usage) -} - -// Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash. -func Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) { - CommandLine.VarP(newUint16Value(value, p), name, shorthand, usage) -} - -// Uint16 defines a uint flag with specified name, default value, and usage string. -// The return value is the address of a uint variable that stores the value of the flag. -func (f *FlagSet) Uint16(name string, value uint16, usage string) *uint16 { - p := new(uint16) - f.Uint16VarP(p, name, "", value, usage) - return p -} - -// Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint16P(name, shorthand string, value uint16, usage string) *uint16 { - p := new(uint16) - f.Uint16VarP(p, name, shorthand, value, usage) - return p -} - -// Uint16 defines a uint flag with specified name, default value, and usage string. -// The return value is the address of a uint variable that stores the value of the flag. -func Uint16(name string, value uint16, usage string) *uint16 { - return CommandLine.Uint16P(name, "", value, usage) -} - -// Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash. -func Uint16P(name, shorthand string, value uint16, usage string) *uint16 { - return CommandLine.Uint16P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/uint32.go b/vendor/github.com/spf13/pflag/uint32.go deleted file mode 100644 index d8024539b..000000000 --- a/vendor/github.com/spf13/pflag/uint32.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- uint32 value -type uint32Value uint32 - -func newUint32Value(val uint32, p *uint32) *uint32Value { - *p = val - return (*uint32Value)(p) -} - -func (i *uint32Value) Set(s string) error { - v, err := strconv.ParseUint(s, 0, 32) - *i = uint32Value(v) - return err -} - -func (i *uint32Value) Type() string { - return "uint32" -} - -func (i *uint32Value) String() string { return strconv.FormatUint(uint64(*i), 10) } - -func uint32Conv(sval string) (interface{}, error) { - v, err := strconv.ParseUint(sval, 0, 32) - if err != nil { - return 0, err - } - return uint32(v), nil -} - -// GetUint32 return the uint32 value of a flag with the given name -func (f *FlagSet) GetUint32(name string) (uint32, error) { - val, err := f.getFlagType(name, "uint32", uint32Conv) - if err != nil { - return 0, err - } - return val.(uint32), nil -} - -// Uint32Var defines a uint32 flag with specified name, default value, and usage string. -// The argument p points to a uint32 variable in which to store the value of the flag. -func (f *FlagSet) Uint32Var(p *uint32, name string, value uint32, usage string) { - f.VarP(newUint32Value(value, p), name, "", usage) -} - -// Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) { - f.VarP(newUint32Value(value, p), name, shorthand, usage) -} - -// Uint32Var defines a uint32 flag with specified name, default value, and usage string. -// The argument p points to a uint32 variable in which to store the value of the flag. -func Uint32Var(p *uint32, name string, value uint32, usage string) { - CommandLine.VarP(newUint32Value(value, p), name, "", usage) -} - -// Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash. -func Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) { - CommandLine.VarP(newUint32Value(value, p), name, shorthand, usage) -} - -// Uint32 defines a uint32 flag with specified name, default value, and usage string. -// The return value is the address of a uint32 variable that stores the value of the flag. -func (f *FlagSet) Uint32(name string, value uint32, usage string) *uint32 { - p := new(uint32) - f.Uint32VarP(p, name, "", value, usage) - return p -} - -// Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint32P(name, shorthand string, value uint32, usage string) *uint32 { - p := new(uint32) - f.Uint32VarP(p, name, shorthand, value, usage) - return p -} - -// Uint32 defines a uint32 flag with specified name, default value, and usage string. -// The return value is the address of a uint32 variable that stores the value of the flag. -func Uint32(name string, value uint32, usage string) *uint32 { - return CommandLine.Uint32P(name, "", value, usage) -} - -// Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash. -func Uint32P(name, shorthand string, value uint32, usage string) *uint32 { - return CommandLine.Uint32P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/uint64.go b/vendor/github.com/spf13/pflag/uint64.go deleted file mode 100644 index f62240f2c..000000000 --- a/vendor/github.com/spf13/pflag/uint64.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- uint64 Value -type uint64Value uint64 - -func newUint64Value(val uint64, p *uint64) *uint64Value { - *p = val - return (*uint64Value)(p) -} - -func (i *uint64Value) Set(s string) error { - v, err := strconv.ParseUint(s, 0, 64) - *i = uint64Value(v) - return err -} - -func (i *uint64Value) Type() string { - return "uint64" -} - -func (i *uint64Value) String() string { return strconv.FormatUint(uint64(*i), 10) } - -func uint64Conv(sval string) (interface{}, error) { - v, err := strconv.ParseUint(sval, 0, 64) - if err != nil { - return 0, err - } - return uint64(v), nil -} - -// GetUint64 return the uint64 value of a flag with the given name -func (f *FlagSet) GetUint64(name string) (uint64, error) { - val, err := f.getFlagType(name, "uint64", uint64Conv) - if err != nil { - return 0, err - } - return val.(uint64), nil -} - -// Uint64Var defines a uint64 flag with specified name, default value, and usage string. -// The argument p points to a uint64 variable in which to store the value of the flag. -func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) { - f.VarP(newUint64Value(value, p), name, "", usage) -} - -// Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) { - f.VarP(newUint64Value(value, p), name, shorthand, usage) -} - -// Uint64Var defines a uint64 flag with specified name, default value, and usage string. -// The argument p points to a uint64 variable in which to store the value of the flag. -func Uint64Var(p *uint64, name string, value uint64, usage string) { - CommandLine.VarP(newUint64Value(value, p), name, "", usage) -} - -// Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash. -func Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) { - CommandLine.VarP(newUint64Value(value, p), name, shorthand, usage) -} - -// Uint64 defines a uint64 flag with specified name, default value, and usage string. -// The return value is the address of a uint64 variable that stores the value of the flag. -func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 { - p := new(uint64) - f.Uint64VarP(p, name, "", value, usage) - return p -} - -// Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint64P(name, shorthand string, value uint64, usage string) *uint64 { - p := new(uint64) - f.Uint64VarP(p, name, shorthand, value, usage) - return p -} - -// Uint64 defines a uint64 flag with specified name, default value, and usage string. -// The return value is the address of a uint64 variable that stores the value of the flag. -func Uint64(name string, value uint64, usage string) *uint64 { - return CommandLine.Uint64P(name, "", value, usage) -} - -// Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash. -func Uint64P(name, shorthand string, value uint64, usage string) *uint64 { - return CommandLine.Uint64P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/uint8.go b/vendor/github.com/spf13/pflag/uint8.go deleted file mode 100644 index bb0e83c1f..000000000 --- a/vendor/github.com/spf13/pflag/uint8.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- uint8 Value -type uint8Value uint8 - -func newUint8Value(val uint8, p *uint8) *uint8Value { - *p = val - return (*uint8Value)(p) -} - -func (i *uint8Value) Set(s string) error { - v, err := strconv.ParseUint(s, 0, 8) - *i = uint8Value(v) - return err -} - -func (i *uint8Value) Type() string { - return "uint8" -} - -func (i *uint8Value) String() string { return strconv.FormatUint(uint64(*i), 10) } - -func uint8Conv(sval string) (interface{}, error) { - v, err := strconv.ParseUint(sval, 0, 8) - if err != nil { - return 0, err - } - return uint8(v), nil -} - -// GetUint8 return the uint8 value of a flag with the given name -func (f *FlagSet) GetUint8(name string) (uint8, error) { - val, err := f.getFlagType(name, "uint8", uint8Conv) - if err != nil { - return 0, err - } - return val.(uint8), nil -} - -// Uint8Var defines a uint8 flag with specified name, default value, and usage string. -// The argument p points to a uint8 variable in which to store the value of the flag. -func (f *FlagSet) Uint8Var(p *uint8, name string, value uint8, usage string) { - f.VarP(newUint8Value(value, p), name, "", usage) -} - -// Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) { - f.VarP(newUint8Value(value, p), name, shorthand, usage) -} - -// Uint8Var defines a uint8 flag with specified name, default value, and usage string. -// The argument p points to a uint8 variable in which to store the value of the flag. -func Uint8Var(p *uint8, name string, value uint8, usage string) { - CommandLine.VarP(newUint8Value(value, p), name, "", usage) -} - -// Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash. -func Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) { - CommandLine.VarP(newUint8Value(value, p), name, shorthand, usage) -} - -// Uint8 defines a uint8 flag with specified name, default value, and usage string. -// The return value is the address of a uint8 variable that stores the value of the flag. -func (f *FlagSet) Uint8(name string, value uint8, usage string) *uint8 { - p := new(uint8) - f.Uint8VarP(p, name, "", value, usage) - return p -} - -// Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint8P(name, shorthand string, value uint8, usage string) *uint8 { - p := new(uint8) - f.Uint8VarP(p, name, shorthand, value, usage) - return p -} - -// Uint8 defines a uint8 flag with specified name, default value, and usage string. -// The return value is the address of a uint8 variable that stores the value of the flag. -func Uint8(name string, value uint8, usage string) *uint8 { - return CommandLine.Uint8P(name, "", value, usage) -} - -// Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash. -func Uint8P(name, shorthand string, value uint8, usage string) *uint8 { - return CommandLine.Uint8P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/uint_slice.go b/vendor/github.com/spf13/pflag/uint_slice.go deleted file mode 100644 index edd94c600..000000000 --- a/vendor/github.com/spf13/pflag/uint_slice.go +++ /dev/null @@ -1,126 +0,0 @@ -package pflag - -import ( - "fmt" - "strconv" - "strings" -) - -// -- uintSlice Value -type uintSliceValue struct { - value *[]uint - changed bool -} - -func newUintSliceValue(val []uint, p *[]uint) *uintSliceValue { - uisv := new(uintSliceValue) - uisv.value = p - *uisv.value = val - return uisv -} - -func (s *uintSliceValue) Set(val string) error { - ss := strings.Split(val, ",") - out := make([]uint, len(ss)) - for i, d := range ss { - u, err := strconv.ParseUint(d, 10, 0) - if err != nil { - return err - } - out[i] = uint(u) - } - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - s.changed = true - return nil -} - -func (s *uintSliceValue) Type() string { - return "uintSlice" -} - -func (s *uintSliceValue) String() string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = fmt.Sprintf("%d", d) - } - return "[" + strings.Join(out, ",") + "]" -} - -func uintSliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Empty string would cause a slice with one (empty) entry - if len(val) == 0 { - return []uint{}, nil - } - ss := strings.Split(val, ",") - out := make([]uint, len(ss)) - for i, d := range ss { - u, err := strconv.ParseUint(d, 10, 0) - if err != nil { - return nil, err - } - out[i] = uint(u) - } - return out, nil -} - -// GetUintSlice returns the []uint value of a flag with the given name. -func (f *FlagSet) GetUintSlice(name string) ([]uint, error) { - val, err := f.getFlagType(name, "uintSlice", uintSliceConv) - if err != nil { - return []uint{}, err - } - return val.([]uint), nil -} - -// UintSliceVar defines a uintSlice flag with specified name, default value, and usage string. -// The argument p points to a []uint variable in which to store the value of the flag. -func (f *FlagSet) UintSliceVar(p *[]uint, name string, value []uint, usage string) { - f.VarP(newUintSliceValue(value, p), name, "", usage) -} - -// UintSliceVarP is like UintSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) { - f.VarP(newUintSliceValue(value, p), name, shorthand, usage) -} - -// UintSliceVar defines a uint[] flag with specified name, default value, and usage string. -// The argument p points to a uint[] variable in which to store the value of the flag. -func UintSliceVar(p *[]uint, name string, value []uint, usage string) { - CommandLine.VarP(newUintSliceValue(value, p), name, "", usage) -} - -// UintSliceVarP is like the UintSliceVar, but accepts a shorthand letter that can be used after a single dash. -func UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) { - CommandLine.VarP(newUintSliceValue(value, p), name, shorthand, usage) -} - -// UintSlice defines a []uint flag with specified name, default value, and usage string. -// The return value is the address of a []uint variable that stores the value of the flag. -func (f *FlagSet) UintSlice(name string, value []uint, usage string) *[]uint { - p := []uint{} - f.UintSliceVarP(&p, name, "", value, usage) - return &p -} - -// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) UintSliceP(name, shorthand string, value []uint, usage string) *[]uint { - p := []uint{} - f.UintSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// UintSlice defines a []uint flag with specified name, default value, and usage string. -// The return value is the address of a []uint variable that stores the value of the flag. -func UintSlice(name string, value []uint, usage string) *[]uint { - return CommandLine.UintSliceP(name, "", value, usage) -} - -// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash. -func UintSliceP(name, shorthand string, value []uint, usage string) *[]uint { - return CommandLine.UintSliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/stretchr/testify/suite/doc.go b/vendor/github.com/stretchr/testify/suite/doc.go deleted file mode 100644 index f91a245d3..000000000 --- a/vendor/github.com/stretchr/testify/suite/doc.go +++ /dev/null @@ -1,65 +0,0 @@ -// Package suite contains logic for creating testing suite structs -// and running the methods on those structs as tests. The most useful -// piece of this package is that you can create setup/teardown methods -// on your testing suites, which will run before/after the whole suite -// or individual tests (depending on which interface(s) you -// implement). -// -// A testing suite is usually built by first extending the built-in -// suite functionality from suite.Suite in testify. Alternatively, -// you could reproduce that logic on your own if you wanted (you -// just need to implement the TestingSuite interface from -// suite/interfaces.go). -// -// After that, you can implement any of the interfaces in -// suite/interfaces.go to add setup/teardown functionality to your -// suite, and add any methods that start with "Test" to add tests. -// Methods that do not match any suite interfaces and do not begin -// with "Test" will not be run by testify, and can safely be used as -// helper methods. -// -// Once you've built your testing suite, you need to run the suite -// (using suite.Run from testify) inside any function that matches the -// identity that "go test" is already looking for (i.e. -// func(*testing.T)). -// -// Regular expression to select test suites specified command-line -// argument "-run". Regular expression to select the methods -// of test suites specified command-line argument "-m". -// Suite object has assertion methods. -// -// A crude example: -// // Basic imports -// import ( -// "testing" -// "github.com/stretchr/testify/assert" -// "github.com/stretchr/testify/suite" -// ) -// -// // Define the suite, and absorb the built-in basic suite -// // functionality from testify - including a T() method which -// // returns the current testing context -// type ExampleTestSuite struct { -// suite.Suite -// VariableThatShouldStartAtFive int -// } -// -// // Make sure that VariableThatShouldStartAtFive is set to five -// // before each test -// func (suite *ExampleTestSuite) SetupTest() { -// suite.VariableThatShouldStartAtFive = 5 -// } -// -// // All methods that begin with "Test" are run as tests within a -// // suite. -// func (suite *ExampleTestSuite) TestExample() { -// assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive) -// suite.Equal(5, suite.VariableThatShouldStartAtFive) -// } -// -// // In order for 'go test' to run this suite, we need to create -// // a normal test function and pass our suite to suite.Run -// func TestExampleTestSuite(t *testing.T) { -// suite.Run(t, new(ExampleTestSuite)) -// } -package suite diff --git a/vendor/github.com/stretchr/testify/suite/interfaces.go b/vendor/github.com/stretchr/testify/suite/interfaces.go deleted file mode 100644 index b37cb0409..000000000 --- a/vendor/github.com/stretchr/testify/suite/interfaces.go +++ /dev/null @@ -1,46 +0,0 @@ -package suite - -import "testing" - -// TestingSuite can store and return the current *testing.T context -// generated by 'go test'. -type TestingSuite interface { - T() *testing.T - SetT(*testing.T) -} - -// SetupAllSuite has a SetupSuite method, which will run before the -// tests in the suite are run. -type SetupAllSuite interface { - SetupSuite() -} - -// SetupTestSuite has a SetupTest method, which will run before each -// test in the suite. -type SetupTestSuite interface { - SetupTest() -} - -// TearDownAllSuite has a TearDownSuite method, which will run after -// all the tests in the suite have been run. -type TearDownAllSuite interface { - TearDownSuite() -} - -// TearDownTestSuite has a TearDownTest method, which will run after -// each test in the suite. -type TearDownTestSuite interface { - TearDownTest() -} - -// BeforeTest has a function to be executed right before the test -// starts and receives the suite and test names as input -type BeforeTest interface { - BeforeTest(suiteName, testName string) -} - -// AfterTest has a function to be executed right after the test -// finishes and receives the suite and test names as input -type AfterTest interface { - AfterTest(suiteName, testName string) -} diff --git a/vendor/github.com/stretchr/testify/suite/suite.go b/vendor/github.com/stretchr/testify/suite/suite.go deleted file mode 100644 index e20afbc21..000000000 --- a/vendor/github.com/stretchr/testify/suite/suite.go +++ /dev/null @@ -1,136 +0,0 @@ -package suite - -import ( - "flag" - "fmt" - "os" - "reflect" - "regexp" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var allTestsFilter = func(_, _ string) (bool, error) { return true, nil } -var matchMethod = flag.String("testify.m", "", "regular expression to select tests of the testify suite to run") - -// Suite is a basic testing suite with methods for storing and -// retrieving the current *testing.T context. -type Suite struct { - *assert.Assertions - require *require.Assertions - t *testing.T -} - -// T retrieves the current *testing.T context. -func (suite *Suite) T() *testing.T { - return suite.t -} - -// SetT sets the current *testing.T context. -func (suite *Suite) SetT(t *testing.T) { - suite.t = t - suite.Assertions = assert.New(t) - suite.require = require.New(t) -} - -// Require returns a require context for suite. -func (suite *Suite) Require() *require.Assertions { - if suite.require == nil { - suite.require = require.New(suite.T()) - } - return suite.require -} - -// Assert returns an assert context for suite. Normally, you can call -// `suite.NoError(expected, actual)`, but for situations where the embedded -// methods are overridden (for example, you might want to override -// assert.Assertions with require.Assertions), this method is provided so you -// can call `suite.Assert().NoError()`. -func (suite *Suite) Assert() *assert.Assertions { - if suite.Assertions == nil { - suite.Assertions = assert.New(suite.T()) - } - return suite.Assertions -} - -// Run takes a testing suite and runs all of the tests attached -// to it. -func Run(t *testing.T, suite TestingSuite) { - suite.SetT(t) - - if setupAllSuite, ok := suite.(SetupAllSuite); ok { - setupAllSuite.SetupSuite() - } - defer func() { - if tearDownAllSuite, ok := suite.(TearDownAllSuite); ok { - tearDownAllSuite.TearDownSuite() - } - }() - - methodFinder := reflect.TypeOf(suite) - tests := []testing.InternalTest{} - for index := 0; index < methodFinder.NumMethod(); index++ { - method := methodFinder.Method(index) - ok, err := methodFilter(method.Name) - if err != nil { - fmt.Fprintf(os.Stderr, "testify: invalid regexp for -m: %s\n", err) - os.Exit(1) - } - if ok { - test := testing.InternalTest{ - Name: method.Name, - F: func(t *testing.T) { - parentT := suite.T() - suite.SetT(t) - if setupTestSuite, ok := suite.(SetupTestSuite); ok { - setupTestSuite.SetupTest() - } - if beforeTestSuite, ok := suite.(BeforeTest); ok { - beforeTestSuite.BeforeTest(methodFinder.Elem().Name(), method.Name) - } - defer func() { - if afterTestSuite, ok := suite.(AfterTest); ok { - afterTestSuite.AfterTest(methodFinder.Elem().Name(), method.Name) - } - if tearDownTestSuite, ok := suite.(TearDownTestSuite); ok { - tearDownTestSuite.TearDownTest() - } - suite.SetT(parentT) - }() - method.Func.Call([]reflect.Value{reflect.ValueOf(suite)}) - }, - } - tests = append(tests, test) - } - } - runTests(t, tests) -} - -func runTests(t testing.TB, tests []testing.InternalTest) { - r, ok := t.(runner) - if !ok { // backwards compatibility with Go 1.6 and below - if !testing.RunTests(allTestsFilter, tests) { - t.Fail() - } - return - } - - for _, test := range tests { - r.Run(test.Name, test.F) - } -} - -// Filtering method according to set regular expression -// specified command-line argument -m -func methodFilter(name string) (bool, error) { - if ok, _ := regexp.MatchString("^Test", name); !ok { - return false, nil - } - return regexp.MatchString(*matchMethod, name) -} - -type runner interface { - Run(name string, f func(t *testing.T)) bool -} diff --git a/vendor/github.com/tendermint/abci/example/kvstore/README.md b/vendor/github.com/tendermint/abci/example/kvstore/README.md new file mode 100644 index 000000000..e988eadb0 --- /dev/null +++ b/vendor/github.com/tendermint/abci/example/kvstore/README.md @@ -0,0 +1,31 @@ +# KVStore + +There are two app's here: the KVStoreApplication and the PersistentKVStoreApplication. + +## KVStoreApplication + +The KVStoreApplication is a simple merkle key-value store. +Transactions of the form `key=value` are stored as key-value pairs in the tree. +Transactions without an `=` sign set the value to the key. +The app has no replay protection (other than what the mempool provides). + +## PersistentKVStoreApplication + +The PersistentKVStoreApplication wraps the KVStoreApplication +and provides two additional features: + +1) persistence of state across app restarts (using Tendermint's ABCI-Handshake mechanism) +2) validator set changes + +The state is persisted in leveldb along with the last block committed, +and the Handshake allows any necessary blocks to be replayed. +Validator set changes are effected using the following transaction format: + +``` +val:pubkey1/power1,addr2/power2,addr3/power3" +``` + +where `power1` is the new voting power for the validator with `pubkey1` (possibly a new one). +There is no sybil protection against new validators joining. +Validators can be removed by setting their power to `0`. + diff --git a/vendor/github.com/tendermint/abci/types/types.proto b/vendor/github.com/tendermint/abci/types/types.proto new file mode 100644 index 000000000..b4f4b2aa6 --- /dev/null +++ b/vendor/github.com/tendermint/abci/types/types.proto @@ -0,0 +1,282 @@ +syntax = "proto3"; +package types; + +// For more information on gogo.proto, see: +// https://github.com/gogo/protobuf/blob/master/extensions.md +import "github.com/gogo/protobuf/gogoproto/gogo.proto"; +import "github.com/tendermint/tmlibs/common/types.proto"; + +// This file is copied from http://github.com/tendermint/abci +// NOTE: When using custom types, mind the warnings. +// https://github.com/gogo/protobuf/blob/master/custom_types.md#warnings-and-issues + +//---------------------------------------- +// Request types + +message Request { + oneof value { + RequestEcho echo = 2; + RequestFlush flush = 3; + RequestInfo info = 4; + RequestSetOption set_option = 5; + RequestInitChain init_chain = 6; + RequestQuery query = 7; + RequestBeginBlock begin_block = 8; + RequestCheckTx check_tx = 9; + RequestDeliverTx deliver_tx = 19; + RequestEndBlock end_block = 11; + RequestCommit commit = 12; + } +} + +message RequestEcho { + string message = 1; +} + +message RequestFlush { +} + +message RequestInfo { + string version = 1; +} + +// nondeterministic +message RequestSetOption { + string key = 1; + string value = 2; +} + +message RequestInitChain { + int64 time = 1; + string chain_id = 2; + ConsensusParams consensus_params = 3; + repeated Validator validators = 4 [(gogoproto.nullable)=false]; + bytes app_state_bytes = 5; +} + +message RequestQuery { + bytes data = 1; + string path = 2; + int64 height = 3; + bool prove = 4; +} + +message RequestBeginBlock { + bytes hash = 1; + Header header = 2 [(gogoproto.nullable)=false]; + repeated SigningValidator validators = 3 [(gogoproto.nullable)=false]; + repeated Evidence byzantine_validators = 4 [(gogoproto.nullable)=false]; +} + +message RequestCheckTx { + bytes tx = 1; +} + +message RequestDeliverTx { + bytes tx = 1; +} + +message RequestEndBlock { + int64 height = 1; +} + +message RequestCommit { +} + +//---------------------------------------- +// Response types + +message Response { + oneof value { + ResponseException exception = 1; + ResponseEcho echo = 2; + ResponseFlush flush = 3; + ResponseInfo info = 4; + ResponseSetOption set_option = 5; + ResponseInitChain init_chain = 6; + ResponseQuery query = 7; + ResponseBeginBlock begin_block = 8; + ResponseCheckTx check_tx = 9; + ResponseDeliverTx deliver_tx = 10; + ResponseEndBlock end_block = 11; + ResponseCommit commit = 12; + } +} + +// nondeterministic +message ResponseException { + string error = 1; +} + +message ResponseEcho { + string message = 1; +} + +message ResponseFlush { +} + +message ResponseInfo { + string data = 1; + string version = 2; + int64 last_block_height = 3; + bytes last_block_app_hash = 4; +} + +// nondeterministic +message ResponseSetOption { + uint32 code = 1; + // bytes data = 2; + string log = 3; + string info = 4; +} + +message ResponseInitChain { + ConsensusParams consensus_params = 1; + repeated Validator validators = 2 [(gogoproto.nullable)=false]; +} + +message ResponseQuery { + uint32 code = 1; + // bytes data = 2; // use "value" instead. + string log = 3; // nondeterministic + string info = 4; // nondeterministic + int64 index = 5; + bytes key = 6; + bytes value = 7; + bytes proof = 8; + int64 height = 9; +} + +message ResponseBeginBlock { + repeated common.KVPair tags = 1 [(gogoproto.nullable)=false, (gogoproto.jsontag)="tags,omitempty"]; +} + +message ResponseCheckTx { + uint32 code = 1; + bytes data = 2; + string log = 3; // nondeterministic + string info = 4; // nondeterministic + int64 gas_wanted = 5; + int64 gas_used = 6; + repeated common.KVPair tags = 7 [(gogoproto.nullable)=false, (gogoproto.jsontag)="tags,omitempty"]; + common.KI64Pair fee = 8 [(gogoproto.nullable)=false]; +} + +message ResponseDeliverTx { + uint32 code = 1; + bytes data = 2; + string log = 3; // nondeterministic + string info = 4; // nondeterministic + int64 gas_wanted = 5; + int64 gas_used = 6; + repeated common.KVPair tags = 7 [(gogoproto.nullable)=false, (gogoproto.jsontag)="tags,omitempty"]; + common.KI64Pair fee = 8 [(gogoproto.nullable)=false]; +} + +message ResponseEndBlock { + repeated Validator validator_updates = 1 [(gogoproto.nullable)=false]; + ConsensusParams consensus_param_updates = 2; + repeated common.KVPair tags = 3 [(gogoproto.nullable)=false, (gogoproto.jsontag)="tags,omitempty"]; +} + +message ResponseCommit { + // reserve 1 + bytes data = 2; +} + +//---------------------------------------- +// Misc. + +// ConsensusParams contains all consensus-relevant parameters +// that can be adjusted by the abci app +message ConsensusParams { + BlockSize block_size = 1; + TxSize tx_size = 2; + BlockGossip block_gossip = 3; +} + +// BlockSize contain limits on the block size. +message BlockSize { + int32 max_bytes = 1; + int32 max_txs = 2; + int64 max_gas = 3; +} + +// TxSize contain limits on the tx size. +message TxSize { + int32 max_bytes = 1; + int64 max_gas = 2; +} + +// BlockGossip determine consensus critical +// elements of how blocks are gossiped +message BlockGossip { + // Note: must not be 0 + int32 block_part_size_bytes = 1; +} + +//---------------------------------------- +// Blockchain Types + +// just the minimum the app might need +message Header { + // basics + string chain_id = 1 [(gogoproto.customname)="ChainID"]; + int64 height = 2; + int64 time = 3; + + // txs + int32 num_txs = 4; + int64 total_txs = 5; + + // hashes + bytes last_block_hash = 6; + bytes validators_hash = 7; + bytes app_hash = 8; + + // consensus + Validator proposer = 9 [(gogoproto.nullable)=false]; +} + +// Validator +message Validator { + bytes address = 1; + PubKey pub_key = 2 [(gogoproto.nullable)=false]; + int64 power = 3; +} + +// Validator with an extra bool +message SigningValidator { + Validator validator = 1 [(gogoproto.nullable)=false]; + bool signed_last_block = 2; +} + +message PubKey { + string type = 1; + bytes data = 2; +} + +message Evidence { + string type = 1; + Validator validator = 2 [(gogoproto.nullable)=false]; + int64 height = 3; + int64 time = 4; + int64 total_voting_power = 5; +} + +//---------------------------------------- +// Service Definition + +service ABCIApplication { + rpc Echo(RequestEcho) returns (ResponseEcho) ; + rpc Flush(RequestFlush) returns (ResponseFlush); + rpc Info(RequestInfo) returns (ResponseInfo); + rpc SetOption(RequestSetOption) returns (ResponseSetOption); + rpc DeliverTx(RequestDeliverTx) returns (ResponseDeliverTx); + rpc CheckTx(RequestCheckTx) returns (ResponseCheckTx); + rpc Query(RequestQuery) returns (ResponseQuery); + rpc Commit(RequestCommit) returns (ResponseCommit); + rpc InitChain(RequestInitChain) returns (ResponseInitChain); + rpc BeginBlock(RequestBeginBlock) returns (ResponseBeginBlock); + rpc EndBlock(RequestEndBlock) returns (ResponseEndBlock); +} diff --git a/vendor/github.com/tendermint/tmlibs/autofile/README.md b/vendor/github.com/tendermint/tmlibs/autofile/README.md new file mode 100644 index 000000000..23799200c --- /dev/null +++ b/vendor/github.com/tendermint/tmlibs/autofile/README.md @@ -0,0 +1 @@ +# go-autofile diff --git a/vendor/github.com/tendermint/tmlibs/common/types.proto b/vendor/github.com/tendermint/tmlibs/common/types.proto new file mode 100644 index 000000000..94abcccc3 --- /dev/null +++ b/vendor/github.com/tendermint/tmlibs/common/types.proto @@ -0,0 +1,24 @@ +syntax = "proto3"; +package common; + +// For more information on gogo.proto, see: +// https://github.com/gogo/protobuf/blob/master/extensions.md +// NOTE: Try really hard not to use custom types, +// it's often complicated, broken, nor not worth it. +import "github.com/gogo/protobuf/gogoproto/gogo.proto"; + + +//---------------------------------------- +// Abstract types + +// Define these here for compatibility but use tmlibs/common.KVPair. +message KVPair { + bytes key = 1; + bytes value = 2; +} + +// Define these here for compatibility but use tmlibs/common.KI64Pair. +message KI64Pair { + bytes key = 1; + int64 value = 2; +} diff --git a/vendor/github.com/tendermint/tmlibs/db/README.md b/vendor/github.com/tendermint/tmlibs/db/README.md new file mode 100644 index 000000000..ca5ab33f9 --- /dev/null +++ b/vendor/github.com/tendermint/tmlibs/db/README.md @@ -0,0 +1 @@ +TODO: syndtr/goleveldb should be replaced with actual LevelDB instance diff --git a/vendor/github.com/tendermint/tmlibs/flowrate/README.md b/vendor/github.com/tendermint/tmlibs/flowrate/README.md new file mode 100644 index 000000000..db428090c --- /dev/null +++ b/vendor/github.com/tendermint/tmlibs/flowrate/README.md @@ -0,0 +1,10 @@ +Data Flow Rate Control +====================== + +To download and install this package run: + +go get github.com/mxk/go-flowrate/flowrate + +The documentation is available at: + +http://godoc.org/github.com/mxk/go-flowrate/flowrate diff --git a/vendor/github.com/tendermint/tmlibs/merkle/README.md b/vendor/github.com/tendermint/tmlibs/merkle/README.md new file mode 100644 index 000000000..c44978368 --- /dev/null +++ b/vendor/github.com/tendermint/tmlibs/merkle/README.md @@ -0,0 +1,4 @@ +## Simple Merkle Tree + +For smaller static data structures that don't require immutable snapshots or mutability; +for instance the transactions and validation signatures of a block can be hashed using this simple merkle tree logic. diff --git a/vendor/github.com/tommy351/gin-cors/LICENSE b/vendor/github.com/tommy351/gin-cors/LICENSE deleted file mode 100644 index e750d3d45..000000000 --- a/vendor/github.com/tommy351/gin-cors/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Tommy Chen - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/tommy351/gin-cors/cors.go b/vendor/github.com/tommy351/gin-cors/cors.go deleted file mode 100644 index a29458042..000000000 --- a/vendor/github.com/tommy351/gin-cors/cors.go +++ /dev/null @@ -1,80 +0,0 @@ -package cors - -import ( - "net/http" - "strconv" - "strings" - "time" - - "github.com/gin-gonic/gin" -) - -var ( - defaultAllowHeaders = []string{"Origin", "Accept", "Content-Type", "Authorization"} - defaultAllowMethods = []string{"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD"} -) - -// Options stores configurations -type Options struct { - AllowOrigins []string - AllowCredentials bool - AllowMethods []string - AllowHeaders []string - ExposeHeaders []string - MaxAge time.Duration -} - -// Middleware sets CORS headers for every request -func Middleware(options Options) gin.HandlerFunc { - if options.AllowHeaders == nil { - options.AllowHeaders = defaultAllowHeaders - } - - if options.AllowMethods == nil { - options.AllowMethods = defaultAllowMethods - } - - return func(c *gin.Context) { - req := c.Request - res := c.Writer - origin := req.Header.Get("Origin") - requestMethod := req.Header.Get("Access-Control-Request-Method") - requestHeaders := req.Header.Get("Access-Control-Request-Headers") - - if len(options.AllowOrigins) > 0 { - res.Header().Set("Access-Control-Allow-Origin", strings.Join(options.AllowOrigins, " ")) - } else { - res.Header().Set("Access-Control-Allow-Origin", origin) - } - - if options.AllowCredentials { - res.Header().Set("Access-Control-Allow-Credentials", "true") - } - - if len(options.ExposeHeaders) > 0 { - res.Header().Set("Access-Control-Expose-Headers", strings.Join(options.ExposeHeaders, ",")) - } - - if req.Method == "OPTIONS" { - if len(options.AllowMethods) > 0 { - res.Header().Set("Access-Control-Allow-Methods", strings.Join(options.AllowMethods, ",")) - } else if requestMethod != "" { - res.Header().Set("Access-Control-Allow-Methods", requestMethod) - } - - if len(options.AllowHeaders) > 0 { - res.Header().Set("Access-Control-Allow-Headers", strings.Join(options.AllowHeaders, ",")) - } else if requestHeaders != "" { - res.Header().Set("Access-Control-Allow-Headers", requestHeaders) - } - - if options.MaxAge > time.Duration(0) { - res.Header().Set("Access-Control-Max-Age", strconv.FormatInt(int64(options.MaxAge/time.Second), 10)) - } - - c.AbortWithStatus(http.StatusOK) - } else { - c.Next() - } - } -} diff --git a/vendor/github.com/ugorji/go/LICENSE b/vendor/github.com/ugorji/go/LICENSE deleted file mode 100644 index 95a0f0541..000000000 --- a/vendor/github.com/ugorji/go/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2012-2015 Ugorji Nwoke. -All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/ugorji/go/codec/0doc.go b/vendor/github.com/ugorji/go/codec/0doc.go deleted file mode 100644 index b61a8180e..000000000 --- a/vendor/github.com/ugorji/go/codec/0doc.go +++ /dev/null @@ -1,264 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -/* -Package codec provides a -High Performance, Feature-Rich Idiomatic Go 1.4+ codec/encoding library -for binc, msgpack, cbor, json. - -Supported Serialization formats are: - - - msgpack: https://github.com/msgpack/msgpack - - binc: http://github.com/ugorji/binc - - cbor: http://cbor.io http://tools.ietf.org/html/rfc7049 - - json: http://json.org http://tools.ietf.org/html/rfc7159 - - simple: - -To install: - - go get github.com/ugorji/go/codec - -This package will carefully use 'unsafe' for performance reasons in specific places. -You can build without unsafe use by passing the safe or appengine tag -i.e. 'go install -tags=safe ...'. Note that unsafe is only supported for the last 3 -go sdk versions e.g. current go release is go 1.9, so we support unsafe use only from -go 1.7+ . This is because supporting unsafe requires knowledge of implementation details. - -For detailed usage information, read the primer at http://ugorji.net/blog/go-codec-primer . - -The idiomatic Go support is as seen in other encoding packages in -the standard library (ie json, xml, gob, etc). - -Rich Feature Set includes: - - - Simple but extremely powerful and feature-rich API - - Support for go1.4 and above, while selectively using newer APIs for later releases - - Excellent code coverage ( > 90% ) - - Very High Performance. - Our extensive benchmarks show us outperforming Gob, Json, Bson, etc by 2-4X. - - Careful selected use of 'unsafe' for targeted performance gains. - 100% mode exists where 'unsafe' is not used at all. - - Lock-free (sans mutex) concurrency for scaling to 100's of cores - - Coerce types where appropriate - e.g. decode an int in the stream into a float, decode numbers from formatted strings, etc - - Corner Cases: - Overflows, nil maps/slices, nil values in streams are handled correctly - - Standard field renaming via tags - - Support for omitting empty fields during an encoding - - Encoding from any value and decoding into pointer to any value - (struct, slice, map, primitives, pointers, interface{}, etc) - - Extensions to support efficient encoding/decoding of any named types - - Support encoding.(Binary|Text)(M|Unm)arshaler interfaces - - Support IsZero() bool to determine if a value is a zero value. - Analogous to time.Time.IsZero() bool. - - Decoding without a schema (into a interface{}). - Includes Options to configure what specific map or slice type to use - when decoding an encoded list or map into a nil interface{} - - Mapping a non-interface type to an interface, so we can decode appropriately - into any interface type with a correctly configured non-interface value. - - Encode a struct as an array, and decode struct from an array in the data stream - - Option to encode struct keys as numbers (instead of strings) - (to support structured streams with fields encoded as numeric codes) - - Comprehensive support for anonymous fields - - Fast (no-reflection) encoding/decoding of common maps and slices - - Code-generation for faster performance. - - Support binary (e.g. messagepack, cbor) and text (e.g. json) formats - - Support indefinite-length formats to enable true streaming - (for formats which support it e.g. json, cbor) - - Support canonical encoding, where a value is ALWAYS encoded as same sequence of bytes. - This mostly applies to maps, where iteration order is non-deterministic. - - NIL in data stream decoded as zero value - - Never silently skip data when decoding. - User decides whether to return an error or silently skip data when keys or indexes - in the data stream do not map to fields in the struct. - - Detect and error when encoding a cyclic reference (instead of stack overflow shutdown) - - Encode/Decode from/to chan types (for iterative streaming support) - - Drop-in replacement for encoding/json. `json:` key in struct tag supported. - - Provides a RPC Server and Client Codec for net/rpc communication protocol. - - Handle unique idiosyncrasies of codecs e.g. - - For messagepack, configure how ambiguities in handling raw bytes are resolved - - For messagepack, provide rpc server/client codec to support - msgpack-rpc protocol defined at: - https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md - -Extension Support - -Users can register a function to handle the encoding or decoding of -their custom types. - -There are no restrictions on what the custom type can be. Some examples: - - type BisSet []int - type BitSet64 uint64 - type UUID string - type MyStructWithUnexportedFields struct { a int; b bool; c []int; } - type GifImage struct { ... } - -As an illustration, MyStructWithUnexportedFields would normally be -encoded as an empty map because it has no exported fields, while UUID -would be encoded as a string. However, with extension support, you can -encode any of these however you like. - -Custom Encoding and Decoding - -This package maintains symmetry in the encoding and decoding halfs. -We determine how to encode or decode by walking this decision tree - - - is type a codec.Selfer? - - is there an extension registered for the type? - - is format binary, and is type a encoding.BinaryMarshaler and BinaryUnmarshaler? - - is format specifically json, and is type a encoding/json.Marshaler and Unmarshaler? - - is format text-based, and type an encoding.TextMarshaler? - - else we use a pair of functions based on the "kind" of the type e.g. map, slice, int64, etc - -This symmetry is important to reduce chances of issues happening because the -encoding and decoding sides are out of sync e.g. decoded via very specific -encoding.TextUnmarshaler but encoded via kind-specific generalized mode. - -Consequently, if a type only defines one-half of the symmetry -(e.g. it implements UnmarshalJSON() but not MarshalJSON() ), -then that type doesn't satisfy the check and we will continue walking down the -decision tree. - -RPC - -RPC Client and Server Codecs are implemented, so the codecs can be used -with the standard net/rpc package. - -Usage - -The Handle is SAFE for concurrent READ, but NOT SAFE for concurrent modification. - -The Encoder and Decoder are NOT safe for concurrent use. - -Consequently, the usage model is basically: - - - Create and initialize the Handle before any use. - Once created, DO NOT modify it. - - Multiple Encoders or Decoders can now use the Handle concurrently. - They only read information off the Handle (never write). - - However, each Encoder or Decoder MUST not be used concurrently - - To re-use an Encoder/Decoder, call Reset(...) on it first. - This allows you use state maintained on the Encoder/Decoder. - -Sample usage model: - - // create and configure Handle - var ( - bh codec.BincHandle - mh codec.MsgpackHandle - ch codec.CborHandle - ) - - mh.MapType = reflect.TypeOf(map[string]interface{}(nil)) - - // configure extensions - // e.g. for msgpack, define functions and enable Time support for tag 1 - // mh.SetExt(reflect.TypeOf(time.Time{}), 1, myExt) - - // create and use decoder/encoder - var ( - r io.Reader - w io.Writer - b []byte - h = &bh // or mh to use msgpack - ) - - dec = codec.NewDecoder(r, h) - dec = codec.NewDecoderBytes(b, h) - err = dec.Decode(&v) - - enc = codec.NewEncoder(w, h) - enc = codec.NewEncoderBytes(&b, h) - err = enc.Encode(v) - - //RPC Server - go func() { - for { - conn, err := listener.Accept() - rpcCodec := codec.GoRpc.ServerCodec(conn, h) - //OR rpcCodec := codec.MsgpackSpecRpc.ServerCodec(conn, h) - rpc.ServeCodec(rpcCodec) - } - }() - - //RPC Communication (client side) - conn, err = net.Dial("tcp", "localhost:5555") - rpcCodec := codec.GoRpc.ClientCodec(conn, h) - //OR rpcCodec := codec.MsgpackSpecRpc.ClientCodec(conn, h) - client := rpc.NewClientWithCodec(rpcCodec) - -Running Tests - -To run tests, use the following: - - go test - -To run the full suite of tests, use the following: - - go test -tags alltests -run Suite - -You can run the tag 'safe' to run tests or build in safe mode. e.g. - - go test -tags safe -run Json - go test -tags "alltests safe" -run Suite - -Running Benchmarks - -Please see http://github.com/ugorji/go-codec-bench . - -Caveats - -Struct fields matching the following are ignored during encoding and decoding - - struct tag value set to - - - func, complex numbers, unsafe pointers - - unexported and not embedded - - unexported and embedded and not struct kind - - unexported and embedded pointers (from go1.10) - -Every other field in a struct will be encoded/decoded. - -Embedded fields are encoded as if they exist in the top-level struct, -with some caveats. See Encode documentation. - -*/ -package codec - -// TODO: -// - For Go 1.11, when mid-stack inlining is enabled, -// we should use committed functions for writeXXX and readXXX calls. -// This involves uncommenting the methods for decReaderSwitch and encWriterSwitch -// and using those (decReaderSwitch and encWriterSwitch) in all handles -// instead of encWriter and decReader. -// The benefit is that, for the (En|De)coder over []byte, the encWriter/decReader -// will be inlined, giving a performance bump for that typical case. -// However, it will only be inlined if mid-stack inlining is enabled, -// as we call panic to raise errors, and panic currently prevents inlining. -// -// PUNTED: -// - To make Handle comparable, make extHandle in BasicHandle a non-embedded pointer, -// and use overlay methods on *BasicHandle to call through to extHandle after initializing -// the "xh *extHandle" to point to a real slice. -// -// BEFORE EACH RELEASE: -// - Look through and fix padding for each type, to eliminate false sharing -// - critical shared objects that are read many times -// TypeInfos -// - pooled objects: -// decNaked, decNakedContainers, codecFner, typeInfoLoadArray, -// - small objects allocated independently, that we read/use much across threads: -// codecFn, typeInfo -// - Objects allocated independently and used a lot -// Decoder, Encoder, -// xxxHandle, xxxEncDriver, xxxDecDriver (xxx = json, msgpack, cbor, binc, simple) -// - In all above, arrange values modified together to be close to each other. -// -// For all of these, either ensure that they occupy full cache lines, -// or ensure that the things just past the cache line boundary are hardly read/written -// e.g. JsonHandle.RawBytesExt - which is copied into json(En|De)cDriver at init -// -// Occupying full cache lines means they occupy 8*N words (where N is an integer). -// Check this out by running: ./run.sh -z -// - look at those tagged ****, meaning they are not occupying full cache lines -// - look at those tagged <<<<, meaning they are larger than 32 words (something to watch) -// - Run "golint -min_confidence 0.81" diff --git a/vendor/github.com/ugorji/go/codec/binc.go b/vendor/github.com/ugorji/go/codec/binc.go deleted file mode 100644 index a3c96fe74..000000000 --- a/vendor/github.com/ugorji/go/codec/binc.go +++ /dev/null @@ -1,1168 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -import ( - "math" - "reflect" - "time" -) - -const bincDoPrune = true // No longer needed. Needed before as C lib did not support pruning. - -// vd as low 4 bits (there are 16 slots) -const ( - bincVdSpecial byte = iota - bincVdPosInt - bincVdNegInt - bincVdFloat - - bincVdString - bincVdByteArray - bincVdArray - bincVdMap - - bincVdTimestamp - bincVdSmallInt - bincVdUnicodeOther - bincVdSymbol - - bincVdDecimal - _ // open slot - _ // open slot - bincVdCustomExt = 0x0f -) - -const ( - bincSpNil byte = iota - bincSpFalse - bincSpTrue - bincSpNan - bincSpPosInf - bincSpNegInf - bincSpZeroFloat - bincSpZero - bincSpNegOne -) - -const ( - bincFlBin16 byte = iota - bincFlBin32 - _ // bincFlBin32e - bincFlBin64 - _ // bincFlBin64e - // others not currently supported -) - -func bincdesc(vd, vs byte) string { - switch vd { - case bincVdSpecial: - switch vs { - case bincSpNil: - return "nil" - case bincSpFalse: - return "false" - case bincSpTrue: - return "true" - case bincSpNan, bincSpPosInf, bincSpNegInf, bincSpZeroFloat: - return "float" - case bincSpZero: - return "uint" - case bincSpNegOne: - return "int" - default: - return "unknown" - } - case bincVdSmallInt, bincVdPosInt: - return "uint" - case bincVdNegInt: - return "int" - case bincVdFloat: - return "float" - case bincVdSymbol: - return "string" - case bincVdString: - return "string" - case bincVdByteArray: - return "bytes" - case bincVdTimestamp: - return "time" - case bincVdCustomExt: - return "ext" - case bincVdArray: - return "array" - case bincVdMap: - return "map" - default: - return "unknown" - } -} - -type bincEncDriver struct { - e *Encoder - h *BincHandle - w encWriter - m map[string]uint16 // symbols - b [16]byte // scratch, used for encoding numbers - bigendian style - s uint16 // symbols sequencer - // c containerState - encDriverTrackContainerWriter - noBuiltInTypes - // encNoSeparator -} - -func (e *bincEncDriver) EncodeNil() { - e.w.writen1(bincVdSpecial<<4 | bincSpNil) -} - -func (e *bincEncDriver) EncodeTime(t time.Time) { - if t.IsZero() { - e.EncodeNil() - } else { - bs := bincEncodeTime(t) - e.w.writen1(bincVdTimestamp<<4 | uint8(len(bs))) - e.w.writeb(bs) - } -} - -func (e *bincEncDriver) EncodeBool(b bool) { - if b { - e.w.writen1(bincVdSpecial<<4 | bincSpTrue) - } else { - e.w.writen1(bincVdSpecial<<4 | bincSpFalse) - } -} - -func (e *bincEncDriver) EncodeFloat32(f float32) { - if f == 0 { - e.w.writen1(bincVdSpecial<<4 | bincSpZeroFloat) - return - } - e.w.writen1(bincVdFloat<<4 | bincFlBin32) - bigenHelper{e.b[:4], e.w}.writeUint32(math.Float32bits(f)) -} - -func (e *bincEncDriver) EncodeFloat64(f float64) { - if f == 0 { - e.w.writen1(bincVdSpecial<<4 | bincSpZeroFloat) - return - } - bigen.PutUint64(e.b[:8], math.Float64bits(f)) - if bincDoPrune { - i := 7 - for ; i >= 0 && (e.b[i] == 0); i-- { - } - i++ - if i <= 6 { - e.w.writen1(bincVdFloat<<4 | 0x8 | bincFlBin64) - e.w.writen1(byte(i)) - e.w.writeb(e.b[:i]) - return - } - } - e.w.writen1(bincVdFloat<<4 | bincFlBin64) - e.w.writeb(e.b[:8]) -} - -func (e *bincEncDriver) encIntegerPrune(bd byte, pos bool, v uint64, lim uint8) { - if lim == 4 { - bigen.PutUint32(e.b[:lim], uint32(v)) - } else { - bigen.PutUint64(e.b[:lim], v) - } - if bincDoPrune { - i := pruneSignExt(e.b[:lim], pos) - e.w.writen1(bd | lim - 1 - byte(i)) - e.w.writeb(e.b[i:lim]) - } else { - e.w.writen1(bd | lim - 1) - e.w.writeb(e.b[:lim]) - } -} - -func (e *bincEncDriver) EncodeInt(v int64) { - const nbd byte = bincVdNegInt << 4 - if v >= 0 { - e.encUint(bincVdPosInt<<4, true, uint64(v)) - } else if v == -1 { - e.w.writen1(bincVdSpecial<<4 | bincSpNegOne) - } else { - e.encUint(bincVdNegInt<<4, false, uint64(-v)) - } -} - -func (e *bincEncDriver) EncodeUint(v uint64) { - e.encUint(bincVdPosInt<<4, true, v) -} - -func (e *bincEncDriver) encUint(bd byte, pos bool, v uint64) { - if v == 0 { - e.w.writen1(bincVdSpecial<<4 | bincSpZero) - } else if pos && v >= 1 && v <= 16 { - e.w.writen1(bincVdSmallInt<<4 | byte(v-1)) - } else if v <= math.MaxUint8 { - e.w.writen2(bd|0x0, byte(v)) - } else if v <= math.MaxUint16 { - e.w.writen1(bd | 0x01) - bigenHelper{e.b[:2], e.w}.writeUint16(uint16(v)) - } else if v <= math.MaxUint32 { - e.encIntegerPrune(bd, pos, v, 4) - } else { - e.encIntegerPrune(bd, pos, v, 8) - } -} - -func (e *bincEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, _ *Encoder) { - bs := ext.WriteExt(rv) - if bs == nil { - e.EncodeNil() - return - } - e.encodeExtPreamble(uint8(xtag), len(bs)) - e.w.writeb(bs) -} - -func (e *bincEncDriver) EncodeRawExt(re *RawExt, _ *Encoder) { - e.encodeExtPreamble(uint8(re.Tag), len(re.Data)) - e.w.writeb(re.Data) -} - -func (e *bincEncDriver) encodeExtPreamble(xtag byte, length int) { - e.encLen(bincVdCustomExt<<4, uint64(length)) - e.w.writen1(xtag) -} - -func (e *bincEncDriver) WriteArrayStart(length int) { - e.encLen(bincVdArray<<4, uint64(length)) - e.c = containerArrayStart -} - -func (e *bincEncDriver) WriteMapStart(length int) { - e.encLen(bincVdMap<<4, uint64(length)) - e.c = containerMapStart -} - -func (e *bincEncDriver) EncodeString(c charEncoding, v string) { - if e.c == containerMapKey && c == cUTF8 && (e.h.AsSymbols == 0 || e.h.AsSymbols == 1) { - e.EncodeSymbol(v) - return - } - l := uint64(len(v)) - e.encBytesLen(c, l) - if l > 0 { - e.w.writestr(v) - } -} - -func (e *bincEncDriver) EncodeSymbol(v string) { - // if WriteSymbolsNoRefs { - // e.encodeString(cUTF8, v) - // return - // } - - //symbols only offer benefit when string length > 1. - //This is because strings with length 1 take only 2 bytes to store - //(bd with embedded length, and single byte for string val). - - l := len(v) - if l == 0 { - e.encBytesLen(cUTF8, 0) - return - } else if l == 1 { - e.encBytesLen(cUTF8, 1) - e.w.writen1(v[0]) - return - } - if e.m == nil { - e.m = make(map[string]uint16, 16) - } - ui, ok := e.m[v] - if ok { - if ui <= math.MaxUint8 { - e.w.writen2(bincVdSymbol<<4, byte(ui)) - } else { - e.w.writen1(bincVdSymbol<<4 | 0x8) - bigenHelper{e.b[:2], e.w}.writeUint16(ui) - } - } else { - e.s++ - ui = e.s - //ui = uint16(atomic.AddUint32(&e.s, 1)) - e.m[v] = ui - var lenprec uint8 - if l <= math.MaxUint8 { - // lenprec = 0 - } else if l <= math.MaxUint16 { - lenprec = 1 - } else if int64(l) <= math.MaxUint32 { - lenprec = 2 - } else { - lenprec = 3 - } - if ui <= math.MaxUint8 { - e.w.writen2(bincVdSymbol<<4|0x0|0x4|lenprec, byte(ui)) - } else { - e.w.writen1(bincVdSymbol<<4 | 0x8 | 0x4 | lenprec) - bigenHelper{e.b[:2], e.w}.writeUint16(ui) - } - if lenprec == 0 { - e.w.writen1(byte(l)) - } else if lenprec == 1 { - bigenHelper{e.b[:2], e.w}.writeUint16(uint16(l)) - } else if lenprec == 2 { - bigenHelper{e.b[:4], e.w}.writeUint32(uint32(l)) - } else { - bigenHelper{e.b[:8], e.w}.writeUint64(uint64(l)) - } - e.w.writestr(v) - } -} - -func (e *bincEncDriver) EncodeStringBytes(c charEncoding, v []byte) { - if v == nil { - e.EncodeNil() - return - } - l := uint64(len(v)) - e.encBytesLen(c, l) - if l > 0 { - e.w.writeb(v) - } -} - -func (e *bincEncDriver) encBytesLen(c charEncoding, length uint64) { - //TODO: support bincUnicodeOther (for now, just use string or bytearray) - if c == cRAW { - e.encLen(bincVdByteArray<<4, length) - } else { - e.encLen(bincVdString<<4, length) - } -} - -func (e *bincEncDriver) encLen(bd byte, l uint64) { - if l < 12 { - e.w.writen1(bd | uint8(l+4)) - } else { - e.encLenNumber(bd, l) - } -} - -func (e *bincEncDriver) encLenNumber(bd byte, v uint64) { - if v <= math.MaxUint8 { - e.w.writen2(bd, byte(v)) - } else if v <= math.MaxUint16 { - e.w.writen1(bd | 0x01) - bigenHelper{e.b[:2], e.w}.writeUint16(uint16(v)) - } else if v <= math.MaxUint32 { - e.w.writen1(bd | 0x02) - bigenHelper{e.b[:4], e.w}.writeUint32(uint32(v)) - } else { - e.w.writen1(bd | 0x03) - bigenHelper{e.b[:8], e.w}.writeUint64(uint64(v)) - } -} - -//------------------------------------ - -type bincDecSymbol struct { - s string - b []byte - i uint16 -} - -type bincDecDriver struct { - decDriverNoopContainerReader - noBuiltInTypes - - d *Decoder - h *BincHandle - r decReader - br bool // bytes reader - bdRead bool - bd byte - vd byte - vs byte - _ [3]byte // padding - // linear searching on this slice is ok, - // because we typically expect < 32 symbols in each stream. - s []bincDecSymbol - - // noStreamingCodec - // decNoSeparator - - b [8 * 8]byte // scratch -} - -func (d *bincDecDriver) readNextBd() { - d.bd = d.r.readn1() - d.vd = d.bd >> 4 - d.vs = d.bd & 0x0f - d.bdRead = true -} - -func (d *bincDecDriver) uncacheRead() { - if d.bdRead { - d.r.unreadn1() - d.bdRead = false - } -} - -func (d *bincDecDriver) ContainerType() (vt valueType) { - if !d.bdRead { - d.readNextBd() - } - if d.vd == bincVdSpecial && d.vs == bincSpNil { - return valueTypeNil - } else if d.vd == bincVdByteArray { - return valueTypeBytes - } else if d.vd == bincVdString { - return valueTypeString - } else if d.vd == bincVdArray { - return valueTypeArray - } else if d.vd == bincVdMap { - return valueTypeMap - } - // else { - // d.d.errorf("isContainerType: unsupported parameter: %v", vt) - // } - return valueTypeUnset -} - -func (d *bincDecDriver) TryDecodeAsNil() bool { - if !d.bdRead { - d.readNextBd() - } - if d.bd == bincVdSpecial<<4|bincSpNil { - d.bdRead = false - return true - } - return false -} - -func (d *bincDecDriver) DecodeTime() (t time.Time) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == bincVdSpecial<<4|bincSpNil { - d.bdRead = false - return - } - if d.vd != bincVdTimestamp { - d.d.errorf("cannot decode time - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs)) - return - } - t, err := bincDecodeTime(d.r.readx(int(d.vs))) - if err != nil { - panic(err) - } - d.bdRead = false - return -} - -func (d *bincDecDriver) decFloatPre(vs, defaultLen byte) { - if vs&0x8 == 0 { - d.r.readb(d.b[0:defaultLen]) - } else { - l := d.r.readn1() - if l > 8 { - d.d.errorf("cannot read float - at most 8 bytes used to represent float - received %v bytes", l) - return - } - for i := l; i < 8; i++ { - d.b[i] = 0 - } - d.r.readb(d.b[0:l]) - } -} - -func (d *bincDecDriver) decFloat() (f float64) { - //if true { f = math.Float64frombits(bigen.Uint64(d.r.readx(8))); break; } - if x := d.vs & 0x7; x == bincFlBin32 { - d.decFloatPre(d.vs, 4) - f = float64(math.Float32frombits(bigen.Uint32(d.b[0:4]))) - } else if x == bincFlBin64 { - d.decFloatPre(d.vs, 8) - f = math.Float64frombits(bigen.Uint64(d.b[0:8])) - } else { - d.d.errorf("read float - only float32 and float64 are supported - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs)) - return - } - return -} - -func (d *bincDecDriver) decUint() (v uint64) { - // need to inline the code (interface conversion and type assertion expensive) - switch d.vs { - case 0: - v = uint64(d.r.readn1()) - case 1: - d.r.readb(d.b[6:8]) - v = uint64(bigen.Uint16(d.b[6:8])) - case 2: - d.b[4] = 0 - d.r.readb(d.b[5:8]) - v = uint64(bigen.Uint32(d.b[4:8])) - case 3: - d.r.readb(d.b[4:8]) - v = uint64(bigen.Uint32(d.b[4:8])) - case 4, 5, 6: - lim := int(7 - d.vs) - d.r.readb(d.b[lim:8]) - for i := 0; i < lim; i++ { - d.b[i] = 0 - } - v = uint64(bigen.Uint64(d.b[:8])) - case 7: - d.r.readb(d.b[:8]) - v = uint64(bigen.Uint64(d.b[:8])) - default: - d.d.errorf("unsigned integers with greater than 64 bits of precision not supported") - return - } - return -} - -func (d *bincDecDriver) decCheckInteger() (ui uint64, neg bool) { - if !d.bdRead { - d.readNextBd() - } - vd, vs := d.vd, d.vs - if vd == bincVdPosInt { - ui = d.decUint() - } else if vd == bincVdNegInt { - ui = d.decUint() - neg = true - } else if vd == bincVdSmallInt { - ui = uint64(d.vs) + 1 - } else if vd == bincVdSpecial { - if vs == bincSpZero { - //i = 0 - } else if vs == bincSpNegOne { - neg = true - ui = 1 - } else { - d.d.errorf("integer decode fails - invalid special value from descriptor %x-%x/%s", - d.vd, d.vs, bincdesc(d.vd, d.vs)) - return - } - } else { - d.d.errorf("integer can only be decoded from int/uint. d.bd: 0x%x, d.vd: 0x%x", d.bd, d.vd) - return - } - return -} - -func (d *bincDecDriver) DecodeInt64() (i int64) { - ui, neg := d.decCheckInteger() - i = chkOvf.SignedIntV(ui) - if neg { - i = -i - } - d.bdRead = false - return -} - -func (d *bincDecDriver) DecodeUint64() (ui uint64) { - ui, neg := d.decCheckInteger() - if neg { - d.d.errorf("assigning negative signed value to unsigned integer type") - return - } - d.bdRead = false - return -} - -func (d *bincDecDriver) DecodeFloat64() (f float64) { - if !d.bdRead { - d.readNextBd() - } - vd, vs := d.vd, d.vs - if vd == bincVdSpecial { - d.bdRead = false - if vs == bincSpNan { - return math.NaN() - } else if vs == bincSpPosInf { - return math.Inf(1) - } else if vs == bincSpZeroFloat || vs == bincSpZero { - return - } else if vs == bincSpNegInf { - return math.Inf(-1) - } else { - d.d.errorf("float - invalid special value from descriptor %x-%x/%s", - d.vd, d.vs, bincdesc(d.vd, d.vs)) - return - } - } else if vd == bincVdFloat { - f = d.decFloat() - } else { - f = float64(d.DecodeInt64()) - } - d.bdRead = false - return -} - -// bool can be decoded from bool only (single byte). -func (d *bincDecDriver) DecodeBool() (b bool) { - if !d.bdRead { - d.readNextBd() - } - if bd := d.bd; bd == (bincVdSpecial | bincSpFalse) { - // b = false - } else if bd == (bincVdSpecial | bincSpTrue) { - b = true - } else { - d.d.errorf("bool - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs)) - return - } - d.bdRead = false - return -} - -func (d *bincDecDriver) ReadMapStart() (length int) { - if !d.bdRead { - d.readNextBd() - } - if d.vd != bincVdMap { - d.d.errorf("map - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs)) - return - } - length = d.decLen() - d.bdRead = false - return -} - -func (d *bincDecDriver) ReadArrayStart() (length int) { - if !d.bdRead { - d.readNextBd() - } - if d.vd != bincVdArray { - d.d.errorf("array - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs)) - return - } - length = d.decLen() - d.bdRead = false - return -} - -func (d *bincDecDriver) decLen() int { - if d.vs > 3 { - return int(d.vs - 4) - } - return int(d.decLenNumber()) -} - -func (d *bincDecDriver) decLenNumber() (v uint64) { - if x := d.vs; x == 0 { - v = uint64(d.r.readn1()) - } else if x == 1 { - d.r.readb(d.b[6:8]) - v = uint64(bigen.Uint16(d.b[6:8])) - } else if x == 2 { - d.r.readb(d.b[4:8]) - v = uint64(bigen.Uint32(d.b[4:8])) - } else { - d.r.readb(d.b[:8]) - v = bigen.Uint64(d.b[:8]) - } - return -} - -func (d *bincDecDriver) decStringAndBytes(bs []byte, withString, zerocopy bool) ( - bs2 []byte, s string) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == bincVdSpecial<<4|bincSpNil { - d.bdRead = false - return - } - var slen = -1 - // var ok bool - switch d.vd { - case bincVdString, bincVdByteArray: - slen = d.decLen() - if zerocopy { - if d.br { - bs2 = d.r.readx(slen) - } else if len(bs) == 0 { - bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, d.b[:]) - } else { - bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, bs) - } - } else { - bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, bs) - } - if withString { - s = string(bs2) - } - case bincVdSymbol: - // zerocopy doesn't apply for symbols, - // as the values must be stored in a table for later use. - // - //from vs: extract numSymbolBytes, containsStringVal, strLenPrecision, - //extract symbol - //if containsStringVal, read it and put in map - //else look in map for string value - var symbol uint16 - vs := d.vs - if vs&0x8 == 0 { - symbol = uint16(d.r.readn1()) - } else { - symbol = uint16(bigen.Uint16(d.r.readx(2))) - } - if d.s == nil { - d.s = make([]bincDecSymbol, 0, 16) - } - - if vs&0x4 == 0 { - for i := range d.s { - j := &d.s[i] - if j.i == symbol { - bs2 = j.b - if withString { - if j.s == "" && bs2 != nil { - j.s = string(bs2) - } - s = j.s - } - break - } - } - } else { - switch vs & 0x3 { - case 0: - slen = int(d.r.readn1()) - case 1: - slen = int(bigen.Uint16(d.r.readx(2))) - case 2: - slen = int(bigen.Uint32(d.r.readx(4))) - case 3: - slen = int(bigen.Uint64(d.r.readx(8))) - } - // since using symbols, do not store any part of - // the parameter bs in the map, as it might be a shared buffer. - // bs2 = decByteSlice(d.r, slen, bs) - bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, nil) - if withString { - s = string(bs2) - } - d.s = append(d.s, bincDecSymbol{i: symbol, s: s, b: bs2}) - } - default: - d.d.errorf("string/bytes - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs)) - return - } - d.bdRead = false - return -} - -func (d *bincDecDriver) DecodeString() (s string) { - // DecodeBytes does not accommodate symbols, whose impl stores string version in map. - // Use decStringAndBytes directly. - // return string(d.DecodeBytes(d.b[:], true, true)) - _, s = d.decStringAndBytes(d.b[:], true, true) - return -} - -func (d *bincDecDriver) DecodeStringAsBytes() (s []byte) { - s, _ = d.decStringAndBytes(d.b[:], false, true) - return -} - -func (d *bincDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == bincVdSpecial<<4|bincSpNil { - d.bdRead = false - return nil - } - // check if an "array" of uint8's (see ContainerType for how to infer if an array) - if d.vd == bincVdArray { - bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d) - return - } - var clen int - if d.vd == bincVdString || d.vd == bincVdByteArray { - clen = d.decLen() - } else { - d.d.errorf("bytes - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs)) - return - } - d.bdRead = false - if zerocopy { - if d.br { - return d.r.readx(clen) - } else if len(bs) == 0 { - bs = d.b[:] - } - } - return decByteSlice(d.r, clen, d.d.h.MaxInitLen, bs) -} - -func (d *bincDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) { - if xtag > 0xff { - d.d.errorf("ext: tag must be <= 0xff; got: %v", xtag) - return - } - realxtag1, xbs := d.decodeExtV(ext != nil, uint8(xtag)) - realxtag = uint64(realxtag1) - if ext == nil { - re := rv.(*RawExt) - re.Tag = realxtag - re.Data = detachZeroCopyBytes(d.br, re.Data, xbs) - } else { - ext.ReadExt(rv, xbs) - } - return -} - -func (d *bincDecDriver) decodeExtV(verifyTag bool, tag byte) (xtag byte, xbs []byte) { - if !d.bdRead { - d.readNextBd() - } - if d.vd == bincVdCustomExt { - l := d.decLen() - xtag = d.r.readn1() - if verifyTag && xtag != tag { - d.d.errorf("wrong extension tag - got %b, expecting: %v", xtag, tag) - return - } - xbs = d.r.readx(l) - } else if d.vd == bincVdByteArray { - xbs = d.DecodeBytes(nil, true) - } else { - d.d.errorf("ext - expecting extensions or byte array - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs)) - return - } - d.bdRead = false - return -} - -func (d *bincDecDriver) DecodeNaked() { - if !d.bdRead { - d.readNextBd() - } - - n := d.d.n - var decodeFurther bool - - switch d.vd { - case bincVdSpecial: - switch d.vs { - case bincSpNil: - n.v = valueTypeNil - case bincSpFalse: - n.v = valueTypeBool - n.b = false - case bincSpTrue: - n.v = valueTypeBool - n.b = true - case bincSpNan: - n.v = valueTypeFloat - n.f = math.NaN() - case bincSpPosInf: - n.v = valueTypeFloat - n.f = math.Inf(1) - case bincSpNegInf: - n.v = valueTypeFloat - n.f = math.Inf(-1) - case bincSpZeroFloat: - n.v = valueTypeFloat - n.f = float64(0) - case bincSpZero: - n.v = valueTypeUint - n.u = uint64(0) // int8(0) - case bincSpNegOne: - n.v = valueTypeInt - n.i = int64(-1) // int8(-1) - default: - d.d.errorf("cannot infer value - unrecognized special value from descriptor %x-%x/%s", d.vd, d.vs, bincdesc(d.vd, d.vs)) - } - case bincVdSmallInt: - n.v = valueTypeUint - n.u = uint64(int8(d.vs)) + 1 // int8(d.vs) + 1 - case bincVdPosInt: - n.v = valueTypeUint - n.u = d.decUint() - case bincVdNegInt: - n.v = valueTypeInt - n.i = -(int64(d.decUint())) - case bincVdFloat: - n.v = valueTypeFloat - n.f = d.decFloat() - case bincVdSymbol: - n.v = valueTypeSymbol - n.s = d.DecodeString() - case bincVdString: - n.v = valueTypeString - n.s = d.DecodeString() - case bincVdByteArray: - n.v = valueTypeBytes - n.l = d.DecodeBytes(nil, false) - case bincVdTimestamp: - n.v = valueTypeTime - tt, err := bincDecodeTime(d.r.readx(int(d.vs))) - if err != nil { - panic(err) - } - n.t = tt - case bincVdCustomExt: - n.v = valueTypeExt - l := d.decLen() - n.u = uint64(d.r.readn1()) - n.l = d.r.readx(l) - case bincVdArray: - n.v = valueTypeArray - decodeFurther = true - case bincVdMap: - n.v = valueTypeMap - decodeFurther = true - default: - d.d.errorf("cannot infer value - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs)) - } - - if !decodeFurther { - d.bdRead = false - } - if n.v == valueTypeUint && d.h.SignedInteger { - n.v = valueTypeInt - n.i = int64(n.u) - } - return -} - -//------------------------------------ - -//BincHandle is a Handle for the Binc Schema-Free Encoding Format -//defined at https://github.com/ugorji/binc . -// -//BincHandle currently supports all Binc features with the following EXCEPTIONS: -// - only integers up to 64 bits of precision are supported. -// big integers are unsupported. -// - Only IEEE 754 binary32 and binary64 floats are supported (ie Go float32 and float64 types). -// extended precision and decimal IEEE 754 floats are unsupported. -// - Only UTF-8 strings supported. -// Unicode_Other Binc types (UTF16, UTF32) are currently unsupported. -// -//Note that these EXCEPTIONS are temporary and full support is possible and may happen soon. -type BincHandle struct { - BasicHandle - binaryEncodingType - noElemSeparators - - // AsSymbols defines what should be encoded as symbols. - // - // Encoding as symbols can reduce the encoded size significantly. - // - // However, during decoding, each string to be encoded as a symbol must - // be checked to see if it has been seen before. Consequently, encoding time - // will increase if using symbols, because string comparisons has a clear cost. - // - // Values: - // - 0: default: library uses best judgement - // - 1: use symbols - // - 2: do not use symbols - AsSymbols uint8 - - // AsSymbols: may later on introduce more options ... - // - m: map keys - // - s: struct fields - // - n: none - // - a: all: same as m, s, ... - - // _ [1]uint64 // padding -} - -// Name returns the name of the handle: binc -func (h *BincHandle) Name() string { return "binc" } - -// SetBytesExt sets an extension -func (h *BincHandle) SetBytesExt(rt reflect.Type, tag uint64, ext BytesExt) (err error) { - return h.SetExt(rt, tag, &extWrapper{ext, interfaceExtFailer{}}) -} - -func (h *BincHandle) newEncDriver(e *Encoder) encDriver { - return &bincEncDriver{e: e, h: h, w: e.w} -} - -func (h *BincHandle) newDecDriver(d *Decoder) decDriver { - return &bincDecDriver{d: d, h: h, r: d.r, br: d.bytes} -} - -func (e *bincEncDriver) reset() { - e.w = e.e.w - e.s = 0 - e.c = 0 - e.m = nil -} - -func (d *bincDecDriver) reset() { - d.r, d.br = d.d.r, d.d.bytes - d.s = nil - d.bd, d.bdRead, d.vd, d.vs = 0, false, 0, 0 -} - -// var timeDigits = [...]byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'} - -// EncodeTime encodes a time.Time as a []byte, including -// information on the instant in time and UTC offset. -// -// Format Description -// -// A timestamp is composed of 3 components: -// -// - secs: signed integer representing seconds since unix epoch -// - nsces: unsigned integer representing fractional seconds as a -// nanosecond offset within secs, in the range 0 <= nsecs < 1e9 -// - tz: signed integer representing timezone offset in minutes east of UTC, -// and a dst (daylight savings time) flag -// -// When encoding a timestamp, the first byte is the descriptor, which -// defines which components are encoded and how many bytes are used to -// encode secs and nsecs components. *If secs/nsecs is 0 or tz is UTC, it -// is not encoded in the byte array explicitly*. -// -// Descriptor 8 bits are of the form `A B C DDD EE`: -// A: Is secs component encoded? 1 = true -// B: Is nsecs component encoded? 1 = true -// C: Is tz component encoded? 1 = true -// DDD: Number of extra bytes for secs (range 0-7). -// If A = 1, secs encoded in DDD+1 bytes. -// If A = 0, secs is not encoded, and is assumed to be 0. -// If A = 1, then we need at least 1 byte to encode secs. -// DDD says the number of extra bytes beyond that 1. -// E.g. if DDD=0, then secs is represented in 1 byte. -// if DDD=2, then secs is represented in 3 bytes. -// EE: Number of extra bytes for nsecs (range 0-3). -// If B = 1, nsecs encoded in EE+1 bytes (similar to secs/DDD above) -// -// Following the descriptor bytes, subsequent bytes are: -// -// secs component encoded in `DDD + 1` bytes (if A == 1) -// nsecs component encoded in `EE + 1` bytes (if B == 1) -// tz component encoded in 2 bytes (if C == 1) -// -// secs and nsecs components are integers encoded in a BigEndian -// 2-complement encoding format. -// -// tz component is encoded as 2 bytes (16 bits). Most significant bit 15 to -// Least significant bit 0 are described below: -// -// Timezone offset has a range of -12:00 to +14:00 (ie -720 to +840 minutes). -// Bit 15 = have\_dst: set to 1 if we set the dst flag. -// Bit 14 = dst\_on: set to 1 if dst is in effect at the time, or 0 if not. -// Bits 13..0 = timezone offset in minutes. It is a signed integer in Big Endian format. -// -func bincEncodeTime(t time.Time) []byte { - //t := rv.Interface().(time.Time) - tsecs, tnsecs := t.Unix(), t.Nanosecond() - var ( - bd byte - btmp [8]byte - bs [16]byte - i int = 1 - ) - l := t.Location() - if l == time.UTC { - l = nil - } - if tsecs != 0 { - bd = bd | 0x80 - bigen.PutUint64(btmp[:], uint64(tsecs)) - f := pruneSignExt(btmp[:], tsecs >= 0) - bd = bd | (byte(7-f) << 2) - copy(bs[i:], btmp[f:]) - i = i + (8 - f) - } - if tnsecs != 0 { - bd = bd | 0x40 - bigen.PutUint32(btmp[:4], uint32(tnsecs)) - f := pruneSignExt(btmp[:4], true) - bd = bd | byte(3-f) - copy(bs[i:], btmp[f:4]) - i = i + (4 - f) - } - if l != nil { - bd = bd | 0x20 - // Note that Go Libs do not give access to dst flag. - _, zoneOffset := t.Zone() - //zoneName, zoneOffset := t.Zone() - zoneOffset /= 60 - z := uint16(zoneOffset) - bigen.PutUint16(btmp[:2], z) - // clear dst flags - bs[i] = btmp[0] & 0x3f - bs[i+1] = btmp[1] - i = i + 2 - } - bs[0] = bd - return bs[0:i] -} - -// bincDecodeTime decodes a []byte into a time.Time. -func bincDecodeTime(bs []byte) (tt time.Time, err error) { - bd := bs[0] - var ( - tsec int64 - tnsec uint32 - tz uint16 - i byte = 1 - i2 byte - n byte - ) - if bd&(1<<7) != 0 { - var btmp [8]byte - n = ((bd >> 2) & 0x7) + 1 - i2 = i + n - copy(btmp[8-n:], bs[i:i2]) - //if first bit of bs[i] is set, then fill btmp[0..8-n] with 0xff (ie sign extend it) - if bs[i]&(1<<7) != 0 { - copy(btmp[0:8-n], bsAll0xff) - //for j,k := byte(0), 8-n; j < k; j++ { btmp[j] = 0xff } - } - i = i2 - tsec = int64(bigen.Uint64(btmp[:])) - } - if bd&(1<<6) != 0 { - var btmp [4]byte - n = (bd & 0x3) + 1 - i2 = i + n - copy(btmp[4-n:], bs[i:i2]) - i = i2 - tnsec = bigen.Uint32(btmp[:]) - } - if bd&(1<<5) == 0 { - tt = time.Unix(tsec, int64(tnsec)).UTC() - return - } - // In stdlib time.Parse, when a date is parsed without a zone name, it uses "" as zone name. - // However, we need name here, so it can be shown when time is printed. - // Zone name is in form: UTC-08:00. - // Note that Go Libs do not give access to dst flag, so we ignore dst bits - - i2 = i + 2 - tz = bigen.Uint16(bs[i:i2]) - // i = i2 - // sign extend sign bit into top 2 MSB (which were dst bits): - if tz&(1<<13) == 0 { // positive - tz = tz & 0x3fff //clear 2 MSBs: dst bits - } else { // negative - tz = tz | 0xc000 //set 2 MSBs: dst bits - } - tzint := int16(tz) - if tzint == 0 { - tt = time.Unix(tsec, int64(tnsec)).UTC() - } else { - // For Go Time, do not use a descriptive timezone. - // It's unnecessary, and makes it harder to do a reflect.DeepEqual. - // The Offset already tells what the offset should be, if not on UTC and unknown zone name. - // var zoneName = timeLocUTCName(tzint) - tt = time.Unix(tsec, int64(tnsec)).In(time.FixedZone("", int(tzint)*60)) - } - return -} - -var _ decDriver = (*bincDecDriver)(nil) -var _ encDriver = (*bincEncDriver)(nil) diff --git a/vendor/github.com/ugorji/go/codec/cbor.go b/vendor/github.com/ugorji/go/codec/cbor.go deleted file mode 100644 index 7633c04ac..000000000 --- a/vendor/github.com/ugorji/go/codec/cbor.go +++ /dev/null @@ -1,756 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -import ( - "math" - "reflect" - "time" -) - -const ( - cborMajorUint byte = iota - cborMajorNegInt - cborMajorBytes - cborMajorText - cborMajorArray - cborMajorMap - cborMajorTag - cborMajorOther -) - -const ( - cborBdFalse byte = 0xf4 + iota - cborBdTrue - cborBdNil - cborBdUndefined - cborBdExt - cborBdFloat16 - cborBdFloat32 - cborBdFloat64 -) - -const ( - cborBdIndefiniteBytes byte = 0x5f - cborBdIndefiniteString = 0x7f - cborBdIndefiniteArray = 0x9f - cborBdIndefiniteMap = 0xbf - cborBdBreak = 0xff -) - -// These define some in-stream descriptors for -// manual encoding e.g. when doing explicit indefinite-length -const ( - CborStreamBytes byte = 0x5f - CborStreamString = 0x7f - CborStreamArray = 0x9f - CborStreamMap = 0xbf - CborStreamBreak = 0xff -) - -const ( - cborBaseUint byte = 0x00 - cborBaseNegInt = 0x20 - cborBaseBytes = 0x40 - cborBaseString = 0x60 - cborBaseArray = 0x80 - cborBaseMap = 0xa0 - cborBaseTag = 0xc0 - cborBaseSimple = 0xe0 -) - -func cbordesc(bd byte) string { - switch bd { - case cborBdNil: - return "nil" - case cborBdFalse: - return "false" - case cborBdTrue: - return "true" - case cborBdFloat16, cborBdFloat32, cborBdFloat64: - return "float" - case cborBdIndefiniteBytes: - return "bytes*" - case cborBdIndefiniteString: - return "string*" - case cborBdIndefiniteArray: - return "array*" - case cborBdIndefiniteMap: - return "map*" - default: - switch { - case bd >= cborBaseUint && bd < cborBaseNegInt: - return "(u)int" - case bd >= cborBaseNegInt && bd < cborBaseBytes: - return "int" - case bd >= cborBaseBytes && bd < cborBaseString: - return "bytes" - case bd >= cborBaseString && bd < cborBaseArray: - return "string" - case bd >= cborBaseArray && bd < cborBaseMap: - return "array" - case bd >= cborBaseMap && bd < cborBaseTag: - return "map" - case bd >= cborBaseTag && bd < cborBaseSimple: - return "ext" - default: - return "unknown" - } - } -} - -// ------------------- - -type cborEncDriver struct { - noBuiltInTypes - encDriverNoopContainerWriter - // encNoSeparator - e *Encoder - w encWriter - h *CborHandle - x [8]byte - _ [3]uint64 // padding -} - -func (e *cborEncDriver) EncodeNil() { - e.w.writen1(cborBdNil) -} - -func (e *cborEncDriver) EncodeBool(b bool) { - if b { - e.w.writen1(cborBdTrue) - } else { - e.w.writen1(cborBdFalse) - } -} - -func (e *cborEncDriver) EncodeFloat32(f float32) { - e.w.writen1(cborBdFloat32) - bigenHelper{e.x[:4], e.w}.writeUint32(math.Float32bits(f)) -} - -func (e *cborEncDriver) EncodeFloat64(f float64) { - e.w.writen1(cborBdFloat64) - bigenHelper{e.x[:8], e.w}.writeUint64(math.Float64bits(f)) -} - -func (e *cborEncDriver) encUint(v uint64, bd byte) { - if v <= 0x17 { - e.w.writen1(byte(v) + bd) - } else if v <= math.MaxUint8 { - e.w.writen2(bd+0x18, uint8(v)) - } else if v <= math.MaxUint16 { - e.w.writen1(bd + 0x19) - bigenHelper{e.x[:2], e.w}.writeUint16(uint16(v)) - } else if v <= math.MaxUint32 { - e.w.writen1(bd + 0x1a) - bigenHelper{e.x[:4], e.w}.writeUint32(uint32(v)) - } else { // if v <= math.MaxUint64 { - e.w.writen1(bd + 0x1b) - bigenHelper{e.x[:8], e.w}.writeUint64(v) - } -} - -func (e *cborEncDriver) EncodeInt(v int64) { - if v < 0 { - e.encUint(uint64(-1-v), cborBaseNegInt) - } else { - e.encUint(uint64(v), cborBaseUint) - } -} - -func (e *cborEncDriver) EncodeUint(v uint64) { - e.encUint(v, cborBaseUint) -} - -func (e *cborEncDriver) encLen(bd byte, length int) { - e.encUint(uint64(length), bd) -} - -func (e *cborEncDriver) EncodeTime(t time.Time) { - if t.IsZero() { - e.EncodeNil() - } else if e.h.TimeRFC3339 { - e.encUint(0, cborBaseTag) - e.EncodeString(cUTF8, t.Format(time.RFC3339Nano)) - } else { - e.encUint(1, cborBaseTag) - t = t.UTC().Round(time.Microsecond) - sec, nsec := t.Unix(), uint64(t.Nanosecond()) - if nsec == 0 { - e.EncodeInt(sec) - } else { - e.EncodeFloat64(float64(sec) + float64(nsec)/1e9) - } - } -} - -func (e *cborEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, en *Encoder) { - e.encUint(uint64(xtag), cborBaseTag) - if v := ext.ConvertExt(rv); v == nil { - e.EncodeNil() - } else { - en.encode(v) - } -} - -func (e *cborEncDriver) EncodeRawExt(re *RawExt, en *Encoder) { - e.encUint(uint64(re.Tag), cborBaseTag) - if false && re.Data != nil { - en.encode(re.Data) - } else if re.Value != nil { - en.encode(re.Value) - } else { - e.EncodeNil() - } -} - -func (e *cborEncDriver) WriteArrayStart(length int) { - if e.h.IndefiniteLength { - e.w.writen1(cborBdIndefiniteArray) - } else { - e.encLen(cborBaseArray, length) - } -} - -func (e *cborEncDriver) WriteMapStart(length int) { - if e.h.IndefiniteLength { - e.w.writen1(cborBdIndefiniteMap) - } else { - e.encLen(cborBaseMap, length) - } -} - -func (e *cborEncDriver) WriteMapEnd() { - if e.h.IndefiniteLength { - e.w.writen1(cborBdBreak) - } -} - -func (e *cborEncDriver) WriteArrayEnd() { - if e.h.IndefiniteLength { - e.w.writen1(cborBdBreak) - } -} - -func (e *cborEncDriver) EncodeString(c charEncoding, v string) { - e.encStringBytesS(cborBaseString, v) -} - -func (e *cborEncDriver) EncodeStringBytes(c charEncoding, v []byte) { - if v == nil { - e.EncodeNil() - } else if c == cRAW { - e.encStringBytesS(cborBaseBytes, stringView(v)) - } else { - e.encStringBytesS(cborBaseString, stringView(v)) - } -} - -func (e *cborEncDriver) encStringBytesS(bb byte, v string) { - if e.h.IndefiniteLength { - if bb == cborBaseBytes { - e.w.writen1(cborBdIndefiniteBytes) - } else { - e.w.writen1(cborBdIndefiniteString) - } - blen := len(v) / 4 - if blen == 0 { - blen = 64 - } else if blen > 1024 { - blen = 1024 - } - for i := 0; i < len(v); { - var v2 string - i2 := i + blen - if i2 < len(v) { - v2 = v[i:i2] - } else { - v2 = v[i:] - } - e.encLen(bb, len(v2)) - e.w.writestr(v2) - i = i2 - } - e.w.writen1(cborBdBreak) - } else { - e.encLen(bb, len(v)) - e.w.writestr(v) - } -} - -// ---------------------- - -type cborDecDriver struct { - d *Decoder - h *CborHandle - r decReader - // b [scratchByteArrayLen]byte - br bool // bytes reader - bdRead bool - bd byte - noBuiltInTypes - // decNoSeparator - decDriverNoopContainerReader - _ [3]uint64 // padding -} - -func (d *cborDecDriver) readNextBd() { - d.bd = d.r.readn1() - d.bdRead = true -} - -func (d *cborDecDriver) uncacheRead() { - if d.bdRead { - d.r.unreadn1() - d.bdRead = false - } -} - -func (d *cborDecDriver) ContainerType() (vt valueType) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == cborBdNil { - return valueTypeNil - } else if d.bd == cborBdIndefiniteBytes || (d.bd >= cborBaseBytes && d.bd < cborBaseString) { - return valueTypeBytes - } else if d.bd == cborBdIndefiniteString || (d.bd >= cborBaseString && d.bd < cborBaseArray) { - return valueTypeString - } else if d.bd == cborBdIndefiniteArray || (d.bd >= cborBaseArray && d.bd < cborBaseMap) { - return valueTypeArray - } else if d.bd == cborBdIndefiniteMap || (d.bd >= cborBaseMap && d.bd < cborBaseTag) { - return valueTypeMap - } - // else { - // d.d.errorf("isContainerType: unsupported parameter: %v", vt) - // } - return valueTypeUnset -} - -func (d *cborDecDriver) TryDecodeAsNil() bool { - if !d.bdRead { - d.readNextBd() - } - // treat Nil and Undefined as nil values - if d.bd == cborBdNil || d.bd == cborBdUndefined { - d.bdRead = false - return true - } - return false -} - -func (d *cborDecDriver) CheckBreak() bool { - if !d.bdRead { - d.readNextBd() - } - if d.bd == cborBdBreak { - d.bdRead = false - return true - } - return false -} - -func (d *cborDecDriver) decUint() (ui uint64) { - v := d.bd & 0x1f - if v <= 0x17 { - ui = uint64(v) - } else { - if v == 0x18 { - ui = uint64(d.r.readn1()) - } else if v == 0x19 { - ui = uint64(bigen.Uint16(d.r.readx(2))) - } else if v == 0x1a { - ui = uint64(bigen.Uint32(d.r.readx(4))) - } else if v == 0x1b { - ui = uint64(bigen.Uint64(d.r.readx(8))) - } else { - d.d.errorf("invalid descriptor decoding uint: %x/%s", d.bd, cbordesc(d.bd)) - return - } - } - return -} - -func (d *cborDecDriver) decCheckInteger() (neg bool) { - if !d.bdRead { - d.readNextBd() - } - major := d.bd >> 5 - if major == cborMajorUint { - } else if major == cborMajorNegInt { - neg = true - } else { - d.d.errorf("not an integer - invalid major %v from descriptor %x/%s", major, d.bd, cbordesc(d.bd)) - return - } - return -} - -func (d *cborDecDriver) DecodeInt64() (i int64) { - neg := d.decCheckInteger() - ui := d.decUint() - // check if this number can be converted to an int without overflow - if neg { - i = -(chkOvf.SignedIntV(ui + 1)) - } else { - i = chkOvf.SignedIntV(ui) - } - d.bdRead = false - return -} - -func (d *cborDecDriver) DecodeUint64() (ui uint64) { - if d.decCheckInteger() { - d.d.errorf("assigning negative signed value to unsigned type") - return - } - ui = d.decUint() - d.bdRead = false - return -} - -func (d *cborDecDriver) DecodeFloat64() (f float64) { - if !d.bdRead { - d.readNextBd() - } - if bd := d.bd; bd == cborBdFloat16 { - f = float64(math.Float32frombits(halfFloatToFloatBits(bigen.Uint16(d.r.readx(2))))) - } else if bd == cborBdFloat32 { - f = float64(math.Float32frombits(bigen.Uint32(d.r.readx(4)))) - } else if bd == cborBdFloat64 { - f = math.Float64frombits(bigen.Uint64(d.r.readx(8))) - } else if bd >= cborBaseUint && bd < cborBaseBytes { - f = float64(d.DecodeInt64()) - } else { - d.d.errorf("float only valid from float16/32/64 - invalid descriptor %x/%s", bd, cbordesc(bd)) - return - } - d.bdRead = false - return -} - -// bool can be decoded from bool only (single byte). -func (d *cborDecDriver) DecodeBool() (b bool) { - if !d.bdRead { - d.readNextBd() - } - if bd := d.bd; bd == cborBdTrue { - b = true - } else if bd == cborBdFalse { - } else { - d.d.errorf("not bool - %s %x/%s", msgBadDesc, d.bd, cbordesc(d.bd)) - return - } - d.bdRead = false - return -} - -func (d *cborDecDriver) ReadMapStart() (length int) { - if !d.bdRead { - d.readNextBd() - } - d.bdRead = false - if d.bd == cborBdIndefiniteMap { - return -1 - } - return d.decLen() -} - -func (d *cborDecDriver) ReadArrayStart() (length int) { - if !d.bdRead { - d.readNextBd() - } - d.bdRead = false - if d.bd == cborBdIndefiniteArray { - return -1 - } - return d.decLen() -} - -func (d *cborDecDriver) decLen() int { - return int(d.decUint()) -} - -func (d *cborDecDriver) decAppendIndefiniteBytes(bs []byte) []byte { - d.bdRead = false - for { - if d.CheckBreak() { - break - } - if major := d.bd >> 5; major != cborMajorBytes && major != cborMajorText { - d.d.errorf("expect bytes/string major type in indefinite string/bytes;"+ - " got major %v from descriptor %x/%x", major, d.bd, cbordesc(d.bd)) - return nil - } - n := d.decLen() - oldLen := len(bs) - newLen := oldLen + n - if newLen > cap(bs) { - bs2 := make([]byte, newLen, 2*cap(bs)+n) - copy(bs2, bs) - bs = bs2 - } else { - bs = bs[:newLen] - } - d.r.readb(bs[oldLen:newLen]) - // bs = append(bs, d.r.readn()...) - d.bdRead = false - } - d.bdRead = false - return bs -} - -func (d *cborDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == cborBdNil || d.bd == cborBdUndefined { - d.bdRead = false - return nil - } - if d.bd == cborBdIndefiniteBytes || d.bd == cborBdIndefiniteString { - d.bdRead = false - if bs == nil { - if zerocopy { - return d.decAppendIndefiniteBytes(d.d.b[:0]) - } - return d.decAppendIndefiniteBytes(zeroByteSlice) - } - return d.decAppendIndefiniteBytes(bs[:0]) - } - // check if an "array" of uint8's (see ContainerType for how to infer if an array) - if d.bd == cborBdIndefiniteArray || (d.bd >= cborBaseArray && d.bd < cborBaseMap) { - bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d) - return - } - clen := d.decLen() - d.bdRead = false - if zerocopy { - if d.br { - return d.r.readx(clen) - } else if len(bs) == 0 { - bs = d.d.b[:] - } - } - return decByteSlice(d.r, clen, d.h.MaxInitLen, bs) -} - -func (d *cborDecDriver) DecodeString() (s string) { - return string(d.DecodeBytes(d.d.b[:], true)) -} - -func (d *cborDecDriver) DecodeStringAsBytes() (s []byte) { - return d.DecodeBytes(d.d.b[:], true) -} - -func (d *cborDecDriver) DecodeTime() (t time.Time) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == cborBdNil || d.bd == cborBdUndefined { - d.bdRead = false - return - } - xtag := d.decUint() - d.bdRead = false - return d.decodeTime(xtag) -} - -func (d *cborDecDriver) decodeTime(xtag uint64) (t time.Time) { - if !d.bdRead { - d.readNextBd() - } - switch xtag { - case 0: - var err error - if t, err = time.Parse(time.RFC3339, stringView(d.DecodeStringAsBytes())); err != nil { - d.d.errorv(err) - } - case 1: - // decode an int64 or a float, and infer time.Time from there. - // for floats, round to microseconds, as that is what is guaranteed to fit well. - switch { - case d.bd == cborBdFloat16, d.bd == cborBdFloat32: - f1, f2 := math.Modf(d.DecodeFloat64()) - t = time.Unix(int64(f1), int64(f2*1e9)) - case d.bd == cborBdFloat64: - f1, f2 := math.Modf(d.DecodeFloat64()) - t = time.Unix(int64(f1), int64(f2*1e9)) - case d.bd >= cborBaseUint && d.bd < cborBaseNegInt, - d.bd >= cborBaseNegInt && d.bd < cborBaseBytes: - t = time.Unix(d.DecodeInt64(), 0) - default: - d.d.errorf("time.Time can only be decoded from a number (or RFC3339 string)") - } - default: - d.d.errorf("invalid tag for time.Time - expecting 0 or 1, got 0x%x", xtag) - } - t = t.UTC().Round(time.Microsecond) - return -} - -func (d *cborDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) { - if !d.bdRead { - d.readNextBd() - } - u := d.decUint() - d.bdRead = false - realxtag = u - if ext == nil { - re := rv.(*RawExt) - re.Tag = realxtag - d.d.decode(&re.Value) - } else if xtag != realxtag { - d.d.errorf("Wrong extension tag. Got %b. Expecting: %v", realxtag, xtag) - return - } else { - var v interface{} - d.d.decode(&v) - ext.UpdateExt(rv, v) - } - d.bdRead = false - return -} - -func (d *cborDecDriver) DecodeNaked() { - if !d.bdRead { - d.readNextBd() - } - - n := d.d.n - var decodeFurther bool - - switch d.bd { - case cborBdNil: - n.v = valueTypeNil - case cborBdFalse: - n.v = valueTypeBool - n.b = false - case cborBdTrue: - n.v = valueTypeBool - n.b = true - case cborBdFloat16, cborBdFloat32, cborBdFloat64: - n.v = valueTypeFloat - n.f = d.DecodeFloat64() - case cborBdIndefiniteBytes: - n.v = valueTypeBytes - n.l = d.DecodeBytes(nil, false) - case cborBdIndefiniteString: - n.v = valueTypeString - n.s = d.DecodeString() - case cborBdIndefiniteArray: - n.v = valueTypeArray - decodeFurther = true - case cborBdIndefiniteMap: - n.v = valueTypeMap - decodeFurther = true - default: - switch { - case d.bd >= cborBaseUint && d.bd < cborBaseNegInt: - if d.h.SignedInteger { - n.v = valueTypeInt - n.i = d.DecodeInt64() - } else { - n.v = valueTypeUint - n.u = d.DecodeUint64() - } - case d.bd >= cborBaseNegInt && d.bd < cborBaseBytes: - n.v = valueTypeInt - n.i = d.DecodeInt64() - case d.bd >= cborBaseBytes && d.bd < cborBaseString: - n.v = valueTypeBytes - n.l = d.DecodeBytes(nil, false) - case d.bd >= cborBaseString && d.bd < cborBaseArray: - n.v = valueTypeString - n.s = d.DecodeString() - case d.bd >= cborBaseArray && d.bd < cborBaseMap: - n.v = valueTypeArray - decodeFurther = true - case d.bd >= cborBaseMap && d.bd < cborBaseTag: - n.v = valueTypeMap - decodeFurther = true - case d.bd >= cborBaseTag && d.bd < cborBaseSimple: - n.v = valueTypeExt - n.u = d.decUint() - n.l = nil - if n.u == 0 || n.u == 1 { - d.bdRead = false - n.v = valueTypeTime - n.t = d.decodeTime(n.u) - } - // d.bdRead = false - // d.d.decode(&re.Value) // handled by decode itself. - // decodeFurther = true - default: - d.d.errorf("decodeNaked: Unrecognized d.bd: 0x%x", d.bd) - return - } - } - - if !decodeFurther { - d.bdRead = false - } - return -} - -// ------------------------- - -// CborHandle is a Handle for the CBOR encoding format, -// defined at http://tools.ietf.org/html/rfc7049 and documented further at http://cbor.io . -// -// CBOR is comprehensively supported, including support for: -// - indefinite-length arrays/maps/bytes/strings -// - (extension) tags in range 0..0xffff (0 .. 65535) -// - half, single and double-precision floats -// - all numbers (1, 2, 4 and 8-byte signed and unsigned integers) -// - nil, true, false, ... -// - arrays and maps, bytes and text strings -// -// None of the optional extensions (with tags) defined in the spec are supported out-of-the-box. -// Users can implement them as needed (using SetExt), including spec-documented ones: -// - timestamp, BigNum, BigFloat, Decimals, -// - Encoded Text (e.g. URL, regexp, base64, MIME Message), etc. -type CborHandle struct { - binaryEncodingType - noElemSeparators - BasicHandle - - // IndefiniteLength=true, means that we encode using indefinitelength - IndefiniteLength bool - - // TimeRFC3339 says to encode time.Time using RFC3339 format. - // If unset, we encode time.Time using seconds past epoch. - TimeRFC3339 bool - - // _ [1]uint64 // padding -} - -// Name returns the name of the handle: cbor -func (h *CborHandle) Name() string { return "cbor" } - -// SetInterfaceExt sets an extension -func (h *CborHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) { - return h.SetExt(rt, tag, &extWrapper{bytesExtFailer{}, ext}) -} - -func (h *CborHandle) newEncDriver(e *Encoder) encDriver { - return &cborEncDriver{e: e, w: e.w, h: h} -} - -func (h *CborHandle) newDecDriver(d *Decoder) decDriver { - return &cborDecDriver{d: d, h: h, r: d.r, br: d.bytes} -} - -func (e *cborEncDriver) reset() { - e.w = e.e.w -} - -func (d *cborDecDriver) reset() { - d.r, d.br = d.d.r, d.d.bytes - d.bd, d.bdRead = 0, false -} - -var _ decDriver = (*cborDecDriver)(nil) -var _ encDriver = (*cborEncDriver)(nil) diff --git a/vendor/github.com/ugorji/go/codec/decode.go b/vendor/github.com/ugorji/go/codec/decode.go deleted file mode 100644 index 1c0817aaf..000000000 --- a/vendor/github.com/ugorji/go/codec/decode.go +++ /dev/null @@ -1,2552 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -import ( - "encoding" - "errors" - "fmt" - "io" - "reflect" - "strconv" - "sync" - "time" -) - -// Some tagging information for error messages. -const ( - msgBadDesc = "unrecognized descriptor byte" - msgDecCannotExpandArr = "cannot expand go array from %v to stream length: %v" -) - -const decDefSliceCap = 8 -const decDefChanCap = 64 // should be large, as cap cannot be expanded -const decScratchByteArrayLen = cacheLineSize - 8 - -var ( - errstrOnlyMapOrArrayCanDecodeIntoStruct = "only encoded map or array can be decoded into a struct" - errstrCannotDecodeIntoNil = "cannot decode into nil" - - errmsgExpandSliceOverflow = "expand slice: slice overflow" - errmsgExpandSliceCannotChange = "expand slice: cannot change" - - errDecoderNotInitialized = errors.New("Decoder not initialized") - - errDecUnreadByteNothingToRead = errors.New("cannot unread - nothing has been read") - errDecUnreadByteLastByteNotRead = errors.New("cannot unread - last byte has not been read") - errDecUnreadByteUnknown = errors.New("cannot unread - reason unknown") -) - -// decReader abstracts the reading source, allowing implementations that can -// read from an io.Reader or directly off a byte slice with zero-copying. -type decReader interface { - unreadn1() - - // readx will use the implementation scratch buffer if possible i.e. n < len(scratchbuf), OR - // just return a view of the []byte being decoded from. - // Ensure you call detachZeroCopyBytes later if this needs to be sent outside codec control. - readx(n int) []byte - readb([]byte) - readn1() uint8 - numread() int // number of bytes read - track() - stopTrack() []byte - - // skip will skip any byte that matches, and return the first non-matching byte - skip(accept *bitset256) (token byte) - // readTo will read any byte that matches, stopping once no-longer matching. - readTo(in []byte, accept *bitset256) (out []byte) - // readUntil will read, only stopping once it matches the 'stop' byte. - readUntil(in []byte, stop byte) (out []byte) -} - -type decDriver interface { - // this will check if the next token is a break. - CheckBreak() bool - // Note: TryDecodeAsNil should be careful not to share any temporary []byte with - // the rest of the decDriver. This is because sometimes, we optimize by holding onto - // a transient []byte, and ensuring the only other call we make to the decDriver - // during that time is maybe a TryDecodeAsNil() call. - TryDecodeAsNil() bool - // vt is one of: Bytes, String, Nil, Slice or Map. Return unSet if not known. - ContainerType() (vt valueType) - // IsBuiltinType(rt uintptr) bool - - // DecodeNaked will decode primitives (number, bool, string, []byte) and RawExt. - // For maps and arrays, it will not do the decoding in-band, but will signal - // the decoder, so that is done later, by setting the decNaked.valueType field. - // - // Note: Numbers are decoded as int64, uint64, float64 only (no smaller sized number types). - // for extensions, DecodeNaked must read the tag and the []byte if it exists. - // if the []byte is not read, then kInterfaceNaked will treat it as a Handle - // that stores the subsequent value in-band, and complete reading the RawExt. - // - // extensions should also use readx to decode them, for efficiency. - // kInterface will extract the detached byte slice if it has to pass it outside its realm. - DecodeNaked() - - // Deprecated: use DecodeInt64 and DecodeUint64 instead - // DecodeInt(bitsize uint8) (i int64) - // DecodeUint(bitsize uint8) (ui uint64) - - DecodeInt64() (i int64) - DecodeUint64() (ui uint64) - - DecodeFloat64() (f float64) - DecodeBool() (b bool) - // DecodeString can also decode symbols. - // It looks redundant as DecodeBytes is available. - // However, some codecs (e.g. binc) support symbols and can - // return a pre-stored string value, meaning that it can bypass - // the cost of []byte->string conversion. - DecodeString() (s string) - DecodeStringAsBytes() (v []byte) - - // DecodeBytes may be called directly, without going through reflection. - // Consequently, it must be designed to handle possible nil. - DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) - // DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOut []byte) - - // decodeExt will decode into a *RawExt or into an extension. - DecodeExt(v interface{}, xtag uint64, ext Ext) (realxtag uint64) - // decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte) - - DecodeTime() (t time.Time) - - ReadArrayStart() int - ReadArrayElem() - ReadArrayEnd() - ReadMapStart() int - ReadMapElemKey() - ReadMapElemValue() - ReadMapEnd() - - reset() - uncacheRead() -} - -type decDriverNoopContainerReader struct{} - -func (x decDriverNoopContainerReader) ReadArrayStart() (v int) { return } -func (x decDriverNoopContainerReader) ReadArrayElem() {} -func (x decDriverNoopContainerReader) ReadArrayEnd() {} -func (x decDriverNoopContainerReader) ReadMapStart() (v int) { return } -func (x decDriverNoopContainerReader) ReadMapElemKey() {} -func (x decDriverNoopContainerReader) ReadMapElemValue() {} -func (x decDriverNoopContainerReader) ReadMapEnd() {} -func (x decDriverNoopContainerReader) CheckBreak() (v bool) { return } - -// func (x decNoSeparator) uncacheRead() {} - -// DecodeOptions captures configuration options during decode. -type DecodeOptions struct { - // MapType specifies type to use during schema-less decoding of a map in the stream. - // If nil (unset), we default to map[string]interface{} iff json handle and MapStringAsKey=true, - // else map[interface{}]interface{}. - MapType reflect.Type - - // SliceType specifies type to use during schema-less decoding of an array in the stream. - // If nil (unset), we default to []interface{} for all formats. - SliceType reflect.Type - - // MaxInitLen defines the maxinum initial length that we "make" a collection - // (string, slice, map, chan). If 0 or negative, we default to a sensible value - // based on the size of an element in the collection. - // - // For example, when decoding, a stream may say that it has 2^64 elements. - // We should not auto-matically provision a slice of that size, to prevent Out-Of-Memory crash. - // Instead, we provision up to MaxInitLen, fill that up, and start appending after that. - MaxInitLen int - - // ReaderBufferSize is the size of the buffer used when reading. - // - // if > 0, we use a smart buffer internally for performance purposes. - ReaderBufferSize int - - // If ErrorIfNoField, return an error when decoding a map - // from a codec stream into a struct, and no matching struct field is found. - ErrorIfNoField bool - - // If ErrorIfNoArrayExpand, return an error when decoding a slice/array that cannot be expanded. - // For example, the stream contains an array of 8 items, but you are decoding into a [4]T array, - // or you are decoding into a slice of length 4 which is non-addressable (and so cannot be set). - ErrorIfNoArrayExpand bool - - // If SignedInteger, use the int64 during schema-less decoding of unsigned values (not uint64). - SignedInteger bool - - // MapValueReset controls how we decode into a map value. - // - // By default, we MAY retrieve the mapping for a key, and then decode into that. - // However, especially with big maps, that retrieval may be expensive and unnecessary - // if the stream already contains all that is necessary to recreate the value. - // - // If true, we will never retrieve the previous mapping, - // but rather decode into a new value and set that in the map. - // - // If false, we will retrieve the previous mapping if necessary e.g. - // the previous mapping is a pointer, or is a struct or array with pre-set state, - // or is an interface. - MapValueReset bool - - // SliceElementReset: on decoding a slice, reset the element to a zero value first. - // - // concern: if the slice already contained some garbage, we will decode into that garbage. - SliceElementReset bool - - // InterfaceReset controls how we decode into an interface. - // - // By default, when we see a field that is an interface{...}, - // or a map with interface{...} value, we will attempt decoding into the - // "contained" value. - // - // However, this prevents us from reading a string into an interface{} - // that formerly contained a number. - // - // If true, we will decode into a new "blank" value, and set that in the interface. - // If false, we will decode into whatever is contained in the interface. - InterfaceReset bool - - // InternString controls interning of strings during decoding. - // - // Some handles, e.g. json, typically will read map keys as strings. - // If the set of keys are finite, it may help reduce allocation to - // look them up from a map (than to allocate them afresh). - // - // Note: Handles will be smart when using the intern functionality. - // Every string should not be interned. - // An excellent use-case for interning is struct field names, - // or map keys where key type is string. - InternString bool - - // PreferArrayOverSlice controls whether to decode to an array or a slice. - // - // This only impacts decoding into a nil interface{}. - // Consequently, it has no effect on codecgen. - // - // *Note*: This only applies if using go1.5 and above, - // as it requires reflect.ArrayOf support which was absent before go1.5. - PreferArrayOverSlice bool - - // DeleteOnNilMapValue controls how to decode a nil value in the stream. - // - // If true, we will delete the mapping of the key. - // Else, just set the mapping to the zero value of the type. - DeleteOnNilMapValue bool -} - -// ------------------------------------ - -type bufioDecReader struct { - buf []byte - r io.Reader - - c int // cursor - n int // num read - err error - - tr []byte - trb bool - b [4]byte -} - -func (z *bufioDecReader) reset(r io.Reader) { - z.r, z.c, z.n, z.err, z.trb = r, 0, 0, nil, false - if z.tr != nil { - z.tr = z.tr[:0] - } -} - -func (z *bufioDecReader) Read(p []byte) (n int, err error) { - if z.err != nil { - return 0, z.err - } - p0 := p - n = copy(p, z.buf[z.c:]) - z.c += n - if z.c == len(z.buf) { - z.c = 0 - } - z.n += n - if len(p) == n { - if z.c == 0 { - z.buf = z.buf[:1] - z.buf[0] = p[len(p)-1] - z.c = 1 - } - if z.trb { - z.tr = append(z.tr, p0[:n]...) - } - return - } - p = p[n:] - var n2 int - // if we are here, then z.buf is all read - if len(p) > len(z.buf) { - n2, err = decReadFull(z.r, p) - n += n2 - z.n += n2 - z.err = err - // don't return EOF if some bytes were read. keep for next time. - if n > 0 && err == io.EOF { - err = nil - } - // always keep last byte in z.buf - z.buf = z.buf[:1] - z.buf[0] = p[len(p)-1] - z.c = 1 - if z.trb { - z.tr = append(z.tr, p0[:n]...) - } - return - } - // z.c is now 0, and len(p) <= len(z.buf) - for len(p) > 0 && z.err == nil { - // println("len(p) loop starting ... ") - z.c = 0 - z.buf = z.buf[0:cap(z.buf)] - n2, err = z.r.Read(z.buf) - if n2 > 0 { - if err == io.EOF { - err = nil - } - z.buf = z.buf[:n2] - n2 = copy(p, z.buf) - z.c = n2 - n += n2 - z.n += n2 - p = p[n2:] - } - z.err = err - // println("... len(p) loop done") - } - if z.c == 0 { - z.buf = z.buf[:1] - z.buf[0] = p[len(p)-1] - z.c = 1 - } - if z.trb { - z.tr = append(z.tr, p0[:n]...) - } - return -} - -func (z *bufioDecReader) ReadByte() (b byte, err error) { - z.b[0] = 0 - _, err = z.Read(z.b[:1]) - b = z.b[0] - return -} - -func (z *bufioDecReader) UnreadByte() (err error) { - if z.err != nil { - return z.err - } - if z.c > 0 { - z.c-- - z.n-- - if z.trb { - z.tr = z.tr[:len(z.tr)-1] - } - return - } - return errDecUnreadByteNothingToRead -} - -func (z *bufioDecReader) numread() int { - return z.n -} - -func (z *bufioDecReader) readx(n int) (bs []byte) { - if n <= 0 || z.err != nil { - return - } - if z.c+n <= len(z.buf) { - bs = z.buf[z.c : z.c+n] - z.n += n - z.c += n - if z.trb { - z.tr = append(z.tr, bs...) - } - return - } - bs = make([]byte, n) - _, err := z.Read(bs) - if err != nil { - panic(err) - } - return -} - -func (z *bufioDecReader) readb(bs []byte) { - _, err := z.Read(bs) - if err != nil { - panic(err) - } -} - -// func (z *bufioDecReader) readn1eof() (b uint8, eof bool) { -// b, err := z.ReadByte() -// if err != nil { -// if err == io.EOF { -// eof = true -// } else { -// panic(err) -// } -// } -// return -// } - -func (z *bufioDecReader) readn1() (b uint8) { - b, err := z.ReadByte() - if err != nil { - panic(err) - } - return -} - -func (z *bufioDecReader) search(in []byte, accept *bitset256, stop, flag uint8) (token byte, out []byte) { - // flag: 1 (skip), 2 (readTo), 4 (readUntil) - if flag == 4 { - for i := z.c; i < len(z.buf); i++ { - if z.buf[i] == stop { - token = z.buf[i] - z.n = z.n + (i - z.c) - 1 - i++ - out = z.buf[z.c:i] - if z.trb { - z.tr = append(z.tr, z.buf[z.c:i]...) - } - z.c = i - return - } - } - } else { - for i := z.c; i < len(z.buf); i++ { - if !accept.isset(z.buf[i]) { - token = z.buf[i] - z.n = z.n + (i - z.c) - 1 - if flag == 1 { - i++ - } else { - out = z.buf[z.c:i] - } - if z.trb { - z.tr = append(z.tr, z.buf[z.c:i]...) - } - z.c = i - return - } - } - } - z.n += len(z.buf) - z.c - if flag != 1 { - out = append(in, z.buf[z.c:]...) - } - if z.trb { - z.tr = append(z.tr, z.buf[z.c:]...) - } - var n2 int - if z.err != nil { - return - } - for { - z.c = 0 - z.buf = z.buf[0:cap(z.buf)] - n2, z.err = z.r.Read(z.buf) - if n2 > 0 && z.err != nil { - z.err = nil - } - z.buf = z.buf[:n2] - if flag == 4 { - for i := 0; i < n2; i++ { - if z.buf[i] == stop { - token = z.buf[i] - z.n += i - 1 - i++ - out = append(out, z.buf[z.c:i]...) - if z.trb { - z.tr = append(z.tr, z.buf[z.c:i]...) - } - z.c = i - return - } - } - } else { - for i := 0; i < n2; i++ { - if !accept.isset(z.buf[i]) { - token = z.buf[i] - z.n += i - 1 - if flag == 1 { - i++ - } - if flag != 1 { - out = append(out, z.buf[z.c:i]...) - } - if z.trb { - z.tr = append(z.tr, z.buf[z.c:i]...) - } - z.c = i - return - } - } - } - if flag != 1 { - out = append(out, z.buf[:n2]...) - } - z.n += n2 - if z.err != nil { - return - } - if z.trb { - z.tr = append(z.tr, z.buf[:n2]...) - } - } -} - -func (z *bufioDecReader) skip(accept *bitset256) (token byte) { - token, _ = z.search(nil, accept, 0, 1) - return -} - -func (z *bufioDecReader) readTo(in []byte, accept *bitset256) (out []byte) { - _, out = z.search(in, accept, 0, 2) - return -} - -func (z *bufioDecReader) readUntil(in []byte, stop byte) (out []byte) { - _, out = z.search(in, nil, stop, 4) - return -} - -func (z *bufioDecReader) unreadn1() { - err := z.UnreadByte() - if err != nil { - panic(err) - } -} - -func (z *bufioDecReader) track() { - if z.tr != nil { - z.tr = z.tr[:0] - } - z.trb = true -} - -func (z *bufioDecReader) stopTrack() (bs []byte) { - z.trb = false - return z.tr -} - -// ioDecReader is a decReader that reads off an io.Reader. -// -// It also has a fallback implementation of ByteScanner if needed. -type ioDecReader struct { - r io.Reader // the reader passed in - - rr io.Reader - br io.ByteScanner - - l byte // last byte - ls byte // last byte status. 0: init-canDoNothing, 1: canRead, 2: canUnread - trb bool // tracking bytes turned on - _ bool - b [4]byte // tiny buffer for reading single bytes - - x [scratchByteArrayLen]byte // for: get struct field name, swallow valueTypeBytes, etc - n int // num read - tr []byte // tracking bytes read -} - -func (z *ioDecReader) reset(r io.Reader) { - z.r = r - z.rr = r - z.l, z.ls, z.n, z.trb = 0, 0, 0, false - if z.tr != nil { - z.tr = z.tr[:0] - } - var ok bool - if z.br, ok = r.(io.ByteScanner); !ok { - z.br = z - z.rr = z - } -} - -func (z *ioDecReader) Read(p []byte) (n int, err error) { - if len(p) == 0 { - return - } - var firstByte bool - if z.ls == 1 { - z.ls = 2 - p[0] = z.l - if len(p) == 1 { - n = 1 - return - } - firstByte = true - p = p[1:] - } - n, err = z.r.Read(p) - if n > 0 { - if err == io.EOF && n == len(p) { - err = nil // read was successful, so postpone EOF (till next time) - } - z.l = p[n-1] - z.ls = 2 - } - if firstByte { - n++ - } - return -} - -func (z *ioDecReader) ReadByte() (c byte, err error) { - n, err := z.Read(z.b[:1]) - if n == 1 { - c = z.b[0] - if err == io.EOF { - err = nil // read was successful, so postpone EOF (till next time) - } - } - return -} - -func (z *ioDecReader) UnreadByte() (err error) { - switch z.ls { - case 2: - z.ls = 1 - case 0: - err = errDecUnreadByteNothingToRead - case 1: - err = errDecUnreadByteLastByteNotRead - default: - err = errDecUnreadByteUnknown - } - return -} - -func (z *ioDecReader) numread() int { - return z.n -} - -func (z *ioDecReader) readx(n int) (bs []byte) { - if n <= 0 { - return - } - if n < len(z.x) { - bs = z.x[:n] - } else { - bs = make([]byte, n) - } - if _, err := decReadFull(z.rr, bs); err != nil { - panic(err) - } - z.n += len(bs) - if z.trb { - z.tr = append(z.tr, bs...) - } - return -} - -func (z *ioDecReader) readb(bs []byte) { - // if len(bs) == 0 { - // return - // } - if _, err := decReadFull(z.rr, bs); err != nil { - panic(err) - } - z.n += len(bs) - if z.trb { - z.tr = append(z.tr, bs...) - } -} - -func (z *ioDecReader) readn1eof() (b uint8, eof bool) { - b, err := z.br.ReadByte() - if err == nil { - z.n++ - if z.trb { - z.tr = append(z.tr, b) - } - } else if err == io.EOF { - eof = true - } else { - panic(err) - } - return -} - -func (z *ioDecReader) readn1() (b uint8) { - var err error - if b, err = z.br.ReadByte(); err == nil { - z.n++ - if z.trb { - z.tr = append(z.tr, b) - } - return - } - panic(err) -} - -func (z *ioDecReader) skip(accept *bitset256) (token byte) { - for { - var eof bool - token, eof = z.readn1eof() - if eof { - return - } - if accept.isset(token) { - continue - } - return - } -} - -func (z *ioDecReader) readTo(in []byte, accept *bitset256) (out []byte) { - out = in - for { - token, eof := z.readn1eof() - if eof { - return - } - if accept.isset(token) { - out = append(out, token) - } else { - z.unreadn1() - return - } - } -} - -func (z *ioDecReader) readUntil(in []byte, stop byte) (out []byte) { - out = in - for { - token, eof := z.readn1eof() - if eof { - panic(io.EOF) - } - out = append(out, token) - if token == stop { - return - } - } -} - -func (z *ioDecReader) unreadn1() { - err := z.br.UnreadByte() - if err != nil { - panic(err) - } - z.n-- - if z.trb { - if l := len(z.tr) - 1; l >= 0 { - z.tr = z.tr[:l] - } - } -} - -func (z *ioDecReader) track() { - if z.tr != nil { - z.tr = z.tr[:0] - } - z.trb = true -} - -func (z *ioDecReader) stopTrack() (bs []byte) { - z.trb = false - return z.tr -} - -// ------------------------------------ - -var errBytesDecReaderCannotUnread = errors.New("cannot unread last byte read") - -// bytesDecReader is a decReader that reads off a byte slice with zero copying -type bytesDecReader struct { - b []byte // data - c int // cursor - a int // available - t int // track start -} - -func (z *bytesDecReader) reset(in []byte) { - z.b = in - z.a = len(in) - z.c = 0 - z.t = 0 -} - -func (z *bytesDecReader) numread() int { - return z.c -} - -func (z *bytesDecReader) unreadn1() { - if z.c == 0 || len(z.b) == 0 { - panic(errBytesDecReaderCannotUnread) - } - z.c-- - z.a++ - return -} - -func (z *bytesDecReader) readx(n int) (bs []byte) { - // slicing from a non-constant start position is more expensive, - // as more computation is required to decipher the pointer start position. - // However, we do it only once, and it's better than reslicing both z.b and return value. - - if n <= 0 { - } else if z.a == 0 { - panic(io.EOF) - } else if n > z.a { - panic(io.ErrUnexpectedEOF) - } else { - c0 := z.c - z.c = c0 + n - z.a = z.a - n - bs = z.b[c0:z.c] - } - return -} - -func (z *bytesDecReader) readb(bs []byte) { - copy(bs, z.readx(len(bs))) -} - -func (z *bytesDecReader) readn1() (v uint8) { - if z.a == 0 { - panic(io.EOF) - } - v = z.b[z.c] - z.c++ - z.a-- - return -} - -// func (z *bytesDecReader) readn1eof() (v uint8, eof bool) { -// if z.a == 0 { -// eof = true -// return -// } -// v = z.b[z.c] -// z.c++ -// z.a-- -// return -// } - -func (z *bytesDecReader) skip(accept *bitset256) (token byte) { - if z.a == 0 { - return - } - blen := len(z.b) - for i := z.c; i < blen; i++ { - if !accept.isset(z.b[i]) { - token = z.b[i] - i++ - z.a -= (i - z.c) - z.c = i - return - } - } - z.a, z.c = 0, blen - return -} - -func (z *bytesDecReader) readTo(_ []byte, accept *bitset256) (out []byte) { - if z.a == 0 { - return - } - blen := len(z.b) - for i := z.c; i < blen; i++ { - if !accept.isset(z.b[i]) { - out = z.b[z.c:i] - z.a -= (i - z.c) - z.c = i - return - } - } - out = z.b[z.c:] - z.a, z.c = 0, blen - return -} - -func (z *bytesDecReader) readUntil(_ []byte, stop byte) (out []byte) { - if z.a == 0 { - panic(io.EOF) - } - blen := len(z.b) - for i := z.c; i < blen; i++ { - if z.b[i] == stop { - i++ - out = z.b[z.c:i] - z.a -= (i - z.c) - z.c = i - return - } - } - z.a, z.c = 0, blen - panic(io.EOF) -} - -func (z *bytesDecReader) track() { - z.t = z.c -} - -func (z *bytesDecReader) stopTrack() (bs []byte) { - return z.b[z.t:z.c] -} - -// ---------------------------------------- - -// func (d *Decoder) builtin(f *codecFnInfo, rv reflect.Value) { -// d.d.DecodeBuiltin(f.ti.rtid, rv2i(rv)) -// } - -func (d *Decoder) rawExt(f *codecFnInfo, rv reflect.Value) { - d.d.DecodeExt(rv2i(rv), 0, nil) -} - -func (d *Decoder) ext(f *codecFnInfo, rv reflect.Value) { - d.d.DecodeExt(rv2i(rv), f.xfTag, f.xfFn) -} - -func (d *Decoder) selferUnmarshal(f *codecFnInfo, rv reflect.Value) { - rv2i(rv).(Selfer).CodecDecodeSelf(d) -} - -func (d *Decoder) binaryUnmarshal(f *codecFnInfo, rv reflect.Value) { - bm := rv2i(rv).(encoding.BinaryUnmarshaler) - xbs := d.d.DecodeBytes(nil, true) - if fnerr := bm.UnmarshalBinary(xbs); fnerr != nil { - panic(fnerr) - } -} - -func (d *Decoder) textUnmarshal(f *codecFnInfo, rv reflect.Value) { - tm := rv2i(rv).(encoding.TextUnmarshaler) - fnerr := tm.UnmarshalText(d.d.DecodeStringAsBytes()) - if fnerr != nil { - panic(fnerr) - } -} - -func (d *Decoder) jsonUnmarshal(f *codecFnInfo, rv reflect.Value) { - tm := rv2i(rv).(jsonUnmarshaler) - // bs := d.d.DecodeBytes(d.b[:], true, true) - // grab the bytes to be read, as UnmarshalJSON needs the full JSON so as to unmarshal it itself. - fnerr := tm.UnmarshalJSON(d.nextValueBytes()) - if fnerr != nil { - panic(fnerr) - } -} - -func (d *Decoder) kErr(f *codecFnInfo, rv reflect.Value) { - d.errorf("no decoding function defined for kind %v", rv.Kind()) -} - -// var kIntfCtr uint64 - -func (d *Decoder) kInterfaceNaked(f *codecFnInfo) (rvn reflect.Value) { - // nil interface: - // use some hieristics to decode it appropriately - // based on the detected next value in the stream. - n := d.naked() - d.d.DecodeNaked() - if n.v == valueTypeNil { - return - } - // We cannot decode non-nil stream value into nil interface with methods (e.g. io.Reader). - if f.ti.numMeth > 0 { - d.errorf("cannot decode non-nil codec value into nil %v (%v methods)", f.ti.rt, f.ti.numMeth) - return - } - // var useRvn bool - switch n.v { - case valueTypeMap: - // if json, default to a map type with string keys - mtid := d.mtid - if mtid == 0 { - if d.jsms { - mtid = mapStrIntfTypId - } else { - mtid = mapIntfIntfTypId - } - } - if mtid == mapIntfIntfTypId { - n.initContainers() - if n.lm < arrayCacheLen { - n.ma[n.lm] = nil - rvn = n.rma[n.lm] - n.lm++ - d.decode(&n.ma[n.lm-1]) - n.lm-- - } else { - var v2 map[interface{}]interface{} - d.decode(&v2) - rvn = reflect.ValueOf(&v2).Elem() - } - } else if mtid == mapStrIntfTypId { // for json performance - n.initContainers() - if n.ln < arrayCacheLen { - n.na[n.ln] = nil - rvn = n.rna[n.ln] - n.ln++ - d.decode(&n.na[n.ln-1]) - n.ln-- - } else { - var v2 map[string]interface{} - d.decode(&v2) - rvn = reflect.ValueOf(&v2).Elem() - } - } else { - if d.mtr { - rvn = reflect.New(d.h.MapType) - d.decode(rv2i(rvn)) - rvn = rvn.Elem() - } else { - rvn = reflect.New(d.h.MapType).Elem() - d.decodeValue(rvn, nil, true) - } - } - case valueTypeArray: - if d.stid == 0 || d.stid == intfSliceTypId { - n.initContainers() - if n.ls < arrayCacheLen { - n.sa[n.ls] = nil - rvn = n.rsa[n.ls] - n.ls++ - d.decode(&n.sa[n.ls-1]) - n.ls-- - } else { - var v2 []interface{} - d.decode(&v2) - rvn = reflect.ValueOf(&v2).Elem() - } - if reflectArrayOfSupported && d.stid == 0 && d.h.PreferArrayOverSlice { - rvn2 := reflect.New(reflectArrayOf(rvn.Len(), intfTyp)).Elem() - reflect.Copy(rvn2, rvn) - rvn = rvn2 - } - } else { - if d.str { - rvn = reflect.New(d.h.SliceType) - d.decode(rv2i(rvn)) - rvn = rvn.Elem() - } else { - rvn = reflect.New(d.h.SliceType).Elem() - d.decodeValue(rvn, nil, true) - } - } - case valueTypeExt: - var v interface{} - tag, bytes := n.u, n.l // calling decode below might taint the values - if bytes == nil { - n.initContainers() - if n.li < arrayCacheLen { - n.ia[n.li] = nil - n.li++ - d.decode(&n.ia[n.li-1]) - // v = *(&n.ia[l]) - n.li-- - v = n.ia[n.li] - n.ia[n.li] = nil - } else { - d.decode(&v) - } - } - bfn := d.h.getExtForTag(tag) - if bfn == nil { - var re RawExt - re.Tag = tag - re.Data = detachZeroCopyBytes(d.bytes, nil, bytes) - re.Value = v - rvn = reflect.ValueOf(&re).Elem() - } else { - rvnA := reflect.New(bfn.rt) - if bytes != nil { - bfn.ext.ReadExt(rv2i(rvnA), bytes) - } else { - bfn.ext.UpdateExt(rv2i(rvnA), v) - } - rvn = rvnA.Elem() - } - case valueTypeNil: - // no-op - case valueTypeInt: - rvn = n.ri - case valueTypeUint: - rvn = n.ru - case valueTypeFloat: - rvn = n.rf - case valueTypeBool: - rvn = n.rb - case valueTypeString, valueTypeSymbol: - rvn = n.rs - case valueTypeBytes: - rvn = n.rl - case valueTypeTime: - rvn = n.rt - default: - panicv.errorf("kInterfaceNaked: unexpected valueType: %d", n.v) - } - return -} - -func (d *Decoder) kInterface(f *codecFnInfo, rv reflect.Value) { - // Note: - // A consequence of how kInterface works, is that - // if an interface already contains something, we try - // to decode into what was there before. - // We do not replace with a generic value (as got from decodeNaked). - - // every interface passed here MUST be settable. - var rvn reflect.Value - if rv.IsNil() || d.h.InterfaceReset { - // check if mapping to a type: if so, initialize it and move on - rvn = d.h.intf2impl(f.ti.rtid) - if rvn.IsValid() { - rv.Set(rvn) - } else { - rvn = d.kInterfaceNaked(f) - if rvn.IsValid() { - rv.Set(rvn) - } else if d.h.InterfaceReset { - // reset to zero value based on current type in there. - rv.Set(reflect.Zero(rv.Elem().Type())) - } - return - } - } else { - // now we have a non-nil interface value, meaning it contains a type - rvn = rv.Elem() - } - if d.d.TryDecodeAsNil() { - rv.Set(reflect.Zero(rvn.Type())) - return - } - - // Note: interface{} is settable, but underlying type may not be. - // Consequently, we MAY have to create a decodable value out of the underlying value, - // decode into it, and reset the interface itself. - // fmt.Printf(">>>> kInterface: rvn type: %v, rv type: %v\n", rvn.Type(), rv.Type()) - - rvn2, canDecode := isDecodeable(rvn) - if canDecode { - d.decodeValue(rvn2, nil, true) - return - } - - rvn2 = reflect.New(rvn.Type()).Elem() - rvn2.Set(rvn) - d.decodeValue(rvn2, nil, true) - rv.Set(rvn2) -} - -func decStructFieldKey(dd decDriver, keyType valueType, b *[decScratchByteArrayLen]byte) (rvkencname []byte) { - // use if-else-if, not switch (which compiles to binary-search) - // since keyType is typically valueTypeString, branch prediction is pretty good. - - if keyType == valueTypeString { - rvkencname = dd.DecodeStringAsBytes() - } else if keyType == valueTypeInt { - rvkencname = strconv.AppendInt(b[:0], dd.DecodeInt64(), 10) - } else if keyType == valueTypeUint { - rvkencname = strconv.AppendUint(b[:0], dd.DecodeUint64(), 10) - } else if keyType == valueTypeFloat { - rvkencname = strconv.AppendFloat(b[:0], dd.DecodeFloat64(), 'f', -1, 64) - } else { - rvkencname = dd.DecodeStringAsBytes() - } - return rvkencname -} - -func (d *Decoder) kStruct(f *codecFnInfo, rv reflect.Value) { - fti := f.ti - dd := d.d - elemsep := d.esep - sfn := structFieldNode{v: rv, update: true} - ctyp := dd.ContainerType() - if ctyp == valueTypeMap { - containerLen := dd.ReadMapStart() - if containerLen == 0 { - dd.ReadMapEnd() - return - } - tisfi := fti.sfiSort - hasLen := containerLen >= 0 - - var rvkencname []byte - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if elemsep { - dd.ReadMapElemKey() - } - rvkencname = decStructFieldKey(dd, fti.keyType, &d.b) - if elemsep { - dd.ReadMapElemValue() - } - if k := fti.indexForEncName(rvkencname); k > -1 { - si := tisfi[k] - if dd.TryDecodeAsNil() { - si.setToZeroValue(rv) - } else { - d.decodeValue(sfn.field(si), nil, true) - } - } else { - d.structFieldNotFound(-1, stringView(rvkencname)) - } - // keepAlive4StringView(rvkencnameB) // not needed, as reference is outside loop - } - dd.ReadMapEnd() - } else if ctyp == valueTypeArray { - containerLen := dd.ReadArrayStart() - if containerLen == 0 { - dd.ReadArrayEnd() - return - } - // Not much gain from doing it two ways for array. - // Arrays are not used as much for structs. - hasLen := containerLen >= 0 - for j, si := range fti.sfiSrc { - if (hasLen && j == containerLen) || (!hasLen && dd.CheckBreak()) { - break - } - if elemsep { - dd.ReadArrayElem() - } - if dd.TryDecodeAsNil() { - si.setToZeroValue(rv) - } else { - d.decodeValue(sfn.field(si), nil, true) - } - } - if containerLen > len(fti.sfiSrc) { - // read remaining values and throw away - for j := len(fti.sfiSrc); j < containerLen; j++ { - if elemsep { - dd.ReadArrayElem() - } - d.structFieldNotFound(j, "") - } - } - dd.ReadArrayEnd() - } else { - d.errorstr(errstrOnlyMapOrArrayCanDecodeIntoStruct) - return - } -} - -func (d *Decoder) kSlice(f *codecFnInfo, rv reflect.Value) { - // A slice can be set from a map or array in stream. - // This way, the order can be kept (as order is lost with map). - ti := f.ti - if f.seq == seqTypeChan && ti.chandir&uint8(reflect.SendDir) == 0 { - d.errorf("receive-only channel cannot be decoded") - } - dd := d.d - rtelem0 := ti.elem - ctyp := dd.ContainerType() - if ctyp == valueTypeBytes || ctyp == valueTypeString { - // you can only decode bytes or string in the stream into a slice or array of bytes - if !(ti.rtid == uint8SliceTypId || rtelem0.Kind() == reflect.Uint8) { - d.errorf("bytes/string in stream must decode into slice/array of bytes, not %v", ti.rt) - } - if f.seq == seqTypeChan { - bs2 := dd.DecodeBytes(nil, true) - irv := rv2i(rv) - ch, ok := irv.(chan<- byte) - if !ok { - ch = irv.(chan byte) - } - for _, b := range bs2 { - ch <- b - } - } else { - rvbs := rv.Bytes() - bs2 := dd.DecodeBytes(rvbs, false) - // if rvbs == nil && bs2 != nil || rvbs != nil && bs2 == nil || len(bs2) != len(rvbs) { - if !(len(bs2) > 0 && len(bs2) == len(rvbs) && &bs2[0] == &rvbs[0]) { - if rv.CanSet() { - rv.SetBytes(bs2) - } else if len(rvbs) > 0 && len(bs2) > 0 { - copy(rvbs, bs2) - } - } - } - return - } - - // array := f.seq == seqTypeChan - - slh, containerLenS := d.decSliceHelperStart() // only expects valueType(Array|Map) - - // an array can never return a nil slice. so no need to check f.array here. - if containerLenS == 0 { - if rv.CanSet() { - if f.seq == seqTypeSlice { - if rv.IsNil() { - rv.Set(reflect.MakeSlice(ti.rt, 0, 0)) - } else { - rv.SetLen(0) - } - } else if f.seq == seqTypeChan { - if rv.IsNil() { - rv.Set(reflect.MakeChan(ti.rt, 0)) - } - } - } - slh.End() - return - } - - rtelem0Size := int(rtelem0.Size()) - rtElem0Kind := rtelem0.Kind() - rtelem0Mut := !isImmutableKind(rtElem0Kind) - rtelem := rtelem0 - rtelemkind := rtelem.Kind() - for rtelemkind == reflect.Ptr { - rtelem = rtelem.Elem() - rtelemkind = rtelem.Kind() - } - - var fn *codecFn - - var rvCanset = rv.CanSet() - var rvChanged bool - var rv0 = rv - var rv9 reflect.Value - - rvlen := rv.Len() - rvcap := rv.Cap() - hasLen := containerLenS > 0 - if hasLen && f.seq == seqTypeSlice { - if containerLenS > rvcap { - oldRvlenGtZero := rvlen > 0 - rvlen = decInferLen(containerLenS, d.h.MaxInitLen, int(rtelem0.Size())) - if rvlen <= rvcap { - if rvCanset { - rv.SetLen(rvlen) - } - } else if rvCanset { - rv = reflect.MakeSlice(ti.rt, rvlen, rvlen) - rvcap = rvlen - rvChanged = true - } else { - d.errorf("cannot decode into non-settable slice") - } - if rvChanged && oldRvlenGtZero && !isImmutableKind(rtelem0.Kind()) { - reflect.Copy(rv, rv0) // only copy up to length NOT cap i.e. rv0.Slice(0, rvcap) - } - } else if containerLenS != rvlen { - rvlen = containerLenS - if rvCanset { - rv.SetLen(rvlen) - } - // else { - // rv = rv.Slice(0, rvlen) - // rvChanged = true - // d.errorf("cannot decode into non-settable slice") - // } - } - } - - // consider creating new element once, and just decoding into it. - var rtelem0Zero reflect.Value - var rtelem0ZeroValid bool - var decodeAsNil bool - var j int - d.cfer() - for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && (f.seq == seqTypeSlice || f.seq == seqTypeChan) && rv.IsNil() { - if hasLen { - rvlen = decInferLen(containerLenS, d.h.MaxInitLen, rtelem0Size) - } else if f.seq == seqTypeSlice { - rvlen = decDefSliceCap - } else { - rvlen = decDefChanCap - } - if rvCanset { - if f.seq == seqTypeSlice { - rv = reflect.MakeSlice(ti.rt, rvlen, rvlen) - rvChanged = true - } else { // chan - // xdebugf(">>>>>> haslen = %v, make chan of type '%v' with length: %v", hasLen, ti.rt, rvlen) - rv = reflect.MakeChan(ti.rt, rvlen) - rvChanged = true - } - } else { - d.errorf("cannot decode into non-settable slice") - } - } - slh.ElemContainerState(j) - decodeAsNil = dd.TryDecodeAsNil() - if f.seq == seqTypeChan { - if decodeAsNil { - rv.Send(reflect.Zero(rtelem0)) - continue - } - if rtelem0Mut || !rv9.IsValid() { // || (rtElem0Kind == reflect.Ptr && rv9.IsNil()) { - rv9 = reflect.New(rtelem0).Elem() - } - if fn == nil { - fn = d.cf.get(rtelem, true, true) - } - d.decodeValue(rv9, fn, true) - // xdebugf(">>>> rv9 sent on %v during decode: %v, with len=%v, cap=%v", rv.Type(), rv9, rv.Len(), rv.Cap()) - rv.Send(rv9) - } else { - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= rvlen { - if f.seq == seqTypeArray { - d.arrayCannotExpand(rvlen, j+1) - decodeIntoBlank = true - } else { // if f.seq == seqTypeSlice - // rv = reflect.Append(rv, reflect.Zero(rtelem0)) // append logic + varargs - var rvcap2 int - var rvErrmsg2 string - rv9, rvcap2, rvChanged, rvErrmsg2 = - expandSliceRV(rv, ti.rt, rvCanset, rtelem0Size, 1, rvlen, rvcap) - if rvErrmsg2 != "" { - d.errorf(rvErrmsg2) - } - rvlen++ - if rvChanged { - rv = rv9 - rvcap = rvcap2 - } - } - } - if decodeIntoBlank { - if !decodeAsNil { - d.swallow() - } - } else { - rv9 = rv.Index(j) - if d.h.SliceElementReset || decodeAsNil { - if !rtelem0ZeroValid { - rtelem0ZeroValid = true - rtelem0Zero = reflect.Zero(rtelem0) - } - rv9.Set(rtelem0Zero) - } - if decodeAsNil { - continue - } - - if fn == nil { - fn = d.cf.get(rtelem, true, true) - } - d.decodeValue(rv9, fn, true) - } - } - } - if f.seq == seqTypeSlice { - if j < rvlen { - if rv.CanSet() { - rv.SetLen(j) - } else if rvCanset { - rv = rv.Slice(0, j) - rvChanged = true - } // else { d.errorf("kSlice: cannot change non-settable slice") } - rvlen = j - } else if j == 0 && rv.IsNil() { - if rvCanset { - rv = reflect.MakeSlice(ti.rt, 0, 0) - rvChanged = true - } // else { d.errorf("kSlice: cannot change non-settable slice") } - } - } - slh.End() - - if rvChanged { // infers rvCanset=true, so it can be reset - rv0.Set(rv) - } -} - -// func (d *Decoder) kArray(f *codecFnInfo, rv reflect.Value) { -// // d.decodeValueFn(rv.Slice(0, rv.Len())) -// f.kSlice(rv.Slice(0, rv.Len())) -// } - -func (d *Decoder) kMap(f *codecFnInfo, rv reflect.Value) { - dd := d.d - containerLen := dd.ReadMapStart() - elemsep := d.esep - ti := f.ti - if rv.IsNil() { - rv.Set(makeMapReflect(ti.rt, containerLen)) - } - - if containerLen == 0 { - dd.ReadMapEnd() - return - } - - ktype, vtype := ti.key, ti.elem - ktypeId := rt2id(ktype) - vtypeKind := vtype.Kind() - - var keyFn, valFn *codecFn - var ktypeLo, vtypeLo reflect.Type - - for ktypeLo = ktype; ktypeLo.Kind() == reflect.Ptr; ktypeLo = ktypeLo.Elem() { - } - - for vtypeLo = vtype; vtypeLo.Kind() == reflect.Ptr; vtypeLo = vtypeLo.Elem() { - } - - var mapGet, mapSet bool - rvvImmut := isImmutableKind(vtypeKind) - if !d.h.MapValueReset { - // if pointer, mapGet = true - // if interface, mapGet = true if !DecodeNakedAlways (else false) - // if builtin, mapGet = false - // else mapGet = true - if vtypeKind == reflect.Ptr { - mapGet = true - } else if vtypeKind == reflect.Interface { - if !d.h.InterfaceReset { - mapGet = true - } - } else if !rvvImmut { - mapGet = true - } - } - - var rvk, rvkp, rvv, rvz reflect.Value - rvkMut := !isImmutableKind(ktype.Kind()) // if ktype is immutable, then re-use the same rvk. - ktypeIsString := ktypeId == stringTypId - ktypeIsIntf := ktypeId == intfTypId - hasLen := containerLen > 0 - var kstrbs []byte - d.cfer() - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if rvkMut || !rvkp.IsValid() { - rvkp = reflect.New(ktype) - rvk = rvkp.Elem() - } - if elemsep { - dd.ReadMapElemKey() - } - if false && dd.TryDecodeAsNil() { // nil cannot be a map key, so disregard this block - // Previously, if a nil key, we just ignored the mapped value and continued. - // However, that makes the result of encoding and then decoding map[intf]intf{nil:nil} - // to be an empty map. - // Instead, we treat a nil key as the zero value of the type. - rvk.Set(reflect.Zero(ktype)) - } else if ktypeIsString { - kstrbs = dd.DecodeStringAsBytes() - rvk.SetString(stringView(kstrbs)) - // NOTE: if doing an insert, you MUST use a real string (not stringview) - } else { - if keyFn == nil { - keyFn = d.cf.get(ktypeLo, true, true) - } - d.decodeValue(rvk, keyFn, true) - } - // special case if a byte array. - if ktypeIsIntf { - if rvk2 := rvk.Elem(); rvk2.IsValid() { - if rvk2.Type() == uint8SliceTyp { - rvk = reflect.ValueOf(d.string(rvk2.Bytes())) - } else { - rvk = rvk2 - } - } - } - - if elemsep { - dd.ReadMapElemValue() - } - - // Brittle, but OK per TryDecodeAsNil() contract. - // i.e. TryDecodeAsNil never shares slices with other decDriver procedures - if dd.TryDecodeAsNil() { - if ktypeIsString { - rvk.SetString(d.string(kstrbs)) - } - if d.h.DeleteOnNilMapValue { - rv.SetMapIndex(rvk, reflect.Value{}) - } else { - rv.SetMapIndex(rvk, reflect.Zero(vtype)) - } - continue - } - - mapSet = true // set to false if u do a get, and its a non-nil pointer - if mapGet { - // mapGet true only in case where kind=Ptr|Interface or kind is otherwise mutable. - rvv = rv.MapIndex(rvk) - if !rvv.IsValid() { - rvv = reflect.New(vtype).Elem() - } else if vtypeKind == reflect.Ptr { - if rvv.IsNil() { - rvv = reflect.New(vtype).Elem() - } else { - mapSet = false - } - } else if vtypeKind == reflect.Interface { - // not addressable, and thus not settable. - // e MUST create a settable/addressable variant - rvv2 := reflect.New(rvv.Type()).Elem() - if !rvv.IsNil() { - rvv2.Set(rvv) - } - rvv = rvv2 - } - // else it is ~mutable, and we can just decode into it directly - } else if rvvImmut { - if !rvz.IsValid() { - rvz = reflect.New(vtype).Elem() - } - rvv = rvz - } else { - rvv = reflect.New(vtype).Elem() - } - - // We MUST be done with the stringview of the key, before decoding the value - // so that we don't bastardize the reused byte array. - if mapSet && ktypeIsString { - rvk.SetString(d.string(kstrbs)) - } - if valFn == nil { - valFn = d.cf.get(vtypeLo, true, true) - } - d.decodeValue(rvv, valFn, true) - // d.decodeValueFn(rvv, valFn) - if mapSet { - rv.SetMapIndex(rvk, rvv) - } - // if ktypeIsString { - // // keepAlive4StringView(kstrbs) // not needed, as reference is outside loop - // } - } - - dd.ReadMapEnd() -} - -// decNaked is used to keep track of the primitives decoded. -// Without it, we would have to decode each primitive and wrap it -// in an interface{}, causing an allocation. -// In this model, the primitives are decoded in a "pseudo-atomic" fashion, -// so we can rest assured that no other decoding happens while these -// primitives are being decoded. -// -// maps and arrays are not handled by this mechanism. -// However, RawExt is, and we accommodate for extensions that decode -// RawExt from DecodeNaked, but need to decode the value subsequently. -// kInterfaceNaked and swallow, which call DecodeNaked, handle this caveat. -// -// However, decNaked also keeps some arrays of default maps and slices -// used in DecodeNaked. This way, we can get a pointer to it -// without causing a new heap allocation. -// -// kInterfaceNaked will ensure that there is no allocation for the common -// uses. - -type decNakedContainers struct { - // array/stacks for reducing allocation - // keep arrays at the bottom? Chance is that they are not used much. - ia [arrayCacheLen]interface{} - ma [arrayCacheLen]map[interface{}]interface{} - na [arrayCacheLen]map[string]interface{} - sa [arrayCacheLen][]interface{} - - // ria [arrayCacheLen]reflect.Value // not needed, as we decode directly into &ia[n] - rma, rna, rsa [arrayCacheLen]reflect.Value // reflect.Value mapping to above -} - -func (n *decNakedContainers) init() { - for i := 0; i < arrayCacheLen; i++ { - // n.ria[i] = reflect.ValueOf(&(n.ia[i])).Elem() - n.rma[i] = reflect.ValueOf(&(n.ma[i])).Elem() - n.rna[i] = reflect.ValueOf(&(n.na[i])).Elem() - n.rsa[i] = reflect.ValueOf(&(n.sa[i])).Elem() - } -} - -type decNaked struct { - // r RawExt // used for RawExt, uint, []byte. - - // primitives below - u uint64 - i int64 - f float64 - l []byte - s string - - // ---- cpu cache line boundary? - t time.Time - b bool - - // state - v valueType - li, lm, ln, ls int8 - inited bool - - *decNakedContainers - - ru, ri, rf, rl, rs, rb, rt reflect.Value // mapping to the primitives above - - // _ [6]uint64 // padding // no padding - rt goes into next cache line -} - -func (n *decNaked) init() { - if n.inited { - return - } - n.ru = reflect.ValueOf(&n.u).Elem() - n.ri = reflect.ValueOf(&n.i).Elem() - n.rf = reflect.ValueOf(&n.f).Elem() - n.rl = reflect.ValueOf(&n.l).Elem() - n.rs = reflect.ValueOf(&n.s).Elem() - n.rt = reflect.ValueOf(&n.t).Elem() - n.rb = reflect.ValueOf(&n.b).Elem() - - n.inited = true - // n.rr[] = reflect.ValueOf(&n.) -} - -func (n *decNaked) initContainers() { - if n.decNakedContainers == nil { - n.decNakedContainers = new(decNakedContainers) - n.decNakedContainers.init() - } -} - -func (n *decNaked) reset() { - if n == nil { - return - } - n.li, n.lm, n.ln, n.ls = 0, 0, 0, 0 -} - -type rtid2rv struct { - rtid uintptr - rv reflect.Value -} - -// -------------- - -type decReaderSwitch struct { - rb bytesDecReader - // ---- cpu cache line boundary? - ri *ioDecReader - mtr, str bool // whether maptype or slicetype are known types - - be bool // is binary encoding - bytes bool // is bytes reader - js bool // is json handle - jsms bool // is json handle, and MapKeyAsString - esep bool // has elem separators -} - -// TODO: Uncomment after mid-stack inlining enabled in go 1.11 -// -// func (z *decReaderSwitch) unreadn1() { -// if z.bytes { -// z.rb.unreadn1() -// } else { -// z.ri.unreadn1() -// } -// } -// func (z *decReaderSwitch) readx(n int) []byte { -// if z.bytes { -// return z.rb.readx(n) -// } -// return z.ri.readx(n) -// } -// func (z *decReaderSwitch) readb(s []byte) { -// if z.bytes { -// z.rb.readb(s) -// } else { -// z.ri.readb(s) -// } -// } -// func (z *decReaderSwitch) readn1() uint8 { -// if z.bytes { -// return z.rb.readn1() -// } -// return z.ri.readn1() -// } -// func (z *decReaderSwitch) numread() int { -// if z.bytes { -// return z.rb.numread() -// } -// return z.ri.numread() -// } -// func (z *decReaderSwitch) track() { -// if z.bytes { -// z.rb.track() -// } else { -// z.ri.track() -// } -// } -// func (z *decReaderSwitch) stopTrack() []byte { -// if z.bytes { -// return z.rb.stopTrack() -// } -// return z.ri.stopTrack() -// } -// func (z *decReaderSwitch) skip(accept *bitset256) (token byte) { -// if z.bytes { -// return z.rb.skip(accept) -// } -// return z.ri.skip(accept) -// } -// func (z *decReaderSwitch) readTo(in []byte, accept *bitset256) (out []byte) { -// if z.bytes { -// return z.rb.readTo(in, accept) -// } -// return z.ri.readTo(in, accept) -// } -// func (z *decReaderSwitch) readUntil(in []byte, stop byte) (out []byte) { -// if z.bytes { -// return z.rb.readUntil(in, stop) -// } -// return z.ri.readUntil(in, stop) -// } - -// A Decoder reads and decodes an object from an input stream in the codec format. -type Decoder struct { - panicHdl - // hopefully, reduce derefencing cost by laying the decReader inside the Decoder. - // Try to put things that go together to fit within a cache line (8 words). - - d decDriver - // NOTE: Decoder shouldn't call it's read methods, - // as the handler MAY need to do some coordination. - r decReader - h *BasicHandle - bi *bufioDecReader - // cache the mapTypeId and sliceTypeId for faster comparisons - mtid uintptr - stid uintptr - - // ---- cpu cache line boundary? - decReaderSwitch - - // ---- cpu cache line boundary? - codecFnPooler - // cr containerStateRecv - n *decNaked - nsp *sync.Pool - err error - - // ---- cpu cache line boundary? - b [decScratchByteArrayLen]byte // scratch buffer, used by Decoder and xxxEncDrivers - is map[string]string // used for interning strings - - // padding - false sharing help // modify 232 if Decoder struct changes. - // _ [cacheLineSize - 232%cacheLineSize]byte -} - -// NewDecoder returns a Decoder for decoding a stream of bytes from an io.Reader. -// -// For efficiency, Users are encouraged to pass in a memory buffered reader -// (eg bufio.Reader, bytes.Buffer). -func NewDecoder(r io.Reader, h Handle) *Decoder { - d := newDecoder(h) - d.Reset(r) - return d -} - -// NewDecoderBytes returns a Decoder which efficiently decodes directly -// from a byte slice with zero copying. -func NewDecoderBytes(in []byte, h Handle) *Decoder { - d := newDecoder(h) - d.ResetBytes(in) - return d -} - -var defaultDecNaked decNaked - -func newDecoder(h Handle) *Decoder { - d := &Decoder{h: h.getBasicHandle(), err: errDecoderNotInitialized} - d.hh = h - d.be = h.isBinary() - // NOTE: do not initialize d.n here. It is lazily initialized in d.naked() - var jh *JsonHandle - jh, d.js = h.(*JsonHandle) - if d.js { - d.jsms = jh.MapKeyAsString - } - d.esep = d.hh.hasElemSeparators() - if d.h.InternString { - d.is = make(map[string]string, 32) - } - d.d = h.newDecDriver(d) - // d.cr, _ = d.d.(containerStateRecv) - return d -} - -func (d *Decoder) resetCommon() { - d.n.reset() - d.d.reset() - d.err = nil - // reset all things which were cached from the Handle, but could change - d.mtid, d.stid = 0, 0 - d.mtr, d.str = false, false - if d.h.MapType != nil { - d.mtid = rt2id(d.h.MapType) - d.mtr = fastpathAV.index(d.mtid) != -1 - } - if d.h.SliceType != nil { - d.stid = rt2id(d.h.SliceType) - d.str = fastpathAV.index(d.stid) != -1 - } -} - -// Reset the Decoder with a new Reader to decode from, -// clearing all state from last run(s). -func (d *Decoder) Reset(r io.Reader) { - if r == nil { - return - } - if d.bi == nil { - d.bi = new(bufioDecReader) - } - d.bytes = false - if d.h.ReaderBufferSize > 0 { - d.bi.buf = make([]byte, 0, d.h.ReaderBufferSize) - d.bi.reset(r) - d.r = d.bi - } else { - // d.ri.x = &d.b - // d.s = d.sa[:0] - if d.ri == nil { - d.ri = new(ioDecReader) - } - d.ri.reset(r) - d.r = d.ri - } - d.resetCommon() -} - -// ResetBytes resets the Decoder with a new []byte to decode from, -// clearing all state from last run(s). -func (d *Decoder) ResetBytes(in []byte) { - if in == nil { - return - } - d.bytes = true - d.rb.reset(in) - d.r = &d.rb - d.resetCommon() -} - -// naked must be called before each call to .DecodeNaked, -// as they will use it. -func (d *Decoder) naked() *decNaked { - if d.n == nil { - // consider one of: - // - get from sync.Pool (if GC is frequent, there's no value here) - // - new alloc (safest. only init'ed if it a naked decode will be done) - // - field in Decoder (makes the Decoder struct very big) - // To support using a decoder where a DecodeNaked is not needed, - // we prefer #1 or #2. - // d.n = new(decNaked) // &d.nv // new(decNaked) // grab from a sync.Pool - // d.n.init() - var v interface{} - d.nsp, v = pool.decNaked() - d.n = v.(*decNaked) - } - return d.n -} - -// Decode decodes the stream from reader and stores the result in the -// value pointed to by v. v cannot be a nil pointer. v can also be -// a reflect.Value of a pointer. -// -// Note that a pointer to a nil interface is not a nil pointer. -// If you do not know what type of stream it is, pass in a pointer to a nil interface. -// We will decode and store a value in that nil interface. -// -// Sample usages: -// // Decoding into a non-nil typed value -// var f float32 -// err = codec.NewDecoder(r, handle).Decode(&f) -// -// // Decoding into nil interface -// var v interface{} -// dec := codec.NewDecoder(r, handle) -// err = dec.Decode(&v) -// -// When decoding into a nil interface{}, we will decode into an appropriate value based -// on the contents of the stream: -// - Numbers are decoded as float64, int64 or uint64. -// - Other values are decoded appropriately depending on the type: -// bool, string, []byte, time.Time, etc -// - Extensions are decoded as RawExt (if no ext function registered for the tag) -// Configurations exist on the Handle to override defaults -// (e.g. for MapType, SliceType and how to decode raw bytes). -// -// When decoding into a non-nil interface{} value, the mode of encoding is based on the -// type of the value. When a value is seen: -// - If an extension is registered for it, call that extension function -// - If it implements BinaryUnmarshaler, call its UnmarshalBinary(data []byte) error -// - Else decode it based on its reflect.Kind -// -// There are some special rules when decoding into containers (slice/array/map/struct). -// Decode will typically use the stream contents to UPDATE the container. -// - A map can be decoded from a stream map, by updating matching keys. -// - A slice can be decoded from a stream array, -// by updating the first n elements, where n is length of the stream. -// - A slice can be decoded from a stream map, by decoding as if -// it contains a sequence of key-value pairs. -// - A struct can be decoded from a stream map, by updating matching fields. -// - A struct can be decoded from a stream array, -// by updating fields as they occur in the struct (by index). -// -// When decoding a stream map or array with length of 0 into a nil map or slice, -// we reset the destination map or slice to a zero-length value. -// -// However, when decoding a stream nil, we reset the destination container -// to its "zero" value (e.g. nil for slice/map, etc). -// -// Note: we allow nil values in the stream anywhere except for map keys. -// A nil value in the encoded stream where a map key is expected is treated as an error. -func (d *Decoder) Decode(v interface{}) (err error) { - defer d.deferred(&err) - d.MustDecode(v) - return -} - -// MustDecode is like Decode, but panics if unable to Decode. -// This provides insight to the code location that triggered the error. -func (d *Decoder) MustDecode(v interface{}) { - // TODO: Top-level: ensure that v is a pointer and not nil. - if d.err != nil { - panic(d.err) - } - if d.d.TryDecodeAsNil() { - setZero(v) - } else { - d.decode(v) - } - d.alwaysAtEnd() - // xprintf(">>>>>>>> >>>>>>>> num decFns: %v\n", d.cf.sn) -} - -func (d *Decoder) deferred(err1 *error) { - d.alwaysAtEnd() - if recoverPanicToErr { - if x := recover(); x != nil { - panicValToErr(d, x, err1) - panicValToErr(d, x, &d.err) - } - } -} - -func (d *Decoder) alwaysAtEnd() { - if d.n != nil { - // if n != nil, then nsp != nil (they are always set together) - d.nsp.Put(d.n) - d.n, d.nsp = nil, nil - } - d.codecFnPooler.alwaysAtEnd() -} - -// // this is not a smart swallow, as it allocates objects and does unnecessary work. -// func (d *Decoder) swallowViaHammer() { -// var blank interface{} -// d.decodeValueNoFn(reflect.ValueOf(&blank).Elem()) -// } - -func (d *Decoder) swallow() { - // smarter decode that just swallows the content - dd := d.d - if dd.TryDecodeAsNil() { - return - } - elemsep := d.esep - switch dd.ContainerType() { - case valueTypeMap: - containerLen := dd.ReadMapStart() - hasLen := containerLen >= 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - // if clenGtEqualZero {if j >= containerLen {break} } else if dd.CheckBreak() {break} - if elemsep { - dd.ReadMapElemKey() - } - d.swallow() - if elemsep { - dd.ReadMapElemValue() - } - d.swallow() - } - dd.ReadMapEnd() - case valueTypeArray: - containerLen := dd.ReadArrayStart() - hasLen := containerLen >= 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if elemsep { - dd.ReadArrayElem() - } - d.swallow() - } - dd.ReadArrayEnd() - case valueTypeBytes: - dd.DecodeBytes(d.b[:], true) - case valueTypeString: - dd.DecodeStringAsBytes() - default: - // these are all primitives, which we can get from decodeNaked - // if RawExt using Value, complete the processing. - n := d.naked() - dd.DecodeNaked() - if n.v == valueTypeExt && n.l == nil { - n.initContainers() - if n.li < arrayCacheLen { - n.ia[n.li] = nil - n.li++ - d.decode(&n.ia[n.li-1]) - n.ia[n.li-1] = nil - n.li-- - } else { - var v2 interface{} - d.decode(&v2) - } - } - } -} - -func setZero(iv interface{}) { - if iv == nil || definitelyNil(iv) { - return - } - var canDecode bool - switch v := iv.(type) { - case *string: - *v = "" - case *bool: - *v = false - case *int: - *v = 0 - case *int8: - *v = 0 - case *int16: - *v = 0 - case *int32: - *v = 0 - case *int64: - *v = 0 - case *uint: - *v = 0 - case *uint8: - *v = 0 - case *uint16: - *v = 0 - case *uint32: - *v = 0 - case *uint64: - *v = 0 - case *float32: - *v = 0 - case *float64: - *v = 0 - case *[]uint8: - *v = nil - case *Raw: - *v = nil - case *time.Time: - *v = time.Time{} - case reflect.Value: - if v, canDecode = isDecodeable(v); canDecode && v.CanSet() { - v.Set(reflect.Zero(v.Type())) - } // TODO: else drain if chan, clear if map, set all to nil if slice??? - default: - if !fastpathDecodeSetZeroTypeSwitch(iv) { - v := reflect.ValueOf(iv) - if v, canDecode = isDecodeable(v); canDecode && v.CanSet() { - v.Set(reflect.Zero(v.Type())) - } // TODO: else drain if chan, clear if map, set all to nil if slice??? - } - } -} - -func (d *Decoder) decode(iv interface{}) { - // check nil and interfaces explicitly, - // so that type switches just have a run of constant non-interface types. - if iv == nil { - d.errorstr(errstrCannotDecodeIntoNil) - return - } - if v, ok := iv.(Selfer); ok { - v.CodecDecodeSelf(d) - return - } - - switch v := iv.(type) { - // case nil: - // case Selfer: - - case reflect.Value: - v = d.ensureDecodeable(v) - d.decodeValue(v, nil, true) - - case *string: - *v = d.d.DecodeString() - case *bool: - *v = d.d.DecodeBool() - case *int: - *v = int(chkOvf.IntV(d.d.DecodeInt64(), intBitsize)) - case *int8: - *v = int8(chkOvf.IntV(d.d.DecodeInt64(), 8)) - case *int16: - *v = int16(chkOvf.IntV(d.d.DecodeInt64(), 16)) - case *int32: - *v = int32(chkOvf.IntV(d.d.DecodeInt64(), 32)) - case *int64: - *v = d.d.DecodeInt64() - case *uint: - *v = uint(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize)) - case *uint8: - *v = uint8(chkOvf.UintV(d.d.DecodeUint64(), 8)) - case *uint16: - *v = uint16(chkOvf.UintV(d.d.DecodeUint64(), 16)) - case *uint32: - *v = uint32(chkOvf.UintV(d.d.DecodeUint64(), 32)) - case *uint64: - *v = d.d.DecodeUint64() - case *float32: - f64 := d.d.DecodeFloat64() - if chkOvf.Float32(f64) { - d.errorf("float32 overflow: %v", f64) - } - *v = float32(f64) - case *float64: - *v = d.d.DecodeFloat64() - case *[]uint8: - *v = d.d.DecodeBytes(*v, false) - case []uint8: - b := d.d.DecodeBytes(v, false) - if !(len(b) > 0 && len(b) == len(v) && &b[0] == &v[0]) { - copy(v, b) - } - case *time.Time: - *v = d.d.DecodeTime() - case *Raw: - *v = d.rawBytes() - - case *interface{}: - d.decodeValue(reflect.ValueOf(iv).Elem(), nil, true) - // d.decodeValueNotNil(reflect.ValueOf(iv).Elem()) - - default: - if !fastpathDecodeTypeSwitch(iv, d) { - v := reflect.ValueOf(iv) - v = d.ensureDecodeable(v) - d.decodeValue(v, nil, false) - // d.decodeValueFallback(v) - } - } -} - -func (d *Decoder) decodeValue(rv reflect.Value, fn *codecFn, chkAll bool) { - // If stream is not containing a nil value, then we can deref to the base - // non-pointer value, and decode into that. - var rvp reflect.Value - var rvpValid bool - if rv.Kind() == reflect.Ptr { - rvpValid = true - for { - if rv.IsNil() { - rv.Set(reflect.New(rv.Type().Elem())) - } - rvp = rv - rv = rv.Elem() - if rv.Kind() != reflect.Ptr { - break - } - } - } - - if fn == nil { - // always pass checkCodecSelfer=true, in case T or ****T is passed, where *T is a Selfer - fn = d.cfer().get(rv.Type(), chkAll, true) // chkAll, chkAll) - } - if fn.i.addrD { - if rvpValid { - fn.fd(d, &fn.i, rvp) - } else if rv.CanAddr() { - fn.fd(d, &fn.i, rv.Addr()) - } else if !fn.i.addrF { - fn.fd(d, &fn.i, rv) - } else { - d.errorf("cannot decode into a non-pointer value") - } - } else { - fn.fd(d, &fn.i, rv) - } - // return rv -} - -func (d *Decoder) structFieldNotFound(index int, rvkencname string) { - // NOTE: rvkencname may be a stringView, so don't pass it to another function. - if d.h.ErrorIfNoField { - if index >= 0 { - d.errorf("no matching struct field found when decoding stream array at index %v", index) - return - } else if rvkencname != "" { - d.errorf("no matching struct field found when decoding stream map with key " + rvkencname) - return - } - } - d.swallow() -} - -func (d *Decoder) arrayCannotExpand(sliceLen, streamLen int) { - if d.h.ErrorIfNoArrayExpand { - d.errorf("cannot expand array len during decode from %v to %v", sliceLen, streamLen) - } -} - -func isDecodeable(rv reflect.Value) (rv2 reflect.Value, canDecode bool) { - switch rv.Kind() { - case reflect.Array: - return rv, true - case reflect.Ptr: - if !rv.IsNil() { - return rv.Elem(), true - } - case reflect.Slice, reflect.Chan, reflect.Map: - if !rv.IsNil() { - return rv, true - } - } - return -} - -func (d *Decoder) ensureDecodeable(rv reflect.Value) (rv2 reflect.Value) { - // decode can take any reflect.Value that is a inherently addressable i.e. - // - array - // - non-nil chan (we will SEND to it) - // - non-nil slice (we will set its elements) - // - non-nil map (we will put into it) - // - non-nil pointer (we can "update" it) - rv2, canDecode := isDecodeable(rv) - if canDecode { - return - } - if !rv.IsValid() { - d.errorstr(errstrCannotDecodeIntoNil) - return - } - if !rv.CanInterface() { - d.errorf("cannot decode into a value without an interface: %v", rv) - return - } - rvi := rv2i(rv) - rvk := rv.Kind() - d.errorf("cannot decode into value of kind: %v, type: %T, %v", rvk, rvi, rvi) - return -} - -// Possibly get an interned version of a string -// -// This should mostly be used for map keys, where the key type is string. -// This is because keys of a map/struct are typically reused across many objects. -func (d *Decoder) string(v []byte) (s string) { - if d.is == nil { - return string(v) // don't return stringView, as we need a real string here. - } - s, ok := d.is[string(v)] // no allocation here, per go implementation - if !ok { - s = string(v) // new allocation here - d.is[s] = s - } - return s -} - -// nextValueBytes returns the next value in the stream as a set of bytes. -func (d *Decoder) nextValueBytes() (bs []byte) { - d.d.uncacheRead() - d.r.track() - d.swallow() - bs = d.r.stopTrack() - return -} - -func (d *Decoder) rawBytes() []byte { - // ensure that this is not a view into the bytes - // i.e. make new copy always. - bs := d.nextValueBytes() - bs2 := make([]byte, len(bs)) - copy(bs2, bs) - return bs2 -} - -func (d *Decoder) wrapErrstr(v interface{}, err *error) { - *err = fmt.Errorf("%s decode error [pos %d]: %v", d.hh.Name(), d.r.numread(), v) -} - -// -------------------------------------------------- - -// decSliceHelper assists when decoding into a slice, from a map or an array in the stream. -// A slice can be set from a map or array in stream. This supports the MapBySlice interface. -type decSliceHelper struct { - d *Decoder - // ct valueType - array bool -} - -func (d *Decoder) decSliceHelperStart() (x decSliceHelper, clen int) { - dd := d.d - ctyp := dd.ContainerType() - switch ctyp { - case valueTypeArray: - x.array = true - clen = dd.ReadArrayStart() - case valueTypeMap: - clen = dd.ReadMapStart() * 2 - default: - d.errorf("only encoded map or array can be decoded into a slice (%d)", ctyp) - } - // x.ct = ctyp - x.d = d - return -} - -func (x decSliceHelper) End() { - if x.array { - x.d.d.ReadArrayEnd() - } else { - x.d.d.ReadMapEnd() - } -} - -func (x decSliceHelper) ElemContainerState(index int) { - if x.array { - x.d.d.ReadArrayElem() - } else if index%2 == 0 { - x.d.d.ReadMapElemKey() - } else { - x.d.d.ReadMapElemValue() - } -} - -func decByteSlice(r decReader, clen, maxInitLen int, bs []byte) (bsOut []byte) { - if clen == 0 { - return zeroByteSlice - } - if len(bs) == clen { - bsOut = bs - r.readb(bsOut) - } else if cap(bs) >= clen { - bsOut = bs[:clen] - r.readb(bsOut) - } else { - // bsOut = make([]byte, clen) - len2 := decInferLen(clen, maxInitLen, 1) - bsOut = make([]byte, len2) - r.readb(bsOut) - for len2 < clen { - len3 := decInferLen(clen-len2, maxInitLen, 1) - bs3 := bsOut - bsOut = make([]byte, len2+len3) - copy(bsOut, bs3) - r.readb(bsOut[len2:]) - len2 += len3 - } - } - return -} - -func detachZeroCopyBytes(isBytesReader bool, dest []byte, in []byte) (out []byte) { - if xlen := len(in); xlen > 0 { - if isBytesReader || xlen <= scratchByteArrayLen { - if cap(dest) >= xlen { - out = dest[:xlen] - } else { - out = make([]byte, xlen) - } - copy(out, in) - return - } - } - return in -} - -// decInferLen will infer a sensible length, given the following: -// - clen: length wanted. -// - maxlen: max length to be returned. -// if <= 0, it is unset, and we infer it based on the unit size -// - unit: number of bytes for each element of the collection -func decInferLen(clen, maxlen, unit int) (rvlen int) { - // handle when maxlen is not set i.e. <= 0 - if clen <= 0 { - return - } - if unit == 0 { - return clen - } - if maxlen <= 0 { - // no maxlen defined. Use maximum of 256K memory, with a floor of 4K items. - // maxlen = 256 * 1024 / unit - // if maxlen < (4 * 1024) { - // maxlen = 4 * 1024 - // } - if unit < (256 / 4) { - maxlen = 256 * 1024 / unit - } else { - maxlen = 4 * 1024 - } - } - if clen > maxlen { - rvlen = maxlen - } else { - rvlen = clen - } - return -} - -func expandSliceRV(s reflect.Value, st reflect.Type, canChange bool, stElemSize, num, slen, scap int) ( - s2 reflect.Value, scap2 int, changed bool, err string) { - l1 := slen + num // new slice length - if l1 < slen { - err = errmsgExpandSliceOverflow - return - } - if l1 <= scap { - if s.CanSet() { - s.SetLen(l1) - } else if canChange { - s2 = s.Slice(0, l1) - scap2 = scap - changed = true - } else { - err = errmsgExpandSliceCannotChange - return - } - return - } - if !canChange { - err = errmsgExpandSliceCannotChange - return - } - scap2 = growCap(scap, stElemSize, num) - s2 = reflect.MakeSlice(st, l1, scap2) - changed = true - reflect.Copy(s2, s) - return -} - -func decReadFull(r io.Reader, bs []byte) (n int, err error) { - var nn int - for n < len(bs) && err == nil { - nn, err = r.Read(bs[n:]) - if nn > 0 { - if err == io.EOF { - // leave EOF for next time - err = nil - } - n += nn - } - } - - // do not do this - it serves no purpose - // if n != len(bs) && err == io.EOF { err = io.ErrUnexpectedEOF } - return -} diff --git a/vendor/github.com/ugorji/go/codec/encode.go b/vendor/github.com/ugorji/go/codec/encode.go deleted file mode 100644 index ef4652945..000000000 --- a/vendor/github.com/ugorji/go/codec/encode.go +++ /dev/null @@ -1,1375 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -import ( - "bufio" - "encoding" - "errors" - "fmt" - "io" - "reflect" - "sort" - "strconv" - "sync" - "time" -) - -const defEncByteBufSize = 1 << 6 // 4:16, 6:64, 8:256, 10:1024 - -var errEncoderNotInitialized = errors.New("Encoder not initialized") - -// encWriter abstracts writing to a byte array or to an io.Writer. -type encWriter interface { - writeb([]byte) - writestr(string) - writen1(byte) - writen2(byte, byte) - atEndOfEncode() -} - -// encDriver abstracts the actual codec (binc vs msgpack, etc) -type encDriver interface { - EncodeNil() - EncodeInt(i int64) - EncodeUint(i uint64) - EncodeBool(b bool) - EncodeFloat32(f float32) - EncodeFloat64(f float64) - // encodeExtPreamble(xtag byte, length int) - EncodeRawExt(re *RawExt, e *Encoder) - EncodeExt(v interface{}, xtag uint64, ext Ext, e *Encoder) - EncodeString(c charEncoding, v string) - // EncodeSymbol(v string) - EncodeStringBytes(c charEncoding, v []byte) - EncodeTime(time.Time) - //encBignum(f *big.Int) - //encStringRunes(c charEncoding, v []rune) - WriteArrayStart(length int) - WriteArrayElem() - WriteArrayEnd() - WriteMapStart(length int) - WriteMapElemKey() - WriteMapElemValue() - WriteMapEnd() - - reset() - atEndOfEncode() -} - -type ioEncStringWriter interface { - WriteString(s string) (n int, err error) -} - -type encDriverAsis interface { - EncodeAsis(v []byte) -} - -type encDriverNoopContainerWriter struct{} - -func (encDriverNoopContainerWriter) WriteArrayStart(length int) {} -func (encDriverNoopContainerWriter) WriteArrayElem() {} -func (encDriverNoopContainerWriter) WriteArrayEnd() {} -func (encDriverNoopContainerWriter) WriteMapStart(length int) {} -func (encDriverNoopContainerWriter) WriteMapElemKey() {} -func (encDriverNoopContainerWriter) WriteMapElemValue() {} -func (encDriverNoopContainerWriter) WriteMapEnd() {} -func (encDriverNoopContainerWriter) atEndOfEncode() {} - -type encDriverTrackContainerWriter struct { - c containerState -} - -func (e *encDriverTrackContainerWriter) WriteArrayStart(length int) { e.c = containerArrayStart } -func (e *encDriverTrackContainerWriter) WriteArrayElem() { e.c = containerArrayElem } -func (e *encDriverTrackContainerWriter) WriteArrayEnd() { e.c = containerArrayEnd } -func (e *encDriverTrackContainerWriter) WriteMapStart(length int) { e.c = containerMapStart } -func (e *encDriverTrackContainerWriter) WriteMapElemKey() { e.c = containerMapKey } -func (e *encDriverTrackContainerWriter) WriteMapElemValue() { e.c = containerMapValue } -func (e *encDriverTrackContainerWriter) WriteMapEnd() { e.c = containerMapEnd } -func (e *encDriverTrackContainerWriter) atEndOfEncode() {} - -// type ioEncWriterWriter interface { -// WriteByte(c byte) error -// WriteString(s string) (n int, err error) -// Write(p []byte) (n int, err error) -// } - -// EncodeOptions captures configuration options during encode. -type EncodeOptions struct { - // WriterBufferSize is the size of the buffer used when writing. - // - // if > 0, we use a smart buffer internally for performance purposes. - WriterBufferSize int - - // ChanRecvTimeout is the timeout used when selecting from a chan. - // - // Configuring this controls how we receive from a chan during the encoding process. - // - If ==0, we only consume the elements currently available in the chan. - // - if <0, we consume until the chan is closed. - // - If >0, we consume until this timeout. - ChanRecvTimeout time.Duration - - // StructToArray specifies to encode a struct as an array, and not as a map - StructToArray bool - - // Canonical representation means that encoding a value will always result in the same - // sequence of bytes. - // - // This only affects maps, as the iteration order for maps is random. - // - // The implementation MAY use the natural sort order for the map keys if possible: - // - // - If there is a natural sort order (ie for number, bool, string or []byte keys), - // then the map keys are first sorted in natural order and then written - // with corresponding map values to the strema. - // - If there is no natural sort order, then the map keys will first be - // encoded into []byte, and then sorted, - // before writing the sorted keys and the corresponding map values to the stream. - // - Canonical bool - - // CheckCircularRef controls whether we check for circular references - // and error fast during an encode. - // - // If enabled, an error is received if a pointer to a struct - // references itself either directly or through one of its fields (iteratively). - // - // This is opt-in, as there may be a performance hit to checking circular references. - CheckCircularRef bool - - // RecursiveEmptyCheck controls whether we descend into interfaces, structs and pointers - // when checking if a value is empty. - // - // Note that this may make OmitEmpty more expensive, as it incurs a lot more reflect calls. - RecursiveEmptyCheck bool - - // Raw controls whether we encode Raw values. - // This is a "dangerous" option and must be explicitly set. - // If set, we blindly encode Raw values as-is, without checking - // if they are a correct representation of a value in that format. - // If unset, we error out. - Raw bool - - // // AsSymbols defines what should be encoded as symbols. - // // - // // Encoding as symbols can reduce the encoded size significantly. - // // - // // However, during decoding, each string to be encoded as a symbol must - // // be checked to see if it has been seen before. Consequently, encoding time - // // will increase if using symbols, because string comparisons has a clear cost. - // // - // // Sample values: - // // AsSymbolNone - // // AsSymbolAll - // // AsSymbolMapStringKeys - // // AsSymbolMapStringKeysFlag | AsSymbolStructFieldNameFlag - // AsSymbols AsSymbolFlag -} - -// --------------------------------------------- - -// ioEncWriter implements encWriter and can write to an io.Writer implementation -type ioEncWriter struct { - w io.Writer - ww io.Writer - bw io.ByteWriter - sw ioEncStringWriter - fw ioFlusher - b [8]byte -} - -func (z *ioEncWriter) WriteByte(b byte) (err error) { - z.b[0] = b - _, err = z.w.Write(z.b[:1]) - return -} - -func (z *ioEncWriter) WriteString(s string) (n int, err error) { - return z.w.Write(bytesView(s)) -} - -func (z *ioEncWriter) writeb(bs []byte) { - if _, err := z.ww.Write(bs); err != nil { - panic(err) - } -} - -func (z *ioEncWriter) writestr(s string) { - if _, err := z.sw.WriteString(s); err != nil { - panic(err) - } -} - -func (z *ioEncWriter) writen1(b byte) { - if err := z.bw.WriteByte(b); err != nil { - panic(err) - } -} - -func (z *ioEncWriter) writen2(b1, b2 byte) { - var err error - if err = z.bw.WriteByte(b1); err == nil { - if err = z.bw.WriteByte(b2); err == nil { - return - } - } - panic(err) -} - -// func (z *ioEncWriter) writen5(b1, b2, b3, b4, b5 byte) { -// z.b[0], z.b[1], z.b[2], z.b[3], z.b[4] = b1, b2, b3, b4, b5 -// if _, err := z.ww.Write(z.b[:5]); err != nil { -// panic(err) -// } -// } - -func (z *ioEncWriter) atEndOfEncode() { - if z.fw != nil { - if err := z.fw.Flush(); err != nil { - panic(err) - } - } -} - -// --------------------------------------------- - -// bytesEncAppender implements encWriter and can write to an byte slice. -type bytesEncAppender struct { - b []byte - out *[]byte -} - -func (z *bytesEncAppender) writeb(s []byte) { - z.b = append(z.b, s...) -} -func (z *bytesEncAppender) writestr(s string) { - z.b = append(z.b, s...) -} -func (z *bytesEncAppender) writen1(b1 byte) { - z.b = append(z.b, b1) -} -func (z *bytesEncAppender) writen2(b1, b2 byte) { - z.b = append(z.b, b1, b2) -} -func (z *bytesEncAppender) atEndOfEncode() { - *(z.out) = z.b -} -func (z *bytesEncAppender) reset(in []byte, out *[]byte) { - z.b = in[:0] - z.out = out -} - -// --------------------------------------------- - -func (e *Encoder) rawExt(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeRawExt(rv2i(rv).(*RawExt), e) -} - -func (e *Encoder) ext(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeExt(rv2i(rv), f.xfTag, f.xfFn, e) -} - -func (e *Encoder) selferMarshal(f *codecFnInfo, rv reflect.Value) { - rv2i(rv).(Selfer).CodecEncodeSelf(e) -} - -func (e *Encoder) binaryMarshal(f *codecFnInfo, rv reflect.Value) { - bs, fnerr := rv2i(rv).(encoding.BinaryMarshaler).MarshalBinary() - e.marshal(bs, fnerr, false, cRAW) -} - -func (e *Encoder) textMarshal(f *codecFnInfo, rv reflect.Value) { - bs, fnerr := rv2i(rv).(encoding.TextMarshaler).MarshalText() - e.marshal(bs, fnerr, false, cUTF8) -} - -func (e *Encoder) jsonMarshal(f *codecFnInfo, rv reflect.Value) { - bs, fnerr := rv2i(rv).(jsonMarshaler).MarshalJSON() - e.marshal(bs, fnerr, true, cUTF8) -} - -func (e *Encoder) raw(f *codecFnInfo, rv reflect.Value) { - e.rawBytes(rv2i(rv).(Raw)) -} - -func (e *Encoder) kInvalid(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeNil() -} - -func (e *Encoder) kErr(f *codecFnInfo, rv reflect.Value) { - e.errorf("unsupported kind %s, for %#v", rv.Kind(), rv) -} - -func (e *Encoder) kSlice(f *codecFnInfo, rv reflect.Value) { - ti := f.ti - ee := e.e - // array may be non-addressable, so we have to manage with care - // (don't call rv.Bytes, rv.Slice, etc). - // E.g. type struct S{B [2]byte}; - // Encode(S{}) will bomb on "panic: slice of unaddressable array". - if f.seq != seqTypeArray { - if rv.IsNil() { - ee.EncodeNil() - return - } - // If in this method, then there was no extension function defined. - // So it's okay to treat as []byte. - if ti.rtid == uint8SliceTypId { - ee.EncodeStringBytes(cRAW, rv.Bytes()) - return - } - } - if f.seq == seqTypeChan && ti.chandir&uint8(reflect.RecvDir) == 0 { - e.errorf("send-only channel cannot be encoded") - } - elemsep := e.esep - rtelem := ti.elem - rtelemIsByte := uint8TypId == rt2id(rtelem) // NOT rtelem.Kind() == reflect.Uint8 - var l int - // if a slice, array or chan of bytes, treat specially - if rtelemIsByte { - switch f.seq { - case seqTypeSlice: - ee.EncodeStringBytes(cRAW, rv.Bytes()) - case seqTypeArray: - l = rv.Len() - if rv.CanAddr() { - ee.EncodeStringBytes(cRAW, rv.Slice(0, l).Bytes()) - } else { - var bs []byte - if l <= cap(e.b) { - bs = e.b[:l] - } else { - bs = make([]byte, l) - } - reflect.Copy(reflect.ValueOf(bs), rv) - ee.EncodeStringBytes(cRAW, bs) - } - case seqTypeChan: - // do not use range, so that the number of elements encoded - // does not change, and encoding does not hang waiting on someone to close chan. - // for b := range rv2i(rv).(<-chan byte) { bs = append(bs, b) } - // ch := rv2i(rv).(<-chan byte) // fix error - that this is a chan byte, not a <-chan byte. - - if rv.IsNil() { - ee.EncodeNil() - break - } - bs := e.b[:0] - irv := rv2i(rv) - ch, ok := irv.(<-chan byte) - if !ok { - ch = irv.(chan byte) - } - - L1: - switch timeout := e.h.ChanRecvTimeout; { - case timeout == 0: // only consume available - for { - select { - case b := <-ch: - bs = append(bs, b) - default: - break L1 - } - } - case timeout > 0: // consume until timeout - tt := time.NewTimer(timeout) - for { - select { - case b := <-ch: - bs = append(bs, b) - case <-tt.C: - // close(tt.C) - break L1 - } - } - default: // consume until close - for b := range ch { - bs = append(bs, b) - } - } - - ee.EncodeStringBytes(cRAW, bs) - } - return - } - - // if chan, consume chan into a slice, and work off that slice. - var rvcs reflect.Value - if f.seq == seqTypeChan { - rvcs = reflect.Zero(reflect.SliceOf(rtelem)) - timeout := e.h.ChanRecvTimeout - if timeout < 0 { // consume until close - for { - recv, recvOk := rv.Recv() - if !recvOk { - break - } - rvcs = reflect.Append(rvcs, recv) - } - } else { - cases := make([]reflect.SelectCase, 2) - cases[0] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: rv} - if timeout == 0 { - cases[1] = reflect.SelectCase{Dir: reflect.SelectDefault} - } else { - tt := time.NewTimer(timeout) - cases[1] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(tt.C)} - } - for { - chosen, recv, recvOk := reflect.Select(cases) - if chosen == 1 || !recvOk { - break - } - rvcs = reflect.Append(rvcs, recv) - } - } - rv = rvcs // TODO: ensure this doesn't mess up anywhere that rv of kind chan is expected - } - - l = rv.Len() - if ti.mbs { - if l%2 == 1 { - e.errorf("mapBySlice requires even slice length, but got %v", l) - return - } - ee.WriteMapStart(l / 2) - } else { - ee.WriteArrayStart(l) - } - - if l > 0 { - var fn *codecFn - for rtelem.Kind() == reflect.Ptr { - rtelem = rtelem.Elem() - } - // if kind is reflect.Interface, do not pre-determine the - // encoding type, because preEncodeValue may break it down to - // a concrete type and kInterface will bomb. - if rtelem.Kind() != reflect.Interface { - fn = e.cfer().get(rtelem, true, true) - } - for j := 0; j < l; j++ { - if elemsep { - if ti.mbs { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - } else { - ee.WriteArrayElem() - } - } - e.encodeValue(rv.Index(j), fn, true) - } - } - - if ti.mbs { - ee.WriteMapEnd() - } else { - ee.WriteArrayEnd() - } -} - -func (e *Encoder) kStructNoOmitempty(f *codecFnInfo, rv reflect.Value) { - fti := f.ti - elemsep := e.esep - tisfi := fti.sfiSrc - toMap := !(fti.toArray || e.h.StructToArray) - if toMap { - tisfi = fti.sfiSort - } - ee := e.e - - sfn := structFieldNode{v: rv, update: false} - if toMap { - ee.WriteMapStart(len(tisfi)) - if elemsep { - for _, si := range tisfi { - ee.WriteMapElemKey() - // ee.EncodeString(cUTF8, si.encName) - encStructFieldKey(ee, fti.keyType, si.encName) - ee.WriteMapElemValue() - e.encodeValue(sfn.field(si), nil, true) - } - } else { - for _, si := range tisfi { - // ee.EncodeString(cUTF8, si.encName) - encStructFieldKey(ee, fti.keyType, si.encName) - e.encodeValue(sfn.field(si), nil, true) - } - } - ee.WriteMapEnd() - } else { - ee.WriteArrayStart(len(tisfi)) - if elemsep { - for _, si := range tisfi { - ee.WriteArrayElem() - e.encodeValue(sfn.field(si), nil, true) - } - } else { - for _, si := range tisfi { - e.encodeValue(sfn.field(si), nil, true) - } - } - ee.WriteArrayEnd() - } -} - -func encStructFieldKey(ee encDriver, keyType valueType, s string) { - var m must - - // use if-else-if, not switch (which compiles to binary-search) - // since keyType is typically valueTypeString, branch prediction is pretty good. - - if keyType == valueTypeString { - ee.EncodeString(cUTF8, s) - } else if keyType == valueTypeInt { - ee.EncodeInt(m.Int(strconv.ParseInt(s, 10, 64))) - } else if keyType == valueTypeUint { - ee.EncodeUint(m.Uint(strconv.ParseUint(s, 10, 64))) - } else if keyType == valueTypeFloat { - ee.EncodeFloat64(m.Float(strconv.ParseFloat(s, 64))) - } else { - ee.EncodeString(cUTF8, s) - } -} - -func (e *Encoder) kStruct(f *codecFnInfo, rv reflect.Value) { - fti := f.ti - elemsep := e.esep - tisfi := fti.sfiSrc - toMap := !(fti.toArray || e.h.StructToArray) - // if toMap, use the sorted array. If toArray, use unsorted array (to match sequence in struct) - if toMap { - tisfi = fti.sfiSort - } - newlen := len(fti.sfiSort) - ee := e.e - - // Use sync.Pool to reduce allocating slices unnecessarily. - // The cost of sync.Pool is less than the cost of new allocation. - // - // Each element of the array pools one of encStructPool(8|16|32|64). - // It allows the re-use of slices up to 64 in length. - // A performance cost of encoding structs was collecting - // which values were empty and should be omitted. - // We needed slices of reflect.Value and string to collect them. - // This shared pool reduces the amount of unnecessary creation we do. - // The cost is that of locking sometimes, but sync.Pool is efficient - // enough to reduce thread contention. - - var spool *sync.Pool - var poolv interface{} - var fkvs []stringRv - // fmt.Printf(">>>>>>>>>>>>>> encode.kStruct: newlen: %d\n", newlen) - if newlen <= 8 { - spool, poolv = pool.stringRv8() - fkvs = poolv.(*[8]stringRv)[:newlen] - } else if newlen <= 16 { - spool, poolv = pool.stringRv16() - fkvs = poolv.(*[16]stringRv)[:newlen] - } else if newlen <= 32 { - spool, poolv = pool.stringRv32() - fkvs = poolv.(*[32]stringRv)[:newlen] - } else if newlen <= 64 { - spool, poolv = pool.stringRv64() - fkvs = poolv.(*[64]stringRv)[:newlen] - } else if newlen <= 128 { - spool, poolv = pool.stringRv128() - fkvs = poolv.(*[128]stringRv)[:newlen] - } else { - fkvs = make([]stringRv, newlen) - } - - newlen = 0 - var kv stringRv - recur := e.h.RecursiveEmptyCheck - sfn := structFieldNode{v: rv, update: false} - for _, si := range tisfi { - // kv.r = si.field(rv, false) - kv.r = sfn.field(si) - if toMap { - if si.omitEmpty() && isEmptyValue(kv.r, e.h.TypeInfos, recur, recur) { - continue - } - kv.v = si.encName - } else { - // use the zero value. - // if a reference or struct, set to nil (so you do not output too much) - if si.omitEmpty() && isEmptyValue(kv.r, e.h.TypeInfos, recur, recur) { - switch kv.r.Kind() { - case reflect.Struct, reflect.Interface, reflect.Ptr, reflect.Array, reflect.Map, reflect.Slice: - kv.r = reflect.Value{} //encode as nil - } - } - } - fkvs[newlen] = kv - newlen++ - } - - if toMap { - ee.WriteMapStart(newlen) - if elemsep { - for j := 0; j < newlen; j++ { - kv = fkvs[j] - ee.WriteMapElemKey() - // ee.EncodeString(cUTF8, kv.v) - encStructFieldKey(ee, fti.keyType, kv.v) - ee.WriteMapElemValue() - e.encodeValue(kv.r, nil, true) - } - } else { - for j := 0; j < newlen; j++ { - kv = fkvs[j] - // ee.EncodeString(cUTF8, kv.v) - encStructFieldKey(ee, fti.keyType, kv.v) - e.encodeValue(kv.r, nil, true) - } - } - ee.WriteMapEnd() - } else { - ee.WriteArrayStart(newlen) - if elemsep { - for j := 0; j < newlen; j++ { - ee.WriteArrayElem() - e.encodeValue(fkvs[j].r, nil, true) - } - } else { - for j := 0; j < newlen; j++ { - e.encodeValue(fkvs[j].r, nil, true) - } - } - ee.WriteArrayEnd() - } - - // do not use defer. Instead, use explicit pool return at end of function. - // defer has a cost we are trying to avoid. - // If there is a panic and these slices are not returned, it is ok. - if spool != nil { - spool.Put(poolv) - } -} - -func (e *Encoder) kMap(f *codecFnInfo, rv reflect.Value) { - ee := e.e - if rv.IsNil() { - ee.EncodeNil() - return - } - - l := rv.Len() - ee.WriteMapStart(l) - elemsep := e.esep - if l == 0 { - ee.WriteMapEnd() - return - } - // var asSymbols bool - // determine the underlying key and val encFn's for the map. - // This eliminates some work which is done for each loop iteration i.e. - // rv.Type(), ref.ValueOf(rt).Pointer(), then check map/list for fn. - // - // However, if kind is reflect.Interface, do not pre-determine the - // encoding type, because preEncodeValue may break it down to - // a concrete type and kInterface will bomb. - var keyFn, valFn *codecFn - ti := f.ti - rtkey0 := ti.key - rtkey := rtkey0 - rtval0 := ti.elem - rtval := rtval0 - // rtkeyid := rt2id(rtkey0) - for rtval.Kind() == reflect.Ptr { - rtval = rtval.Elem() - } - if rtval.Kind() != reflect.Interface { - valFn = e.cfer().get(rtval, true, true) - } - mks := rv.MapKeys() - - if e.h.Canonical { - e.kMapCanonical(rtkey, rv, mks, valFn) - ee.WriteMapEnd() - return - } - - var keyTypeIsString = stringTypId == rt2id(rtkey0) // rtkeyid - if !keyTypeIsString { - for rtkey.Kind() == reflect.Ptr { - rtkey = rtkey.Elem() - } - if rtkey.Kind() != reflect.Interface { - // rtkeyid = rt2id(rtkey) - keyFn = e.cfer().get(rtkey, true, true) - } - } - - // for j, lmks := 0, len(mks); j < lmks; j++ { - for j := range mks { - if elemsep { - ee.WriteMapElemKey() - } - if keyTypeIsString { - ee.EncodeString(cUTF8, mks[j].String()) - } else { - e.encodeValue(mks[j], keyFn, true) - } - if elemsep { - ee.WriteMapElemValue() - } - e.encodeValue(rv.MapIndex(mks[j]), valFn, true) - - } - ee.WriteMapEnd() -} - -func (e *Encoder) kMapCanonical(rtkey reflect.Type, rv reflect.Value, mks []reflect.Value, valFn *codecFn) { - ee := e.e - elemsep := e.esep - // we previously did out-of-band if an extension was registered. - // This is not necessary, as the natural kind is sufficient for ordering. - - switch rtkey.Kind() { - case reflect.Bool: - mksv := make([]boolRv, len(mks)) - for i, k := range mks { - v := &mksv[i] - v.r = k - v.v = k.Bool() - } - sort.Sort(boolRvSlice(mksv)) - for i := range mksv { - if elemsep { - ee.WriteMapElemKey() - } - ee.EncodeBool(mksv[i].v) - if elemsep { - ee.WriteMapElemValue() - } - e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true) - } - case reflect.String: - mksv := make([]stringRv, len(mks)) - for i, k := range mks { - v := &mksv[i] - v.r = k - v.v = k.String() - } - sort.Sort(stringRvSlice(mksv)) - for i := range mksv { - if elemsep { - ee.WriteMapElemKey() - } - ee.EncodeString(cUTF8, mksv[i].v) - if elemsep { - ee.WriteMapElemValue() - } - e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true) - } - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint, reflect.Uintptr: - mksv := make([]uintRv, len(mks)) - for i, k := range mks { - v := &mksv[i] - v.r = k - v.v = k.Uint() - } - sort.Sort(uintRvSlice(mksv)) - for i := range mksv { - if elemsep { - ee.WriteMapElemKey() - } - ee.EncodeUint(mksv[i].v) - if elemsep { - ee.WriteMapElemValue() - } - e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true) - } - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - mksv := make([]intRv, len(mks)) - for i, k := range mks { - v := &mksv[i] - v.r = k - v.v = k.Int() - } - sort.Sort(intRvSlice(mksv)) - for i := range mksv { - if elemsep { - ee.WriteMapElemKey() - } - ee.EncodeInt(mksv[i].v) - if elemsep { - ee.WriteMapElemValue() - } - e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true) - } - case reflect.Float32: - mksv := make([]floatRv, len(mks)) - for i, k := range mks { - v := &mksv[i] - v.r = k - v.v = k.Float() - } - sort.Sort(floatRvSlice(mksv)) - for i := range mksv { - if elemsep { - ee.WriteMapElemKey() - } - ee.EncodeFloat32(float32(mksv[i].v)) - if elemsep { - ee.WriteMapElemValue() - } - e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true) - } - case reflect.Float64: - mksv := make([]floatRv, len(mks)) - for i, k := range mks { - v := &mksv[i] - v.r = k - v.v = k.Float() - } - sort.Sort(floatRvSlice(mksv)) - for i := range mksv { - if elemsep { - ee.WriteMapElemKey() - } - ee.EncodeFloat64(mksv[i].v) - if elemsep { - ee.WriteMapElemValue() - } - e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true) - } - case reflect.Struct: - if rv.Type() == timeTyp { - mksv := make([]timeRv, len(mks)) - for i, k := range mks { - v := &mksv[i] - v.r = k - v.v = rv2i(k).(time.Time) - } - sort.Sort(timeRvSlice(mksv)) - for i := range mksv { - if elemsep { - ee.WriteMapElemKey() - } - ee.EncodeTime(mksv[i].v) - if elemsep { - ee.WriteMapElemValue() - } - e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true) - } - break - } - fallthrough - default: - // out-of-band - // first encode each key to a []byte first, then sort them, then record - var mksv []byte = make([]byte, 0, len(mks)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - mksbv := make([]bytesRv, len(mks)) - for i, k := range mks { - v := &mksbv[i] - l := len(mksv) - e2.MustEncode(k) - v.r = k - v.v = mksv[l:] - } - sort.Sort(bytesRvSlice(mksbv)) - for j := range mksbv { - if elemsep { - ee.WriteMapElemKey() - } - e.asis(mksbv[j].v) - if elemsep { - ee.WriteMapElemValue() - } - e.encodeValue(rv.MapIndex(mksbv[j].r), valFn, true) - } - } -} - -// // -------------------------------------------------- - -type encWriterSwitch struct { - wi *ioEncWriter - // wb bytesEncWriter - wb bytesEncAppender - wx bool // if bytes, wx=true - esep bool // whether it has elem separators - isas bool // whether e.as != nil -} - -// // TODO: Uncomment after mid-stack inlining enabled in go 1.11 - -// func (z *encWriterSwitch) writeb(s []byte) { -// if z.wx { -// z.wb.writeb(s) -// } else { -// z.wi.writeb(s) -// } -// } -// func (z *encWriterSwitch) writestr(s string) { -// if z.wx { -// z.wb.writestr(s) -// } else { -// z.wi.writestr(s) -// } -// } -// func (z *encWriterSwitch) writen1(b1 byte) { -// if z.wx { -// z.wb.writen1(b1) -// } else { -// z.wi.writen1(b1) -// } -// } -// func (z *encWriterSwitch) writen2(b1, b2 byte) { -// if z.wx { -// z.wb.writen2(b1, b2) -// } else { -// z.wi.writen2(b1, b2) -// } -// } - -// An Encoder writes an object to an output stream in the codec format. -type Encoder struct { - panicHdl - // hopefully, reduce derefencing cost by laying the encWriter inside the Encoder - e encDriver - // NOTE: Encoder shouldn't call it's write methods, - // as the handler MAY need to do some coordination. - w encWriter - - h *BasicHandle - bw *bufio.Writer - as encDriverAsis - - // ---- cpu cache line boundary? - - // ---- cpu cache line boundary? - encWriterSwitch - err error - - // ---- cpu cache line boundary? - codecFnPooler - ci set - js bool // here, so that no need to piggy back on *codecFner for this - be bool // here, so that no need to piggy back on *codecFner for this - _ [6]byte // padding - - // ---- writable fields during execution --- *try* to keep in sep cache line - - // ---- cpu cache line boundary? - // b [scratchByteArrayLen]byte - // _ [cacheLineSize - scratchByteArrayLen]byte // padding - b [cacheLineSize - 0]byte // used for encoding a chan or (non-addressable) array of bytes -} - -// NewEncoder returns an Encoder for encoding into an io.Writer. -// -// For efficiency, Users are encouraged to pass in a memory buffered writer -// (eg bufio.Writer, bytes.Buffer). -func NewEncoder(w io.Writer, h Handle) *Encoder { - e := newEncoder(h) - e.Reset(w) - return e -} - -// NewEncoderBytes returns an encoder for encoding directly and efficiently -// into a byte slice, using zero-copying to temporary slices. -// -// It will potentially replace the output byte slice pointed to. -// After encoding, the out parameter contains the encoded contents. -func NewEncoderBytes(out *[]byte, h Handle) *Encoder { - e := newEncoder(h) - e.ResetBytes(out) - return e -} - -func newEncoder(h Handle) *Encoder { - e := &Encoder{h: h.getBasicHandle(), err: errEncoderNotInitialized} - e.hh = h - e.esep = h.hasElemSeparators() - return e -} - -func (e *Encoder) resetCommon() { - if e.e == nil || e.hh.recreateEncDriver(e.e) { - e.e = e.hh.newEncDriver(e) - e.as, e.isas = e.e.(encDriverAsis) - // e.cr, _ = e.e.(containerStateRecv) - } - e.be = e.hh.isBinary() - _, e.js = e.hh.(*JsonHandle) - e.e.reset() - e.err = nil -} - -// Reset resets the Encoder with a new output stream. -// -// This accommodates using the state of the Encoder, -// where it has "cached" information about sub-engines. -func (e *Encoder) Reset(w io.Writer) { - if w == nil { - return - } - if e.wi == nil { - e.wi = new(ioEncWriter) - } - var ok bool - e.wx = false - e.wi.w = w - if e.h.WriterBufferSize > 0 { - e.bw = bufio.NewWriterSize(w, e.h.WriterBufferSize) - e.wi.bw = e.bw - e.wi.sw = e.bw - e.wi.fw = e.bw - e.wi.ww = e.bw - } else { - if e.wi.bw, ok = w.(io.ByteWriter); !ok { - e.wi.bw = e.wi - } - if e.wi.sw, ok = w.(ioEncStringWriter); !ok { - e.wi.sw = e.wi - } - e.wi.fw, _ = w.(ioFlusher) - e.wi.ww = w - } - e.w = e.wi - e.resetCommon() -} - -// ResetBytes resets the Encoder with a new destination output []byte. -func (e *Encoder) ResetBytes(out *[]byte) { - if out == nil { - return - } - var in []byte - if out != nil { - in = *out - } - if in == nil { - in = make([]byte, defEncByteBufSize) - } - e.wx = true - e.wb.reset(in, out) - e.w = &e.wb - e.resetCommon() -} - -// Encode writes an object into a stream. -// -// Encoding can be configured via the struct tag for the fields. -// The key (in the struct tags) that we look at is configurable. -// -// By default, we look up the "codec" key in the struct field's tags, -// and fall bak to the "json" key if "codec" is absent. -// That key in struct field's tag value is the key name, -// followed by an optional comma and options. -// -// To set an option on all fields (e.g. omitempty on all fields), you -// can create a field called _struct, and set flags on it. The options -// which can be set on _struct are: -// - omitempty: so all fields are omitted if empty -// - toarray: so struct is encoded as an array -// - int: so struct key names are encoded as signed integers (instead of strings) -// - uint: so struct key names are encoded as unsigned integers (instead of strings) -// - float: so struct key names are encoded as floats (instead of strings) -// More details on these below. -// -// Struct values "usually" encode as maps. Each exported struct field is encoded unless: -// - the field's tag is "-", OR -// - the field is empty (empty or the zero value) and its tag specifies the "omitempty" option. -// -// When encoding as a map, the first string in the tag (before the comma) -// is the map key string to use when encoding. -// ... -// This key is typically encoded as a string. -// However, there are instances where the encoded stream has mapping keys encoded as numbers. -// For example, some cbor streams have keys as integer codes in the stream, but they should map -// to fields in a structured object. Consequently, a struct is the natural representation in code. -// For these, configure the struct to encode/decode the keys as numbers (instead of string). -// This is done with the int,uint or float option on the _struct field (see above). -// -// However, struct values may encode as arrays. This happens when: -// - StructToArray Encode option is set, OR -// - the tag on the _struct field sets the "toarray" option -// Note that omitempty is ignored when encoding struct values as arrays, -// as an entry must be encoded for each field, to maintain its position. -// -// Values with types that implement MapBySlice are encoded as stream maps. -// -// The empty values (for omitempty option) are false, 0, any nil pointer -// or interface value, and any array, slice, map, or string of length zero. -// -// Anonymous fields are encoded inline except: -// - the struct tag specifies a replacement name (first value) -// - the field is of an interface type -// -// Examples: -// -// // NOTE: 'json:' can be used as struct tag key, in place 'codec:' below. -// type MyStruct struct { -// _struct bool `codec:",omitempty"` //set omitempty for every field -// Field1 string `codec:"-"` //skip this field -// Field2 int `codec:"myName"` //Use key "myName" in encode stream -// Field3 int32 `codec:",omitempty"` //use key "Field3". Omit if empty. -// Field4 bool `codec:"f4,omitempty"` //use key "f4". Omit if empty. -// io.Reader //use key "Reader". -// MyStruct `codec:"my1" //use key "my1". -// MyStruct //inline it -// ... -// } -// -// type MyStruct struct { -// _struct bool `codec:",toarray"` //encode struct as an array -// } -// -// type MyStruct struct { -// _struct bool `codec:",uint"` //encode struct with "unsigned integer" keys -// Field1 string `codec:"1"` //encode Field1 key using: EncodeInt(1) -// Field2 string `codec:"2"` //encode Field2 key using: EncodeInt(2) -// } -// -// The mode of encoding is based on the type of the value. When a value is seen: -// - If a Selfer, call its CodecEncodeSelf method -// - If an extension is registered for it, call that extension function -// - If implements encoding.(Binary|Text|JSON)Marshaler, call Marshal(Binary|Text|JSON) method -// - Else encode it based on its reflect.Kind -// -// Note that struct field names and keys in map[string]XXX will be treated as symbols. -// Some formats support symbols (e.g. binc) and will properly encode the string -// only once in the stream, and use a tag to refer to it thereafter. -func (e *Encoder) Encode(v interface{}) (err error) { - defer e.deferred(&err) - e.MustEncode(v) - return -} - -// MustEncode is like Encode, but panics if unable to Encode. -// This provides insight to the code location that triggered the error. -func (e *Encoder) MustEncode(v interface{}) { - if e.err != nil { - panic(e.err) - } - e.encode(v) - e.e.atEndOfEncode() - e.w.atEndOfEncode() - e.alwaysAtEnd() -} - -func (e *Encoder) deferred(err1 *error) { - e.alwaysAtEnd() - if recoverPanicToErr { - if x := recover(); x != nil { - panicValToErr(e, x, err1) - panicValToErr(e, x, &e.err) - } - } -} - -// func (e *Encoder) alwaysAtEnd() { -// e.codecFnPooler.alwaysAtEnd() -// } - -func (e *Encoder) encode(iv interface{}) { - if iv == nil || definitelyNil(iv) { - e.e.EncodeNil() - return - } - if v, ok := iv.(Selfer); ok { - v.CodecEncodeSelf(e) - return - } - - // a switch with only concrete types can be optimized. - // consequently, we deal with nil and interfaces outside. - - switch v := iv.(type) { - case Raw: - e.rawBytes(v) - case reflect.Value: - e.encodeValue(v, nil, true) - - case string: - e.e.EncodeString(cUTF8, v) - case bool: - e.e.EncodeBool(v) - case int: - e.e.EncodeInt(int64(v)) - case int8: - e.e.EncodeInt(int64(v)) - case int16: - e.e.EncodeInt(int64(v)) - case int32: - e.e.EncodeInt(int64(v)) - case int64: - e.e.EncodeInt(v) - case uint: - e.e.EncodeUint(uint64(v)) - case uint8: - e.e.EncodeUint(uint64(v)) - case uint16: - e.e.EncodeUint(uint64(v)) - case uint32: - e.e.EncodeUint(uint64(v)) - case uint64: - e.e.EncodeUint(v) - case uintptr: - e.e.EncodeUint(uint64(v)) - case float32: - e.e.EncodeFloat32(v) - case float64: - e.e.EncodeFloat64(v) - case time.Time: - e.e.EncodeTime(v) - case []uint8: - e.e.EncodeStringBytes(cRAW, v) - - case *Raw: - e.rawBytes(*v) - - case *string: - e.e.EncodeString(cUTF8, *v) - case *bool: - e.e.EncodeBool(*v) - case *int: - e.e.EncodeInt(int64(*v)) - case *int8: - e.e.EncodeInt(int64(*v)) - case *int16: - e.e.EncodeInt(int64(*v)) - case *int32: - e.e.EncodeInt(int64(*v)) - case *int64: - e.e.EncodeInt(*v) - case *uint: - e.e.EncodeUint(uint64(*v)) - case *uint8: - e.e.EncodeUint(uint64(*v)) - case *uint16: - e.e.EncodeUint(uint64(*v)) - case *uint32: - e.e.EncodeUint(uint64(*v)) - case *uint64: - e.e.EncodeUint(*v) - case *uintptr: - e.e.EncodeUint(uint64(*v)) - case *float32: - e.e.EncodeFloat32(*v) - case *float64: - e.e.EncodeFloat64(*v) - case *time.Time: - e.e.EncodeTime(*v) - - case *[]uint8: - e.e.EncodeStringBytes(cRAW, *v) - - default: - if !fastpathEncodeTypeSwitch(iv, e) { - // checkfastpath=true (not false), as underlying slice/map type may be fast-path - e.encodeValue(reflect.ValueOf(iv), nil, true) - } - } -} - -func (e *Encoder) encodeValue(rv reflect.Value, fn *codecFn, checkFastpath bool) { - // if a valid fn is passed, it MUST BE for the dereferenced type of rv - var sptr uintptr - var rvp reflect.Value - var rvpValid bool -TOP: - switch rv.Kind() { - case reflect.Ptr: - if rv.IsNil() { - e.e.EncodeNil() - return - } - rvpValid = true - rvp = rv - rv = rv.Elem() - if e.h.CheckCircularRef && rv.Kind() == reflect.Struct { - // TODO: Movable pointers will be an issue here. Future problem. - sptr = rv.UnsafeAddr() - break TOP - } - goto TOP - case reflect.Interface: - if rv.IsNil() { - e.e.EncodeNil() - return - } - rv = rv.Elem() - goto TOP - case reflect.Slice, reflect.Map: - if rv.IsNil() { - e.e.EncodeNil() - return - } - case reflect.Invalid, reflect.Func: - e.e.EncodeNil() - return - } - - if sptr != 0 && (&e.ci).add(sptr) { - e.errorf("circular reference found: # %d", sptr) - } - - if fn == nil { - rt := rv.Type() - // always pass checkCodecSelfer=true, in case T or ****T is passed, where *T is a Selfer - fn = e.cfer().get(rt, checkFastpath, true) - } - if fn.i.addrE { - if rvpValid { - fn.fe(e, &fn.i, rvp) - } else if rv.CanAddr() { - fn.fe(e, &fn.i, rv.Addr()) - } else { - rv2 := reflect.New(rv.Type()) - rv2.Elem().Set(rv) - fn.fe(e, &fn.i, rv2) - } - } else { - fn.fe(e, &fn.i, rv) - } - if sptr != 0 { - (&e.ci).remove(sptr) - } -} - -func (e *Encoder) marshal(bs []byte, fnerr error, asis bool, c charEncoding) { - if fnerr != nil { - panic(fnerr) - } - if bs == nil { - e.e.EncodeNil() - } else if asis { - e.asis(bs) - } else { - e.e.EncodeStringBytes(c, bs) - } -} - -func (e *Encoder) asis(v []byte) { - if e.isas { - e.as.EncodeAsis(v) - } else { - e.w.writeb(v) - } -} - -func (e *Encoder) rawBytes(vv Raw) { - v := []byte(vv) - if !e.h.Raw { - e.errorf("Raw values cannot be encoded: %v", v) - } - e.asis(v) -} - -func (e *Encoder) wrapErrstr(v interface{}, err *error) { - *err = fmt.Errorf("%s encode error: %v", e.hh.Name(), v) -} diff --git a/vendor/github.com/ugorji/go/codec/fast-path.generated.go b/vendor/github.com/ugorji/go/codec/fast-path.generated.go deleted file mode 100644 index 87f2562f6..000000000 --- a/vendor/github.com/ugorji/go/codec/fast-path.generated.go +++ /dev/null @@ -1,34522 +0,0 @@ -// +build !notfastpath - -// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// Code generated from fast-path.go.tmpl - DO NOT EDIT. - -package codec - -// Fast path functions try to create a fast path encode or decode implementation -// for common maps and slices. -// -// We define the functions and register then in this single file -// so as not to pollute the encode.go and decode.go, and create a dependency in there. -// This file can be omitted without causing a build failure. -// -// The advantage of fast paths is: -// - Many calls bypass reflection altogether -// -// Currently support -// - slice of all builtin types, -// - map of all builtin types to string or interface value -// - symmetrical maps of all builtin types (e.g. str-str, uint8-uint8) -// This should provide adequate "typical" implementations. -// -// Note that fast track decode functions must handle values for which an address cannot be obtained. -// For example: -// m2 := map[string]int{} -// p2 := []interface{}{m2} -// // decoding into p2 will bomb if fast track functions do not treat like unaddressable. -// - -import ( - "reflect" - "sort" -) - -const fastpathEnabled = true - -type fastpathT struct{} - -var fastpathTV fastpathT - -type fastpathE struct { - rtid uintptr - rt reflect.Type - encfn func(*Encoder, *codecFnInfo, reflect.Value) - decfn func(*Decoder, *codecFnInfo, reflect.Value) -} - -type fastpathA [271]fastpathE - -func (x *fastpathA) index(rtid uintptr) int { - // use binary search to grab the index (adapted from sort/search.go) - h, i, j := 0, 0, 271 // len(x) - for i < j { - h = i + (j-i)/2 - if x[h].rtid < rtid { - i = h + 1 - } else { - j = h - } - } - if i < 271 && x[i].rtid == rtid { - return i - } - return -1 -} - -type fastpathAslice []fastpathE - -func (x fastpathAslice) Len() int { return len(x) } -func (x fastpathAslice) Less(i, j int) bool { return x[i].rtid < x[j].rtid } -func (x fastpathAslice) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -var fastpathAV fastpathA - -// due to possible initialization loop error, make fastpath in an init() -func init() { - i := 0 - fn := func(v interface{}, - fe func(*Encoder, *codecFnInfo, reflect.Value), - fd func(*Decoder, *codecFnInfo, reflect.Value)) (f fastpathE) { - xrt := reflect.TypeOf(v) - xptr := rt2id(xrt) - fastpathAV[i] = fastpathE{xptr, xrt, fe, fd} - i++ - return - } - - fn([]interface{}(nil), (*Encoder).fastpathEncSliceIntfR, (*Decoder).fastpathDecSliceIntfR) - fn([]string(nil), (*Encoder).fastpathEncSliceStringR, (*Decoder).fastpathDecSliceStringR) - fn([]float32(nil), (*Encoder).fastpathEncSliceFloat32R, (*Decoder).fastpathDecSliceFloat32R) - fn([]float64(nil), (*Encoder).fastpathEncSliceFloat64R, (*Decoder).fastpathDecSliceFloat64R) - fn([]uint(nil), (*Encoder).fastpathEncSliceUintR, (*Decoder).fastpathDecSliceUintR) - fn([]uint16(nil), (*Encoder).fastpathEncSliceUint16R, (*Decoder).fastpathDecSliceUint16R) - fn([]uint32(nil), (*Encoder).fastpathEncSliceUint32R, (*Decoder).fastpathDecSliceUint32R) - fn([]uint64(nil), (*Encoder).fastpathEncSliceUint64R, (*Decoder).fastpathDecSliceUint64R) - fn([]uintptr(nil), (*Encoder).fastpathEncSliceUintptrR, (*Decoder).fastpathDecSliceUintptrR) - fn([]int(nil), (*Encoder).fastpathEncSliceIntR, (*Decoder).fastpathDecSliceIntR) - fn([]int8(nil), (*Encoder).fastpathEncSliceInt8R, (*Decoder).fastpathDecSliceInt8R) - fn([]int16(nil), (*Encoder).fastpathEncSliceInt16R, (*Decoder).fastpathDecSliceInt16R) - fn([]int32(nil), (*Encoder).fastpathEncSliceInt32R, (*Decoder).fastpathDecSliceInt32R) - fn([]int64(nil), (*Encoder).fastpathEncSliceInt64R, (*Decoder).fastpathDecSliceInt64R) - fn([]bool(nil), (*Encoder).fastpathEncSliceBoolR, (*Decoder).fastpathDecSliceBoolR) - - fn(map[interface{}]interface{}(nil), (*Encoder).fastpathEncMapIntfIntfR, (*Decoder).fastpathDecMapIntfIntfR) - fn(map[interface{}]string(nil), (*Encoder).fastpathEncMapIntfStringR, (*Decoder).fastpathDecMapIntfStringR) - fn(map[interface{}]uint(nil), (*Encoder).fastpathEncMapIntfUintR, (*Decoder).fastpathDecMapIntfUintR) - fn(map[interface{}]uint8(nil), (*Encoder).fastpathEncMapIntfUint8R, (*Decoder).fastpathDecMapIntfUint8R) - fn(map[interface{}]uint16(nil), (*Encoder).fastpathEncMapIntfUint16R, (*Decoder).fastpathDecMapIntfUint16R) - fn(map[interface{}]uint32(nil), (*Encoder).fastpathEncMapIntfUint32R, (*Decoder).fastpathDecMapIntfUint32R) - fn(map[interface{}]uint64(nil), (*Encoder).fastpathEncMapIntfUint64R, (*Decoder).fastpathDecMapIntfUint64R) - fn(map[interface{}]uintptr(nil), (*Encoder).fastpathEncMapIntfUintptrR, (*Decoder).fastpathDecMapIntfUintptrR) - fn(map[interface{}]int(nil), (*Encoder).fastpathEncMapIntfIntR, (*Decoder).fastpathDecMapIntfIntR) - fn(map[interface{}]int8(nil), (*Encoder).fastpathEncMapIntfInt8R, (*Decoder).fastpathDecMapIntfInt8R) - fn(map[interface{}]int16(nil), (*Encoder).fastpathEncMapIntfInt16R, (*Decoder).fastpathDecMapIntfInt16R) - fn(map[interface{}]int32(nil), (*Encoder).fastpathEncMapIntfInt32R, (*Decoder).fastpathDecMapIntfInt32R) - fn(map[interface{}]int64(nil), (*Encoder).fastpathEncMapIntfInt64R, (*Decoder).fastpathDecMapIntfInt64R) - fn(map[interface{}]float32(nil), (*Encoder).fastpathEncMapIntfFloat32R, (*Decoder).fastpathDecMapIntfFloat32R) - fn(map[interface{}]float64(nil), (*Encoder).fastpathEncMapIntfFloat64R, (*Decoder).fastpathDecMapIntfFloat64R) - fn(map[interface{}]bool(nil), (*Encoder).fastpathEncMapIntfBoolR, (*Decoder).fastpathDecMapIntfBoolR) - fn(map[string]interface{}(nil), (*Encoder).fastpathEncMapStringIntfR, (*Decoder).fastpathDecMapStringIntfR) - fn(map[string]string(nil), (*Encoder).fastpathEncMapStringStringR, (*Decoder).fastpathDecMapStringStringR) - fn(map[string]uint(nil), (*Encoder).fastpathEncMapStringUintR, (*Decoder).fastpathDecMapStringUintR) - fn(map[string]uint8(nil), (*Encoder).fastpathEncMapStringUint8R, (*Decoder).fastpathDecMapStringUint8R) - fn(map[string]uint16(nil), (*Encoder).fastpathEncMapStringUint16R, (*Decoder).fastpathDecMapStringUint16R) - fn(map[string]uint32(nil), (*Encoder).fastpathEncMapStringUint32R, (*Decoder).fastpathDecMapStringUint32R) - fn(map[string]uint64(nil), (*Encoder).fastpathEncMapStringUint64R, (*Decoder).fastpathDecMapStringUint64R) - fn(map[string]uintptr(nil), (*Encoder).fastpathEncMapStringUintptrR, (*Decoder).fastpathDecMapStringUintptrR) - fn(map[string]int(nil), (*Encoder).fastpathEncMapStringIntR, (*Decoder).fastpathDecMapStringIntR) - fn(map[string]int8(nil), (*Encoder).fastpathEncMapStringInt8R, (*Decoder).fastpathDecMapStringInt8R) - fn(map[string]int16(nil), (*Encoder).fastpathEncMapStringInt16R, (*Decoder).fastpathDecMapStringInt16R) - fn(map[string]int32(nil), (*Encoder).fastpathEncMapStringInt32R, (*Decoder).fastpathDecMapStringInt32R) - fn(map[string]int64(nil), (*Encoder).fastpathEncMapStringInt64R, (*Decoder).fastpathDecMapStringInt64R) - fn(map[string]float32(nil), (*Encoder).fastpathEncMapStringFloat32R, (*Decoder).fastpathDecMapStringFloat32R) - fn(map[string]float64(nil), (*Encoder).fastpathEncMapStringFloat64R, (*Decoder).fastpathDecMapStringFloat64R) - fn(map[string]bool(nil), (*Encoder).fastpathEncMapStringBoolR, (*Decoder).fastpathDecMapStringBoolR) - fn(map[float32]interface{}(nil), (*Encoder).fastpathEncMapFloat32IntfR, (*Decoder).fastpathDecMapFloat32IntfR) - fn(map[float32]string(nil), (*Encoder).fastpathEncMapFloat32StringR, (*Decoder).fastpathDecMapFloat32StringR) - fn(map[float32]uint(nil), (*Encoder).fastpathEncMapFloat32UintR, (*Decoder).fastpathDecMapFloat32UintR) - fn(map[float32]uint8(nil), (*Encoder).fastpathEncMapFloat32Uint8R, (*Decoder).fastpathDecMapFloat32Uint8R) - fn(map[float32]uint16(nil), (*Encoder).fastpathEncMapFloat32Uint16R, (*Decoder).fastpathDecMapFloat32Uint16R) - fn(map[float32]uint32(nil), (*Encoder).fastpathEncMapFloat32Uint32R, (*Decoder).fastpathDecMapFloat32Uint32R) - fn(map[float32]uint64(nil), (*Encoder).fastpathEncMapFloat32Uint64R, (*Decoder).fastpathDecMapFloat32Uint64R) - fn(map[float32]uintptr(nil), (*Encoder).fastpathEncMapFloat32UintptrR, (*Decoder).fastpathDecMapFloat32UintptrR) - fn(map[float32]int(nil), (*Encoder).fastpathEncMapFloat32IntR, (*Decoder).fastpathDecMapFloat32IntR) - fn(map[float32]int8(nil), (*Encoder).fastpathEncMapFloat32Int8R, (*Decoder).fastpathDecMapFloat32Int8R) - fn(map[float32]int16(nil), (*Encoder).fastpathEncMapFloat32Int16R, (*Decoder).fastpathDecMapFloat32Int16R) - fn(map[float32]int32(nil), (*Encoder).fastpathEncMapFloat32Int32R, (*Decoder).fastpathDecMapFloat32Int32R) - fn(map[float32]int64(nil), (*Encoder).fastpathEncMapFloat32Int64R, (*Decoder).fastpathDecMapFloat32Int64R) - fn(map[float32]float32(nil), (*Encoder).fastpathEncMapFloat32Float32R, (*Decoder).fastpathDecMapFloat32Float32R) - fn(map[float32]float64(nil), (*Encoder).fastpathEncMapFloat32Float64R, (*Decoder).fastpathDecMapFloat32Float64R) - fn(map[float32]bool(nil), (*Encoder).fastpathEncMapFloat32BoolR, (*Decoder).fastpathDecMapFloat32BoolR) - fn(map[float64]interface{}(nil), (*Encoder).fastpathEncMapFloat64IntfR, (*Decoder).fastpathDecMapFloat64IntfR) - fn(map[float64]string(nil), (*Encoder).fastpathEncMapFloat64StringR, (*Decoder).fastpathDecMapFloat64StringR) - fn(map[float64]uint(nil), (*Encoder).fastpathEncMapFloat64UintR, (*Decoder).fastpathDecMapFloat64UintR) - fn(map[float64]uint8(nil), (*Encoder).fastpathEncMapFloat64Uint8R, (*Decoder).fastpathDecMapFloat64Uint8R) - fn(map[float64]uint16(nil), (*Encoder).fastpathEncMapFloat64Uint16R, (*Decoder).fastpathDecMapFloat64Uint16R) - fn(map[float64]uint32(nil), (*Encoder).fastpathEncMapFloat64Uint32R, (*Decoder).fastpathDecMapFloat64Uint32R) - fn(map[float64]uint64(nil), (*Encoder).fastpathEncMapFloat64Uint64R, (*Decoder).fastpathDecMapFloat64Uint64R) - fn(map[float64]uintptr(nil), (*Encoder).fastpathEncMapFloat64UintptrR, (*Decoder).fastpathDecMapFloat64UintptrR) - fn(map[float64]int(nil), (*Encoder).fastpathEncMapFloat64IntR, (*Decoder).fastpathDecMapFloat64IntR) - fn(map[float64]int8(nil), (*Encoder).fastpathEncMapFloat64Int8R, (*Decoder).fastpathDecMapFloat64Int8R) - fn(map[float64]int16(nil), (*Encoder).fastpathEncMapFloat64Int16R, (*Decoder).fastpathDecMapFloat64Int16R) - fn(map[float64]int32(nil), (*Encoder).fastpathEncMapFloat64Int32R, (*Decoder).fastpathDecMapFloat64Int32R) - fn(map[float64]int64(nil), (*Encoder).fastpathEncMapFloat64Int64R, (*Decoder).fastpathDecMapFloat64Int64R) - fn(map[float64]float32(nil), (*Encoder).fastpathEncMapFloat64Float32R, (*Decoder).fastpathDecMapFloat64Float32R) - fn(map[float64]float64(nil), (*Encoder).fastpathEncMapFloat64Float64R, (*Decoder).fastpathDecMapFloat64Float64R) - fn(map[float64]bool(nil), (*Encoder).fastpathEncMapFloat64BoolR, (*Decoder).fastpathDecMapFloat64BoolR) - fn(map[uint]interface{}(nil), (*Encoder).fastpathEncMapUintIntfR, (*Decoder).fastpathDecMapUintIntfR) - fn(map[uint]string(nil), (*Encoder).fastpathEncMapUintStringR, (*Decoder).fastpathDecMapUintStringR) - fn(map[uint]uint(nil), (*Encoder).fastpathEncMapUintUintR, (*Decoder).fastpathDecMapUintUintR) - fn(map[uint]uint8(nil), (*Encoder).fastpathEncMapUintUint8R, (*Decoder).fastpathDecMapUintUint8R) - fn(map[uint]uint16(nil), (*Encoder).fastpathEncMapUintUint16R, (*Decoder).fastpathDecMapUintUint16R) - fn(map[uint]uint32(nil), (*Encoder).fastpathEncMapUintUint32R, (*Decoder).fastpathDecMapUintUint32R) - fn(map[uint]uint64(nil), (*Encoder).fastpathEncMapUintUint64R, (*Decoder).fastpathDecMapUintUint64R) - fn(map[uint]uintptr(nil), (*Encoder).fastpathEncMapUintUintptrR, (*Decoder).fastpathDecMapUintUintptrR) - fn(map[uint]int(nil), (*Encoder).fastpathEncMapUintIntR, (*Decoder).fastpathDecMapUintIntR) - fn(map[uint]int8(nil), (*Encoder).fastpathEncMapUintInt8R, (*Decoder).fastpathDecMapUintInt8R) - fn(map[uint]int16(nil), (*Encoder).fastpathEncMapUintInt16R, (*Decoder).fastpathDecMapUintInt16R) - fn(map[uint]int32(nil), (*Encoder).fastpathEncMapUintInt32R, (*Decoder).fastpathDecMapUintInt32R) - fn(map[uint]int64(nil), (*Encoder).fastpathEncMapUintInt64R, (*Decoder).fastpathDecMapUintInt64R) - fn(map[uint]float32(nil), (*Encoder).fastpathEncMapUintFloat32R, (*Decoder).fastpathDecMapUintFloat32R) - fn(map[uint]float64(nil), (*Encoder).fastpathEncMapUintFloat64R, (*Decoder).fastpathDecMapUintFloat64R) - fn(map[uint]bool(nil), (*Encoder).fastpathEncMapUintBoolR, (*Decoder).fastpathDecMapUintBoolR) - fn(map[uint8]interface{}(nil), (*Encoder).fastpathEncMapUint8IntfR, (*Decoder).fastpathDecMapUint8IntfR) - fn(map[uint8]string(nil), (*Encoder).fastpathEncMapUint8StringR, (*Decoder).fastpathDecMapUint8StringR) - fn(map[uint8]uint(nil), (*Encoder).fastpathEncMapUint8UintR, (*Decoder).fastpathDecMapUint8UintR) - fn(map[uint8]uint8(nil), (*Encoder).fastpathEncMapUint8Uint8R, (*Decoder).fastpathDecMapUint8Uint8R) - fn(map[uint8]uint16(nil), (*Encoder).fastpathEncMapUint8Uint16R, (*Decoder).fastpathDecMapUint8Uint16R) - fn(map[uint8]uint32(nil), (*Encoder).fastpathEncMapUint8Uint32R, (*Decoder).fastpathDecMapUint8Uint32R) - fn(map[uint8]uint64(nil), (*Encoder).fastpathEncMapUint8Uint64R, (*Decoder).fastpathDecMapUint8Uint64R) - fn(map[uint8]uintptr(nil), (*Encoder).fastpathEncMapUint8UintptrR, (*Decoder).fastpathDecMapUint8UintptrR) - fn(map[uint8]int(nil), (*Encoder).fastpathEncMapUint8IntR, (*Decoder).fastpathDecMapUint8IntR) - fn(map[uint8]int8(nil), (*Encoder).fastpathEncMapUint8Int8R, (*Decoder).fastpathDecMapUint8Int8R) - fn(map[uint8]int16(nil), (*Encoder).fastpathEncMapUint8Int16R, (*Decoder).fastpathDecMapUint8Int16R) - fn(map[uint8]int32(nil), (*Encoder).fastpathEncMapUint8Int32R, (*Decoder).fastpathDecMapUint8Int32R) - fn(map[uint8]int64(nil), (*Encoder).fastpathEncMapUint8Int64R, (*Decoder).fastpathDecMapUint8Int64R) - fn(map[uint8]float32(nil), (*Encoder).fastpathEncMapUint8Float32R, (*Decoder).fastpathDecMapUint8Float32R) - fn(map[uint8]float64(nil), (*Encoder).fastpathEncMapUint8Float64R, (*Decoder).fastpathDecMapUint8Float64R) - fn(map[uint8]bool(nil), (*Encoder).fastpathEncMapUint8BoolR, (*Decoder).fastpathDecMapUint8BoolR) - fn(map[uint16]interface{}(nil), (*Encoder).fastpathEncMapUint16IntfR, (*Decoder).fastpathDecMapUint16IntfR) - fn(map[uint16]string(nil), (*Encoder).fastpathEncMapUint16StringR, (*Decoder).fastpathDecMapUint16StringR) - fn(map[uint16]uint(nil), (*Encoder).fastpathEncMapUint16UintR, (*Decoder).fastpathDecMapUint16UintR) - fn(map[uint16]uint8(nil), (*Encoder).fastpathEncMapUint16Uint8R, (*Decoder).fastpathDecMapUint16Uint8R) - fn(map[uint16]uint16(nil), (*Encoder).fastpathEncMapUint16Uint16R, (*Decoder).fastpathDecMapUint16Uint16R) - fn(map[uint16]uint32(nil), (*Encoder).fastpathEncMapUint16Uint32R, (*Decoder).fastpathDecMapUint16Uint32R) - fn(map[uint16]uint64(nil), (*Encoder).fastpathEncMapUint16Uint64R, (*Decoder).fastpathDecMapUint16Uint64R) - fn(map[uint16]uintptr(nil), (*Encoder).fastpathEncMapUint16UintptrR, (*Decoder).fastpathDecMapUint16UintptrR) - fn(map[uint16]int(nil), (*Encoder).fastpathEncMapUint16IntR, (*Decoder).fastpathDecMapUint16IntR) - fn(map[uint16]int8(nil), (*Encoder).fastpathEncMapUint16Int8R, (*Decoder).fastpathDecMapUint16Int8R) - fn(map[uint16]int16(nil), (*Encoder).fastpathEncMapUint16Int16R, (*Decoder).fastpathDecMapUint16Int16R) - fn(map[uint16]int32(nil), (*Encoder).fastpathEncMapUint16Int32R, (*Decoder).fastpathDecMapUint16Int32R) - fn(map[uint16]int64(nil), (*Encoder).fastpathEncMapUint16Int64R, (*Decoder).fastpathDecMapUint16Int64R) - fn(map[uint16]float32(nil), (*Encoder).fastpathEncMapUint16Float32R, (*Decoder).fastpathDecMapUint16Float32R) - fn(map[uint16]float64(nil), (*Encoder).fastpathEncMapUint16Float64R, (*Decoder).fastpathDecMapUint16Float64R) - fn(map[uint16]bool(nil), (*Encoder).fastpathEncMapUint16BoolR, (*Decoder).fastpathDecMapUint16BoolR) - fn(map[uint32]interface{}(nil), (*Encoder).fastpathEncMapUint32IntfR, (*Decoder).fastpathDecMapUint32IntfR) - fn(map[uint32]string(nil), (*Encoder).fastpathEncMapUint32StringR, (*Decoder).fastpathDecMapUint32StringR) - fn(map[uint32]uint(nil), (*Encoder).fastpathEncMapUint32UintR, (*Decoder).fastpathDecMapUint32UintR) - fn(map[uint32]uint8(nil), (*Encoder).fastpathEncMapUint32Uint8R, (*Decoder).fastpathDecMapUint32Uint8R) - fn(map[uint32]uint16(nil), (*Encoder).fastpathEncMapUint32Uint16R, (*Decoder).fastpathDecMapUint32Uint16R) - fn(map[uint32]uint32(nil), (*Encoder).fastpathEncMapUint32Uint32R, (*Decoder).fastpathDecMapUint32Uint32R) - fn(map[uint32]uint64(nil), (*Encoder).fastpathEncMapUint32Uint64R, (*Decoder).fastpathDecMapUint32Uint64R) - fn(map[uint32]uintptr(nil), (*Encoder).fastpathEncMapUint32UintptrR, (*Decoder).fastpathDecMapUint32UintptrR) - fn(map[uint32]int(nil), (*Encoder).fastpathEncMapUint32IntR, (*Decoder).fastpathDecMapUint32IntR) - fn(map[uint32]int8(nil), (*Encoder).fastpathEncMapUint32Int8R, (*Decoder).fastpathDecMapUint32Int8R) - fn(map[uint32]int16(nil), (*Encoder).fastpathEncMapUint32Int16R, (*Decoder).fastpathDecMapUint32Int16R) - fn(map[uint32]int32(nil), (*Encoder).fastpathEncMapUint32Int32R, (*Decoder).fastpathDecMapUint32Int32R) - fn(map[uint32]int64(nil), (*Encoder).fastpathEncMapUint32Int64R, (*Decoder).fastpathDecMapUint32Int64R) - fn(map[uint32]float32(nil), (*Encoder).fastpathEncMapUint32Float32R, (*Decoder).fastpathDecMapUint32Float32R) - fn(map[uint32]float64(nil), (*Encoder).fastpathEncMapUint32Float64R, (*Decoder).fastpathDecMapUint32Float64R) - fn(map[uint32]bool(nil), (*Encoder).fastpathEncMapUint32BoolR, (*Decoder).fastpathDecMapUint32BoolR) - fn(map[uint64]interface{}(nil), (*Encoder).fastpathEncMapUint64IntfR, (*Decoder).fastpathDecMapUint64IntfR) - fn(map[uint64]string(nil), (*Encoder).fastpathEncMapUint64StringR, (*Decoder).fastpathDecMapUint64StringR) - fn(map[uint64]uint(nil), (*Encoder).fastpathEncMapUint64UintR, (*Decoder).fastpathDecMapUint64UintR) - fn(map[uint64]uint8(nil), (*Encoder).fastpathEncMapUint64Uint8R, (*Decoder).fastpathDecMapUint64Uint8R) - fn(map[uint64]uint16(nil), (*Encoder).fastpathEncMapUint64Uint16R, (*Decoder).fastpathDecMapUint64Uint16R) - fn(map[uint64]uint32(nil), (*Encoder).fastpathEncMapUint64Uint32R, (*Decoder).fastpathDecMapUint64Uint32R) - fn(map[uint64]uint64(nil), (*Encoder).fastpathEncMapUint64Uint64R, (*Decoder).fastpathDecMapUint64Uint64R) - fn(map[uint64]uintptr(nil), (*Encoder).fastpathEncMapUint64UintptrR, (*Decoder).fastpathDecMapUint64UintptrR) - fn(map[uint64]int(nil), (*Encoder).fastpathEncMapUint64IntR, (*Decoder).fastpathDecMapUint64IntR) - fn(map[uint64]int8(nil), (*Encoder).fastpathEncMapUint64Int8R, (*Decoder).fastpathDecMapUint64Int8R) - fn(map[uint64]int16(nil), (*Encoder).fastpathEncMapUint64Int16R, (*Decoder).fastpathDecMapUint64Int16R) - fn(map[uint64]int32(nil), (*Encoder).fastpathEncMapUint64Int32R, (*Decoder).fastpathDecMapUint64Int32R) - fn(map[uint64]int64(nil), (*Encoder).fastpathEncMapUint64Int64R, (*Decoder).fastpathDecMapUint64Int64R) - fn(map[uint64]float32(nil), (*Encoder).fastpathEncMapUint64Float32R, (*Decoder).fastpathDecMapUint64Float32R) - fn(map[uint64]float64(nil), (*Encoder).fastpathEncMapUint64Float64R, (*Decoder).fastpathDecMapUint64Float64R) - fn(map[uint64]bool(nil), (*Encoder).fastpathEncMapUint64BoolR, (*Decoder).fastpathDecMapUint64BoolR) - fn(map[uintptr]interface{}(nil), (*Encoder).fastpathEncMapUintptrIntfR, (*Decoder).fastpathDecMapUintptrIntfR) - fn(map[uintptr]string(nil), (*Encoder).fastpathEncMapUintptrStringR, (*Decoder).fastpathDecMapUintptrStringR) - fn(map[uintptr]uint(nil), (*Encoder).fastpathEncMapUintptrUintR, (*Decoder).fastpathDecMapUintptrUintR) - fn(map[uintptr]uint8(nil), (*Encoder).fastpathEncMapUintptrUint8R, (*Decoder).fastpathDecMapUintptrUint8R) - fn(map[uintptr]uint16(nil), (*Encoder).fastpathEncMapUintptrUint16R, (*Decoder).fastpathDecMapUintptrUint16R) - fn(map[uintptr]uint32(nil), (*Encoder).fastpathEncMapUintptrUint32R, (*Decoder).fastpathDecMapUintptrUint32R) - fn(map[uintptr]uint64(nil), (*Encoder).fastpathEncMapUintptrUint64R, (*Decoder).fastpathDecMapUintptrUint64R) - fn(map[uintptr]uintptr(nil), (*Encoder).fastpathEncMapUintptrUintptrR, (*Decoder).fastpathDecMapUintptrUintptrR) - fn(map[uintptr]int(nil), (*Encoder).fastpathEncMapUintptrIntR, (*Decoder).fastpathDecMapUintptrIntR) - fn(map[uintptr]int8(nil), (*Encoder).fastpathEncMapUintptrInt8R, (*Decoder).fastpathDecMapUintptrInt8R) - fn(map[uintptr]int16(nil), (*Encoder).fastpathEncMapUintptrInt16R, (*Decoder).fastpathDecMapUintptrInt16R) - fn(map[uintptr]int32(nil), (*Encoder).fastpathEncMapUintptrInt32R, (*Decoder).fastpathDecMapUintptrInt32R) - fn(map[uintptr]int64(nil), (*Encoder).fastpathEncMapUintptrInt64R, (*Decoder).fastpathDecMapUintptrInt64R) - fn(map[uintptr]float32(nil), (*Encoder).fastpathEncMapUintptrFloat32R, (*Decoder).fastpathDecMapUintptrFloat32R) - fn(map[uintptr]float64(nil), (*Encoder).fastpathEncMapUintptrFloat64R, (*Decoder).fastpathDecMapUintptrFloat64R) - fn(map[uintptr]bool(nil), (*Encoder).fastpathEncMapUintptrBoolR, (*Decoder).fastpathDecMapUintptrBoolR) - fn(map[int]interface{}(nil), (*Encoder).fastpathEncMapIntIntfR, (*Decoder).fastpathDecMapIntIntfR) - fn(map[int]string(nil), (*Encoder).fastpathEncMapIntStringR, (*Decoder).fastpathDecMapIntStringR) - fn(map[int]uint(nil), (*Encoder).fastpathEncMapIntUintR, (*Decoder).fastpathDecMapIntUintR) - fn(map[int]uint8(nil), (*Encoder).fastpathEncMapIntUint8R, (*Decoder).fastpathDecMapIntUint8R) - fn(map[int]uint16(nil), (*Encoder).fastpathEncMapIntUint16R, (*Decoder).fastpathDecMapIntUint16R) - fn(map[int]uint32(nil), (*Encoder).fastpathEncMapIntUint32R, (*Decoder).fastpathDecMapIntUint32R) - fn(map[int]uint64(nil), (*Encoder).fastpathEncMapIntUint64R, (*Decoder).fastpathDecMapIntUint64R) - fn(map[int]uintptr(nil), (*Encoder).fastpathEncMapIntUintptrR, (*Decoder).fastpathDecMapIntUintptrR) - fn(map[int]int(nil), (*Encoder).fastpathEncMapIntIntR, (*Decoder).fastpathDecMapIntIntR) - fn(map[int]int8(nil), (*Encoder).fastpathEncMapIntInt8R, (*Decoder).fastpathDecMapIntInt8R) - fn(map[int]int16(nil), (*Encoder).fastpathEncMapIntInt16R, (*Decoder).fastpathDecMapIntInt16R) - fn(map[int]int32(nil), (*Encoder).fastpathEncMapIntInt32R, (*Decoder).fastpathDecMapIntInt32R) - fn(map[int]int64(nil), (*Encoder).fastpathEncMapIntInt64R, (*Decoder).fastpathDecMapIntInt64R) - fn(map[int]float32(nil), (*Encoder).fastpathEncMapIntFloat32R, (*Decoder).fastpathDecMapIntFloat32R) - fn(map[int]float64(nil), (*Encoder).fastpathEncMapIntFloat64R, (*Decoder).fastpathDecMapIntFloat64R) - fn(map[int]bool(nil), (*Encoder).fastpathEncMapIntBoolR, (*Decoder).fastpathDecMapIntBoolR) - fn(map[int8]interface{}(nil), (*Encoder).fastpathEncMapInt8IntfR, (*Decoder).fastpathDecMapInt8IntfR) - fn(map[int8]string(nil), (*Encoder).fastpathEncMapInt8StringR, (*Decoder).fastpathDecMapInt8StringR) - fn(map[int8]uint(nil), (*Encoder).fastpathEncMapInt8UintR, (*Decoder).fastpathDecMapInt8UintR) - fn(map[int8]uint8(nil), (*Encoder).fastpathEncMapInt8Uint8R, (*Decoder).fastpathDecMapInt8Uint8R) - fn(map[int8]uint16(nil), (*Encoder).fastpathEncMapInt8Uint16R, (*Decoder).fastpathDecMapInt8Uint16R) - fn(map[int8]uint32(nil), (*Encoder).fastpathEncMapInt8Uint32R, (*Decoder).fastpathDecMapInt8Uint32R) - fn(map[int8]uint64(nil), (*Encoder).fastpathEncMapInt8Uint64R, (*Decoder).fastpathDecMapInt8Uint64R) - fn(map[int8]uintptr(nil), (*Encoder).fastpathEncMapInt8UintptrR, (*Decoder).fastpathDecMapInt8UintptrR) - fn(map[int8]int(nil), (*Encoder).fastpathEncMapInt8IntR, (*Decoder).fastpathDecMapInt8IntR) - fn(map[int8]int8(nil), (*Encoder).fastpathEncMapInt8Int8R, (*Decoder).fastpathDecMapInt8Int8R) - fn(map[int8]int16(nil), (*Encoder).fastpathEncMapInt8Int16R, (*Decoder).fastpathDecMapInt8Int16R) - fn(map[int8]int32(nil), (*Encoder).fastpathEncMapInt8Int32R, (*Decoder).fastpathDecMapInt8Int32R) - fn(map[int8]int64(nil), (*Encoder).fastpathEncMapInt8Int64R, (*Decoder).fastpathDecMapInt8Int64R) - fn(map[int8]float32(nil), (*Encoder).fastpathEncMapInt8Float32R, (*Decoder).fastpathDecMapInt8Float32R) - fn(map[int8]float64(nil), (*Encoder).fastpathEncMapInt8Float64R, (*Decoder).fastpathDecMapInt8Float64R) - fn(map[int8]bool(nil), (*Encoder).fastpathEncMapInt8BoolR, (*Decoder).fastpathDecMapInt8BoolR) - fn(map[int16]interface{}(nil), (*Encoder).fastpathEncMapInt16IntfR, (*Decoder).fastpathDecMapInt16IntfR) - fn(map[int16]string(nil), (*Encoder).fastpathEncMapInt16StringR, (*Decoder).fastpathDecMapInt16StringR) - fn(map[int16]uint(nil), (*Encoder).fastpathEncMapInt16UintR, (*Decoder).fastpathDecMapInt16UintR) - fn(map[int16]uint8(nil), (*Encoder).fastpathEncMapInt16Uint8R, (*Decoder).fastpathDecMapInt16Uint8R) - fn(map[int16]uint16(nil), (*Encoder).fastpathEncMapInt16Uint16R, (*Decoder).fastpathDecMapInt16Uint16R) - fn(map[int16]uint32(nil), (*Encoder).fastpathEncMapInt16Uint32R, (*Decoder).fastpathDecMapInt16Uint32R) - fn(map[int16]uint64(nil), (*Encoder).fastpathEncMapInt16Uint64R, (*Decoder).fastpathDecMapInt16Uint64R) - fn(map[int16]uintptr(nil), (*Encoder).fastpathEncMapInt16UintptrR, (*Decoder).fastpathDecMapInt16UintptrR) - fn(map[int16]int(nil), (*Encoder).fastpathEncMapInt16IntR, (*Decoder).fastpathDecMapInt16IntR) - fn(map[int16]int8(nil), (*Encoder).fastpathEncMapInt16Int8R, (*Decoder).fastpathDecMapInt16Int8R) - fn(map[int16]int16(nil), (*Encoder).fastpathEncMapInt16Int16R, (*Decoder).fastpathDecMapInt16Int16R) - fn(map[int16]int32(nil), (*Encoder).fastpathEncMapInt16Int32R, (*Decoder).fastpathDecMapInt16Int32R) - fn(map[int16]int64(nil), (*Encoder).fastpathEncMapInt16Int64R, (*Decoder).fastpathDecMapInt16Int64R) - fn(map[int16]float32(nil), (*Encoder).fastpathEncMapInt16Float32R, (*Decoder).fastpathDecMapInt16Float32R) - fn(map[int16]float64(nil), (*Encoder).fastpathEncMapInt16Float64R, (*Decoder).fastpathDecMapInt16Float64R) - fn(map[int16]bool(nil), (*Encoder).fastpathEncMapInt16BoolR, (*Decoder).fastpathDecMapInt16BoolR) - fn(map[int32]interface{}(nil), (*Encoder).fastpathEncMapInt32IntfR, (*Decoder).fastpathDecMapInt32IntfR) - fn(map[int32]string(nil), (*Encoder).fastpathEncMapInt32StringR, (*Decoder).fastpathDecMapInt32StringR) - fn(map[int32]uint(nil), (*Encoder).fastpathEncMapInt32UintR, (*Decoder).fastpathDecMapInt32UintR) - fn(map[int32]uint8(nil), (*Encoder).fastpathEncMapInt32Uint8R, (*Decoder).fastpathDecMapInt32Uint8R) - fn(map[int32]uint16(nil), (*Encoder).fastpathEncMapInt32Uint16R, (*Decoder).fastpathDecMapInt32Uint16R) - fn(map[int32]uint32(nil), (*Encoder).fastpathEncMapInt32Uint32R, (*Decoder).fastpathDecMapInt32Uint32R) - fn(map[int32]uint64(nil), (*Encoder).fastpathEncMapInt32Uint64R, (*Decoder).fastpathDecMapInt32Uint64R) - fn(map[int32]uintptr(nil), (*Encoder).fastpathEncMapInt32UintptrR, (*Decoder).fastpathDecMapInt32UintptrR) - fn(map[int32]int(nil), (*Encoder).fastpathEncMapInt32IntR, (*Decoder).fastpathDecMapInt32IntR) - fn(map[int32]int8(nil), (*Encoder).fastpathEncMapInt32Int8R, (*Decoder).fastpathDecMapInt32Int8R) - fn(map[int32]int16(nil), (*Encoder).fastpathEncMapInt32Int16R, (*Decoder).fastpathDecMapInt32Int16R) - fn(map[int32]int32(nil), (*Encoder).fastpathEncMapInt32Int32R, (*Decoder).fastpathDecMapInt32Int32R) - fn(map[int32]int64(nil), (*Encoder).fastpathEncMapInt32Int64R, (*Decoder).fastpathDecMapInt32Int64R) - fn(map[int32]float32(nil), (*Encoder).fastpathEncMapInt32Float32R, (*Decoder).fastpathDecMapInt32Float32R) - fn(map[int32]float64(nil), (*Encoder).fastpathEncMapInt32Float64R, (*Decoder).fastpathDecMapInt32Float64R) - fn(map[int32]bool(nil), (*Encoder).fastpathEncMapInt32BoolR, (*Decoder).fastpathDecMapInt32BoolR) - fn(map[int64]interface{}(nil), (*Encoder).fastpathEncMapInt64IntfR, (*Decoder).fastpathDecMapInt64IntfR) - fn(map[int64]string(nil), (*Encoder).fastpathEncMapInt64StringR, (*Decoder).fastpathDecMapInt64StringR) - fn(map[int64]uint(nil), (*Encoder).fastpathEncMapInt64UintR, (*Decoder).fastpathDecMapInt64UintR) - fn(map[int64]uint8(nil), (*Encoder).fastpathEncMapInt64Uint8R, (*Decoder).fastpathDecMapInt64Uint8R) - fn(map[int64]uint16(nil), (*Encoder).fastpathEncMapInt64Uint16R, (*Decoder).fastpathDecMapInt64Uint16R) - fn(map[int64]uint32(nil), (*Encoder).fastpathEncMapInt64Uint32R, (*Decoder).fastpathDecMapInt64Uint32R) - fn(map[int64]uint64(nil), (*Encoder).fastpathEncMapInt64Uint64R, (*Decoder).fastpathDecMapInt64Uint64R) - fn(map[int64]uintptr(nil), (*Encoder).fastpathEncMapInt64UintptrR, (*Decoder).fastpathDecMapInt64UintptrR) - fn(map[int64]int(nil), (*Encoder).fastpathEncMapInt64IntR, (*Decoder).fastpathDecMapInt64IntR) - fn(map[int64]int8(nil), (*Encoder).fastpathEncMapInt64Int8R, (*Decoder).fastpathDecMapInt64Int8R) - fn(map[int64]int16(nil), (*Encoder).fastpathEncMapInt64Int16R, (*Decoder).fastpathDecMapInt64Int16R) - fn(map[int64]int32(nil), (*Encoder).fastpathEncMapInt64Int32R, (*Decoder).fastpathDecMapInt64Int32R) - fn(map[int64]int64(nil), (*Encoder).fastpathEncMapInt64Int64R, (*Decoder).fastpathDecMapInt64Int64R) - fn(map[int64]float32(nil), (*Encoder).fastpathEncMapInt64Float32R, (*Decoder).fastpathDecMapInt64Float32R) - fn(map[int64]float64(nil), (*Encoder).fastpathEncMapInt64Float64R, (*Decoder).fastpathDecMapInt64Float64R) - fn(map[int64]bool(nil), (*Encoder).fastpathEncMapInt64BoolR, (*Decoder).fastpathDecMapInt64BoolR) - fn(map[bool]interface{}(nil), (*Encoder).fastpathEncMapBoolIntfR, (*Decoder).fastpathDecMapBoolIntfR) - fn(map[bool]string(nil), (*Encoder).fastpathEncMapBoolStringR, (*Decoder).fastpathDecMapBoolStringR) - fn(map[bool]uint(nil), (*Encoder).fastpathEncMapBoolUintR, (*Decoder).fastpathDecMapBoolUintR) - fn(map[bool]uint8(nil), (*Encoder).fastpathEncMapBoolUint8R, (*Decoder).fastpathDecMapBoolUint8R) - fn(map[bool]uint16(nil), (*Encoder).fastpathEncMapBoolUint16R, (*Decoder).fastpathDecMapBoolUint16R) - fn(map[bool]uint32(nil), (*Encoder).fastpathEncMapBoolUint32R, (*Decoder).fastpathDecMapBoolUint32R) - fn(map[bool]uint64(nil), (*Encoder).fastpathEncMapBoolUint64R, (*Decoder).fastpathDecMapBoolUint64R) - fn(map[bool]uintptr(nil), (*Encoder).fastpathEncMapBoolUintptrR, (*Decoder).fastpathDecMapBoolUintptrR) - fn(map[bool]int(nil), (*Encoder).fastpathEncMapBoolIntR, (*Decoder).fastpathDecMapBoolIntR) - fn(map[bool]int8(nil), (*Encoder).fastpathEncMapBoolInt8R, (*Decoder).fastpathDecMapBoolInt8R) - fn(map[bool]int16(nil), (*Encoder).fastpathEncMapBoolInt16R, (*Decoder).fastpathDecMapBoolInt16R) - fn(map[bool]int32(nil), (*Encoder).fastpathEncMapBoolInt32R, (*Decoder).fastpathDecMapBoolInt32R) - fn(map[bool]int64(nil), (*Encoder).fastpathEncMapBoolInt64R, (*Decoder).fastpathDecMapBoolInt64R) - fn(map[bool]float32(nil), (*Encoder).fastpathEncMapBoolFloat32R, (*Decoder).fastpathDecMapBoolFloat32R) - fn(map[bool]float64(nil), (*Encoder).fastpathEncMapBoolFloat64R, (*Decoder).fastpathDecMapBoolFloat64R) - fn(map[bool]bool(nil), (*Encoder).fastpathEncMapBoolBoolR, (*Decoder).fastpathDecMapBoolBoolR) - - sort.Sort(fastpathAslice(fastpathAV[:])) -} - -// -- encode - -// -- -- fast path type switch -func fastpathEncodeTypeSwitch(iv interface{}, e *Encoder) bool { - switch v := iv.(type) { - - case []interface{}: - fastpathTV.EncSliceIntfV(v, e) - case *[]interface{}: - fastpathTV.EncSliceIntfV(*v, e) - case []string: - fastpathTV.EncSliceStringV(v, e) - case *[]string: - fastpathTV.EncSliceStringV(*v, e) - case []float32: - fastpathTV.EncSliceFloat32V(v, e) - case *[]float32: - fastpathTV.EncSliceFloat32V(*v, e) - case []float64: - fastpathTV.EncSliceFloat64V(v, e) - case *[]float64: - fastpathTV.EncSliceFloat64V(*v, e) - case []uint: - fastpathTV.EncSliceUintV(v, e) - case *[]uint: - fastpathTV.EncSliceUintV(*v, e) - case []uint16: - fastpathTV.EncSliceUint16V(v, e) - case *[]uint16: - fastpathTV.EncSliceUint16V(*v, e) - case []uint32: - fastpathTV.EncSliceUint32V(v, e) - case *[]uint32: - fastpathTV.EncSliceUint32V(*v, e) - case []uint64: - fastpathTV.EncSliceUint64V(v, e) - case *[]uint64: - fastpathTV.EncSliceUint64V(*v, e) - case []uintptr: - fastpathTV.EncSliceUintptrV(v, e) - case *[]uintptr: - fastpathTV.EncSliceUintptrV(*v, e) - case []int: - fastpathTV.EncSliceIntV(v, e) - case *[]int: - fastpathTV.EncSliceIntV(*v, e) - case []int8: - fastpathTV.EncSliceInt8V(v, e) - case *[]int8: - fastpathTV.EncSliceInt8V(*v, e) - case []int16: - fastpathTV.EncSliceInt16V(v, e) - case *[]int16: - fastpathTV.EncSliceInt16V(*v, e) - case []int32: - fastpathTV.EncSliceInt32V(v, e) - case *[]int32: - fastpathTV.EncSliceInt32V(*v, e) - case []int64: - fastpathTV.EncSliceInt64V(v, e) - case *[]int64: - fastpathTV.EncSliceInt64V(*v, e) - case []bool: - fastpathTV.EncSliceBoolV(v, e) - case *[]bool: - fastpathTV.EncSliceBoolV(*v, e) - - case map[interface{}]interface{}: - fastpathTV.EncMapIntfIntfV(v, e) - case *map[interface{}]interface{}: - fastpathTV.EncMapIntfIntfV(*v, e) - case map[interface{}]string: - fastpathTV.EncMapIntfStringV(v, e) - case *map[interface{}]string: - fastpathTV.EncMapIntfStringV(*v, e) - case map[interface{}]uint: - fastpathTV.EncMapIntfUintV(v, e) - case *map[interface{}]uint: - fastpathTV.EncMapIntfUintV(*v, e) - case map[interface{}]uint8: - fastpathTV.EncMapIntfUint8V(v, e) - case *map[interface{}]uint8: - fastpathTV.EncMapIntfUint8V(*v, e) - case map[interface{}]uint16: - fastpathTV.EncMapIntfUint16V(v, e) - case *map[interface{}]uint16: - fastpathTV.EncMapIntfUint16V(*v, e) - case map[interface{}]uint32: - fastpathTV.EncMapIntfUint32V(v, e) - case *map[interface{}]uint32: - fastpathTV.EncMapIntfUint32V(*v, e) - case map[interface{}]uint64: - fastpathTV.EncMapIntfUint64V(v, e) - case *map[interface{}]uint64: - fastpathTV.EncMapIntfUint64V(*v, e) - case map[interface{}]uintptr: - fastpathTV.EncMapIntfUintptrV(v, e) - case *map[interface{}]uintptr: - fastpathTV.EncMapIntfUintptrV(*v, e) - case map[interface{}]int: - fastpathTV.EncMapIntfIntV(v, e) - case *map[interface{}]int: - fastpathTV.EncMapIntfIntV(*v, e) - case map[interface{}]int8: - fastpathTV.EncMapIntfInt8V(v, e) - case *map[interface{}]int8: - fastpathTV.EncMapIntfInt8V(*v, e) - case map[interface{}]int16: - fastpathTV.EncMapIntfInt16V(v, e) - case *map[interface{}]int16: - fastpathTV.EncMapIntfInt16V(*v, e) - case map[interface{}]int32: - fastpathTV.EncMapIntfInt32V(v, e) - case *map[interface{}]int32: - fastpathTV.EncMapIntfInt32V(*v, e) - case map[interface{}]int64: - fastpathTV.EncMapIntfInt64V(v, e) - case *map[interface{}]int64: - fastpathTV.EncMapIntfInt64V(*v, e) - case map[interface{}]float32: - fastpathTV.EncMapIntfFloat32V(v, e) - case *map[interface{}]float32: - fastpathTV.EncMapIntfFloat32V(*v, e) - case map[interface{}]float64: - fastpathTV.EncMapIntfFloat64V(v, e) - case *map[interface{}]float64: - fastpathTV.EncMapIntfFloat64V(*v, e) - case map[interface{}]bool: - fastpathTV.EncMapIntfBoolV(v, e) - case *map[interface{}]bool: - fastpathTV.EncMapIntfBoolV(*v, e) - case map[string]interface{}: - fastpathTV.EncMapStringIntfV(v, e) - case *map[string]interface{}: - fastpathTV.EncMapStringIntfV(*v, e) - case map[string]string: - fastpathTV.EncMapStringStringV(v, e) - case *map[string]string: - fastpathTV.EncMapStringStringV(*v, e) - case map[string]uint: - fastpathTV.EncMapStringUintV(v, e) - case *map[string]uint: - fastpathTV.EncMapStringUintV(*v, e) - case map[string]uint8: - fastpathTV.EncMapStringUint8V(v, e) - case *map[string]uint8: - fastpathTV.EncMapStringUint8V(*v, e) - case map[string]uint16: - fastpathTV.EncMapStringUint16V(v, e) - case *map[string]uint16: - fastpathTV.EncMapStringUint16V(*v, e) - case map[string]uint32: - fastpathTV.EncMapStringUint32V(v, e) - case *map[string]uint32: - fastpathTV.EncMapStringUint32V(*v, e) - case map[string]uint64: - fastpathTV.EncMapStringUint64V(v, e) - case *map[string]uint64: - fastpathTV.EncMapStringUint64V(*v, e) - case map[string]uintptr: - fastpathTV.EncMapStringUintptrV(v, e) - case *map[string]uintptr: - fastpathTV.EncMapStringUintptrV(*v, e) - case map[string]int: - fastpathTV.EncMapStringIntV(v, e) - case *map[string]int: - fastpathTV.EncMapStringIntV(*v, e) - case map[string]int8: - fastpathTV.EncMapStringInt8V(v, e) - case *map[string]int8: - fastpathTV.EncMapStringInt8V(*v, e) - case map[string]int16: - fastpathTV.EncMapStringInt16V(v, e) - case *map[string]int16: - fastpathTV.EncMapStringInt16V(*v, e) - case map[string]int32: - fastpathTV.EncMapStringInt32V(v, e) - case *map[string]int32: - fastpathTV.EncMapStringInt32V(*v, e) - case map[string]int64: - fastpathTV.EncMapStringInt64V(v, e) - case *map[string]int64: - fastpathTV.EncMapStringInt64V(*v, e) - case map[string]float32: - fastpathTV.EncMapStringFloat32V(v, e) - case *map[string]float32: - fastpathTV.EncMapStringFloat32V(*v, e) - case map[string]float64: - fastpathTV.EncMapStringFloat64V(v, e) - case *map[string]float64: - fastpathTV.EncMapStringFloat64V(*v, e) - case map[string]bool: - fastpathTV.EncMapStringBoolV(v, e) - case *map[string]bool: - fastpathTV.EncMapStringBoolV(*v, e) - case map[float32]interface{}: - fastpathTV.EncMapFloat32IntfV(v, e) - case *map[float32]interface{}: - fastpathTV.EncMapFloat32IntfV(*v, e) - case map[float32]string: - fastpathTV.EncMapFloat32StringV(v, e) - case *map[float32]string: - fastpathTV.EncMapFloat32StringV(*v, e) - case map[float32]uint: - fastpathTV.EncMapFloat32UintV(v, e) - case *map[float32]uint: - fastpathTV.EncMapFloat32UintV(*v, e) - case map[float32]uint8: - fastpathTV.EncMapFloat32Uint8V(v, e) - case *map[float32]uint8: - fastpathTV.EncMapFloat32Uint8V(*v, e) - case map[float32]uint16: - fastpathTV.EncMapFloat32Uint16V(v, e) - case *map[float32]uint16: - fastpathTV.EncMapFloat32Uint16V(*v, e) - case map[float32]uint32: - fastpathTV.EncMapFloat32Uint32V(v, e) - case *map[float32]uint32: - fastpathTV.EncMapFloat32Uint32V(*v, e) - case map[float32]uint64: - fastpathTV.EncMapFloat32Uint64V(v, e) - case *map[float32]uint64: - fastpathTV.EncMapFloat32Uint64V(*v, e) - case map[float32]uintptr: - fastpathTV.EncMapFloat32UintptrV(v, e) - case *map[float32]uintptr: - fastpathTV.EncMapFloat32UintptrV(*v, e) - case map[float32]int: - fastpathTV.EncMapFloat32IntV(v, e) - case *map[float32]int: - fastpathTV.EncMapFloat32IntV(*v, e) - case map[float32]int8: - fastpathTV.EncMapFloat32Int8V(v, e) - case *map[float32]int8: - fastpathTV.EncMapFloat32Int8V(*v, e) - case map[float32]int16: - fastpathTV.EncMapFloat32Int16V(v, e) - case *map[float32]int16: - fastpathTV.EncMapFloat32Int16V(*v, e) - case map[float32]int32: - fastpathTV.EncMapFloat32Int32V(v, e) - case *map[float32]int32: - fastpathTV.EncMapFloat32Int32V(*v, e) - case map[float32]int64: - fastpathTV.EncMapFloat32Int64V(v, e) - case *map[float32]int64: - fastpathTV.EncMapFloat32Int64V(*v, e) - case map[float32]float32: - fastpathTV.EncMapFloat32Float32V(v, e) - case *map[float32]float32: - fastpathTV.EncMapFloat32Float32V(*v, e) - case map[float32]float64: - fastpathTV.EncMapFloat32Float64V(v, e) - case *map[float32]float64: - fastpathTV.EncMapFloat32Float64V(*v, e) - case map[float32]bool: - fastpathTV.EncMapFloat32BoolV(v, e) - case *map[float32]bool: - fastpathTV.EncMapFloat32BoolV(*v, e) - case map[float64]interface{}: - fastpathTV.EncMapFloat64IntfV(v, e) - case *map[float64]interface{}: - fastpathTV.EncMapFloat64IntfV(*v, e) - case map[float64]string: - fastpathTV.EncMapFloat64StringV(v, e) - case *map[float64]string: - fastpathTV.EncMapFloat64StringV(*v, e) - case map[float64]uint: - fastpathTV.EncMapFloat64UintV(v, e) - case *map[float64]uint: - fastpathTV.EncMapFloat64UintV(*v, e) - case map[float64]uint8: - fastpathTV.EncMapFloat64Uint8V(v, e) - case *map[float64]uint8: - fastpathTV.EncMapFloat64Uint8V(*v, e) - case map[float64]uint16: - fastpathTV.EncMapFloat64Uint16V(v, e) - case *map[float64]uint16: - fastpathTV.EncMapFloat64Uint16V(*v, e) - case map[float64]uint32: - fastpathTV.EncMapFloat64Uint32V(v, e) - case *map[float64]uint32: - fastpathTV.EncMapFloat64Uint32V(*v, e) - case map[float64]uint64: - fastpathTV.EncMapFloat64Uint64V(v, e) - case *map[float64]uint64: - fastpathTV.EncMapFloat64Uint64V(*v, e) - case map[float64]uintptr: - fastpathTV.EncMapFloat64UintptrV(v, e) - case *map[float64]uintptr: - fastpathTV.EncMapFloat64UintptrV(*v, e) - case map[float64]int: - fastpathTV.EncMapFloat64IntV(v, e) - case *map[float64]int: - fastpathTV.EncMapFloat64IntV(*v, e) - case map[float64]int8: - fastpathTV.EncMapFloat64Int8V(v, e) - case *map[float64]int8: - fastpathTV.EncMapFloat64Int8V(*v, e) - case map[float64]int16: - fastpathTV.EncMapFloat64Int16V(v, e) - case *map[float64]int16: - fastpathTV.EncMapFloat64Int16V(*v, e) - case map[float64]int32: - fastpathTV.EncMapFloat64Int32V(v, e) - case *map[float64]int32: - fastpathTV.EncMapFloat64Int32V(*v, e) - case map[float64]int64: - fastpathTV.EncMapFloat64Int64V(v, e) - case *map[float64]int64: - fastpathTV.EncMapFloat64Int64V(*v, e) - case map[float64]float32: - fastpathTV.EncMapFloat64Float32V(v, e) - case *map[float64]float32: - fastpathTV.EncMapFloat64Float32V(*v, e) - case map[float64]float64: - fastpathTV.EncMapFloat64Float64V(v, e) - case *map[float64]float64: - fastpathTV.EncMapFloat64Float64V(*v, e) - case map[float64]bool: - fastpathTV.EncMapFloat64BoolV(v, e) - case *map[float64]bool: - fastpathTV.EncMapFloat64BoolV(*v, e) - case map[uint]interface{}: - fastpathTV.EncMapUintIntfV(v, e) - case *map[uint]interface{}: - fastpathTV.EncMapUintIntfV(*v, e) - case map[uint]string: - fastpathTV.EncMapUintStringV(v, e) - case *map[uint]string: - fastpathTV.EncMapUintStringV(*v, e) - case map[uint]uint: - fastpathTV.EncMapUintUintV(v, e) - case *map[uint]uint: - fastpathTV.EncMapUintUintV(*v, e) - case map[uint]uint8: - fastpathTV.EncMapUintUint8V(v, e) - case *map[uint]uint8: - fastpathTV.EncMapUintUint8V(*v, e) - case map[uint]uint16: - fastpathTV.EncMapUintUint16V(v, e) - case *map[uint]uint16: - fastpathTV.EncMapUintUint16V(*v, e) - case map[uint]uint32: - fastpathTV.EncMapUintUint32V(v, e) - case *map[uint]uint32: - fastpathTV.EncMapUintUint32V(*v, e) - case map[uint]uint64: - fastpathTV.EncMapUintUint64V(v, e) - case *map[uint]uint64: - fastpathTV.EncMapUintUint64V(*v, e) - case map[uint]uintptr: - fastpathTV.EncMapUintUintptrV(v, e) - case *map[uint]uintptr: - fastpathTV.EncMapUintUintptrV(*v, e) - case map[uint]int: - fastpathTV.EncMapUintIntV(v, e) - case *map[uint]int: - fastpathTV.EncMapUintIntV(*v, e) - case map[uint]int8: - fastpathTV.EncMapUintInt8V(v, e) - case *map[uint]int8: - fastpathTV.EncMapUintInt8V(*v, e) - case map[uint]int16: - fastpathTV.EncMapUintInt16V(v, e) - case *map[uint]int16: - fastpathTV.EncMapUintInt16V(*v, e) - case map[uint]int32: - fastpathTV.EncMapUintInt32V(v, e) - case *map[uint]int32: - fastpathTV.EncMapUintInt32V(*v, e) - case map[uint]int64: - fastpathTV.EncMapUintInt64V(v, e) - case *map[uint]int64: - fastpathTV.EncMapUintInt64V(*v, e) - case map[uint]float32: - fastpathTV.EncMapUintFloat32V(v, e) - case *map[uint]float32: - fastpathTV.EncMapUintFloat32V(*v, e) - case map[uint]float64: - fastpathTV.EncMapUintFloat64V(v, e) - case *map[uint]float64: - fastpathTV.EncMapUintFloat64V(*v, e) - case map[uint]bool: - fastpathTV.EncMapUintBoolV(v, e) - case *map[uint]bool: - fastpathTV.EncMapUintBoolV(*v, e) - case map[uint8]interface{}: - fastpathTV.EncMapUint8IntfV(v, e) - case *map[uint8]interface{}: - fastpathTV.EncMapUint8IntfV(*v, e) - case map[uint8]string: - fastpathTV.EncMapUint8StringV(v, e) - case *map[uint8]string: - fastpathTV.EncMapUint8StringV(*v, e) - case map[uint8]uint: - fastpathTV.EncMapUint8UintV(v, e) - case *map[uint8]uint: - fastpathTV.EncMapUint8UintV(*v, e) - case map[uint8]uint8: - fastpathTV.EncMapUint8Uint8V(v, e) - case *map[uint8]uint8: - fastpathTV.EncMapUint8Uint8V(*v, e) - case map[uint8]uint16: - fastpathTV.EncMapUint8Uint16V(v, e) - case *map[uint8]uint16: - fastpathTV.EncMapUint8Uint16V(*v, e) - case map[uint8]uint32: - fastpathTV.EncMapUint8Uint32V(v, e) - case *map[uint8]uint32: - fastpathTV.EncMapUint8Uint32V(*v, e) - case map[uint8]uint64: - fastpathTV.EncMapUint8Uint64V(v, e) - case *map[uint8]uint64: - fastpathTV.EncMapUint8Uint64V(*v, e) - case map[uint8]uintptr: - fastpathTV.EncMapUint8UintptrV(v, e) - case *map[uint8]uintptr: - fastpathTV.EncMapUint8UintptrV(*v, e) - case map[uint8]int: - fastpathTV.EncMapUint8IntV(v, e) - case *map[uint8]int: - fastpathTV.EncMapUint8IntV(*v, e) - case map[uint8]int8: - fastpathTV.EncMapUint8Int8V(v, e) - case *map[uint8]int8: - fastpathTV.EncMapUint8Int8V(*v, e) - case map[uint8]int16: - fastpathTV.EncMapUint8Int16V(v, e) - case *map[uint8]int16: - fastpathTV.EncMapUint8Int16V(*v, e) - case map[uint8]int32: - fastpathTV.EncMapUint8Int32V(v, e) - case *map[uint8]int32: - fastpathTV.EncMapUint8Int32V(*v, e) - case map[uint8]int64: - fastpathTV.EncMapUint8Int64V(v, e) - case *map[uint8]int64: - fastpathTV.EncMapUint8Int64V(*v, e) - case map[uint8]float32: - fastpathTV.EncMapUint8Float32V(v, e) - case *map[uint8]float32: - fastpathTV.EncMapUint8Float32V(*v, e) - case map[uint8]float64: - fastpathTV.EncMapUint8Float64V(v, e) - case *map[uint8]float64: - fastpathTV.EncMapUint8Float64V(*v, e) - case map[uint8]bool: - fastpathTV.EncMapUint8BoolV(v, e) - case *map[uint8]bool: - fastpathTV.EncMapUint8BoolV(*v, e) - case map[uint16]interface{}: - fastpathTV.EncMapUint16IntfV(v, e) - case *map[uint16]interface{}: - fastpathTV.EncMapUint16IntfV(*v, e) - case map[uint16]string: - fastpathTV.EncMapUint16StringV(v, e) - case *map[uint16]string: - fastpathTV.EncMapUint16StringV(*v, e) - case map[uint16]uint: - fastpathTV.EncMapUint16UintV(v, e) - case *map[uint16]uint: - fastpathTV.EncMapUint16UintV(*v, e) - case map[uint16]uint8: - fastpathTV.EncMapUint16Uint8V(v, e) - case *map[uint16]uint8: - fastpathTV.EncMapUint16Uint8V(*v, e) - case map[uint16]uint16: - fastpathTV.EncMapUint16Uint16V(v, e) - case *map[uint16]uint16: - fastpathTV.EncMapUint16Uint16V(*v, e) - case map[uint16]uint32: - fastpathTV.EncMapUint16Uint32V(v, e) - case *map[uint16]uint32: - fastpathTV.EncMapUint16Uint32V(*v, e) - case map[uint16]uint64: - fastpathTV.EncMapUint16Uint64V(v, e) - case *map[uint16]uint64: - fastpathTV.EncMapUint16Uint64V(*v, e) - case map[uint16]uintptr: - fastpathTV.EncMapUint16UintptrV(v, e) - case *map[uint16]uintptr: - fastpathTV.EncMapUint16UintptrV(*v, e) - case map[uint16]int: - fastpathTV.EncMapUint16IntV(v, e) - case *map[uint16]int: - fastpathTV.EncMapUint16IntV(*v, e) - case map[uint16]int8: - fastpathTV.EncMapUint16Int8V(v, e) - case *map[uint16]int8: - fastpathTV.EncMapUint16Int8V(*v, e) - case map[uint16]int16: - fastpathTV.EncMapUint16Int16V(v, e) - case *map[uint16]int16: - fastpathTV.EncMapUint16Int16V(*v, e) - case map[uint16]int32: - fastpathTV.EncMapUint16Int32V(v, e) - case *map[uint16]int32: - fastpathTV.EncMapUint16Int32V(*v, e) - case map[uint16]int64: - fastpathTV.EncMapUint16Int64V(v, e) - case *map[uint16]int64: - fastpathTV.EncMapUint16Int64V(*v, e) - case map[uint16]float32: - fastpathTV.EncMapUint16Float32V(v, e) - case *map[uint16]float32: - fastpathTV.EncMapUint16Float32V(*v, e) - case map[uint16]float64: - fastpathTV.EncMapUint16Float64V(v, e) - case *map[uint16]float64: - fastpathTV.EncMapUint16Float64V(*v, e) - case map[uint16]bool: - fastpathTV.EncMapUint16BoolV(v, e) - case *map[uint16]bool: - fastpathTV.EncMapUint16BoolV(*v, e) - case map[uint32]interface{}: - fastpathTV.EncMapUint32IntfV(v, e) - case *map[uint32]interface{}: - fastpathTV.EncMapUint32IntfV(*v, e) - case map[uint32]string: - fastpathTV.EncMapUint32StringV(v, e) - case *map[uint32]string: - fastpathTV.EncMapUint32StringV(*v, e) - case map[uint32]uint: - fastpathTV.EncMapUint32UintV(v, e) - case *map[uint32]uint: - fastpathTV.EncMapUint32UintV(*v, e) - case map[uint32]uint8: - fastpathTV.EncMapUint32Uint8V(v, e) - case *map[uint32]uint8: - fastpathTV.EncMapUint32Uint8V(*v, e) - case map[uint32]uint16: - fastpathTV.EncMapUint32Uint16V(v, e) - case *map[uint32]uint16: - fastpathTV.EncMapUint32Uint16V(*v, e) - case map[uint32]uint32: - fastpathTV.EncMapUint32Uint32V(v, e) - case *map[uint32]uint32: - fastpathTV.EncMapUint32Uint32V(*v, e) - case map[uint32]uint64: - fastpathTV.EncMapUint32Uint64V(v, e) - case *map[uint32]uint64: - fastpathTV.EncMapUint32Uint64V(*v, e) - case map[uint32]uintptr: - fastpathTV.EncMapUint32UintptrV(v, e) - case *map[uint32]uintptr: - fastpathTV.EncMapUint32UintptrV(*v, e) - case map[uint32]int: - fastpathTV.EncMapUint32IntV(v, e) - case *map[uint32]int: - fastpathTV.EncMapUint32IntV(*v, e) - case map[uint32]int8: - fastpathTV.EncMapUint32Int8V(v, e) - case *map[uint32]int8: - fastpathTV.EncMapUint32Int8V(*v, e) - case map[uint32]int16: - fastpathTV.EncMapUint32Int16V(v, e) - case *map[uint32]int16: - fastpathTV.EncMapUint32Int16V(*v, e) - case map[uint32]int32: - fastpathTV.EncMapUint32Int32V(v, e) - case *map[uint32]int32: - fastpathTV.EncMapUint32Int32V(*v, e) - case map[uint32]int64: - fastpathTV.EncMapUint32Int64V(v, e) - case *map[uint32]int64: - fastpathTV.EncMapUint32Int64V(*v, e) - case map[uint32]float32: - fastpathTV.EncMapUint32Float32V(v, e) - case *map[uint32]float32: - fastpathTV.EncMapUint32Float32V(*v, e) - case map[uint32]float64: - fastpathTV.EncMapUint32Float64V(v, e) - case *map[uint32]float64: - fastpathTV.EncMapUint32Float64V(*v, e) - case map[uint32]bool: - fastpathTV.EncMapUint32BoolV(v, e) - case *map[uint32]bool: - fastpathTV.EncMapUint32BoolV(*v, e) - case map[uint64]interface{}: - fastpathTV.EncMapUint64IntfV(v, e) - case *map[uint64]interface{}: - fastpathTV.EncMapUint64IntfV(*v, e) - case map[uint64]string: - fastpathTV.EncMapUint64StringV(v, e) - case *map[uint64]string: - fastpathTV.EncMapUint64StringV(*v, e) - case map[uint64]uint: - fastpathTV.EncMapUint64UintV(v, e) - case *map[uint64]uint: - fastpathTV.EncMapUint64UintV(*v, e) - case map[uint64]uint8: - fastpathTV.EncMapUint64Uint8V(v, e) - case *map[uint64]uint8: - fastpathTV.EncMapUint64Uint8V(*v, e) - case map[uint64]uint16: - fastpathTV.EncMapUint64Uint16V(v, e) - case *map[uint64]uint16: - fastpathTV.EncMapUint64Uint16V(*v, e) - case map[uint64]uint32: - fastpathTV.EncMapUint64Uint32V(v, e) - case *map[uint64]uint32: - fastpathTV.EncMapUint64Uint32V(*v, e) - case map[uint64]uint64: - fastpathTV.EncMapUint64Uint64V(v, e) - case *map[uint64]uint64: - fastpathTV.EncMapUint64Uint64V(*v, e) - case map[uint64]uintptr: - fastpathTV.EncMapUint64UintptrV(v, e) - case *map[uint64]uintptr: - fastpathTV.EncMapUint64UintptrV(*v, e) - case map[uint64]int: - fastpathTV.EncMapUint64IntV(v, e) - case *map[uint64]int: - fastpathTV.EncMapUint64IntV(*v, e) - case map[uint64]int8: - fastpathTV.EncMapUint64Int8V(v, e) - case *map[uint64]int8: - fastpathTV.EncMapUint64Int8V(*v, e) - case map[uint64]int16: - fastpathTV.EncMapUint64Int16V(v, e) - case *map[uint64]int16: - fastpathTV.EncMapUint64Int16V(*v, e) - case map[uint64]int32: - fastpathTV.EncMapUint64Int32V(v, e) - case *map[uint64]int32: - fastpathTV.EncMapUint64Int32V(*v, e) - case map[uint64]int64: - fastpathTV.EncMapUint64Int64V(v, e) - case *map[uint64]int64: - fastpathTV.EncMapUint64Int64V(*v, e) - case map[uint64]float32: - fastpathTV.EncMapUint64Float32V(v, e) - case *map[uint64]float32: - fastpathTV.EncMapUint64Float32V(*v, e) - case map[uint64]float64: - fastpathTV.EncMapUint64Float64V(v, e) - case *map[uint64]float64: - fastpathTV.EncMapUint64Float64V(*v, e) - case map[uint64]bool: - fastpathTV.EncMapUint64BoolV(v, e) - case *map[uint64]bool: - fastpathTV.EncMapUint64BoolV(*v, e) - case map[uintptr]interface{}: - fastpathTV.EncMapUintptrIntfV(v, e) - case *map[uintptr]interface{}: - fastpathTV.EncMapUintptrIntfV(*v, e) - case map[uintptr]string: - fastpathTV.EncMapUintptrStringV(v, e) - case *map[uintptr]string: - fastpathTV.EncMapUintptrStringV(*v, e) - case map[uintptr]uint: - fastpathTV.EncMapUintptrUintV(v, e) - case *map[uintptr]uint: - fastpathTV.EncMapUintptrUintV(*v, e) - case map[uintptr]uint8: - fastpathTV.EncMapUintptrUint8V(v, e) - case *map[uintptr]uint8: - fastpathTV.EncMapUintptrUint8V(*v, e) - case map[uintptr]uint16: - fastpathTV.EncMapUintptrUint16V(v, e) - case *map[uintptr]uint16: - fastpathTV.EncMapUintptrUint16V(*v, e) - case map[uintptr]uint32: - fastpathTV.EncMapUintptrUint32V(v, e) - case *map[uintptr]uint32: - fastpathTV.EncMapUintptrUint32V(*v, e) - case map[uintptr]uint64: - fastpathTV.EncMapUintptrUint64V(v, e) - case *map[uintptr]uint64: - fastpathTV.EncMapUintptrUint64V(*v, e) - case map[uintptr]uintptr: - fastpathTV.EncMapUintptrUintptrV(v, e) - case *map[uintptr]uintptr: - fastpathTV.EncMapUintptrUintptrV(*v, e) - case map[uintptr]int: - fastpathTV.EncMapUintptrIntV(v, e) - case *map[uintptr]int: - fastpathTV.EncMapUintptrIntV(*v, e) - case map[uintptr]int8: - fastpathTV.EncMapUintptrInt8V(v, e) - case *map[uintptr]int8: - fastpathTV.EncMapUintptrInt8V(*v, e) - case map[uintptr]int16: - fastpathTV.EncMapUintptrInt16V(v, e) - case *map[uintptr]int16: - fastpathTV.EncMapUintptrInt16V(*v, e) - case map[uintptr]int32: - fastpathTV.EncMapUintptrInt32V(v, e) - case *map[uintptr]int32: - fastpathTV.EncMapUintptrInt32V(*v, e) - case map[uintptr]int64: - fastpathTV.EncMapUintptrInt64V(v, e) - case *map[uintptr]int64: - fastpathTV.EncMapUintptrInt64V(*v, e) - case map[uintptr]float32: - fastpathTV.EncMapUintptrFloat32V(v, e) - case *map[uintptr]float32: - fastpathTV.EncMapUintptrFloat32V(*v, e) - case map[uintptr]float64: - fastpathTV.EncMapUintptrFloat64V(v, e) - case *map[uintptr]float64: - fastpathTV.EncMapUintptrFloat64V(*v, e) - case map[uintptr]bool: - fastpathTV.EncMapUintptrBoolV(v, e) - case *map[uintptr]bool: - fastpathTV.EncMapUintptrBoolV(*v, e) - case map[int]interface{}: - fastpathTV.EncMapIntIntfV(v, e) - case *map[int]interface{}: - fastpathTV.EncMapIntIntfV(*v, e) - case map[int]string: - fastpathTV.EncMapIntStringV(v, e) - case *map[int]string: - fastpathTV.EncMapIntStringV(*v, e) - case map[int]uint: - fastpathTV.EncMapIntUintV(v, e) - case *map[int]uint: - fastpathTV.EncMapIntUintV(*v, e) - case map[int]uint8: - fastpathTV.EncMapIntUint8V(v, e) - case *map[int]uint8: - fastpathTV.EncMapIntUint8V(*v, e) - case map[int]uint16: - fastpathTV.EncMapIntUint16V(v, e) - case *map[int]uint16: - fastpathTV.EncMapIntUint16V(*v, e) - case map[int]uint32: - fastpathTV.EncMapIntUint32V(v, e) - case *map[int]uint32: - fastpathTV.EncMapIntUint32V(*v, e) - case map[int]uint64: - fastpathTV.EncMapIntUint64V(v, e) - case *map[int]uint64: - fastpathTV.EncMapIntUint64V(*v, e) - case map[int]uintptr: - fastpathTV.EncMapIntUintptrV(v, e) - case *map[int]uintptr: - fastpathTV.EncMapIntUintptrV(*v, e) - case map[int]int: - fastpathTV.EncMapIntIntV(v, e) - case *map[int]int: - fastpathTV.EncMapIntIntV(*v, e) - case map[int]int8: - fastpathTV.EncMapIntInt8V(v, e) - case *map[int]int8: - fastpathTV.EncMapIntInt8V(*v, e) - case map[int]int16: - fastpathTV.EncMapIntInt16V(v, e) - case *map[int]int16: - fastpathTV.EncMapIntInt16V(*v, e) - case map[int]int32: - fastpathTV.EncMapIntInt32V(v, e) - case *map[int]int32: - fastpathTV.EncMapIntInt32V(*v, e) - case map[int]int64: - fastpathTV.EncMapIntInt64V(v, e) - case *map[int]int64: - fastpathTV.EncMapIntInt64V(*v, e) - case map[int]float32: - fastpathTV.EncMapIntFloat32V(v, e) - case *map[int]float32: - fastpathTV.EncMapIntFloat32V(*v, e) - case map[int]float64: - fastpathTV.EncMapIntFloat64V(v, e) - case *map[int]float64: - fastpathTV.EncMapIntFloat64V(*v, e) - case map[int]bool: - fastpathTV.EncMapIntBoolV(v, e) - case *map[int]bool: - fastpathTV.EncMapIntBoolV(*v, e) - case map[int8]interface{}: - fastpathTV.EncMapInt8IntfV(v, e) - case *map[int8]interface{}: - fastpathTV.EncMapInt8IntfV(*v, e) - case map[int8]string: - fastpathTV.EncMapInt8StringV(v, e) - case *map[int8]string: - fastpathTV.EncMapInt8StringV(*v, e) - case map[int8]uint: - fastpathTV.EncMapInt8UintV(v, e) - case *map[int8]uint: - fastpathTV.EncMapInt8UintV(*v, e) - case map[int8]uint8: - fastpathTV.EncMapInt8Uint8V(v, e) - case *map[int8]uint8: - fastpathTV.EncMapInt8Uint8V(*v, e) - case map[int8]uint16: - fastpathTV.EncMapInt8Uint16V(v, e) - case *map[int8]uint16: - fastpathTV.EncMapInt8Uint16V(*v, e) - case map[int8]uint32: - fastpathTV.EncMapInt8Uint32V(v, e) - case *map[int8]uint32: - fastpathTV.EncMapInt8Uint32V(*v, e) - case map[int8]uint64: - fastpathTV.EncMapInt8Uint64V(v, e) - case *map[int8]uint64: - fastpathTV.EncMapInt8Uint64V(*v, e) - case map[int8]uintptr: - fastpathTV.EncMapInt8UintptrV(v, e) - case *map[int8]uintptr: - fastpathTV.EncMapInt8UintptrV(*v, e) - case map[int8]int: - fastpathTV.EncMapInt8IntV(v, e) - case *map[int8]int: - fastpathTV.EncMapInt8IntV(*v, e) - case map[int8]int8: - fastpathTV.EncMapInt8Int8V(v, e) - case *map[int8]int8: - fastpathTV.EncMapInt8Int8V(*v, e) - case map[int8]int16: - fastpathTV.EncMapInt8Int16V(v, e) - case *map[int8]int16: - fastpathTV.EncMapInt8Int16V(*v, e) - case map[int8]int32: - fastpathTV.EncMapInt8Int32V(v, e) - case *map[int8]int32: - fastpathTV.EncMapInt8Int32V(*v, e) - case map[int8]int64: - fastpathTV.EncMapInt8Int64V(v, e) - case *map[int8]int64: - fastpathTV.EncMapInt8Int64V(*v, e) - case map[int8]float32: - fastpathTV.EncMapInt8Float32V(v, e) - case *map[int8]float32: - fastpathTV.EncMapInt8Float32V(*v, e) - case map[int8]float64: - fastpathTV.EncMapInt8Float64V(v, e) - case *map[int8]float64: - fastpathTV.EncMapInt8Float64V(*v, e) - case map[int8]bool: - fastpathTV.EncMapInt8BoolV(v, e) - case *map[int8]bool: - fastpathTV.EncMapInt8BoolV(*v, e) - case map[int16]interface{}: - fastpathTV.EncMapInt16IntfV(v, e) - case *map[int16]interface{}: - fastpathTV.EncMapInt16IntfV(*v, e) - case map[int16]string: - fastpathTV.EncMapInt16StringV(v, e) - case *map[int16]string: - fastpathTV.EncMapInt16StringV(*v, e) - case map[int16]uint: - fastpathTV.EncMapInt16UintV(v, e) - case *map[int16]uint: - fastpathTV.EncMapInt16UintV(*v, e) - case map[int16]uint8: - fastpathTV.EncMapInt16Uint8V(v, e) - case *map[int16]uint8: - fastpathTV.EncMapInt16Uint8V(*v, e) - case map[int16]uint16: - fastpathTV.EncMapInt16Uint16V(v, e) - case *map[int16]uint16: - fastpathTV.EncMapInt16Uint16V(*v, e) - case map[int16]uint32: - fastpathTV.EncMapInt16Uint32V(v, e) - case *map[int16]uint32: - fastpathTV.EncMapInt16Uint32V(*v, e) - case map[int16]uint64: - fastpathTV.EncMapInt16Uint64V(v, e) - case *map[int16]uint64: - fastpathTV.EncMapInt16Uint64V(*v, e) - case map[int16]uintptr: - fastpathTV.EncMapInt16UintptrV(v, e) - case *map[int16]uintptr: - fastpathTV.EncMapInt16UintptrV(*v, e) - case map[int16]int: - fastpathTV.EncMapInt16IntV(v, e) - case *map[int16]int: - fastpathTV.EncMapInt16IntV(*v, e) - case map[int16]int8: - fastpathTV.EncMapInt16Int8V(v, e) - case *map[int16]int8: - fastpathTV.EncMapInt16Int8V(*v, e) - case map[int16]int16: - fastpathTV.EncMapInt16Int16V(v, e) - case *map[int16]int16: - fastpathTV.EncMapInt16Int16V(*v, e) - case map[int16]int32: - fastpathTV.EncMapInt16Int32V(v, e) - case *map[int16]int32: - fastpathTV.EncMapInt16Int32V(*v, e) - case map[int16]int64: - fastpathTV.EncMapInt16Int64V(v, e) - case *map[int16]int64: - fastpathTV.EncMapInt16Int64V(*v, e) - case map[int16]float32: - fastpathTV.EncMapInt16Float32V(v, e) - case *map[int16]float32: - fastpathTV.EncMapInt16Float32V(*v, e) - case map[int16]float64: - fastpathTV.EncMapInt16Float64V(v, e) - case *map[int16]float64: - fastpathTV.EncMapInt16Float64V(*v, e) - case map[int16]bool: - fastpathTV.EncMapInt16BoolV(v, e) - case *map[int16]bool: - fastpathTV.EncMapInt16BoolV(*v, e) - case map[int32]interface{}: - fastpathTV.EncMapInt32IntfV(v, e) - case *map[int32]interface{}: - fastpathTV.EncMapInt32IntfV(*v, e) - case map[int32]string: - fastpathTV.EncMapInt32StringV(v, e) - case *map[int32]string: - fastpathTV.EncMapInt32StringV(*v, e) - case map[int32]uint: - fastpathTV.EncMapInt32UintV(v, e) - case *map[int32]uint: - fastpathTV.EncMapInt32UintV(*v, e) - case map[int32]uint8: - fastpathTV.EncMapInt32Uint8V(v, e) - case *map[int32]uint8: - fastpathTV.EncMapInt32Uint8V(*v, e) - case map[int32]uint16: - fastpathTV.EncMapInt32Uint16V(v, e) - case *map[int32]uint16: - fastpathTV.EncMapInt32Uint16V(*v, e) - case map[int32]uint32: - fastpathTV.EncMapInt32Uint32V(v, e) - case *map[int32]uint32: - fastpathTV.EncMapInt32Uint32V(*v, e) - case map[int32]uint64: - fastpathTV.EncMapInt32Uint64V(v, e) - case *map[int32]uint64: - fastpathTV.EncMapInt32Uint64V(*v, e) - case map[int32]uintptr: - fastpathTV.EncMapInt32UintptrV(v, e) - case *map[int32]uintptr: - fastpathTV.EncMapInt32UintptrV(*v, e) - case map[int32]int: - fastpathTV.EncMapInt32IntV(v, e) - case *map[int32]int: - fastpathTV.EncMapInt32IntV(*v, e) - case map[int32]int8: - fastpathTV.EncMapInt32Int8V(v, e) - case *map[int32]int8: - fastpathTV.EncMapInt32Int8V(*v, e) - case map[int32]int16: - fastpathTV.EncMapInt32Int16V(v, e) - case *map[int32]int16: - fastpathTV.EncMapInt32Int16V(*v, e) - case map[int32]int32: - fastpathTV.EncMapInt32Int32V(v, e) - case *map[int32]int32: - fastpathTV.EncMapInt32Int32V(*v, e) - case map[int32]int64: - fastpathTV.EncMapInt32Int64V(v, e) - case *map[int32]int64: - fastpathTV.EncMapInt32Int64V(*v, e) - case map[int32]float32: - fastpathTV.EncMapInt32Float32V(v, e) - case *map[int32]float32: - fastpathTV.EncMapInt32Float32V(*v, e) - case map[int32]float64: - fastpathTV.EncMapInt32Float64V(v, e) - case *map[int32]float64: - fastpathTV.EncMapInt32Float64V(*v, e) - case map[int32]bool: - fastpathTV.EncMapInt32BoolV(v, e) - case *map[int32]bool: - fastpathTV.EncMapInt32BoolV(*v, e) - case map[int64]interface{}: - fastpathTV.EncMapInt64IntfV(v, e) - case *map[int64]interface{}: - fastpathTV.EncMapInt64IntfV(*v, e) - case map[int64]string: - fastpathTV.EncMapInt64StringV(v, e) - case *map[int64]string: - fastpathTV.EncMapInt64StringV(*v, e) - case map[int64]uint: - fastpathTV.EncMapInt64UintV(v, e) - case *map[int64]uint: - fastpathTV.EncMapInt64UintV(*v, e) - case map[int64]uint8: - fastpathTV.EncMapInt64Uint8V(v, e) - case *map[int64]uint8: - fastpathTV.EncMapInt64Uint8V(*v, e) - case map[int64]uint16: - fastpathTV.EncMapInt64Uint16V(v, e) - case *map[int64]uint16: - fastpathTV.EncMapInt64Uint16V(*v, e) - case map[int64]uint32: - fastpathTV.EncMapInt64Uint32V(v, e) - case *map[int64]uint32: - fastpathTV.EncMapInt64Uint32V(*v, e) - case map[int64]uint64: - fastpathTV.EncMapInt64Uint64V(v, e) - case *map[int64]uint64: - fastpathTV.EncMapInt64Uint64V(*v, e) - case map[int64]uintptr: - fastpathTV.EncMapInt64UintptrV(v, e) - case *map[int64]uintptr: - fastpathTV.EncMapInt64UintptrV(*v, e) - case map[int64]int: - fastpathTV.EncMapInt64IntV(v, e) - case *map[int64]int: - fastpathTV.EncMapInt64IntV(*v, e) - case map[int64]int8: - fastpathTV.EncMapInt64Int8V(v, e) - case *map[int64]int8: - fastpathTV.EncMapInt64Int8V(*v, e) - case map[int64]int16: - fastpathTV.EncMapInt64Int16V(v, e) - case *map[int64]int16: - fastpathTV.EncMapInt64Int16V(*v, e) - case map[int64]int32: - fastpathTV.EncMapInt64Int32V(v, e) - case *map[int64]int32: - fastpathTV.EncMapInt64Int32V(*v, e) - case map[int64]int64: - fastpathTV.EncMapInt64Int64V(v, e) - case *map[int64]int64: - fastpathTV.EncMapInt64Int64V(*v, e) - case map[int64]float32: - fastpathTV.EncMapInt64Float32V(v, e) - case *map[int64]float32: - fastpathTV.EncMapInt64Float32V(*v, e) - case map[int64]float64: - fastpathTV.EncMapInt64Float64V(v, e) - case *map[int64]float64: - fastpathTV.EncMapInt64Float64V(*v, e) - case map[int64]bool: - fastpathTV.EncMapInt64BoolV(v, e) - case *map[int64]bool: - fastpathTV.EncMapInt64BoolV(*v, e) - case map[bool]interface{}: - fastpathTV.EncMapBoolIntfV(v, e) - case *map[bool]interface{}: - fastpathTV.EncMapBoolIntfV(*v, e) - case map[bool]string: - fastpathTV.EncMapBoolStringV(v, e) - case *map[bool]string: - fastpathTV.EncMapBoolStringV(*v, e) - case map[bool]uint: - fastpathTV.EncMapBoolUintV(v, e) - case *map[bool]uint: - fastpathTV.EncMapBoolUintV(*v, e) - case map[bool]uint8: - fastpathTV.EncMapBoolUint8V(v, e) - case *map[bool]uint8: - fastpathTV.EncMapBoolUint8V(*v, e) - case map[bool]uint16: - fastpathTV.EncMapBoolUint16V(v, e) - case *map[bool]uint16: - fastpathTV.EncMapBoolUint16V(*v, e) - case map[bool]uint32: - fastpathTV.EncMapBoolUint32V(v, e) - case *map[bool]uint32: - fastpathTV.EncMapBoolUint32V(*v, e) - case map[bool]uint64: - fastpathTV.EncMapBoolUint64V(v, e) - case *map[bool]uint64: - fastpathTV.EncMapBoolUint64V(*v, e) - case map[bool]uintptr: - fastpathTV.EncMapBoolUintptrV(v, e) - case *map[bool]uintptr: - fastpathTV.EncMapBoolUintptrV(*v, e) - case map[bool]int: - fastpathTV.EncMapBoolIntV(v, e) - case *map[bool]int: - fastpathTV.EncMapBoolIntV(*v, e) - case map[bool]int8: - fastpathTV.EncMapBoolInt8V(v, e) - case *map[bool]int8: - fastpathTV.EncMapBoolInt8V(*v, e) - case map[bool]int16: - fastpathTV.EncMapBoolInt16V(v, e) - case *map[bool]int16: - fastpathTV.EncMapBoolInt16V(*v, e) - case map[bool]int32: - fastpathTV.EncMapBoolInt32V(v, e) - case *map[bool]int32: - fastpathTV.EncMapBoolInt32V(*v, e) - case map[bool]int64: - fastpathTV.EncMapBoolInt64V(v, e) - case *map[bool]int64: - fastpathTV.EncMapBoolInt64V(*v, e) - case map[bool]float32: - fastpathTV.EncMapBoolFloat32V(v, e) - case *map[bool]float32: - fastpathTV.EncMapBoolFloat32V(*v, e) - case map[bool]float64: - fastpathTV.EncMapBoolFloat64V(v, e) - case *map[bool]float64: - fastpathTV.EncMapBoolFloat64V(*v, e) - case map[bool]bool: - fastpathTV.EncMapBoolBoolV(v, e) - case *map[bool]bool: - fastpathTV.EncMapBoolBoolV(*v, e) - - default: - _ = v // workaround https://github.com/golang/go/issues/12927 seen in go1.4 - return false - } - return true -} - -// -- -- fast path functions - -func (e *Encoder) fastpathEncSliceIntfR(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceIntfV(rv2i(rv).([]interface{}), e) - } else { - fastpathTV.EncSliceIntfV(rv2i(rv).([]interface{}), e) - } -} -func (_ fastpathT) EncSliceIntfV(v []interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - if esep { - for _, v2 := range v { - ee.WriteArrayElem() - e.encode(v2) - } - } else { - for _, v2 := range v { - e.encode(v2) - } - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceIntfV(v []interface{}, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf("mapBySlice requires even slice length, but got %v", len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - if esep { - for j, v2 := range v { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } else { - for _, v2 := range v { - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceStringR(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceStringV(rv2i(rv).([]string), e) - } else { - fastpathTV.EncSliceStringV(rv2i(rv).([]string), e) - } -} -func (_ fastpathT) EncSliceStringV(v []string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - if esep { - for _, v2 := range v { - ee.WriteArrayElem() - ee.EncodeString(cUTF8, v2) - } - } else { - for _, v2 := range v { - ee.EncodeString(cUTF8, v2) - } - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceStringV(v []string, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf("mapBySlice requires even slice length, but got %v", len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - if esep { - for j, v2 := range v { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - ee.EncodeString(cUTF8, v2) - } - } else { - for _, v2 := range v { - ee.EncodeString(cUTF8, v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceFloat32R(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceFloat32V(rv2i(rv).([]float32), e) - } else { - fastpathTV.EncSliceFloat32V(rv2i(rv).([]float32), e) - } -} -func (_ fastpathT) EncSliceFloat32V(v []float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - if esep { - for _, v2 := range v { - ee.WriteArrayElem() - ee.EncodeFloat32(v2) - } - } else { - for _, v2 := range v { - ee.EncodeFloat32(v2) - } - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceFloat32V(v []float32, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf("mapBySlice requires even slice length, but got %v", len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - if esep { - for j, v2 := range v { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - ee.EncodeFloat32(v2) - } - } else { - for _, v2 := range v { - ee.EncodeFloat32(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceFloat64R(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceFloat64V(rv2i(rv).([]float64), e) - } else { - fastpathTV.EncSliceFloat64V(rv2i(rv).([]float64), e) - } -} -func (_ fastpathT) EncSliceFloat64V(v []float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - if esep { - for _, v2 := range v { - ee.WriteArrayElem() - ee.EncodeFloat64(v2) - } - } else { - for _, v2 := range v { - ee.EncodeFloat64(v2) - } - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceFloat64V(v []float64, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf("mapBySlice requires even slice length, but got %v", len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - if esep { - for j, v2 := range v { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - ee.EncodeFloat64(v2) - } - } else { - for _, v2 := range v { - ee.EncodeFloat64(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceUintR(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceUintV(rv2i(rv).([]uint), e) - } else { - fastpathTV.EncSliceUintV(rv2i(rv).([]uint), e) - } -} -func (_ fastpathT) EncSliceUintV(v []uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - if esep { - for _, v2 := range v { - ee.WriteArrayElem() - ee.EncodeUint(uint64(v2)) - } - } else { - for _, v2 := range v { - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceUintV(v []uint, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf("mapBySlice requires even slice length, but got %v", len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - if esep { - for j, v2 := range v { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } else { - for _, v2 := range v { - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceUint8R(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceUint8V(rv2i(rv).([]uint8), e) - } else { - fastpathTV.EncSliceUint8V(rv2i(rv).([]uint8), e) - } -} -func (_ fastpathT) EncSliceUint8V(v []uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - if esep { - for _, v2 := range v { - ee.WriteArrayElem() - ee.EncodeUint(uint64(v2)) - } - } else { - for _, v2 := range v { - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceUint8V(v []uint8, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf("mapBySlice requires even slice length, but got %v", len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - if esep { - for j, v2 := range v { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } else { - for _, v2 := range v { - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceUint16R(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceUint16V(rv2i(rv).([]uint16), e) - } else { - fastpathTV.EncSliceUint16V(rv2i(rv).([]uint16), e) - } -} -func (_ fastpathT) EncSliceUint16V(v []uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - if esep { - for _, v2 := range v { - ee.WriteArrayElem() - ee.EncodeUint(uint64(v2)) - } - } else { - for _, v2 := range v { - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceUint16V(v []uint16, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf("mapBySlice requires even slice length, but got %v", len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - if esep { - for j, v2 := range v { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } else { - for _, v2 := range v { - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceUint32R(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceUint32V(rv2i(rv).([]uint32), e) - } else { - fastpathTV.EncSliceUint32V(rv2i(rv).([]uint32), e) - } -} -func (_ fastpathT) EncSliceUint32V(v []uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - if esep { - for _, v2 := range v { - ee.WriteArrayElem() - ee.EncodeUint(uint64(v2)) - } - } else { - for _, v2 := range v { - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceUint32V(v []uint32, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf("mapBySlice requires even slice length, but got %v", len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - if esep { - for j, v2 := range v { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } else { - for _, v2 := range v { - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceUint64R(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceUint64V(rv2i(rv).([]uint64), e) - } else { - fastpathTV.EncSliceUint64V(rv2i(rv).([]uint64), e) - } -} -func (_ fastpathT) EncSliceUint64V(v []uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - if esep { - for _, v2 := range v { - ee.WriteArrayElem() - ee.EncodeUint(uint64(v2)) - } - } else { - for _, v2 := range v { - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceUint64V(v []uint64, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf("mapBySlice requires even slice length, but got %v", len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - if esep { - for j, v2 := range v { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - ee.EncodeUint(uint64(v2)) - } - } else { - for _, v2 := range v { - ee.EncodeUint(uint64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceUintptrR(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceUintptrV(rv2i(rv).([]uintptr), e) - } else { - fastpathTV.EncSliceUintptrV(rv2i(rv).([]uintptr), e) - } -} -func (_ fastpathT) EncSliceUintptrV(v []uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - if esep { - for _, v2 := range v { - ee.WriteArrayElem() - e.encode(v2) - } - } else { - for _, v2 := range v { - e.encode(v2) - } - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceUintptrV(v []uintptr, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf("mapBySlice requires even slice length, but got %v", len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - if esep { - for j, v2 := range v { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - e.encode(v2) - } - } else { - for _, v2 := range v { - e.encode(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceIntR(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceIntV(rv2i(rv).([]int), e) - } else { - fastpathTV.EncSliceIntV(rv2i(rv).([]int), e) - } -} -func (_ fastpathT) EncSliceIntV(v []int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - if esep { - for _, v2 := range v { - ee.WriteArrayElem() - ee.EncodeInt(int64(v2)) - } - } else { - for _, v2 := range v { - ee.EncodeInt(int64(v2)) - } - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceIntV(v []int, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf("mapBySlice requires even slice length, but got %v", len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - if esep { - for j, v2 := range v { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } else { - for _, v2 := range v { - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceInt8R(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceInt8V(rv2i(rv).([]int8), e) - } else { - fastpathTV.EncSliceInt8V(rv2i(rv).([]int8), e) - } -} -func (_ fastpathT) EncSliceInt8V(v []int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - if esep { - for _, v2 := range v { - ee.WriteArrayElem() - ee.EncodeInt(int64(v2)) - } - } else { - for _, v2 := range v { - ee.EncodeInt(int64(v2)) - } - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceInt8V(v []int8, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf("mapBySlice requires even slice length, but got %v", len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - if esep { - for j, v2 := range v { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } else { - for _, v2 := range v { - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceInt16R(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceInt16V(rv2i(rv).([]int16), e) - } else { - fastpathTV.EncSliceInt16V(rv2i(rv).([]int16), e) - } -} -func (_ fastpathT) EncSliceInt16V(v []int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - if esep { - for _, v2 := range v { - ee.WriteArrayElem() - ee.EncodeInt(int64(v2)) - } - } else { - for _, v2 := range v { - ee.EncodeInt(int64(v2)) - } - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceInt16V(v []int16, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf("mapBySlice requires even slice length, but got %v", len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - if esep { - for j, v2 := range v { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } else { - for _, v2 := range v { - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceInt32R(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceInt32V(rv2i(rv).([]int32), e) - } else { - fastpathTV.EncSliceInt32V(rv2i(rv).([]int32), e) - } -} -func (_ fastpathT) EncSliceInt32V(v []int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - if esep { - for _, v2 := range v { - ee.WriteArrayElem() - ee.EncodeInt(int64(v2)) - } - } else { - for _, v2 := range v { - ee.EncodeInt(int64(v2)) - } - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceInt32V(v []int32, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf("mapBySlice requires even slice length, but got %v", len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - if esep { - for j, v2 := range v { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } else { - for _, v2 := range v { - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceInt64R(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceInt64V(rv2i(rv).([]int64), e) - } else { - fastpathTV.EncSliceInt64V(rv2i(rv).([]int64), e) - } -} -func (_ fastpathT) EncSliceInt64V(v []int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - if esep { - for _, v2 := range v { - ee.WriteArrayElem() - ee.EncodeInt(int64(v2)) - } - } else { - for _, v2 := range v { - ee.EncodeInt(int64(v2)) - } - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceInt64V(v []int64, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf("mapBySlice requires even slice length, but got %v", len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - if esep { - for j, v2 := range v { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - ee.EncodeInt(int64(v2)) - } - } else { - for _, v2 := range v { - ee.EncodeInt(int64(v2)) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncSliceBoolR(f *codecFnInfo, rv reflect.Value) { - if f.ti.mbs { - fastpathTV.EncAsMapSliceBoolV(rv2i(rv).([]bool), e) - } else { - fastpathTV.EncSliceBoolV(rv2i(rv).([]bool), e) - } -} -func (_ fastpathT) EncSliceBoolV(v []bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteArrayStart(len(v)) - if esep { - for _, v2 := range v { - ee.WriteArrayElem() - ee.EncodeBool(v2) - } - } else { - for _, v2 := range v { - ee.EncodeBool(v2) - } - } - ee.WriteArrayEnd() -} -func (_ fastpathT) EncAsMapSliceBoolV(v []bool, e *Encoder) { - ee, esep := e.e, e.hh.hasElemSeparators() - if len(v)%2 == 1 { - e.errorf("mapBySlice requires even slice length, but got %v", len(v)) - return - } - ee.WriteMapStart(len(v) / 2) - if esep { - for j, v2 := range v { - if j%2 == 0 { - ee.WriteMapElemKey() - } else { - ee.WriteMapElemValue() - } - ee.EncodeBool(v2) - } - } else { - for _, v2 := range v { - ee.EncodeBool(v2) - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfIntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfIntfV(rv2i(rv).(map[interface{}]interface{}), e) -} -func (_ fastpathT) EncMapIntfIntfV(v map[interface{}]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l int - var vp *bytesI - for k2, _ := range v { - l = len(mksv) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - if esep { - for j := range v2 { - ee.WriteMapElemKey() - e.asis(v2[j].v) - ee.WriteMapElemValue() - e.encode(v[v2[j].i]) - } - } else { - for j := range v2 { - e.asis(v2[j].v) - e.encode(v[v2[j].i]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - e.encode(k2) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfStringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfStringV(rv2i(rv).(map[interface{}]string), e) -} -func (_ fastpathT) EncMapIntfStringV(v map[interface{}]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l int - var vp *bytesI - for k2, _ := range v { - l = len(mksv) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - if esep { - for j := range v2 { - ee.WriteMapElemKey() - e.asis(v2[j].v) - ee.WriteMapElemValue() - e.encode(v[v2[j].i]) - } - } else { - for j := range v2 { - e.asis(v2[j].v) - e.encode(v[v2[j].i]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v2) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeString(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfUintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfUintV(rv2i(rv).(map[interface{}]uint), e) -} -func (_ fastpathT) EncMapIntfUintV(v map[interface{}]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l int - var vp *bytesI - for k2, _ := range v { - l = len(mksv) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - if esep { - for j := range v2 { - ee.WriteMapElemKey() - e.asis(v2[j].v) - ee.WriteMapElemValue() - e.encode(v[v2[j].i]) - } - } else { - for j := range v2 { - e.asis(v2[j].v) - e.encode(v[v2[j].i]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfUint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfUint8V(rv2i(rv).(map[interface{}]uint8), e) -} -func (_ fastpathT) EncMapIntfUint8V(v map[interface{}]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l int - var vp *bytesI - for k2, _ := range v { - l = len(mksv) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - if esep { - for j := range v2 { - ee.WriteMapElemKey() - e.asis(v2[j].v) - ee.WriteMapElemValue() - e.encode(v[v2[j].i]) - } - } else { - for j := range v2 { - e.asis(v2[j].v) - e.encode(v[v2[j].i]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfUint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfUint16V(rv2i(rv).(map[interface{}]uint16), e) -} -func (_ fastpathT) EncMapIntfUint16V(v map[interface{}]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l int - var vp *bytesI - for k2, _ := range v { - l = len(mksv) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - if esep { - for j := range v2 { - ee.WriteMapElemKey() - e.asis(v2[j].v) - ee.WriteMapElemValue() - e.encode(v[v2[j].i]) - } - } else { - for j := range v2 { - e.asis(v2[j].v) - e.encode(v[v2[j].i]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfUint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfUint32V(rv2i(rv).(map[interface{}]uint32), e) -} -func (_ fastpathT) EncMapIntfUint32V(v map[interface{}]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l int - var vp *bytesI - for k2, _ := range v { - l = len(mksv) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - if esep { - for j := range v2 { - ee.WriteMapElemKey() - e.asis(v2[j].v) - ee.WriteMapElemValue() - e.encode(v[v2[j].i]) - } - } else { - for j := range v2 { - e.asis(v2[j].v) - e.encode(v[v2[j].i]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfUint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfUint64V(rv2i(rv).(map[interface{}]uint64), e) -} -func (_ fastpathT) EncMapIntfUint64V(v map[interface{}]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l int - var vp *bytesI - for k2, _ := range v { - l = len(mksv) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - if esep { - for j := range v2 { - ee.WriteMapElemKey() - e.asis(v2[j].v) - ee.WriteMapElemValue() - e.encode(v[v2[j].i]) - } - } else { - for j := range v2 { - e.asis(v2[j].v) - e.encode(v[v2[j].i]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfUintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfUintptrV(rv2i(rv).(map[interface{}]uintptr), e) -} -func (_ fastpathT) EncMapIntfUintptrV(v map[interface{}]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l int - var vp *bytesI - for k2, _ := range v { - l = len(mksv) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - if esep { - for j := range v2 { - ee.WriteMapElemKey() - e.asis(v2[j].v) - ee.WriteMapElemValue() - e.encode(v[v2[j].i]) - } - } else { - for j := range v2 { - e.asis(v2[j].v) - e.encode(v[v2[j].i]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - e.encode(k2) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfIntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfIntV(rv2i(rv).(map[interface{}]int), e) -} -func (_ fastpathT) EncMapIntfIntV(v map[interface{}]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l int - var vp *bytesI - for k2, _ := range v { - l = len(mksv) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - if esep { - for j := range v2 { - ee.WriteMapElemKey() - e.asis(v2[j].v) - ee.WriteMapElemValue() - e.encode(v[v2[j].i]) - } - } else { - for j := range v2 { - e.asis(v2[j].v) - e.encode(v[v2[j].i]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfInt8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfInt8V(rv2i(rv).(map[interface{}]int8), e) -} -func (_ fastpathT) EncMapIntfInt8V(v map[interface{}]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l int - var vp *bytesI - for k2, _ := range v { - l = len(mksv) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - if esep { - for j := range v2 { - ee.WriteMapElemKey() - e.asis(v2[j].v) - ee.WriteMapElemValue() - e.encode(v[v2[j].i]) - } - } else { - for j := range v2 { - e.asis(v2[j].v) - e.encode(v[v2[j].i]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfInt16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfInt16V(rv2i(rv).(map[interface{}]int16), e) -} -func (_ fastpathT) EncMapIntfInt16V(v map[interface{}]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l int - var vp *bytesI - for k2, _ := range v { - l = len(mksv) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - if esep { - for j := range v2 { - ee.WriteMapElemKey() - e.asis(v2[j].v) - ee.WriteMapElemValue() - e.encode(v[v2[j].i]) - } - } else { - for j := range v2 { - e.asis(v2[j].v) - e.encode(v[v2[j].i]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfInt32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfInt32V(rv2i(rv).(map[interface{}]int32), e) -} -func (_ fastpathT) EncMapIntfInt32V(v map[interface{}]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l int - var vp *bytesI - for k2, _ := range v { - l = len(mksv) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - if esep { - for j := range v2 { - ee.WriteMapElemKey() - e.asis(v2[j].v) - ee.WriteMapElemValue() - e.encode(v[v2[j].i]) - } - } else { - for j := range v2 { - e.asis(v2[j].v) - e.encode(v[v2[j].i]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfInt64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfInt64V(rv2i(rv).(map[interface{}]int64), e) -} -func (_ fastpathT) EncMapIntfInt64V(v map[interface{}]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l int - var vp *bytesI - for k2, _ := range v { - l = len(mksv) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - if esep { - for j := range v2 { - ee.WriteMapElemKey() - e.asis(v2[j].v) - ee.WriteMapElemValue() - e.encode(v[v2[j].i]) - } - } else { - for j := range v2 { - e.asis(v2[j].v) - e.encode(v[v2[j].i]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfFloat32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfFloat32V(rv2i(rv).(map[interface{}]float32), e) -} -func (_ fastpathT) EncMapIntfFloat32V(v map[interface{}]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l int - var vp *bytesI - for k2, _ := range v { - l = len(mksv) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - if esep { - for j := range v2 { - ee.WriteMapElemKey() - e.asis(v2[j].v) - ee.WriteMapElemValue() - e.encode(v[v2[j].i]) - } - } else { - for j := range v2 { - e.asis(v2[j].v) - e.encode(v[v2[j].i]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeFloat32(v2) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeFloat32(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfFloat64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfFloat64V(rv2i(rv).(map[interface{}]float64), e) -} -func (_ fastpathT) EncMapIntfFloat64V(v map[interface{}]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l int - var vp *bytesI - for k2, _ := range v { - l = len(mksv) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - if esep { - for j := range v2 { - ee.WriteMapElemKey() - e.asis(v2[j].v) - ee.WriteMapElemValue() - e.encode(v[v2[j].i]) - } - } else { - for j := range v2 { - e.asis(v2[j].v) - e.encode(v[v2[j].i]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeFloat64(v2) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeFloat64(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntfBoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntfBoolV(rv2i(rv).(map[interface{}]bool), e) -} -func (_ fastpathT) EncMapIntfBoolV(v map[interface{}]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - var mksv []byte = make([]byte, 0, len(v)*16) // temporary byte slice for the encoding - e2 := NewEncoderBytes(&mksv, e.hh) - v2 := make([]bytesI, len(v)) - var i, l int - var vp *bytesI - for k2, _ := range v { - l = len(mksv) - e2.MustEncode(k2) - vp = &v2[i] - vp.v = mksv[l:] - vp.i = k2 - i++ - } - sort.Sort(bytesISlice(v2)) - if esep { - for j := range v2 { - ee.WriteMapElemKey() - e.asis(v2[j].v) - ee.WriteMapElemValue() - e.encode(v[v2[j].i]) - } - } else { - for j := range v2 { - e.asis(v2[j].v) - e.encode(v[v2[j].i]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeBool(v2) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeBool(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringIntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringIntfV(rv2i(rv).(map[string]interface{}), e) -} -func (_ fastpathT) EncMapStringIntfV(v map[string]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i int - for k, _ := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - e.encode(v[string(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeString(cUTF8, k2) - e.encode(v[string(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeString(cUTF8, k2) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringStringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringStringV(rv2i(rv).(map[string]string), e) -} -func (_ fastpathT) EncMapStringStringV(v map[string]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i int - for k, _ := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v[string(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeString(cUTF8, k2) - ee.EncodeString(cUTF8, v[string(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v2) - } - } else { - for k2, v2 := range v { - ee.EncodeString(cUTF8, k2) - ee.EncodeString(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringUintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringUintV(rv2i(rv).(map[string]uint), e) -} -func (_ fastpathT) EncMapStringUintV(v map[string]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i int - for k, _ := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[string(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeString(cUTF8, k2) - ee.EncodeUint(uint64(v[string(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeString(cUTF8, k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringUint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringUint8V(rv2i(rv).(map[string]uint8), e) -} -func (_ fastpathT) EncMapStringUint8V(v map[string]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i int - for k, _ := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[string(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeString(cUTF8, k2) - ee.EncodeUint(uint64(v[string(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeString(cUTF8, k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringUint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringUint16V(rv2i(rv).(map[string]uint16), e) -} -func (_ fastpathT) EncMapStringUint16V(v map[string]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i int - for k, _ := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[string(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeString(cUTF8, k2) - ee.EncodeUint(uint64(v[string(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeString(cUTF8, k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringUint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringUint32V(rv2i(rv).(map[string]uint32), e) -} -func (_ fastpathT) EncMapStringUint32V(v map[string]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i int - for k, _ := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[string(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeString(cUTF8, k2) - ee.EncodeUint(uint64(v[string(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeString(cUTF8, k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringUint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringUint64V(rv2i(rv).(map[string]uint64), e) -} -func (_ fastpathT) EncMapStringUint64V(v map[string]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i int - for k, _ := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[string(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeString(cUTF8, k2) - ee.EncodeUint(uint64(v[string(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeString(cUTF8, k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringUintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringUintptrV(rv2i(rv).(map[string]uintptr), e) -} -func (_ fastpathT) EncMapStringUintptrV(v map[string]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i int - for k, _ := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - e.encode(v[string(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeString(cUTF8, k2) - e.encode(v[string(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeString(cUTF8, k2) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringIntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringIntV(rv2i(rv).(map[string]int), e) -} -func (_ fastpathT) EncMapStringIntV(v map[string]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i int - for k, _ := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[string(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeString(cUTF8, k2) - ee.EncodeInt(int64(v[string(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeString(cUTF8, k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringInt8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringInt8V(rv2i(rv).(map[string]int8), e) -} -func (_ fastpathT) EncMapStringInt8V(v map[string]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i int - for k, _ := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[string(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeString(cUTF8, k2) - ee.EncodeInt(int64(v[string(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeString(cUTF8, k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringInt16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringInt16V(rv2i(rv).(map[string]int16), e) -} -func (_ fastpathT) EncMapStringInt16V(v map[string]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i int - for k, _ := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[string(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeString(cUTF8, k2) - ee.EncodeInt(int64(v[string(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeString(cUTF8, k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringInt32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringInt32V(rv2i(rv).(map[string]int32), e) -} -func (_ fastpathT) EncMapStringInt32V(v map[string]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i int - for k, _ := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[string(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeString(cUTF8, k2) - ee.EncodeInt(int64(v[string(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeString(cUTF8, k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringInt64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringInt64V(rv2i(rv).(map[string]int64), e) -} -func (_ fastpathT) EncMapStringInt64V(v map[string]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i int - for k, _ := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[string(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeString(cUTF8, k2) - ee.EncodeInt(int64(v[string(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeString(cUTF8, k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringFloat32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringFloat32V(rv2i(rv).(map[string]float32), e) -} -func (_ fastpathT) EncMapStringFloat32V(v map[string]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i int - for k, _ := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeFloat32(v[string(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeString(cUTF8, k2) - ee.EncodeFloat32(v[string(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeFloat32(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeString(cUTF8, k2) - ee.EncodeFloat32(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringFloat64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringFloat64V(rv2i(rv).(map[string]float64), e) -} -func (_ fastpathT) EncMapStringFloat64V(v map[string]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i int - for k, _ := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeFloat64(v[string(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeString(cUTF8, k2) - ee.EncodeFloat64(v[string(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeFloat64(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeString(cUTF8, k2) - ee.EncodeFloat64(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapStringBoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapStringBoolV(rv2i(rv).(map[string]bool), e) -} -func (_ fastpathT) EncMapStringBoolV(v map[string]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]string, len(v)) - var i int - for k, _ := range v { - v2[i] = string(k) - i++ - } - sort.Sort(stringSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeBool(v[string(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeString(cUTF8, k2) - ee.EncodeBool(v[string(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeString(cUTF8, k2) - ee.WriteMapElemValue() - ee.EncodeBool(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeString(cUTF8, k2) - ee.EncodeBool(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32IntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32IntfV(rv2i(rv).(map[float32]interface{}), e) -} -func (_ fastpathT) EncMapFloat32IntfV(v map[float32]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat32(float32(k2)) - ee.WriteMapElemValue() - e.encode(v[float32(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat32(float32(k2)) - e.encode(v[float32(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat32(k2) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32StringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32StringV(rv2i(rv).(map[float32]string), e) -} -func (_ fastpathT) EncMapFloat32StringV(v map[float32]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat32(float32(k2)) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v[float32(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat32(float32(k2)) - ee.EncodeString(cUTF8, v[float32(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat32(k2) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v2) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeString(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32UintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32UintV(rv2i(rv).(map[float32]uint), e) -} -func (_ fastpathT) EncMapFloat32UintV(v map[float32]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat32(float32(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[float32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat32(float32(k2)) - ee.EncodeUint(uint64(v[float32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat32(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32Uint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32Uint8V(rv2i(rv).(map[float32]uint8), e) -} -func (_ fastpathT) EncMapFloat32Uint8V(v map[float32]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat32(float32(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[float32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat32(float32(k2)) - ee.EncodeUint(uint64(v[float32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat32(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32Uint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32Uint16V(rv2i(rv).(map[float32]uint16), e) -} -func (_ fastpathT) EncMapFloat32Uint16V(v map[float32]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat32(float32(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[float32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat32(float32(k2)) - ee.EncodeUint(uint64(v[float32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat32(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32Uint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32Uint32V(rv2i(rv).(map[float32]uint32), e) -} -func (_ fastpathT) EncMapFloat32Uint32V(v map[float32]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat32(float32(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[float32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat32(float32(k2)) - ee.EncodeUint(uint64(v[float32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat32(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32Uint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32Uint64V(rv2i(rv).(map[float32]uint64), e) -} -func (_ fastpathT) EncMapFloat32Uint64V(v map[float32]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat32(float32(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[float32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat32(float32(k2)) - ee.EncodeUint(uint64(v[float32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat32(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32UintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32UintptrV(rv2i(rv).(map[float32]uintptr), e) -} -func (_ fastpathT) EncMapFloat32UintptrV(v map[float32]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat32(float32(k2)) - ee.WriteMapElemValue() - e.encode(v[float32(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat32(float32(k2)) - e.encode(v[float32(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat32(k2) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32IntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32IntV(rv2i(rv).(map[float32]int), e) -} -func (_ fastpathT) EncMapFloat32IntV(v map[float32]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat32(float32(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[float32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat32(float32(k2)) - ee.EncodeInt(int64(v[float32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat32(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32Int8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32Int8V(rv2i(rv).(map[float32]int8), e) -} -func (_ fastpathT) EncMapFloat32Int8V(v map[float32]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat32(float32(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[float32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat32(float32(k2)) - ee.EncodeInt(int64(v[float32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat32(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32Int16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32Int16V(rv2i(rv).(map[float32]int16), e) -} -func (_ fastpathT) EncMapFloat32Int16V(v map[float32]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat32(float32(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[float32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat32(float32(k2)) - ee.EncodeInt(int64(v[float32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat32(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32Int32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32Int32V(rv2i(rv).(map[float32]int32), e) -} -func (_ fastpathT) EncMapFloat32Int32V(v map[float32]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat32(float32(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[float32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat32(float32(k2)) - ee.EncodeInt(int64(v[float32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat32(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32Int64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32Int64V(rv2i(rv).(map[float32]int64), e) -} -func (_ fastpathT) EncMapFloat32Int64V(v map[float32]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat32(float32(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[float32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat32(float32(k2)) - ee.EncodeInt(int64(v[float32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat32(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32Float32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32Float32V(rv2i(rv).(map[float32]float32), e) -} -func (_ fastpathT) EncMapFloat32Float32V(v map[float32]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat32(float32(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat32(v[float32(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat32(float32(k2)) - ee.EncodeFloat32(v[float32(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat32(k2) - ee.WriteMapElemValue() - ee.EncodeFloat32(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeFloat32(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32Float64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32Float64V(rv2i(rv).(map[float32]float64), e) -} -func (_ fastpathT) EncMapFloat32Float64V(v map[float32]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat32(float32(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat64(v[float32(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat32(float32(k2)) - ee.EncodeFloat64(v[float32(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat32(k2) - ee.WriteMapElemValue() - ee.EncodeFloat64(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeFloat64(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat32BoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat32BoolV(rv2i(rv).(map[float32]bool), e) -} -func (_ fastpathT) EncMapFloat32BoolV(v map[float32]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat32(float32(k2)) - ee.WriteMapElemValue() - ee.EncodeBool(v[float32(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat32(float32(k2)) - ee.EncodeBool(v[float32(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat32(k2) - ee.WriteMapElemValue() - ee.EncodeBool(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeBool(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64IntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64IntfV(rv2i(rv).(map[float64]interface{}), e) -} -func (_ fastpathT) EncMapFloat64IntfV(v map[float64]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat64(float64(k2)) - ee.WriteMapElemValue() - e.encode(v[float64(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat64(float64(k2)) - e.encode(v[float64(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat64(k2) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64StringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64StringV(rv2i(rv).(map[float64]string), e) -} -func (_ fastpathT) EncMapFloat64StringV(v map[float64]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat64(float64(k2)) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v[float64(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat64(float64(k2)) - ee.EncodeString(cUTF8, v[float64(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat64(k2) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v2) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeString(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64UintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64UintV(rv2i(rv).(map[float64]uint), e) -} -func (_ fastpathT) EncMapFloat64UintV(v map[float64]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat64(float64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[float64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat64(float64(k2)) - ee.EncodeUint(uint64(v[float64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat64(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64Uint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64Uint8V(rv2i(rv).(map[float64]uint8), e) -} -func (_ fastpathT) EncMapFloat64Uint8V(v map[float64]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat64(float64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[float64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat64(float64(k2)) - ee.EncodeUint(uint64(v[float64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat64(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64Uint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64Uint16V(rv2i(rv).(map[float64]uint16), e) -} -func (_ fastpathT) EncMapFloat64Uint16V(v map[float64]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat64(float64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[float64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat64(float64(k2)) - ee.EncodeUint(uint64(v[float64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat64(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64Uint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64Uint32V(rv2i(rv).(map[float64]uint32), e) -} -func (_ fastpathT) EncMapFloat64Uint32V(v map[float64]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat64(float64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[float64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat64(float64(k2)) - ee.EncodeUint(uint64(v[float64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat64(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64Uint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64Uint64V(rv2i(rv).(map[float64]uint64), e) -} -func (_ fastpathT) EncMapFloat64Uint64V(v map[float64]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat64(float64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[float64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat64(float64(k2)) - ee.EncodeUint(uint64(v[float64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat64(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64UintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64UintptrV(rv2i(rv).(map[float64]uintptr), e) -} -func (_ fastpathT) EncMapFloat64UintptrV(v map[float64]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat64(float64(k2)) - ee.WriteMapElemValue() - e.encode(v[float64(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat64(float64(k2)) - e.encode(v[float64(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat64(k2) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64IntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64IntV(rv2i(rv).(map[float64]int), e) -} -func (_ fastpathT) EncMapFloat64IntV(v map[float64]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat64(float64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[float64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat64(float64(k2)) - ee.EncodeInt(int64(v[float64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat64(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64Int8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64Int8V(rv2i(rv).(map[float64]int8), e) -} -func (_ fastpathT) EncMapFloat64Int8V(v map[float64]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat64(float64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[float64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat64(float64(k2)) - ee.EncodeInt(int64(v[float64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat64(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64Int16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64Int16V(rv2i(rv).(map[float64]int16), e) -} -func (_ fastpathT) EncMapFloat64Int16V(v map[float64]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat64(float64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[float64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat64(float64(k2)) - ee.EncodeInt(int64(v[float64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat64(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64Int32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64Int32V(rv2i(rv).(map[float64]int32), e) -} -func (_ fastpathT) EncMapFloat64Int32V(v map[float64]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat64(float64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[float64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat64(float64(k2)) - ee.EncodeInt(int64(v[float64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat64(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64Int64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64Int64V(rv2i(rv).(map[float64]int64), e) -} -func (_ fastpathT) EncMapFloat64Int64V(v map[float64]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat64(float64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[float64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat64(float64(k2)) - ee.EncodeInt(int64(v[float64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat64(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64Float32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64Float32V(rv2i(rv).(map[float64]float32), e) -} -func (_ fastpathT) EncMapFloat64Float32V(v map[float64]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat64(float64(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat32(v[float64(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat64(float64(k2)) - ee.EncodeFloat32(v[float64(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat64(k2) - ee.WriteMapElemValue() - ee.EncodeFloat32(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeFloat32(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64Float64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64Float64V(rv2i(rv).(map[float64]float64), e) -} -func (_ fastpathT) EncMapFloat64Float64V(v map[float64]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat64(float64(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat64(v[float64(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat64(float64(k2)) - ee.EncodeFloat64(v[float64(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat64(k2) - ee.WriteMapElemValue() - ee.EncodeFloat64(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeFloat64(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapFloat64BoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapFloat64BoolV(rv2i(rv).(map[float64]bool), e) -} -func (_ fastpathT) EncMapFloat64BoolV(v map[float64]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]float64, len(v)) - var i int - for k, _ := range v { - v2[i] = float64(k) - i++ - } - sort.Sort(floatSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeFloat64(float64(k2)) - ee.WriteMapElemValue() - ee.EncodeBool(v[float64(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeFloat64(float64(k2)) - ee.EncodeBool(v[float64(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeFloat64(k2) - ee.WriteMapElemValue() - ee.EncodeBool(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeBool(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintIntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintIntfV(rv2i(rv).(map[uint]interface{}), e) -} -func (_ fastpathT) EncMapUintIntfV(v map[uint]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint(k2))) - ee.WriteMapElemValue() - e.encode(v[uint(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint(k2))) - e.encode(v[uint(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintStringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintStringV(rv2i(rv).(map[uint]string), e) -} -func (_ fastpathT) EncMapUintStringV(v map[uint]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint(k2))) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v[uint(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint(k2))) - ee.EncodeString(cUTF8, v[uint(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeString(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintUintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintUintV(rv2i(rv).(map[uint]uint), e) -} -func (_ fastpathT) EncMapUintUintV(v map[uint]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint(k2))) - ee.EncodeUint(uint64(v[uint(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintUint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintUint8V(rv2i(rv).(map[uint]uint8), e) -} -func (_ fastpathT) EncMapUintUint8V(v map[uint]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint(k2))) - ee.EncodeUint(uint64(v[uint(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintUint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintUint16V(rv2i(rv).(map[uint]uint16), e) -} -func (_ fastpathT) EncMapUintUint16V(v map[uint]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint(k2))) - ee.EncodeUint(uint64(v[uint(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintUint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintUint32V(rv2i(rv).(map[uint]uint32), e) -} -func (_ fastpathT) EncMapUintUint32V(v map[uint]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint(k2))) - ee.EncodeUint(uint64(v[uint(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintUint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintUint64V(rv2i(rv).(map[uint]uint64), e) -} -func (_ fastpathT) EncMapUintUint64V(v map[uint]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint(k2))) - ee.EncodeUint(uint64(v[uint(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintUintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintUintptrV(rv2i(rv).(map[uint]uintptr), e) -} -func (_ fastpathT) EncMapUintUintptrV(v map[uint]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint(k2))) - ee.WriteMapElemValue() - e.encode(v[uint(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint(k2))) - e.encode(v[uint(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintIntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintIntV(rv2i(rv).(map[uint]int), e) -} -func (_ fastpathT) EncMapUintIntV(v map[uint]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint(k2))) - ee.EncodeInt(int64(v[uint(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintInt8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintInt8V(rv2i(rv).(map[uint]int8), e) -} -func (_ fastpathT) EncMapUintInt8V(v map[uint]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint(k2))) - ee.EncodeInt(int64(v[uint(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintInt16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintInt16V(rv2i(rv).(map[uint]int16), e) -} -func (_ fastpathT) EncMapUintInt16V(v map[uint]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint(k2))) - ee.EncodeInt(int64(v[uint(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintInt32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintInt32V(rv2i(rv).(map[uint]int32), e) -} -func (_ fastpathT) EncMapUintInt32V(v map[uint]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint(k2))) - ee.EncodeInt(int64(v[uint(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintInt64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintInt64V(rv2i(rv).(map[uint]int64), e) -} -func (_ fastpathT) EncMapUintInt64V(v map[uint]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint(k2))) - ee.EncodeInt(int64(v[uint(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintFloat32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintFloat32V(rv2i(rv).(map[uint]float32), e) -} -func (_ fastpathT) EncMapUintFloat32V(v map[uint]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint(k2))) - ee.WriteMapElemValue() - ee.EncodeFloat32(v[uint(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint(k2))) - ee.EncodeFloat32(v[uint(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat32(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeFloat32(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintFloat64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintFloat64V(rv2i(rv).(map[uint]float64), e) -} -func (_ fastpathT) EncMapUintFloat64V(v map[uint]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint(k2))) - ee.WriteMapElemValue() - ee.EncodeFloat64(v[uint(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint(k2))) - ee.EncodeFloat64(v[uint(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat64(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeFloat64(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintBoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintBoolV(rv2i(rv).(map[uint]bool), e) -} -func (_ fastpathT) EncMapUintBoolV(v map[uint]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint(k2))) - ee.WriteMapElemValue() - ee.EncodeBool(v[uint(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint(k2))) - ee.EncodeBool(v[uint(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeBool(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeBool(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8IntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8IntfV(rv2i(rv).(map[uint8]interface{}), e) -} -func (_ fastpathT) EncMapUint8IntfV(v map[uint8]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint8(k2))) - ee.WriteMapElemValue() - e.encode(v[uint8(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint8(k2))) - e.encode(v[uint8(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8StringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8StringV(rv2i(rv).(map[uint8]string), e) -} -func (_ fastpathT) EncMapUint8StringV(v map[uint8]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint8(k2))) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v[uint8(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint8(k2))) - ee.EncodeString(cUTF8, v[uint8(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeString(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8UintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8UintV(rv2i(rv).(map[uint8]uint), e) -} -func (_ fastpathT) EncMapUint8UintV(v map[uint8]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint8(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint8(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint8(k2))) - ee.EncodeUint(uint64(v[uint8(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8Uint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8Uint8V(rv2i(rv).(map[uint8]uint8), e) -} -func (_ fastpathT) EncMapUint8Uint8V(v map[uint8]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint8(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint8(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint8(k2))) - ee.EncodeUint(uint64(v[uint8(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8Uint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8Uint16V(rv2i(rv).(map[uint8]uint16), e) -} -func (_ fastpathT) EncMapUint8Uint16V(v map[uint8]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint8(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint8(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint8(k2))) - ee.EncodeUint(uint64(v[uint8(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8Uint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8Uint32V(rv2i(rv).(map[uint8]uint32), e) -} -func (_ fastpathT) EncMapUint8Uint32V(v map[uint8]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint8(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint8(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint8(k2))) - ee.EncodeUint(uint64(v[uint8(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8Uint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8Uint64V(rv2i(rv).(map[uint8]uint64), e) -} -func (_ fastpathT) EncMapUint8Uint64V(v map[uint8]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint8(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint8(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint8(k2))) - ee.EncodeUint(uint64(v[uint8(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8UintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8UintptrV(rv2i(rv).(map[uint8]uintptr), e) -} -func (_ fastpathT) EncMapUint8UintptrV(v map[uint8]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint8(k2))) - ee.WriteMapElemValue() - e.encode(v[uint8(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint8(k2))) - e.encode(v[uint8(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8IntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8IntV(rv2i(rv).(map[uint8]int), e) -} -func (_ fastpathT) EncMapUint8IntV(v map[uint8]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint8(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint8(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint8(k2))) - ee.EncodeInt(int64(v[uint8(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8Int8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8Int8V(rv2i(rv).(map[uint8]int8), e) -} -func (_ fastpathT) EncMapUint8Int8V(v map[uint8]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint8(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint8(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint8(k2))) - ee.EncodeInt(int64(v[uint8(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8Int16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8Int16V(rv2i(rv).(map[uint8]int16), e) -} -func (_ fastpathT) EncMapUint8Int16V(v map[uint8]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint8(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint8(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint8(k2))) - ee.EncodeInt(int64(v[uint8(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8Int32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8Int32V(rv2i(rv).(map[uint8]int32), e) -} -func (_ fastpathT) EncMapUint8Int32V(v map[uint8]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint8(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint8(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint8(k2))) - ee.EncodeInt(int64(v[uint8(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8Int64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8Int64V(rv2i(rv).(map[uint8]int64), e) -} -func (_ fastpathT) EncMapUint8Int64V(v map[uint8]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint8(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint8(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint8(k2))) - ee.EncodeInt(int64(v[uint8(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8Float32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8Float32V(rv2i(rv).(map[uint8]float32), e) -} -func (_ fastpathT) EncMapUint8Float32V(v map[uint8]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint8(k2))) - ee.WriteMapElemValue() - ee.EncodeFloat32(v[uint8(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint8(k2))) - ee.EncodeFloat32(v[uint8(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat32(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeFloat32(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8Float64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8Float64V(rv2i(rv).(map[uint8]float64), e) -} -func (_ fastpathT) EncMapUint8Float64V(v map[uint8]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint8(k2))) - ee.WriteMapElemValue() - ee.EncodeFloat64(v[uint8(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint8(k2))) - ee.EncodeFloat64(v[uint8(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat64(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeFloat64(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint8BoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint8BoolV(rv2i(rv).(map[uint8]bool), e) -} -func (_ fastpathT) EncMapUint8BoolV(v map[uint8]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint8(k2))) - ee.WriteMapElemValue() - ee.EncodeBool(v[uint8(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint8(k2))) - ee.EncodeBool(v[uint8(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeBool(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeBool(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16IntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16IntfV(rv2i(rv).(map[uint16]interface{}), e) -} -func (_ fastpathT) EncMapUint16IntfV(v map[uint16]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint16(k2))) - ee.WriteMapElemValue() - e.encode(v[uint16(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint16(k2))) - e.encode(v[uint16(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16StringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16StringV(rv2i(rv).(map[uint16]string), e) -} -func (_ fastpathT) EncMapUint16StringV(v map[uint16]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint16(k2))) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v[uint16(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint16(k2))) - ee.EncodeString(cUTF8, v[uint16(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeString(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16UintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16UintV(rv2i(rv).(map[uint16]uint), e) -} -func (_ fastpathT) EncMapUint16UintV(v map[uint16]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint16(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint16(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint16(k2))) - ee.EncodeUint(uint64(v[uint16(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16Uint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16Uint8V(rv2i(rv).(map[uint16]uint8), e) -} -func (_ fastpathT) EncMapUint16Uint8V(v map[uint16]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint16(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint16(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint16(k2))) - ee.EncodeUint(uint64(v[uint16(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16Uint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16Uint16V(rv2i(rv).(map[uint16]uint16), e) -} -func (_ fastpathT) EncMapUint16Uint16V(v map[uint16]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint16(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint16(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint16(k2))) - ee.EncodeUint(uint64(v[uint16(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16Uint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16Uint32V(rv2i(rv).(map[uint16]uint32), e) -} -func (_ fastpathT) EncMapUint16Uint32V(v map[uint16]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint16(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint16(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint16(k2))) - ee.EncodeUint(uint64(v[uint16(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16Uint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16Uint64V(rv2i(rv).(map[uint16]uint64), e) -} -func (_ fastpathT) EncMapUint16Uint64V(v map[uint16]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint16(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint16(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint16(k2))) - ee.EncodeUint(uint64(v[uint16(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16UintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16UintptrV(rv2i(rv).(map[uint16]uintptr), e) -} -func (_ fastpathT) EncMapUint16UintptrV(v map[uint16]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint16(k2))) - ee.WriteMapElemValue() - e.encode(v[uint16(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint16(k2))) - e.encode(v[uint16(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16IntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16IntV(rv2i(rv).(map[uint16]int), e) -} -func (_ fastpathT) EncMapUint16IntV(v map[uint16]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint16(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint16(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint16(k2))) - ee.EncodeInt(int64(v[uint16(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16Int8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16Int8V(rv2i(rv).(map[uint16]int8), e) -} -func (_ fastpathT) EncMapUint16Int8V(v map[uint16]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint16(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint16(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint16(k2))) - ee.EncodeInt(int64(v[uint16(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16Int16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16Int16V(rv2i(rv).(map[uint16]int16), e) -} -func (_ fastpathT) EncMapUint16Int16V(v map[uint16]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint16(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint16(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint16(k2))) - ee.EncodeInt(int64(v[uint16(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16Int32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16Int32V(rv2i(rv).(map[uint16]int32), e) -} -func (_ fastpathT) EncMapUint16Int32V(v map[uint16]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint16(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint16(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint16(k2))) - ee.EncodeInt(int64(v[uint16(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16Int64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16Int64V(rv2i(rv).(map[uint16]int64), e) -} -func (_ fastpathT) EncMapUint16Int64V(v map[uint16]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint16(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint16(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint16(k2))) - ee.EncodeInt(int64(v[uint16(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16Float32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16Float32V(rv2i(rv).(map[uint16]float32), e) -} -func (_ fastpathT) EncMapUint16Float32V(v map[uint16]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint16(k2))) - ee.WriteMapElemValue() - ee.EncodeFloat32(v[uint16(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint16(k2))) - ee.EncodeFloat32(v[uint16(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat32(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeFloat32(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16Float64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16Float64V(rv2i(rv).(map[uint16]float64), e) -} -func (_ fastpathT) EncMapUint16Float64V(v map[uint16]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint16(k2))) - ee.WriteMapElemValue() - ee.EncodeFloat64(v[uint16(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint16(k2))) - ee.EncodeFloat64(v[uint16(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat64(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeFloat64(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint16BoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint16BoolV(rv2i(rv).(map[uint16]bool), e) -} -func (_ fastpathT) EncMapUint16BoolV(v map[uint16]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint16(k2))) - ee.WriteMapElemValue() - ee.EncodeBool(v[uint16(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint16(k2))) - ee.EncodeBool(v[uint16(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeBool(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeBool(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32IntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32IntfV(rv2i(rv).(map[uint32]interface{}), e) -} -func (_ fastpathT) EncMapUint32IntfV(v map[uint32]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint32(k2))) - ee.WriteMapElemValue() - e.encode(v[uint32(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint32(k2))) - e.encode(v[uint32(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32StringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32StringV(rv2i(rv).(map[uint32]string), e) -} -func (_ fastpathT) EncMapUint32StringV(v map[uint32]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint32(k2))) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v[uint32(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint32(k2))) - ee.EncodeString(cUTF8, v[uint32(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeString(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32UintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32UintV(rv2i(rv).(map[uint32]uint), e) -} -func (_ fastpathT) EncMapUint32UintV(v map[uint32]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint32(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint32(k2))) - ee.EncodeUint(uint64(v[uint32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32Uint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32Uint8V(rv2i(rv).(map[uint32]uint8), e) -} -func (_ fastpathT) EncMapUint32Uint8V(v map[uint32]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint32(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint32(k2))) - ee.EncodeUint(uint64(v[uint32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32Uint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32Uint16V(rv2i(rv).(map[uint32]uint16), e) -} -func (_ fastpathT) EncMapUint32Uint16V(v map[uint32]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint32(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint32(k2))) - ee.EncodeUint(uint64(v[uint32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32Uint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32Uint32V(rv2i(rv).(map[uint32]uint32), e) -} -func (_ fastpathT) EncMapUint32Uint32V(v map[uint32]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint32(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint32(k2))) - ee.EncodeUint(uint64(v[uint32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32Uint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32Uint64V(rv2i(rv).(map[uint32]uint64), e) -} -func (_ fastpathT) EncMapUint32Uint64V(v map[uint32]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint32(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint32(k2))) - ee.EncodeUint(uint64(v[uint32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32UintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32UintptrV(rv2i(rv).(map[uint32]uintptr), e) -} -func (_ fastpathT) EncMapUint32UintptrV(v map[uint32]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint32(k2))) - ee.WriteMapElemValue() - e.encode(v[uint32(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint32(k2))) - e.encode(v[uint32(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32IntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32IntV(rv2i(rv).(map[uint32]int), e) -} -func (_ fastpathT) EncMapUint32IntV(v map[uint32]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint32(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint32(k2))) - ee.EncodeInt(int64(v[uint32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32Int8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32Int8V(rv2i(rv).(map[uint32]int8), e) -} -func (_ fastpathT) EncMapUint32Int8V(v map[uint32]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint32(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint32(k2))) - ee.EncodeInt(int64(v[uint32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32Int16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32Int16V(rv2i(rv).(map[uint32]int16), e) -} -func (_ fastpathT) EncMapUint32Int16V(v map[uint32]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint32(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint32(k2))) - ee.EncodeInt(int64(v[uint32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32Int32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32Int32V(rv2i(rv).(map[uint32]int32), e) -} -func (_ fastpathT) EncMapUint32Int32V(v map[uint32]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint32(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint32(k2))) - ee.EncodeInt(int64(v[uint32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32Int64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32Int64V(rv2i(rv).(map[uint32]int64), e) -} -func (_ fastpathT) EncMapUint32Int64V(v map[uint32]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint32(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint32(k2))) - ee.EncodeInt(int64(v[uint32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32Float32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32Float32V(rv2i(rv).(map[uint32]float32), e) -} -func (_ fastpathT) EncMapUint32Float32V(v map[uint32]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint32(k2))) - ee.WriteMapElemValue() - ee.EncodeFloat32(v[uint32(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint32(k2))) - ee.EncodeFloat32(v[uint32(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat32(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeFloat32(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32Float64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32Float64V(rv2i(rv).(map[uint32]float64), e) -} -func (_ fastpathT) EncMapUint32Float64V(v map[uint32]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint32(k2))) - ee.WriteMapElemValue() - ee.EncodeFloat64(v[uint32(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint32(k2))) - ee.EncodeFloat64(v[uint32(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat64(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeFloat64(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint32BoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint32BoolV(rv2i(rv).(map[uint32]bool), e) -} -func (_ fastpathT) EncMapUint32BoolV(v map[uint32]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint32(k2))) - ee.WriteMapElemValue() - ee.EncodeBool(v[uint32(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint32(k2))) - ee.EncodeBool(v[uint32(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeBool(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeBool(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64IntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64IntfV(rv2i(rv).(map[uint64]interface{}), e) -} -func (_ fastpathT) EncMapUint64IntfV(v map[uint64]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint64(k2))) - ee.WriteMapElemValue() - e.encode(v[uint64(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint64(k2))) - e.encode(v[uint64(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64StringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64StringV(rv2i(rv).(map[uint64]string), e) -} -func (_ fastpathT) EncMapUint64StringV(v map[uint64]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint64(k2))) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v[uint64(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint64(k2))) - ee.EncodeString(cUTF8, v[uint64(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeString(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64UintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64UintV(rv2i(rv).(map[uint64]uint), e) -} -func (_ fastpathT) EncMapUint64UintV(v map[uint64]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint64(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint64(k2))) - ee.EncodeUint(uint64(v[uint64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64Uint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64Uint8V(rv2i(rv).(map[uint64]uint8), e) -} -func (_ fastpathT) EncMapUint64Uint8V(v map[uint64]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint64(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint64(k2))) - ee.EncodeUint(uint64(v[uint64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64Uint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64Uint16V(rv2i(rv).(map[uint64]uint16), e) -} -func (_ fastpathT) EncMapUint64Uint16V(v map[uint64]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint64(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint64(k2))) - ee.EncodeUint(uint64(v[uint64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64Uint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64Uint32V(rv2i(rv).(map[uint64]uint32), e) -} -func (_ fastpathT) EncMapUint64Uint32V(v map[uint64]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint64(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint64(k2))) - ee.EncodeUint(uint64(v[uint64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64Uint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64Uint64V(rv2i(rv).(map[uint64]uint64), e) -} -func (_ fastpathT) EncMapUint64Uint64V(v map[uint64]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint64(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uint64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint64(k2))) - ee.EncodeUint(uint64(v[uint64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64UintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64UintptrV(rv2i(rv).(map[uint64]uintptr), e) -} -func (_ fastpathT) EncMapUint64UintptrV(v map[uint64]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint64(k2))) - ee.WriteMapElemValue() - e.encode(v[uint64(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint64(k2))) - e.encode(v[uint64(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64IntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64IntV(rv2i(rv).(map[uint64]int), e) -} -func (_ fastpathT) EncMapUint64IntV(v map[uint64]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint64(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint64(k2))) - ee.EncodeInt(int64(v[uint64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64Int8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64Int8V(rv2i(rv).(map[uint64]int8), e) -} -func (_ fastpathT) EncMapUint64Int8V(v map[uint64]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint64(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint64(k2))) - ee.EncodeInt(int64(v[uint64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64Int16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64Int16V(rv2i(rv).(map[uint64]int16), e) -} -func (_ fastpathT) EncMapUint64Int16V(v map[uint64]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint64(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint64(k2))) - ee.EncodeInt(int64(v[uint64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64Int32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64Int32V(rv2i(rv).(map[uint64]int32), e) -} -func (_ fastpathT) EncMapUint64Int32V(v map[uint64]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint64(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint64(k2))) - ee.EncodeInt(int64(v[uint64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64Int64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64Int64V(rv2i(rv).(map[uint64]int64), e) -} -func (_ fastpathT) EncMapUint64Int64V(v map[uint64]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint64(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uint64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint64(k2))) - ee.EncodeInt(int64(v[uint64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64Float32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64Float32V(rv2i(rv).(map[uint64]float32), e) -} -func (_ fastpathT) EncMapUint64Float32V(v map[uint64]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint64(k2))) - ee.WriteMapElemValue() - ee.EncodeFloat32(v[uint64(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint64(k2))) - ee.EncodeFloat32(v[uint64(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat32(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeFloat32(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64Float64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64Float64V(rv2i(rv).(map[uint64]float64), e) -} -func (_ fastpathT) EncMapUint64Float64V(v map[uint64]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint64(k2))) - ee.WriteMapElemValue() - ee.EncodeFloat64(v[uint64(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint64(k2))) - ee.EncodeFloat64(v[uint64(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat64(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeFloat64(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUint64BoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUint64BoolV(rv2i(rv).(map[uint64]bool), e) -} -func (_ fastpathT) EncMapUint64BoolV(v map[uint64]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(uint64(k2))) - ee.WriteMapElemValue() - ee.EncodeBool(v[uint64(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeUint(uint64(uint64(k2))) - ee.EncodeBool(v[uint64(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeUint(uint64(k2)) - ee.WriteMapElemValue() - ee.EncodeBool(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeBool(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrIntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrIntfV(rv2i(rv).(map[uintptr]interface{}), e) -} -func (_ fastpathT) EncMapUintptrIntfV(v map[uintptr]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - e.encode(uintptr(k2)) - ee.WriteMapElemValue() - e.encode(v[uintptr(k2)]) - } - } else { - for _, k2 := range v2 { - e.encode(uintptr(k2)) - e.encode(v[uintptr(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - e.encode(k2) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrStringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrStringV(rv2i(rv).(map[uintptr]string), e) -} -func (_ fastpathT) EncMapUintptrStringV(v map[uintptr]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - e.encode(uintptr(k2)) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v[uintptr(k2)]) - } - } else { - for _, k2 := range v2 { - e.encode(uintptr(k2)) - ee.EncodeString(cUTF8, v[uintptr(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v2) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeString(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrUintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrUintV(rv2i(rv).(map[uintptr]uint), e) -} -func (_ fastpathT) EncMapUintptrUintV(v map[uintptr]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - e.encode(uintptr(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uintptr(k2)])) - } - } else { - for _, k2 := range v2 { - e.encode(uintptr(k2)) - ee.EncodeUint(uint64(v[uintptr(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrUint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrUint8V(rv2i(rv).(map[uintptr]uint8), e) -} -func (_ fastpathT) EncMapUintptrUint8V(v map[uintptr]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - e.encode(uintptr(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uintptr(k2)])) - } - } else { - for _, k2 := range v2 { - e.encode(uintptr(k2)) - ee.EncodeUint(uint64(v[uintptr(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrUint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrUint16V(rv2i(rv).(map[uintptr]uint16), e) -} -func (_ fastpathT) EncMapUintptrUint16V(v map[uintptr]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - e.encode(uintptr(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uintptr(k2)])) - } - } else { - for _, k2 := range v2 { - e.encode(uintptr(k2)) - ee.EncodeUint(uint64(v[uintptr(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrUint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrUint32V(rv2i(rv).(map[uintptr]uint32), e) -} -func (_ fastpathT) EncMapUintptrUint32V(v map[uintptr]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - e.encode(uintptr(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uintptr(k2)])) - } - } else { - for _, k2 := range v2 { - e.encode(uintptr(k2)) - ee.EncodeUint(uint64(v[uintptr(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrUint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrUint64V(rv2i(rv).(map[uintptr]uint64), e) -} -func (_ fastpathT) EncMapUintptrUint64V(v map[uintptr]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - e.encode(uintptr(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[uintptr(k2)])) - } - } else { - for _, k2 := range v2 { - e.encode(uintptr(k2)) - ee.EncodeUint(uint64(v[uintptr(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrUintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrUintptrV(rv2i(rv).(map[uintptr]uintptr), e) -} -func (_ fastpathT) EncMapUintptrUintptrV(v map[uintptr]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - e.encode(uintptr(k2)) - ee.WriteMapElemValue() - e.encode(v[uintptr(k2)]) - } - } else { - for _, k2 := range v2 { - e.encode(uintptr(k2)) - e.encode(v[uintptr(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - e.encode(k2) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrIntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrIntV(rv2i(rv).(map[uintptr]int), e) -} -func (_ fastpathT) EncMapUintptrIntV(v map[uintptr]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - e.encode(uintptr(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uintptr(k2)])) - } - } else { - for _, k2 := range v2 { - e.encode(uintptr(k2)) - ee.EncodeInt(int64(v[uintptr(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrInt8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrInt8V(rv2i(rv).(map[uintptr]int8), e) -} -func (_ fastpathT) EncMapUintptrInt8V(v map[uintptr]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - e.encode(uintptr(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uintptr(k2)])) - } - } else { - for _, k2 := range v2 { - e.encode(uintptr(k2)) - ee.EncodeInt(int64(v[uintptr(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrInt16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrInt16V(rv2i(rv).(map[uintptr]int16), e) -} -func (_ fastpathT) EncMapUintptrInt16V(v map[uintptr]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - e.encode(uintptr(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uintptr(k2)])) - } - } else { - for _, k2 := range v2 { - e.encode(uintptr(k2)) - ee.EncodeInt(int64(v[uintptr(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrInt32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrInt32V(rv2i(rv).(map[uintptr]int32), e) -} -func (_ fastpathT) EncMapUintptrInt32V(v map[uintptr]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - e.encode(uintptr(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uintptr(k2)])) - } - } else { - for _, k2 := range v2 { - e.encode(uintptr(k2)) - ee.EncodeInt(int64(v[uintptr(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrInt64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrInt64V(rv2i(rv).(map[uintptr]int64), e) -} -func (_ fastpathT) EncMapUintptrInt64V(v map[uintptr]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - e.encode(uintptr(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[uintptr(k2)])) - } - } else { - for _, k2 := range v2 { - e.encode(uintptr(k2)) - ee.EncodeInt(int64(v[uintptr(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrFloat32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrFloat32V(rv2i(rv).(map[uintptr]float32), e) -} -func (_ fastpathT) EncMapUintptrFloat32V(v map[uintptr]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - e.encode(uintptr(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat32(v[uintptr(k2)]) - } - } else { - for _, k2 := range v2 { - e.encode(uintptr(k2)) - ee.EncodeFloat32(v[uintptr(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeFloat32(v2) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeFloat32(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrFloat64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrFloat64V(rv2i(rv).(map[uintptr]float64), e) -} -func (_ fastpathT) EncMapUintptrFloat64V(v map[uintptr]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - e.encode(uintptr(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat64(v[uintptr(k2)]) - } - } else { - for _, k2 := range v2 { - e.encode(uintptr(k2)) - ee.EncodeFloat64(v[uintptr(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeFloat64(v2) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeFloat64(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapUintptrBoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapUintptrBoolV(rv2i(rv).(map[uintptr]bool), e) -} -func (_ fastpathT) EncMapUintptrBoolV(v map[uintptr]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]uint64, len(v)) - var i int - for k, _ := range v { - v2[i] = uint64(k) - i++ - } - sort.Sort(uintSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - e.encode(uintptr(k2)) - ee.WriteMapElemValue() - ee.EncodeBool(v[uintptr(k2)]) - } - } else { - for _, k2 := range v2 { - e.encode(uintptr(k2)) - ee.EncodeBool(v[uintptr(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - e.encode(k2) - ee.WriteMapElemValue() - ee.EncodeBool(v2) - } - } else { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeBool(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntIntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntIntfV(rv2i(rv).(map[int]interface{}), e) -} -func (_ fastpathT) EncMapIntIntfV(v map[int]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int(k2))) - ee.WriteMapElemValue() - e.encode(v[int(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int(k2))) - e.encode(v[int(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntStringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntStringV(rv2i(rv).(map[int]string), e) -} -func (_ fastpathT) EncMapIntStringV(v map[int]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int(k2))) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v[int(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int(k2))) - ee.EncodeString(cUTF8, v[int(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeString(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntUintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntUintV(rv2i(rv).(map[int]uint), e) -} -func (_ fastpathT) EncMapIntUintV(v map[int]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int(k2))) - ee.EncodeUint(uint64(v[int(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntUint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntUint8V(rv2i(rv).(map[int]uint8), e) -} -func (_ fastpathT) EncMapIntUint8V(v map[int]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int(k2))) - ee.EncodeUint(uint64(v[int(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntUint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntUint16V(rv2i(rv).(map[int]uint16), e) -} -func (_ fastpathT) EncMapIntUint16V(v map[int]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int(k2))) - ee.EncodeUint(uint64(v[int(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntUint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntUint32V(rv2i(rv).(map[int]uint32), e) -} -func (_ fastpathT) EncMapIntUint32V(v map[int]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int(k2))) - ee.EncodeUint(uint64(v[int(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntUint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntUint64V(rv2i(rv).(map[int]uint64), e) -} -func (_ fastpathT) EncMapIntUint64V(v map[int]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int(k2))) - ee.EncodeUint(uint64(v[int(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntUintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntUintptrV(rv2i(rv).(map[int]uintptr), e) -} -func (_ fastpathT) EncMapIntUintptrV(v map[int]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int(k2))) - ee.WriteMapElemValue() - e.encode(v[int(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int(k2))) - e.encode(v[int(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntIntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntIntV(rv2i(rv).(map[int]int), e) -} -func (_ fastpathT) EncMapIntIntV(v map[int]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int(k2))) - ee.EncodeInt(int64(v[int(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntInt8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntInt8V(rv2i(rv).(map[int]int8), e) -} -func (_ fastpathT) EncMapIntInt8V(v map[int]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int(k2))) - ee.EncodeInt(int64(v[int(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntInt16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntInt16V(rv2i(rv).(map[int]int16), e) -} -func (_ fastpathT) EncMapIntInt16V(v map[int]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int(k2))) - ee.EncodeInt(int64(v[int(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntInt32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntInt32V(rv2i(rv).(map[int]int32), e) -} -func (_ fastpathT) EncMapIntInt32V(v map[int]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int(k2))) - ee.EncodeInt(int64(v[int(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntInt64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntInt64V(rv2i(rv).(map[int]int64), e) -} -func (_ fastpathT) EncMapIntInt64V(v map[int]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int(k2))) - ee.EncodeInt(int64(v[int(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntFloat32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntFloat32V(rv2i(rv).(map[int]float32), e) -} -func (_ fastpathT) EncMapIntFloat32V(v map[int]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int(k2))) - ee.WriteMapElemValue() - ee.EncodeFloat32(v[int(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int(k2))) - ee.EncodeFloat32(v[int(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat32(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeFloat32(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntFloat64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntFloat64V(rv2i(rv).(map[int]float64), e) -} -func (_ fastpathT) EncMapIntFloat64V(v map[int]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int(k2))) - ee.WriteMapElemValue() - ee.EncodeFloat64(v[int(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int(k2))) - ee.EncodeFloat64(v[int(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat64(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeFloat64(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapIntBoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapIntBoolV(rv2i(rv).(map[int]bool), e) -} -func (_ fastpathT) EncMapIntBoolV(v map[int]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int(k2))) - ee.WriteMapElemValue() - ee.EncodeBool(v[int(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int(k2))) - ee.EncodeBool(v[int(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeBool(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeBool(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8IntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8IntfV(rv2i(rv).(map[int8]interface{}), e) -} -func (_ fastpathT) EncMapInt8IntfV(v map[int8]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int8(k2))) - ee.WriteMapElemValue() - e.encode(v[int8(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int8(k2))) - e.encode(v[int8(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8StringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8StringV(rv2i(rv).(map[int8]string), e) -} -func (_ fastpathT) EncMapInt8StringV(v map[int8]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int8(k2))) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v[int8(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int8(k2))) - ee.EncodeString(cUTF8, v[int8(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeString(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8UintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8UintV(rv2i(rv).(map[int8]uint), e) -} -func (_ fastpathT) EncMapInt8UintV(v map[int8]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int8(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int8(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int8(k2))) - ee.EncodeUint(uint64(v[int8(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8Uint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8Uint8V(rv2i(rv).(map[int8]uint8), e) -} -func (_ fastpathT) EncMapInt8Uint8V(v map[int8]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int8(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int8(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int8(k2))) - ee.EncodeUint(uint64(v[int8(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8Uint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8Uint16V(rv2i(rv).(map[int8]uint16), e) -} -func (_ fastpathT) EncMapInt8Uint16V(v map[int8]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int8(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int8(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int8(k2))) - ee.EncodeUint(uint64(v[int8(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8Uint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8Uint32V(rv2i(rv).(map[int8]uint32), e) -} -func (_ fastpathT) EncMapInt8Uint32V(v map[int8]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int8(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int8(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int8(k2))) - ee.EncodeUint(uint64(v[int8(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8Uint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8Uint64V(rv2i(rv).(map[int8]uint64), e) -} -func (_ fastpathT) EncMapInt8Uint64V(v map[int8]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int8(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int8(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int8(k2))) - ee.EncodeUint(uint64(v[int8(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8UintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8UintptrV(rv2i(rv).(map[int8]uintptr), e) -} -func (_ fastpathT) EncMapInt8UintptrV(v map[int8]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int8(k2))) - ee.WriteMapElemValue() - e.encode(v[int8(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int8(k2))) - e.encode(v[int8(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8IntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8IntV(rv2i(rv).(map[int8]int), e) -} -func (_ fastpathT) EncMapInt8IntV(v map[int8]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int8(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int8(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int8(k2))) - ee.EncodeInt(int64(v[int8(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8Int8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8Int8V(rv2i(rv).(map[int8]int8), e) -} -func (_ fastpathT) EncMapInt8Int8V(v map[int8]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int8(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int8(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int8(k2))) - ee.EncodeInt(int64(v[int8(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8Int16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8Int16V(rv2i(rv).(map[int8]int16), e) -} -func (_ fastpathT) EncMapInt8Int16V(v map[int8]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int8(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int8(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int8(k2))) - ee.EncodeInt(int64(v[int8(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8Int32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8Int32V(rv2i(rv).(map[int8]int32), e) -} -func (_ fastpathT) EncMapInt8Int32V(v map[int8]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int8(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int8(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int8(k2))) - ee.EncodeInt(int64(v[int8(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8Int64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8Int64V(rv2i(rv).(map[int8]int64), e) -} -func (_ fastpathT) EncMapInt8Int64V(v map[int8]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int8(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int8(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int8(k2))) - ee.EncodeInt(int64(v[int8(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8Float32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8Float32V(rv2i(rv).(map[int8]float32), e) -} -func (_ fastpathT) EncMapInt8Float32V(v map[int8]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int8(k2))) - ee.WriteMapElemValue() - ee.EncodeFloat32(v[int8(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int8(k2))) - ee.EncodeFloat32(v[int8(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat32(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeFloat32(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8Float64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8Float64V(rv2i(rv).(map[int8]float64), e) -} -func (_ fastpathT) EncMapInt8Float64V(v map[int8]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int8(k2))) - ee.WriteMapElemValue() - ee.EncodeFloat64(v[int8(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int8(k2))) - ee.EncodeFloat64(v[int8(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat64(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeFloat64(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt8BoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt8BoolV(rv2i(rv).(map[int8]bool), e) -} -func (_ fastpathT) EncMapInt8BoolV(v map[int8]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int8(k2))) - ee.WriteMapElemValue() - ee.EncodeBool(v[int8(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int8(k2))) - ee.EncodeBool(v[int8(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeBool(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeBool(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16IntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16IntfV(rv2i(rv).(map[int16]interface{}), e) -} -func (_ fastpathT) EncMapInt16IntfV(v map[int16]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int16(k2))) - ee.WriteMapElemValue() - e.encode(v[int16(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int16(k2))) - e.encode(v[int16(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16StringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16StringV(rv2i(rv).(map[int16]string), e) -} -func (_ fastpathT) EncMapInt16StringV(v map[int16]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int16(k2))) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v[int16(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int16(k2))) - ee.EncodeString(cUTF8, v[int16(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeString(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16UintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16UintV(rv2i(rv).(map[int16]uint), e) -} -func (_ fastpathT) EncMapInt16UintV(v map[int16]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int16(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int16(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int16(k2))) - ee.EncodeUint(uint64(v[int16(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16Uint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16Uint8V(rv2i(rv).(map[int16]uint8), e) -} -func (_ fastpathT) EncMapInt16Uint8V(v map[int16]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int16(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int16(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int16(k2))) - ee.EncodeUint(uint64(v[int16(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16Uint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16Uint16V(rv2i(rv).(map[int16]uint16), e) -} -func (_ fastpathT) EncMapInt16Uint16V(v map[int16]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int16(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int16(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int16(k2))) - ee.EncodeUint(uint64(v[int16(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16Uint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16Uint32V(rv2i(rv).(map[int16]uint32), e) -} -func (_ fastpathT) EncMapInt16Uint32V(v map[int16]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int16(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int16(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int16(k2))) - ee.EncodeUint(uint64(v[int16(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16Uint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16Uint64V(rv2i(rv).(map[int16]uint64), e) -} -func (_ fastpathT) EncMapInt16Uint64V(v map[int16]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int16(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int16(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int16(k2))) - ee.EncodeUint(uint64(v[int16(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16UintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16UintptrV(rv2i(rv).(map[int16]uintptr), e) -} -func (_ fastpathT) EncMapInt16UintptrV(v map[int16]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int16(k2))) - ee.WriteMapElemValue() - e.encode(v[int16(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int16(k2))) - e.encode(v[int16(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16IntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16IntV(rv2i(rv).(map[int16]int), e) -} -func (_ fastpathT) EncMapInt16IntV(v map[int16]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int16(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int16(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int16(k2))) - ee.EncodeInt(int64(v[int16(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16Int8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16Int8V(rv2i(rv).(map[int16]int8), e) -} -func (_ fastpathT) EncMapInt16Int8V(v map[int16]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int16(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int16(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int16(k2))) - ee.EncodeInt(int64(v[int16(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16Int16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16Int16V(rv2i(rv).(map[int16]int16), e) -} -func (_ fastpathT) EncMapInt16Int16V(v map[int16]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int16(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int16(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int16(k2))) - ee.EncodeInt(int64(v[int16(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16Int32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16Int32V(rv2i(rv).(map[int16]int32), e) -} -func (_ fastpathT) EncMapInt16Int32V(v map[int16]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int16(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int16(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int16(k2))) - ee.EncodeInt(int64(v[int16(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16Int64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16Int64V(rv2i(rv).(map[int16]int64), e) -} -func (_ fastpathT) EncMapInt16Int64V(v map[int16]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int16(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int16(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int16(k2))) - ee.EncodeInt(int64(v[int16(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16Float32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16Float32V(rv2i(rv).(map[int16]float32), e) -} -func (_ fastpathT) EncMapInt16Float32V(v map[int16]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int16(k2))) - ee.WriteMapElemValue() - ee.EncodeFloat32(v[int16(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int16(k2))) - ee.EncodeFloat32(v[int16(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat32(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeFloat32(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16Float64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16Float64V(rv2i(rv).(map[int16]float64), e) -} -func (_ fastpathT) EncMapInt16Float64V(v map[int16]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int16(k2))) - ee.WriteMapElemValue() - ee.EncodeFloat64(v[int16(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int16(k2))) - ee.EncodeFloat64(v[int16(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat64(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeFloat64(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt16BoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt16BoolV(rv2i(rv).(map[int16]bool), e) -} -func (_ fastpathT) EncMapInt16BoolV(v map[int16]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int16(k2))) - ee.WriteMapElemValue() - ee.EncodeBool(v[int16(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int16(k2))) - ee.EncodeBool(v[int16(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeBool(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeBool(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32IntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32IntfV(rv2i(rv).(map[int32]interface{}), e) -} -func (_ fastpathT) EncMapInt32IntfV(v map[int32]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int32(k2))) - ee.WriteMapElemValue() - e.encode(v[int32(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int32(k2))) - e.encode(v[int32(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32StringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32StringV(rv2i(rv).(map[int32]string), e) -} -func (_ fastpathT) EncMapInt32StringV(v map[int32]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int32(k2))) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v[int32(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int32(k2))) - ee.EncodeString(cUTF8, v[int32(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeString(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32UintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32UintV(rv2i(rv).(map[int32]uint), e) -} -func (_ fastpathT) EncMapInt32UintV(v map[int32]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int32(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int32(k2))) - ee.EncodeUint(uint64(v[int32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32Uint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32Uint8V(rv2i(rv).(map[int32]uint8), e) -} -func (_ fastpathT) EncMapInt32Uint8V(v map[int32]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int32(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int32(k2))) - ee.EncodeUint(uint64(v[int32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32Uint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32Uint16V(rv2i(rv).(map[int32]uint16), e) -} -func (_ fastpathT) EncMapInt32Uint16V(v map[int32]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int32(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int32(k2))) - ee.EncodeUint(uint64(v[int32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32Uint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32Uint32V(rv2i(rv).(map[int32]uint32), e) -} -func (_ fastpathT) EncMapInt32Uint32V(v map[int32]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int32(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int32(k2))) - ee.EncodeUint(uint64(v[int32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32Uint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32Uint64V(rv2i(rv).(map[int32]uint64), e) -} -func (_ fastpathT) EncMapInt32Uint64V(v map[int32]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int32(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int32(k2))) - ee.EncodeUint(uint64(v[int32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32UintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32UintptrV(rv2i(rv).(map[int32]uintptr), e) -} -func (_ fastpathT) EncMapInt32UintptrV(v map[int32]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int32(k2))) - ee.WriteMapElemValue() - e.encode(v[int32(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int32(k2))) - e.encode(v[int32(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32IntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32IntV(rv2i(rv).(map[int32]int), e) -} -func (_ fastpathT) EncMapInt32IntV(v map[int32]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int32(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int32(k2))) - ee.EncodeInt(int64(v[int32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32Int8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32Int8V(rv2i(rv).(map[int32]int8), e) -} -func (_ fastpathT) EncMapInt32Int8V(v map[int32]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int32(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int32(k2))) - ee.EncodeInt(int64(v[int32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32Int16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32Int16V(rv2i(rv).(map[int32]int16), e) -} -func (_ fastpathT) EncMapInt32Int16V(v map[int32]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int32(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int32(k2))) - ee.EncodeInt(int64(v[int32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32Int32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32Int32V(rv2i(rv).(map[int32]int32), e) -} -func (_ fastpathT) EncMapInt32Int32V(v map[int32]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int32(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int32(k2))) - ee.EncodeInt(int64(v[int32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32Int64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32Int64V(rv2i(rv).(map[int32]int64), e) -} -func (_ fastpathT) EncMapInt32Int64V(v map[int32]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int32(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int32(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int32(k2))) - ee.EncodeInt(int64(v[int32(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32Float32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32Float32V(rv2i(rv).(map[int32]float32), e) -} -func (_ fastpathT) EncMapInt32Float32V(v map[int32]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int32(k2))) - ee.WriteMapElemValue() - ee.EncodeFloat32(v[int32(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int32(k2))) - ee.EncodeFloat32(v[int32(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat32(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeFloat32(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32Float64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32Float64V(rv2i(rv).(map[int32]float64), e) -} -func (_ fastpathT) EncMapInt32Float64V(v map[int32]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int32(k2))) - ee.WriteMapElemValue() - ee.EncodeFloat64(v[int32(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int32(k2))) - ee.EncodeFloat64(v[int32(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat64(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeFloat64(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt32BoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt32BoolV(rv2i(rv).(map[int32]bool), e) -} -func (_ fastpathT) EncMapInt32BoolV(v map[int32]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int32(k2))) - ee.WriteMapElemValue() - ee.EncodeBool(v[int32(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int32(k2))) - ee.EncodeBool(v[int32(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeBool(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeBool(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64IntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64IntfV(rv2i(rv).(map[int64]interface{}), e) -} -func (_ fastpathT) EncMapInt64IntfV(v map[int64]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int64(k2))) - ee.WriteMapElemValue() - e.encode(v[int64(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int64(k2))) - e.encode(v[int64(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64StringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64StringV(rv2i(rv).(map[int64]string), e) -} -func (_ fastpathT) EncMapInt64StringV(v map[int64]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int64(k2))) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v[int64(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int64(k2))) - ee.EncodeString(cUTF8, v[int64(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeString(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64UintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64UintV(rv2i(rv).(map[int64]uint), e) -} -func (_ fastpathT) EncMapInt64UintV(v map[int64]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int64(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int64(k2))) - ee.EncodeUint(uint64(v[int64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64Uint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64Uint8V(rv2i(rv).(map[int64]uint8), e) -} -func (_ fastpathT) EncMapInt64Uint8V(v map[int64]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int64(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int64(k2))) - ee.EncodeUint(uint64(v[int64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64Uint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64Uint16V(rv2i(rv).(map[int64]uint16), e) -} -func (_ fastpathT) EncMapInt64Uint16V(v map[int64]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int64(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int64(k2))) - ee.EncodeUint(uint64(v[int64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64Uint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64Uint32V(rv2i(rv).(map[int64]uint32), e) -} -func (_ fastpathT) EncMapInt64Uint32V(v map[int64]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int64(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int64(k2))) - ee.EncodeUint(uint64(v[int64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64Uint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64Uint64V(rv2i(rv).(map[int64]uint64), e) -} -func (_ fastpathT) EncMapInt64Uint64V(v map[int64]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int64(k2))) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[int64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int64(k2))) - ee.EncodeUint(uint64(v[int64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64UintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64UintptrV(rv2i(rv).(map[int64]uintptr), e) -} -func (_ fastpathT) EncMapInt64UintptrV(v map[int64]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int64(k2))) - ee.WriteMapElemValue() - e.encode(v[int64(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int64(k2))) - e.encode(v[int64(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64IntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64IntV(rv2i(rv).(map[int64]int), e) -} -func (_ fastpathT) EncMapInt64IntV(v map[int64]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int64(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int64(k2))) - ee.EncodeInt(int64(v[int64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64Int8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64Int8V(rv2i(rv).(map[int64]int8), e) -} -func (_ fastpathT) EncMapInt64Int8V(v map[int64]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int64(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int64(k2))) - ee.EncodeInt(int64(v[int64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64Int16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64Int16V(rv2i(rv).(map[int64]int16), e) -} -func (_ fastpathT) EncMapInt64Int16V(v map[int64]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int64(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int64(k2))) - ee.EncodeInt(int64(v[int64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64Int32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64Int32V(rv2i(rv).(map[int64]int32), e) -} -func (_ fastpathT) EncMapInt64Int32V(v map[int64]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int64(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int64(k2))) - ee.EncodeInt(int64(v[int64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64Int64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64Int64V(rv2i(rv).(map[int64]int64), e) -} -func (_ fastpathT) EncMapInt64Int64V(v map[int64]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int64(k2))) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[int64(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int64(k2))) - ee.EncodeInt(int64(v[int64(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64Float32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64Float32V(rv2i(rv).(map[int64]float32), e) -} -func (_ fastpathT) EncMapInt64Float32V(v map[int64]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int64(k2))) - ee.WriteMapElemValue() - ee.EncodeFloat32(v[int64(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int64(k2))) - ee.EncodeFloat32(v[int64(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat32(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeFloat32(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64Float64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64Float64V(rv2i(rv).(map[int64]float64), e) -} -func (_ fastpathT) EncMapInt64Float64V(v map[int64]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int64(k2))) - ee.WriteMapElemValue() - ee.EncodeFloat64(v[int64(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int64(k2))) - ee.EncodeFloat64(v[int64(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat64(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeFloat64(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapInt64BoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapInt64BoolV(rv2i(rv).(map[int64]bool), e) -} -func (_ fastpathT) EncMapInt64BoolV(v map[int64]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]int64, len(v)) - var i int - for k, _ := range v { - v2[i] = int64(k) - i++ - } - sort.Sort(intSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeInt(int64(int64(k2))) - ee.WriteMapElemValue() - ee.EncodeBool(v[int64(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeInt(int64(int64(k2))) - ee.EncodeBool(v[int64(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeInt(int64(k2)) - ee.WriteMapElemValue() - ee.EncodeBool(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeBool(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolIntfR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolIntfV(rv2i(rv).(map[bool]interface{}), e) -} -func (_ fastpathT) EncMapBoolIntfV(v map[bool]interface{}, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i int - for k, _ := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeBool(bool(k2)) - ee.WriteMapElemValue() - e.encode(v[bool(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeBool(bool(k2)) - e.encode(v[bool(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeBool(k2) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeBool(k2) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolStringR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolStringV(rv2i(rv).(map[bool]string), e) -} -func (_ fastpathT) EncMapBoolStringV(v map[bool]string, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i int - for k, _ := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeBool(bool(k2)) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v[bool(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeBool(bool(k2)) - ee.EncodeString(cUTF8, v[bool(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeBool(k2) - ee.WriteMapElemValue() - ee.EncodeString(cUTF8, v2) - } - } else { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeString(cUTF8, v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolUintR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolUintV(rv2i(rv).(map[bool]uint), e) -} -func (_ fastpathT) EncMapBoolUintV(v map[bool]uint, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i int - for k, _ := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeBool(bool(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[bool(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeBool(bool(k2)) - ee.EncodeUint(uint64(v[bool(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeBool(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolUint8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolUint8V(rv2i(rv).(map[bool]uint8), e) -} -func (_ fastpathT) EncMapBoolUint8V(v map[bool]uint8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i int - for k, _ := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeBool(bool(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[bool(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeBool(bool(k2)) - ee.EncodeUint(uint64(v[bool(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeBool(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolUint16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolUint16V(rv2i(rv).(map[bool]uint16), e) -} -func (_ fastpathT) EncMapBoolUint16V(v map[bool]uint16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i int - for k, _ := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeBool(bool(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[bool(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeBool(bool(k2)) - ee.EncodeUint(uint64(v[bool(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeBool(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolUint32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolUint32V(rv2i(rv).(map[bool]uint32), e) -} -func (_ fastpathT) EncMapBoolUint32V(v map[bool]uint32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i int - for k, _ := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeBool(bool(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[bool(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeBool(bool(k2)) - ee.EncodeUint(uint64(v[bool(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeBool(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolUint64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolUint64V(rv2i(rv).(map[bool]uint64), e) -} -func (_ fastpathT) EncMapBoolUint64V(v map[bool]uint64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i int - for k, _ := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeBool(bool(k2)) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v[bool(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeBool(bool(k2)) - ee.EncodeUint(uint64(v[bool(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeBool(k2) - ee.WriteMapElemValue() - ee.EncodeUint(uint64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeUint(uint64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolUintptrR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolUintptrV(rv2i(rv).(map[bool]uintptr), e) -} -func (_ fastpathT) EncMapBoolUintptrV(v map[bool]uintptr, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i int - for k, _ := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeBool(bool(k2)) - ee.WriteMapElemValue() - e.encode(v[bool(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeBool(bool(k2)) - e.encode(v[bool(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeBool(k2) - ee.WriteMapElemValue() - e.encode(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeBool(k2) - e.encode(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolIntR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolIntV(rv2i(rv).(map[bool]int), e) -} -func (_ fastpathT) EncMapBoolIntV(v map[bool]int, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i int - for k, _ := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeBool(bool(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[bool(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeBool(bool(k2)) - ee.EncodeInt(int64(v[bool(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeBool(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolInt8R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolInt8V(rv2i(rv).(map[bool]int8), e) -} -func (_ fastpathT) EncMapBoolInt8V(v map[bool]int8, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i int - for k, _ := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeBool(bool(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[bool(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeBool(bool(k2)) - ee.EncodeInt(int64(v[bool(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeBool(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolInt16R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolInt16V(rv2i(rv).(map[bool]int16), e) -} -func (_ fastpathT) EncMapBoolInt16V(v map[bool]int16, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i int - for k, _ := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeBool(bool(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[bool(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeBool(bool(k2)) - ee.EncodeInt(int64(v[bool(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeBool(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolInt32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolInt32V(rv2i(rv).(map[bool]int32), e) -} -func (_ fastpathT) EncMapBoolInt32V(v map[bool]int32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i int - for k, _ := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeBool(bool(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[bool(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeBool(bool(k2)) - ee.EncodeInt(int64(v[bool(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeBool(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolInt64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolInt64V(rv2i(rv).(map[bool]int64), e) -} -func (_ fastpathT) EncMapBoolInt64V(v map[bool]int64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i int - for k, _ := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeBool(bool(k2)) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v[bool(k2)])) - } - } else { - for _, k2 := range v2 { - ee.EncodeBool(bool(k2)) - ee.EncodeInt(int64(v[bool(k2)])) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeBool(k2) - ee.WriteMapElemValue() - ee.EncodeInt(int64(v2)) - } - } else { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeInt(int64(v2)) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolFloat32R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolFloat32V(rv2i(rv).(map[bool]float32), e) -} -func (_ fastpathT) EncMapBoolFloat32V(v map[bool]float32, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i int - for k, _ := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeBool(bool(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat32(v[bool(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeBool(bool(k2)) - ee.EncodeFloat32(v[bool(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeBool(k2) - ee.WriteMapElemValue() - ee.EncodeFloat32(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeFloat32(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolFloat64R(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolFloat64V(rv2i(rv).(map[bool]float64), e) -} -func (_ fastpathT) EncMapBoolFloat64V(v map[bool]float64, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i int - for k, _ := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeBool(bool(k2)) - ee.WriteMapElemValue() - ee.EncodeFloat64(v[bool(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeBool(bool(k2)) - ee.EncodeFloat64(v[bool(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeBool(k2) - ee.WriteMapElemValue() - ee.EncodeFloat64(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeFloat64(v2) - } - } - } - ee.WriteMapEnd() -} - -func (e *Encoder) fastpathEncMapBoolBoolR(f *codecFnInfo, rv reflect.Value) { - fastpathTV.EncMapBoolBoolV(rv2i(rv).(map[bool]bool), e) -} -func (_ fastpathT) EncMapBoolBoolV(v map[bool]bool, e *Encoder) { - if v == nil { - e.e.EncodeNil() - return - } - ee, esep := e.e, e.hh.hasElemSeparators() - ee.WriteMapStart(len(v)) - if e.h.Canonical { - v2 := make([]bool, len(v)) - var i int - for k, _ := range v { - v2[i] = bool(k) - i++ - } - sort.Sort(boolSlice(v2)) - if esep { - for _, k2 := range v2 { - ee.WriteMapElemKey() - ee.EncodeBool(bool(k2)) - ee.WriteMapElemValue() - ee.EncodeBool(v[bool(k2)]) - } - } else { - for _, k2 := range v2 { - ee.EncodeBool(bool(k2)) - ee.EncodeBool(v[bool(k2)]) - } - } - } else { - if esep { - for k2, v2 := range v { - ee.WriteMapElemKey() - ee.EncodeBool(k2) - ee.WriteMapElemValue() - ee.EncodeBool(v2) - } - } else { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeBool(v2) - } - } - } - ee.WriteMapEnd() -} - -// -- decode - -// -- -- fast path type switch -func fastpathDecodeTypeSwitch(iv interface{}, d *Decoder) bool { - var changed bool - switch v := iv.(type) { - - case []interface{}: - var v2 []interface{} - v2, changed = fastpathTV.DecSliceIntfV(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]interface{}: - var v2 []interface{} - v2, changed = fastpathTV.DecSliceIntfV(*v, true, d) - if changed { - *v = v2 - } - case []string: - var v2 []string - v2, changed = fastpathTV.DecSliceStringV(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]string: - var v2 []string - v2, changed = fastpathTV.DecSliceStringV(*v, true, d) - if changed { - *v = v2 - } - case []float32: - var v2 []float32 - v2, changed = fastpathTV.DecSliceFloat32V(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]float32: - var v2 []float32 - v2, changed = fastpathTV.DecSliceFloat32V(*v, true, d) - if changed { - *v = v2 - } - case []float64: - var v2 []float64 - v2, changed = fastpathTV.DecSliceFloat64V(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]float64: - var v2 []float64 - v2, changed = fastpathTV.DecSliceFloat64V(*v, true, d) - if changed { - *v = v2 - } - case []uint: - var v2 []uint - v2, changed = fastpathTV.DecSliceUintV(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]uint: - var v2 []uint - v2, changed = fastpathTV.DecSliceUintV(*v, true, d) - if changed { - *v = v2 - } - case []uint16: - var v2 []uint16 - v2, changed = fastpathTV.DecSliceUint16V(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]uint16: - var v2 []uint16 - v2, changed = fastpathTV.DecSliceUint16V(*v, true, d) - if changed { - *v = v2 - } - case []uint32: - var v2 []uint32 - v2, changed = fastpathTV.DecSliceUint32V(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]uint32: - var v2 []uint32 - v2, changed = fastpathTV.DecSliceUint32V(*v, true, d) - if changed { - *v = v2 - } - case []uint64: - var v2 []uint64 - v2, changed = fastpathTV.DecSliceUint64V(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]uint64: - var v2 []uint64 - v2, changed = fastpathTV.DecSliceUint64V(*v, true, d) - if changed { - *v = v2 - } - case []uintptr: - var v2 []uintptr - v2, changed = fastpathTV.DecSliceUintptrV(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]uintptr: - var v2 []uintptr - v2, changed = fastpathTV.DecSliceUintptrV(*v, true, d) - if changed { - *v = v2 - } - case []int: - var v2 []int - v2, changed = fastpathTV.DecSliceIntV(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]int: - var v2 []int - v2, changed = fastpathTV.DecSliceIntV(*v, true, d) - if changed { - *v = v2 - } - case []int8: - var v2 []int8 - v2, changed = fastpathTV.DecSliceInt8V(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]int8: - var v2 []int8 - v2, changed = fastpathTV.DecSliceInt8V(*v, true, d) - if changed { - *v = v2 - } - case []int16: - var v2 []int16 - v2, changed = fastpathTV.DecSliceInt16V(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]int16: - var v2 []int16 - v2, changed = fastpathTV.DecSliceInt16V(*v, true, d) - if changed { - *v = v2 - } - case []int32: - var v2 []int32 - v2, changed = fastpathTV.DecSliceInt32V(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]int32: - var v2 []int32 - v2, changed = fastpathTV.DecSliceInt32V(*v, true, d) - if changed { - *v = v2 - } - case []int64: - var v2 []int64 - v2, changed = fastpathTV.DecSliceInt64V(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]int64: - var v2 []int64 - v2, changed = fastpathTV.DecSliceInt64V(*v, true, d) - if changed { - *v = v2 - } - case []bool: - var v2 []bool - v2, changed = fastpathTV.DecSliceBoolV(v, false, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - case *[]bool: - var v2 []bool - v2, changed = fastpathTV.DecSliceBoolV(*v, true, d) - if changed { - *v = v2 - } - - case map[interface{}]interface{}: - fastpathTV.DecMapIntfIntfV(v, false, d) - case *map[interface{}]interface{}: - var v2 map[interface{}]interface{} - v2, changed = fastpathTV.DecMapIntfIntfV(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]string: - fastpathTV.DecMapIntfStringV(v, false, d) - case *map[interface{}]string: - var v2 map[interface{}]string - v2, changed = fastpathTV.DecMapIntfStringV(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]uint: - fastpathTV.DecMapIntfUintV(v, false, d) - case *map[interface{}]uint: - var v2 map[interface{}]uint - v2, changed = fastpathTV.DecMapIntfUintV(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]uint8: - fastpathTV.DecMapIntfUint8V(v, false, d) - case *map[interface{}]uint8: - var v2 map[interface{}]uint8 - v2, changed = fastpathTV.DecMapIntfUint8V(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]uint16: - fastpathTV.DecMapIntfUint16V(v, false, d) - case *map[interface{}]uint16: - var v2 map[interface{}]uint16 - v2, changed = fastpathTV.DecMapIntfUint16V(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]uint32: - fastpathTV.DecMapIntfUint32V(v, false, d) - case *map[interface{}]uint32: - var v2 map[interface{}]uint32 - v2, changed = fastpathTV.DecMapIntfUint32V(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]uint64: - fastpathTV.DecMapIntfUint64V(v, false, d) - case *map[interface{}]uint64: - var v2 map[interface{}]uint64 - v2, changed = fastpathTV.DecMapIntfUint64V(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]uintptr: - fastpathTV.DecMapIntfUintptrV(v, false, d) - case *map[interface{}]uintptr: - var v2 map[interface{}]uintptr - v2, changed = fastpathTV.DecMapIntfUintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]int: - fastpathTV.DecMapIntfIntV(v, false, d) - case *map[interface{}]int: - var v2 map[interface{}]int - v2, changed = fastpathTV.DecMapIntfIntV(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]int8: - fastpathTV.DecMapIntfInt8V(v, false, d) - case *map[interface{}]int8: - var v2 map[interface{}]int8 - v2, changed = fastpathTV.DecMapIntfInt8V(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]int16: - fastpathTV.DecMapIntfInt16V(v, false, d) - case *map[interface{}]int16: - var v2 map[interface{}]int16 - v2, changed = fastpathTV.DecMapIntfInt16V(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]int32: - fastpathTV.DecMapIntfInt32V(v, false, d) - case *map[interface{}]int32: - var v2 map[interface{}]int32 - v2, changed = fastpathTV.DecMapIntfInt32V(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]int64: - fastpathTV.DecMapIntfInt64V(v, false, d) - case *map[interface{}]int64: - var v2 map[interface{}]int64 - v2, changed = fastpathTV.DecMapIntfInt64V(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]float32: - fastpathTV.DecMapIntfFloat32V(v, false, d) - case *map[interface{}]float32: - var v2 map[interface{}]float32 - v2, changed = fastpathTV.DecMapIntfFloat32V(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]float64: - fastpathTV.DecMapIntfFloat64V(v, false, d) - case *map[interface{}]float64: - var v2 map[interface{}]float64 - v2, changed = fastpathTV.DecMapIntfFloat64V(*v, true, d) - if changed { - *v = v2 - } - case map[interface{}]bool: - fastpathTV.DecMapIntfBoolV(v, false, d) - case *map[interface{}]bool: - var v2 map[interface{}]bool - v2, changed = fastpathTV.DecMapIntfBoolV(*v, true, d) - if changed { - *v = v2 - } - case map[string]interface{}: - fastpathTV.DecMapStringIntfV(v, false, d) - case *map[string]interface{}: - var v2 map[string]interface{} - v2, changed = fastpathTV.DecMapStringIntfV(*v, true, d) - if changed { - *v = v2 - } - case map[string]string: - fastpathTV.DecMapStringStringV(v, false, d) - case *map[string]string: - var v2 map[string]string - v2, changed = fastpathTV.DecMapStringStringV(*v, true, d) - if changed { - *v = v2 - } - case map[string]uint: - fastpathTV.DecMapStringUintV(v, false, d) - case *map[string]uint: - var v2 map[string]uint - v2, changed = fastpathTV.DecMapStringUintV(*v, true, d) - if changed { - *v = v2 - } - case map[string]uint8: - fastpathTV.DecMapStringUint8V(v, false, d) - case *map[string]uint8: - var v2 map[string]uint8 - v2, changed = fastpathTV.DecMapStringUint8V(*v, true, d) - if changed { - *v = v2 - } - case map[string]uint16: - fastpathTV.DecMapStringUint16V(v, false, d) - case *map[string]uint16: - var v2 map[string]uint16 - v2, changed = fastpathTV.DecMapStringUint16V(*v, true, d) - if changed { - *v = v2 - } - case map[string]uint32: - fastpathTV.DecMapStringUint32V(v, false, d) - case *map[string]uint32: - var v2 map[string]uint32 - v2, changed = fastpathTV.DecMapStringUint32V(*v, true, d) - if changed { - *v = v2 - } - case map[string]uint64: - fastpathTV.DecMapStringUint64V(v, false, d) - case *map[string]uint64: - var v2 map[string]uint64 - v2, changed = fastpathTV.DecMapStringUint64V(*v, true, d) - if changed { - *v = v2 - } - case map[string]uintptr: - fastpathTV.DecMapStringUintptrV(v, false, d) - case *map[string]uintptr: - var v2 map[string]uintptr - v2, changed = fastpathTV.DecMapStringUintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[string]int: - fastpathTV.DecMapStringIntV(v, false, d) - case *map[string]int: - var v2 map[string]int - v2, changed = fastpathTV.DecMapStringIntV(*v, true, d) - if changed { - *v = v2 - } - case map[string]int8: - fastpathTV.DecMapStringInt8V(v, false, d) - case *map[string]int8: - var v2 map[string]int8 - v2, changed = fastpathTV.DecMapStringInt8V(*v, true, d) - if changed { - *v = v2 - } - case map[string]int16: - fastpathTV.DecMapStringInt16V(v, false, d) - case *map[string]int16: - var v2 map[string]int16 - v2, changed = fastpathTV.DecMapStringInt16V(*v, true, d) - if changed { - *v = v2 - } - case map[string]int32: - fastpathTV.DecMapStringInt32V(v, false, d) - case *map[string]int32: - var v2 map[string]int32 - v2, changed = fastpathTV.DecMapStringInt32V(*v, true, d) - if changed { - *v = v2 - } - case map[string]int64: - fastpathTV.DecMapStringInt64V(v, false, d) - case *map[string]int64: - var v2 map[string]int64 - v2, changed = fastpathTV.DecMapStringInt64V(*v, true, d) - if changed { - *v = v2 - } - case map[string]float32: - fastpathTV.DecMapStringFloat32V(v, false, d) - case *map[string]float32: - var v2 map[string]float32 - v2, changed = fastpathTV.DecMapStringFloat32V(*v, true, d) - if changed { - *v = v2 - } - case map[string]float64: - fastpathTV.DecMapStringFloat64V(v, false, d) - case *map[string]float64: - var v2 map[string]float64 - v2, changed = fastpathTV.DecMapStringFloat64V(*v, true, d) - if changed { - *v = v2 - } - case map[string]bool: - fastpathTV.DecMapStringBoolV(v, false, d) - case *map[string]bool: - var v2 map[string]bool - v2, changed = fastpathTV.DecMapStringBoolV(*v, true, d) - if changed { - *v = v2 - } - case map[float32]interface{}: - fastpathTV.DecMapFloat32IntfV(v, false, d) - case *map[float32]interface{}: - var v2 map[float32]interface{} - v2, changed = fastpathTV.DecMapFloat32IntfV(*v, true, d) - if changed { - *v = v2 - } - case map[float32]string: - fastpathTV.DecMapFloat32StringV(v, false, d) - case *map[float32]string: - var v2 map[float32]string - v2, changed = fastpathTV.DecMapFloat32StringV(*v, true, d) - if changed { - *v = v2 - } - case map[float32]uint: - fastpathTV.DecMapFloat32UintV(v, false, d) - case *map[float32]uint: - var v2 map[float32]uint - v2, changed = fastpathTV.DecMapFloat32UintV(*v, true, d) - if changed { - *v = v2 - } - case map[float32]uint8: - fastpathTV.DecMapFloat32Uint8V(v, false, d) - case *map[float32]uint8: - var v2 map[float32]uint8 - v2, changed = fastpathTV.DecMapFloat32Uint8V(*v, true, d) - if changed { - *v = v2 - } - case map[float32]uint16: - fastpathTV.DecMapFloat32Uint16V(v, false, d) - case *map[float32]uint16: - var v2 map[float32]uint16 - v2, changed = fastpathTV.DecMapFloat32Uint16V(*v, true, d) - if changed { - *v = v2 - } - case map[float32]uint32: - fastpathTV.DecMapFloat32Uint32V(v, false, d) - case *map[float32]uint32: - var v2 map[float32]uint32 - v2, changed = fastpathTV.DecMapFloat32Uint32V(*v, true, d) - if changed { - *v = v2 - } - case map[float32]uint64: - fastpathTV.DecMapFloat32Uint64V(v, false, d) - case *map[float32]uint64: - var v2 map[float32]uint64 - v2, changed = fastpathTV.DecMapFloat32Uint64V(*v, true, d) - if changed { - *v = v2 - } - case map[float32]uintptr: - fastpathTV.DecMapFloat32UintptrV(v, false, d) - case *map[float32]uintptr: - var v2 map[float32]uintptr - v2, changed = fastpathTV.DecMapFloat32UintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[float32]int: - fastpathTV.DecMapFloat32IntV(v, false, d) - case *map[float32]int: - var v2 map[float32]int - v2, changed = fastpathTV.DecMapFloat32IntV(*v, true, d) - if changed { - *v = v2 - } - case map[float32]int8: - fastpathTV.DecMapFloat32Int8V(v, false, d) - case *map[float32]int8: - var v2 map[float32]int8 - v2, changed = fastpathTV.DecMapFloat32Int8V(*v, true, d) - if changed { - *v = v2 - } - case map[float32]int16: - fastpathTV.DecMapFloat32Int16V(v, false, d) - case *map[float32]int16: - var v2 map[float32]int16 - v2, changed = fastpathTV.DecMapFloat32Int16V(*v, true, d) - if changed { - *v = v2 - } - case map[float32]int32: - fastpathTV.DecMapFloat32Int32V(v, false, d) - case *map[float32]int32: - var v2 map[float32]int32 - v2, changed = fastpathTV.DecMapFloat32Int32V(*v, true, d) - if changed { - *v = v2 - } - case map[float32]int64: - fastpathTV.DecMapFloat32Int64V(v, false, d) - case *map[float32]int64: - var v2 map[float32]int64 - v2, changed = fastpathTV.DecMapFloat32Int64V(*v, true, d) - if changed { - *v = v2 - } - case map[float32]float32: - fastpathTV.DecMapFloat32Float32V(v, false, d) - case *map[float32]float32: - var v2 map[float32]float32 - v2, changed = fastpathTV.DecMapFloat32Float32V(*v, true, d) - if changed { - *v = v2 - } - case map[float32]float64: - fastpathTV.DecMapFloat32Float64V(v, false, d) - case *map[float32]float64: - var v2 map[float32]float64 - v2, changed = fastpathTV.DecMapFloat32Float64V(*v, true, d) - if changed { - *v = v2 - } - case map[float32]bool: - fastpathTV.DecMapFloat32BoolV(v, false, d) - case *map[float32]bool: - var v2 map[float32]bool - v2, changed = fastpathTV.DecMapFloat32BoolV(*v, true, d) - if changed { - *v = v2 - } - case map[float64]interface{}: - fastpathTV.DecMapFloat64IntfV(v, false, d) - case *map[float64]interface{}: - var v2 map[float64]interface{} - v2, changed = fastpathTV.DecMapFloat64IntfV(*v, true, d) - if changed { - *v = v2 - } - case map[float64]string: - fastpathTV.DecMapFloat64StringV(v, false, d) - case *map[float64]string: - var v2 map[float64]string - v2, changed = fastpathTV.DecMapFloat64StringV(*v, true, d) - if changed { - *v = v2 - } - case map[float64]uint: - fastpathTV.DecMapFloat64UintV(v, false, d) - case *map[float64]uint: - var v2 map[float64]uint - v2, changed = fastpathTV.DecMapFloat64UintV(*v, true, d) - if changed { - *v = v2 - } - case map[float64]uint8: - fastpathTV.DecMapFloat64Uint8V(v, false, d) - case *map[float64]uint8: - var v2 map[float64]uint8 - v2, changed = fastpathTV.DecMapFloat64Uint8V(*v, true, d) - if changed { - *v = v2 - } - case map[float64]uint16: - fastpathTV.DecMapFloat64Uint16V(v, false, d) - case *map[float64]uint16: - var v2 map[float64]uint16 - v2, changed = fastpathTV.DecMapFloat64Uint16V(*v, true, d) - if changed { - *v = v2 - } - case map[float64]uint32: - fastpathTV.DecMapFloat64Uint32V(v, false, d) - case *map[float64]uint32: - var v2 map[float64]uint32 - v2, changed = fastpathTV.DecMapFloat64Uint32V(*v, true, d) - if changed { - *v = v2 - } - case map[float64]uint64: - fastpathTV.DecMapFloat64Uint64V(v, false, d) - case *map[float64]uint64: - var v2 map[float64]uint64 - v2, changed = fastpathTV.DecMapFloat64Uint64V(*v, true, d) - if changed { - *v = v2 - } - case map[float64]uintptr: - fastpathTV.DecMapFloat64UintptrV(v, false, d) - case *map[float64]uintptr: - var v2 map[float64]uintptr - v2, changed = fastpathTV.DecMapFloat64UintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[float64]int: - fastpathTV.DecMapFloat64IntV(v, false, d) - case *map[float64]int: - var v2 map[float64]int - v2, changed = fastpathTV.DecMapFloat64IntV(*v, true, d) - if changed { - *v = v2 - } - case map[float64]int8: - fastpathTV.DecMapFloat64Int8V(v, false, d) - case *map[float64]int8: - var v2 map[float64]int8 - v2, changed = fastpathTV.DecMapFloat64Int8V(*v, true, d) - if changed { - *v = v2 - } - case map[float64]int16: - fastpathTV.DecMapFloat64Int16V(v, false, d) - case *map[float64]int16: - var v2 map[float64]int16 - v2, changed = fastpathTV.DecMapFloat64Int16V(*v, true, d) - if changed { - *v = v2 - } - case map[float64]int32: - fastpathTV.DecMapFloat64Int32V(v, false, d) - case *map[float64]int32: - var v2 map[float64]int32 - v2, changed = fastpathTV.DecMapFloat64Int32V(*v, true, d) - if changed { - *v = v2 - } - case map[float64]int64: - fastpathTV.DecMapFloat64Int64V(v, false, d) - case *map[float64]int64: - var v2 map[float64]int64 - v2, changed = fastpathTV.DecMapFloat64Int64V(*v, true, d) - if changed { - *v = v2 - } - case map[float64]float32: - fastpathTV.DecMapFloat64Float32V(v, false, d) - case *map[float64]float32: - var v2 map[float64]float32 - v2, changed = fastpathTV.DecMapFloat64Float32V(*v, true, d) - if changed { - *v = v2 - } - case map[float64]float64: - fastpathTV.DecMapFloat64Float64V(v, false, d) - case *map[float64]float64: - var v2 map[float64]float64 - v2, changed = fastpathTV.DecMapFloat64Float64V(*v, true, d) - if changed { - *v = v2 - } - case map[float64]bool: - fastpathTV.DecMapFloat64BoolV(v, false, d) - case *map[float64]bool: - var v2 map[float64]bool - v2, changed = fastpathTV.DecMapFloat64BoolV(*v, true, d) - if changed { - *v = v2 - } - case map[uint]interface{}: - fastpathTV.DecMapUintIntfV(v, false, d) - case *map[uint]interface{}: - var v2 map[uint]interface{} - v2, changed = fastpathTV.DecMapUintIntfV(*v, true, d) - if changed { - *v = v2 - } - case map[uint]string: - fastpathTV.DecMapUintStringV(v, false, d) - case *map[uint]string: - var v2 map[uint]string - v2, changed = fastpathTV.DecMapUintStringV(*v, true, d) - if changed { - *v = v2 - } - case map[uint]uint: - fastpathTV.DecMapUintUintV(v, false, d) - case *map[uint]uint: - var v2 map[uint]uint - v2, changed = fastpathTV.DecMapUintUintV(*v, true, d) - if changed { - *v = v2 - } - case map[uint]uint8: - fastpathTV.DecMapUintUint8V(v, false, d) - case *map[uint]uint8: - var v2 map[uint]uint8 - v2, changed = fastpathTV.DecMapUintUint8V(*v, true, d) - if changed { - *v = v2 - } - case map[uint]uint16: - fastpathTV.DecMapUintUint16V(v, false, d) - case *map[uint]uint16: - var v2 map[uint]uint16 - v2, changed = fastpathTV.DecMapUintUint16V(*v, true, d) - if changed { - *v = v2 - } - case map[uint]uint32: - fastpathTV.DecMapUintUint32V(v, false, d) - case *map[uint]uint32: - var v2 map[uint]uint32 - v2, changed = fastpathTV.DecMapUintUint32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint]uint64: - fastpathTV.DecMapUintUint64V(v, false, d) - case *map[uint]uint64: - var v2 map[uint]uint64 - v2, changed = fastpathTV.DecMapUintUint64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint]uintptr: - fastpathTV.DecMapUintUintptrV(v, false, d) - case *map[uint]uintptr: - var v2 map[uint]uintptr - v2, changed = fastpathTV.DecMapUintUintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[uint]int: - fastpathTV.DecMapUintIntV(v, false, d) - case *map[uint]int: - var v2 map[uint]int - v2, changed = fastpathTV.DecMapUintIntV(*v, true, d) - if changed { - *v = v2 - } - case map[uint]int8: - fastpathTV.DecMapUintInt8V(v, false, d) - case *map[uint]int8: - var v2 map[uint]int8 - v2, changed = fastpathTV.DecMapUintInt8V(*v, true, d) - if changed { - *v = v2 - } - case map[uint]int16: - fastpathTV.DecMapUintInt16V(v, false, d) - case *map[uint]int16: - var v2 map[uint]int16 - v2, changed = fastpathTV.DecMapUintInt16V(*v, true, d) - if changed { - *v = v2 - } - case map[uint]int32: - fastpathTV.DecMapUintInt32V(v, false, d) - case *map[uint]int32: - var v2 map[uint]int32 - v2, changed = fastpathTV.DecMapUintInt32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint]int64: - fastpathTV.DecMapUintInt64V(v, false, d) - case *map[uint]int64: - var v2 map[uint]int64 - v2, changed = fastpathTV.DecMapUintInt64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint]float32: - fastpathTV.DecMapUintFloat32V(v, false, d) - case *map[uint]float32: - var v2 map[uint]float32 - v2, changed = fastpathTV.DecMapUintFloat32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint]float64: - fastpathTV.DecMapUintFloat64V(v, false, d) - case *map[uint]float64: - var v2 map[uint]float64 - v2, changed = fastpathTV.DecMapUintFloat64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint]bool: - fastpathTV.DecMapUintBoolV(v, false, d) - case *map[uint]bool: - var v2 map[uint]bool - v2, changed = fastpathTV.DecMapUintBoolV(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]interface{}: - fastpathTV.DecMapUint8IntfV(v, false, d) - case *map[uint8]interface{}: - var v2 map[uint8]interface{} - v2, changed = fastpathTV.DecMapUint8IntfV(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]string: - fastpathTV.DecMapUint8StringV(v, false, d) - case *map[uint8]string: - var v2 map[uint8]string - v2, changed = fastpathTV.DecMapUint8StringV(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]uint: - fastpathTV.DecMapUint8UintV(v, false, d) - case *map[uint8]uint: - var v2 map[uint8]uint - v2, changed = fastpathTV.DecMapUint8UintV(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]uint8: - fastpathTV.DecMapUint8Uint8V(v, false, d) - case *map[uint8]uint8: - var v2 map[uint8]uint8 - v2, changed = fastpathTV.DecMapUint8Uint8V(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]uint16: - fastpathTV.DecMapUint8Uint16V(v, false, d) - case *map[uint8]uint16: - var v2 map[uint8]uint16 - v2, changed = fastpathTV.DecMapUint8Uint16V(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]uint32: - fastpathTV.DecMapUint8Uint32V(v, false, d) - case *map[uint8]uint32: - var v2 map[uint8]uint32 - v2, changed = fastpathTV.DecMapUint8Uint32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]uint64: - fastpathTV.DecMapUint8Uint64V(v, false, d) - case *map[uint8]uint64: - var v2 map[uint8]uint64 - v2, changed = fastpathTV.DecMapUint8Uint64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]uintptr: - fastpathTV.DecMapUint8UintptrV(v, false, d) - case *map[uint8]uintptr: - var v2 map[uint8]uintptr - v2, changed = fastpathTV.DecMapUint8UintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]int: - fastpathTV.DecMapUint8IntV(v, false, d) - case *map[uint8]int: - var v2 map[uint8]int - v2, changed = fastpathTV.DecMapUint8IntV(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]int8: - fastpathTV.DecMapUint8Int8V(v, false, d) - case *map[uint8]int8: - var v2 map[uint8]int8 - v2, changed = fastpathTV.DecMapUint8Int8V(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]int16: - fastpathTV.DecMapUint8Int16V(v, false, d) - case *map[uint8]int16: - var v2 map[uint8]int16 - v2, changed = fastpathTV.DecMapUint8Int16V(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]int32: - fastpathTV.DecMapUint8Int32V(v, false, d) - case *map[uint8]int32: - var v2 map[uint8]int32 - v2, changed = fastpathTV.DecMapUint8Int32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]int64: - fastpathTV.DecMapUint8Int64V(v, false, d) - case *map[uint8]int64: - var v2 map[uint8]int64 - v2, changed = fastpathTV.DecMapUint8Int64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]float32: - fastpathTV.DecMapUint8Float32V(v, false, d) - case *map[uint8]float32: - var v2 map[uint8]float32 - v2, changed = fastpathTV.DecMapUint8Float32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]float64: - fastpathTV.DecMapUint8Float64V(v, false, d) - case *map[uint8]float64: - var v2 map[uint8]float64 - v2, changed = fastpathTV.DecMapUint8Float64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint8]bool: - fastpathTV.DecMapUint8BoolV(v, false, d) - case *map[uint8]bool: - var v2 map[uint8]bool - v2, changed = fastpathTV.DecMapUint8BoolV(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]interface{}: - fastpathTV.DecMapUint16IntfV(v, false, d) - case *map[uint16]interface{}: - var v2 map[uint16]interface{} - v2, changed = fastpathTV.DecMapUint16IntfV(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]string: - fastpathTV.DecMapUint16StringV(v, false, d) - case *map[uint16]string: - var v2 map[uint16]string - v2, changed = fastpathTV.DecMapUint16StringV(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]uint: - fastpathTV.DecMapUint16UintV(v, false, d) - case *map[uint16]uint: - var v2 map[uint16]uint - v2, changed = fastpathTV.DecMapUint16UintV(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]uint8: - fastpathTV.DecMapUint16Uint8V(v, false, d) - case *map[uint16]uint8: - var v2 map[uint16]uint8 - v2, changed = fastpathTV.DecMapUint16Uint8V(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]uint16: - fastpathTV.DecMapUint16Uint16V(v, false, d) - case *map[uint16]uint16: - var v2 map[uint16]uint16 - v2, changed = fastpathTV.DecMapUint16Uint16V(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]uint32: - fastpathTV.DecMapUint16Uint32V(v, false, d) - case *map[uint16]uint32: - var v2 map[uint16]uint32 - v2, changed = fastpathTV.DecMapUint16Uint32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]uint64: - fastpathTV.DecMapUint16Uint64V(v, false, d) - case *map[uint16]uint64: - var v2 map[uint16]uint64 - v2, changed = fastpathTV.DecMapUint16Uint64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]uintptr: - fastpathTV.DecMapUint16UintptrV(v, false, d) - case *map[uint16]uintptr: - var v2 map[uint16]uintptr - v2, changed = fastpathTV.DecMapUint16UintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]int: - fastpathTV.DecMapUint16IntV(v, false, d) - case *map[uint16]int: - var v2 map[uint16]int - v2, changed = fastpathTV.DecMapUint16IntV(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]int8: - fastpathTV.DecMapUint16Int8V(v, false, d) - case *map[uint16]int8: - var v2 map[uint16]int8 - v2, changed = fastpathTV.DecMapUint16Int8V(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]int16: - fastpathTV.DecMapUint16Int16V(v, false, d) - case *map[uint16]int16: - var v2 map[uint16]int16 - v2, changed = fastpathTV.DecMapUint16Int16V(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]int32: - fastpathTV.DecMapUint16Int32V(v, false, d) - case *map[uint16]int32: - var v2 map[uint16]int32 - v2, changed = fastpathTV.DecMapUint16Int32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]int64: - fastpathTV.DecMapUint16Int64V(v, false, d) - case *map[uint16]int64: - var v2 map[uint16]int64 - v2, changed = fastpathTV.DecMapUint16Int64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]float32: - fastpathTV.DecMapUint16Float32V(v, false, d) - case *map[uint16]float32: - var v2 map[uint16]float32 - v2, changed = fastpathTV.DecMapUint16Float32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]float64: - fastpathTV.DecMapUint16Float64V(v, false, d) - case *map[uint16]float64: - var v2 map[uint16]float64 - v2, changed = fastpathTV.DecMapUint16Float64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint16]bool: - fastpathTV.DecMapUint16BoolV(v, false, d) - case *map[uint16]bool: - var v2 map[uint16]bool - v2, changed = fastpathTV.DecMapUint16BoolV(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]interface{}: - fastpathTV.DecMapUint32IntfV(v, false, d) - case *map[uint32]interface{}: - var v2 map[uint32]interface{} - v2, changed = fastpathTV.DecMapUint32IntfV(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]string: - fastpathTV.DecMapUint32StringV(v, false, d) - case *map[uint32]string: - var v2 map[uint32]string - v2, changed = fastpathTV.DecMapUint32StringV(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]uint: - fastpathTV.DecMapUint32UintV(v, false, d) - case *map[uint32]uint: - var v2 map[uint32]uint - v2, changed = fastpathTV.DecMapUint32UintV(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]uint8: - fastpathTV.DecMapUint32Uint8V(v, false, d) - case *map[uint32]uint8: - var v2 map[uint32]uint8 - v2, changed = fastpathTV.DecMapUint32Uint8V(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]uint16: - fastpathTV.DecMapUint32Uint16V(v, false, d) - case *map[uint32]uint16: - var v2 map[uint32]uint16 - v2, changed = fastpathTV.DecMapUint32Uint16V(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]uint32: - fastpathTV.DecMapUint32Uint32V(v, false, d) - case *map[uint32]uint32: - var v2 map[uint32]uint32 - v2, changed = fastpathTV.DecMapUint32Uint32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]uint64: - fastpathTV.DecMapUint32Uint64V(v, false, d) - case *map[uint32]uint64: - var v2 map[uint32]uint64 - v2, changed = fastpathTV.DecMapUint32Uint64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]uintptr: - fastpathTV.DecMapUint32UintptrV(v, false, d) - case *map[uint32]uintptr: - var v2 map[uint32]uintptr - v2, changed = fastpathTV.DecMapUint32UintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]int: - fastpathTV.DecMapUint32IntV(v, false, d) - case *map[uint32]int: - var v2 map[uint32]int - v2, changed = fastpathTV.DecMapUint32IntV(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]int8: - fastpathTV.DecMapUint32Int8V(v, false, d) - case *map[uint32]int8: - var v2 map[uint32]int8 - v2, changed = fastpathTV.DecMapUint32Int8V(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]int16: - fastpathTV.DecMapUint32Int16V(v, false, d) - case *map[uint32]int16: - var v2 map[uint32]int16 - v2, changed = fastpathTV.DecMapUint32Int16V(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]int32: - fastpathTV.DecMapUint32Int32V(v, false, d) - case *map[uint32]int32: - var v2 map[uint32]int32 - v2, changed = fastpathTV.DecMapUint32Int32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]int64: - fastpathTV.DecMapUint32Int64V(v, false, d) - case *map[uint32]int64: - var v2 map[uint32]int64 - v2, changed = fastpathTV.DecMapUint32Int64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]float32: - fastpathTV.DecMapUint32Float32V(v, false, d) - case *map[uint32]float32: - var v2 map[uint32]float32 - v2, changed = fastpathTV.DecMapUint32Float32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]float64: - fastpathTV.DecMapUint32Float64V(v, false, d) - case *map[uint32]float64: - var v2 map[uint32]float64 - v2, changed = fastpathTV.DecMapUint32Float64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint32]bool: - fastpathTV.DecMapUint32BoolV(v, false, d) - case *map[uint32]bool: - var v2 map[uint32]bool - v2, changed = fastpathTV.DecMapUint32BoolV(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]interface{}: - fastpathTV.DecMapUint64IntfV(v, false, d) - case *map[uint64]interface{}: - var v2 map[uint64]interface{} - v2, changed = fastpathTV.DecMapUint64IntfV(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]string: - fastpathTV.DecMapUint64StringV(v, false, d) - case *map[uint64]string: - var v2 map[uint64]string - v2, changed = fastpathTV.DecMapUint64StringV(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]uint: - fastpathTV.DecMapUint64UintV(v, false, d) - case *map[uint64]uint: - var v2 map[uint64]uint - v2, changed = fastpathTV.DecMapUint64UintV(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]uint8: - fastpathTV.DecMapUint64Uint8V(v, false, d) - case *map[uint64]uint8: - var v2 map[uint64]uint8 - v2, changed = fastpathTV.DecMapUint64Uint8V(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]uint16: - fastpathTV.DecMapUint64Uint16V(v, false, d) - case *map[uint64]uint16: - var v2 map[uint64]uint16 - v2, changed = fastpathTV.DecMapUint64Uint16V(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]uint32: - fastpathTV.DecMapUint64Uint32V(v, false, d) - case *map[uint64]uint32: - var v2 map[uint64]uint32 - v2, changed = fastpathTV.DecMapUint64Uint32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]uint64: - fastpathTV.DecMapUint64Uint64V(v, false, d) - case *map[uint64]uint64: - var v2 map[uint64]uint64 - v2, changed = fastpathTV.DecMapUint64Uint64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]uintptr: - fastpathTV.DecMapUint64UintptrV(v, false, d) - case *map[uint64]uintptr: - var v2 map[uint64]uintptr - v2, changed = fastpathTV.DecMapUint64UintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]int: - fastpathTV.DecMapUint64IntV(v, false, d) - case *map[uint64]int: - var v2 map[uint64]int - v2, changed = fastpathTV.DecMapUint64IntV(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]int8: - fastpathTV.DecMapUint64Int8V(v, false, d) - case *map[uint64]int8: - var v2 map[uint64]int8 - v2, changed = fastpathTV.DecMapUint64Int8V(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]int16: - fastpathTV.DecMapUint64Int16V(v, false, d) - case *map[uint64]int16: - var v2 map[uint64]int16 - v2, changed = fastpathTV.DecMapUint64Int16V(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]int32: - fastpathTV.DecMapUint64Int32V(v, false, d) - case *map[uint64]int32: - var v2 map[uint64]int32 - v2, changed = fastpathTV.DecMapUint64Int32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]int64: - fastpathTV.DecMapUint64Int64V(v, false, d) - case *map[uint64]int64: - var v2 map[uint64]int64 - v2, changed = fastpathTV.DecMapUint64Int64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]float32: - fastpathTV.DecMapUint64Float32V(v, false, d) - case *map[uint64]float32: - var v2 map[uint64]float32 - v2, changed = fastpathTV.DecMapUint64Float32V(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]float64: - fastpathTV.DecMapUint64Float64V(v, false, d) - case *map[uint64]float64: - var v2 map[uint64]float64 - v2, changed = fastpathTV.DecMapUint64Float64V(*v, true, d) - if changed { - *v = v2 - } - case map[uint64]bool: - fastpathTV.DecMapUint64BoolV(v, false, d) - case *map[uint64]bool: - var v2 map[uint64]bool - v2, changed = fastpathTV.DecMapUint64BoolV(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]interface{}: - fastpathTV.DecMapUintptrIntfV(v, false, d) - case *map[uintptr]interface{}: - var v2 map[uintptr]interface{} - v2, changed = fastpathTV.DecMapUintptrIntfV(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]string: - fastpathTV.DecMapUintptrStringV(v, false, d) - case *map[uintptr]string: - var v2 map[uintptr]string - v2, changed = fastpathTV.DecMapUintptrStringV(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]uint: - fastpathTV.DecMapUintptrUintV(v, false, d) - case *map[uintptr]uint: - var v2 map[uintptr]uint - v2, changed = fastpathTV.DecMapUintptrUintV(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]uint8: - fastpathTV.DecMapUintptrUint8V(v, false, d) - case *map[uintptr]uint8: - var v2 map[uintptr]uint8 - v2, changed = fastpathTV.DecMapUintptrUint8V(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]uint16: - fastpathTV.DecMapUintptrUint16V(v, false, d) - case *map[uintptr]uint16: - var v2 map[uintptr]uint16 - v2, changed = fastpathTV.DecMapUintptrUint16V(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]uint32: - fastpathTV.DecMapUintptrUint32V(v, false, d) - case *map[uintptr]uint32: - var v2 map[uintptr]uint32 - v2, changed = fastpathTV.DecMapUintptrUint32V(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]uint64: - fastpathTV.DecMapUintptrUint64V(v, false, d) - case *map[uintptr]uint64: - var v2 map[uintptr]uint64 - v2, changed = fastpathTV.DecMapUintptrUint64V(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]uintptr: - fastpathTV.DecMapUintptrUintptrV(v, false, d) - case *map[uintptr]uintptr: - var v2 map[uintptr]uintptr - v2, changed = fastpathTV.DecMapUintptrUintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]int: - fastpathTV.DecMapUintptrIntV(v, false, d) - case *map[uintptr]int: - var v2 map[uintptr]int - v2, changed = fastpathTV.DecMapUintptrIntV(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]int8: - fastpathTV.DecMapUintptrInt8V(v, false, d) - case *map[uintptr]int8: - var v2 map[uintptr]int8 - v2, changed = fastpathTV.DecMapUintptrInt8V(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]int16: - fastpathTV.DecMapUintptrInt16V(v, false, d) - case *map[uintptr]int16: - var v2 map[uintptr]int16 - v2, changed = fastpathTV.DecMapUintptrInt16V(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]int32: - fastpathTV.DecMapUintptrInt32V(v, false, d) - case *map[uintptr]int32: - var v2 map[uintptr]int32 - v2, changed = fastpathTV.DecMapUintptrInt32V(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]int64: - fastpathTV.DecMapUintptrInt64V(v, false, d) - case *map[uintptr]int64: - var v2 map[uintptr]int64 - v2, changed = fastpathTV.DecMapUintptrInt64V(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]float32: - fastpathTV.DecMapUintptrFloat32V(v, false, d) - case *map[uintptr]float32: - var v2 map[uintptr]float32 - v2, changed = fastpathTV.DecMapUintptrFloat32V(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]float64: - fastpathTV.DecMapUintptrFloat64V(v, false, d) - case *map[uintptr]float64: - var v2 map[uintptr]float64 - v2, changed = fastpathTV.DecMapUintptrFloat64V(*v, true, d) - if changed { - *v = v2 - } - case map[uintptr]bool: - fastpathTV.DecMapUintptrBoolV(v, false, d) - case *map[uintptr]bool: - var v2 map[uintptr]bool - v2, changed = fastpathTV.DecMapUintptrBoolV(*v, true, d) - if changed { - *v = v2 - } - case map[int]interface{}: - fastpathTV.DecMapIntIntfV(v, false, d) - case *map[int]interface{}: - var v2 map[int]interface{} - v2, changed = fastpathTV.DecMapIntIntfV(*v, true, d) - if changed { - *v = v2 - } - case map[int]string: - fastpathTV.DecMapIntStringV(v, false, d) - case *map[int]string: - var v2 map[int]string - v2, changed = fastpathTV.DecMapIntStringV(*v, true, d) - if changed { - *v = v2 - } - case map[int]uint: - fastpathTV.DecMapIntUintV(v, false, d) - case *map[int]uint: - var v2 map[int]uint - v2, changed = fastpathTV.DecMapIntUintV(*v, true, d) - if changed { - *v = v2 - } - case map[int]uint8: - fastpathTV.DecMapIntUint8V(v, false, d) - case *map[int]uint8: - var v2 map[int]uint8 - v2, changed = fastpathTV.DecMapIntUint8V(*v, true, d) - if changed { - *v = v2 - } - case map[int]uint16: - fastpathTV.DecMapIntUint16V(v, false, d) - case *map[int]uint16: - var v2 map[int]uint16 - v2, changed = fastpathTV.DecMapIntUint16V(*v, true, d) - if changed { - *v = v2 - } - case map[int]uint32: - fastpathTV.DecMapIntUint32V(v, false, d) - case *map[int]uint32: - var v2 map[int]uint32 - v2, changed = fastpathTV.DecMapIntUint32V(*v, true, d) - if changed { - *v = v2 - } - case map[int]uint64: - fastpathTV.DecMapIntUint64V(v, false, d) - case *map[int]uint64: - var v2 map[int]uint64 - v2, changed = fastpathTV.DecMapIntUint64V(*v, true, d) - if changed { - *v = v2 - } - case map[int]uintptr: - fastpathTV.DecMapIntUintptrV(v, false, d) - case *map[int]uintptr: - var v2 map[int]uintptr - v2, changed = fastpathTV.DecMapIntUintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[int]int: - fastpathTV.DecMapIntIntV(v, false, d) - case *map[int]int: - var v2 map[int]int - v2, changed = fastpathTV.DecMapIntIntV(*v, true, d) - if changed { - *v = v2 - } - case map[int]int8: - fastpathTV.DecMapIntInt8V(v, false, d) - case *map[int]int8: - var v2 map[int]int8 - v2, changed = fastpathTV.DecMapIntInt8V(*v, true, d) - if changed { - *v = v2 - } - case map[int]int16: - fastpathTV.DecMapIntInt16V(v, false, d) - case *map[int]int16: - var v2 map[int]int16 - v2, changed = fastpathTV.DecMapIntInt16V(*v, true, d) - if changed { - *v = v2 - } - case map[int]int32: - fastpathTV.DecMapIntInt32V(v, false, d) - case *map[int]int32: - var v2 map[int]int32 - v2, changed = fastpathTV.DecMapIntInt32V(*v, true, d) - if changed { - *v = v2 - } - case map[int]int64: - fastpathTV.DecMapIntInt64V(v, false, d) - case *map[int]int64: - var v2 map[int]int64 - v2, changed = fastpathTV.DecMapIntInt64V(*v, true, d) - if changed { - *v = v2 - } - case map[int]float32: - fastpathTV.DecMapIntFloat32V(v, false, d) - case *map[int]float32: - var v2 map[int]float32 - v2, changed = fastpathTV.DecMapIntFloat32V(*v, true, d) - if changed { - *v = v2 - } - case map[int]float64: - fastpathTV.DecMapIntFloat64V(v, false, d) - case *map[int]float64: - var v2 map[int]float64 - v2, changed = fastpathTV.DecMapIntFloat64V(*v, true, d) - if changed { - *v = v2 - } - case map[int]bool: - fastpathTV.DecMapIntBoolV(v, false, d) - case *map[int]bool: - var v2 map[int]bool - v2, changed = fastpathTV.DecMapIntBoolV(*v, true, d) - if changed { - *v = v2 - } - case map[int8]interface{}: - fastpathTV.DecMapInt8IntfV(v, false, d) - case *map[int8]interface{}: - var v2 map[int8]interface{} - v2, changed = fastpathTV.DecMapInt8IntfV(*v, true, d) - if changed { - *v = v2 - } - case map[int8]string: - fastpathTV.DecMapInt8StringV(v, false, d) - case *map[int8]string: - var v2 map[int8]string - v2, changed = fastpathTV.DecMapInt8StringV(*v, true, d) - if changed { - *v = v2 - } - case map[int8]uint: - fastpathTV.DecMapInt8UintV(v, false, d) - case *map[int8]uint: - var v2 map[int8]uint - v2, changed = fastpathTV.DecMapInt8UintV(*v, true, d) - if changed { - *v = v2 - } - case map[int8]uint8: - fastpathTV.DecMapInt8Uint8V(v, false, d) - case *map[int8]uint8: - var v2 map[int8]uint8 - v2, changed = fastpathTV.DecMapInt8Uint8V(*v, true, d) - if changed { - *v = v2 - } - case map[int8]uint16: - fastpathTV.DecMapInt8Uint16V(v, false, d) - case *map[int8]uint16: - var v2 map[int8]uint16 - v2, changed = fastpathTV.DecMapInt8Uint16V(*v, true, d) - if changed { - *v = v2 - } - case map[int8]uint32: - fastpathTV.DecMapInt8Uint32V(v, false, d) - case *map[int8]uint32: - var v2 map[int8]uint32 - v2, changed = fastpathTV.DecMapInt8Uint32V(*v, true, d) - if changed { - *v = v2 - } - case map[int8]uint64: - fastpathTV.DecMapInt8Uint64V(v, false, d) - case *map[int8]uint64: - var v2 map[int8]uint64 - v2, changed = fastpathTV.DecMapInt8Uint64V(*v, true, d) - if changed { - *v = v2 - } - case map[int8]uintptr: - fastpathTV.DecMapInt8UintptrV(v, false, d) - case *map[int8]uintptr: - var v2 map[int8]uintptr - v2, changed = fastpathTV.DecMapInt8UintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[int8]int: - fastpathTV.DecMapInt8IntV(v, false, d) - case *map[int8]int: - var v2 map[int8]int - v2, changed = fastpathTV.DecMapInt8IntV(*v, true, d) - if changed { - *v = v2 - } - case map[int8]int8: - fastpathTV.DecMapInt8Int8V(v, false, d) - case *map[int8]int8: - var v2 map[int8]int8 - v2, changed = fastpathTV.DecMapInt8Int8V(*v, true, d) - if changed { - *v = v2 - } - case map[int8]int16: - fastpathTV.DecMapInt8Int16V(v, false, d) - case *map[int8]int16: - var v2 map[int8]int16 - v2, changed = fastpathTV.DecMapInt8Int16V(*v, true, d) - if changed { - *v = v2 - } - case map[int8]int32: - fastpathTV.DecMapInt8Int32V(v, false, d) - case *map[int8]int32: - var v2 map[int8]int32 - v2, changed = fastpathTV.DecMapInt8Int32V(*v, true, d) - if changed { - *v = v2 - } - case map[int8]int64: - fastpathTV.DecMapInt8Int64V(v, false, d) - case *map[int8]int64: - var v2 map[int8]int64 - v2, changed = fastpathTV.DecMapInt8Int64V(*v, true, d) - if changed { - *v = v2 - } - case map[int8]float32: - fastpathTV.DecMapInt8Float32V(v, false, d) - case *map[int8]float32: - var v2 map[int8]float32 - v2, changed = fastpathTV.DecMapInt8Float32V(*v, true, d) - if changed { - *v = v2 - } - case map[int8]float64: - fastpathTV.DecMapInt8Float64V(v, false, d) - case *map[int8]float64: - var v2 map[int8]float64 - v2, changed = fastpathTV.DecMapInt8Float64V(*v, true, d) - if changed { - *v = v2 - } - case map[int8]bool: - fastpathTV.DecMapInt8BoolV(v, false, d) - case *map[int8]bool: - var v2 map[int8]bool - v2, changed = fastpathTV.DecMapInt8BoolV(*v, true, d) - if changed { - *v = v2 - } - case map[int16]interface{}: - fastpathTV.DecMapInt16IntfV(v, false, d) - case *map[int16]interface{}: - var v2 map[int16]interface{} - v2, changed = fastpathTV.DecMapInt16IntfV(*v, true, d) - if changed { - *v = v2 - } - case map[int16]string: - fastpathTV.DecMapInt16StringV(v, false, d) - case *map[int16]string: - var v2 map[int16]string - v2, changed = fastpathTV.DecMapInt16StringV(*v, true, d) - if changed { - *v = v2 - } - case map[int16]uint: - fastpathTV.DecMapInt16UintV(v, false, d) - case *map[int16]uint: - var v2 map[int16]uint - v2, changed = fastpathTV.DecMapInt16UintV(*v, true, d) - if changed { - *v = v2 - } - case map[int16]uint8: - fastpathTV.DecMapInt16Uint8V(v, false, d) - case *map[int16]uint8: - var v2 map[int16]uint8 - v2, changed = fastpathTV.DecMapInt16Uint8V(*v, true, d) - if changed { - *v = v2 - } - case map[int16]uint16: - fastpathTV.DecMapInt16Uint16V(v, false, d) - case *map[int16]uint16: - var v2 map[int16]uint16 - v2, changed = fastpathTV.DecMapInt16Uint16V(*v, true, d) - if changed { - *v = v2 - } - case map[int16]uint32: - fastpathTV.DecMapInt16Uint32V(v, false, d) - case *map[int16]uint32: - var v2 map[int16]uint32 - v2, changed = fastpathTV.DecMapInt16Uint32V(*v, true, d) - if changed { - *v = v2 - } - case map[int16]uint64: - fastpathTV.DecMapInt16Uint64V(v, false, d) - case *map[int16]uint64: - var v2 map[int16]uint64 - v2, changed = fastpathTV.DecMapInt16Uint64V(*v, true, d) - if changed { - *v = v2 - } - case map[int16]uintptr: - fastpathTV.DecMapInt16UintptrV(v, false, d) - case *map[int16]uintptr: - var v2 map[int16]uintptr - v2, changed = fastpathTV.DecMapInt16UintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[int16]int: - fastpathTV.DecMapInt16IntV(v, false, d) - case *map[int16]int: - var v2 map[int16]int - v2, changed = fastpathTV.DecMapInt16IntV(*v, true, d) - if changed { - *v = v2 - } - case map[int16]int8: - fastpathTV.DecMapInt16Int8V(v, false, d) - case *map[int16]int8: - var v2 map[int16]int8 - v2, changed = fastpathTV.DecMapInt16Int8V(*v, true, d) - if changed { - *v = v2 - } - case map[int16]int16: - fastpathTV.DecMapInt16Int16V(v, false, d) - case *map[int16]int16: - var v2 map[int16]int16 - v2, changed = fastpathTV.DecMapInt16Int16V(*v, true, d) - if changed { - *v = v2 - } - case map[int16]int32: - fastpathTV.DecMapInt16Int32V(v, false, d) - case *map[int16]int32: - var v2 map[int16]int32 - v2, changed = fastpathTV.DecMapInt16Int32V(*v, true, d) - if changed { - *v = v2 - } - case map[int16]int64: - fastpathTV.DecMapInt16Int64V(v, false, d) - case *map[int16]int64: - var v2 map[int16]int64 - v2, changed = fastpathTV.DecMapInt16Int64V(*v, true, d) - if changed { - *v = v2 - } - case map[int16]float32: - fastpathTV.DecMapInt16Float32V(v, false, d) - case *map[int16]float32: - var v2 map[int16]float32 - v2, changed = fastpathTV.DecMapInt16Float32V(*v, true, d) - if changed { - *v = v2 - } - case map[int16]float64: - fastpathTV.DecMapInt16Float64V(v, false, d) - case *map[int16]float64: - var v2 map[int16]float64 - v2, changed = fastpathTV.DecMapInt16Float64V(*v, true, d) - if changed { - *v = v2 - } - case map[int16]bool: - fastpathTV.DecMapInt16BoolV(v, false, d) - case *map[int16]bool: - var v2 map[int16]bool - v2, changed = fastpathTV.DecMapInt16BoolV(*v, true, d) - if changed { - *v = v2 - } - case map[int32]interface{}: - fastpathTV.DecMapInt32IntfV(v, false, d) - case *map[int32]interface{}: - var v2 map[int32]interface{} - v2, changed = fastpathTV.DecMapInt32IntfV(*v, true, d) - if changed { - *v = v2 - } - case map[int32]string: - fastpathTV.DecMapInt32StringV(v, false, d) - case *map[int32]string: - var v2 map[int32]string - v2, changed = fastpathTV.DecMapInt32StringV(*v, true, d) - if changed { - *v = v2 - } - case map[int32]uint: - fastpathTV.DecMapInt32UintV(v, false, d) - case *map[int32]uint: - var v2 map[int32]uint - v2, changed = fastpathTV.DecMapInt32UintV(*v, true, d) - if changed { - *v = v2 - } - case map[int32]uint8: - fastpathTV.DecMapInt32Uint8V(v, false, d) - case *map[int32]uint8: - var v2 map[int32]uint8 - v2, changed = fastpathTV.DecMapInt32Uint8V(*v, true, d) - if changed { - *v = v2 - } - case map[int32]uint16: - fastpathTV.DecMapInt32Uint16V(v, false, d) - case *map[int32]uint16: - var v2 map[int32]uint16 - v2, changed = fastpathTV.DecMapInt32Uint16V(*v, true, d) - if changed { - *v = v2 - } - case map[int32]uint32: - fastpathTV.DecMapInt32Uint32V(v, false, d) - case *map[int32]uint32: - var v2 map[int32]uint32 - v2, changed = fastpathTV.DecMapInt32Uint32V(*v, true, d) - if changed { - *v = v2 - } - case map[int32]uint64: - fastpathTV.DecMapInt32Uint64V(v, false, d) - case *map[int32]uint64: - var v2 map[int32]uint64 - v2, changed = fastpathTV.DecMapInt32Uint64V(*v, true, d) - if changed { - *v = v2 - } - case map[int32]uintptr: - fastpathTV.DecMapInt32UintptrV(v, false, d) - case *map[int32]uintptr: - var v2 map[int32]uintptr - v2, changed = fastpathTV.DecMapInt32UintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[int32]int: - fastpathTV.DecMapInt32IntV(v, false, d) - case *map[int32]int: - var v2 map[int32]int - v2, changed = fastpathTV.DecMapInt32IntV(*v, true, d) - if changed { - *v = v2 - } - case map[int32]int8: - fastpathTV.DecMapInt32Int8V(v, false, d) - case *map[int32]int8: - var v2 map[int32]int8 - v2, changed = fastpathTV.DecMapInt32Int8V(*v, true, d) - if changed { - *v = v2 - } - case map[int32]int16: - fastpathTV.DecMapInt32Int16V(v, false, d) - case *map[int32]int16: - var v2 map[int32]int16 - v2, changed = fastpathTV.DecMapInt32Int16V(*v, true, d) - if changed { - *v = v2 - } - case map[int32]int32: - fastpathTV.DecMapInt32Int32V(v, false, d) - case *map[int32]int32: - var v2 map[int32]int32 - v2, changed = fastpathTV.DecMapInt32Int32V(*v, true, d) - if changed { - *v = v2 - } - case map[int32]int64: - fastpathTV.DecMapInt32Int64V(v, false, d) - case *map[int32]int64: - var v2 map[int32]int64 - v2, changed = fastpathTV.DecMapInt32Int64V(*v, true, d) - if changed { - *v = v2 - } - case map[int32]float32: - fastpathTV.DecMapInt32Float32V(v, false, d) - case *map[int32]float32: - var v2 map[int32]float32 - v2, changed = fastpathTV.DecMapInt32Float32V(*v, true, d) - if changed { - *v = v2 - } - case map[int32]float64: - fastpathTV.DecMapInt32Float64V(v, false, d) - case *map[int32]float64: - var v2 map[int32]float64 - v2, changed = fastpathTV.DecMapInt32Float64V(*v, true, d) - if changed { - *v = v2 - } - case map[int32]bool: - fastpathTV.DecMapInt32BoolV(v, false, d) - case *map[int32]bool: - var v2 map[int32]bool - v2, changed = fastpathTV.DecMapInt32BoolV(*v, true, d) - if changed { - *v = v2 - } - case map[int64]interface{}: - fastpathTV.DecMapInt64IntfV(v, false, d) - case *map[int64]interface{}: - var v2 map[int64]interface{} - v2, changed = fastpathTV.DecMapInt64IntfV(*v, true, d) - if changed { - *v = v2 - } - case map[int64]string: - fastpathTV.DecMapInt64StringV(v, false, d) - case *map[int64]string: - var v2 map[int64]string - v2, changed = fastpathTV.DecMapInt64StringV(*v, true, d) - if changed { - *v = v2 - } - case map[int64]uint: - fastpathTV.DecMapInt64UintV(v, false, d) - case *map[int64]uint: - var v2 map[int64]uint - v2, changed = fastpathTV.DecMapInt64UintV(*v, true, d) - if changed { - *v = v2 - } - case map[int64]uint8: - fastpathTV.DecMapInt64Uint8V(v, false, d) - case *map[int64]uint8: - var v2 map[int64]uint8 - v2, changed = fastpathTV.DecMapInt64Uint8V(*v, true, d) - if changed { - *v = v2 - } - case map[int64]uint16: - fastpathTV.DecMapInt64Uint16V(v, false, d) - case *map[int64]uint16: - var v2 map[int64]uint16 - v2, changed = fastpathTV.DecMapInt64Uint16V(*v, true, d) - if changed { - *v = v2 - } - case map[int64]uint32: - fastpathTV.DecMapInt64Uint32V(v, false, d) - case *map[int64]uint32: - var v2 map[int64]uint32 - v2, changed = fastpathTV.DecMapInt64Uint32V(*v, true, d) - if changed { - *v = v2 - } - case map[int64]uint64: - fastpathTV.DecMapInt64Uint64V(v, false, d) - case *map[int64]uint64: - var v2 map[int64]uint64 - v2, changed = fastpathTV.DecMapInt64Uint64V(*v, true, d) - if changed { - *v = v2 - } - case map[int64]uintptr: - fastpathTV.DecMapInt64UintptrV(v, false, d) - case *map[int64]uintptr: - var v2 map[int64]uintptr - v2, changed = fastpathTV.DecMapInt64UintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[int64]int: - fastpathTV.DecMapInt64IntV(v, false, d) - case *map[int64]int: - var v2 map[int64]int - v2, changed = fastpathTV.DecMapInt64IntV(*v, true, d) - if changed { - *v = v2 - } - case map[int64]int8: - fastpathTV.DecMapInt64Int8V(v, false, d) - case *map[int64]int8: - var v2 map[int64]int8 - v2, changed = fastpathTV.DecMapInt64Int8V(*v, true, d) - if changed { - *v = v2 - } - case map[int64]int16: - fastpathTV.DecMapInt64Int16V(v, false, d) - case *map[int64]int16: - var v2 map[int64]int16 - v2, changed = fastpathTV.DecMapInt64Int16V(*v, true, d) - if changed { - *v = v2 - } - case map[int64]int32: - fastpathTV.DecMapInt64Int32V(v, false, d) - case *map[int64]int32: - var v2 map[int64]int32 - v2, changed = fastpathTV.DecMapInt64Int32V(*v, true, d) - if changed { - *v = v2 - } - case map[int64]int64: - fastpathTV.DecMapInt64Int64V(v, false, d) - case *map[int64]int64: - var v2 map[int64]int64 - v2, changed = fastpathTV.DecMapInt64Int64V(*v, true, d) - if changed { - *v = v2 - } - case map[int64]float32: - fastpathTV.DecMapInt64Float32V(v, false, d) - case *map[int64]float32: - var v2 map[int64]float32 - v2, changed = fastpathTV.DecMapInt64Float32V(*v, true, d) - if changed { - *v = v2 - } - case map[int64]float64: - fastpathTV.DecMapInt64Float64V(v, false, d) - case *map[int64]float64: - var v2 map[int64]float64 - v2, changed = fastpathTV.DecMapInt64Float64V(*v, true, d) - if changed { - *v = v2 - } - case map[int64]bool: - fastpathTV.DecMapInt64BoolV(v, false, d) - case *map[int64]bool: - var v2 map[int64]bool - v2, changed = fastpathTV.DecMapInt64BoolV(*v, true, d) - if changed { - *v = v2 - } - case map[bool]interface{}: - fastpathTV.DecMapBoolIntfV(v, false, d) - case *map[bool]interface{}: - var v2 map[bool]interface{} - v2, changed = fastpathTV.DecMapBoolIntfV(*v, true, d) - if changed { - *v = v2 - } - case map[bool]string: - fastpathTV.DecMapBoolStringV(v, false, d) - case *map[bool]string: - var v2 map[bool]string - v2, changed = fastpathTV.DecMapBoolStringV(*v, true, d) - if changed { - *v = v2 - } - case map[bool]uint: - fastpathTV.DecMapBoolUintV(v, false, d) - case *map[bool]uint: - var v2 map[bool]uint - v2, changed = fastpathTV.DecMapBoolUintV(*v, true, d) - if changed { - *v = v2 - } - case map[bool]uint8: - fastpathTV.DecMapBoolUint8V(v, false, d) - case *map[bool]uint8: - var v2 map[bool]uint8 - v2, changed = fastpathTV.DecMapBoolUint8V(*v, true, d) - if changed { - *v = v2 - } - case map[bool]uint16: - fastpathTV.DecMapBoolUint16V(v, false, d) - case *map[bool]uint16: - var v2 map[bool]uint16 - v2, changed = fastpathTV.DecMapBoolUint16V(*v, true, d) - if changed { - *v = v2 - } - case map[bool]uint32: - fastpathTV.DecMapBoolUint32V(v, false, d) - case *map[bool]uint32: - var v2 map[bool]uint32 - v2, changed = fastpathTV.DecMapBoolUint32V(*v, true, d) - if changed { - *v = v2 - } - case map[bool]uint64: - fastpathTV.DecMapBoolUint64V(v, false, d) - case *map[bool]uint64: - var v2 map[bool]uint64 - v2, changed = fastpathTV.DecMapBoolUint64V(*v, true, d) - if changed { - *v = v2 - } - case map[bool]uintptr: - fastpathTV.DecMapBoolUintptrV(v, false, d) - case *map[bool]uintptr: - var v2 map[bool]uintptr - v2, changed = fastpathTV.DecMapBoolUintptrV(*v, true, d) - if changed { - *v = v2 - } - case map[bool]int: - fastpathTV.DecMapBoolIntV(v, false, d) - case *map[bool]int: - var v2 map[bool]int - v2, changed = fastpathTV.DecMapBoolIntV(*v, true, d) - if changed { - *v = v2 - } - case map[bool]int8: - fastpathTV.DecMapBoolInt8V(v, false, d) - case *map[bool]int8: - var v2 map[bool]int8 - v2, changed = fastpathTV.DecMapBoolInt8V(*v, true, d) - if changed { - *v = v2 - } - case map[bool]int16: - fastpathTV.DecMapBoolInt16V(v, false, d) - case *map[bool]int16: - var v2 map[bool]int16 - v2, changed = fastpathTV.DecMapBoolInt16V(*v, true, d) - if changed { - *v = v2 - } - case map[bool]int32: - fastpathTV.DecMapBoolInt32V(v, false, d) - case *map[bool]int32: - var v2 map[bool]int32 - v2, changed = fastpathTV.DecMapBoolInt32V(*v, true, d) - if changed { - *v = v2 - } - case map[bool]int64: - fastpathTV.DecMapBoolInt64V(v, false, d) - case *map[bool]int64: - var v2 map[bool]int64 - v2, changed = fastpathTV.DecMapBoolInt64V(*v, true, d) - if changed { - *v = v2 - } - case map[bool]float32: - fastpathTV.DecMapBoolFloat32V(v, false, d) - case *map[bool]float32: - var v2 map[bool]float32 - v2, changed = fastpathTV.DecMapBoolFloat32V(*v, true, d) - if changed { - *v = v2 - } - case map[bool]float64: - fastpathTV.DecMapBoolFloat64V(v, false, d) - case *map[bool]float64: - var v2 map[bool]float64 - v2, changed = fastpathTV.DecMapBoolFloat64V(*v, true, d) - if changed { - *v = v2 - } - case map[bool]bool: - fastpathTV.DecMapBoolBoolV(v, false, d) - case *map[bool]bool: - var v2 map[bool]bool - v2, changed = fastpathTV.DecMapBoolBoolV(*v, true, d) - if changed { - *v = v2 - } - default: - _ = v // workaround https://github.com/golang/go/issues/12927 seen in go1.4 - return false - } - return true -} - -func fastpathDecodeSetZeroTypeSwitch(iv interface{}) bool { - switch v := iv.(type) { - - case *[]interface{}: - *v = nil - case *[]string: - *v = nil - case *[]float32: - *v = nil - case *[]float64: - *v = nil - case *[]uint: - *v = nil - case *[]uint8: - *v = nil - case *[]uint16: - *v = nil - case *[]uint32: - *v = nil - case *[]uint64: - *v = nil - case *[]uintptr: - *v = nil - case *[]int: - *v = nil - case *[]int8: - *v = nil - case *[]int16: - *v = nil - case *[]int32: - *v = nil - case *[]int64: - *v = nil - case *[]bool: - *v = nil - - case *map[interface{}]interface{}: - *v = nil - case *map[interface{}]string: - *v = nil - case *map[interface{}]uint: - *v = nil - case *map[interface{}]uint8: - *v = nil - case *map[interface{}]uint16: - *v = nil - case *map[interface{}]uint32: - *v = nil - case *map[interface{}]uint64: - *v = nil - case *map[interface{}]uintptr: - *v = nil - case *map[interface{}]int: - *v = nil - case *map[interface{}]int8: - *v = nil - case *map[interface{}]int16: - *v = nil - case *map[interface{}]int32: - *v = nil - case *map[interface{}]int64: - *v = nil - case *map[interface{}]float32: - *v = nil - case *map[interface{}]float64: - *v = nil - case *map[interface{}]bool: - *v = nil - case *map[string]interface{}: - *v = nil - case *map[string]string: - *v = nil - case *map[string]uint: - *v = nil - case *map[string]uint8: - *v = nil - case *map[string]uint16: - *v = nil - case *map[string]uint32: - *v = nil - case *map[string]uint64: - *v = nil - case *map[string]uintptr: - *v = nil - case *map[string]int: - *v = nil - case *map[string]int8: - *v = nil - case *map[string]int16: - *v = nil - case *map[string]int32: - *v = nil - case *map[string]int64: - *v = nil - case *map[string]float32: - *v = nil - case *map[string]float64: - *v = nil - case *map[string]bool: - *v = nil - case *map[float32]interface{}: - *v = nil - case *map[float32]string: - *v = nil - case *map[float32]uint: - *v = nil - case *map[float32]uint8: - *v = nil - case *map[float32]uint16: - *v = nil - case *map[float32]uint32: - *v = nil - case *map[float32]uint64: - *v = nil - case *map[float32]uintptr: - *v = nil - case *map[float32]int: - *v = nil - case *map[float32]int8: - *v = nil - case *map[float32]int16: - *v = nil - case *map[float32]int32: - *v = nil - case *map[float32]int64: - *v = nil - case *map[float32]float32: - *v = nil - case *map[float32]float64: - *v = nil - case *map[float32]bool: - *v = nil - case *map[float64]interface{}: - *v = nil - case *map[float64]string: - *v = nil - case *map[float64]uint: - *v = nil - case *map[float64]uint8: - *v = nil - case *map[float64]uint16: - *v = nil - case *map[float64]uint32: - *v = nil - case *map[float64]uint64: - *v = nil - case *map[float64]uintptr: - *v = nil - case *map[float64]int: - *v = nil - case *map[float64]int8: - *v = nil - case *map[float64]int16: - *v = nil - case *map[float64]int32: - *v = nil - case *map[float64]int64: - *v = nil - case *map[float64]float32: - *v = nil - case *map[float64]float64: - *v = nil - case *map[float64]bool: - *v = nil - case *map[uint]interface{}: - *v = nil - case *map[uint]string: - *v = nil - case *map[uint]uint: - *v = nil - case *map[uint]uint8: - *v = nil - case *map[uint]uint16: - *v = nil - case *map[uint]uint32: - *v = nil - case *map[uint]uint64: - *v = nil - case *map[uint]uintptr: - *v = nil - case *map[uint]int: - *v = nil - case *map[uint]int8: - *v = nil - case *map[uint]int16: - *v = nil - case *map[uint]int32: - *v = nil - case *map[uint]int64: - *v = nil - case *map[uint]float32: - *v = nil - case *map[uint]float64: - *v = nil - case *map[uint]bool: - *v = nil - case *map[uint8]interface{}: - *v = nil - case *map[uint8]string: - *v = nil - case *map[uint8]uint: - *v = nil - case *map[uint8]uint8: - *v = nil - case *map[uint8]uint16: - *v = nil - case *map[uint8]uint32: - *v = nil - case *map[uint8]uint64: - *v = nil - case *map[uint8]uintptr: - *v = nil - case *map[uint8]int: - *v = nil - case *map[uint8]int8: - *v = nil - case *map[uint8]int16: - *v = nil - case *map[uint8]int32: - *v = nil - case *map[uint8]int64: - *v = nil - case *map[uint8]float32: - *v = nil - case *map[uint8]float64: - *v = nil - case *map[uint8]bool: - *v = nil - case *map[uint16]interface{}: - *v = nil - case *map[uint16]string: - *v = nil - case *map[uint16]uint: - *v = nil - case *map[uint16]uint8: - *v = nil - case *map[uint16]uint16: - *v = nil - case *map[uint16]uint32: - *v = nil - case *map[uint16]uint64: - *v = nil - case *map[uint16]uintptr: - *v = nil - case *map[uint16]int: - *v = nil - case *map[uint16]int8: - *v = nil - case *map[uint16]int16: - *v = nil - case *map[uint16]int32: - *v = nil - case *map[uint16]int64: - *v = nil - case *map[uint16]float32: - *v = nil - case *map[uint16]float64: - *v = nil - case *map[uint16]bool: - *v = nil - case *map[uint32]interface{}: - *v = nil - case *map[uint32]string: - *v = nil - case *map[uint32]uint: - *v = nil - case *map[uint32]uint8: - *v = nil - case *map[uint32]uint16: - *v = nil - case *map[uint32]uint32: - *v = nil - case *map[uint32]uint64: - *v = nil - case *map[uint32]uintptr: - *v = nil - case *map[uint32]int: - *v = nil - case *map[uint32]int8: - *v = nil - case *map[uint32]int16: - *v = nil - case *map[uint32]int32: - *v = nil - case *map[uint32]int64: - *v = nil - case *map[uint32]float32: - *v = nil - case *map[uint32]float64: - *v = nil - case *map[uint32]bool: - *v = nil - case *map[uint64]interface{}: - *v = nil - case *map[uint64]string: - *v = nil - case *map[uint64]uint: - *v = nil - case *map[uint64]uint8: - *v = nil - case *map[uint64]uint16: - *v = nil - case *map[uint64]uint32: - *v = nil - case *map[uint64]uint64: - *v = nil - case *map[uint64]uintptr: - *v = nil - case *map[uint64]int: - *v = nil - case *map[uint64]int8: - *v = nil - case *map[uint64]int16: - *v = nil - case *map[uint64]int32: - *v = nil - case *map[uint64]int64: - *v = nil - case *map[uint64]float32: - *v = nil - case *map[uint64]float64: - *v = nil - case *map[uint64]bool: - *v = nil - case *map[uintptr]interface{}: - *v = nil - case *map[uintptr]string: - *v = nil - case *map[uintptr]uint: - *v = nil - case *map[uintptr]uint8: - *v = nil - case *map[uintptr]uint16: - *v = nil - case *map[uintptr]uint32: - *v = nil - case *map[uintptr]uint64: - *v = nil - case *map[uintptr]uintptr: - *v = nil - case *map[uintptr]int: - *v = nil - case *map[uintptr]int8: - *v = nil - case *map[uintptr]int16: - *v = nil - case *map[uintptr]int32: - *v = nil - case *map[uintptr]int64: - *v = nil - case *map[uintptr]float32: - *v = nil - case *map[uintptr]float64: - *v = nil - case *map[uintptr]bool: - *v = nil - case *map[int]interface{}: - *v = nil - case *map[int]string: - *v = nil - case *map[int]uint: - *v = nil - case *map[int]uint8: - *v = nil - case *map[int]uint16: - *v = nil - case *map[int]uint32: - *v = nil - case *map[int]uint64: - *v = nil - case *map[int]uintptr: - *v = nil - case *map[int]int: - *v = nil - case *map[int]int8: - *v = nil - case *map[int]int16: - *v = nil - case *map[int]int32: - *v = nil - case *map[int]int64: - *v = nil - case *map[int]float32: - *v = nil - case *map[int]float64: - *v = nil - case *map[int]bool: - *v = nil - case *map[int8]interface{}: - *v = nil - case *map[int8]string: - *v = nil - case *map[int8]uint: - *v = nil - case *map[int8]uint8: - *v = nil - case *map[int8]uint16: - *v = nil - case *map[int8]uint32: - *v = nil - case *map[int8]uint64: - *v = nil - case *map[int8]uintptr: - *v = nil - case *map[int8]int: - *v = nil - case *map[int8]int8: - *v = nil - case *map[int8]int16: - *v = nil - case *map[int8]int32: - *v = nil - case *map[int8]int64: - *v = nil - case *map[int8]float32: - *v = nil - case *map[int8]float64: - *v = nil - case *map[int8]bool: - *v = nil - case *map[int16]interface{}: - *v = nil - case *map[int16]string: - *v = nil - case *map[int16]uint: - *v = nil - case *map[int16]uint8: - *v = nil - case *map[int16]uint16: - *v = nil - case *map[int16]uint32: - *v = nil - case *map[int16]uint64: - *v = nil - case *map[int16]uintptr: - *v = nil - case *map[int16]int: - *v = nil - case *map[int16]int8: - *v = nil - case *map[int16]int16: - *v = nil - case *map[int16]int32: - *v = nil - case *map[int16]int64: - *v = nil - case *map[int16]float32: - *v = nil - case *map[int16]float64: - *v = nil - case *map[int16]bool: - *v = nil - case *map[int32]interface{}: - *v = nil - case *map[int32]string: - *v = nil - case *map[int32]uint: - *v = nil - case *map[int32]uint8: - *v = nil - case *map[int32]uint16: - *v = nil - case *map[int32]uint32: - *v = nil - case *map[int32]uint64: - *v = nil - case *map[int32]uintptr: - *v = nil - case *map[int32]int: - *v = nil - case *map[int32]int8: - *v = nil - case *map[int32]int16: - *v = nil - case *map[int32]int32: - *v = nil - case *map[int32]int64: - *v = nil - case *map[int32]float32: - *v = nil - case *map[int32]float64: - *v = nil - case *map[int32]bool: - *v = nil - case *map[int64]interface{}: - *v = nil - case *map[int64]string: - *v = nil - case *map[int64]uint: - *v = nil - case *map[int64]uint8: - *v = nil - case *map[int64]uint16: - *v = nil - case *map[int64]uint32: - *v = nil - case *map[int64]uint64: - *v = nil - case *map[int64]uintptr: - *v = nil - case *map[int64]int: - *v = nil - case *map[int64]int8: - *v = nil - case *map[int64]int16: - *v = nil - case *map[int64]int32: - *v = nil - case *map[int64]int64: - *v = nil - case *map[int64]float32: - *v = nil - case *map[int64]float64: - *v = nil - case *map[int64]bool: - *v = nil - case *map[bool]interface{}: - *v = nil - case *map[bool]string: - *v = nil - case *map[bool]uint: - *v = nil - case *map[bool]uint8: - *v = nil - case *map[bool]uint16: - *v = nil - case *map[bool]uint32: - *v = nil - case *map[bool]uint64: - *v = nil - case *map[bool]uintptr: - *v = nil - case *map[bool]int: - *v = nil - case *map[bool]int8: - *v = nil - case *map[bool]int16: - *v = nil - case *map[bool]int32: - *v = nil - case *map[bool]int64: - *v = nil - case *map[bool]float32: - *v = nil - case *map[bool]float64: - *v = nil - case *map[bool]bool: - *v = nil - default: - _ = v // workaround https://github.com/golang/go/issues/12927 seen in go1.4 - return false - } - return true -} - -// -- -- fast path functions - -func (d *Decoder) fastpathDecSliceIntfR(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]interface{}) - v, changed := fastpathTV.DecSliceIntfV(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]interface{}) - v2, changed := fastpathTV.DecSliceIntfV(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceIntfX(vp *[]interface{}, d *Decoder) { - v, changed := f.DecSliceIntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceIntfV(v []interface{}, canChange bool, d *Decoder) (_ []interface{}, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []interface{}{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 16) - if xlen <= cap(v) { - v = v[:xlen] - } else { - v = make([]interface{}, xlen) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - j := 0 - for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 16) - } else { - xlen = 8 - } - v = make([]interface{}, xlen) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, nil) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[j] = nil - } else { - d.decode(&v[j]) - } - } - if canChange { - if j < len(v) { - v = v[:j] - changed = true - } else if j == 0 && v == nil { - v = make([]interface{}, 0) - changed = true - } - } - slh.End() - return v, changed -} - -func (d *Decoder) fastpathDecSliceStringR(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]string) - v, changed := fastpathTV.DecSliceStringV(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]string) - v2, changed := fastpathTV.DecSliceStringV(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceStringX(vp *[]string, d *Decoder) { - v, changed := f.DecSliceStringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceStringV(v []string, canChange bool, d *Decoder) (_ []string, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []string{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 16) - if xlen <= cap(v) { - v = v[:xlen] - } else { - v = make([]string, xlen) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - j := 0 - for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 16) - } else { - xlen = 8 - } - v = make([]string, xlen) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, "") - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[j] = "" - } else { - v[j] = dd.DecodeString() - } - } - if canChange { - if j < len(v) { - v = v[:j] - changed = true - } else if j == 0 && v == nil { - v = make([]string, 0) - changed = true - } - } - slh.End() - return v, changed -} - -func (d *Decoder) fastpathDecSliceFloat32R(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]float32) - v, changed := fastpathTV.DecSliceFloat32V(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]float32) - v2, changed := fastpathTV.DecSliceFloat32V(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceFloat32X(vp *[]float32, d *Decoder) { - v, changed := f.DecSliceFloat32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceFloat32V(v []float32, canChange bool, d *Decoder) (_ []float32, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []float32{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 4) - if xlen <= cap(v) { - v = v[:xlen] - } else { - v = make([]float32, xlen) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - j := 0 - for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 4) - } else { - xlen = 8 - } - v = make([]float32, xlen) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[j] = 0 - } else { - v[j] = float32(chkOvf.Float32V(dd.DecodeFloat64())) - } - } - if canChange { - if j < len(v) { - v = v[:j] - changed = true - } else if j == 0 && v == nil { - v = make([]float32, 0) - changed = true - } - } - slh.End() - return v, changed -} - -func (d *Decoder) fastpathDecSliceFloat64R(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]float64) - v, changed := fastpathTV.DecSliceFloat64V(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]float64) - v2, changed := fastpathTV.DecSliceFloat64V(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceFloat64X(vp *[]float64, d *Decoder) { - v, changed := f.DecSliceFloat64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceFloat64V(v []float64, canChange bool, d *Decoder) (_ []float64, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []float64{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - if xlen <= cap(v) { - v = v[:xlen] - } else { - v = make([]float64, xlen) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - j := 0 - for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - } else { - xlen = 8 - } - v = make([]float64, xlen) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[j] = 0 - } else { - v[j] = dd.DecodeFloat64() - } - } - if canChange { - if j < len(v) { - v = v[:j] - changed = true - } else if j == 0 && v == nil { - v = make([]float64, 0) - changed = true - } - } - slh.End() - return v, changed -} - -func (d *Decoder) fastpathDecSliceUintR(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]uint) - v, changed := fastpathTV.DecSliceUintV(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]uint) - v2, changed := fastpathTV.DecSliceUintV(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceUintX(vp *[]uint, d *Decoder) { - v, changed := f.DecSliceUintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceUintV(v []uint, canChange bool, d *Decoder) (_ []uint, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []uint{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - if xlen <= cap(v) { - v = v[:xlen] - } else { - v = make([]uint, xlen) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - j := 0 - for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - } else { - xlen = 8 - } - v = make([]uint, xlen) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[j] = 0 - } else { - v[j] = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - } - } - if canChange { - if j < len(v) { - v = v[:j] - changed = true - } else if j == 0 && v == nil { - v = make([]uint, 0) - changed = true - } - } - slh.End() - return v, changed -} - -func (d *Decoder) fastpathDecSliceUint8R(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]uint8) - v, changed := fastpathTV.DecSliceUint8V(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]uint8) - v2, changed := fastpathTV.DecSliceUint8V(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceUint8X(vp *[]uint8, d *Decoder) { - v, changed := f.DecSliceUint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceUint8V(v []uint8, canChange bool, d *Decoder) (_ []uint8, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []uint8{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 1) - if xlen <= cap(v) { - v = v[:xlen] - } else { - v = make([]uint8, xlen) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - j := 0 - for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 1) - } else { - xlen = 8 - } - v = make([]uint8, xlen) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[j] = 0 - } else { - v[j] = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - } - } - if canChange { - if j < len(v) { - v = v[:j] - changed = true - } else if j == 0 && v == nil { - v = make([]uint8, 0) - changed = true - } - } - slh.End() - return v, changed -} - -func (d *Decoder) fastpathDecSliceUint16R(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]uint16) - v, changed := fastpathTV.DecSliceUint16V(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]uint16) - v2, changed := fastpathTV.DecSliceUint16V(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceUint16X(vp *[]uint16, d *Decoder) { - v, changed := f.DecSliceUint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceUint16V(v []uint16, canChange bool, d *Decoder) (_ []uint16, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []uint16{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 2) - if xlen <= cap(v) { - v = v[:xlen] - } else { - v = make([]uint16, xlen) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - j := 0 - for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 2) - } else { - xlen = 8 - } - v = make([]uint16, xlen) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[j] = 0 - } else { - v[j] = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - } - } - if canChange { - if j < len(v) { - v = v[:j] - changed = true - } else if j == 0 && v == nil { - v = make([]uint16, 0) - changed = true - } - } - slh.End() - return v, changed -} - -func (d *Decoder) fastpathDecSliceUint32R(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]uint32) - v, changed := fastpathTV.DecSliceUint32V(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]uint32) - v2, changed := fastpathTV.DecSliceUint32V(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceUint32X(vp *[]uint32, d *Decoder) { - v, changed := f.DecSliceUint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceUint32V(v []uint32, canChange bool, d *Decoder) (_ []uint32, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []uint32{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 4) - if xlen <= cap(v) { - v = v[:xlen] - } else { - v = make([]uint32, xlen) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - j := 0 - for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 4) - } else { - xlen = 8 - } - v = make([]uint32, xlen) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[j] = 0 - } else { - v[j] = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - } - } - if canChange { - if j < len(v) { - v = v[:j] - changed = true - } else if j == 0 && v == nil { - v = make([]uint32, 0) - changed = true - } - } - slh.End() - return v, changed -} - -func (d *Decoder) fastpathDecSliceUint64R(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]uint64) - v, changed := fastpathTV.DecSliceUint64V(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]uint64) - v2, changed := fastpathTV.DecSliceUint64V(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceUint64X(vp *[]uint64, d *Decoder) { - v, changed := f.DecSliceUint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceUint64V(v []uint64, canChange bool, d *Decoder) (_ []uint64, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []uint64{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - if xlen <= cap(v) { - v = v[:xlen] - } else { - v = make([]uint64, xlen) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - j := 0 - for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - } else { - xlen = 8 - } - v = make([]uint64, xlen) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[j] = 0 - } else { - v[j] = dd.DecodeUint64() - } - } - if canChange { - if j < len(v) { - v = v[:j] - changed = true - } else if j == 0 && v == nil { - v = make([]uint64, 0) - changed = true - } - } - slh.End() - return v, changed -} - -func (d *Decoder) fastpathDecSliceUintptrR(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]uintptr) - v, changed := fastpathTV.DecSliceUintptrV(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]uintptr) - v2, changed := fastpathTV.DecSliceUintptrV(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceUintptrX(vp *[]uintptr, d *Decoder) { - v, changed := f.DecSliceUintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceUintptrV(v []uintptr, canChange bool, d *Decoder) (_ []uintptr, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []uintptr{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - if xlen <= cap(v) { - v = v[:xlen] - } else { - v = make([]uintptr, xlen) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - j := 0 - for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - } else { - xlen = 8 - } - v = make([]uintptr, xlen) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[j] = 0 - } else { - v[j] = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - } - } - if canChange { - if j < len(v) { - v = v[:j] - changed = true - } else if j == 0 && v == nil { - v = make([]uintptr, 0) - changed = true - } - } - slh.End() - return v, changed -} - -func (d *Decoder) fastpathDecSliceIntR(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]int) - v, changed := fastpathTV.DecSliceIntV(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]int) - v2, changed := fastpathTV.DecSliceIntV(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceIntX(vp *[]int, d *Decoder) { - v, changed := f.DecSliceIntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceIntV(v []int, canChange bool, d *Decoder) (_ []int, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []int{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - if xlen <= cap(v) { - v = v[:xlen] - } else { - v = make([]int, xlen) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - j := 0 - for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - } else { - xlen = 8 - } - v = make([]int, xlen) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[j] = 0 - } else { - v[j] = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - } - } - if canChange { - if j < len(v) { - v = v[:j] - changed = true - } else if j == 0 && v == nil { - v = make([]int, 0) - changed = true - } - } - slh.End() - return v, changed -} - -func (d *Decoder) fastpathDecSliceInt8R(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]int8) - v, changed := fastpathTV.DecSliceInt8V(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]int8) - v2, changed := fastpathTV.DecSliceInt8V(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceInt8X(vp *[]int8, d *Decoder) { - v, changed := f.DecSliceInt8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceInt8V(v []int8, canChange bool, d *Decoder) (_ []int8, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []int8{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 1) - if xlen <= cap(v) { - v = v[:xlen] - } else { - v = make([]int8, xlen) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - j := 0 - for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 1) - } else { - xlen = 8 - } - v = make([]int8, xlen) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[j] = 0 - } else { - v[j] = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - } - } - if canChange { - if j < len(v) { - v = v[:j] - changed = true - } else if j == 0 && v == nil { - v = make([]int8, 0) - changed = true - } - } - slh.End() - return v, changed -} - -func (d *Decoder) fastpathDecSliceInt16R(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]int16) - v, changed := fastpathTV.DecSliceInt16V(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]int16) - v2, changed := fastpathTV.DecSliceInt16V(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceInt16X(vp *[]int16, d *Decoder) { - v, changed := f.DecSliceInt16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceInt16V(v []int16, canChange bool, d *Decoder) (_ []int16, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []int16{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 2) - if xlen <= cap(v) { - v = v[:xlen] - } else { - v = make([]int16, xlen) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - j := 0 - for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 2) - } else { - xlen = 8 - } - v = make([]int16, xlen) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[j] = 0 - } else { - v[j] = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - } - } - if canChange { - if j < len(v) { - v = v[:j] - changed = true - } else if j == 0 && v == nil { - v = make([]int16, 0) - changed = true - } - } - slh.End() - return v, changed -} - -func (d *Decoder) fastpathDecSliceInt32R(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]int32) - v, changed := fastpathTV.DecSliceInt32V(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]int32) - v2, changed := fastpathTV.DecSliceInt32V(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceInt32X(vp *[]int32, d *Decoder) { - v, changed := f.DecSliceInt32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceInt32V(v []int32, canChange bool, d *Decoder) (_ []int32, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []int32{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 4) - if xlen <= cap(v) { - v = v[:xlen] - } else { - v = make([]int32, xlen) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - j := 0 - for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 4) - } else { - xlen = 8 - } - v = make([]int32, xlen) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[j] = 0 - } else { - v[j] = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - } - } - if canChange { - if j < len(v) { - v = v[:j] - changed = true - } else if j == 0 && v == nil { - v = make([]int32, 0) - changed = true - } - } - slh.End() - return v, changed -} - -func (d *Decoder) fastpathDecSliceInt64R(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]int64) - v, changed := fastpathTV.DecSliceInt64V(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]int64) - v2, changed := fastpathTV.DecSliceInt64V(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceInt64X(vp *[]int64, d *Decoder) { - v, changed := f.DecSliceInt64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceInt64V(v []int64, canChange bool, d *Decoder) (_ []int64, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []int64{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - if xlen <= cap(v) { - v = v[:xlen] - } else { - v = make([]int64, xlen) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - j := 0 - for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 8) - } else { - xlen = 8 - } - v = make([]int64, xlen) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, 0) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[j] = 0 - } else { - v[j] = dd.DecodeInt64() - } - } - if canChange { - if j < len(v) { - v = v[:j] - changed = true - } else if j == 0 && v == nil { - v = make([]int64, 0) - changed = true - } - } - slh.End() - return v, changed -} - -func (d *Decoder) fastpathDecSliceBoolR(f *codecFnInfo, rv reflect.Value) { - if array := f.seq == seqTypeArray; !array && rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*[]bool) - v, changed := fastpathTV.DecSliceBoolV(*vp, !array, d) - if changed { - *vp = v - } - } else { - v := rv2i(rv).([]bool) - v2, changed := fastpathTV.DecSliceBoolV(v, !array, d) - if changed && len(v) > 0 && len(v2) > 0 && !(len(v2) == len(v) && &v2[0] == &v[0]) { - copy(v, v2) - } - } -} -func (f fastpathT) DecSliceBoolX(vp *[]bool, d *Decoder) { - v, changed := f.DecSliceBoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecSliceBoolV(v []bool, canChange bool, d *Decoder) (_ []bool, changed bool) { - dd := d.d - slh, containerLenS := d.decSliceHelperStart() - if containerLenS == 0 { - if canChange { - if v == nil { - v = []bool{} - } else if len(v) != 0 { - v = v[:0] - } - changed = true - } - slh.End() - return v, changed - } - hasLen := containerLenS > 0 - var xlen int - if hasLen && canChange { - if containerLenS > cap(v) { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 1) - if xlen <= cap(v) { - v = v[:xlen] - } else { - v = make([]bool, xlen) - } - changed = true - } else if containerLenS != len(v) { - v = v[:containerLenS] - changed = true - } - } - j := 0 - for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ { - if j == 0 && len(v) == 0 && canChange { - if hasLen { - xlen = decInferLen(containerLenS, d.h.MaxInitLen, 1) - } else { - xlen = 8 - } - v = make([]bool, xlen) - changed = true - } - // if indefinite, etc, then expand the slice if necessary - var decodeIntoBlank bool - if j >= len(v) { - if canChange { - v = append(v, false) - changed = true - } else { - d.arrayCannotExpand(len(v), j+1) - decodeIntoBlank = true - } - } - slh.ElemContainerState(j) - if decodeIntoBlank { - d.swallow() - } else if dd.TryDecodeAsNil() { - v[j] = false - } else { - v[j] = dd.DecodeBool() - } - } - if canChange { - if j < len(v) { - v = v[:j] - changed = true - } else if j == 0 && v == nil { - v = make([]bool, 0) - changed = true - } - } - slh.End() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfIntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]interface{}) - v, changed := fastpathTV.DecMapIntfIntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfIntfV(rv2i(rv).(map[interface{}]interface{}), false, d) - } -} -func (f fastpathT) DecMapIntfIntfX(vp *map[interface{}]interface{}, d *Decoder) { - v, changed := f.DecMapIntfIntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfIntfV(v map[interface{}]interface{}, canChange bool, - d *Decoder) (_ map[interface{}]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 32) - v = make(map[interface{}]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk interface{} - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfStringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]string) - v, changed := fastpathTV.DecMapIntfStringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfStringV(rv2i(rv).(map[interface{}]string), false, d) - } -} -func (f fastpathT) DecMapIntfStringX(vp *map[interface{}]string, d *Decoder) { - v, changed := f.DecMapIntfStringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfStringV(v map[interface{}]string, canChange bool, - d *Decoder) (_ map[interface{}]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 32) - v = make(map[interface{}]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk interface{} - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfUintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]uint) - v, changed := fastpathTV.DecMapIntfUintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfUintV(rv2i(rv).(map[interface{}]uint), false, d) - } -} -func (f fastpathT) DecMapIntfUintX(vp *map[interface{}]uint, d *Decoder) { - v, changed := f.DecMapIntfUintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfUintV(v map[interface{}]uint, canChange bool, - d *Decoder) (_ map[interface{}]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[interface{}]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk interface{} - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfUint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]uint8) - v, changed := fastpathTV.DecMapIntfUint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfUint8V(rv2i(rv).(map[interface{}]uint8), false, d) - } -} -func (f fastpathT) DecMapIntfUint8X(vp *map[interface{}]uint8, d *Decoder) { - v, changed := f.DecMapIntfUint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfUint8V(v map[interface{}]uint8, canChange bool, - d *Decoder) (_ map[interface{}]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[interface{}]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk interface{} - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfUint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]uint16) - v, changed := fastpathTV.DecMapIntfUint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfUint16V(rv2i(rv).(map[interface{}]uint16), false, d) - } -} -func (f fastpathT) DecMapIntfUint16X(vp *map[interface{}]uint16, d *Decoder) { - v, changed := f.DecMapIntfUint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfUint16V(v map[interface{}]uint16, canChange bool, - d *Decoder) (_ map[interface{}]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 18) - v = make(map[interface{}]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk interface{} - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfUint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]uint32) - v, changed := fastpathTV.DecMapIntfUint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfUint32V(rv2i(rv).(map[interface{}]uint32), false, d) - } -} -func (f fastpathT) DecMapIntfUint32X(vp *map[interface{}]uint32, d *Decoder) { - v, changed := f.DecMapIntfUint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfUint32V(v map[interface{}]uint32, canChange bool, - d *Decoder) (_ map[interface{}]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[interface{}]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk interface{} - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfUint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]uint64) - v, changed := fastpathTV.DecMapIntfUint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfUint64V(rv2i(rv).(map[interface{}]uint64), false, d) - } -} -func (f fastpathT) DecMapIntfUint64X(vp *map[interface{}]uint64, d *Decoder) { - v, changed := f.DecMapIntfUint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfUint64V(v map[interface{}]uint64, canChange bool, - d *Decoder) (_ map[interface{}]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[interface{}]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk interface{} - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfUintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]uintptr) - v, changed := fastpathTV.DecMapIntfUintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfUintptrV(rv2i(rv).(map[interface{}]uintptr), false, d) - } -} -func (f fastpathT) DecMapIntfUintptrX(vp *map[interface{}]uintptr, d *Decoder) { - v, changed := f.DecMapIntfUintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfUintptrV(v map[interface{}]uintptr, canChange bool, - d *Decoder) (_ map[interface{}]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[interface{}]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk interface{} - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfIntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]int) - v, changed := fastpathTV.DecMapIntfIntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfIntV(rv2i(rv).(map[interface{}]int), false, d) - } -} -func (f fastpathT) DecMapIntfIntX(vp *map[interface{}]int, d *Decoder) { - v, changed := f.DecMapIntfIntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfIntV(v map[interface{}]int, canChange bool, - d *Decoder) (_ map[interface{}]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[interface{}]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk interface{} - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfInt8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]int8) - v, changed := fastpathTV.DecMapIntfInt8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfInt8V(rv2i(rv).(map[interface{}]int8), false, d) - } -} -func (f fastpathT) DecMapIntfInt8X(vp *map[interface{}]int8, d *Decoder) { - v, changed := f.DecMapIntfInt8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfInt8V(v map[interface{}]int8, canChange bool, - d *Decoder) (_ map[interface{}]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[interface{}]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk interface{} - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfInt16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]int16) - v, changed := fastpathTV.DecMapIntfInt16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfInt16V(rv2i(rv).(map[interface{}]int16), false, d) - } -} -func (f fastpathT) DecMapIntfInt16X(vp *map[interface{}]int16, d *Decoder) { - v, changed := f.DecMapIntfInt16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfInt16V(v map[interface{}]int16, canChange bool, - d *Decoder) (_ map[interface{}]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 18) - v = make(map[interface{}]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk interface{} - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfInt32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]int32) - v, changed := fastpathTV.DecMapIntfInt32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfInt32V(rv2i(rv).(map[interface{}]int32), false, d) - } -} -func (f fastpathT) DecMapIntfInt32X(vp *map[interface{}]int32, d *Decoder) { - v, changed := f.DecMapIntfInt32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfInt32V(v map[interface{}]int32, canChange bool, - d *Decoder) (_ map[interface{}]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[interface{}]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk interface{} - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfInt64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]int64) - v, changed := fastpathTV.DecMapIntfInt64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfInt64V(rv2i(rv).(map[interface{}]int64), false, d) - } -} -func (f fastpathT) DecMapIntfInt64X(vp *map[interface{}]int64, d *Decoder) { - v, changed := f.DecMapIntfInt64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfInt64V(v map[interface{}]int64, canChange bool, - d *Decoder) (_ map[interface{}]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[interface{}]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk interface{} - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfFloat32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]float32) - v, changed := fastpathTV.DecMapIntfFloat32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfFloat32V(rv2i(rv).(map[interface{}]float32), false, d) - } -} -func (f fastpathT) DecMapIntfFloat32X(vp *map[interface{}]float32, d *Decoder) { - v, changed := f.DecMapIntfFloat32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfFloat32V(v map[interface{}]float32, canChange bool, - d *Decoder) (_ map[interface{}]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[interface{}]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk interface{} - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfFloat64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]float64) - v, changed := fastpathTV.DecMapIntfFloat64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfFloat64V(rv2i(rv).(map[interface{}]float64), false, d) - } -} -func (f fastpathT) DecMapIntfFloat64X(vp *map[interface{}]float64, d *Decoder) { - v, changed := f.DecMapIntfFloat64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfFloat64V(v map[interface{}]float64, canChange bool, - d *Decoder) (_ map[interface{}]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[interface{}]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk interface{} - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntfBoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[interface{}]bool) - v, changed := fastpathTV.DecMapIntfBoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntfBoolV(rv2i(rv).(map[interface{}]bool), false, d) - } -} -func (f fastpathT) DecMapIntfBoolX(vp *map[interface{}]bool, d *Decoder) { - v, changed := f.DecMapIntfBoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntfBoolV(v map[interface{}]bool, canChange bool, - d *Decoder) (_ map[interface{}]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[interface{}]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk interface{} - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = nil - d.decode(&mk) - if bv, bok := mk.([]byte); bok { - mk = d.string(bv) - } - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringIntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]interface{}) - v, changed := fastpathTV.DecMapStringIntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringIntfV(rv2i(rv).(map[string]interface{}), false, d) - } -} -func (f fastpathT) DecMapStringIntfX(vp *map[string]interface{}, d *Decoder) { - v, changed := f.DecMapStringIntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringIntfV(v map[string]interface{}, canChange bool, - d *Decoder) (_ map[string]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 32) - v = make(map[string]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk string - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringStringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]string) - v, changed := fastpathTV.DecMapStringStringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringStringV(rv2i(rv).(map[string]string), false, d) - } -} -func (f fastpathT) DecMapStringStringX(vp *map[string]string, d *Decoder) { - v, changed := f.DecMapStringStringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringStringV(v map[string]string, canChange bool, - d *Decoder) (_ map[string]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 32) - v = make(map[string]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk string - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringUintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]uint) - v, changed := fastpathTV.DecMapStringUintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringUintV(rv2i(rv).(map[string]uint), false, d) - } -} -func (f fastpathT) DecMapStringUintX(vp *map[string]uint, d *Decoder) { - v, changed := f.DecMapStringUintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringUintV(v map[string]uint, canChange bool, - d *Decoder) (_ map[string]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[string]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk string - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringUint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]uint8) - v, changed := fastpathTV.DecMapStringUint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringUint8V(rv2i(rv).(map[string]uint8), false, d) - } -} -func (f fastpathT) DecMapStringUint8X(vp *map[string]uint8, d *Decoder) { - v, changed := f.DecMapStringUint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringUint8V(v map[string]uint8, canChange bool, - d *Decoder) (_ map[string]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[string]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk string - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringUint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]uint16) - v, changed := fastpathTV.DecMapStringUint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringUint16V(rv2i(rv).(map[string]uint16), false, d) - } -} -func (f fastpathT) DecMapStringUint16X(vp *map[string]uint16, d *Decoder) { - v, changed := f.DecMapStringUint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringUint16V(v map[string]uint16, canChange bool, - d *Decoder) (_ map[string]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 18) - v = make(map[string]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk string - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringUint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]uint32) - v, changed := fastpathTV.DecMapStringUint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringUint32V(rv2i(rv).(map[string]uint32), false, d) - } -} -func (f fastpathT) DecMapStringUint32X(vp *map[string]uint32, d *Decoder) { - v, changed := f.DecMapStringUint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringUint32V(v map[string]uint32, canChange bool, - d *Decoder) (_ map[string]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[string]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk string - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringUint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]uint64) - v, changed := fastpathTV.DecMapStringUint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringUint64V(rv2i(rv).(map[string]uint64), false, d) - } -} -func (f fastpathT) DecMapStringUint64X(vp *map[string]uint64, d *Decoder) { - v, changed := f.DecMapStringUint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringUint64V(v map[string]uint64, canChange bool, - d *Decoder) (_ map[string]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[string]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk string - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringUintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]uintptr) - v, changed := fastpathTV.DecMapStringUintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringUintptrV(rv2i(rv).(map[string]uintptr), false, d) - } -} -func (f fastpathT) DecMapStringUintptrX(vp *map[string]uintptr, d *Decoder) { - v, changed := f.DecMapStringUintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringUintptrV(v map[string]uintptr, canChange bool, - d *Decoder) (_ map[string]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[string]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk string - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringIntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]int) - v, changed := fastpathTV.DecMapStringIntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringIntV(rv2i(rv).(map[string]int), false, d) - } -} -func (f fastpathT) DecMapStringIntX(vp *map[string]int, d *Decoder) { - v, changed := f.DecMapStringIntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringIntV(v map[string]int, canChange bool, - d *Decoder) (_ map[string]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[string]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk string - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringInt8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]int8) - v, changed := fastpathTV.DecMapStringInt8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringInt8V(rv2i(rv).(map[string]int8), false, d) - } -} -func (f fastpathT) DecMapStringInt8X(vp *map[string]int8, d *Decoder) { - v, changed := f.DecMapStringInt8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringInt8V(v map[string]int8, canChange bool, - d *Decoder) (_ map[string]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[string]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk string - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringInt16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]int16) - v, changed := fastpathTV.DecMapStringInt16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringInt16V(rv2i(rv).(map[string]int16), false, d) - } -} -func (f fastpathT) DecMapStringInt16X(vp *map[string]int16, d *Decoder) { - v, changed := f.DecMapStringInt16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringInt16V(v map[string]int16, canChange bool, - d *Decoder) (_ map[string]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 18) - v = make(map[string]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk string - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringInt32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]int32) - v, changed := fastpathTV.DecMapStringInt32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringInt32V(rv2i(rv).(map[string]int32), false, d) - } -} -func (f fastpathT) DecMapStringInt32X(vp *map[string]int32, d *Decoder) { - v, changed := f.DecMapStringInt32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringInt32V(v map[string]int32, canChange bool, - d *Decoder) (_ map[string]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[string]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk string - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringInt64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]int64) - v, changed := fastpathTV.DecMapStringInt64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringInt64V(rv2i(rv).(map[string]int64), false, d) - } -} -func (f fastpathT) DecMapStringInt64X(vp *map[string]int64, d *Decoder) { - v, changed := f.DecMapStringInt64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringInt64V(v map[string]int64, canChange bool, - d *Decoder) (_ map[string]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[string]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk string - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringFloat32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]float32) - v, changed := fastpathTV.DecMapStringFloat32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringFloat32V(rv2i(rv).(map[string]float32), false, d) - } -} -func (f fastpathT) DecMapStringFloat32X(vp *map[string]float32, d *Decoder) { - v, changed := f.DecMapStringFloat32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringFloat32V(v map[string]float32, canChange bool, - d *Decoder) (_ map[string]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[string]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk string - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringFloat64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]float64) - v, changed := fastpathTV.DecMapStringFloat64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringFloat64V(rv2i(rv).(map[string]float64), false, d) - } -} -func (f fastpathT) DecMapStringFloat64X(vp *map[string]float64, d *Decoder) { - v, changed := f.DecMapStringFloat64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringFloat64V(v map[string]float64, canChange bool, - d *Decoder) (_ map[string]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[string]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk string - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapStringBoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[string]bool) - v, changed := fastpathTV.DecMapStringBoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapStringBoolV(rv2i(rv).(map[string]bool), false, d) - } -} -func (f fastpathT) DecMapStringBoolX(vp *map[string]bool, d *Decoder) { - v, changed := f.DecMapStringBoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapStringBoolV(v map[string]bool, canChange bool, - d *Decoder) (_ map[string]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[string]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk string - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeString() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32IntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]interface{}) - v, changed := fastpathTV.DecMapFloat32IntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32IntfV(rv2i(rv).(map[float32]interface{}), false, d) - } -} -func (f fastpathT) DecMapFloat32IntfX(vp *map[float32]interface{}, d *Decoder) { - v, changed := f.DecMapFloat32IntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32IntfV(v map[float32]interface{}, canChange bool, - d *Decoder) (_ map[float32]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[float32]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk float32 - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32StringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]string) - v, changed := fastpathTV.DecMapFloat32StringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32StringV(rv2i(rv).(map[float32]string), false, d) - } -} -func (f fastpathT) DecMapFloat32StringX(vp *map[float32]string, d *Decoder) { - v, changed := f.DecMapFloat32StringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32StringV(v map[float32]string, canChange bool, - d *Decoder) (_ map[float32]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[float32]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float32 - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32UintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]uint) - v, changed := fastpathTV.DecMapFloat32UintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32UintV(rv2i(rv).(map[float32]uint), false, d) - } -} -func (f fastpathT) DecMapFloat32UintX(vp *map[float32]uint, d *Decoder) { - v, changed := f.DecMapFloat32UintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32UintV(v map[float32]uint, canChange bool, - d *Decoder) (_ map[float32]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[float32]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float32 - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32Uint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]uint8) - v, changed := fastpathTV.DecMapFloat32Uint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32Uint8V(rv2i(rv).(map[float32]uint8), false, d) - } -} -func (f fastpathT) DecMapFloat32Uint8X(vp *map[float32]uint8, d *Decoder) { - v, changed := f.DecMapFloat32Uint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32Uint8V(v map[float32]uint8, canChange bool, - d *Decoder) (_ map[float32]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[float32]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float32 - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32Uint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]uint16) - v, changed := fastpathTV.DecMapFloat32Uint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32Uint16V(rv2i(rv).(map[float32]uint16), false, d) - } -} -func (f fastpathT) DecMapFloat32Uint16X(vp *map[float32]uint16, d *Decoder) { - v, changed := f.DecMapFloat32Uint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32Uint16V(v map[float32]uint16, canChange bool, - d *Decoder) (_ map[float32]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[float32]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float32 - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32Uint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]uint32) - v, changed := fastpathTV.DecMapFloat32Uint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32Uint32V(rv2i(rv).(map[float32]uint32), false, d) - } -} -func (f fastpathT) DecMapFloat32Uint32X(vp *map[float32]uint32, d *Decoder) { - v, changed := f.DecMapFloat32Uint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32Uint32V(v map[float32]uint32, canChange bool, - d *Decoder) (_ map[float32]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 8) - v = make(map[float32]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float32 - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32Uint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]uint64) - v, changed := fastpathTV.DecMapFloat32Uint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32Uint64V(rv2i(rv).(map[float32]uint64), false, d) - } -} -func (f fastpathT) DecMapFloat32Uint64X(vp *map[float32]uint64, d *Decoder) { - v, changed := f.DecMapFloat32Uint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32Uint64V(v map[float32]uint64, canChange bool, - d *Decoder) (_ map[float32]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[float32]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float32 - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32UintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]uintptr) - v, changed := fastpathTV.DecMapFloat32UintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32UintptrV(rv2i(rv).(map[float32]uintptr), false, d) - } -} -func (f fastpathT) DecMapFloat32UintptrX(vp *map[float32]uintptr, d *Decoder) { - v, changed := f.DecMapFloat32UintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32UintptrV(v map[float32]uintptr, canChange bool, - d *Decoder) (_ map[float32]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[float32]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float32 - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32IntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]int) - v, changed := fastpathTV.DecMapFloat32IntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32IntV(rv2i(rv).(map[float32]int), false, d) - } -} -func (f fastpathT) DecMapFloat32IntX(vp *map[float32]int, d *Decoder) { - v, changed := f.DecMapFloat32IntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32IntV(v map[float32]int, canChange bool, - d *Decoder) (_ map[float32]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[float32]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float32 - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32Int8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]int8) - v, changed := fastpathTV.DecMapFloat32Int8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32Int8V(rv2i(rv).(map[float32]int8), false, d) - } -} -func (f fastpathT) DecMapFloat32Int8X(vp *map[float32]int8, d *Decoder) { - v, changed := f.DecMapFloat32Int8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32Int8V(v map[float32]int8, canChange bool, - d *Decoder) (_ map[float32]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[float32]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float32 - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32Int16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]int16) - v, changed := fastpathTV.DecMapFloat32Int16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32Int16V(rv2i(rv).(map[float32]int16), false, d) - } -} -func (f fastpathT) DecMapFloat32Int16X(vp *map[float32]int16, d *Decoder) { - v, changed := f.DecMapFloat32Int16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32Int16V(v map[float32]int16, canChange bool, - d *Decoder) (_ map[float32]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[float32]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float32 - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32Int32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]int32) - v, changed := fastpathTV.DecMapFloat32Int32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32Int32V(rv2i(rv).(map[float32]int32), false, d) - } -} -func (f fastpathT) DecMapFloat32Int32X(vp *map[float32]int32, d *Decoder) { - v, changed := f.DecMapFloat32Int32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32Int32V(v map[float32]int32, canChange bool, - d *Decoder) (_ map[float32]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 8) - v = make(map[float32]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float32 - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32Int64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]int64) - v, changed := fastpathTV.DecMapFloat32Int64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32Int64V(rv2i(rv).(map[float32]int64), false, d) - } -} -func (f fastpathT) DecMapFloat32Int64X(vp *map[float32]int64, d *Decoder) { - v, changed := f.DecMapFloat32Int64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32Int64V(v map[float32]int64, canChange bool, - d *Decoder) (_ map[float32]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[float32]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float32 - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32Float32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]float32) - v, changed := fastpathTV.DecMapFloat32Float32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32Float32V(rv2i(rv).(map[float32]float32), false, d) - } -} -func (f fastpathT) DecMapFloat32Float32X(vp *map[float32]float32, d *Decoder) { - v, changed := f.DecMapFloat32Float32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32Float32V(v map[float32]float32, canChange bool, - d *Decoder) (_ map[float32]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 8) - v = make(map[float32]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float32 - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32Float64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]float64) - v, changed := fastpathTV.DecMapFloat32Float64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32Float64V(rv2i(rv).(map[float32]float64), false, d) - } -} -func (f fastpathT) DecMapFloat32Float64X(vp *map[float32]float64, d *Decoder) { - v, changed := f.DecMapFloat32Float64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32Float64V(v map[float32]float64, canChange bool, - d *Decoder) (_ map[float32]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[float32]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float32 - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat32BoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float32]bool) - v, changed := fastpathTV.DecMapFloat32BoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat32BoolV(rv2i(rv).(map[float32]bool), false, d) - } -} -func (f fastpathT) DecMapFloat32BoolX(vp *map[float32]bool, d *Decoder) { - v, changed := f.DecMapFloat32BoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat32BoolV(v map[float32]bool, canChange bool, - d *Decoder) (_ map[float32]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[float32]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float32 - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64IntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]interface{}) - v, changed := fastpathTV.DecMapFloat64IntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64IntfV(rv2i(rv).(map[float64]interface{}), false, d) - } -} -func (f fastpathT) DecMapFloat64IntfX(vp *map[float64]interface{}, d *Decoder) { - v, changed := f.DecMapFloat64IntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64IntfV(v map[float64]interface{}, canChange bool, - d *Decoder) (_ map[float64]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[float64]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk float64 - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64StringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]string) - v, changed := fastpathTV.DecMapFloat64StringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64StringV(rv2i(rv).(map[float64]string), false, d) - } -} -func (f fastpathT) DecMapFloat64StringX(vp *map[float64]string, d *Decoder) { - v, changed := f.DecMapFloat64StringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64StringV(v map[float64]string, canChange bool, - d *Decoder) (_ map[float64]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[float64]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float64 - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64UintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]uint) - v, changed := fastpathTV.DecMapFloat64UintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64UintV(rv2i(rv).(map[float64]uint), false, d) - } -} -func (f fastpathT) DecMapFloat64UintX(vp *map[float64]uint, d *Decoder) { - v, changed := f.DecMapFloat64UintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64UintV(v map[float64]uint, canChange bool, - d *Decoder) (_ map[float64]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[float64]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float64 - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64Uint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]uint8) - v, changed := fastpathTV.DecMapFloat64Uint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64Uint8V(rv2i(rv).(map[float64]uint8), false, d) - } -} -func (f fastpathT) DecMapFloat64Uint8X(vp *map[float64]uint8, d *Decoder) { - v, changed := f.DecMapFloat64Uint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64Uint8V(v map[float64]uint8, canChange bool, - d *Decoder) (_ map[float64]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[float64]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float64 - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64Uint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]uint16) - v, changed := fastpathTV.DecMapFloat64Uint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64Uint16V(rv2i(rv).(map[float64]uint16), false, d) - } -} -func (f fastpathT) DecMapFloat64Uint16X(vp *map[float64]uint16, d *Decoder) { - v, changed := f.DecMapFloat64Uint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64Uint16V(v map[float64]uint16, canChange bool, - d *Decoder) (_ map[float64]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[float64]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float64 - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64Uint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]uint32) - v, changed := fastpathTV.DecMapFloat64Uint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64Uint32V(rv2i(rv).(map[float64]uint32), false, d) - } -} -func (f fastpathT) DecMapFloat64Uint32X(vp *map[float64]uint32, d *Decoder) { - v, changed := f.DecMapFloat64Uint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64Uint32V(v map[float64]uint32, canChange bool, - d *Decoder) (_ map[float64]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[float64]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float64 - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64Uint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]uint64) - v, changed := fastpathTV.DecMapFloat64Uint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64Uint64V(rv2i(rv).(map[float64]uint64), false, d) - } -} -func (f fastpathT) DecMapFloat64Uint64X(vp *map[float64]uint64, d *Decoder) { - v, changed := f.DecMapFloat64Uint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64Uint64V(v map[float64]uint64, canChange bool, - d *Decoder) (_ map[float64]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[float64]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float64 - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64UintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]uintptr) - v, changed := fastpathTV.DecMapFloat64UintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64UintptrV(rv2i(rv).(map[float64]uintptr), false, d) - } -} -func (f fastpathT) DecMapFloat64UintptrX(vp *map[float64]uintptr, d *Decoder) { - v, changed := f.DecMapFloat64UintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64UintptrV(v map[float64]uintptr, canChange bool, - d *Decoder) (_ map[float64]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[float64]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float64 - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64IntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]int) - v, changed := fastpathTV.DecMapFloat64IntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64IntV(rv2i(rv).(map[float64]int), false, d) - } -} -func (f fastpathT) DecMapFloat64IntX(vp *map[float64]int, d *Decoder) { - v, changed := f.DecMapFloat64IntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64IntV(v map[float64]int, canChange bool, - d *Decoder) (_ map[float64]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[float64]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float64 - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64Int8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]int8) - v, changed := fastpathTV.DecMapFloat64Int8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64Int8V(rv2i(rv).(map[float64]int8), false, d) - } -} -func (f fastpathT) DecMapFloat64Int8X(vp *map[float64]int8, d *Decoder) { - v, changed := f.DecMapFloat64Int8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64Int8V(v map[float64]int8, canChange bool, - d *Decoder) (_ map[float64]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[float64]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float64 - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64Int16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]int16) - v, changed := fastpathTV.DecMapFloat64Int16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64Int16V(rv2i(rv).(map[float64]int16), false, d) - } -} -func (f fastpathT) DecMapFloat64Int16X(vp *map[float64]int16, d *Decoder) { - v, changed := f.DecMapFloat64Int16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64Int16V(v map[float64]int16, canChange bool, - d *Decoder) (_ map[float64]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[float64]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float64 - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64Int32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]int32) - v, changed := fastpathTV.DecMapFloat64Int32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64Int32V(rv2i(rv).(map[float64]int32), false, d) - } -} -func (f fastpathT) DecMapFloat64Int32X(vp *map[float64]int32, d *Decoder) { - v, changed := f.DecMapFloat64Int32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64Int32V(v map[float64]int32, canChange bool, - d *Decoder) (_ map[float64]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[float64]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float64 - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64Int64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]int64) - v, changed := fastpathTV.DecMapFloat64Int64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64Int64V(rv2i(rv).(map[float64]int64), false, d) - } -} -func (f fastpathT) DecMapFloat64Int64X(vp *map[float64]int64, d *Decoder) { - v, changed := f.DecMapFloat64Int64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64Int64V(v map[float64]int64, canChange bool, - d *Decoder) (_ map[float64]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[float64]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float64 - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64Float32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]float32) - v, changed := fastpathTV.DecMapFloat64Float32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64Float32V(rv2i(rv).(map[float64]float32), false, d) - } -} -func (f fastpathT) DecMapFloat64Float32X(vp *map[float64]float32, d *Decoder) { - v, changed := f.DecMapFloat64Float32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64Float32V(v map[float64]float32, canChange bool, - d *Decoder) (_ map[float64]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[float64]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float64 - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64Float64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]float64) - v, changed := fastpathTV.DecMapFloat64Float64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64Float64V(rv2i(rv).(map[float64]float64), false, d) - } -} -func (f fastpathT) DecMapFloat64Float64X(vp *map[float64]float64, d *Decoder) { - v, changed := f.DecMapFloat64Float64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64Float64V(v map[float64]float64, canChange bool, - d *Decoder) (_ map[float64]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[float64]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float64 - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapFloat64BoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[float64]bool) - v, changed := fastpathTV.DecMapFloat64BoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapFloat64BoolV(rv2i(rv).(map[float64]bool), false, d) - } -} -func (f fastpathT) DecMapFloat64BoolX(vp *map[float64]bool, d *Decoder) { - v, changed := f.DecMapFloat64BoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapFloat64BoolV(v map[float64]bool, canChange bool, - d *Decoder) (_ map[float64]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[float64]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk float64 - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeFloat64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintIntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]interface{}) - v, changed := fastpathTV.DecMapUintIntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintIntfV(rv2i(rv).(map[uint]interface{}), false, d) - } -} -func (f fastpathT) DecMapUintIntfX(vp *map[uint]interface{}, d *Decoder) { - v, changed := f.DecMapUintIntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintIntfV(v map[uint]interface{}, canChange bool, - d *Decoder) (_ map[uint]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[uint]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk uint - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintStringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]string) - v, changed := fastpathTV.DecMapUintStringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintStringV(rv2i(rv).(map[uint]string), false, d) - } -} -func (f fastpathT) DecMapUintStringX(vp *map[uint]string, d *Decoder) { - v, changed := f.DecMapUintStringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintStringV(v map[uint]string, canChange bool, - d *Decoder) (_ map[uint]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[uint]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintUintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]uint) - v, changed := fastpathTV.DecMapUintUintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintUintV(rv2i(rv).(map[uint]uint), false, d) - } -} -func (f fastpathT) DecMapUintUintX(vp *map[uint]uint, d *Decoder) { - v, changed := f.DecMapUintUintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintUintV(v map[uint]uint, canChange bool, - d *Decoder) (_ map[uint]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintUint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]uint8) - v, changed := fastpathTV.DecMapUintUint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintUint8V(rv2i(rv).(map[uint]uint8), false, d) - } -} -func (f fastpathT) DecMapUintUint8X(vp *map[uint]uint8, d *Decoder) { - v, changed := f.DecMapUintUint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintUint8V(v map[uint]uint8, canChange bool, - d *Decoder) (_ map[uint]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintUint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]uint16) - v, changed := fastpathTV.DecMapUintUint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintUint16V(rv2i(rv).(map[uint]uint16), false, d) - } -} -func (f fastpathT) DecMapUintUint16X(vp *map[uint]uint16, d *Decoder) { - v, changed := f.DecMapUintUint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintUint16V(v map[uint]uint16, canChange bool, - d *Decoder) (_ map[uint]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uint]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintUint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]uint32) - v, changed := fastpathTV.DecMapUintUint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintUint32V(rv2i(rv).(map[uint]uint32), false, d) - } -} -func (f fastpathT) DecMapUintUint32X(vp *map[uint]uint32, d *Decoder) { - v, changed := f.DecMapUintUint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintUint32V(v map[uint]uint32, canChange bool, - d *Decoder) (_ map[uint]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintUint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]uint64) - v, changed := fastpathTV.DecMapUintUint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintUint64V(rv2i(rv).(map[uint]uint64), false, d) - } -} -func (f fastpathT) DecMapUintUint64X(vp *map[uint]uint64, d *Decoder) { - v, changed := f.DecMapUintUint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintUint64V(v map[uint]uint64, canChange bool, - d *Decoder) (_ map[uint]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintUintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]uintptr) - v, changed := fastpathTV.DecMapUintUintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintUintptrV(rv2i(rv).(map[uint]uintptr), false, d) - } -} -func (f fastpathT) DecMapUintUintptrX(vp *map[uint]uintptr, d *Decoder) { - v, changed := f.DecMapUintUintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintUintptrV(v map[uint]uintptr, canChange bool, - d *Decoder) (_ map[uint]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintIntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]int) - v, changed := fastpathTV.DecMapUintIntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintIntV(rv2i(rv).(map[uint]int), false, d) - } -} -func (f fastpathT) DecMapUintIntX(vp *map[uint]int, d *Decoder) { - v, changed := f.DecMapUintIntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintIntV(v map[uint]int, canChange bool, - d *Decoder) (_ map[uint]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintInt8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]int8) - v, changed := fastpathTV.DecMapUintInt8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintInt8V(rv2i(rv).(map[uint]int8), false, d) - } -} -func (f fastpathT) DecMapUintInt8X(vp *map[uint]int8, d *Decoder) { - v, changed := f.DecMapUintInt8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintInt8V(v map[uint]int8, canChange bool, - d *Decoder) (_ map[uint]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintInt16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]int16) - v, changed := fastpathTV.DecMapUintInt16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintInt16V(rv2i(rv).(map[uint]int16), false, d) - } -} -func (f fastpathT) DecMapUintInt16X(vp *map[uint]int16, d *Decoder) { - v, changed := f.DecMapUintInt16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintInt16V(v map[uint]int16, canChange bool, - d *Decoder) (_ map[uint]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uint]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintInt32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]int32) - v, changed := fastpathTV.DecMapUintInt32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintInt32V(rv2i(rv).(map[uint]int32), false, d) - } -} -func (f fastpathT) DecMapUintInt32X(vp *map[uint]int32, d *Decoder) { - v, changed := f.DecMapUintInt32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintInt32V(v map[uint]int32, canChange bool, - d *Decoder) (_ map[uint]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintInt64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]int64) - v, changed := fastpathTV.DecMapUintInt64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintInt64V(rv2i(rv).(map[uint]int64), false, d) - } -} -func (f fastpathT) DecMapUintInt64X(vp *map[uint]int64, d *Decoder) { - v, changed := f.DecMapUintInt64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintInt64V(v map[uint]int64, canChange bool, - d *Decoder) (_ map[uint]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintFloat32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]float32) - v, changed := fastpathTV.DecMapUintFloat32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintFloat32V(rv2i(rv).(map[uint]float32), false, d) - } -} -func (f fastpathT) DecMapUintFloat32X(vp *map[uint]float32, d *Decoder) { - v, changed := f.DecMapUintFloat32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintFloat32V(v map[uint]float32, canChange bool, - d *Decoder) (_ map[uint]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintFloat64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]float64) - v, changed := fastpathTV.DecMapUintFloat64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintFloat64V(rv2i(rv).(map[uint]float64), false, d) - } -} -func (f fastpathT) DecMapUintFloat64X(vp *map[uint]float64, d *Decoder) { - v, changed := f.DecMapUintFloat64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintFloat64V(v map[uint]float64, canChange bool, - d *Decoder) (_ map[uint]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintBoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint]bool) - v, changed := fastpathTV.DecMapUintBoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintBoolV(rv2i(rv).(map[uint]bool), false, d) - } -} -func (f fastpathT) DecMapUintBoolX(vp *map[uint]bool, d *Decoder) { - v, changed := f.DecMapUintBoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintBoolV(v map[uint]bool, canChange bool, - d *Decoder) (_ map[uint]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8IntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]interface{}) - v, changed := fastpathTV.DecMapUint8IntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8IntfV(rv2i(rv).(map[uint8]interface{}), false, d) - } -} -func (f fastpathT) DecMapUint8IntfX(vp *map[uint8]interface{}, d *Decoder) { - v, changed := f.DecMapUint8IntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8IntfV(v map[uint8]interface{}, canChange bool, - d *Decoder) (_ map[uint8]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[uint8]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk uint8 - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8StringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]string) - v, changed := fastpathTV.DecMapUint8StringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8StringV(rv2i(rv).(map[uint8]string), false, d) - } -} -func (f fastpathT) DecMapUint8StringX(vp *map[uint8]string, d *Decoder) { - v, changed := f.DecMapUint8StringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8StringV(v map[uint8]string, canChange bool, - d *Decoder) (_ map[uint8]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[uint8]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint8 - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8UintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]uint) - v, changed := fastpathTV.DecMapUint8UintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8UintV(rv2i(rv).(map[uint8]uint), false, d) - } -} -func (f fastpathT) DecMapUint8UintX(vp *map[uint8]uint, d *Decoder) { - v, changed := f.DecMapUint8UintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8UintV(v map[uint8]uint, canChange bool, - d *Decoder) (_ map[uint8]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint8]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint8 - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8Uint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]uint8) - v, changed := fastpathTV.DecMapUint8Uint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8Uint8V(rv2i(rv).(map[uint8]uint8), false, d) - } -} -func (f fastpathT) DecMapUint8Uint8X(vp *map[uint8]uint8, d *Decoder) { - v, changed := f.DecMapUint8Uint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8Uint8V(v map[uint8]uint8, canChange bool, - d *Decoder) (_ map[uint8]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 2) - v = make(map[uint8]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint8 - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8Uint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]uint16) - v, changed := fastpathTV.DecMapUint8Uint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8Uint16V(rv2i(rv).(map[uint8]uint16), false, d) - } -} -func (f fastpathT) DecMapUint8Uint16X(vp *map[uint8]uint16, d *Decoder) { - v, changed := f.DecMapUint8Uint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8Uint16V(v map[uint8]uint16, canChange bool, - d *Decoder) (_ map[uint8]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[uint8]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint8 - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8Uint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]uint32) - v, changed := fastpathTV.DecMapUint8Uint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8Uint32V(rv2i(rv).(map[uint8]uint32), false, d) - } -} -func (f fastpathT) DecMapUint8Uint32X(vp *map[uint8]uint32, d *Decoder) { - v, changed := f.DecMapUint8Uint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8Uint32V(v map[uint8]uint32, canChange bool, - d *Decoder) (_ map[uint8]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[uint8]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint8 - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8Uint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]uint64) - v, changed := fastpathTV.DecMapUint8Uint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8Uint64V(rv2i(rv).(map[uint8]uint64), false, d) - } -} -func (f fastpathT) DecMapUint8Uint64X(vp *map[uint8]uint64, d *Decoder) { - v, changed := f.DecMapUint8Uint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8Uint64V(v map[uint8]uint64, canChange bool, - d *Decoder) (_ map[uint8]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint8]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint8 - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8UintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]uintptr) - v, changed := fastpathTV.DecMapUint8UintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8UintptrV(rv2i(rv).(map[uint8]uintptr), false, d) - } -} -func (f fastpathT) DecMapUint8UintptrX(vp *map[uint8]uintptr, d *Decoder) { - v, changed := f.DecMapUint8UintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8UintptrV(v map[uint8]uintptr, canChange bool, - d *Decoder) (_ map[uint8]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint8]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint8 - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8IntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]int) - v, changed := fastpathTV.DecMapUint8IntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8IntV(rv2i(rv).(map[uint8]int), false, d) - } -} -func (f fastpathT) DecMapUint8IntX(vp *map[uint8]int, d *Decoder) { - v, changed := f.DecMapUint8IntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8IntV(v map[uint8]int, canChange bool, - d *Decoder) (_ map[uint8]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint8]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint8 - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8Int8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]int8) - v, changed := fastpathTV.DecMapUint8Int8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8Int8V(rv2i(rv).(map[uint8]int8), false, d) - } -} -func (f fastpathT) DecMapUint8Int8X(vp *map[uint8]int8, d *Decoder) { - v, changed := f.DecMapUint8Int8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8Int8V(v map[uint8]int8, canChange bool, - d *Decoder) (_ map[uint8]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 2) - v = make(map[uint8]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint8 - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8Int16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]int16) - v, changed := fastpathTV.DecMapUint8Int16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8Int16V(rv2i(rv).(map[uint8]int16), false, d) - } -} -func (f fastpathT) DecMapUint8Int16X(vp *map[uint8]int16, d *Decoder) { - v, changed := f.DecMapUint8Int16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8Int16V(v map[uint8]int16, canChange bool, - d *Decoder) (_ map[uint8]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[uint8]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint8 - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8Int32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]int32) - v, changed := fastpathTV.DecMapUint8Int32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8Int32V(rv2i(rv).(map[uint8]int32), false, d) - } -} -func (f fastpathT) DecMapUint8Int32X(vp *map[uint8]int32, d *Decoder) { - v, changed := f.DecMapUint8Int32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8Int32V(v map[uint8]int32, canChange bool, - d *Decoder) (_ map[uint8]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[uint8]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint8 - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8Int64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]int64) - v, changed := fastpathTV.DecMapUint8Int64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8Int64V(rv2i(rv).(map[uint8]int64), false, d) - } -} -func (f fastpathT) DecMapUint8Int64X(vp *map[uint8]int64, d *Decoder) { - v, changed := f.DecMapUint8Int64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8Int64V(v map[uint8]int64, canChange bool, - d *Decoder) (_ map[uint8]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint8]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint8 - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8Float32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]float32) - v, changed := fastpathTV.DecMapUint8Float32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8Float32V(rv2i(rv).(map[uint8]float32), false, d) - } -} -func (f fastpathT) DecMapUint8Float32X(vp *map[uint8]float32, d *Decoder) { - v, changed := f.DecMapUint8Float32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8Float32V(v map[uint8]float32, canChange bool, - d *Decoder) (_ map[uint8]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[uint8]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint8 - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8Float64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]float64) - v, changed := fastpathTV.DecMapUint8Float64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8Float64V(rv2i(rv).(map[uint8]float64), false, d) - } -} -func (f fastpathT) DecMapUint8Float64X(vp *map[uint8]float64, d *Decoder) { - v, changed := f.DecMapUint8Float64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8Float64V(v map[uint8]float64, canChange bool, - d *Decoder) (_ map[uint8]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint8]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint8 - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint8BoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint8]bool) - v, changed := fastpathTV.DecMapUint8BoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint8BoolV(rv2i(rv).(map[uint8]bool), false, d) - } -} -func (f fastpathT) DecMapUint8BoolX(vp *map[uint8]bool, d *Decoder) { - v, changed := f.DecMapUint8BoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint8BoolV(v map[uint8]bool, canChange bool, - d *Decoder) (_ map[uint8]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 2) - v = make(map[uint8]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint8 - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16IntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]interface{}) - v, changed := fastpathTV.DecMapUint16IntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16IntfV(rv2i(rv).(map[uint16]interface{}), false, d) - } -} -func (f fastpathT) DecMapUint16IntfX(vp *map[uint16]interface{}, d *Decoder) { - v, changed := f.DecMapUint16IntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16IntfV(v map[uint16]interface{}, canChange bool, - d *Decoder) (_ map[uint16]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 18) - v = make(map[uint16]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk uint16 - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16StringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]string) - v, changed := fastpathTV.DecMapUint16StringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16StringV(rv2i(rv).(map[uint16]string), false, d) - } -} -func (f fastpathT) DecMapUint16StringX(vp *map[uint16]string, d *Decoder) { - v, changed := f.DecMapUint16StringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16StringV(v map[uint16]string, canChange bool, - d *Decoder) (_ map[uint16]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 18) - v = make(map[uint16]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint16 - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16UintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]uint) - v, changed := fastpathTV.DecMapUint16UintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16UintV(rv2i(rv).(map[uint16]uint), false, d) - } -} -func (f fastpathT) DecMapUint16UintX(vp *map[uint16]uint, d *Decoder) { - v, changed := f.DecMapUint16UintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16UintV(v map[uint16]uint, canChange bool, - d *Decoder) (_ map[uint16]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uint16]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint16 - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16Uint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]uint8) - v, changed := fastpathTV.DecMapUint16Uint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16Uint8V(rv2i(rv).(map[uint16]uint8), false, d) - } -} -func (f fastpathT) DecMapUint16Uint8X(vp *map[uint16]uint8, d *Decoder) { - v, changed := f.DecMapUint16Uint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16Uint8V(v map[uint16]uint8, canChange bool, - d *Decoder) (_ map[uint16]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[uint16]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint16 - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16Uint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]uint16) - v, changed := fastpathTV.DecMapUint16Uint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16Uint16V(rv2i(rv).(map[uint16]uint16), false, d) - } -} -func (f fastpathT) DecMapUint16Uint16X(vp *map[uint16]uint16, d *Decoder) { - v, changed := f.DecMapUint16Uint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16Uint16V(v map[uint16]uint16, canChange bool, - d *Decoder) (_ map[uint16]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 4) - v = make(map[uint16]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint16 - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16Uint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]uint32) - v, changed := fastpathTV.DecMapUint16Uint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16Uint32V(rv2i(rv).(map[uint16]uint32), false, d) - } -} -func (f fastpathT) DecMapUint16Uint32X(vp *map[uint16]uint32, d *Decoder) { - v, changed := f.DecMapUint16Uint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16Uint32V(v map[uint16]uint32, canChange bool, - d *Decoder) (_ map[uint16]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[uint16]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint16 - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16Uint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]uint64) - v, changed := fastpathTV.DecMapUint16Uint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16Uint64V(rv2i(rv).(map[uint16]uint64), false, d) - } -} -func (f fastpathT) DecMapUint16Uint64X(vp *map[uint16]uint64, d *Decoder) { - v, changed := f.DecMapUint16Uint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16Uint64V(v map[uint16]uint64, canChange bool, - d *Decoder) (_ map[uint16]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uint16]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint16 - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16UintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]uintptr) - v, changed := fastpathTV.DecMapUint16UintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16UintptrV(rv2i(rv).(map[uint16]uintptr), false, d) - } -} -func (f fastpathT) DecMapUint16UintptrX(vp *map[uint16]uintptr, d *Decoder) { - v, changed := f.DecMapUint16UintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16UintptrV(v map[uint16]uintptr, canChange bool, - d *Decoder) (_ map[uint16]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uint16]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint16 - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16IntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]int) - v, changed := fastpathTV.DecMapUint16IntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16IntV(rv2i(rv).(map[uint16]int), false, d) - } -} -func (f fastpathT) DecMapUint16IntX(vp *map[uint16]int, d *Decoder) { - v, changed := f.DecMapUint16IntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16IntV(v map[uint16]int, canChange bool, - d *Decoder) (_ map[uint16]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uint16]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint16 - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16Int8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]int8) - v, changed := fastpathTV.DecMapUint16Int8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16Int8V(rv2i(rv).(map[uint16]int8), false, d) - } -} -func (f fastpathT) DecMapUint16Int8X(vp *map[uint16]int8, d *Decoder) { - v, changed := f.DecMapUint16Int8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16Int8V(v map[uint16]int8, canChange bool, - d *Decoder) (_ map[uint16]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[uint16]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint16 - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16Int16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]int16) - v, changed := fastpathTV.DecMapUint16Int16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16Int16V(rv2i(rv).(map[uint16]int16), false, d) - } -} -func (f fastpathT) DecMapUint16Int16X(vp *map[uint16]int16, d *Decoder) { - v, changed := f.DecMapUint16Int16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16Int16V(v map[uint16]int16, canChange bool, - d *Decoder) (_ map[uint16]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 4) - v = make(map[uint16]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint16 - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16Int32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]int32) - v, changed := fastpathTV.DecMapUint16Int32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16Int32V(rv2i(rv).(map[uint16]int32), false, d) - } -} -func (f fastpathT) DecMapUint16Int32X(vp *map[uint16]int32, d *Decoder) { - v, changed := f.DecMapUint16Int32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16Int32V(v map[uint16]int32, canChange bool, - d *Decoder) (_ map[uint16]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[uint16]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint16 - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16Int64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]int64) - v, changed := fastpathTV.DecMapUint16Int64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16Int64V(rv2i(rv).(map[uint16]int64), false, d) - } -} -func (f fastpathT) DecMapUint16Int64X(vp *map[uint16]int64, d *Decoder) { - v, changed := f.DecMapUint16Int64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16Int64V(v map[uint16]int64, canChange bool, - d *Decoder) (_ map[uint16]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uint16]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint16 - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16Float32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]float32) - v, changed := fastpathTV.DecMapUint16Float32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16Float32V(rv2i(rv).(map[uint16]float32), false, d) - } -} -func (f fastpathT) DecMapUint16Float32X(vp *map[uint16]float32, d *Decoder) { - v, changed := f.DecMapUint16Float32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16Float32V(v map[uint16]float32, canChange bool, - d *Decoder) (_ map[uint16]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[uint16]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint16 - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16Float64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]float64) - v, changed := fastpathTV.DecMapUint16Float64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16Float64V(rv2i(rv).(map[uint16]float64), false, d) - } -} -func (f fastpathT) DecMapUint16Float64X(vp *map[uint16]float64, d *Decoder) { - v, changed := f.DecMapUint16Float64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16Float64V(v map[uint16]float64, canChange bool, - d *Decoder) (_ map[uint16]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uint16]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint16 - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint16BoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint16]bool) - v, changed := fastpathTV.DecMapUint16BoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint16BoolV(rv2i(rv).(map[uint16]bool), false, d) - } -} -func (f fastpathT) DecMapUint16BoolX(vp *map[uint16]bool, d *Decoder) { - v, changed := f.DecMapUint16BoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint16BoolV(v map[uint16]bool, canChange bool, - d *Decoder) (_ map[uint16]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[uint16]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint16 - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32IntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]interface{}) - v, changed := fastpathTV.DecMapUint32IntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32IntfV(rv2i(rv).(map[uint32]interface{}), false, d) - } -} -func (f fastpathT) DecMapUint32IntfX(vp *map[uint32]interface{}, d *Decoder) { - v, changed := f.DecMapUint32IntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32IntfV(v map[uint32]interface{}, canChange bool, - d *Decoder) (_ map[uint32]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[uint32]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk uint32 - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32StringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]string) - v, changed := fastpathTV.DecMapUint32StringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32StringV(rv2i(rv).(map[uint32]string), false, d) - } -} -func (f fastpathT) DecMapUint32StringX(vp *map[uint32]string, d *Decoder) { - v, changed := f.DecMapUint32StringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32StringV(v map[uint32]string, canChange bool, - d *Decoder) (_ map[uint32]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[uint32]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint32 - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32UintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]uint) - v, changed := fastpathTV.DecMapUint32UintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32UintV(rv2i(rv).(map[uint32]uint), false, d) - } -} -func (f fastpathT) DecMapUint32UintX(vp *map[uint32]uint, d *Decoder) { - v, changed := f.DecMapUint32UintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32UintV(v map[uint32]uint, canChange bool, - d *Decoder) (_ map[uint32]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint32]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint32 - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32Uint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]uint8) - v, changed := fastpathTV.DecMapUint32Uint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32Uint8V(rv2i(rv).(map[uint32]uint8), false, d) - } -} -func (f fastpathT) DecMapUint32Uint8X(vp *map[uint32]uint8, d *Decoder) { - v, changed := f.DecMapUint32Uint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32Uint8V(v map[uint32]uint8, canChange bool, - d *Decoder) (_ map[uint32]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[uint32]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint32 - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32Uint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]uint16) - v, changed := fastpathTV.DecMapUint32Uint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32Uint16V(rv2i(rv).(map[uint32]uint16), false, d) - } -} -func (f fastpathT) DecMapUint32Uint16X(vp *map[uint32]uint16, d *Decoder) { - v, changed := f.DecMapUint32Uint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32Uint16V(v map[uint32]uint16, canChange bool, - d *Decoder) (_ map[uint32]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[uint32]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint32 - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32Uint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]uint32) - v, changed := fastpathTV.DecMapUint32Uint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32Uint32V(rv2i(rv).(map[uint32]uint32), false, d) - } -} -func (f fastpathT) DecMapUint32Uint32X(vp *map[uint32]uint32, d *Decoder) { - v, changed := f.DecMapUint32Uint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32Uint32V(v map[uint32]uint32, canChange bool, - d *Decoder) (_ map[uint32]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 8) - v = make(map[uint32]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint32 - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32Uint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]uint64) - v, changed := fastpathTV.DecMapUint32Uint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32Uint64V(rv2i(rv).(map[uint32]uint64), false, d) - } -} -func (f fastpathT) DecMapUint32Uint64X(vp *map[uint32]uint64, d *Decoder) { - v, changed := f.DecMapUint32Uint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32Uint64V(v map[uint32]uint64, canChange bool, - d *Decoder) (_ map[uint32]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint32]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint32 - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32UintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]uintptr) - v, changed := fastpathTV.DecMapUint32UintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32UintptrV(rv2i(rv).(map[uint32]uintptr), false, d) - } -} -func (f fastpathT) DecMapUint32UintptrX(vp *map[uint32]uintptr, d *Decoder) { - v, changed := f.DecMapUint32UintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32UintptrV(v map[uint32]uintptr, canChange bool, - d *Decoder) (_ map[uint32]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint32]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint32 - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32IntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]int) - v, changed := fastpathTV.DecMapUint32IntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32IntV(rv2i(rv).(map[uint32]int), false, d) - } -} -func (f fastpathT) DecMapUint32IntX(vp *map[uint32]int, d *Decoder) { - v, changed := f.DecMapUint32IntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32IntV(v map[uint32]int, canChange bool, - d *Decoder) (_ map[uint32]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint32]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint32 - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32Int8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]int8) - v, changed := fastpathTV.DecMapUint32Int8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32Int8V(rv2i(rv).(map[uint32]int8), false, d) - } -} -func (f fastpathT) DecMapUint32Int8X(vp *map[uint32]int8, d *Decoder) { - v, changed := f.DecMapUint32Int8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32Int8V(v map[uint32]int8, canChange bool, - d *Decoder) (_ map[uint32]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[uint32]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint32 - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32Int16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]int16) - v, changed := fastpathTV.DecMapUint32Int16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32Int16V(rv2i(rv).(map[uint32]int16), false, d) - } -} -func (f fastpathT) DecMapUint32Int16X(vp *map[uint32]int16, d *Decoder) { - v, changed := f.DecMapUint32Int16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32Int16V(v map[uint32]int16, canChange bool, - d *Decoder) (_ map[uint32]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[uint32]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint32 - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32Int32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]int32) - v, changed := fastpathTV.DecMapUint32Int32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32Int32V(rv2i(rv).(map[uint32]int32), false, d) - } -} -func (f fastpathT) DecMapUint32Int32X(vp *map[uint32]int32, d *Decoder) { - v, changed := f.DecMapUint32Int32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32Int32V(v map[uint32]int32, canChange bool, - d *Decoder) (_ map[uint32]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 8) - v = make(map[uint32]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint32 - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32Int64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]int64) - v, changed := fastpathTV.DecMapUint32Int64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32Int64V(rv2i(rv).(map[uint32]int64), false, d) - } -} -func (f fastpathT) DecMapUint32Int64X(vp *map[uint32]int64, d *Decoder) { - v, changed := f.DecMapUint32Int64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32Int64V(v map[uint32]int64, canChange bool, - d *Decoder) (_ map[uint32]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint32]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint32 - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32Float32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]float32) - v, changed := fastpathTV.DecMapUint32Float32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32Float32V(rv2i(rv).(map[uint32]float32), false, d) - } -} -func (f fastpathT) DecMapUint32Float32X(vp *map[uint32]float32, d *Decoder) { - v, changed := f.DecMapUint32Float32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32Float32V(v map[uint32]float32, canChange bool, - d *Decoder) (_ map[uint32]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 8) - v = make(map[uint32]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint32 - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32Float64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]float64) - v, changed := fastpathTV.DecMapUint32Float64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32Float64V(rv2i(rv).(map[uint32]float64), false, d) - } -} -func (f fastpathT) DecMapUint32Float64X(vp *map[uint32]float64, d *Decoder) { - v, changed := f.DecMapUint32Float64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32Float64V(v map[uint32]float64, canChange bool, - d *Decoder) (_ map[uint32]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint32]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint32 - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint32BoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint32]bool) - v, changed := fastpathTV.DecMapUint32BoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint32BoolV(rv2i(rv).(map[uint32]bool), false, d) - } -} -func (f fastpathT) DecMapUint32BoolX(vp *map[uint32]bool, d *Decoder) { - v, changed := f.DecMapUint32BoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint32BoolV(v map[uint32]bool, canChange bool, - d *Decoder) (_ map[uint32]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[uint32]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint32 - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64IntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]interface{}) - v, changed := fastpathTV.DecMapUint64IntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64IntfV(rv2i(rv).(map[uint64]interface{}), false, d) - } -} -func (f fastpathT) DecMapUint64IntfX(vp *map[uint64]interface{}, d *Decoder) { - v, changed := f.DecMapUint64IntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64IntfV(v map[uint64]interface{}, canChange bool, - d *Decoder) (_ map[uint64]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[uint64]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk uint64 - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64StringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]string) - v, changed := fastpathTV.DecMapUint64StringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64StringV(rv2i(rv).(map[uint64]string), false, d) - } -} -func (f fastpathT) DecMapUint64StringX(vp *map[uint64]string, d *Decoder) { - v, changed := f.DecMapUint64StringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64StringV(v map[uint64]string, canChange bool, - d *Decoder) (_ map[uint64]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[uint64]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint64 - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64UintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]uint) - v, changed := fastpathTV.DecMapUint64UintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64UintV(rv2i(rv).(map[uint64]uint), false, d) - } -} -func (f fastpathT) DecMapUint64UintX(vp *map[uint64]uint, d *Decoder) { - v, changed := f.DecMapUint64UintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64UintV(v map[uint64]uint, canChange bool, - d *Decoder) (_ map[uint64]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint64]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint64 - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64Uint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]uint8) - v, changed := fastpathTV.DecMapUint64Uint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64Uint8V(rv2i(rv).(map[uint64]uint8), false, d) - } -} -func (f fastpathT) DecMapUint64Uint8X(vp *map[uint64]uint8, d *Decoder) { - v, changed := f.DecMapUint64Uint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64Uint8V(v map[uint64]uint8, canChange bool, - d *Decoder) (_ map[uint64]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint64]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint64 - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64Uint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]uint16) - v, changed := fastpathTV.DecMapUint64Uint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64Uint16V(rv2i(rv).(map[uint64]uint16), false, d) - } -} -func (f fastpathT) DecMapUint64Uint16X(vp *map[uint64]uint16, d *Decoder) { - v, changed := f.DecMapUint64Uint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64Uint16V(v map[uint64]uint16, canChange bool, - d *Decoder) (_ map[uint64]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uint64]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint64 - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64Uint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]uint32) - v, changed := fastpathTV.DecMapUint64Uint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64Uint32V(rv2i(rv).(map[uint64]uint32), false, d) - } -} -func (f fastpathT) DecMapUint64Uint32X(vp *map[uint64]uint32, d *Decoder) { - v, changed := f.DecMapUint64Uint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64Uint32V(v map[uint64]uint32, canChange bool, - d *Decoder) (_ map[uint64]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint64]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint64 - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64Uint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]uint64) - v, changed := fastpathTV.DecMapUint64Uint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64Uint64V(rv2i(rv).(map[uint64]uint64), false, d) - } -} -func (f fastpathT) DecMapUint64Uint64X(vp *map[uint64]uint64, d *Decoder) { - v, changed := f.DecMapUint64Uint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64Uint64V(v map[uint64]uint64, canChange bool, - d *Decoder) (_ map[uint64]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint64]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint64 - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64UintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]uintptr) - v, changed := fastpathTV.DecMapUint64UintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64UintptrV(rv2i(rv).(map[uint64]uintptr), false, d) - } -} -func (f fastpathT) DecMapUint64UintptrX(vp *map[uint64]uintptr, d *Decoder) { - v, changed := f.DecMapUint64UintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64UintptrV(v map[uint64]uintptr, canChange bool, - d *Decoder) (_ map[uint64]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint64]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint64 - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64IntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]int) - v, changed := fastpathTV.DecMapUint64IntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64IntV(rv2i(rv).(map[uint64]int), false, d) - } -} -func (f fastpathT) DecMapUint64IntX(vp *map[uint64]int, d *Decoder) { - v, changed := f.DecMapUint64IntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64IntV(v map[uint64]int, canChange bool, - d *Decoder) (_ map[uint64]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint64]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint64 - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64Int8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]int8) - v, changed := fastpathTV.DecMapUint64Int8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64Int8V(rv2i(rv).(map[uint64]int8), false, d) - } -} -func (f fastpathT) DecMapUint64Int8X(vp *map[uint64]int8, d *Decoder) { - v, changed := f.DecMapUint64Int8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64Int8V(v map[uint64]int8, canChange bool, - d *Decoder) (_ map[uint64]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint64]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint64 - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64Int16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]int16) - v, changed := fastpathTV.DecMapUint64Int16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64Int16V(rv2i(rv).(map[uint64]int16), false, d) - } -} -func (f fastpathT) DecMapUint64Int16X(vp *map[uint64]int16, d *Decoder) { - v, changed := f.DecMapUint64Int16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64Int16V(v map[uint64]int16, canChange bool, - d *Decoder) (_ map[uint64]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uint64]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint64 - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64Int32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]int32) - v, changed := fastpathTV.DecMapUint64Int32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64Int32V(rv2i(rv).(map[uint64]int32), false, d) - } -} -func (f fastpathT) DecMapUint64Int32X(vp *map[uint64]int32, d *Decoder) { - v, changed := f.DecMapUint64Int32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64Int32V(v map[uint64]int32, canChange bool, - d *Decoder) (_ map[uint64]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint64]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint64 - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64Int64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]int64) - v, changed := fastpathTV.DecMapUint64Int64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64Int64V(rv2i(rv).(map[uint64]int64), false, d) - } -} -func (f fastpathT) DecMapUint64Int64X(vp *map[uint64]int64, d *Decoder) { - v, changed := f.DecMapUint64Int64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64Int64V(v map[uint64]int64, canChange bool, - d *Decoder) (_ map[uint64]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint64]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint64 - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64Float32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]float32) - v, changed := fastpathTV.DecMapUint64Float32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64Float32V(rv2i(rv).(map[uint64]float32), false, d) - } -} -func (f fastpathT) DecMapUint64Float32X(vp *map[uint64]float32, d *Decoder) { - v, changed := f.DecMapUint64Float32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64Float32V(v map[uint64]float32, canChange bool, - d *Decoder) (_ map[uint64]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uint64]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint64 - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64Float64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]float64) - v, changed := fastpathTV.DecMapUint64Float64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64Float64V(rv2i(rv).(map[uint64]float64), false, d) - } -} -func (f fastpathT) DecMapUint64Float64X(vp *map[uint64]float64, d *Decoder) { - v, changed := f.DecMapUint64Float64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64Float64V(v map[uint64]float64, canChange bool, - d *Decoder) (_ map[uint64]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uint64]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint64 - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUint64BoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uint64]bool) - v, changed := fastpathTV.DecMapUint64BoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUint64BoolV(rv2i(rv).(map[uint64]bool), false, d) - } -} -func (f fastpathT) DecMapUint64BoolX(vp *map[uint64]bool, d *Decoder) { - v, changed := f.DecMapUint64BoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUint64BoolV(v map[uint64]bool, canChange bool, - d *Decoder) (_ map[uint64]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uint64]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uint64 - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeUint64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrIntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]interface{}) - v, changed := fastpathTV.DecMapUintptrIntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrIntfV(rv2i(rv).(map[uintptr]interface{}), false, d) - } -} -func (f fastpathT) DecMapUintptrIntfX(vp *map[uintptr]interface{}, d *Decoder) { - v, changed := f.DecMapUintptrIntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrIntfV(v map[uintptr]interface{}, canChange bool, - d *Decoder) (_ map[uintptr]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[uintptr]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk uintptr - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrStringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]string) - v, changed := fastpathTV.DecMapUintptrStringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrStringV(rv2i(rv).(map[uintptr]string), false, d) - } -} -func (f fastpathT) DecMapUintptrStringX(vp *map[uintptr]string, d *Decoder) { - v, changed := f.DecMapUintptrStringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrStringV(v map[uintptr]string, canChange bool, - d *Decoder) (_ map[uintptr]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[uintptr]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uintptr - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrUintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]uint) - v, changed := fastpathTV.DecMapUintptrUintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrUintV(rv2i(rv).(map[uintptr]uint), false, d) - } -} -func (f fastpathT) DecMapUintptrUintX(vp *map[uintptr]uint, d *Decoder) { - v, changed := f.DecMapUintptrUintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrUintV(v map[uintptr]uint, canChange bool, - d *Decoder) (_ map[uintptr]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uintptr]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uintptr - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrUint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]uint8) - v, changed := fastpathTV.DecMapUintptrUint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrUint8V(rv2i(rv).(map[uintptr]uint8), false, d) - } -} -func (f fastpathT) DecMapUintptrUint8X(vp *map[uintptr]uint8, d *Decoder) { - v, changed := f.DecMapUintptrUint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrUint8V(v map[uintptr]uint8, canChange bool, - d *Decoder) (_ map[uintptr]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uintptr]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uintptr - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrUint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]uint16) - v, changed := fastpathTV.DecMapUintptrUint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrUint16V(rv2i(rv).(map[uintptr]uint16), false, d) - } -} -func (f fastpathT) DecMapUintptrUint16X(vp *map[uintptr]uint16, d *Decoder) { - v, changed := f.DecMapUintptrUint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrUint16V(v map[uintptr]uint16, canChange bool, - d *Decoder) (_ map[uintptr]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uintptr]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uintptr - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrUint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]uint32) - v, changed := fastpathTV.DecMapUintptrUint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrUint32V(rv2i(rv).(map[uintptr]uint32), false, d) - } -} -func (f fastpathT) DecMapUintptrUint32X(vp *map[uintptr]uint32, d *Decoder) { - v, changed := f.DecMapUintptrUint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrUint32V(v map[uintptr]uint32, canChange bool, - d *Decoder) (_ map[uintptr]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uintptr]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uintptr - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrUint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]uint64) - v, changed := fastpathTV.DecMapUintptrUint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrUint64V(rv2i(rv).(map[uintptr]uint64), false, d) - } -} -func (f fastpathT) DecMapUintptrUint64X(vp *map[uintptr]uint64, d *Decoder) { - v, changed := f.DecMapUintptrUint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrUint64V(v map[uintptr]uint64, canChange bool, - d *Decoder) (_ map[uintptr]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uintptr]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uintptr - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrUintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]uintptr) - v, changed := fastpathTV.DecMapUintptrUintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrUintptrV(rv2i(rv).(map[uintptr]uintptr), false, d) - } -} -func (f fastpathT) DecMapUintptrUintptrX(vp *map[uintptr]uintptr, d *Decoder) { - v, changed := f.DecMapUintptrUintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrUintptrV(v map[uintptr]uintptr, canChange bool, - d *Decoder) (_ map[uintptr]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uintptr]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uintptr - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrIntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]int) - v, changed := fastpathTV.DecMapUintptrIntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrIntV(rv2i(rv).(map[uintptr]int), false, d) - } -} -func (f fastpathT) DecMapUintptrIntX(vp *map[uintptr]int, d *Decoder) { - v, changed := f.DecMapUintptrIntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrIntV(v map[uintptr]int, canChange bool, - d *Decoder) (_ map[uintptr]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uintptr]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uintptr - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrInt8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]int8) - v, changed := fastpathTV.DecMapUintptrInt8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrInt8V(rv2i(rv).(map[uintptr]int8), false, d) - } -} -func (f fastpathT) DecMapUintptrInt8X(vp *map[uintptr]int8, d *Decoder) { - v, changed := f.DecMapUintptrInt8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrInt8V(v map[uintptr]int8, canChange bool, - d *Decoder) (_ map[uintptr]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uintptr]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uintptr - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrInt16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]int16) - v, changed := fastpathTV.DecMapUintptrInt16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrInt16V(rv2i(rv).(map[uintptr]int16), false, d) - } -} -func (f fastpathT) DecMapUintptrInt16X(vp *map[uintptr]int16, d *Decoder) { - v, changed := f.DecMapUintptrInt16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrInt16V(v map[uintptr]int16, canChange bool, - d *Decoder) (_ map[uintptr]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[uintptr]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uintptr - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrInt32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]int32) - v, changed := fastpathTV.DecMapUintptrInt32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrInt32V(rv2i(rv).(map[uintptr]int32), false, d) - } -} -func (f fastpathT) DecMapUintptrInt32X(vp *map[uintptr]int32, d *Decoder) { - v, changed := f.DecMapUintptrInt32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrInt32V(v map[uintptr]int32, canChange bool, - d *Decoder) (_ map[uintptr]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uintptr]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uintptr - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrInt64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]int64) - v, changed := fastpathTV.DecMapUintptrInt64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrInt64V(rv2i(rv).(map[uintptr]int64), false, d) - } -} -func (f fastpathT) DecMapUintptrInt64X(vp *map[uintptr]int64, d *Decoder) { - v, changed := f.DecMapUintptrInt64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrInt64V(v map[uintptr]int64, canChange bool, - d *Decoder) (_ map[uintptr]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uintptr]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uintptr - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrFloat32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]float32) - v, changed := fastpathTV.DecMapUintptrFloat32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrFloat32V(rv2i(rv).(map[uintptr]float32), false, d) - } -} -func (f fastpathT) DecMapUintptrFloat32X(vp *map[uintptr]float32, d *Decoder) { - v, changed := f.DecMapUintptrFloat32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrFloat32V(v map[uintptr]float32, canChange bool, - d *Decoder) (_ map[uintptr]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[uintptr]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uintptr - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrFloat64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]float64) - v, changed := fastpathTV.DecMapUintptrFloat64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrFloat64V(rv2i(rv).(map[uintptr]float64), false, d) - } -} -func (f fastpathT) DecMapUintptrFloat64X(vp *map[uintptr]float64, d *Decoder) { - v, changed := f.DecMapUintptrFloat64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrFloat64V(v map[uintptr]float64, canChange bool, - d *Decoder) (_ map[uintptr]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[uintptr]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uintptr - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapUintptrBoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[uintptr]bool) - v, changed := fastpathTV.DecMapUintptrBoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapUintptrBoolV(rv2i(rv).(map[uintptr]bool), false, d) - } -} -func (f fastpathT) DecMapUintptrBoolX(vp *map[uintptr]bool, d *Decoder) { - v, changed := f.DecMapUintptrBoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapUintptrBoolV(v map[uintptr]bool, canChange bool, - d *Decoder) (_ map[uintptr]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[uintptr]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk uintptr - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntIntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]interface{}) - v, changed := fastpathTV.DecMapIntIntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntIntfV(rv2i(rv).(map[int]interface{}), false, d) - } -} -func (f fastpathT) DecMapIntIntfX(vp *map[int]interface{}, d *Decoder) { - v, changed := f.DecMapIntIntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntIntfV(v map[int]interface{}, canChange bool, - d *Decoder) (_ map[int]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[int]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk int - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntStringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]string) - v, changed := fastpathTV.DecMapIntStringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntStringV(rv2i(rv).(map[int]string), false, d) - } -} -func (f fastpathT) DecMapIntStringX(vp *map[int]string, d *Decoder) { - v, changed := f.DecMapIntStringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntStringV(v map[int]string, canChange bool, - d *Decoder) (_ map[int]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[int]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntUintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]uint) - v, changed := fastpathTV.DecMapIntUintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntUintV(rv2i(rv).(map[int]uint), false, d) - } -} -func (f fastpathT) DecMapIntUintX(vp *map[int]uint, d *Decoder) { - v, changed := f.DecMapIntUintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntUintV(v map[int]uint, canChange bool, - d *Decoder) (_ map[int]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntUint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]uint8) - v, changed := fastpathTV.DecMapIntUint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntUint8V(rv2i(rv).(map[int]uint8), false, d) - } -} -func (f fastpathT) DecMapIntUint8X(vp *map[int]uint8, d *Decoder) { - v, changed := f.DecMapIntUint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntUint8V(v map[int]uint8, canChange bool, - d *Decoder) (_ map[int]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntUint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]uint16) - v, changed := fastpathTV.DecMapIntUint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntUint16V(rv2i(rv).(map[int]uint16), false, d) - } -} -func (f fastpathT) DecMapIntUint16X(vp *map[int]uint16, d *Decoder) { - v, changed := f.DecMapIntUint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntUint16V(v map[int]uint16, canChange bool, - d *Decoder) (_ map[int]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[int]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntUint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]uint32) - v, changed := fastpathTV.DecMapIntUint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntUint32V(rv2i(rv).(map[int]uint32), false, d) - } -} -func (f fastpathT) DecMapIntUint32X(vp *map[int]uint32, d *Decoder) { - v, changed := f.DecMapIntUint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntUint32V(v map[int]uint32, canChange bool, - d *Decoder) (_ map[int]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntUint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]uint64) - v, changed := fastpathTV.DecMapIntUint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntUint64V(rv2i(rv).(map[int]uint64), false, d) - } -} -func (f fastpathT) DecMapIntUint64X(vp *map[int]uint64, d *Decoder) { - v, changed := f.DecMapIntUint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntUint64V(v map[int]uint64, canChange bool, - d *Decoder) (_ map[int]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntUintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]uintptr) - v, changed := fastpathTV.DecMapIntUintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntUintptrV(rv2i(rv).(map[int]uintptr), false, d) - } -} -func (f fastpathT) DecMapIntUintptrX(vp *map[int]uintptr, d *Decoder) { - v, changed := f.DecMapIntUintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntUintptrV(v map[int]uintptr, canChange bool, - d *Decoder) (_ map[int]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntIntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]int) - v, changed := fastpathTV.DecMapIntIntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntIntV(rv2i(rv).(map[int]int), false, d) - } -} -func (f fastpathT) DecMapIntIntX(vp *map[int]int, d *Decoder) { - v, changed := f.DecMapIntIntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntIntV(v map[int]int, canChange bool, - d *Decoder) (_ map[int]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntInt8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]int8) - v, changed := fastpathTV.DecMapIntInt8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntInt8V(rv2i(rv).(map[int]int8), false, d) - } -} -func (f fastpathT) DecMapIntInt8X(vp *map[int]int8, d *Decoder) { - v, changed := f.DecMapIntInt8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntInt8V(v map[int]int8, canChange bool, - d *Decoder) (_ map[int]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntInt16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]int16) - v, changed := fastpathTV.DecMapIntInt16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntInt16V(rv2i(rv).(map[int]int16), false, d) - } -} -func (f fastpathT) DecMapIntInt16X(vp *map[int]int16, d *Decoder) { - v, changed := f.DecMapIntInt16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntInt16V(v map[int]int16, canChange bool, - d *Decoder) (_ map[int]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[int]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntInt32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]int32) - v, changed := fastpathTV.DecMapIntInt32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntInt32V(rv2i(rv).(map[int]int32), false, d) - } -} -func (f fastpathT) DecMapIntInt32X(vp *map[int]int32, d *Decoder) { - v, changed := f.DecMapIntInt32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntInt32V(v map[int]int32, canChange bool, - d *Decoder) (_ map[int]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntInt64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]int64) - v, changed := fastpathTV.DecMapIntInt64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntInt64V(rv2i(rv).(map[int]int64), false, d) - } -} -func (f fastpathT) DecMapIntInt64X(vp *map[int]int64, d *Decoder) { - v, changed := f.DecMapIntInt64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntInt64V(v map[int]int64, canChange bool, - d *Decoder) (_ map[int]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntFloat32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]float32) - v, changed := fastpathTV.DecMapIntFloat32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntFloat32V(rv2i(rv).(map[int]float32), false, d) - } -} -func (f fastpathT) DecMapIntFloat32X(vp *map[int]float32, d *Decoder) { - v, changed := f.DecMapIntFloat32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntFloat32V(v map[int]float32, canChange bool, - d *Decoder) (_ map[int]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntFloat64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]float64) - v, changed := fastpathTV.DecMapIntFloat64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntFloat64V(rv2i(rv).(map[int]float64), false, d) - } -} -func (f fastpathT) DecMapIntFloat64X(vp *map[int]float64, d *Decoder) { - v, changed := f.DecMapIntFloat64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntFloat64V(v map[int]float64, canChange bool, - d *Decoder) (_ map[int]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapIntBoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int]bool) - v, changed := fastpathTV.DecMapIntBoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapIntBoolV(rv2i(rv).(map[int]bool), false, d) - } -} -func (f fastpathT) DecMapIntBoolX(vp *map[int]bool, d *Decoder) { - v, changed := f.DecMapIntBoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapIntBoolV(v map[int]bool, canChange bool, - d *Decoder) (_ map[int]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8IntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]interface{}) - v, changed := fastpathTV.DecMapInt8IntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8IntfV(rv2i(rv).(map[int8]interface{}), false, d) - } -} -func (f fastpathT) DecMapInt8IntfX(vp *map[int8]interface{}, d *Decoder) { - v, changed := f.DecMapInt8IntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8IntfV(v map[int8]interface{}, canChange bool, - d *Decoder) (_ map[int8]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[int8]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk int8 - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8StringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]string) - v, changed := fastpathTV.DecMapInt8StringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8StringV(rv2i(rv).(map[int8]string), false, d) - } -} -func (f fastpathT) DecMapInt8StringX(vp *map[int8]string, d *Decoder) { - v, changed := f.DecMapInt8StringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8StringV(v map[int8]string, canChange bool, - d *Decoder) (_ map[int8]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[int8]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int8 - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8UintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]uint) - v, changed := fastpathTV.DecMapInt8UintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8UintV(rv2i(rv).(map[int8]uint), false, d) - } -} -func (f fastpathT) DecMapInt8UintX(vp *map[int8]uint, d *Decoder) { - v, changed := f.DecMapInt8UintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8UintV(v map[int8]uint, canChange bool, - d *Decoder) (_ map[int8]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int8]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int8 - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8Uint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]uint8) - v, changed := fastpathTV.DecMapInt8Uint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8Uint8V(rv2i(rv).(map[int8]uint8), false, d) - } -} -func (f fastpathT) DecMapInt8Uint8X(vp *map[int8]uint8, d *Decoder) { - v, changed := f.DecMapInt8Uint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8Uint8V(v map[int8]uint8, canChange bool, - d *Decoder) (_ map[int8]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 2) - v = make(map[int8]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int8 - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8Uint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]uint16) - v, changed := fastpathTV.DecMapInt8Uint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8Uint16V(rv2i(rv).(map[int8]uint16), false, d) - } -} -func (f fastpathT) DecMapInt8Uint16X(vp *map[int8]uint16, d *Decoder) { - v, changed := f.DecMapInt8Uint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8Uint16V(v map[int8]uint16, canChange bool, - d *Decoder) (_ map[int8]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[int8]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int8 - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8Uint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]uint32) - v, changed := fastpathTV.DecMapInt8Uint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8Uint32V(rv2i(rv).(map[int8]uint32), false, d) - } -} -func (f fastpathT) DecMapInt8Uint32X(vp *map[int8]uint32, d *Decoder) { - v, changed := f.DecMapInt8Uint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8Uint32V(v map[int8]uint32, canChange bool, - d *Decoder) (_ map[int8]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[int8]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int8 - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8Uint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]uint64) - v, changed := fastpathTV.DecMapInt8Uint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8Uint64V(rv2i(rv).(map[int8]uint64), false, d) - } -} -func (f fastpathT) DecMapInt8Uint64X(vp *map[int8]uint64, d *Decoder) { - v, changed := f.DecMapInt8Uint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8Uint64V(v map[int8]uint64, canChange bool, - d *Decoder) (_ map[int8]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int8]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int8 - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8UintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]uintptr) - v, changed := fastpathTV.DecMapInt8UintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8UintptrV(rv2i(rv).(map[int8]uintptr), false, d) - } -} -func (f fastpathT) DecMapInt8UintptrX(vp *map[int8]uintptr, d *Decoder) { - v, changed := f.DecMapInt8UintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8UintptrV(v map[int8]uintptr, canChange bool, - d *Decoder) (_ map[int8]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int8]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int8 - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8IntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]int) - v, changed := fastpathTV.DecMapInt8IntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8IntV(rv2i(rv).(map[int8]int), false, d) - } -} -func (f fastpathT) DecMapInt8IntX(vp *map[int8]int, d *Decoder) { - v, changed := f.DecMapInt8IntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8IntV(v map[int8]int, canChange bool, - d *Decoder) (_ map[int8]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int8]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int8 - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8Int8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]int8) - v, changed := fastpathTV.DecMapInt8Int8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8Int8V(rv2i(rv).(map[int8]int8), false, d) - } -} -func (f fastpathT) DecMapInt8Int8X(vp *map[int8]int8, d *Decoder) { - v, changed := f.DecMapInt8Int8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8Int8V(v map[int8]int8, canChange bool, - d *Decoder) (_ map[int8]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 2) - v = make(map[int8]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int8 - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8Int16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]int16) - v, changed := fastpathTV.DecMapInt8Int16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8Int16V(rv2i(rv).(map[int8]int16), false, d) - } -} -func (f fastpathT) DecMapInt8Int16X(vp *map[int8]int16, d *Decoder) { - v, changed := f.DecMapInt8Int16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8Int16V(v map[int8]int16, canChange bool, - d *Decoder) (_ map[int8]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[int8]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int8 - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8Int32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]int32) - v, changed := fastpathTV.DecMapInt8Int32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8Int32V(rv2i(rv).(map[int8]int32), false, d) - } -} -func (f fastpathT) DecMapInt8Int32X(vp *map[int8]int32, d *Decoder) { - v, changed := f.DecMapInt8Int32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8Int32V(v map[int8]int32, canChange bool, - d *Decoder) (_ map[int8]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[int8]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int8 - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8Int64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]int64) - v, changed := fastpathTV.DecMapInt8Int64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8Int64V(rv2i(rv).(map[int8]int64), false, d) - } -} -func (f fastpathT) DecMapInt8Int64X(vp *map[int8]int64, d *Decoder) { - v, changed := f.DecMapInt8Int64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8Int64V(v map[int8]int64, canChange bool, - d *Decoder) (_ map[int8]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int8]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int8 - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8Float32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]float32) - v, changed := fastpathTV.DecMapInt8Float32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8Float32V(rv2i(rv).(map[int8]float32), false, d) - } -} -func (f fastpathT) DecMapInt8Float32X(vp *map[int8]float32, d *Decoder) { - v, changed := f.DecMapInt8Float32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8Float32V(v map[int8]float32, canChange bool, - d *Decoder) (_ map[int8]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[int8]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int8 - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8Float64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]float64) - v, changed := fastpathTV.DecMapInt8Float64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8Float64V(rv2i(rv).(map[int8]float64), false, d) - } -} -func (f fastpathT) DecMapInt8Float64X(vp *map[int8]float64, d *Decoder) { - v, changed := f.DecMapInt8Float64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8Float64V(v map[int8]float64, canChange bool, - d *Decoder) (_ map[int8]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int8]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int8 - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt8BoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int8]bool) - v, changed := fastpathTV.DecMapInt8BoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt8BoolV(rv2i(rv).(map[int8]bool), false, d) - } -} -func (f fastpathT) DecMapInt8BoolX(vp *map[int8]bool, d *Decoder) { - v, changed := f.DecMapInt8BoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt8BoolV(v map[int8]bool, canChange bool, - d *Decoder) (_ map[int8]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 2) - v = make(map[int8]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int8 - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16IntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]interface{}) - v, changed := fastpathTV.DecMapInt16IntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16IntfV(rv2i(rv).(map[int16]interface{}), false, d) - } -} -func (f fastpathT) DecMapInt16IntfX(vp *map[int16]interface{}, d *Decoder) { - v, changed := f.DecMapInt16IntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16IntfV(v map[int16]interface{}, canChange bool, - d *Decoder) (_ map[int16]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 18) - v = make(map[int16]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk int16 - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16StringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]string) - v, changed := fastpathTV.DecMapInt16StringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16StringV(rv2i(rv).(map[int16]string), false, d) - } -} -func (f fastpathT) DecMapInt16StringX(vp *map[int16]string, d *Decoder) { - v, changed := f.DecMapInt16StringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16StringV(v map[int16]string, canChange bool, - d *Decoder) (_ map[int16]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 18) - v = make(map[int16]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int16 - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16UintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]uint) - v, changed := fastpathTV.DecMapInt16UintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16UintV(rv2i(rv).(map[int16]uint), false, d) - } -} -func (f fastpathT) DecMapInt16UintX(vp *map[int16]uint, d *Decoder) { - v, changed := f.DecMapInt16UintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16UintV(v map[int16]uint, canChange bool, - d *Decoder) (_ map[int16]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[int16]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int16 - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16Uint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]uint8) - v, changed := fastpathTV.DecMapInt16Uint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16Uint8V(rv2i(rv).(map[int16]uint8), false, d) - } -} -func (f fastpathT) DecMapInt16Uint8X(vp *map[int16]uint8, d *Decoder) { - v, changed := f.DecMapInt16Uint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16Uint8V(v map[int16]uint8, canChange bool, - d *Decoder) (_ map[int16]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[int16]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int16 - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16Uint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]uint16) - v, changed := fastpathTV.DecMapInt16Uint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16Uint16V(rv2i(rv).(map[int16]uint16), false, d) - } -} -func (f fastpathT) DecMapInt16Uint16X(vp *map[int16]uint16, d *Decoder) { - v, changed := f.DecMapInt16Uint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16Uint16V(v map[int16]uint16, canChange bool, - d *Decoder) (_ map[int16]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 4) - v = make(map[int16]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int16 - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16Uint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]uint32) - v, changed := fastpathTV.DecMapInt16Uint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16Uint32V(rv2i(rv).(map[int16]uint32), false, d) - } -} -func (f fastpathT) DecMapInt16Uint32X(vp *map[int16]uint32, d *Decoder) { - v, changed := f.DecMapInt16Uint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16Uint32V(v map[int16]uint32, canChange bool, - d *Decoder) (_ map[int16]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[int16]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int16 - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16Uint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]uint64) - v, changed := fastpathTV.DecMapInt16Uint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16Uint64V(rv2i(rv).(map[int16]uint64), false, d) - } -} -func (f fastpathT) DecMapInt16Uint64X(vp *map[int16]uint64, d *Decoder) { - v, changed := f.DecMapInt16Uint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16Uint64V(v map[int16]uint64, canChange bool, - d *Decoder) (_ map[int16]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[int16]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int16 - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16UintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]uintptr) - v, changed := fastpathTV.DecMapInt16UintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16UintptrV(rv2i(rv).(map[int16]uintptr), false, d) - } -} -func (f fastpathT) DecMapInt16UintptrX(vp *map[int16]uintptr, d *Decoder) { - v, changed := f.DecMapInt16UintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16UintptrV(v map[int16]uintptr, canChange bool, - d *Decoder) (_ map[int16]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[int16]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int16 - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16IntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]int) - v, changed := fastpathTV.DecMapInt16IntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16IntV(rv2i(rv).(map[int16]int), false, d) - } -} -func (f fastpathT) DecMapInt16IntX(vp *map[int16]int, d *Decoder) { - v, changed := f.DecMapInt16IntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16IntV(v map[int16]int, canChange bool, - d *Decoder) (_ map[int16]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[int16]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int16 - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16Int8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]int8) - v, changed := fastpathTV.DecMapInt16Int8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16Int8V(rv2i(rv).(map[int16]int8), false, d) - } -} -func (f fastpathT) DecMapInt16Int8X(vp *map[int16]int8, d *Decoder) { - v, changed := f.DecMapInt16Int8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16Int8V(v map[int16]int8, canChange bool, - d *Decoder) (_ map[int16]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[int16]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int16 - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16Int16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]int16) - v, changed := fastpathTV.DecMapInt16Int16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16Int16V(rv2i(rv).(map[int16]int16), false, d) - } -} -func (f fastpathT) DecMapInt16Int16X(vp *map[int16]int16, d *Decoder) { - v, changed := f.DecMapInt16Int16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16Int16V(v map[int16]int16, canChange bool, - d *Decoder) (_ map[int16]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 4) - v = make(map[int16]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int16 - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16Int32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]int32) - v, changed := fastpathTV.DecMapInt16Int32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16Int32V(rv2i(rv).(map[int16]int32), false, d) - } -} -func (f fastpathT) DecMapInt16Int32X(vp *map[int16]int32, d *Decoder) { - v, changed := f.DecMapInt16Int32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16Int32V(v map[int16]int32, canChange bool, - d *Decoder) (_ map[int16]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[int16]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int16 - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16Int64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]int64) - v, changed := fastpathTV.DecMapInt16Int64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16Int64V(rv2i(rv).(map[int16]int64), false, d) - } -} -func (f fastpathT) DecMapInt16Int64X(vp *map[int16]int64, d *Decoder) { - v, changed := f.DecMapInt16Int64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16Int64V(v map[int16]int64, canChange bool, - d *Decoder) (_ map[int16]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[int16]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int16 - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16Float32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]float32) - v, changed := fastpathTV.DecMapInt16Float32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16Float32V(rv2i(rv).(map[int16]float32), false, d) - } -} -func (f fastpathT) DecMapInt16Float32X(vp *map[int16]float32, d *Decoder) { - v, changed := f.DecMapInt16Float32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16Float32V(v map[int16]float32, canChange bool, - d *Decoder) (_ map[int16]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[int16]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int16 - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16Float64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]float64) - v, changed := fastpathTV.DecMapInt16Float64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16Float64V(rv2i(rv).(map[int16]float64), false, d) - } -} -func (f fastpathT) DecMapInt16Float64X(vp *map[int16]float64, d *Decoder) { - v, changed := f.DecMapInt16Float64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16Float64V(v map[int16]float64, canChange bool, - d *Decoder) (_ map[int16]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[int16]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int16 - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt16BoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int16]bool) - v, changed := fastpathTV.DecMapInt16BoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt16BoolV(rv2i(rv).(map[int16]bool), false, d) - } -} -func (f fastpathT) DecMapInt16BoolX(vp *map[int16]bool, d *Decoder) { - v, changed := f.DecMapInt16BoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt16BoolV(v map[int16]bool, canChange bool, - d *Decoder) (_ map[int16]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[int16]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int16 - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32IntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]interface{}) - v, changed := fastpathTV.DecMapInt32IntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32IntfV(rv2i(rv).(map[int32]interface{}), false, d) - } -} -func (f fastpathT) DecMapInt32IntfX(vp *map[int32]interface{}, d *Decoder) { - v, changed := f.DecMapInt32IntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32IntfV(v map[int32]interface{}, canChange bool, - d *Decoder) (_ map[int32]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[int32]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk int32 - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32StringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]string) - v, changed := fastpathTV.DecMapInt32StringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32StringV(rv2i(rv).(map[int32]string), false, d) - } -} -func (f fastpathT) DecMapInt32StringX(vp *map[int32]string, d *Decoder) { - v, changed := f.DecMapInt32StringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32StringV(v map[int32]string, canChange bool, - d *Decoder) (_ map[int32]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 20) - v = make(map[int32]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int32 - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32UintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]uint) - v, changed := fastpathTV.DecMapInt32UintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32UintV(rv2i(rv).(map[int32]uint), false, d) - } -} -func (f fastpathT) DecMapInt32UintX(vp *map[int32]uint, d *Decoder) { - v, changed := f.DecMapInt32UintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32UintV(v map[int32]uint, canChange bool, - d *Decoder) (_ map[int32]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int32]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int32 - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32Uint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]uint8) - v, changed := fastpathTV.DecMapInt32Uint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32Uint8V(rv2i(rv).(map[int32]uint8), false, d) - } -} -func (f fastpathT) DecMapInt32Uint8X(vp *map[int32]uint8, d *Decoder) { - v, changed := f.DecMapInt32Uint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32Uint8V(v map[int32]uint8, canChange bool, - d *Decoder) (_ map[int32]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[int32]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int32 - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32Uint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]uint16) - v, changed := fastpathTV.DecMapInt32Uint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32Uint16V(rv2i(rv).(map[int32]uint16), false, d) - } -} -func (f fastpathT) DecMapInt32Uint16X(vp *map[int32]uint16, d *Decoder) { - v, changed := f.DecMapInt32Uint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32Uint16V(v map[int32]uint16, canChange bool, - d *Decoder) (_ map[int32]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[int32]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int32 - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32Uint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]uint32) - v, changed := fastpathTV.DecMapInt32Uint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32Uint32V(rv2i(rv).(map[int32]uint32), false, d) - } -} -func (f fastpathT) DecMapInt32Uint32X(vp *map[int32]uint32, d *Decoder) { - v, changed := f.DecMapInt32Uint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32Uint32V(v map[int32]uint32, canChange bool, - d *Decoder) (_ map[int32]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 8) - v = make(map[int32]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int32 - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32Uint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]uint64) - v, changed := fastpathTV.DecMapInt32Uint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32Uint64V(rv2i(rv).(map[int32]uint64), false, d) - } -} -func (f fastpathT) DecMapInt32Uint64X(vp *map[int32]uint64, d *Decoder) { - v, changed := f.DecMapInt32Uint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32Uint64V(v map[int32]uint64, canChange bool, - d *Decoder) (_ map[int32]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int32]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int32 - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32UintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]uintptr) - v, changed := fastpathTV.DecMapInt32UintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32UintptrV(rv2i(rv).(map[int32]uintptr), false, d) - } -} -func (f fastpathT) DecMapInt32UintptrX(vp *map[int32]uintptr, d *Decoder) { - v, changed := f.DecMapInt32UintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32UintptrV(v map[int32]uintptr, canChange bool, - d *Decoder) (_ map[int32]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int32]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int32 - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32IntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]int) - v, changed := fastpathTV.DecMapInt32IntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32IntV(rv2i(rv).(map[int32]int), false, d) - } -} -func (f fastpathT) DecMapInt32IntX(vp *map[int32]int, d *Decoder) { - v, changed := f.DecMapInt32IntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32IntV(v map[int32]int, canChange bool, - d *Decoder) (_ map[int32]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int32]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int32 - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32Int8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]int8) - v, changed := fastpathTV.DecMapInt32Int8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32Int8V(rv2i(rv).(map[int32]int8), false, d) - } -} -func (f fastpathT) DecMapInt32Int8X(vp *map[int32]int8, d *Decoder) { - v, changed := f.DecMapInt32Int8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32Int8V(v map[int32]int8, canChange bool, - d *Decoder) (_ map[int32]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[int32]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int32 - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32Int16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]int16) - v, changed := fastpathTV.DecMapInt32Int16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32Int16V(rv2i(rv).(map[int32]int16), false, d) - } -} -func (f fastpathT) DecMapInt32Int16X(vp *map[int32]int16, d *Decoder) { - v, changed := f.DecMapInt32Int16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32Int16V(v map[int32]int16, canChange bool, - d *Decoder) (_ map[int32]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 6) - v = make(map[int32]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int32 - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32Int32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]int32) - v, changed := fastpathTV.DecMapInt32Int32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32Int32V(rv2i(rv).(map[int32]int32), false, d) - } -} -func (f fastpathT) DecMapInt32Int32X(vp *map[int32]int32, d *Decoder) { - v, changed := f.DecMapInt32Int32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32Int32V(v map[int32]int32, canChange bool, - d *Decoder) (_ map[int32]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 8) - v = make(map[int32]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int32 - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32Int64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]int64) - v, changed := fastpathTV.DecMapInt32Int64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32Int64V(rv2i(rv).(map[int32]int64), false, d) - } -} -func (f fastpathT) DecMapInt32Int64X(vp *map[int32]int64, d *Decoder) { - v, changed := f.DecMapInt32Int64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32Int64V(v map[int32]int64, canChange bool, - d *Decoder) (_ map[int32]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int32]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int32 - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32Float32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]float32) - v, changed := fastpathTV.DecMapInt32Float32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32Float32V(rv2i(rv).(map[int32]float32), false, d) - } -} -func (f fastpathT) DecMapInt32Float32X(vp *map[int32]float32, d *Decoder) { - v, changed := f.DecMapInt32Float32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32Float32V(v map[int32]float32, canChange bool, - d *Decoder) (_ map[int32]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 8) - v = make(map[int32]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int32 - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32Float64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]float64) - v, changed := fastpathTV.DecMapInt32Float64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32Float64V(rv2i(rv).(map[int32]float64), false, d) - } -} -func (f fastpathT) DecMapInt32Float64X(vp *map[int32]float64, d *Decoder) { - v, changed := f.DecMapInt32Float64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32Float64V(v map[int32]float64, canChange bool, - d *Decoder) (_ map[int32]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int32]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int32 - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt32BoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int32]bool) - v, changed := fastpathTV.DecMapInt32BoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt32BoolV(rv2i(rv).(map[int32]bool), false, d) - } -} -func (f fastpathT) DecMapInt32BoolX(vp *map[int32]bool, d *Decoder) { - v, changed := f.DecMapInt32BoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt32BoolV(v map[int32]bool, canChange bool, - d *Decoder) (_ map[int32]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[int32]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int32 - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64IntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]interface{}) - v, changed := fastpathTV.DecMapInt64IntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64IntfV(rv2i(rv).(map[int64]interface{}), false, d) - } -} -func (f fastpathT) DecMapInt64IntfX(vp *map[int64]interface{}, d *Decoder) { - v, changed := f.DecMapInt64IntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64IntfV(v map[int64]interface{}, canChange bool, - d *Decoder) (_ map[int64]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[int64]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk int64 - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64StringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]string) - v, changed := fastpathTV.DecMapInt64StringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64StringV(rv2i(rv).(map[int64]string), false, d) - } -} -func (f fastpathT) DecMapInt64StringX(vp *map[int64]string, d *Decoder) { - v, changed := f.DecMapInt64StringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64StringV(v map[int64]string, canChange bool, - d *Decoder) (_ map[int64]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 24) - v = make(map[int64]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int64 - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64UintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]uint) - v, changed := fastpathTV.DecMapInt64UintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64UintV(rv2i(rv).(map[int64]uint), false, d) - } -} -func (f fastpathT) DecMapInt64UintX(vp *map[int64]uint, d *Decoder) { - v, changed := f.DecMapInt64UintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64UintV(v map[int64]uint, canChange bool, - d *Decoder) (_ map[int64]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int64]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int64 - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64Uint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]uint8) - v, changed := fastpathTV.DecMapInt64Uint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64Uint8V(rv2i(rv).(map[int64]uint8), false, d) - } -} -func (f fastpathT) DecMapInt64Uint8X(vp *map[int64]uint8, d *Decoder) { - v, changed := f.DecMapInt64Uint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64Uint8V(v map[int64]uint8, canChange bool, - d *Decoder) (_ map[int64]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int64]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int64 - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64Uint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]uint16) - v, changed := fastpathTV.DecMapInt64Uint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64Uint16V(rv2i(rv).(map[int64]uint16), false, d) - } -} -func (f fastpathT) DecMapInt64Uint16X(vp *map[int64]uint16, d *Decoder) { - v, changed := f.DecMapInt64Uint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64Uint16V(v map[int64]uint16, canChange bool, - d *Decoder) (_ map[int64]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[int64]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int64 - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64Uint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]uint32) - v, changed := fastpathTV.DecMapInt64Uint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64Uint32V(rv2i(rv).(map[int64]uint32), false, d) - } -} -func (f fastpathT) DecMapInt64Uint32X(vp *map[int64]uint32, d *Decoder) { - v, changed := f.DecMapInt64Uint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64Uint32V(v map[int64]uint32, canChange bool, - d *Decoder) (_ map[int64]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int64]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int64 - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64Uint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]uint64) - v, changed := fastpathTV.DecMapInt64Uint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64Uint64V(rv2i(rv).(map[int64]uint64), false, d) - } -} -func (f fastpathT) DecMapInt64Uint64X(vp *map[int64]uint64, d *Decoder) { - v, changed := f.DecMapInt64Uint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64Uint64V(v map[int64]uint64, canChange bool, - d *Decoder) (_ map[int64]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int64]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int64 - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64UintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]uintptr) - v, changed := fastpathTV.DecMapInt64UintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64UintptrV(rv2i(rv).(map[int64]uintptr), false, d) - } -} -func (f fastpathT) DecMapInt64UintptrX(vp *map[int64]uintptr, d *Decoder) { - v, changed := f.DecMapInt64UintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64UintptrV(v map[int64]uintptr, canChange bool, - d *Decoder) (_ map[int64]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int64]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int64 - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64IntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]int) - v, changed := fastpathTV.DecMapInt64IntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64IntV(rv2i(rv).(map[int64]int), false, d) - } -} -func (f fastpathT) DecMapInt64IntX(vp *map[int64]int, d *Decoder) { - v, changed := f.DecMapInt64IntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64IntV(v map[int64]int, canChange bool, - d *Decoder) (_ map[int64]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int64]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int64 - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64Int8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]int8) - v, changed := fastpathTV.DecMapInt64Int8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64Int8V(rv2i(rv).(map[int64]int8), false, d) - } -} -func (f fastpathT) DecMapInt64Int8X(vp *map[int64]int8, d *Decoder) { - v, changed := f.DecMapInt64Int8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64Int8V(v map[int64]int8, canChange bool, - d *Decoder) (_ map[int64]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int64]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int64 - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64Int16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]int16) - v, changed := fastpathTV.DecMapInt64Int16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64Int16V(rv2i(rv).(map[int64]int16), false, d) - } -} -func (f fastpathT) DecMapInt64Int16X(vp *map[int64]int16, d *Decoder) { - v, changed := f.DecMapInt64Int16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64Int16V(v map[int64]int16, canChange bool, - d *Decoder) (_ map[int64]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 10) - v = make(map[int64]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int64 - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64Int32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]int32) - v, changed := fastpathTV.DecMapInt64Int32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64Int32V(rv2i(rv).(map[int64]int32), false, d) - } -} -func (f fastpathT) DecMapInt64Int32X(vp *map[int64]int32, d *Decoder) { - v, changed := f.DecMapInt64Int32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64Int32V(v map[int64]int32, canChange bool, - d *Decoder) (_ map[int64]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int64]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int64 - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64Int64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]int64) - v, changed := fastpathTV.DecMapInt64Int64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64Int64V(rv2i(rv).(map[int64]int64), false, d) - } -} -func (f fastpathT) DecMapInt64Int64X(vp *map[int64]int64, d *Decoder) { - v, changed := f.DecMapInt64Int64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64Int64V(v map[int64]int64, canChange bool, - d *Decoder) (_ map[int64]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int64]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int64 - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64Float32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]float32) - v, changed := fastpathTV.DecMapInt64Float32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64Float32V(rv2i(rv).(map[int64]float32), false, d) - } -} -func (f fastpathT) DecMapInt64Float32X(vp *map[int64]float32, d *Decoder) { - v, changed := f.DecMapInt64Float32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64Float32V(v map[int64]float32, canChange bool, - d *Decoder) (_ map[int64]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 12) - v = make(map[int64]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int64 - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64Float64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]float64) - v, changed := fastpathTV.DecMapInt64Float64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64Float64V(rv2i(rv).(map[int64]float64), false, d) - } -} -func (f fastpathT) DecMapInt64Float64X(vp *map[int64]float64, d *Decoder) { - v, changed := f.DecMapInt64Float64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64Float64V(v map[int64]float64, canChange bool, - d *Decoder) (_ map[int64]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 16) - v = make(map[int64]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int64 - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapInt64BoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[int64]bool) - v, changed := fastpathTV.DecMapInt64BoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapInt64BoolV(rv2i(rv).(map[int64]bool), false, d) - } -} -func (f fastpathT) DecMapInt64BoolX(vp *map[int64]bool, d *Decoder) { - v, changed := f.DecMapInt64BoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapInt64BoolV(v map[int64]bool, canChange bool, - d *Decoder) (_ map[int64]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[int64]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk int64 - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeInt64() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolIntfR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]interface{}) - v, changed := fastpathTV.DecMapBoolIntfV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolIntfV(rv2i(rv).(map[bool]interface{}), false, d) - } -} -func (f fastpathT) DecMapBoolIntfX(vp *map[bool]interface{}, d *Decoder) { - v, changed := f.DecMapBoolIntfV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolIntfV(v map[bool]interface{}, canChange bool, - d *Decoder) (_ map[bool]interface{}, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[bool]interface{}, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - mapGet := v != nil && !d.h.MapValueReset && !d.h.InterfaceReset - var mk bool - var mv interface{} - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = nil - } - continue - } - if mapGet { - mv = v[mk] - } else { - mv = nil - } - d.decode(&mv) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolStringR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]string) - v, changed := fastpathTV.DecMapBoolStringV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolStringV(rv2i(rv).(map[bool]string), false, d) - } -} -func (f fastpathT) DecMapBoolStringX(vp *map[bool]string, d *Decoder) { - v, changed := f.DecMapBoolStringV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolStringV(v map[bool]string, canChange bool, - d *Decoder) (_ map[bool]string, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 17) - v = make(map[bool]string, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk bool - var mv string - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = "" - } - continue - } - mv = dd.DecodeString() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolUintR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]uint) - v, changed := fastpathTV.DecMapBoolUintV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolUintV(rv2i(rv).(map[bool]uint), false, d) - } -} -func (f fastpathT) DecMapBoolUintX(vp *map[bool]uint, d *Decoder) { - v, changed := f.DecMapBoolUintV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolUintV(v map[bool]uint, canChange bool, - d *Decoder) (_ map[bool]uint, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[bool]uint, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk bool - var mv uint - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolUint8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]uint8) - v, changed := fastpathTV.DecMapBoolUint8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolUint8V(rv2i(rv).(map[bool]uint8), false, d) - } -} -func (f fastpathT) DecMapBoolUint8X(vp *map[bool]uint8, d *Decoder) { - v, changed := f.DecMapBoolUint8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolUint8V(v map[bool]uint8, canChange bool, - d *Decoder) (_ map[bool]uint8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 2) - v = make(map[bool]uint8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk bool - var mv uint8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint8(chkOvf.UintV(dd.DecodeUint64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolUint16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]uint16) - v, changed := fastpathTV.DecMapBoolUint16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolUint16V(rv2i(rv).(map[bool]uint16), false, d) - } -} -func (f fastpathT) DecMapBoolUint16X(vp *map[bool]uint16, d *Decoder) { - v, changed := f.DecMapBoolUint16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolUint16V(v map[bool]uint16, canChange bool, - d *Decoder) (_ map[bool]uint16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[bool]uint16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk bool - var mv uint16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint16(chkOvf.UintV(dd.DecodeUint64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolUint32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]uint32) - v, changed := fastpathTV.DecMapBoolUint32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolUint32V(rv2i(rv).(map[bool]uint32), false, d) - } -} -func (f fastpathT) DecMapBoolUint32X(vp *map[bool]uint32, d *Decoder) { - v, changed := f.DecMapBoolUint32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolUint32V(v map[bool]uint32, canChange bool, - d *Decoder) (_ map[bool]uint32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[bool]uint32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk bool - var mv uint32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uint32(chkOvf.UintV(dd.DecodeUint64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolUint64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]uint64) - v, changed := fastpathTV.DecMapBoolUint64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolUint64V(rv2i(rv).(map[bool]uint64), false, d) - } -} -func (f fastpathT) DecMapBoolUint64X(vp *map[bool]uint64, d *Decoder) { - v, changed := f.DecMapBoolUint64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolUint64V(v map[bool]uint64, canChange bool, - d *Decoder) (_ map[bool]uint64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[bool]uint64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk bool - var mv uint64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeUint64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolUintptrR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]uintptr) - v, changed := fastpathTV.DecMapBoolUintptrV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolUintptrV(rv2i(rv).(map[bool]uintptr), false, d) - } -} -func (f fastpathT) DecMapBoolUintptrX(vp *map[bool]uintptr, d *Decoder) { - v, changed := f.DecMapBoolUintptrV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolUintptrV(v map[bool]uintptr, canChange bool, - d *Decoder) (_ map[bool]uintptr, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[bool]uintptr, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk bool - var mv uintptr - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolIntR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]int) - v, changed := fastpathTV.DecMapBoolIntV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolIntV(rv2i(rv).(map[bool]int), false, d) - } -} -func (f fastpathT) DecMapBoolIntX(vp *map[bool]int, d *Decoder) { - v, changed := f.DecMapBoolIntV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolIntV(v map[bool]int, canChange bool, - d *Decoder) (_ map[bool]int, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[bool]int, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk bool - var mv int - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int(chkOvf.IntV(dd.DecodeInt64(), intBitsize)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolInt8R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]int8) - v, changed := fastpathTV.DecMapBoolInt8V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolInt8V(rv2i(rv).(map[bool]int8), false, d) - } -} -func (f fastpathT) DecMapBoolInt8X(vp *map[bool]int8, d *Decoder) { - v, changed := f.DecMapBoolInt8V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolInt8V(v map[bool]int8, canChange bool, - d *Decoder) (_ map[bool]int8, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 2) - v = make(map[bool]int8, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk bool - var mv int8 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int8(chkOvf.IntV(dd.DecodeInt64(), 8)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolInt16R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]int16) - v, changed := fastpathTV.DecMapBoolInt16V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolInt16V(rv2i(rv).(map[bool]int16), false, d) - } -} -func (f fastpathT) DecMapBoolInt16X(vp *map[bool]int16, d *Decoder) { - v, changed := f.DecMapBoolInt16V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolInt16V(v map[bool]int16, canChange bool, - d *Decoder) (_ map[bool]int16, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 3) - v = make(map[bool]int16, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk bool - var mv int16 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int16(chkOvf.IntV(dd.DecodeInt64(), 16)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolInt32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]int32) - v, changed := fastpathTV.DecMapBoolInt32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolInt32V(rv2i(rv).(map[bool]int32), false, d) - } -} -func (f fastpathT) DecMapBoolInt32X(vp *map[bool]int32, d *Decoder) { - v, changed := f.DecMapBoolInt32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolInt32V(v map[bool]int32, canChange bool, - d *Decoder) (_ map[bool]int32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[bool]int32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk bool - var mv int32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = int32(chkOvf.IntV(dd.DecodeInt64(), 32)) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolInt64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]int64) - v, changed := fastpathTV.DecMapBoolInt64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolInt64V(rv2i(rv).(map[bool]int64), false, d) - } -} -func (f fastpathT) DecMapBoolInt64X(vp *map[bool]int64, d *Decoder) { - v, changed := f.DecMapBoolInt64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolInt64V(v map[bool]int64, canChange bool, - d *Decoder) (_ map[bool]int64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[bool]int64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk bool - var mv int64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeInt64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolFloat32R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]float32) - v, changed := fastpathTV.DecMapBoolFloat32V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolFloat32V(rv2i(rv).(map[bool]float32), false, d) - } -} -func (f fastpathT) DecMapBoolFloat32X(vp *map[bool]float32, d *Decoder) { - v, changed := f.DecMapBoolFloat32V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolFloat32V(v map[bool]float32, canChange bool, - d *Decoder) (_ map[bool]float32, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 5) - v = make(map[bool]float32, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk bool - var mv float32 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = float32(chkOvf.Float32V(dd.DecodeFloat64())) - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolFloat64R(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]float64) - v, changed := fastpathTV.DecMapBoolFloat64V(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolFloat64V(rv2i(rv).(map[bool]float64), false, d) - } -} -func (f fastpathT) DecMapBoolFloat64X(vp *map[bool]float64, d *Decoder) { - v, changed := f.DecMapBoolFloat64V(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolFloat64V(v map[bool]float64, canChange bool, - d *Decoder) (_ map[bool]float64, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 9) - v = make(map[bool]float64, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk bool - var mv float64 - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = 0 - } - continue - } - mv = dd.DecodeFloat64() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} - -func (d *Decoder) fastpathDecMapBoolBoolR(f *codecFnInfo, rv reflect.Value) { - if rv.Kind() == reflect.Ptr { - vp := rv2i(rv).(*map[bool]bool) - v, changed := fastpathTV.DecMapBoolBoolV(*vp, true, d) - if changed { - *vp = v - } - } else { - fastpathTV.DecMapBoolBoolV(rv2i(rv).(map[bool]bool), false, d) - } -} -func (f fastpathT) DecMapBoolBoolX(vp *map[bool]bool, d *Decoder) { - v, changed := f.DecMapBoolBoolV(*vp, true, d) - if changed { - *vp = v - } -} -func (_ fastpathT) DecMapBoolBoolV(v map[bool]bool, canChange bool, - d *Decoder) (_ map[bool]bool, changed bool) { - dd, esep := d.d, d.hh.hasElemSeparators() - containerLen := dd.ReadMapStart() - if canChange && v == nil { - xlen := decInferLen(containerLen, d.h.MaxInitLen, 2) - v = make(map[bool]bool, xlen) - changed = true - } - if containerLen == 0 { - dd.ReadMapEnd() - return v, changed - } - var mk bool - var mv bool - hasLen := containerLen > 0 - for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ { - if esep { - dd.ReadMapElemKey() - } - mk = dd.DecodeBool() - if esep { - dd.ReadMapElemValue() - } - if dd.TryDecodeAsNil() { - if v == nil { - } else if d.h.DeleteOnNilMapValue { - delete(v, mk) - } else { - v[mk] = false - } - continue - } - mv = dd.DecodeBool() - if v != nil { - v[mk] = mv - } - } - dd.ReadMapEnd() - return v, changed -} diff --git a/vendor/github.com/ugorji/go/codec/fast-path.not.go b/vendor/github.com/ugorji/go/codec/fast-path.not.go deleted file mode 100644 index f11b4674f..000000000 --- a/vendor/github.com/ugorji/go/codec/fast-path.not.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build notfastpath - -package codec - -import "reflect" - -const fastpathEnabled = false - -// The generated fast-path code is very large, and adds a few seconds to the build time. -// This causes test execution, execution of small tools which use codec, etc -// to take a long time. -// -// To mitigate, we now support the notfastpath tag. -// This tag disables fastpath during build, allowing for faster build, test execution, -// short-program runs, etc. - -func fastpathDecodeTypeSwitch(iv interface{}, d *Decoder) bool { return false } -func fastpathEncodeTypeSwitch(iv interface{}, e *Encoder) bool { return false } -func fastpathEncodeTypeSwitchSlice(iv interface{}, e *Encoder) bool { return false } -func fastpathEncodeTypeSwitchMap(iv interface{}, e *Encoder) bool { return false } -func fastpathDecodeSetZeroTypeSwitch(iv interface{}) bool { return false } - -type fastpathT struct{} -type fastpathE struct { - rtid uintptr - rt reflect.Type - encfn func(*Encoder, *codecFnInfo, reflect.Value) - decfn func(*Decoder, *codecFnInfo, reflect.Value) -} -type fastpathA [0]fastpathE - -func (x fastpathA) index(rtid uintptr) int { return -1 } - -func (_ fastpathT) DecSliceUint8V(v []uint8, canChange bool, d *Decoder) (_ []uint8, changed bool) { - fn := d.cfer().get(uint8SliceTyp, true, true) - d.kSlice(&fn.i, reflect.ValueOf(&v).Elem()) - return v, true -} - -var fastpathAV fastpathA -var fastpathTV fastpathT - -// ---- -type TestMammoth2Wrapper struct{} // to allow testMammoth work in notfastpath mode diff --git a/vendor/github.com/ugorji/go/codec/gen-helper.generated.go b/vendor/github.com/ugorji/go/codec/gen-helper.generated.go deleted file mode 100644 index 917d28283..000000000 --- a/vendor/github.com/ugorji/go/codec/gen-helper.generated.go +++ /dev/null @@ -1,335 +0,0 @@ -/* // +build ignore */ - -// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// Code generated from gen-helper.go.tmpl - DO NOT EDIT. - -package codec - -import ( - "encoding" - "reflect" -) - -// GenVersion is the current version of codecgen. -const GenVersion = 8 - -// This file is used to generate helper code for codecgen. -// The values here i.e. genHelper(En|De)coder are not to be used directly by -// library users. They WILL change continuously and without notice. -// -// To help enforce this, we create an unexported type with exported members. -// The only way to get the type is via the one exported type that we control (somewhat). -// -// When static codecs are created for types, they will use this value -// to perform encoding or decoding of primitives or known slice or map types. - -// GenHelperEncoder is exported so that it can be used externally by codecgen. -// -// Library users: DO NOT USE IT DIRECTLY. IT WILL CHANGE CONTINOUSLY WITHOUT NOTICE. -func GenHelperEncoder(e *Encoder) (ge genHelperEncoder, ee genHelperEncDriver) { - ge = genHelperEncoder{e: e} - ee = genHelperEncDriver{encDriver: e.e} - return -} - -// GenHelperDecoder is exported so that it can be used externally by codecgen. -// -// Library users: DO NOT USE IT DIRECTLY. IT WILL CHANGE CONTINOUSLY WITHOUT NOTICE. -func GenHelperDecoder(d *Decoder) (gd genHelperDecoder, dd genHelperDecDriver) { - gd = genHelperDecoder{d: d} - dd = genHelperDecDriver{decDriver: d.d} - return -} - -type genHelperEncDriver struct { - encDriver -} - -func (x genHelperEncDriver) EncodeBuiltin(rt uintptr, v interface{}) {} -func (x genHelperEncDriver) EncStructFieldKey(keyType valueType, s string) { - encStructFieldKey(x.encDriver, keyType, s) -} -func (x genHelperEncDriver) EncodeSymbol(s string) { - x.encDriver.EncodeString(cUTF8, s) -} - -type genHelperDecDriver struct { - decDriver - C checkOverflow -} - -func (x genHelperDecDriver) DecodeBuiltin(rt uintptr, v interface{}) {} -func (x genHelperDecDriver) DecStructFieldKey(keyType valueType, buf *[decScratchByteArrayLen]byte) []byte { - return decStructFieldKey(x.decDriver, keyType, buf) -} -func (x genHelperDecDriver) DecodeInt(bitsize uint8) (i int64) { - return x.C.IntV(x.decDriver.DecodeInt64(), bitsize) -} -func (x genHelperDecDriver) DecodeUint(bitsize uint8) (ui uint64) { - return x.C.UintV(x.decDriver.DecodeUint64(), bitsize) -} -func (x genHelperDecDriver) DecodeFloat(chkOverflow32 bool) (f float64) { - f = x.DecodeFloat64() - if chkOverflow32 && chkOvf.Float32(f) { - panicv.errorf("float32 overflow: %v", f) - } - return -} -func (x genHelperDecDriver) DecodeFloat32As64() (f float64) { - f = x.DecodeFloat64() - if chkOvf.Float32(f) { - panicv.errorf("float32 overflow: %v", f) - } - return -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -type genHelperEncoder struct { - M must - e *Encoder - F fastpathT -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -type genHelperDecoder struct { - C checkOverflow - d *Decoder - F fastpathT -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncBasicHandle() *BasicHandle { - return f.e.h -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncBinary() bool { - return f.e.be // f.e.hh.isBinaryEncoding() -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) IsJSONHandle() bool { - return f.e.js -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncFallback(iv interface{}) { - // println(">>>>>>>>> EncFallback") - // f.e.encodeI(iv, false, false) - f.e.encodeValue(reflect.ValueOf(iv), nil, false) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncTextMarshal(iv encoding.TextMarshaler) { - bs, fnerr := iv.MarshalText() - f.e.marshal(bs, fnerr, false, cUTF8) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncJSONMarshal(iv jsonMarshaler) { - bs, fnerr := iv.MarshalJSON() - f.e.marshal(bs, fnerr, true, cUTF8) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncBinaryMarshal(iv encoding.BinaryMarshaler) { - bs, fnerr := iv.MarshalBinary() - f.e.marshal(bs, fnerr, false, cRAW) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncRaw(iv Raw) { f.e.rawBytes(iv) } - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -// -// Deprecated: builtin no longer supported - so we make this method a no-op, -// but leave in-place so that old generated files continue to work without regeneration. -func (f genHelperEncoder) TimeRtidIfBinc() (v uintptr) { return } - -// func (f genHelperEncoder) TimeRtidIfBinc() uintptr { -// if _, ok := f.e.hh.(*BincHandle); ok { -// return timeTypId -// } -// } - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) I2Rtid(v interface{}) uintptr { - return i2rtid(v) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) Extension(rtid uintptr) (xfn *extTypeTagFn) { - return f.e.h.getExt(rtid) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperEncoder) EncExtension(v interface{}, xfFn *extTypeTagFn) { - f.e.e.EncodeExt(v, xfFn.tag, xfFn.ext, f.e) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -// -// Deprecated: No longer used, -// but leave in-place so that old generated files continue to work without regeneration. -func (f genHelperEncoder) HasExtensions() bool { - return len(f.e.h.extHandle) != 0 -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -// -// Deprecated: No longer used, -// but leave in-place so that old generated files continue to work without regeneration. -func (f genHelperEncoder) EncExt(v interface{}) (r bool) { - if xfFn := f.e.h.getExt(i2rtid(v)); xfFn != nil { - f.e.e.EncodeExt(v, xfFn.tag, xfFn.ext, f.e) - return true - } - return false -} - -// ---------------- DECODER FOLLOWS ----------------- - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecBasicHandle() *BasicHandle { - return f.d.h -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecBinary() bool { - return f.d.be // f.d.hh.isBinaryEncoding() -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecSwallow() { f.d.swallow() } - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecScratchBuffer() []byte { - return f.d.b[:] -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecScratchArrayBuffer() *[decScratchByteArrayLen]byte { - return &f.d.b -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecFallback(iv interface{}, chkPtr bool) { - // println(">>>>>>>>> DecFallback") - rv := reflect.ValueOf(iv) - if chkPtr { - rv = f.d.ensureDecodeable(rv) - } - f.d.decodeValue(rv, nil, false) - // f.d.decodeValueFallback(rv) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecSliceHelperStart() (decSliceHelper, int) { - return f.d.decSliceHelperStart() -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecStructFieldNotFound(index int, name string) { - f.d.structFieldNotFound(index, name) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecArrayCannotExpand(sliceLen, streamLen int) { - f.d.arrayCannotExpand(sliceLen, streamLen) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecTextUnmarshal(tm encoding.TextUnmarshaler) { - fnerr := tm.UnmarshalText(f.d.d.DecodeStringAsBytes()) - if fnerr != nil { - panic(fnerr) - } -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecJSONUnmarshal(tm jsonUnmarshaler) { - // bs := f.dd.DecodeStringAsBytes() - // grab the bytes to be read, as UnmarshalJSON needs the full JSON so as to unmarshal it itself. - fnerr := tm.UnmarshalJSON(f.d.nextValueBytes()) - if fnerr != nil { - panic(fnerr) - } -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecBinaryUnmarshal(bm encoding.BinaryUnmarshaler) { - fnerr := bm.UnmarshalBinary(f.d.d.DecodeBytes(nil, true)) - if fnerr != nil { - panic(fnerr) - } -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecRaw() []byte { return f.d.rawBytes() } - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -// -// Deprecated: builtin no longer supported - so we make this method a no-op, -// but leave in-place so that old generated files continue to work without regeneration. -func (f genHelperDecoder) TimeRtidIfBinc() (v uintptr) { return } - -// func (f genHelperDecoder) TimeRtidIfBinc() uintptr { -// // Note: builtin is no longer supported - so make this a no-op -// if _, ok := f.d.hh.(*BincHandle); ok { -// return timeTypId -// } -// return 0 -// } - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) IsJSONHandle() bool { - return f.d.js -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) I2Rtid(v interface{}) uintptr { - return i2rtid(v) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) Extension(rtid uintptr) (xfn *extTypeTagFn) { - return f.d.h.getExt(rtid) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecExtension(v interface{}, xfFn *extTypeTagFn) { - f.d.d.DecodeExt(v, xfFn.tag, xfFn.ext) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -// -// Deprecated: No longer used, -// but leave in-place so that old generated files continue to work without regeneration. -func (f genHelperDecoder) HasExtensions() bool { - return len(f.d.h.extHandle) != 0 -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -// -// Deprecated: No longer used, -// but leave in-place so that old generated files continue to work without regeneration. -func (f genHelperDecoder) DecExt(v interface{}) (r bool) { - if xfFn := f.d.h.getExt(i2rtid(v)); xfFn != nil { - f.d.d.DecodeExt(v, xfFn.tag, xfFn.ext) - return true - } - return false -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -func (f genHelperDecoder) DecInferLen(clen, maxlen, unit int) (rvlen int) { - return decInferLen(clen, maxlen, unit) -} - -// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* -// -// Deprecated: no longer used, -// but leave in-place so that old generated files continue to work without regeneration. -func (f genHelperDecoder) StringView(v []byte) string { return stringView(v) } diff --git a/vendor/github.com/ugorji/go/codec/gen.generated.go b/vendor/github.com/ugorji/go/codec/gen.generated.go deleted file mode 100644 index 240ba9f8c..000000000 --- a/vendor/github.com/ugorji/go/codec/gen.generated.go +++ /dev/null @@ -1,164 +0,0 @@ -// +build codecgen.exec - -// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -// DO NOT EDIT. THIS FILE IS AUTO-GENERATED FROM gen-dec-(map|array).go.tmpl - -const genDecMapTmpl = ` -{{var "v"}} := *{{ .Varname }} -{{var "l"}} := r.ReadMapStart() -{{var "bh"}} := z.DecBasicHandle() -if {{var "v"}} == nil { - {{var "rl"}} := z.DecInferLen({{var "l"}}, {{var "bh"}}.MaxInitLen, {{ .Size }}) - {{var "v"}} = make(map[{{ .KTyp }}]{{ .Typ }}, {{var "rl"}}) - *{{ .Varname }} = {{var "v"}} -} -var {{var "mk"}} {{ .KTyp }} -var {{var "mv"}} {{ .Typ }} -var {{var "mg"}}, {{var "mdn"}} {{if decElemKindPtr}}, {{var "ms"}}, {{var "mok"}}{{end}} bool -if {{var "bh"}}.MapValueReset { - {{if decElemKindPtr}}{{var "mg"}} = true - {{else if decElemKindIntf}}if !{{var "bh"}}.InterfaceReset { {{var "mg"}} = true } - {{else if not decElemKindImmutable}}{{var "mg"}} = true - {{end}} } -if {{var "l"}} != 0 { -{{var "hl"}} := {{var "l"}} > 0 - for {{var "j"}} := 0; ({{var "hl"}} && {{var "j"}} < {{var "l"}}) || !({{var "hl"}} || r.CheckBreak()); {{var "j"}}++ { - r.ReadMapElemKey() {{/* z.DecSendContainerState(codecSelfer_containerMapKey{{ .Sfx }}) */}} - {{ $x := printf "%vmk%v" .TempVar .Rand }}{{ decLineVarK $x }} -{{ if eq .KTyp "interface{}" }}{{/* // special case if a byte array. */}}if {{var "bv"}}, {{var "bok"}} := {{var "mk"}}.([]byte); {{var "bok"}} { - {{var "mk"}} = string({{var "bv"}}) - }{{ end }}{{if decElemKindPtr}} - {{var "ms"}} = true{{end}} - if {{var "mg"}} { - {{if decElemKindPtr}}{{var "mv"}}, {{var "mok"}} = {{var "v"}}[{{var "mk"}}] - if {{var "mok"}} { - {{var "ms"}} = false - } {{else}}{{var "mv"}} = {{var "v"}}[{{var "mk"}}] {{end}} - } {{if not decElemKindImmutable}}else { {{var "mv"}} = {{decElemZero}} }{{end}} - r.ReadMapElemValue() {{/* z.DecSendContainerState(codecSelfer_containerMapValue{{ .Sfx }}) */}} - {{var "mdn"}} = false - {{ $x := printf "%vmv%v" .TempVar .Rand }}{{ $y := printf "%vmdn%v" .TempVar .Rand }}{{ decLineVar $x $y }} - if {{var "mdn"}} { - if {{ var "bh" }}.DeleteOnNilMapValue { delete({{var "v"}}, {{var "mk"}}) } else { {{var "v"}}[{{var "mk"}}] = {{decElemZero}} } - } else if {{if decElemKindPtr}} {{var "ms"}} && {{end}} {{var "v"}} != nil { - {{var "v"}}[{{var "mk"}}] = {{var "mv"}} - } -} -} // else len==0: TODO: Should we clear map entries? -r.ReadMapEnd() {{/* z.DecSendContainerState(codecSelfer_containerMapEnd{{ .Sfx }}) */}} -` - -const genDecListTmpl = ` -{{var "v"}} := {{if not isArray}}*{{end}}{{ .Varname }} -{{var "h"}}, {{var "l"}} := z.DecSliceHelperStart() {{/* // helper, containerLenS */}}{{if not isArray}} -var {{var "c"}} bool {{/* // changed */}} -_ = {{var "c"}}{{end}} -if {{var "l"}} == 0 { - {{if isSlice }}if {{var "v"}} == nil { - {{var "v"}} = []{{ .Typ }}{} - {{var "c"}} = true - } else if len({{var "v"}}) != 0 { - {{var "v"}} = {{var "v"}}[:0] - {{var "c"}} = true - } {{else if isChan }}if {{var "v"}} == nil { - {{var "v"}} = make({{ .CTyp }}, 0) - {{var "c"}} = true - } {{end}} -} else { - {{var "hl"}} := {{var "l"}} > 0 - var {{var "rl"}} int - _ = {{var "rl"}} - {{if isSlice }} if {{var "hl"}} { - if {{var "l"}} > cap({{var "v"}}) { - {{var "rl"}} = z.DecInferLen({{var "l"}}, z.DecBasicHandle().MaxInitLen, {{ .Size }}) - if {{var "rl"}} <= cap({{var "v"}}) { - {{var "v"}} = {{var "v"}}[:{{var "rl"}}] - } else { - {{var "v"}} = make([]{{ .Typ }}, {{var "rl"}}) - } - {{var "c"}} = true - } else if {{var "l"}} != len({{var "v"}}) { - {{var "v"}} = {{var "v"}}[:{{var "l"}}] - {{var "c"}} = true - } - } {{end}} - var {{var "j"}} int - // var {{var "dn"}} bool - for ; ({{var "hl"}} && {{var "j"}} < {{var "l"}}) || !({{var "hl"}} || r.CheckBreak()); {{var "j"}}++ { - {{if not isArray}} if {{var "j"}} == 0 && {{var "v"}} == nil { - if {{var "hl"}} { - {{var "rl"}} = z.DecInferLen({{var "l"}}, z.DecBasicHandle().MaxInitLen, {{ .Size }}) - } else { - {{var "rl"}} = {{if isSlice}}8{{else if isChan}}64{{end}} - } - {{var "v"}} = make({{if isSlice}}[]{{ .Typ }}{{else if isChan}}{{.CTyp}}{{end}}, {{var "rl"}}) - {{var "c"}} = true - }{{end}} - {{var "h"}}.ElemContainerState({{var "j"}}) - {{/* {{var "dn"}} = r.TryDecodeAsNil() */}}{{/* commented out, as decLineVar handles this already each time */}} - {{if isChan}}{{ $x := printf "%[1]vvcx%[2]v" .TempVar .Rand }}var {{$x}} {{ .Typ }} - {{ decLineVar $x }} - {{var "v"}} <- {{ $x }} - // println(">>>> sending ", {{ $x }}, " into ", {{var "v"}}) // TODO: remove this - {{else}}{{/* // if indefinite, etc, then expand the slice if necessary */}} - var {{var "db"}} bool - if {{var "j"}} >= len({{var "v"}}) { - {{if isSlice }} {{var "v"}} = append({{var "v"}}, {{ zero }}) - {{var "c"}} = true - {{else}} z.DecArrayCannotExpand(len(v), {{var "j"}}+1); {{var "db"}} = true - {{end}} - } - if {{var "db"}} { - z.DecSwallow() - } else { - {{ $x := printf "%[1]vv%[2]v[%[1]vj%[2]v]" .TempVar .Rand }}{{ decLineVar $x }} - } - {{end}} - } - {{if isSlice}} if {{var "j"}} < len({{var "v"}}) { - {{var "v"}} = {{var "v"}}[:{{var "j"}}] - {{var "c"}} = true - } else if {{var "j"}} == 0 && {{var "v"}} == nil { - {{var "v"}} = make([]{{ .Typ }}, 0) - {{var "c"}} = true - } {{end}} -} -{{var "h"}}.End() -{{if not isArray }}if {{var "c"}} { - *{{ .Varname }} = {{var "v"}} -}{{end}} -` - -const genEncChanTmpl = ` -{{.Label}}: -switch timeout{{.Sfx}} := z.EncBasicHandle().ChanRecvTimeout; { -case timeout{{.Sfx}} == 0: // only consume available - for { - select { - case b{{.Sfx}} := <-{{.Chan}}: - {{ .Slice }} = append({{.Slice}}, b{{.Sfx}}) - default: - break {{.Label}} - } - } -case timeout{{.Sfx}} > 0: // consume until timeout - tt{{.Sfx}} := time.NewTimer(timeout{{.Sfx}}) - for { - select { - case b{{.Sfx}} := <-{{.Chan}}: - {{.Slice}} = append({{.Slice}}, b{{.Sfx}}) - case <-tt{{.Sfx}}.C: - // close(tt.C) - break {{.Label}} - } - } -default: // consume until close - for b{{.Sfx}} := range {{.Chan}} { - {{.Slice}} = append({{.Slice}}, b{{.Sfx}}) - } -} -` diff --git a/vendor/github.com/ugorji/go/codec/gen.go b/vendor/github.com/ugorji/go/codec/gen.go deleted file mode 100644 index b4c4031ff..000000000 --- a/vendor/github.com/ugorji/go/codec/gen.go +++ /dev/null @@ -1,2139 +0,0 @@ -// +build codecgen.exec - -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -import ( - "bytes" - "encoding/base64" - "errors" - "fmt" - "go/format" - "io" - "io/ioutil" - "math/rand" - "reflect" - "regexp" - "sort" - "strconv" - "strings" - "sync" - "text/template" - "time" - "unicode" - "unicode/utf8" -) - -// --------------------------------------------------- -// codecgen supports the full cycle of reflection-based codec: -// - RawExt -// - Raw -// - Extensions -// - (Binary|Text|JSON)(Unm|M)arshal -// - generic by-kind -// -// This means that, for dynamic things, we MUST use reflection to at least get the reflect.Type. -// In those areas, we try to only do reflection or interface-conversion when NECESSARY: -// - Extensions, only if Extensions are configured. -// -// However, codecgen doesn't support the following: -// - Canonical option. (codecgen IGNORES it currently) -// This is just because it has not been implemented. -// -// During encode/decode, Selfer takes precedence. -// A type implementing Selfer will know how to encode/decode itself statically. -// -// The following field types are supported: -// array: [n]T -// slice: []T -// map: map[K]V -// primitive: [u]int[n], float(32|64), bool, string -// struct -// -// --------------------------------------------------- -// Note that a Selfer cannot call (e|d).(En|De)code on itself, -// as this will cause a circular reference, as (En|De)code will call Selfer methods. -// Any type that implements Selfer must implement completely and not fallback to (En|De)code. -// -// In addition, code in this file manages the generation of fast-path implementations of -// encode/decode of slices/maps of primitive keys/values. -// -// Users MUST re-generate their implementations whenever the code shape changes. -// The generated code will panic if it was generated with a version older than the supporting library. -// --------------------------------------------------- -// -// codec framework is very feature rich. -// When encoding or decoding into an interface, it depends on the runtime type of the interface. -// The type of the interface may be a named type, an extension, etc. -// Consequently, we fallback to runtime codec for encoding/decoding interfaces. -// In addition, we fallback for any value which cannot be guaranteed at runtime. -// This allows us support ANY value, including any named types, specifically those which -// do not implement our interfaces (e.g. Selfer). -// -// This explains some slowness compared to other code generation codecs (e.g. msgp). -// This reduction in speed is only seen when your refers to interfaces, -// e.g. type T struct { A interface{}; B []interface{}; C map[string]interface{} } -// -// codecgen will panic if the file was generated with an old version of the library in use. -// -// Note: -// It was a conscious decision to have gen.go always explicitly call EncodeNil or TryDecodeAsNil. -// This way, there isn't a function call overhead just to see that we should not enter a block of code. -// -// Note: -// codecgen-generated code depends on the variables defined by fast-path.generated.go. -// consequently, you cannot run with tags "codecgen notfastpath". - -// GenVersion is the current version of codecgen. -// -// NOTE: Increment this value each time codecgen changes fundamentally. -// Fundamental changes are: -// - helper methods change (signature change, new ones added, some removed, etc) -// - codecgen command line changes -// -// v1: Initial Version -// v2: -// v3: Changes for Kubernetes: -// changes in signature of some unpublished helper methods and codecgen cmdline arguments. -// v4: Removed separator support from (en|de)cDriver, and refactored codec(gen) -// v5: changes to support faster json decoding. Let encoder/decoder maintain state of collections. -// v6: removed unsafe from gen, and now uses codecgen.exec tag -// v7: -// v8: current - we now maintain compatibility with old generated code. -const genVersion = 8 - -const ( - genCodecPkg = "codec1978" - genTempVarPfx = "yy" - genTopLevelVarName = "x" - - // ignore canBeNil parameter, and always set to true. - // This is because nil can appear anywhere, so we should always check. - genAnythingCanBeNil = true - - // if genUseOneFunctionForDecStructMap, make a single codecDecodeSelferFromMap function; - // else make codecDecodeSelferFromMap{LenPrefix,CheckBreak} so that conditionals - // are not executed a lot. - // - // From testing, it didn't make much difference in runtime, so keep as true (one function only) - genUseOneFunctionForDecStructMap = true -) - -type genStructMapStyle uint8 - -const ( - genStructMapStyleConsolidated genStructMapStyle = iota - genStructMapStyleLenPrefix - genStructMapStyleCheckBreak -) - -var ( - errGenAllTypesSamePkg = errors.New("All types must be in the same package") - errGenExpectArrayOrMap = errors.New("unexpected type. Expecting array/map/slice") - - genBase64enc = base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789__") - genQNameRegex = regexp.MustCompile(`[A-Za-z_.]+`) -) - -type genBuf struct { - buf []byte -} - -func (x *genBuf) s(s string) *genBuf { x.buf = append(x.buf, s...); return x } -func (x *genBuf) b(s []byte) *genBuf { x.buf = append(x.buf, s...); return x } -func (x *genBuf) v() string { return string(x.buf) } -func (x *genBuf) f(s string, args ...interface{}) { x.s(fmt.Sprintf(s, args...)) } -func (x *genBuf) reset() { - if x.buf != nil { - x.buf = x.buf[:0] - } -} - -// genRunner holds some state used during a Gen run. -type genRunner struct { - w io.Writer // output - c uint64 // counter used for generating varsfx - t []reflect.Type // list of types to run selfer on - - tc reflect.Type // currently running selfer on this type - te map[uintptr]bool // types for which the encoder has been created - td map[uintptr]bool // types for which the decoder has been created - cp string // codec import path - - im map[string]reflect.Type // imports to add - imn map[string]string // package names of imports to add - imc uint64 // counter for import numbers - - is map[reflect.Type]struct{} // types seen during import search - bp string // base PkgPath, for which we are generating for - - cpfx string // codec package prefix - - tm map[reflect.Type]struct{} // types for which enc/dec must be generated - ts []reflect.Type // types for which enc/dec must be generated - - xs string // top level variable/constant suffix - hn string // fn helper type name - - ti *TypeInfos - // rr *rand.Rand // random generator for file-specific types - - nx bool // no extensions -} - -// Gen will write a complete go file containing Selfer implementations for each -// type passed. All the types must be in the same package. -// -// Library users: DO NOT USE IT DIRECTLY. IT WILL CHANGE CONTINUOUSLY WITHOUT NOTICE. -func Gen(w io.Writer, buildTags, pkgName, uid string, noExtensions bool, - ti *TypeInfos, typ ...reflect.Type) { - // All types passed to this method do not have a codec.Selfer method implemented directly. - // codecgen already checks the AST and skips any types that define the codec.Selfer methods. - // Consequently, there's no need to check and trim them if they implement codec.Selfer - - if len(typ) == 0 { - return - } - x := genRunner{ - w: w, - t: typ, - te: make(map[uintptr]bool), - td: make(map[uintptr]bool), - im: make(map[string]reflect.Type), - imn: make(map[string]string), - is: make(map[reflect.Type]struct{}), - tm: make(map[reflect.Type]struct{}), - ts: []reflect.Type{}, - bp: genImportPath(typ[0]), - xs: uid, - ti: ti, - nx: noExtensions, - } - if x.ti == nil { - x.ti = defTypeInfos - } - if x.xs == "" { - rr := rand.New(rand.NewSource(time.Now().UnixNano())) - x.xs = strconv.FormatInt(rr.Int63n(9999), 10) - } - - // gather imports first: - x.cp = genImportPath(reflect.TypeOf(x)) - x.imn[x.cp] = genCodecPkg - for _, t := range typ { - // fmt.Printf("###########: PkgPath: '%v', Name: '%s'\n", genImportPath(t), t.Name()) - if genImportPath(t) != x.bp { - panic(errGenAllTypesSamePkg) - } - x.genRefPkgs(t) - } - if buildTags != "" { - x.line("// +build " + buildTags) - x.line("") - } - x.line(` - -// Code generated by codecgen - DO NOT EDIT. - -`) - x.line("package " + pkgName) - x.line("") - x.line("import (") - if x.cp != x.bp { - x.cpfx = genCodecPkg + "." - x.linef("%s \"%s\"", genCodecPkg, x.cp) - } - // use a sorted set of im keys, so that we can get consistent output - imKeys := make([]string, 0, len(x.im)) - for k := range x.im { - imKeys = append(imKeys, k) - } - sort.Strings(imKeys) - for _, k := range imKeys { // for k, _ := range x.im { - if k == x.imn[k] { - x.linef("\"%s\"", k) - } else { - x.linef("%s \"%s\"", x.imn[k], k) - } - } - // add required packages - for _, k := range [...]string{"runtime", "errors", "strconv"} { // "reflect", "fmt" - if _, ok := x.im[k]; !ok { - x.line("\"" + k + "\"") - } - } - x.line(")") - x.line("") - - x.line("const (") - x.linef("// ----- content types ----") - x.linef("codecSelferCcUTF8%s = %v", x.xs, int64(cUTF8)) - x.linef("codecSelferCcRAW%s = %v", x.xs, int64(cRAW)) - x.linef("// ----- value types used ----") - for _, vt := range [...]valueType{ - valueTypeArray, valueTypeMap, valueTypeString, - valueTypeInt, valueTypeUint, valueTypeFloat} { - x.linef("codecSelferValueType%s%s = %v", vt.String(), x.xs, int64(vt)) - } - - x.linef("codecSelferBitsize%s = uint8(32 << (^uint(0) >> 63))", x.xs) - x.line(")") - x.line("var (") - x.line("errCodecSelferOnlyMapOrArrayEncodeToStruct" + x.xs + " = errors.New(`only encoded map or array can be decoded into a struct`)") - x.line(")") - x.line("") - - x.hn = "codecSelfer" + x.xs - x.line("type " + x.hn + " struct{}") - x.line("") - - x.varsfxreset() - x.line("func init() {") - x.linef("if %sGenVersion != %v {", x.cpfx, genVersion) - x.line("_, file, _, _ := runtime.Caller(0)") - x.outf(`panic("codecgen version mismatch: current: %v, need " + strconv.FormatInt(int64(%sGenVersion), 10) + ". Re-generate file: " + file)`, genVersion, x.cpfx) - // x.out(`panic(fmt.Errorf("codecgen version mismatch: current: %v, need %v. Re-generate file: %v", `) - // x.linef(`%v, %sGenVersion, file))`, genVersion, x.cpfx) - x.linef("}") - x.line("if false { // reference the types, but skip this branch at build/run time") - // x.line("_ = strconv.ParseInt") - var n int - // for k, t := range x.im { - for _, k := range imKeys { - t := x.im[k] - x.linef("var v%v %s.%s", n, x.imn[k], t.Name()) - n++ - } - if n > 0 { - x.out("_") - for i := 1; i < n; i++ { - x.out(", _") - } - x.out(" = v0") - for i := 1; i < n; i++ { - x.outf(", v%v", i) - } - } - x.line("} ") // close if false - x.line("}") // close init - x.line("") - - // generate rest of type info - for _, t := range typ { - x.tc = t - x.selfer(true) - x.selfer(false) - } - - for _, t := range x.ts { - rtid := rt2id(t) - // generate enc functions for all these slice/map types. - x.varsfxreset() - x.linef("func (x %s) enc%s(v %s%s, e *%sEncoder) {", x.hn, x.genMethodNameT(t), x.arr2str(t, "*"), x.genTypeName(t), x.cpfx) - x.genRequiredMethodVars(true) - switch t.Kind() { - case reflect.Array, reflect.Slice, reflect.Chan: - x.encListFallback("v", t) - case reflect.Map: - x.encMapFallback("v", t) - default: - panic(errGenExpectArrayOrMap) - } - x.line("}") - x.line("") - - // generate dec functions for all these slice/map types. - x.varsfxreset() - x.linef("func (x %s) dec%s(v *%s, d *%sDecoder) {", x.hn, x.genMethodNameT(t), x.genTypeName(t), x.cpfx) - x.genRequiredMethodVars(false) - switch t.Kind() { - case reflect.Array, reflect.Slice, reflect.Chan: - x.decListFallback("v", rtid, t) - case reflect.Map: - x.decMapFallback("v", rtid, t) - default: - panic(errGenExpectArrayOrMap) - } - x.line("}") - x.line("") - } - - x.line("") -} - -func (x *genRunner) checkForSelfer(t reflect.Type, varname string) bool { - // return varname != genTopLevelVarName && t != x.tc - // the only time we checkForSelfer is if we are not at the TOP of the generated code. - return varname != genTopLevelVarName -} - -func (x *genRunner) arr2str(t reflect.Type, s string) string { - if t.Kind() == reflect.Array { - return s - } - return "" -} - -func (x *genRunner) genRequiredMethodVars(encode bool) { - x.line("var h " + x.hn) - if encode { - x.line("z, r := " + x.cpfx + "GenHelperEncoder(e)") - } else { - x.line("z, r := " + x.cpfx + "GenHelperDecoder(d)") - } - x.line("_, _, _ = h, z, r") -} - -func (x *genRunner) genRefPkgs(t reflect.Type) { - if _, ok := x.is[t]; ok { - return - } - x.is[t] = struct{}{} - tpkg, tname := genImportPath(t), t.Name() - if tpkg != "" && tpkg != x.bp && tpkg != x.cp && tname != "" && tname[0] >= 'A' && tname[0] <= 'Z' { - if _, ok := x.im[tpkg]; !ok { - x.im[tpkg] = t - if idx := strings.LastIndex(tpkg, "/"); idx < 0 { - x.imn[tpkg] = tpkg - } else { - x.imc++ - x.imn[tpkg] = "pkg" + strconv.FormatUint(x.imc, 10) + "_" + genGoIdentifier(tpkg[idx+1:], false) - } - } - } - switch t.Kind() { - case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Chan: - x.genRefPkgs(t.Elem()) - case reflect.Map: - x.genRefPkgs(t.Elem()) - x.genRefPkgs(t.Key()) - case reflect.Struct: - for i := 0; i < t.NumField(); i++ { - if fname := t.Field(i).Name; fname != "" && fname[0] >= 'A' && fname[0] <= 'Z' { - x.genRefPkgs(t.Field(i).Type) - } - } - } -} - -func (x *genRunner) varsfx() string { - x.c++ - return strconv.FormatUint(x.c, 10) -} - -func (x *genRunner) varsfxreset() { - x.c = 0 -} - -func (x *genRunner) out(s string) { - _, err := io.WriteString(x.w, s) - if err != nil { - panic(err) - } -} - -func (x *genRunner) outf(s string, params ...interface{}) { - _, err := fmt.Fprintf(x.w, s, params...) - if err != nil { - panic(err) - } -} - -func (x *genRunner) line(s string) { - x.out(s) - if len(s) == 0 || s[len(s)-1] != '\n' { - x.out("\n") - } -} - -func (x *genRunner) linef(s string, params ...interface{}) { - x.outf(s, params...) - if len(s) == 0 || s[len(s)-1] != '\n' { - x.out("\n") - } -} - -func (x *genRunner) genTypeName(t reflect.Type) (n string) { - // defer func() { fmt.Printf(">>>> ####: genTypeName: t: %v, name: '%s'\n", t, n) }() - - // if the type has a PkgPath, which doesn't match the current package, - // then include it. - // We cannot depend on t.String() because it includes current package, - // or t.PkgPath because it includes full import path, - // - var ptrPfx string - for t.Kind() == reflect.Ptr { - ptrPfx += "*" - t = t.Elem() - } - if tn := t.Name(); tn != "" { - return ptrPfx + x.genTypeNamePrim(t) - } - switch t.Kind() { - case reflect.Map: - return ptrPfx + "map[" + x.genTypeName(t.Key()) + "]" + x.genTypeName(t.Elem()) - case reflect.Slice: - return ptrPfx + "[]" + x.genTypeName(t.Elem()) - case reflect.Array: - return ptrPfx + "[" + strconv.FormatInt(int64(t.Len()), 10) + "]" + x.genTypeName(t.Elem()) - case reflect.Chan: - return ptrPfx + t.ChanDir().String() + " " + x.genTypeName(t.Elem()) - default: - if t == intfTyp { - return ptrPfx + "interface{}" - } else { - return ptrPfx + x.genTypeNamePrim(t) - } - } -} - -func (x *genRunner) genTypeNamePrim(t reflect.Type) (n string) { - if t.Name() == "" { - return t.String() - } else if genImportPath(t) == "" || genImportPath(t) == genImportPath(x.tc) { - return t.Name() - } else { - return x.imn[genImportPath(t)] + "." + t.Name() - // return t.String() // best way to get the package name inclusive - } -} - -func (x *genRunner) genZeroValueR(t reflect.Type) string { - // if t is a named type, w - switch t.Kind() { - case reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func, - reflect.Slice, reflect.Map, reflect.Invalid: - return "nil" - case reflect.Bool: - return "false" - case reflect.String: - return `""` - case reflect.Struct, reflect.Array: - return x.genTypeName(t) + "{}" - default: // all numbers - return "0" - } -} - -func (x *genRunner) genMethodNameT(t reflect.Type) (s string) { - return genMethodNameT(t, x.tc) -} - -func (x *genRunner) selfer(encode bool) { - t := x.tc - t0 := t - // always make decode use a pointer receiver, - // and structs/arrays always use a ptr receiver (encode|decode) - isptr := !encode || t.Kind() == reflect.Array || (t.Kind() == reflect.Struct && t != timeTyp) - x.varsfxreset() - - fnSigPfx := "func (" + genTopLevelVarName + " " - if isptr { - fnSigPfx += "*" - } - fnSigPfx += x.genTypeName(t) - x.out(fnSigPfx) - - if isptr { - t = reflect.PtrTo(t) - } - if encode { - x.line(") CodecEncodeSelf(e *" + x.cpfx + "Encoder) {") - x.genRequiredMethodVars(true) - x.encVar(genTopLevelVarName, t) - } else { - x.line(") CodecDecodeSelf(d *" + x.cpfx + "Decoder) {") - x.genRequiredMethodVars(false) - // do not use decVar, as there is no need to check TryDecodeAsNil - // or way to elegantly handle that, and also setting it to a - // non-nil value doesn't affect the pointer passed. - // x.decVar(genTopLevelVarName, t, false) - x.dec(genTopLevelVarName, t0, true) - } - x.line("}") - x.line("") - - if encode || t0.Kind() != reflect.Struct { - return - } - - // write is containerMap - if genUseOneFunctionForDecStructMap { - x.out(fnSigPfx) - x.line(") codecDecodeSelfFromMap(l int, d *" + x.cpfx + "Decoder) {") - x.genRequiredMethodVars(false) - x.decStructMap(genTopLevelVarName, "l", rt2id(t0), t0, genStructMapStyleConsolidated) - x.line("}") - x.line("") - } else { - x.out(fnSigPfx) - x.line(") codecDecodeSelfFromMapLenPrefix(l int, d *" + x.cpfx + "Decoder) {") - x.genRequiredMethodVars(false) - x.decStructMap(genTopLevelVarName, "l", rt2id(t0), t0, genStructMapStyleLenPrefix) - x.line("}") - x.line("") - - x.out(fnSigPfx) - x.line(") codecDecodeSelfFromMapCheckBreak(l int, d *" + x.cpfx + "Decoder) {") - x.genRequiredMethodVars(false) - x.decStructMap(genTopLevelVarName, "l", rt2id(t0), t0, genStructMapStyleCheckBreak) - x.line("}") - x.line("") - } - - // write containerArray - x.out(fnSigPfx) - x.line(") codecDecodeSelfFromArray(l int, d *" + x.cpfx + "Decoder) {") - x.genRequiredMethodVars(false) - x.decStructArray(genTopLevelVarName, "l", "return", rt2id(t0), t0) - x.line("}") - x.line("") - -} - -// used for chan, array, slice, map -func (x *genRunner) xtraSM(varname string, t reflect.Type, encode, isptr bool) { - var ptrPfx, addrPfx string - if isptr { - ptrPfx = "*" - } else { - addrPfx = "&" - } - if encode { - x.linef("h.enc%s((%s%s)(%s), e)", x.genMethodNameT(t), ptrPfx, x.genTypeName(t), varname) - } else { - x.linef("h.dec%s((*%s)(%s%s), d)", x.genMethodNameT(t), x.genTypeName(t), addrPfx, varname) - } - x.registerXtraT(t) -} - -func (x *genRunner) registerXtraT(t reflect.Type) { - // recursively register the types - if _, ok := x.tm[t]; ok { - return - } - var tkey reflect.Type - switch t.Kind() { - case reflect.Chan, reflect.Slice, reflect.Array: - case reflect.Map: - tkey = t.Key() - default: - return - } - x.tm[t] = struct{}{} - x.ts = append(x.ts, t) - // check if this refers to any xtra types eg. a slice of array: add the array - x.registerXtraT(t.Elem()) - if tkey != nil { - x.registerXtraT(tkey) - } -} - -// encVar will encode a variable. -// The parameter, t, is the reflect.Type of the variable itself -func (x *genRunner) encVar(varname string, t reflect.Type) { - // fmt.Printf(">>>>>> varname: %s, t: %v\n", varname, t) - var checkNil bool - switch t.Kind() { - case reflect.Ptr, reflect.Interface, reflect.Slice, reflect.Map, reflect.Chan: - checkNil = true - } - if checkNil { - x.linef("if %s == nil { r.EncodeNil() } else { ", varname) - } - - switch t.Kind() { - case reflect.Ptr: - telem := t.Elem() - tek := telem.Kind() - if tek == reflect.Array || (tek == reflect.Struct && telem != timeTyp) { - x.enc(varname, genNonPtr(t)) - break - } - i := x.varsfx() - x.line(genTempVarPfx + i + " := *" + varname) - x.enc(genTempVarPfx+i, genNonPtr(t)) - case reflect.Struct, reflect.Array: - if t == timeTyp { - x.enc(varname, t) - break - } - i := x.varsfx() - x.line(genTempVarPfx + i + " := &" + varname) - x.enc(genTempVarPfx+i, t) - default: - x.enc(varname, t) - } - - if checkNil { - x.line("}") - } - -} - -// enc will encode a variable (varname) of type t, where t represents T. -// if t is !time.Time and t is of kind reflect.Struct or reflect.Array, varname is of type *T -// (to prevent copying), -// else t is of type T -func (x *genRunner) enc(varname string, t reflect.Type) { - rtid := rt2id(t) - ti2 := x.ti.get(rtid, t) - // We call CodecEncodeSelf if one of the following are honored: - // - the type already implements Selfer, call that - // - the type has a Selfer implementation just created, use that - // - the type is in the list of the ones we will generate for, but it is not currently being generated - - mi := x.varsfx() - // tptr := reflect.PtrTo(t) - tk := t.Kind() - if x.checkForSelfer(t, varname) { - if tk == reflect.Array || (tk == reflect.Struct && rtid != timeTypId) { // varname is of type *T - // if tptr.Implements(selferTyp) || t.Implements(selferTyp) { - if ti2.isFlag(typeInfoFlagIsZeroerPtr) || ti2.isFlag(typeInfoFlagIsZeroer) { - x.line(varname + ".CodecEncodeSelf(e)") - return - } - } else { // varname is of type T - if ti2.cs { // t.Implements(selferTyp) { - x.line(varname + ".CodecEncodeSelf(e)") - return - } else if ti2.csp { // tptr.Implements(selferTyp) { - x.linef("%ssf%s := &%s", genTempVarPfx, mi, varname) - x.linef("%ssf%s.CodecEncodeSelf(e)", genTempVarPfx, mi) - return - } - } - - if _, ok := x.te[rtid]; ok { - x.line(varname + ".CodecEncodeSelf(e)") - return - } - } - - inlist := false - for _, t0 := range x.t { - if t == t0 { - inlist = true - if x.checkForSelfer(t, varname) { - x.line(varname + ".CodecEncodeSelf(e)") - return - } - break - } - } - - var rtidAdded bool - if t == x.tc { - x.te[rtid] = true - rtidAdded = true - } - - // check if - // - type is time.Time, RawExt, Raw - // - the type implements (Text|JSON|Binary)(Unm|M)arshal - - x.line("if false {") //start if block - defer func() { x.line("}") }() //end if block - - if t == timeTyp { - x.linef("} else { r.EncodeTime(%s)", varname) - return - } - if t == rawTyp { - x.linef("} else { z.EncRaw(%s)", varname) - return - } - if t == rawExtTyp { - x.linef("} else { r.EncodeRawExt(%s, e)", varname) - return - } - // only check for extensions if the type is named, and has a packagePath. - var arrayOrStruct = tk == reflect.Array || tk == reflect.Struct // meaning varname if of type *T - if !x.nx && genImportPath(t) != "" && t.Name() != "" { - yy := fmt.Sprintf("%sxt%s", genTempVarPfx, mi) - x.linef("} else if %s := z.Extension(z.I2Rtid(%s)); %s != nil { z.EncExtension(%s, %s) ", yy, varname, yy, varname, yy) - } - if arrayOrStruct { // varname is of type *T - if ti2.bm || ti2.bmp { // t.Implements(binaryMarshalerTyp) || tptr.Implements(binaryMarshalerTyp) { - x.linef("} else if z.EncBinary() { z.EncBinaryMarshal(%v) ", varname) - } - if ti2.jm || ti2.jmp { // t.Implements(jsonMarshalerTyp) || tptr.Implements(jsonMarshalerTyp) { - x.linef("} else if !z.EncBinary() && z.IsJSONHandle() { z.EncJSONMarshal(%v) ", varname) - } else if ti2.tm || ti2.tmp { // t.Implements(textMarshalerTyp) || tptr.Implements(textMarshalerTyp) { - x.linef("} else if !z.EncBinary() { z.EncTextMarshal(%v) ", varname) - } - } else { // varname is of type T - if ti2.bm { // t.Implements(binaryMarshalerTyp) { - x.linef("} else if z.EncBinary() { z.EncBinaryMarshal(%v) ", varname) - } else if ti2.bmp { // tptr.Implements(binaryMarshalerTyp) { - x.linef("} else if z.EncBinary() { z.EncBinaryMarshal(&%v) ", varname) - } - if ti2.jm { // t.Implements(jsonMarshalerTyp) { - x.linef("} else if !z.EncBinary() && z.IsJSONHandle() { z.EncJSONMarshal(%v) ", varname) - } else if ti2.jmp { // tptr.Implements(jsonMarshalerTyp) { - x.linef("} else if !z.EncBinary() && z.IsJSONHandle() { z.EncJSONMarshal(&%v) ", varname) - } else if ti2.tm { // t.Implements(textMarshalerTyp) { - x.linef("} else if !z.EncBinary() { z.EncTextMarshal(%v) ", varname) - } else if ti2.tmp { // tptr.Implements(textMarshalerTyp) { - x.linef("} else if !z.EncBinary() { z.EncTextMarshal(&%v) ", varname) - } - } - x.line("} else {") - - switch t.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - x.line("r.EncodeInt(int64(" + varname + "))") - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - x.line("r.EncodeUint(uint64(" + varname + "))") - case reflect.Float32: - x.line("r.EncodeFloat32(float32(" + varname + "))") - case reflect.Float64: - x.line("r.EncodeFloat64(float64(" + varname + "))") - case reflect.Bool: - x.line("r.EncodeBool(bool(" + varname + "))") - case reflect.String: - x.line("r.EncodeString(codecSelferCcUTF8" + x.xs + ", string(" + varname + "))") - case reflect.Chan: - x.xtraSM(varname, t, true, false) - // x.encListFallback(varname, rtid, t) - case reflect.Array: - x.xtraSM(varname, t, true, true) - case reflect.Slice: - // if nil, call dedicated function - // if a []uint8, call dedicated function - // if a known fastpath slice, call dedicated function - // else write encode function in-line. - // - if elements are primitives or Selfers, call dedicated function on each member. - // - else call Encoder.encode(XXX) on it. - if rtid == uint8SliceTypId { - x.line("r.EncodeStringBytes(codecSelferCcRAW" + x.xs + ", []byte(" + varname + "))") - } else if fastpathAV.index(rtid) != -1 { - g := x.newGenV(t) - x.line("z.F." + g.MethodNamePfx("Enc", false) + "V(" + varname + ", e)") - } else { - x.xtraSM(varname, t, true, false) - // x.encListFallback(varname, rtid, t) - } - case reflect.Map: - // if nil, call dedicated function - // if a known fastpath map, call dedicated function - // else write encode function in-line. - // - if elements are primitives or Selfers, call dedicated function on each member. - // - else call Encoder.encode(XXX) on it. - // x.line("if " + varname + " == nil { \nr.EncodeNil()\n } else { ") - if fastpathAV.index(rtid) != -1 { - g := x.newGenV(t) - x.line("z.F." + g.MethodNamePfx("Enc", false) + "V(" + varname + ", e)") - } else { - x.xtraSM(varname, t, true, false) - // x.encMapFallback(varname, rtid, t) - } - case reflect.Struct: - if !inlist { - delete(x.te, rtid) - x.line("z.EncFallback(" + varname + ")") - break - } - x.encStruct(varname, rtid, t) - default: - if rtidAdded { - delete(x.te, rtid) - } - x.line("z.EncFallback(" + varname + ")") - } -} - -func (x *genRunner) encZero(t reflect.Type) { - switch t.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - x.line("r.EncodeInt(0)") - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - x.line("r.EncodeUint(0)") - case reflect.Float32: - x.line("r.EncodeFloat32(0)") - case reflect.Float64: - x.line("r.EncodeFloat64(0)") - case reflect.Bool: - x.line("r.EncodeBool(false)") - case reflect.String: - x.line("r.EncodeString(codecSelferCcUTF8" + x.xs + `, "")`) - default: - x.line("r.EncodeNil()") - } -} - -func (x *genRunner) encOmitEmptyLine(t2 reflect.StructField, varname string, buf *genBuf) { - // smartly check omitEmpty on a struct type, as it may contain uncomparable map/slice/etc. - // also, for maps/slices/arrays, check if len ! 0 (not if == zero value) - varname2 := varname + "." + t2.Name - switch t2.Type.Kind() { - case reflect.Struct: - rtid2 := rt2id(t2.Type) - ti2 := x.ti.get(rtid2, t2.Type) - // fmt.Printf(">>>> structfield: omitempty: type: %s, field: %s\n", t2.Type.Name(), t2.Name) - if ti2.rtid == timeTypId { - buf.s("!(").s(varname2).s(".IsZero())") - break - } - if ti2.isFlag(typeInfoFlagIsZeroerPtr) || ti2.isFlag(typeInfoFlagIsZeroer) { - buf.s("!(").s(varname2).s(".IsZero())") - break - } - if ti2.isFlag(typeInfoFlagComparable) { - buf.s(varname2).s(" != ").s(x.genZeroValueR(t2.Type)) - break - } - // buf.s("(") - buf.s("false") - for i, n := 0, t2.Type.NumField(); i < n; i++ { - f := t2.Type.Field(i) - if f.PkgPath != "" { // unexported - continue - } - buf.s(" || ") - x.encOmitEmptyLine(f, varname2, buf) - } - //buf.s(")") - case reflect.Bool: - buf.s(varname2) - case reflect.Map, reflect.Slice, reflect.Array, reflect.Chan: - buf.s("len(").s(varname2).s(") != 0") - default: - buf.s(varname2).s(" != ").s(x.genZeroValueR(t2.Type)) - } -} - -func (x *genRunner) encStruct(varname string, rtid uintptr, t reflect.Type) { - // Use knowledge from structfieldinfo (mbs, encodable fields. Ignore omitempty. ) - // replicate code in kStruct i.e. for each field, deref type to non-pointer, and call x.enc on it - - // if t === type currently running selfer on, do for all - ti := x.ti.get(rtid, t) - i := x.varsfx() - sepVarname := genTempVarPfx + "sep" + i - numfieldsvar := genTempVarPfx + "q" + i - ti2arrayvar := genTempVarPfx + "r" + i - struct2arrvar := genTempVarPfx + "2arr" + i - - x.line(sepVarname + " := !z.EncBinary()") - x.linef("%s := z.EncBasicHandle().StructToArray", struct2arrvar) - x.linef("_, _ = %s, %s", sepVarname, struct2arrvar) - x.linef("const %s bool = %v // struct tag has 'toArray'", ti2arrayvar, ti.toArray) - - tisfi := ti.sfiSrc // always use sequence from file. decStruct expects same thing. - - // var nn int - // due to omitEmpty, we need to calculate the - // number of non-empty things we write out first. - // This is required as we need to pre-determine the size of the container, - // to support length-prefixing. - if ti.anyOmitEmpty { - x.linef("var %s = [%v]bool{ // should field at this index be written?", numfieldsvar, len(tisfi)) - - for j, si := range tisfi { - _ = j - if !si.omitEmpty() { - // x.linef("%s[%v] = true // %s", numfieldsvar, j, si.fieldName) - x.linef("true, // %s", si.fieldName) - // nn++ - continue - } - var t2 reflect.StructField - var omitline genBuf - { - t2typ := t - varname3 := varname - // go through the loop, record the t2 field explicitly, - // and gather the omit line if embedded in pointers. - for ij, ix := range si.is { - if uint8(ij) == si.nis { - break - } - for t2typ.Kind() == reflect.Ptr { - t2typ = t2typ.Elem() - } - t2 = t2typ.Field(int(ix)) - t2typ = t2.Type - varname3 = varname3 + "." + t2.Name - // do not include actual field in the omit line. - // that is done subsequently (right after - below). - if uint8(ij+1) < si.nis && t2typ.Kind() == reflect.Ptr { - omitline.s(varname3).s(" != nil && ") - } - } - } - x.encOmitEmptyLine(t2, varname, &omitline) - x.linef("%s, // %s", omitline.v(), si.fieldName) - } - x.line("}") - x.linef("_ = %s", numfieldsvar) - } - // x.linef("var %snn%s int", genTempVarPfx, i) - x.linef("if %s || %s {", ti2arrayvar, struct2arrvar) // if ti.toArray { - x.linef("r.WriteArrayStart(%d)", len(tisfi)) - x.linef("} else {") // if not ti.toArray - if ti.anyOmitEmpty { - // nn = 0 - // x.linef("var %snn%s = %v", genTempVarPfx, i, nn) - x.linef("var %snn%s int", genTempVarPfx, i) - x.linef("for _, b := range %s { if b { %snn%s++ } }", numfieldsvar, genTempVarPfx, i) - x.linef("r.WriteMapStart(%snn%s)", genTempVarPfx, i) - x.linef("%snn%s = %v", genTempVarPfx, i, 0) - } else { - x.linef("r.WriteMapStart(%d)", len(tisfi)) - } - x.line("}") // close if not StructToArray - - for j, si := range tisfi { - i := x.varsfx() - isNilVarName := genTempVarPfx + "n" + i - var labelUsed bool - var t2 reflect.StructField - { - t2typ := t - varname3 := varname - for ij, ix := range si.is { - if uint8(ij) == si.nis { - break - } - for t2typ.Kind() == reflect.Ptr { - t2typ = t2typ.Elem() - } - t2 = t2typ.Field(int(ix)) - t2typ = t2.Type - varname3 = varname3 + "." + t2.Name - if t2typ.Kind() == reflect.Ptr { - if !labelUsed { - x.line("var " + isNilVarName + " bool") - } - x.line("if " + varname3 + " == nil { " + isNilVarName + " = true ") - x.line("goto LABEL" + i) - x.line("}") - labelUsed = true - // "varname3 = new(" + x.genTypeName(t3.Elem()) + ") }") - } - } - // t2 = t.FieldByIndex(si.is) - } - if labelUsed { - x.line("LABEL" + i + ":") - } - // if the type of the field is a Selfer, or one of the ones - - x.linef("if %s || %s {", ti2arrayvar, struct2arrvar) // if ti.toArray - if labelUsed { - x.linef("if %s { r.WriteArrayElem(); r.EncodeNil() } else { ", isNilVarName) - } - x.line("r.WriteArrayElem()") - if si.omitEmpty() { - x.linef("if %s[%v] {", numfieldsvar, j) - } - x.encVar(varname+"."+t2.Name, t2.Type) - if si.omitEmpty() { - x.linef("} else {") - x.encZero(t2.Type) - x.linef("}") - } - if labelUsed { - x.line("}") - } - - x.linef("} else {") // if not ti.toArray - - if si.omitEmpty() { - x.linef("if %s[%v] {", numfieldsvar, j) - } - x.line("r.WriteMapElemKey()") - - // x.line("r.EncodeString(codecSelferCcUTF8" + x.xs + ", `" + si.encName + "`)") - // emulate EncStructFieldKey - switch ti.keyType { - case valueTypeInt: - x.linef("r.EncodeInt(z.M.Int(strconv.ParseInt(`%s`, 10, 64)))", si.encName) - case valueTypeUint: - x.linef("r.EncodeUint(z.M.Uint(strconv.ParseUint(`%s`, 10, 64)))", si.encName) - case valueTypeFloat: - x.linef("r.EncodeFloat64(z.M.Float(strconv.ParseFloat(`%s`, 64)))", si.encName) - default: // string - x.linef("r.EncodeString(codecSelferCcUTF8%s, `%s`)", x.xs, si.encName) - } - // x.linef("r.EncStructFieldKey(codecSelferValueType%s%s, `%s`)", ti.keyType.String(), x.xs, si.encName) - x.line("r.WriteMapElemValue()") - if labelUsed { - x.line("if " + isNilVarName + " { r.EncodeNil() } else { ") - x.encVar(varname+"."+t2.Name, t2.Type) - x.line("}") - } else { - x.encVar(varname+"."+t2.Name, t2.Type) - } - if si.omitEmpty() { - x.line("}") - } - x.linef("} ") // end if/else ti.toArray - } - x.linef("if %s || %s {", ti2arrayvar, struct2arrvar) // if ti.toArray { - x.line("r.WriteArrayEnd()") - x.line("} else {") - x.line("r.WriteMapEnd()") - x.line("}") - -} - -func (x *genRunner) encListFallback(varname string, t reflect.Type) { - elemBytes := t.Elem().Kind() == reflect.Uint8 - if t.AssignableTo(uint8SliceTyp) { - x.linef("r.EncodeStringBytes(codecSelferCcRAW%s, []byte(%s))", x.xs, varname) - return - } - if t.Kind() == reflect.Array && elemBytes { - x.linef("r.EncodeStringBytes(codecSelferCcRAW%s, ((*[%d]byte)(%s))[:])", x.xs, t.Len(), varname) - return - } - i := x.varsfx() - if t.Kind() == reflect.Chan { - type ts struct { - Label, Chan, Slice, Sfx string - } - tm, err := template.New("").Parse(genEncChanTmpl) - if err != nil { - panic(err) - } - x.linef("if %s == nil { r.EncodeNil() } else { ", varname) - x.linef("var sch%s []%s", i, x.genTypeName(t.Elem())) - err = tm.Execute(x.w, &ts{"Lsch" + i, varname, "sch" + i, i}) - if err != nil { - panic(err) - } - // x.linef("%s = sch%s", varname, i) - if elemBytes { - x.linef("r.EncodeStringBytes(codecSelferCcRAW%s, []byte(%s))", x.xs, "sch"+i) - x.line("}") - return - } - varname = "sch" + i - } - - x.line("r.WriteArrayStart(len(" + varname + "))") - x.linef("for _, %sv%s := range %s {", genTempVarPfx, i, varname) - x.line("r.WriteArrayElem()") - - x.encVar(genTempVarPfx+"v"+i, t.Elem()) - x.line("}") - x.line("r.WriteArrayEnd()") - if t.Kind() == reflect.Chan { - x.line("}") - } -} - -func (x *genRunner) encMapFallback(varname string, t reflect.Type) { - // TODO: expand this to handle canonical. - i := x.varsfx() - x.line("r.WriteMapStart(len(" + varname + "))") - x.linef("for %sk%s, %sv%s := range %s {", genTempVarPfx, i, genTempVarPfx, i, varname) - x.line("r.WriteMapElemKey()") - x.encVar(genTempVarPfx+"k"+i, t.Key()) - x.line("r.WriteMapElemValue()") - x.encVar(genTempVarPfx+"v"+i, t.Elem()) - x.line("}") - x.line("r.WriteMapEnd()") -} - -func (x *genRunner) decVarInitPtr(varname, nilvar string, t reflect.Type, si *structFieldInfo, - newbuf, nilbuf *genBuf) (t2 reflect.StructField) { - //we must accommodate anonymous fields, where the embedded field is a nil pointer in the value. - // t2 = t.FieldByIndex(si.is) - t2typ := t - varname3 := varname - t2kind := t2typ.Kind() - var nilbufed bool - if si != nil { - for ij, ix := range si.is { - if uint8(ij) == si.nis { - break - } - for t2typ.Kind() == reflect.Ptr { - t2typ = t2typ.Elem() - } - t2 = t2typ.Field(int(ix)) - t2typ = t2.Type - varname3 = varname3 + "." + t2.Name - t2kind = t2typ.Kind() - if t2kind != reflect.Ptr { - continue - } - if newbuf != nil { - newbuf.f("if %s == nil { %s = new(%s) }\n", varname3, varname3, x.genTypeName(t2typ.Elem())) - } - if nilbuf != nil { - if !nilbufed { - nilbuf.s("if true") - nilbufed = true - } - nilbuf.s(" && ").s(varname3).s(" != nil") - } - } - } - // if t2typ.Kind() == reflect.Ptr { - // varname3 = varname3 + t2.Name - // } - if nilbuf != nil { - if nilbufed { - nilbuf.s(" { ") - } - if nilvar != "" { - nilbuf.s(nilvar).s(" = true") - } else if tk := t2typ.Kind(); tk == reflect.Ptr { - if strings.IndexByte(varname3, '.') != -1 || strings.IndexByte(varname3, '[') != -1 { - nilbuf.s(varname3).s(" = nil") - } else { - nilbuf.s("*").s(varname3).s(" = ").s(x.genZeroValueR(t2typ.Elem())) - } - } else { - nilbuf.s(varname3).s(" = ").s(x.genZeroValueR(t2typ)) - } - if nilbufed { - nilbuf.s("}") - } - } - return t2 -} - -// decVar takes a variable called varname, of type t -func (x *genRunner) decVarMain(varname, rand string, t reflect.Type, checkNotNil bool) { - // We only encode as nil if a nillable value. - // This removes some of the wasted checks for TryDecodeAsNil. - // We need to think about this more, to see what happens if omitempty, etc - // cause a nil value to be stored when something is expected. - // This could happen when decoding from a struct encoded as an array. - // For that, decVar should be called with canNil=true, to force true as its value. - var varname2 string - if t.Kind() != reflect.Ptr { - if t.PkgPath() != "" || !x.decTryAssignPrimitive(varname, t, false) { - x.dec(varname, t, false) - } - } else { - if checkNotNil { - x.linef("if %s == nil { %s = new(%s) }", varname, varname, x.genTypeName(t.Elem())) - } - // Ensure we set underlying ptr to a non-nil value (so we can deref to it later). - // There's a chance of a **T in here which is nil. - var ptrPfx string - for t = t.Elem(); t.Kind() == reflect.Ptr; t = t.Elem() { - ptrPfx += "*" - if checkNotNil { - x.linef("if %s%s == nil { %s%s = new(%s)}", - ptrPfx, varname, ptrPfx, varname, x.genTypeName(t)) - } - } - // Should we create temp var if a slice/map indexing? No. dec(...) can now handle it. - - if ptrPfx == "" { - x.dec(varname, t, true) - } else { - varname2 = genTempVarPfx + "z" + rand - x.line(varname2 + " := " + ptrPfx + varname) - x.dec(varname2, t, true) - } - } -} - -// decVar takes a variable called varname, of type t -func (x *genRunner) decVar(varname, nilvar string, t reflect.Type, canBeNil, checkNotNil bool) { - i := x.varsfx() - - // We only encode as nil if a nillable value. - // This removes some of the wasted checks for TryDecodeAsNil. - // We need to think about this more, to see what happens if omitempty, etc - // cause a nil value to be stored when something is expected. - // This could happen when decoding from a struct encoded as an array. - // For that, decVar should be called with canNil=true, to force true as its value. - - if !canBeNil { - canBeNil = genAnythingCanBeNil || !genIsImmutable(t) - } - - if canBeNil { - var buf genBuf - x.decVarInitPtr(varname, nilvar, t, nil, nil, &buf) - x.linef("if r.TryDecodeAsNil() { %s } else {", buf.buf) - } else { - x.line("// cannot be nil") - } - - x.decVarMain(varname, i, t, checkNotNil) - - if canBeNil { - x.line("} ") - } -} - -// dec will decode a variable (varname) of type t or ptrTo(t) if isptr==true. -// t is always a basetype (i.e. not of kind reflect.Ptr). -func (x *genRunner) dec(varname string, t reflect.Type, isptr bool) { - // assumptions: - // - the varname is to a pointer already. No need to take address of it - // - t is always a baseType T (not a *T, etc). - rtid := rt2id(t) - ti2 := x.ti.get(rtid, t) - // tptr := reflect.PtrTo(t) - if x.checkForSelfer(t, varname) { - if ti2.cs || ti2.csp { // t.Implements(selferTyp) || tptr.Implements(selferTyp) { - x.line(varname + ".CodecDecodeSelf(d)") - return - } - if _, ok := x.td[rtid]; ok { - x.line(varname + ".CodecDecodeSelf(d)") - return - } - } - - inlist := false - for _, t0 := range x.t { - if t == t0 { - inlist = true - if x.checkForSelfer(t, varname) { - x.line(varname + ".CodecDecodeSelf(d)") - return - } - break - } - } - - var rtidAdded bool - if t == x.tc { - x.td[rtid] = true - rtidAdded = true - } - - // check if - // - type is time.Time, Raw, RawExt - // - the type implements (Text|JSON|Binary)(Unm|M)arshal - - mi := x.varsfx() - // x.linef("%sm%s := z.DecBinary()", genTempVarPfx, mi) - // x.linef("_ = %sm%s", genTempVarPfx, mi) - x.line("if false {") //start if block - defer func() { x.line("}") }() //end if block - - var ptrPfx, addrPfx string - if isptr { - ptrPfx = "*" - } else { - addrPfx = "&" - } - if t == timeTyp { - x.linef("} else { %s%v = r.DecodeTime()", ptrPfx, varname) - return - } - if t == rawTyp { - x.linef("} else { %s%v = z.DecRaw()", ptrPfx, varname) - return - } - - if t == rawExtTyp { - x.linef("} else { r.DecodeExt(%s%v, 0, nil)", addrPfx, varname) - return - } - - // only check for extensions if the type is named, and has a packagePath. - if !x.nx && genImportPath(t) != "" && t.Name() != "" { - // first check if extensions are configued, before doing the interface conversion - // x.linef("} else if z.HasExtensions() && z.DecExt(%s) {", varname) - yy := fmt.Sprintf("%sxt%s", genTempVarPfx, mi) - x.linef("} else if %s := z.Extension(z.I2Rtid(%s)); %s != nil { z.DecExtension(%s, %s) ", yy, varname, yy, varname, yy) - } - - if ti2.bu || ti2.bup { // t.Implements(binaryUnmarshalerTyp) || tptr.Implements(binaryUnmarshalerTyp) { - x.linef("} else if z.DecBinary() { z.DecBinaryUnmarshal(%s%v) ", addrPfx, varname) - } - if ti2.ju || ti2.jup { // t.Implements(jsonUnmarshalerTyp) || tptr.Implements(jsonUnmarshalerTyp) { - x.linef("} else if !z.DecBinary() && z.IsJSONHandle() { z.DecJSONUnmarshal(%s%v)", addrPfx, varname) - } else if ti2.tu || ti2.tup { // t.Implements(textUnmarshalerTyp) || tptr.Implements(textUnmarshalerTyp) { - x.linef("} else if !z.DecBinary() { z.DecTextUnmarshal(%s%v)", addrPfx, varname) - } - - x.line("} else {") - - if x.decTryAssignPrimitive(varname, t, isptr) { - return - } - - switch t.Kind() { - case reflect.Array, reflect.Chan: - x.xtraSM(varname, t, false, isptr) - case reflect.Slice: - // if a []uint8, call dedicated function - // if a known fastpath slice, call dedicated function - // else write encode function in-line. - // - if elements are primitives or Selfers, call dedicated function on each member. - // - else call Encoder.encode(XXX) on it. - if rtid == uint8SliceTypId { - x.linef("%s%s = r.DecodeBytes(%s(%s[]byte)(%s), false)", - ptrPfx, varname, ptrPfx, ptrPfx, varname) - } else if fastpathAV.index(rtid) != -1 { - g := x.newGenV(t) - x.linef("z.F.%sX(%s%s, d)", g.MethodNamePfx("Dec", false), addrPfx, varname) - } else { - x.xtraSM(varname, t, false, isptr) - // x.decListFallback(varname, rtid, false, t) - } - case reflect.Map: - // if a known fastpath map, call dedicated function - // else write encode function in-line. - // - if elements are primitives or Selfers, call dedicated function on each member. - // - else call Encoder.encode(XXX) on it. - if fastpathAV.index(rtid) != -1 { - g := x.newGenV(t) - x.linef("z.F.%sX(%s%s, d)", g.MethodNamePfx("Dec", false), addrPfx, varname) - } else { - x.xtraSM(varname, t, false, isptr) - // x.decMapFallback(varname, rtid, t) - } - case reflect.Struct: - if inlist { - // no need to create temp variable if isptr, or x.F or x[F] - if isptr || strings.IndexByte(varname, '.') != -1 || strings.IndexByte(varname, '[') != -1 { - x.decStruct(varname, rtid, t) - } else { - varname2 := genTempVarPfx + "j" + mi - x.line(varname2 + " := &" + varname) - x.decStruct(varname2, rtid, t) - } - } else { - // delete(x.td, rtid) - x.line("z.DecFallback(" + addrPfx + varname + ", false)") - } - default: - if rtidAdded { - delete(x.te, rtid) - } - x.line("z.DecFallback(" + addrPfx + varname + ", true)") - } -} - -func (x *genRunner) decTryAssignPrimitive(varname string, t reflect.Type, isptr bool) (done bool) { - // This should only be used for exact primitives (ie un-named types). - // Named types may be implementations of Selfer, Unmarshaler, etc. - // They should be handled by dec(...) - - var ptr string - if isptr { - ptr = "*" - } - switch t.Kind() { - case reflect.Int: - x.linef("%s%s = (%s)(z.C.IntV(r.DecodeInt64(), codecSelferBitsize%s))", ptr, varname, x.genTypeName(t), x.xs) - case reflect.Int8: - x.linef("%s%s = (%s)(z.C.IntV(r.DecodeInt64(), 8))", ptr, varname, x.genTypeName(t)) - case reflect.Int16: - x.linef("%s%s = (%s)(z.C.IntV(r.DecodeInt64(), 16))", ptr, varname, x.genTypeName(t)) - case reflect.Int32: - x.linef("%s%s = (%s)(z.C.IntV(r.DecodeInt64(), 32))", ptr, varname, x.genTypeName(t)) - case reflect.Int64: - x.linef("%s%s = (%s)(r.DecodeInt64())", ptr, varname, x.genTypeName(t)) - - case reflect.Uint: - x.linef("%s%s = (%s)(z.C.UintV(r.DecodeUint64(), codecSelferBitsize%s))", ptr, varname, x.genTypeName(t), x.xs) - case reflect.Uint8: - x.linef("%s%s = (%s)(z.C.UintV(r.DecodeUint64(), 8))", ptr, varname, x.genTypeName(t)) - case reflect.Uint16: - x.linef("%s%s = (%s)(z.C.UintV(r.DecodeUint64(), 16))", ptr, varname, x.genTypeName(t)) - case reflect.Uint32: - x.linef("%s%s = (%s)(z.C.UintV(r.DecodeUint64(), 32))", ptr, varname, x.genTypeName(t)) - case reflect.Uint64: - x.linef("%s%s = (%s)(r.DecodeUint64())", ptr, varname, x.genTypeName(t)) - case reflect.Uintptr: - x.linef("%s%s = (%s)(z.C.UintV(r.DecodeUint64(), codecSelferBitsize%s))", ptr, varname, x.genTypeName(t), x.xs) - - case reflect.Float32: - x.linef("%s%s = (%s)(r.DecodeFloat32As64())", ptr, varname, x.genTypeName(t)) - case reflect.Float64: - x.linef("%s%s = (%s)(r.DecodeFloat64())", ptr, varname, x.genTypeName(t)) - - case reflect.Bool: - x.linef("%s%s = (%s)(r.DecodeBool())", ptr, varname, x.genTypeName(t)) - case reflect.String: - x.linef("%s%s = (%s)(r.DecodeString())", ptr, varname, x.genTypeName(t)) - default: - return false - } - return true -} - -func (x *genRunner) decListFallback(varname string, rtid uintptr, t reflect.Type) { - if t.AssignableTo(uint8SliceTyp) { - x.line("*" + varname + " = r.DecodeBytes(*((*[]byte)(" + varname + ")), false)") - return - } - if t.Kind() == reflect.Array && t.Elem().Kind() == reflect.Uint8 { - x.linef("r.DecodeBytes( ((*[%d]byte)(%s))[:], true)", t.Len(), varname) - return - } - type tstruc struct { - TempVar string - Rand string - Varname string - CTyp string - Typ string - Immutable bool - Size int - } - telem := t.Elem() - ts := tstruc{genTempVarPfx, x.varsfx(), varname, x.genTypeName(t), x.genTypeName(telem), genIsImmutable(telem), int(telem.Size())} - - funcs := make(template.FuncMap) - - funcs["decLineVar"] = func(varname string) string { - x.decVar(varname, "", telem, false, true) - return "" - } - funcs["var"] = func(s string) string { - return ts.TempVar + s + ts.Rand - } - funcs["zero"] = func() string { - return x.genZeroValueR(telem) - } - funcs["isArray"] = func() bool { - return t.Kind() == reflect.Array - } - funcs["isSlice"] = func() bool { - return t.Kind() == reflect.Slice - } - funcs["isChan"] = func() bool { - return t.Kind() == reflect.Chan - } - tm, err := template.New("").Funcs(funcs).Parse(genDecListTmpl) - if err != nil { - panic(err) - } - if err = tm.Execute(x.w, &ts); err != nil { - panic(err) - } -} - -func (x *genRunner) decMapFallback(varname string, rtid uintptr, t reflect.Type) { - type tstruc struct { - TempVar string - Sfx string - Rand string - Varname string - KTyp string - Typ string - Size int - } - telem := t.Elem() - tkey := t.Key() - ts := tstruc{ - genTempVarPfx, x.xs, x.varsfx(), varname, x.genTypeName(tkey), - x.genTypeName(telem), int(telem.Size() + tkey.Size()), - } - - funcs := make(template.FuncMap) - funcs["decElemZero"] = func() string { - return x.genZeroValueR(telem) - } - funcs["decElemKindImmutable"] = func() bool { - return genIsImmutable(telem) - } - funcs["decElemKindPtr"] = func() bool { - return telem.Kind() == reflect.Ptr - } - funcs["decElemKindIntf"] = func() bool { - return telem.Kind() == reflect.Interface - } - funcs["decLineVarK"] = func(varname string) string { - x.decVar(varname, "", tkey, false, true) - return "" - } - funcs["decLineVar"] = func(varname, decodedNilVarname string) string { - x.decVar(varname, decodedNilVarname, telem, false, true) - return "" - } - funcs["var"] = func(s string) string { - return ts.TempVar + s + ts.Rand - } - - tm, err := template.New("").Funcs(funcs).Parse(genDecMapTmpl) - if err != nil { - panic(err) - } - if err = tm.Execute(x.w, &ts); err != nil { - panic(err) - } -} - -func (x *genRunner) decStructMapSwitch(kName string, varname string, rtid uintptr, t reflect.Type) { - ti := x.ti.get(rtid, t) - tisfi := ti.sfiSrc // always use sequence from file. decStruct expects same thing. - x.line("switch (" + kName + ") {") - var newbuf, nilbuf genBuf - for _, si := range tisfi { - x.line("case \"" + si.encName + "\":") - newbuf.reset() - nilbuf.reset() - t2 := x.decVarInitPtr(varname, "", t, si, &newbuf, &nilbuf) - x.linef("if r.TryDecodeAsNil() { %s } else { %s", nilbuf.buf, newbuf.buf) - x.decVarMain(varname+"."+t2.Name, x.varsfx(), t2.Type, false) - x.line("}") - } - x.line("default:") - // pass the slice here, so that the string will not escape, and maybe save allocation - x.line("z.DecStructFieldNotFound(-1, " + kName + ")") - x.line("} // end switch " + kName) -} - -func (x *genRunner) decStructMap(varname, lenvarname string, rtid uintptr, t reflect.Type, style genStructMapStyle) { - tpfx := genTempVarPfx - ti := x.ti.get(rtid, t) - i := x.varsfx() - kName := tpfx + "s" + i - - switch style { - case genStructMapStyleLenPrefix: - x.linef("for %sj%s := 0; %sj%s < %s; %sj%s++ {", tpfx, i, tpfx, i, lenvarname, tpfx, i) - case genStructMapStyleCheckBreak: - x.linef("for %sj%s := 0; !r.CheckBreak(); %sj%s++ {", tpfx, i, tpfx, i) - default: // 0, otherwise. - x.linef("var %shl%s bool = %s >= 0", tpfx, i, lenvarname) // has length - x.linef("for %sj%s := 0; ; %sj%s++ {", tpfx, i, tpfx, i) - x.linef("if %shl%s { if %sj%s >= %s { break }", tpfx, i, tpfx, i, lenvarname) - x.line("} else { if r.CheckBreak() { break }; }") - } - x.line("r.ReadMapElemKey()") - - // emulate decstructfieldkey - switch ti.keyType { - case valueTypeInt: - x.linef("%s := z.StringView(strconv.AppendInt(z.DecScratchArrayBuffer()[:0], r.DecodeInt64(), 10))", kName) - case valueTypeUint: - x.linef("%s := z.StringView(strconv.AppendUint(z.DecScratchArrayBuffer()[:0], r.DecodeUint64(), 10))", kName) - case valueTypeFloat: - x.linef("%s := z.StringView(strconv.AppendFloat(z.DecScratchArrayBuffer()[:0], r.DecodeFloat64(), 'f', -1, 64))", kName) - default: // string - x.linef("%s := z.StringView(r.DecodeStringAsBytes())", kName) - } - // x.linef("%s := z.StringView(r.DecStructFieldKey(codecSelferValueType%s%s, z.DecScratchArrayBuffer()))", kName, ti.keyType.String(), x.xs) - - x.line("r.ReadMapElemValue()") - x.decStructMapSwitch(kName, varname, rtid, t) - - x.line("} // end for " + tpfx + "j" + i) - x.line("r.ReadMapEnd()") -} - -func (x *genRunner) decStructArray(varname, lenvarname, breakString string, rtid uintptr, t reflect.Type) { - tpfx := genTempVarPfx - i := x.varsfx() - ti := x.ti.get(rtid, t) - tisfi := ti.sfiSrc // always use sequence from file. decStruct expects same thing. - x.linef("var %sj%s int", tpfx, i) - x.linef("var %sb%s bool", tpfx, i) // break - x.linef("var %shl%s bool = %s >= 0", tpfx, i, lenvarname) // has length - var newbuf, nilbuf genBuf - for _, si := range tisfi { - x.linef("%sj%s++; if %shl%s { %sb%s = %sj%s > %s } else { %sb%s = r.CheckBreak() }", - tpfx, i, tpfx, i, tpfx, i, - tpfx, i, lenvarname, tpfx, i) - x.linef("if %sb%s { r.ReadArrayEnd(); %s }", tpfx, i, breakString) - x.line("r.ReadArrayElem()") - newbuf.reset() - nilbuf.reset() - t2 := x.decVarInitPtr(varname, "", t, si, &newbuf, &nilbuf) - x.linef("if r.TryDecodeAsNil() { %s } else { %s", nilbuf.buf, newbuf.buf) - x.decVarMain(varname+"."+t2.Name, x.varsfx(), t2.Type, false) - x.line("}") - } - // read remaining values and throw away. - x.line("for {") - x.linef("%sj%s++; if %shl%s { %sb%s = %sj%s > %s } else { %sb%s = r.CheckBreak() }", - tpfx, i, tpfx, i, tpfx, i, - tpfx, i, lenvarname, tpfx, i) - x.linef("if %sb%s { break }", tpfx, i) - x.line("r.ReadArrayElem()") - x.linef(`z.DecStructFieldNotFound(%sj%s - 1, "")`, tpfx, i) - x.line("}") - x.line("r.ReadArrayEnd()") -} - -func (x *genRunner) decStruct(varname string, rtid uintptr, t reflect.Type) { - // varname MUST be a ptr, or a struct field or a slice element. - i := x.varsfx() - x.linef("%sct%s := r.ContainerType()", genTempVarPfx, i) - x.linef("if %sct%s == codecSelferValueTypeMap%s {", genTempVarPfx, i, x.xs) - x.line(genTempVarPfx + "l" + i + " := r.ReadMapStart()") - x.linef("if %sl%s == 0 {", genTempVarPfx, i) - x.line("r.ReadMapEnd()") - if genUseOneFunctionForDecStructMap { - x.line("} else { ") - x.linef("%s.codecDecodeSelfFromMap(%sl%s, d)", varname, genTempVarPfx, i) - } else { - x.line("} else if " + genTempVarPfx + "l" + i + " > 0 { ") - x.line(varname + ".codecDecodeSelfFromMapLenPrefix(" + genTempVarPfx + "l" + i + ", d)") - x.line("} else {") - x.line(varname + ".codecDecodeSelfFromMapCheckBreak(" + genTempVarPfx + "l" + i + ", d)") - } - x.line("}") - - // else if container is array - x.linef("} else if %sct%s == codecSelferValueTypeArray%s {", genTempVarPfx, i, x.xs) - x.line(genTempVarPfx + "l" + i + " := r.ReadArrayStart()") - x.linef("if %sl%s == 0 {", genTempVarPfx, i) - x.line("r.ReadArrayEnd()") - x.line("} else { ") - x.linef("%s.codecDecodeSelfFromArray(%sl%s, d)", varname, genTempVarPfx, i) - x.line("}") - // else panic - x.line("} else { ") - x.line("panic(errCodecSelferOnlyMapOrArrayEncodeToStruct" + x.xs + ")") - x.line("} ") -} - -// -------- - -type genV struct { - // genV is either a primitive (Primitive != "") or a map (MapKey != "") or a slice - MapKey string - Elem string - Primitive string - Size int -} - -func (x *genRunner) newGenV(t reflect.Type) (v genV) { - switch t.Kind() { - case reflect.Slice, reflect.Array: - te := t.Elem() - v.Elem = x.genTypeName(te) - v.Size = int(te.Size()) - case reflect.Map: - te, tk := t.Elem(), t.Key() - v.Elem = x.genTypeName(te) - v.MapKey = x.genTypeName(tk) - v.Size = int(te.Size() + tk.Size()) - default: - panic("unexpected type for newGenV. Requires map or slice type") - } - return -} - -func (x *genV) MethodNamePfx(prefix string, prim bool) string { - var name []byte - if prefix != "" { - name = append(name, prefix...) - } - if prim { - name = append(name, genTitleCaseName(x.Primitive)...) - } else { - if x.MapKey == "" { - name = append(name, "Slice"...) - } else { - name = append(name, "Map"...) - name = append(name, genTitleCaseName(x.MapKey)...) - } - name = append(name, genTitleCaseName(x.Elem)...) - } - return string(name) - -} - -// genImportPath returns import path of a non-predeclared named typed, or an empty string otherwise. -// -// This handles the misbehaviour that occurs when 1.5-style vendoring is enabled, -// where PkgPath returns the full path, including the vendoring pre-fix that should have been stripped. -// We strip it here. -func genImportPath(t reflect.Type) (s string) { - s = t.PkgPath() - if genCheckVendor { - // HACK: always handle vendoring. It should be typically on in go 1.6, 1.7 - s = genStripVendor(s) - } - return -} - -// A go identifier is (letter|_)[letter|number|_]* -func genGoIdentifier(s string, checkFirstChar bool) string { - b := make([]byte, 0, len(s)) - t := make([]byte, 4) - var n int - for i, r := range s { - if checkFirstChar && i == 0 && !unicode.IsLetter(r) { - b = append(b, '_') - } - // r must be unicode_letter, unicode_digit or _ - if unicode.IsLetter(r) || unicode.IsDigit(r) { - n = utf8.EncodeRune(t, r) - b = append(b, t[:n]...) - } else { - b = append(b, '_') - } - } - return string(b) -} - -func genNonPtr(t reflect.Type) reflect.Type { - for t.Kind() == reflect.Ptr { - t = t.Elem() - } - return t -} - -func genTitleCaseName(s string) string { - switch s { - case "interface{}", "interface {}": - return "Intf" - default: - return strings.ToUpper(s[0:1]) + s[1:] - } -} - -func genMethodNameT(t reflect.Type, tRef reflect.Type) (n string) { - var ptrPfx string - for t.Kind() == reflect.Ptr { - ptrPfx += "Ptrto" - t = t.Elem() - } - tstr := t.String() - if tn := t.Name(); tn != "" { - if tRef != nil && genImportPath(t) == genImportPath(tRef) { - return ptrPfx + tn - } else { - if genQNameRegex.MatchString(tstr) { - return ptrPfx + strings.Replace(tstr, ".", "_", 1000) - } else { - return ptrPfx + genCustomTypeName(tstr) - } - } - } - switch t.Kind() { - case reflect.Map: - return ptrPfx + "Map" + genMethodNameT(t.Key(), tRef) + genMethodNameT(t.Elem(), tRef) - case reflect.Slice: - return ptrPfx + "Slice" + genMethodNameT(t.Elem(), tRef) - case reflect.Array: - return ptrPfx + "Array" + strconv.FormatInt(int64(t.Len()), 10) + genMethodNameT(t.Elem(), tRef) - case reflect.Chan: - var cx string - switch t.ChanDir() { - case reflect.SendDir: - cx = "ChanSend" - case reflect.RecvDir: - cx = "ChanRecv" - default: - cx = "Chan" - } - return ptrPfx + cx + genMethodNameT(t.Elem(), tRef) - default: - if t == intfTyp { - return ptrPfx + "Interface" - } else { - if tRef != nil && genImportPath(t) == genImportPath(tRef) { - if t.Name() != "" { - return ptrPfx + t.Name() - } else { - return ptrPfx + genCustomTypeName(tstr) - } - } else { - // best way to get the package name inclusive - // return ptrPfx + strings.Replace(tstr, ".", "_", 1000) - // return ptrPfx + genBase64enc.EncodeToString([]byte(tstr)) - if t.Name() != "" && genQNameRegex.MatchString(tstr) { - return ptrPfx + strings.Replace(tstr, ".", "_", 1000) - } else { - return ptrPfx + genCustomTypeName(tstr) - } - } - } - } -} - -// genCustomNameForType base64encodes the t.String() value in such a way -// that it can be used within a function name. -func genCustomTypeName(tstr string) string { - len2 := genBase64enc.EncodedLen(len(tstr)) - bufx := make([]byte, len2) - genBase64enc.Encode(bufx, []byte(tstr)) - for i := len2 - 1; i >= 0; i-- { - if bufx[i] == '=' { - len2-- - } else { - break - } - } - return string(bufx[:len2]) -} - -func genIsImmutable(t reflect.Type) (v bool) { - return isImmutableKind(t.Kind()) -} - -type genInternal struct { - Version int - Values []genV -} - -func (x genInternal) FastpathLen() (l int) { - for _, v := range x.Values { - if v.Primitive == "" && !(v.MapKey == "" && v.Elem == "uint8") { - l++ - } - } - return -} - -func genInternalZeroValue(s string) string { - switch s { - case "interface{}", "interface {}": - return "nil" - case "bool": - return "false" - case "string": - return `""` - default: - return "0" - } -} - -var genInternalNonZeroValueIdx [5]uint64 -var genInternalNonZeroValueStrs = [2][5]string{ - {`"string-is-an-interface"`, "true", `"some-string"`, "11.1", "33"}, - {`"string-is-an-interface-2"`, "true", `"some-string-2"`, "22.2", "44"}, -} - -func genInternalNonZeroValue(s string) string { - switch s { - case "interface{}", "interface {}": - genInternalNonZeroValueIdx[0]++ - return genInternalNonZeroValueStrs[genInternalNonZeroValueIdx[0]%2][0] // return string, to remove ambiguity - case "bool": - genInternalNonZeroValueIdx[1]++ - return genInternalNonZeroValueStrs[genInternalNonZeroValueIdx[1]%2][1] - case "string": - genInternalNonZeroValueIdx[2]++ - return genInternalNonZeroValueStrs[genInternalNonZeroValueIdx[2]%2][2] - case "float32", "float64", "float", "double": - genInternalNonZeroValueIdx[3]++ - return genInternalNonZeroValueStrs[genInternalNonZeroValueIdx[3]%2][3] - default: - genInternalNonZeroValueIdx[4]++ - return genInternalNonZeroValueStrs[genInternalNonZeroValueIdx[4]%2][4] - } -} - -func genInternalEncCommandAsString(s string, vname string) string { - switch s { - case "uint", "uint8", "uint16", "uint32", "uint64": - return "ee.EncodeUint(uint64(" + vname + "))" - case "int", "int8", "int16", "int32", "int64": - return "ee.EncodeInt(int64(" + vname + "))" - case "string": - return "ee.EncodeString(cUTF8, " + vname + ")" - case "float32": - return "ee.EncodeFloat32(" + vname + ")" - case "float64": - return "ee.EncodeFloat64(" + vname + ")" - case "bool": - return "ee.EncodeBool(" + vname + ")" - // case "symbol": - // return "ee.EncodeSymbol(" + vname + ")" - default: - return "e.encode(" + vname + ")" - } -} - -func genInternalDecCommandAsString(s string) string { - switch s { - case "uint": - return "uint(chkOvf.UintV(dd.DecodeUint64(), uintBitsize))" - case "uint8": - return "uint8(chkOvf.UintV(dd.DecodeUint64(), 8))" - case "uint16": - return "uint16(chkOvf.UintV(dd.DecodeUint64(), 16))" - case "uint32": - return "uint32(chkOvf.UintV(dd.DecodeUint64(), 32))" - case "uint64": - return "dd.DecodeUint64()" - case "uintptr": - return "uintptr(chkOvf.UintV(dd.DecodeUint64(), uintBitsize))" - case "int": - return "int(chkOvf.IntV(dd.DecodeInt64(), intBitsize))" - case "int8": - return "int8(chkOvf.IntV(dd.DecodeInt64(), 8))" - case "int16": - return "int16(chkOvf.IntV(dd.DecodeInt64(), 16))" - case "int32": - return "int32(chkOvf.IntV(dd.DecodeInt64(), 32))" - case "int64": - return "dd.DecodeInt64()" - - case "string": - return "dd.DecodeString()" - case "float32": - return "float32(chkOvf.Float32V(dd.DecodeFloat64()))" - case "float64": - return "dd.DecodeFloat64()" - case "bool": - return "dd.DecodeBool()" - default: - panic(errors.New("gen internal: unknown type for decode: " + s)) - } -} - -func genInternalSortType(s string, elem bool) string { - for _, v := range [...]string{"int", "uint", "float", "bool", "string"} { - if strings.HasPrefix(s, v) { - if elem { - if v == "int" || v == "uint" || v == "float" { - return v + "64" - } else { - return v - } - } - return v + "Slice" - } - } - panic("sorttype: unexpected type: " + s) -} - -func genStripVendor(s string) string { - // HACK: Misbehaviour occurs in go 1.5. May have to re-visit this later. - // if s contains /vendor/ OR startsWith vendor/, then return everything after it. - const vendorStart = "vendor/" - const vendorInline = "/vendor/" - if i := strings.LastIndex(s, vendorInline); i >= 0 { - s = s[i+len(vendorInline):] - } else if strings.HasPrefix(s, vendorStart) { - s = s[len(vendorStart):] - } - return s -} - -// var genInternalMu sync.Mutex -var genInternalV = genInternal{Version: genVersion} -var genInternalTmplFuncs template.FuncMap -var genInternalOnce sync.Once - -func genInternalInit() { - types := [...]string{ - "interface{}", - "string", - "float32", - "float64", - "uint", - "uint8", - "uint16", - "uint32", - "uint64", - "uintptr", - "int", - "int8", - "int16", - "int32", - "int64", - "bool", - } - // keep as slice, so it is in specific iteration order. - // Initial order was uint64, string, interface{}, int, int64 - mapvaltypes := [...]string{ - "interface{}", - "string", - "uint", - "uint8", - "uint16", - "uint32", - "uint64", - "uintptr", - "int", - "int8", - "int16", - "int32", - "int64", - "float32", - "float64", - "bool", - } - wordSizeBytes := int(intBitsize) / 8 - - mapvaltypes2 := map[string]int{ - "interface{}": 2 * wordSizeBytes, - "string": 2 * wordSizeBytes, - "uint": 1 * wordSizeBytes, - "uint8": 1, - "uint16": 2, - "uint32": 4, - "uint64": 8, - "uintptr": 1 * wordSizeBytes, - "int": 1 * wordSizeBytes, - "int8": 1, - "int16": 2, - "int32": 4, - "int64": 8, - "float32": 4, - "float64": 8, - "bool": 1, - } - var gt = genInternal{Version: genVersion} - - // For each slice or map type, there must be a (symmetrical) Encode and Decode fast-path function - for _, s := range types { - gt.Values = append(gt.Values, genV{Primitive: s, Size: mapvaltypes2[s]}) - // if s != "uint8" { // do not generate fast path for slice of bytes. Treat specially already. - // gt.Values = append(gt.Values, genV{Elem: s, Size: mapvaltypes2[s]}) - // } - gt.Values = append(gt.Values, genV{Elem: s, Size: mapvaltypes2[s]}) - if _, ok := mapvaltypes2[s]; !ok { - gt.Values = append(gt.Values, genV{MapKey: s, Elem: s, Size: 2 * mapvaltypes2[s]}) - } - for _, ms := range mapvaltypes { - gt.Values = append(gt.Values, genV{MapKey: s, Elem: ms, Size: mapvaltypes2[s] + mapvaltypes2[ms]}) - } - } - - funcs := make(template.FuncMap) - // funcs["haspfx"] = strings.HasPrefix - funcs["encmd"] = genInternalEncCommandAsString - funcs["decmd"] = genInternalDecCommandAsString - funcs["zerocmd"] = genInternalZeroValue - funcs["nonzerocmd"] = genInternalNonZeroValue - funcs["hasprefix"] = strings.HasPrefix - funcs["sorttype"] = genInternalSortType - - genInternalV = gt - genInternalTmplFuncs = funcs -} - -// genInternalGoFile is used to generate source files from templates. -// It is run by the program author alone. -// Unfortunately, it has to be exported so that it can be called from a command line tool. -// *** DO NOT USE *** -func genInternalGoFile(r io.Reader, w io.Writer) (err error) { - genInternalOnce.Do(genInternalInit) - - gt := genInternalV - - t := template.New("").Funcs(genInternalTmplFuncs) - - tmplstr, err := ioutil.ReadAll(r) - if err != nil { - return - } - - if t, err = t.Parse(string(tmplstr)); err != nil { - return - } - - var out bytes.Buffer - err = t.Execute(&out, gt) - if err != nil { - return - } - - bout, err := format.Source(out.Bytes()) - if err != nil { - w.Write(out.Bytes()) // write out if error, so we can still see. - // w.Write(bout) // write out if error, as much as possible, so we can still see. - return - } - w.Write(bout) - return -} diff --git a/vendor/github.com/ugorji/go/codec/goversion_arrayof_gte_go15.go b/vendor/github.com/ugorji/go/codec/goversion_arrayof_gte_go15.go deleted file mode 100644 index 9ddbe2059..000000000 --- a/vendor/github.com/ugorji/go/codec/goversion_arrayof_gte_go15.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build go1.5 - -package codec - -import "reflect" - -const reflectArrayOfSupported = true - -func reflectArrayOf(count int, elem reflect.Type) reflect.Type { - return reflect.ArrayOf(count, elem) -} diff --git a/vendor/github.com/ugorji/go/codec/goversion_arrayof_lt_go15.go b/vendor/github.com/ugorji/go/codec/goversion_arrayof_lt_go15.go deleted file mode 100644 index c5fcd6697..000000000 --- a/vendor/github.com/ugorji/go/codec/goversion_arrayof_lt_go15.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build !go1.5 - -package codec - -import "reflect" - -const reflectArrayOfSupported = false - -func reflectArrayOf(count int, elem reflect.Type) reflect.Type { - panic("codec: reflect.ArrayOf unsupported in this go version") -} diff --git a/vendor/github.com/ugorji/go/codec/goversion_makemap_gte_go19.go b/vendor/github.com/ugorji/go/codec/goversion_makemap_gte_go19.go deleted file mode 100644 index bc39d6b71..000000000 --- a/vendor/github.com/ugorji/go/codec/goversion_makemap_gte_go19.go +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build go1.9 - -package codec - -import "reflect" - -func makeMapReflect(t reflect.Type, size int) reflect.Value { - if size < 0 { - return reflect.MakeMapWithSize(t, 4) - } - return reflect.MakeMapWithSize(t, size) -} diff --git a/vendor/github.com/ugorji/go/codec/goversion_makemap_lt_go19.go b/vendor/github.com/ugorji/go/codec/goversion_makemap_lt_go19.go deleted file mode 100644 index cde4cd372..000000000 --- a/vendor/github.com/ugorji/go/codec/goversion_makemap_lt_go19.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build !go1.9 - -package codec - -import "reflect" - -func makeMapReflect(t reflect.Type, size int) reflect.Value { - return reflect.MakeMap(t) -} diff --git a/vendor/github.com/ugorji/go/codec/goversion_unexportedembeddedptr_gte_go110.go b/vendor/github.com/ugorji/go/codec/goversion_unexportedembeddedptr_gte_go110.go deleted file mode 100644 index 794133a3c..000000000 --- a/vendor/github.com/ugorji/go/codec/goversion_unexportedembeddedptr_gte_go110.go +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build go1.10 - -package codec - -const allowSetUnexportedEmbeddedPtr = false diff --git a/vendor/github.com/ugorji/go/codec/goversion_unexportedembeddedptr_lt_go110.go b/vendor/github.com/ugorji/go/codec/goversion_unexportedembeddedptr_lt_go110.go deleted file mode 100644 index fd92ede35..000000000 --- a/vendor/github.com/ugorji/go/codec/goversion_unexportedembeddedptr_lt_go110.go +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build !go1.10 - -package codec - -const allowSetUnexportedEmbeddedPtr = true diff --git a/vendor/github.com/ugorji/go/codec/goversion_unsupported_lt_go14.go b/vendor/github.com/ugorji/go/codec/goversion_unsupported_lt_go14.go deleted file mode 100644 index 8debfa613..000000000 --- a/vendor/github.com/ugorji/go/codec/goversion_unsupported_lt_go14.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build !go1.4 - -package codec - -// This codec package will only work for go1.4 and above. -// This is for the following reasons: -// - go 1.4 was released in 2014 -// - go runtime is written fully in go -// - interface only holds pointers -// - reflect.Value is stabilized as 3 words - -func init() { - panic("codec: go 1.3 and below are not supported") -} diff --git a/vendor/github.com/ugorji/go/codec/goversion_vendor_eq_go15.go b/vendor/github.com/ugorji/go/codec/goversion_vendor_eq_go15.go deleted file mode 100644 index 0f1bb01e5..000000000 --- a/vendor/github.com/ugorji/go/codec/goversion_vendor_eq_go15.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build go1.5,!go1.6 - -package codec - -import "os" - -var genCheckVendor = os.Getenv("GO15VENDOREXPERIMENT") == "1" diff --git a/vendor/github.com/ugorji/go/codec/goversion_vendor_eq_go16.go b/vendor/github.com/ugorji/go/codec/goversion_vendor_eq_go16.go deleted file mode 100644 index 2fb4b057d..000000000 --- a/vendor/github.com/ugorji/go/codec/goversion_vendor_eq_go16.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build go1.6,!go1.7 - -package codec - -import "os" - -var genCheckVendor = os.Getenv("GO15VENDOREXPERIMENT") != "0" diff --git a/vendor/github.com/ugorji/go/codec/goversion_vendor_gte_go17.go b/vendor/github.com/ugorji/go/codec/goversion_vendor_gte_go17.go deleted file mode 100644 index c5b815505..000000000 --- a/vendor/github.com/ugorji/go/codec/goversion_vendor_gte_go17.go +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build go1.7 - -package codec - -const genCheckVendor = true diff --git a/vendor/github.com/ugorji/go/codec/goversion_vendor_lt_go15.go b/vendor/github.com/ugorji/go/codec/goversion_vendor_lt_go15.go deleted file mode 100644 index 837cf240b..000000000 --- a/vendor/github.com/ugorji/go/codec/goversion_vendor_lt_go15.go +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build !go1.5 - -package codec - -var genCheckVendor = false diff --git a/vendor/github.com/ugorji/go/codec/helper.go b/vendor/github.com/ugorji/go/codec/helper.go deleted file mode 100644 index bd29895b6..000000000 --- a/vendor/github.com/ugorji/go/codec/helper.go +++ /dev/null @@ -1,2414 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -// Contains code shared by both encode and decode. - -// Some shared ideas around encoding/decoding -// ------------------------------------------ -// -// If an interface{} is passed, we first do a type assertion to see if it is -// a primitive type or a map/slice of primitive types, and use a fastpath to handle it. -// -// If we start with a reflect.Value, we are already in reflect.Value land and -// will try to grab the function for the underlying Type and directly call that function. -// This is more performant than calling reflect.Value.Interface(). -// -// This still helps us bypass many layers of reflection, and give best performance. -// -// Containers -// ------------ -// Containers in the stream are either associative arrays (key-value pairs) or -// regular arrays (indexed by incrementing integers). -// -// Some streams support indefinite-length containers, and use a breaking -// byte-sequence to denote that the container has come to an end. -// -// Some streams also are text-based, and use explicit separators to denote the -// end/beginning of different values. -// -// During encode, we use a high-level condition to determine how to iterate through -// the container. That decision is based on whether the container is text-based (with -// separators) or binary (without separators). If binary, we do not even call the -// encoding of separators. -// -// During decode, we use a different high-level condition to determine how to iterate -// through the containers. That decision is based on whether the stream contained -// a length prefix, or if it used explicit breaks. If length-prefixed, we assume that -// it has to be binary, and we do not even try to read separators. -// -// Philosophy -// ------------ -// On decode, this codec will update containers appropriately: -// - If struct, update fields from stream into fields of struct. -// If field in stream not found in struct, handle appropriately (based on option). -// If a struct field has no corresponding value in the stream, leave it AS IS. -// If nil in stream, set value to nil/zero value. -// - If map, update map from stream. -// If the stream value is NIL, set the map to nil. -// - if slice, try to update up to length of array in stream. -// if container len is less than stream array length, -// and container cannot be expanded, handled (based on option). -// This means you can decode 4-element stream array into 1-element array. -// -// ------------------------------------ -// On encode, user can specify omitEmpty. This means that the value will be omitted -// if the zero value. The problem may occur during decode, where omitted values do not affect -// the value being decoded into. This means that if decoding into a struct with an -// int field with current value=5, and the field is omitted in the stream, then after -// decoding, the value will still be 5 (not 0). -// omitEmpty only works if you guarantee that you always decode into zero-values. -// -// ------------------------------------ -// We could have truncated a map to remove keys not available in the stream, -// or set values in the struct which are not in the stream to their zero values. -// We decided against it because there is no efficient way to do it. -// We may introduce it as an option later. -// However, that will require enabling it for both runtime and code generation modes. -// -// To support truncate, we need to do 2 passes over the container: -// map -// - first collect all keys (e.g. in k1) -// - for each key in stream, mark k1 that the key should not be removed -// - after updating map, do second pass and call delete for all keys in k1 which are not marked -// struct: -// - for each field, track the *typeInfo s1 -// - iterate through all s1, and for each one not marked, set value to zero -// - this involves checking the possible anonymous fields which are nil ptrs. -// too much work. -// -// ------------------------------------------ -// Error Handling is done within the library using panic. -// -// This way, the code doesn't have to keep checking if an error has happened, -// and we don't have to keep sending the error value along with each call -// or storing it in the En|Decoder and checking it constantly along the way. -// -// The disadvantage is that small functions which use panics cannot be inlined. -// The code accounts for that by only using panics behind an interface; -// since interface calls cannot be inlined, this is irrelevant. -// -// We considered storing the error is En|Decoder. -// - once it has its err field set, it cannot be used again. -// - panicing will be optional, controlled by const flag. -// - code should always check error first and return early. -// We eventually decided against it as it makes the code clumsier to always -// check for these error conditions. - -import ( - "bytes" - "encoding" - "encoding/binary" - "errors" - "fmt" - "io" - "math" - "reflect" - "sort" - "strconv" - "strings" - "sync" - "time" -) - -const ( - scratchByteArrayLen = 32 - // initCollectionCap = 16 // 32 is defensive. 16 is preferred. - - // Support encoding.(Binary|Text)(Unm|M)arshaler. - // This constant flag will enable or disable it. - supportMarshalInterfaces = true - - // for debugging, set this to false, to catch panic traces. - // Note that this will always cause rpc tests to fail, since they need io.EOF sent via panic. - recoverPanicToErr = true - - // arrayCacheLen is the length of the cache used in encoder or decoder for - // allowing zero-alloc initialization. - arrayCacheLen = 8 - - // size of the cacheline: defaulting to value for archs: amd64, arm64, 386 - // should use "runtime/internal/sys".CacheLineSize, but that is not exposed. - cacheLineSize = 64 - - wordSizeBits = 32 << (^uint(0) >> 63) // strconv.IntSize - wordSize = wordSizeBits / 8 - - maxLevelsEmbedding = 15 // use this, so structFieldInfo fits into 8 bytes -) - -var ( - oneByteArr = [1]byte{0} - zeroByteSlice = oneByteArr[:0:0] -) - -var refBitset bitset32 -var pool pooler -var panicv panicHdl - -func init() { - pool.init() - - refBitset.set(byte(reflect.Map)) - refBitset.set(byte(reflect.Ptr)) - refBitset.set(byte(reflect.Func)) - refBitset.set(byte(reflect.Chan)) -} - -type charEncoding uint8 - -const ( - cRAW charEncoding = iota - cUTF8 - cUTF16LE - cUTF16BE - cUTF32LE - cUTF32BE -) - -// valueType is the stream type -type valueType uint8 - -const ( - valueTypeUnset valueType = iota - valueTypeNil - valueTypeInt - valueTypeUint - valueTypeFloat - valueTypeBool - valueTypeString - valueTypeSymbol - valueTypeBytes - valueTypeMap - valueTypeArray - valueTypeTime - valueTypeExt - - // valueTypeInvalid = 0xff -) - -var valueTypeStrings = [...]string{ - "Unset", - "Nil", - "Int", - "Uint", - "Float", - "Bool", - "String", - "Symbol", - "Bytes", - "Map", - "Array", - "Timestamp", - "Ext", -} - -func (x valueType) String() string { - if int(x) < len(valueTypeStrings) { - return valueTypeStrings[x] - } - return strconv.FormatInt(int64(x), 10) -} - -type seqType uint8 - -const ( - _ seqType = iota - seqTypeArray - seqTypeSlice - seqTypeChan -) - -// note that containerMapStart and containerArraySend are not sent. -// This is because the ReadXXXStart and EncodeXXXStart already does these. -type containerState uint8 - -const ( - _ containerState = iota - - containerMapStart // slot left open, since Driver method already covers it - containerMapKey - containerMapValue - containerMapEnd - containerArrayStart // slot left open, since Driver methods already cover it - containerArrayElem - containerArrayEnd -) - -// // sfiIdx used for tracking where a (field/enc)Name is seen in a []*structFieldInfo -// type sfiIdx struct { -// name string -// index int -// } - -// do not recurse if a containing type refers to an embedded type -// which refers back to its containing type (via a pointer). -// The second time this back-reference happens, break out, -// so as not to cause an infinite loop. -const rgetMaxRecursion = 2 - -// Anecdotally, we believe most types have <= 12 fields. -// - even Java's PMD rules set TooManyFields threshold to 15. -// However, go has embedded fields, which should be regarded as -// top level, allowing structs to possibly double or triple. -// In addition, we don't want to keep creating transient arrays, -// especially for the sfi index tracking, and the evtypes tracking. -// -// So - try to keep typeInfoLoadArray within 2K bytes -const ( - typeInfoLoadArraySfisLen = 16 - typeInfoLoadArraySfiidxLen = 8 * 112 - typeInfoLoadArrayEtypesLen = 12 - typeInfoLoadArrayBLen = 8 * 4 -) - -type typeInfoLoad struct { - // fNames []string - // encNames []string - etypes []uintptr - sfis []structFieldInfo -} - -type typeInfoLoadArray struct { - // fNames [typeInfoLoadArrayLen]string - // encNames [typeInfoLoadArrayLen]string - sfis [typeInfoLoadArraySfisLen]structFieldInfo - sfiidx [typeInfoLoadArraySfiidxLen]byte - etypes [typeInfoLoadArrayEtypesLen]uintptr - b [typeInfoLoadArrayBLen]byte // scratch - used for struct field names -} - -// mirror json.Marshaler and json.Unmarshaler here, -// so we don't import the encoding/json package - -type jsonMarshaler interface { - MarshalJSON() ([]byte, error) -} -type jsonUnmarshaler interface { - UnmarshalJSON([]byte) error -} - -type isZeroer interface { - IsZero() bool -} - -// type byteAccepter func(byte) bool - -var ( - bigen = binary.BigEndian - structInfoFieldName = "_struct" - - mapStrIntfTyp = reflect.TypeOf(map[string]interface{}(nil)) - mapIntfIntfTyp = reflect.TypeOf(map[interface{}]interface{}(nil)) - intfSliceTyp = reflect.TypeOf([]interface{}(nil)) - intfTyp = intfSliceTyp.Elem() - - reflectValTyp = reflect.TypeOf((*reflect.Value)(nil)).Elem() - - stringTyp = reflect.TypeOf("") - timeTyp = reflect.TypeOf(time.Time{}) - rawExtTyp = reflect.TypeOf(RawExt{}) - rawTyp = reflect.TypeOf(Raw{}) - uintptrTyp = reflect.TypeOf(uintptr(0)) - uint8Typ = reflect.TypeOf(uint8(0)) - uint8SliceTyp = reflect.TypeOf([]uint8(nil)) - uintTyp = reflect.TypeOf(uint(0)) - intTyp = reflect.TypeOf(int(0)) - - mapBySliceTyp = reflect.TypeOf((*MapBySlice)(nil)).Elem() - - binaryMarshalerTyp = reflect.TypeOf((*encoding.BinaryMarshaler)(nil)).Elem() - binaryUnmarshalerTyp = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem() - - textMarshalerTyp = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() - textUnmarshalerTyp = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() - - jsonMarshalerTyp = reflect.TypeOf((*jsonMarshaler)(nil)).Elem() - jsonUnmarshalerTyp = reflect.TypeOf((*jsonUnmarshaler)(nil)).Elem() - - selferTyp = reflect.TypeOf((*Selfer)(nil)).Elem() - iszeroTyp = reflect.TypeOf((*isZeroer)(nil)).Elem() - - uint8TypId = rt2id(uint8Typ) - uint8SliceTypId = rt2id(uint8SliceTyp) - rawExtTypId = rt2id(rawExtTyp) - rawTypId = rt2id(rawTyp) - intfTypId = rt2id(intfTyp) - timeTypId = rt2id(timeTyp) - stringTypId = rt2id(stringTyp) - - mapStrIntfTypId = rt2id(mapStrIntfTyp) - mapIntfIntfTypId = rt2id(mapIntfIntfTyp) - intfSliceTypId = rt2id(intfSliceTyp) - // mapBySliceTypId = rt2id(mapBySliceTyp) - - intBitsize = uint8(intTyp.Bits()) - uintBitsize = uint8(uintTyp.Bits()) - - bsAll0x00 = []byte{0, 0, 0, 0, 0, 0, 0, 0} - bsAll0xff = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff} - - chkOvf checkOverflow - - errNoFieldNameToStructFieldInfo = errors.New("no field name passed to parseStructFieldInfo") -) - -var defTypeInfos = NewTypeInfos([]string{"codec", "json"}) - -var immutableKindsSet = [32]bool{ - // reflect.Invalid: , - reflect.Bool: true, - reflect.Int: true, - reflect.Int8: true, - reflect.Int16: true, - reflect.Int32: true, - reflect.Int64: true, - reflect.Uint: true, - reflect.Uint8: true, - reflect.Uint16: true, - reflect.Uint32: true, - reflect.Uint64: true, - reflect.Uintptr: true, - reflect.Float32: true, - reflect.Float64: true, - reflect.Complex64: true, - reflect.Complex128: true, - // reflect.Array - // reflect.Chan - // reflect.Func: true, - // reflect.Interface - // reflect.Map - // reflect.Ptr - // reflect.Slice - reflect.String: true, - // reflect.Struct - // reflect.UnsafePointer -} - -// Selfer defines methods by which a value can encode or decode itself. -// -// Any type which implements Selfer will be able to encode or decode itself. -// Consequently, during (en|de)code, this takes precedence over -// (text|binary)(M|Unm)arshal or extension support. -// -// Note: *the first set of bytes of any value MUST NOT represent nil in the format*. -// This is because, during each decode, we first check the the next set of bytes -// represent nil, and if so, we just set the value to nil. -type Selfer interface { - CodecEncodeSelf(*Encoder) - CodecDecodeSelf(*Decoder) -} - -// MapBySlice is a tag interface that denotes wrapped slice should encode as a map in the stream. -// The slice contains a sequence of key-value pairs. -// This affords storing a map in a specific sequence in the stream. -// -// Example usage: -// type T1 []string // or []int or []Point or any other "slice" type -// func (_ T1) MapBySlice{} // T1 now implements MapBySlice, and will be encoded as a map -// type T2 struct { KeyValues T1 } -// -// var kvs = []string{"one", "1", "two", "2", "three", "3"} -// var v2 = T2{ KeyValues: T1(kvs) } -// // v2 will be encoded like the map: {"KeyValues": {"one": "1", "two": "2", "three": "3"} } -// -// The support of MapBySlice affords the following: -// - A slice type which implements MapBySlice will be encoded as a map -// - A slice can be decoded from a map in the stream -// - It MUST be a slice type (not a pointer receiver) that implements MapBySlice -type MapBySlice interface { - MapBySlice() -} - -// BasicHandle encapsulates the common options and extension functions. -// -// Deprecated: DO NOT USE DIRECTLY. EXPORTED FOR GODOC BENEFIT. WILL BE REMOVED. -type BasicHandle struct { - // BasicHandle is always a part of a different type. - // It doesn't have to fit into it own cache lines. - - // TypeInfos is used to get the type info for any type. - // - // If not configured, the default TypeInfos is used, which uses struct tag keys: codec, json - TypeInfos *TypeInfos - - // Note: BasicHandle is not comparable, due to these slices here (extHandle, intf2impls). - // If *[]T is used instead, this becomes comparable, at the cost of extra indirection. - // Thses slices are used all the time, so keep as slices (not pointers). - - extHandle - - intf2impls - - RPCOptions - - // ---- cache line - - DecodeOptions - - // ---- cache line - - EncodeOptions - - // noBuiltInTypeChecker -} - -func (x *BasicHandle) getBasicHandle() *BasicHandle { - return x -} - -func (x *BasicHandle) getTypeInfo(rtid uintptr, rt reflect.Type) (pti *typeInfo) { - if x.TypeInfos == nil { - return defTypeInfos.get(rtid, rt) - } - return x.TypeInfos.get(rtid, rt) -} - -// Handle is the interface for a specific encoding format. -// -// Typically, a Handle is pre-configured before first time use, -// and not modified while in use. Such a pre-configured Handle -// is safe for concurrent access. -type Handle interface { - Name() string - getBasicHandle() *BasicHandle - recreateEncDriver(encDriver) bool - newEncDriver(w *Encoder) encDriver - newDecDriver(r *Decoder) decDriver - isBinary() bool - hasElemSeparators() bool - // IsBuiltinType(rtid uintptr) bool -} - -// Raw represents raw formatted bytes. -// We "blindly" store it during encode and retrieve the raw bytes during decode. -// Note: it is dangerous during encode, so we may gate the behaviour -// behind an Encode flag which must be explicitly set. -type Raw []byte - -// RawExt represents raw unprocessed extension data. -// Some codecs will decode extension data as a *RawExt -// if there is no registered extension for the tag. -// -// Only one of Data or Value is nil. -// If Data is nil, then the content of the RawExt is in the Value. -type RawExt struct { - Tag uint64 - // Data is the []byte which represents the raw ext. If nil, ext is exposed in Value. - // Data is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of types - Data []byte - // Value represents the extension, if Data is nil. - // Value is used by codecs (e.g. cbor, json) which leverage the format to do - // custom serialization of the types. - Value interface{} -} - -// BytesExt handles custom (de)serialization of types to/from []byte. -// It is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of the types. -type BytesExt interface { - // WriteExt converts a value to a []byte. - // - // Note: v is a pointer iff the registered extension type is a struct or array kind. - WriteExt(v interface{}) []byte - - // ReadExt updates a value from a []byte. - // - // Note: dst is always a pointer kind to the registered extension type. - ReadExt(dst interface{}, src []byte) -} - -// InterfaceExt handles custom (de)serialization of types to/from another interface{} value. -// The Encoder or Decoder will then handle the further (de)serialization of that known type. -// -// It is used by codecs (e.g. cbor, json) which use the format to do custom serialization of types. -type InterfaceExt interface { - // ConvertExt converts a value into a simpler interface for easy encoding - // e.g. convert time.Time to int64. - // - // Note: v is a pointer iff the registered extension type is a struct or array kind. - ConvertExt(v interface{}) interface{} - - // UpdateExt updates a value from a simpler interface for easy decoding - // e.g. convert int64 to time.Time. - // - // Note: dst is always a pointer kind to the registered extension type. - UpdateExt(dst interface{}, src interface{}) -} - -// Ext handles custom (de)serialization of custom types / extensions. -type Ext interface { - BytesExt - InterfaceExt -} - -// addExtWrapper is a wrapper implementation to support former AddExt exported method. -type addExtWrapper struct { - encFn func(reflect.Value) ([]byte, error) - decFn func(reflect.Value, []byte) error -} - -func (x addExtWrapper) WriteExt(v interface{}) []byte { - bs, err := x.encFn(reflect.ValueOf(v)) - if err != nil { - panic(err) - } - return bs -} - -func (x addExtWrapper) ReadExt(v interface{}, bs []byte) { - if err := x.decFn(reflect.ValueOf(v), bs); err != nil { - panic(err) - } -} - -func (x addExtWrapper) ConvertExt(v interface{}) interface{} { - return x.WriteExt(v) -} - -func (x addExtWrapper) UpdateExt(dest interface{}, v interface{}) { - x.ReadExt(dest, v.([]byte)) -} - -type extWrapper struct { - BytesExt - InterfaceExt -} - -type bytesExtFailer struct{} - -func (bytesExtFailer) WriteExt(v interface{}) []byte { - panicv.errorstr("BytesExt.WriteExt is not supported") - return nil -} -func (bytesExtFailer) ReadExt(v interface{}, bs []byte) { - panicv.errorstr("BytesExt.ReadExt is not supported") -} - -type interfaceExtFailer struct{} - -func (interfaceExtFailer) ConvertExt(v interface{}) interface{} { - panicv.errorstr("InterfaceExt.ConvertExt is not supported") - return nil -} -func (interfaceExtFailer) UpdateExt(dest interface{}, v interface{}) { - panicv.errorstr("InterfaceExt.UpdateExt is not supported") -} - -type binaryEncodingType struct{} - -func (binaryEncodingType) isBinary() bool { return true } - -type textEncodingType struct{} - -func (textEncodingType) isBinary() bool { return false } - -// noBuiltInTypes is embedded into many types which do not support builtins -// e.g. msgpack, simple, cbor. - -// type noBuiltInTypeChecker struct{} -// func (noBuiltInTypeChecker) IsBuiltinType(rt uintptr) bool { return false } -// type noBuiltInTypes struct{ noBuiltInTypeChecker } - -type noBuiltInTypes struct{} - -func (noBuiltInTypes) EncodeBuiltin(rt uintptr, v interface{}) {} -func (noBuiltInTypes) DecodeBuiltin(rt uintptr, v interface{}) {} - -// type noStreamingCodec struct{} -// func (noStreamingCodec) CheckBreak() bool { return false } -// func (noStreamingCodec) hasElemSeparators() bool { return false } - -type noElemSeparators struct{} - -func (noElemSeparators) hasElemSeparators() (v bool) { return } -func (noElemSeparators) recreateEncDriver(e encDriver) (v bool) { return } - -// bigenHelper. -// Users must already slice the x completely, because we will not reslice. -type bigenHelper struct { - x []byte // must be correctly sliced to appropriate len. slicing is a cost. - w encWriter -} - -func (z bigenHelper) writeUint16(v uint16) { - bigen.PutUint16(z.x, v) - z.w.writeb(z.x) -} - -func (z bigenHelper) writeUint32(v uint32) { - bigen.PutUint32(z.x, v) - z.w.writeb(z.x) -} - -func (z bigenHelper) writeUint64(v uint64) { - bigen.PutUint64(z.x, v) - z.w.writeb(z.x) -} - -type extTypeTagFn struct { - rtid uintptr - rtidptr uintptr - rt reflect.Type - tag uint64 - ext Ext - _ [1]uint64 // padding -} - -type extHandle []extTypeTagFn - -// AddExt registes an encode and decode function for a reflect.Type. -// To deregister an Ext, call AddExt with nil encfn and/or nil decfn. -// -// Deprecated: Use SetBytesExt or SetInterfaceExt on the Handle instead. -func (o *extHandle) AddExt(rt reflect.Type, tag byte, - encfn func(reflect.Value) ([]byte, error), - decfn func(reflect.Value, []byte) error) (err error) { - if encfn == nil || decfn == nil { - return o.SetExt(rt, uint64(tag), nil) - } - return o.SetExt(rt, uint64(tag), addExtWrapper{encfn, decfn}) -} - -// SetExt will set the extension for a tag and reflect.Type. -// Note that the type must be a named type, and specifically not a pointer or Interface. -// An error is returned if that is not honored. -// To Deregister an ext, call SetExt with nil Ext. -// -// Deprecated: Use SetBytesExt or SetInterfaceExt on the Handle instead. -func (o *extHandle) SetExt(rt reflect.Type, tag uint64, ext Ext) (err error) { - // o is a pointer, because we may need to initialize it - rk := rt.Kind() - for rk == reflect.Ptr { - rt = rt.Elem() - rk = rt.Kind() - } - - if rt.PkgPath() == "" || rk == reflect.Interface { // || rk == reflect.Ptr { - return fmt.Errorf("codec.Handle.SetExt: Takes named type, not a pointer or interface: %v", rt) - } - - rtid := rt2id(rt) - switch rtid { - case timeTypId, rawTypId, rawExtTypId: - // all natively supported type, so cannot have an extension - return // TODO: should we silently ignore, or return an error??? - } - // if o == nil { - // return errors.New("codec.Handle.SetExt: extHandle not initialized") - // } - o2 := *o - // if o2 == nil { - // return errors.New("codec.Handle.SetExt: extHandle not initialized") - // } - for i := range o2 { - v := &o2[i] - if v.rtid == rtid { - v.tag, v.ext = tag, ext - return - } - } - rtidptr := rt2id(reflect.PtrTo(rt)) - *o = append(o2, extTypeTagFn{rtid, rtidptr, rt, tag, ext, [1]uint64{}}) - return -} - -func (o extHandle) getExt(rtid uintptr) (v *extTypeTagFn) { - for i := range o { - v = &o[i] - if v.rtid == rtid || v.rtidptr == rtid { - return - } - } - return nil -} - -func (o extHandle) getExtForTag(tag uint64) (v *extTypeTagFn) { - for i := range o { - v = &o[i] - if v.tag == tag { - return - } - } - return nil -} - -type intf2impl struct { - rtid uintptr // for intf - impl reflect.Type - // _ [1]uint64 // padding // not-needed, as *intf2impl is never returned. -} - -type intf2impls []intf2impl - -// Intf2Impl maps an interface to an implementing type. -// This allows us support infering the concrete type -// and populating it when passed an interface. -// e.g. var v io.Reader can be decoded as a bytes.Buffer, etc. -// -// Passing a nil impl will clear the mapping. -func (o *intf2impls) Intf2Impl(intf, impl reflect.Type) (err error) { - if impl != nil && !impl.Implements(intf) { - return fmt.Errorf("Intf2Impl: %v does not implement %v", impl, intf) - } - rtid := rt2id(intf) - o2 := *o - for i := range o2 { - v := &o2[i] - if v.rtid == rtid { - v.impl = impl - return - } - } - *o = append(o2, intf2impl{rtid, impl}) - return -} - -func (o intf2impls) intf2impl(rtid uintptr) (rv reflect.Value) { - for i := range o { - v := &o[i] - if v.rtid == rtid { - if v.impl == nil { - return - } - if v.impl.Kind() == reflect.Ptr { - return reflect.New(v.impl.Elem()) - } - return reflect.New(v.impl).Elem() - } - } - return -} - -type structFieldInfoFlag uint8 - -const ( - _ structFieldInfoFlag = 1 << iota - structFieldInfoFlagReady - structFieldInfoFlagOmitEmpty -) - -func (x *structFieldInfoFlag) flagSet(f structFieldInfoFlag) { - *x = *x | f -} - -func (x *structFieldInfoFlag) flagClr(f structFieldInfoFlag) { - *x = *x &^ f -} - -func (x structFieldInfoFlag) flagGet(f structFieldInfoFlag) bool { - return x&f != 0 -} - -func (x structFieldInfoFlag) omitEmpty() bool { - return x.flagGet(structFieldInfoFlagOmitEmpty) -} - -func (x structFieldInfoFlag) ready() bool { - return x.flagGet(structFieldInfoFlagReady) -} - -type structFieldInfo struct { - encName string // encode name - fieldName string // field name - - is [maxLevelsEmbedding]uint16 // (recursive/embedded) field index in struct - nis uint8 // num levels of embedding. if 1, then it's not embedded. - structFieldInfoFlag -} - -func (si *structFieldInfo) setToZeroValue(v reflect.Value) { - if v, valid := si.field(v, false); valid { - v.Set(reflect.Zero(v.Type())) - } -} - -// rv returns the field of the struct. -// If anonymous, it returns an Invalid -func (si *structFieldInfo) field(v reflect.Value, update bool) (rv2 reflect.Value, valid bool) { - // replicate FieldByIndex - for i, x := range si.is { - if uint8(i) == si.nis { - break - } - if v, valid = baseStructRv(v, update); !valid { - return - } - v = v.Field(int(x)) - } - - return v, true -} - -// func (si *structFieldInfo) fieldval(v reflect.Value, update bool) reflect.Value { -// v, _ = si.field(v, update) -// return v -// } - -func parseStructInfo(stag string) (toArray, omitEmpty bool, keytype valueType) { - keytype = valueTypeString // default - if stag == "" { - return - } - for i, s := range strings.Split(stag, ",") { - if i == 0 { - } else { - switch s { - case "omitempty": - omitEmpty = true - case "toarray": - toArray = true - case "int": - keytype = valueTypeInt - case "uint": - keytype = valueTypeUint - case "float": - keytype = valueTypeFloat - // case "bool": - // keytype = valueTypeBool - case "string": - keytype = valueTypeString - } - } - } - return -} - -func (si *structFieldInfo) parseTag(stag string) { - // if fname == "" { - // panic(errNoFieldNameToStructFieldInfo) - // } - - if stag == "" { - return - } - for i, s := range strings.Split(stag, ",") { - if i == 0 { - if s != "" { - si.encName = s - } - } else { - switch s { - case "omitempty": - si.flagSet(structFieldInfoFlagOmitEmpty) - // si.omitEmpty = true - // case "toarray": - // si.toArray = true - } - } - } -} - -type sfiSortedByEncName []*structFieldInfo - -func (p sfiSortedByEncName) Len() int { - return len(p) -} - -func (p sfiSortedByEncName) Less(i, j int) bool { - return p[i].encName < p[j].encName -} - -func (p sfiSortedByEncName) Swap(i, j int) { - p[i], p[j] = p[j], p[i] -} - -const structFieldNodeNumToCache = 4 - -type structFieldNodeCache struct { - rv [structFieldNodeNumToCache]reflect.Value - idx [structFieldNodeNumToCache]uint32 - num uint8 -} - -func (x *structFieldNodeCache) get(key uint32) (fv reflect.Value, valid bool) { - for i, k := range &x.idx { - if uint8(i) == x.num { - return // break - } - if key == k { - return x.rv[i], true - } - } - return -} - -func (x *structFieldNodeCache) tryAdd(fv reflect.Value, key uint32) { - if x.num < structFieldNodeNumToCache { - x.rv[x.num] = fv - x.idx[x.num] = key - x.num++ - return - } -} - -type structFieldNode struct { - v reflect.Value - cache2 structFieldNodeCache - cache3 structFieldNodeCache - update bool -} - -func (x *structFieldNode) field(si *structFieldInfo) (fv reflect.Value) { - // return si.fieldval(x.v, x.update) - // Note: we only cache if nis=2 or nis=3 i.e. up to 2 levels of embedding - // This mostly saves us time on the repeated calls to v.Elem, v.Field, etc. - var valid bool - switch si.nis { - case 1: - fv = x.v.Field(int(si.is[0])) - case 2: - if fv, valid = x.cache2.get(uint32(si.is[0])); valid { - fv = fv.Field(int(si.is[1])) - return - } - fv = x.v.Field(int(si.is[0])) - if fv, valid = baseStructRv(fv, x.update); !valid { - return - } - x.cache2.tryAdd(fv, uint32(si.is[0])) - fv = fv.Field(int(si.is[1])) - case 3: - var key uint32 = uint32(si.is[0])<<16 | uint32(si.is[1]) - if fv, valid = x.cache3.get(key); valid { - fv = fv.Field(int(si.is[2])) - return - } - fv = x.v.Field(int(si.is[0])) - if fv, valid = baseStructRv(fv, x.update); !valid { - return - } - fv = fv.Field(int(si.is[1])) - if fv, valid = baseStructRv(fv, x.update); !valid { - return - } - x.cache3.tryAdd(fv, key) - fv = fv.Field(int(si.is[2])) - default: - fv, _ = si.field(x.v, x.update) - } - return -} - -func baseStructRv(v reflect.Value, update bool) (v2 reflect.Value, valid bool) { - for v.Kind() == reflect.Ptr { - if v.IsNil() { - if !update { - return - } - v.Set(reflect.New(v.Type().Elem())) - } - v = v.Elem() - } - return v, true -} - -type typeInfoFlag uint8 - -const ( - typeInfoFlagComparable = 1 << iota - typeInfoFlagIsZeroer - typeInfoFlagIsZeroerPtr -) - -// typeInfo keeps information about each (non-ptr) type referenced in the encode/decode sequence. -// -// During an encode/decode sequence, we work as below: -// - If base is a built in type, en/decode base value -// - If base is registered as an extension, en/decode base value -// - If type is binary(M/Unm)arshaler, call Binary(M/Unm)arshal method -// - If type is text(M/Unm)arshaler, call Text(M/Unm)arshal method -// - Else decode appropriately based on the reflect.Kind -type typeInfo struct { - rt reflect.Type - elem reflect.Type - pkgpath string - - rtid uintptr - // rv0 reflect.Value // saved zero value, used if immutableKind - - numMeth uint16 // number of methods - kind uint8 - chandir uint8 - - anyOmitEmpty bool // true if a struct, and any of the fields are tagged "omitempty" - toArray bool // whether this (struct) type should be encoded as an array - keyType valueType // if struct, how is the field name stored in a stream? default is string - mbs bool // base type (T or *T) is a MapBySlice - - // ---- cpu cache line boundary? - sfiSort []*structFieldInfo // sorted. Used when enc/dec struct to map. - sfiSrc []*structFieldInfo // unsorted. Used when enc/dec struct to array. - - key reflect.Type - - // ---- cpu cache line boundary? - // sfis []structFieldInfo // all sfi, in src order, as created. - sfiNamesSort []byte // all names, with indexes into the sfiSort - - // format of marshal type fields below: [btj][mu]p? OR csp? - - bm bool // T is a binaryMarshaler - bmp bool // *T is a binaryMarshaler - bu bool // T is a binaryUnmarshaler - bup bool // *T is a binaryUnmarshaler - tm bool // T is a textMarshaler - tmp bool // *T is a textMarshaler - tu bool // T is a textUnmarshaler - tup bool // *T is a textUnmarshaler - - jm bool // T is a jsonMarshaler - jmp bool // *T is a jsonMarshaler - ju bool // T is a jsonUnmarshaler - jup bool // *T is a jsonUnmarshaler - cs bool // T is a Selfer - csp bool // *T is a Selfer - - // other flags, with individual bits representing if set. - flags typeInfoFlag - - // _ [2]byte // padding - _ [3]uint64 // padding -} - -func (ti *typeInfo) isFlag(f typeInfoFlag) bool { - return ti.flags&f != 0 -} - -func (ti *typeInfo) indexForEncName(name []byte) (index int16) { - var sn []byte - if len(name)+2 <= 32 { - var buf [32]byte // should not escape - sn = buf[:len(name)+2] - } else { - sn = make([]byte, len(name)+2) - } - copy(sn[1:], name) - sn[0], sn[len(sn)-1] = tiSep2(name), 0xff - j := bytes.Index(ti.sfiNamesSort, sn) - if j < 0 { - return -1 - } - index = int16(uint16(ti.sfiNamesSort[j+len(sn)+1]) | uint16(ti.sfiNamesSort[j+len(sn)])<<8) - return -} - -type rtid2ti struct { - rtid uintptr - ti *typeInfo -} - -// TypeInfos caches typeInfo for each type on first inspection. -// -// It is configured with a set of tag keys, which are used to get -// configuration for the type. -type TypeInfos struct { - // infos: formerly map[uintptr]*typeInfo, now *[]rtid2ti, 2 words expected - infos atomicTypeInfoSlice - mu sync.Mutex - tags []string - _ [2]uint64 // padding -} - -// NewTypeInfos creates a TypeInfos given a set of struct tags keys. -// -// This allows users customize the struct tag keys which contain configuration -// of their types. -func NewTypeInfos(tags []string) *TypeInfos { - return &TypeInfos{tags: tags} -} - -func (x *TypeInfos) structTag(t reflect.StructTag) (s string) { - // check for tags: codec, json, in that order. - // this allows seamless support for many configured structs. - for _, x := range x.tags { - s = t.Get(x) - if s != "" { - return s - } - } - return -} - -func (x *TypeInfos) find(s []rtid2ti, rtid uintptr) (idx int, ti *typeInfo) { - // binary search. adapted from sort/search.go. - // if sp == nil { - // return -1, nil - // } - // s := *sp - h, i, j := 0, 0, len(s) - for i < j { - h = i + (j-i)/2 - if s[h].rtid < rtid { - i = h + 1 - } else { - j = h - } - } - if i < len(s) && s[i].rtid == rtid { - return i, s[i].ti - } - return i, nil -} - -func (x *TypeInfos) get(rtid uintptr, rt reflect.Type) (pti *typeInfo) { - sp := x.infos.load() - var idx int - if sp != nil { - idx, pti = x.find(sp, rtid) - if pti != nil { - return - } - } - - rk := rt.Kind() - - if rk == reflect.Ptr { // || (rk == reflect.Interface && rtid != intfTypId) { - panicv.errorf("invalid kind passed to TypeInfos.get: %v - %v", rk, rt) - } - - // do not hold lock while computing this. - // it may lead to duplication, but that's ok. - ti := typeInfo{rt: rt, rtid: rtid, kind: uint8(rk), pkgpath: rt.PkgPath()} - // ti.rv0 = reflect.Zero(rt) - - // ti.comparable = rt.Comparable() - ti.numMeth = uint16(rt.NumMethod()) - - ti.bm, ti.bmp = implIntf(rt, binaryMarshalerTyp) - ti.bu, ti.bup = implIntf(rt, binaryUnmarshalerTyp) - ti.tm, ti.tmp = implIntf(rt, textMarshalerTyp) - ti.tu, ti.tup = implIntf(rt, textUnmarshalerTyp) - ti.jm, ti.jmp = implIntf(rt, jsonMarshalerTyp) - ti.ju, ti.jup = implIntf(rt, jsonUnmarshalerTyp) - ti.cs, ti.csp = implIntf(rt, selferTyp) - - b1, b2 := implIntf(rt, iszeroTyp) - if b1 { - ti.flags |= typeInfoFlagIsZeroer - } - if b2 { - ti.flags |= typeInfoFlagIsZeroerPtr - } - if rt.Comparable() { - ti.flags |= typeInfoFlagComparable - } - - switch rk { - case reflect.Struct: - var omitEmpty bool - if f, ok := rt.FieldByName(structInfoFieldName); ok { - ti.toArray, omitEmpty, ti.keyType = parseStructInfo(x.structTag(f.Tag)) - } else { - ti.keyType = valueTypeString - } - pp, pi := pool.tiLoad() - pv := pi.(*typeInfoLoadArray) - pv.etypes[0] = ti.rtid - // vv := typeInfoLoad{pv.fNames[:0], pv.encNames[:0], pv.etypes[:1], pv.sfis[:0]} - vv := typeInfoLoad{pv.etypes[:1], pv.sfis[:0]} - x.rget(rt, rtid, omitEmpty, nil, &vv) - // ti.sfis = vv.sfis - ti.sfiSrc, ti.sfiSort, ti.sfiNamesSort, ti.anyOmitEmpty = rgetResolveSFI(rt, vv.sfis, pv) - pp.Put(pi) - case reflect.Map: - ti.elem = rt.Elem() - ti.key = rt.Key() - case reflect.Slice: - ti.mbs, _ = implIntf(rt, mapBySliceTyp) - ti.elem = rt.Elem() - case reflect.Chan: - ti.elem = rt.Elem() - ti.chandir = uint8(rt.ChanDir()) - case reflect.Array, reflect.Ptr: - ti.elem = rt.Elem() - } - // sfi = sfiSrc - - x.mu.Lock() - sp = x.infos.load() - if sp == nil { - pti = &ti - vs := []rtid2ti{{rtid, pti}} - x.infos.store(vs) - } else { - idx, pti = x.find(sp, rtid) - if pti == nil { - pti = &ti - vs := make([]rtid2ti, len(sp)+1) - copy(vs, sp[:idx]) - copy(vs[idx+1:], sp[idx:]) - vs[idx] = rtid2ti{rtid, pti} - x.infos.store(vs) - } - } - x.mu.Unlock() - return -} - -func (x *TypeInfos) rget(rt reflect.Type, rtid uintptr, omitEmpty bool, - indexstack []uint16, pv *typeInfoLoad) { - // Read up fields and store how to access the value. - // - // It uses go's rules for message selectors, - // which say that the field with the shallowest depth is selected. - // - // Note: we consciously use slices, not a map, to simulate a set. - // Typically, types have < 16 fields, - // and iteration using equals is faster than maps there - flen := rt.NumField() - if flen > (1< %v fields are not supported - has %v fields", - (1< maxLevelsEmbedding-1 { - panicv.errorf("codec: only supports up to %v depth of embedding - type has %v depth", - maxLevelsEmbedding-1, len(indexstack)) - } - si.nis = uint8(len(indexstack)) + 1 - copy(si.is[:], indexstack) - si.is[len(indexstack)] = j - - if omitEmpty { - si.flagSet(structFieldInfoFlagOmitEmpty) - } - pv.sfis = append(pv.sfis, si) - } -} - -func tiSep(name string) uint8 { - // (xn[0]%64) // (between 192-255 - outside ascii BMP) - // return 0xfe - (name[0] & 63) - // return 0xfe - (name[0] & 63) - uint8(len(name)) - // return 0xfe - (name[0] & 63) - uint8(len(name)&63) - // return ((0xfe - (name[0] & 63)) & 0xf8) | (uint8(len(name) & 0x07)) - return 0xfe - (name[0] & 63) - uint8(len(name)&63) -} - -func tiSep2(name []byte) uint8 { - return 0xfe - (name[0] & 63) - uint8(len(name)&63) -} - -// resolves the struct field info got from a call to rget. -// Returns a trimmed, unsorted and sorted []*structFieldInfo. -func rgetResolveSFI(rt reflect.Type, x []structFieldInfo, pv *typeInfoLoadArray) ( - y, z []*structFieldInfo, ss []byte, anyOmitEmpty bool) { - sa := pv.sfiidx[:0] - sn := pv.b[:] - n := len(x) - - var xn string - var ui uint16 - var sep byte - - for i := range x { - ui = uint16(i) - xn = x[i].encName // fieldName or encName? use encName for now. - if len(xn)+2 > cap(pv.b) { - sn = make([]byte, len(xn)+2) - } else { - sn = sn[:len(xn)+2] - } - // use a custom sep, so that misses are less frequent, - // since the sep (first char in search) is as unique as first char in field name. - sep = tiSep(xn) - sn[0], sn[len(sn)-1] = sep, 0xff - copy(sn[1:], xn) - j := bytes.Index(sa, sn) - if j == -1 { - sa = append(sa, sep) - sa = append(sa, xn...) - sa = append(sa, 0xff, byte(ui>>8), byte(ui)) - } else { - index := uint16(sa[j+len(sn)+1]) | uint16(sa[j+len(sn)])<<8 - // one of them must be reset to nil, - // and the index updated appropriately to the other one - if x[i].nis == x[index].nis { - } else if x[i].nis < x[index].nis { - sa[j+len(sn)], sa[j+len(sn)+1] = byte(ui>>8), byte(ui) - if x[index].ready() { - x[index].flagClr(structFieldInfoFlagReady) - n-- - } - } else { - if x[i].ready() { - x[i].flagClr(structFieldInfoFlagReady) - n-- - } - } - } - - } - var w []structFieldInfo - sharingArray := len(x) <= typeInfoLoadArraySfisLen // sharing array with typeInfoLoadArray - if sharingArray { - w = make([]structFieldInfo, n) - } - - // remove all the nils (non-ready) - y = make([]*structFieldInfo, n) - n = 0 - var sslen int - for i := range x { - if !x[i].ready() { - continue - } - if !anyOmitEmpty && x[i].omitEmpty() { - anyOmitEmpty = true - } - if sharingArray { - w[n] = x[i] - y[n] = &w[n] - } else { - y[n] = &x[i] - } - sslen = sslen + len(x[i].encName) + 4 - n++ - } - if n != len(y) { - panicv.errorf("failure reading struct %v - expecting %d of %d valid fields, got %d", - rt, len(y), len(x), n) - } - - z = make([]*structFieldInfo, len(y)) - copy(z, y) - sort.Sort(sfiSortedByEncName(z)) - - sharingArray = len(sa) <= typeInfoLoadArraySfiidxLen - if sharingArray { - ss = make([]byte, 0, sslen) - } else { - ss = sa[:0] // reuse the newly made sa array if necessary - } - for i := range z { - xn = z[i].encName - sep = tiSep(xn) - ui = uint16(i) - ss = append(ss, sep) - ss = append(ss, xn...) - ss = append(ss, 0xff, byte(ui>>8), byte(ui)) - } - return -} - -func implIntf(rt, iTyp reflect.Type) (base bool, indir bool) { - return rt.Implements(iTyp), reflect.PtrTo(rt).Implements(iTyp) -} - -// isEmptyStruct is only called from isEmptyValue, and checks if a struct is empty: -// - does it implement IsZero() bool -// - is it comparable, and can i compare directly using == -// - if checkStruct, then walk through the encodable fields -// and check if they are empty or not. -func isEmptyStruct(v reflect.Value, tinfos *TypeInfos, deref, checkStruct bool) bool { - // v is a struct kind - no need to check again. - // We only check isZero on a struct kind, to reduce the amount of times - // that we lookup the rtid and typeInfo for each type as we walk the tree. - - vt := v.Type() - rtid := rt2id(vt) - if tinfos == nil { - tinfos = defTypeInfos - } - ti := tinfos.get(rtid, vt) - if ti.rtid == timeTypId { - return rv2i(v).(time.Time).IsZero() - } - if ti.isFlag(typeInfoFlagIsZeroerPtr) && v.CanAddr() { - return rv2i(v.Addr()).(isZeroer).IsZero() - } - if ti.isFlag(typeInfoFlagIsZeroer) { - return rv2i(v).(isZeroer).IsZero() - } - if ti.isFlag(typeInfoFlagComparable) { - return rv2i(v) == rv2i(reflect.Zero(vt)) - } - if !checkStruct { - return false - } - // We only care about what we can encode/decode, - // so that is what we use to check omitEmpty. - for _, si := range ti.sfiSrc { - sfv, valid := si.field(v, false) - if valid && !isEmptyValue(sfv, tinfos, deref, checkStruct) { - return false - } - } - return true -} - -// func roundFloat(x float64) float64 { -// t := math.Trunc(x) -// if math.Abs(x-t) >= 0.5 { -// return t + math.Copysign(1, x) -// } -// return t -// } - -func panicToErr(h errstrDecorator, err *error) { - // Note: This method MUST be called directly from defer i.e. defer panicToErr ... - // else it seems the recover is not fully handled - if recoverPanicToErr { - if x := recover(); x != nil { - // fmt.Printf("panic'ing with: %v\n", x) - // debug.PrintStack() - panicValToErr(h, x, err) - } - } -} - -func panicValToErr(h errstrDecorator, v interface{}, err *error) { - switch xerr := v.(type) { - case nil: - case error: - switch xerr { - case nil: - case io.EOF, io.ErrUnexpectedEOF, errEncoderNotInitialized, errDecoderNotInitialized: - // treat as special (bubble up) - *err = xerr - default: - h.wrapErrstr(xerr.Error(), err) - } - case string: - if xerr != "" { - h.wrapErrstr(xerr, err) - } - case fmt.Stringer: - if xerr != nil { - h.wrapErrstr(xerr.String(), err) - } - default: - h.wrapErrstr(v, err) - } -} - -func isImmutableKind(k reflect.Kind) (v bool) { - return immutableKindsSet[k] -} - -// ---- - -type codecFnInfo struct { - ti *typeInfo - xfFn Ext - xfTag uint64 - seq seqType - addrD bool - addrF bool // if addrD, this says whether decode function can take a value or a ptr - addrE bool - ready bool // ready to use -} - -// codecFn encapsulates the captured variables and the encode function. -// This way, we only do some calculations one times, and pass to the -// code block that should be called (encapsulated in a function) -// instead of executing the checks every time. -type codecFn struct { - i codecFnInfo - fe func(*Encoder, *codecFnInfo, reflect.Value) - fd func(*Decoder, *codecFnInfo, reflect.Value) - _ [1]uint64 // padding -} - -type codecRtidFn struct { - rtid uintptr - fn *codecFn -} - -type codecFner struct { - // hh Handle - h *BasicHandle - s []codecRtidFn - be bool - js bool - _ [6]byte // padding - _ [3]uint64 // padding -} - -func (c *codecFner) reset(hh Handle) { - bh := hh.getBasicHandle() - // only reset iff extensions changed or *TypeInfos changed - var hhSame = true && - c.h == bh && c.h.TypeInfos == bh.TypeInfos && - len(c.h.extHandle) == len(bh.extHandle) && - (len(c.h.extHandle) == 0 || &c.h.extHandle[0] == &bh.extHandle[0]) - if !hhSame { - // c.hh = hh - c.h, bh = bh, c.h // swap both - _, c.js = hh.(*JsonHandle) - c.be = hh.isBinary() - for i := range c.s { - c.s[i].fn.i.ready = false - } - } -} - -func (c *codecFner) get(rt reflect.Type, checkFastpath, checkCodecSelfer bool) (fn *codecFn) { - rtid := rt2id(rt) - - for _, x := range c.s { - if x.rtid == rtid { - // if rtid exists, then there's a *codenFn attached (non-nil) - fn = x.fn - if fn.i.ready { - return - } - break - } - } - var ti *typeInfo - if fn == nil { - fn = new(codecFn) - if c.s == nil { - c.s = make([]codecRtidFn, 0, 8) - } - c.s = append(c.s, codecRtidFn{rtid, fn}) - } else { - ti = fn.i.ti - *fn = codecFn{} - fn.i.ti = ti - // fn.fe, fn.fd = nil, nil - } - fi := &(fn.i) - fi.ready = true - if ti == nil { - ti = c.h.getTypeInfo(rtid, rt) - fi.ti = ti - } - - rk := reflect.Kind(ti.kind) - - if checkCodecSelfer && (ti.cs || ti.csp) { - fn.fe = (*Encoder).selferMarshal - fn.fd = (*Decoder).selferUnmarshal - fi.addrF = true - fi.addrD = ti.csp - fi.addrE = ti.csp - } else if rtid == timeTypId { - fn.fe = (*Encoder).kTime - fn.fd = (*Decoder).kTime - } else if rtid == rawTypId { - fn.fe = (*Encoder).raw - fn.fd = (*Decoder).raw - } else if rtid == rawExtTypId { - fn.fe = (*Encoder).rawExt - fn.fd = (*Decoder).rawExt - fi.addrF = true - fi.addrD = true - fi.addrE = true - } else if xfFn := c.h.getExt(rtid); xfFn != nil { - fi.xfTag, fi.xfFn = xfFn.tag, xfFn.ext - fn.fe = (*Encoder).ext - fn.fd = (*Decoder).ext - fi.addrF = true - fi.addrD = true - if rk == reflect.Struct || rk == reflect.Array { - fi.addrE = true - } - } else if supportMarshalInterfaces && c.be && (ti.bm || ti.bmp) && (ti.bu || ti.bup) { - fn.fe = (*Encoder).binaryMarshal - fn.fd = (*Decoder).binaryUnmarshal - fi.addrF = true - fi.addrD = ti.bup - fi.addrE = ti.bmp - } else if supportMarshalInterfaces && !c.be && c.js && (ti.jm || ti.jmp) && (ti.ju || ti.jup) { - //If JSON, we should check JSONMarshal before textMarshal - fn.fe = (*Encoder).jsonMarshal - fn.fd = (*Decoder).jsonUnmarshal - fi.addrF = true - fi.addrD = ti.jup - fi.addrE = ti.jmp - } else if supportMarshalInterfaces && !c.be && (ti.tm || ti.tmp) && (ti.tu || ti.tup) { - fn.fe = (*Encoder).textMarshal - fn.fd = (*Decoder).textUnmarshal - fi.addrF = true - fi.addrD = ti.tup - fi.addrE = ti.tmp - } else { - if fastpathEnabled && checkFastpath && (rk == reflect.Map || rk == reflect.Slice) { - if ti.pkgpath == "" { // un-named slice or map - if idx := fastpathAV.index(rtid); idx != -1 { - fn.fe = fastpathAV[idx].encfn - fn.fd = fastpathAV[idx].decfn - fi.addrD = true - fi.addrF = false - } - } else { - // use mapping for underlying type if there - var rtu reflect.Type - if rk == reflect.Map { - rtu = reflect.MapOf(ti.key, ti.elem) - } else { - rtu = reflect.SliceOf(ti.elem) - } - rtuid := rt2id(rtu) - if idx := fastpathAV.index(rtuid); idx != -1 { - xfnf := fastpathAV[idx].encfn - xrt := fastpathAV[idx].rt - fn.fe = func(e *Encoder, xf *codecFnInfo, xrv reflect.Value) { - xfnf(e, xf, xrv.Convert(xrt)) - } - fi.addrD = true - fi.addrF = false // meaning it can be an address(ptr) or a value - xfnf2 := fastpathAV[idx].decfn - fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) { - if xrv.Kind() == reflect.Ptr { - xfnf2(d, xf, xrv.Convert(reflect.PtrTo(xrt))) - } else { - xfnf2(d, xf, xrv.Convert(xrt)) - } - } - } - } - } - if fn.fe == nil && fn.fd == nil { - switch rk { - case reflect.Bool: - fn.fe = (*Encoder).kBool - fn.fd = (*Decoder).kBool - case reflect.String: - fn.fe = (*Encoder).kString - fn.fd = (*Decoder).kString - case reflect.Int: - fn.fd = (*Decoder).kInt - fn.fe = (*Encoder).kInt - case reflect.Int8: - fn.fe = (*Encoder).kInt8 - fn.fd = (*Decoder).kInt8 - case reflect.Int16: - fn.fe = (*Encoder).kInt16 - fn.fd = (*Decoder).kInt16 - case reflect.Int32: - fn.fe = (*Encoder).kInt32 - fn.fd = (*Decoder).kInt32 - case reflect.Int64: - fn.fe = (*Encoder).kInt64 - fn.fd = (*Decoder).kInt64 - case reflect.Uint: - fn.fd = (*Decoder).kUint - fn.fe = (*Encoder).kUint - case reflect.Uint8: - fn.fe = (*Encoder).kUint8 - fn.fd = (*Decoder).kUint8 - case reflect.Uint16: - fn.fe = (*Encoder).kUint16 - fn.fd = (*Decoder).kUint16 - case reflect.Uint32: - fn.fe = (*Encoder).kUint32 - fn.fd = (*Decoder).kUint32 - case reflect.Uint64: - fn.fe = (*Encoder).kUint64 - fn.fd = (*Decoder).kUint64 - case reflect.Uintptr: - fn.fe = (*Encoder).kUintptr - fn.fd = (*Decoder).kUintptr - case reflect.Float32: - fn.fe = (*Encoder).kFloat32 - fn.fd = (*Decoder).kFloat32 - case reflect.Float64: - fn.fe = (*Encoder).kFloat64 - fn.fd = (*Decoder).kFloat64 - case reflect.Invalid: - fn.fe = (*Encoder).kInvalid - fn.fd = (*Decoder).kErr - case reflect.Chan: - fi.seq = seqTypeChan - fn.fe = (*Encoder).kSlice - fn.fd = (*Decoder).kSlice - case reflect.Slice: - fi.seq = seqTypeSlice - fn.fe = (*Encoder).kSlice - fn.fd = (*Decoder).kSlice - case reflect.Array: - fi.seq = seqTypeArray - fn.fe = (*Encoder).kSlice - fi.addrF = false - fi.addrD = false - rt2 := reflect.SliceOf(ti.elem) - fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) { - d.cfer().get(rt2, true, false).fd(d, xf, xrv.Slice(0, xrv.Len())) - } - // fn.fd = (*Decoder).kArray - case reflect.Struct: - if ti.anyOmitEmpty { - fn.fe = (*Encoder).kStruct - } else { - fn.fe = (*Encoder).kStructNoOmitempty - } - fn.fd = (*Decoder).kStruct - case reflect.Map: - fn.fe = (*Encoder).kMap - fn.fd = (*Decoder).kMap - case reflect.Interface: - // encode: reflect.Interface are handled already by preEncodeValue - fn.fd = (*Decoder).kInterface - fn.fe = (*Encoder).kErr - default: - // reflect.Ptr and reflect.Interface are handled already by preEncodeValue - fn.fe = (*Encoder).kErr - fn.fd = (*Decoder).kErr - } - } - } - return -} - -type codecFnPooler struct { - cf *codecFner - cfp *sync.Pool - hh Handle -} - -func (d *codecFnPooler) cfer() *codecFner { - if d.cf == nil { - var v interface{} - d.cfp, v = pool.codecFner() - d.cf = v.(*codecFner) - d.cf.reset(d.hh) - } - return d.cf -} - -func (d *codecFnPooler) alwaysAtEnd() { - if d.cf != nil { - d.cfp.Put(d.cf) - d.cf, d.cfp = nil, nil - } -} - -// ---- - -// these "checkOverflow" functions must be inlinable, and not call anybody. -// Overflow means that the value cannot be represented without wrapping/overflow. -// Overflow=false does not mean that the value can be represented without losing precision -// (especially for floating point). - -type checkOverflow struct{} - -// func (checkOverflow) Float16(f float64) (overflow bool) { -// panicv.errorf("unimplemented") -// if f < 0 { -// f = -f -// } -// return math.MaxFloat32 < f && f <= math.MaxFloat64 -// } - -func (checkOverflow) Float32(v float64) (overflow bool) { - if v < 0 { - v = -v - } - return math.MaxFloat32 < v && v <= math.MaxFloat64 -} -func (checkOverflow) Uint(v uint64, bitsize uint8) (overflow bool) { - if bitsize == 0 || bitsize >= 64 || v == 0 { - return - } - if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc { - overflow = true - } - return -} -func (checkOverflow) Int(v int64, bitsize uint8) (overflow bool) { - if bitsize == 0 || bitsize >= 64 || v == 0 { - return - } - if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc { - overflow = true - } - return -} -func (checkOverflow) SignedInt(v uint64) (overflow bool) { - //e.g. -127 to 128 for int8 - pos := (v >> 63) == 0 - ui2 := v & 0x7fffffffffffffff - if pos { - if ui2 > math.MaxInt64 { - overflow = true - } - } else { - if ui2 > math.MaxInt64-1 { - overflow = true - } - } - return -} - -func (x checkOverflow) Float32V(v float64) float64 { - if x.Float32(v) { - panicv.errorf("float32 overflow: %v", v) - } - return v -} -func (x checkOverflow) UintV(v uint64, bitsize uint8) uint64 { - if x.Uint(v, bitsize) { - panicv.errorf("uint64 overflow: %v", v) - } - return v -} -func (x checkOverflow) IntV(v int64, bitsize uint8) int64 { - if x.Int(v, bitsize) { - panicv.errorf("int64 overflow: %v", v) - } - return v -} -func (x checkOverflow) SignedIntV(v uint64) int64 { - if x.SignedInt(v) { - panicv.errorf("uint64 to int64 overflow: %v", v) - } - return int64(v) -} - -// ------------------ SORT ----------------- - -func isNaN(f float64) bool { return f != f } - -// ----------------------- - -type ioFlusher interface { - Flush() error -} - -type ioPeeker interface { - Peek(int) ([]byte, error) -} - -type ioBuffered interface { - Buffered() int -} - -// ----------------------- - -type intSlice []int64 -type uintSlice []uint64 - -// type uintptrSlice []uintptr -type floatSlice []float64 -type boolSlice []bool -type stringSlice []string - -// type bytesSlice [][]byte - -func (p intSlice) Len() int { return len(p) } -func (p intSlice) Less(i, j int) bool { return p[i] < p[j] } -func (p intSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -func (p uintSlice) Len() int { return len(p) } -func (p uintSlice) Less(i, j int) bool { return p[i] < p[j] } -func (p uintSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -// func (p uintptrSlice) Len() int { return len(p) } -// func (p uintptrSlice) Less(i, j int) bool { return p[i] < p[j] } -// func (p uintptrSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -func (p floatSlice) Len() int { return len(p) } -func (p floatSlice) Less(i, j int) bool { - return p[i] < p[j] || isNaN(p[i]) && !isNaN(p[j]) -} -func (p floatSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -func (p stringSlice) Len() int { return len(p) } -func (p stringSlice) Less(i, j int) bool { return p[i] < p[j] } -func (p stringSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -// func (p bytesSlice) Len() int { return len(p) } -// func (p bytesSlice) Less(i, j int) bool { return bytes.Compare(p[i], p[j]) == -1 } -// func (p bytesSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -func (p boolSlice) Len() int { return len(p) } -func (p boolSlice) Less(i, j int) bool { return !p[i] && p[j] } -func (p boolSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -// --------------------- - -type intRv struct { - v int64 - r reflect.Value -} -type intRvSlice []intRv -type uintRv struct { - v uint64 - r reflect.Value -} -type uintRvSlice []uintRv -type floatRv struct { - v float64 - r reflect.Value -} -type floatRvSlice []floatRv -type boolRv struct { - v bool - r reflect.Value -} -type boolRvSlice []boolRv -type stringRv struct { - v string - r reflect.Value -} -type stringRvSlice []stringRv -type bytesRv struct { - v []byte - r reflect.Value -} -type bytesRvSlice []bytesRv -type timeRv struct { - v time.Time - r reflect.Value -} -type timeRvSlice []timeRv - -func (p intRvSlice) Len() int { return len(p) } -func (p intRvSlice) Less(i, j int) bool { return p[i].v < p[j].v } -func (p intRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -func (p uintRvSlice) Len() int { return len(p) } -func (p uintRvSlice) Less(i, j int) bool { return p[i].v < p[j].v } -func (p uintRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -func (p floatRvSlice) Len() int { return len(p) } -func (p floatRvSlice) Less(i, j int) bool { - return p[i].v < p[j].v || isNaN(p[i].v) && !isNaN(p[j].v) -} -func (p floatRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -func (p stringRvSlice) Len() int { return len(p) } -func (p stringRvSlice) Less(i, j int) bool { return p[i].v < p[j].v } -func (p stringRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -func (p bytesRvSlice) Len() int { return len(p) } -func (p bytesRvSlice) Less(i, j int) bool { return bytes.Compare(p[i].v, p[j].v) == -1 } -func (p bytesRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -func (p boolRvSlice) Len() int { return len(p) } -func (p boolRvSlice) Less(i, j int) bool { return !p[i].v && p[j].v } -func (p boolRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -func (p timeRvSlice) Len() int { return len(p) } -func (p timeRvSlice) Less(i, j int) bool { return p[i].v.Before(p[j].v) } -func (p timeRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -// ----------------- - -type bytesI struct { - v []byte - i interface{} -} - -type bytesISlice []bytesI - -func (p bytesISlice) Len() int { return len(p) } -func (p bytesISlice) Less(i, j int) bool { return bytes.Compare(p[i].v, p[j].v) == -1 } -func (p bytesISlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -// ----------------- - -type set []uintptr - -func (s *set) add(v uintptr) (exists bool) { - // e.ci is always nil, or len >= 1 - x := *s - if x == nil { - x = make([]uintptr, 1, 8) - x[0] = v - *s = x - return - } - // typically, length will be 1. make this perform. - if len(x) == 1 { - if j := x[0]; j == 0 { - x[0] = v - } else if j == v { - exists = true - } else { - x = append(x, v) - *s = x - } - return - } - // check if it exists - for _, j := range x { - if j == v { - exists = true - return - } - } - // try to replace a "deleted" slot - for i, j := range x { - if j == 0 { - x[i] = v - return - } - } - // if unable to replace deleted slot, just append it. - x = append(x, v) - *s = x - return -} - -func (s *set) remove(v uintptr) (exists bool) { - x := *s - if len(x) == 0 { - return - } - if len(x) == 1 { - if x[0] == v { - x[0] = 0 - } - return - } - for i, j := range x { - if j == v { - exists = true - x[i] = 0 // set it to 0, as way to delete it. - // copy(x[i:], x[i+1:]) - // x = x[:len(x)-1] - return - } - } - return -} - -// ------ - -// bitset types are better than [256]bool, because they permit the whole -// bitset array being on a single cache line and use less memory. - -// given x > 0 and n > 0 and x is exactly 2^n, then pos/x === pos>>n AND pos%x === pos&(x-1). -// consequently, pos/32 === pos>>5, pos/16 === pos>>4, pos/8 === pos>>3, pos%8 == pos&7 - -type bitset256 [32]byte - -func (x *bitset256) isset(pos byte) bool { - return x[pos>>3]&(1<<(pos&7)) != 0 -} -func (x *bitset256) issetv(pos byte) byte { - return x[pos>>3] & (1 << (pos & 7)) -} -func (x *bitset256) set(pos byte) { - x[pos>>3] |= (1 << (pos & 7)) -} - -// func (x *bitset256) unset(pos byte) { -// x[pos>>3] &^= (1 << (pos & 7)) -// } - -type bitset128 [16]byte - -func (x *bitset128) isset(pos byte) bool { - return x[pos>>3]&(1<<(pos&7)) != 0 -} -func (x *bitset128) set(pos byte) { - x[pos>>3] |= (1 << (pos & 7)) -} - -// func (x *bitset128) unset(pos byte) { -// x[pos>>3] &^= (1 << (pos & 7)) -// } - -type bitset32 [4]byte - -func (x *bitset32) isset(pos byte) bool { - return x[pos>>3]&(1<<(pos&7)) != 0 -} -func (x *bitset32) set(pos byte) { - x[pos>>3] |= (1 << (pos & 7)) -} - -// func (x *bitset32) unset(pos byte) { -// x[pos>>3] &^= (1 << (pos & 7)) -// } - -// type bit2set256 [64]byte - -// func (x *bit2set256) set(pos byte, v1, v2 bool) { -// var pos2 uint8 = (pos & 3) << 1 // returning 0, 2, 4 or 6 -// if v1 { -// x[pos>>2] |= 1 << (pos2 + 1) -// } -// if v2 { -// x[pos>>2] |= 1 << pos2 -// } -// } -// func (x *bit2set256) get(pos byte) uint8 { -// var pos2 uint8 = (pos & 3) << 1 // returning 0, 2, 4 or 6 -// return x[pos>>2] << (6 - pos2) >> 6 // 11000000 -> 00000011 -// } - -// ------------ - -type pooler struct { - dn sync.Pool // for decNaked - cfn sync.Pool // for codecFner - tiload sync.Pool - strRv8, strRv16, strRv32, strRv64, strRv128 sync.Pool // for stringRV -} - -func (p *pooler) init() { - p.strRv8.New = func() interface{} { return new([8]stringRv) } - p.strRv16.New = func() interface{} { return new([16]stringRv) } - p.strRv32.New = func() interface{} { return new([32]stringRv) } - p.strRv64.New = func() interface{} { return new([64]stringRv) } - p.strRv128.New = func() interface{} { return new([128]stringRv) } - p.dn.New = func() interface{} { x := new(decNaked); x.init(); return x } - p.tiload.New = func() interface{} { return new(typeInfoLoadArray) } - p.cfn.New = func() interface{} { return new(codecFner) } -} - -func (p *pooler) stringRv8() (sp *sync.Pool, v interface{}) { - return &p.strRv8, p.strRv8.Get() -} -func (p *pooler) stringRv16() (sp *sync.Pool, v interface{}) { - return &p.strRv16, p.strRv16.Get() -} -func (p *pooler) stringRv32() (sp *sync.Pool, v interface{}) { - return &p.strRv32, p.strRv32.Get() -} -func (p *pooler) stringRv64() (sp *sync.Pool, v interface{}) { - return &p.strRv64, p.strRv64.Get() -} -func (p *pooler) stringRv128() (sp *sync.Pool, v interface{}) { - return &p.strRv128, p.strRv128.Get() -} -func (p *pooler) decNaked() (sp *sync.Pool, v interface{}) { - return &p.dn, p.dn.Get() -} -func (p *pooler) codecFner() (sp *sync.Pool, v interface{}) { - return &p.cfn, p.cfn.Get() -} -func (p *pooler) tiLoad() (sp *sync.Pool, v interface{}) { - return &p.tiload, p.tiload.Get() -} - -// func (p *pooler) decNaked() (v *decNaked, f func(*decNaked) ) { -// sp := &(p.dn) -// vv := sp.Get() -// return vv.(*decNaked), func(x *decNaked) { sp.Put(vv) } -// } -// func (p *pooler) decNakedGet() (v interface{}) { -// return p.dn.Get() -// } -// func (p *pooler) codecFnerGet() (v interface{}) { -// return p.cfn.Get() -// } -// func (p *pooler) tiLoadGet() (v interface{}) { -// return p.tiload.Get() -// } -// func (p *pooler) decNakedPut(v interface{}) { -// p.dn.Put(v) -// } -// func (p *pooler) codecFnerPut(v interface{}) { -// p.cfn.Put(v) -// } -// func (p *pooler) tiLoadPut(v interface{}) { -// p.tiload.Put(v) -// } - -type panicHdl struct{} - -func (panicHdl) errorv(err error) { - if err != nil { - panic(err) - } -} - -func (panicHdl) errorstr(message string) { - if message != "" { - panic(message) - } -} - -func (panicHdl) errorf(format string, params ...interface{}) { - if format != "" { - if len(params) == 0 { - panic(format) - } else { - panic(fmt.Sprintf(format, params...)) - } - } -} - -type errstrDecorator interface { - wrapErrstr(interface{}, *error) -} - -type errstrDecoratorDef struct{} - -func (errstrDecoratorDef) wrapErrstr(v interface{}, e *error) { *e = fmt.Errorf("%v", v) } - -type must struct{} - -func (must) String(s string, err error) string { - if err != nil { - panicv.errorv(err) - } - return s -} -func (must) Int(s int64, err error) int64 { - if err != nil { - panicv.errorv(err) - } - return s -} -func (must) Uint(s uint64, err error) uint64 { - if err != nil { - panicv.errorv(err) - } - return s -} -func (must) Float(s float64, err error) float64 { - if err != nil { - panicv.errorv(err) - } - return s -} - -// xdebugf prints the message in red on the terminal. -// Use it in place of fmt.Printf (which it calls internally) -func xdebugf(pattern string, args ...interface{}) { - var delim string - if len(pattern) > 0 && pattern[len(pattern)-1] != '\n' { - delim = "\n" - } - fmt.Printf("\033[1;31m"+pattern+delim+"\033[0m", args...) -} - -// func isImmutableKind(k reflect.Kind) (v bool) { -// return false || -// k == reflect.Int || -// k == reflect.Int8 || -// k == reflect.Int16 || -// k == reflect.Int32 || -// k == reflect.Int64 || -// k == reflect.Uint || -// k == reflect.Uint8 || -// k == reflect.Uint16 || -// k == reflect.Uint32 || -// k == reflect.Uint64 || -// k == reflect.Uintptr || -// k == reflect.Float32 || -// k == reflect.Float64 || -// k == reflect.Bool || -// k == reflect.String -// } - -// func timeLocUTCName(tzint int16) string { -// if tzint == 0 { -// return "UTC" -// } -// var tzname = []byte("UTC+00:00") -// //tzname := fmt.Sprintf("UTC%s%02d:%02d", tzsign, tz/60, tz%60) //perf issue using Sprintf. inline below. -// //tzhr, tzmin := tz/60, tz%60 //faster if u convert to int first -// var tzhr, tzmin int16 -// if tzint < 0 { -// tzname[3] = '-' // (TODO: verify. this works here) -// tzhr, tzmin = -tzint/60, (-tzint)%60 -// } else { -// tzhr, tzmin = tzint/60, tzint%60 -// } -// tzname[4] = timeDigits[tzhr/10] -// tzname[5] = timeDigits[tzhr%10] -// tzname[7] = timeDigits[tzmin/10] -// tzname[8] = timeDigits[tzmin%10] -// return string(tzname) -// //return time.FixedZone(string(tzname), int(tzint)*60) -// } diff --git a/vendor/github.com/ugorji/go/codec/helper_internal.go b/vendor/github.com/ugorji/go/codec/helper_internal.go deleted file mode 100644 index 0cbd665e2..000000000 --- a/vendor/github.com/ugorji/go/codec/helper_internal.go +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -// All non-std package dependencies live in this file, -// so porting to different environment is easy (just update functions). - -func pruneSignExt(v []byte, pos bool) (n int) { - if len(v) < 2 { - } else if pos && v[0] == 0 { - for ; v[n] == 0 && n+1 < len(v) && (v[n+1]&(1<<7) == 0); n++ { - } - } else if !pos && v[0] == 0xff { - for ; v[n] == 0xff && n+1 < len(v) && (v[n+1]&(1<<7) != 0); n++ { - } - } - return -} - -// validate that this function is correct ... -// culled from OGRE (Object-Oriented Graphics Rendering Engine) -// function: halfToFloatI (http://stderr.org/doc/ogre-doc/api/OgreBitwise_8h-source.html) -func halfFloatToFloatBits(yy uint16) (d uint32) { - y := uint32(yy) - s := (y >> 15) & 0x01 - e := (y >> 10) & 0x1f - m := y & 0x03ff - - if e == 0 { - if m == 0 { // plu or minus 0 - return s << 31 - } - // Denormalized number -- renormalize it - for (m & 0x00000400) == 0 { - m <<= 1 - e -= 1 - } - e += 1 - const zz uint32 = 0x0400 - m &= ^zz - } else if e == 31 { - if m == 0 { // Inf - return (s << 31) | 0x7f800000 - } - return (s << 31) | 0x7f800000 | (m << 13) // NaN - } - e = e + (127 - 15) - m = m << 13 - return (s << 31) | (e << 23) | m -} - -// GrowCap will return a new capacity for a slice, given the following: -// - oldCap: current capacity -// - unit: in-memory size of an element -// - num: number of elements to add -func growCap(oldCap, unit, num int) (newCap int) { - // appendslice logic (if cap < 1024, *2, else *1.25): - // leads to many copy calls, especially when copying bytes. - // bytes.Buffer model (2*cap + n): much better for bytes. - // smarter way is to take the byte-size of the appended element(type) into account - - // maintain 3 thresholds: - // t1: if cap <= t1, newcap = 2x - // t2: if cap <= t2, newcap = 1.75x - // t3: if cap <= t3, newcap = 1.5x - // else newcap = 1.25x - // - // t1, t2, t3 >= 1024 always. - // i.e. if unit size >= 16, then always do 2x or 1.25x (ie t1, t2, t3 are all same) - // - // With this, appending for bytes increase by: - // 100% up to 4K - // 75% up to 8K - // 50% up to 16K - // 25% beyond that - - // unit can be 0 e.g. for struct{}{}; handle that appropriately - var t1, t2, t3 int // thresholds - if unit <= 1 { - t1, t2, t3 = 4*1024, 8*1024, 16*1024 - } else if unit < 16 { - t3 = 16 / unit * 1024 - t1 = t3 * 1 / 4 - t2 = t3 * 2 / 4 - } else { - t1, t2, t3 = 1024, 1024, 1024 - } - - var x int // temporary variable - - // x is multiplier here: one of 5, 6, 7 or 8; incr of 25%, 50%, 75% or 100% respectively - if oldCap <= t1 { // [0,t1] - x = 8 - } else if oldCap > t3 { // (t3,infinity] - x = 5 - } else if oldCap <= t2 { // (t1,t2] - x = 7 - } else { // (t2,t3] - x = 6 - } - newCap = x * oldCap / 4 - - if num > 0 { - newCap += num - } - - // ensure newCap is a multiple of 64 (if it is > 64) or 16. - if newCap > 64 { - if x = newCap % 64; x != 0 { - x = newCap / 64 - newCap = 64 * (x + 1) - } - } else { - if x = newCap % 16; x != 0 { - x = newCap / 16 - newCap = 16 * (x + 1) - } - } - return -} diff --git a/vendor/github.com/ugorji/go/codec/helper_not_unsafe.go b/vendor/github.com/ugorji/go/codec/helper_not_unsafe.go deleted file mode 100644 index fd52690c9..000000000 --- a/vendor/github.com/ugorji/go/codec/helper_not_unsafe.go +++ /dev/null @@ -1,272 +0,0 @@ -// +build !go1.7 safe appengine - -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -import ( - "reflect" - "sync/atomic" - "time" -) - -const safeMode = true - -// stringView returns a view of the []byte as a string. -// In unsafe mode, it doesn't incur allocation and copying caused by conversion. -// In regular safe mode, it is an allocation and copy. -// -// Usage: Always maintain a reference to v while result of this call is in use, -// and call keepAlive4BytesView(v) at point where done with view. -func stringView(v []byte) string { - return string(v) -} - -// bytesView returns a view of the string as a []byte. -// In unsafe mode, it doesn't incur allocation and copying caused by conversion. -// In regular safe mode, it is an allocation and copy. -// -// Usage: Always maintain a reference to v while result of this call is in use, -// and call keepAlive4BytesView(v) at point where done with view. -func bytesView(v string) []byte { - return []byte(v) -} - -func definitelyNil(v interface{}) bool { - // this is a best-effort option. - // We just return false, so we don't unnecessarily incur the cost of reflection this early. - return false -} - -func rv2i(rv reflect.Value) interface{} { - return rv.Interface() -} - -func rt2id(rt reflect.Type) uintptr { - return reflect.ValueOf(rt).Pointer() -} - -func rv2rtid(rv reflect.Value) uintptr { - return reflect.ValueOf(rv.Type()).Pointer() -} - -func i2rtid(i interface{}) uintptr { - return reflect.ValueOf(reflect.TypeOf(i)).Pointer() -} - -// -------------------------- - -func isEmptyValue(v reflect.Value, tinfos *TypeInfos, deref, checkStruct bool) bool { - switch v.Kind() { - case reflect.Invalid: - return true - case reflect.Array, reflect.Map, reflect.Slice, reflect.String: - return v.Len() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Interface, reflect.Ptr: - if deref { - if v.IsNil() { - return true - } - return isEmptyValue(v.Elem(), tinfos, deref, checkStruct) - } - return v.IsNil() - case reflect.Struct: - return isEmptyStruct(v, tinfos, deref, checkStruct) - } - return false -} - -// -------------------------- -// type ptrToRvMap struct{} - -// func (*ptrToRvMap) init() {} -// func (*ptrToRvMap) get(i interface{}) reflect.Value { -// return reflect.ValueOf(i).Elem() -// } - -// -------------------------- -type atomicTypeInfoSlice struct { // expected to be 2 words - v atomic.Value -} - -func (x *atomicTypeInfoSlice) load() []rtid2ti { - i := x.v.Load() - if i == nil { - return nil - } - return i.([]rtid2ti) -} - -func (x *atomicTypeInfoSlice) store(p []rtid2ti) { - x.v.Store(p) -} - -// -------------------------- -func (d *Decoder) raw(f *codecFnInfo, rv reflect.Value) { - rv.SetBytes(d.rawBytes()) -} - -func (d *Decoder) kString(f *codecFnInfo, rv reflect.Value) { - rv.SetString(d.d.DecodeString()) -} - -func (d *Decoder) kBool(f *codecFnInfo, rv reflect.Value) { - rv.SetBool(d.d.DecodeBool()) -} - -func (d *Decoder) kTime(f *codecFnInfo, rv reflect.Value) { - rv.Set(reflect.ValueOf(d.d.DecodeTime())) -} - -func (d *Decoder) kFloat32(f *codecFnInfo, rv reflect.Value) { - fv := d.d.DecodeFloat64() - if chkOvf.Float32(fv) { - d.errorf("float32 overflow: %v", fv) - } - rv.SetFloat(fv) -} - -func (d *Decoder) kFloat64(f *codecFnInfo, rv reflect.Value) { - rv.SetFloat(d.d.DecodeFloat64()) -} - -func (d *Decoder) kInt(f *codecFnInfo, rv reflect.Value) { - rv.SetInt(chkOvf.IntV(d.d.DecodeInt64(), intBitsize)) -} - -func (d *Decoder) kInt8(f *codecFnInfo, rv reflect.Value) { - rv.SetInt(chkOvf.IntV(d.d.DecodeInt64(), 8)) -} - -func (d *Decoder) kInt16(f *codecFnInfo, rv reflect.Value) { - rv.SetInt(chkOvf.IntV(d.d.DecodeInt64(), 16)) -} - -func (d *Decoder) kInt32(f *codecFnInfo, rv reflect.Value) { - rv.SetInt(chkOvf.IntV(d.d.DecodeInt64(), 32)) -} - -func (d *Decoder) kInt64(f *codecFnInfo, rv reflect.Value) { - rv.SetInt(d.d.DecodeInt64()) -} - -func (d *Decoder) kUint(f *codecFnInfo, rv reflect.Value) { - rv.SetUint(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize)) -} - -func (d *Decoder) kUintptr(f *codecFnInfo, rv reflect.Value) { - rv.SetUint(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize)) -} - -func (d *Decoder) kUint8(f *codecFnInfo, rv reflect.Value) { - rv.SetUint(chkOvf.UintV(d.d.DecodeUint64(), 8)) -} - -func (d *Decoder) kUint16(f *codecFnInfo, rv reflect.Value) { - rv.SetUint(chkOvf.UintV(d.d.DecodeUint64(), 16)) -} - -func (d *Decoder) kUint32(f *codecFnInfo, rv reflect.Value) { - rv.SetUint(chkOvf.UintV(d.d.DecodeUint64(), 32)) -} - -func (d *Decoder) kUint64(f *codecFnInfo, rv reflect.Value) { - rv.SetUint(d.d.DecodeUint64()) -} - -// ---------------- - -func (e *Encoder) kBool(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeBool(rv.Bool()) -} - -func (e *Encoder) kTime(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeTime(rv2i(rv).(time.Time)) -} - -func (e *Encoder) kString(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeString(cUTF8, rv.String()) -} - -func (e *Encoder) kFloat64(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeFloat64(rv.Float()) -} - -func (e *Encoder) kFloat32(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeFloat32(float32(rv.Float())) -} - -func (e *Encoder) kInt(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeInt(rv.Int()) -} - -func (e *Encoder) kInt8(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeInt(rv.Int()) -} - -func (e *Encoder) kInt16(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeInt(rv.Int()) -} - -func (e *Encoder) kInt32(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeInt(rv.Int()) -} - -func (e *Encoder) kInt64(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeInt(rv.Int()) -} - -func (e *Encoder) kUint(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeUint(rv.Uint()) -} - -func (e *Encoder) kUint8(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeUint(rv.Uint()) -} - -func (e *Encoder) kUint16(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeUint(rv.Uint()) -} - -func (e *Encoder) kUint32(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeUint(rv.Uint()) -} - -func (e *Encoder) kUint64(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeUint(rv.Uint()) -} - -func (e *Encoder) kUintptr(f *codecFnInfo, rv reflect.Value) { - e.e.EncodeUint(rv.Uint()) -} - -// // keepAlive4BytesView maintains a reference to the input parameter for bytesView. -// // -// // Usage: call this at point where done with the bytes view. -// func keepAlive4BytesView(v string) {} - -// // keepAlive4BytesView maintains a reference to the input parameter for stringView. -// // -// // Usage: call this at point where done with the string view. -// func keepAlive4StringView(v []byte) {} - -// func definitelyNil(v interface{}) bool { -// rv := reflect.ValueOf(v) -// switch rv.Kind() { -// case reflect.Invalid: -// return true -// case reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Slice, reflect.Map, reflect.Func: -// return rv.IsNil() -// default: -// return false -// } -// } diff --git a/vendor/github.com/ugorji/go/codec/helper_unsafe.go b/vendor/github.com/ugorji/go/codec/helper_unsafe.go deleted file mode 100644 index e3df60abe..000000000 --- a/vendor/github.com/ugorji/go/codec/helper_unsafe.go +++ /dev/null @@ -1,639 +0,0 @@ -// +build !safe -// +build !appengine -// +build go1.7 - -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -import ( - "reflect" - "sync/atomic" - "time" - "unsafe" -) - -// This file has unsafe variants of some helper methods. -// NOTE: See helper_not_unsafe.go for the usage information. - -// var zeroRTv [4]uintptr - -const safeMode = false -const unsafeFlagIndir = 1 << 7 // keep in sync with GO_ROOT/src/reflect/value.go - -type unsafeString struct { - Data unsafe.Pointer - Len int -} - -type unsafeSlice struct { - Data unsafe.Pointer - Len int - Cap int -} - -type unsafeIntf struct { - typ unsafe.Pointer - word unsafe.Pointer -} - -type unsafeReflectValue struct { - typ unsafe.Pointer - ptr unsafe.Pointer - flag uintptr -} - -func stringView(v []byte) string { - if len(v) == 0 { - return "" - } - bx := (*unsafeSlice)(unsafe.Pointer(&v)) - return *(*string)(unsafe.Pointer(&unsafeString{bx.Data, bx.Len})) -} - -func bytesView(v string) []byte { - if len(v) == 0 { - return zeroByteSlice - } - sx := (*unsafeString)(unsafe.Pointer(&v)) - return *(*[]byte)(unsafe.Pointer(&unsafeSlice{sx.Data, sx.Len, sx.Len})) -} - -func definitelyNil(v interface{}) bool { - // There is no global way of checking if an interface is nil. - // For true references (map, ptr, func, chan), you can just look - // at the word of the interface. However, for slices, you have to dereference - // the word, and get a pointer to the 3-word interface value. - // - // However, the following are cheap calls - // - TypeOf(interface): cheap 2-line call. - // - ValueOf(interface{}): expensive - // - type.Kind: cheap call through an interface - // - Value.Type(): cheap call - // except it's a method value (e.g. r.Read, which implies that it is a Func) - - return ((*unsafeIntf)(unsafe.Pointer(&v))).word == nil -} - -func rv2i(rv reflect.Value) interface{} { - // TODO: consider a more generally-known optimization for reflect.Value ==> Interface - // - // Currently, we use this fragile method that taps into implememtation details from - // the source go stdlib reflect/value.go, and trims the implementation. - - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - // true references (map, func, chan, ptr - NOT slice) may be double-referenced as flagIndir - var ptr unsafe.Pointer - if refBitset.isset(byte(urv.flag&(1<<5-1))) && urv.flag&unsafeFlagIndir != 0 { - ptr = *(*unsafe.Pointer)(urv.ptr) - } else { - ptr = urv.ptr - } - return *(*interface{})(unsafe.Pointer(&unsafeIntf{typ: urv.typ, word: ptr})) -} - -func rt2id(rt reflect.Type) uintptr { - return uintptr(((*unsafeIntf)(unsafe.Pointer(&rt))).word) -} - -func rv2rtid(rv reflect.Value) uintptr { - return uintptr((*unsafeReflectValue)(unsafe.Pointer(&rv)).typ) -} - -func i2rtid(i interface{}) uintptr { - return uintptr(((*unsafeIntf)(unsafe.Pointer(&i))).typ) -} - -// -------------------------- - -func isEmptyValue(v reflect.Value, tinfos *TypeInfos, deref, checkStruct bool) bool { - urv := (*unsafeReflectValue)(unsafe.Pointer(&v)) - if urv.flag == 0 { - return true - } - switch v.Kind() { - case reflect.Invalid: - return true - case reflect.String: - return (*unsafeString)(urv.ptr).Len == 0 - case reflect.Slice: - return (*unsafeSlice)(urv.ptr).Len == 0 - case reflect.Bool: - return !*(*bool)(urv.ptr) - case reflect.Int: - return *(*int)(urv.ptr) == 0 - case reflect.Int8: - return *(*int8)(urv.ptr) == 0 - case reflect.Int16: - return *(*int16)(urv.ptr) == 0 - case reflect.Int32: - return *(*int32)(urv.ptr) == 0 - case reflect.Int64: - return *(*int64)(urv.ptr) == 0 - case reflect.Uint: - return *(*uint)(urv.ptr) == 0 - case reflect.Uint8: - return *(*uint8)(urv.ptr) == 0 - case reflect.Uint16: - return *(*uint16)(urv.ptr) == 0 - case reflect.Uint32: - return *(*uint32)(urv.ptr) == 0 - case reflect.Uint64: - return *(*uint64)(urv.ptr) == 0 - case reflect.Uintptr: - return *(*uintptr)(urv.ptr) == 0 - case reflect.Float32: - return *(*float32)(urv.ptr) == 0 - case reflect.Float64: - return *(*float64)(urv.ptr) == 0 - case reflect.Interface: - isnil := urv.ptr == nil || *(*unsafe.Pointer)(urv.ptr) == nil - if deref { - if isnil { - return true - } - return isEmptyValue(v.Elem(), tinfos, deref, checkStruct) - } - return isnil - case reflect.Ptr: - // isnil := urv.ptr == nil (not sufficient, as a pointer value encodes the type) - isnil := urv.ptr == nil || *(*unsafe.Pointer)(urv.ptr) == nil - if deref { - if isnil { - return true - } - return isEmptyValue(v.Elem(), tinfos, deref, checkStruct) - } - return isnil - case reflect.Struct: - return isEmptyStruct(v, tinfos, deref, checkStruct) - case reflect.Map, reflect.Array, reflect.Chan: - return v.Len() == 0 - } - return false -} - -// -------------------------- - -// atomicTypeInfoSlice contains length and pointer to the array for a slice. -// It is expected to be 2 words. -// -// Previously, we atomically loaded and stored the length and array pointer separately, -// which could lead to some races. -// We now just atomically store and load the pointer to the value directly. - -type atomicTypeInfoSlice struct { // expected to be 2 words - l int // length of the data array (must be first in struct, for 64-bit alignment necessary for 386) - v unsafe.Pointer // data array - Pointer (not uintptr) to maintain GC reference -} - -func (x *atomicTypeInfoSlice) load() []rtid2ti { - xp := unsafe.Pointer(x) - x2 := *(*atomicTypeInfoSlice)(atomic.LoadPointer(&xp)) - if x2.l == 0 { - return nil - } - return *(*[]rtid2ti)(unsafe.Pointer(&unsafeSlice{Data: x2.v, Len: x2.l, Cap: x2.l})) -} - -func (x *atomicTypeInfoSlice) store(p []rtid2ti) { - s := (*unsafeSlice)(unsafe.Pointer(&p)) - xp := unsafe.Pointer(x) - atomic.StorePointer(&xp, unsafe.Pointer(&atomicTypeInfoSlice{l: s.Len, v: s.Data})) -} - -// -------------------------- -func (d *Decoder) raw(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*[]byte)(urv.ptr) = d.rawBytes() -} - -func (d *Decoder) kString(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*string)(urv.ptr) = d.d.DecodeString() -} - -func (d *Decoder) kBool(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*bool)(urv.ptr) = d.d.DecodeBool() -} - -func (d *Decoder) kTime(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*time.Time)(urv.ptr) = d.d.DecodeTime() -} - -func (d *Decoder) kFloat32(f *codecFnInfo, rv reflect.Value) { - fv := d.d.DecodeFloat64() - if chkOvf.Float32(fv) { - d.errorf("float32 overflow: %v", fv) - } - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*float32)(urv.ptr) = float32(fv) -} - -func (d *Decoder) kFloat64(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*float64)(urv.ptr) = d.d.DecodeFloat64() -} - -func (d *Decoder) kInt(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*int)(urv.ptr) = int(chkOvf.IntV(d.d.DecodeInt64(), intBitsize)) -} - -func (d *Decoder) kInt8(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*int8)(urv.ptr) = int8(chkOvf.IntV(d.d.DecodeInt64(), 8)) -} - -func (d *Decoder) kInt16(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*int16)(urv.ptr) = int16(chkOvf.IntV(d.d.DecodeInt64(), 16)) -} - -func (d *Decoder) kInt32(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*int32)(urv.ptr) = int32(chkOvf.IntV(d.d.DecodeInt64(), 32)) -} - -func (d *Decoder) kInt64(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*int64)(urv.ptr) = d.d.DecodeInt64() -} - -func (d *Decoder) kUint(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*uint)(urv.ptr) = uint(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize)) -} - -func (d *Decoder) kUintptr(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*uintptr)(urv.ptr) = uintptr(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize)) -} - -func (d *Decoder) kUint8(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*uint8)(urv.ptr) = uint8(chkOvf.UintV(d.d.DecodeUint64(), 8)) -} - -func (d *Decoder) kUint16(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*uint16)(urv.ptr) = uint16(chkOvf.UintV(d.d.DecodeUint64(), 16)) -} - -func (d *Decoder) kUint32(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*uint32)(urv.ptr) = uint32(chkOvf.UintV(d.d.DecodeUint64(), 32)) -} - -func (d *Decoder) kUint64(f *codecFnInfo, rv reflect.Value) { - urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - *(*uint64)(urv.ptr) = d.d.DecodeUint64() -} - -// ------------ - -func (e *Encoder) kBool(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeBool(*(*bool)(v.ptr)) -} - -func (e *Encoder) kTime(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeTime(*(*time.Time)(v.ptr)) -} - -func (e *Encoder) kString(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeString(cUTF8, *(*string)(v.ptr)) -} - -func (e *Encoder) kFloat64(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeFloat64(*(*float64)(v.ptr)) -} - -func (e *Encoder) kFloat32(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeFloat32(*(*float32)(v.ptr)) -} - -func (e *Encoder) kInt(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeInt(int64(*(*int)(v.ptr))) -} - -func (e *Encoder) kInt8(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeInt(int64(*(*int8)(v.ptr))) -} - -func (e *Encoder) kInt16(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeInt(int64(*(*int16)(v.ptr))) -} - -func (e *Encoder) kInt32(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeInt(int64(*(*int32)(v.ptr))) -} - -func (e *Encoder) kInt64(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeInt(int64(*(*int64)(v.ptr))) -} - -func (e *Encoder) kUint(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeUint(uint64(*(*uint)(v.ptr))) -} - -func (e *Encoder) kUint8(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeUint(uint64(*(*uint8)(v.ptr))) -} - -func (e *Encoder) kUint16(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeUint(uint64(*(*uint16)(v.ptr))) -} - -func (e *Encoder) kUint32(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeUint(uint64(*(*uint32)(v.ptr))) -} - -func (e *Encoder) kUint64(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeUint(uint64(*(*uint64)(v.ptr))) -} - -func (e *Encoder) kUintptr(f *codecFnInfo, rv reflect.Value) { - v := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - e.e.EncodeUint(uint64(*(*uintptr)(v.ptr))) -} - -// ------------ - -// func (d *Decoder) raw(f *codecFnInfo, rv reflect.Value) { -// urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) -// // if urv.flag&unsafeFlagIndir != 0 { -// // urv.ptr = *(*unsafe.Pointer)(urv.ptr) -// // } -// *(*[]byte)(urv.ptr) = d.rawBytes() -// } - -// func rv0t(rt reflect.Type) reflect.Value { -// ut := (*unsafeIntf)(unsafe.Pointer(&rt)) -// // we need to determine whether ifaceIndir, and then whether to just pass 0 as the ptr -// uv := unsafeReflectValue{ut.word, &zeroRTv, flag(rt.Kind())} -// return *(*reflect.Value)(unsafe.Pointer(&uv}) -// } - -// func rv2i(rv reflect.Value) interface{} { -// urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) -// // true references (map, func, chan, ptr - NOT slice) may be double-referenced as flagIndir -// var ptr unsafe.Pointer -// // kk := reflect.Kind(urv.flag & (1<<5 - 1)) -// // if (kk == reflect.Map || kk == reflect.Ptr || kk == reflect.Chan || kk == reflect.Func) && urv.flag&unsafeFlagIndir != 0 { -// if refBitset.isset(byte(urv.flag&(1<<5-1))) && urv.flag&unsafeFlagIndir != 0 { -// ptr = *(*unsafe.Pointer)(urv.ptr) -// } else { -// ptr = urv.ptr -// } -// return *(*interface{})(unsafe.Pointer(&unsafeIntf{typ: urv.typ, word: ptr})) -// // return *(*interface{})(unsafe.Pointer(&unsafeIntf{word: *(*unsafe.Pointer)(urv.ptr), typ: urv.typ})) -// // return *(*interface{})(unsafe.Pointer(&unsafeIntf{word: urv.ptr, typ: urv.typ})) -// } - -// func definitelyNil(v interface{}) bool { -// var ui *unsafeIntf = (*unsafeIntf)(unsafe.Pointer(&v)) -// if ui.word == nil { -// return true -// } -// var tk = reflect.TypeOf(v).Kind() -// return (tk == reflect.Interface || tk == reflect.Slice) && *(*unsafe.Pointer)(ui.word) == nil -// fmt.Printf(">>>> definitely nil: isnil: %v, TYPE: \t%T, word: %v, *word: %v, type: %v, nil: %v\n", -// v == nil, v, word, *((*unsafe.Pointer)(word)), ui.typ, nil) -// } - -// func keepAlive4BytesView(v string) { -// runtime.KeepAlive(v) -// } - -// func keepAlive4StringView(v []byte) { -// runtime.KeepAlive(v) -// } - -// func rt2id(rt reflect.Type) uintptr { -// return uintptr(((*unsafeIntf)(unsafe.Pointer(&rt))).word) -// // var i interface{} = rt -// // // ui := (*unsafeIntf)(unsafe.Pointer(&i)) -// // return ((*unsafeIntf)(unsafe.Pointer(&i))).word -// } - -// func rv2i(rv reflect.Value) interface{} { -// urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) -// // non-reference type: already indir -// // reference type: depend on flagIndir property ('cos maybe was double-referenced) -// // const (unsafeRvFlagKindMask = 1<<5 - 1 , unsafeRvFlagIndir = 1 << 7 ) -// // rvk := reflect.Kind(urv.flag & (1<<5 - 1)) -// // if (rvk == reflect.Chan || -// // rvk == reflect.Func || -// // rvk == reflect.Interface || -// // rvk == reflect.Map || -// // rvk == reflect.Ptr || -// // rvk == reflect.UnsafePointer) && urv.flag&(1<<8) != 0 { -// // fmt.Printf(">>>>> ---- double indirect reference: %v, %v\n", rvk, rv.Type()) -// // return *(*interface{})(unsafe.Pointer(&unsafeIntf{word: *(*unsafe.Pointer)(urv.ptr), typ: urv.typ})) -// // } -// if urv.flag&(1<<5-1) == uintptr(reflect.Map) && urv.flag&(1<<7) != 0 { -// // fmt.Printf(">>>>> ---- double indirect reference: %v, %v\n", rvk, rv.Type()) -// return *(*interface{})(unsafe.Pointer(&unsafeIntf{word: *(*unsafe.Pointer)(urv.ptr), typ: urv.typ})) -// } -// // fmt.Printf(">>>>> ++++ direct reference: %v, %v\n", rvk, rv.Type()) -// return *(*interface{})(unsafe.Pointer(&unsafeIntf{word: urv.ptr, typ: urv.typ})) -// } - -// const ( -// unsafeRvFlagKindMask = 1<<5 - 1 -// unsafeRvKindDirectIface = 1 << 5 -// unsafeRvFlagIndir = 1 << 7 -// unsafeRvFlagAddr = 1 << 8 -// unsafeRvFlagMethod = 1 << 9 - -// _USE_RV_INTERFACE bool = false -// _UNSAFE_RV_DEBUG = true -// ) - -// type unsafeRtype struct { -// _ [2]uintptr -// _ uint32 -// _ uint8 -// _ uint8 -// _ uint8 -// kind uint8 -// _ [2]uintptr -// _ int32 -// } - -// func _rv2i(rv reflect.Value) interface{} { -// // Note: From use, -// // - it's never an interface -// // - the only calls here are for ifaceIndir types. -// // (though that conditional is wrong) -// // To know for sure, we need the value of t.kind (which is not exposed). -// // -// // Need to validate the path: type is indirect ==> only value is indirect ==> default (value is direct) -// // - Type indirect, Value indirect: ==> numbers, boolean, slice, struct, array, string -// // - Type Direct, Value indirect: ==> map??? -// // - Type Direct, Value direct: ==> pointers, unsafe.Pointer, func, chan, map -// // -// // TRANSLATES TO: -// // if typeIndirect { } else if valueIndirect { } else { } -// // -// // Since we don't deal with funcs, then "flagNethod" is unset, and can be ignored. - -// if _USE_RV_INTERFACE { -// return rv.Interface() -// } -// urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) - -// // if urv.flag&unsafeRvFlagMethod != 0 || urv.flag&unsafeRvFlagKindMask == uintptr(reflect.Interface) { -// // println("***** IS flag method or interface: delegating to rv.Interface()") -// // return rv.Interface() -// // } - -// // if urv.flag&unsafeRvFlagKindMask == uintptr(reflect.Interface) { -// // println("***** IS Interface: delegate to rv.Interface") -// // return rv.Interface() -// // } -// // if urv.flag&unsafeRvFlagKindMask&unsafeRvKindDirectIface == 0 { -// // if urv.flag&unsafeRvFlagAddr == 0 { -// // println("***** IS ifaceIndir typ") -// // // ui := unsafeIntf{word: urv.ptr, typ: urv.typ} -// // // return *(*interface{})(unsafe.Pointer(&ui)) -// // // return *(*interface{})(unsafe.Pointer(&unsafeIntf{word: urv.ptr, typ: urv.typ})) -// // } -// // } else if urv.flag&unsafeRvFlagIndir != 0 { -// // println("***** IS flagindir") -// // // return *(*interface{})(unsafe.Pointer(&unsafeIntf{word: *(*unsafe.Pointer)(urv.ptr), typ: urv.typ})) -// // } else { -// // println("***** NOT flagindir") -// // return *(*interface{})(unsafe.Pointer(&unsafeIntf{word: urv.ptr, typ: urv.typ})) -// // } -// // println("***** default: delegate to rv.Interface") - -// urt := (*unsafeRtype)(unsafe.Pointer(urv.typ)) -// if _UNSAFE_RV_DEBUG { -// fmt.Printf(">>>> start: %v: ", rv.Type()) -// fmt.Printf("%v - %v\n", *urv, *urt) -// } -// if urt.kind&unsafeRvKindDirectIface == 0 { -// if _UNSAFE_RV_DEBUG { -// fmt.Printf("**** +ifaceIndir type: %v\n", rv.Type()) -// } -// // println("***** IS ifaceIndir typ") -// // if true || urv.flag&unsafeRvFlagAddr == 0 { -// // // println(" ***** IS NOT addr") -// return *(*interface{})(unsafe.Pointer(&unsafeIntf{word: urv.ptr, typ: urv.typ})) -// // } -// } else if urv.flag&unsafeRvFlagIndir != 0 { -// if _UNSAFE_RV_DEBUG { -// fmt.Printf("**** +flagIndir type: %v\n", rv.Type()) -// } -// // println("***** IS flagindir") -// return *(*interface{})(unsafe.Pointer(&unsafeIntf{word: *(*unsafe.Pointer)(urv.ptr), typ: urv.typ})) -// } else { -// if _UNSAFE_RV_DEBUG { -// fmt.Printf("**** -flagIndir type: %v\n", rv.Type()) -// } -// // println("***** NOT flagindir") -// return *(*interface{})(unsafe.Pointer(&unsafeIntf{word: urv.ptr, typ: urv.typ})) -// } -// // println("***** default: delegating to rv.Interface()") -// // return rv.Interface() -// } - -// var staticM0 = make(map[string]uint64) -// var staticI0 = (int32)(-5) - -// func staticRv2iTest() { -// i0 := (int32)(-5) -// m0 := make(map[string]uint16) -// m0["1"] = 1 -// for _, i := range []interface{}{ -// (int)(7), -// (uint)(8), -// (int16)(-9), -// (uint16)(19), -// (uintptr)(77), -// (bool)(true), -// float32(-32.7), -// float64(64.9), -// complex(float32(19), 5), -// complex(float64(-32), 7), -// [4]uint64{1, 2, 3, 4}, -// (chan<- int)(nil), // chan, -// rv2i, // func -// io.Writer(ioutil.Discard), -// make(map[string]uint), -// (map[string]uint)(nil), -// staticM0, -// m0, -// &m0, -// i0, -// &i0, -// &staticI0, -// &staticM0, -// []uint32{6, 7, 8}, -// "abc", -// Raw{}, -// RawExt{}, -// &Raw{}, -// &RawExt{}, -// unsafe.Pointer(&i0), -// } { -// i2 := rv2i(reflect.ValueOf(i)) -// eq := reflect.DeepEqual(i, i2) -// fmt.Printf(">>>> %v == %v? %v\n", i, i2, eq) -// } -// // os.Exit(0) -// } - -// func init() { -// staticRv2iTest() -// } - -// func rv2i(rv reflect.Value) interface{} { -// if _USE_RV_INTERFACE || rv.Kind() == reflect.Interface || rv.CanAddr() { -// return rv.Interface() -// } -// // var i interface{} -// // ui := (*unsafeIntf)(unsafe.Pointer(&i)) -// var ui unsafeIntf -// urv := (*unsafeReflectValue)(unsafe.Pointer(&rv)) -// // fmt.Printf("urv: flag: %b, typ: %b, ptr: %b\n", urv.flag, uintptr(urv.typ), uintptr(urv.ptr)) -// if (urv.flag&unsafeRvFlagKindMask)&unsafeRvKindDirectIface == 0 { -// if urv.flag&unsafeRvFlagAddr != 0 { -// println("***** indirect and addressable! Needs typed move - delegate to rv.Interface()") -// return rv.Interface() -// } -// println("****** indirect type/kind") -// ui.word = urv.ptr -// } else if urv.flag&unsafeRvFlagIndir != 0 { -// println("****** unsafe rv flag indir") -// ui.word = *(*unsafe.Pointer)(urv.ptr) -// } else { -// println("****** default: assign prt to word directly") -// ui.word = urv.ptr -// } -// // ui.word = urv.ptr -// ui.typ = urv.typ -// // fmt.Printf("(pointers) ui.typ: %p, word: %p\n", ui.typ, ui.word) -// // fmt.Printf("(binary) ui.typ: %b, word: %b\n", uintptr(ui.typ), uintptr(ui.word)) -// return *(*interface{})(unsafe.Pointer(&ui)) -// // return i -// } diff --git a/vendor/github.com/ugorji/go/codec/json.go b/vendor/github.com/ugorji/go/codec/json.go deleted file mode 100644 index bdd199663..000000000 --- a/vendor/github.com/ugorji/go/codec/json.go +++ /dev/null @@ -1,1423 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -// By default, this json support uses base64 encoding for bytes, because you cannot -// store and read any arbitrary string in json (only unicode). -// However, the user can configre how to encode/decode bytes. -// -// This library specifically supports UTF-8 for encoding and decoding only. -// -// Note that the library will happily encode/decode things which are not valid -// json e.g. a map[int64]string. We do it for consistency. With valid json, -// we will encode and decode appropriately. -// Users can specify their map type if necessary to force it. -// -// Note: -// - we cannot use strconv.Quote and strconv.Unquote because json quotes/unquotes differently. -// We implement it here. - -// Top-level methods of json(End|Dec)Driver (which are implementations of (en|de)cDriver -// MUST not call one-another. - -import ( - "bytes" - "encoding/base64" - "math" - "reflect" - "strconv" - "time" - "unicode" - "unicode/utf16" - "unicode/utf8" -) - -//-------------------------------- - -var jsonLiterals = [...]byte{ - '"', 't', 'r', 'u', 'e', '"', - '"', 'f', 'a', 'l', 's', 'e', '"', - '"', 'n', 'u', 'l', 'l', '"', -} - -const ( - jsonLitTrueQ = 0 - jsonLitTrue = 1 - jsonLitFalseQ = 6 - jsonLitFalse = 7 - jsonLitNullQ = 13 - jsonLitNull = 14 -) - -const ( - jsonU4Chk2 = '0' - jsonU4Chk1 = 'a' - 10 - jsonU4Chk0 = 'A' - 10 - - jsonScratchArrayLen = 64 -) - -const ( - // If !jsonValidateSymbols, decoding will be faster, by skipping some checks: - // - If we see first character of null, false or true, - // do not validate subsequent characters. - // - e.g. if we see a n, assume null and skip next 3 characters, - // and do not validate they are ull. - // P.S. Do not expect a significant decoding boost from this. - jsonValidateSymbols = true - - jsonSpacesOrTabsLen = 128 - - jsonAlwaysReturnInternString = false -) - -var ( - // jsonTabs and jsonSpaces are used as caches for indents - jsonTabs, jsonSpaces [jsonSpacesOrTabsLen]byte - - jsonCharHtmlSafeSet bitset128 - jsonCharSafeSet bitset128 - jsonCharWhitespaceSet bitset256 - jsonNumSet bitset256 -) - -func init() { - for i := 0; i < jsonSpacesOrTabsLen; i++ { - jsonSpaces[i] = ' ' - jsonTabs[i] = '\t' - } - - // populate the safe values as true: note: ASCII control characters are (0-31) - // jsonCharSafeSet: all true except (0-31) " \ - // jsonCharHtmlSafeSet: all true except (0-31) " \ < > & - var i byte - for i = 32; i < utf8.RuneSelf; i++ { - switch i { - case '"', '\\': - case '<', '>', '&': - jsonCharSafeSet.set(i) // = true - default: - jsonCharSafeSet.set(i) - jsonCharHtmlSafeSet.set(i) - } - } - for i = 0; i <= utf8.RuneSelf; i++ { - switch i { - case ' ', '\t', '\r', '\n': - jsonCharWhitespaceSet.set(i) - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'e', 'E', '.', '+', '-': - jsonNumSet.set(i) - } - } -} - -// ---------------- - -type jsonEncDriverTypical struct { - w encWriter - // w *encWriterSwitch - b *[jsonScratchArrayLen]byte - tw bool // term white space - c containerState -} - -func (e *jsonEncDriverTypical) typical() {} - -func (e *jsonEncDriverTypical) reset(ee *jsonEncDriver) { - e.w = ee.ew - // e.w = &ee.e.encWriterSwitch - e.b = &ee.b - e.tw = ee.h.TermWhitespace - e.c = 0 -} - -func (e *jsonEncDriverTypical) WriteArrayStart(length int) { - e.w.writen1('[') - e.c = containerArrayStart -} - -func (e *jsonEncDriverTypical) WriteArrayElem() { - if e.c != containerArrayStart { - e.w.writen1(',') - } - e.c = containerArrayElem -} - -func (e *jsonEncDriverTypical) WriteArrayEnd() { - e.w.writen1(']') - e.c = containerArrayEnd -} - -func (e *jsonEncDriverTypical) WriteMapStart(length int) { - e.w.writen1('{') - e.c = containerMapStart -} - -func (e *jsonEncDriverTypical) WriteMapElemKey() { - if e.c != containerMapStart { - e.w.writen1(',') - } - e.c = containerMapKey -} - -func (e *jsonEncDriverTypical) WriteMapElemValue() { - e.w.writen1(':') - e.c = containerMapValue -} - -func (e *jsonEncDriverTypical) WriteMapEnd() { - e.w.writen1('}') - e.c = containerMapEnd -} - -func (e *jsonEncDriverTypical) EncodeBool(b bool) { - if b { - e.w.writeb(jsonLiterals[jsonLitTrue : jsonLitTrue+4]) - } else { - e.w.writeb(jsonLiterals[jsonLitFalse : jsonLitFalse+5]) - } -} - -func (e *jsonEncDriverTypical) EncodeFloat64(f float64) { - fmt, prec := jsonFloatStrconvFmtPrec(f) - e.w.writeb(strconv.AppendFloat(e.b[:0], f, fmt, prec, 64)) -} - -func (e *jsonEncDriverTypical) EncodeInt(v int64) { - e.w.writeb(strconv.AppendInt(e.b[:0], v, 10)) -} - -func (e *jsonEncDriverTypical) EncodeUint(v uint64) { - e.w.writeb(strconv.AppendUint(e.b[:0], v, 10)) -} - -func (e *jsonEncDriverTypical) EncodeFloat32(f float32) { - e.EncodeFloat64(float64(f)) -} - -func (e *jsonEncDriverTypical) atEndOfEncode() { - if e.tw { - e.w.writen1(' ') - } -} - -// ---------------- - -type jsonEncDriverGeneric struct { - w encWriter // encWriter // *encWriterSwitch - b *[jsonScratchArrayLen]byte - c containerState - // ds string // indent string - di int8 // indent per - d bool // indenting? - dt bool // indent using tabs - dl uint16 // indent level - ks bool // map key as string - is byte // integer as string - tw bool // term white space - _ [7]byte // padding -} - -// indent is done as below: -// - newline and indent are added before each mapKey or arrayElem -// - newline and indent are added before each ending, -// except there was no entry (so we can have {} or []) - -func (e *jsonEncDriverGeneric) reset(ee *jsonEncDriver) { - e.w = ee.ew - e.b = &ee.b - e.tw = ee.h.TermWhitespace - e.c = 0 - e.d, e.dt, e.dl, e.di = false, false, 0, 0 - h := ee.h - if h.Indent > 0 { - e.d = true - e.di = int8(h.Indent) - } else if h.Indent < 0 { - e.d = true - e.dt = true - e.di = int8(-h.Indent) - } - e.ks = h.MapKeyAsString - e.is = h.IntegerAsString -} - -func (e *jsonEncDriverGeneric) WriteArrayStart(length int) { - if e.d { - e.dl++ - } - e.w.writen1('[') - e.c = containerArrayStart -} - -func (e *jsonEncDriverGeneric) WriteArrayElem() { - if e.c != containerArrayStart { - e.w.writen1(',') - } - if e.d { - e.writeIndent() - } - e.c = containerArrayElem -} - -func (e *jsonEncDriverGeneric) WriteArrayEnd() { - if e.d { - e.dl-- - if e.c != containerArrayStart { - e.writeIndent() - } - } - e.w.writen1(']') - e.c = containerArrayEnd -} - -func (e *jsonEncDriverGeneric) WriteMapStart(length int) { - if e.d { - e.dl++ - } - e.w.writen1('{') - e.c = containerMapStart -} - -func (e *jsonEncDriverGeneric) WriteMapElemKey() { - if e.c != containerMapStart { - e.w.writen1(',') - } - if e.d { - e.writeIndent() - } - e.c = containerMapKey -} - -func (e *jsonEncDriverGeneric) WriteMapElemValue() { - if e.d { - e.w.writen2(':', ' ') - } else { - e.w.writen1(':') - } - e.c = containerMapValue -} - -func (e *jsonEncDriverGeneric) WriteMapEnd() { - if e.d { - e.dl-- - if e.c != containerMapStart { - e.writeIndent() - } - } - e.w.writen1('}') - e.c = containerMapEnd -} - -func (e *jsonEncDriverGeneric) writeIndent() { - e.w.writen1('\n') - x := int(e.di) * int(e.dl) - if e.dt { - for x > jsonSpacesOrTabsLen { - e.w.writeb(jsonTabs[:]) - x -= jsonSpacesOrTabsLen - } - e.w.writeb(jsonTabs[:x]) - } else { - for x > jsonSpacesOrTabsLen { - e.w.writeb(jsonSpaces[:]) - x -= jsonSpacesOrTabsLen - } - e.w.writeb(jsonSpaces[:x]) - } -} - -func (e *jsonEncDriverGeneric) EncodeBool(b bool) { - if e.ks && e.c == containerMapKey { - if b { - e.w.writeb(jsonLiterals[jsonLitTrueQ : jsonLitTrueQ+6]) - } else { - e.w.writeb(jsonLiterals[jsonLitFalseQ : jsonLitFalseQ+7]) - } - } else { - if b { - e.w.writeb(jsonLiterals[jsonLitTrue : jsonLitTrue+4]) - } else { - e.w.writeb(jsonLiterals[jsonLitFalse : jsonLitFalse+5]) - } - } -} - -func (e *jsonEncDriverGeneric) EncodeFloat64(f float64) { - // instead of using 'g', specify whether to use 'e' or 'f' - fmt, prec := jsonFloatStrconvFmtPrec(f) - - var blen int - if e.ks && e.c == containerMapKey { - blen = 2 + len(strconv.AppendFloat(e.b[1:1], f, fmt, prec, 64)) - e.b[0] = '"' - e.b[blen-1] = '"' - } else { - blen = len(strconv.AppendFloat(e.b[:0], f, fmt, prec, 64)) - } - e.w.writeb(e.b[:blen]) -} - -func (e *jsonEncDriverGeneric) EncodeInt(v int64) { - x := e.is - if x == 'A' || x == 'L' && (v > 1<<53 || v < -(1<<53)) || (e.ks && e.c == containerMapKey) { - blen := 2 + len(strconv.AppendInt(e.b[1:1], v, 10)) - e.b[0] = '"' - e.b[blen-1] = '"' - e.w.writeb(e.b[:blen]) - return - } - e.w.writeb(strconv.AppendInt(e.b[:0], v, 10)) -} - -func (e *jsonEncDriverGeneric) EncodeUint(v uint64) { - x := e.is - if x == 'A' || x == 'L' && v > 1<<53 || (e.ks && e.c == containerMapKey) { - blen := 2 + len(strconv.AppendUint(e.b[1:1], v, 10)) - e.b[0] = '"' - e.b[blen-1] = '"' - e.w.writeb(e.b[:blen]) - return - } - e.w.writeb(strconv.AppendUint(e.b[:0], v, 10)) -} - -func (e *jsonEncDriverGeneric) EncodeFloat32(f float32) { - // e.encodeFloat(float64(f), 32) - // always encode all floats as IEEE 64-bit floating point. - // It also ensures that we can decode in full precision even if into a float32, - // as what is written is always to float64 precision. - e.EncodeFloat64(float64(f)) -} - -func (e *jsonEncDriverGeneric) atEndOfEncode() { - if e.tw { - if e.d { - e.w.writen1('\n') - } else { - e.w.writen1(' ') - } - } -} - -// -------------------- - -type jsonEncDriver struct { - noBuiltInTypes - e *Encoder - h *JsonHandle - ew encWriter // encWriter // *encWriterSwitch - se extWrapper - // ---- cpu cache line boundary? - bs []byte // scratch - // ---- cpu cache line boundary? - b [jsonScratchArrayLen]byte // scratch (encode time, -} - -func (e *jsonEncDriver) EncodeNil() { - // We always encode nil as just null (never in quotes) - // This allows us to easily decode if a nil in the json stream - // ie if initial token is n. - e.ew.writeb(jsonLiterals[jsonLitNull : jsonLitNull+4]) - - // if e.h.MapKeyAsString && e.c == containerMapKey { - // e.ew.writeb(jsonLiterals[jsonLitNullQ : jsonLitNullQ+6]) - // } else { - // e.ew.writeb(jsonLiterals[jsonLitNull : jsonLitNull+4]) - // } -} - -func (e *jsonEncDriver) EncodeTime(t time.Time) { - // Do NOT use MarshalJSON, as it allocates internally. - // instead, we call AppendFormat directly, using our scratch buffer (e.b) - if t.IsZero() { - e.EncodeNil() - } else { - e.b[0] = '"' - b := t.AppendFormat(e.b[1:1], time.RFC3339Nano) - e.b[len(b)+1] = '"' - e.ew.writeb(e.b[:len(b)+2]) - } - // v, err := t.MarshalJSON(); if err != nil { e.e.error(err) } e.ew.writeb(v) -} - -func (e *jsonEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, en *Encoder) { - if v := ext.ConvertExt(rv); v == nil { - e.EncodeNil() - } else { - en.encode(v) - } -} - -func (e *jsonEncDriver) EncodeRawExt(re *RawExt, en *Encoder) { - // only encodes re.Value (never re.Data) - if re.Value == nil { - e.EncodeNil() - } else { - en.encode(re.Value) - } -} - -func (e *jsonEncDriver) EncodeString(c charEncoding, v string) { - e.quoteStr(v) -} - -func (e *jsonEncDriver) EncodeStringBytes(c charEncoding, v []byte) { - // if encoding raw bytes and RawBytesExt is configured, use it to encode - if v == nil { - e.EncodeNil() - return - } - if c == cRAW { - if e.se.InterfaceExt != nil { - e.EncodeExt(v, 0, &e.se, e.e) - return - } - - slen := base64.StdEncoding.EncodedLen(len(v)) - if cap(e.bs) >= slen+2 { - e.bs = e.bs[:slen+2] - } else { - e.bs = make([]byte, slen+2) - } - e.bs[0] = '"' - base64.StdEncoding.Encode(e.bs[1:], v) - e.bs[slen+1] = '"' - e.ew.writeb(e.bs) - } else { - e.quoteStr(stringView(v)) - } -} - -func (e *jsonEncDriver) EncodeAsis(v []byte) { - e.ew.writeb(v) -} - -func (e *jsonEncDriver) quoteStr(s string) { - // adapted from std pkg encoding/json - const hex = "0123456789abcdef" - w := e.ew - htmlasis := e.h.HTMLCharsAsIs - w.writen1('"') - var start int - for i, slen := 0, len(s); i < slen; { - // encode all bytes < 0x20 (except \r, \n). - // also encode < > & to prevent security holes when served to some browsers. - if b := s[i]; b < utf8.RuneSelf { - // if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' { - // if (htmlasis && jsonCharSafeSet.isset(b)) || jsonCharHtmlSafeSet.isset(b) { - if jsonCharHtmlSafeSet.isset(b) || (htmlasis && jsonCharSafeSet.isset(b)) { - i++ - continue - } - if start < i { - w.writestr(s[start:i]) - } - switch b { - case '\\', '"': - w.writen2('\\', b) - case '\n': - w.writen2('\\', 'n') - case '\r': - w.writen2('\\', 'r') - case '\b': - w.writen2('\\', 'b') - case '\f': - w.writen2('\\', 'f') - case '\t': - w.writen2('\\', 't') - default: - w.writestr(`\u00`) - w.writen2(hex[b>>4], hex[b&0xF]) - } - i++ - start = i - continue - } - c, size := utf8.DecodeRuneInString(s[i:]) - if c == utf8.RuneError && size == 1 { - if start < i { - w.writestr(s[start:i]) - } - w.writestr(`\ufffd`) - i += size - start = i - continue - } - // U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR. - // Both technically valid JSON, but bomb on JSONP, so fix here unconditionally. - if c == '\u2028' || c == '\u2029' { - if start < i { - w.writestr(s[start:i]) - } - w.writestr(`\u202`) - w.writen1(hex[c&0xF]) - i += size - start = i - continue - } - i += size - } - if start < len(s) { - w.writestr(s[start:]) - } - w.writen1('"') -} - -type jsonDecDriver struct { - noBuiltInTypes - d *Decoder - h *JsonHandle - r decReader // *decReaderSwitch // decReader - se extWrapper - - // ---- writable fields during execution --- *try* to keep in sep cache line - - c containerState - // tok is used to store the token read right after skipWhiteSpace. - tok uint8 - fnull bool // found null from appendStringAsBytes - bs []byte // scratch. Initialized from b. Used for parsing strings or numbers. - bstr [8]byte // scratch used for string \UXXX parsing - // ---- cpu cache line boundary? - b [jsonScratchArrayLen]byte // scratch 1, used for parsing strings or numbers or time.Time - b2 [jsonScratchArrayLen]byte // scratch 2, used only for readUntil, decNumBytes - - _ [3]uint64 // padding - // n jsonNum -} - -// func jsonIsWS(b byte) bool { -// // return b == ' ' || b == '\t' || b == '\r' || b == '\n' -// return jsonCharWhitespaceSet.isset(b) -// } - -func (d *jsonDecDriver) uncacheRead() { - if d.tok != 0 { - d.r.unreadn1() - d.tok = 0 - } -} - -func (d *jsonDecDriver) ReadMapStart() int { - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - const xc uint8 = '{' - if d.tok != xc { - d.d.errorf("read map - expect char '%c' but got char '%c'", xc, d.tok) - } - d.tok = 0 - d.c = containerMapStart - return -1 -} - -func (d *jsonDecDriver) ReadArrayStart() int { - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - const xc uint8 = '[' - if d.tok != xc { - d.d.errorf("read array - expect char '%c' but got char '%c'", xc, d.tok) - } - d.tok = 0 - d.c = containerArrayStart - return -1 -} - -func (d *jsonDecDriver) CheckBreak() bool { - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - return d.tok == '}' || d.tok == ']' -} - -// For the ReadXXX methods below, we could just delegate to helper functions -// readContainerState(c containerState, xc uint8, check bool) -// - ReadArrayElem would become: -// readContainerState(containerArrayElem, ',', d.c != containerArrayStart) -// -// However, until mid-stack inlining comes in go1.11 which supports inlining of -// one-liners, we explicitly write them all 5 out to elide the extra func call. -// -// TODO: For Go 1.11, if inlined, consider consolidating these. - -func (d *jsonDecDriver) ReadArrayElem() { - const xc uint8 = ',' - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - if d.c != containerArrayStart { - if d.tok != xc { - d.d.errorf("read array element - expect char '%c' but got char '%c'", xc, d.tok) - } - d.tok = 0 - } - d.c = containerArrayElem -} - -func (d *jsonDecDriver) ReadArrayEnd() { - const xc uint8 = ']' - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - if d.tok != xc { - d.d.errorf("read array end - expect char '%c' but got char '%c'", xc, d.tok) - } - d.tok = 0 - d.c = containerArrayEnd -} - -func (d *jsonDecDriver) ReadMapElemKey() { - const xc uint8 = ',' - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - if d.c != containerMapStart { - if d.tok != xc { - d.d.errorf("read map key - expect char '%c' but got char '%c'", xc, d.tok) - } - d.tok = 0 - } - d.c = containerMapKey -} - -func (d *jsonDecDriver) ReadMapElemValue() { - const xc uint8 = ':' - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - if d.tok != xc { - d.d.errorf("read map value - expect char '%c' but got char '%c'", xc, d.tok) - } - d.tok = 0 - d.c = containerMapValue -} - -func (d *jsonDecDriver) ReadMapEnd() { - const xc uint8 = '}' - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - if d.tok != xc { - d.d.errorf("read map end - expect char '%c' but got char '%c'", xc, d.tok) - } - d.tok = 0 - d.c = containerMapEnd -} - -func (d *jsonDecDriver) readLit(length, fromIdx uint8) { - bs := d.r.readx(int(length)) - d.tok = 0 - if jsonValidateSymbols && !bytes.Equal(bs, jsonLiterals[fromIdx:fromIdx+length]) { - d.d.errorf("expecting %s: got %s", jsonLiterals[fromIdx:fromIdx+length], bs) - return - } -} - -func (d *jsonDecDriver) TryDecodeAsNil() bool { - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - // we shouldn't try to see if "null" was here, right? - // only the plain string: `null` denotes a nil (ie not quotes) - if d.tok == 'n' { - d.readLit(3, jsonLitNull+1) // (n)ull - return true - } - return false -} - -func (d *jsonDecDriver) DecodeBool() (v bool) { - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - fquot := d.c == containerMapKey && d.tok == '"' - if fquot { - d.tok = d.r.readn1() - } - switch d.tok { - case 'f': - d.readLit(4, jsonLitFalse+1) // (f)alse - // v = false - case 't': - d.readLit(3, jsonLitTrue+1) // (t)rue - v = true - default: - d.d.errorf("decode bool: got first char %c", d.tok) - // v = false // "unreachable" - } - if fquot { - d.r.readn1() - } - return -} - -func (d *jsonDecDriver) DecodeTime() (t time.Time) { - // read string, and pass the string into json.unmarshal - d.appendStringAsBytes() - if d.fnull { - return - } - t, err := time.Parse(time.RFC3339, stringView(d.bs)) - if err != nil { - d.d.errorv(err) - } - return -} - -func (d *jsonDecDriver) ContainerType() (vt valueType) { - // check container type by checking the first char - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - - // optimize this, so we don't do 4 checks but do one computation. - // return jsonContainerSet[d.tok] - - // ContainerType is mostly called for Map and Array, - // so this conditional is good enough (max 2 checks typically) - if b := d.tok; b == '{' { - return valueTypeMap - } else if b == '[' { - return valueTypeArray - } else if b == 'n' { - return valueTypeNil - } else if b == '"' { - return valueTypeString - } - return valueTypeUnset -} - -func (d *jsonDecDriver) decNumBytes() (bs []byte) { - // stores num bytes in d.bs - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - if d.tok == '"' { - bs = d.r.readUntil(d.b2[:0], '"') - bs = bs[:len(bs)-1] - } else { - d.r.unreadn1() - bs = d.r.readTo(d.bs[:0], &jsonNumSet) - } - d.tok = 0 - return bs -} - -func (d *jsonDecDriver) DecodeUint64() (u uint64) { - bs := d.decNumBytes() - n, neg, badsyntax, overflow := jsonParseInteger(bs) - if overflow { - d.d.errorf("overflow parsing unsigned integer: %s", bs) - } else if neg { - d.d.errorf("minus found parsing unsigned integer: %s", bs) - } else if badsyntax { - // fallback: try to decode as float, and cast - n = d.decUint64ViaFloat(stringView(bs)) - } - return n -} - -func (d *jsonDecDriver) DecodeInt64() (i int64) { - const cutoff = uint64(1 << uint(64-1)) - bs := d.decNumBytes() - n, neg, badsyntax, overflow := jsonParseInteger(bs) - if overflow { - d.d.errorf("overflow parsing integer: %s", bs) - } else if badsyntax { - // d.d.errorf("invalid syntax for integer: %s", bs) - // fallback: try to decode as float, and cast - if neg { - n = d.decUint64ViaFloat(stringView(bs[1:])) - } else { - n = d.decUint64ViaFloat(stringView(bs)) - } - } - if neg { - if n > cutoff { - d.d.errorf("overflow parsing integer: %s", bs) - } - i = -(int64(n)) - } else { - if n >= cutoff { - d.d.errorf("overflow parsing integer: %s", bs) - } - i = int64(n) - } - return -} - -func (d *jsonDecDriver) decUint64ViaFloat(s string) (u uint64) { - f, err := strconv.ParseFloat(s, 64) - if err != nil { - d.d.errorf("invalid syntax for integer: %s", s) - // d.d.errorv(err) - } - fi, ff := math.Modf(f) - if ff > 0 { - d.d.errorf("fractional part found parsing integer: %s", s) - } else if fi > float64(math.MaxUint64) { - d.d.errorf("overflow parsing integer: %s", s) - } - return uint64(fi) -} - -func (d *jsonDecDriver) DecodeFloat64() (f float64) { - bs := d.decNumBytes() - f, err := strconv.ParseFloat(stringView(bs), 64) - if err != nil { - d.d.errorv(err) - } - return -} - -func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) { - if ext == nil { - re := rv.(*RawExt) - re.Tag = xtag - d.d.decode(&re.Value) - } else { - var v interface{} - d.d.decode(&v) - ext.UpdateExt(rv, v) - } - return -} - -func (d *jsonDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) { - // if decoding into raw bytes, and the RawBytesExt is configured, use it to decode. - if d.se.InterfaceExt != nil { - bsOut = bs - d.DecodeExt(&bsOut, 0, &d.se) - return - } - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - // check if an "array" of uint8's (see ContainerType for how to infer if an array) - if d.tok == '[' { - bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d) - return - } - d.appendStringAsBytes() - // base64 encodes []byte{} as "", and we encode nil []byte as null. - // Consequently, base64 should decode null as a nil []byte, and "" as an empty []byte{}. - // appendStringAsBytes returns a zero-len slice for both, so as not to reset d.bs. - // However, it sets a fnull field to true, so we can check if a null was found. - if len(d.bs) == 0 { - if d.fnull { - return nil - } - return []byte{} - } - bs0 := d.bs - slen := base64.StdEncoding.DecodedLen(len(bs0)) - if slen <= cap(bs) { - bsOut = bs[:slen] - } else if zerocopy && slen <= cap(d.b2) { - bsOut = d.b2[:slen] - } else { - bsOut = make([]byte, slen) - } - slen2, err := base64.StdEncoding.Decode(bsOut, bs0) - if err != nil { - d.d.errorf("error decoding base64 binary '%s': %v", bs0, err) - return nil - } - if slen != slen2 { - bsOut = bsOut[:slen2] - } - return -} - -func (d *jsonDecDriver) DecodeString() (s string) { - d.appendStringAsBytes() - return d.bsToString() -} - -func (d *jsonDecDriver) DecodeStringAsBytes() (s []byte) { - d.appendStringAsBytes() - return d.bs -} - -func (d *jsonDecDriver) appendStringAsBytes() { - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - - d.fnull = false - if d.tok != '"' { - // d.d.errorf("expect char '%c' but got char '%c'", '"', d.tok) - // handle non-string scalar: null, true, false or a number - switch d.tok { - case 'n': - d.readLit(3, jsonLitNull+1) // (n)ull - d.bs = d.bs[:0] - d.fnull = true - case 'f': - d.readLit(4, jsonLitFalse+1) // (f)alse - d.bs = d.bs[:5] - copy(d.bs, "false") - case 't': - d.readLit(3, jsonLitTrue+1) // (t)rue - d.bs = d.bs[:4] - copy(d.bs, "true") - default: - // try to parse a valid number - bs := d.decNumBytes() - if len(bs) <= cap(d.bs) { - d.bs = d.bs[:len(bs)] - } else { - d.bs = make([]byte, len(bs)) - } - copy(d.bs, bs) - } - return - } - - d.tok = 0 - r := d.r - var cs = r.readUntil(d.b2[:0], '"') - var cslen = len(cs) - var c uint8 - v := d.bs[:0] - // append on each byte seen can be expensive, so we just - // keep track of where we last read a contiguous set of - // non-special bytes (using cursor variable), - // and when we see a special byte - // e.g. end-of-slice, " or \, - // we will append the full range into the v slice before proceeding - for i, cursor := 0, 0; ; { - if i == cslen { - v = append(v, cs[cursor:]...) - cs = r.readUntil(d.b2[:0], '"') - cslen = len(cs) - i, cursor = 0, 0 - } - c = cs[i] - if c == '"' { - v = append(v, cs[cursor:i]...) - break - } - if c != '\\' { - i++ - continue - } - v = append(v, cs[cursor:i]...) - i++ - c = cs[i] - switch c { - case '"', '\\', '/', '\'': - v = append(v, c) - case 'b': - v = append(v, '\b') - case 'f': - v = append(v, '\f') - case 'n': - v = append(v, '\n') - case 'r': - v = append(v, '\r') - case 't': - v = append(v, '\t') - case 'u': - var r rune - var rr uint32 - if len(cs) < i+4 { // may help reduce bounds-checking - d.d.errorf("need at least 4 more bytes for unicode sequence") - } - // c = cs[i+4] // may help reduce bounds-checking - for j := 1; j < 5; j++ { - // best to use explicit if-else - // - not a table, etc which involve memory loads, array lookup with bounds checks, etc - c = cs[i+j] - if c >= '0' && c <= '9' { - rr = rr*16 + uint32(c-jsonU4Chk2) - } else if c >= 'a' && c <= 'f' { - rr = rr*16 + uint32(c-jsonU4Chk1) - } else if c >= 'A' && c <= 'F' { - rr = rr*16 + uint32(c-jsonU4Chk0) - } else { - r = unicode.ReplacementChar - i += 4 - goto encode_rune - } - } - r = rune(rr) - i += 4 - if utf16.IsSurrogate(r) { - if len(cs) >= i+6 && cs[i+2] == 'u' && cs[i+1] == '\\' { - i += 2 - // c = cs[i+4] // may help reduce bounds-checking - var rr1 uint32 - for j := 1; j < 5; j++ { - c = cs[i+j] - if c >= '0' && c <= '9' { - rr = rr*16 + uint32(c-jsonU4Chk2) - } else if c >= 'a' && c <= 'f' { - rr = rr*16 + uint32(c-jsonU4Chk1) - } else if c >= 'A' && c <= 'F' { - rr = rr*16 + uint32(c-jsonU4Chk0) - } else { - r = unicode.ReplacementChar - i += 4 - goto encode_rune - } - } - r = utf16.DecodeRune(r, rune(rr1)) - i += 4 - } else { - r = unicode.ReplacementChar - goto encode_rune - } - } - encode_rune: - w2 := utf8.EncodeRune(d.bstr[:], r) - v = append(v, d.bstr[:w2]...) - default: - d.d.errorf("unsupported escaped value: %c", c) - } - i++ - cursor = i - } - d.bs = v -} - -func (d *jsonDecDriver) nakedNum(z *decNaked, bs []byte) (err error) { - const cutoff = uint64(1 << uint(64-1)) - var n uint64 - var neg, badsyntax, overflow bool - - if d.h.PreferFloat { - goto F - } - n, neg, badsyntax, overflow = jsonParseInteger(bs) - if badsyntax || overflow { - goto F - } - if neg { - if n > cutoff { - goto F - } - z.v = valueTypeInt - z.i = -(int64(n)) - } else if d.h.SignedInteger { - if n >= cutoff { - goto F - } - z.v = valueTypeInt - z.i = int64(n) - } else { - z.v = valueTypeUint - z.u = n - } - return -F: - z.v = valueTypeFloat - z.f, err = strconv.ParseFloat(stringView(bs), 64) - return -} - -func (d *jsonDecDriver) bsToString() string { - // if x := d.s.sc; x != nil && x.so && x.st == '}' { // map key - if jsonAlwaysReturnInternString || d.c == containerMapKey { - return d.d.string(d.bs) - } - return string(d.bs) -} - -func (d *jsonDecDriver) DecodeNaked() { - z := d.d.n - // var decodeFurther bool - - if d.tok == 0 { - d.tok = d.r.skip(&jsonCharWhitespaceSet) - } - switch d.tok { - case 'n': - d.readLit(3, jsonLitNull+1) // (n)ull - z.v = valueTypeNil - case 'f': - d.readLit(4, jsonLitFalse+1) // (f)alse - z.v = valueTypeBool - z.b = false - case 't': - d.readLit(3, jsonLitTrue+1) // (t)rue - z.v = valueTypeBool - z.b = true - case '{': - z.v = valueTypeMap // don't consume. kInterfaceNaked will call ReadMapStart - case '[': - z.v = valueTypeArray // don't consume. kInterfaceNaked will call ReadArrayStart - case '"': - // if a string, and MapKeyAsString, then try to decode it as a nil, bool or number first - d.appendStringAsBytes() - if len(d.bs) > 0 && d.c == containerMapKey && d.h.MapKeyAsString { - switch stringView(d.bs) { - case "null": - z.v = valueTypeNil - case "true": - z.v = valueTypeBool - z.b = true - case "false": - z.v = valueTypeBool - z.b = false - default: - // check if a number: float, int or uint - if err := d.nakedNum(z, d.bs); err != nil { - z.v = valueTypeString - z.s = d.bsToString() - } - } - } else { - z.v = valueTypeString - z.s = d.bsToString() - } - default: // number - bs := d.decNumBytes() - if len(bs) == 0 { - d.d.errorf("decode number from empty string") - return - } - if err := d.nakedNum(z, bs); err != nil { - d.d.errorf("decode number from %s: %v", bs, err) - return - } - } - // if decodeFurther { - // d.s.sc.retryRead() - // } - return -} - -//---------------------- - -// JsonHandle is a handle for JSON encoding format. -// -// Json is comprehensively supported: -// - decodes numbers into interface{} as int, uint or float64 -// based on how the number looks and some config parameters e.g. PreferFloat, SignedInt, etc. -// - decode integers from float formatted numbers e.g. 1.27e+8 -// - decode any json value (numbers, bool, etc) from quoted strings -// - configurable way to encode/decode []byte . -// by default, encodes and decodes []byte using base64 Std Encoding -// - UTF-8 support for encoding and decoding -// -// It has better performance than the json library in the standard library, -// by leveraging the performance improvements of the codec library. -// -// In addition, it doesn't read more bytes than necessary during a decode, which allows -// reading multiple values from a stream containing json and non-json content. -// For example, a user can read a json value, then a cbor value, then a msgpack value, -// all from the same stream in sequence. -// -// Note that, when decoding quoted strings, invalid UTF-8 or invalid UTF-16 surrogate pairs are -// not treated as an error. Instead, they are replaced by the Unicode replacement character U+FFFD. -type JsonHandle struct { - textEncodingType - BasicHandle - - // Indent indicates how a value is encoded. - // - If positive, indent by that number of spaces. - // - If negative, indent by that number of tabs. - Indent int8 - - // IntegerAsString controls how integers (signed and unsigned) are encoded. - // - // Per the JSON Spec, JSON numbers are 64-bit floating point numbers. - // Consequently, integers > 2^53 cannot be represented as a JSON number without losing precision. - // This can be mitigated by configuring how to encode integers. - // - // IntegerAsString interpretes the following values: - // - if 'L', then encode integers > 2^53 as a json string. - // - if 'A', then encode all integers as a json string - // containing the exact integer representation as a decimal. - // - else encode all integers as a json number (default) - IntegerAsString byte - - // HTMLCharsAsIs controls how to encode some special characters to html: < > & - // - // By default, we encode them as \uXXX - // to prevent security holes when served from some browsers. - HTMLCharsAsIs bool - - // PreferFloat says that we will default to decoding a number as a float. - // If not set, we will examine the characters of the number and decode as an - // integer type if it doesn't have any of the characters [.eE]. - PreferFloat bool - - // TermWhitespace says that we add a whitespace character - // at the end of an encoding. - // - // The whitespace is important, especially if using numbers in a context - // where multiple items are written to a stream. - TermWhitespace bool - - // MapKeyAsString says to encode all map keys as strings. - // - // Use this to enforce strict json output. - // The only caveat is that nil value is ALWAYS written as null (never as "null") - MapKeyAsString bool - - // _ [2]byte // padding - - // Note: below, we store hardly-used items e.g. RawBytesExt is cached in the (en|de)cDriver. - - // RawBytesExt, if configured, is used to encode and decode raw bytes in a custom way. - // If not configured, raw bytes are encoded to/from base64 text. - RawBytesExt InterfaceExt - - _ [2]uint64 // padding -} - -// Name returns the name of the handle: json -func (h *JsonHandle) Name() string { return "json" } -func (h *JsonHandle) hasElemSeparators() bool { return true } -func (h *JsonHandle) typical() bool { - return h.Indent == 0 && !h.MapKeyAsString && h.IntegerAsString != 'A' && h.IntegerAsString != 'L' -} - -type jsonTypical interface { - typical() -} - -func (h *JsonHandle) recreateEncDriver(ed encDriver) (v bool) { - _, v = ed.(jsonTypical) - return v != h.typical() -} - -// SetInterfaceExt sets an extension -func (h *JsonHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) { - return h.SetExt(rt, tag, &extWrapper{bytesExtFailer{}, ext}) -} - -type jsonEncDriverTypicalImpl struct { - jsonEncDriver - jsonEncDriverTypical - _ [1]uint64 // padding -} - -func (x *jsonEncDriverTypicalImpl) reset() { - x.jsonEncDriver.reset() - x.jsonEncDriverTypical.reset(&x.jsonEncDriver) -} - -type jsonEncDriverGenericImpl struct { - jsonEncDriver - jsonEncDriverGeneric -} - -func (x *jsonEncDriverGenericImpl) reset() { - x.jsonEncDriver.reset() - x.jsonEncDriverGeneric.reset(&x.jsonEncDriver) -} - -func (h *JsonHandle) newEncDriver(e *Encoder) (ee encDriver) { - var hd *jsonEncDriver - if h.typical() { - var v jsonEncDriverTypicalImpl - ee = &v - hd = &v.jsonEncDriver - } else { - var v jsonEncDriverGenericImpl - ee = &v - hd = &v.jsonEncDriver - } - hd.e, hd.h, hd.bs = e, h, hd.b[:0] - hd.se.BytesExt = bytesExtFailer{} - ee.reset() - return -} - -func (h *JsonHandle) newDecDriver(d *Decoder) decDriver { - // d := jsonDecDriver{r: r.(*bytesDecReader), h: h} - hd := jsonDecDriver{d: d, h: h} - hd.se.BytesExt = bytesExtFailer{} - hd.bs = hd.b[:0] - hd.reset() - return &hd -} - -func (e *jsonEncDriver) reset() { - e.ew = e.e.w // e.e.w // &e.e.encWriterSwitch - e.se.InterfaceExt = e.h.RawBytesExt - if e.bs != nil { - e.bs = e.bs[:0] - } -} - -func (d *jsonDecDriver) reset() { - d.r = d.d.r // &d.d.decReaderSwitch // d.d.r - d.se.InterfaceExt = d.h.RawBytesExt - if d.bs != nil { - d.bs = d.bs[:0] - } - d.c, d.tok = 0, 0 - // d.n.reset() -} - -func jsonFloatStrconvFmtPrec(f float64) (fmt byte, prec int) { - prec = -1 - var abs = math.Abs(f) - if abs != 0 && (abs < 1e-6 || abs >= 1e21) { - fmt = 'e' - } else { - fmt = 'f' - // set prec to 1 iff mod is 0. - // better than using jsonIsFloatBytesB2 to check if a . or E in the float bytes. - // this ensures that every float has an e or .0 in it. - if abs <= 1 { - if abs == 0 || abs == 1 { - prec = 1 - } - } else if _, mod := math.Modf(abs); mod == 0 { - prec = 1 - } - } - return -} - -// custom-fitted version of strconv.Parse(Ui|I)nt. -// Also ensures we don't have to search for .eE to determine if a float or not. -func jsonParseInteger(s []byte) (n uint64, neg, badSyntax, overflow bool) { - const maxUint64 = (1<<64 - 1) - const cutoff = maxUint64/10 + 1 - - if len(s) == 0 { - badSyntax = true - return - } - switch s[0] { - case '+': - s = s[1:] - case '-': - s = s[1:] - neg = true - } - for _, c := range s { - if c < '0' || c > '9' { - badSyntax = true - return - } - // unsigned integers don't overflow well on multiplication, so check cutoff here - // e.g. (maxUint64-5)*10 doesn't overflow well ... - if n >= cutoff { - overflow = true - return - } - n *= 10 - n1 := n + uint64(c-'0') - if n1 < n || n1 > maxUint64 { - overflow = true - return - } - n = n1 - } - return -} - -var _ decDriver = (*jsonDecDriver)(nil) -var _ encDriver = (*jsonEncDriverGenericImpl)(nil) -var _ encDriver = (*jsonEncDriverTypicalImpl)(nil) -var _ jsonTypical = (*jsonEncDriverTypical)(nil) diff --git a/vendor/github.com/ugorji/go/codec/msgpack.go b/vendor/github.com/ugorji/go/codec/msgpack.go deleted file mode 100644 index 3271579a1..000000000 --- a/vendor/github.com/ugorji/go/codec/msgpack.go +++ /dev/null @@ -1,1092 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -/* -MSGPACK - -Msgpack-c implementation powers the c, c++, python, ruby, etc libraries. -We need to maintain compatibility with it and how it encodes integer values -without caring about the type. - -For compatibility with behaviour of msgpack-c reference implementation: - - Go intX (>0) and uintX - IS ENCODED AS - msgpack +ve fixnum, unsigned - - Go intX (<0) - IS ENCODED AS - msgpack -ve fixnum, signed -*/ - -package codec - -import ( - "fmt" - "io" - "math" - "net/rpc" - "reflect" - "time" -) - -const ( - mpPosFixNumMin byte = 0x00 - mpPosFixNumMax = 0x7f - mpFixMapMin = 0x80 - mpFixMapMax = 0x8f - mpFixArrayMin = 0x90 - mpFixArrayMax = 0x9f - mpFixStrMin = 0xa0 - mpFixStrMax = 0xbf - mpNil = 0xc0 - _ = 0xc1 - mpFalse = 0xc2 - mpTrue = 0xc3 - mpFloat = 0xca - mpDouble = 0xcb - mpUint8 = 0xcc - mpUint16 = 0xcd - mpUint32 = 0xce - mpUint64 = 0xcf - mpInt8 = 0xd0 - mpInt16 = 0xd1 - mpInt32 = 0xd2 - mpInt64 = 0xd3 - - // extensions below - mpBin8 = 0xc4 - mpBin16 = 0xc5 - mpBin32 = 0xc6 - mpExt8 = 0xc7 - mpExt16 = 0xc8 - mpExt32 = 0xc9 - mpFixExt1 = 0xd4 - mpFixExt2 = 0xd5 - mpFixExt4 = 0xd6 - mpFixExt8 = 0xd7 - mpFixExt16 = 0xd8 - - mpStr8 = 0xd9 // new - mpStr16 = 0xda - mpStr32 = 0xdb - - mpArray16 = 0xdc - mpArray32 = 0xdd - - mpMap16 = 0xde - mpMap32 = 0xdf - - mpNegFixNumMin = 0xe0 - mpNegFixNumMax = 0xff -) - -var mpTimeExtTag int8 = -1 -var mpTimeExtTagU = uint8(mpTimeExtTag) - -// var mpdesc = map[byte]string{ -// mpPosFixNumMin: "PosFixNumMin", -// mpPosFixNumMax: "PosFixNumMax", -// mpFixMapMin: "FixMapMin", -// mpFixMapMax: "FixMapMax", -// mpFixArrayMin: "FixArrayMin", -// mpFixArrayMax: "FixArrayMax", -// mpFixStrMin: "FixStrMin", -// mpFixStrMax: "FixStrMax", -// mpNil: "Nil", -// mpFalse: "False", -// mpTrue: "True", -// mpFloat: "Float", -// mpDouble: "Double", -// mpUint8: "Uint8", -// mpUint16: "Uint16", -// mpUint32: "Uint32", -// mpUint64: "Uint64", -// mpInt8: "Int8", -// mpInt16: "Int16", -// mpInt32: "Int32", -// mpInt64: "Int64", -// mpBin8: "Bin8", -// mpBin16: "Bin16", -// mpBin32: "Bin32", -// mpExt8: "Ext8", -// mpExt16: "Ext16", -// mpExt32: "Ext32", -// mpFixExt1: "FixExt1", -// mpFixExt2: "FixExt2", -// mpFixExt4: "FixExt4", -// mpFixExt8: "FixExt8", -// mpFixExt16: "FixExt16", -// mpStr8: "Str8", -// mpStr16: "Str16", -// mpStr32: "Str32", -// mpArray16: "Array16", -// mpArray32: "Array32", -// mpMap16: "Map16", -// mpMap32: "Map32", -// mpNegFixNumMin: "NegFixNumMin", -// mpNegFixNumMax: "NegFixNumMax", -// } - -func mpdesc(bd byte) string { - switch bd { - case mpNil: - return "nil" - case mpFalse: - return "false" - case mpTrue: - return "true" - case mpFloat, mpDouble: - return "float" - case mpUint8, mpUint16, mpUint32, mpUint64: - return "uint" - case mpInt8, mpInt16, mpInt32, mpInt64: - return "int" - default: - switch { - case bd >= mpPosFixNumMin && bd <= mpPosFixNumMax: - return "int" - case bd >= mpNegFixNumMin && bd <= mpNegFixNumMax: - return "int" - case bd == mpStr8, bd == mpStr16, bd == mpStr32, bd >= mpFixStrMin && bd <= mpFixStrMax: - return "string|bytes" - case bd == mpBin8, bd == mpBin16, bd == mpBin32: - return "bytes" - case bd == mpArray16, bd == mpArray32, bd >= mpFixArrayMin && bd <= mpFixArrayMax: - return "array" - case bd == mpMap16, bd == mpMap32, bd >= mpFixMapMin && bd <= mpFixMapMax: - return "map" - case bd >= mpFixExt1 && bd <= mpFixExt16, bd >= mpExt8 && bd <= mpExt32: - return "ext" - default: - return "unknown" - } - } -} - -// MsgpackSpecRpcMultiArgs is a special type which signifies to the MsgpackSpecRpcCodec -// that the backend RPC service takes multiple arguments, which have been arranged -// in sequence in the slice. -// -// The Codec then passes it AS-IS to the rpc service (without wrapping it in an -// array of 1 element). -type MsgpackSpecRpcMultiArgs []interface{} - -// A MsgpackContainer type specifies the different types of msgpackContainers. -type msgpackContainerType struct { - fixCutoff int - bFixMin, b8, b16, b32 byte - hasFixMin, has8, has8Always bool -} - -var ( - msgpackContainerStr = msgpackContainerType{ - 32, mpFixStrMin, mpStr8, mpStr16, mpStr32, true, true, false, - } - msgpackContainerBin = msgpackContainerType{ - 0, 0, mpBin8, mpBin16, mpBin32, false, true, true, - } - msgpackContainerList = msgpackContainerType{ - 16, mpFixArrayMin, 0, mpArray16, mpArray32, true, false, false, - } - msgpackContainerMap = msgpackContainerType{ - 16, mpFixMapMin, 0, mpMap16, mpMap32, true, false, false, - } -) - -//--------------------------------------------- - -type msgpackEncDriver struct { - noBuiltInTypes - encDriverNoopContainerWriter - // encNoSeparator - e *Encoder - w encWriter - h *MsgpackHandle - x [8]byte - _ [3]uint64 // padding -} - -func (e *msgpackEncDriver) EncodeNil() { - e.w.writen1(mpNil) -} - -func (e *msgpackEncDriver) EncodeInt(i int64) { - // if i >= 0 { - // e.EncodeUint(uint64(i)) - // } else if false && - if i > math.MaxInt8 { - if i <= math.MaxInt16 { - e.w.writen1(mpInt16) - bigenHelper{e.x[:2], e.w}.writeUint16(uint16(i)) - } else if i <= math.MaxInt32 { - e.w.writen1(mpInt32) - bigenHelper{e.x[:4], e.w}.writeUint32(uint32(i)) - } else { - e.w.writen1(mpInt64) - bigenHelper{e.x[:8], e.w}.writeUint64(uint64(i)) - } - } else if i >= -32 { - if e.h.NoFixedNum { - e.w.writen2(mpInt8, byte(i)) - } else { - e.w.writen1(byte(i)) - } - } else if i >= math.MinInt8 { - e.w.writen2(mpInt8, byte(i)) - } else if i >= math.MinInt16 { - e.w.writen1(mpInt16) - bigenHelper{e.x[:2], e.w}.writeUint16(uint16(i)) - } else if i >= math.MinInt32 { - e.w.writen1(mpInt32) - bigenHelper{e.x[:4], e.w}.writeUint32(uint32(i)) - } else { - e.w.writen1(mpInt64) - bigenHelper{e.x[:8], e.w}.writeUint64(uint64(i)) - } -} - -func (e *msgpackEncDriver) EncodeUint(i uint64) { - if i <= math.MaxInt8 { - if e.h.NoFixedNum { - e.w.writen2(mpUint8, byte(i)) - } else { - e.w.writen1(byte(i)) - } - } else if i <= math.MaxUint8 { - e.w.writen2(mpUint8, byte(i)) - } else if i <= math.MaxUint16 { - e.w.writen1(mpUint16) - bigenHelper{e.x[:2], e.w}.writeUint16(uint16(i)) - } else if i <= math.MaxUint32 { - e.w.writen1(mpUint32) - bigenHelper{e.x[:4], e.w}.writeUint32(uint32(i)) - } else { - e.w.writen1(mpUint64) - bigenHelper{e.x[:8], e.w}.writeUint64(uint64(i)) - } -} - -func (e *msgpackEncDriver) EncodeBool(b bool) { - if b { - e.w.writen1(mpTrue) - } else { - e.w.writen1(mpFalse) - } -} - -func (e *msgpackEncDriver) EncodeFloat32(f float32) { - e.w.writen1(mpFloat) - bigenHelper{e.x[:4], e.w}.writeUint32(math.Float32bits(f)) -} - -func (e *msgpackEncDriver) EncodeFloat64(f float64) { - e.w.writen1(mpDouble) - bigenHelper{e.x[:8], e.w}.writeUint64(math.Float64bits(f)) -} - -func (e *msgpackEncDriver) EncodeTime(t time.Time) { - if t.IsZero() { - e.EncodeNil() - return - } - t = t.UTC() - sec, nsec := t.Unix(), uint64(t.Nanosecond()) - var data64 uint64 - var l = 4 - if sec >= 0 && sec>>34 == 0 { - data64 = (nsec << 34) | uint64(sec) - if data64&0xffffffff00000000 != 0 { - l = 8 - } - } else { - l = 12 - } - if e.h.WriteExt { - e.encodeExtPreamble(mpTimeExtTagU, l) - } else { - e.writeContainerLen(msgpackContainerStr, l) - } - switch l { - case 4: - bigenHelper{e.x[:4], e.w}.writeUint32(uint32(data64)) - case 8: - bigenHelper{e.x[:8], e.w}.writeUint64(data64) - case 12: - bigenHelper{e.x[:4], e.w}.writeUint32(uint32(nsec)) - bigenHelper{e.x[:8], e.w}.writeUint64(uint64(sec)) - } -} - -func (e *msgpackEncDriver) EncodeExt(v interface{}, xtag uint64, ext Ext, _ *Encoder) { - bs := ext.WriteExt(v) - if bs == nil { - e.EncodeNil() - return - } - if e.h.WriteExt { - e.encodeExtPreamble(uint8(xtag), len(bs)) - e.w.writeb(bs) - } else { - e.EncodeStringBytes(cRAW, bs) - } -} - -func (e *msgpackEncDriver) EncodeRawExt(re *RawExt, _ *Encoder) { - e.encodeExtPreamble(uint8(re.Tag), len(re.Data)) - e.w.writeb(re.Data) -} - -func (e *msgpackEncDriver) encodeExtPreamble(xtag byte, l int) { - if l == 1 { - e.w.writen2(mpFixExt1, xtag) - } else if l == 2 { - e.w.writen2(mpFixExt2, xtag) - } else if l == 4 { - e.w.writen2(mpFixExt4, xtag) - } else if l == 8 { - e.w.writen2(mpFixExt8, xtag) - } else if l == 16 { - e.w.writen2(mpFixExt16, xtag) - } else if l < 256 { - e.w.writen2(mpExt8, byte(l)) - e.w.writen1(xtag) - } else if l < 65536 { - e.w.writen1(mpExt16) - bigenHelper{e.x[:2], e.w}.writeUint16(uint16(l)) - e.w.writen1(xtag) - } else { - e.w.writen1(mpExt32) - bigenHelper{e.x[:4], e.w}.writeUint32(uint32(l)) - e.w.writen1(xtag) - } -} - -func (e *msgpackEncDriver) WriteArrayStart(length int) { - e.writeContainerLen(msgpackContainerList, length) -} - -func (e *msgpackEncDriver) WriteMapStart(length int) { - e.writeContainerLen(msgpackContainerMap, length) -} - -func (e *msgpackEncDriver) EncodeString(c charEncoding, s string) { - slen := len(s) - if c == cRAW && e.h.WriteExt { - e.writeContainerLen(msgpackContainerBin, slen) - } else { - e.writeContainerLen(msgpackContainerStr, slen) - } - if slen > 0 { - e.w.writestr(s) - } -} - -func (e *msgpackEncDriver) EncodeStringBytes(c charEncoding, bs []byte) { - if bs == nil { - e.EncodeNil() - return - } - slen := len(bs) - if c == cRAW && e.h.WriteExt { - e.writeContainerLen(msgpackContainerBin, slen) - } else { - e.writeContainerLen(msgpackContainerStr, slen) - } - if slen > 0 { - e.w.writeb(bs) - } -} - -func (e *msgpackEncDriver) writeContainerLen(ct msgpackContainerType, l int) { - if ct.hasFixMin && l < ct.fixCutoff { - e.w.writen1(ct.bFixMin | byte(l)) - } else if ct.has8 && l < 256 && (ct.has8Always || e.h.WriteExt) { - e.w.writen2(ct.b8, uint8(l)) - } else if l < 65536 { - e.w.writen1(ct.b16) - bigenHelper{e.x[:2], e.w}.writeUint16(uint16(l)) - } else { - e.w.writen1(ct.b32) - bigenHelper{e.x[:4], e.w}.writeUint32(uint32(l)) - } -} - -//--------------------------------------------- - -type msgpackDecDriver struct { - d *Decoder - r decReader // *Decoder decReader decReaderT - h *MsgpackHandle - // b [scratchByteArrayLen]byte - bd byte - bdRead bool - br bool // bytes reader - noBuiltInTypes - // noStreamingCodec - // decNoSeparator - decDriverNoopContainerReader - _ [3]uint64 // padding -} - -// Note: This returns either a primitive (int, bool, etc) for non-containers, -// or a containerType, or a specific type denoting nil or extension. -// It is called when a nil interface{} is passed, leaving it up to the DecDriver -// to introspect the stream and decide how best to decode. -// It deciphers the value by looking at the stream first. -func (d *msgpackDecDriver) DecodeNaked() { - if !d.bdRead { - d.readNextBd() - } - bd := d.bd - n := d.d.n - var decodeFurther bool - - switch bd { - case mpNil: - n.v = valueTypeNil - d.bdRead = false - case mpFalse: - n.v = valueTypeBool - n.b = false - case mpTrue: - n.v = valueTypeBool - n.b = true - - case mpFloat: - n.v = valueTypeFloat - n.f = float64(math.Float32frombits(bigen.Uint32(d.r.readx(4)))) - case mpDouble: - n.v = valueTypeFloat - n.f = math.Float64frombits(bigen.Uint64(d.r.readx(8))) - - case mpUint8: - n.v = valueTypeUint - n.u = uint64(d.r.readn1()) - case mpUint16: - n.v = valueTypeUint - n.u = uint64(bigen.Uint16(d.r.readx(2))) - case mpUint32: - n.v = valueTypeUint - n.u = uint64(bigen.Uint32(d.r.readx(4))) - case mpUint64: - n.v = valueTypeUint - n.u = uint64(bigen.Uint64(d.r.readx(8))) - - case mpInt8: - n.v = valueTypeInt - n.i = int64(int8(d.r.readn1())) - case mpInt16: - n.v = valueTypeInt - n.i = int64(int16(bigen.Uint16(d.r.readx(2)))) - case mpInt32: - n.v = valueTypeInt - n.i = int64(int32(bigen.Uint32(d.r.readx(4)))) - case mpInt64: - n.v = valueTypeInt - n.i = int64(int64(bigen.Uint64(d.r.readx(8)))) - - default: - switch { - case bd >= mpPosFixNumMin && bd <= mpPosFixNumMax: - // positive fixnum (always signed) - n.v = valueTypeInt - n.i = int64(int8(bd)) - case bd >= mpNegFixNumMin && bd <= mpNegFixNumMax: - // negative fixnum - n.v = valueTypeInt - n.i = int64(int8(bd)) - case bd == mpStr8, bd == mpStr16, bd == mpStr32, bd >= mpFixStrMin && bd <= mpFixStrMax: - if d.h.RawToString { - n.v = valueTypeString - n.s = d.DecodeString() - } else { - n.v = valueTypeBytes - n.l = d.DecodeBytes(nil, false) - } - case bd == mpBin8, bd == mpBin16, bd == mpBin32: - n.v = valueTypeBytes - n.l = d.DecodeBytes(nil, false) - case bd == mpArray16, bd == mpArray32, bd >= mpFixArrayMin && bd <= mpFixArrayMax: - n.v = valueTypeArray - decodeFurther = true - case bd == mpMap16, bd == mpMap32, bd >= mpFixMapMin && bd <= mpFixMapMax: - n.v = valueTypeMap - decodeFurther = true - case bd >= mpFixExt1 && bd <= mpFixExt16, bd >= mpExt8 && bd <= mpExt32: - n.v = valueTypeExt - clen := d.readExtLen() - n.u = uint64(d.r.readn1()) - if n.u == uint64(mpTimeExtTagU) { - n.v = valueTypeTime - n.t = d.decodeTime(clen) - } else { - n.l = d.r.readx(clen) - } - default: - d.d.errorf("cannot infer value: %s: Ox%x/%d/%s", msgBadDesc, bd, bd, mpdesc(bd)) - } - } - if !decodeFurther { - d.bdRead = false - } - if n.v == valueTypeUint && d.h.SignedInteger { - n.v = valueTypeInt - n.i = int64(n.u) - } - return -} - -// int can be decoded from msgpack type: intXXX or uintXXX -func (d *msgpackDecDriver) DecodeInt64() (i int64) { - if !d.bdRead { - d.readNextBd() - } - switch d.bd { - case mpUint8: - i = int64(uint64(d.r.readn1())) - case mpUint16: - i = int64(uint64(bigen.Uint16(d.r.readx(2)))) - case mpUint32: - i = int64(uint64(bigen.Uint32(d.r.readx(4)))) - case mpUint64: - i = int64(bigen.Uint64(d.r.readx(8))) - case mpInt8: - i = int64(int8(d.r.readn1())) - case mpInt16: - i = int64(int16(bigen.Uint16(d.r.readx(2)))) - case mpInt32: - i = int64(int32(bigen.Uint32(d.r.readx(4)))) - case mpInt64: - i = int64(bigen.Uint64(d.r.readx(8))) - default: - switch { - case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax: - i = int64(int8(d.bd)) - case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax: - i = int64(int8(d.bd)) - default: - d.d.errorf("cannot decode signed integer: %s: %x/%s", msgBadDesc, d.bd, mpdesc(d.bd)) - return - } - } - d.bdRead = false - return -} - -// uint can be decoded from msgpack type: intXXX or uintXXX -func (d *msgpackDecDriver) DecodeUint64() (ui uint64) { - if !d.bdRead { - d.readNextBd() - } - switch d.bd { - case mpUint8: - ui = uint64(d.r.readn1()) - case mpUint16: - ui = uint64(bigen.Uint16(d.r.readx(2))) - case mpUint32: - ui = uint64(bigen.Uint32(d.r.readx(4))) - case mpUint64: - ui = bigen.Uint64(d.r.readx(8)) - case mpInt8: - if i := int64(int8(d.r.readn1())); i >= 0 { - ui = uint64(i) - } else { - d.d.errorf("assigning negative signed value: %v, to unsigned type", i) - return - } - case mpInt16: - if i := int64(int16(bigen.Uint16(d.r.readx(2)))); i >= 0 { - ui = uint64(i) - } else { - d.d.errorf("assigning negative signed value: %v, to unsigned type", i) - return - } - case mpInt32: - if i := int64(int32(bigen.Uint32(d.r.readx(4)))); i >= 0 { - ui = uint64(i) - } else { - d.d.errorf("assigning negative signed value: %v, to unsigned type", i) - return - } - case mpInt64: - if i := int64(bigen.Uint64(d.r.readx(8))); i >= 0 { - ui = uint64(i) - } else { - d.d.errorf("assigning negative signed value: %v, to unsigned type", i) - return - } - default: - switch { - case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax: - ui = uint64(d.bd) - case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax: - d.d.errorf("assigning negative signed value: %v, to unsigned type", int(d.bd)) - return - default: - d.d.errorf("cannot decode unsigned integer: %s: %x/%s", msgBadDesc, d.bd, mpdesc(d.bd)) - return - } - } - d.bdRead = false - return -} - -// float can either be decoded from msgpack type: float, double or intX -func (d *msgpackDecDriver) DecodeFloat64() (f float64) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == mpFloat { - f = float64(math.Float32frombits(bigen.Uint32(d.r.readx(4)))) - } else if d.bd == mpDouble { - f = math.Float64frombits(bigen.Uint64(d.r.readx(8))) - } else { - f = float64(d.DecodeInt64()) - } - d.bdRead = false - return -} - -// bool can be decoded from bool, fixnum 0 or 1. -func (d *msgpackDecDriver) DecodeBool() (b bool) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == mpFalse || d.bd == 0 { - // b = false - } else if d.bd == mpTrue || d.bd == 1 { - b = true - } else { - d.d.errorf("cannot decode bool: %s: %x/%s", msgBadDesc, d.bd, mpdesc(d.bd)) - return - } - d.bdRead = false - return -} - -func (d *msgpackDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) { - if !d.bdRead { - d.readNextBd() - } - - // check if an "array" of uint8's (see ContainerType for how to infer if an array) - bd := d.bd - // DecodeBytes could be from: bin str fixstr fixarray array ... - var clen int - vt := d.ContainerType() - switch vt { - case valueTypeBytes: - // valueTypeBytes may be a mpBin or an mpStr container - if bd == mpBin8 || bd == mpBin16 || bd == mpBin32 { - clen = d.readContainerLen(msgpackContainerBin) - } else { - clen = d.readContainerLen(msgpackContainerStr) - } - case valueTypeString: - clen = d.readContainerLen(msgpackContainerStr) - case valueTypeArray: - if zerocopy && len(bs) == 0 { - bs = d.d.b[:] - } - bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d) - return - default: - d.d.errorf("invalid container type: expecting bin|str|array, got: 0x%x", uint8(vt)) - return - } - - // these are (bin|str)(8|16|32) - d.bdRead = false - // bytes may be nil, so handle it. if nil, clen=-1. - if clen < 0 { - return nil - } - if zerocopy { - if d.br { - return d.r.readx(clen) - } else if len(bs) == 0 { - bs = d.d.b[:] - } - } - return decByteSlice(d.r, clen, d.h.MaxInitLen, bs) -} - -func (d *msgpackDecDriver) DecodeString() (s string) { - return string(d.DecodeBytes(d.d.b[:], true)) -} - -func (d *msgpackDecDriver) DecodeStringAsBytes() (s []byte) { - return d.DecodeBytes(d.d.b[:], true) -} - -func (d *msgpackDecDriver) readNextBd() { - d.bd = d.r.readn1() - d.bdRead = true -} - -func (d *msgpackDecDriver) uncacheRead() { - if d.bdRead { - d.r.unreadn1() - d.bdRead = false - } -} - -func (d *msgpackDecDriver) ContainerType() (vt valueType) { - if !d.bdRead { - d.readNextBd() - } - bd := d.bd - if bd == mpNil { - return valueTypeNil - } else if bd == mpBin8 || bd == mpBin16 || bd == mpBin32 || - (!d.h.RawToString && - (bd == mpStr8 || bd == mpStr16 || bd == mpStr32 || (bd >= mpFixStrMin && bd <= mpFixStrMax))) { - return valueTypeBytes - } else if d.h.RawToString && - (bd == mpStr8 || bd == mpStr16 || bd == mpStr32 || (bd >= mpFixStrMin && bd <= mpFixStrMax)) { - return valueTypeString - } else if bd == mpArray16 || bd == mpArray32 || (bd >= mpFixArrayMin && bd <= mpFixArrayMax) { - return valueTypeArray - } else if bd == mpMap16 || bd == mpMap32 || (bd >= mpFixMapMin && bd <= mpFixMapMax) { - return valueTypeMap - } - // else { - // d.d.errorf("isContainerType: unsupported parameter: %v", vt) - // } - return valueTypeUnset -} - -func (d *msgpackDecDriver) TryDecodeAsNil() (v bool) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == mpNil { - d.bdRead = false - return true - } - return -} - -func (d *msgpackDecDriver) readContainerLen(ct msgpackContainerType) (clen int) { - bd := d.bd - if bd == mpNil { - clen = -1 // to represent nil - } else if bd == ct.b8 { - clen = int(d.r.readn1()) - } else if bd == ct.b16 { - clen = int(bigen.Uint16(d.r.readx(2))) - } else if bd == ct.b32 { - clen = int(bigen.Uint32(d.r.readx(4))) - } else if (ct.bFixMin & bd) == ct.bFixMin { - clen = int(ct.bFixMin ^ bd) - } else { - d.d.errorf("cannot read container length: %s: hex: %x, decimal: %d", msgBadDesc, bd, bd) - return - } - d.bdRead = false - return -} - -func (d *msgpackDecDriver) ReadMapStart() int { - if !d.bdRead { - d.readNextBd() - } - return d.readContainerLen(msgpackContainerMap) -} - -func (d *msgpackDecDriver) ReadArrayStart() int { - if !d.bdRead { - d.readNextBd() - } - return d.readContainerLen(msgpackContainerList) -} - -func (d *msgpackDecDriver) readExtLen() (clen int) { - switch d.bd { - case mpNil: - clen = -1 // to represent nil - case mpFixExt1: - clen = 1 - case mpFixExt2: - clen = 2 - case mpFixExt4: - clen = 4 - case mpFixExt8: - clen = 8 - case mpFixExt16: - clen = 16 - case mpExt8: - clen = int(d.r.readn1()) - case mpExt16: - clen = int(bigen.Uint16(d.r.readx(2))) - case mpExt32: - clen = int(bigen.Uint32(d.r.readx(4))) - default: - d.d.errorf("decoding ext bytes: found unexpected byte: %x", d.bd) - return - } - return -} - -func (d *msgpackDecDriver) DecodeTime() (t time.Time) { - // decode time from string bytes or ext - if !d.bdRead { - d.readNextBd() - } - if d.bd == mpNil { - d.bdRead = false - return - } - var clen int - switch d.ContainerType() { - case valueTypeBytes, valueTypeString: - clen = d.readContainerLen(msgpackContainerStr) - default: - // expect to see mpFixExt4,-1 OR mpFixExt8,-1 OR mpExt8,12,-1 - d.bdRead = false - b2 := d.r.readn1() - if d.bd == mpFixExt4 && b2 == mpTimeExtTagU { - clen = 4 - } else if d.bd == mpFixExt8 && b2 == mpTimeExtTagU { - clen = 8 - } else if d.bd == mpExt8 && b2 == 12 && d.r.readn1() == mpTimeExtTagU { - clen = 12 - } else { - d.d.errorf("invalid bytes for decoding time as extension: got 0x%x, 0x%x", d.bd, b2) - return - } - } - return d.decodeTime(clen) -} - -func (d *msgpackDecDriver) decodeTime(clen int) (t time.Time) { - // bs = d.r.readx(clen) - d.bdRead = false - switch clen { - case 4: - t = time.Unix(int64(bigen.Uint32(d.r.readx(4))), 0).UTC() - case 8: - tv := bigen.Uint64(d.r.readx(8)) - t = time.Unix(int64(tv&0x00000003ffffffff), int64(tv>>34)).UTC() - case 12: - nsec := bigen.Uint32(d.r.readx(4)) - sec := bigen.Uint64(d.r.readx(8)) - t = time.Unix(int64(sec), int64(nsec)).UTC() - default: - d.d.errorf("invalid length of bytes for decoding time - expecting 4 or 8 or 12, got %d", clen) - return - } - return -} - -func (d *msgpackDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) { - if xtag > 0xff { - d.d.errorf("ext: tag must be <= 0xff; got: %v", xtag) - return - } - realxtag1, xbs := d.decodeExtV(ext != nil, uint8(xtag)) - realxtag = uint64(realxtag1) - if ext == nil { - re := rv.(*RawExt) - re.Tag = realxtag - re.Data = detachZeroCopyBytes(d.br, re.Data, xbs) - } else { - ext.ReadExt(rv, xbs) - } - return -} - -func (d *msgpackDecDriver) decodeExtV(verifyTag bool, tag byte) (xtag byte, xbs []byte) { - if !d.bdRead { - d.readNextBd() - } - xbd := d.bd - if xbd == mpBin8 || xbd == mpBin16 || xbd == mpBin32 { - xbs = d.DecodeBytes(nil, true) - } else if xbd == mpStr8 || xbd == mpStr16 || xbd == mpStr32 || - (xbd >= mpFixStrMin && xbd <= mpFixStrMax) { - xbs = d.DecodeStringAsBytes() - } else { - clen := d.readExtLen() - xtag = d.r.readn1() - if verifyTag && xtag != tag { - d.d.errorf("wrong extension tag - got %b, expecting %v", xtag, tag) - return - } - xbs = d.r.readx(clen) - } - d.bdRead = false - return -} - -//-------------------------------------------------- - -//MsgpackHandle is a Handle for the Msgpack Schema-Free Encoding Format. -type MsgpackHandle struct { - BasicHandle - - // RawToString controls how raw bytes are decoded into a nil interface{}. - RawToString bool - - // NoFixedNum says to output all signed integers as 2-bytes, never as 1-byte fixednum. - NoFixedNum bool - - // WriteExt flag supports encoding configured extensions with extension tags. - // It also controls whether other elements of the new spec are encoded (ie Str8). - // - // With WriteExt=false, configured extensions are serialized as raw bytes - // and Str8 is not encoded. - // - // A stream can still be decoded into a typed value, provided an appropriate value - // is provided, but the type cannot be inferred from the stream. If no appropriate - // type is provided (e.g. decoding into a nil interface{}), you get back - // a []byte or string based on the setting of RawToString. - WriteExt bool - - binaryEncodingType - noElemSeparators - - // _ [1]uint64 // padding -} - -// Name returns the name of the handle: msgpack -func (h *MsgpackHandle) Name() string { return "msgpack" } - -// SetBytesExt sets an extension -func (h *MsgpackHandle) SetBytesExt(rt reflect.Type, tag uint64, ext BytesExt) (err error) { - return h.SetExt(rt, tag, &extWrapper{ext, interfaceExtFailer{}}) -} - -func (h *MsgpackHandle) newEncDriver(e *Encoder) encDriver { - return &msgpackEncDriver{e: e, w: e.w, h: h} -} - -func (h *MsgpackHandle) newDecDriver(d *Decoder) decDriver { - return &msgpackDecDriver{d: d, h: h, r: d.r, br: d.bytes} -} - -func (e *msgpackEncDriver) reset() { - e.w = e.e.w -} - -func (d *msgpackDecDriver) reset() { - d.r, d.br = d.d.r, d.d.bytes - d.bd, d.bdRead = 0, false -} - -//-------------------------------------------------- - -type msgpackSpecRpcCodec struct { - rpcCodec -} - -// /////////////// Spec RPC Codec /////////////////// -func (c *msgpackSpecRpcCodec) WriteRequest(r *rpc.Request, body interface{}) error { - // WriteRequest can write to both a Go service, and other services that do - // not abide by the 1 argument rule of a Go service. - // We discriminate based on if the body is a MsgpackSpecRpcMultiArgs - var bodyArr []interface{} - if m, ok := body.(MsgpackSpecRpcMultiArgs); ok { - bodyArr = ([]interface{})(m) - } else { - bodyArr = []interface{}{body} - } - r2 := []interface{}{0, uint32(r.Seq), r.ServiceMethod, bodyArr} - return c.write(r2, nil, false) -} - -func (c *msgpackSpecRpcCodec) WriteResponse(r *rpc.Response, body interface{}) error { - var moe interface{} - if r.Error != "" { - moe = r.Error - } - if moe != nil && body != nil { - body = nil - } - r2 := []interface{}{1, uint32(r.Seq), moe, body} - return c.write(r2, nil, false) -} - -func (c *msgpackSpecRpcCodec) ReadResponseHeader(r *rpc.Response) error { - return c.parseCustomHeader(1, &r.Seq, &r.Error) -} - -func (c *msgpackSpecRpcCodec) ReadRequestHeader(r *rpc.Request) error { - return c.parseCustomHeader(0, &r.Seq, &r.ServiceMethod) -} - -func (c *msgpackSpecRpcCodec) ReadRequestBody(body interface{}) error { - if body == nil { // read and discard - return c.read(nil) - } - bodyArr := []interface{}{body} - return c.read(&bodyArr) -} - -func (c *msgpackSpecRpcCodec) parseCustomHeader(expectTypeByte byte, msgid *uint64, methodOrError *string) (err error) { - if c.isClosed() { - return io.EOF - } - - // We read the response header by hand - // so that the body can be decoded on its own from the stream at a later time. - - const fia byte = 0x94 //four item array descriptor value - // Not sure why the panic of EOF is swallowed above. - // if bs1 := c.dec.r.readn1(); bs1 != fia { - // err = fmt.Errorf("Unexpected value for array descriptor: Expecting %v. Received %v", fia, bs1) - // return - // } - var ba [1]byte - var n int - for { - n, err = c.r.Read(ba[:]) - if err != nil { - return - } - if n == 1 { - break - } - } - - var b = ba[0] - if b != fia { - err = fmt.Errorf("not array - %s %x/%s", msgBadDesc, b, mpdesc(b)) - } else { - err = c.read(&b) - if err == nil { - if b != expectTypeByte { - err = fmt.Errorf("%s - expecting %v but got %x/%s", - msgBadDesc, expectTypeByte, b, mpdesc(b)) - } else { - err = c.read(msgid) - if err == nil { - err = c.read(methodOrError) - } - } - } - } - return -} - -//-------------------------------------------------- - -// msgpackSpecRpc is the implementation of Rpc that uses custom communication protocol -// as defined in the msgpack spec at https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md -type msgpackSpecRpc struct{} - -// MsgpackSpecRpc implements Rpc using the communication protocol defined in -// the msgpack spec at https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md . -// -// See GoRpc documentation, for information on buffering for better performance. -var MsgpackSpecRpc msgpackSpecRpc - -func (x msgpackSpecRpc) ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec { - return &msgpackSpecRpcCodec{newRPCCodec(conn, h)} -} - -func (x msgpackSpecRpc) ClientCodec(conn io.ReadWriteCloser, h Handle) rpc.ClientCodec { - return &msgpackSpecRpcCodec{newRPCCodec(conn, h)} -} - -var _ decDriver = (*msgpackDecDriver)(nil) -var _ encDriver = (*msgpackEncDriver)(nil) diff --git a/vendor/github.com/ugorji/go/codec/rpc.go b/vendor/github.com/ugorji/go/codec/rpc.go deleted file mode 100644 index 9fb3c0149..000000000 --- a/vendor/github.com/ugorji/go/codec/rpc.go +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -import ( - "bufio" - "errors" - "io" - "net/rpc" - "sync" -) - -// Rpc provides a rpc Server or Client Codec for rpc communication. -type Rpc interface { - ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec - ClientCodec(conn io.ReadWriteCloser, h Handle) rpc.ClientCodec -} - -// RPCOptions holds options specific to rpc functionality -type RPCOptions struct { - // RPCNoBuffer configures whether we attempt to buffer reads and writes during RPC calls. - // - // Set RPCNoBuffer=true to turn buffering off. - // Buffering can still be done if buffered connections are passed in, or - // buffering is configured on the handle. - RPCNoBuffer bool -} - -// rpcCodec defines the struct members and common methods. -type rpcCodec struct { - c io.Closer - r io.Reader - w io.Writer - f ioFlusher - - dec *Decoder - enc *Encoder - // bw *bufio.Writer - // br *bufio.Reader - mu sync.Mutex - h Handle - - cls bool - clsmu sync.RWMutex - clsErr error -} - -func newRPCCodec(conn io.ReadWriteCloser, h Handle) rpcCodec { - // return newRPCCodec2(bufio.NewReader(conn), bufio.NewWriter(conn), conn, h) - return newRPCCodec2(conn, conn, conn, h) -} - -func newRPCCodec2(r io.Reader, w io.Writer, c io.Closer, h Handle) rpcCodec { - // defensive: ensure that jsonH has TermWhitespace turned on. - if jsonH, ok := h.(*JsonHandle); ok && !jsonH.TermWhitespace { - panic(errors.New("rpc requires a JsonHandle with TermWhitespace set to true")) - } - // always ensure that we use a flusher, and always flush what was written to the connection. - // we lose nothing by using a buffered writer internally. - f, ok := w.(ioFlusher) - bh := h.getBasicHandle() - if !bh.RPCNoBuffer { - if bh.WriterBufferSize <= 0 { - if !ok { - bw := bufio.NewWriter(w) - f, w = bw, bw - } - } - if bh.ReaderBufferSize <= 0 { - if _, ok = w.(ioPeeker); !ok { - if _, ok = w.(ioBuffered); !ok { - br := bufio.NewReader(r) - r = br - } - } - } - } - return rpcCodec{ - c: c, - w: w, - r: r, - f: f, - h: h, - enc: NewEncoder(w, h), - dec: NewDecoder(r, h), - } -} - -func (c *rpcCodec) write(obj1, obj2 interface{}, writeObj2 bool) (err error) { - if c.isClosed() { - return c.clsErr - } - err = c.enc.Encode(obj1) - if err == nil { - if writeObj2 { - err = c.enc.Encode(obj2) - } - // if err == nil && c.f != nil { - // err = c.f.Flush() - // } - } - if c.f != nil { - if err == nil { - err = c.f.Flush() - } else { - _ = c.f.Flush() // swallow flush error, so we maintain prior error on write - } - } - return -} - -func (c *rpcCodec) swallow(err *error) { - defer panicToErr(c.dec, err) - c.dec.swallow() -} - -func (c *rpcCodec) read(obj interface{}) (err error) { - if c.isClosed() { - return c.clsErr - } - //If nil is passed in, we should read and discard - if obj == nil { - // var obj2 interface{} - // return c.dec.Decode(&obj2) - c.swallow(&err) - return - } - return c.dec.Decode(obj) -} - -func (c *rpcCodec) isClosed() (b bool) { - if c.c != nil { - c.clsmu.RLock() - b = c.cls - c.clsmu.RUnlock() - } - return -} - -func (c *rpcCodec) Close() error { - if c.c == nil || c.isClosed() { - return c.clsErr - } - c.clsmu.Lock() - c.cls = true - c.clsErr = c.c.Close() - c.clsmu.Unlock() - return c.clsErr -} - -func (c *rpcCodec) ReadResponseBody(body interface{}) error { - return c.read(body) -} - -// ------------------------------------- - -type goRpcCodec struct { - rpcCodec -} - -func (c *goRpcCodec) WriteRequest(r *rpc.Request, body interface{}) error { - // Must protect for concurrent access as per API - c.mu.Lock() - defer c.mu.Unlock() - return c.write(r, body, true) -} - -func (c *goRpcCodec) WriteResponse(r *rpc.Response, body interface{}) error { - c.mu.Lock() - defer c.mu.Unlock() - return c.write(r, body, true) -} - -func (c *goRpcCodec) ReadResponseHeader(r *rpc.Response) error { - return c.read(r) -} - -func (c *goRpcCodec) ReadRequestHeader(r *rpc.Request) error { - return c.read(r) -} - -func (c *goRpcCodec) ReadRequestBody(body interface{}) error { - return c.read(body) -} - -// ------------------------------------- - -// goRpc is the implementation of Rpc that uses the communication protocol -// as defined in net/rpc package. -type goRpc struct{} - -// GoRpc implements Rpc using the communication protocol defined in net/rpc package. -// -// Note: network connection (from net.Dial, of type io.ReadWriteCloser) is not buffered. -// -// For performance, you should configure WriterBufferSize and ReaderBufferSize on the handle. -// This ensures we use an adequate buffer during reading and writing. -// If not configured, we will internally initialize and use a buffer during reads and writes. -// This can be turned off via the RPCNoBuffer option on the Handle. -// var handle codec.JsonHandle -// handle.RPCNoBuffer = true // turns off attempt by rpc module to initialize a buffer -// -// Example 1: one way of configuring buffering explicitly: -// var handle codec.JsonHandle // codec handle -// handle.ReaderBufferSize = 1024 -// handle.WriterBufferSize = 1024 -// var conn io.ReadWriteCloser // connection got from a socket -// var serverCodec = GoRpc.ServerCodec(conn, handle) -// var clientCodec = GoRpc.ClientCodec(conn, handle) -// -// Example 2: you can also explicitly create a buffered connection yourself, -// and not worry about configuring the buffer sizes in the Handle. -// var handle codec.Handle // codec handle -// var conn io.ReadWriteCloser // connection got from a socket -// var bufconn = struct { // bufconn here is a buffered io.ReadWriteCloser -// io.Closer -// *bufio.Reader -// *bufio.Writer -// }{conn, bufio.NewReader(conn), bufio.NewWriter(conn)} -// var serverCodec = GoRpc.ServerCodec(bufconn, handle) -// var clientCodec = GoRpc.ClientCodec(bufconn, handle) -// -var GoRpc goRpc - -func (x goRpc) ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec { - return &goRpcCodec{newRPCCodec(conn, h)} -} - -func (x goRpc) ClientCodec(conn io.ReadWriteCloser, h Handle) rpc.ClientCodec { - return &goRpcCodec{newRPCCodec(conn, h)} -} diff --git a/vendor/github.com/ugorji/go/codec/simple.go b/vendor/github.com/ugorji/go/codec/simple.go deleted file mode 100644 index f1e181ef3..000000000 --- a/vendor/github.com/ugorji/go/codec/simple.go +++ /dev/null @@ -1,652 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -import ( - "math" - "reflect" - "time" -) - -const ( - _ uint8 = iota - simpleVdNil = 1 - simpleVdFalse = 2 - simpleVdTrue = 3 - simpleVdFloat32 = 4 - simpleVdFloat64 = 5 - - // each lasts for 4 (ie n, n+1, n+2, n+3) - simpleVdPosInt = 8 - simpleVdNegInt = 12 - - simpleVdTime = 24 - - // containers: each lasts for 4 (ie n, n+1, n+2, ... n+7) - simpleVdString = 216 - simpleVdByteArray = 224 - simpleVdArray = 232 - simpleVdMap = 240 - simpleVdExt = 248 -) - -type simpleEncDriver struct { - noBuiltInTypes - // encNoSeparator - e *Encoder - h *SimpleHandle - w encWriter - b [8]byte - // c containerState - encDriverTrackContainerWriter - // encDriverNoopContainerWriter - _ [2]uint64 // padding -} - -func (e *simpleEncDriver) EncodeNil() { - e.w.writen1(simpleVdNil) -} - -func (e *simpleEncDriver) EncodeBool(b bool) { - if e.h.EncZeroValuesAsNil && e.c != containerMapKey && !b { - e.EncodeNil() - return - } - if b { - e.w.writen1(simpleVdTrue) - } else { - e.w.writen1(simpleVdFalse) - } -} - -func (e *simpleEncDriver) EncodeFloat32(f float32) { - if e.h.EncZeroValuesAsNil && e.c != containerMapKey && f == 0.0 { - e.EncodeNil() - return - } - e.w.writen1(simpleVdFloat32) - bigenHelper{e.b[:4], e.w}.writeUint32(math.Float32bits(f)) -} - -func (e *simpleEncDriver) EncodeFloat64(f float64) { - if e.h.EncZeroValuesAsNil && e.c != containerMapKey && f == 0.0 { - e.EncodeNil() - return - } - e.w.writen1(simpleVdFloat64) - bigenHelper{e.b[:8], e.w}.writeUint64(math.Float64bits(f)) -} - -func (e *simpleEncDriver) EncodeInt(v int64) { - if v < 0 { - e.encUint(uint64(-v), simpleVdNegInt) - } else { - e.encUint(uint64(v), simpleVdPosInt) - } -} - -func (e *simpleEncDriver) EncodeUint(v uint64) { - e.encUint(v, simpleVdPosInt) -} - -func (e *simpleEncDriver) encUint(v uint64, bd uint8) { - if e.h.EncZeroValuesAsNil && e.c != containerMapKey && v == 0 { - e.EncodeNil() - return - } - if v <= math.MaxUint8 { - e.w.writen2(bd, uint8(v)) - } else if v <= math.MaxUint16 { - e.w.writen1(bd + 1) - bigenHelper{e.b[:2], e.w}.writeUint16(uint16(v)) - } else if v <= math.MaxUint32 { - e.w.writen1(bd + 2) - bigenHelper{e.b[:4], e.w}.writeUint32(uint32(v)) - } else { // if v <= math.MaxUint64 { - e.w.writen1(bd + 3) - bigenHelper{e.b[:8], e.w}.writeUint64(v) - } -} - -func (e *simpleEncDriver) encLen(bd byte, length int) { - if length == 0 { - e.w.writen1(bd) - } else if length <= math.MaxUint8 { - e.w.writen1(bd + 1) - e.w.writen1(uint8(length)) - } else if length <= math.MaxUint16 { - e.w.writen1(bd + 2) - bigenHelper{e.b[:2], e.w}.writeUint16(uint16(length)) - } else if int64(length) <= math.MaxUint32 { - e.w.writen1(bd + 3) - bigenHelper{e.b[:4], e.w}.writeUint32(uint32(length)) - } else { - e.w.writen1(bd + 4) - bigenHelper{e.b[:8], e.w}.writeUint64(uint64(length)) - } -} - -func (e *simpleEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, _ *Encoder) { - bs := ext.WriteExt(rv) - if bs == nil { - e.EncodeNil() - return - } - e.encodeExtPreamble(uint8(xtag), len(bs)) - e.w.writeb(bs) -} - -func (e *simpleEncDriver) EncodeRawExt(re *RawExt, _ *Encoder) { - e.encodeExtPreamble(uint8(re.Tag), len(re.Data)) - e.w.writeb(re.Data) -} - -func (e *simpleEncDriver) encodeExtPreamble(xtag byte, length int) { - e.encLen(simpleVdExt, length) - e.w.writen1(xtag) -} - -func (e *simpleEncDriver) WriteArrayStart(length int) { - e.c = containerArrayStart - e.encLen(simpleVdArray, length) -} - -func (e *simpleEncDriver) WriteMapStart(length int) { - e.c = containerMapStart - e.encLen(simpleVdMap, length) -} - -func (e *simpleEncDriver) EncodeString(c charEncoding, v string) { - if false && e.h.EncZeroValuesAsNil && e.c != containerMapKey && v == "" { - e.EncodeNil() - return - } - e.encLen(simpleVdString, len(v)) - e.w.writestr(v) -} - -// func (e *simpleEncDriver) EncodeSymbol(v string) { -// e.EncodeString(cUTF8, v) -// } - -func (e *simpleEncDriver) EncodeStringBytes(c charEncoding, v []byte) { - // if e.h.EncZeroValuesAsNil && e.c != containerMapKey && v == nil { - if v == nil { - e.EncodeNil() - return - } - e.encLen(simpleVdByteArray, len(v)) - e.w.writeb(v) -} - -func (e *simpleEncDriver) EncodeTime(t time.Time) { - // if e.h.EncZeroValuesAsNil && e.c != containerMapKey && t.IsZero() { - if t.IsZero() { - e.EncodeNil() - return - } - v, err := t.MarshalBinary() - if err != nil { - e.e.errorv(err) - return - } - // time.Time marshalbinary takes about 14 bytes. - e.w.writen2(simpleVdTime, uint8(len(v))) - e.w.writeb(v) -} - -//------------------------------------ - -type simpleDecDriver struct { - d *Decoder - h *SimpleHandle - r decReader - bdRead bool - bd byte - br bool // a bytes reader? - c containerState - // b [scratchByteArrayLen]byte - noBuiltInTypes - // noStreamingCodec - decDriverNoopContainerReader - _ [3]uint64 // padding -} - -func (d *simpleDecDriver) readNextBd() { - d.bd = d.r.readn1() - d.bdRead = true -} - -func (d *simpleDecDriver) uncacheRead() { - if d.bdRead { - d.r.unreadn1() - d.bdRead = false - } -} - -func (d *simpleDecDriver) ContainerType() (vt valueType) { - if !d.bdRead { - d.readNextBd() - } - switch d.bd { - case simpleVdNil: - return valueTypeNil - case simpleVdByteArray, simpleVdByteArray + 1, - simpleVdByteArray + 2, simpleVdByteArray + 3, simpleVdByteArray + 4: - return valueTypeBytes - case simpleVdString, simpleVdString + 1, - simpleVdString + 2, simpleVdString + 3, simpleVdString + 4: - return valueTypeString - case simpleVdArray, simpleVdArray + 1, - simpleVdArray + 2, simpleVdArray + 3, simpleVdArray + 4: - return valueTypeArray - case simpleVdMap, simpleVdMap + 1, - simpleVdMap + 2, simpleVdMap + 3, simpleVdMap + 4: - return valueTypeMap - // case simpleVdTime: - // return valueTypeTime - } - // else { - // d.d.errorf("isContainerType: unsupported parameter: %v", vt) - // } - return valueTypeUnset -} - -func (d *simpleDecDriver) TryDecodeAsNil() bool { - if !d.bdRead { - d.readNextBd() - } - if d.bd == simpleVdNil { - d.bdRead = false - return true - } - return false -} - -func (d *simpleDecDriver) decCheckInteger() (ui uint64, neg bool) { - if !d.bdRead { - d.readNextBd() - } - switch d.bd { - case simpleVdPosInt: - ui = uint64(d.r.readn1()) - case simpleVdPosInt + 1: - ui = uint64(bigen.Uint16(d.r.readx(2))) - case simpleVdPosInt + 2: - ui = uint64(bigen.Uint32(d.r.readx(4))) - case simpleVdPosInt + 3: - ui = uint64(bigen.Uint64(d.r.readx(8))) - case simpleVdNegInt: - ui = uint64(d.r.readn1()) - neg = true - case simpleVdNegInt + 1: - ui = uint64(bigen.Uint16(d.r.readx(2))) - neg = true - case simpleVdNegInt + 2: - ui = uint64(bigen.Uint32(d.r.readx(4))) - neg = true - case simpleVdNegInt + 3: - ui = uint64(bigen.Uint64(d.r.readx(8))) - neg = true - default: - d.d.errorf("integer only valid from pos/neg integer1..8. Invalid descriptor: %v", d.bd) - return - } - // don't do this check, because callers may only want the unsigned value. - // if ui > math.MaxInt64 { - // d.d.errorf("decIntAny: Integer out of range for signed int64: %v", ui) - // return - // } - return -} - -func (d *simpleDecDriver) DecodeInt64() (i int64) { - ui, neg := d.decCheckInteger() - i = chkOvf.SignedIntV(ui) - if neg { - i = -i - } - d.bdRead = false - return -} - -func (d *simpleDecDriver) DecodeUint64() (ui uint64) { - ui, neg := d.decCheckInteger() - if neg { - d.d.errorf("assigning negative signed value to unsigned type") - return - } - d.bdRead = false - return -} - -func (d *simpleDecDriver) DecodeFloat64() (f float64) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == simpleVdFloat32 { - f = float64(math.Float32frombits(bigen.Uint32(d.r.readx(4)))) - } else if d.bd == simpleVdFloat64 { - f = math.Float64frombits(bigen.Uint64(d.r.readx(8))) - } else { - if d.bd >= simpleVdPosInt && d.bd <= simpleVdNegInt+3 { - f = float64(d.DecodeInt64()) - } else { - d.d.errorf("float only valid from float32/64: Invalid descriptor: %v", d.bd) - return - } - } - d.bdRead = false - return -} - -// bool can be decoded from bool only (single byte). -func (d *simpleDecDriver) DecodeBool() (b bool) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == simpleVdTrue { - b = true - } else if d.bd == simpleVdFalse { - } else { - d.d.errorf("cannot decode bool - %s: %x", msgBadDesc, d.bd) - return - } - d.bdRead = false - return -} - -func (d *simpleDecDriver) ReadMapStart() (length int) { - if !d.bdRead { - d.readNextBd() - } - d.bdRead = false - d.c = containerMapStart - return d.decLen() -} - -func (d *simpleDecDriver) ReadArrayStart() (length int) { - if !d.bdRead { - d.readNextBd() - } - d.bdRead = false - d.c = containerArrayStart - return d.decLen() -} - -func (d *simpleDecDriver) ReadArrayElem() { - d.c = containerArrayElem -} - -func (d *simpleDecDriver) ReadArrayEnd() { - d.c = containerArrayEnd -} - -func (d *simpleDecDriver) ReadMapElemKey() { - d.c = containerMapKey -} - -func (d *simpleDecDriver) ReadMapElemValue() { - d.c = containerMapValue -} - -func (d *simpleDecDriver) ReadMapEnd() { - d.c = containerMapEnd -} - -func (d *simpleDecDriver) decLen() int { - switch d.bd % 8 { - case 0: - return 0 - case 1: - return int(d.r.readn1()) - case 2: - return int(bigen.Uint16(d.r.readx(2))) - case 3: - ui := uint64(bigen.Uint32(d.r.readx(4))) - if chkOvf.Uint(ui, intBitsize) { - d.d.errorf("overflow integer: %v", ui) - return 0 - } - return int(ui) - case 4: - ui := bigen.Uint64(d.r.readx(8)) - if chkOvf.Uint(ui, intBitsize) { - d.d.errorf("overflow integer: %v", ui) - return 0 - } - return int(ui) - } - d.d.errorf("cannot read length: bd%%8 must be in range 0..4. Got: %d", d.bd%8) - return -1 -} - -func (d *simpleDecDriver) DecodeString() (s string) { - return string(d.DecodeBytes(d.d.b[:], true)) -} - -func (d *simpleDecDriver) DecodeStringAsBytes() (s []byte) { - return d.DecodeBytes(d.d.b[:], true) -} - -func (d *simpleDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == simpleVdNil { - d.bdRead = false - return - } - // check if an "array" of uint8's (see ContainerType for how to infer if an array) - if d.bd >= simpleVdArray && d.bd <= simpleVdMap+4 { - if len(bs) == 0 && zerocopy { - bs = d.d.b[:] - } - bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d) - return - } - - clen := d.decLen() - d.bdRead = false - if zerocopy { - if d.br { - return d.r.readx(clen) - } else if len(bs) == 0 { - bs = d.d.b[:] - } - } - return decByteSlice(d.r, clen, d.d.h.MaxInitLen, bs) -} - -func (d *simpleDecDriver) DecodeTime() (t time.Time) { - if !d.bdRead { - d.readNextBd() - } - if d.bd == simpleVdNil { - d.bdRead = false - return - } - if d.bd != simpleVdTime { - d.d.errorf("invalid descriptor for time.Time - expect 0x%x, received 0x%x", simpleVdTime, d.bd) - return - } - d.bdRead = false - clen := int(d.r.readn1()) - b := d.r.readx(clen) - if err := (&t).UnmarshalBinary(b); err != nil { - d.d.errorv(err) - } - return -} - -func (d *simpleDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) { - if xtag > 0xff { - d.d.errorf("ext: tag must be <= 0xff; got: %v", xtag) - return - } - realxtag1, xbs := d.decodeExtV(ext != nil, uint8(xtag)) - realxtag = uint64(realxtag1) - if ext == nil { - re := rv.(*RawExt) - re.Tag = realxtag - re.Data = detachZeroCopyBytes(d.br, re.Data, xbs) - } else { - ext.ReadExt(rv, xbs) - } - return -} - -func (d *simpleDecDriver) decodeExtV(verifyTag bool, tag byte) (xtag byte, xbs []byte) { - if !d.bdRead { - d.readNextBd() - } - switch d.bd { - case simpleVdExt, simpleVdExt + 1, simpleVdExt + 2, simpleVdExt + 3, simpleVdExt + 4: - l := d.decLen() - xtag = d.r.readn1() - if verifyTag && xtag != tag { - d.d.errorf("wrong extension tag. Got %b. Expecting: %v", xtag, tag) - return - } - xbs = d.r.readx(l) - case simpleVdByteArray, simpleVdByteArray + 1, - simpleVdByteArray + 2, simpleVdByteArray + 3, simpleVdByteArray + 4: - xbs = d.DecodeBytes(nil, true) - default: - d.d.errorf("ext - %s - expecting extensions/bytearray, got: 0x%x", msgBadDesc, d.bd) - return - } - d.bdRead = false - return -} - -func (d *simpleDecDriver) DecodeNaked() { - if !d.bdRead { - d.readNextBd() - } - - n := d.d.n - var decodeFurther bool - - switch d.bd { - case simpleVdNil: - n.v = valueTypeNil - case simpleVdFalse: - n.v = valueTypeBool - n.b = false - case simpleVdTrue: - n.v = valueTypeBool - n.b = true - case simpleVdPosInt, simpleVdPosInt + 1, simpleVdPosInt + 2, simpleVdPosInt + 3: - if d.h.SignedInteger { - n.v = valueTypeInt - n.i = d.DecodeInt64() - } else { - n.v = valueTypeUint - n.u = d.DecodeUint64() - } - case simpleVdNegInt, simpleVdNegInt + 1, simpleVdNegInt + 2, simpleVdNegInt + 3: - n.v = valueTypeInt - n.i = d.DecodeInt64() - case simpleVdFloat32: - n.v = valueTypeFloat - n.f = d.DecodeFloat64() - case simpleVdFloat64: - n.v = valueTypeFloat - n.f = d.DecodeFloat64() - case simpleVdTime: - n.v = valueTypeTime - n.t = d.DecodeTime() - case simpleVdString, simpleVdString + 1, - simpleVdString + 2, simpleVdString + 3, simpleVdString + 4: - n.v = valueTypeString - n.s = d.DecodeString() - case simpleVdByteArray, simpleVdByteArray + 1, - simpleVdByteArray + 2, simpleVdByteArray + 3, simpleVdByteArray + 4: - n.v = valueTypeBytes - n.l = d.DecodeBytes(nil, false) - case simpleVdExt, simpleVdExt + 1, simpleVdExt + 2, simpleVdExt + 3, simpleVdExt + 4: - n.v = valueTypeExt - l := d.decLen() - n.u = uint64(d.r.readn1()) - n.l = d.r.readx(l) - case simpleVdArray, simpleVdArray + 1, simpleVdArray + 2, - simpleVdArray + 3, simpleVdArray + 4: - n.v = valueTypeArray - decodeFurther = true - case simpleVdMap, simpleVdMap + 1, simpleVdMap + 2, simpleVdMap + 3, simpleVdMap + 4: - n.v = valueTypeMap - decodeFurther = true - default: - d.d.errorf("cannot infer value - %s 0x%x", msgBadDesc, d.bd) - } - - if !decodeFurther { - d.bdRead = false - } - return -} - -//------------------------------------ - -// SimpleHandle is a Handle for a very simple encoding format. -// -// simple is a simplistic codec similar to binc, but not as compact. -// - Encoding of a value is always preceded by the descriptor byte (bd) -// - True, false, nil are encoded fully in 1 byte (the descriptor) -// - Integers (intXXX, uintXXX) are encoded in 1, 2, 4 or 8 bytes (plus a descriptor byte). -// There are positive (uintXXX and intXXX >= 0) and negative (intXXX < 0) integers. -// - Floats are encoded in 4 or 8 bytes (plus a descriptor byte) -// - Length of containers (strings, bytes, array, map, extensions) -// are encoded in 0, 1, 2, 4 or 8 bytes. -// Zero-length containers have no length encoded. -// For others, the number of bytes is given by pow(2, bd%3) -// - maps are encoded as [bd] [length] [[key][value]]... -// - arrays are encoded as [bd] [length] [value]... -// - extensions are encoded as [bd] [length] [tag] [byte]... -// - strings/bytearrays are encoded as [bd] [length] [byte]... -// - time.Time are encoded as [bd] [length] [byte]... -// -// The full spec will be published soon. -type SimpleHandle struct { - BasicHandle - binaryEncodingType - noElemSeparators - // EncZeroValuesAsNil says to encode zero values for numbers, bool, string, etc as nil - EncZeroValuesAsNil bool - - // _ [1]uint64 // padding -} - -// Name returns the name of the handle: simple -func (h *SimpleHandle) Name() string { return "simple" } - -// SetBytesExt sets an extension -func (h *SimpleHandle) SetBytesExt(rt reflect.Type, tag uint64, ext BytesExt) (err error) { - return h.SetExt(rt, tag, &extWrapper{ext, interfaceExtFailer{}}) -} - -func (h *SimpleHandle) hasElemSeparators() bool { return true } // as it implements Write(Map|Array)XXX - -func (h *SimpleHandle) newEncDriver(e *Encoder) encDriver { - return &simpleEncDriver{e: e, w: e.w, h: h} -} - -func (h *SimpleHandle) newDecDriver(d *Decoder) decDriver { - return &simpleDecDriver{d: d, h: h, r: d.r, br: d.bytes} -} - -func (e *simpleEncDriver) reset() { - e.c = 0 - e.w = e.e.w -} - -func (d *simpleDecDriver) reset() { - d.c = 0 - d.r, d.br = d.d.r, d.d.bytes - d.bd, d.bdRead = 0, false -} - -var _ decDriver = (*simpleDecDriver)(nil) -var _ encDriver = (*simpleEncDriver)(nil) diff --git a/vendor/github.com/ugorji/go/codec/xml.go b/vendor/github.com/ugorji/go/codec/xml.go deleted file mode 100644 index 19fc36caf..000000000 --- a/vendor/github.com/ugorji/go/codec/xml.go +++ /dev/null @@ -1,508 +0,0 @@ -// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// +build ignore - -package codec - -import "reflect" - -/* - -A strict Non-validating namespace-aware XML 1.0 parser and (en|de)coder. - -We are attempting this due to perceived issues with encoding/xml: - - Complicated. It tried to do too much, and is not as simple to use as json. - - Due to over-engineering, reflection is over-used AND performance suffers: - java is 6X faster:http://fabsk.eu/blog/category/informatique/dev/golang/ - even PYTHON performs better: http://outgoing.typepad.com/outgoing/2014/07/exploring-golang.html - -codec framework will offer the following benefits - - VASTLY improved performance (when using reflection-mode or codecgen) - - simplicity and consistency: with the rest of the supported formats - - all other benefits of codec framework (streaming, codegeneration, etc) - -codec is not a drop-in replacement for encoding/xml. -It is a replacement, based on the simplicity and performance of codec. -Look at it like JAXB for Go. - -Challenges: - - Need to output XML preamble, with all namespaces at the right location in the output. - - Each "end" block is dynamic, so we need to maintain a context-aware stack - - How to decide when to use an attribute VS an element - - How to handle chardata, attr, comment EXPLICITLY. - - Should it output fragments? - e.g. encoding a bool should just output true OR false, which is not well-formed XML. - -Extend the struct tag. See representative example: - type X struct { - ID uint8 `codec:"http://ugorji.net/x-namespace xid id,omitempty,toarray,attr,cdata"` - // format: [namespace-uri ][namespace-prefix ]local-name, ... - } - -Based on this, we encode - - fields as elements, BUT - encode as attributes if struct tag contains ",attr" and is a scalar (bool, number or string) - - text as entity-escaped text, BUT encode as CDATA if struct tag contains ",cdata". - -To handle namespaces: - - XMLHandle is denoted as being namespace-aware. - Consequently, we WILL use the ns:name pair to encode and decode if defined, else use the plain name. - - *Encoder and *Decoder know whether the Handle "prefers" namespaces. - - add *Encoder.getEncName(*structFieldInfo). - No one calls *structFieldInfo.indexForEncName directly anymore - - OR better yet: indexForEncName is namespace-aware, and helper.go is all namespace-aware - indexForEncName takes a parameter of the form namespace:local-name OR local-name - - add *Decoder.getStructFieldInfo(encName string) // encName here is either like abc, or h1:nsabc - by being a method on *Decoder, or maybe a method on the Handle itself. - No one accesses .encName anymore - - let encode.go and decode.go use these (for consistency) - - only problem exists for gen.go, where we create a big switch on encName. - Now, we also have to add a switch on strings.endsWith(kName, encNsName) - - gen.go will need to have many more methods, and then double-on the 2 switch loops like: - switch k { - case "abc" : x.abc() - case "def" : x.def() - default { - switch { - case !nsAware: panic(...) - case strings.endsWith(":abc"): x.abc() - case strings.endsWith(":def"): x.def() - default: panic(...) - } - } - } - -The structure below accommodates this: - - type typeInfo struct { - sfi []*structFieldInfo // sorted by encName - sfins // sorted by namespace - sfia // sorted, to have those with attributes at the top. Needed to write XML appropriately. - sfip // unsorted - } - type structFieldInfo struct { - encName - nsEncName - ns string - attr bool - cdata bool - } - -indexForEncName is now an internal helper function that takes a sorted array -(one of ti.sfins or ti.sfi). It is only used by *Encoder.getStructFieldInfo(...) - -There will be a separate parser from the builder. -The parser will have a method: next() xmlToken method. It has lookahead support, -so you can pop multiple tokens, make a determination, and push them back in the order popped. -This will be needed to determine whether we are "nakedly" decoding a container or not. -The stack will be implemented using a slice and push/pop happens at the [0] element. - -xmlToken has fields: - - type uint8: 0 | ElementStart | ElementEnd | AttrKey | AttrVal | Text - - value string - - ns string - -SEE: http://www.xml.com/pub/a/98/10/guide0.html?page=3#ENTDECL - -The following are skipped when parsing: - - External Entities (from external file) - - Notation Declaration e.g. - - Entity Declarations & References - - XML Declaration (assume UTF-8) - - XML Directive i.e. - - Other Declarations: Notation, etc. - - Comment - - Processing Instruction - - schema / DTD for validation: - We are not a VALIDATING parser. Validation is done elsewhere. - However, some parts of the DTD internal subset are used (SEE BELOW). - For Attribute List Declarations e.g. - - We considered using the ATTLIST to get "default" value, but not to validate the contents. (VETOED) - -The following XML features are supported - - Namespace - - Element - - Attribute - - cdata - - Unicode escape - -The following DTD (when as an internal sub-set) features are supported: - - Internal Entities e.g. - AND entities for the set: [<>&"'] - - Parameter entities e.g. - - -At decode time, a structure containing the following is kept - - namespace mapping - - default attribute values - - all internal entities (<>&"' and others written in the document) - -When decode starts, it parses XML namespace declarations and creates a map in the -xmlDecDriver. While parsing, that map continuously gets updated. -The only problem happens when a namespace declaration happens on the node that it defines. -e.g. -To handle this, each Element must be fully parsed at a time, -even if it amounts to multiple tokens which are returned one at a time on request. - -xmlns is a special attribute name. - - It is used to define namespaces, including the default - - It is never returned as an AttrKey or AttrVal. - *We may decide later to allow user to use it e.g. you want to parse the xmlns mappings into a field.* - -Number, bool, null, mapKey, etc can all be decoded from any xmlToken. -This accommodates map[int]string for example. - -It should be possible to create a schema from the types, -or vice versa (generate types from schema with appropriate tags). -This is however out-of-scope from this parsing project. - -We should write all namespace information at the first point that it is referenced in the tree, -and use the mapping for all child nodes and attributes. This means that state is maintained -at a point in the tree. This also means that calls to Decode or MustDecode will reset some state. - -When decoding, it is important to keep track of entity references and default attribute values. -It seems these can only be stored in the DTD components. We should honor them when decoding. - -Configuration for XMLHandle will look like this: - - XMLHandle - DefaultNS string - // Encoding: - NS map[string]string // ns URI to key, used for encoding - // Decoding: in case ENTITY declared in external schema or dtd, store info needed here - Entities map[string]string // map of entity rep to character - - -During encode, if a namespace mapping is not defined for a namespace found on a struct, -then we create a mapping for it using nsN (where N is 1..1000000, and doesn't conflict -with any other namespace mapping). - -Note that different fields in a struct can have different namespaces. -However, all fields will default to the namespace on the _struct field (if defined). - -An XML document is a name, a map of attributes and a list of children. -Consequently, we cannot "DecodeNaked" into a map[string]interface{} (for example). -We have to "DecodeNaked" into something that resembles XML data. - -To support DecodeNaked (decode into nil interface{}), we have to define some "supporting" types: - type Name struct { // Preferred. Less allocations due to conversions. - Local string - Space string - } - type Element struct { - Name Name - Attrs map[Name]string - Children []interface{} // each child is either *Element or string - } -Only two "supporting" types are exposed for XML: Name and Element. - -// ------------------ - -We considered 'type Name string' where Name is like "Space Local" (space-separated). -We decided against it, because each creation of a name would lead to -double allocation (first convert []byte to string, then concatenate them into a string). -The benefit is that it is faster to read Attrs from a map. But given that Element is a value -object, we want to eschew methods and have public exposed variables. - -We also considered the following, where xml types were not value objects, and we used -intelligent accessor methods to extract information and for performance. -*** WE DECIDED AGAINST THIS. *** - type Attr struct { - Name Name - Value string - } - // Element is a ValueObject: There are no accessor methods. - // Make element self-contained. - type Element struct { - Name Name - attrsMap map[string]string // where key is "Space Local" - attrs []Attr - childrenT []string - childrenE []Element - childrenI []int // each child is a index into T or E. - } - func (x *Element) child(i) interface{} // returns string or *Element - -// ------------------ - -Per XML spec and our default handling, white space is always treated as -insignificant between elements, except in a text node. The xml:space='preserve' -attribute is ignored. - -**Note: there is no xml: namespace. The xml: attributes were defined before namespaces.** -**So treat them as just "directives" that should be interpreted to mean something**. - -On encoding, we support indenting aka prettifying markup in the same way we support it for json. - -A document or element can only be encoded/decoded from/to a struct. In this mode: - - struct name maps to element name (or tag-info from _struct field) - - fields are mapped to child elements or attributes - -A map is either encoded as attributes on current element, or as a set of child elements. -Maps are encoded as attributes iff their keys and values are primitives (number, bool, string). - -A list is encoded as a set of child elements. - -Primitives (number, bool, string) are encoded as an element, attribute or text -depending on the context. - -Extensions must encode themselves as a text string. - -Encoding is tough, specifically when encoding mappings, because we need to encode -as either attribute or element. To do this, we need to default to encoding as attributes, -and then let Encoder inform the Handle when to start encoding as nodes. -i.e. Encoder does something like: - - h.EncodeMapStart() - h.Encode(), h.Encode(), ... - h.EncodeMapNotAttrSignal() // this is not a bool, because it's a signal - h.Encode(), h.Encode(), ... - h.EncodeEnd() - -Only XMLHandle understands this, and will set itself to start encoding as elements. - -This support extends to maps. For example, if a struct field is a map, and it has -the struct tag signifying it should be attr, then all its fields are encoded as attributes. -e.g. - - type X struct { - M map[string]int `codec:"m,attr"` // encode keys as attributes named - } - -Question: - - if encoding a map, what if map keys have spaces in them??? - Then they cannot be attributes or child elements. Error. - -Options to consider adding later: - - For attribute values, normalize by trimming beginning and ending white space, - and converting every white space sequence to a single space. - - ATTLIST restrictions are enforced. - e.g. default value of xml:space, skipping xml:XYZ style attributes, etc. - - Consider supporting NON-STRICT mode (e.g. to handle HTML parsing). - Some elements e.g. br, hr, etc need not close and should be auto-closed - ... (see http://www.w3.org/TR/html4/loose.dtd) - An expansive set of entities are pre-defined. - - Have easy way to create a HTML parser: - add a HTML() method to XMLHandle, that will set Strict=false, specify AutoClose, - and add HTML Entities to the list. - - Support validating element/attribute XMLName before writing it. - Keep this behind a flag, which is set to false by default (for performance). - type XMLHandle struct { - CheckName bool - } - -Misc: - -ROADMAP (1 weeks): - - build encoder (1 day) - - build decoder (based off xmlParser) (1 day) - - implement xmlParser (2 days). - Look at encoding/xml for inspiration. - - integrate and TEST (1 days) - - write article and post it (1 day) - -// ---------- MORE NOTES FROM 2017-11-30 ------------ - -when parsing -- parse the attributes first -- then parse the nodes - -basically: -- if encoding a field: we use the field name for the wrapper -- if encoding a non-field, then just use the element type name - - map[string]string ==> abcval... or - val... OR - val1val2... <- PREFERED - []string ==> v1v2... - string v1 ==> v1 - bool true ==> true - float 1.0 ==> 1.0 - ... - - F1 map[string]string ==> abcval... OR - val... OR - val... <- PREFERED - F2 []string ==> v1v2... - F3 bool ==> true - ... - -- a scalar is encoded as: - (value) of type T ==> - (value) of field F ==> -- A kv-pair is encoded as: - (key,value) ==> OR - (key,value) of field F ==> OR -- A map or struct is just a list of kv-pairs -- A list is encoded as sequences of same node e.g. - - - value21 - value22 -- we may have to singularize the field name, when entering into xml, - and pluralize them when encoding. -- bi-directional encode->decode->encode is not a MUST. - even encoding/xml cannot decode correctly what was encoded: - - see https://play.golang.org/p/224V_nyhMS - func main() { - fmt.Println("Hello, playground") - v := []interface{}{"hello", 1, true, nil, time.Now()} - s, err := xml.Marshal(v) - fmt.Printf("err: %v, \ns: %s\n", err, s) - var v2 []interface{} - err = xml.Unmarshal(s, &v2) - fmt.Printf("err: %v, \nv2: %v\n", err, v2) - type T struct { - V []interface{} - } - v3 := T{V: v} - s, err = xml.Marshal(v3) - fmt.Printf("err: %v, \ns: %s\n", err, s) - var v4 T - err = xml.Unmarshal(s, &v4) - fmt.Printf("err: %v, \nv4: %v\n", err, v4) - } - Output: - err: , - s: hello1true - err: , - v2: [] - err: , - s: hello1true2009-11-10T23:00:00Z - err: , - v4: {[ ]} -- -*/ - -// ----------- PARSER ------------------- - -type xmlTokenType uint8 - -const ( - _ xmlTokenType = iota << 1 - xmlTokenElemStart - xmlTokenElemEnd - xmlTokenAttrKey - xmlTokenAttrVal - xmlTokenText -) - -type xmlToken struct { - Type xmlTokenType - Value string - Namespace string // blank for AttrVal and Text -} - -type xmlParser struct { - r decReader - toks []xmlToken // list of tokens. - ptr int // ptr into the toks slice - done bool // nothing else to parse. r now returns EOF. -} - -func (x *xmlParser) next() (t *xmlToken) { - // once x.done, or x.ptr == len(x.toks) == 0, then return nil (to signify finish) - if !x.done && len(x.toks) == 0 { - x.nextTag() - } - // parses one element at a time (into possible many tokens) - if x.ptr < len(x.toks) { - t = &(x.toks[x.ptr]) - x.ptr++ - if x.ptr == len(x.toks) { - x.ptr = 0 - x.toks = x.toks[:0] - } - } - return -} - -// nextTag will parses the next element and fill up toks. -// It set done flag if/once EOF is reached. -func (x *xmlParser) nextTag() { - // TODO: implement. -} - -// ----------- ENCODER ------------------- - -type xmlEncDriver struct { - e *Encoder - w encWriter - h *XMLHandle - b [64]byte // scratch - bs []byte // scratch - // s jsonStack - noBuiltInTypes -} - -// ----------- DECODER ------------------- - -type xmlDecDriver struct { - d *Decoder - h *XMLHandle - r decReader // *bytesDecReader decReader - ct valueType // container type. one of unset, array or map. - bstr [8]byte // scratch used for string \UXXX parsing - b [64]byte // scratch - - // wsSkipped bool // whitespace skipped - - // s jsonStack - - noBuiltInTypes -} - -// DecodeNaked will decode into an XMLNode - -// XMLName is a value object representing a namespace-aware NAME -type XMLName struct { - Local string - Space string -} - -// XMLNode represents a "union" of the different types of XML Nodes. -// Only one of fields (Text or *Element) is set. -type XMLNode struct { - Element *Element - Text string -} - -// XMLElement is a value object representing an fully-parsed XML element. -type XMLElement struct { - Name Name - Attrs map[XMLName]string - // Children is a list of child nodes, each being a *XMLElement or string - Children []XMLNode -} - -// ----------- HANDLE ------------------- - -type XMLHandle struct { - BasicHandle - textEncodingType - - DefaultNS string - NS map[string]string // ns URI to key, for encoding - Entities map[string]string // entity representation to string, for encoding. -} - -func (h *XMLHandle) newEncDriver(e *Encoder) encDriver { - return &xmlEncDriver{e: e, w: e.w, h: h} -} - -func (h *XMLHandle) newDecDriver(d *Decoder) decDriver { - // d := xmlDecDriver{r: r.(*bytesDecReader), h: h} - hd := xmlDecDriver{d: d, r: d.r, h: h} - hd.n.bytes = d.b[:] - return &hd -} - -func (h *XMLHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) { - return h.SetExt(rt, tag, &extWrapper{bytesExtFailer{}, ext}) -} - -var _ decDriver = (*xmlDecDriver)(nil) -var _ encDriver = (*xmlEncDriver)(nil) diff --git a/vendor/google.golang.org/grpc/backoff.go b/vendor/google.golang.org/grpc/backoff.go index c40facce5..fa31565fd 100644 --- a/vendor/google.golang.org/grpc/backoff.go +++ b/vendor/google.golang.org/grpc/backoff.go @@ -16,81 +16,23 @@ * */ +// See internal/backoff package for the backoff implementation. This file is +// kept for the exported types and API backward compatility. + package grpc import ( - "math/rand" "time" ) // DefaultBackoffConfig uses values specified for backoff in // https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. var DefaultBackoffConfig = BackoffConfig{ - MaxDelay: 120 * time.Second, - baseDelay: 1.0 * time.Second, - factor: 1.6, - jitter: 0.2, -} - -// backoffStrategy defines the methodology for backing off after a grpc -// connection failure. -// -// This is unexported until the gRPC project decides whether or not to allow -// alternative backoff strategies. Once a decision is made, this type and its -// method may be exported. -type backoffStrategy interface { - // backoff returns the amount of time to wait before the next retry given - // the number of consecutive failures. - backoff(retries int) time.Duration + MaxDelay: 120 * time.Second, } // BackoffConfig defines the parameters for the default gRPC backoff strategy. type BackoffConfig struct { // MaxDelay is the upper bound of backoff delay. MaxDelay time.Duration - - // TODO(stevvooe): The following fields are not exported, as allowing - // changes would violate the current gRPC specification for backoff. If - // gRPC decides to allow more interesting backoff strategies, these fields - // may be opened up in the future. - - // baseDelay is the amount of time to wait before retrying after the first - // failure. - baseDelay time.Duration - - // factor is applied to the backoff after each retry. - factor float64 - - // jitter provides a range to randomize backoff delays. - jitter float64 -} - -func setDefaults(bc *BackoffConfig) { - md := bc.MaxDelay - *bc = DefaultBackoffConfig - - if md > 0 { - bc.MaxDelay = md - } -} - -func (bc BackoffConfig) backoff(retries int) time.Duration { - if retries == 0 { - return bc.baseDelay - } - backoff, max := float64(bc.baseDelay), float64(bc.MaxDelay) - for backoff < max && retries > 0 { - backoff *= bc.factor - retries-- - } - if backoff > max { - backoff = max - } - // Randomize backoff delays so that if a cluster of requests start at - // the same time, they won't operate in lockstep. - backoff *= 1 + bc.jitter*(rand.Float64()*2-1) - if backoff < 0 { - return 0 - } - return time.Duration(backoff) } diff --git a/vendor/google.golang.org/grpc/balancer/balancer.go b/vendor/google.golang.org/grpc/balancer/balancer.go index 63b8d7137..f9d83c2f3 100644 --- a/vendor/google.golang.org/grpc/balancer/balancer.go +++ b/vendor/google.golang.org/grpc/balancer/balancer.go @@ -226,3 +226,45 @@ type Balancer interface { // ClientConn.RemoveSubConn for its existing SubConns. Close() } + +// ConnectivityStateEvaluator takes the connectivity states of multiple SubConns +// and returns one aggregated connectivity state. +// +// It's not thread safe. +type ConnectivityStateEvaluator struct { + numReady uint64 // Number of addrConns in ready state. + numConnecting uint64 // Number of addrConns in connecting state. + numTransientFailure uint64 // Number of addrConns in transientFailure. +} + +// RecordTransition records state change happening in subConn and based on that +// it evaluates what aggregated state should be. +// +// - If at least one SubConn in Ready, the aggregated state is Ready; +// - Else if at least one SubConn in Connecting, the aggregated state is Connecting; +// - Else the aggregated state is TransientFailure. +// +// Idle and Shutdown are not considered. +func (cse *ConnectivityStateEvaluator) RecordTransition(oldState, newState connectivity.State) connectivity.State { + // Update counters. + for idx, state := range []connectivity.State{oldState, newState} { + updateVal := 2*uint64(idx) - 1 // -1 for oldState and +1 for new. + switch state { + case connectivity.Ready: + cse.numReady += updateVal + case connectivity.Connecting: + cse.numConnecting += updateVal + case connectivity.TransientFailure: + cse.numTransientFailure += updateVal + } + } + + // Evaluate. + if cse.numReady > 0 { + return connectivity.Ready + } + if cse.numConnecting > 0 { + return connectivity.Connecting + } + return connectivity.TransientFailure +} diff --git a/vendor/google.golang.org/grpc/balancer_v1_wrapper.go b/vendor/google.golang.org/grpc/balancer_v1_wrapper.go index b7abc6b74..e0ce32cfb 100644 --- a/vendor/google.golang.org/grpc/balancer_v1_wrapper.go +++ b/vendor/google.golang.org/grpc/balancer_v1_wrapper.go @@ -55,7 +55,7 @@ func (bwb *balancerWrapperBuilder) Build(cc balancer.ClientConn, opts balancer.B startCh: make(chan struct{}), conns: make(map[resolver.Address]balancer.SubConn), connSt: make(map[balancer.SubConn]*scState), - csEvltr: &connectivityStateEvaluator{}, + csEvltr: &balancer.ConnectivityStateEvaluator{}, state: connectivity.Idle, } cc.UpdateBalancerState(connectivity.Idle, bw) @@ -80,10 +80,6 @@ type balancerWrapper struct { cc balancer.ClientConn targetAddr string // Target without the scheme. - // To aggregate the connectivity state. - csEvltr *connectivityStateEvaluator - state connectivity.State - mu sync.Mutex conns map[resolver.Address]balancer.SubConn connSt map[balancer.SubConn]*scState @@ -92,6 +88,10 @@ type balancerWrapper struct { // - NewSubConn is created, cc wants to notify balancer of state changes; // - Build hasn't return, cc doesn't have access to balancer. startCh chan struct{} + + // To aggregate the connectivity state. + csEvltr *balancer.ConnectivityStateEvaluator + state connectivity.State } // lbWatcher watches the Notify channel of the balancer and manages @@ -248,7 +248,7 @@ func (bw *balancerWrapper) HandleSubConnStateChange(sc balancer.SubConn, s conne scSt.down(errConnClosing) } } - sa := bw.csEvltr.recordTransition(oldS, s) + sa := bw.csEvltr.RecordTransition(oldS, s) if bw.state != sa { bw.state = sa } @@ -326,47 +326,3 @@ func (bw *balancerWrapper) Pick(ctx context.Context, opts balancer.PickOptions) return sc, done, nil } - -// connectivityStateEvaluator gets updated by addrConns when their -// states transition, based on which it evaluates the state of -// ClientConn. -type connectivityStateEvaluator struct { - mu sync.Mutex - numReady uint64 // Number of addrConns in ready state. - numConnecting uint64 // Number of addrConns in connecting state. - numTransientFailure uint64 // Number of addrConns in transientFailure. -} - -// recordTransition records state change happening in every subConn and based on -// that it evaluates what aggregated state should be. -// It can only transition between Ready, Connecting and TransientFailure. Other states, -// Idle and Shutdown are transitioned into by ClientConn; in the beginning of the connection -// before any subConn is created ClientConn is in idle state. In the end when ClientConn -// closes it is in Shutdown state. -// TODO Note that in later releases, a ClientConn with no activity will be put into an Idle state. -func (cse *connectivityStateEvaluator) recordTransition(oldState, newState connectivity.State) connectivity.State { - cse.mu.Lock() - defer cse.mu.Unlock() - - // Update counters. - for idx, state := range []connectivity.State{oldState, newState} { - updateVal := 2*uint64(idx) - 1 // -1 for oldState and +1 for new. - switch state { - case connectivity.Ready: - cse.numReady += updateVal - case connectivity.Connecting: - cse.numConnecting += updateVal - case connectivity.TransientFailure: - cse.numTransientFailure += updateVal - } - } - - // Evaluate. - if cse.numReady > 0 { - return connectivity.Ready - } - if cse.numConnecting > 0 { - return connectivity.Connecting - } - return connectivity.TransientFailure -} diff --git a/vendor/google.golang.org/grpc/clientconn.go b/vendor/google.golang.org/grpc/clientconn.go index e8d95b43b..84ba9e5ad 100644 --- a/vendor/google.golang.org/grpc/clientconn.go +++ b/vendor/google.golang.org/grpc/clientconn.go @@ -32,11 +32,13 @@ import ( "golang.org/x/net/trace" "google.golang.org/grpc/balancer" _ "google.golang.org/grpc/balancer/roundrobin" // To register roundrobin. - "google.golang.org/grpc/channelz" "google.golang.org/grpc/codes" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/credentials" "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/internal" + "google.golang.org/grpc/internal/backoff" + "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/resolver" _ "google.golang.org/grpc/resolver/dns" // To register dns resolver. @@ -49,6 +51,8 @@ import ( const ( // minimum time to give a connection to complete minConnectTimeout = 20 * time.Second + // must match grpclbName in grpclb/grpclb.go + grpclbName = "grpclb" ) var ( @@ -97,7 +101,7 @@ type dialOptions struct { streamInt StreamClientInterceptor cp Compressor dc Decompressor - bs backoffStrategy + bs backoff.Strategy block bool insecure bool timeout time.Duration @@ -275,17 +279,17 @@ func WithBackoffMaxDelay(md time.Duration) DialOption { // Use WithBackoffMaxDelay until more parameters on BackoffConfig are opened up // for use. func WithBackoffConfig(b BackoffConfig) DialOption { - // Set defaults to ensure that provided BackoffConfig is valid and - // unexported fields get default values. - setDefaults(&b) - return withBackoff(b) + + return withBackoff(backoff.Exponential{ + MaxDelay: b.MaxDelay, + }) } // withBackoff sets the backoff strategy used for connectRetryNum after a // failed connection attempt. // // This can be exported if arbitrary backoff strategies are allowed by gRPC. -func withBackoff(bs backoffStrategy) DialOption { +func withBackoff(bs backoff.Strategy) DialOption { return func(o *dialOptions) { o.bs = bs } @@ -340,6 +344,11 @@ func withContextDialer(f func(context.Context, string) (net.Conn, error)) DialOp } } +func init() { + internal.WithContextDialer = withContextDialer + internal.WithResolverBuilder = withResolverBuilder +} + // WithDialer returns a DialOption that specifies a function to use for dialing network addresses. // If FailOnNonTempDialError() is set to true, and an error is returned by f, gRPC checks the error's // Temporary() method to decide if it should try to reconnect to the network address. @@ -532,7 +541,9 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * } } if cc.dopts.bs == nil { - cc.dopts.bs = DefaultBackoffConfig + cc.dopts.bs = backoff.Exponential{ + MaxDelay: DefaultBackoffConfig.MaxDelay, + } } if cc.dopts.resolverBuilder == nil { // Only try to parse target when resolver builder is not already set. @@ -1052,9 +1063,9 @@ func (cc *ClientConn) handleServiceConfig(js string) error { } func (cc *ClientConn) resolveNow(o resolver.ResolveNowOption) { - cc.mu.Lock() + cc.mu.RLock() r := cc.resolverWrapper - cc.mu.Unlock() + cc.mu.RUnlock() if r == nil { return } @@ -1203,7 +1214,7 @@ func (ac *addrConn) resetTransport() error { // This means either a successful HTTP2 connection was established // or this is the first time this addrConn is trying to establish a // connection. - backoffFor := ac.dopts.bs.backoff(connectRetryNum) // time.Duration. + backoffFor := ac.dopts.bs.Backoff(connectRetryNum) // time.Duration. // This will be the duration that dial gets to finish. dialDuration := getMinConnectTimeout() if backoffFor > dialDuration { diff --git a/vendor/google.golang.org/grpc/codes/codes.go b/vendor/google.golang.org/grpc/codes/codes.go index a8280ae66..d9b9d5782 100644 --- a/vendor/google.golang.org/grpc/codes/codes.go +++ b/vendor/google.golang.org/grpc/codes/codes.go @@ -22,6 +22,7 @@ package codes // import "google.golang.org/grpc/codes" import ( "fmt" + "strconv" ) // A Code is an unsigned 32-bit error code as defined in the gRPC spec. @@ -143,6 +144,8 @@ const ( // Unauthenticated indicates the request does not have valid // authentication credentials for the operation. Unauthenticated Code = 16 + + _maxCode = 17 ) var strToCode = map[string]Code{ @@ -176,6 +179,16 @@ func (c *Code) UnmarshalJSON(b []byte) error { if c == nil { return fmt.Errorf("nil receiver passed to UnmarshalJSON") } + + if ci, err := strconv.ParseUint(string(b), 10, 32); err == nil { + if ci >= _maxCode { + return fmt.Errorf("invalid code: %q", ci) + } + + *c = Code(ci) + return nil + } + if jc, ok := strToCode[string(b)]; ok { *c = jc return nil diff --git a/vendor/google.golang.org/grpc/grpclb.go b/vendor/google.golang.org/grpc/grpclb.go deleted file mode 100644 index bc2b44525..000000000 --- a/vendor/google.golang.org/grpc/grpclb.go +++ /dev/null @@ -1,341 +0,0 @@ -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "strconv" - "strings" - "sync" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/connectivity" - lbpb "google.golang.org/grpc/grpclb/grpc_lb_v1/messages" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/resolver" -) - -const ( - lbTokeyKey = "lb-token" - defaultFallbackTimeout = 10 * time.Second - grpclbName = "grpclb" -) - -func convertDuration(d *lbpb.Duration) time.Duration { - if d == nil { - return 0 - } - return time.Duration(d.Seconds)*time.Second + time.Duration(d.Nanos)*time.Nanosecond -} - -// Client API for LoadBalancer service. -// Mostly copied from generated pb.go file. -// To avoid circular dependency. -type loadBalancerClient struct { - cc *ClientConn -} - -func (c *loadBalancerClient) BalanceLoad(ctx context.Context, opts ...CallOption) (*balanceLoadClientStream, error) { - desc := &StreamDesc{ - StreamName: "BalanceLoad", - ServerStreams: true, - ClientStreams: true, - } - stream, err := c.cc.NewStream(ctx, desc, "/grpc.lb.v1.LoadBalancer/BalanceLoad", opts...) - if err != nil { - return nil, err - } - x := &balanceLoadClientStream{stream} - return x, nil -} - -type balanceLoadClientStream struct { - ClientStream -} - -func (x *balanceLoadClientStream) Send(m *lbpb.LoadBalanceRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *balanceLoadClientStream) Recv() (*lbpb.LoadBalanceResponse, error) { - m := new(lbpb.LoadBalanceResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func init() { - balancer.Register(newLBBuilder()) -} - -// newLBBuilder creates a builder for grpclb. -func newLBBuilder() balancer.Builder { - return NewLBBuilderWithFallbackTimeout(defaultFallbackTimeout) -} - -// NewLBBuilderWithFallbackTimeout creates a grpclb builder with the given -// fallbackTimeout. If no response is received from the remote balancer within -// fallbackTimeout, the backend addresses from the resolved address list will be -// used. -// -// Only call this function when a non-default fallback timeout is needed. -func NewLBBuilderWithFallbackTimeout(fallbackTimeout time.Duration) balancer.Builder { - return &lbBuilder{ - fallbackTimeout: fallbackTimeout, - } -} - -type lbBuilder struct { - fallbackTimeout time.Duration -} - -func (b *lbBuilder) Name() string { - return grpclbName -} - -func (b *lbBuilder) Build(cc balancer.ClientConn, opt balancer.BuildOptions) balancer.Balancer { - // This generates a manual resolver builder with a random scheme. This - // scheme will be used to dial to remote LB, so we can send filtered address - // updates to remote LB ClientConn using this manual resolver. - scheme := "grpclb_internal_" + strconv.FormatInt(time.Now().UnixNano(), 36) - r := &lbManualResolver{scheme: scheme, ccb: cc} - - var target string - targetSplitted := strings.Split(cc.Target(), ":///") - if len(targetSplitted) < 2 { - target = cc.Target() - } else { - target = targetSplitted[1] - } - - lb := &lbBalancer{ - cc: newLBCacheClientConn(cc), - target: target, - opt: opt, - fallbackTimeout: b.fallbackTimeout, - doneCh: make(chan struct{}), - - manualResolver: r, - csEvltr: &connectivityStateEvaluator{}, - subConns: make(map[resolver.Address]balancer.SubConn), - scStates: make(map[balancer.SubConn]connectivity.State), - picker: &errPicker{err: balancer.ErrNoSubConnAvailable}, - clientStats: &rpcStats{}, - } - - return lb -} - -type lbBalancer struct { - cc *lbCacheClientConn - target string - opt balancer.BuildOptions - fallbackTimeout time.Duration - doneCh chan struct{} - - // manualResolver is used in the remote LB ClientConn inside grpclb. When - // resolved address updates are received by grpclb, filtered updates will be - // send to remote LB ClientConn through this resolver. - manualResolver *lbManualResolver - // The ClientConn to talk to the remote balancer. - ccRemoteLB *ClientConn - - // Support client side load reporting. Each picker gets a reference to this, - // and will update its content. - clientStats *rpcStats - - mu sync.Mutex // guards everything following. - // The full server list including drops, used to check if the newly received - // serverList contains anything new. Each generate picker will also have - // reference to this list to do the first layer pick. - fullServerList []*lbpb.Server - // All backends addresses, with metadata set to nil. This list contains all - // backend addresses in the same order and with the same duplicates as in - // serverlist. When generating picker, a SubConn slice with the same order - // but with only READY SCs will be gerenated. - backendAddrs []resolver.Address - // Roundrobin functionalities. - csEvltr *connectivityStateEvaluator - state connectivity.State - subConns map[resolver.Address]balancer.SubConn // Used to new/remove SubConn. - scStates map[balancer.SubConn]connectivity.State // Used to filter READY SubConns. - picker balancer.Picker - // Support fallback to resolved backend addresses if there's no response - // from remote balancer within fallbackTimeout. - fallbackTimerExpired bool - serverListReceived bool - // resolvedBackendAddrs is resolvedAddrs minus remote balancers. It's set - // when resolved address updates are received, and read in the goroutine - // handling fallback. - resolvedBackendAddrs []resolver.Address -} - -// regeneratePicker takes a snapshot of the balancer, and generates a picker from -// it. The picker -// - always returns ErrTransientFailure if the balancer is in TransientFailure, -// - does two layer roundrobin pick otherwise. -// Caller must hold lb.mu. -func (lb *lbBalancer) regeneratePicker() { - if lb.state == connectivity.TransientFailure { - lb.picker = &errPicker{err: balancer.ErrTransientFailure} - return - } - var readySCs []balancer.SubConn - for _, a := range lb.backendAddrs { - if sc, ok := lb.subConns[a]; ok { - if st, ok := lb.scStates[sc]; ok && st == connectivity.Ready { - readySCs = append(readySCs, sc) - } - } - } - - if len(lb.fullServerList) <= 0 { - if len(readySCs) <= 0 { - lb.picker = &errPicker{err: balancer.ErrNoSubConnAvailable} - return - } - lb.picker = &rrPicker{subConns: readySCs} - return - } - lb.picker = &lbPicker{ - serverList: lb.fullServerList, - subConns: readySCs, - stats: lb.clientStats, - } -} - -func (lb *lbBalancer) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { - grpclog.Infof("lbBalancer: handle SubConn state change: %p, %v", sc, s) - lb.mu.Lock() - defer lb.mu.Unlock() - - oldS, ok := lb.scStates[sc] - if !ok { - grpclog.Infof("lbBalancer: got state changes for an unknown SubConn: %p, %v", sc, s) - return - } - lb.scStates[sc] = s - switch s { - case connectivity.Idle: - sc.Connect() - case connectivity.Shutdown: - // When an address was removed by resolver, b called RemoveSubConn but - // kept the sc's state in scStates. Remove state for this sc here. - delete(lb.scStates, sc) - } - - oldAggrState := lb.state - lb.state = lb.csEvltr.recordTransition(oldS, s) - - // Regenerate picker when one of the following happens: - // - this sc became ready from not-ready - // - this sc became not-ready from ready - // - the aggregated state of balancer became TransientFailure from non-TransientFailure - // - the aggregated state of balancer became non-TransientFailure from TransientFailure - if (oldS == connectivity.Ready) != (s == connectivity.Ready) || - (lb.state == connectivity.TransientFailure) != (oldAggrState == connectivity.TransientFailure) { - lb.regeneratePicker() - } - - lb.cc.UpdateBalancerState(lb.state, lb.picker) -} - -// fallbackToBackendsAfter blocks for fallbackTimeout and falls back to use -// resolved backends (backends received from resolver, not from remote balancer) -// if no connection to remote balancers was successful. -func (lb *lbBalancer) fallbackToBackendsAfter(fallbackTimeout time.Duration) { - timer := time.NewTimer(fallbackTimeout) - defer timer.Stop() - select { - case <-timer.C: - case <-lb.doneCh: - return - } - lb.mu.Lock() - if lb.serverListReceived { - lb.mu.Unlock() - return - } - lb.fallbackTimerExpired = true - lb.refreshSubConns(lb.resolvedBackendAddrs) - lb.mu.Unlock() -} - -// HandleResolvedAddrs sends the updated remoteLB addresses to remoteLB -// clientConn. The remoteLB clientConn will handle creating/removing remoteLB -// connections. -func (lb *lbBalancer) HandleResolvedAddrs(addrs []resolver.Address, err error) { - grpclog.Infof("lbBalancer: handleResolvedResult: %+v", addrs) - if len(addrs) <= 0 { - return - } - - var remoteBalancerAddrs, backendAddrs []resolver.Address - for _, a := range addrs { - if a.Type == resolver.GRPCLB { - remoteBalancerAddrs = append(remoteBalancerAddrs, a) - } else { - backendAddrs = append(backendAddrs, a) - } - } - - if lb.ccRemoteLB == nil { - if len(remoteBalancerAddrs) <= 0 { - grpclog.Errorf("grpclb: no remote balancer address is available, should never happen") - return - } - // First time receiving resolved addresses, create a cc to remote - // balancers. - lb.dialRemoteLB(remoteBalancerAddrs[0].ServerName) - // Start the fallback goroutine. - go lb.fallbackToBackendsAfter(lb.fallbackTimeout) - } - - // cc to remote balancers uses lb.manualResolver. Send the updated remote - // balancer addresses to it through manualResolver. - lb.manualResolver.NewAddress(remoteBalancerAddrs) - - lb.mu.Lock() - lb.resolvedBackendAddrs = backendAddrs - // If serverListReceived is true, connection to remote balancer was - // successful and there's no need to do fallback anymore. - // If fallbackTimerExpired is false, fallback hasn't happened yet. - if !lb.serverListReceived && lb.fallbackTimerExpired { - // This means we received a new list of resolved backends, and we are - // still in fallback mode. Need to update the list of backends we are - // using to the new list of backends. - lb.refreshSubConns(lb.resolvedBackendAddrs) - } - lb.mu.Unlock() -} - -func (lb *lbBalancer) Close() { - select { - case <-lb.doneCh: - return - default: - } - close(lb.doneCh) - if lb.ccRemoteLB != nil { - lb.ccRemoteLB.Close() - } - lb.cc.close() -} diff --git a/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.pb.go b/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.pb.go deleted file mode 100644 index b3b32b48e..000000000 --- a/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.pb.go +++ /dev/null @@ -1,799 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc_lb_v1/messages/messages.proto - -package messages // import "google.golang.org/grpc/grpclb/grpc_lb_v1/messages" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Duration struct { - // Signed seconds of the span of time. Must be from -315,576,000,000 - // to +315,576,000,000 inclusive. - Seconds int64 `protobuf:"varint,1,opt,name=seconds" json:"seconds,omitempty"` - // Signed fractions of a second at nanosecond resolution of the span - // of time. Durations less than one second are represented with a 0 - // `seconds` field and a positive or negative `nanos` field. For durations - // of one second or more, a non-zero value for the `nanos` field must be - // of the same sign as the `seconds` field. Must be from -999,999,999 - // to +999,999,999 inclusive. - Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Duration) Reset() { *m = Duration{} } -func (m *Duration) String() string { return proto.CompactTextString(m) } -func (*Duration) ProtoMessage() {} -func (*Duration) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b81c731f0e83edbd, []int{0} -} -func (m *Duration) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Duration.Unmarshal(m, b) -} -func (m *Duration) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Duration.Marshal(b, m, deterministic) -} -func (dst *Duration) XXX_Merge(src proto.Message) { - xxx_messageInfo_Duration.Merge(dst, src) -} -func (m *Duration) XXX_Size() int { - return xxx_messageInfo_Duration.Size(m) -} -func (m *Duration) XXX_DiscardUnknown() { - xxx_messageInfo_Duration.DiscardUnknown(m) -} - -var xxx_messageInfo_Duration proto.InternalMessageInfo - -func (m *Duration) GetSeconds() int64 { - if m != nil { - return m.Seconds - } - return 0 -} - -func (m *Duration) GetNanos() int32 { - if m != nil { - return m.Nanos - } - return 0 -} - -type Timestamp struct { - // Represents seconds of UTC time since Unix epoch - // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - // 9999-12-31T23:59:59Z inclusive. - Seconds int64 `protobuf:"varint,1,opt,name=seconds" json:"seconds,omitempty"` - // Non-negative fractions of a second at nanosecond resolution. Negative - // second values with fractions must still have non-negative nanos values - // that count forward in time. Must be from 0 to 999,999,999 - // inclusive. - Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Timestamp) Reset() { *m = Timestamp{} } -func (m *Timestamp) String() string { return proto.CompactTextString(m) } -func (*Timestamp) ProtoMessage() {} -func (*Timestamp) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b81c731f0e83edbd, []int{1} -} -func (m *Timestamp) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Timestamp.Unmarshal(m, b) -} -func (m *Timestamp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Timestamp.Marshal(b, m, deterministic) -} -func (dst *Timestamp) XXX_Merge(src proto.Message) { - xxx_messageInfo_Timestamp.Merge(dst, src) -} -func (m *Timestamp) XXX_Size() int { - return xxx_messageInfo_Timestamp.Size(m) -} -func (m *Timestamp) XXX_DiscardUnknown() { - xxx_messageInfo_Timestamp.DiscardUnknown(m) -} - -var xxx_messageInfo_Timestamp proto.InternalMessageInfo - -func (m *Timestamp) GetSeconds() int64 { - if m != nil { - return m.Seconds - } - return 0 -} - -func (m *Timestamp) GetNanos() int32 { - if m != nil { - return m.Nanos - } - return 0 -} - -type LoadBalanceRequest struct { - // Types that are valid to be assigned to LoadBalanceRequestType: - // *LoadBalanceRequest_InitialRequest - // *LoadBalanceRequest_ClientStats - LoadBalanceRequestType isLoadBalanceRequest_LoadBalanceRequestType `protobuf_oneof:"load_balance_request_type"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *LoadBalanceRequest) Reset() { *m = LoadBalanceRequest{} } -func (m *LoadBalanceRequest) String() string { return proto.CompactTextString(m) } -func (*LoadBalanceRequest) ProtoMessage() {} -func (*LoadBalanceRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b81c731f0e83edbd, []int{2} -} -func (m *LoadBalanceRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_LoadBalanceRequest.Unmarshal(m, b) -} -func (m *LoadBalanceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_LoadBalanceRequest.Marshal(b, m, deterministic) -} -func (dst *LoadBalanceRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_LoadBalanceRequest.Merge(dst, src) -} -func (m *LoadBalanceRequest) XXX_Size() int { - return xxx_messageInfo_LoadBalanceRequest.Size(m) -} -func (m *LoadBalanceRequest) XXX_DiscardUnknown() { - xxx_messageInfo_LoadBalanceRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_LoadBalanceRequest proto.InternalMessageInfo - -type isLoadBalanceRequest_LoadBalanceRequestType interface { - isLoadBalanceRequest_LoadBalanceRequestType() -} - -type LoadBalanceRequest_InitialRequest struct { - InitialRequest *InitialLoadBalanceRequest `protobuf:"bytes,1,opt,name=initial_request,json=initialRequest,oneof"` -} -type LoadBalanceRequest_ClientStats struct { - ClientStats *ClientStats `protobuf:"bytes,2,opt,name=client_stats,json=clientStats,oneof"` -} - -func (*LoadBalanceRequest_InitialRequest) isLoadBalanceRequest_LoadBalanceRequestType() {} -func (*LoadBalanceRequest_ClientStats) isLoadBalanceRequest_LoadBalanceRequestType() {} - -func (m *LoadBalanceRequest) GetLoadBalanceRequestType() isLoadBalanceRequest_LoadBalanceRequestType { - if m != nil { - return m.LoadBalanceRequestType - } - return nil -} - -func (m *LoadBalanceRequest) GetInitialRequest() *InitialLoadBalanceRequest { - if x, ok := m.GetLoadBalanceRequestType().(*LoadBalanceRequest_InitialRequest); ok { - return x.InitialRequest - } - return nil -} - -func (m *LoadBalanceRequest) GetClientStats() *ClientStats { - if x, ok := m.GetLoadBalanceRequestType().(*LoadBalanceRequest_ClientStats); ok { - return x.ClientStats - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*LoadBalanceRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _LoadBalanceRequest_OneofMarshaler, _LoadBalanceRequest_OneofUnmarshaler, _LoadBalanceRequest_OneofSizer, []interface{}{ - (*LoadBalanceRequest_InitialRequest)(nil), - (*LoadBalanceRequest_ClientStats)(nil), - } -} - -func _LoadBalanceRequest_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*LoadBalanceRequest) - // load_balance_request_type - switch x := m.LoadBalanceRequestType.(type) { - case *LoadBalanceRequest_InitialRequest: - b.EncodeVarint(1<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.InitialRequest); err != nil { - return err - } - case *LoadBalanceRequest_ClientStats: - b.EncodeVarint(2<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ClientStats); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("LoadBalanceRequest.LoadBalanceRequestType has unexpected type %T", x) - } - return nil -} - -func _LoadBalanceRequest_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*LoadBalanceRequest) - switch tag { - case 1: // load_balance_request_type.initial_request - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(InitialLoadBalanceRequest) - err := b.DecodeMessage(msg) - m.LoadBalanceRequestType = &LoadBalanceRequest_InitialRequest{msg} - return true, err - case 2: // load_balance_request_type.client_stats - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ClientStats) - err := b.DecodeMessage(msg) - m.LoadBalanceRequestType = &LoadBalanceRequest_ClientStats{msg} - return true, err - default: - return false, nil - } -} - -func _LoadBalanceRequest_OneofSizer(msg proto.Message) (n int) { - m := msg.(*LoadBalanceRequest) - // load_balance_request_type - switch x := m.LoadBalanceRequestType.(type) { - case *LoadBalanceRequest_InitialRequest: - s := proto.Size(x.InitialRequest) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *LoadBalanceRequest_ClientStats: - s := proto.Size(x.ClientStats) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type InitialLoadBalanceRequest struct { - // Name of load balanced service (IE, balancer.service.com) - // length should be less than 256 bytes. - Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InitialLoadBalanceRequest) Reset() { *m = InitialLoadBalanceRequest{} } -func (m *InitialLoadBalanceRequest) String() string { return proto.CompactTextString(m) } -func (*InitialLoadBalanceRequest) ProtoMessage() {} -func (*InitialLoadBalanceRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b81c731f0e83edbd, []int{3} -} -func (m *InitialLoadBalanceRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InitialLoadBalanceRequest.Unmarshal(m, b) -} -func (m *InitialLoadBalanceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InitialLoadBalanceRequest.Marshal(b, m, deterministic) -} -func (dst *InitialLoadBalanceRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_InitialLoadBalanceRequest.Merge(dst, src) -} -func (m *InitialLoadBalanceRequest) XXX_Size() int { - return xxx_messageInfo_InitialLoadBalanceRequest.Size(m) -} -func (m *InitialLoadBalanceRequest) XXX_DiscardUnknown() { - xxx_messageInfo_InitialLoadBalanceRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_InitialLoadBalanceRequest proto.InternalMessageInfo - -func (m *InitialLoadBalanceRequest) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -// Contains client level statistics that are useful to load balancing. Each -// count except the timestamp should be reset to zero after reporting the stats. -type ClientStats struct { - // The timestamp of generating the report. - Timestamp *Timestamp `protobuf:"bytes,1,opt,name=timestamp" json:"timestamp,omitempty"` - // The total number of RPCs that started. - NumCallsStarted int64 `protobuf:"varint,2,opt,name=num_calls_started,json=numCallsStarted" json:"num_calls_started,omitempty"` - // The total number of RPCs that finished. - NumCallsFinished int64 `protobuf:"varint,3,opt,name=num_calls_finished,json=numCallsFinished" json:"num_calls_finished,omitempty"` - // The total number of RPCs that were dropped by the client because of rate - // limiting. - NumCallsFinishedWithDropForRateLimiting int64 `protobuf:"varint,4,opt,name=num_calls_finished_with_drop_for_rate_limiting,json=numCallsFinishedWithDropForRateLimiting" json:"num_calls_finished_with_drop_for_rate_limiting,omitempty"` - // The total number of RPCs that were dropped by the client because of load - // balancing. - NumCallsFinishedWithDropForLoadBalancing int64 `protobuf:"varint,5,opt,name=num_calls_finished_with_drop_for_load_balancing,json=numCallsFinishedWithDropForLoadBalancing" json:"num_calls_finished_with_drop_for_load_balancing,omitempty"` - // The total number of RPCs that failed to reach a server except dropped RPCs. - NumCallsFinishedWithClientFailedToSend int64 `protobuf:"varint,6,opt,name=num_calls_finished_with_client_failed_to_send,json=numCallsFinishedWithClientFailedToSend" json:"num_calls_finished_with_client_failed_to_send,omitempty"` - // The total number of RPCs that finished and are known to have been received - // by a server. - NumCallsFinishedKnownReceived int64 `protobuf:"varint,7,opt,name=num_calls_finished_known_received,json=numCallsFinishedKnownReceived" json:"num_calls_finished_known_received,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ClientStats) Reset() { *m = ClientStats{} } -func (m *ClientStats) String() string { return proto.CompactTextString(m) } -func (*ClientStats) ProtoMessage() {} -func (*ClientStats) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b81c731f0e83edbd, []int{4} -} -func (m *ClientStats) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ClientStats.Unmarshal(m, b) -} -func (m *ClientStats) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ClientStats.Marshal(b, m, deterministic) -} -func (dst *ClientStats) XXX_Merge(src proto.Message) { - xxx_messageInfo_ClientStats.Merge(dst, src) -} -func (m *ClientStats) XXX_Size() int { - return xxx_messageInfo_ClientStats.Size(m) -} -func (m *ClientStats) XXX_DiscardUnknown() { - xxx_messageInfo_ClientStats.DiscardUnknown(m) -} - -var xxx_messageInfo_ClientStats proto.InternalMessageInfo - -func (m *ClientStats) GetTimestamp() *Timestamp { - if m != nil { - return m.Timestamp - } - return nil -} - -func (m *ClientStats) GetNumCallsStarted() int64 { - if m != nil { - return m.NumCallsStarted - } - return 0 -} - -func (m *ClientStats) GetNumCallsFinished() int64 { - if m != nil { - return m.NumCallsFinished - } - return 0 -} - -func (m *ClientStats) GetNumCallsFinishedWithDropForRateLimiting() int64 { - if m != nil { - return m.NumCallsFinishedWithDropForRateLimiting - } - return 0 -} - -func (m *ClientStats) GetNumCallsFinishedWithDropForLoadBalancing() int64 { - if m != nil { - return m.NumCallsFinishedWithDropForLoadBalancing - } - return 0 -} - -func (m *ClientStats) GetNumCallsFinishedWithClientFailedToSend() int64 { - if m != nil { - return m.NumCallsFinishedWithClientFailedToSend - } - return 0 -} - -func (m *ClientStats) GetNumCallsFinishedKnownReceived() int64 { - if m != nil { - return m.NumCallsFinishedKnownReceived - } - return 0 -} - -type LoadBalanceResponse struct { - // Types that are valid to be assigned to LoadBalanceResponseType: - // *LoadBalanceResponse_InitialResponse - // *LoadBalanceResponse_ServerList - LoadBalanceResponseType isLoadBalanceResponse_LoadBalanceResponseType `protobuf_oneof:"load_balance_response_type"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *LoadBalanceResponse) Reset() { *m = LoadBalanceResponse{} } -func (m *LoadBalanceResponse) String() string { return proto.CompactTextString(m) } -func (*LoadBalanceResponse) ProtoMessage() {} -func (*LoadBalanceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b81c731f0e83edbd, []int{5} -} -func (m *LoadBalanceResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_LoadBalanceResponse.Unmarshal(m, b) -} -func (m *LoadBalanceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_LoadBalanceResponse.Marshal(b, m, deterministic) -} -func (dst *LoadBalanceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_LoadBalanceResponse.Merge(dst, src) -} -func (m *LoadBalanceResponse) XXX_Size() int { - return xxx_messageInfo_LoadBalanceResponse.Size(m) -} -func (m *LoadBalanceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_LoadBalanceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_LoadBalanceResponse proto.InternalMessageInfo - -type isLoadBalanceResponse_LoadBalanceResponseType interface { - isLoadBalanceResponse_LoadBalanceResponseType() -} - -type LoadBalanceResponse_InitialResponse struct { - InitialResponse *InitialLoadBalanceResponse `protobuf:"bytes,1,opt,name=initial_response,json=initialResponse,oneof"` -} -type LoadBalanceResponse_ServerList struct { - ServerList *ServerList `protobuf:"bytes,2,opt,name=server_list,json=serverList,oneof"` -} - -func (*LoadBalanceResponse_InitialResponse) isLoadBalanceResponse_LoadBalanceResponseType() {} -func (*LoadBalanceResponse_ServerList) isLoadBalanceResponse_LoadBalanceResponseType() {} - -func (m *LoadBalanceResponse) GetLoadBalanceResponseType() isLoadBalanceResponse_LoadBalanceResponseType { - if m != nil { - return m.LoadBalanceResponseType - } - return nil -} - -func (m *LoadBalanceResponse) GetInitialResponse() *InitialLoadBalanceResponse { - if x, ok := m.GetLoadBalanceResponseType().(*LoadBalanceResponse_InitialResponse); ok { - return x.InitialResponse - } - return nil -} - -func (m *LoadBalanceResponse) GetServerList() *ServerList { - if x, ok := m.GetLoadBalanceResponseType().(*LoadBalanceResponse_ServerList); ok { - return x.ServerList - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*LoadBalanceResponse) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _LoadBalanceResponse_OneofMarshaler, _LoadBalanceResponse_OneofUnmarshaler, _LoadBalanceResponse_OneofSizer, []interface{}{ - (*LoadBalanceResponse_InitialResponse)(nil), - (*LoadBalanceResponse_ServerList)(nil), - } -} - -func _LoadBalanceResponse_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*LoadBalanceResponse) - // load_balance_response_type - switch x := m.LoadBalanceResponseType.(type) { - case *LoadBalanceResponse_InitialResponse: - b.EncodeVarint(1<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.InitialResponse); err != nil { - return err - } - case *LoadBalanceResponse_ServerList: - b.EncodeVarint(2<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ServerList); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("LoadBalanceResponse.LoadBalanceResponseType has unexpected type %T", x) - } - return nil -} - -func _LoadBalanceResponse_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*LoadBalanceResponse) - switch tag { - case 1: // load_balance_response_type.initial_response - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(InitialLoadBalanceResponse) - err := b.DecodeMessage(msg) - m.LoadBalanceResponseType = &LoadBalanceResponse_InitialResponse{msg} - return true, err - case 2: // load_balance_response_type.server_list - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ServerList) - err := b.DecodeMessage(msg) - m.LoadBalanceResponseType = &LoadBalanceResponse_ServerList{msg} - return true, err - default: - return false, nil - } -} - -func _LoadBalanceResponse_OneofSizer(msg proto.Message) (n int) { - m := msg.(*LoadBalanceResponse) - // load_balance_response_type - switch x := m.LoadBalanceResponseType.(type) { - case *LoadBalanceResponse_InitialResponse: - s := proto.Size(x.InitialResponse) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *LoadBalanceResponse_ServerList: - s := proto.Size(x.ServerList) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type InitialLoadBalanceResponse struct { - // This is an application layer redirect that indicates the client should use - // the specified server for load balancing. When this field is non-empty in - // the response, the client should open a separate connection to the - // load_balancer_delegate and call the BalanceLoad method. Its length should - // be less than 64 bytes. - LoadBalancerDelegate string `protobuf:"bytes,1,opt,name=load_balancer_delegate,json=loadBalancerDelegate" json:"load_balancer_delegate,omitempty"` - // This interval defines how often the client should send the client stats - // to the load balancer. Stats should only be reported when the duration is - // positive. - ClientStatsReportInterval *Duration `protobuf:"bytes,2,opt,name=client_stats_report_interval,json=clientStatsReportInterval" json:"client_stats_report_interval,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InitialLoadBalanceResponse) Reset() { *m = InitialLoadBalanceResponse{} } -func (m *InitialLoadBalanceResponse) String() string { return proto.CompactTextString(m) } -func (*InitialLoadBalanceResponse) ProtoMessage() {} -func (*InitialLoadBalanceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b81c731f0e83edbd, []int{6} -} -func (m *InitialLoadBalanceResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InitialLoadBalanceResponse.Unmarshal(m, b) -} -func (m *InitialLoadBalanceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InitialLoadBalanceResponse.Marshal(b, m, deterministic) -} -func (dst *InitialLoadBalanceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_InitialLoadBalanceResponse.Merge(dst, src) -} -func (m *InitialLoadBalanceResponse) XXX_Size() int { - return xxx_messageInfo_InitialLoadBalanceResponse.Size(m) -} -func (m *InitialLoadBalanceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_InitialLoadBalanceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_InitialLoadBalanceResponse proto.InternalMessageInfo - -func (m *InitialLoadBalanceResponse) GetLoadBalancerDelegate() string { - if m != nil { - return m.LoadBalancerDelegate - } - return "" -} - -func (m *InitialLoadBalanceResponse) GetClientStatsReportInterval() *Duration { - if m != nil { - return m.ClientStatsReportInterval - } - return nil -} - -type ServerList struct { - // Contains a list of servers selected by the load balancer. The list will - // be updated when server resolutions change or as needed to balance load - // across more servers. The client should consume the server list in order - // unless instructed otherwise via the client_config. - Servers []*Server `protobuf:"bytes,1,rep,name=servers" json:"servers,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServerList) Reset() { *m = ServerList{} } -func (m *ServerList) String() string { return proto.CompactTextString(m) } -func (*ServerList) ProtoMessage() {} -func (*ServerList) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b81c731f0e83edbd, []int{7} -} -func (m *ServerList) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServerList.Unmarshal(m, b) -} -func (m *ServerList) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServerList.Marshal(b, m, deterministic) -} -func (dst *ServerList) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServerList.Merge(dst, src) -} -func (m *ServerList) XXX_Size() int { - return xxx_messageInfo_ServerList.Size(m) -} -func (m *ServerList) XXX_DiscardUnknown() { - xxx_messageInfo_ServerList.DiscardUnknown(m) -} - -var xxx_messageInfo_ServerList proto.InternalMessageInfo - -func (m *ServerList) GetServers() []*Server { - if m != nil { - return m.Servers - } - return nil -} - -// Contains server information. When none of the [drop_for_*] fields are true, -// use the other fields. When drop_for_rate_limiting is true, ignore all other -// fields. Use drop_for_load_balancing only when it is true and -// drop_for_rate_limiting is false. -type Server struct { - // A resolved address for the server, serialized in network-byte-order. It may - // either be an IPv4 or IPv6 address. - IpAddress []byte `protobuf:"bytes,1,opt,name=ip_address,json=ipAddress,proto3" json:"ip_address,omitempty"` - // A resolved port number for the server. - Port int32 `protobuf:"varint,2,opt,name=port" json:"port,omitempty"` - // An opaque but printable token given to the frontend for each pick. All - // frontend requests for that pick must include the token in its initial - // metadata. The token is used by the backend to verify the request and to - // allow the backend to report load to the gRPC LB system. - // - // Its length is variable but less than 50 bytes. - LoadBalanceToken string `protobuf:"bytes,3,opt,name=load_balance_token,json=loadBalanceToken" json:"load_balance_token,omitempty"` - // Indicates whether this particular request should be dropped by the client - // for rate limiting. - DropForRateLimiting bool `protobuf:"varint,4,opt,name=drop_for_rate_limiting,json=dropForRateLimiting" json:"drop_for_rate_limiting,omitempty"` - // Indicates whether this particular request should be dropped by the client - // for load balancing. - DropForLoadBalancing bool `protobuf:"varint,5,opt,name=drop_for_load_balancing,json=dropForLoadBalancing" json:"drop_for_load_balancing,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Server) Reset() { *m = Server{} } -func (m *Server) String() string { return proto.CompactTextString(m) } -func (*Server) ProtoMessage() {} -func (*Server) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b81c731f0e83edbd, []int{8} -} -func (m *Server) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Server.Unmarshal(m, b) -} -func (m *Server) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Server.Marshal(b, m, deterministic) -} -func (dst *Server) XXX_Merge(src proto.Message) { - xxx_messageInfo_Server.Merge(dst, src) -} -func (m *Server) XXX_Size() int { - return xxx_messageInfo_Server.Size(m) -} -func (m *Server) XXX_DiscardUnknown() { - xxx_messageInfo_Server.DiscardUnknown(m) -} - -var xxx_messageInfo_Server proto.InternalMessageInfo - -func (m *Server) GetIpAddress() []byte { - if m != nil { - return m.IpAddress - } - return nil -} - -func (m *Server) GetPort() int32 { - if m != nil { - return m.Port - } - return 0 -} - -func (m *Server) GetLoadBalanceToken() string { - if m != nil { - return m.LoadBalanceToken - } - return "" -} - -func (m *Server) GetDropForRateLimiting() bool { - if m != nil { - return m.DropForRateLimiting - } - return false -} - -func (m *Server) GetDropForLoadBalancing() bool { - if m != nil { - return m.DropForLoadBalancing - } - return false -} - -func init() { - proto.RegisterType((*Duration)(nil), "grpc.lb.v1.Duration") - proto.RegisterType((*Timestamp)(nil), "grpc.lb.v1.Timestamp") - proto.RegisterType((*LoadBalanceRequest)(nil), "grpc.lb.v1.LoadBalanceRequest") - proto.RegisterType((*InitialLoadBalanceRequest)(nil), "grpc.lb.v1.InitialLoadBalanceRequest") - proto.RegisterType((*ClientStats)(nil), "grpc.lb.v1.ClientStats") - proto.RegisterType((*LoadBalanceResponse)(nil), "grpc.lb.v1.LoadBalanceResponse") - proto.RegisterType((*InitialLoadBalanceResponse)(nil), "grpc.lb.v1.InitialLoadBalanceResponse") - proto.RegisterType((*ServerList)(nil), "grpc.lb.v1.ServerList") - proto.RegisterType((*Server)(nil), "grpc.lb.v1.Server") -} - -func init() { - proto.RegisterFile("grpc_lb_v1/messages/messages.proto", fileDescriptor_messages_b81c731f0e83edbd) -} - -var fileDescriptor_messages_b81c731f0e83edbd = []byte{ - // 731 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x55, 0xdd, 0x4e, 0x1b, 0x39, - 0x14, 0x26, 0x9b, 0x00, 0xc9, 0x09, 0x5a, 0xb2, 0x26, 0x0b, 0x81, 0x05, 0x89, 0x1d, 0x69, 0xd9, - 0x68, 0xc5, 0x4e, 0x04, 0xd9, 0xbd, 0xe8, 0xcf, 0x45, 0x1b, 0x10, 0x0a, 0x2d, 0x17, 0x95, 0x43, - 0x55, 0xa9, 0x52, 0x65, 0x39, 0x19, 0x33, 0x58, 0x38, 0xf6, 0xd4, 0x76, 0x82, 0xfa, 0x08, 0x7d, - 0x94, 0x3e, 0x46, 0xd5, 0x67, 0xe8, 0xfb, 0x54, 0xe3, 0x99, 0xc9, 0x0c, 0x10, 0x40, 0xbd, 0x89, - 0xec, 0xe3, 0xef, 0x7c, 0xdf, 0xf1, 0x89, 0xbf, 0x33, 0xe0, 0x85, 0x3a, 0x1a, 0x11, 0x31, 0x24, - 0xd3, 0x83, 0xce, 0x98, 0x19, 0x43, 0x43, 0x66, 0x66, 0x0b, 0x3f, 0xd2, 0xca, 0x2a, 0x04, 0x31, - 0xc6, 0x17, 0x43, 0x7f, 0x7a, 0xe0, 0x3d, 0x85, 0xea, 0xf1, 0x44, 0x53, 0xcb, 0x95, 0x44, 0x2d, - 0x58, 0x36, 0x6c, 0xa4, 0x64, 0x60, 0x5a, 0xa5, 0xdd, 0x52, 0xbb, 0x8c, 0xb3, 0x2d, 0x6a, 0xc2, - 0xa2, 0xa4, 0x52, 0x99, 0xd6, 0x2f, 0xbb, 0xa5, 0xf6, 0x22, 0x4e, 0x36, 0xde, 0x33, 0xa8, 0x9d, - 0xf3, 0x31, 0x33, 0x96, 0x8e, 0xa3, 0x9f, 0x4e, 0xfe, 0x5a, 0x02, 0x74, 0xa6, 0x68, 0xd0, 0xa3, - 0x82, 0xca, 0x11, 0xc3, 0xec, 0xe3, 0x84, 0x19, 0x8b, 0xde, 0xc0, 0x2a, 0x97, 0xdc, 0x72, 0x2a, - 0x88, 0x4e, 0x42, 0x8e, 0xae, 0x7e, 0xf8, 0x97, 0x9f, 0x57, 0xed, 0x9f, 0x26, 0x90, 0xbb, 0xf9, - 0xfd, 0x05, 0xfc, 0x6b, 0x9a, 0x9f, 0x31, 0x3e, 0x87, 0x95, 0x91, 0xe0, 0x4c, 0x5a, 0x62, 0x2c, - 0xb5, 0x49, 0x15, 0xf5, 0xc3, 0x8d, 0x22, 0xdd, 0x91, 0x3b, 0x1f, 0xc4, 0xc7, 0xfd, 0x05, 0x5c, - 0x1f, 0xe5, 0xdb, 0xde, 0x1f, 0xb0, 0x29, 0x14, 0x0d, 0xc8, 0x30, 0x91, 0xc9, 0x8a, 0x22, 0xf6, - 0x53, 0xc4, 0xbc, 0x0e, 0x6c, 0xde, 0x5b, 0x09, 0x42, 0x50, 0x91, 0x74, 0xcc, 0x5c, 0xf9, 0x35, - 0xec, 0xd6, 0xde, 0xe7, 0x0a, 0xd4, 0x0b, 0x62, 0xa8, 0x0b, 0x35, 0x9b, 0x75, 0x30, 0xbd, 0xe7, - 0xef, 0xc5, 0xc2, 0x66, 0xed, 0xc5, 0x39, 0x0e, 0xfd, 0x03, 0xbf, 0xc9, 0xc9, 0x98, 0x8c, 0xa8, - 0x10, 0x26, 0xbe, 0x93, 0xb6, 0x2c, 0x70, 0xb7, 0x2a, 0xe3, 0x55, 0x39, 0x19, 0x1f, 0xc5, 0xf1, - 0x41, 0x12, 0x46, 0xfb, 0x80, 0x72, 0xec, 0x05, 0x97, 0xdc, 0x5c, 0xb2, 0xa0, 0x55, 0x76, 0xe0, - 0x46, 0x06, 0x3e, 0x49, 0xe3, 0x88, 0x80, 0x7f, 0x17, 0x4d, 0xae, 0xb9, 0xbd, 0x24, 0x81, 0x56, - 0x11, 0xb9, 0x50, 0x9a, 0x68, 0x6a, 0x19, 0x11, 0x7c, 0xcc, 0x2d, 0x97, 0x61, 0xab, 0xe2, 0x98, - 0xfe, 0xbe, 0xcd, 0xf4, 0x8e, 0xdb, 0xcb, 0x63, 0xad, 0xa2, 0x13, 0xa5, 0x31, 0xb5, 0xec, 0x2c, - 0x85, 0x23, 0x0a, 0x9d, 0x47, 0x05, 0x0a, 0xed, 0x8e, 0x15, 0x16, 0x9d, 0x42, 0xfb, 0x01, 0x85, - 0xbc, 0xf7, 0xb1, 0xc4, 0x07, 0xf8, 0xf7, 0x3e, 0x89, 0xf4, 0x19, 0x5c, 0x50, 0x2e, 0x58, 0x40, - 0xac, 0x22, 0x86, 0xc9, 0xa0, 0xb5, 0xe4, 0x04, 0xf6, 0xe6, 0x09, 0x24, 0x7f, 0xd5, 0x89, 0xc3, - 0x9f, 0xab, 0x01, 0x93, 0x01, 0xea, 0xc3, 0x9f, 0x73, 0xe8, 0xaf, 0xa4, 0xba, 0x96, 0x44, 0xb3, - 0x11, 0xe3, 0x53, 0x16, 0xb4, 0x96, 0x1d, 0xe5, 0xce, 0x6d, 0xca, 0xd7, 0x31, 0x0a, 0xa7, 0x20, - 0xef, 0x5b, 0x09, 0xd6, 0x6e, 0x3c, 0x1b, 0x13, 0x29, 0x69, 0x18, 0x1a, 0x40, 0x23, 0x77, 0x40, - 0x12, 0x4b, 0x9f, 0xc6, 0xde, 0x63, 0x16, 0x48, 0xd0, 0xfd, 0x05, 0xbc, 0x3a, 0xf3, 0x40, 0x4a, - 0xfa, 0x04, 0xea, 0x86, 0xe9, 0x29, 0xd3, 0x44, 0x70, 0x63, 0x53, 0x0f, 0xac, 0x17, 0xf9, 0x06, - 0xee, 0xf8, 0x8c, 0x3b, 0x0f, 0x81, 0x99, 0xed, 0x7a, 0xdb, 0xb0, 0x75, 0xcb, 0x01, 0x09, 0x67, - 0x62, 0x81, 0x2f, 0x25, 0xd8, 0xba, 0xbf, 0x14, 0xf4, 0x1f, 0xac, 0x17, 0x93, 0x35, 0x09, 0x98, - 0x60, 0x21, 0xb5, 0x99, 0x2d, 0x9a, 0x22, 0x4f, 0xd2, 0xc7, 0xe9, 0x19, 0x7a, 0x0b, 0xdb, 0x45, - 0xcb, 0x12, 0xcd, 0x22, 0xa5, 0x2d, 0xe1, 0xd2, 0x32, 0x3d, 0xa5, 0x22, 0x2d, 0xbf, 0x59, 0x2c, - 0x3f, 0x1b, 0x62, 0x78, 0xb3, 0xe0, 0x5e, 0xec, 0xf2, 0x4e, 0xd3, 0x34, 0xef, 0x05, 0x40, 0x7e, - 0x4b, 0xb4, 0x1f, 0x0f, 0xac, 0x78, 0x17, 0x0f, 0xac, 0x72, 0xbb, 0x7e, 0x88, 0xee, 0xb6, 0x03, - 0x67, 0x90, 0x57, 0x95, 0x6a, 0xb9, 0x51, 0xf1, 0xbe, 0x97, 0x60, 0x29, 0x39, 0x41, 0x3b, 0x00, - 0x3c, 0x22, 0x34, 0x08, 0x34, 0x33, 0xc9, 0xc8, 0x5b, 0xc1, 0x35, 0x1e, 0xbd, 0x4c, 0x02, 0xb1, - 0xfb, 0x63, 0xed, 0x74, 0xe6, 0xb9, 0x75, 0x6c, 0xc6, 0x1b, 0x9d, 0xb4, 0xea, 0x8a, 0x49, 0x67, - 0xc6, 0x1a, 0x6e, 0x14, 0x1a, 0x71, 0x1e, 0xc7, 0x51, 0x17, 0xd6, 0x1f, 0x30, 0x5d, 0x15, 0xaf, - 0x05, 0x73, 0x0c, 0xf6, 0x3f, 0x6c, 0x3c, 0x64, 0xa4, 0x2a, 0x6e, 0x06, 0x73, 0x4c, 0xd3, 0xeb, - 0xbe, 0x3f, 0x08, 0x95, 0x0a, 0x05, 0xf3, 0x43, 0x25, 0xa8, 0x0c, 0x7d, 0xa5, 0xc3, 0x4e, 0xdc, - 0x0d, 0xf7, 0x23, 0x86, 0x9d, 0x39, 0x5f, 0x95, 0xe1, 0x92, 0xfb, 0x9a, 0x74, 0x7f, 0x04, 0x00, - 0x00, 0xff, 0xff, 0x8e, 0xd0, 0x70, 0xb7, 0x73, 0x06, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/grpclb_picker.go b/vendor/google.golang.org/grpc/grpclb_picker.go deleted file mode 100644 index 872c7ccea..000000000 --- a/vendor/google.golang.org/grpc/grpclb_picker.go +++ /dev/null @@ -1,159 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "sync" - "sync/atomic" - - "golang.org/x/net/context" - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/codes" - lbpb "google.golang.org/grpc/grpclb/grpc_lb_v1/messages" - "google.golang.org/grpc/status" -) - -type rpcStats struct { - NumCallsStarted int64 - NumCallsFinished int64 - NumCallsFinishedWithDropForRateLimiting int64 - NumCallsFinishedWithDropForLoadBalancing int64 - NumCallsFinishedWithClientFailedToSend int64 - NumCallsFinishedKnownReceived int64 -} - -// toClientStats converts rpcStats to lbpb.ClientStats, and clears rpcStats. -func (s *rpcStats) toClientStats() *lbpb.ClientStats { - stats := &lbpb.ClientStats{ - NumCallsStarted: atomic.SwapInt64(&s.NumCallsStarted, 0), - NumCallsFinished: atomic.SwapInt64(&s.NumCallsFinished, 0), - NumCallsFinishedWithDropForRateLimiting: atomic.SwapInt64(&s.NumCallsFinishedWithDropForRateLimiting, 0), - NumCallsFinishedWithDropForLoadBalancing: atomic.SwapInt64(&s.NumCallsFinishedWithDropForLoadBalancing, 0), - NumCallsFinishedWithClientFailedToSend: atomic.SwapInt64(&s.NumCallsFinishedWithClientFailedToSend, 0), - NumCallsFinishedKnownReceived: atomic.SwapInt64(&s.NumCallsFinishedKnownReceived, 0), - } - return stats -} - -func (s *rpcStats) dropForRateLimiting() { - atomic.AddInt64(&s.NumCallsStarted, 1) - atomic.AddInt64(&s.NumCallsFinishedWithDropForRateLimiting, 1) - atomic.AddInt64(&s.NumCallsFinished, 1) -} - -func (s *rpcStats) dropForLoadBalancing() { - atomic.AddInt64(&s.NumCallsStarted, 1) - atomic.AddInt64(&s.NumCallsFinishedWithDropForLoadBalancing, 1) - atomic.AddInt64(&s.NumCallsFinished, 1) -} - -func (s *rpcStats) failedToSend() { - atomic.AddInt64(&s.NumCallsStarted, 1) - atomic.AddInt64(&s.NumCallsFinishedWithClientFailedToSend, 1) - atomic.AddInt64(&s.NumCallsFinished, 1) -} - -func (s *rpcStats) knownReceived() { - atomic.AddInt64(&s.NumCallsStarted, 1) - atomic.AddInt64(&s.NumCallsFinishedKnownReceived, 1) - atomic.AddInt64(&s.NumCallsFinished, 1) -} - -type errPicker struct { - // Pick always returns this err. - err error -} - -func (p *errPicker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { - return nil, nil, p.err -} - -// rrPicker does roundrobin on subConns. It's typically used when there's no -// response from remote balancer, and grpclb falls back to the resolved -// backends. -// -// It guaranteed that len(subConns) > 0. -type rrPicker struct { - mu sync.Mutex - subConns []balancer.SubConn // The subConns that were READY when taking the snapshot. - subConnsNext int -} - -func (p *rrPicker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { - p.mu.Lock() - defer p.mu.Unlock() - sc := p.subConns[p.subConnsNext] - p.subConnsNext = (p.subConnsNext + 1) % len(p.subConns) - return sc, nil, nil -} - -// lbPicker does two layers of picks: -// -// First layer: roundrobin on all servers in serverList, including drops and backends. -// - If it picks a drop, the RPC will fail as being dropped. -// - If it picks a backend, do a second layer pick to pick the real backend. -// -// Second layer: roundrobin on all READY backends. -// -// It's guaranteed that len(serverList) > 0. -type lbPicker struct { - mu sync.Mutex - serverList []*lbpb.Server - serverListNext int - subConns []balancer.SubConn // The subConns that were READY when taking the snapshot. - subConnsNext int - - stats *rpcStats -} - -func (p *lbPicker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { - p.mu.Lock() - defer p.mu.Unlock() - - // Layer one roundrobin on serverList. - s := p.serverList[p.serverListNext] - p.serverListNext = (p.serverListNext + 1) % len(p.serverList) - - // If it's a drop, return an error and fail the RPC. - if s.DropForRateLimiting { - p.stats.dropForRateLimiting() - return nil, nil, status.Errorf(codes.Unavailable, "request dropped by grpclb") - } - if s.DropForLoadBalancing { - p.stats.dropForLoadBalancing() - return nil, nil, status.Errorf(codes.Unavailable, "request dropped by grpclb") - } - - // If not a drop but there's no ready subConns. - if len(p.subConns) <= 0 { - return nil, nil, balancer.ErrNoSubConnAvailable - } - - // Return the next ready subConn in the list, also collect rpc stats. - sc := p.subConns[p.subConnsNext] - p.subConnsNext = (p.subConnsNext + 1) % len(p.subConns) - done := func(info balancer.DoneInfo) { - if !info.BytesSent { - p.stats.failedToSend() - } else if info.BytesReceived { - p.stats.knownReceived() - } - } - return sc, done, nil -} diff --git a/vendor/google.golang.org/grpc/grpclb_remote_balancer.go b/vendor/google.golang.org/grpc/grpclb_remote_balancer.go deleted file mode 100644 index b8dd4f18c..000000000 --- a/vendor/google.golang.org/grpc/grpclb_remote_balancer.go +++ /dev/null @@ -1,266 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "fmt" - "net" - "reflect" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/channelz" - - "google.golang.org/grpc/connectivity" - lbpb "google.golang.org/grpc/grpclb/grpc_lb_v1/messages" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/resolver" -) - -// processServerList updates balaner's internal state, create/remove SubConns -// and regenerates picker using the received serverList. -func (lb *lbBalancer) processServerList(l *lbpb.ServerList) { - grpclog.Infof("lbBalancer: processing server list: %+v", l) - lb.mu.Lock() - defer lb.mu.Unlock() - - // Set serverListReceived to true so fallback will not take effect if it has - // not hit timeout. - lb.serverListReceived = true - - // If the new server list == old server list, do nothing. - if reflect.DeepEqual(lb.fullServerList, l.Servers) { - grpclog.Infof("lbBalancer: new serverlist same as the previous one, ignoring") - return - } - lb.fullServerList = l.Servers - - var backendAddrs []resolver.Address - for _, s := range l.Servers { - if s.DropForLoadBalancing || s.DropForRateLimiting { - continue - } - - md := metadata.Pairs(lbTokeyKey, s.LoadBalanceToken) - ip := net.IP(s.IpAddress) - ipStr := ip.String() - if ip.To4() == nil { - // Add square brackets to ipv6 addresses, otherwise net.Dial() and - // net.SplitHostPort() will return too many colons error. - ipStr = fmt.Sprintf("[%s]", ipStr) - } - addr := resolver.Address{ - Addr: fmt.Sprintf("%s:%d", ipStr, s.Port), - Metadata: &md, - } - - backendAddrs = append(backendAddrs, addr) - } - - // Call refreshSubConns to create/remove SubConns. - lb.refreshSubConns(backendAddrs) - // Regenerate and update picker no matter if there's update on backends (if - // any SubConn will be newed/removed). Because since the full serverList was - // different, there might be updates in drops or pick weights(different - // number of duplicates). We need to update picker with the fulllist. - // - // Now with cache, even if SubConn was newed/removed, there might be no - // state changes. - lb.regeneratePicker() - lb.cc.UpdateBalancerState(lb.state, lb.picker) -} - -// refreshSubConns creates/removes SubConns with backendAddrs. It returns a bool -// indicating whether the backendAddrs are different from the cached -// backendAddrs (whether any SubConn was newed/removed). -// Caller must hold lb.mu. -func (lb *lbBalancer) refreshSubConns(backendAddrs []resolver.Address) bool { - lb.backendAddrs = nil - var backendsUpdated bool - // addrsSet is the set converted from backendAddrs, it's used to quick - // lookup for an address. - addrsSet := make(map[resolver.Address]struct{}) - // Create new SubConns. - for _, addr := range backendAddrs { - addrWithoutMD := addr - addrWithoutMD.Metadata = nil - addrsSet[addrWithoutMD] = struct{}{} - lb.backendAddrs = append(lb.backendAddrs, addrWithoutMD) - - if _, ok := lb.subConns[addrWithoutMD]; !ok { - backendsUpdated = true - - // Use addrWithMD to create the SubConn. - sc, err := lb.cc.NewSubConn([]resolver.Address{addr}, balancer.NewSubConnOptions{}) - if err != nil { - grpclog.Warningf("roundrobinBalancer: failed to create new SubConn: %v", err) - continue - } - lb.subConns[addrWithoutMD] = sc // Use the addr without MD as key for the map. - if _, ok := lb.scStates[sc]; !ok { - // Only set state of new sc to IDLE. The state could already be - // READY for cached SubConns. - lb.scStates[sc] = connectivity.Idle - } - sc.Connect() - } - } - - for a, sc := range lb.subConns { - // a was removed by resolver. - if _, ok := addrsSet[a]; !ok { - backendsUpdated = true - - lb.cc.RemoveSubConn(sc) - delete(lb.subConns, a) - // Keep the state of this sc in b.scStates until sc's state becomes Shutdown. - // The entry will be deleted in HandleSubConnStateChange. - } - } - - return backendsUpdated -} - -func (lb *lbBalancer) readServerList(s *balanceLoadClientStream) error { - for { - reply, err := s.Recv() - if err != nil { - return fmt.Errorf("grpclb: failed to recv server list: %v", err) - } - if serverList := reply.GetServerList(); serverList != nil { - lb.processServerList(serverList) - } - } -} - -func (lb *lbBalancer) sendLoadReport(s *balanceLoadClientStream, interval time.Duration) { - ticker := time.NewTicker(interval) - defer ticker.Stop() - for { - select { - case <-ticker.C: - case <-s.Context().Done(): - return - } - stats := lb.clientStats.toClientStats() - t := time.Now() - stats.Timestamp = &lbpb.Timestamp{ - Seconds: t.Unix(), - Nanos: int32(t.Nanosecond()), - } - if err := s.Send(&lbpb.LoadBalanceRequest{ - LoadBalanceRequestType: &lbpb.LoadBalanceRequest_ClientStats{ - ClientStats: stats, - }, - }); err != nil { - return - } - } -} - -func (lb *lbBalancer) callRemoteBalancer() error { - lbClient := &loadBalancerClient{cc: lb.ccRemoteLB} - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - stream, err := lbClient.BalanceLoad(ctx, FailFast(false)) - if err != nil { - return fmt.Errorf("grpclb: failed to perform RPC to the remote balancer %v", err) - } - - // grpclb handshake on the stream. - initReq := &lbpb.LoadBalanceRequest{ - LoadBalanceRequestType: &lbpb.LoadBalanceRequest_InitialRequest{ - InitialRequest: &lbpb.InitialLoadBalanceRequest{ - Name: lb.target, - }, - }, - } - if err := stream.Send(initReq); err != nil { - return fmt.Errorf("grpclb: failed to send init request: %v", err) - } - reply, err := stream.Recv() - if err != nil { - return fmt.Errorf("grpclb: failed to recv init response: %v", err) - } - initResp := reply.GetInitialResponse() - if initResp == nil { - return fmt.Errorf("grpclb: reply from remote balancer did not include initial response") - } - if initResp.LoadBalancerDelegate != "" { - return fmt.Errorf("grpclb: Delegation is not supported") - } - - go func() { - if d := convertDuration(initResp.ClientStatsReportInterval); d > 0 { - lb.sendLoadReport(stream, d) - } - }() - return lb.readServerList(stream) -} - -func (lb *lbBalancer) watchRemoteBalancer() { - for { - err := lb.callRemoteBalancer() - select { - case <-lb.doneCh: - return - default: - if err != nil { - grpclog.Error(err) - } - } - - } -} - -func (lb *lbBalancer) dialRemoteLB(remoteLBName string) { - var dopts []DialOption - if creds := lb.opt.DialCreds; creds != nil { - if err := creds.OverrideServerName(remoteLBName); err == nil { - dopts = append(dopts, WithTransportCredentials(creds)) - } else { - grpclog.Warningf("grpclb: failed to override the server name in the credentials: %v, using Insecure", err) - dopts = append(dopts, WithInsecure()) - } - } else { - dopts = append(dopts, WithInsecure()) - } - if lb.opt.Dialer != nil { - // WithDialer takes a different type of function, so we instead use a - // special DialOption here. - dopts = append(dopts, withContextDialer(lb.opt.Dialer)) - } - // Explicitly set pickfirst as the balancer. - dopts = append(dopts, WithBalancerName(PickFirstBalancerName)) - dopts = append(dopts, withResolverBuilder(lb.manualResolver)) - if channelz.IsOn() { - dopts = append(dopts, WithChannelzParentID(lb.opt.ChannelzParentID)) - } - - // DialContext using manualResolver.Scheme, which is a random scheme generated - // when init grpclb. The target name is not important. - cc, err := DialContext(context.Background(), "grpclb:///grpclb.server", dopts...) - if err != nil { - grpclog.Fatalf("failed to dial: %v", err) - } - lb.ccRemoteLB = cc - go lb.watchRemoteBalancer() -} diff --git a/vendor/google.golang.org/grpc/grpclb_util.go b/vendor/google.golang.org/grpc/grpclb_util.go deleted file mode 100644 index 063ba9d85..000000000 --- a/vendor/google.golang.org/grpc/grpclb_util.go +++ /dev/null @@ -1,214 +0,0 @@ -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "fmt" - "sync" - "time" - - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/resolver" -) - -// The parent ClientConn should re-resolve when grpclb loses connection to the -// remote balancer. When the ClientConn inside grpclb gets a TransientFailure, -// it calls lbManualResolver.ResolveNow(), which calls parent ClientConn's -// ResolveNow, and eventually results in re-resolve happening in parent -// ClientConn's resolver (DNS for example). -// -// parent -// ClientConn -// +-----------------------------------------------------------------+ -// | parent +---------------------------------+ | -// | DNS ClientConn | grpclb | | -// | resolver balancerWrapper | | | -// | + + | grpclb grpclb | | -// | | | | ManualResolver ClientConn | | -// | | | | + + | | -// | | | | | | Transient | | -// | | | | | | Failure | | -// | | | | | <--------- | | | -// | | | <--------------- | ResolveNow | | | -// | | <--------- | ResolveNow | | | | | -// | | ResolveNow | | | | | | -// | | | | | | | | -// | + + | + + | | -// | +---------------------------------+ | -// +-----------------------------------------------------------------+ - -// lbManualResolver is used by the ClientConn inside grpclb. It's a manual -// resolver with a special ResolveNow() function. -// -// When ResolveNow() is called, it calls ResolveNow() on the parent ClientConn, -// so when grpclb client lose contact with remote balancers, the parent -// ClientConn's resolver will re-resolve. -type lbManualResolver struct { - scheme string - ccr resolver.ClientConn - - ccb balancer.ClientConn -} - -func (r *lbManualResolver) Build(_ resolver.Target, cc resolver.ClientConn, _ resolver.BuildOption) (resolver.Resolver, error) { - r.ccr = cc - return r, nil -} - -func (r *lbManualResolver) Scheme() string { - return r.scheme -} - -// ResolveNow calls resolveNow on the parent ClientConn. -func (r *lbManualResolver) ResolveNow(o resolver.ResolveNowOption) { - r.ccb.ResolveNow(o) -} - -// Close is a noop for Resolver. -func (*lbManualResolver) Close() {} - -// NewAddress calls cc.NewAddress. -func (r *lbManualResolver) NewAddress(addrs []resolver.Address) { - r.ccr.NewAddress(addrs) -} - -// NewServiceConfig calls cc.NewServiceConfig. -func (r *lbManualResolver) NewServiceConfig(sc string) { - r.ccr.NewServiceConfig(sc) -} - -const subConnCacheTime = time.Second * 10 - -// lbCacheClientConn is a wrapper balancer.ClientConn with a SubConn cache. -// SubConns will be kept in cache for subConnCacheTime before being removed. -// -// Its new and remove methods are updated to do cache first. -type lbCacheClientConn struct { - cc balancer.ClientConn - timeout time.Duration - - mu sync.Mutex - // subConnCache only keeps subConns that are being deleted. - subConnCache map[resolver.Address]*subConnCacheEntry - subConnToAddr map[balancer.SubConn]resolver.Address -} - -type subConnCacheEntry struct { - sc balancer.SubConn - - cancel func() - abortDeleting bool -} - -func newLBCacheClientConn(cc balancer.ClientConn) *lbCacheClientConn { - return &lbCacheClientConn{ - cc: cc, - timeout: subConnCacheTime, - subConnCache: make(map[resolver.Address]*subConnCacheEntry), - subConnToAddr: make(map[balancer.SubConn]resolver.Address), - } -} - -func (ccc *lbCacheClientConn) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) { - if len(addrs) != 1 { - return nil, fmt.Errorf("grpclb calling NewSubConn with addrs of length %v", len(addrs)) - } - addrWithoutMD := addrs[0] - addrWithoutMD.Metadata = nil - - ccc.mu.Lock() - defer ccc.mu.Unlock() - if entry, ok := ccc.subConnCache[addrWithoutMD]; ok { - // If entry is in subConnCache, the SubConn was being deleted. - // cancel function will never be nil. - entry.cancel() - delete(ccc.subConnCache, addrWithoutMD) - return entry.sc, nil - } - - scNew, err := ccc.cc.NewSubConn(addrs, opts) - if err != nil { - return nil, err - } - - ccc.subConnToAddr[scNew] = addrWithoutMD - return scNew, nil -} - -func (ccc *lbCacheClientConn) RemoveSubConn(sc balancer.SubConn) { - ccc.mu.Lock() - defer ccc.mu.Unlock() - addr, ok := ccc.subConnToAddr[sc] - if !ok { - return - } - - if entry, ok := ccc.subConnCache[addr]; ok { - if entry.sc != sc { - // This could happen if NewSubConn was called multiple times for the - // same address, and those SubConns are all removed. We remove sc - // immediately here. - delete(ccc.subConnToAddr, sc) - ccc.cc.RemoveSubConn(sc) - } - return - } - - entry := &subConnCacheEntry{ - sc: sc, - } - ccc.subConnCache[addr] = entry - - timer := time.AfterFunc(ccc.timeout, func() { - ccc.mu.Lock() - if entry.abortDeleting { - return - } - ccc.cc.RemoveSubConn(sc) - delete(ccc.subConnToAddr, sc) - delete(ccc.subConnCache, addr) - ccc.mu.Unlock() - }) - entry.cancel = func() { - if !timer.Stop() { - // If stop was not successful, the timer has fired (this can only - // happen in a race). But the deleting function is blocked on ccc.mu - // because the mutex was held by the caller of this function. - // - // Set abortDeleting to true to abort the deleting function. When - // the lock is released, the deleting function will acquire the - // lock, check the value of abortDeleting and return. - entry.abortDeleting = true - } - } -} - -func (ccc *lbCacheClientConn) UpdateBalancerState(s connectivity.State, p balancer.Picker) { - ccc.cc.UpdateBalancerState(s, p) -} - -func (ccc *lbCacheClientConn) close() { - ccc.mu.Lock() - // Only cancel all existing timers. There's no need to remove SubConns. - for _, entry := range ccc.subConnCache { - entry.cancel() - } - ccc.mu.Unlock() -} diff --git a/vendor/google.golang.org/grpc/internal/backoff/backoff.go b/vendor/google.golang.org/grpc/internal/backoff/backoff.go new file mode 100644 index 000000000..1bd0cce5a --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/backoff/backoff.go @@ -0,0 +1,78 @@ +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Package backoff implement the backoff strategy for gRPC. +// +// This is kept in internal until the gRPC project decides whether or not to +// allow alternative backoff strategies. +package backoff + +import ( + "time" + + "google.golang.org/grpc/internal/grpcrand" +) + +// Strategy defines the methodology for backing off after a grpc connection +// failure. +// +type Strategy interface { + // Backoff returns the amount of time to wait before the next retry given + // the number of consecutive failures. + Backoff(retries int) time.Duration +} + +const ( + // baseDelay is the amount of time to wait before retrying after the first + // failure. + baseDelay = 1.0 * time.Second + // factor is applied to the backoff after each retry. + factor = 1.6 + // jitter provides a range to randomize backoff delays. + jitter = 0.2 +) + +// Exponential implements exponential backoff algorithm as defined in +// https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. +type Exponential struct { + // MaxDelay is the upper bound of backoff delay. + MaxDelay time.Duration +} + +// Backoff returns the amount of time to wait before the next retry given the +// number of retries. +func (bc Exponential) Backoff(retries int) time.Duration { + if retries == 0 { + return baseDelay + } + backoff, max := float64(baseDelay), float64(bc.MaxDelay) + for backoff < max && retries > 0 { + backoff *= factor + retries-- + } + if backoff > max { + backoff = max + } + // Randomize backoff delays so that if a cluster of requests start at + // the same time, they won't operate in lockstep. + backoff *= 1 + jitter*(grpcrand.Float64()*2-1) + if backoff < 0 { + return 0 + } + return time.Duration(backoff) +} diff --git a/vendor/google.golang.org/grpc/channelz/funcs.go b/vendor/google.golang.org/grpc/internal/channelz/funcs.go similarity index 100% rename from vendor/google.golang.org/grpc/channelz/funcs.go rename to vendor/google.golang.org/grpc/internal/channelz/funcs.go diff --git a/vendor/google.golang.org/grpc/channelz/types.go b/vendor/google.golang.org/grpc/internal/channelz/types.go similarity index 100% rename from vendor/google.golang.org/grpc/channelz/types.go rename to vendor/google.golang.org/grpc/internal/channelz/types.go diff --git a/vendor/google.golang.org/grpc/internal/grpcrand/grpcrand.go b/vendor/google.golang.org/grpc/internal/grpcrand/grpcrand.go new file mode 100644 index 000000000..200b115ca --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/grpcrand/grpcrand.go @@ -0,0 +1,56 @@ +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Package grpcrand implements math/rand functions in a concurrent-safe way +// with a global random source, independent of math/rand's global source. +package grpcrand + +import ( + "math/rand" + "sync" + "time" +) + +var ( + r = rand.New(rand.NewSource(time.Now().UnixNano())) + mu sync.Mutex +) + +// Int63n implements rand.Int63n on the grpcrand global source. +func Int63n(n int64) int64 { + mu.Lock() + res := r.Int63n(n) + mu.Unlock() + return res +} + +// Intn implements rand.Intn on the grpcrand global source. +func Intn(n int) int { + mu.Lock() + res := r.Intn(n) + mu.Unlock() + return res +} + +// Float64 implements rand.Float64 on the grpcrand global source. +func Float64() float64 { + mu.Lock() + res := r.Float64() + mu.Unlock() + return res +} diff --git a/vendor/google.golang.org/grpc/internal/internal.go b/vendor/google.golang.org/grpc/internal/internal.go index 53f177520..cd34267f7 100644 --- a/vendor/google.golang.org/grpc/internal/internal.go +++ b/vendor/google.golang.org/grpc/internal/internal.go @@ -15,13 +15,22 @@ * */ -// Package internal contains gRPC-internal code for testing, to avoid polluting -// the godoc of the top-level grpc package. +// Package internal contains gRPC-internal code, to avoid polluting +// the godoc of the top-level grpc package. It must not import any grpc +// symbols to avoid circular dependencies. package internal -// TestingUseHandlerImpl enables the http.Handler-based server implementation. -// It must be called before Serve and requires TLS credentials. -// -// The provided grpcServer must be of type *grpc.Server. It is untyped -// for circular dependency reasons. -var TestingUseHandlerImpl func(grpcServer interface{}) +var ( + + // TestingUseHandlerImpl enables the http.Handler-based server implementation. + // It must be called before Serve and requires TLS credentials. + // + // The provided grpcServer must be of type *grpc.Server. It is untyped + // for circular dependency reasons. + TestingUseHandlerImpl func(grpcServer interface{}) + + // WithContextDialer is exported by clientconn.go + WithContextDialer interface{} // func(context.Context, string) (net.Conn, error) grpc.DialOption + // WithResolverBuilder is exported by clientconn.go + WithResolverBuilder interface{} // func (resolver.Builder) grpc.DialOption +) diff --git a/vendor/google.golang.org/grpc/picker_wrapper.go b/vendor/google.golang.org/grpc/picker_wrapper.go index 0a984e6c8..019e65800 100644 --- a/vendor/google.golang.org/grpc/picker_wrapper.go +++ b/vendor/google.golang.org/grpc/picker_wrapper.go @@ -25,9 +25,9 @@ import ( "golang.org/x/net/context" "google.golang.org/grpc/balancer" - "google.golang.org/grpc/channelz" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/metadata" "google.golang.org/grpc/resolver" "google.golang.org/grpc/status" @@ -233,6 +233,8 @@ func (bp *pickerWrapper) close() { close(bp.blockingCh) } +const stickinessKeyCountLimit = 1000 + type stickyStoreEntry struct { acw *acBalancerWrapper addr resolver.Address @@ -243,12 +245,12 @@ type stickyStore struct { // curMDKey is check before every get/put to avoid races. The operation will // abort immediately when the given mdKey is different from the curMDKey. curMDKey string - store map[string]*stickyStoreEntry + store *linkedMap } func newStickyStore() *stickyStore { return &stickyStore{ - store: make(map[string]*stickyStoreEntry), + store: newLinkedMap(), } } @@ -256,7 +258,7 @@ func newStickyStore() *stickyStore { func (ss *stickyStore) reset(newMDKey string) { ss.mu.Lock() ss.curMDKey = newMDKey - ss.store = make(map[string]*stickyStoreEntry) + ss.store.clear() ss.mu.Unlock() } @@ -269,9 +271,12 @@ func (ss *stickyStore) put(mdKey, stickyKey string, acw *acBalancerWrapper) { return } // TODO(stickiness): limit the total number of entries. - ss.store[stickyKey] = &stickyStoreEntry{ + ss.store.put(stickyKey, &stickyStoreEntry{ acw: acw, addr: acw.getAddrConn().getCurAddr(), + }) + if ss.store.len() > stickinessKeyCountLimit { + ss.store.removeOldest() } } @@ -283,18 +288,18 @@ func (ss *stickyStore) get(mdKey, stickyKey string) (transport.ClientTransport, if mdKey != ss.curMDKey { return nil, false } - entry, ok := ss.store[stickyKey] + entry, ok := ss.store.get(stickyKey) if !ok { return nil, false } ac := entry.acw.getAddrConn() if ac.getCurAddr() != entry.addr { - delete(ss.store, stickyKey) + ss.store.remove(stickyKey) return nil, false } t, ok := ac.getReadyTransport() if !ok { - delete(ss.store, stickyKey) + ss.store.remove(stickyKey) return nil, false } return t, true diff --git a/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.pb.go b/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.pb.go deleted file mode 100644 index ab5b18893..000000000 --- a/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.pb.go +++ /dev/null @@ -1,925 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc_reflection_v1alpha/reflection.proto - -package grpc_reflection_v1alpha - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// The message sent by the client when calling ServerReflectionInfo method. -type ServerReflectionRequest struct { - Host string `protobuf:"bytes,1,opt,name=host" json:"host,omitempty"` - // To use reflection service, the client should set one of the following - // fields in message_request. The server distinguishes requests by their - // defined field and then handles them using corresponding methods. - // - // Types that are valid to be assigned to MessageRequest: - // *ServerReflectionRequest_FileByFilename - // *ServerReflectionRequest_FileContainingSymbol - // *ServerReflectionRequest_FileContainingExtension - // *ServerReflectionRequest_AllExtensionNumbersOfType - // *ServerReflectionRequest_ListServices - MessageRequest isServerReflectionRequest_MessageRequest `protobuf_oneof:"message_request"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServerReflectionRequest) Reset() { *m = ServerReflectionRequest{} } -func (m *ServerReflectionRequest) String() string { return proto.CompactTextString(m) } -func (*ServerReflectionRequest) ProtoMessage() {} -func (*ServerReflectionRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_reflection_178bd1e101bf8b63, []int{0} -} -func (m *ServerReflectionRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServerReflectionRequest.Unmarshal(m, b) -} -func (m *ServerReflectionRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServerReflectionRequest.Marshal(b, m, deterministic) -} -func (dst *ServerReflectionRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServerReflectionRequest.Merge(dst, src) -} -func (m *ServerReflectionRequest) XXX_Size() int { - return xxx_messageInfo_ServerReflectionRequest.Size(m) -} -func (m *ServerReflectionRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ServerReflectionRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ServerReflectionRequest proto.InternalMessageInfo - -type isServerReflectionRequest_MessageRequest interface { - isServerReflectionRequest_MessageRequest() -} - -type ServerReflectionRequest_FileByFilename struct { - FileByFilename string `protobuf:"bytes,3,opt,name=file_by_filename,json=fileByFilename,oneof"` -} -type ServerReflectionRequest_FileContainingSymbol struct { - FileContainingSymbol string `protobuf:"bytes,4,opt,name=file_containing_symbol,json=fileContainingSymbol,oneof"` -} -type ServerReflectionRequest_FileContainingExtension struct { - FileContainingExtension *ExtensionRequest `protobuf:"bytes,5,opt,name=file_containing_extension,json=fileContainingExtension,oneof"` -} -type ServerReflectionRequest_AllExtensionNumbersOfType struct { - AllExtensionNumbersOfType string `protobuf:"bytes,6,opt,name=all_extension_numbers_of_type,json=allExtensionNumbersOfType,oneof"` -} -type ServerReflectionRequest_ListServices struct { - ListServices string `protobuf:"bytes,7,opt,name=list_services,json=listServices,oneof"` -} - -func (*ServerReflectionRequest_FileByFilename) isServerReflectionRequest_MessageRequest() {} -func (*ServerReflectionRequest_FileContainingSymbol) isServerReflectionRequest_MessageRequest() {} -func (*ServerReflectionRequest_FileContainingExtension) isServerReflectionRequest_MessageRequest() {} -func (*ServerReflectionRequest_AllExtensionNumbersOfType) isServerReflectionRequest_MessageRequest() {} -func (*ServerReflectionRequest_ListServices) isServerReflectionRequest_MessageRequest() {} - -func (m *ServerReflectionRequest) GetMessageRequest() isServerReflectionRequest_MessageRequest { - if m != nil { - return m.MessageRequest - } - return nil -} - -func (m *ServerReflectionRequest) GetHost() string { - if m != nil { - return m.Host - } - return "" -} - -func (m *ServerReflectionRequest) GetFileByFilename() string { - if x, ok := m.GetMessageRequest().(*ServerReflectionRequest_FileByFilename); ok { - return x.FileByFilename - } - return "" -} - -func (m *ServerReflectionRequest) GetFileContainingSymbol() string { - if x, ok := m.GetMessageRequest().(*ServerReflectionRequest_FileContainingSymbol); ok { - return x.FileContainingSymbol - } - return "" -} - -func (m *ServerReflectionRequest) GetFileContainingExtension() *ExtensionRequest { - if x, ok := m.GetMessageRequest().(*ServerReflectionRequest_FileContainingExtension); ok { - return x.FileContainingExtension - } - return nil -} - -func (m *ServerReflectionRequest) GetAllExtensionNumbersOfType() string { - if x, ok := m.GetMessageRequest().(*ServerReflectionRequest_AllExtensionNumbersOfType); ok { - return x.AllExtensionNumbersOfType - } - return "" -} - -func (m *ServerReflectionRequest) GetListServices() string { - if x, ok := m.GetMessageRequest().(*ServerReflectionRequest_ListServices); ok { - return x.ListServices - } - return "" -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*ServerReflectionRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _ServerReflectionRequest_OneofMarshaler, _ServerReflectionRequest_OneofUnmarshaler, _ServerReflectionRequest_OneofSizer, []interface{}{ - (*ServerReflectionRequest_FileByFilename)(nil), - (*ServerReflectionRequest_FileContainingSymbol)(nil), - (*ServerReflectionRequest_FileContainingExtension)(nil), - (*ServerReflectionRequest_AllExtensionNumbersOfType)(nil), - (*ServerReflectionRequest_ListServices)(nil), - } -} - -func _ServerReflectionRequest_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*ServerReflectionRequest) - // message_request - switch x := m.MessageRequest.(type) { - case *ServerReflectionRequest_FileByFilename: - b.EncodeVarint(3<<3 | proto.WireBytes) - b.EncodeStringBytes(x.FileByFilename) - case *ServerReflectionRequest_FileContainingSymbol: - b.EncodeVarint(4<<3 | proto.WireBytes) - b.EncodeStringBytes(x.FileContainingSymbol) - case *ServerReflectionRequest_FileContainingExtension: - b.EncodeVarint(5<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.FileContainingExtension); err != nil { - return err - } - case *ServerReflectionRequest_AllExtensionNumbersOfType: - b.EncodeVarint(6<<3 | proto.WireBytes) - b.EncodeStringBytes(x.AllExtensionNumbersOfType) - case *ServerReflectionRequest_ListServices: - b.EncodeVarint(7<<3 | proto.WireBytes) - b.EncodeStringBytes(x.ListServices) - case nil: - default: - return fmt.Errorf("ServerReflectionRequest.MessageRequest has unexpected type %T", x) - } - return nil -} - -func _ServerReflectionRequest_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*ServerReflectionRequest) - switch tag { - case 3: // message_request.file_by_filename - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.MessageRequest = &ServerReflectionRequest_FileByFilename{x} - return true, err - case 4: // message_request.file_containing_symbol - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.MessageRequest = &ServerReflectionRequest_FileContainingSymbol{x} - return true, err - case 5: // message_request.file_containing_extension - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ExtensionRequest) - err := b.DecodeMessage(msg) - m.MessageRequest = &ServerReflectionRequest_FileContainingExtension{msg} - return true, err - case 6: // message_request.all_extension_numbers_of_type - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.MessageRequest = &ServerReflectionRequest_AllExtensionNumbersOfType{x} - return true, err - case 7: // message_request.list_services - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.MessageRequest = &ServerReflectionRequest_ListServices{x} - return true, err - default: - return false, nil - } -} - -func _ServerReflectionRequest_OneofSizer(msg proto.Message) (n int) { - m := msg.(*ServerReflectionRequest) - // message_request - switch x := m.MessageRequest.(type) { - case *ServerReflectionRequest_FileByFilename: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.FileByFilename))) - n += len(x.FileByFilename) - case *ServerReflectionRequest_FileContainingSymbol: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.FileContainingSymbol))) - n += len(x.FileContainingSymbol) - case *ServerReflectionRequest_FileContainingExtension: - s := proto.Size(x.FileContainingExtension) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *ServerReflectionRequest_AllExtensionNumbersOfType: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.AllExtensionNumbersOfType))) - n += len(x.AllExtensionNumbersOfType) - case *ServerReflectionRequest_ListServices: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.ListServices))) - n += len(x.ListServices) - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -// The type name and extension number sent by the client when requesting -// file_containing_extension. -type ExtensionRequest struct { - // Fully-qualified type name. The format should be . - ContainingType string `protobuf:"bytes,1,opt,name=containing_type,json=containingType" json:"containing_type,omitempty"` - ExtensionNumber int32 `protobuf:"varint,2,opt,name=extension_number,json=extensionNumber" json:"extension_number,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ExtensionRequest) Reset() { *m = ExtensionRequest{} } -func (m *ExtensionRequest) String() string { return proto.CompactTextString(m) } -func (*ExtensionRequest) ProtoMessage() {} -func (*ExtensionRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_reflection_178bd1e101bf8b63, []int{1} -} -func (m *ExtensionRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ExtensionRequest.Unmarshal(m, b) -} -func (m *ExtensionRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ExtensionRequest.Marshal(b, m, deterministic) -} -func (dst *ExtensionRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ExtensionRequest.Merge(dst, src) -} -func (m *ExtensionRequest) XXX_Size() int { - return xxx_messageInfo_ExtensionRequest.Size(m) -} -func (m *ExtensionRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ExtensionRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ExtensionRequest proto.InternalMessageInfo - -func (m *ExtensionRequest) GetContainingType() string { - if m != nil { - return m.ContainingType - } - return "" -} - -func (m *ExtensionRequest) GetExtensionNumber() int32 { - if m != nil { - return m.ExtensionNumber - } - return 0 -} - -// The message sent by the server to answer ServerReflectionInfo method. -type ServerReflectionResponse struct { - ValidHost string `protobuf:"bytes,1,opt,name=valid_host,json=validHost" json:"valid_host,omitempty"` - OriginalRequest *ServerReflectionRequest `protobuf:"bytes,2,opt,name=original_request,json=originalRequest" json:"original_request,omitempty"` - // The server sets one of the following fields according to the - // message_request in the request. - // - // Types that are valid to be assigned to MessageResponse: - // *ServerReflectionResponse_FileDescriptorResponse - // *ServerReflectionResponse_AllExtensionNumbersResponse - // *ServerReflectionResponse_ListServicesResponse - // *ServerReflectionResponse_ErrorResponse - MessageResponse isServerReflectionResponse_MessageResponse `protobuf_oneof:"message_response"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServerReflectionResponse) Reset() { *m = ServerReflectionResponse{} } -func (m *ServerReflectionResponse) String() string { return proto.CompactTextString(m) } -func (*ServerReflectionResponse) ProtoMessage() {} -func (*ServerReflectionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_reflection_178bd1e101bf8b63, []int{2} -} -func (m *ServerReflectionResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServerReflectionResponse.Unmarshal(m, b) -} -func (m *ServerReflectionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServerReflectionResponse.Marshal(b, m, deterministic) -} -func (dst *ServerReflectionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServerReflectionResponse.Merge(dst, src) -} -func (m *ServerReflectionResponse) XXX_Size() int { - return xxx_messageInfo_ServerReflectionResponse.Size(m) -} -func (m *ServerReflectionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ServerReflectionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ServerReflectionResponse proto.InternalMessageInfo - -type isServerReflectionResponse_MessageResponse interface { - isServerReflectionResponse_MessageResponse() -} - -type ServerReflectionResponse_FileDescriptorResponse struct { - FileDescriptorResponse *FileDescriptorResponse `protobuf:"bytes,4,opt,name=file_descriptor_response,json=fileDescriptorResponse,oneof"` -} -type ServerReflectionResponse_AllExtensionNumbersResponse struct { - AllExtensionNumbersResponse *ExtensionNumberResponse `protobuf:"bytes,5,opt,name=all_extension_numbers_response,json=allExtensionNumbersResponse,oneof"` -} -type ServerReflectionResponse_ListServicesResponse struct { - ListServicesResponse *ListServiceResponse `protobuf:"bytes,6,opt,name=list_services_response,json=listServicesResponse,oneof"` -} -type ServerReflectionResponse_ErrorResponse struct { - ErrorResponse *ErrorResponse `protobuf:"bytes,7,opt,name=error_response,json=errorResponse,oneof"` -} - -func (*ServerReflectionResponse_FileDescriptorResponse) isServerReflectionResponse_MessageResponse() {} -func (*ServerReflectionResponse_AllExtensionNumbersResponse) isServerReflectionResponse_MessageResponse() { -} -func (*ServerReflectionResponse_ListServicesResponse) isServerReflectionResponse_MessageResponse() {} -func (*ServerReflectionResponse_ErrorResponse) isServerReflectionResponse_MessageResponse() {} - -func (m *ServerReflectionResponse) GetMessageResponse() isServerReflectionResponse_MessageResponse { - if m != nil { - return m.MessageResponse - } - return nil -} - -func (m *ServerReflectionResponse) GetValidHost() string { - if m != nil { - return m.ValidHost - } - return "" -} - -func (m *ServerReflectionResponse) GetOriginalRequest() *ServerReflectionRequest { - if m != nil { - return m.OriginalRequest - } - return nil -} - -func (m *ServerReflectionResponse) GetFileDescriptorResponse() *FileDescriptorResponse { - if x, ok := m.GetMessageResponse().(*ServerReflectionResponse_FileDescriptorResponse); ok { - return x.FileDescriptorResponse - } - return nil -} - -func (m *ServerReflectionResponse) GetAllExtensionNumbersResponse() *ExtensionNumberResponse { - if x, ok := m.GetMessageResponse().(*ServerReflectionResponse_AllExtensionNumbersResponse); ok { - return x.AllExtensionNumbersResponse - } - return nil -} - -func (m *ServerReflectionResponse) GetListServicesResponse() *ListServiceResponse { - if x, ok := m.GetMessageResponse().(*ServerReflectionResponse_ListServicesResponse); ok { - return x.ListServicesResponse - } - return nil -} - -func (m *ServerReflectionResponse) GetErrorResponse() *ErrorResponse { - if x, ok := m.GetMessageResponse().(*ServerReflectionResponse_ErrorResponse); ok { - return x.ErrorResponse - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*ServerReflectionResponse) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _ServerReflectionResponse_OneofMarshaler, _ServerReflectionResponse_OneofUnmarshaler, _ServerReflectionResponse_OneofSizer, []interface{}{ - (*ServerReflectionResponse_FileDescriptorResponse)(nil), - (*ServerReflectionResponse_AllExtensionNumbersResponse)(nil), - (*ServerReflectionResponse_ListServicesResponse)(nil), - (*ServerReflectionResponse_ErrorResponse)(nil), - } -} - -func _ServerReflectionResponse_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*ServerReflectionResponse) - // message_response - switch x := m.MessageResponse.(type) { - case *ServerReflectionResponse_FileDescriptorResponse: - b.EncodeVarint(4<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.FileDescriptorResponse); err != nil { - return err - } - case *ServerReflectionResponse_AllExtensionNumbersResponse: - b.EncodeVarint(5<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.AllExtensionNumbersResponse); err != nil { - return err - } - case *ServerReflectionResponse_ListServicesResponse: - b.EncodeVarint(6<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ListServicesResponse); err != nil { - return err - } - case *ServerReflectionResponse_ErrorResponse: - b.EncodeVarint(7<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ErrorResponse); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("ServerReflectionResponse.MessageResponse has unexpected type %T", x) - } - return nil -} - -func _ServerReflectionResponse_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*ServerReflectionResponse) - switch tag { - case 4: // message_response.file_descriptor_response - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(FileDescriptorResponse) - err := b.DecodeMessage(msg) - m.MessageResponse = &ServerReflectionResponse_FileDescriptorResponse{msg} - return true, err - case 5: // message_response.all_extension_numbers_response - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ExtensionNumberResponse) - err := b.DecodeMessage(msg) - m.MessageResponse = &ServerReflectionResponse_AllExtensionNumbersResponse{msg} - return true, err - case 6: // message_response.list_services_response - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ListServiceResponse) - err := b.DecodeMessage(msg) - m.MessageResponse = &ServerReflectionResponse_ListServicesResponse{msg} - return true, err - case 7: // message_response.error_response - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ErrorResponse) - err := b.DecodeMessage(msg) - m.MessageResponse = &ServerReflectionResponse_ErrorResponse{msg} - return true, err - default: - return false, nil - } -} - -func _ServerReflectionResponse_OneofSizer(msg proto.Message) (n int) { - m := msg.(*ServerReflectionResponse) - // message_response - switch x := m.MessageResponse.(type) { - case *ServerReflectionResponse_FileDescriptorResponse: - s := proto.Size(x.FileDescriptorResponse) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *ServerReflectionResponse_AllExtensionNumbersResponse: - s := proto.Size(x.AllExtensionNumbersResponse) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *ServerReflectionResponse_ListServicesResponse: - s := proto.Size(x.ListServicesResponse) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *ServerReflectionResponse_ErrorResponse: - s := proto.Size(x.ErrorResponse) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -// Serialized FileDescriptorProto messages sent by the server answering -// a file_by_filename, file_containing_symbol, or file_containing_extension -// request. -type FileDescriptorResponse struct { - // Serialized FileDescriptorProto messages. We avoid taking a dependency on - // descriptor.proto, which uses proto2 only features, by making them opaque - // bytes instead. - FileDescriptorProto [][]byte `protobuf:"bytes,1,rep,name=file_descriptor_proto,json=fileDescriptorProto,proto3" json:"file_descriptor_proto,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FileDescriptorResponse) Reset() { *m = FileDescriptorResponse{} } -func (m *FileDescriptorResponse) String() string { return proto.CompactTextString(m) } -func (*FileDescriptorResponse) ProtoMessage() {} -func (*FileDescriptorResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_reflection_178bd1e101bf8b63, []int{3} -} -func (m *FileDescriptorResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FileDescriptorResponse.Unmarshal(m, b) -} -func (m *FileDescriptorResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FileDescriptorResponse.Marshal(b, m, deterministic) -} -func (dst *FileDescriptorResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_FileDescriptorResponse.Merge(dst, src) -} -func (m *FileDescriptorResponse) XXX_Size() int { - return xxx_messageInfo_FileDescriptorResponse.Size(m) -} -func (m *FileDescriptorResponse) XXX_DiscardUnknown() { - xxx_messageInfo_FileDescriptorResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_FileDescriptorResponse proto.InternalMessageInfo - -func (m *FileDescriptorResponse) GetFileDescriptorProto() [][]byte { - if m != nil { - return m.FileDescriptorProto - } - return nil -} - -// A list of extension numbers sent by the server answering -// all_extension_numbers_of_type request. -type ExtensionNumberResponse struct { - // Full name of the base type, including the package name. The format - // is . - BaseTypeName string `protobuf:"bytes,1,opt,name=base_type_name,json=baseTypeName" json:"base_type_name,omitempty"` - ExtensionNumber []int32 `protobuf:"varint,2,rep,packed,name=extension_number,json=extensionNumber" json:"extension_number,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ExtensionNumberResponse) Reset() { *m = ExtensionNumberResponse{} } -func (m *ExtensionNumberResponse) String() string { return proto.CompactTextString(m) } -func (*ExtensionNumberResponse) ProtoMessage() {} -func (*ExtensionNumberResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_reflection_178bd1e101bf8b63, []int{4} -} -func (m *ExtensionNumberResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ExtensionNumberResponse.Unmarshal(m, b) -} -func (m *ExtensionNumberResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ExtensionNumberResponse.Marshal(b, m, deterministic) -} -func (dst *ExtensionNumberResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ExtensionNumberResponse.Merge(dst, src) -} -func (m *ExtensionNumberResponse) XXX_Size() int { - return xxx_messageInfo_ExtensionNumberResponse.Size(m) -} -func (m *ExtensionNumberResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ExtensionNumberResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ExtensionNumberResponse proto.InternalMessageInfo - -func (m *ExtensionNumberResponse) GetBaseTypeName() string { - if m != nil { - return m.BaseTypeName - } - return "" -} - -func (m *ExtensionNumberResponse) GetExtensionNumber() []int32 { - if m != nil { - return m.ExtensionNumber - } - return nil -} - -// A list of ServiceResponse sent by the server answering list_services request. -type ListServiceResponse struct { - // The information of each service may be expanded in the future, so we use - // ServiceResponse message to encapsulate it. - Service []*ServiceResponse `protobuf:"bytes,1,rep,name=service" json:"service,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListServiceResponse) Reset() { *m = ListServiceResponse{} } -func (m *ListServiceResponse) String() string { return proto.CompactTextString(m) } -func (*ListServiceResponse) ProtoMessage() {} -func (*ListServiceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_reflection_178bd1e101bf8b63, []int{5} -} -func (m *ListServiceResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListServiceResponse.Unmarshal(m, b) -} -func (m *ListServiceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListServiceResponse.Marshal(b, m, deterministic) -} -func (dst *ListServiceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListServiceResponse.Merge(dst, src) -} -func (m *ListServiceResponse) XXX_Size() int { - return xxx_messageInfo_ListServiceResponse.Size(m) -} -func (m *ListServiceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ListServiceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ListServiceResponse proto.InternalMessageInfo - -func (m *ListServiceResponse) GetService() []*ServiceResponse { - if m != nil { - return m.Service - } - return nil -} - -// The information of a single service used by ListServiceResponse to answer -// list_services request. -type ServiceResponse struct { - // Full name of a registered service, including its package name. The format - // is . - Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServiceResponse) Reset() { *m = ServiceResponse{} } -func (m *ServiceResponse) String() string { return proto.CompactTextString(m) } -func (*ServiceResponse) ProtoMessage() {} -func (*ServiceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_reflection_178bd1e101bf8b63, []int{6} -} -func (m *ServiceResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServiceResponse.Unmarshal(m, b) -} -func (m *ServiceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServiceResponse.Marshal(b, m, deterministic) -} -func (dst *ServiceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServiceResponse.Merge(dst, src) -} -func (m *ServiceResponse) XXX_Size() int { - return xxx_messageInfo_ServiceResponse.Size(m) -} -func (m *ServiceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ServiceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ServiceResponse proto.InternalMessageInfo - -func (m *ServiceResponse) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -// The error code and error message sent by the server when an error occurs. -type ErrorResponse struct { - // This field uses the error codes defined in grpc::StatusCode. - ErrorCode int32 `protobuf:"varint,1,opt,name=error_code,json=errorCode" json:"error_code,omitempty"` - ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage" json:"error_message,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ErrorResponse) Reset() { *m = ErrorResponse{} } -func (m *ErrorResponse) String() string { return proto.CompactTextString(m) } -func (*ErrorResponse) ProtoMessage() {} -func (*ErrorResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_reflection_178bd1e101bf8b63, []int{7} -} -func (m *ErrorResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ErrorResponse.Unmarshal(m, b) -} -func (m *ErrorResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ErrorResponse.Marshal(b, m, deterministic) -} -func (dst *ErrorResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ErrorResponse.Merge(dst, src) -} -func (m *ErrorResponse) XXX_Size() int { - return xxx_messageInfo_ErrorResponse.Size(m) -} -func (m *ErrorResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ErrorResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ErrorResponse proto.InternalMessageInfo - -func (m *ErrorResponse) GetErrorCode() int32 { - if m != nil { - return m.ErrorCode - } - return 0 -} - -func (m *ErrorResponse) GetErrorMessage() string { - if m != nil { - return m.ErrorMessage - } - return "" -} - -func init() { - proto.RegisterType((*ServerReflectionRequest)(nil), "grpc.reflection.v1alpha.ServerReflectionRequest") - proto.RegisterType((*ExtensionRequest)(nil), "grpc.reflection.v1alpha.ExtensionRequest") - proto.RegisterType((*ServerReflectionResponse)(nil), "grpc.reflection.v1alpha.ServerReflectionResponse") - proto.RegisterType((*FileDescriptorResponse)(nil), "grpc.reflection.v1alpha.FileDescriptorResponse") - proto.RegisterType((*ExtensionNumberResponse)(nil), "grpc.reflection.v1alpha.ExtensionNumberResponse") - proto.RegisterType((*ListServiceResponse)(nil), "grpc.reflection.v1alpha.ListServiceResponse") - proto.RegisterType((*ServiceResponse)(nil), "grpc.reflection.v1alpha.ServiceResponse") - proto.RegisterType((*ErrorResponse)(nil), "grpc.reflection.v1alpha.ErrorResponse") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// Client API for ServerReflection service - -type ServerReflectionClient interface { - // The reflection service is structured as a bidirectional stream, ensuring - // all related requests go to a single server. - ServerReflectionInfo(ctx context.Context, opts ...grpc.CallOption) (ServerReflection_ServerReflectionInfoClient, error) -} - -type serverReflectionClient struct { - cc *grpc.ClientConn -} - -func NewServerReflectionClient(cc *grpc.ClientConn) ServerReflectionClient { - return &serverReflectionClient{cc} -} - -func (c *serverReflectionClient) ServerReflectionInfo(ctx context.Context, opts ...grpc.CallOption) (ServerReflection_ServerReflectionInfoClient, error) { - stream, err := grpc.NewClientStream(ctx, &_ServerReflection_serviceDesc.Streams[0], c.cc, "/grpc.reflection.v1alpha.ServerReflection/ServerReflectionInfo", opts...) - if err != nil { - return nil, err - } - x := &serverReflectionServerReflectionInfoClient{stream} - return x, nil -} - -type ServerReflection_ServerReflectionInfoClient interface { - Send(*ServerReflectionRequest) error - Recv() (*ServerReflectionResponse, error) - grpc.ClientStream -} - -type serverReflectionServerReflectionInfoClient struct { - grpc.ClientStream -} - -func (x *serverReflectionServerReflectionInfoClient) Send(m *ServerReflectionRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *serverReflectionServerReflectionInfoClient) Recv() (*ServerReflectionResponse, error) { - m := new(ServerReflectionResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// Server API for ServerReflection service - -type ServerReflectionServer interface { - // The reflection service is structured as a bidirectional stream, ensuring - // all related requests go to a single server. - ServerReflectionInfo(ServerReflection_ServerReflectionInfoServer) error -} - -func RegisterServerReflectionServer(s *grpc.Server, srv ServerReflectionServer) { - s.RegisterService(&_ServerReflection_serviceDesc, srv) -} - -func _ServerReflection_ServerReflectionInfo_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(ServerReflectionServer).ServerReflectionInfo(&serverReflectionServerReflectionInfoServer{stream}) -} - -type ServerReflection_ServerReflectionInfoServer interface { - Send(*ServerReflectionResponse) error - Recv() (*ServerReflectionRequest, error) - grpc.ServerStream -} - -type serverReflectionServerReflectionInfoServer struct { - grpc.ServerStream -} - -func (x *serverReflectionServerReflectionInfoServer) Send(m *ServerReflectionResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *serverReflectionServerReflectionInfoServer) Recv() (*ServerReflectionRequest, error) { - m := new(ServerReflectionRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _ServerReflection_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.reflection.v1alpha.ServerReflection", - HandlerType: (*ServerReflectionServer)(nil), - Methods: []grpc.MethodDesc{}, - Streams: []grpc.StreamDesc{ - { - StreamName: "ServerReflectionInfo", - Handler: _ServerReflection_ServerReflectionInfo_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "grpc_reflection_v1alpha/reflection.proto", -} - -func init() { - proto.RegisterFile("grpc_reflection_v1alpha/reflection.proto", fileDescriptor_reflection_178bd1e101bf8b63) -} - -var fileDescriptor_reflection_178bd1e101bf8b63 = []byte{ - // 656 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x54, 0x51, 0x73, 0xd2, 0x40, - 0x10, 0x6e, 0x5a, 0x68, 0x87, 0x85, 0x02, 0x5e, 0x2b, 0xa4, 0x3a, 0x75, 0x98, 0x68, 0x35, 0x75, - 0x1c, 0xda, 0xe2, 0x8c, 0x3f, 0x80, 0xaa, 0x83, 0x33, 0xb5, 0x75, 0x0e, 0x5f, 0x1c, 0x1f, 0x6e, - 0x02, 0x2c, 0x34, 0x1a, 0x72, 0xf1, 0x2e, 0x45, 0x79, 0xf2, 0x47, 0xf8, 0xa3, 0xfc, 0x4b, 0x3e, - 0x3a, 0x77, 0x09, 0x21, 0xa4, 0x44, 0xa7, 0x4f, 0x30, 0xdf, 0xee, 0xde, 0xb7, 0xbb, 0xdf, 0xb7, - 0x01, 0x7b, 0x22, 0x82, 0x21, 0x13, 0x38, 0xf6, 0x70, 0x18, 0xba, 0xdc, 0x67, 0xb3, 0x33, 0xc7, - 0x0b, 0xae, 0x9d, 0x93, 0x25, 0xd4, 0x0e, 0x04, 0x0f, 0x39, 0x69, 0xaa, 0xcc, 0x76, 0x0a, 0x8e, - 0x33, 0xad, 0x3f, 0x9b, 0xd0, 0xec, 0xa3, 0x98, 0xa1, 0xa0, 0x49, 0x90, 0xe2, 0xb7, 0x1b, 0x94, - 0x21, 0x21, 0x50, 0xb8, 0xe6, 0x32, 0x34, 0x8d, 0x96, 0x61, 0x97, 0xa8, 0xfe, 0x4f, 0x9e, 0x43, - 0x7d, 0xec, 0x7a, 0xc8, 0x06, 0x73, 0xa6, 0x7e, 0x7d, 0x67, 0x8a, 0xe6, 0x96, 0x8a, 0xf7, 0x36, - 0x68, 0x55, 0x21, 0xdd, 0xf9, 0xdb, 0x18, 0x27, 0xaf, 0xa0, 0xa1, 0x73, 0x87, 0xdc, 0x0f, 0x1d, - 0xd7, 0x77, 0xfd, 0x09, 0x93, 0xf3, 0xe9, 0x80, 0x7b, 0x66, 0x21, 0xae, 0xd8, 0x57, 0xf1, 0xf3, - 0x24, 0xdc, 0xd7, 0x51, 0x32, 0x81, 0x83, 0x6c, 0x1d, 0xfe, 0x08, 0xd1, 0x97, 0x2e, 0xf7, 0xcd, - 0x62, 0xcb, 0xb0, 0xcb, 0x9d, 0xe3, 0x76, 0xce, 0x40, 0xed, 0x37, 0x8b, 0xcc, 0x78, 0x8a, 0xde, - 0x06, 0x6d, 0xae, 0xb2, 0x24, 0x19, 0xa4, 0x0b, 0x87, 0x8e, 0xe7, 0x2d, 0x1f, 0x67, 0xfe, 0xcd, - 0x74, 0x80, 0x42, 0x32, 0x3e, 0x66, 0xe1, 0x3c, 0x40, 0x73, 0x3b, 0xee, 0xf3, 0xc0, 0xf1, 0xbc, - 0xa4, 0xec, 0x32, 0x4a, 0xba, 0x1a, 0x7f, 0x9c, 0x07, 0x48, 0x8e, 0x60, 0xd7, 0x73, 0x65, 0xc8, - 0x24, 0x8a, 0x99, 0x3b, 0x44, 0x69, 0xee, 0xc4, 0x35, 0x15, 0x05, 0xf7, 0x63, 0xb4, 0x7b, 0x0f, - 0x6a, 0x53, 0x94, 0xd2, 0x99, 0x20, 0x13, 0x51, 0x63, 0xd6, 0x18, 0xea, 0xd9, 0x66, 0xc9, 0x33, - 0xa8, 0xa5, 0xa6, 0xd6, 0x3d, 0x44, 0xdb, 0xaf, 0x2e, 0x61, 0x4d, 0x7b, 0x0c, 0xf5, 0x6c, 0xdb, - 0xe6, 0x66, 0xcb, 0xb0, 0x8b, 0xb4, 0x86, 0xab, 0x8d, 0x5a, 0xbf, 0x0b, 0x60, 0xde, 0x96, 0x58, - 0x06, 0xdc, 0x97, 0x48, 0x0e, 0x01, 0x66, 0x8e, 0xe7, 0x8e, 0x58, 0x4a, 0xe9, 0x92, 0x46, 0x7a, - 0x4a, 0xee, 0xcf, 0x50, 0xe7, 0xc2, 0x9d, 0xb8, 0xbe, 0xe3, 0x2d, 0xfa, 0xd6, 0x34, 0xe5, 0xce, - 0x69, 0xae, 0x02, 0x39, 0x76, 0xa2, 0xb5, 0xc5, 0x4b, 0x8b, 0x61, 0xbf, 0x82, 0xa9, 0x75, 0x1e, - 0xa1, 0x1c, 0x0a, 0x37, 0x08, 0xb9, 0x60, 0x22, 0xee, 0x4b, 0x3b, 0xa4, 0xdc, 0x39, 0xc9, 0x25, - 0x51, 0x26, 0x7b, 0x9d, 0xd4, 0x2d, 0xc6, 0xe9, 0x6d, 0x50, 0x6d, 0xb9, 0xdb, 0x11, 0xf2, 0x1d, - 0x1e, 0xad, 0xd7, 0x3a, 0xa1, 0x2c, 0xfe, 0x67, 0xae, 0x8c, 0x01, 0x52, 0x9c, 0x0f, 0xd7, 0xd8, - 0x23, 0x21, 0x1e, 0x41, 0x63, 0xc5, 0x20, 0x4b, 0xc2, 0x6d, 0x4d, 0xf8, 0x22, 0x97, 0xf0, 0x62, - 0x69, 0xa0, 0x14, 0xd9, 0x7e, 0xda, 0x57, 0x09, 0xcb, 0x15, 0x54, 0x51, 0x88, 0xf4, 0x06, 0x77, - 0xf4, 0xeb, 0x4f, 0xf3, 0xc7, 0x51, 0xe9, 0xa9, 0x77, 0x77, 0x31, 0x0d, 0x74, 0x09, 0xd4, 0x97, - 0x86, 0x8d, 0x30, 0xeb, 0x02, 0x1a, 0xeb, 0xf7, 0x4e, 0x3a, 0x70, 0x3f, 0x2b, 0xa5, 0xfe, 0xf0, - 0x98, 0x46, 0x6b, 0xcb, 0xae, 0xd0, 0xbd, 0x55, 0x51, 0x3e, 0xa8, 0x90, 0xf5, 0x05, 0x9a, 0x39, - 0x2b, 0x25, 0x4f, 0xa0, 0x3a, 0x70, 0x24, 0xea, 0x03, 0x60, 0xfa, 0x1b, 0x13, 0x39, 0xb3, 0xa2, - 0x50, 0xe5, 0xff, 0x4b, 0xf5, 0x7d, 0x59, 0x7f, 0x03, 0x5b, 0xeb, 0x6e, 0xe0, 0x13, 0xec, 0xad, - 0xd9, 0x26, 0xe9, 0xc2, 0x4e, 0x2c, 0x8b, 0x6e, 0xb4, 0xdc, 0xb1, 0xff, 0xe9, 0xea, 0x54, 0x29, - 0x5d, 0x14, 0x5a, 0x47, 0x50, 0xcb, 0x3e, 0x4b, 0xa0, 0x90, 0x6a, 0x5a, 0xff, 0xb7, 0xfa, 0xb0, - 0xbb, 0xb2, 0x71, 0x75, 0x79, 0x91, 0x62, 0x43, 0x3e, 0x8a, 0x52, 0x8b, 0xb4, 0xa4, 0x91, 0x73, - 0x3e, 0x42, 0xf2, 0x18, 0x22, 0x41, 0x58, 0xac, 0x82, 0x3e, 0xbb, 0x12, 0xad, 0x68, 0xf0, 0x7d, - 0x84, 0x75, 0x7e, 0x19, 0x50, 0xcf, 0x9e, 0x1b, 0xf9, 0x09, 0xfb, 0x59, 0xec, 0x9d, 0x3f, 0xe6, - 0xe4, 0xce, 0x17, 0xfb, 0xe0, 0xec, 0x0e, 0x15, 0xd1, 0x54, 0xb6, 0x71, 0x6a, 0x0c, 0xb6, 0xb5, - 0xf4, 0x2f, 0xff, 0x06, 0x00, 0x00, 0xff, 0xff, 0x85, 0x02, 0x09, 0x9d, 0x9f, 0x06, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/reflection/serverreflection.go b/vendor/google.golang.org/grpc/reflection/serverreflection.go deleted file mode 100644 index dd22a2da7..000000000 --- a/vendor/google.golang.org/grpc/reflection/serverreflection.go +++ /dev/null @@ -1,454 +0,0 @@ -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -//go:generate protoc --go_out=plugins=grpc:. grpc_reflection_v1alpha/reflection.proto - -/* -Package reflection implements server reflection service. - -The service implemented is defined in: -https://github.com/grpc/grpc/blob/master/src/proto/grpc/reflection/v1alpha/reflection.proto. - -To register server reflection on a gRPC server: - import "google.golang.org/grpc/reflection" - - s := grpc.NewServer() - pb.RegisterYourOwnServer(s, &server{}) - - // Register reflection service on gRPC server. - reflection.Register(s) - - s.Serve(lis) - -*/ -package reflection // import "google.golang.org/grpc/reflection" - -import ( - "bytes" - "compress/gzip" - "fmt" - "io" - "io/ioutil" - "reflect" - "sort" - "sync" - - "github.com/golang/protobuf/proto" - dpb "github.com/golang/protobuf/protoc-gen-go/descriptor" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - rpb "google.golang.org/grpc/reflection/grpc_reflection_v1alpha" - "google.golang.org/grpc/status" -) - -type serverReflectionServer struct { - s *grpc.Server - - initSymbols sync.Once - serviceNames []string - symbols map[string]*dpb.FileDescriptorProto // map of fully-qualified names to files -} - -// Register registers the server reflection service on the given gRPC server. -func Register(s *grpc.Server) { - rpb.RegisterServerReflectionServer(s, &serverReflectionServer{ - s: s, - }) -} - -// protoMessage is used for type assertion on proto messages. -// Generated proto message implements function Descriptor(), but Descriptor() -// is not part of interface proto.Message. This interface is needed to -// call Descriptor(). -type protoMessage interface { - Descriptor() ([]byte, []int) -} - -func (s *serverReflectionServer) getSymbols() (svcNames []string, symbolIndex map[string]*dpb.FileDescriptorProto) { - s.initSymbols.Do(func() { - serviceInfo := s.s.GetServiceInfo() - - s.symbols = map[string]*dpb.FileDescriptorProto{} - s.serviceNames = make([]string, 0, len(serviceInfo)) - processed := map[string]struct{}{} - for svc, info := range serviceInfo { - s.serviceNames = append(s.serviceNames, svc) - fdenc, ok := parseMetadata(info.Metadata) - if !ok { - continue - } - fd, err := decodeFileDesc(fdenc) - if err != nil { - continue - } - s.processFile(fd, processed) - } - sort.Strings(s.serviceNames) - }) - - return s.serviceNames, s.symbols -} - -func (s *serverReflectionServer) processFile(fd *dpb.FileDescriptorProto, processed map[string]struct{}) { - filename := fd.GetName() - if _, ok := processed[filename]; ok { - return - } - processed[filename] = struct{}{} - - prefix := fd.GetPackage() - - for _, msg := range fd.MessageType { - s.processMessage(fd, prefix, msg) - } - for _, en := range fd.EnumType { - s.processEnum(fd, prefix, en) - } - for _, ext := range fd.Extension { - s.processField(fd, prefix, ext) - } - for _, svc := range fd.Service { - svcName := fqn(prefix, svc.GetName()) - s.symbols[svcName] = fd - for _, meth := range svc.Method { - name := fqn(svcName, meth.GetName()) - s.symbols[name] = fd - } - } - - for _, dep := range fd.Dependency { - fdenc := proto.FileDescriptor(dep) - fdDep, err := decodeFileDesc(fdenc) - if err != nil { - continue - } - s.processFile(fdDep, processed) - } -} - -func (s *serverReflectionServer) processMessage(fd *dpb.FileDescriptorProto, prefix string, msg *dpb.DescriptorProto) { - msgName := fqn(prefix, msg.GetName()) - s.symbols[msgName] = fd - - for _, nested := range msg.NestedType { - s.processMessage(fd, msgName, nested) - } - for _, en := range msg.EnumType { - s.processEnum(fd, msgName, en) - } - for _, ext := range msg.Extension { - s.processField(fd, msgName, ext) - } - for _, fld := range msg.Field { - s.processField(fd, msgName, fld) - } - for _, oneof := range msg.OneofDecl { - oneofName := fqn(msgName, oneof.GetName()) - s.symbols[oneofName] = fd - } -} - -func (s *serverReflectionServer) processEnum(fd *dpb.FileDescriptorProto, prefix string, en *dpb.EnumDescriptorProto) { - enName := fqn(prefix, en.GetName()) - s.symbols[enName] = fd - - for _, val := range en.Value { - valName := fqn(enName, val.GetName()) - s.symbols[valName] = fd - } -} - -func (s *serverReflectionServer) processField(fd *dpb.FileDescriptorProto, prefix string, fld *dpb.FieldDescriptorProto) { - fldName := fqn(prefix, fld.GetName()) - s.symbols[fldName] = fd -} - -func fqn(prefix, name string) string { - if prefix == "" { - return name - } - return prefix + "." + name -} - -// fileDescForType gets the file descriptor for the given type. -// The given type should be a proto message. -func (s *serverReflectionServer) fileDescForType(st reflect.Type) (*dpb.FileDescriptorProto, error) { - m, ok := reflect.Zero(reflect.PtrTo(st)).Interface().(protoMessage) - if !ok { - return nil, fmt.Errorf("failed to create message from type: %v", st) - } - enc, _ := m.Descriptor() - - return decodeFileDesc(enc) -} - -// decodeFileDesc does decompression and unmarshalling on the given -// file descriptor byte slice. -func decodeFileDesc(enc []byte) (*dpb.FileDescriptorProto, error) { - raw, err := decompress(enc) - if err != nil { - return nil, fmt.Errorf("failed to decompress enc: %v", err) - } - - fd := new(dpb.FileDescriptorProto) - if err := proto.Unmarshal(raw, fd); err != nil { - return nil, fmt.Errorf("bad descriptor: %v", err) - } - return fd, nil -} - -// decompress does gzip decompression. -func decompress(b []byte) ([]byte, error) { - r, err := gzip.NewReader(bytes.NewReader(b)) - if err != nil { - return nil, fmt.Errorf("bad gzipped descriptor: %v", err) - } - out, err := ioutil.ReadAll(r) - if err != nil { - return nil, fmt.Errorf("bad gzipped descriptor: %v", err) - } - return out, nil -} - -func typeForName(name string) (reflect.Type, error) { - pt := proto.MessageType(name) - if pt == nil { - return nil, fmt.Errorf("unknown type: %q", name) - } - st := pt.Elem() - - return st, nil -} - -func fileDescContainingExtension(st reflect.Type, ext int32) (*dpb.FileDescriptorProto, error) { - m, ok := reflect.Zero(reflect.PtrTo(st)).Interface().(proto.Message) - if !ok { - return nil, fmt.Errorf("failed to create message from type: %v", st) - } - - var extDesc *proto.ExtensionDesc - for id, desc := range proto.RegisteredExtensions(m) { - if id == ext { - extDesc = desc - break - } - } - - if extDesc == nil { - return nil, fmt.Errorf("failed to find registered extension for extension number %v", ext) - } - - return decodeFileDesc(proto.FileDescriptor(extDesc.Filename)) -} - -func (s *serverReflectionServer) allExtensionNumbersForType(st reflect.Type) ([]int32, error) { - m, ok := reflect.Zero(reflect.PtrTo(st)).Interface().(proto.Message) - if !ok { - return nil, fmt.Errorf("failed to create message from type: %v", st) - } - - exts := proto.RegisteredExtensions(m) - out := make([]int32, 0, len(exts)) - for id := range exts { - out = append(out, id) - } - return out, nil -} - -// fileDescEncodingByFilename finds the file descriptor for given filename, -// does marshalling on it and returns the marshalled result. -func (s *serverReflectionServer) fileDescEncodingByFilename(name string) ([]byte, error) { - enc := proto.FileDescriptor(name) - if enc == nil { - return nil, fmt.Errorf("unknown file: %v", name) - } - fd, err := decodeFileDesc(enc) - if err != nil { - return nil, err - } - return proto.Marshal(fd) -} - -// parseMetadata finds the file descriptor bytes specified meta. -// For SupportPackageIsVersion4, m is the name of the proto file, we -// call proto.FileDescriptor to get the byte slice. -// For SupportPackageIsVersion3, m is a byte slice itself. -func parseMetadata(meta interface{}) ([]byte, bool) { - // Check if meta is the file name. - if fileNameForMeta, ok := meta.(string); ok { - return proto.FileDescriptor(fileNameForMeta), true - } - - // Check if meta is the byte slice. - if enc, ok := meta.([]byte); ok { - return enc, true - } - - return nil, false -} - -// fileDescEncodingContainingSymbol finds the file descriptor containing the given symbol, -// does marshalling on it and returns the marshalled result. -// The given symbol can be a type, a service or a method. -func (s *serverReflectionServer) fileDescEncodingContainingSymbol(name string) ([]byte, error) { - _, symbols := s.getSymbols() - fd := symbols[name] - if fd == nil { - // Check if it's a type name that was not present in the - // transitive dependencies of the registered services. - if st, err := typeForName(name); err == nil { - fd, err = s.fileDescForType(st) - if err != nil { - return nil, err - } - } - } - - if fd == nil { - return nil, fmt.Errorf("unknown symbol: %v", name) - } - - return proto.Marshal(fd) -} - -// fileDescEncodingContainingExtension finds the file descriptor containing given extension, -// does marshalling on it and returns the marshalled result. -func (s *serverReflectionServer) fileDescEncodingContainingExtension(typeName string, extNum int32) ([]byte, error) { - st, err := typeForName(typeName) - if err != nil { - return nil, err - } - fd, err := fileDescContainingExtension(st, extNum) - if err != nil { - return nil, err - } - return proto.Marshal(fd) -} - -// allExtensionNumbersForTypeName returns all extension numbers for the given type. -func (s *serverReflectionServer) allExtensionNumbersForTypeName(name string) ([]int32, error) { - st, err := typeForName(name) - if err != nil { - return nil, err - } - extNums, err := s.allExtensionNumbersForType(st) - if err != nil { - return nil, err - } - return extNums, nil -} - -// ServerReflectionInfo is the reflection service handler. -func (s *serverReflectionServer) ServerReflectionInfo(stream rpb.ServerReflection_ServerReflectionInfoServer) error { - for { - in, err := stream.Recv() - if err == io.EOF { - return nil - } - if err != nil { - return err - } - - out := &rpb.ServerReflectionResponse{ - ValidHost: in.Host, - OriginalRequest: in, - } - switch req := in.MessageRequest.(type) { - case *rpb.ServerReflectionRequest_FileByFilename: - b, err := s.fileDescEncodingByFilename(req.FileByFilename) - if err != nil { - out.MessageResponse = &rpb.ServerReflectionResponse_ErrorResponse{ - ErrorResponse: &rpb.ErrorResponse{ - ErrorCode: int32(codes.NotFound), - ErrorMessage: err.Error(), - }, - } - } else { - out.MessageResponse = &rpb.ServerReflectionResponse_FileDescriptorResponse{ - FileDescriptorResponse: &rpb.FileDescriptorResponse{FileDescriptorProto: [][]byte{b}}, - } - } - case *rpb.ServerReflectionRequest_FileContainingSymbol: - b, err := s.fileDescEncodingContainingSymbol(req.FileContainingSymbol) - if err != nil { - out.MessageResponse = &rpb.ServerReflectionResponse_ErrorResponse{ - ErrorResponse: &rpb.ErrorResponse{ - ErrorCode: int32(codes.NotFound), - ErrorMessage: err.Error(), - }, - } - } else { - out.MessageResponse = &rpb.ServerReflectionResponse_FileDescriptorResponse{ - FileDescriptorResponse: &rpb.FileDescriptorResponse{FileDescriptorProto: [][]byte{b}}, - } - } - case *rpb.ServerReflectionRequest_FileContainingExtension: - typeName := req.FileContainingExtension.ContainingType - extNum := req.FileContainingExtension.ExtensionNumber - b, err := s.fileDescEncodingContainingExtension(typeName, extNum) - if err != nil { - out.MessageResponse = &rpb.ServerReflectionResponse_ErrorResponse{ - ErrorResponse: &rpb.ErrorResponse{ - ErrorCode: int32(codes.NotFound), - ErrorMessage: err.Error(), - }, - } - } else { - out.MessageResponse = &rpb.ServerReflectionResponse_FileDescriptorResponse{ - FileDescriptorResponse: &rpb.FileDescriptorResponse{FileDescriptorProto: [][]byte{b}}, - } - } - case *rpb.ServerReflectionRequest_AllExtensionNumbersOfType: - extNums, err := s.allExtensionNumbersForTypeName(req.AllExtensionNumbersOfType) - if err != nil { - out.MessageResponse = &rpb.ServerReflectionResponse_ErrorResponse{ - ErrorResponse: &rpb.ErrorResponse{ - ErrorCode: int32(codes.NotFound), - ErrorMessage: err.Error(), - }, - } - } else { - out.MessageResponse = &rpb.ServerReflectionResponse_AllExtensionNumbersResponse{ - AllExtensionNumbersResponse: &rpb.ExtensionNumberResponse{ - BaseTypeName: req.AllExtensionNumbersOfType, - ExtensionNumber: extNums, - }, - } - } - case *rpb.ServerReflectionRequest_ListServices: - svcNames, _ := s.getSymbols() - serviceResponses := make([]*rpb.ServiceResponse, len(svcNames)) - for i, n := range svcNames { - serviceResponses[i] = &rpb.ServiceResponse{ - Name: n, - } - } - out.MessageResponse = &rpb.ServerReflectionResponse_ListServicesResponse{ - ListServicesResponse: &rpb.ListServiceResponse{ - Service: serviceResponses, - }, - } - default: - return status.Errorf(codes.InvalidArgument, "invalid MessageRequest: %v", in.MessageRequest) - } - - if err := stream.Send(out); err != nil { - return err - } - } -} diff --git a/vendor/google.golang.org/grpc/resolver/dns/dns_resolver.go b/vendor/google.golang.org/grpc/resolver/dns/dns_resolver.go index c1cabfc99..048fde67d 100644 --- a/vendor/google.golang.org/grpc/resolver/dns/dns_resolver.go +++ b/vendor/google.golang.org/grpc/resolver/dns/dns_resolver.go @@ -24,7 +24,6 @@ import ( "encoding/json" "errors" "fmt" - "math/rand" "net" "os" "strconv" @@ -34,6 +33,7 @@ import ( "golang.org/x/net/context" "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/internal/grpcrand" "google.golang.org/grpc/resolver" ) @@ -52,7 +52,6 @@ const ( var ( errMissingAddr = errors.New("missing address") - randomGen = rand.New(rand.NewSource(time.Now().UnixNano())) ) // NewBuilder creates a dnsBuilder which is used to factory DNS resolvers. @@ -67,6 +66,9 @@ type dnsBuilder struct { // Build creates and starts a DNS resolver that watches the name resolution of the target. func (b *dnsBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOption) (resolver.Resolver, error) { + if target.Authority != "" { + return nil, fmt.Errorf("Default DNS resolver does not support custom DNS server") + } host, port, err := parseTarget(target.Endpoint) if err != nil { return nil, err @@ -346,7 +348,7 @@ func chosenByPercentage(a *int) bool { if a == nil { return true } - return randomGen.Intn(100)+1 <= *a + return grpcrand.Intn(100)+1 <= *a } func canaryingSC(js string) string { diff --git a/vendor/google.golang.org/grpc/resolver_conn_wrapper.go b/vendor/google.golang.org/grpc/resolver_conn_wrapper.go index 1b493db2e..494d6931e 100644 --- a/vendor/google.golang.org/grpc/resolver_conn_wrapper.go +++ b/vendor/google.golang.org/grpc/resolver_conn_wrapper.go @@ -65,8 +65,8 @@ func parseTarget(target string) (ret resolver.Target) { } // newCCResolverWrapper parses cc.target for scheme and gets the resolver -// builder for this scheme. It then builds the resolver and starts the -// monitoring goroutine for it. +// builder for this scheme and builds the resolver. The monitoring goroutine +// for it is not started yet and can be created by calling start(). // // If withResolverBuilder dial option is set, the specified resolver will be // used instead. @@ -148,7 +148,7 @@ func (ccr *ccResolverWrapper) NewAddress(addrs []resolver.Address) { } // NewServiceConfig is called by the resolver implemenetion to send service -// configs to gPRC. +// configs to gRPC. func (ccr *ccResolverWrapper) NewServiceConfig(sc string) { select { case <-ccr.scCh: diff --git a/vendor/google.golang.org/grpc/rpc_util.go b/vendor/google.golang.org/grpc/rpc_util.go index 5de1b031e..033801f34 100644 --- a/vendor/google.golang.org/grpc/rpc_util.go +++ b/vendor/google.golang.org/grpc/rpc_util.go @@ -419,8 +419,8 @@ func (o CustomCodecCallOption) after(c *callInfo) {} type payloadFormat uint8 const ( - compressionNone payloadFormat = iota // no compression - compressionMade + compressionNone payloadFormat = 0 // no compression + compressionMade payloadFormat = 1 // compressed ) // parser reads complete gRPC messages from the underlying reader. @@ -477,65 +477,82 @@ func (p *parser) recvMsg(maxReceiveMessageSize int) (pf payloadFormat, msg []byt return pf, msg, nil } -// encode serializes msg and returns a buffer of message header and a buffer of msg. -// If msg is nil, it generates the message header and an empty msg buffer. -// TODO(ddyihai): eliminate extra Compressor parameter. -func encode(c baseCodec, msg interface{}, cp Compressor, outPayload *stats.OutPayload, compressor encoding.Compressor) ([]byte, []byte, error) { - var ( - b []byte - cbuf *bytes.Buffer - ) - const ( - payloadLen = 1 - sizeLen = 4 - ) - if msg != nil { - var err error - b, err = c.Marshal(msg) - if err != nil { - return nil, nil, status.Errorf(codes.Internal, "grpc: error while marshaling: %v", err.Error()) +// encode serializes msg and returns a buffer containing the message, or an +// error if it is too large to be transmitted by grpc. If msg is nil, it +// generates an empty message. +func encode(c baseCodec, msg interface{}) ([]byte, error) { + if msg == nil { // NOTE: typed nils will not be caught by this check + return nil, nil + } + b, err := c.Marshal(msg) + if err != nil { + return nil, status.Errorf(codes.Internal, "grpc: error while marshaling: %v", err.Error()) + } + if uint(len(b)) > math.MaxUint32 { + return nil, status.Errorf(codes.ResourceExhausted, "grpc: message too large (%d bytes)", len(b)) + } + return b, nil +} + +// compress returns the input bytes compressed by compressor or cp. If both +// compressors are nil, returns nil. +// +// TODO(dfawley): eliminate cp parameter by wrapping Compressor in an encoding.Compressor. +func compress(in []byte, cp Compressor, compressor encoding.Compressor) ([]byte, error) { + if compressor == nil && cp == nil { + return nil, nil + } + wrapErr := func(err error) error { + return status.Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error()) + } + cbuf := &bytes.Buffer{} + if compressor != nil { + z, _ := compressor.Compress(cbuf) + if _, err := z.Write(in); err != nil { + return nil, wrapErr(err) } - if outPayload != nil { - outPayload.Payload = msg - // TODO truncate large payload. - outPayload.Data = b - outPayload.Length = len(b) + if err := z.Close(); err != nil { + return nil, wrapErr(err) } - if compressor != nil || cp != nil { - cbuf = new(bytes.Buffer) - // Has compressor, check Compressor is set by UseCompressor first. - if compressor != nil { - z, _ := compressor.Compress(cbuf) - if _, err := z.Write(b); err != nil { - return nil, nil, status.Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error()) - } - z.Close() - } else { - // If Compressor is not set by UseCompressor, use default Compressor - if err := cp.Do(cbuf, b); err != nil { - return nil, nil, status.Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error()) - } - } - b = cbuf.Bytes() + } else { + if err := cp.Do(cbuf, in); err != nil { + return nil, wrapErr(err) } } - if uint(len(b)) > math.MaxUint32 { - return nil, nil, status.Errorf(codes.ResourceExhausted, "grpc: message too large (%d bytes)", len(b)) - } + return cbuf.Bytes(), nil +} - bufHeader := make([]byte, payloadLen+sizeLen) - if compressor != nil || cp != nil { - bufHeader[0] = byte(compressionMade) +const ( + payloadLen = 1 + sizeLen = 4 + headerLen = payloadLen + sizeLen +) + +// msgHeader returns a 5-byte header for the message being transmitted and the +// payload, which is compData if non-nil or data otherwise. +func msgHeader(data, compData []byte) (hdr []byte, payload []byte) { + hdr = make([]byte, headerLen) + if compData != nil { + hdr[0] = byte(compressionMade) + data = compData } else { - bufHeader[0] = byte(compressionNone) + hdr[0] = byte(compressionNone) } - // Write length of b into buf - binary.BigEndian.PutUint32(bufHeader[payloadLen:], uint32(len(b))) - if outPayload != nil { - outPayload.WireLength = payloadLen + sizeLen + len(b) + // Write length of payload into buf + binary.BigEndian.PutUint32(hdr[payloadLen:], uint32(len(data))) + return hdr, data +} + +func outPayload(client bool, msg interface{}, data, payload []byte, t time.Time) *stats.OutPayload { + return &stats.OutPayload{ + Client: client, + Payload: msg, + Data: data, + Length: len(data), + WireLength: len(payload) + headerLen, + SentTime: t, } - return bufHeader, b, nil } func checkRecvPayload(pf payloadFormat, recvCompress string, haveCompressor bool) *status.Status { @@ -721,7 +738,4 @@ const ( SupportPackageIsVersion5 = true ) -// Version is the current grpc version. -const Version = "1.12.2" - const grpcUA = "grpc-go/" + Version diff --git a/vendor/google.golang.org/grpc/server.go b/vendor/google.golang.org/grpc/server.go index 4969331cb..014c72b3f 100644 --- a/vendor/google.golang.org/grpc/server.go +++ b/vendor/google.golang.org/grpc/server.go @@ -38,13 +38,13 @@ import ( "golang.org/x/net/http2" "golang.org/x/net/trace" - "google.golang.org/grpc/channelz" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/encoding" "google.golang.org/grpc/encoding/proto" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/internal" + "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/metadata" "google.golang.org/grpc/stats" @@ -827,24 +827,24 @@ func (s *Server) incrCallsFailed() { } func (s *Server) sendResponse(t transport.ServerTransport, stream *transport.Stream, msg interface{}, cp Compressor, opts *transport.Options, comp encoding.Compressor) error { - var ( - outPayload *stats.OutPayload - ) - if s.opts.statsHandler != nil { - outPayload = &stats.OutPayload{} - } - hdr, data, err := encode(s.getCodec(stream.ContentSubtype()), msg, cp, outPayload, comp) + data, err := encode(s.getCodec(stream.ContentSubtype()), msg) if err != nil { grpclog.Errorln("grpc: server failed to encode response: ", err) return err } - if len(data) > s.opts.maxSendMessageSize { - return status.Errorf(codes.ResourceExhausted, "grpc: trying to send message larger than max (%d vs. %d)", len(data), s.opts.maxSendMessageSize) + compData, err := compress(data, cp, comp) + if err != nil { + grpclog.Errorln("grpc: server failed to compress response: ", err) + return err + } + hdr, payload := msgHeader(data, compData) + // TODO(dfawley): should we be checking len(data) instead? + if len(payload) > s.opts.maxSendMessageSize { + return status.Errorf(codes.ResourceExhausted, "grpc: trying to send message larger than max (%d vs. %d)", len(payload), s.opts.maxSendMessageSize) } - err = t.Write(stream, hdr, data, opts) - if err == nil && outPayload != nil { - outPayload.SentTime = time.Now() - s.opts.statsHandler.HandleRPC(stream.Context(), outPayload) + err = t.Write(stream, hdr, payload, opts) + if err == nil && s.opts.statsHandler != nil { + s.opts.statsHandler.HandleRPC(stream.Context(), outPayload(false, msg, data, payload, time.Now())) } return err } diff --git a/vendor/google.golang.org/grpc/status/go16.go b/vendor/google.golang.org/grpc/status/go16.go new file mode 100644 index 000000000..e59b53e82 --- /dev/null +++ b/vendor/google.golang.org/grpc/status/go16.go @@ -0,0 +1,42 @@ +// +build go1.6,!go1.7 + +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package status + +import ( + "golang.org/x/net/context" + "google.golang.org/grpc/codes" +) + +// FromContextError converts a context error into a Status. It returns a +// Status with codes.OK if err is nil, or a Status with codes.Unknown if err is +// non-nil and not a context error. +func FromContextError(err error) *Status { + switch err { + case nil: + return New(codes.OK, "") + case context.DeadlineExceeded: + return New(codes.DeadlineExceeded, err.Error()) + case context.Canceled: + return New(codes.Canceled, err.Error()) + default: + return New(codes.Unknown, err.Error()) + } +} diff --git a/vendor/google.golang.org/grpc/status/go17.go b/vendor/google.golang.org/grpc/status/go17.go new file mode 100644 index 000000000..090215149 --- /dev/null +++ b/vendor/google.golang.org/grpc/status/go17.go @@ -0,0 +1,44 @@ +// +build go1.7 + +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package status + +import ( + "context" + + netctx "golang.org/x/net/context" + "google.golang.org/grpc/codes" +) + +// FromContextError converts a context error into a Status. It returns a +// Status with codes.OK if err is nil, or a Status with codes.Unknown if err is +// non-nil and not a context error. +func FromContextError(err error) *Status { + switch err { + case nil: + return New(codes.OK, "") + case context.DeadlineExceeded, netctx.DeadlineExceeded: + return New(codes.DeadlineExceeded, err.Error()) + case context.Canceled, netctx.Canceled: + return New(codes.Canceled, err.Error()) + default: + return New(codes.Unknown, err.Error()) + } +} diff --git a/vendor/google.golang.org/grpc/stickiness_linkedmap.go b/vendor/google.golang.org/grpc/stickiness_linkedmap.go new file mode 100644 index 000000000..1c726af16 --- /dev/null +++ b/vendor/google.golang.org/grpc/stickiness_linkedmap.go @@ -0,0 +1,97 @@ +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package grpc + +import ( + "container/list" +) + +type linkedMapKVPair struct { + key string + value *stickyStoreEntry +} + +// linkedMap is an implementation of a map that supports removing the oldest +// entry. +// +// linkedMap is NOT thread safe. +// +// It's for use of stickiness only! +type linkedMap struct { + m map[string]*list.Element + l *list.List // Head of the list is the oldest element. +} + +// newLinkedMap returns a new LinkedMap. +func newLinkedMap() *linkedMap { + return &linkedMap{ + m: make(map[string]*list.Element), + l: list.New(), + } +} + +// put adds entry (key, value) to the map. Existing key will be overridden. +func (m *linkedMap) put(key string, value *stickyStoreEntry) { + if oldE, ok := m.m[key]; ok { + // Remove existing entry. + m.l.Remove(oldE) + } + e := m.l.PushBack(&linkedMapKVPair{key: key, value: value}) + m.m[key] = e +} + +// get returns the value of the given key. +func (m *linkedMap) get(key string) (*stickyStoreEntry, bool) { + e, ok := m.m[key] + if !ok { + return nil, false + } + m.l.MoveToBack(e) + return e.Value.(*linkedMapKVPair).value, true +} + +// remove removes key from the map, and returns the value. The map is not +// modified if key is not in the map. +func (m *linkedMap) remove(key string) (*stickyStoreEntry, bool) { + e, ok := m.m[key] + if !ok { + return nil, false + } + delete(m.m, key) + m.l.Remove(e) + return e.Value.(*linkedMapKVPair).value, true +} + +// len returns the len of the map. +func (m *linkedMap) len() int { + return len(m.m) +} + +// clear removes all elements from the map. +func (m *linkedMap) clear() { + m.m = make(map[string]*list.Element) + m.l = list.New() +} + +// removeOldest removes the oldest key from the map. +func (m *linkedMap) removeOldest() { + e := m.l.Front() + m.l.Remove(e) + delete(m.m, e.Value.(*linkedMapKVPair).key) +} diff --git a/vendor/google.golang.org/grpc/stream.go b/vendor/google.golang.org/grpc/stream.go index 82921a15a..152d9eccd 100644 --- a/vendor/google.golang.org/grpc/stream.go +++ b/vendor/google.golang.org/grpc/stream.go @@ -27,9 +27,9 @@ import ( "golang.org/x/net/context" "golang.org/x/net/trace" "google.golang.org/grpc/balancer" - "google.golang.org/grpc/channelz" "google.golang.org/grpc/codes" "google.golang.org/grpc/encoding" + "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/metadata" "google.golang.org/grpc/stats" "google.golang.org/grpc/status" @@ -101,7 +101,21 @@ type ClientStream interface { } // NewStream creates a new Stream for the client side. This is typically -// called by generated code. +// called by generated code. ctx is used for the lifetime of the stream. +// +// To ensure resources are not leaked due to the stream returned, one of the following +// actions must be performed: +// +// 1. Call Close on the ClientConn. +// 2. Cancel the context provided. +// 3. Call RecvMsg until a non-nil error is returned. A protobuf-generated +// client-streaming RPC, for instance, might use the helper function +// CloseAndRecv (note that CloseSend does not Recv, therefore is not +// guaranteed to release all resources). +// 4. Receive a non-nil, non-io.EOF error from Header or SendMsg. +// +// If none of the above happen, a goroutine and a context will be leaked, and grpc +// will not call the optionally-configured stats handler with a stats.End message. func (cc *ClientConn) NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error) { // allow interceptor to see all applicable call options, which means those // configured as defaults from dial option as well as per-call options @@ -113,8 +127,7 @@ func (cc *ClientConn) NewStream(ctx context.Context, desc *StreamDesc, method st return newClientStream(ctx, desc, cc, method, opts...) } -// NewClientStream creates a new Stream for the client side. This is typically -// called by generated code. +// NewClientStream is a wrapper for ClientConn.NewStream. // // DEPRECATED: Use ClientConn.NewStream instead. func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error) { @@ -466,27 +479,27 @@ func (a *csAttempt) sendMsg(m interface{}) (err error) { } a.mu.Unlock() } - var outPayload *stats.OutPayload - if a.statsHandler != nil { - outPayload = &stats.OutPayload{ - Client: true, - } + data, err := encode(cs.codec, m) + if err != nil { + return err } - hdr, data, err := encode(cs.codec, m, cs.cp, outPayload, cs.comp) + compData, err := compress(data, cs.cp, cs.comp) if err != nil { return err } - if len(data) > *cs.c.maxSendMessageSize { - return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(data), *cs.c.maxSendMessageSize) + hdr, payload := msgHeader(data, compData) + // TODO(dfawley): should we be checking len(data) instead? + if len(payload) > *cs.c.maxSendMessageSize { + return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(payload), *cs.c.maxSendMessageSize) } + if !cs.desc.ClientStreams { cs.sentLast = true } - err = a.t.Write(a.s, hdr, data, &transport.Options{Last: !cs.desc.ClientStreams}) + err = a.t.Write(a.s, hdr, payload, &transport.Options{Last: !cs.desc.ClientStreams}) if err == nil { - if outPayload != nil { - outPayload.SentTime = time.Now() - a.statsHandler.HandleRPC(a.ctx, outPayload) + if a.statsHandler != nil { + a.statsHandler.HandleRPC(a.ctx, outPayload(true, m, data, payload, time.Now())) } if channelz.IsOn() { a.t.IncrMsgSent() @@ -696,23 +709,24 @@ func (ss *serverStream) SendMsg(m interface{}) (err error) { ss.t.IncrMsgSent() } }() - var outPayload *stats.OutPayload - if ss.statsHandler != nil { - outPayload = &stats.OutPayload{} + data, err := encode(ss.codec, m) + if err != nil { + return err } - hdr, data, err := encode(ss.codec, m, ss.cp, outPayload, ss.comp) + compData, err := compress(data, ss.cp, ss.comp) if err != nil { return err } - if len(data) > ss.maxSendMessageSize { - return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(data), ss.maxSendMessageSize) + hdr, payload := msgHeader(data, compData) + // TODO(dfawley): should we be checking len(data) instead? + if len(payload) > ss.maxSendMessageSize { + return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(payload), ss.maxSendMessageSize) } - if err := ss.t.Write(ss.s, hdr, data, &transport.Options{Last: false}); err != nil { + if err := ss.t.Write(ss.s, hdr, payload, &transport.Options{Last: false}); err != nil { return toRPCErr(err) } - if outPayload != nil { - outPayload.SentTime = time.Now() - ss.statsHandler.HandleRPC(ss.s.Context(), outPayload) + if ss.statsHandler != nil { + ss.statsHandler.HandleRPC(ss.s.Context(), outPayload(false, m, data, payload, time.Now())) } return nil } diff --git a/vendor/google.golang.org/grpc/transport/controlbuf.go b/vendor/google.golang.org/grpc/transport/controlbuf.go index e147cd51b..5c5891a11 100644 --- a/vendor/google.golang.org/grpc/transport/controlbuf.go +++ b/vendor/google.golang.org/grpc/transport/controlbuf.go @@ -28,6 +28,10 @@ import ( "golang.org/x/net/http2/hpack" ) +var updateHeaderTblSize = func(e *hpack.Encoder, v uint32) { + e.SetMaxDynamicTableSizeLimit(v) +} + type itemNode struct { it interface{} next *itemNode @@ -80,6 +84,13 @@ func (il *itemList) isEmpty() bool { // the control buffer of transport. They represent different aspects of // control tasks, e.g., flow control, settings, streaming resetting, etc. +// registerStream is used to register an incoming stream with loopy writer. +type registerStream struct { + streamID uint32 + wq *writeQuota +} + +// headerFrame is also used to register stream on the client-side. type headerFrame struct { streamID uint32 hf []hpack.HeaderField @@ -361,44 +372,47 @@ func newLoopyWriter(s side, fr *framer, cbuf *controlBuffer, bdpEst *bdpEstimato const minBatchSize = 1000 // run should be run in a separate goroutine. -func (l *loopyWriter) run() { - var ( - it interface{} - err error - isEmpty bool - ) +func (l *loopyWriter) run() (err error) { defer func() { - errorf("transport: loopyWriter.run returning. Err: %v", err) + if err == ErrConnClosing { + // Don't log ErrConnClosing as error since it happens + // 1. When the connection is closed by some other known issue. + // 2. User closed the connection. + // 3. A graceful close of connection. + infof("transport: loopyWriter.run returning. %v", err) + err = nil + } }() for { - it, err = l.cbuf.get(true) + it, err := l.cbuf.get(true) if err != nil { - return + return err } if err = l.handle(it); err != nil { - return + return err } if _, err = l.processData(); err != nil { - return + return err } gosched := true hasdata: for { - it, err = l.cbuf.get(false) + it, err := l.cbuf.get(false) if err != nil { - return + return err } if it != nil { if err = l.handle(it); err != nil { - return + return err } if _, err = l.processData(); err != nil { - return + return err } continue hasdata } - if isEmpty, err = l.processData(); err != nil { - return + isEmpty, err := l.processData() + if err != nil { + return err } if !isEmpty { continue hasdata @@ -450,30 +464,39 @@ func (l *loopyWriter) incomingSettingsHandler(s *incomingSettings) error { return l.framer.fr.WriteSettingsAck() } +func (l *loopyWriter) registerStreamHandler(h *registerStream) error { + str := &outStream{ + id: h.streamID, + state: empty, + itl: &itemList{}, + wq: h.wq, + } + l.estdStreams[h.streamID] = str + return nil +} + func (l *loopyWriter) headerHandler(h *headerFrame) error { if l.side == serverSide { - if h.endStream { // Case 1.A: Server wants to close stream. - // Make sure it's not a trailers only response. - if str, ok := l.estdStreams[h.streamID]; ok { - if str.state != empty { // either active or waiting on stream quota. - // add it str's list of items. - str.itl.enqueue(h) - return nil - } - } - if err := l.writeHeader(h.streamID, h.endStream, h.hf, h.onWrite); err != nil { - return err - } - return l.cleanupStreamHandler(h.cleanup) + str, ok := l.estdStreams[h.streamID] + if !ok { + warningf("transport: loopy doesn't recognize the stream: %d", h.streamID) + return nil + } + // Case 1.A: Server is responding back with headers. + if !h.endStream { + return l.writeHeader(h.streamID, h.endStream, h.hf, h.onWrite) } - // Case 1.B: Server is responding back with headers. - str := &outStream{ - state: empty, - itl: &itemList{}, - wq: h.wq, + // else: Case 1.B: Server wants to close stream. + + if str.state != empty { // either active or waiting on stream quota. + // add it str's list of items. + str.itl.enqueue(h) + return nil + } + if err := l.writeHeader(h.streamID, h.endStream, h.hf, h.onWrite); err != nil { + return err } - l.estdStreams[h.streamID] = str - return l.writeHeader(h.streamID, h.endStream, h.hf, h.onWrite) + return l.cleanupStreamHandler(h.cleanup) } // Case 2: Client wants to originate stream. str := &outStream{ @@ -632,6 +655,8 @@ func (l *loopyWriter) handle(i interface{}) error { return l.outgoingSettingsHandler(i) case *headerFrame: return l.headerHandler(i) + case *registerStream: + return l.registerStreamHandler(i) case *cleanupStream: return l.cleanupStreamHandler(i) case *incomingGoAway: @@ -664,6 +689,8 @@ func (l *loopyWriter) applySettings(ss []http2.Setting) error { } } } + case http2.SettingHeaderTableSize: + updateHeaderTblSize(l.hEnc, s.Val) } } return nil diff --git a/vendor/google.golang.org/grpc/transport/flowcontrol.go b/vendor/google.golang.org/grpc/transport/flowcontrol.go index 378f5c450..bbf98b6f5 100644 --- a/vendor/google.golang.org/grpc/transport/flowcontrol.go +++ b/vendor/google.golang.org/grpc/transport/flowcontrol.go @@ -58,14 +58,20 @@ type writeQuota struct { ch chan struct{} // done is triggered in error case. done <-chan struct{} + // replenish is called by loopyWriter to give quota back to. + // It is implemented as a field so that it can be updated + // by tests. + replenish func(n int) } func newWriteQuota(sz int32, done <-chan struct{}) *writeQuota { - return &writeQuota{ + w := &writeQuota{ quota: sz, ch: make(chan struct{}, 1), done: done, } + w.replenish = w.realReplenish + return w } func (w *writeQuota) get(sz int32) error { @@ -83,7 +89,7 @@ func (w *writeQuota) get(sz int32) error { } } -func (w *writeQuota) replenish(n int) { +func (w *writeQuota) realReplenish(n int) { sz := int32(n) a := atomic.AddInt32(&w.quota, sz) b := a - sz diff --git a/vendor/google.golang.org/grpc/transport/http2_client.go b/vendor/google.golang.org/grpc/transport/http2_client.go index 1fdabd954..eaf007eb0 100644 --- a/vendor/google.golang.org/grpc/transport/http2_client.go +++ b/vendor/google.golang.org/grpc/transport/http2_client.go @@ -31,9 +31,9 @@ import ( "golang.org/x/net/http2" "golang.org/x/net/http2/hpack" - "google.golang.org/grpc/channelz" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" + "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" @@ -76,8 +76,9 @@ type http2Client struct { // Boolean to keep track of reading activity on transport. // 1 is true and 0 is false. - activity uint32 // Accessed atomically. - kp keepalive.ClientParameters + activity uint32 // Accessed atomically. + kp keepalive.ClientParameters + keepaliveEnabled bool statsHandler stats.Handler @@ -259,6 +260,10 @@ func newHTTP2Client(connectCtx, ctx context.Context, addr TargetInfo, opts Conne if channelz.IsOn() { t.channelzID = channelz.RegisterNormalSocket(t, opts.ChannelzParentID, "") } + if t.kp.Time != infinity { + t.keepaliveEnabled = true + go t.keepalive() + } // Start the reader goroutine for incoming message. Each transport has // a dedicated goroutine which reads HTTP2 frame from network. Then it // dispatches the frame to the corresponding stream entity. @@ -295,13 +300,17 @@ func newHTTP2Client(connectCtx, ctx context.Context, addr TargetInfo, opts Conne t.framer.writer.Flush() go func() { t.loopy = newLoopyWriter(clientSide, t.framer, t.controlBuf, t.bdpEst) - t.loopy.run() - t.conn.Close() + err := t.loopy.run() + if err != nil { + errorf("transport: loopyWriter.run returning. Err: %v", err) + } + // If it's a connection error, let reader goroutine handle it + // since there might be data in the buffers. + if _, ok := err.(net.Error); !ok { + t.conn.Close() + } close(t.writerDone) }() - if t.kp.Time != infinity { - go t.keepalive() - } return t, nil } @@ -537,7 +546,7 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Strea var sendPing bool // If the number of active streams change from 0 to 1, then check if keepalive // has gone dormant. If so, wake it up. - if len(t.activeStreams) == 1 { + if len(t.activeStreams) == 1 && t.keepaliveEnabled { select { case t.awakenKeepalive <- struct{}{}: sendPing = true @@ -735,6 +744,7 @@ func (t *http2Client) GracefulClose() error { if active == 0 { return t.Close() } + t.controlBuf.put(&incomingGoAway{}) return nil } @@ -1109,7 +1119,9 @@ func (t *http2Client) reader() { t.Close() return } - atomic.CompareAndSwapUint32(&t.activity, 0, 1) + if t.keepaliveEnabled { + atomic.CompareAndSwapUint32(&t.activity, 0, 1) + } sf, ok := frame.(*http2.SettingsFrame) if !ok { t.Close() @@ -1121,7 +1133,9 @@ func (t *http2Client) reader() { // loop to keep reading incoming messages on this transport. for { frame, err := t.framer.fr.ReadFrame() - atomic.CompareAndSwapUint32(&t.activity, 0, 1) + if t.keepaliveEnabled { + atomic.CompareAndSwapUint32(&t.activity, 0, 1) + } if err != nil { // Abort an active stream if the http2.Framer returns a // http2.StreamError. This can happen only if the server's response diff --git a/vendor/google.golang.org/grpc/transport/http2_server.go b/vendor/google.golang.org/grpc/transport/http2_server.go index ab3561890..19acedb2b 100644 --- a/vendor/google.golang.org/grpc/transport/http2_server.go +++ b/vendor/google.golang.org/grpc/transport/http2_server.go @@ -24,7 +24,6 @@ import ( "fmt" "io" "math" - "math/rand" "net" "strconv" "sync" @@ -36,9 +35,11 @@ import ( "golang.org/x/net/http2" "golang.org/x/net/http2/hpack" - "google.golang.org/grpc/channelz" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/internal/channelz" + "google.golang.org/grpc/internal/grpcrand" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" @@ -273,7 +274,9 @@ func newHTTP2Server(conn net.Conn, config *ServerConfig) (_ ServerTransport, err go func() { t.loopy = newLoopyWriter(serverSide, t.framer, t.controlBuf, t.bdpEst) t.loopy.ssGoAwayHandler = t.outgoingGoAwayHandler - t.loopy.run() + if err := t.loopy.run(); err != nil { + errorf("transport: loopyWriter.run returning. Err: %v", err) + } t.conn.Close() close(t.writerDone) }() @@ -413,6 +416,11 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( t.updateWindow(s, uint32(n)) }, } + // Register the stream with loopy. + t.controlBuf.put(®isterStream{ + streamID: s.id, + wq: s.wq, + }) handle(s) return } @@ -730,7 +738,6 @@ func (t *http2Server) writeHeaderLocked(s *Stream) { onWrite: func() { atomic.StoreUint32(&t.resetPingStrikes, 1) }, - wq: s.wq, }) if t.stats != nil { // Note: WireLength is not set in outHeader. @@ -767,10 +774,10 @@ func (t *http2Server) WriteStatus(s *Stream, st *status.Status) error { stBytes, err := proto.Marshal(p) if err != nil { // TODO: return error instead, when callers are able to handle it. - panic(err) + grpclog.Errorf("transport: failed to marshal rpc status: %v, error: %v", p, err) + } else { + headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-status-details-bin", Value: encodeBinHeader(stBytes)}) } - - headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-status-details-bin", Value: encodeBinHeader(stBytes)}) } // Attach the trailer metadata. @@ -1124,14 +1131,12 @@ func (t *http2Server) getOutFlowWindow() int64 { } } -var rgen = rand.New(rand.NewSource(time.Now().UnixNano())) - func getJitter(v time.Duration) time.Duration { if v == infinity { return 0 } // Generate a jitter between +/- 10% of the value. r := int64(v / 10) - j := rgen.Int63n(2*r) - r + j := grpcrand.Int63n(2*r) - r return time.Duration(j) } diff --git a/vendor/google.golang.org/grpc/transport/http_util.go b/vendor/google.golang.org/grpc/transport/http_util.go index 835c81269..7d15c7d74 100644 --- a/vendor/google.golang.org/grpc/transport/http_util.go +++ b/vendor/google.golang.org/grpc/transport/http_util.go @@ -28,6 +28,7 @@ import ( "strconv" "strings" "time" + "unicode/utf8" "github.com/golang/protobuf/proto" "golang.org/x/net/http2" @@ -437,16 +438,17 @@ func decodeTimeout(s string) (time.Duration, error) { const ( spaceByte = ' ' - tildaByte = '~' + tildeByte = '~' percentByte = '%' ) // encodeGrpcMessage is used to encode status code in header field -// "grpc-message". -// It checks to see if each individual byte in msg is an -// allowable byte, and then either percent encoding or passing it through. -// When percent encoding, the byte is converted into hexadecimal notation -// with a '%' prepended. +// "grpc-message". It does percent encoding and also replaces invalid utf-8 +// characters with Unicode replacement character. +// +// It checks to see if each individual byte in msg is an allowable byte, and +// then either percent encoding or passing it through. When percent encoding, +// the byte is converted into hexadecimal notation with a '%' prepended. func encodeGrpcMessage(msg string) string { if msg == "" { return "" @@ -454,7 +456,7 @@ func encodeGrpcMessage(msg string) string { lenMsg := len(msg) for i := 0; i < lenMsg; i++ { c := msg[i] - if !(c >= spaceByte && c < tildaByte && c != percentByte) { + if !(c >= spaceByte && c <= tildeByte && c != percentByte) { return encodeGrpcMessageUnchecked(msg) } } @@ -463,14 +465,26 @@ func encodeGrpcMessage(msg string) string { func encodeGrpcMessageUnchecked(msg string) string { var buf bytes.Buffer - lenMsg := len(msg) - for i := 0; i < lenMsg; i++ { - c := msg[i] - if c >= spaceByte && c < tildaByte && c != percentByte { - buf.WriteByte(c) - } else { - buf.WriteString(fmt.Sprintf("%%%02X", c)) + for len(msg) > 0 { + r, size := utf8.DecodeRuneInString(msg) + for _, b := range []byte(string(r)) { + if size > 1 { + // If size > 1, r is not ascii. Always do percent encoding. + buf.WriteString(fmt.Sprintf("%%%02X", b)) + continue + } + + // The for loop is necessary even if size == 1. r could be + // utf8.RuneError. + // + // fmt.Sprintf("%%%02X", utf8.RuneError) gives "%FFFD". + if b >= spaceByte && b <= tildeByte && b != percentByte { + buf.WriteByte(b) + } else { + buf.WriteString(fmt.Sprintf("%%%02X", b)) + } } + msg = msg[size:] } return buf.String() } diff --git a/vendor/google.golang.org/grpc/version.go b/vendor/google.golang.org/grpc/version.go new file mode 100644 index 000000000..7f124fbd5 --- /dev/null +++ b/vendor/google.golang.org/grpc/version.go @@ -0,0 +1,22 @@ +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package grpc + +// Version is the current grpc version. +const Version = "1.13.0" diff --git a/vendor/gopkg.in/go-playground/validator.v8/LICENSE b/vendor/gopkg.in/go-playground/validator.v8/LICENSE deleted file mode 100644 index 6a2ae9aa4..000000000 --- a/vendor/gopkg.in/go-playground/validator.v8/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Dean Karn - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/vendor/gopkg.in/go-playground/validator.v8/baked_in.go b/vendor/gopkg.in/go-playground/validator.v8/baked_in.go deleted file mode 100644 index 44aaa0851..000000000 --- a/vendor/gopkg.in/go-playground/validator.v8/baked_in.go +++ /dev/null @@ -1,1410 +0,0 @@ -package validator - -import ( - "fmt" - "net" - "net/url" - "reflect" - "strings" - "time" - "unicode/utf8" -) - -// BakedInAliasValidators is a default mapping of a single validationstag that -// defines a common or complex set of validation(s) to simplify -// adding validation to structs. i.e. set key "_ageok" and the tags -// are "gt=0,lte=130" or key "_preferredname" and tags "omitempty,gt=0,lte=60" -var bakedInAliasValidators = map[string]string{ - "iscolor": "hexcolor|rgb|rgba|hsl|hsla", -} - -// BakedInValidators is the default map of ValidationFunc -// you can add, remove or even replace items to suite your needs, -// or even disregard and use your own map if so desired. -var bakedInValidators = map[string]Func{ - "required": HasValue, - "len": HasLengthOf, - "min": HasMinOf, - "max": HasMaxOf, - "eq": IsEq, - "ne": IsNe, - "lt": IsLt, - "lte": IsLte, - "gt": IsGt, - "gte": IsGte, - "eqfield": IsEqField, - "eqcsfield": IsEqCrossStructField, - "necsfield": IsNeCrossStructField, - "gtcsfield": IsGtCrossStructField, - "gtecsfield": IsGteCrossStructField, - "ltcsfield": IsLtCrossStructField, - "ltecsfield": IsLteCrossStructField, - "nefield": IsNeField, - "gtefield": IsGteField, - "gtfield": IsGtField, - "ltefield": IsLteField, - "ltfield": IsLtField, - "alpha": IsAlpha, - "alphanum": IsAlphanum, - "numeric": IsNumeric, - "number": IsNumber, - "hexadecimal": IsHexadecimal, - "hexcolor": IsHEXColor, - "rgb": IsRGB, - "rgba": IsRGBA, - "hsl": IsHSL, - "hsla": IsHSLA, - "email": IsEmail, - "url": IsURL, - "uri": IsURI, - "base64": IsBase64, - "contains": Contains, - "containsany": ContainsAny, - "containsrune": ContainsRune, - "excludes": Excludes, - "excludesall": ExcludesAll, - "excludesrune": ExcludesRune, - "isbn": IsISBN, - "isbn10": IsISBN10, - "isbn13": IsISBN13, - "uuid": IsUUID, - "uuid3": IsUUID3, - "uuid4": IsUUID4, - "uuid5": IsUUID5, - "ascii": IsASCII, - "printascii": IsPrintableASCII, - "multibyte": HasMultiByteCharacter, - "datauri": IsDataURI, - "latitude": IsLatitude, - "longitude": IsLongitude, - "ssn": IsSSN, - "ipv4": IsIPv4, - "ipv6": IsIPv6, - "ip": IsIP, - "cidrv4": IsCIDRv4, - "cidrv6": IsCIDRv6, - "cidr": IsCIDR, - "tcp4_addr": IsTCP4AddrResolvable, - "tcp6_addr": IsTCP6AddrResolvable, - "tcp_addr": IsTCPAddrResolvable, - "udp4_addr": IsUDP4AddrResolvable, - "udp6_addr": IsUDP6AddrResolvable, - "udp_addr": IsUDPAddrResolvable, - "ip4_addr": IsIP4AddrResolvable, - "ip6_addr": IsIP6AddrResolvable, - "ip_addr": IsIPAddrResolvable, - "unix_addr": IsUnixAddrResolvable, - "mac": IsMAC, -} - -// IsMAC is the validation function for validating if the field's value is a valid MAC address. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsMAC(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - _, err := net.ParseMAC(field.String()) - return err == nil -} - -// IsCIDRv4 is the validation function for validating if the field's value is a valid v4 CIDR address. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsCIDRv4(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - ip, _, err := net.ParseCIDR(field.String()) - - return err == nil && ip.To4() != nil -} - -// IsCIDRv6 is the validation function for validating if the field's value is a valid v6 CIDR address. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsCIDRv6(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - ip, _, err := net.ParseCIDR(field.String()) - - return err == nil && ip.To4() == nil -} - -// IsCIDR is the validation function for validating if the field's value is a valid v4 or v6 CIDR address. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsCIDR(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - _, _, err := net.ParseCIDR(field.String()) - - return err == nil -} - -// IsIPv4 is the validation function for validating if a value is a valid v4 IP address. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsIPv4(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - ip := net.ParseIP(field.String()) - - return ip != nil && ip.To4() != nil -} - -// IsIPv6 is the validation function for validating if the field's value is a valid v6 IP address. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsIPv6(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - ip := net.ParseIP(field.String()) - - return ip != nil && ip.To4() == nil -} - -// IsIP is the validation function for validating if the field's value is a valid v4 or v6 IP address. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsIP(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - ip := net.ParseIP(field.String()) - - return ip != nil -} - -// IsSSN is the validation function for validating if the field's value is a valid SSN. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsSSN(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - if field.Len() != 11 { - return false - } - - return sSNRegex.MatchString(field.String()) -} - -// IsLongitude is the validation function for validating if the field's value is a valid longitude coordinate. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsLongitude(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return longitudeRegex.MatchString(field.String()) -} - -// IsLatitude is the validation function for validating if the field's value is a valid latitude coordinate. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsLatitude(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return latitudeRegex.MatchString(field.String()) -} - -// IsDataURI is the validation function for validating if the field's value is a valid data URI. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsDataURI(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - uri := strings.SplitN(field.String(), ",", 2) - - if len(uri) != 2 { - return false - } - - if !dataURIRegex.MatchString(uri[0]) { - return false - } - - fld := reflect.ValueOf(uri[1]) - - return IsBase64(v, topStruct, currentStructOrField, fld, fld.Type(), fld.Kind(), param) -} - -// HasMultiByteCharacter is the validation function for validating if the field's value has a multi byte character. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func HasMultiByteCharacter(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - if field.Len() == 0 { - return true - } - - return multibyteRegex.MatchString(field.String()) -} - -// IsPrintableASCII is the validation function for validating if the field's value is a valid printable ASCII character. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsPrintableASCII(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return printableASCIIRegex.MatchString(field.String()) -} - -// IsASCII is the validation function for validating if the field's value is a valid ASCII character. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsASCII(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return aSCIIRegex.MatchString(field.String()) -} - -// IsUUID5 is the validation function for validating if the field's value is a valid v5 UUID. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsUUID5(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return uUID5Regex.MatchString(field.String()) -} - -// IsUUID4 is the validation function for validating if the field's value is a valid v4 UUID. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsUUID4(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return uUID4Regex.MatchString(field.String()) -} - -// IsUUID3 is the validation function for validating if the field's value is a valid v3 UUID. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsUUID3(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return uUID3Regex.MatchString(field.String()) -} - -// IsUUID is the validation function for validating if the field's value is a valid UUID of any version. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsUUID(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return uUIDRegex.MatchString(field.String()) -} - -// IsISBN is the validation function for validating if the field's value is a valid v10 or v13 ISBN. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsISBN(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return IsISBN10(v, topStruct, currentStructOrField, field, fieldType, fieldKind, param) || IsISBN13(v, topStruct, currentStructOrField, field, fieldType, fieldKind, param) -} - -// IsISBN13 is the validation function for validating if the field's value is a valid v13 ISBN. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsISBN13(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - s := strings.Replace(strings.Replace(field.String(), "-", "", 4), " ", "", 4) - - if !iSBN13Regex.MatchString(s) { - return false - } - - var checksum int32 - var i int32 - - factor := []int32{1, 3} - - for i = 0; i < 12; i++ { - checksum += factor[i%2] * int32(s[i]-'0') - } - - return (int32(s[12]-'0'))-((10-(checksum%10))%10) == 0 -} - -// IsISBN10 is the validation function for validating if the field's value is a valid v10 ISBN. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsISBN10(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - s := strings.Replace(strings.Replace(field.String(), "-", "", 3), " ", "", 3) - - if !iSBN10Regex.MatchString(s) { - return false - } - - var checksum int32 - var i int32 - - for i = 0; i < 9; i++ { - checksum += (i + 1) * int32(s[i]-'0') - } - - if s[9] == 'X' { - checksum += 10 * 10 - } else { - checksum += 10 * int32(s[9]-'0') - } - - return checksum%11 == 0 -} - -// ExcludesRune is the validation function for validating that the field's value does not contain the rune specified within the param. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func ExcludesRune(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return !ContainsRune(v, topStruct, currentStructOrField, field, fieldType, fieldKind, param) -} - -// ExcludesAll is the validation function for validating that the field's value does not contain any of the characters specified within the param. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func ExcludesAll(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return !ContainsAny(v, topStruct, currentStructOrField, field, fieldType, fieldKind, param) -} - -// Excludes is the validation function for validating that the field's value does not contain the text specified within the param. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func Excludes(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return !Contains(v, topStruct, currentStructOrField, field, fieldType, fieldKind, param) -} - -// ContainsRune is the validation function for validating that the field's value contains the rune specified within the param. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func ContainsRune(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - r, _ := utf8.DecodeRuneInString(param) - - return strings.ContainsRune(field.String(), r) -} - -// ContainsAny is the validation function for validating that the field's value contains any of the characters specified within the param. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func ContainsAny(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return strings.ContainsAny(field.String(), param) -} - -// Contains is the validation function for validating that the field's value contains the text specified within the param. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func Contains(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return strings.Contains(field.String(), param) -} - -// IsNeField is the validation function for validating if the current field's value is not equal to the field specified by the param's value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsNeField(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - currentField, currentKind, ok := v.GetStructFieldOK(currentStructOrField, param) - - if !ok || currentKind != fieldKind { - return true - } - - switch fieldKind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return field.Int() != currentField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return field.Uint() != currentField.Uint() - - case reflect.Float32, reflect.Float64: - return field.Float() != currentField.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(field.Len()) != int64(currentField.Len()) - - case reflect.Struct: - - // Not Same underlying type i.e. struct and time - if fieldType != currentField.Type() { - return true - } - - if fieldType == timeType { - - t := currentField.Interface().(time.Time) - fieldTime := field.Interface().(time.Time) - - return !fieldTime.Equal(t) - } - - } - - // default reflect.String: - return field.String() != currentField.String() -} - -// IsNe is the validation function for validating that the field's value does not equal the provided param value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsNe(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return !IsEq(v, topStruct, currentStructOrField, field, fieldType, fieldKind, param) -} - -// IsLteCrossStructField is the validation function for validating if the current field's value is less than or equal to the field, within a separate struct, specified by the param's value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsLteCrossStructField(v *Validate, topStruct reflect.Value, current reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - topField, topKind, ok := v.GetStructFieldOK(topStruct, param) - if !ok || topKind != fieldKind { - return false - } - - switch fieldKind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return field.Int() <= topField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return field.Uint() <= topField.Uint() - - case reflect.Float32, reflect.Float64: - return field.Float() <= topField.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(field.Len()) <= int64(topField.Len()) - - case reflect.Struct: - - // Not Same underlying type i.e. struct and time - if fieldType != topField.Type() { - return false - } - - if fieldType == timeType { - - fieldTime := field.Interface().(time.Time) - topTime := topField.Interface().(time.Time) - - return fieldTime.Before(topTime) || fieldTime.Equal(topTime) - } - } - - // default reflect.String: - return field.String() <= topField.String() -} - -// IsLtCrossStructField is the validation function for validating if the current field's value is less than the field, within a separate struct, specified by the param's value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsLtCrossStructField(v *Validate, topStruct reflect.Value, current reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - topField, topKind, ok := v.GetStructFieldOK(topStruct, param) - if !ok || topKind != fieldKind { - return false - } - - switch fieldKind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return field.Int() < topField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return field.Uint() < topField.Uint() - - case reflect.Float32, reflect.Float64: - return field.Float() < topField.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(field.Len()) < int64(topField.Len()) - - case reflect.Struct: - - // Not Same underlying type i.e. struct and time - if fieldType != topField.Type() { - return false - } - - if fieldType == timeType { - - fieldTime := field.Interface().(time.Time) - topTime := topField.Interface().(time.Time) - - return fieldTime.Before(topTime) - } - } - - // default reflect.String: - return field.String() < topField.String() -} - -// IsGteCrossStructField is the validation function for validating if the current field's value is greater than or equal to the field, within a separate struct, specified by the param's value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsGteCrossStructField(v *Validate, topStruct reflect.Value, current reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - topField, topKind, ok := v.GetStructFieldOK(topStruct, param) - if !ok || topKind != fieldKind { - return false - } - - switch fieldKind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return field.Int() >= topField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return field.Uint() >= topField.Uint() - - case reflect.Float32, reflect.Float64: - return field.Float() >= topField.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(field.Len()) >= int64(topField.Len()) - - case reflect.Struct: - - // Not Same underlying type i.e. struct and time - if fieldType != topField.Type() { - return false - } - - if fieldType == timeType { - - fieldTime := field.Interface().(time.Time) - topTime := topField.Interface().(time.Time) - - return fieldTime.After(topTime) || fieldTime.Equal(topTime) - } - } - - // default reflect.String: - return field.String() >= topField.String() -} - -// IsGtCrossStructField is the validation function for validating if the current field's value is greater than the field, within a separate struct, specified by the param's value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsGtCrossStructField(v *Validate, topStruct reflect.Value, current reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - topField, topKind, ok := v.GetStructFieldOK(topStruct, param) - if !ok || topKind != fieldKind { - return false - } - - switch fieldKind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return field.Int() > topField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return field.Uint() > topField.Uint() - - case reflect.Float32, reflect.Float64: - return field.Float() > topField.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(field.Len()) > int64(topField.Len()) - - case reflect.Struct: - - // Not Same underlying type i.e. struct and time - if fieldType != topField.Type() { - return false - } - - if fieldType == timeType { - - fieldTime := field.Interface().(time.Time) - topTime := topField.Interface().(time.Time) - - return fieldTime.After(topTime) - } - } - - // default reflect.String: - return field.String() > topField.String() -} - -// IsNeCrossStructField is the validation function for validating that the current field's value is not equal to the field, within a separate struct, specified by the param's value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsNeCrossStructField(v *Validate, topStruct reflect.Value, current reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - topField, currentKind, ok := v.GetStructFieldOK(topStruct, param) - if !ok || currentKind != fieldKind { - return true - } - - switch fieldKind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return topField.Int() != field.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return topField.Uint() != field.Uint() - - case reflect.Float32, reflect.Float64: - return topField.Float() != field.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(topField.Len()) != int64(field.Len()) - - case reflect.Struct: - - // Not Same underlying type i.e. struct and time - if fieldType != topField.Type() { - return true - } - - if fieldType == timeType { - - t := field.Interface().(time.Time) - fieldTime := topField.Interface().(time.Time) - - return !fieldTime.Equal(t) - } - } - - // default reflect.String: - return topField.String() != field.String() -} - -// IsEqCrossStructField is the validation function for validating that the current field's value is equal to the field, within a separate struct, specified by the param's value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsEqCrossStructField(v *Validate, topStruct reflect.Value, current reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - topField, topKind, ok := v.GetStructFieldOK(topStruct, param) - if !ok || topKind != fieldKind { - return false - } - - switch fieldKind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return topField.Int() == field.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return topField.Uint() == field.Uint() - - case reflect.Float32, reflect.Float64: - return topField.Float() == field.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(topField.Len()) == int64(field.Len()) - - case reflect.Struct: - - // Not Same underlying type i.e. struct and time - if fieldType != topField.Type() { - return false - } - - if fieldType == timeType { - - t := field.Interface().(time.Time) - fieldTime := topField.Interface().(time.Time) - - return fieldTime.Equal(t) - } - } - - // default reflect.String: - return topField.String() == field.String() -} - -// IsEqField is the validation function for validating if the current field's value is equal to the field specified by the param's value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsEqField(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - currentField, currentKind, ok := v.GetStructFieldOK(currentStructOrField, param) - if !ok || currentKind != fieldKind { - return false - } - - switch fieldKind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return field.Int() == currentField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return field.Uint() == currentField.Uint() - - case reflect.Float32, reflect.Float64: - return field.Float() == currentField.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(field.Len()) == int64(currentField.Len()) - - case reflect.Struct: - - // Not Same underlying type i.e. struct and time - if fieldType != currentField.Type() { - return false - } - - if fieldType == timeType { - - t := currentField.Interface().(time.Time) - fieldTime := field.Interface().(time.Time) - - return fieldTime.Equal(t) - } - - } - - // default reflect.String: - return field.String() == currentField.String() -} - -// IsEq is the validation function for validating if the current field's value is equal to the param's value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsEq(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - switch fieldKind { - - case reflect.String: - return field.String() == param - - case reflect.Slice, reflect.Map, reflect.Array: - p := asInt(param) - - return int64(field.Len()) == p - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - p := asInt(param) - - return field.Int() == p - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - p := asUint(param) - - return field.Uint() == p - - case reflect.Float32, reflect.Float64: - p := asFloat(param) - - return field.Float() == p - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// IsBase64 is the validation function for validating if the current field's value is a valid base 64. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsBase64(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return base64Regex.MatchString(field.String()) -} - -// IsURI is the validation function for validating if the current field's value is a valid URI. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsURI(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - switch fieldKind { - - case reflect.String: - - s := field.String() - - // checks needed as of Go 1.6 because of change https://github.com/golang/go/commit/617c93ce740c3c3cc28cdd1a0d712be183d0b328#diff-6c2d018290e298803c0c9419d8739885L195 - // emulate browser and strip the '#' suffix prior to validation. see issue-#237 - if i := strings.Index(s, "#"); i > -1 { - s = s[:i] - } - - if s == blank { - return false - } - - _, err := url.ParseRequestURI(s) - - return err == nil - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// IsURL is the validation function for validating if the current field's value is a valid URL. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsURL(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - switch fieldKind { - - case reflect.String: - - var i int - s := field.String() - - // checks needed as of Go 1.6 because of change https://github.com/golang/go/commit/617c93ce740c3c3cc28cdd1a0d712be183d0b328#diff-6c2d018290e298803c0c9419d8739885L195 - // emulate browser and strip the '#' suffix prior to validation. see issue-#237 - if i = strings.Index(s, "#"); i > -1 { - s = s[:i] - } - - if s == blank { - return false - } - - url, err := url.ParseRequestURI(s) - - if err != nil || url.Scheme == blank { - return false - } - - return err == nil - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// IsEmail is the validation function for validating if the current field's value is a valid email address. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsEmail(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return emailRegex.MatchString(field.String()) -} - -// IsHSLA is the validation function for validating if the current field's value is a valid HSLA color. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsHSLA(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return hslaRegex.MatchString(field.String()) -} - -// IsHSL is the validation function for validating if the current field's value is a valid HSL color. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsHSL(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return hslRegex.MatchString(field.String()) -} - -// IsRGBA is the validation function for validating if the current field's value is a valid RGBA color. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsRGBA(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return rgbaRegex.MatchString(field.String()) -} - -// IsRGB is the validation function for validating if the current field's value is a valid RGB color. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsRGB(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return rgbRegex.MatchString(field.String()) -} - -// IsHEXColor is the validation function for validating if the current field's value is a valid HEX color. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsHEXColor(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return hexcolorRegex.MatchString(field.String()) -} - -// IsHexadecimal is the validation function for validating if the current field's value is a valid hexadecimal. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsHexadecimal(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return hexadecimalRegex.MatchString(field.String()) -} - -// IsNumber is the validation function for validating if the current field's value is a valid number. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsNumber(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return numberRegex.MatchString(field.String()) -} - -// IsNumeric is the validation function for validating if the current field's value is a valid numeric value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsNumeric(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return numericRegex.MatchString(field.String()) -} - -// IsAlphanum is the validation function for validating if the current field's value is a valid alphanumeric value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsAlphanum(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return alphaNumericRegex.MatchString(field.String()) -} - -// IsAlpha is the validation function for validating if the current field's value is a valid alpha value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsAlpha(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return alphaRegex.MatchString(field.String()) -} - -// HasValue is the validation function for validating if the current field's value is not the default static value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func HasValue(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - switch fieldKind { - case reflect.Slice, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func: - return !field.IsNil() - default: - return field.IsValid() && field.Interface() != reflect.Zero(fieldType).Interface() - } -} - -// IsGteField is the validation function for validating if the current field's value is greater than or equal to the field specified by the param's value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsGteField(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - currentField, currentKind, ok := v.GetStructFieldOK(currentStructOrField, param) - if !ok || currentKind != fieldKind { - return false - } - - switch fieldKind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - - return field.Int() >= currentField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - - return field.Uint() >= currentField.Uint() - - case reflect.Float32, reflect.Float64: - - return field.Float() >= currentField.Float() - - case reflect.Struct: - - // Not Same underlying type i.e. struct and time - if fieldType != currentField.Type() { - return false - } - - if fieldType == timeType { - - t := currentField.Interface().(time.Time) - fieldTime := field.Interface().(time.Time) - - return fieldTime.After(t) || fieldTime.Equal(t) - } - } - - // default reflect.String - return len(field.String()) >= len(currentField.String()) -} - -// IsGtField is the validation function for validating if the current field's value is greater than the field specified by the param's value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsGtField(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - currentField, currentKind, ok := v.GetStructFieldOK(currentStructOrField, param) - if !ok || currentKind != fieldKind { - return false - } - - switch fieldKind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - - return field.Int() > currentField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - - return field.Uint() > currentField.Uint() - - case reflect.Float32, reflect.Float64: - - return field.Float() > currentField.Float() - - case reflect.Struct: - - // Not Same underlying type i.e. struct and time - if fieldType != currentField.Type() { - return false - } - - if fieldType == timeType { - - t := currentField.Interface().(time.Time) - fieldTime := field.Interface().(time.Time) - - return fieldTime.After(t) - } - } - - // default reflect.String - return len(field.String()) > len(currentField.String()) -} - -// IsGte is the validation function for validating if the current field's value is greater than or equal to the param's value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsGte(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - switch fieldKind { - - case reflect.String: - p := asInt(param) - - return int64(utf8.RuneCountInString(field.String())) >= p - - case reflect.Slice, reflect.Map, reflect.Array: - p := asInt(param) - - return int64(field.Len()) >= p - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - p := asInt(param) - - return field.Int() >= p - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - p := asUint(param) - - return field.Uint() >= p - - case reflect.Float32, reflect.Float64: - p := asFloat(param) - - return field.Float() >= p - - case reflect.Struct: - - if fieldType == timeType || fieldType == timePtrType { - - now := time.Now().UTC() - t := field.Interface().(time.Time) - - return t.After(now) || t.Equal(now) - } - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// IsGt is the validation function for validating if the current field's value is greater than the param's value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsGt(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - switch fieldKind { - - case reflect.String: - p := asInt(param) - - return int64(utf8.RuneCountInString(field.String())) > p - - case reflect.Slice, reflect.Map, reflect.Array: - p := asInt(param) - - return int64(field.Len()) > p - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - p := asInt(param) - - return field.Int() > p - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - p := asUint(param) - - return field.Uint() > p - - case reflect.Float32, reflect.Float64: - p := asFloat(param) - - return field.Float() > p - case reflect.Struct: - - if fieldType == timeType || fieldType == timePtrType { - - return field.Interface().(time.Time).After(time.Now().UTC()) - } - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// HasLengthOf is the validation function for validating if the current field's value is equal to the param's value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func HasLengthOf(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - switch fieldKind { - - case reflect.String: - p := asInt(param) - - return int64(utf8.RuneCountInString(field.String())) == p - - case reflect.Slice, reflect.Map, reflect.Array: - p := asInt(param) - - return int64(field.Len()) == p - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - p := asInt(param) - - return field.Int() == p - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - p := asUint(param) - - return field.Uint() == p - - case reflect.Float32, reflect.Float64: - p := asFloat(param) - - return field.Float() == p - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// HasMinOf is the validation function for validating if the current field's value is greater than or equal to the param's value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func HasMinOf(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - return IsGte(v, topStruct, currentStructOrField, field, fieldType, fieldKind, param) -} - -// IsLteField is the validation function for validating if the current field's value is less than or equal to the field specified by the param's value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsLteField(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - currentField, currentKind, ok := v.GetStructFieldOK(currentStructOrField, param) - if !ok || currentKind != fieldKind { - return false - } - - switch fieldKind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - - return field.Int() <= currentField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - - return field.Uint() <= currentField.Uint() - - case reflect.Float32, reflect.Float64: - - return field.Float() <= currentField.Float() - - case reflect.Struct: - - // Not Same underlying type i.e. struct and time - if fieldType != currentField.Type() { - return false - } - - if fieldType == timeType { - - t := currentField.Interface().(time.Time) - fieldTime := field.Interface().(time.Time) - - return fieldTime.Before(t) || fieldTime.Equal(t) - } - } - - // default reflect.String - return len(field.String()) <= len(currentField.String()) -} - -// IsLtField is the validation function for validating if the current field's value is less than the field specified by the param's value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsLtField(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - currentField, currentKind, ok := v.GetStructFieldOK(currentStructOrField, param) - if !ok || currentKind != fieldKind { - return false - } - - switch fieldKind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - - return field.Int() < currentField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - - return field.Uint() < currentField.Uint() - - case reflect.Float32, reflect.Float64: - - return field.Float() < currentField.Float() - - case reflect.Struct: - - // Not Same underlying type i.e. struct and time - if fieldType != currentField.Type() { - return false - } - - if fieldType == timeType { - - t := currentField.Interface().(time.Time) - fieldTime := field.Interface().(time.Time) - - return fieldTime.Before(t) - } - } - - // default reflect.String - return len(field.String()) < len(currentField.String()) -} - -// IsLte is the validation function for validating if the current field's value is less than or equal to the param's value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsLte(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - switch fieldKind { - - case reflect.String: - p := asInt(param) - - return int64(utf8.RuneCountInString(field.String())) <= p - - case reflect.Slice, reflect.Map, reflect.Array: - p := asInt(param) - - return int64(field.Len()) <= p - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - p := asInt(param) - - return field.Int() <= p - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - p := asUint(param) - - return field.Uint() <= p - - case reflect.Float32, reflect.Float64: - p := asFloat(param) - - return field.Float() <= p - - case reflect.Struct: - - if fieldType == timeType || fieldType == timePtrType { - - now := time.Now().UTC() - t := field.Interface().(time.Time) - - return t.Before(now) || t.Equal(now) - } - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// IsLt is the validation function for validating if the current field's value is less than the param's value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsLt(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - switch fieldKind { - - case reflect.String: - p := asInt(param) - - return int64(utf8.RuneCountInString(field.String())) < p - - case reflect.Slice, reflect.Map, reflect.Array: - p := asInt(param) - - return int64(field.Len()) < p - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - p := asInt(param) - - return field.Int() < p - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - p := asUint(param) - - return field.Uint() < p - - case reflect.Float32, reflect.Float64: - p := asFloat(param) - - return field.Float() < p - - case reflect.Struct: - - if fieldType == timeType || fieldType == timePtrType { - - return field.Interface().(time.Time).Before(time.Now().UTC()) - } - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// HasMaxOf is the validation function for validating if the current field's value is less than or equal to the param's value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func HasMaxOf(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - return IsLte(v, topStruct, currentStructOrField, field, fieldType, fieldKind, param) -} - -// IsTCP4AddrResolvable is the validation function for validating if the field's value is a resolvable tcp4 address. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsTCP4AddrResolvable(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - if !isIP4Addr(v, topStruct, currentStructOrField, field, fieldType, fieldKind, param) { - return false - } - - _, err := net.ResolveTCPAddr("tcp4", field.String()) - return err == nil -} - -// IsTCP6AddrResolvable is the validation function for validating if the field's value is a resolvable tcp6 address. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsTCP6AddrResolvable(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - if !isIP6Addr(v, topStruct, currentStructOrField, field, fieldType, fieldKind, param) { - return false - } - - _, err := net.ResolveTCPAddr("tcp6", field.String()) - return err == nil -} - -// IsTCPAddrResolvable is the validation function for validating if the field's value is a resolvable tcp address. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsTCPAddrResolvable(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - if !isIP4Addr(v, topStruct, currentStructOrField, field, fieldType, fieldKind, param) && - !isIP6Addr(v, topStruct, currentStructOrField, field, fieldType, fieldKind, param) { - return false - } - - _, err := net.ResolveTCPAddr("tcp", field.String()) - return err == nil -} - -// IsUDP4AddrResolvable is the validation function for validating if the field's value is a resolvable udp4 address. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsUDP4AddrResolvable(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - if !isIP4Addr(v, topStruct, currentStructOrField, field, fieldType, fieldKind, param) { - return false - } - - _, err := net.ResolveUDPAddr("udp4", field.String()) - return err == nil -} - -// IsUDP6AddrResolvable is the validation function for validating if the field's value is a resolvable udp6 address. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsUDP6AddrResolvable(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - if !isIP6Addr(v, topStruct, currentStructOrField, field, fieldType, fieldKind, param) { - return false - } - - _, err := net.ResolveUDPAddr("udp6", field.String()) - return err == nil -} - -// IsUDPAddrResolvable is the validation function for validating if the field's value is a resolvable udp address. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsUDPAddrResolvable(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - if !isIP4Addr(v, topStruct, currentStructOrField, field, fieldType, fieldKind, param) && - !isIP6Addr(v, topStruct, currentStructOrField, field, fieldType, fieldKind, param) { - return false - } - - _, err := net.ResolveUDPAddr("udp", field.String()) - return err == nil -} - -// IsIP4AddrResolvable is the validation function for validating if the field's value is a resolvable ip4 address. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsIP4AddrResolvable(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - if !IsIPv4(v, topStruct, currentStructOrField, field, fieldType, fieldKind, param) { - return false - } - - _, err := net.ResolveIPAddr("ip4", field.String()) - return err == nil -} - -// IsIP6AddrResolvable is the validation function for validating if the field's value is a resolvable ip6 address. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsIP6AddrResolvable(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - if !IsIPv6(v, topStruct, currentStructOrField, field, fieldType, fieldKind, param) { - return false - } - - _, err := net.ResolveIPAddr("ip6", field.String()) - return err == nil -} - -// IsIPAddrResolvable is the validation function for validating if the field's value is a resolvable ip address. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsIPAddrResolvable(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - if !IsIP(v, topStruct, currentStructOrField, field, fieldType, fieldKind, param) { - return false - } - - _, err := net.ResolveIPAddr("ip", field.String()) - return err == nil -} - -// IsUnixAddrResolvable is the validation function for validating if the field's value is a resolvable unix address. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func IsUnixAddrResolvable(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - _, err := net.ResolveUnixAddr("unix", field.String()) - return err == nil -} - -func isIP4Addr(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - val := field.String() - - if idx := strings.LastIndex(val, ":"); idx != -1 { - val = val[0:idx] - } - - if !IsIPv4(v, topStruct, currentStructOrField, reflect.ValueOf(val), fieldType, fieldKind, param) { - return false - } - - return true -} - -func isIP6Addr(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - val := field.String() - - if idx := strings.LastIndex(val, ":"); idx != -1 { - if idx != 0 && val[idx-1:idx] == "]" { - val = val[1 : idx-1] - } - } - - if !IsIPv6(v, topStruct, currentStructOrField, reflect.ValueOf(val), fieldType, fieldKind, param) { - return false - } - - return true -} diff --git a/vendor/gopkg.in/go-playground/validator.v8/cache.go b/vendor/gopkg.in/go-playground/validator.v8/cache.go deleted file mode 100644 index 76670c1dd..000000000 --- a/vendor/gopkg.in/go-playground/validator.v8/cache.go +++ /dev/null @@ -1,263 +0,0 @@ -package validator - -import ( - "fmt" - "reflect" - "strings" - "sync" - "sync/atomic" -) - -type tagType uint8 - -const ( - typeDefault tagType = iota - typeOmitEmpty - typeNoStructLevel - typeStructOnly - typeDive - typeOr - typeExists -) - -type structCache struct { - lock sync.Mutex - m atomic.Value // map[reflect.Type]*cStruct -} - -func (sc *structCache) Get(key reflect.Type) (c *cStruct, found bool) { - c, found = sc.m.Load().(map[reflect.Type]*cStruct)[key] - return -} - -func (sc *structCache) Set(key reflect.Type, value *cStruct) { - - m := sc.m.Load().(map[reflect.Type]*cStruct) - - nm := make(map[reflect.Type]*cStruct, len(m)+1) - for k, v := range m { - nm[k] = v - } - nm[key] = value - sc.m.Store(nm) -} - -type tagCache struct { - lock sync.Mutex - m atomic.Value // map[string]*cTag -} - -func (tc *tagCache) Get(key string) (c *cTag, found bool) { - c, found = tc.m.Load().(map[string]*cTag)[key] - return -} - -func (tc *tagCache) Set(key string, value *cTag) { - - m := tc.m.Load().(map[string]*cTag) - - nm := make(map[string]*cTag, len(m)+1) - for k, v := range m { - nm[k] = v - } - nm[key] = value - tc.m.Store(nm) -} - -type cStruct struct { - Name string - fields map[int]*cField - fn StructLevelFunc -} - -type cField struct { - Idx int - Name string - AltName string - cTags *cTag -} - -type cTag struct { - tag string - aliasTag string - actualAliasTag string - param string - hasAlias bool - typeof tagType - hasTag bool - fn Func - next *cTag -} - -func (v *Validate) extractStructCache(current reflect.Value, sName string) *cStruct { - - v.structCache.lock.Lock() - defer v.structCache.lock.Unlock() // leave as defer! because if inner panics, it will never get unlocked otherwise! - - typ := current.Type() - - // could have been multiple trying to access, but once first is done this ensures struct - // isn't parsed again. - cs, ok := v.structCache.Get(typ) - if ok { - return cs - } - - cs = &cStruct{Name: sName, fields: make(map[int]*cField), fn: v.structLevelFuncs[typ]} - - numFields := current.NumField() - - var ctag *cTag - var fld reflect.StructField - var tag string - var customName string - - for i := 0; i < numFields; i++ { - - fld = typ.Field(i) - - if !fld.Anonymous && fld.PkgPath != blank { - continue - } - - tag = fld.Tag.Get(v.tagName) - - if tag == skipValidationTag { - continue - } - - customName = fld.Name - - if v.fieldNameTag != blank { - - name := strings.SplitN(fld.Tag.Get(v.fieldNameTag), ",", 2)[0] - - // dash check is for json "-" (aka skipValidationTag) means don't output in json - if name != "" && name != skipValidationTag { - customName = name - } - } - - // NOTE: cannot use shared tag cache, because tags may be equal, but things like alias may be different - // and so only struct level caching can be used instead of combined with Field tag caching - - if len(tag) > 0 { - ctag, _ = v.parseFieldTagsRecursive(tag, fld.Name, blank, false) - } else { - // even if field doesn't have validations need cTag for traversing to potential inner/nested - // elements of the field. - ctag = new(cTag) - } - - cs.fields[i] = &cField{Idx: i, Name: fld.Name, AltName: customName, cTags: ctag} - } - - v.structCache.Set(typ, cs) - - return cs -} - -func (v *Validate) parseFieldTagsRecursive(tag string, fieldName string, alias string, hasAlias bool) (firstCtag *cTag, current *cTag) { - - var t string - var ok bool - noAlias := len(alias) == 0 - tags := strings.Split(tag, tagSeparator) - - for i := 0; i < len(tags); i++ { - - t = tags[i] - - if noAlias { - alias = t - } - - if v.hasAliasValidators { - // check map for alias and process new tags, otherwise process as usual - if tagsVal, found := v.aliasValidators[t]; found { - - if i == 0 { - firstCtag, current = v.parseFieldTagsRecursive(tagsVal, fieldName, t, true) - } else { - next, curr := v.parseFieldTagsRecursive(tagsVal, fieldName, t, true) - current.next, current = next, curr - - } - - continue - } - } - - if i == 0 { - current = &cTag{aliasTag: alias, hasAlias: hasAlias, hasTag: true} - firstCtag = current - } else { - current.next = &cTag{aliasTag: alias, hasAlias: hasAlias, hasTag: true} - current = current.next - } - - switch t { - - case diveTag: - current.typeof = typeDive - continue - - case omitempty: - current.typeof = typeOmitEmpty - continue - - case structOnlyTag: - current.typeof = typeStructOnly - continue - - case noStructLevelTag: - current.typeof = typeNoStructLevel - continue - - case existsTag: - current.typeof = typeExists - continue - - default: - - // if a pipe character is needed within the param you must use the utf8Pipe representation "0x7C" - orVals := strings.Split(t, orSeparator) - - for j := 0; j < len(orVals); j++ { - - vals := strings.SplitN(orVals[j], tagKeySeparator, 2) - - if noAlias { - alias = vals[0] - current.aliasTag = alias - } else { - current.actualAliasTag = t - } - - if j > 0 { - current.next = &cTag{aliasTag: alias, actualAliasTag: current.actualAliasTag, hasAlias: hasAlias, hasTag: true} - current = current.next - } - - current.tag = vals[0] - if len(current.tag) == 0 { - panic(strings.TrimSpace(fmt.Sprintf(invalidValidation, fieldName))) - } - - if current.fn, ok = v.validationFuncs[current.tag]; !ok { - panic(strings.TrimSpace(fmt.Sprintf(undefinedValidation, fieldName))) - } - - if len(orVals) > 1 { - current.typeof = typeOr - } - - if len(vals) > 1 { - current.param = strings.Replace(strings.Replace(vals[1], utf8HexComma, ",", -1), utf8Pipe, "|", -1) - } - } - } - } - - return -} diff --git a/vendor/gopkg.in/go-playground/validator.v8/doc.go b/vendor/gopkg.in/go-playground/validator.v8/doc.go deleted file mode 100644 index fdede2c4c..000000000 --- a/vendor/gopkg.in/go-playground/validator.v8/doc.go +++ /dev/null @@ -1,852 +0,0 @@ -/* -Package validator implements value validations for structs and individual fields -based on tags. - -It can also handle Cross-Field and Cross-Struct validation for nested structs -and has the ability to dive into arrays and maps of any type. - -Why not a better error message? -Because this library intends for you to handle your own error messages. - -Why should I handle my own errors? -Many reasons. We built an internationalized application and needed to know the -field, and what validation failed so we could provide a localized error. - - if fieldErr.Field == "Name" { - switch fieldErr.ErrorTag - case "required": - return "Translated string based on field + error" - default: - return "Translated string based on field" - } - - -Validation Functions Return Type error - -Doing things this way is actually the way the standard library does, see the -file.Open method here: - - https://golang.org/pkg/os/#Open. - -The authors return type "error" to avoid the issue discussed in the following, -where err is always != nil: - - http://stackoverflow.com/a/29138676/3158232 - https://github.com/go-playground/validator/issues/134 - -Validator only returns nil or ValidationErrors as type error; so, in your code -all you need to do is check if the error returned is not nil, and if it's not -type cast it to type ValidationErrors like so err.(validator.ValidationErrors). - -Custom Functions - -Custom functions can be added. Example: - - // Structure - func customFunc(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { - - if whatever { - return false - } - - return true - } - - validate.RegisterValidation("custom tag name", customFunc) - // NOTES: using the same tag name as an existing function - // will overwrite the existing one - -Cross-Field Validation - -Cross-Field Validation can be done via the following tags: - - eqfield - - nefield - - gtfield - - gtefield - - ltfield - - ltefield - - eqcsfield - - necsfield - - gtcsfield - - ftecsfield - - ltcsfield - - ltecsfield - -If, however, some custom cross-field validation is required, it can be done -using a custom validation. - -Why not just have cross-fields validation tags (i.e. only eqcsfield and not -eqfield)? - -The reason is efficiency. If you want to check a field within the same struct -"eqfield" only has to find the field on the same struct (1 level). But, if we -used "eqcsfield" it could be multiple levels down. Example: - - type Inner struct { - StartDate time.Time - } - - type Outer struct { - InnerStructField *Inner - CreatedAt time.Time `validate:"ltecsfield=InnerStructField.StartDate"` - } - - now := time.Now() - - inner := &Inner{ - StartDate: now, - } - - outer := &Outer{ - InnerStructField: inner, - CreatedAt: now, - } - - errs := validate.Struct(outer) - - // NOTE: when calling validate.Struct(val) topStruct will be the top level struct passed - // into the function - // when calling validate.FieldWithValue(val, field, tag) val will be - // whatever you pass, struct, field... - // when calling validate.Field(field, tag) val will be nil - -Multiple Validators - -Multiple validators on a field will process in the order defined. Example: - - type Test struct { - Field `validate:"max=10,min=1"` - } - - // max will be checked then min - -Bad Validator definitions are not handled by the library. Example: - - type Test struct { - Field `validate:"min=10,max=0"` - } - - // this definition of min max will never succeed - -Using Validator Tags - -Baked In Cross-Field validation only compares fields on the same struct. -If Cross-Field + Cross-Struct validation is needed you should implement your -own custom validator. - -Comma (",") is the default separator of validation tags. If you wish to -have a comma included within the parameter (i.e. excludesall=,) you will need to -use the UTF-8 hex representation 0x2C, which is replaced in the code as a comma, -so the above will become excludesall=0x2C. - - type Test struct { - Field `validate:"excludesall=,"` // BAD! Do not include a comma. - Field `validate:"excludesall=0x2C"` // GOOD! Use the UTF-8 hex representation. - } - -Pipe ("|") is the default separator of validation tags. If you wish to -have a pipe included within the parameter i.e. excludesall=| you will need to -use the UTF-8 hex representation 0x7C, which is replaced in the code as a pipe, -so the above will become excludesall=0x7C - - type Test struct { - Field `validate:"excludesall=|"` // BAD! Do not include a a pipe! - Field `validate:"excludesall=0x7C"` // GOOD! Use the UTF-8 hex representation. - } - - -Baked In Validators and Tags - -Here is a list of the current built in validators: - - -Skip Field - -Tells the validation to skip this struct field; this is particularly -handy in ignoring embedded structs from being validated. (Usage: -) - Usage: - - - -Or Operator - -This is the 'or' operator allowing multiple validators to be used and -accepted. (Usage: rbg|rgba) <-- this would allow either rgb or rgba -colors to be accepted. This can also be combined with 'and' for example -( Usage: omitempty,rgb|rgba) - - Usage: | - -StructOnly - -When a field that is a nested struct is encountered, and contains this flag -any validation on the nested struct will be run, but none of the nested -struct fields will be validated. This is usefull if inside of you program -you know the struct will be valid, but need to verify it has been assigned. -NOTE: only "required" and "omitempty" can be used on a struct itself. - - Usage: structonly - -NoStructLevel - -Same as structonly tag except that any struct level validations will not run. - - Usage: nostructlevel - -Exists - -Is a special tag without a validation function attached. It is used when a field -is a Pointer, Interface or Invalid and you wish to validate that it exists. -Example: want to ensure a bool exists if you define the bool as a pointer and -use exists it will ensure there is a value; couldn't use required as it would -fail when the bool was false. exists will fail is the value is a Pointer, Interface -or Invalid and is nil. - - Usage: exists - -Omit Empty - -Allows conditional validation, for example if a field is not set with -a value (Determined by the "required" validator) then other validation -such as min or max won't run, but if a value is set validation will run. - - Usage: omitempty - -Dive - -This tells the validator to dive into a slice, array or map and validate that -level of the slice, array or map with the validation tags that follow. -Multidimensional nesting is also supported, each level you wish to dive will -require another dive tag. - - Usage: dive - -Example #1 - - [][]string with validation tag "gt=0,dive,len=1,dive,required" - // gt=0 will be applied to [] - // len=1 will be applied to []string - // required will be applied to string - -Example #2 - - [][]string with validation tag "gt=0,dive,dive,required" - // gt=0 will be applied to [] - // []string will be spared validation - // required will be applied to string - -Required - -This validates that the value is not the data types default zero value. -For numbers ensures value is not zero. For strings ensures value is -not "". For slices, maps, pointers, interfaces, channels and functions -ensures the value is not nil. - - Usage: required - -Length - -For numbers, max will ensure that the value is -equal to the parameter given. For strings, it checks that -the string length is exactly that number of characters. For slices, -arrays, and maps, validates the number of items. - - Usage: len=10 - -Maximum - -For numbers, max will ensure that the value is -less than or equal to the parameter given. For strings, it checks -that the string length is at most that number of characters. For -slices, arrays, and maps, validates the number of items. - - Usage: max=10 - -Mininum - -For numbers, min will ensure that the value is -greater or equal to the parameter given. For strings, it checks that -the string length is at least that number of characters. For slices, -arrays, and maps, validates the number of items. - - Usage: min=10 - -Equals - -For strings & numbers, eq will ensure that the value is -equal to the parameter given. For slices, arrays, and maps, -validates the number of items. - - Usage: eq=10 - -Not Equal - -For strings & numbers, ne will ensure that the value is not -equal to the parameter given. For slices, arrays, and maps, -validates the number of items. - - Usage: ne=10 - -Greater Than - -For numbers, this will ensure that the value is greater than the -parameter given. For strings, it checks that the string length -is greater than that number of characters. For slices, arrays -and maps it validates the number of items. - -Example #1 - - Usage: gt=10 - -Example #2 (time.Time) - -For time.Time ensures the time value is greater than time.Now.UTC(). - - Usage: gt - -Greater Than or Equal - -Same as 'min' above. Kept both to make terminology with 'len' easier. - - -Example #1 - - Usage: gte=10 - -Example #2 (time.Time) - -For time.Time ensures the time value is greater than or equal to time.Now.UTC(). - - Usage: gte - -Less Than - -For numbers, this will ensure that the value is less than the parameter given. -For strings, it checks that the string length is less than that number of -characters. For slices, arrays, and maps it validates the number of items. - -Example #1 - - Usage: lt=10 - -Example #2 (time.Time) -For time.Time ensures the time value is less than time.Now.UTC(). - - Usage: lt - -Less Than or Equal - -Same as 'max' above. Kept both to make terminology with 'len' easier. - -Example #1 - - Usage: lte=10 - -Example #2 (time.Time) - -For time.Time ensures the time value is less than or equal to time.Now.UTC(). - - Usage: lte - -Field Equals Another Field - -This will validate the field value against another fields value either within -a struct or passed in field. - -Example #1: - - // Validation on Password field using: - Usage: eqfield=ConfirmPassword - -Example #2: - - // Validating by field: - validate.FieldWithValue(password, confirmpassword, "eqfield") - -Field Equals Another Field (relative) - -This does the same as eqfield except that it validates the field provided relative -to the top level struct. - - Usage: eqcsfield=InnerStructField.Field) - -Field Does Not Equal Another Field - -This will validate the field value against another fields value either within -a struct or passed in field. - -Examples: - - // Confirm two colors are not the same: - // - // Validation on Color field: - Usage: nefield=Color2 - - // Validating by field: - validate.FieldWithValue(color1, color2, "nefield") - -Field Does Not Equal Another Field (relative) - -This does the same as nefield except that it validates the field provided -relative to the top level struct. - - Usage: necsfield=InnerStructField.Field - -Field Greater Than Another Field - -Only valid for Numbers and time.Time types, this will validate the field value -against another fields value either within a struct or passed in field. -usage examples are for validation of a Start and End date: - -Example #1: - - // Validation on End field using: - validate.Struct Usage(gtfield=Start) - -Example #2: - - // Validating by field: - validate.FieldWithValue(start, end, "gtfield") - - -Field Greater Than Another Relative Field - -This does the same as gtfield except that it validates the field provided -relative to the top level struct. - - Usage: gtcsfield=InnerStructField.Field - -Field Greater Than or Equal To Another Field - -Only valid for Numbers and time.Time types, this will validate the field value -against another fields value either within a struct or passed in field. -usage examples are for validation of a Start and End date: - -Example #1: - - // Validation on End field using: - validate.Struct Usage(gtefield=Start) - -Example #2: - - // Validating by field: - validate.FieldWithValue(start, end, "gtefield") - -Field Greater Than or Equal To Another Relative Field - -This does the same as gtefield except that it validates the field provided relative -to the top level struct. - - Usage: gtecsfield=InnerStructField.Field - -Less Than Another Field - -Only valid for Numbers and time.Time types, this will validate the field value -against another fields value either within a struct or passed in field. -usage examples are for validation of a Start and End date: - -Example #1: - - // Validation on End field using: - validate.Struct Usage(ltfield=Start) - -Example #2: - - // Validating by field: - validate.FieldWithValue(start, end, "ltfield") - -Less Than Another Relative Field - -This does the same as ltfield except that it validates the field provided relative -to the top level struct. - - Usage: ltcsfield=InnerStructField.Field - -Less Than or Equal To Another Field - -Only valid for Numbers and time.Time types, this will validate the field value -against another fields value either within a struct or passed in field. -usage examples are for validation of a Start and End date: - -Example #1: - - // Validation on End field using: - validate.Struct Usage(ltefield=Start) - -Example #2: - - // Validating by field: - validate.FieldWithValue(start, end, "ltefield") - -Less Than or Equal To Another Relative Field - -This does the same as ltefield except that it validates the field provided relative -to the top level struct. - - Usage: ltecsfield=InnerStructField.Field - -Alpha Only - -This validates that a string value contains alpha characters only - - Usage: alpha - -Alphanumeric - -This validates that a string value contains alphanumeric characters only - - Usage: alphanum - -Numeric - -This validates that a string value contains a basic numeric value. -basic excludes exponents etc... - - Usage: numeric - -Hexadecimal String - -This validates that a string value contains a valid hexadecimal. - - Usage: hexadecimal - -Hexcolor String - -This validates that a string value contains a valid hex color including -hashtag (#) - - Usage: hexcolor - -RGB String - -This validates that a string value contains a valid rgb color - - Usage: rgb - -RGBA String - -This validates that a string value contains a valid rgba color - - Usage: rgba - -HSL String - -This validates that a string value contains a valid hsl color - - Usage: hsl - -HSLA String - -This validates that a string value contains a valid hsla color - - Usage: hsla - -E-mail String - -This validates that a string value contains a valid email -This may not conform to all possibilities of any rfc standard, but neither -does any email provider accept all posibilities. - - Usage: email - -URL String - -This validates that a string value contains a valid url -This will accept any url the golang request uri accepts but must contain -a schema for example http:// or rtmp:// - - Usage: url - -URI String - -This validates that a string value contains a valid uri -This will accept any uri the golang request uri accepts - - Usage: uri - -Base64 String - -This validates that a string value contains a valid base64 value. -Although an empty string is valid base64 this will report an empty string -as an error, if you wish to accept an empty string as valid you can use -this with the omitempty tag. - - Usage: base64 - -Contains - -This validates that a string value contains the substring value. - - Usage: contains=@ - -Contains Any - -This validates that a string value contains any Unicode code points -in the substring value. - - Usage: containsany=!@#? - -Contains Rune - -This validates that a string value contains the supplied rune value. - - Usage: containsrune=@ - -Excludes - -This validates that a string value does not contain the substring value. - - Usage: excludes=@ - -Excludes All - -This validates that a string value does not contain any Unicode code -points in the substring value. - - Usage: excludesall=!@#? - -Excludes Rune - -This validates that a string value does not contain the supplied rune value. - - Usage: excludesrune=@ - -International Standard Book Number - -This validates that a string value contains a valid isbn10 or isbn13 value. - - Usage: isbn - -International Standard Book Number 10 - -This validates that a string value contains a valid isbn10 value. - - Usage: isbn10 - -International Standard Book Number 13 - -This validates that a string value contains a valid isbn13 value. - - Usage: isbn13 - - -Universally Unique Identifier UUID - -This validates that a string value contains a valid UUID. - - Usage: uuid - -Universally Unique Identifier UUID v3 - -This validates that a string value contains a valid version 3 UUID. - - Usage: uuid3 - -Universally Unique Identifier UUID v4 - -This validates that a string value contains a valid version 4 UUID. - - Usage: uuid4 - -Universally Unique Identifier UUID v5 - -This validates that a string value contains a valid version 5 UUID. - - Usage: uuid5 - -ASCII - -This validates that a string value contains only ASCII characters. -NOTE: if the string is blank, this validates as true. - - Usage: ascii - -Printable ASCII - -This validates that a string value contains only printable ASCII characters. -NOTE: if the string is blank, this validates as true. - - Usage: asciiprint - -Multi-Byte Characters - -This validates that a string value contains one or more multibyte characters. -NOTE: if the string is blank, this validates as true. - - Usage: multibyte - -Data URL - -This validates that a string value contains a valid DataURI. -NOTE: this will also validate that the data portion is valid base64 - - Usage: datauri - -Latitude - -This validates that a string value contains a valid latitude. - - Usage: latitude - -Longitude - -This validates that a string value contains a valid longitude. - - Usage: longitude - -Social Security Number SSN - -This validates that a string value contains a valid U.S. Social Security Number. - - Usage: ssn - -Internet Protocol Address IP - -This validates that a string value contains a valid IP Adress. - - Usage: ip - -Internet Protocol Address IPv4 - -This validates that a string value contains a valid v4 IP Adress. - - Usage: ipv4 - -Internet Protocol Address IPv6 - -This validates that a string value contains a valid v6 IP Adress. - - Usage: ipv6 - -Classless Inter-Domain Routing CIDR - -This validates that a string value contains a valid CIDR Adress. - - Usage: cidr - -Classless Inter-Domain Routing CIDRv4 - -This validates that a string value contains a valid v4 CIDR Adress. - - Usage: cidrv4 - -Classless Inter-Domain Routing CIDRv6 - -This validates that a string value contains a valid v6 CIDR Adress. - - Usage: cidrv6 - -Transmission Control Protocol Address TCP - -This validates that a string value contains a valid resolvable TCP Adress. - - Usage: tcp_addr - -Transmission Control Protocol Address TCPv4 - -This validates that a string value contains a valid resolvable v4 TCP Adress. - - Usage: tcp4_addr - -Transmission Control Protocol Address TCPv6 - -This validates that a string value contains a valid resolvable v6 TCP Adress. - - Usage: tcp6_addr - -User Datagram Protocol Address UDP - -This validates that a string value contains a valid resolvable UDP Adress. - - Usage: udp_addr - -User Datagram Protocol Address UDPv4 - -This validates that a string value contains a valid resolvable v4 UDP Adress. - - Usage: udp4_addr - -User Datagram Protocol Address UDPv6 - -This validates that a string value contains a valid resolvable v6 UDP Adress. - - Usage: udp6_addr - -Internet Protocol Address IP - -This validates that a string value contains a valid resolvable IP Adress. - - Usage: ip_addr - -Internet Protocol Address IPv4 - -This validates that a string value contains a valid resolvable v4 IP Adress. - - Usage: ip4_addr - -Internet Protocol Address IPv6 - -This validates that a string value contains a valid resolvable v6 IP Adress. - - Usage: ip6_addr - -Unix domain socket end point Address - -This validates that a string value contains a valid Unix Adress. - - Usage: unix_addr - -Media Access Control Address MAC - -This validates that a string value contains a valid MAC Adress. - - Usage: mac - -Note: See Go's ParseMAC for accepted formats and types: - - http://golang.org/src/net/mac.go?s=866:918#L29 - -Alias Validators and Tags - -NOTE: When returning an error, the tag returned in "FieldError" will be -the alias tag unless the dive tag is part of the alias. Everything after the -dive tag is not reported as the alias tag. Also, the "ActualTag" in the before -case will be the actual tag within the alias that failed. - -Here is a list of the current built in alias tags: - - "iscolor" - alias is "hexcolor|rgb|rgba|hsl|hsla" (Usage: iscolor) - -Validator notes: - - regex - a regex validator won't be added because commas and = signs can be part - of a regex which conflict with the validation definitions. Although - workarounds can be made, they take away from using pure regex's. - Furthermore it's quick and dirty but the regex's become harder to - maintain and are not reusable, so it's as much a programming philosiphy - as anything. - - In place of this new validator functions should be created; a regex can - be used within the validator function and even be precompiled for better - efficiency within regexes.go. - - And the best reason, you can submit a pull request and we can keep on - adding to the validation library of this package! - -Panics - -This package panics when bad input is provided, this is by design, bad code like -that should not make it to production. - - type Test struct { - TestField string `validate:"nonexistantfunction=1"` - } - - t := &Test{ - TestField: "Test" - } - - validate.Struct(t) // this will panic -*/ -package validator diff --git a/vendor/gopkg.in/go-playground/validator.v8/regexes.go b/vendor/gopkg.in/go-playground/validator.v8/regexes.go deleted file mode 100644 index 83ae1982a..000000000 --- a/vendor/gopkg.in/go-playground/validator.v8/regexes.go +++ /dev/null @@ -1,59 +0,0 @@ -package validator - -import "regexp" - -const ( - alphaRegexString = "^[a-zA-Z]+$" - alphaNumericRegexString = "^[a-zA-Z0-9]+$" - numericRegexString = "^[-+]?[0-9]+(?:\\.[0-9]+)?$" - numberRegexString = "^[0-9]+$" - hexadecimalRegexString = "^[0-9a-fA-F]+$" - hexcolorRegexString = "^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$" - rgbRegexString = "^rgb\\(\\s*(?:(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])|(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%)\\s*\\)$" - rgbaRegexString = "^rgba\\(\\s*(?:(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])|(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%)\\s*,\\s*(?:(?:0.[1-9]*)|[01])\\s*\\)$" - hslRegexString = "^hsl\\(\\s*(?:0|[1-9]\\d?|[12]\\d\\d|3[0-5]\\d|360)\\s*,\\s*(?:(?:0|[1-9]\\d?|100)%)\\s*,\\s*(?:(?:0|[1-9]\\d?|100)%)\\s*\\)$" - hslaRegexString = "^hsla\\(\\s*(?:0|[1-9]\\d?|[12]\\d\\d|3[0-5]\\d|360)\\s*,\\s*(?:(?:0|[1-9]\\d?|100)%)\\s*,\\s*(?:(?:0|[1-9]\\d?|100)%)\\s*,\\s*(?:(?:0.[1-9]*)|[01])\\s*\\)$" - emailRegexString = "^(?:(?:(?:(?:[a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(?:\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|(?:(?:\\x22)(?:(?:(?:(?:\\x20|\\x09)*(?:\\x0d\\x0a))?(?:\\x20|\\x09)+)?(?:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:\\(?:[\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(?:(?:(?:\\x20|\\x09)*(?:\\x0d\\x0a))?(\\x20|\\x09)+)?(?:\\x22)))@(?:(?:(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])(?:[a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(?:(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])(?:[a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$" - base64RegexString = "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$" - iSBN10RegexString = "^(?:[0-9]{9}X|[0-9]{10})$" - iSBN13RegexString = "^(?:(?:97(?:8|9))[0-9]{10})$" - uUID3RegexString = "^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$" - uUID4RegexString = "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" - uUID5RegexString = "^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" - uUIDRegexString = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" - aSCIIRegexString = "^[\x00-\x7F]*$" - printableASCIIRegexString = "^[\x20-\x7E]*$" - multibyteRegexString = "[^\x00-\x7F]" - dataURIRegexString = "^data:.+\\/(.+);base64$" - latitudeRegexString = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$" - longitudeRegexString = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$" - sSNRegexString = `^\d{3}[- ]?\d{2}[- ]?\d{4}$` -) - -var ( - alphaRegex = regexp.MustCompile(alphaRegexString) - alphaNumericRegex = regexp.MustCompile(alphaNumericRegexString) - numericRegex = regexp.MustCompile(numericRegexString) - numberRegex = regexp.MustCompile(numberRegexString) - hexadecimalRegex = regexp.MustCompile(hexadecimalRegexString) - hexcolorRegex = regexp.MustCompile(hexcolorRegexString) - rgbRegex = regexp.MustCompile(rgbRegexString) - rgbaRegex = regexp.MustCompile(rgbaRegexString) - hslRegex = regexp.MustCompile(hslRegexString) - hslaRegex = regexp.MustCompile(hslaRegexString) - emailRegex = regexp.MustCompile(emailRegexString) - base64Regex = regexp.MustCompile(base64RegexString) - iSBN10Regex = regexp.MustCompile(iSBN10RegexString) - iSBN13Regex = regexp.MustCompile(iSBN13RegexString) - uUID3Regex = regexp.MustCompile(uUID3RegexString) - uUID4Regex = regexp.MustCompile(uUID4RegexString) - uUID5Regex = regexp.MustCompile(uUID5RegexString) - uUIDRegex = regexp.MustCompile(uUIDRegexString) - aSCIIRegex = regexp.MustCompile(aSCIIRegexString) - printableASCIIRegex = regexp.MustCompile(printableASCIIRegexString) - multibyteRegex = regexp.MustCompile(multibyteRegexString) - dataURIRegex = regexp.MustCompile(dataURIRegexString) - latitudeRegex = regexp.MustCompile(latitudeRegexString) - longitudeRegex = regexp.MustCompile(longitudeRegexString) - sSNRegex = regexp.MustCompile(sSNRegexString) -) diff --git a/vendor/gopkg.in/go-playground/validator.v8/util.go b/vendor/gopkg.in/go-playground/validator.v8/util.go deleted file mode 100644 index e81157909..000000000 --- a/vendor/gopkg.in/go-playground/validator.v8/util.go +++ /dev/null @@ -1,252 +0,0 @@ -package validator - -import ( - "reflect" - "strconv" - "strings" -) - -const ( - blank = "" - namespaceSeparator = "." - leftBracket = "[" - rightBracket = "]" - restrictedTagChars = ".[],|=+()`~!@#$%^&*\\\"/?<>{}" - restrictedAliasErr = "Alias '%s' either contains restricted characters or is the same as a restricted tag needed for normal operation" - restrictedTagErr = "Tag '%s' either contains restricted characters or is the same as a restricted tag needed for normal operation" -) - -var ( - restrictedTags = map[string]struct{}{ - diveTag: {}, - existsTag: {}, - structOnlyTag: {}, - omitempty: {}, - skipValidationTag: {}, - utf8HexComma: {}, - utf8Pipe: {}, - noStructLevelTag: {}, - } -) - -// ExtractType gets the actual underlying type of field value. -// It will dive into pointers, customTypes and return you the -// underlying value and it's kind. -// it is exposed for use within you Custom Functions -func (v *Validate) ExtractType(current reflect.Value) (reflect.Value, reflect.Kind) { - - val, k, _ := v.extractTypeInternal(current, false) - return val, k -} - -// only exists to not break backward compatibility, needed to return the third param for a bug fix internally -func (v *Validate) extractTypeInternal(current reflect.Value, nullable bool) (reflect.Value, reflect.Kind, bool) { - - switch current.Kind() { - case reflect.Ptr: - - nullable = true - - if current.IsNil() { - return current, reflect.Ptr, nullable - } - - return v.extractTypeInternal(current.Elem(), nullable) - - case reflect.Interface: - - nullable = true - - if current.IsNil() { - return current, reflect.Interface, nullable - } - - return v.extractTypeInternal(current.Elem(), nullable) - - case reflect.Invalid: - return current, reflect.Invalid, nullable - - default: - - if v.hasCustomFuncs { - - if fn, ok := v.customTypeFuncs[current.Type()]; ok { - return v.extractTypeInternal(reflect.ValueOf(fn(current)), nullable) - } - } - - return current, current.Kind(), nullable - } -} - -// GetStructFieldOK traverses a struct to retrieve a specific field denoted by the provided namespace and -// returns the field, field kind and whether is was successful in retrieving the field at all. -// NOTE: when not successful ok will be false, this can happen when a nested struct is nil and so the field -// could not be retrieved because it didn't exist. -func (v *Validate) GetStructFieldOK(current reflect.Value, namespace string) (reflect.Value, reflect.Kind, bool) { - - current, kind := v.ExtractType(current) - - if kind == reflect.Invalid { - return current, kind, false - } - - if namespace == blank { - return current, kind, true - } - - switch kind { - - case reflect.Ptr, reflect.Interface: - - return current, kind, false - - case reflect.Struct: - - typ := current.Type() - fld := namespace - ns := namespace - - if typ != timeType && typ != timePtrType { - - idx := strings.Index(namespace, namespaceSeparator) - - if idx != -1 { - fld = namespace[:idx] - ns = namespace[idx+1:] - } else { - ns = blank - } - - bracketIdx := strings.Index(fld, leftBracket) - if bracketIdx != -1 { - fld = fld[:bracketIdx] - - ns = namespace[bracketIdx:] - } - - current = current.FieldByName(fld) - - return v.GetStructFieldOK(current, ns) - } - - case reflect.Array, reflect.Slice: - idx := strings.Index(namespace, leftBracket) - idx2 := strings.Index(namespace, rightBracket) - - arrIdx, _ := strconv.Atoi(namespace[idx+1 : idx2]) - - if arrIdx >= current.Len() { - return current, kind, false - } - - startIdx := idx2 + 1 - - if startIdx < len(namespace) { - if namespace[startIdx:startIdx+1] == namespaceSeparator { - startIdx++ - } - } - - return v.GetStructFieldOK(current.Index(arrIdx), namespace[startIdx:]) - - case reflect.Map: - idx := strings.Index(namespace, leftBracket) + 1 - idx2 := strings.Index(namespace, rightBracket) - - endIdx := idx2 - - if endIdx+1 < len(namespace) { - if namespace[endIdx+1:endIdx+2] == namespaceSeparator { - endIdx++ - } - } - - key := namespace[idx:idx2] - - switch current.Type().Key().Kind() { - case reflect.Int: - i, _ := strconv.Atoi(key) - return v.GetStructFieldOK(current.MapIndex(reflect.ValueOf(i)), namespace[endIdx+1:]) - case reflect.Int8: - i, _ := strconv.ParseInt(key, 10, 8) - return v.GetStructFieldOK(current.MapIndex(reflect.ValueOf(int8(i))), namespace[endIdx+1:]) - case reflect.Int16: - i, _ := strconv.ParseInt(key, 10, 16) - return v.GetStructFieldOK(current.MapIndex(reflect.ValueOf(int16(i))), namespace[endIdx+1:]) - case reflect.Int32: - i, _ := strconv.ParseInt(key, 10, 32) - return v.GetStructFieldOK(current.MapIndex(reflect.ValueOf(int32(i))), namespace[endIdx+1:]) - case reflect.Int64: - i, _ := strconv.ParseInt(key, 10, 64) - return v.GetStructFieldOK(current.MapIndex(reflect.ValueOf(i)), namespace[endIdx+1:]) - case reflect.Uint: - i, _ := strconv.ParseUint(key, 10, 0) - return v.GetStructFieldOK(current.MapIndex(reflect.ValueOf(uint(i))), namespace[endIdx+1:]) - case reflect.Uint8: - i, _ := strconv.ParseUint(key, 10, 8) - return v.GetStructFieldOK(current.MapIndex(reflect.ValueOf(uint8(i))), namespace[endIdx+1:]) - case reflect.Uint16: - i, _ := strconv.ParseUint(key, 10, 16) - return v.GetStructFieldOK(current.MapIndex(reflect.ValueOf(uint16(i))), namespace[endIdx+1:]) - case reflect.Uint32: - i, _ := strconv.ParseUint(key, 10, 32) - return v.GetStructFieldOK(current.MapIndex(reflect.ValueOf(uint32(i))), namespace[endIdx+1:]) - case reflect.Uint64: - i, _ := strconv.ParseUint(key, 10, 64) - return v.GetStructFieldOK(current.MapIndex(reflect.ValueOf(i)), namespace[endIdx+1:]) - case reflect.Float32: - f, _ := strconv.ParseFloat(key, 32) - return v.GetStructFieldOK(current.MapIndex(reflect.ValueOf(float32(f))), namespace[endIdx+1:]) - case reflect.Float64: - f, _ := strconv.ParseFloat(key, 64) - return v.GetStructFieldOK(current.MapIndex(reflect.ValueOf(f)), namespace[endIdx+1:]) - case reflect.Bool: - b, _ := strconv.ParseBool(key) - return v.GetStructFieldOK(current.MapIndex(reflect.ValueOf(b)), namespace[endIdx+1:]) - - // reflect.Type = string - default: - return v.GetStructFieldOK(current.MapIndex(reflect.ValueOf(key)), namespace[endIdx+1:]) - } - } - - // if got here there was more namespace, cannot go any deeper - panic("Invalid field namespace") -} - -// asInt returns the parameter as a int64 -// or panics if it can't convert -func asInt(param string) int64 { - - i, err := strconv.ParseInt(param, 0, 64) - panicIf(err) - - return i -} - -// asUint returns the parameter as a uint64 -// or panics if it can't convert -func asUint(param string) uint64 { - - i, err := strconv.ParseUint(param, 0, 64) - panicIf(err) - - return i -} - -// asFloat returns the parameter as a float64 -// or panics if it can't convert -func asFloat(param string) float64 { - - i, err := strconv.ParseFloat(param, 64) - panicIf(err) - - return i -} - -func panicIf(err error) { - if err != nil { - panic(err.Error()) - } -} diff --git a/vendor/gopkg.in/go-playground/validator.v8/validator.go b/vendor/gopkg.in/go-playground/validator.v8/validator.go deleted file mode 100644 index 2b1d7164d..000000000 --- a/vendor/gopkg.in/go-playground/validator.v8/validator.go +++ /dev/null @@ -1,782 +0,0 @@ -/** - * Package validator - * - * MISC: - * - anonymous structs - they don't have names so expect the Struct name within StructErrors to be blank - * - */ - -package validator - -import ( - "bytes" - "errors" - "fmt" - "reflect" - "strings" - "sync" - "time" -) - -const ( - utf8HexComma = "0x2C" - utf8Pipe = "0x7C" - tagSeparator = "," - orSeparator = "|" - tagKeySeparator = "=" - structOnlyTag = "structonly" - noStructLevelTag = "nostructlevel" - omitempty = "omitempty" - skipValidationTag = "-" - diveTag = "dive" - existsTag = "exists" - fieldErrMsg = "Key: '%s' Error:Field validation for '%s' failed on the '%s' tag" - arrayIndexFieldName = "%s" + leftBracket + "%d" + rightBracket - mapIndexFieldName = "%s" + leftBracket + "%v" + rightBracket - invalidValidation = "Invalid validation tag on field %s" - undefinedValidation = "Undefined validation function on field %s" - validatorNotInitialized = "Validator instance not initialized" - fieldNameRequired = "Field Name Required" - tagRequired = "Tag Required" -) - -var ( - timeType = reflect.TypeOf(time.Time{}) - timePtrType = reflect.TypeOf(&time.Time{}) - defaultCField = new(cField) -) - -// StructLevel contains all of the information and helper methods -// for reporting errors during struct level validation -type StructLevel struct { - TopStruct reflect.Value - CurrentStruct reflect.Value - errPrefix string - nsPrefix string - errs ValidationErrors - v *Validate -} - -// ReportValidationErrors accepts the key relative to the top level struct and validatin errors. -// Example: had a triple nested struct User, ContactInfo, Country and ran errs := validate.Struct(country) -// from within a User struct level validation would call this method like so: -// ReportValidationErrors("ContactInfo.", errs) -// NOTE: relativeKey can contain both the Field Relative and Custom name relative paths -// i.e. ReportValidationErrors("ContactInfo.|cInfo", errs) where cInfo represents say the JSON name of -// the relative path; this will be split into 2 variables in the next valiator version. -func (sl *StructLevel) ReportValidationErrors(relativeKey string, errs ValidationErrors) { - for _, e := range errs { - - idx := strings.Index(relativeKey, "|") - var rel string - var cRel string - - if idx != -1 { - rel = relativeKey[:idx] - cRel = relativeKey[idx+1:] - } else { - rel = relativeKey - } - - key := sl.errPrefix + rel + e.Field - - e.FieldNamespace = key - e.NameNamespace = sl.nsPrefix + cRel + e.Name - - sl.errs[key] = e - } -} - -// ReportError reports an error just by passing the field and tag information -// NOTE: tag can be an existing validation tag or just something you make up -// and precess on the flip side it's up to you. -func (sl *StructLevel) ReportError(field reflect.Value, fieldName string, customName string, tag string) { - - field, kind := sl.v.ExtractType(field) - - if fieldName == blank { - panic(fieldNameRequired) - } - - if customName == blank { - customName = fieldName - } - - if tag == blank { - panic(tagRequired) - } - - ns := sl.errPrefix + fieldName - - switch kind { - case reflect.Invalid: - sl.errs[ns] = &FieldError{ - FieldNamespace: ns, - NameNamespace: sl.nsPrefix + customName, - Name: customName, - Field: fieldName, - Tag: tag, - ActualTag: tag, - Param: blank, - Kind: kind, - } - default: - sl.errs[ns] = &FieldError{ - FieldNamespace: ns, - NameNamespace: sl.nsPrefix + customName, - Name: customName, - Field: fieldName, - Tag: tag, - ActualTag: tag, - Param: blank, - Value: field.Interface(), - Kind: kind, - Type: field.Type(), - } - } -} - -// Validate contains the validator settings passed in using the Config struct -type Validate struct { - tagName string - fieldNameTag string - validationFuncs map[string]Func - structLevelFuncs map[reflect.Type]StructLevelFunc - customTypeFuncs map[reflect.Type]CustomTypeFunc - aliasValidators map[string]string - hasCustomFuncs bool - hasAliasValidators bool - hasStructLevelFuncs bool - tagCache *tagCache - structCache *structCache - errsPool *sync.Pool -} - -func (v *Validate) initCheck() { - if v == nil { - panic(validatorNotInitialized) - } -} - -// Config contains the options that a Validator instance will use. -// It is passed to the New() function -type Config struct { - TagName string - FieldNameTag string -} - -// CustomTypeFunc allows for overriding or adding custom field type handler functions -// field = field value of the type to return a value to be validated -// example Valuer from sql drive see https://golang.org/src/database/sql/driver/types.go?s=1210:1293#L29 -type CustomTypeFunc func(field reflect.Value) interface{} - -// Func accepts all values needed for file and cross field validation -// v = validator instance, needed but some built in functions for it's custom types -// topStruct = top level struct when validating by struct otherwise nil -// currentStruct = current level struct when validating by struct otherwise optional comparison value -// field = field value for validation -// param = parameter used in validation i.e. gt=0 param would be 0 -type Func func(v *Validate, topStruct reflect.Value, currentStruct reflect.Value, field reflect.Value, fieldtype reflect.Type, fieldKind reflect.Kind, param string) bool - -// StructLevelFunc accepts all values needed for struct level validation -type StructLevelFunc func(v *Validate, structLevel *StructLevel) - -// ValidationErrors is a type of map[string]*FieldError -// it exists to allow for multiple errors to be passed from this library -// and yet still subscribe to the error interface -type ValidationErrors map[string]*FieldError - -// Error is intended for use in development + debugging and not intended to be a production error message. -// It allows ValidationErrors to subscribe to the Error interface. -// All information to create an error message specific to your application is contained within -// the FieldError found within the ValidationErrors map -func (ve ValidationErrors) Error() string { - - buff := bytes.NewBufferString(blank) - - for key, err := range ve { - buff.WriteString(fmt.Sprintf(fieldErrMsg, key, err.Field, err.Tag)) - buff.WriteString("\n") - } - - return strings.TrimSpace(buff.String()) -} - -// FieldError contains a single field's validation error along -// with other properties that may be needed for error message creation -type FieldError struct { - FieldNamespace string - NameNamespace string - Field string - Name string - Tag string - ActualTag string - Kind reflect.Kind - Type reflect.Type - Param string - Value interface{} -} - -// New creates a new Validate instance for use. -func New(config *Config) *Validate { - - tc := new(tagCache) - tc.m.Store(make(map[string]*cTag)) - - sc := new(structCache) - sc.m.Store(make(map[reflect.Type]*cStruct)) - - v := &Validate{ - tagName: config.TagName, - fieldNameTag: config.FieldNameTag, - tagCache: tc, - structCache: sc, - errsPool: &sync.Pool{New: func() interface{} { - return ValidationErrors{} - }}} - - if len(v.aliasValidators) == 0 { - // must copy alias validators for separate validations to be used in each validator instance - v.aliasValidators = map[string]string{} - for k, val := range bakedInAliasValidators { - v.RegisterAliasValidation(k, val) - } - } - - if len(v.validationFuncs) == 0 { - // must copy validators for separate validations to be used in each instance - v.validationFuncs = map[string]Func{} - for k, val := range bakedInValidators { - v.RegisterValidation(k, val) - } - } - - return v -} - -// RegisterStructValidation registers a StructLevelFunc against a number of types -// NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation -func (v *Validate) RegisterStructValidation(fn StructLevelFunc, types ...interface{}) { - v.initCheck() - - if v.structLevelFuncs == nil { - v.structLevelFuncs = map[reflect.Type]StructLevelFunc{} - } - - for _, t := range types { - v.structLevelFuncs[reflect.TypeOf(t)] = fn - } - - v.hasStructLevelFuncs = true -} - -// RegisterValidation adds a validation Func to a Validate's map of validators denoted by the key -// NOTE: if the key already exists, the previous validation function will be replaced. -// NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation -func (v *Validate) RegisterValidation(key string, fn Func) error { - v.initCheck() - - if key == blank { - return errors.New("Function Key cannot be empty") - } - - if fn == nil { - return errors.New("Function cannot be empty") - } - - _, ok := restrictedTags[key] - - if ok || strings.ContainsAny(key, restrictedTagChars) { - panic(fmt.Sprintf(restrictedTagErr, key)) - } - - v.validationFuncs[key] = fn - - return nil -} - -// RegisterCustomTypeFunc registers a CustomTypeFunc against a number of types -// NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation -func (v *Validate) RegisterCustomTypeFunc(fn CustomTypeFunc, types ...interface{}) { - v.initCheck() - - if v.customTypeFuncs == nil { - v.customTypeFuncs = map[reflect.Type]CustomTypeFunc{} - } - - for _, t := range types { - v.customTypeFuncs[reflect.TypeOf(t)] = fn - } - - v.hasCustomFuncs = true -} - -// RegisterAliasValidation registers a mapping of a single validationstag that -// defines a common or complex set of validation(s) to simplify adding validation -// to structs. NOTE: when returning an error the tag returned in FieldError will be -// the alias tag unless the dive tag is part of the alias; everything after the -// dive tag is not reported as the alias tag. Also the ActualTag in the before case -// will be the actual tag within the alias that failed. -// NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation -func (v *Validate) RegisterAliasValidation(alias, tags string) { - v.initCheck() - - _, ok := restrictedTags[alias] - - if ok || strings.ContainsAny(alias, restrictedTagChars) { - panic(fmt.Sprintf(restrictedAliasErr, alias)) - } - - v.aliasValidators[alias] = tags - v.hasAliasValidators = true -} - -// Field validates a single field using tag style validation and returns nil or ValidationErrors as type error. -// You will need to assert the error if it's not nil i.e. err.(validator.ValidationErrors) to access the map of errors. -// NOTE: it returns ValidationErrors instead of a single FieldError because this can also -// validate Array, Slice and maps fields which may contain more than one error -func (v *Validate) Field(field interface{}, tag string) error { - v.initCheck() - - if len(tag) == 0 || tag == skipValidationTag { - return nil - } - - errs := v.errsPool.Get().(ValidationErrors) - fieldVal := reflect.ValueOf(field) - - ctag, ok := v.tagCache.Get(tag) - if !ok { - v.tagCache.lock.Lock() - defer v.tagCache.lock.Unlock() - - // could have been multiple trying to access, but once first is done this ensures tag - // isn't parsed again. - ctag, ok = v.tagCache.Get(tag) - if !ok { - ctag, _ = v.parseFieldTagsRecursive(tag, blank, blank, false) - v.tagCache.Set(tag, ctag) - } - } - - v.traverseField(fieldVal, fieldVal, fieldVal, blank, blank, errs, false, false, nil, nil, defaultCField, ctag) - - if len(errs) == 0 { - v.errsPool.Put(errs) - return nil - } - - return errs -} - -// FieldWithValue validates a single field, against another fields value using tag style validation and returns nil or ValidationErrors. -// You will need to assert the error if it's not nil i.e. err.(validator.ValidationErrors) to access the map of errors. -// NOTE: it returns ValidationErrors instead of a single FieldError because this can also -// validate Array, Slice and maps fields which may contain more than one error -func (v *Validate) FieldWithValue(val interface{}, field interface{}, tag string) error { - v.initCheck() - - if len(tag) == 0 || tag == skipValidationTag { - return nil - } - - errs := v.errsPool.Get().(ValidationErrors) - topVal := reflect.ValueOf(val) - - ctag, ok := v.tagCache.Get(tag) - if !ok { - v.tagCache.lock.Lock() - defer v.tagCache.lock.Unlock() - - // could have been multiple trying to access, but once first is done this ensures tag - // isn't parsed again. - ctag, ok = v.tagCache.Get(tag) - if !ok { - ctag, _ = v.parseFieldTagsRecursive(tag, blank, blank, false) - v.tagCache.Set(tag, ctag) - } - } - - v.traverseField(topVal, topVal, reflect.ValueOf(field), blank, blank, errs, false, false, nil, nil, defaultCField, ctag) - - if len(errs) == 0 { - v.errsPool.Put(errs) - return nil - } - - return errs -} - -// StructPartial validates the fields passed in only, ignoring all others. -// Fields may be provided in a namespaced fashion relative to the struct provided -// i.e. NestedStruct.Field or NestedArrayField[0].Struct.Name and returns nil or ValidationErrors as error -// You will need to assert the error if it's not nil i.e. err.(validator.ValidationErrors) to access the map of errors. -func (v *Validate) StructPartial(current interface{}, fields ...string) error { - v.initCheck() - - sv, _ := v.ExtractType(reflect.ValueOf(current)) - name := sv.Type().Name() - m := map[string]struct{}{} - - if fields != nil { - for _, k := range fields { - - flds := strings.Split(k, namespaceSeparator) - if len(flds) > 0 { - - key := name + namespaceSeparator - for _, s := range flds { - - idx := strings.Index(s, leftBracket) - - if idx != -1 { - for idx != -1 { - key += s[:idx] - m[key] = struct{}{} - - idx2 := strings.Index(s, rightBracket) - idx2++ - key += s[idx:idx2] - m[key] = struct{}{} - s = s[idx2:] - idx = strings.Index(s, leftBracket) - } - } else { - - key += s - m[key] = struct{}{} - } - - key += namespaceSeparator - } - } - } - } - - errs := v.errsPool.Get().(ValidationErrors) - - v.ensureValidStruct(sv, sv, sv, blank, blank, errs, true, len(m) != 0, false, m, false) - - if len(errs) == 0 { - v.errsPool.Put(errs) - return nil - } - - return errs -} - -// StructExcept validates all fields except the ones passed in. -// Fields may be provided in a namespaced fashion relative to the struct provided -// i.e. NestedStruct.Field or NestedArrayField[0].Struct.Name and returns nil or ValidationErrors as error -// You will need to assert the error if it's not nil i.e. err.(validator.ValidationErrors) to access the map of errors. -func (v *Validate) StructExcept(current interface{}, fields ...string) error { - v.initCheck() - - sv, _ := v.ExtractType(reflect.ValueOf(current)) - name := sv.Type().Name() - m := map[string]struct{}{} - - for _, key := range fields { - m[name+namespaceSeparator+key] = struct{}{} - } - - errs := v.errsPool.Get().(ValidationErrors) - - v.ensureValidStruct(sv, sv, sv, blank, blank, errs, true, len(m) != 0, true, m, false) - - if len(errs) == 0 { - v.errsPool.Put(errs) - return nil - } - - return errs -} - -// Struct validates a structs exposed fields, and automatically validates nested structs, unless otherwise specified. -// it returns nil or ValidationErrors as error. -// You will need to assert the error if it's not nil i.e. err.(validator.ValidationErrors) to access the map of errors. -func (v *Validate) Struct(current interface{}) error { - v.initCheck() - - errs := v.errsPool.Get().(ValidationErrors) - sv := reflect.ValueOf(current) - - v.ensureValidStruct(sv, sv, sv, blank, blank, errs, true, false, false, nil, false) - - if len(errs) == 0 { - v.errsPool.Put(errs) - return nil - } - - return errs -} - -func (v *Validate) ensureValidStruct(topStruct reflect.Value, currentStruct reflect.Value, current reflect.Value, errPrefix string, nsPrefix string, errs ValidationErrors, useStructName bool, partial bool, exclude bool, includeExclude map[string]struct{}, isStructOnly bool) { - - if current.Kind() == reflect.Ptr && !current.IsNil() { - current = current.Elem() - } - - if current.Kind() != reflect.Struct && current.Kind() != reflect.Interface { - panic("value passed for validation is not a struct") - } - - v.tranverseStruct(topStruct, currentStruct, current, errPrefix, nsPrefix, errs, useStructName, partial, exclude, includeExclude, nil, nil) -} - -// tranverseStruct traverses a structs fields and then passes them to be validated by traverseField -func (v *Validate) tranverseStruct(topStruct reflect.Value, currentStruct reflect.Value, current reflect.Value, errPrefix string, nsPrefix string, errs ValidationErrors, useStructName bool, partial bool, exclude bool, includeExclude map[string]struct{}, cs *cStruct, ct *cTag) { - - var ok bool - first := len(nsPrefix) == 0 - typ := current.Type() - - cs, ok = v.structCache.Get(typ) - if !ok { - cs = v.extractStructCache(current, typ.Name()) - } - - if useStructName { - errPrefix += cs.Name + namespaceSeparator - - if len(v.fieldNameTag) != 0 { - nsPrefix += cs.Name + namespaceSeparator - } - } - - // structonly tag present don't tranverseFields - // but must still check and run below struct level validation - // if present - if first || ct == nil || ct.typeof != typeStructOnly { - - for _, f := range cs.fields { - - if partial { - - _, ok = includeExclude[errPrefix+f.Name] - - if (ok && exclude) || (!ok && !exclude) { - continue - } - } - - v.traverseField(topStruct, currentStruct, current.Field(f.Idx), errPrefix, nsPrefix, errs, partial, exclude, includeExclude, cs, f, f.cTags) - } - } - - // check if any struct level validations, after all field validations already checked. - if cs.fn != nil { - cs.fn(v, &StructLevel{v: v, TopStruct: topStruct, CurrentStruct: current, errPrefix: errPrefix, nsPrefix: nsPrefix, errs: errs}) - } -} - -// traverseField validates any field, be it a struct or single field, ensures it's validity and passes it along to be validated via it's tag options -func (v *Validate) traverseField(topStruct reflect.Value, currentStruct reflect.Value, current reflect.Value, errPrefix string, nsPrefix string, errs ValidationErrors, partial bool, exclude bool, includeExclude map[string]struct{}, cs *cStruct, cf *cField, ct *cTag) { - - current, kind, nullable := v.extractTypeInternal(current, false) - var typ reflect.Type - - switch kind { - case reflect.Ptr, reflect.Interface, reflect.Invalid: - - if ct == nil { - return - } - - if ct.typeof == typeOmitEmpty { - return - } - - if ct.hasTag { - - ns := errPrefix + cf.Name - - if kind == reflect.Invalid { - errs[ns] = &FieldError{ - FieldNamespace: ns, - NameNamespace: nsPrefix + cf.AltName, - Name: cf.AltName, - Field: cf.Name, - Tag: ct.aliasTag, - ActualTag: ct.tag, - Param: ct.param, - Kind: kind, - } - return - } - - errs[ns] = &FieldError{ - FieldNamespace: ns, - NameNamespace: nsPrefix + cf.AltName, - Name: cf.AltName, - Field: cf.Name, - Tag: ct.aliasTag, - ActualTag: ct.tag, - Param: ct.param, - Value: current.Interface(), - Kind: kind, - Type: current.Type(), - } - - return - } - - case reflect.Struct: - typ = current.Type() - - if typ != timeType { - - if ct != nil { - ct = ct.next - } - - if ct != nil && ct.typeof == typeNoStructLevel { - return - } - - v.tranverseStruct(topStruct, current, current, errPrefix+cf.Name+namespaceSeparator, nsPrefix+cf.AltName+namespaceSeparator, errs, false, partial, exclude, includeExclude, cs, ct) - return - } - } - - if !ct.hasTag { - return - } - - typ = current.Type() - -OUTER: - for { - if ct == nil { - return - } - - switch ct.typeof { - - case typeExists: - ct = ct.next - continue - - case typeOmitEmpty: - - if !nullable && !HasValue(v, topStruct, currentStruct, current, typ, kind, blank) { - return - } - - ct = ct.next - continue - - case typeDive: - - ct = ct.next - - // traverse slice or map here - // or panic ;) - switch kind { - case reflect.Slice, reflect.Array: - - for i := 0; i < current.Len(); i++ { - v.traverseField(topStruct, currentStruct, current.Index(i), errPrefix, nsPrefix, errs, partial, exclude, includeExclude, cs, &cField{Name: fmt.Sprintf(arrayIndexFieldName, cf.Name, i), AltName: fmt.Sprintf(arrayIndexFieldName, cf.AltName, i)}, ct) - } - - case reflect.Map: - for _, key := range current.MapKeys() { - v.traverseField(topStruct, currentStruct, current.MapIndex(key), errPrefix, nsPrefix, errs, partial, exclude, includeExclude, cs, &cField{Name: fmt.Sprintf(mapIndexFieldName, cf.Name, key.Interface()), AltName: fmt.Sprintf(mapIndexFieldName, cf.AltName, key.Interface())}, ct) - } - - default: - // throw error, if not a slice or map then should not have gotten here - // bad dive tag - panic("dive error! can't dive on a non slice or map") - } - - return - - case typeOr: - - errTag := blank - - for { - - if ct.fn(v, topStruct, currentStruct, current, typ, kind, ct.param) { - - // drain rest of the 'or' values, then continue or leave - for { - - ct = ct.next - - if ct == nil { - return - } - - if ct.typeof != typeOr { - continue OUTER - } - } - } - - errTag += orSeparator + ct.tag - - if ct.next == nil { - // if we get here, no valid 'or' value and no more tags - - ns := errPrefix + cf.Name - - if ct.hasAlias { - errs[ns] = &FieldError{ - FieldNamespace: ns, - NameNamespace: nsPrefix + cf.AltName, - Name: cf.AltName, - Field: cf.Name, - Tag: ct.aliasTag, - ActualTag: ct.actualAliasTag, - Value: current.Interface(), - Type: typ, - Kind: kind, - } - } else { - errs[errPrefix+cf.Name] = &FieldError{ - FieldNamespace: ns, - NameNamespace: nsPrefix + cf.AltName, - Name: cf.AltName, - Field: cf.Name, - Tag: errTag[1:], - ActualTag: errTag[1:], - Value: current.Interface(), - Type: typ, - Kind: kind, - } - } - - return - } - - ct = ct.next - } - - default: - if !ct.fn(v, topStruct, currentStruct, current, typ, kind, ct.param) { - - ns := errPrefix + cf.Name - - errs[ns] = &FieldError{ - FieldNamespace: ns, - NameNamespace: nsPrefix + cf.AltName, - Name: cf.AltName, - Field: cf.Name, - Tag: ct.aliasTag, - ActualTag: ct.tag, - Value: current.Interface(), - Param: ct.param, - Type: typ, - Kind: kind, - } - - return - - } - - ct = ct.next - } - } -} diff --git a/vendor/gopkg.in/tylerb/graceful.v1/LICENSE b/vendor/gopkg.in/tylerb/graceful.v1/LICENSE deleted file mode 100644 index a4f2f281b..000000000 --- a/vendor/gopkg.in/tylerb/graceful.v1/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Tyler Bunnell - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/gopkg.in/tylerb/graceful.v1/graceful.go b/vendor/gopkg.in/tylerb/graceful.v1/graceful.go deleted file mode 100644 index ebf0aeb7d..000000000 --- a/vendor/gopkg.in/tylerb/graceful.v1/graceful.go +++ /dev/null @@ -1,489 +0,0 @@ -package graceful - -import ( - "crypto/tls" - "log" - "net" - "net/http" - "os" - "sync" - "time" -) - -// Server wraps an http.Server with graceful connection handling. -// It may be used directly in the same way as http.Server, or may -// be constructed with the global functions in this package. -// -// Example: -// srv := &graceful.Server{ -// Timeout: 5 * time.Second, -// Server: &http.Server{Addr: ":1234", Handler: handler}, -// } -// srv.ListenAndServe() -type Server struct { - *http.Server - - // Timeout is the duration to allow outstanding requests to survive - // before forcefully terminating them. - Timeout time.Duration - - // Limit the number of outstanding requests - ListenLimit int - - // TCPKeepAlive sets the TCP keep-alive timeouts on accepted - // connections. It prunes dead TCP connections ( e.g. closing - // laptop mid-download) - TCPKeepAlive time.Duration - - // ConnState specifies an optional callback function that is - // called when a client connection changes state. This is a proxy - // to the underlying http.Server's ConnState, and the original - // must not be set directly. - ConnState func(net.Conn, http.ConnState) - - // BeforeShutdown is an optional callback function that is called - // before the listener is closed. Returns true if shutdown is allowed - BeforeShutdown func() bool - - // ShutdownInitiated is an optional callback function that is called - // when shutdown is initiated. It can be used to notify the client - // side of long lived connections (e.g. websockets) to reconnect. - ShutdownInitiated func() - - // NoSignalHandling prevents graceful from automatically shutting down - // on SIGINT and SIGTERM. If set to true, you must shut down the server - // manually with Stop(). - NoSignalHandling bool - - // Logger used to notify of errors on startup and on stop. - Logger *log.Logger - - // LogFunc can be assigned with a logging function of your choice, allowing - // you to use whatever logging approach you would like - LogFunc func(format string, args ...interface{}) - - // Interrupted is true if the server is handling a SIGINT or SIGTERM - // signal and is thus shutting down. - Interrupted bool - - // interrupt signals the listener to stop serving connections, - // and the server to shut down. - interrupt chan os.Signal - - // stopLock is used to protect against concurrent calls to Stop - stopLock sync.Mutex - - // stopChan is the channel on which callers may block while waiting for - // the server to stop. - stopChan chan struct{} - - // chanLock is used to protect access to the various channel constructors. - chanLock sync.RWMutex - - // connections holds all connections managed by graceful - connections map[net.Conn]struct{} - - // idleConnections holds all idle connections managed by graceful - idleConnections map[net.Conn]struct{} -} - -// Run serves the http.Handler with graceful shutdown enabled. -// -// timeout is the duration to wait until killing active requests and stopping the server. -// If timeout is 0, the server never times out. It waits for all active requests to finish. -func Run(addr string, timeout time.Duration, n http.Handler) { - srv := &Server{ - Timeout: timeout, - TCPKeepAlive: 3 * time.Minute, - Server: &http.Server{Addr: addr, Handler: n}, - // Logger: DefaultLogger(), - } - - if err := srv.ListenAndServe(); err != nil { - if opErr, ok := err.(*net.OpError); !ok || (ok && opErr.Op != "accept") { - srv.logf("%s", err) - os.Exit(1) - } - } - -} - -// RunWithErr is an alternative version of Run function which can return error. -// -// Unlike Run this version will not exit the program if an error is encountered but will -// return it instead. -func RunWithErr(addr string, timeout time.Duration, n http.Handler) error { - srv := &Server{ - Timeout: timeout, - TCPKeepAlive: 3 * time.Minute, - Server: &http.Server{Addr: addr, Handler: n}, - Logger: DefaultLogger(), - } - - return srv.ListenAndServe() -} - -// ListenAndServe is equivalent to http.Server.ListenAndServe with graceful shutdown enabled. -// -// timeout is the duration to wait until killing active requests and stopping the server. -// If timeout is 0, the server never times out. It waits for all active requests to finish. -func ListenAndServe(server *http.Server, timeout time.Duration) error { - srv := &Server{Timeout: timeout, Server: server, Logger: DefaultLogger()} - return srv.ListenAndServe() -} - -// ListenAndServe is equivalent to http.Server.ListenAndServe with graceful shutdown enabled. -func (srv *Server) ListenAndServe() error { - // Create the listener so we can control their lifetime - addr := srv.Addr - if addr == "" { - addr = ":http" - } - conn, err := srv.newTCPListener(addr) - if err != nil { - return err - } - - return srv.Serve(conn) -} - -// ListenAndServeTLS is equivalent to http.Server.ListenAndServeTLS with graceful shutdown enabled. -// -// timeout is the duration to wait until killing active requests and stopping the server. -// If timeout is 0, the server never times out. It waits for all active requests to finish. -func ListenAndServeTLS(server *http.Server, certFile, keyFile string, timeout time.Duration) error { - srv := &Server{Timeout: timeout, Server: server, Logger: DefaultLogger()} - return srv.ListenAndServeTLS(certFile, keyFile) -} - -// ListenTLS is a convenience method that creates an https listener using the -// provided cert and key files. Use this method if you need access to the -// listener object directly. When ready, pass it to the Serve method. -func (srv *Server) ListenTLS(certFile, keyFile string) (net.Listener, error) { - // Create the listener ourselves so we can control its lifetime - addr := srv.Addr - if addr == "" { - addr = ":https" - } - - config := &tls.Config{} - if srv.TLSConfig != nil { - *config = *srv.TLSConfig - } - - var err error - if certFile != "" && keyFile != "" { - config.Certificates = make([]tls.Certificate, 1) - config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile) - if err != nil { - return nil, err - } - } - - // Enable http2 - enableHTTP2ForTLSConfig(config) - - conn, err := srv.newTCPListener(addr) - if err != nil { - return nil, err - } - - srv.TLSConfig = config - - tlsListener := tls.NewListener(conn, config) - return tlsListener, nil -} - -// Enable HTTP2ForTLSConfig explicitly enables http/2 for a TLS Config. This is due to changes in Go 1.7 where -// http servers are no longer automatically configured to enable http/2 if the server's TLSConfig is set. -// See https://github.com/golang/go/issues/15908 -func enableHTTP2ForTLSConfig(t *tls.Config) { - - if TLSConfigHasHTTP2Enabled(t) { - return - } - - t.NextProtos = append(t.NextProtos, "h2") -} - -// TLSConfigHasHTTP2Enabled checks to see if a given TLS Config has http2 enabled. -func TLSConfigHasHTTP2Enabled(t *tls.Config) bool { - for _, value := range t.NextProtos { - if value == "h2" { - return true - } - } - return false -} - -// ListenAndServeTLS is equivalent to http.Server.ListenAndServeTLS with graceful shutdown enabled. -func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error { - l, err := srv.ListenTLS(certFile, keyFile) - if err != nil { - return err - } - - return srv.Serve(l) -} - -// ListenAndServeTLSConfig can be used with an existing TLS config and is equivalent to -// http.Server.ListenAndServeTLS with graceful shutdown enabled, -func (srv *Server) ListenAndServeTLSConfig(config *tls.Config) error { - addr := srv.Addr - if addr == "" { - addr = ":https" - } - - conn, err := srv.newTCPListener(addr) - if err != nil { - return err - } - - srv.TLSConfig = config - - tlsListener := tls.NewListener(conn, config) - return srv.Serve(tlsListener) -} - -// Serve is equivalent to http.Server.Serve with graceful shutdown enabled. -// -// timeout is the duration to wait until killing active requests and stopping the server. -// If timeout is 0, the server never times out. It waits for all active requests to finish. -func Serve(server *http.Server, l net.Listener, timeout time.Duration) error { - srv := &Server{Timeout: timeout, Server: server, Logger: DefaultLogger()} - - return srv.Serve(l) -} - -// Serve is equivalent to http.Server.Serve with graceful shutdown enabled. -func (srv *Server) Serve(listener net.Listener) error { - - if srv.ListenLimit != 0 { - listener = LimitListener(listener, srv.ListenLimit) - } - - // Make our stopchan - srv.StopChan() - - // Track connection state - add := make(chan net.Conn) - idle := make(chan net.Conn) - active := make(chan net.Conn) - remove := make(chan net.Conn) - - srv.Server.ConnState = func(conn net.Conn, state http.ConnState) { - switch state { - case http.StateNew: - add <- conn - case http.StateActive: - active <- conn - case http.StateIdle: - idle <- conn - case http.StateClosed, http.StateHijacked: - remove <- conn - } - - srv.stopLock.Lock() - defer srv.stopLock.Unlock() - - if srv.ConnState != nil { - srv.ConnState(conn, state) - } - } - - // Manage open connections - shutdown := make(chan chan struct{}) - kill := make(chan struct{}) - go srv.manageConnections(add, idle, active, remove, shutdown, kill) - - interrupt := srv.interruptChan() - // Set up the interrupt handler - if !srv.NoSignalHandling { - signalNotify(interrupt) - } - quitting := make(chan struct{}) - go srv.handleInterrupt(interrupt, quitting, listener) - - // Serve with graceful listener. - // Execution blocks here until listener.Close() is called, above. - err := srv.Server.Serve(listener) - if err != nil { - // If the underlying listening is closed, Serve returns an error - // complaining about listening on a closed socket. This is expected, so - // let's ignore the error if we are the ones who explicitly closed the - // socket. - select { - case <-quitting: - err = nil - default: - } - } - - srv.shutdown(shutdown, kill) - - return err -} - -// Stop instructs the type to halt operations and close -// the stop channel when it is finished. -// -// timeout is grace period for which to wait before shutting -// down the server. The timeout value passed here will override the -// timeout given when constructing the server, as this is an explicit -// command to stop the server. -func (srv *Server) Stop(timeout time.Duration) { - srv.stopLock.Lock() - defer srv.stopLock.Unlock() - - srv.Timeout = timeout - sendSignalInt(srv.interruptChan()) -} - -// StopChan gets the stop channel which will block until -// stopping has completed, at which point it is closed. -// Callers should never close the stop channel. -func (srv *Server) StopChan() <-chan struct{} { - srv.chanLock.Lock() - defer srv.chanLock.Unlock() - - if srv.stopChan == nil { - srv.stopChan = make(chan struct{}) - } - return srv.stopChan -} - -// DefaultLogger returns the logger used by Run, RunWithErr, ListenAndServe, ListenAndServeTLS and Serve. -// The logger outputs to STDERR by default. -func DefaultLogger() *log.Logger { - return log.New(os.Stderr, "[graceful] ", 0) -} - -func (srv *Server) manageConnections(add, idle, active, remove chan net.Conn, shutdown chan chan struct{}, kill chan struct{}) { - var done chan struct{} - srv.connections = map[net.Conn]struct{}{} - srv.idleConnections = map[net.Conn]struct{}{} - for { - select { - case conn := <-add: - srv.connections[conn] = struct{}{} - srv.idleConnections[conn] = struct{}{} // Newly-added connections are considered idle until they become active. - case conn := <-idle: - srv.idleConnections[conn] = struct{}{} - case conn := <-active: - delete(srv.idleConnections, conn) - case conn := <-remove: - delete(srv.connections, conn) - delete(srv.idleConnections, conn) - if done != nil && len(srv.connections) == 0 { - done <- struct{}{} - return - } - case done = <-shutdown: - if len(srv.connections) == 0 && len(srv.idleConnections) == 0 { - done <- struct{}{} - return - } - // a shutdown request has been received. if we have open idle - // connections, we must close all of them now. this prevents idle - // connections from holding the server open while waiting for them to - // hit their idle timeout. - for k := range srv.idleConnections { - if err := k.Close(); err != nil { - srv.logf("[ERROR] %s", err) - } - } - case <-kill: - srv.stopLock.Lock() - defer srv.stopLock.Unlock() - - srv.Server.ConnState = nil - for k := range srv.connections { - if err := k.Close(); err != nil { - srv.logf("[ERROR] %s", err) - } - } - return - } - } -} - -func (srv *Server) interruptChan() chan os.Signal { - srv.chanLock.Lock() - defer srv.chanLock.Unlock() - - if srv.interrupt == nil { - srv.interrupt = make(chan os.Signal, 1) - } - - return srv.interrupt -} - -func (srv *Server) handleInterrupt(interrupt chan os.Signal, quitting chan struct{}, listener net.Listener) { - for _ = range interrupt { - if srv.Interrupted { - srv.logf("already shutting down") - continue - } - srv.logf("shutdown initiated") - srv.Interrupted = true - if srv.BeforeShutdown != nil { - if !srv.BeforeShutdown() { - srv.Interrupted = false - continue - } - } - - close(quitting) - srv.SetKeepAlivesEnabled(false) - if err := listener.Close(); err != nil { - srv.logf("[ERROR] %s", err) - } - - if srv.ShutdownInitiated != nil { - srv.ShutdownInitiated() - } - } -} - -func (srv *Server) logf(format string, args ...interface{}) { - if srv.LogFunc != nil { - srv.LogFunc(format, args...) - } else if srv.Logger != nil { - srv.Logger.Printf(format, args...) - } -} - -func (srv *Server) shutdown(shutdown chan chan struct{}, kill chan struct{}) { - // Request done notification - done := make(chan struct{}) - shutdown <- done - - srv.stopLock.Lock() - defer srv.stopLock.Unlock() - if srv.Timeout > 0 { - select { - case <-done: - case <-time.After(srv.Timeout): - close(kill) - } - } else { - <-done - } - // Close the stopChan to wake up any blocked goroutines. - srv.chanLock.Lock() - if srv.stopChan != nil { - close(srv.stopChan) - } - srv.chanLock.Unlock() -} - -func (srv *Server) newTCPListener(addr string) (net.Listener, error) { - conn, err := net.Listen("tcp", addr) - if err != nil { - return conn, err - } - if srv.TCPKeepAlive != 0 { - conn = keepAliveListener{conn, srv.TCPKeepAlive} - } - return conn, nil -} diff --git a/vendor/gopkg.in/tylerb/graceful.v1/keepalive_listener.go b/vendor/gopkg.in/tylerb/graceful.v1/keepalive_listener.go deleted file mode 100644 index 1484bc213..000000000 --- a/vendor/gopkg.in/tylerb/graceful.v1/keepalive_listener.go +++ /dev/null @@ -1,32 +0,0 @@ -package graceful - -import ( - "net" - "time" -) - -type keepAliveConn interface { - SetKeepAlive(bool) error - SetKeepAlivePeriod(d time.Duration) error -} - -// keepAliveListener sets TCP keep-alive timeouts on accepted -// connections. It's used by ListenAndServe and ListenAndServeTLS so -// dead TCP connections (e.g. closing laptop mid-download) eventually -// go away. -type keepAliveListener struct { - net.Listener - keepAlivePeriod time.Duration -} - -func (ln keepAliveListener) Accept() (net.Conn, error) { - c, err := ln.Listener.Accept() - if err != nil { - return nil, err - } - - kac := c.(keepAliveConn) - kac.SetKeepAlive(true) - kac.SetKeepAlivePeriod(ln.keepAlivePeriod) - return c, nil -} diff --git a/vendor/gopkg.in/tylerb/graceful.v1/limit_listen.go b/vendor/gopkg.in/tylerb/graceful.v1/limit_listen.go deleted file mode 100644 index ce32ce992..000000000 --- a/vendor/gopkg.in/tylerb/graceful.v1/limit_listen.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2013 The etcd Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package graceful - -import ( - "errors" - "net" - "sync" - "time" -) - -// ErrNotTCP indicates that network connection is not a TCP connection. -var ErrNotTCP = errors.New("only tcp connections have keepalive") - -// LimitListener returns a Listener that accepts at most n simultaneous -// connections from the provided Listener. -func LimitListener(l net.Listener, n int) net.Listener { - return &limitListener{l, make(chan struct{}, n)} -} - -type limitListener struct { - net.Listener - sem chan struct{} -} - -func (l *limitListener) acquire() { l.sem <- struct{}{} } -func (l *limitListener) release() { <-l.sem } - -func (l *limitListener) Accept() (net.Conn, error) { - l.acquire() - c, err := l.Listener.Accept() - if err != nil { - l.release() - return nil, err - } - return &limitListenerConn{Conn: c, release: l.release}, nil -} - -type limitListenerConn struct { - net.Conn - releaseOnce sync.Once - release func() -} - -func (l *limitListenerConn) Close() error { - err := l.Conn.Close() - l.releaseOnce.Do(l.release) - return err -} - -func (l *limitListenerConn) SetKeepAlive(doKeepAlive bool) error { - tcpc, ok := l.Conn.(*net.TCPConn) - if !ok { - return ErrNotTCP - } - return tcpc.SetKeepAlive(doKeepAlive) -} - -func (l *limitListenerConn) SetKeepAlivePeriod(d time.Duration) error { - tcpc, ok := l.Conn.(*net.TCPConn) - if !ok { - return ErrNotTCP - } - return tcpc.SetKeepAlivePeriod(d) -} diff --git a/vendor/gopkg.in/tylerb/graceful.v1/signal.go b/vendor/gopkg.in/tylerb/graceful.v1/signal.go deleted file mode 100644 index 9550978fe..000000000 --- a/vendor/gopkg.in/tylerb/graceful.v1/signal.go +++ /dev/null @@ -1,17 +0,0 @@ -//+build !appengine - -package graceful - -import ( - "os" - "os/signal" - "syscall" -) - -func signalNotify(interrupt chan<- os.Signal) { - signal.Notify(interrupt, syscall.SIGINT, syscall.SIGTERM) -} - -func sendSignalInt(interrupt chan<- os.Signal) { - interrupt <- syscall.SIGINT -} diff --git a/vendor/gopkg.in/tylerb/graceful.v1/signal_appengine.go b/vendor/gopkg.in/tylerb/graceful.v1/signal_appengine.go deleted file mode 100644 index 6b776f087..000000000 --- a/vendor/gopkg.in/tylerb/graceful.v1/signal_appengine.go +++ /dev/null @@ -1,13 +0,0 @@ -//+build appengine - -package graceful - -import "os" - -func signalNotify(interrupt chan<- os.Signal) { - // Does not notify in the case of AppEngine. -} - -func sendSignalInt(interrupt chan<- os.Signal) { - // Does not send in the case of AppEngine. -} From aee26feb942b7ab4e64df4f07853c919803c593d Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Wed, 18 Jul 2018 17:27:17 +0100 Subject: [PATCH 09/28] Update and centralise protobuf Signed-off-by: Silas Davis --- Makefile | 40 ++++------ protobuf/acm.proto | 31 ++++++++ protobuf/crypto.proto | 29 ++++++++ protobuf/errors.proto | 24 ++++++ protobuf/exec.proto | 149 +++++++++++++++++++++++++++++++++++++ protobuf/keys.proto | 141 +++++++++++++++++++++++++++++++++++ protobuf/names.proto | 33 ++++++++ protobuf/payload.proto | 123 ++++++++++++++++++++++++++++++ protobuf/permission.proto | 39 ++++++++++ protobuf/rpcevents.proto | 128 +++++++++++++++++++++++++++++++ protobuf/rpcquery.proto | 40 ++++++++++ protobuf/rpctransact.proto | 80 ++++++++++++++++++++ protobuf/spec.proto | 35 +++++++++ protobuf/txs.proto | 47 ++++++++++++ 14 files changed, 913 insertions(+), 26 deletions(-) create mode 100644 protobuf/acm.proto create mode 100644 protobuf/crypto.proto create mode 100644 protobuf/errors.proto create mode 100644 protobuf/exec.proto create mode 100644 protobuf/keys.proto create mode 100644 protobuf/names.proto create mode 100644 protobuf/payload.proto create mode 100644 protobuf/permission.proto create mode 100644 protobuf/rpcevents.proto create mode 100644 protobuf/rpcquery.proto create mode 100644 protobuf/rpctransact.proto create mode 100644 protobuf/spec.proto create mode 100644 protobuf/txs.proto diff --git a/Makefile b/Makefile index 86ad8624a..ffa4a8d41 100644 --- a/Makefile +++ b/Makefile @@ -10,18 +10,18 @@ SHELL := /bin/bash REPO := $(shell pwd) GOFILES_NOVENDOR := $(shell go list -f "{{.Dir}}" ./...) PACKAGES_NOVENDOR := $(shell go list ./...) -LDFLAGS := # Bosmarmot integration testing BOSMARMOT_PROJECT := github.com/monax/bosmarmot BOSMARMOT_GOPATH := ${REPO}/.gopath_bos BOSMARMOT_CHECKOUT := ${BOSMARMOT_GOPATH}/src/${BOSMARMOT_PROJECT} # Protobuf generated go files -PROTO_FILES = $(shell find . -path ./vendor -prune -o -type f -name '*.proto') +PROTO_FILES = $(shell find . -path ./vendor -prune -o -type f -name '*.proto' -print) PROTO_GO_FILES = $(patsubst %.proto, %.pb.go, $(PROTO_FILES)) +PROTO_GO_FILES_REAL = $(shell find . -path ./vendor -prune -o -type f -name '*.pb.go' -print) # Our own Go files containing the compiled bytecode of solidity files as a constant -SOLIDITY_FILES = $(shell find . -path ./vendor -prune -o -type f -name '*.sol') +SOLIDITY_FILES = $(shell find . -path ./vendor -prune -o -type f -name '*.sol' -print) SOLIDITY_GO_FILES = $(patsubst %.sol, %.sol.go, $(SOLIDITY_FILES)) ### Formatting, linting and vetting @@ -71,18 +71,20 @@ megacheck: # Protobuffing .PHONY: protobuf_deps protobuf_deps: - @go get -u github.com/golang/protobuf/protoc-gen-go + @go get -u github.com/gogo/protobuf/protoc-gen-gogo +# @go get -u github.com/golang/protobuf/protoc-gen-go -# Implicit compile rule for GRPC/proto files +# Implicit compile rule for GRPC/proto files (note since pb.go files no longer generated +# in same directory as proto file this just regenerates everything %.pb.go: %.proto - protoc -I ${GOPATH}/src ${REPO}/$< --go_out=plugins=grpc:${GOPATH}/src + protoc -I vendor -I protobuf $< --gogo_out=plugins=grpc:${GOPATH}/src .PHONY: protobuf protobuf: $(PROTO_GO_FILES) .PHONY: clean_protobuf clean_protobuf: - @rm -f $(PROTO_GO_FILES) + @rm -f $(PROTO_GO_FILES_REAL) ### Dependency management for github.com/hyperledger/burrow # erase vendor wipes the full vendor directory @@ -117,11 +119,11 @@ commit_hash: # build all targets in github.com/hyperledger/burrow .PHONY: build -build: check build_db build_client +build: check build_db # build all targets in github.com/hyperledger/burrow with checks for race conditions .PHONY: build_race -build_race: check build_race_db build_race_client +build_race: check build_race_db # build burrow .PHONY: build_db @@ -134,23 +136,11 @@ build_db: commit_hash install_db: build_db cp ${REPO}/bin/burrow ${GOPATH}/bin/burrow -# build burrow-client -.PHONY: build_client -build_client: commit_hash - go build -ldflags "-extldflags '-static' \ - -X github.com/hyperledger/burrow/project.commit=$(shell cat commit_hash.txt)" \ - -o ${REPO}/bin/burrow-client ./client/cmd/burrow-client - # build burrow with checks for race conditions .PHONY: build_race_db build_race_db: go build -race -o ${REPO}/bin/burrow ./cmd/burrow -# build burrow-client with checks for race conditions -.PHONY: build_race_client -build_race_client: - go build -race -o ${REPO}/bin/burrow-client ./client/cmd/burrow-client - # Get the Bosmarmot code .PHONY: bos bos: ./scripts/deps/bos.sh @@ -185,15 +175,13 @@ test: check test_keys: build_db burrow_bin="${REPO}/bin/burrow" keys/test.sh -rpc/test/strange_loop.go: rpc/test/strange_loop.sol +rpc/test/strange_loop.go: integration/rpctest @rpc/test/strange_loop.sh +# Go will attempt to run separate packages in parallel .PHONY: test_integration test_integration: test_keys - @go test -tags integration ./rpc/rpcevents/integration - @go test -tags integration ./rpc/rpctransactor/integration - @go test -tags integration ./rpc/v0/integration - @go test -tags integration ./rpc/tm/integration + @go test -v -tags integration ./integration/... # Run integration test from bosmarmot (separated from other integration tests so we can # make exception when this test fails when we make a breaking change in Burrow) diff --git a/protobuf/acm.proto b/protobuf/acm.proto new file mode 100644 index 000000000..8a52a277d --- /dev/null +++ b/protobuf/acm.proto @@ -0,0 +1,31 @@ +syntax = 'proto3'; + +package acm; + +option go_package = "github.com/hyperledger/burrow/acm"; + +import "github.com/gogo/protobuf/gogoproto/gogo.proto"; + +import "permission.proto"; +import "crypto.proto"; + +// Enable custom Marshal method. +option (gogoproto.marshaler_all) = true; +// Enable custom Unmarshal method. +option (gogoproto.unmarshaler_all) = true; +// Enable custom Size method (Required by Marshal and Unmarshal). +option (gogoproto.sizer_all) = true; +// Enable registration with golang/protobuf for the grpc-gateway. +option (gogoproto.goproto_registration) = true; +// Enable generation of XXX_MessageName methods for grpc-go/status. +option (gogoproto.messagename_all) = true; + +message ConcreteAccount { + option (gogoproto.goproto_stringer) = false; + bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false]; + crypto.PublicKey PublicKey = 2 [(gogoproto.nullable) = false]; + uint64 Sequence = 3; + uint64 Balance = 4; + bytes Code = 5 [(gogoproto.customtype) = "Bytecode", (gogoproto.nullable) = false]; + permission.AccountPermissions Permissions = 6 [(gogoproto.nullable) = false]; +} \ No newline at end of file diff --git a/protobuf/crypto.proto b/protobuf/crypto.proto new file mode 100644 index 000000000..425236f4c --- /dev/null +++ b/protobuf/crypto.proto @@ -0,0 +1,29 @@ +syntax = 'proto3'; + +package crypto; + +option go_package = "github.com/hyperledger/burrow/crypto"; + +import "github.com/gogo/protobuf/gogoproto/gogo.proto"; + +option (gogoproto.marshaler_all) = true; +option (gogoproto.unmarshaler_all) = true; +option (gogoproto.sizer_all) = true; +option (gogoproto.goproto_registration) = true; +option (gogoproto.messagename_all) = true; + +// PublicKey +message PublicKey { + option (gogoproto.goproto_stringer) = false; + uint32 CurveType = 1 [(gogoproto.casttype) = "CurveType"]; + bytes PublicKey = 2; +} + +message PrivateKey { + option (gogoproto.goproto_stringer) = false; + option (gogoproto.goproto_getters) = false; + uint32 CurveType = 1 [(gogoproto.casttype) = "CurveType"]; + // Note may need initialisation + bytes PublicKey = 2; + bytes PrivateKey = 3; +} diff --git a/protobuf/errors.proto b/protobuf/errors.proto new file mode 100644 index 000000000..6f81e457b --- /dev/null +++ b/protobuf/errors.proto @@ -0,0 +1,24 @@ +syntax = "proto3"; + +package errors; + +option go_package = "github.com/hyperledger/burrow/execution/errors"; + +import "github.com/gogo/protobuf/gogoproto/gogo.proto"; + +// Enable custom Marshal method. +option (gogoproto.marshaler_all) = true; +// Enable custom Unmarshal method. +option (gogoproto.unmarshaler_all) = true; +// Enable custom Size method (Required by Marshal and Unmarshal). +option (gogoproto.sizer_all) = true; +// Enable registration with golang/protobuf for the grpc-gateway. +option (gogoproto.goproto_registration) = true; +// Enable generation of XXX_MessageName methods for grpc-go/status. +option (gogoproto.messagename_all) = true; + +message Exception { + option (gogoproto.goproto_stringer) = false; + uint32 Code = 1 [(gogoproto.casttype) = "Code"]; + string Exception = 2; +} diff --git a/protobuf/exec.proto b/protobuf/exec.proto new file mode 100644 index 000000000..6eb935117 --- /dev/null +++ b/protobuf/exec.proto @@ -0,0 +1,149 @@ +syntax = 'proto3'; + +package exec; + +option go_package = "github.com/hyperledger/burrow/execution/exec"; + +import "github.com/gogo/protobuf/gogoproto/gogo.proto"; +import "github.com/tendermint/abci/types/types.proto"; + +import "errors.proto"; +import "names.proto"; +import "txs.proto"; +import "permission.proto"; + +option (gogoproto.marshaler_all) = true; +option (gogoproto.unmarshaler_all) = true; +option (gogoproto.sizer_all) = true; +option (gogoproto.goproto_registration) = true; +option (gogoproto.messagename_all) = true; + +message BlockExecution { + // The height of this block + uint64 Height = 1; + // TODO: reintroduce this when upstream merges: https://github.com/tendermint/tendermint/pull/1987 +// types.Header BlockHeader = 2; + BlockHeader BlockHeader = 2; + repeated TxExecution TxExecutions = 3; +} + +message BlockHeader { + string JSON = 1; + int32 NumTxs = 2; +} + +message TxExecution { + option (gogoproto.sizer) = true; + option (gogoproto.marshaler) = true; + option (gogoproto.unmarshaler) = true; + // Transaction type + uint32 TxType = 2 [(gogoproto.casttype) = "github.com/hyperledger/burrow/txs/payload.Type"]; + // The hash of the transaction that caused this event to be generated + bytes TxHash = 3 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false]; + // The block height at which this Tx was included + uint64 Height = 4; + // The index of this transaction within the block + uint64 Index = 5; + // Signed Tx that triggered this execution + txs.Envelope Envelope = 6 [(gogoproto.customtype) = "github.com/hyperledger/burrow/txs.Envelope"]; + // Execution events + repeated Event Events = 7; + // The execution results + Result Result = 8; + // The transaction receipt + txs.Receipt Receipt = 9; + // If execution was an exception + errors.Exception Exception = 10; +} + +message Header { + option (gogoproto.goproto_stringer) = false; + option (gogoproto.sizer) = true; + option (gogoproto.marshaler) = true; + option (gogoproto.unmarshaler) = true; + // Transaction type + uint32 TxType = 1 [(gogoproto.casttype) = "github.com/hyperledger/burrow/txs/payload.Type"]; + // The hash of the transaction that caused this event to be generated + bytes TxHash = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false]; + // The type of event + uint32 EventType = 3 [(gogoproto.casttype) = "EventType"]; + // EventID published with event + string EventID = 4; + // The block height at which this event was emitted + uint64 Height = 5; + // The index of this event relative to other events generated by the same transaction + uint64 Index = 6; + // If event is exception + errors.Exception Exception = 7; +} + +message Event { + option (gogoproto.sizer) = true; + option (gogoproto.marshaler) = true; + option (gogoproto.unmarshaler) = true; + option (gogoproto.goproto_stringer) = false; + Header Header = 1; + InputEvent Input = 2; + OutputEvent Output = 3; + CallEvent Call = 4; + LogEvent Log = 5; +} + +// Could structure this further if needed - sum type of various results relevant to different transaction types +message Result { + option (gogoproto.sizer) = true; + option (gogoproto.marshaler) = true; + option (gogoproto.unmarshaler) = true; + // EVM execution return + bytes Return = 1; + // Gas used in computation + uint64 GasUsed = 2; + // Name entry created + names.Entry NameEntry = 3; + // Permission update performed + permission.PermArgs PermArgs = 4; +} + +message LogEvent { + option (gogoproto.sizer) = true; + option (gogoproto.marshaler) = true; + option (gogoproto.unmarshaler) = true; + bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false]; + bytes Data = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false]; + repeated bytes Topics = 3 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.Word256", (gogoproto.nullable) = false]; +} + +message CallEvent { + option (gogoproto.sizer) = true; + option (gogoproto.marshaler) = true; + option (gogoproto.unmarshaler) = true; + CallData CallData = 1; + bytes Origin = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false]; + uint64 StackDepth = 3; + bytes Return = 4 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false]; +} + +message InputEvent { + option (gogoproto.sizer) = true; + option (gogoproto.marshaler) = true; + option (gogoproto.unmarshaler) = true; + bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false]; +} + +message OutputEvent { + option (gogoproto.sizer) = true; + option (gogoproto.marshaler) = true; + option (gogoproto.unmarshaler) = true; + bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false]; +} + +message CallData { + option (gogoproto.sizer) = true; + option (gogoproto.marshaler) = true; + option (gogoproto.unmarshaler) = true; + bytes Caller = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false]; + bytes Callee = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false]; + bytes Data = 3 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false]; + uint64 Value = 4; + uint64 Gas = 5; +} diff --git a/protobuf/keys.proto b/protobuf/keys.proto new file mode 100644 index 000000000..caf39d37d --- /dev/null +++ b/protobuf/keys.proto @@ -0,0 +1,141 @@ +syntax = "proto3"; + +option go_package = "github.com/hyperledger/burrow/keys"; + +package keys; + +import "github.com/gogo/protobuf/gogoproto/gogo.proto"; + +option (gogoproto.marshaler_all) = true; +option (gogoproto.unmarshaler_all) = true; +option (gogoproto.sizer_all) = true; +option (gogoproto.goproto_registration) = true; +option (gogoproto.messagename_all) = true; + +service Keys { + rpc GenerateKey(GenRequest) returns (GenResponse); + rpc PublicKey(PubRequest) returns (PubResponse); + rpc Sign(SignRequest) returns (SignResponse); + rpc Verify(VerifyRequest) returns (VerifyResponse); + rpc Import(ImportRequest) returns (ImportResponse); + rpc ImportJSON(ImportJSONRequest) returns (ImportResponse); + rpc Export(ExportRequest) returns (ExportResponse); + rpc Hash(HashRequest) returns (HashResponse); + rpc RemoveName(RemoveNameRequest) returns (RemoveNameResponse); + rpc List(ListRequest) returns (ListResponse); + rpc AddName(AddNameRequest) returns (AddNameResponse); +} + +// Some empty types we may define later + +message ListRequest { + +} + +message VerifyResponse { + +} + +message RemoveNameResponse { + +} + +message AddNameResponse { + +} + +message RemoveNameRequest { + string KeyName = 1; +} + + +message GenRequest { + string Passphrase = 1; + string CurveType = 2; + string KeyName = 3; +} + +message GenResponse { + string Address = 1; +} + +message PubRequest { + string Address = 1; + string Name = 2; +} + +message PubResponse { + bytes PublicKey = 1; + string CurveType = 2; +} + +message ImportJSONRequest { + string Passphrase = 1; + string JSON = 2; +} + +message ImportResponse { + string Address = 1; +} + +message ImportRequest { + string Passphrase = 1; + string Name = 2; + string CurveType = 3; + bytes KeyBytes = 4; +} + +message ExportRequest { + string Passphrase = 1; + string Name = 2; + string Address = 3; +} + +message ExportResponse { + bytes Publickey = 1; + bytes Privatekey = 2; + bytes Address = 3; + string CurveType = 4; +} + +message SignRequest { + string Passphrase = 1; + string Address = 2; + string Name = 3; + bytes Message = 4; +} + +message SignResponse { + bytes Signature = 1; + string CurveType = 2; +} + +message VerifyRequest { + string CurveType = 1; + bytes PublicKey = 2; + bytes Message = 3; + bytes Signature = 4; +} + +message HashRequest { + string Hashtype = 1; + bytes Message = 2; +} + +message HashResponse { + string Hash = 1; +} + +message KeyID { + string Address = 1; + string KeyName = 2; +} + +message ListResponse { + repeated KeyID key = 1; +} + +message AddNameRequest { + string Keyname = 1; + string Address = 2; +} diff --git a/protobuf/names.proto b/protobuf/names.proto new file mode 100644 index 000000000..0be792b2d --- /dev/null +++ b/protobuf/names.proto @@ -0,0 +1,33 @@ +syntax = 'proto3'; + +package names; + +option go_package = "github.com/hyperledger/burrow/execution/names"; + +import "github.com/gogo/protobuf/gogoproto/gogo.proto"; + +// Enable custom Marshal method. +option (gogoproto.marshaler_all) = true; +// Enable custom Unmarshal method. +option (gogoproto.unmarshaler_all) = true; +// Enable custom Size method (Required by Marshal and Unmarshal). +option (gogoproto.sizer_all) = true; +// Enable registration with golang/protobuf for the grpc-gateway. +option (gogoproto.goproto_registration) = true; +// Enable generation of XXX_MessageName methods for grpc-go/status. +option (gogoproto.messagename_all) = true; + +// NameReg provides a global key value store based on Name, Data pairs that are subject to expiry and ownership by an +// account. +message Entry { + option (gogoproto.goproto_stringer) = false; + // registered name for the entry + string Name = 1; + // address that created the entry + bytes Owner = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false]; + // data to store under this name + string Data = 3; + // block at which this entry expires + uint64 Expires = 4; +} + diff --git a/protobuf/payload.proto b/protobuf/payload.proto new file mode 100644 index 000000000..1e75fdf40 --- /dev/null +++ b/protobuf/payload.proto @@ -0,0 +1,123 @@ +syntax = 'proto3'; + +option go_package = "github.com/hyperledger/burrow/txs/payload"; + +import "github.com/gogo/protobuf/gogoproto/gogo.proto"; + +import "permission.proto"; +import "spec.proto"; + +package payload; + +// Enable custom Marshal method. +option (gogoproto.marshaler_all) = true; +// Enable custom Unmarshal method. +option (gogoproto.unmarshaler_all) = true; +// Enable custom Size method (Required by Marshal and Unmarshal). +option (gogoproto.sizer_all) = true; +// Enable registration with golang/protobuf for the grpc-gateway. +option (gogoproto.goproto_registration) = true; +// Enable generation of XXX_MessageName methods for grpc-go/status. +option (gogoproto.messagename_all) = true; + +message AnyPayload { + CallTx CallTx = 1; + SendTx SendTx = 2; + NameTx NameTx = 3; + PermissionsTx PermissionsTx = 4; + GovernanceTx GovernanceTx = 5; +} + +// An input to a transaction that may carry an Amount as a charge and whose sequence number must be one greater than +// that associated with the account at Address at the time of being received +message TxInput { + option (gogoproto.goproto_stringer) = false; + // The address from which this input flows + bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false]; + // The amount of native token to transfer from the input address + uint64 Amount = 2; + // The sequence number that this transaction will induce (i.e. one greater than the input account's current sequence) + uint64 Sequence = 3; +} + +// An output from a transaction that may carry an amount as a charge +message TxOutput { + option (gogoproto.goproto_stringer) = false; + // The address to which this output flows + bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false]; + // The amount of native token to transfer to the output address + uint64 Amount = 2; +} + +// A instruction to run smart contract code in the EVM +message CallTx { + option (gogoproto.goproto_stringer) = false; + // The caller's input + TxInput Input = 1; + // The contract address to call or nil if we are creating a contract + bytes Address = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address"]; + // The upper bound on the amount of gas (and therefore EVM execution steps) this CallTx may generate + uint64 GasLimit = 3; + // Fee to offer validators for processing transaction + uint64 Fee = 4; + // EVM bytecode payload + bytes Data = 5 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false]; + +} + +// A payment between two sets of parties +message SendTx { + option (gogoproto.goproto_stringer) = false; + option (gogoproto.goproto_getters) = false; + // The payers + repeated TxInput Inputs = 1; + // The payees + repeated TxOutput Outputs = 2; +} + +// An update to the on-chain permissions +message PermissionsTx { + option (gogoproto.goproto_stringer) = false; + // The permission moderator + TxInput Input = 1; + // The modified permissions + permission.PermArgs PermArgs = 2 [(gogoproto.nullable) = false]; +} + +// A request to claim a globally unique name across the entire chain with some optional data storage leased for a fee +message NameTx { + option (gogoproto.goproto_stringer) = false; + // The name updater + TxInput Input = 1; + // The name to update or create + string Name = 2; + // The data to store against the name + string Data = 3; + // The fee to provide that will determine the lenght of the name lease + uint64 Fee = 4; +} + +message BondTx { + option (gogoproto.goproto_stringer) = false; + option (gogoproto.goproto_getters) = false; + + repeated TxInput Inputs = 1; + repeated TxOutput UnbondTo = 2; +} + +message UnbondTx { + option (gogoproto.goproto_stringer) = false; + option (gogoproto.goproto_getters) = false; + + TxInput Input = 1; + bytes Address = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false]; + uint64 Height = 3; +} + +message GovernanceTx { + option (gogoproto.goproto_stringer) = false; + option (gogoproto.goproto_getters) = false; + + repeated TxInput Inputs = 1; + repeated spec.TemplateAccount AccountUpdates = 2 [(gogoproto.nullable) = true]; +} diff --git a/protobuf/permission.proto b/protobuf/permission.proto new file mode 100644 index 000000000..d7ba52af5 --- /dev/null +++ b/protobuf/permission.proto @@ -0,0 +1,39 @@ +syntax = 'proto2'; + +package permission; + +option go_package = "github.com/hyperledger/burrow/permission"; + +import "github.com/gogo/protobuf/gogoproto/gogo.proto"; + +// Enable custom Marshal method. +option (gogoproto.marshaler_all) = true; +// Enable custom Unmarshal method. +option (gogoproto.unmarshaler_all) = true; +// Enable custom Size method (Required by Marshal and Unmarshal). +option (gogoproto.sizer_all) = true; +// Enable registration with golang/protobuf for the grpc-gateway. +option (gogoproto.goproto_registration) = true; +// Enable generation of XXX_MessageName methods for grpc-go/status. +option (gogoproto.messagename_all) = true; + +message AccountPermissions { + optional BasePermissions Base = 1 [(gogoproto.nullable) = false]; + repeated string Roles = 2; +} + +message BasePermissions { + option (gogoproto.goproto_stringer) = false; + optional uint64 Perms = 1 [(gogoproto.casttype) = "PermFlag", (gogoproto.nullable) = false]; + optional uint64 SetBit = 2 [(gogoproto.casttype) = "PermFlag", (gogoproto.nullable) = false]; +} + +message PermArgs { + option (gogoproto.goproto_unrecognized) = false; + option (gogoproto.goproto_stringer) = false; + optional uint64 PermFlag = 1 [(gogoproto.casttype) = "PermFlag", (gogoproto.nullable) = false]; + optional bytes Address = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address"]; + optional uint64 Permission = 3 [(gogoproto.casttype) = "PermFlag"]; + optional string Role = 4; + optional bool Value = 5; +} diff --git a/protobuf/rpcevents.proto b/protobuf/rpcevents.proto new file mode 100644 index 000000000..39d824196 --- /dev/null +++ b/protobuf/rpcevents.proto @@ -0,0 +1,128 @@ +syntax = 'proto3'; + +option go_package = "github.com/hyperledger/burrow/rpc/rpcevents"; + +import "github.com/gogo/protobuf/gogoproto/gogo.proto"; +import "exec.proto"; + +package rpcevents; + +// Enable custom Marshal method. +option (gogoproto.marshaler_all) = true; +// Enable custom Unmarshal method. +option (gogoproto.unmarshaler_all) = true; +// Enable custom Size method (Required by Marshal and Unmarshal). +option (gogoproto.sizer_all) = true; +// Enable registration with golang/protobuf for the grpc-gateway. +option (gogoproto.goproto_registration) = true; +// Enable generation of XXX_MessageName methods for grpc-go/status. +option (gogoproto.messagename_all) = true; + +//-------------------------------------------------- +// Execution events +service ExecutionEvents { + // Get Blockexecution at particular height + rpc GetBlock (GetBlockRequest) returns (exec.BlockExecution); + // Get BlockExecutions for a range of blocks + rpc GetBlocks (BlocksRequest) returns (stream exec.BlockExecution); + // Get a particular TxExecution + rpc GetTx (GetTxRequest) returns (exec.TxExecution); + // Get TxExecutions for a range of block + rpc GetTxs (BlocksRequest) returns (stream GetTxsResponse); + // GetEvents provides events streaming one block at a time - that is all events emitted in a particular block + // are guaranteed to be delivered in each GetEventsResponse + rpc GetEvents (BlocksRequest) returns (stream GetEventsResponse); +} + +message GetBlockRequest { + // Height of block required + uint64 Height = 1; + // Whether to wait for the block to become available + bool Wait = 2; +} + +message GetTxRequest { + // Height of block required + bytes TxHash = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false]; + // Whether to wait for the block to become available + bool Wait = 2; +} + +message BlocksRequest { + BlockRange BlockRange = 1; + // Specify a query on which to match the tags of events. + // Tag | Match type | Values + // ----------------------------------------- + // All events + // ----------------------------------------- + // TxType | String | "UnknownTx", "SendTx", "CallTx", "NameTx", "BondTx", "UnbondTx", "PermissionsTx", "GovernanceTx" + // TxHash | String | bytes + // EventType | String | "CallEvent", "LogEvent", "AccountInputEvent", "AccountOutputEvent" + // EventID | String | string + // Height | Integer | uint64 + // Index | Integer | uint64 + // MessageType | String | Go type name + // ----------------------------------------- + // Log event + // ----------------------------------------- + // Address | String | Address (hex) + // Log<0-4> | String | Word256 (hex) + // Log<0-4>Text | String | string (trimmed) + // ----------------------------------------- + // Call event + // ----------------------------------------- + // Origin | String | Address (hex) + // Callee | String | Address (hex) + // Caller | String | Address (hex) + // Value | Integer | uint64 + // Gas | Integer | uint64 + // StackDepth | Integer | uint64 + // Exception | String | string + // ----------------------------------------- + // Tx event (input/output) + // ----------------------------------------- + // Exception | String | string + // + // For example: + // EventType = 'LogEvent' AND EventID CONTAINS 'bar' AND TxHash = '020304' AND Height >= 34 AND Index < 3 AND Address = 'DEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF' + string Query = 2; +} + +message GetEventsResponse { + uint64 Height = 1; + repeated exec.Event Events = 2; +} + +message GetTxsResponse { + uint64 Height = 1; + repeated exec.TxExecution TxExecutions = 2; +} + +message Bound { + BoundType Type = 1; + uint64 Index = 2; + enum BoundType { + // Index is absolute index of an item + ABSOLUTE = 0; + // Index is an offset relative to last item + RELATIVE = 1; + // The first block + FIRST = 2; + // Ignore provided index and evaluate to latest index + LATEST = 3; + // Ignore provided index and stream new objects as they are generated + STREAM = 4; + } +} + +// An inclusive range of blocks to include in output +message BlockRange { + // Bounds can be set to: + // absolute: block height + // relative: block height counting back from latest + // latest: latest block when call is processed + // stream: for End keep sending new blocks, for start same as latest + Bound Start = 1; + Bound End = 2; +} + diff --git a/protobuf/rpcquery.proto b/protobuf/rpcquery.proto new file mode 100644 index 000000000..bbb512255 --- /dev/null +++ b/protobuf/rpcquery.proto @@ -0,0 +1,40 @@ +syntax = 'proto3'; + +package rpcquery; + +option go_package = "github.com/hyperledger/burrow/rpc/rpcquery"; + +import "github.com/gogo/protobuf/gogoproto/gogo.proto"; + +import "names.proto"; +import "acm.proto"; + +option (gogoproto.marshaler_all) = true; +option (gogoproto.unmarshaler_all) = true; +option (gogoproto.sizer_all) = true; +option (gogoproto.goproto_registration) = true; +option (gogoproto.messagename_all) = true; + +service Query { + rpc GetAccount (GetAccountParam) returns (acm.ConcreteAccount); + rpc ListAccounts (ListAccountsParam) returns (stream acm.ConcreteAccount); + rpc GetName (GetNameParam) returns (names.Entry); + rpc ListNames (ListNamesParam) returns (stream names.Entry); +} + +message GetAccountParam { + bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false]; +} + +message ListAccountsParam { + string Query = 1; +} + +message GetNameParam { + string Name = 1; +} + +message ListNamesParam { + string Query = 1; +} + diff --git a/protobuf/rpctransact.proto b/protobuf/rpctransact.proto new file mode 100644 index 000000000..b2753a171 --- /dev/null +++ b/protobuf/rpctransact.proto @@ -0,0 +1,80 @@ +syntax = 'proto3'; + +package rpctransact; + +option go_package = "github.com/hyperledger/burrow/rpc/rpctransact"; + +import "github.com/gogo/protobuf/gogoproto/gogo.proto"; + +import "exec.proto"; +import "payload.proto"; +import "txs.proto"; + +// Enable custom Marshal method. +option (gogoproto.marshaler_all) = true; +// Enable custom Unmarshal method. +option (gogoproto.unmarshaler_all) = true; +// Enable custom Size method (Required by Marshal and Unmarshal). +option (gogoproto.sizer_all) = true; +// Enable registration with golang/protobuf for the grpc-gateway. +option (gogoproto.goproto_registration) = true; +// Enable generation of XXX_MessageName methods for grpc-go/status. +option (gogoproto.messagename_all) = true; + +// Transaction Service Definition +service Transact { + // Broadcast a transaction to the mempool - if the transaction is not signed signing will be attempted server-side + // and wait for it to be included in block + rpc BroadcastTxSync (TxEnvelopeParam) returns (exec.TxExecution); + // Broadcast a transaction to the mempool - if the transaction is not signed signing will be attempted server-side + rpc BroadcastTxAsync (TxEnvelopeParam) returns (txs.Receipt); + + // Sign transaction server-side + rpc SignTx (TxEnvelopeParam) returns (TxEnvelope); + // Formulate a transaction from a Payload and retrun the envelop with the Tx bytes ready to sign + rpc FormulateTx (PayloadParam) returns (TxEnvelope); + + // Formulate and sign a CallTx transaction signed server-side and wait for it to be included in a block, retrieving response + rpc CallTxSync (payload.CallTx) returns (exec.TxExecution); + // Formulate and sign a CallTx transaction signed server-side + rpc CallTxAsync (payload.CallTx) returns (txs.Receipt); + // Perform a 'simulated' call of a contract against the current committed EVM state without any changes been saved + // and wait for the transaction to be included in a block + rpc CallTxSim (payload.CallTx) returns (exec.TxExecution); + // Perform a 'simulated' execution of provided code against the current committed EVM state without any changes been saved + rpc CallCodeSim (CallCodeParam) returns (exec.TxExecution); + + // Formulate a SendTx transaction signed server-side and wait for it to be included in a block, retrieving response + rpc SendTxSync (payload.SendTx) returns (exec.TxExecution); + // Formulate and SendTx transaction signed server-side + rpc SendTxAsync (payload.SendTx) returns (txs.Receipt); + + // Formualte a NameTx signed server-side and wait for it to be included in a block returning the registered name + rpc NameTxSync (payload.NameTx) returns (exec.TxExecution); + // Formulate a NameTx signed server-side + rpc NameTxAsync (payload.NameTx) returns (txs.Receipt); +} + +message CallCodeParam { + bytes FromAddress = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false]; + bytes Code = 2; + bytes Data = 3; +} + +message PayloadParam { + payload.CallTx CallTx = 1; + payload.SendTx SendTx = 2; + payload.NameTx NameTx = 3; +} + +message TxEnvelope { + txs.Envelope Envelope = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/txs.Envelope"]; +} + +message TxEnvelopeParam { + // An existing Envelope - either signed or unsigned - if the latter will be signed server-side + txs.Envelope Envelope = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/txs.Envelope"]; + // If no Envelope provided then one will be generated from the provided payload and signed server-side + PayloadParam Payload = 2; +} + diff --git a/protobuf/spec.proto b/protobuf/spec.proto new file mode 100644 index 000000000..7f0c6abec --- /dev/null +++ b/protobuf/spec.proto @@ -0,0 +1,35 @@ +// Needed to proto2 rather than proto3 to get pointer field for PermArg +syntax = 'proto2'; + +option go_package = "github.com/hyperledger/burrow/genesis/spec"; + +import "github.com/gogo/protobuf/gogoproto/gogo.proto"; + +import "crypto.proto"; + +package spec; + +// Enable custom Marshal method. +option (gogoproto.marshaler_all) = true; +// Enable custom Unmarshal method. +option (gogoproto.unmarshaler_all) = true; +// Enable custom Size method (Required by Marshal and Unmarshal). +option (gogoproto.sizer_all) = true; +// Enable registration with golang/protobuf for the grpc-gateway. +option (gogoproto.goproto_registration) = true; +// Enable generation of XXX_MessageName methods for grpc-go/status. +option (gogoproto.messagename_all) = true; + +message TemplateAccount { + option (gogoproto.goproto_unrecognized) = false; + + optional string Name = 1 [(gogoproto.nullable) = false]; + optional bytes Address = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""]; + optional bytes NodeAddress = 3 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""]; + optional crypto.PublicKey PublicKey = 4 [(gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""]; + optional uint64 Amount = 5 [(gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""]; + optional uint64 Power = 6 [(gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""]; + repeated string Permissions = 7 [(gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""]; + repeated string Roles = 8 [(gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""]; +} + diff --git a/protobuf/txs.proto b/protobuf/txs.proto new file mode 100644 index 000000000..b7048d4a7 --- /dev/null +++ b/protobuf/txs.proto @@ -0,0 +1,47 @@ +syntax = 'proto3'; + +option go_package = "github.com/hyperledger/burrow/txs"; + +import "github.com/gogo/protobuf/gogoproto/gogo.proto"; + +import "crypto.proto"; + +package txs; + +// Enable custom Marshal method. +option (gogoproto.marshaler_all) = true; +// Enable custom Unmarshal method. +option (gogoproto.unmarshaler_all) = true; +// Enable custom Size method (Required by Marshal and Unmarshal). +option (gogoproto.sizer_all) = true; +// Enable registration with golang/protobuf for the grpc-gateway. +option (gogoproto.goproto_registration) = true; +// Enable generation of XXX_MessageName methods for grpc-go/status. +option (gogoproto.messagename_all) = true; + +// An envelope contains both the signable Tx and the signatures for each input (in signatories) +message Envelope { + option (gogoproto.goproto_stringer) = false; + repeated Signatory Signatories = 1 [(gogoproto.nullable) = false]; + // Canonical bytes of the Tx ready to be signed + bytes Tx = 2 [(gogoproto.customtype) = "Tx"]; +} + +// Signatory contains signature and one or both of Address and PublicKey to identify the signer +message Signatory { + bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address"]; + crypto.PublicKey PublicKey = 2; + bytes Signature = 3 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Signature", (gogoproto.nullable) = false]; +} + +// BroadcastTx or Transaction receipt +message Receipt { + // Transaction type + uint32 TxType = 1[(gogoproto.casttype) = "github.com/hyperledger/burrow/txs/payload.Type"]; + // The hash of the transaction that caused this event to be generated + bytes TxHash = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false]; + // Whether the transaction creates a contract + bool CreatesContract = 3; + // The address of the contract being called + bytes ContractAddress = 4 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false]; +} From b5762d6541a9e4c2174bfbe1bcfb2dab1fa41e32 Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Wed, 18 Jul 2018 17:28:04 +0100 Subject: [PATCH 10/28] Move account to well-known acm Signed-off-by: Silas Davis --- account/account.go | 324 ------------- account/validator_test.go | 1 - acm/account.go | 241 ++++++++++ {account => acm}/account_test.go | 29 +- acm/acm.go | 3 + acm/acm.pb.go | 528 +++++++++++++++++++++ {account => acm}/bytecode.go | 20 +- {account => acm}/bytecode_test.go | 2 +- {account => acm}/private_account.go | 97 ++-- {account => acm}/state/memory_state.go | 2 +- {account => acm}/state/state.go | 10 +- {account => acm}/state/state_cache.go | 2 +- {account => acm}/state/state_cache_test.go | 8 +- {account => acm}/validator.go | 2 +- acm/validator_test.go | 1 + 15 files changed, 875 insertions(+), 395 deletions(-) delete mode 100644 account/account.go delete mode 100644 account/validator_test.go create mode 100644 acm/account.go rename {account => acm}/account_test.go (79%) create mode 100644 acm/acm.go create mode 100644 acm/acm.pb.go rename {account => acm}/bytecode.go (88%) rename {account => acm}/bytecode_test.go (99%) rename {account => acm}/private_account.go (52%) rename {account => acm}/state/memory_state.go (97%) rename {account => acm}/state/state.go (91%) rename {account => acm}/state/state_cache.go (99%) rename {account => acm}/state/state_cache_test.go (97%) rename {account => acm}/validator.go (99%) create mode 100644 acm/validator_test.go diff --git a/account/account.go b/account/account.go deleted file mode 100644 index a708bb673..000000000 --- a/account/account.go +++ /dev/null @@ -1,324 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package account - -import ( - "encoding/json" - "fmt" - - "github.com/hyperledger/burrow/binary" - "github.com/hyperledger/burrow/crypto" - ptypes "github.com/hyperledger/burrow/permission/types" - "github.com/tendermint/go-amino" -) - -var GlobalPermissionsAddress = crypto.Address(binary.Zero160) - -type Addressable interface { - // Get the 20 byte EVM address of this account - Address() crypto.Address - // Public key from which the Address is derived - PublicKey() crypto.PublicKey -} - -// The default immutable interface to an account -type Account interface { - Addressable - // The value held by this account in terms of the chain-native token - Balance() uint64 - // The EVM byte code held by this account (or equivalently, this contract) - Code() Bytecode - // The sequence number of this account, incremented each time a mutation of the - // Account is persisted to the blockchain state - Sequence() uint64 - // The hash of all the values in this accounts storage (typically the root of some subtree - // in the merkle tree of global storage state) - StorageRoot() []byte - // The permission flags and roles for this account - Permissions() ptypes.AccountPermissions - // Obtain a deterministic serialisation of this account - // (i.e. update order and Go runtime independent) - Encode() ([]byte, error) - // String representation of the account - String() string -} - -type MutableAccount interface { - Account - // Set public key (needed for lazy initialisation), should also set the dependent address - SetPublicKey(pubKey crypto.PublicKey) MutableAccount - // Subtract amount from account balance (will panic if amount is greater than balance) - SubtractFromBalance(amount uint64) (MutableAccount, error) - // Add amount to balance (will panic if amount plus balance is a uint64 overflow) - AddToBalance(amount uint64) (MutableAccount, error) - // Set EVM byte code associated with account - SetCode(code []byte) MutableAccount - // Increment Sequence number by 1 (capturing the current Sequence number as the index for any pending mutations) - IncSequence() MutableAccount - // Set the storage root hash - SetStorageRoot(storageRoot []byte) MutableAccount - // Set account permissions - SetPermissions(permissions ptypes.AccountPermissions) MutableAccount - // Get a pointer this account's AccountPermissions in order to mutate them - MutablePermissions() *ptypes.AccountPermissions - // Create a complete copy of this MutableAccount that is itself mutable - Copy() MutableAccount -} - -// ------------------------------------------------- -// ConcreteAccount - -// ConcreteAccount is the canonical serialisation and bash-in-place object for an Account -type ConcreteAccount struct { - Address crypto.Address - PublicKey crypto.PublicKey - Sequence uint64 - Balance uint64 - Code Bytecode - StorageRoot []byte - Permissions ptypes.AccountPermissions -} - -func NewConcreteAccount(pubKey crypto.PublicKey) ConcreteAccount { - return ConcreteAccount{ - Address: pubKey.Address(), - PublicKey: pubKey, - } -} - -func NewConcreteAccountFromSecret(secret string) ConcreteAccount { - return NewConcreteAccount(crypto.PrivateKeyFromSecret(secret, crypto.CurveTypeEd25519).GetPublicKey()) -} - -// Return as immutable Account -func (acc ConcreteAccount) Account() Account { - return concreteAccountWrapper{&acc} -} - -// Return as mutable MutableAccount -func (acc ConcreteAccount) MutableAccount() MutableAccount { - return concreteAccountWrapper{&acc} -} - -func (acc *ConcreteAccount) Copy() *ConcreteAccount { - accCopy := *acc - return &accCopy -} - -func (acc *ConcreteAccount) String() string { - if acc == nil { - return "Account{nil}" - } - - return fmt.Sprintf("Account{Address: %s; Sequence: %v; PublicKey: %v Balance: %v; CodeBytes: %v; StorageRoot: 0x%X; Permissions: %s}", - acc.Address, acc.Sequence, acc.PublicKey, acc.Balance, len(acc.Code), acc.StorageRoot, acc.Permissions) -} - -// ConcreteAccount -// ------------------------------------------------- -// Conversions -// -// Using the naming convention is this package of 'As' being -// a conversion from Account to and 'From' being conversion -// from to Account. Conversions are done by copying - -// Returns a mutable, serialisable ConcreteAccount by copying from account -func AsConcreteAccount(account Account) *ConcreteAccount { - if account == nil { - return nil - } - // Avoid a copy - if ca, ok := account.(concreteAccountWrapper); ok { - return ca.ConcreteAccount - } - return &ConcreteAccount{ - Address: account.Address(), - PublicKey: account.PublicKey(), - Balance: account.Balance(), - Code: account.Code(), - Sequence: account.Sequence(), - StorageRoot: account.StorageRoot(), - Permissions: account.Permissions(), - } -} - -// Creates an otherwise zeroed Account from an Addressable and returns it as MutableAccount -func FromAddressable(addressable Addressable) MutableAccount { - return ConcreteAccount{ - Address: addressable.Address(), - PublicKey: addressable.PublicKey(), - // Since nil slices and maps compare differently to empty ones - Code: Bytecode{}, - StorageRoot: []byte{}, - Permissions: ptypes.AccountPermissions{ - Roles: []string{}, - }, - }.MutableAccount() -} - -// Returns an immutable account by copying from account -func AsAccount(account Account) Account { - if account == nil { - return nil - } - return AsConcreteAccount(account).Account() -} - -// Returns a MutableAccount by copying from account -func AsMutableAccount(account Account) MutableAccount { - if account == nil { - return nil - } - return AsConcreteAccount(account).MutableAccount() -} - -//---------------------------------------------- -// concreteAccount Wrapper - -// concreteAccountWrapper wraps ConcreteAccount to provide a immutable read-only view -// via its implementation of Account and a mutable implementation via its implementation of -// MutableAccount -type concreteAccountWrapper struct { - *ConcreteAccount `json:"unwrap"` -} - -var _ Account = concreteAccountWrapper{} - -func (caw concreteAccountWrapper) Address() crypto.Address { - return caw.ConcreteAccount.Address -} - -func (caw concreteAccountWrapper) PublicKey() crypto.PublicKey { - return caw.ConcreteAccount.PublicKey -} - -func (caw concreteAccountWrapper) Balance() uint64 { - return caw.ConcreteAccount.Balance -} - -func (caw concreteAccountWrapper) Code() Bytecode { - return caw.ConcreteAccount.Code -} - -func (caw concreteAccountWrapper) Sequence() uint64 { - return caw.ConcreteAccount.Sequence -} - -func (caw concreteAccountWrapper) StorageRoot() []byte { - return caw.ConcreteAccount.StorageRoot -} - -func (caw concreteAccountWrapper) Permissions() ptypes.AccountPermissions { - return caw.ConcreteAccount.Permissions -} - -func (caw concreteAccountWrapper) Encode() ([]byte, error) { - return caw.ConcreteAccount.Encode() -} - -func (caw concreteAccountWrapper) String() string { - return caw.ConcreteAccount.String() -} - -func (caw concreteAccountWrapper) MarshalJSON() ([]byte, error) { - return json.Marshal(caw.ConcreteAccount) -} - -// Account mutation via MutableAccount interface -var _ MutableAccount = concreteAccountWrapper{} - -func (caw concreteAccountWrapper) SetPublicKey(pubKey crypto.PublicKey) MutableAccount { - caw.ConcreteAccount.PublicKey = pubKey - addressFromPubKey := pubKey.Address() - // We don't want the wrong public key to take control of an account so we panic here - if caw.ConcreteAccount.Address != addressFromPubKey { - panic(fmt.Errorf("attempt to set public key of account %s to %v, "+ - "but that public key has address %s", - caw.ConcreteAccount.Address, pubKey, addressFromPubKey)) - } - return caw -} - -func (caw concreteAccountWrapper) SubtractFromBalance(amount uint64) (MutableAccount, error) { - if amount > caw.Balance() { - return nil, fmt.Errorf("insufficient funds: attempt to subtract %v from the balance of %s", - amount, caw.ConcreteAccount) - } - caw.ConcreteAccount.Balance -= amount - return caw, nil -} - -func (caw concreteAccountWrapper) AddToBalance(amount uint64) (MutableAccount, error) { - if binary.IsUint64SumOverflow(caw.Balance(), amount) { - return nil, fmt.Errorf("uint64 overflow: attempt to add %v to the balance of %s", - amount, caw.ConcreteAccount) - } - caw.ConcreteAccount.Balance += amount - return caw, nil -} - -func (caw concreteAccountWrapper) SetCode(code []byte) MutableAccount { - caw.ConcreteAccount.Code = code - return caw -} - -func (caw concreteAccountWrapper) IncSequence() MutableAccount { - caw.ConcreteAccount.Sequence += 1 - return caw -} - -func (caw concreteAccountWrapper) SetStorageRoot(storageRoot []byte) MutableAccount { - caw.ConcreteAccount.StorageRoot = storageRoot - return caw -} - -func (caw concreteAccountWrapper) SetPermissions(permissions ptypes.AccountPermissions) MutableAccount { - caw.ConcreteAccount.Permissions = permissions - return caw -} - -func (caw concreteAccountWrapper) MutablePermissions() *ptypes.AccountPermissions { - return &caw.ConcreteAccount.Permissions -} - -func (caw concreteAccountWrapper) Copy() MutableAccount { - return concreteAccountWrapper{caw.ConcreteAccount.Copy()} -} - -// concreteAccount Wrapper -//---------------------------------------------- -// Encoding/decoding -var cdc = amino.NewCodec() - -func (acc *ConcreteAccount) Encode() ([]byte, error) { - return cdc.MarshalBinary(acc) -} - -func Decode(accBytes []byte) (Account, error) { - ca, err := DecodeConcrete(accBytes) - if err != nil { - return nil, err - } - return ca.Account(), nil -} - -func DecodeConcrete(accBytes []byte) (*ConcreteAccount, error) { - ca := new(ConcreteAccount) - err := cdc.UnmarshalBinary(accBytes, ca) - if err != nil { - return nil, fmt.Errorf("could not convert decoded account to *ConcreteAccount: %v", err) - } - return ca, nil -} diff --git a/account/validator_test.go b/account/validator_test.go deleted file mode 100644 index 0bc76357b..000000000 --- a/account/validator_test.go +++ /dev/null @@ -1 +0,0 @@ -package account diff --git a/acm/account.go b/acm/account.go new file mode 100644 index 000000000..4c3b11700 --- /dev/null +++ b/acm/account.go @@ -0,0 +1,241 @@ +// Copyright 2017 Monax Industries Limited +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package acm + +import ( + "encoding/json" + "fmt" + + "github.com/hyperledger/burrow/binary" + "github.com/hyperledger/burrow/crypto" + "github.com/hyperledger/burrow/event/query" + "github.com/hyperledger/burrow/permission" + "github.com/tendermint/go-amino" +) + +var GlobalPermissionsAddress = crypto.Address(binary.Zero160) + +type Addressable interface { + // Get the 20 byte EVM address of this account + Address() crypto.Address + // Public key from which the Address is derived + PublicKey() crypto.PublicKey +} + +// The default immutable interface to an account +type Account interface { + Addressable + // The value held by this account in terms of the chain-native token + Balance() uint64 + // The EVM byte code held by this account (or equivalently, this contract) + Code() Bytecode + // The sequence number of this account, incremented each time a mutation of the + // Account is persisted to the blockchain state + Sequence() uint64 + // The permission flags and roles for this account + Permissions() permission.AccountPermissions + // Obtain a deterministic serialisation of this account + // (i.e. update order and Go runtime independent) + Encode() ([]byte, error) + // String representation of the account + String() string + // Get tags for this account + Tagged() query.Tagged +} + +// MutableAccount structure +type MutableAccount struct { + concreteAccount *ConcreteAccount +} + +func NewConcreteAccount(pubKey crypto.PublicKey) *ConcreteAccount { + return &ConcreteAccount{ + Address: pubKey.Address(), + PublicKey: pubKey, + } +} + +func NewConcreteAccountFromSecret(secret string) *ConcreteAccount { + return NewConcreteAccount(crypto.PrivateKeyFromSecret(secret, crypto.CurveTypeEd25519).GetPublicKey()) +} + +func (ca ConcreteAccount) Account() Account { + return ca.MutableAccount() +} + +// Wrap a copy of ConcreteAccount in a MutableAccount +func (ca ConcreteAccount) MutableAccount() *MutableAccount { + return &MutableAccount{ + concreteAccount: &ca, + } +} + +func (ca ConcreteAccount) Encode() ([]byte, error) { + return cdc.MarshalBinary(ca) +} + +func DecodeConcrete(accBytes []byte) (*ConcreteAccount, error) { + ca := new(ConcreteAccount) + err := cdc.UnmarshalBinary(accBytes, ca) + if err != nil { + return nil, err + } + return ca, nil +} + +// Conversions +// +// Using the naming convention is this package of 'As' being +// a conversion from Account to and 'From' being conversion +// from to Account. Conversions are done by copying + +// Returns a mutable, serialisable ConcreteAccount by copying from account +func AsConcreteAccount(account Account) *ConcreteAccount { + if account == nil { + return nil + } + return &ConcreteAccount{ + Address: account.Address(), + PublicKey: account.PublicKey(), + Balance: account.Balance(), + Code: account.Code(), + Sequence: account.Sequence(), + Permissions: account.Permissions(), + } +} + +// Creates an otherwise zeroed Account from an Addressable and returns it as MutableAccount +func FromAddressable(addressable Addressable) *MutableAccount { + ca := &ConcreteAccount{ + Address: addressable.Address(), + PublicKey: addressable.PublicKey(), + // Since nil slices and maps compare differently to empty ones + Code: Bytecode{}, + Permissions: permission.AccountPermissions{ + Roles: []string{}, + }, + } + return ca.MutableAccount() +} + +// Returns a MutableAccount by copying from account +func AsMutableAccount(account Account) *MutableAccount { + if account == nil { + return nil + } + return AsConcreteAccount(account).MutableAccount() +} + +func (acc ConcreteAccount) String() string { + return fmt.Sprintf("ConcreteAccount{Address: %s; Sequence: %v; PublicKey: %v Balance: %v; CodeLength: %v; Permissions: %s}", + acc.Address, acc.Sequence, acc.PublicKey, acc.Balance, len(acc.Code), acc.Permissions) +} + +///---- Getter methods +func (acc MutableAccount) Address() crypto.Address { return acc.concreteAccount.Address } +func (acc MutableAccount) PublicKey() crypto.PublicKey { return acc.concreteAccount.PublicKey } +func (acc MutableAccount) Balance() uint64 { return acc.concreteAccount.Balance } +func (acc MutableAccount) Code() Bytecode { return acc.concreteAccount.Code } +func (acc MutableAccount) Sequence() uint64 { return acc.concreteAccount.Sequence } +func (acc MutableAccount) Permissions() permission.AccountPermissions { + return acc.concreteAccount.Permissions +} + +///---- Mutable methods +// Set public key (needed for lazy initialisation), should also set the dependent address +func (acc *MutableAccount) SetPublicKey(publicKey crypto.PublicKey) { + acc.concreteAccount.PublicKey = publicKey +} + +func (acc *MutableAccount) SubtractFromBalance(amount uint64) error { + if amount > acc.Balance() { + return fmt.Errorf("insufficient funds: attempt to subtract %v from the balance of %s", + amount, acc.Address()) + } + acc.concreteAccount.Balance -= amount + return nil +} + +func (acc *MutableAccount) AddToBalance(amount uint64) error { + if binary.IsUint64SumOverflow(acc.Balance(), amount) { + return fmt.Errorf("uint64 overflow: attempt to add %v to the balance of %s", + amount, acc.Address()) + } + acc.concreteAccount.Balance += amount + return nil +} + +func (acc *MutableAccount) SetCode(code []byte) error { + acc.concreteAccount.Code = code + return nil +} + +func (acc *MutableAccount) IncSequence() { + acc.concreteAccount.Sequence++ +} + +func (acc *MutableAccount) SetPermissions(permissions permission.AccountPermissions) error { + acc.concreteAccount.Permissions = permissions + return nil +} + +func (acc *MutableAccount) MutablePermissions() *permission.AccountPermissions { + return &acc.concreteAccount.Permissions +} + +type TaggedAccount struct { + *MutableAccount + query.Tagged +} + +func (acc *MutableAccount) Tagged() query.Tagged { + return &TaggedAccount{ + MutableAccount: acc, + Tagged: query.MustReflectTags(acc), + } +} + +///---- Serialisation methods + +var cdc = amino.NewCodec() + +func (acc MutableAccount) Encode() ([]byte, error) { + return acc.concreteAccount.Encode() +} + +func Decode(accBytes []byte) (*MutableAccount, error) { + ca, err := DecodeConcrete(accBytes) + if err != nil { + return nil, err + } + return &MutableAccount{ + concreteAccount: ca, + }, nil +} + +func (acc MutableAccount) MarshalJSON() ([]byte, error) { + return json.Marshal(acc.concreteAccount) +} +func (acc *MutableAccount) UnmarshalJSON(bytes []byte) error { + err := json.Unmarshal(bytes, &acc.concreteAccount) + if err != nil { + return err + } + return nil +} + +func (acc MutableAccount) String() string { + return fmt.Sprintf("MutableAccount{%s}", acc.concreteAccount.String()) +} diff --git a/account/account_test.go b/acm/account_test.go similarity index 79% rename from account/account_test.go rename to acm/account_test.go index 5e8f0ed3d..af55ec502 100644 --- a/account/account_test.go +++ b/acm/account_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package account +package acm import ( "testing" @@ -22,7 +22,7 @@ import ( "fmt" "github.com/hyperledger/burrow/crypto" - ptypes "github.com/hyperledger/burrow/permission/types" + "github.com/hyperledger/burrow/permission" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -50,21 +50,21 @@ func TestAddress(t *testing.T) { func TestDecodeConcrete(t *testing.T) { concreteAcc := NewConcreteAccountFromSecret("Super Semi Secret") - concreteAcc.Permissions = ptypes.AccountPermissions{ - Base: ptypes.BasePermissions{ - Perms: ptypes.SetGlobal, - SetBit: ptypes.SetGlobal, + concreteAcc.Permissions = permission.AccountPermissions{ + Base: permission.BasePermissions{ + Perms: permission.SetGlobal, + SetBit: permission.SetGlobal, }, Roles: []string{"bums"}, } - acc := concreteAcc.Account() + acc := concreteAcc encodedAcc, err := acc.Encode() require.NoError(t, err) concreteAccOut, err := DecodeConcrete(encodedAcc) require.NoError(t, err) - assert.Equal(t, concreteAcc, *concreteAccOut) + assert.Equal(t, concreteAcc, concreteAccOut) concreteAccOut, err = DecodeConcrete([]byte("flungepliffery munknut tolopops")) assert.Error(t, err) } @@ -76,7 +76,7 @@ func TestDecode(t *testing.T) { require.NoError(t, err) accOut, err := Decode(encodedAcc) require.NoError(t, err) - assert.Equal(t, concreteAcc, *AsConcreteAccount(accOut)) + assert.Equal(t, concreteAcc, AsConcreteAccount(accOut)) accOut, err = Decode([]byte("flungepliffery munknut tolopops")) require.Error(t, err) @@ -86,12 +86,19 @@ func TestDecode(t *testing.T) { func TestMarshalJSON(t *testing.T) { concreteAcc := NewConcreteAccountFromSecret("Super Semi Secret") concreteAcc.Code = []byte{60, 23, 45} + concreteAcc.Permissions = permission.AccountPermissions{ + Base: permission.BasePermissions{ + Perms: permission.AllPermFlags, + }, + } + concreteAcc.Sequence = 4 + concreteAcc.Balance = 10 acc := concreteAcc.Account() bs, err := json.Marshal(acc) expected := fmt.Sprintf(`{"Address":"%s","PublicKey":{"CurveType":"ed25519","PublicKey":"%s"},`+ - `"Sequence":0,"Balance":0,"Code":"3C172D","StorageRoot":null,`+ - `"Permissions":{"Base":{"Perms":0,"SetBit":0},"Roles":null}}`, + `"Sequence":4,"Balance":10,"Code":"3C172D",`+ + `"Permissions":{"Base":{"Perms":16383,"SetBit":0}}}`, concreteAcc.Address, concreteAcc.PublicKey) assert.Equal(t, expected, string(bs)) assert.NoError(t, err) diff --git a/acm/acm.go b/acm/acm.go new file mode 100644 index 000000000..9b84345be --- /dev/null +++ b/acm/acm.go @@ -0,0 +1,3 @@ +// The acm package contains code relating to accounts and account state +// the abbreviation probably derives from 'ACcount Management' +package acm diff --git a/acm/acm.pb.go b/acm/acm.pb.go new file mode 100644 index 000000000..98896e1db --- /dev/null +++ b/acm/acm.pb.go @@ -0,0 +1,528 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: acm.proto + +/* + Package acm is a generated protocol buffer package. + + It is generated from these files: + acm.proto + + It has these top-level messages: + ConcreteAccount +*/ +package acm + +import proto "github.com/gogo/protobuf/proto" +import golang_proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" +import _ "github.com/gogo/protobuf/gogoproto" +import permission "github.com/hyperledger/burrow/permission" +import crypto "github.com/hyperledger/burrow/crypto" + +import github_com_hyperledger_burrow_crypto "github.com/hyperledger/burrow/crypto" + +import io "io" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = golang_proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package + +type ConcreteAccount struct { + Address github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,1,opt,name=Address,proto3,customtype=github.com/hyperledger/burrow/crypto.Address" json:"Address"` + PublicKey crypto.PublicKey `protobuf:"bytes,2,opt,name=PublicKey" json:"PublicKey"` + Sequence uint64 `protobuf:"varint,3,opt,name=Sequence,proto3" json:"Sequence,omitempty"` + Balance uint64 `protobuf:"varint,4,opt,name=Balance,proto3" json:"Balance,omitempty"` + Code Bytecode `protobuf:"bytes,5,opt,name=Code,proto3,customtype=Bytecode" json:"Code"` + Permissions permission.AccountPermissions `protobuf:"bytes,6,opt,name=Permissions" json:"Permissions"` +} + +func (m *ConcreteAccount) Reset() { *m = ConcreteAccount{} } +func (*ConcreteAccount) ProtoMessage() {} +func (*ConcreteAccount) Descriptor() ([]byte, []int) { return fileDescriptorAcm, []int{0} } + +func (m *ConcreteAccount) GetPublicKey() crypto.PublicKey { + if m != nil { + return m.PublicKey + } + return crypto.PublicKey{} +} + +func (m *ConcreteAccount) GetSequence() uint64 { + if m != nil { + return m.Sequence + } + return 0 +} + +func (m *ConcreteAccount) GetBalance() uint64 { + if m != nil { + return m.Balance + } + return 0 +} + +func (m *ConcreteAccount) GetPermissions() permission.AccountPermissions { + if m != nil { + return m.Permissions + } + return permission.AccountPermissions{} +} + +func (*ConcreteAccount) XXX_MessageName() string { + return "acm.ConcreteAccount" +} +func init() { + proto.RegisterType((*ConcreteAccount)(nil), "acm.ConcreteAccount") + golang_proto.RegisterType((*ConcreteAccount)(nil), "acm.ConcreteAccount") +} +func (m *ConcreteAccount) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ConcreteAccount) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + dAtA[i] = 0xa + i++ + i = encodeVarintAcm(dAtA, i, uint64(m.Address.Size())) + n1, err := m.Address.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n1 + dAtA[i] = 0x12 + i++ + i = encodeVarintAcm(dAtA, i, uint64(m.PublicKey.Size())) + n2, err := m.PublicKey.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n2 + if m.Sequence != 0 { + dAtA[i] = 0x18 + i++ + i = encodeVarintAcm(dAtA, i, uint64(m.Sequence)) + } + if m.Balance != 0 { + dAtA[i] = 0x20 + i++ + i = encodeVarintAcm(dAtA, i, uint64(m.Balance)) + } + dAtA[i] = 0x2a + i++ + i = encodeVarintAcm(dAtA, i, uint64(m.Code.Size())) + n3, err := m.Code.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n3 + dAtA[i] = 0x32 + i++ + i = encodeVarintAcm(dAtA, i, uint64(m.Permissions.Size())) + n4, err := m.Permissions.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n4 + return i, nil +} + +func encodeVarintAcm(dAtA []byte, offset int, v uint64) int { + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return offset + 1 +} +func (m *ConcreteAccount) Size() (n int) { + var l int + _ = l + l = m.Address.Size() + n += 1 + l + sovAcm(uint64(l)) + l = m.PublicKey.Size() + n += 1 + l + sovAcm(uint64(l)) + if m.Sequence != 0 { + n += 1 + sovAcm(uint64(m.Sequence)) + } + if m.Balance != 0 { + n += 1 + sovAcm(uint64(m.Balance)) + } + l = m.Code.Size() + n += 1 + l + sovAcm(uint64(l)) + l = m.Permissions.Size() + n += 1 + l + sovAcm(uint64(l)) + return n +} + +func sovAcm(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n +} +func sozAcm(x uint64) (n int) { + return sovAcm(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *ConcreteAccount) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowAcm + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ConcreteAccount: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ConcreteAccount: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowAcm + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthAcm + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Address.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PublicKey", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowAcm + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthAcm + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.PublicKey.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Sequence", wireType) + } + m.Sequence = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowAcm + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Sequence |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Balance", wireType) + } + m.Balance = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowAcm + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Balance |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Code", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowAcm + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthAcm + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Code.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Permissions", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowAcm + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthAcm + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Permissions.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipAcm(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthAcm + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipAcm(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowAcm + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowAcm + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowAcm + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + iNdEx += length + if length < 0 { + return 0, ErrInvalidLengthAcm + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowAcm + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipAcm(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} + +var ( + ErrInvalidLengthAcm = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowAcm = fmt.Errorf("proto: integer overflow") +) + +func init() { proto.RegisterFile("acm.proto", fileDescriptorAcm) } +func init() { golang_proto.RegisterFile("acm.proto", fileDescriptorAcm) } + +var fileDescriptorAcm = []byte{ + // 330 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x91, 0xbd, 0x4e, 0xfb, 0x30, + 0x14, 0xc5, 0xeb, 0x36, 0xff, 0x7e, 0xb8, 0x95, 0xfe, 0xc5, 0x53, 0xd4, 0xc1, 0x2d, 0x88, 0xa1, + 0x03, 0x24, 0x12, 0x1f, 0x42, 0x62, 0x6b, 0x2a, 0xb1, 0x20, 0xa1, 0x2a, 0x6c, 0x6c, 0x89, 0x73, + 0x49, 0x23, 0x35, 0x71, 0x70, 0x6c, 0xa1, 0xbc, 0x09, 0x23, 0x8f, 0x82, 0x98, 0x3a, 0x32, 0x33, + 0x54, 0xa8, 0x7d, 0x11, 0x54, 0xe3, 0x96, 0x4c, 0x6c, 0x39, 0xf9, 0xdd, 0x73, 0xef, 0xd1, 0x31, + 0xee, 0x04, 0x2c, 0x75, 0x72, 0xc1, 0x25, 0x27, 0x8d, 0x80, 0xa5, 0x83, 0xd3, 0x38, 0x91, 0x73, + 0x15, 0x3a, 0x8c, 0xa7, 0x6e, 0xcc, 0x63, 0xee, 0x6a, 0x16, 0xaa, 0x47, 0xad, 0xb4, 0xd0, 0x5f, + 0x3f, 0x9e, 0x41, 0x3f, 0x07, 0x91, 0x26, 0x45, 0x91, 0xf0, 0xcc, 0xfc, 0xe9, 0x31, 0x51, 0xe6, + 0xd2, 0xf0, 0xa3, 0xf7, 0x3a, 0xfe, 0x3f, 0xe5, 0x19, 0x13, 0x20, 0x61, 0xc2, 0x18, 0x57, 0x99, + 0x24, 0x77, 0xb8, 0x35, 0x89, 0x22, 0x01, 0x45, 0x61, 0xa3, 0x11, 0x1a, 0xf7, 0xbc, 0x8b, 0xe5, + 0x6a, 0x58, 0xfb, 0x5c, 0x0d, 0x4f, 0x2a, 0xb7, 0xe7, 0x65, 0x0e, 0x62, 0x01, 0x51, 0x0c, 0xc2, + 0x0d, 0x95, 0x10, 0xfc, 0xd9, 0x35, 0x8b, 0x8d, 0xd7, 0xdf, 0x2d, 0x21, 0x97, 0xb8, 0x33, 0x53, + 0xe1, 0x22, 0x61, 0xb7, 0x50, 0xda, 0xf5, 0x11, 0x1a, 0x77, 0xcf, 0x0e, 0x1c, 0x33, 0xbc, 0x07, + 0x9e, 0xb5, 0x3d, 0xe2, 0xff, 0x4e, 0x92, 0x01, 0x6e, 0xdf, 0xc3, 0x93, 0x82, 0x8c, 0x81, 0xdd, + 0x18, 0xa1, 0xb1, 0xe5, 0xef, 0x35, 0xb1, 0x71, 0xcb, 0x0b, 0x16, 0xc1, 0x16, 0x59, 0x1a, 0xed, + 0x24, 0x39, 0xc6, 0xd6, 0x94, 0x47, 0x60, 0xff, 0xd3, 0xc9, 0xfb, 0x26, 0x79, 0xdb, 0x2b, 0x25, + 0x30, 0x1e, 0x81, 0xaf, 0x29, 0xb9, 0xc1, 0xdd, 0xd9, 0xbe, 0x98, 0xc2, 0x6e, 0xea, 0x50, 0xd4, + 0xa9, 0x94, 0x65, 0xca, 0xa8, 0x4c, 0x99, 0x84, 0x55, 0xe3, 0xb5, 0xf5, 0xf2, 0x3a, 0xac, 0x79, + 0x57, 0xcb, 0x35, 0x45, 0x1f, 0x6b, 0x8a, 0xbe, 0xd6, 0x14, 0xbd, 0x6d, 0x28, 0x5a, 0x6e, 0x28, + 0x7a, 0x38, 0xfc, 0xbb, 0xad, 0x80, 0xa5, 0x61, 0x53, 0x3f, 0xc2, 0xf9, 0x77, 0x00, 0x00, 0x00, + 0xff, 0xff, 0x5b, 0x02, 0x22, 0xf4, 0xe5, 0x01, 0x00, 0x00, +} diff --git a/account/bytecode.go b/acm/bytecode.go similarity index 88% rename from account/bytecode.go rename to acm/bytecode.go index 01a1cdadd..bb926242e 100644 --- a/account/bytecode.go +++ b/acm/bytecode.go @@ -1,4 +1,4 @@ -package account +package acm import ( "encoding/json" @@ -64,6 +64,24 @@ func (bc *Bytecode) UnmarshalText(text []byte) error { return err } +// Protobuf support +func (bc Bytecode) Marshal() ([]byte, error) { + return bc, nil +} + +func (bc *Bytecode) Unmarshal(data []byte) error { + *bc = data + return nil +} + +func (bc Bytecode) MarshalTo(data []byte) (int, error) { + return copy(data, bc), nil +} + +func (bc Bytecode) Size() int { + return len(bc) +} + // Tokenises the bytecode into opcodes and values func (bc Bytecode) Tokens() ([]string, error) { // Overestimate of capacity in the presence of pushes diff --git a/account/bytecode_test.go b/acm/bytecode_test.go similarity index 99% rename from account/bytecode_test.go rename to acm/bytecode_test.go index 00f1bd0c2..462a4cb71 100644 --- a/account/bytecode_test.go +++ b/acm/bytecode_test.go @@ -1,4 +1,4 @@ -package account +package acm import ( "encoding/json" diff --git a/account/private_account.go b/acm/private_account.go similarity index 52% rename from account/private_account.go rename to acm/private_account.go index 204096c1d..f9cf705d5 100644 --- a/account/private_account.go +++ b/acm/private_account.go @@ -12,11 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -package account +package acm import ( "fmt" + "encoding/json" + "github.com/hyperledger/burrow/crypto" ) @@ -25,80 +27,85 @@ type AddressableSigner interface { crypto.Signer } -type PrivateAccount interface { - AddressableSigner - PrivateKey() crypto.PrivateKey +type PrivateAccount struct { + concretePrivateAccount *ConcretePrivateAccount } -// -type ConcretePrivateAccount struct { - Address crypto.Address - PublicKey crypto.PublicKey - PrivateKey crypto.PrivateKey +func (pa *PrivateAccount) Address() crypto.Address { + return pa.concretePrivateAccount.Address } -type concretePrivateAccountWrapper struct { - *ConcretePrivateAccount `json:"unwrap"` +func (pa *PrivateAccount) PublicKey() crypto.PublicKey { + return pa.concretePrivateAccount.PublicKey } -var _ PrivateAccount = concretePrivateAccountWrapper{} +func (pa *PrivateAccount) Sign(msg []byte) (crypto.Signature, error) { + return pa.concretePrivateAccount.PrivateKey.Sign(msg) +} -func AsConcretePrivateAccount(privateAccount PrivateAccount) *ConcretePrivateAccount { - if privateAccount == nil { - return nil - } - // Avoid a copy - if ca, ok := privateAccount.(concretePrivateAccountWrapper); ok { - return ca.ConcretePrivateAccount - } - return &ConcretePrivateAccount{ - Address: privateAccount.Address(), - PublicKey: privateAccount.PublicKey(), - PrivateKey: privateAccount.PrivateKey(), - } +func (pa PrivateAccount) MarshalJSON() ([]byte, error) { + return json.Marshal(pa.concretePrivateAccount) } -func (cpaw concretePrivateAccountWrapper) Address() crypto.Address { - return cpaw.ConcretePrivateAccount.Address +func (pa *PrivateAccount) UnmarshalJSON(bytes []byte) error { + err := json.Unmarshal(bytes, &pa.concretePrivateAccount) + if err != nil { + return err + } + return nil } -func (cpaw concretePrivateAccountWrapper) PublicKey() crypto.PublicKey { - return cpaw.ConcretePrivateAccount.PublicKey +func (pa *PrivateAccount) PrivateKey() crypto.PrivateKey { + return pa.concretePrivateAccount.PrivateKey } -func (cpaw concretePrivateAccountWrapper) PrivateKey() crypto.PrivateKey { - return cpaw.ConcretePrivateAccount.PrivateKey +func (pa *PrivateAccount) ConcretePrivateAccount() *ConcretePrivateAccount { + cpa := *pa.concretePrivateAccount + return &cpa } -func (cpaw concretePrivateAccountWrapper) String() string { - return cpaw.ConcretePrivateAccount.String() +func (pa *PrivateAccount) String() string { + return fmt.Sprintf("PrivateAccount{%v}", pa.Address()) } -// ConcretePrivateAccount +type ConcretePrivateAccount struct { + Address crypto.Address + PublicKey crypto.PublicKey + PrivateKey crypto.PrivateKey +} -func (pa ConcretePrivateAccount) PrivateAccount() PrivateAccount { - return concretePrivateAccountWrapper{ConcretePrivateAccount: &pa} +func (cpa *ConcretePrivateAccount) String() string { + return fmt.Sprintf("ConcretePrivateAccount{%v}", cpa.Address) } -func (pa ConcretePrivateAccount) Sign(msg []byte) (crypto.Signature, error) { - return pa.PrivateKey.Sign(msg) +func (cpa ConcretePrivateAccount) PrivateAccount() *PrivateAccount { + return &PrivateAccount{ + concretePrivateAccount: &cpa, + } } -func (pa *ConcretePrivateAccount) String() string { - return fmt.Sprintf("ConcretePrivateAccount{%s}", pa.Address) +func PrivateAccountFromPrivateKey(privateKey crypto.PrivateKey) *PrivateAccount { + publicKey := privateKey.GetPublicKey() + return &PrivateAccount{ + concretePrivateAccount: &ConcretePrivateAccount{ + PrivateKey: privateKey, + PublicKey: publicKey, + Address: publicKey.Address(), + }, + } } // Convert slice of ConcretePrivateAccounts to slice of SigningAccounts -func SigningAccounts(concretePrivateAccounts []*ConcretePrivateAccount) []AddressableSigner { +func SigningAccounts(concretePrivateAccounts []*PrivateAccount) []AddressableSigner { signingAccounts := make([]AddressableSigner, len(concretePrivateAccounts)) for i, cpa := range concretePrivateAccounts { - signingAccounts[i] = cpa.PrivateAccount() + signingAccounts[i] = cpa } return signingAccounts } // Generates a new account with private key. -func GeneratePrivateAccount() (PrivateAccount, error) { +func GeneratePrivateAccount() (*PrivateAccount, error) { privateKey, err := crypto.GeneratePrivateKey(nil, crypto.CurveTypeEd25519) if err != nil { return nil, err @@ -112,7 +119,7 @@ func GeneratePrivateAccount() (PrivateAccount, error) { } // Generates a new account with private key from SHA256 hash of a secret -func GeneratePrivateAccountFromSecret(secret string) PrivateAccount { +func GeneratePrivateAccountFromSecret(secret string) *PrivateAccount { privateKey := crypto.PrivateKeyFromSecret(secret, crypto.CurveTypeEd25519) publicKey := privateKey.GetPublicKey() return ConcretePrivateAccount{ @@ -122,7 +129,7 @@ func GeneratePrivateAccountFromSecret(secret string) PrivateAccount { }.PrivateAccount() } -func GeneratePrivateAccountFromPrivateKeyBytes(privKeyBytes []byte) (PrivateAccount, error) { +func PrivateAccountFromPrivateKeyBytes(privKeyBytes []byte) (*PrivateAccount, error) { privateKey, err := crypto.PrivateKeyFromRawBytes(privKeyBytes, crypto.CurveTypeEd25519) if err != nil { return nil, err diff --git a/account/state/memory_state.go b/acm/state/memory_state.go similarity index 97% rename from account/state/memory_state.go rename to acm/state/memory_state.go index 605ecd05e..937430c54 100644 --- a/account/state/memory_state.go +++ b/acm/state/memory_state.go @@ -3,7 +3,7 @@ package state import ( "fmt" - acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/crypto" ) diff --git a/account/state/state.go b/acm/state/state.go similarity index 91% rename from account/state/state.go rename to acm/state/state.go index 95389ad3d..1c2f06a69 100644 --- a/account/state/state.go +++ b/acm/state/state.go @@ -1,10 +1,10 @@ package state import ( - acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/crypto" - ptypes "github.com/hyperledger/burrow/permission/types" + "github.com/hyperledger/burrow/permission" ) type AccountGetter interface { @@ -81,7 +81,7 @@ type IterableReaderWriter interface { Writer } -func GetMutableAccount(getter AccountGetter, address crypto.Address) (acm.MutableAccount, error) { +func GetMutableAccount(getter AccountGetter, address crypto.Address) (*acm.MutableAccount, error) { acc, err := getter.GetAccount(address) if err != nil { return nil, err @@ -98,9 +98,9 @@ func GlobalPermissionsAccount(getter AccountGetter) acm.Account { } // Get global permissions from the account at GlobalPermissionsAddress -func GlobalAccountPermissions(getter AccountGetter) ptypes.AccountPermissions { +func GlobalAccountPermissions(getter AccountGetter) permission.AccountPermissions { if getter == nil { - return ptypes.AccountPermissions{ + return permission.AccountPermissions{ Roles: []string{}, } } diff --git a/account/state/state_cache.go b/acm/state/state_cache.go similarity index 99% rename from account/state/state_cache.go rename to acm/state/state_cache.go index 4daf76874..968f2867b 100644 --- a/account/state/state_cache.go +++ b/acm/state/state_cache.go @@ -19,7 +19,7 @@ import ( "sort" "sync" - acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/crypto" ) diff --git a/account/state/state_cache_test.go b/acm/state/state_cache_test.go similarity index 97% rename from account/state/state_cache_test.go rename to acm/state/state_cache_test.go index 6df18eb92..ef975d820 100644 --- a/account/state/state_cache_test.go +++ b/acm/state/state_cache_test.go @@ -4,11 +4,11 @@ import ( "fmt" "testing" - acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/execution/evm/asm" - ptypes "github.com/hyperledger/burrow/permission/types" + "github.com/hyperledger/burrow/permission" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -289,11 +289,11 @@ func TestStateCache_get(t *testing.T) { func testAccounts() *MemoryState { acc1 := acm.NewConcreteAccountFromSecret("acc1") - acc1.Permissions.Base.Perms = ptypes.AddRole | ptypes.Send + acc1.Permissions.Base.Perms = permission.AddRole | permission.Send acc1.Permissions.Base.SetBit = acc1.Permissions.Base.Perms acc2 := acm.NewConcreteAccountFromSecret("acc2") - acc2.Permissions.Base.Perms = ptypes.AddRole | ptypes.Send + acc2.Permissions.Base.Perms = permission.AddRole | permission.Send acc2.Permissions.Base.SetBit = acc1.Permissions.Base.Perms acc2.Code, _ = acm.NewBytecode(asm.PUSH1, 0x20) diff --git a/account/validator.go b/acm/validator.go similarity index 99% rename from account/validator.go rename to acm/validator.go index 121b76fd2..51027539d 100644 --- a/account/validator.go +++ b/acm/validator.go @@ -1,4 +1,4 @@ -package account +package acm import ( "encoding/json" diff --git a/acm/validator_test.go b/acm/validator_test.go new file mode 100644 index 000000000..512990819 --- /dev/null +++ b/acm/validator_test.go @@ -0,0 +1 @@ +package acm From 5ad47d83d9eba40f1c3170887634837fb9a29cac Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Wed, 18 Jul 2018 17:28:46 +0100 Subject: [PATCH 11/28] Rationalise GRPC, protobuf, integration testing Signed-off-by: Silas Davis --- binary/bytes.go | 22 + binary/integer.go | 16 - binary/word256.go | 32 + blockchain/validators_test.go | 2 +- client/client_do.go | 74 - client/cmd/burrow-client.go | 103 - client/cmd/burrow-client/main.go | 23 - client/cmd/status.go | 48 - client/cmd/transaction.go | 192 - client/methods/call.go | 60 - client/methods/helpers.go | 55 - client/methods/send.go | 58 - client/methods/status.go | 50 - client/mock/client_mock.go | 103 - client/node_client.go | 264 - client/rpc/client.go | 307 -- client/rpc/client_test.go | 170 - client/rpc/client_util.go | 125 - client/websocket_client.go | 210 - client/ws_client.go | 86 - cmd/burrow/commands/configure.go | 4 +- cmd/burrow/commands/keys.go | 38 +- cmd/burrow/commands/spec.go | 2 +- cmd/burrow/commands/start.go | 2 +- cmd/burrow/main.go | 2 +- config/config.go | 1 + consensus/tendermint/abci/app.go | 161 +- consensus/tendermint/events.go | 103 - consensus/tendermint/logger.go | 2 +- consensus/tendermint/tendermint.go | 58 +- .../validator/priv_validator_memory.go | 2 +- core/kernel.go | 98 +- crypto/address.go | 29 + crypto/crypto.go | 2 +- crypto/crypto.pb.go | 555 ++ crypto/private_key.go | 37 +- crypto/public_key.go | 20 +- crypto/public_key_test.go | 30 + crypto/signature.go | 61 +- deployment/config.go | 4 +- event/cache.go | 88 - event/cache_test.go | 98 - event/convention.go | 79 - event/convention_test.go | 39 - event/emitter.go | 41 +- event/emitter_test.go | 27 +- event/pubsub/example_test.go | 23 + event/pubsub/pubsub.go | 330 ++ event/pubsub/pubsub_test.go | 237 + event/query/Makefile | 11 + event/query/builder.go | 263 + event/query/builder_test.go | 52 + event/query/empty.go | 24 +- event/query/empty_test.go | 15 + event/query/parser_test.go | 90 + event/query/query.go | 512 +- event/query/query.peg | 33 + event/query/query.peg.go | 1553 ++++++ event/query/query_test.go | 99 +- event/query/reflect_tagged.go | 99 + event/query/reflect_tagged_test.go | 97 + event/query/tags.go | 126 + event/tags.go | 87 - execution/accounts.go | 51 +- execution/config.go | 8 + execution/errors/errors.go | 43 +- execution/errors/errors.pb.go | 388 +- execution/errors/errors.proto | 13 - execution/errors/errors_test.go | 25 +- execution/errors/vm.go | 4 +- execution/events/call.go | 149 - execution/events/event.go | 121 - execution/events/event_test.go | 92 - execution/events/header.go | 76 - execution/events/key.go | 57 - execution/events/pbevents/events.go | 168 - execution/events/pbevents/events.pb.go | 1403 ----- execution/events/pbevents/events.proto | 177 - execution/events/tx.go | 134 - execution/events/type.go | 47 - execution/evm/accounts.go | 8 +- execution/evm/asm/opcodes.go | 2 +- execution/evm/fake_app_state.go | 4 +- execution/evm/log_event_test.go | 48 +- execution/evm/native.go | 4 +- execution/evm/snative.go | 50 +- execution/evm/snative_test.go | 13 +- execution/evm/vm.go | 121 +- execution/evm/vm_test.go | 58 +- execution/exec/block_execution.go | 99 + execution/exec/block_execution_test.go | 24 + execution/exec/codec.go | 5 + execution/exec/event.go | 120 + execution/exec/event_test.go | 72 + execution/exec/exec.pb.go | 3216 ++++++++++++ execution/exec/header.go | 13 + .../{events/log.go => exec/log_event.go} | 71 +- execution/exec/tx_execution.go | 154 + execution/execution.go | 149 +- execution/execution_test.go | 436 +- .../executors/{call.go => call_context.go} | 91 +- .../executors/{name.go => name_context.go} | 84 +- ...{permissions.go => permissions_context.go} | 60 +- .../executors/{send.go => send_context.go} | 34 +- execution/executors/shared.go | 55 +- execution/names/cache.go | 16 +- execution/names/names.go | 50 +- execution/names/names.pb.go | 449 ++ execution/names/names_test.go | 39 + execution/options.go | 11 - execution/pbtransactor/transactor.pb.go | 960 ---- execution/pbtransactor/transactor.proto | 96 - execution/simulated_call.go | 75 + execution/state.go | 156 +- execution/state_test.go | 82 +- execution/transactor.go | 470 +- execution/transactor_test.go | 77 + genesis/deterministic_genesis.go | 2 +- genesis/genesis.go | 7 +- genesis/genesis_test.go | 2 +- genesis/spec/genesis_spec.go | 3 +- genesis/spec/genesis_spec_test.go | 2 +- genesis/spec/presets.go | 2 +- genesis/spec/presets_test.go | 2 +- genesis/spec/spec.pb.go | 662 +++ genesis/spec/template_account.go | 18 +- {core => integration/core}/kernel_test.go | 44 +- .../core}/main_test.go | 14 +- .../integration.go | 96 +- .../rpcevents/execution_events_server_test.go | 192 + .../rpcevents}/main_test.go | 23 +- .../rpcquery}/main_test.go | 20 +- integration/rpcquery/query_server_test.go | 87 + integration/rpctest/helpers.go | 188 + .../rpctest}/strange_loop.sol | 0 .../rpctest}/strange_loop.sol.go | 2 +- integration/rpctransact/call_test.go | 343 ++ .../rpctransact}/main_test.go | 20 +- integration/rpctransact/name_test.go | 117 + integration/rpctransact/send_test.go | 31 + .../rpctransact/transact_server_test.go | 109 + integration/tm/main_test.go | 49 + integration/tm/tm_server_test.go | 224 + keys/key_client.go | 31 +- keys/key_store.go | 2 +- keys/keys.pb.go | 4538 +++++++++++++++++ keys/mock/key.go | 4 +- keys/mock/key_client.go | 4 +- keys/pbkeys/keys.pb.go | 1492 ------ keys/pbkeys/keys.proto | 131 - keys/server.go | 71 +- keys/server_test.go | 25 +- permission/{types => }/account_permissions.go | 7 +- permission/{types => }/base_permissions.go | 13 +- .../{types => }/base_permissions_test.go | 2 +- permission/{types => }/errors.go | 2 +- permission/{types => }/perm_flag.go | 2 +- permission/{types => }/perm_flag_test.go | 2 +- permission/permission.pb.go | 844 +++ permission/permissions.go | 27 +- permission/{snatives => }/snatives.go | 45 +- permission/snatives/snatives_test.go | 22 - permission/util.go | 40 +- permission/util_test.go | 21 +- rpc/config.go | 16 - rpc/filters/accounts.go | 119 - rpc/filters/filter.go | 134 - rpc/filters/filter_factory.go | 78 - rpc/filters/filter_test.go | 258 - rpc/filters/namereg.go | 196 - rpc/grpc.go | 3 +- rpc/lib/client/ws_client.go | 2 +- rpc/lib/server/http_params.go | 2 +- rpc/result.go | 98 +- rpc/result_test.go | 86 +- .../pbevents => rpc/rpcevents}/blocks.go | 12 +- .../pbevents => rpc/rpcevents}/blocks_test.go | 7 +- rpc/rpcevents/events_server.go | 57 - rpc/rpcevents/execution_events_server.go | 275 +- .../integration/events_server_test.go | 130 - .../execution_events_server_test.go | 118 - rpc/rpcevents/rpcevents.pb.go | 1838 +++++++ rpc/rpcquery/query_server.go | 76 + rpc/rpcquery/rpcquery.pb.go | 961 ++++ rpc/rpctransact/rpctransact.pb.go | 1488 ++++++ rpc/rpctransact/transact_server.go | 148 + .../integration/transactor_server_test.go | 168 - rpc/rpctransactor/transactor_server.go | 190 - rpc/service.go | 120 +- rpc/subscriptions.go | 144 - rpc/subscriptions_test.go | 166 - rpc/test/helpers.go | 99 - rpc/tm/client/websocket_client.go | 51 - rpc/tm/integration/server_test.go | 398 -- rpc/tm/integration/shared.go | 240 - rpc/tm/integration/websocket_client_test.go | 337 -- rpc/tm/integration/websocket_helpers.go | 323 -- rpc/tm/methods.go | 99 +- rpc/tm/{server.go => tm_server.go} | 12 +- rpc/tm/{client => tmclient}/client.go | 32 +- rpc/tm/{client => tmclient}/client_test.go | 2 +- rpc/v0/client.go | 127 - rpc/v0/codec.go | 62 - rpc/v0/codec_test.go | 45 - rpc/v0/integration/v0_test.go | 178 - rpc/v0/json_service.go | 219 - rpc/v0/json_service_data_test.go | 74 - rpc/v0/json_service_test.go | 30 - rpc/v0/methods.go | 455 -- rpc/v0/params.go | 124 - rpc/v0/server/README.md | 33 - rpc/v0/server/config.go | 83 - rpc/v0/server/idpool.go | 56 - rpc/v0/server/server.go | 264 - rpc/v0/server/server_test.go | 55 - rpc/v0/server/websocket.go | 440 -- rpc/v0/websocket_service.go | 166 - txs/amino_codec_test.go | 2 +- txs/envelope.go | 22 +- txs/json_codec_test.go | 14 +- txs/payload/bond_tx.go | 8 +- txs/payload/call_tx.go | 24 +- txs/payload/errors.go | 8 - txs/payload/governance_tx.go | 19 +- txs/payload/name_tx.go | 47 +- txs/payload/payload.go | 13 +- txs/payload/payload.pb.go | 2498 +++++++++ txs/payload/permission_tx.go | 15 +- txs/payload/send_tx.go | 7 +- txs/payload/tx_input.go | 8 +- txs/payload/tx_output.go | 9 +- txs/payload/unbond_tx.go | 10 +- txs/tx.go | 57 +- txs/tx_test.go | 31 +- txs/txs.pb.go | 878 ++++ 235 files changed, 25839 insertions(+), 15971 deletions(-) delete mode 100644 client/client_do.go delete mode 100644 client/cmd/burrow-client.go delete mode 100644 client/cmd/burrow-client/main.go delete mode 100644 client/cmd/status.go delete mode 100644 client/cmd/transaction.go delete mode 100644 client/methods/call.go delete mode 100644 client/methods/helpers.go delete mode 100644 client/methods/send.go delete mode 100644 client/methods/status.go delete mode 100644 client/mock/client_mock.go delete mode 100644 client/node_client.go delete mode 100644 client/rpc/client.go delete mode 100644 client/rpc/client_test.go delete mode 100644 client/rpc/client_util.go delete mode 100644 client/websocket_client.go delete mode 100644 client/ws_client.go delete mode 100644 consensus/tendermint/events.go create mode 100644 crypto/crypto.pb.go create mode 100644 crypto/public_key_test.go delete mode 100644 event/cache.go delete mode 100644 event/cache_test.go delete mode 100644 event/convention_test.go create mode 100644 event/pubsub/example_test.go create mode 100644 event/pubsub/pubsub.go create mode 100644 event/pubsub/pubsub_test.go create mode 100644 event/query/Makefile create mode 100644 event/query/builder.go create mode 100644 event/query/builder_test.go create mode 100644 event/query/empty_test.go create mode 100644 event/query/parser_test.go create mode 100644 event/query/query.peg create mode 100644 event/query/query.peg.go create mode 100644 event/query/reflect_tagged.go create mode 100644 event/query/reflect_tagged_test.go create mode 100644 event/query/tags.go delete mode 100644 event/tags.go delete mode 100644 execution/errors/errors.proto delete mode 100644 execution/events/call.go delete mode 100644 execution/events/event.go delete mode 100644 execution/events/event_test.go delete mode 100644 execution/events/header.go delete mode 100644 execution/events/key.go delete mode 100644 execution/events/pbevents/events.go delete mode 100644 execution/events/pbevents/events.pb.go delete mode 100644 execution/events/pbevents/events.proto delete mode 100644 execution/events/tx.go delete mode 100644 execution/events/type.go create mode 100644 execution/exec/block_execution.go create mode 100644 execution/exec/block_execution_test.go create mode 100644 execution/exec/codec.go create mode 100644 execution/exec/event.go create mode 100644 execution/exec/event_test.go create mode 100644 execution/exec/exec.pb.go create mode 100644 execution/exec/header.go rename execution/{events/log.go => exec/log_event.go} (51%) create mode 100644 execution/exec/tx_execution.go rename execution/executors/{call.go => call_context.go} (73%) rename execution/executors/{name.go => name_context.go} (67%) rename execution/executors/{permissions.go => permissions_context.go} (72%) rename execution/executors/{send.go => send_context.go} (59%) create mode 100644 execution/names/names.pb.go create mode 100644 execution/names/names_test.go delete mode 100644 execution/options.go delete mode 100644 execution/pbtransactor/transactor.pb.go delete mode 100644 execution/pbtransactor/transactor.proto create mode 100644 execution/simulated_call.go create mode 100644 execution/transactor_test.go create mode 100644 genesis/spec/spec.pb.go rename {core => integration/core}/kernel_test.go (61%) rename {rpc/tm/integration => integration/core}/main_test.go (75%) rename core/integration/test_wrapper.go => integration/integration.go (53%) create mode 100644 integration/rpcevents/execution_events_server_test.go rename {rpc/rpcevents/integration => integration/rpcevents}/main_test.go (62%) rename {rpc/rpctransactor/integration => integration/rpcquery}/main_test.go (69%) create mode 100644 integration/rpcquery/query_server_test.go create mode 100644 integration/rpctest/helpers.go rename {rpc/test => integration/rpctest}/strange_loop.sol (100%) rename {rpc/test => integration/rpctest}/strange_loop.sol.go (99%) create mode 100644 integration/rpctransact/call_test.go rename {rpc/v0/integration => integration/rpctransact}/main_test.go (69%) create mode 100644 integration/rpctransact/name_test.go create mode 100644 integration/rpctransact/send_test.go create mode 100644 integration/rpctransact/transact_server_test.go create mode 100644 integration/tm/main_test.go create mode 100644 integration/tm/tm_server_test.go create mode 100644 keys/keys.pb.go delete mode 100644 keys/pbkeys/keys.pb.go delete mode 100644 keys/pbkeys/keys.proto rename permission/{types => }/account_permissions.go (93%) rename permission/{types => }/base_permissions.go (83%) rename permission/{types => }/base_permissions_test.go (99%) rename permission/{types => }/errors.go (98%) rename permission/{types => }/perm_flag.go (99%) rename permission/{types => }/perm_flag_test.go (91%) create mode 100644 permission/permission.pb.go rename permission/{snatives => }/snatives.go (65%) delete mode 100644 permission/snatives/snatives_test.go delete mode 100644 rpc/filters/accounts.go delete mode 100644 rpc/filters/filter.go delete mode 100644 rpc/filters/filter_factory.go delete mode 100644 rpc/filters/filter_test.go delete mode 100644 rpc/filters/namereg.go rename {execution/events/pbevents => rpc/rpcevents}/blocks.go (72%) rename {execution/events/pbevents => rpc/rpcevents}/blocks_test.go (56%) delete mode 100644 rpc/rpcevents/events_server.go delete mode 100644 rpc/rpcevents/integration/events_server_test.go delete mode 100644 rpc/rpcevents/integration/execution_events_server_test.go create mode 100644 rpc/rpcevents/rpcevents.pb.go create mode 100644 rpc/rpcquery/query_server.go create mode 100644 rpc/rpcquery/rpcquery.pb.go create mode 100644 rpc/rpctransact/rpctransact.pb.go create mode 100644 rpc/rpctransact/transact_server.go delete mode 100644 rpc/rpctransactor/integration/transactor_server_test.go delete mode 100644 rpc/rpctransactor/transactor_server.go delete mode 100644 rpc/subscriptions.go delete mode 100644 rpc/subscriptions_test.go delete mode 100644 rpc/test/helpers.go delete mode 100644 rpc/tm/client/websocket_client.go delete mode 100644 rpc/tm/integration/server_test.go delete mode 100644 rpc/tm/integration/shared.go delete mode 100644 rpc/tm/integration/websocket_client_test.go delete mode 100644 rpc/tm/integration/websocket_helpers.go rename rpc/tm/{server.go => tm_server.go} (75%) rename rpc/tm/{client => tmclient}/client.go (84%) rename rpc/tm/{client => tmclient}/client_test.go (97%) delete mode 100644 rpc/v0/client.go delete mode 100644 rpc/v0/codec.go delete mode 100644 rpc/v0/codec_test.go delete mode 100644 rpc/v0/integration/v0_test.go delete mode 100644 rpc/v0/json_service.go delete mode 100644 rpc/v0/json_service_data_test.go delete mode 100644 rpc/v0/json_service_test.go delete mode 100644 rpc/v0/methods.go delete mode 100644 rpc/v0/params.go delete mode 100644 rpc/v0/server/README.md delete mode 100644 rpc/v0/server/config.go delete mode 100644 rpc/v0/server/idpool.go delete mode 100644 rpc/v0/server/server.go delete mode 100644 rpc/v0/server/server_test.go delete mode 100644 rpc/v0/server/websocket.go delete mode 100644 rpc/v0/websocket_service.go create mode 100644 txs/payload/payload.pb.go create mode 100644 txs/txs.pb.go diff --git a/binary/bytes.go b/binary/bytes.go index 03a736c45..85588da20 100644 --- a/binary/bytes.go +++ b/binary/bytes.go @@ -20,3 +20,25 @@ func (hb HexBytes) MarshalText() ([]byte, error) { func (hb HexBytes) String() string { return hex.EncodeUpperToString(hb) } + +// Protobuf support +func (hb HexBytes) Marshal() ([]byte, error) { + return hb, nil +} + +func (hb *HexBytes) Unmarshal(data []byte) error { + *hb = data + return nil +} + +func (hb HexBytes) MarshalTo(data []byte) (int, error) { + return copy(data, hb), nil +} + +func (hb HexBytes) Size() int { + return len(hb) +} + +func (hb HexBytes) Bytes() []byte { + return hb +} diff --git a/binary/integer.go b/binary/integer.go index 5824a4a9a..82e757c29 100644 --- a/binary/integer.go +++ b/binary/integer.go @@ -18,7 +18,6 @@ import ( "encoding/binary" "math" "math/big" - "sort" ) var big1 = big.NewInt(1) @@ -27,21 +26,6 @@ var tt256 = new(big.Int).Lsh(big1, 256) var tt256m1 = new(big.Int).Sub(new(big.Int).Lsh(big1, 256), big1) var tt255 = new(big.Int).Lsh(big1, 255) -// Sort for []uint64 - -type Uint64Slice []uint64 - -func (p Uint64Slice) Len() int { return len(p) } -func (p Uint64Slice) Less(i, j int) bool { return p[i] < p[j] } -func (p Uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } -func (p Uint64Slice) Sort() { sort.Sort(p) } - -func SearchUint64s(a []uint64, x uint64) int { - return sort.Search(len(a), func(i int) bool { return a[i] >= x }) -} - -func (p Uint64Slice) Search(x uint64) int { return SearchUint64s(p, x) } - //-------------------------------------------------------------------------------- func PutUint64LE(dest []byte, i uint64) { diff --git a/binary/word256.go b/binary/word256.go index 7d69e6000..a41b60d7d 100644 --- a/binary/word256.go +++ b/binary/word256.go @@ -16,6 +16,7 @@ package binary import ( "bytes" + "fmt" "math/big" "sort" @@ -95,6 +96,37 @@ func (w Word256) UnpadRight() []byte { return bytes.TrimRight(w[:], trimCutSet) } +// Gogo proto support +func (w *Word256) Marshal() ([]byte, error) { + if w == nil { + return nil, nil + } + return w.Bytes(), nil +} + +func (w *Word256) Unmarshal(data []byte) error { + if len(data) == 0 { + return nil + } + if len(data) != Word256Length { + return fmt.Errorf("error unmarshallling Word256 '%X' from bytes: %d bytes but should have %d bytes", + data, len(data), Word256Length) + } + copy(w[:], data) + return nil +} + +func (w *Word256) MarshalTo(data []byte) (int, error) { + if w == nil { + return 0, nil + } + return copy(data, w[:]), nil +} + +func (w Word256) Size() int { + return Word256Length +} + func Uint64ToWord256(i uint64) Word256 { buf := [8]byte{} PutUint64BE(buf[:], i) diff --git a/blockchain/validators_test.go b/blockchain/validators_test.go index 35513d43a..433db89eb 100644 --- a/blockchain/validators_test.go +++ b/blockchain/validators_test.go @@ -7,7 +7,7 @@ import ( "math/rand" - acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/crypto" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/client/client_do.go b/client/client_do.go deleted file mode 100644 index 4816cafd8..000000000 --- a/client/client_do.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package client - -type Do struct { - // Persistent flags not reflected in the configuration files - // only set through command line flags or environment variables - Debug bool // BURROW_DEBUG - Verbose bool // BURROW_VERBOSE - - // Following parameters are global flags for burrow-client tx - SignAddrFlag string - NodeAddrFlag string - PubkeyFlag string - AddrFlag string - - // signFlag bool // TODO: remove; unsafe signing without monax-keys - BroadcastFlag bool - WaitFlag bool - - // Following parameters are vary for different Transaction subcommands - // some of these are strings rather than flags because the `core` - // functions have a pure string interface so they work nicely from http - AmtFlag string - NonceFlag string - NameFlag string - DataFlag string - DataFileFlag string - ToFlag string - FeeFlag string - GasFlag string - UnbondtoFlag string - HeightFlag string -} - -func NewClientDo() *Do { - clientDo := new(Do) - clientDo.Debug = false - clientDo.Verbose = false - - clientDo.SignAddrFlag = "" - clientDo.NodeAddrFlag = "" - clientDo.PubkeyFlag = "" - clientDo.AddrFlag = "" - - // clientDo.signFlag = false - clientDo.BroadcastFlag = false - clientDo.WaitFlag = false - - clientDo.AmtFlag = "" - clientDo.NonceFlag = "" - clientDo.NameFlag = "" - clientDo.DataFlag = "" - clientDo.DataFileFlag = "" - clientDo.ToFlag = "" - clientDo.FeeFlag = "" - clientDo.GasFlag = "" - clientDo.UnbondtoFlag = "" - clientDo.HeightFlag = "" - - return clientDo -} diff --git a/client/cmd/burrow-client.go b/client/cmd/burrow-client.go deleted file mode 100644 index bbd1d7563..000000000 --- a/client/cmd/burrow-client.go +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package commands - -import ( - "os" - "strconv" - - "fmt" - - "github.com/hyperledger/burrow/client" - "github.com/hyperledger/burrow/project" - "github.com/spf13/cobra" -) - -// Global flags for persistent flags -var clientDo *client.Do - -var BurrowClientCmd = &cobra.Command{ - Use: "burrow-client", - Short: "burrow-client interacts with a running burrow chain.", - Long: `burrow-client interacts with a running burrow chain. - -Made with <3 by Monax Industries. - -Complete documentation is available at https://monax.io/docs - -VERSION: ` + project.FullVersion(), - Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, -} - -func Execute() { - InitBurrowClientInit() - AddGlobalFlags() - AddClientCommands() - BurrowClientCmd.Execute() -} - -func InitBurrowClientInit() { - // initialise an empty Do struct for command execution - clientDo = client.NewClientDo() -} - -func AddGlobalFlags() { - BurrowClientCmd.PersistentFlags().BoolVarP(&clientDo.Verbose, "verbose", "v", defaultVerbose(), "verbose output; more output than no output flags; less output than debug level; default respects $BURROW_CLIENT_VERBOSE") - BurrowClientCmd.PersistentFlags().BoolVarP(&clientDo.Debug, "debug", "d", defaultDebug(), "debug level output; the most output available for burrow-client; if it is too chatty use verbose flag; default respects $BURROW_CLIENT_DEBUG") -} - -func AddClientCommands() { - BurrowClientCmd.AddCommand(buildTransactionCommand(), buildStatusCommand()) - BurrowClientCmd.AddCommand(&cobra.Command{ - Use: "version", - Short: "Print full version", - Run: func(cmd *cobra.Command, args []string) { fmt.Println(project.FullVersion()) }, - }) -} - -//------------------------------------------------------------------------------ -// Defaults - -// defaultVerbose is set to false unless the BURROW_CLIENT_VERBOSE environment -// variable is set to a parsable boolean. -func defaultVerbose() bool { - return setDefaultBool("BURROW_CLIENT_VERBOSE", false) -} - -// defaultDebug is set to false unless the BURROW_CLIENT_DEBUG environment -// variable is set to a parsable boolean. -func defaultDebug() bool { - return setDefaultBool("BURROW_CLIENT_DEBUG", false) -} - -// setDefaultBool returns the provided default value if the environment variable -// is not set or not parsable as a bool. -func setDefaultBool(environmentVariable string, defaultValue bool) bool { - value := os.Getenv(environmentVariable) - if value != "" { - if parsedValue, err := strconv.ParseBool(value); err == nil { - return parsedValue - } - } - return defaultValue -} - -func setDefaultString(envVar, def string) string { - env := os.Getenv(envVar) - if env != "" { - return env - } - return def -} diff --git a/client/cmd/burrow-client/main.go b/client/cmd/burrow-client/main.go deleted file mode 100644 index dc79298a9..000000000 --- a/client/cmd/burrow-client/main.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package main - -import ( - commands "github.com/hyperledger/burrow/client/cmd" -) - -func main() { - commands.Execute() -} diff --git a/client/cmd/status.go b/client/cmd/status.go deleted file mode 100644 index 555e9428d..000000000 --- a/client/cmd/status.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package commands - -import ( - "github.com/spf13/cobra" - - "github.com/hyperledger/burrow/client/methods" - "github.com/hyperledger/burrow/util" -) - -func buildStatusCommand() *cobra.Command { - statusCmd := &cobra.Command{ - Use: "status", - Short: "burrow-client status returns the current status from a chain.", - Long: `burrow-client status returns the current status from a chain. -`, - Run: func(cmd *cobra.Command, args []string) { - err := methods.Status(clientDo) - if err != nil { - util.Fatalf("Could not get status: %s", err) - } - }, - } - statusCmd.PersistentFlags().StringVarP(&clientDo.NodeAddrFlag, "node-addr", "", defaultNodeRpcAddress(), "set the burrow node rpc server address (default respects $BURROW_CLIENT_NODE_ADDRESS)") - // TransactionCmd.PersistentFlags().StringVarP(&clientDo.PubkeyFlag, "pubkey", "", defaultPublicKey(), "specify the public key to sign with (defaults to $BURROW_CLIENT_PUBLIC_KEY)") - // TransactionCmd.PersistentFlags().StringVarP(&clientDo.AddrFlag, "addr", "", defaultAddress(), "specify the account address (for which the public key can be found at monax-keys) (default respects $BURROW_CLIENT_ADDRESS)") - // TransactionCmd.PersistentFlags().StringVarP(&clientDo.ChainidFlag, "chain-id", "", defaultChainId(), "specify the chainID (default respects $CHAIN_ID)") - // TransactionCmd.PersistentFlags().StringVarP(&clientDo.NonceFlag, "sequence", "", "", "specify the sequence to use for the transaction (should equal the sender account's sequence + 1)") - - // // TransactionCmd.PersistentFlags().BoolVarP(&clientDo.SignFlag, "sign", "s", false, "sign the transaction using the monax-keys daemon") - // TransactionCmd.PersistentFlags().BoolVarP(&clientDo.BroadcastFlag, "broadcast", "b", true, "broadcast the transaction to the blockchain") - // TransactionCmd.PersistentFlags().BoolVarP(&clientDo.WaitFlag, "wait", "w", false, "wait for the transaction to be committed in a block") - - return statusCmd -} diff --git a/client/cmd/transaction.go b/client/cmd/transaction.go deleted file mode 100644 index a5a1c0ac1..000000000 --- a/client/cmd/transaction.go +++ /dev/null @@ -1,192 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package commands - -import ( - "strings" - - "github.com/spf13/cobra" - - "github.com/hyperledger/burrow/client/methods" - "github.com/hyperledger/burrow/util" -) - -func buildTransactionCommand() *cobra.Command { - // Transaction command has subcommands send, name, call, bond, - // unbond, rebond, permissions. - transactionCmd := &cobra.Command{ - Use: "tx", - Short: "burrow-client tx formulates and signs a transaction to a chain", - Long: "burrow-client tx formulates and signs a transaction to a chain.", - Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, - } - - addTransactionPersistentFlags(transactionCmd) - - // SendTx - sendCmd := &cobra.Command{ - Use: "send", - Short: "burrow-client tx send --amt --to ", - Long: "burrow-client tx send --amt --to ", - Run: func(cmd *cobra.Command, args []string) { - err := methods.Send(clientDo) - if err != nil { - util.Fatalf("Could not complete send: %s", err) - } - }, - PreRun: assertParameters, - } - sendCmd.Flags().StringVarP(&clientDo.AmtFlag, "amt", "a", "", "specify an amount") - sendCmd.Flags().StringVarP(&clientDo.ToFlag, "to", "t", "", "specify an address to send to") - - // NameTx - nameCmd := &cobra.Command{ - Use: "name", - Short: "burrow-client tx name --amt --name --data ", - Long: "burrow-client tx name --amt --name --data ", - Run: func(cmd *cobra.Command, args []string) { - // transaction.Name(clientDo) - }, - PreRun: assertParameters, - } - nameCmd.Flags().StringVarP(&clientDo.AmtFlag, "amt", "a", "", "specify an amount") - nameCmd.Flags().StringVarP(&clientDo.NameFlag, "name", "n", "", "specify a name") - nameCmd.Flags().StringVarP(&clientDo.DataFlag, "data", "", "", "specify some data") - nameCmd.Flags().StringVarP(&clientDo.DataFileFlag, "data-file", "", "", "specify a file with some data") - nameCmd.Flags().StringVarP(&clientDo.FeeFlag, "fee", "f", "", "specify the fee to send") - - // CallTx - callCmd := &cobra.Command{ - Use: "call", - Short: "burrow-client tx call --amt --fee --gas --to --data ", - Long: "burrow-client tx call --amt --fee --gas --to --data ", - Run: func(cmd *cobra.Command, args []string) { - err := methods.Call(clientDo) - if err != nil { - util.Fatalf("Could not complete call: %s", err) - } - }, - PreRun: assertParameters, - } - callCmd.Flags().StringVarP(&clientDo.AmtFlag, "amt", "a", "", "specify an amount") - callCmd.Flags().StringVarP(&clientDo.ToFlag, "to", "t", "", "specify an address to send to") - callCmd.Flags().StringVarP(&clientDo.DataFlag, "data", "", "", "specify some data") - callCmd.Flags().StringVarP(&clientDo.FeeFlag, "fee", "f", "", "specify the fee to send") - callCmd.Flags().StringVarP(&clientDo.GasFlag, "gas", "g", "", "specify the gas limit for a CallTx") - - // BondTx - bondCmd := &cobra.Command{ - Use: "bond", - Short: "burrow-client tx bond --pubkey --amt --unbond-to
", - Long: "burrow-client tx bond --pubkey --amt --unbond-to
", - Run: func(cmd *cobra.Command, args []string) { - // transaction.Bond(clientDo) - }, - PreRun: assertParameters, - } - bondCmd.Flags().StringVarP(&clientDo.AmtFlag, "amt", "a", "", "specify an amount") - bondCmd.Flags().StringVarP(&clientDo.UnbondtoFlag, "to", "t", "", "specify an address to unbond to") - - // UnbondTx - unbondCmd := &cobra.Command{ - Use: "unbond", - Short: "burrow-client tx unbond --addr
--height ", - Long: "burrow-client tx unbond --addr
--height ", - Run: func(cmd *cobra.Command, args []string) { - // transaction.Unbond(clientDo) - }, - PreRun: assertParameters, - } - unbondCmd.Flags().StringVarP(&clientDo.AddrFlag, "addr", "a", "", "specify an address") - unbondCmd.Flags().StringVarP(&clientDo.HeightFlag, "height", "n", "", "specify a height to unbond at") - - // RebondTx - var rebondCmd = &cobra.Command{ - Use: "rebond", - Short: "burrow-client tx rebond --addr
--height ", - Long: "burrow-client tx rebond --addr
--height ", - Run: func(cmd *cobra.Command, args []string) { - // transaction.Rebond(clientDo) - }, - PreRun: assertParameters, - } - rebondCmd.Flags().StringVarP(&clientDo.AddrFlag, "addr", "a", "", "specify an address") - rebondCmd.Flags().StringVarP(&clientDo.HeightFlag, "height", "n", "", "specify a height to unbond at") - - // PermissionsTx - permissionsCmd := &cobra.Command{ - Use: "permission", - Short: "burrow-client tx perm ", - Long: "burrow-client tx perm ", - Run: func(cmd *cobra.Command, args []string) { - // transaction.Permsissions(clientDo) - }, - PreRun: assertParameters, - } - - transactionCmd.AddCommand(sendCmd, nameCmd, callCmd, bondCmd, unbondCmd, rebondCmd, permissionsCmd) - return transactionCmd -} - -func addTransactionPersistentFlags(transactionCmd *cobra.Command) { - transactionCmd.PersistentFlags().StringVarP(&clientDo.SignAddrFlag, "sign-addr", "", defaultKeyDaemonAddress(), "set monax-keys daemon address (default respects $BURROW_CLIENT_SIGN_ADDRESS)") - transactionCmd.PersistentFlags().StringVarP(&clientDo.NodeAddrFlag, "node-addr", "", defaultNodeRpcAddress(), "set the burrow node rpc server address (default respects $BURROW_CLIENT_NODE_ADDRESS)") - transactionCmd.PersistentFlags().StringVarP(&clientDo.PubkeyFlag, "pubkey", "", defaultPublicKey(), "specify the public key to sign with (defaults to $BURROW_CLIENT_PUBLIC_KEY)") - transactionCmd.PersistentFlags().StringVarP(&clientDo.AddrFlag, "addr", "", defaultAddress(), "specify the account address (for which the public key can be found at monax-keys) (default respects $BURROW_CLIENT_ADDRESS)") - transactionCmd.PersistentFlags().StringVarP(&clientDo.NonceFlag, "sequence", "", "", "specify the sequence to use for the transaction (should equal the sender account's sequence + 1)") - - // transactionCmd.PersistentFlags().BoolVarP(&clientDo.SignFlag, "sign", "s", false, "sign the transaction using the monax-keys daemon") - transactionCmd.PersistentFlags().BoolVarP(&clientDo.BroadcastFlag, "broadcast", "b", true, "broadcast the transaction to the blockchain") - transactionCmd.PersistentFlags().BoolVarP(&clientDo.WaitFlag, "wait", "w", true, "wait for the transaction to be committed in a block") -} - -//------------------------------------------------------------------------------ -// Defaults - -func defaultKeyDaemonAddress() string { - return setDefaultString("BURROW_CLIENT_SIGN_ADDRESS", "http://127.0.0.1:4767") -} - -func defaultNodeRpcAddress() string { - return setDefaultString("BURROW_CLIENT_NODE_ADDRESS", "tcp://127.0.0.1:46657") -} - -func defaultPublicKey() string { - return setDefaultString("BURROW_CLIENT_PUBLIC_KEY", "") -} - -func defaultAddress() string { - return setDefaultString("BURROW_CLIENT_ADDRESS", "") -} - -//------------------------------------------------------------------------------ -// Helper functions - -func assertParameters(cmd *cobra.Command, args []string) { - if !strings.HasPrefix(clientDo.NodeAddrFlag, "tcp://") && - !strings.HasPrefix(clientDo.NodeAddrFlag, "unix://") { - // TODO: [ben] go-rpc will deprecate reformatting; also it is bad practice to auto-correct for this; - // TODO: [Silas] I've made this fatal, but I'm inclined to define the default as tcp:// and normalise as with http - // below - util.Fatalf(`Please use fully formed listening address for the node, including the tcp:// or unix:// prefix.`) - } - - if !strings.HasPrefix(clientDo.SignAddrFlag, "http://") { - // NOTE: [ben] we preserve the auto-correction here as it is a simple http request-response to the key server. - // TODO: [Silas] we don't have logging here to log that we've done this. I'm inclined to either urls without a scheme - // and be quiet about it, or to make non-compliance fatal - clientDo.SignAddrFlag = "http://" + clientDo.SignAddrFlag - } -} diff --git a/client/methods/call.go b/client/methods/call.go deleted file mode 100644 index 16655803f..000000000 --- a/client/methods/call.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package methods - -import ( - "fmt" - - "github.com/hyperledger/burrow/client" - "github.com/hyperledger/burrow/client/rpc" - "github.com/hyperledger/burrow/keys" - "github.com/hyperledger/burrow/txs" -) - -func Call(do *client.Do) error { - // construct two clients to call out to keys server and - // blockchain node. - logger, err := loggerFromClientDo(do, "Call") - if err != nil { - return fmt.Errorf("Could not generate logging config from Do: %s", err) - } - burrowKeyClient, err := keys.NewRemoteKeyClient(do.SignAddrFlag, logger) - if err != nil { - return fmt.Errorf("Could not create remote key client: %s", err) - } - burrowNodeClient := client.NewBurrowNodeClient(do.NodeAddrFlag, logger) - // form the call transaction - callTransaction, err := rpc.Call(burrowNodeClient, burrowKeyClient, - do.PubkeyFlag, do.AddrFlag, do.ToFlag, do.AmtFlag, do.NonceFlag, - do.GasFlag, do.FeeFlag, do.DataFlag) - if err != nil { - return fmt.Errorf("Failed on forming Call Transaction: %s", err) - } - _, chainID, _, err := burrowNodeClient.ChainId() - if err != nil { - return err - } - // TODO: [ben] we carry over the sign bool, but always set it to true, - // as we move away from and deprecate the api that allows sending unsigned - // transactions and relying on (our) receiving node to sign it. - txResult, err := rpc.SignAndBroadcast(burrowNodeClient, burrowKeyClient, - txs.Enclose(chainID, callTransaction), true, do.BroadcastFlag, do.WaitFlag) - - if err != nil { - return fmt.Errorf("Failed on signing (and broadcasting) transaction: %s", err) - } - unpackSignAndBroadcast(txResult, logger) - return nil -} diff --git a/client/methods/helpers.go b/client/methods/helpers.go deleted file mode 100644 index 6fbf1f46e..000000000 --- a/client/methods/helpers.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package methods - -import ( - "github.com/hyperledger/burrow/client" - "github.com/hyperledger/burrow/client/rpc" - "github.com/hyperledger/burrow/logging" - "github.com/hyperledger/burrow/logging/config" - "github.com/hyperledger/burrow/logging/lifecycle" -) - -func unpackSignAndBroadcast(result *rpc.TxResult, logger *logging.Logger) { - if result == nil { - // if we don't provide --sign or --broadcast - return - } - - logger = logger.With("transaction hash", result.Hash) - - if result.Address != nil { - logger = logger.With("Contract Address", result.Address) - } - - if result.Return != nil { - logger = logger.With("Block Hash", result.BlockHash, - "Return Value", result.Return, - "Exception", result.Exception, - ) - } - - logger.InfoMsg("SignAndBroadcast result") -} - -func loggerFromClientDo(do *client.Do, scope string) (*logging.Logger, error) { - logger, err := lifecycle.NewLoggerFromLoggingConfig(config.DefaultClientLoggingConfig()) - if err != nil { - return nil, err - } - logger = logger.WithScope(scope) - lifecycle.CaptureStdlibLogOutput(logger) - return logger, nil -} diff --git a/client/methods/send.go b/client/methods/send.go deleted file mode 100644 index 6ce809721..000000000 --- a/client/methods/send.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package methods - -import ( - "fmt" - - "github.com/hyperledger/burrow/client" - "github.com/hyperledger/burrow/client/rpc" - "github.com/hyperledger/burrow/keys" - "github.com/hyperledger/burrow/txs" -) - -func Send(do *client.Do) error { - // construct two clients to call out to keys server and - // blockchain node. - logger, err := loggerFromClientDo(do, "Send") - if err != nil { - return fmt.Errorf("Could not generate logging config from Do: %s", err) - } - burrowKeyClient, err := keys.NewRemoteKeyClient(do.SignAddrFlag, logger) - if err != nil { - return fmt.Errorf("Could not create remote key client: %s", err) - } - burrowNodeClient := client.NewBurrowNodeClient(do.NodeAddrFlag, logger) - // form the send transaction - sendTransaction, err := rpc.Send(burrowNodeClient, burrowKeyClient, - do.PubkeyFlag, do.AddrFlag, do.ToFlag, do.AmtFlag, do.NonceFlag) - if err != nil { - fmt.Errorf("Failed on forming Send Transaction: %s", err) - } - _, chainID, _, err := burrowNodeClient.ChainId() - if err != nil { - return err - } - // TODO: [ben] we carry over the sign bool, but always set it to true, - // as we move away from and deprecate the api that allows sending unsigned - // transactions and relying on (our) receiving node to sign it. - txResult, err := rpc.SignAndBroadcast(burrowNodeClient, burrowKeyClient, - txs.Enclose(chainID, sendTransaction), true, do.BroadcastFlag, do.WaitFlag) - if err != nil { - return fmt.Errorf("Failed on signing (and broadcasting) transaction: %s", err) - } - unpackSignAndBroadcast(txResult, logger) - return nil -} diff --git a/client/methods/status.go b/client/methods/status.go deleted file mode 100644 index 7487fdf19..000000000 --- a/client/methods/status.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package methods - -import ( - "fmt" - - "github.com/hyperledger/burrow/client" -) - -func Status(do *client.Do) error { - logger, err := loggerFromClientDo(do, "Status") - if err != nil { - return fmt.Errorf("Could not generate logging config from Do: %s", err) - } - burrowNodeClient := client.NewBurrowNodeClient(do.NodeAddrFlag, logger) - genesisHash, validatorPublicKey, latestBlockHash, latestBlockHeight, latestBlockTime, err := burrowNodeClient.Status() - if err != nil { - return fmt.Errorf("Error requesting status from chain at (%s): %s", do.NodeAddrFlag, err) - } - - chainName, chainId, genesisHashfromChainId, err := burrowNodeClient.ChainId() - if err != nil { - return fmt.Errorf("Error requesting chainId from chain at (%s): %s", do.NodeAddrFlag, err) - } - - logger.Info.Log("chain", do.NodeAddrFlag, - "genesisHash", fmt.Sprintf("%X", genesisHash), - "chainName", chainName, - "chainId", chainId, - "genesisHash from chainId", fmt.Sprintf("%X", genesisHashfromChainId), - "validator public key", fmt.Sprintf("%X", validatorPublicKey), - "latest block hash", fmt.Sprintf("%X", latestBlockHash), - "latest block height", latestBlockHeight, - "latest block time", latestBlockTime, - ) - return nil -} diff --git a/client/mock/client_mock.go b/client/mock/client_mock.go deleted file mode 100644 index 223166122..000000000 --- a/client/mock/client_mock.go +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package mock - -import ( - acm "github.com/hyperledger/burrow/account" - . "github.com/hyperledger/burrow/client" - "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/logging" - "github.com/hyperledger/burrow/rpc" - "github.com/hyperledger/burrow/txs" -) - -var _ NodeClient = (*MockNodeClient)(nil) - -type MockNodeClient struct { - accounts map[string]*acm.ConcreteAccount -} - -func NewMockNodeClient() *MockNodeClient { - return &MockNodeClient{ - accounts: make(map[string]*acm.ConcreteAccount), - } -} - -func (mock *MockNodeClient) Broadcast(txEnv *txs.Envelope) (*txs.Receipt, error) { - // make zero transaction receipt - txReceipt := &txs.Receipt{ - TxHash: make([]byte, 20), - CreatesContract: false, - } - return txReceipt, nil -} - -func (mock *MockNodeClient) DeriveWebsocketClient() (nodeWsClient NodeWebsocketClient, err error) { - return nil, nil -} - -func (mock *MockNodeClient) GetAccount(address crypto.Address) (acm.Account, error) { - // make zero account - return acm.FromAddressable(acm.GeneratePrivateAccountFromSecret("mock-node-client-account")), nil -} - -func (mock *MockNodeClient) MockAddAccount(account *acm.ConcreteAccount) { - addressString := string(account.Address[:]) - mock.accounts[addressString] = account.Copy() -} - -func (mock *MockNodeClient) Status() (ChainId []byte, ValidatorPublicKey []byte, LatestBlockHash []byte, - BlockHeight uint64, LatestBlockTime int64, err error) { - // fill return values - ChainId = make([]byte, 64) - LatestBlockHash = make([]byte, 64) - BlockHeight = 0 - LatestBlockTime = 0 - return -} - -// QueryContract executes the contract code at address with the given data -func (mock *MockNodeClient) QueryContract(callerAddress, calleeAddress crypto.Address, - data []byte) (ret []byte, gasUsed uint64, err error) { - - // return zero - ret = make([]byte, 0) - return -} - -// QueryContractCode executes the contract code at address with the given data but with provided code -func (mock *MockNodeClient) QueryContractCode(address crypto.Address, code, - data []byte) (ret []byte, gasUsed uint64, err error) { - // return zero - ret = make([]byte, 0) - return -} - -func (mock *MockNodeClient) DumpStorage(address crypto.Address) (storage *rpc.ResultDumpStorage, err error) { - return -} - -func (mock *MockNodeClient) GetName(name string) (owner crypto.Address, data string, expirationBlock uint64, err error) { - return -} - -func (mock *MockNodeClient) ListValidators() (blockHeight uint64, bondedValidators, - unbondingValidators []acm.Validator, err error) { - return -} - -func (mock *MockNodeClient) Logger() *logging.Logger { - return logging.NewNoopLogger() -} diff --git a/client/node_client.go b/client/node_client.go deleted file mode 100644 index 8c3464cf0..000000000 --- a/client/node_client.go +++ /dev/null @@ -1,264 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package client - -import ( - "fmt" - - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/logging" - "github.com/hyperledger/burrow/rpc" - rpcClient "github.com/hyperledger/burrow/rpc/lib/client" - tmClient "github.com/hyperledger/burrow/rpc/tm/client" - "github.com/hyperledger/burrow/txs" -) - -type NodeClient interface { - Broadcast(transaction *txs.Envelope) (*txs.Receipt, error) - DeriveWebsocketClient() (nodeWsClient NodeWebsocketClient, err error) - - Status() (ChainId []byte, ValidatorPublicKey []byte, LatestBlockHash []byte, - LatestBlockHeight uint64, LatestBlockTime int64, err error) - GetAccount(address crypto.Address) (acm.Account, error) - QueryContract(callerAddress, calleeAddress crypto.Address, data []byte) (ret []byte, gasUsed uint64, err error) - QueryContractCode(address crypto.Address, code, data []byte) (ret []byte, gasUsed uint64, err error) - - DumpStorage(address crypto.Address) (storage *rpc.ResultDumpStorage, err error) - GetName(name string) (owner crypto.Address, data string, expirationBlock uint64, err error) - ListValidators() (blockHeight uint64, bondedValidators, unbondingValidators []acm.Validator, err error) - - // Logging context for this NodeClient - Logger() *logging.Logger -} - -type NodeWebsocketClient interface { - Subscribe(eventId string) error - Unsubscribe(eventId string) error - WaitForConfirmation(tx *txs.Envelope, inputAddr crypto.Address) (chan Confirmation, error) - Close() -} - -// NOTE [ben] Compiler check to ensure burrowNodeClient successfully implements -// burrow/client.NodeClient -var _ NodeClient = (*burrowNodeClient)(nil) - -// burrow-client is a simple struct exposing the client rpc methods -type burrowNodeClient struct { - broadcastRPC string - logger *logging.Logger -} - -// BurrowKeyClient.New returns a new monax-keys client for provided rpc location -// Monax-keys connects over http request-responses -func NewBurrowNodeClient(rpcString string, logger *logging.Logger) *burrowNodeClient { - return &burrowNodeClient{ - broadcastRPC: rpcString, - logger: logger.WithScope("BurrowNodeClient"), - } -} - -//------------------------------------------------------------------------------------ -// broadcast to blockchain node - -func (burrowNodeClient *burrowNodeClient) Broadcast(txEnv *txs.Envelope) (*txs.Receipt, error) { - client := rpcClient.NewURIClient(burrowNodeClient.broadcastRPC) - receipt, err := tmClient.BroadcastTx(client, txEnv) - if err != nil { - return nil, err - } - return receipt, nil -} - -func (burrowNodeClient *burrowNodeClient) DeriveWebsocketClient() (nodeWsClient NodeWebsocketClient, err error) { - var wsAddr string - // TODO: clean up this inherited mess on dealing with the address prefixes. - nodeAddr := burrowNodeClient.broadcastRPC - // if strings.HasPrefix(nodeAddr, "http://") { - // wsAddr = strings.TrimPrefix(nodeAddr, "http://") - // } - // if strings.HasPrefix(nodeAddr, "tcp://") { - // wsAddr = strings.TrimPrefix(nodeAddr, "tcp://") - // } - // if strings.HasPrefix(nodeAddr, "unix://") { - // log.WithFields(log.Fields{ - // "node address": nodeAddr, - // }).Error("Unable to subscribe to websocket from unix socket.") - // return nil, fmt.Errorf("Unable to construct websocket from unix socket: %s", nodeAddr) - // } - // wsAddr = "ws://" + wsAddr - wsAddr = nodeAddr - burrowNodeClient.logger.TraceMsg("Subscribing to websocket address", - "websocket address", wsAddr, - "endpoint", "/websocket", - ) - wsClient := rpcClient.NewWSClient(wsAddr, "/websocket") - if err = wsClient.Start(); err != nil { - return nil, err - } - derivedBurrowNodeWebsocketClient := &burrowNodeWebsocketClient{ - tendermintWebsocket: wsClient, - logger: burrowNodeClient.logger.WithScope("BurrowNodeWebsocketClient"), - } - return derivedBurrowNodeWebsocketClient, nil -} - -//------------------------------------------------------------------------------------ -// RPC requests other than transaction related - -// Status returns the ChainId (GenesisHash), validator's PublicKey, latest block hash -// the block height and the latest block time. -func (burrowNodeClient *burrowNodeClient) Status() (GenesisHash []byte, ValidatorPublicKey []byte, - LatestBlockHash []byte, LatestBlockHeight uint64, LatestBlockTime int64, err error) { - - client := rpcClient.NewJSONRPCClient(burrowNodeClient.broadcastRPC) - res, err := tmClient.Status(client) - if err != nil { - err = fmt.Errorf("error connecting to node (%s) to get status: %s", - burrowNodeClient.broadcastRPC, err.Error()) - return - } - - // unwrap return results - GenesisHash = res.GenesisHash - ValidatorPublicKey = res.PubKey.RawBytes() - LatestBlockHash = res.LatestBlockHash - LatestBlockHeight = res.LatestBlockHeight - LatestBlockTime = res.LatestBlockTime - return -} - -func (burrowNodeClient *burrowNodeClient) ChainId() (ChainName, ChainId string, GenesisHash []byte, err error) { - client := rpcClient.NewJSONRPCClient(burrowNodeClient.broadcastRPC) - chainIdResult, err := tmClient.ChainId(client) - if err != nil { - err = fmt.Errorf("error connecting to node (%s) to get chain id: %s", - burrowNodeClient.broadcastRPC, err.Error()) - return "", "", nil, err - } - // unwrap results - ChainName = chainIdResult.ChainName - ChainId = chainIdResult.ChainId - GenesisHash = make([]byte, len(chainIdResult.GenesisHash)) - copy(GenesisHash[:], chainIdResult.GenesisHash) - return -} - -// QueryContract executes the contract code at address with the given data -// NOTE: there is no check on the caller; -func (burrowNodeClient *burrowNodeClient) QueryContract(callerAddress, calleeAddress crypto.Address, - data []byte) (ret []byte, gasUsed uint64, err error) { - - client := rpcClient.NewJSONRPCClient(burrowNodeClient.broadcastRPC) - callResult, err := tmClient.Call(client, callerAddress, calleeAddress, data) - if err != nil { - err = fmt.Errorf("error (%v) connnecting to node (%s) to query contract at (%s) with data (%X)", - err.Error(), burrowNodeClient.broadcastRPC, calleeAddress, data) - return - } - return callResult.Return, callResult.GasUsed, nil -} - -// QueryContractCode executes the contract code at address with the given data but with provided code -func (burrowNodeClient *burrowNodeClient) QueryContractCode(address crypto.Address, code, - data []byte) (ret []byte, gasUsed uint64, err error) { - - client := rpcClient.NewJSONRPCClient(burrowNodeClient.broadcastRPC) - // TODO: [ben] Call and CallCode have an inconsistent signature; it makes sense for both to only - // have a single address that is the contract to query. - callResult, err := tmClient.CallCode(client, address, code, data) - if err != nil { - err = fmt.Errorf("error connnecting to node (%s) to query contract code at (%s) with data (%X) and code (%X): %v", - burrowNodeClient.broadcastRPC, address, data, code, err.Error()) - return nil, uint64(0), err - } - return callResult.Return, callResult.GasUsed, nil -} - -// GetAccount returns a copy of the account -func (burrowNodeClient *burrowNodeClient) GetAccount(address crypto.Address) (acm.Account, error) { - client := rpcClient.NewJSONRPCClient(burrowNodeClient.broadcastRPC) - account, err := tmClient.GetAccount(client, address) - if err != nil { - err = fmt.Errorf("error connecting to node (%s) to fetch account (%s): %s", - burrowNodeClient.broadcastRPC, address, err.Error()) - return nil, err - } - if account == nil { - err = fmt.Errorf("unknown account %s at node (%s)", address, burrowNodeClient.broadcastRPC) - return nil, err - } - - return account, nil -} - -// DumpStorage returns the full storage for an acm. -func (burrowNodeClient *burrowNodeClient) DumpStorage(address crypto.Address) (*rpc.ResultDumpStorage, error) { - client := rpcClient.NewJSONRPCClient(burrowNodeClient.broadcastRPC) - resultStorage, err := tmClient.DumpStorage(client, address) - if err != nil { - return nil, fmt.Errorf("error connecting to node (%s) to get storage for account (%X): %s", - burrowNodeClient.broadcastRPC, address, err.Error()) - } - return resultStorage, nil -} - -//-------------------------------------------------------------------------------------------- -// Name registry - -func (burrowNodeClient *burrowNodeClient) GetName(name string) (owner crypto.Address, data string, - expirationBlock uint64, err error) { - - client := rpcClient.NewJSONRPCClient(burrowNodeClient.broadcastRPC) - entryResult, err := tmClient.GetName(client, name) - if err != nil { - err = fmt.Errorf("error connecting to node (%s) to get name registrar entry for name (%s)", - burrowNodeClient.broadcastRPC, name) - return crypto.ZeroAddress, "", 0, err - } - // unwrap return results - owner = entryResult.Owner - data = entryResult.Data - expirationBlock = entryResult.Expires - return -} - -//-------------------------------------------------------------------------------------------- - -func (burrowNodeClient *burrowNodeClient) ListValidators() (blockHeight uint64, - bondedValidators, unbondingValidators []acm.Validator, err error) { - - client := rpcClient.NewJSONRPCClient(burrowNodeClient.broadcastRPC) - validatorsResult, err := tmClient.ListValidators(client) - if err != nil { - err = fmt.Errorf("error connecting to node (%s) to get validators", burrowNodeClient.broadcastRPC) - return - } - // unwrap return results - blockHeight = validatorsResult.BlockHeight - bondedValidators = make([]acm.Validator, len(validatorsResult.BondedValidators)) - for i, cv := range validatorsResult.BondedValidators { - bondedValidators[i] = cv.Validator() - } - unbondingValidators = make([]acm.Validator, len(validatorsResult.UnbondingValidators)) - for i, cv := range validatorsResult.UnbondingValidators { - unbondingValidators[i] = cv.Validator() - } - return -} - -func (burrowNodeClient *burrowNodeClient) Logger() *logging.Logger { - return burrowNodeClient.logger -} diff --git a/client/rpc/client.go b/client/rpc/client.go deleted file mode 100644 index 9e5364246..000000000 --- a/client/rpc/client.go +++ /dev/null @@ -1,307 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package rpc - -import ( - "encoding/hex" - "fmt" - "strconv" - - "github.com/hyperledger/burrow/client" - "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/keys" - "github.com/hyperledger/burrow/permission/snatives" - ptypes "github.com/hyperledger/burrow/permission/types" - "github.com/hyperledger/burrow/txs" - "github.com/hyperledger/burrow/txs/payload" -) - -//------------------------------------------------------------------------------------ -// core functions with string args. -// validates strings and forms transaction - -func Send(nodeClient client.NodeClient, keyClient keys.KeyClient, pubkey, addr, toAddr, amtS, sequenceS string) (*payload.SendTx, error) { - pub, amt, sequence, err := checkCommon(nodeClient, keyClient, pubkey, addr, amtS, sequenceS) - if err != nil { - return nil, err - } - - if toAddr == "" { - return nil, fmt.Errorf("destination address must be given with --to flag") - } - - toAddress, err := addressFromHexString(toAddr) - if err != nil { - return nil, err - } - - tx := payload.NewSendTx() - tx.AddInputWithSequence(pub, amt, sequence) - tx.AddOutput(toAddress, amt) - - return tx, nil -} - -func Call(nodeClient client.NodeClient, keyClient keys.KeyClient, pubkey, addr, toAddr, amtS, sequenceS, gasS, feeS, data string) (*payload.CallTx, error) { - pub, amt, sequence, err := checkCommon(nodeClient, keyClient, pubkey, addr, amtS, sequenceS) - if err != nil { - return nil, err - } - - var toAddress *crypto.Address - - if toAddr != "" { - address, err := addressFromHexString(toAddr) - if err != nil { - return nil, fmt.Errorf("toAddr is bad hex: %v", err) - } - toAddress = &address - } - - fee, err := strconv.ParseUint(feeS, 10, 64) - if err != nil { - return nil, fmt.Errorf("fee is misformatted: %v", err) - } - - gas, err := strconv.ParseUint(gasS, 10, 64) - if err != nil { - return nil, fmt.Errorf("gas is misformatted: %v", err) - } - - dataBytes, err := hex.DecodeString(data) - if err != nil { - return nil, fmt.Errorf("data is bad hex: %v", err) - } - - tx := payload.NewCallTxWithSequence(pub, toAddress, dataBytes, amt, gas, fee, sequence) - return tx, nil -} - -func Name(nodeClient client.NodeClient, keyClient keys.KeyClient, pubkey, addr, amtS, sequenceS, feeS, name, data string) (*payload.NameTx, error) { - pub, amt, sequence, err := checkCommon(nodeClient, keyClient, pubkey, addr, amtS, sequenceS) - if err != nil { - return nil, err - } - - fee, err := strconv.ParseUint(feeS, 10, 64) - if err != nil { - return nil, fmt.Errorf("fee is misformatted: %v", err) - } - - tx := payload.NewNameTxWithSequence(pub, name, data, amt, fee, sequence) - return tx, nil -} - -func Permissions(nodeClient client.NodeClient, keyClient keys.KeyClient, pubkey, addrS, sequenceS string, - action, target, permissionFlag, role, value string) (*payload.PermissionsTx, error) { - - pub, _, sequence, err := checkCommon(nodeClient, keyClient, pubkey, addrS, "0", sequenceS) - if err != nil { - return nil, err - } - permFlag, err := ptypes.PermStringToFlag(action) - if err != nil { - return nil, fmt.Errorf("could not convert action '%s' to PermFlag: %v", action, err) - } - permArgs := snatives.PermArgs{ - PermFlag: permFlag, - } - - // Try and set each PermArg field for which a string has been provided we'll validate afterwards - if target != "" { - address, err := crypto.AddressFromHexString(target) - if err != nil { - return nil, err - } - permArgs.Address = &address - } - - if value != "" { - valueBool := value == "true" - permArgs.Value = &valueBool - if !valueBool && value != "false" { - return nil, fmt.Errorf("did not recognise value %s as boolean, use 'true' or 'false'", value) - } - permArgs.Value = &valueBool - } - - if permissionFlag != "" { - permission, err := ptypes.PermStringToFlag(permissionFlag) - if err != nil { - return nil, err - } - permArgs.Permission = &permission - } - - if role != "" { - permArgs.Role = &role - } - - err = permArgs.EnsureValid() - if err != nil { - return nil, err - } - - tx := payload.NewPermissionsTxWithSequence(pub, permArgs, sequence) - return tx, nil -} - -func Bond(nodeClient client.NodeClient, keyClient keys.KeyClient, pubkey, unbondAddr, amtS, sequenceS string) (*payload.BondTx, error) { - return nil, fmt.Errorf("Bond Transaction formation to be implemented on 0.12.0") - // pub, amt, sequence, err := checkCommon(nodeAddr, signAddr, pubkey, "", amtS, sequenceS) - // if err != nil { - // return nil, err - // } - // var pubKey acm.PublicKeyEd25519 - // var unbondAddrBytes []byte - - // if unbondAddr == "" { - // pkb, _ := hex.DecodeString(pubkey) - // copy(pubKey[:], pkb) - // unbondAddrBytes = pubKey.Address() - // } else { - // unbondAddrBytes, err = hex.DecodeString(unbondAddr) - // if err != nil { - // return nil, fmt.Errorf("unbondAddr is bad hex: %v", err) - // } - - // } - - // tx, err := types.NewBondTx(pub) - // if err != nil { - // return nil, err - // } - // tx.AddInputWithSequence(pub, amt, int(sequence)) - // tx.AddOutput(unbondAddrBytes, amt) - - // return tx, nil -} - -func Unbond(addrS, heightS string) (*payload.UnbondTx, error) { - return nil, fmt.Errorf("Unbond Transaction formation to be implemented on 0.12.0") - // if addrS == "" { - // return nil, fmt.Errorf("Validator address must be given with --addr flag") - // } - - // addrBytes, err := hex.DecodeString(addrS) - // if err != nil { - // return nil, fmt.Errorf("addr is bad hex: %v", err) - // } - - // height, err := strconv.ParseInt(heightS, 10, 32) - // if err != nil { - // return nil, fmt.Errorf("height is misformatted: %v", err) - // } - - // return &types.UnbondTx{ - // Address: addrBytes, - // Height: int(height), - // }, nil -} - -type TxResult struct { - BlockHash []byte // all txs get in a block - Hash []byte // all txs get a hash - - // only CallTx - Address *crypto.Address // only for new contracts - Return []byte - Exception string - - //TODO: make Broadcast() errors more responsive so we - // can differentiate mempool errors from other -} - -// Preserve -func SignAndBroadcast(nodeClient client.NodeClient, keyClient keys.KeyClient, txEnv *txs.Envelope, sign, - broadcast, wait bool) (txResult *TxResult, err error) { - - var inputAddr crypto.Address - if sign { - inputAddr, txEnv, err = signTx(keyClient, txEnv.Tx) - if err != nil { - return nil, err - } - } - - if broadcast { - if wait { - var wsClient client.NodeWebsocketClient - wsClient, err = nodeClient.DeriveWebsocketClient() - if err != nil { - return nil, err - } - var confirmationChannel chan client.Confirmation - confirmationChannel, err = wsClient.WaitForConfirmation(txEnv, inputAddr) - if err != nil { - return nil, err - } - defer func() { - if err != nil { - // if broadcast threw an error, just return - return - } - if txResult == nil { - err = fmt.Errorf("txResult unexpectedly not initialised in SignAndBroadcast") - return - } - confirmation := <-confirmationChannel - if confirmation.Error != nil { - err = fmt.Errorf("encountered error waiting for event: %s", confirmation.Error) - return - } - if confirmation.Exception != nil { - err = fmt.Errorf("encountered Exception from chain: %s", confirmation.Exception) - return - } - txResult.BlockHash = confirmation.BlockHash - txResult.Exception = "" - eventDataTx := confirmation.EventDataTx - if eventDataTx == nil { - err = fmt.Errorf("EventDataTx was nil") - return - } - txResult.Return = eventDataTx.Return - }() - } - - var receipt *txs.Receipt - receipt, err = nodeClient.Broadcast(txEnv) - if err != nil { - return nil, err - } - txResult = &TxResult{ - Hash: receipt.TxHash, - } - // NOTE: [ben] is this consistent with the Ethereum protocol? It should seem - // reasonable to get this returned from the chain directly. Alternatively, - // the benefit is that the we don't need to trust the chain node - if tx_, ok := txEnv.Tx.Payload.(*payload.CallTx); ok { - if tx_.Address == nil { - address := crypto.NewContractAddress(tx_.Input.Address, tx_.Input.Sequence) - txResult.Address = &address - } - } - } - return -} - -func addressFromHexString(addrString string) (crypto.Address, error) { - addrBytes, err := hex.DecodeString(addrString) - if err != nil { - return crypto.Address{}, err - } - return crypto.AddressFromBytes(addrBytes) -} diff --git a/client/rpc/client_test.go b/client/rpc/client_test.go deleted file mode 100644 index 3a8ebc42d..000000000 --- a/client/rpc/client_test.go +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package rpc - -import ( - "encoding/json" - "fmt" - "testing" - - // "github.com/stretchr/testify/assert" - - mockclient "github.com/hyperledger/burrow/client/mock" - mockkeys "github.com/hyperledger/burrow/keys/mock" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestSend(t *testing.T) { - mockKeyClient := mockkeys.NewKeyClient() - mockNodeClient := mockclient.NewMockNodeClient() - testSend(t, mockNodeClient, mockKeyClient) -} - -func TestCall(t *testing.T) { - mockKeyClient := mockkeys.NewKeyClient() - mockNodeClient := mockclient.NewMockNodeClient() - testCall(t, mockNodeClient, mockKeyClient) -} - -func TestName(t *testing.T) { - mockKeyClient := mockkeys.NewKeyClient() - mockNodeClient := mockclient.NewMockNodeClient() - testName(t, mockNodeClient, mockKeyClient) -} - -func TestPermissions(t *testing.T) { - mockKeyClient := mockkeys.NewKeyClient() - mockNodeClient := mockclient.NewMockNodeClient() - testPermissions(t, mockNodeClient, mockKeyClient) -} - -func testSend(t *testing.T, - nodeClient *mockclient.MockNodeClient, keyClient *mockkeys.KeyClient) { - - // generate an ED25519 key and ripemd160 address - addressString := keyClient.NewKey("").String() - // Public key can be queried from mockKeyClient.PublicKey(address) - // but here we let the transaction factory retrieve the public key - // which will then also overwrite the address we provide the function. - // As a result we will assert whether address generated above, is identical - // to address in generated transation. - publicKeyString := "" - // generate an additional address to send amount to - toAddressString := keyClient.NewKey("").String() - // set an amount to transfer - amountString := "1000" - // unset sequence so that we retrieve sequence from account - sequenceString := "" - - _, err := Send(nodeClient, keyClient, publicKeyString, addressString, - toAddressString, amountString, sequenceString) - require.NoError(t, err, "Error in Send") - // assert.NotEqual(t, txSend) - // TODO: test content of Transaction -} - -func testCall(t *testing.T, - nodeClient *mockclient.MockNodeClient, keyClient *mockkeys.KeyClient) { - - // generate an ED25519 key and ripemd160 address - addressString := keyClient.NewKey("").String() - // Public key can be queried from mockKeyClient.PublicKey(address) - // but here we let the transaction factory retrieve the public key - // which will then also overwrite the address we provide the function. - // As a result we will assert whether address generated above, is identical - // to address in generated transation. - publicKeyString := "" - // generate an additional address to send amount to - toAddressString := keyClient.NewKey("").String() - // set an amount to transfer - amountString := "1000" - // unset sequence so that we retrieve sequence from account - sequenceString := "" - // set gas - gasString := "1000" - // set fee - feeString := "100" - // set data - dataString := fmt.Sprintf("%X", "We are DOUG.") - - _, err := Call(nodeClient, keyClient, publicKeyString, addressString, - toAddressString, amountString, sequenceString, gasString, feeString, dataString) - if err != nil { - t.Logf("Error in CallTx: %s", err) - t.Fail() - } - // TODO: test content of Transaction -} - -func testName(t *testing.T, - nodeClient *mockclient.MockNodeClient, keyClient *mockkeys.KeyClient) { - - // generate an ED25519 key and ripemd160 address - addressString := keyClient.NewKey("").String() - // Public key can be queried from mockKeyClient.PublicKey(address) - // but here we let the transaction factory retrieve the public key - // which will then also overwrite the address we provide the function. - // As a result we will assert whether address generated above, is identical - // to address in generated transation. - publicKeyString := "" - // set an amount to transfer - amountString := "1000" - // unset sequence so that we retrieve sequence from account - sequenceString := "" - // set fee - feeString := "100" - // set data - dataString := fmt.Sprintf("%X", "We are DOUG.") - // set name - nameString := "DOUG" - - _, err := Name(nodeClient, keyClient, publicKeyString, addressString, - amountString, sequenceString, feeString, nameString, dataString) - if err != nil { - t.Logf("Error in NameTx: %s", err) - t.Fail() - } - // TODO: test content of Transaction -} - -func testPermissions(t *testing.T, - nodeClient *mockclient.MockNodeClient, keyClient *mockkeys.KeyClient) { - - // generate an ED25519 key and ripemd160 address - addressString := keyClient.NewKey("").String() - // Public key can be queried from mockKeyClient.PublicKey(address) - // but here we let the transaction factory retrieve the public key - // which will then also overwrite the address we provide the function. - // As a result we will assert whether address generated above, is identical - // to address in generated transation. - publicKeyString := "" - // generate an additional address to set permissions for - permAddressString := keyClient.NewKey("").String() - // unset sequence so that we retrieve sequence from account - sequenceString := "" - - tx, err := Permissions(nodeClient, keyClient, publicKeyString, addressString, - sequenceString, "setBase", permAddressString, "root", "", "true") - if err != nil { - t.Logf("Error in PermissionsTx: %s", err) - t.Fail() - } - - bs, err := json.Marshal(tx.PermArgs) - require.NoError(t, err) - expected := fmt.Sprintf(`{"PermFlag":256,"Address":"%s","Permission":1,"Value":true}`, permAddressString) - assert.Equal(t, expected, string(bs)) -} diff --git a/client/rpc/client_util.go b/client/rpc/client_util.go deleted file mode 100644 index d59453a7c..000000000 --- a/client/rpc/client_util.go +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package rpc - -import ( - "encoding/hex" - "fmt" - "strconv" - - "github.com/hyperledger/burrow/client" - "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/keys" - "github.com/hyperledger/burrow/txs" -) - -//------------------------------------------------------------------------------------ -// sign and broadcast convenience - -// tx has either one input or we default to the first one (ie for send/bond) -// TODO: better support for multisig and bonding -func signTx(keyClient keys.KeyClient, tx *txs.Tx) (crypto.Address, *txs.Envelope, error) { - txEnv := tx.Enclose() - inputs := tx.GetInputs() - signer, err := keys.AddressableSigner(keyClient, inputs[0].Address) - if err != nil { - return crypto.ZeroAddress, nil, err - } - err = txEnv.Sign(signer) - if err != nil { - return crypto.ZeroAddress, nil, err - } - return signer.Address(), txEnv, nil -} - -func checkCommon(nodeClient client.NodeClient, keyClient keys.KeyClient, pubkey, addr, amtS, - sequenceS string) (pub crypto.PublicKey, amt uint64, sequence uint64, err error) { - - if amtS == "" { - err = fmt.Errorf("input must specify an amount with the --amt flag") - return - } - - if pubkey == "" && addr == "" { - err = fmt.Errorf("at least one of --pubkey or --addr must be given") - return - } else if pubkey != "" { - if addr != "" { - nodeClient.Logger().InfoMsg("Both a public key and an address have been specified. The public key takes precedent.", - "public_key", pubkey, - "address", addr, - ) - } - var pubKeyBytes []byte - pubKeyBytes, err = hex.DecodeString(pubkey) - if err != nil { - err = fmt.Errorf("pubkey is bad hex: %v", err) - return - } - pub, err = crypto.PublicKeyFromBytes(pubKeyBytes, crypto.CurveTypeEd25519) - if err != nil { - return - } - } else { - // grab the pubkey from monax-keys - addressBytes, err2 := hex.DecodeString(addr) - if err2 != nil { - err = fmt.Errorf("Bad hex string for address (%s): %v", addr, err) - return - } - address, err2 := crypto.AddressFromBytes(addressBytes) - if err2 != nil { - err = fmt.Errorf("Could not convert bytes (%X) to address: %v", addressBytes, err2) - } - pub, err2 = keyClient.PublicKey(address) - if err2 != nil { - err = fmt.Errorf("Failed to fetch pubkey for address (%s): %v", addr, err2) - return - } - } - - var address crypto.Address - address = pub.Address() - - amt, err = strconv.ParseUint(amtS, 10, 64) - if err != nil { - err = fmt.Errorf("amt is misformatted: %v", err) - } - - if sequenceS == "" { - if nodeClient == nil { - err = fmt.Errorf("input must specify a sequence with the --sequence flag or use --node-addr (or BURROW_CLIENT_NODE_ADDR) to fetch the sequence from a node") - return - } - // fetch sequence from node - account, err2 := nodeClient.GetAccount(address) - if err2 != nil { - return pub, amt, sequence, err2 - } - sequence = account.Sequence() + 1 - nodeClient.Logger().TraceMsg("Fetch sequence from node", - "sequence", sequence, - "account address", address, - ) - } else { - sequence, err = strconv.ParseUint(sequenceS, 10, 64) - if err != nil { - err = fmt.Errorf("sequence is misformatted: %v", err) - return - } - } - - return -} diff --git a/client/websocket_client.go b/client/websocket_client.go deleted file mode 100644 index 2580dc4bb..000000000 --- a/client/websocket_client.go +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package client - -import ( - "bytes" - "fmt" - "time" - - "encoding/json" - - "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/execution/errors" - exeEvents "github.com/hyperledger/burrow/execution/events" - "github.com/hyperledger/burrow/logging" - "github.com/hyperledger/burrow/logging/structure" - "github.com/hyperledger/burrow/rpc" - rpcClient "github.com/hyperledger/burrow/rpc/lib/client" - "github.com/hyperledger/burrow/rpc/tm/client" - "github.com/hyperledger/burrow/txs" - tmTypes "github.com/tendermint/tendermint/types" -) - -const ( - MaxCommitWaitTimeSeconds = 10 -) - -type Confirmation struct { - BlockHash []byte - EventDataTx *exeEvents.EventDataTx - Exception error - Error error -} - -// NOTE [ben] Compiler check to ensure burrowNodeClient successfully implements -// burrow/client.NodeClient -var _ NodeWebsocketClient = (*burrowNodeWebsocketClient)(nil) - -type burrowNodeWebsocketClient struct { - // TODO: assert no memory leak on closing with open websocket - tendermintWebsocket *rpcClient.WSClient - logger *logging.Logger -} - -// Subscribe to an eventid -func (burrowNodeWebsocketClient *burrowNodeWebsocketClient) Subscribe(eventId string) error { - // TODO we can in the background listen to the subscription id and remember it to ease unsubscribing later. - return client.Subscribe(burrowNodeWebsocketClient.tendermintWebsocket, - eventId) -} - -// Unsubscribe from an eventid -func (burrowNodeWebsocketClient *burrowNodeWebsocketClient) Unsubscribe(subscriptionId string) error { - return client.Unsubscribe(burrowNodeWebsocketClient.tendermintWebsocket, - subscriptionId) -} - -// Returns a channel that will receive a confirmation with a result or the exception that -// has been confirmed; or an error is returned and the confirmation channel is nil. -func (burrowNodeWebsocketClient *burrowNodeWebsocketClient) WaitForConfirmation(txEnv *txs.Envelope, - inputAddr crypto.Address) (chan Confirmation, error) { - - // Setup the confirmation channel to be returned - confirmationChannel := make(chan Confirmation, 1) - var latestBlockHash []byte - - eventID := exeEvents.EventStringAccountInput(inputAddr) - if err := burrowNodeWebsocketClient.Subscribe(eventID); err != nil { - return nil, fmt.Errorf("Error subscribing to AccInput event (%s): %v", eventID, err) - } - if err := burrowNodeWebsocketClient.Subscribe(tmTypes.EventNewBlock); err != nil { - return nil, fmt.Errorf("Error subscribing to NewBlock event: %v", err) - } - // Read the incoming events - go func() { - var err error - - timeoutTimer := time.NewTimer(time.Duration(MaxCommitWaitTimeSeconds) * time.Second) - defer func() { - if !timeoutTimer.Stop() { - <-timeoutTimer.C - } - }() - - for { - select { - case <-timeoutTimer.C: - confirmationChannel <- Confirmation{ - BlockHash: nil, - EventDataTx: nil, - Exception: nil, - Error: fmt.Errorf("timed out waiting for event"), - } - return - - case response := <-burrowNodeWebsocketClient.tendermintWebsocket.ResponsesCh: - if response.Error != nil { - burrowNodeWebsocketClient.logger.InfoMsg( - "Error received on websocket channel", structure.ErrorKey, err) - continue - } - - switch response.ID { - case client.SubscribeRequestID: - resultSubscribe := new(rpc.ResultSubscribe) - err = json.Unmarshal(response.Result, resultSubscribe) - if err != nil { - burrowNodeWebsocketClient.logger.InfoMsg("Unable to unmarshal ResultSubscribe", - structure.ErrorKey, err) - continue - } - // TODO: collect subscription IDs, push into channel and on completion - burrowNodeWebsocketClient.logger.InfoMsg("Received confirmation for event", - "event", resultSubscribe.EventID, - "subscription_id", resultSubscribe.SubscriptionID) - - case client.EventResponseID(tmTypes.EventNewBlock): - resultEvent := new(rpc.ResultEvent) - err = json.Unmarshal(response.Result, resultEvent) - if err != nil { - burrowNodeWebsocketClient.logger.InfoMsg("Unable to unmarshal ResultEvent", - structure.ErrorKey, err) - continue - } - blockData := resultEvent.Tendermint.EventDataNewBlock() - if blockData != nil { - latestBlockHash = blockData.Block.Hash() - burrowNodeWebsocketClient.logger.TraceMsg("Registered new block", - "block", blockData.Block, - "latest_block_hash", latestBlockHash, - ) - } - - case client.EventResponseID(eventID): - resultEvent := new(rpc.ResultEvent) - err = json.Unmarshal(response.Result, resultEvent) - if err != nil { - burrowNodeWebsocketClient.logger.InfoMsg("Unable to unmarshal ResultEvent", - structure.ErrorKey, err) - continue - } - - eventDataTx := resultEvent.Execution.GetTx() - if eventDataTx == nil { - // We are on the lookout for EventDataTx - confirmationChannel <- Confirmation{ - BlockHash: latestBlockHash, - EventDataTx: nil, - Exception: fmt.Errorf("response error: expected result.Data to be *types.EventDataTx"), - Error: nil, - } - return - } - - if !bytes.Equal(eventDataTx.Tx.Hash(), txEnv.Tx.Hash()) { - burrowNodeWebsocketClient.logger.TraceMsg("Received different event", - // TODO: consider re-implementing TxID again, or other more clear debug - "received transaction event", eventDataTx.Tx.Hash()) - continue - } - - if eventDataTx.Exception != nil && eventDataTx.Exception.ErrorCode() != errors.ErrorCodeExecutionReverted { - confirmationChannel <- Confirmation{ - BlockHash: latestBlockHash, - EventDataTx: eventDataTx, - Exception: errors.Wrap(eventDataTx.Exception, - "transaction confirmed but execution gave exception: %v"), - Error: nil, - } - return - } - // success, return the full event and blockhash and exit go-routine - confirmationChannel <- Confirmation{ - BlockHash: latestBlockHash, - EventDataTx: eventDataTx, - Exception: nil, - Error: nil, - } - return - - default: - burrowNodeWebsocketClient.logger.InfoMsg("Received unsolicited response", - "response_id", response.ID, - "expected_response_id", client.EventResponseID(eventID)) - } - } - } - - }() - - return confirmationChannel, nil -} - -func (burrowNodeWebsocketClient *burrowNodeWebsocketClient) Close() { - if burrowNodeWebsocketClient.tendermintWebsocket != nil { - burrowNodeWebsocketClient.tendermintWebsocket.Stop() - } -} diff --git a/client/ws_client.go b/client/ws_client.go deleted file mode 100644 index cdcb0b570..000000000 --- a/client/ws_client.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package client - -// NOTE: this websocket client acts on rpc/v0, -// uses github.com/gorilla/websocket -// and will be deprecated after 0.12 -// It is recommended to use the interfaces NodeClient -// and NodeWebsocketClient. -// Websocket client implementation. This will be used in tests. - -import ( - "fmt" - "net/http" - - "github.com/gorilla/websocket" -) - -// A websocket client subscribes and unsubscribes to events -type WSClient struct { - host string - closed bool - conn *websocket.Conn -} - -// create a new connection -func NewWSClient(addr string) *WSClient { - return &WSClient{ - host: addr, - } -} - -func (this *WSClient) Dial() (*http.Response, error) { - dialer := websocket.DefaultDialer - rHeader := http.Header{} - conn, r, err := dialer.Dial(this.host, rHeader) - if err != nil { - return r, err - } - this.conn = conn - - return r, nil -} - -// returns a channel from which messages can be pulled -// from a go routine that reads the socket. -// if the ws returns an error (eg. closes), we return -func (this *WSClient) StartRead() <-chan []byte { - ch := make(chan []byte) - go func() { - for { - _, msg, err := this.conn.ReadMessage() - if err != nil { - if !this.closed { - // TODO For now. - fmt.Println("Error: " + err.Error()) - close(ch) - } - return - } - ch <- msg - } - }() - return ch -} - -func (this *WSClient) WriteMsg(msg []byte) { - this.conn.WriteMessage(websocket.TextMessage, msg) -} - -func (this *WSClient) Close() { - this.closed = true - this.conn.Close() -} diff --git a/cmd/burrow/commands/configure.go b/cmd/burrow/commands/configure.go index 142309de5..c64d4c72a 100644 --- a/cmd/burrow/commands/configure.go +++ b/cmd/burrow/commands/configure.go @@ -17,8 +17,8 @@ import ( "github.com/hyperledger/burrow/logging" logging_config "github.com/hyperledger/burrow/logging/config" "github.com/hyperledger/burrow/logging/config/presets" - "github.com/jawher/mow.cli" - "github.com/tendermint/go-amino" + cli "github.com/jawher/mow.cli" + amino "github.com/tendermint/go-amino" tm_crypto "github.com/tendermint/go-crypto" "github.com/tendermint/tendermint/p2p" ) diff --git a/cmd/burrow/commands/keys.go b/cmd/burrow/commands/keys.go index e8ba5d4b0..8fcf1a817 100644 --- a/cmd/burrow/commands/keys.go +++ b/cmd/burrow/commands/keys.go @@ -7,6 +7,7 @@ import ( "os" "github.com/hyperledger/burrow/deployment" + cli "github.com/jawher/mow.cli" "time" @@ -16,9 +17,7 @@ import ( "github.com/hyperledger/burrow/config" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/keys" - "github.com/hyperledger/burrow/keys/pbkeys" "github.com/hyperledger/burrow/logging/lifecycle" - "github.com/jawher/mow.cli" "google.golang.org/grpc" ) @@ -38,14 +37,14 @@ func Keys(output Output) func(cmd *cli.Cmd) { EnvVar: "MONAX_KEYS_PORT", }) - grpcKeysClient := func(output Output) pbkeys.KeysClient { + grpcKeysClient := func(output Output) keys.KeysClient { var opts []grpc.DialOption opts = append(opts, grpc.WithInsecure()) conn, err := grpc.Dial(*keysHost+":"+*keysPort, opts...) if err != nil { output.Fatalf("Failed to connect to grpc server: %v", err) } - return pbkeys.NewKeysClient(conn) + return keys.NewKeysClient(conn) } cmd.Command("server", "run keys server", func(cmd *cli.Cmd) { @@ -108,7 +107,7 @@ func Keys(output Output) func(cmd *cli.Cmd) { c := grpcKeysClient(output) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - resp, err := c.GenerateKey(ctx, &pbkeys.GenRequest{Passphrase: password, Curvetype: curve.String(), Keyname: *keyName}) + resp, err := c.GenerateKey(ctx, &keys.GenRequest{Passphrase: password, CurveType: curve.String(), KeyName: *keyName}) if err != nil { output.Fatalf("failed to generate key: %v", err) } @@ -139,7 +138,7 @@ func Keys(output Output) func(cmd *cli.Cmd) { c := grpcKeysClient(output) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - resp, err := c.Hash(ctx, &pbkeys.HashRequest{Hashtype: *hashType, Message: message}) + resp, err := c.Hash(ctx, &keys.HashRequest{Hashtype: *hashType, Message: message}) if err != nil { output.Fatalf("failed to get public key: %v", err) } @@ -158,7 +157,7 @@ func Keys(output Output) func(cmd *cli.Cmd) { c := grpcKeysClient(output) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - resp, err := c.Export(ctx, &pbkeys.ExportRequest{Passphrase: *passphrase, Name: *keyName, Address: *keyAddr}) + resp, err := c.Export(ctx, &keys.ExportRequest{Passphrase: *passphrase, Name: *keyName, Address: *keyAddr}) if err != nil { output.Fatalf("failed to export key: %v", err) } @@ -170,7 +169,7 @@ func Keys(output Output) func(cmd *cli.Cmd) { key := deployment.Key{ Name: *keyName, - CurveType: resp.GetCurvetype(), + CurveType: resp.GetCurveType(), Address: addr, PublicKey: resp.GetPublickey(), PrivateKey: resp.GetPrivatekey(), @@ -212,7 +211,7 @@ func Keys(output Output) func(cmd *cli.Cmd) { defer cancel() if (*key)[:1] == "{" { - resp, err := c.ImportJSON(ctx, &pbkeys.ImportJSONRequest{JSON: *key}) + resp, err := c.ImportJSON(ctx, &keys.ImportJSONRequest{JSON: *key}) if err != nil { output.Fatalf("failed to import json key: %v", err) } @@ -223,7 +222,7 @@ func Keys(output Output) func(cmd *cli.Cmd) { if err != nil { output.Fatalf("failed to hex decode key: %s", *key) } - resp, err := c.Import(ctx, &pbkeys.ImportRequest{Passphrase: password, Keybytes: privKeyBytes, Curvetype: *curveType}) + resp, err := c.Import(ctx, &keys.ImportRequest{Passphrase: password, KeyBytes: privKeyBytes, CurveType: *curveType}) if err != nil { output.Fatalf("failed to import json key: %v", err) } @@ -242,12 +241,12 @@ func Keys(output Output) func(cmd *cli.Cmd) { c := grpcKeysClient(output) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - resp, err := c.PublicKey(ctx, &pbkeys.PubRequest{Name: *name, Address: *addr}) + resp, err := c.PublicKey(ctx, &keys.PubRequest{Name: *name, Address: *addr}) if err != nil { output.Fatalf("failed to get public key: %v", err) } - fmt.Printf("%X\n", resp.GetPub()) + fmt.Printf("%X\n", resp.GetPublicKey()) } }) @@ -266,7 +265,7 @@ func Keys(output Output) func(cmd *cli.Cmd) { c := grpcKeysClient(output) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - resp, err := c.Sign(ctx, &pbkeys.SignRequest{Passphrase: *passphrase, Name: *name, Address: *addr, Message: message}) + resp, err := c.Sign(ctx, &keys.SignRequest{Passphrase: *passphrase, Name: *name, Address: *addr, Message: message}) if err != nil { output.Fatalf("failed to get public key: %v", err) } @@ -300,7 +299,10 @@ func Keys(output Output) func(cmd *cli.Cmd) { c := grpcKeysClient(output) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - _, err = c.Verify(ctx, &pbkeys.VerifyRequest{Curvetype: *curveType, Pub: publickey, Signature: signature, Message: message}) + _, err = c.Verify(ctx, &keys.VerifyRequest{ + CurveType: *curveType, + PublicKey: publickey, + Signature: signature, Message: message}) if err != nil { output.Fatalf("failed to verify: %v", err) } @@ -316,7 +318,7 @@ func Keys(output Output) func(cmd *cli.Cmd) { c := grpcKeysClient(output) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - _, err := c.AddName(ctx, &pbkeys.AddNameRequest{Keyname: *keyname, Address: *addr}) + _, err := c.AddName(ctx, &keys.AddNameRequest{Keyname: *keyname, Address: *addr}) if err != nil { output.Fatalf("failed to add name to addr: %v", err) } @@ -330,13 +332,13 @@ func Keys(output Output) func(cmd *cli.Cmd) { c := grpcKeysClient(output) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - resp, err := c.List(ctx, &pbkeys.ListRequest{}) + resp, err := c.List(ctx, &keys.ListRequest{}) if err != nil { output.Fatalf("failed to list key names: %v", err) } if *name != "" { for _, k := range resp.Key { - if k.Keyname == *name { + if k.KeyName == *name { output.Printf("%s\n", k.Address) } } @@ -355,7 +357,7 @@ func Keys(output Output) func(cmd *cli.Cmd) { c := grpcKeysClient(output) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - _, err := c.RemoveName(ctx, &pbkeys.RemoveNameRequest{Keyname: *name}) + _, err := c.RemoveName(ctx, &keys.RemoveNameRequest{KeyName: *name}) if err != nil { output.Fatalf("failed to remove key: %v", err) } diff --git a/cmd/burrow/commands/spec.go b/cmd/burrow/commands/spec.go index 36fad65a7..1110d869e 100644 --- a/cmd/burrow/commands/spec.go +++ b/cmd/burrow/commands/spec.go @@ -5,7 +5,7 @@ import ( "github.com/hyperledger/burrow/config/source" "github.com/hyperledger/burrow/genesis/spec" - "github.com/jawher/mow.cli" + cli "github.com/jawher/mow.cli" ) func Spec(output Output) func(cmd *cli.Cmd) { diff --git a/cmd/burrow/commands/start.go b/cmd/burrow/commands/start.go index e3d11c130..e6b56f09b 100644 --- a/cmd/burrow/commands/start.go +++ b/cmd/burrow/commands/start.go @@ -4,7 +4,7 @@ import ( "context" "github.com/hyperledger/burrow/crypto" - "github.com/jawher/mow.cli" + cli "github.com/jawher/mow.cli" ) func Start(output Output) func(cmd *cli.Cmd) { diff --git a/cmd/burrow/main.go b/cmd/burrow/main.go index 0bc401363..38c17d59f 100644 --- a/cmd/burrow/main.go +++ b/cmd/burrow/main.go @@ -6,7 +6,7 @@ import ( "github.com/hyperledger/burrow/cmd/burrow/commands" "github.com/hyperledger/burrow/project" - "github.com/jawher/mow.cli" + cli "github.com/jawher/mow.cli" ) func main() { diff --git a/config/config.go b/config/config.go index c9958d56d..c22ddbb11 100644 --- a/config/config.go +++ b/config/config.go @@ -40,6 +40,7 @@ func DefaultBurrowConfig() *BurrowConfig { Tendermint: tendermint.DefaultBurrowTendermintConfig(), Keys: keys.DefaultKeysConfig(), RPC: rpc.DefaultRPCConfig(), + Execution: execution.DefaultExecutionConfig(), Logging: logging_config.DefaultNodeLoggingConfig(), } } diff --git a/consensus/tendermint/abci/app.go b/consensus/tendermint/abci/app.go index ba7fec9f5..6c5247481 100644 --- a/consensus/tendermint/abci/app.go +++ b/consensus/tendermint/abci/app.go @@ -5,7 +5,7 @@ import ( "sync" "time" - "encoding/json" + "runtime/debug" bcm "github.com/hyperledger/burrow/blockchain" "github.com/hyperledger/burrow/consensus/tendermint/codes" @@ -26,11 +26,13 @@ type App struct { blockchain *bcm.Blockchain checker execution.BatchExecutor committer execution.BatchCommitter + checkTx func(txBytes []byte) abciTypes.ResponseCheckTx + deliverTx func(txBytes []byte) abciTypes.ResponseCheckTx mempoolLocker sync.Locker // We need to cache these from BeginBlock for when we need actually need it in Commit block *abciTypes.RequestBeginBlock - // Utility - txDecoder txs.Decoder + // Function to use to fail gracefully from panic rather than letting Tendermint make us a zombie + panicFunc func(error) // Logging logger *logging.Logger } @@ -38,12 +40,14 @@ type App struct { var _ abciTypes.Application = &App{} func NewApp(blockchain *bcm.Blockchain, checker execution.BatchExecutor, committer execution.BatchCommitter, - txDecoder txs.Decoder, logger *logging.Logger) *App { + txDecoder txs.Decoder, panicFunc func(error), logger *logging.Logger) *App { return &App{ blockchain: blockchain, checker: checker, committer: committer, - txDecoder: txDecoder, + checkTx: txExecutor(checker, txDecoder, logger.WithScope("CheckTx")), + deliverTx: txExecutor(committer, txDecoder, logger.WithScope("DeliverTx")), + panicFunc: panicFunc, logger: logger.WithScope("abci.NewApp").With(structure.ComponentKey, "ABCI_App"), } } @@ -77,50 +81,6 @@ func (app *App) Query(reqQuery abciTypes.RequestQuery) (respQuery abciTypes.Resp return } -func (app *App) CheckTx(txBytes []byte) abciTypes.ResponseCheckTx { - txEnv, err := app.txDecoder.DecodeTx(txBytes) - if err != nil { - app.logger.TraceMsg("CheckTx decoding error", - "tag", "CheckTx", - structure.ErrorKey, err) - return abciTypes.ResponseCheckTx{ - Code: codes.EncodingErrorCode, - Log: fmt.Sprintf("Encoding error: %s", err), - } - } - receipt := txEnv.Tx.GenerateReceipt() - - err = app.checker.Execute(txEnv) - if err != nil { - app.logger.TraceMsg("CheckTx execution error", - structure.ErrorKey, err, - "tag", "CheckTx", - "tx_hash", receipt.TxHash, - "creates_contract", receipt.CreatesContract) - return abciTypes.ResponseCheckTx{ - Code: codes.EncodingErrorCode, - Log: fmt.Sprintf("CheckTx could not execute transaction: %s, error: %v", txEnv, err), - } - } - - receiptBytes, err := json.Marshal(receipt) - if err != nil { - return abciTypes.ResponseCheckTx{ - Code: codes.TxExecutionErrorCode, - Log: fmt.Sprintf("CheckTx could not serialise receipt: %s", err), - } - } - app.logger.TraceMsg("CheckTx success", - "tag", "CheckTx", - "tx_hash", receipt.TxHash, - "creates_contract", receipt.CreatesContract) - return abciTypes.ResponseCheckTx{ - Code: codes.TxExecutionSuccessCode, - Log: "CheckTx success - receipt in data", - Data: receiptBytes, - } -} - func (app *App) InitChain(chain abciTypes.RequestInitChain) (respInitChain abciTypes.ResponseInitChain) { // Could verify agreement on initial validator set here return @@ -131,47 +91,74 @@ func (app *App) BeginBlock(block abciTypes.RequestBeginBlock) (respBeginBlock ab return } +func (app *App) CheckTx(txBytes []byte) abciTypes.ResponseCheckTx { + defer func() { + if r := recover(); r != nil { + app.panicFunc(fmt.Errorf("panic occurred in abci.App/CheckTx: %v\n%s", r, debug.Stack())) + } + }() + return app.checkTx(txBytes) +} + func (app *App) DeliverTx(txBytes []byte) abciTypes.ResponseDeliverTx { - txEnv, err := app.txDecoder.DecodeTx(txBytes) - if err != nil { - app.logger.TraceMsg("DeliverTx decoding error", - "tag", "DeliverTx", - structure.ErrorKey, err) - return abciTypes.ResponseDeliverTx{ - Code: codes.EncodingErrorCode, - Log: fmt.Sprintf("Encoding error: %s", err), + defer func() { + if r := recover(); r != nil { + app.panicFunc(fmt.Errorf("panic occurred in abci.App/DeliverTx: %v\n%s", r, debug.Stack())) } + }() + ctr := app.deliverTx(txBytes) + // Currently these message types are identical, if they are ever different can map between + return abciTypes.ResponseDeliverTx{ + Code: ctr.Code, + Log: ctr.Log, + Data: ctr.Data, + Tags: ctr.Tags, + Fee: ctr.Fee, + GasUsed: ctr.GasUsed, + GasWanted: ctr.GasWanted, + Info: ctr.Info, } +} - receipt := txEnv.Tx.GenerateReceipt() - err = app.committer.Execute(txEnv) - if err != nil { - app.logger.TraceMsg("DeliverTx execution error", - structure.ErrorKey, err, - "tag", "DeliverTx", - "tx_hash", receipt.TxHash, - "creates_contract", receipt.CreatesContract) - return abciTypes.ResponseDeliverTx{ - Code: codes.TxExecutionErrorCode, - Log: fmt.Sprintf("DeliverTx could not execute transaction: %s, error: %s", txEnv, err), +func txExecutor(executor execution.BatchExecutor, txDecoder txs.Decoder, logger *logging.Logger) func(txBytes []byte) abciTypes.ResponseCheckTx { + return func(txBytes []byte) abciTypes.ResponseCheckTx { + txEnv, err := txDecoder.DecodeTx(txBytes) + if err != nil { + logger.TraceMsg("Decoding error", + structure.ErrorKey, err) + return abciTypes.ResponseCheckTx{ + Code: codes.EncodingErrorCode, + Log: fmt.Sprintf("Encoding error: %s", err), + } } - } - app.logger.TraceMsg("DeliverTx success", - "tag", "DeliverTx", - "tx_hash", receipt.TxHash, - "creates_contract", receipt.CreatesContract) - receiptBytes, err := json.Marshal(receipt) - if err != nil { - return abciTypes.ResponseDeliverTx{ - Code: codes.TxExecutionErrorCode, - Log: fmt.Sprintf("DeliverTx could not serialise receipt: %s", err), + txe, err := executor.Execute(txEnv) + if err != nil { + logger.TraceMsg("Execution error", + structure.ErrorKey, err, + "tx_hash", txEnv.Tx.Hash()) + return abciTypes.ResponseCheckTx{ + Code: codes.EncodingErrorCode, + Log: fmt.Sprintf("Could not execute transaction: %s, error: %v", txEnv, err), + } + } + + bs, err := txe.Receipt.Encode() + if err != nil { + return abciTypes.ResponseCheckTx{ + Code: codes.TxExecutionErrorCode, + Log: fmt.Sprintf("Could not serialise receipt: %s", err), + } + } + logger.TraceMsg("Execution success", + "tx_hash", txe.TxHash, + "contract_address", txe.Receipt.ContractAddress, + "creates_contract", txe.Receipt.CreatesContract) + return abciTypes.ResponseCheckTx{ + Code: codes.TxExecutionSuccessCode, + Log: "Execution success - TxExecution in data", + Data: bs, } - } - return abciTypes.ResponseDeliverTx{ - Code: codes.TxExecutionSuccessCode, - Log: "DeliverTx success - receipt in data", - Data: receiptBytes, } } @@ -192,6 +179,11 @@ func (app *App) EndBlock(reqEndBlock abciTypes.RequestEndBlock) abciTypes.Respon } func (app *App) Commit() abciTypes.ResponseCommit { + defer func() { + if r := recover(); r != nil { + app.panicFunc(fmt.Errorf("panic occurred in abci.App/Commit: %v\n%s", r, debug.Stack())) + } + }() app.logger.InfoMsg("Committing block", "tag", "Commit", structure.ScopeKey, "Commit()", @@ -229,7 +221,8 @@ func (app *App) Commit() abciTypes.ResponseCommit { // First commit the app start, this app hash will not get checkpointed until the next block when we are sure // that nothing in the downstream commit process could have failed. At worst we go back one block. - appHash, err := app.committer.Commit() + blockHeader := app.block.Header + appHash, err := app.committer.Commit(&blockHeader) if err != nil { panic(errors.Wrap(err, "Could not commit transactions in block to execution state")) } diff --git a/consensus/tendermint/events.go b/consensus/tendermint/events.go deleted file mode 100644 index c85f976c0..000000000 --- a/consensus/tendermint/events.go +++ /dev/null @@ -1,103 +0,0 @@ -package tendermint - -import ( - "context" - - "github.com/hyperledger/burrow/event" - "github.com/hyperledger/burrow/event/query" - "github.com/hyperledger/burrow/logging/structure" - "github.com/tendermint/tendermint/libs/pubsub" - tm_types "github.com/tendermint/tendermint/types" -) - -// Publishes all tendermint events available on subscribable to publisher -func PublishAllEvents(ctx context.Context, fromSubscribable event.Subscribable, subscriber string, - toPublisher event.Publisher) error { - - var err error - - // This is a work-around for the fact we cannot access a message's tags and need a separate query for each event type - tendermintEventTypes := []string{ - tm_types.EventBond, - tm_types.EventCompleteProposal, - tm_types.EventDupeout, - tm_types.EventFork, - tm_types.EventLock, - tm_types.EventNewBlock, - tm_types.EventNewBlockHeader, - tm_types.EventNewRound, - tm_types.EventNewRoundStep, - tm_types.EventPolka, - tm_types.EventRebond, - tm_types.EventRelock, - tm_types.EventTimeoutPropose, - tm_types.EventTimeoutWait, - tm_types.EventTx, - tm_types.EventUnbond, - tm_types.EventUnlock, - tm_types.EventVote, - tm_types.EventProposalHeartbeat, - } - - for _, eventType := range tendermintEventTypes { - publishErr := PublishEvent(ctx, fromSubscribable, subscriber, eventType, toPublisher) - if publishErr != nil && err == nil { - err = publishErr - } - } - - return err -} - -func PublishEvent(ctx context.Context, fromSubscribable event.Subscribable, subscriber string, eventType string, - toPublisher event.Publisher) error { - tags := map[string]interface{}{ - structure.ComponentKey: "Tendermint", - tm_types.EventTypeKey: eventType, - event.EventIDKey: eventType, - } - return event.PublishAll(ctx, fromSubscribable, subscriber, query.WrapQuery(tm_types.QueryForEvent(eventType)), - toPublisher, tags) -} - -type eventBusSubscriber struct { - tm_types.EventBusSubscriber -} - -func EventBusAsSubscribable(eventBus tm_types.EventBusSubscriber) event.Subscribable { - return eventBusSubscriber{eventBus} -} - -func (ebs eventBusSubscriber) Subscribe(ctx context.Context, subscriber string, queryable query.Queryable, - out chan<- interface{}) error { - qry, err := queryable.Query() - if err != nil { - return err - } - return ebs.EventBusSubscriber.Subscribe(ctx, subscriber, qry, out) -} - -func (ebs eventBusSubscriber) Unsubscribe(ctx context.Context, subscriber string, queryable query.Queryable) error { - qry, err := queryable.Query() - if err != nil { - return err - } - return ebs.EventBusSubscriber.Unsubscribe(ctx, subscriber, qry) -} - -type subscribableEventBus struct { - event.Subscribable -} - -func SubscribableAsEventBus(subscribable event.Subscribable) tm_types.EventBusSubscriber { - return subscribableEventBus{subscribable} -} - -func (seb subscribableEventBus) Subscribe(ctx context.Context, subscriber string, qry pubsub.Query, - out chan<- interface{}) error { - return seb.Subscribable.Subscribe(ctx, subscriber, query.WrapQuery(qry), out) -} - -func (seb subscribableEventBus) Unsubscribe(ctx context.Context, subscriber string, qry pubsub.Query) error { - return seb.Subscribable.Unsubscribe(ctx, subscriber, query.WrapQuery(qry)) -} diff --git a/consensus/tendermint/logger.go b/consensus/tendermint/logger.go index 6022f4730..2a73c22fb 100644 --- a/consensus/tendermint/logger.go +++ b/consensus/tendermint/logger.go @@ -9,7 +9,7 @@ type tendermintLogger struct { logger *logging.Logger } -func NewLogger(logger *logging.Logger) *tendermintLogger { +func NewLogger(logger *logging.Logger) log.Logger { return &tendermintLogger{ logger: logger, } diff --git a/consensus/tendermint/tendermint.go b/consensus/tendermint/tendermint.go index e7ddf260b..3ada43cf2 100644 --- a/consensus/tendermint/tendermint.go +++ b/consensus/tendermint/tendermint.go @@ -1,25 +1,22 @@ package tendermint import ( - "context" - "os" "path" bcm "github.com/hyperledger/burrow/blockchain" "github.com/hyperledger/burrow/consensus/tendermint/abci" "github.com/hyperledger/burrow/event" - "github.com/hyperledger/burrow/event/query" "github.com/hyperledger/burrow/execution" "github.com/hyperledger/burrow/genesis" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" "github.com/hyperledger/burrow/txs" - tm_crypto "github.com/tendermint/go-crypto" + tmCrypto "github.com/tendermint/go-crypto" "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/node" "github.com/tendermint/tendermint/proxy" - tm_types "github.com/tendermint/tendermint/types" + tmTypes "github.com/tendermint/tendermint/types" dbm "github.com/tendermint/tmlibs/db" ) @@ -31,7 +28,7 @@ type Node struct { } } -var NewBlockQuery = query.Must(event.QueryForEventID(tm_types.EventNewBlock).Query()) +var NewBlockQuery = event.QueryForEventID(tmTypes.EventNewBlock) func DBProvider(ID string, backendType dbm.DBBackendType, dbDir string) dbm.DB { return dbm.NewDB(ID, backendType, dbDir) @@ -50,9 +47,9 @@ func (n *Node) Close() { } } -func NewNode(conf *config.Config, privValidator tm_types.PrivValidator, genesisDoc *tm_types.GenesisDoc, +func NewNode(conf *config.Config, privValidator tmTypes.PrivValidator, genesisDoc *tmTypes.GenesisDoc, blockchain *bcm.Blockchain, checker execution.BatchExecutor, committer execution.BatchCommitter, - txDecoder txs.Decoder, logger *logging.Logger) (*Node, error) { + txDecoder txs.Decoder, panicFunc func(error), logger *logging.Logger) (*Node, error) { var err error // disable Tendermint's RPC @@ -64,11 +61,11 @@ func NewNode(conf *config.Config, privValidator tm_types.PrivValidator, genesisD } nde := &Node{} - app := abci.NewApp(blockchain, checker, committer, txDecoder, logger) + app := abci.NewApp(blockchain, checker, committer, txDecoder, panicFunc, logger) conf.NodeKeyFile() nde.Node, err = node.NewNode(conf, privValidator, proxy.NewLocalClientCreator(app), - func() (*tm_types.GenesisDoc, error) { + func() (*tmTypes.GenesisDoc, error) { return genesisDoc, nil }, nde.DBProvider, @@ -81,56 +78,33 @@ func NewNode(conf *config.Config, privValidator tm_types.PrivValidator, genesisD return nde, nil } -func DeriveGenesisDoc(burrowGenesisDoc *genesis.GenesisDoc) *tm_types.GenesisDoc { - validators := make([]tm_types.GenesisValidator, len(burrowGenesisDoc.Validators)) +func DeriveGenesisDoc(burrowGenesisDoc *genesis.GenesisDoc) *tmTypes.GenesisDoc { + validators := make([]tmTypes.GenesisValidator, len(burrowGenesisDoc.Validators)) for i, validator := range burrowGenesisDoc.Validators { - tm := tm_crypto.PubKeyEd25519{} + tm := tmCrypto.PubKeyEd25519{} copy(tm[:], validator.PublicKey.RawBytes()) - validators[i] = tm_types.GenesisValidator{ + validators[i] = tmTypes.GenesisValidator{ PubKey: tm, Name: validator.Name, Power: int64(validator.Amount), } } - return &tm_types.GenesisDoc{ + return &tmTypes.GenesisDoc{ ChainID: burrowGenesisDoc.ChainID(), GenesisTime: burrowGenesisDoc.GenesisTime, Validators: validators, AppHash: burrowGenesisDoc.Hash(), - ConsensusParams: tm_types.DefaultConsensusParams(), + ConsensusParams: tmTypes.DefaultConsensusParams(), } } -func NewBlockEvent(message interface{}) *tm_types.EventDataNewBlock { - tmEventData, ok := message.(tm_types.TMEventData) +func NewBlockEvent(message interface{}) *tmTypes.EventDataNewBlock { + tmEventData, ok := message.(tmTypes.TMEventData) if ok { - eventDataNewBlock, ok := tmEventData.(tm_types.EventDataNewBlock) + eventDataNewBlock, ok := tmEventData.(tmTypes.EventDataNewBlock) if ok { return &eventDataNewBlock } } return nil } - -// Subscribe to NewBlock event safely that ensures progress by a non-blocking receive as well as handling unsubscribe -func SubscribeNewBlock(ctx context.Context, subscribable event.Subscribable) (<-chan *tm_types.EventDataNewBlock, error) { - subID, err := event.GenerateSubscriptionID() - if err != nil { - return nil, err - } - const unconsumedBlocksBeforeUnsubscribe = 3 - ch := make(chan *tm_types.EventDataNewBlock, unconsumedBlocksBeforeUnsubscribe) - return ch, event.SubscribeCallback(ctx, subscribable, subID, NewBlockQuery, func(message interface{}) (stop bool) { - eventDataNewBlock := NewBlockEvent(message) - if eventDataNewBlock != nil { - select { - case ch <- eventDataNewBlock: - return false - default: - // If we can't send shut down the channel - return true - } - } - return - }) -} diff --git a/consensus/tendermint/validator/priv_validator_memory.go b/consensus/tendermint/validator/priv_validator_memory.go index 7f5077c1f..05455cba2 100644 --- a/consensus/tendermint/validator/priv_validator_memory.go +++ b/consensus/tendermint/validator/priv_validator_memory.go @@ -1,7 +1,7 @@ package validator import ( - acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/crypto" tm_crypto "github.com/tendermint/go-crypto" tm_types "github.com/tendermint/tendermint/types" diff --git a/core/kernel.go b/core/kernel.go index 1ea5f95b9..fee805da8 100644 --- a/core/kernel.go +++ b/core/kernel.go @@ -32,32 +32,28 @@ import ( "github.com/hyperledger/burrow/consensus/tendermint/query" "github.com/hyperledger/burrow/event" "github.com/hyperledger/burrow/execution" - "github.com/hyperledger/burrow/execution/events/pbevents" - "github.com/hyperledger/burrow/execution/pbtransactor" "github.com/hyperledger/burrow/genesis" "github.com/hyperledger/burrow/keys" - "github.com/hyperledger/burrow/keys/pbkeys" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" "github.com/hyperledger/burrow/process" "github.com/hyperledger/burrow/rpc" "github.com/hyperledger/burrow/rpc/metrics" "github.com/hyperledger/burrow/rpc/rpcevents" - "github.com/hyperledger/burrow/rpc/rpctransactor" + "github.com/hyperledger/burrow/rpc/rpcquery" + "github.com/hyperledger/burrow/rpc/rpctransact" "github.com/hyperledger/burrow/rpc/tm" - "github.com/hyperledger/burrow/rpc/v0" - v0_server "github.com/hyperledger/burrow/rpc/v0/server" "github.com/hyperledger/burrow/txs" - tm_config "github.com/tendermint/tendermint/config" - tm_types "github.com/tendermint/tendermint/types" + tmConfig "github.com/tendermint/tendermint/config" + tmTypes "github.com/tendermint/tendermint/types" dbm "github.com/tendermint/tmlibs/db" - "google.golang.org/grpc/reflection" ) const ( CooldownMilliseconds = 1000 ServerShutdownTimeoutMilliseconds = 1000 LoggingCallerDepth = 5 + AccountsRingMutexCount = 100 ) // Kernel is the root structure of Burrow @@ -74,10 +70,14 @@ type Kernel struct { shutdownOnce sync.Once } -func NewKernel(ctx context.Context, keyClient keys.KeyClient, privValidator tm_types.PrivValidator, - genesisDoc *genesis.GenesisDoc, tmConf *tm_config.Config, rpcConfig *rpc.RPCConfig, keyConfig *keys.KeysConfig, +func NewKernel(ctx context.Context, keyClient keys.KeyClient, privValidator tmTypes.PrivValidator, + genesisDoc *genesis.GenesisDoc, tmConf *tmConfig.Config, rpcConfig *rpc.RPCConfig, keyConfig *keys.KeysConfig, keyStore *keys.KeyStore, exeOptions []execution.ExecutionOption, logger *logging.Logger) (*Kernel, error) { + kern := &Kernel{ + processes: make(map[string]process.Process), + shutdownNotify: make(chan struct{}), + } logger = logger.WithScope("NewKernel()").With(structure.TimeKey, kitlog.DefaultTimestampUTC) tmLogger := logger.With(structure.CallerKey, kitlog.Caller(LoggingCallerDepth+1)) logger = logger.WithInfo(structure.CallerKey, kitlog.Caller(LoggingCallerDepth)) @@ -107,16 +107,17 @@ func NewKernel(ctx context.Context, keyClient keys.KeyClient, privValidator tm_t emitter := event.NewEmitter(logger) committer := execution.NewBatchCommitter(state, blockchain.Tip, emitter, logger, exeOptions...) tmNode, err := tendermint.NewNode(tmConf, privValidator, tmGenesisDoc, blockchain, checker, committer, txCodec, - tmLogger) + kern.Panic, tmLogger) if err != nil { return nil, err } - transactor := execution.NewTransactor(blockchain.Tip, emitter, tmNode.MempoolReactor().BroadcastTx, txCodec, - logger) + + transactor := execution.NewTransactor(blockchain.Tip, emitter, execution.NewAccounts(checker, keyClient, AccountsRingMutexCount), + tmNode.MempoolReactor().BroadcastTx, txCodec, logger) nameRegState := state accountState := state - service := rpc.NewService(ctx, accountState, nameRegState, checker, emitter, blockchain, keyClient, transactor, + service := rpc.NewService(accountState, nameRegState, blockchain, transactor, query.NewNodeView(tmNode, txCodec), logger) launchers := []process.Launcher{ @@ -155,14 +156,6 @@ func NewKernel(ctx context.Context, keyClient keys.KeyClient, privValidator tm_t if err != nil { return nil, fmt.Errorf("error starting Tendermint node: %v", err) } - subscriber := fmt.Sprintf("TendermintFireHose-%s-%s", genesisDoc.ChainName, genesisDoc.ChainID()) - // Multiplex Tendermint and EVM events - - err = tendermint.PublishAllEvents(ctx, tendermint.EventBusAsSubscribable(tmNode.EventBus()), subscriber, - emitter) - if err != nil { - return nil, fmt.Errorf("could not subscribe to Tendermint events: %v", err) - } return process.ShutdownFunc(func(ctx context.Context) error { err := tmNode.Stop() // Close tendermint database connections using our wrapper @@ -185,7 +178,7 @@ func NewKernel(ctx context.Context, keyClient keys.KeyClient, privValidator tm_t Name: "RPC/tm", Enabled: rpcConfig.TM.Enabled, Launch: func() (process.Process, error) { - server, err := tm.StartServer(service, "/websocket", rpcConfig.TM.ListenAddress, emitter, logger) + server, err := tm.StartServer(service, "/websocket", rpcConfig.TM.ListenAddress, logger) if err != nil { return nil, err } @@ -203,26 +196,6 @@ func NewKernel(ctx context.Context, keyClient keys.KeyClient, privValidator tm_t return server, nil }, }, - { - Name: "RPC/V0", - Enabled: rpcConfig.V0.Enabled, - Launch: func() (process.Process, error) { - codec := v0.NewTCodec() - jsonServer := v0.NewJSONServer(v0.NewJSONService(codec, service, logger)) - websocketServer := v0_server.NewWebSocketServer(rpcConfig.V0.Server.WebSocket.MaxWebSocketSessions, - v0.NewWebsocketService(codec, service, logger), logger) - - serveProcess, err := v0_server.NewServeProcess(rpcConfig.V0.Server, logger, jsonServer, websocketServer) - if err != nil { - return nil, err - } - err = serveProcess.Start() - if err != nil { - return nil, err - } - return serveProcess, nil - }, - }, { Name: "RPC/GRPC", Enabled: rpcConfig.GRPC.Enabled, @@ -231,6 +204,7 @@ func NewKernel(ctx context.Context, keyClient keys.KeyClient, privValidator tm_t if err != nil { return nil, err } + listen.Addr() grpcServer := rpc.NewGRPCServer(logger) var ks *keys.KeyStore @@ -242,19 +216,18 @@ func NewKernel(ctx context.Context, keyClient keys.KeyClient, privValidator tm_t if keyStore == nil { ks = keys.NewKeyStore(keyConfig.KeysDirectory, keyConfig.AllowBadFilePermissions, logger) } - pbkeys.RegisterKeysServer(grpcServer, ks) + keys.RegisterKeysServer(grpcServer, ks) } - pbtransactor.RegisterTransactorServer(grpcServer, rpctransactor.NewTransactorServer(service.Transactor(), - service.MempoolAccounts(), state, txCodec)) + rpcquery.RegisterQueryServer(grpcServer, rpcquery.NewQueryServer(state, nameRegState)) - pbevents.RegisterEventsServer(grpcServer, rpcevents.NewEventsServer(rpc.NewSubscriptions(service))) + rpctransact.RegisterTransactServer(grpcServer, rpctransact.NewTransactServer(transactor, txCodec)) - pbevents.RegisterExecutionEventsServer(grpcServer, rpcevents.NewExecutionEventsServer(state, emitter, - blockchain.Tip)) + rpcevents.RegisterExecutionEventsServer(grpcServer, rpcevents.NewExecutionEventsServer(state, emitter, + blockchain.Tip, logger)) // Provides metadata about services registered - reflection.Register(grpcServer) + //reflection.Register(grpcServer) go grpcServer.Serve(listen) @@ -267,16 +240,13 @@ func NewKernel(ctx context.Context, keyClient keys.KeyClient, privValidator tm_t }, } - return &Kernel{ - Emitter: emitter, - Service: service, - Launchers: launchers, - State: state, - Blockchain: blockchain, - Logger: logger, - processes: make(map[string]process.Process), - shutdownNotify: make(chan struct{}), - }, nil + kern.Emitter = emitter + kern.Service = service + kern.Launchers = launchers + kern.State = state + kern.Blockchain = blockchain + kern.Logger = logger + return kern, nil } // Boot the kernel starting Tendermint and RPC layers @@ -295,6 +265,12 @@ func (kern *Kernel) Boot() error { return nil } +func (kern *Kernel) Panic(err error) { + fmt.Fprintf(os.Stderr, "Kernel shutting down due to panic: %v", err) + kern.Shutdown(context.Background()) + os.Exit(1) +} + // Wait for a graceful shutdown func (kern *Kernel) WaitForShutdown() { // Supports multiple goroutines waiting for shutdown since channel is closed diff --git a/crypto/address.go b/crypto/address.go index a72f8c02d..9dab20155 100644 --- a/crypto/address.go +++ b/crypto/address.go @@ -120,6 +120,35 @@ func (address *Address) UnmarshalText(text []byte) error { func (address Address) MarshalText() ([]byte, error) { return ([]byte)(hex.EncodeUpperToString(address[:])), nil + +} + +// Gogo proto support +func (address *Address) Marshal() ([]byte, error) { + if address == nil { + return nil, nil + } + return address.Bytes(), nil +} + +func (address *Address) Unmarshal(data []byte) error { + if len(data) == 0 { + return nil + } + if len(data) != binary.Word160Length { + return fmt.Errorf("error unmarshallling address '%X' from bytes: %d bytes but should have %d bytes", + data, len(data), binary.Word160Length) + } + copy(address[:], data) + return nil +} + +func (address *Address) MarshalTo(data []byte) (int, error) { + return copy(data, address[:]), nil +} + +func (address *Address) Size() int { + return binary.Word160Length } func NewContractAddress(caller Address, sequence uint64) (newAddr Address) { diff --git a/crypto/crypto.go b/crypto/crypto.go index a1d588e90..e5f62db10 100644 --- a/crypto/crypto.go +++ b/crypto/crypto.go @@ -4,7 +4,7 @@ import ( "fmt" ) -type CurveType int8 +type CurveType uint32 const ( CurveTypeSecp256k1 CurveType = iota diff --git a/crypto/crypto.pb.go b/crypto/crypto.pb.go new file mode 100644 index 000000000..230f0f5e5 --- /dev/null +++ b/crypto/crypto.pb.go @@ -0,0 +1,555 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: crypto.proto + +/* + Package crypto is a generated protocol buffer package. + + It is generated from these files: + crypto.proto + + It has these top-level messages: + PublicKey + PrivateKey +*/ +package crypto + +import proto "github.com/gogo/protobuf/proto" +import golang_proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" +import _ "github.com/gogo/protobuf/gogoproto" + +import io "io" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = golang_proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package + +// PublicKey +type PublicKey struct { + CurveType CurveType `protobuf:"varint,1,opt,name=CurveType,proto3,casttype=CurveType" json:"CurveType,omitempty"` + PublicKey []byte `protobuf:"bytes,2,opt,name=PublicKey,proto3" json:"PublicKey,omitempty"` +} + +func (m *PublicKey) Reset() { *m = PublicKey{} } +func (*PublicKey) ProtoMessage() {} +func (*PublicKey) Descriptor() ([]byte, []int) { return fileDescriptorCrypto, []int{0} } + +func (m *PublicKey) GetCurveType() CurveType { + if m != nil { + return m.CurveType + } + return 0 +} + +func (m *PublicKey) GetPublicKey() []byte { + if m != nil { + return m.PublicKey + } + return nil +} + +func (*PublicKey) XXX_MessageName() string { + return "crypto.PublicKey" +} + +type PrivateKey struct { + CurveType CurveType `protobuf:"varint,1,opt,name=CurveType,proto3,casttype=CurveType" json:"CurveType,omitempty"` + // Note may need initialisation + PublicKey []byte `protobuf:"bytes,2,opt,name=PublicKey,proto3" json:"PublicKey,omitempty"` + PrivateKey []byte `protobuf:"bytes,3,opt,name=PrivateKey,proto3" json:"PrivateKey,omitempty"` +} + +func (m *PrivateKey) Reset() { *m = PrivateKey{} } +func (*PrivateKey) ProtoMessage() {} +func (*PrivateKey) Descriptor() ([]byte, []int) { return fileDescriptorCrypto, []int{1} } + +func (*PrivateKey) XXX_MessageName() string { + return "crypto.PrivateKey" +} +func init() { + proto.RegisterType((*PublicKey)(nil), "crypto.PublicKey") + golang_proto.RegisterType((*PublicKey)(nil), "crypto.PublicKey") + proto.RegisterType((*PrivateKey)(nil), "crypto.PrivateKey") + golang_proto.RegisterType((*PrivateKey)(nil), "crypto.PrivateKey") +} +func (m *PublicKey) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PublicKey) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.CurveType != 0 { + dAtA[i] = 0x8 + i++ + i = encodeVarintCrypto(dAtA, i, uint64(m.CurveType)) + } + if len(m.PublicKey) > 0 { + dAtA[i] = 0x12 + i++ + i = encodeVarintCrypto(dAtA, i, uint64(len(m.PublicKey))) + i += copy(dAtA[i:], m.PublicKey) + } + return i, nil +} + +func (m *PrivateKey) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PrivateKey) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.CurveType != 0 { + dAtA[i] = 0x8 + i++ + i = encodeVarintCrypto(dAtA, i, uint64(m.CurveType)) + } + if len(m.PublicKey) > 0 { + dAtA[i] = 0x12 + i++ + i = encodeVarintCrypto(dAtA, i, uint64(len(m.PublicKey))) + i += copy(dAtA[i:], m.PublicKey) + } + if len(m.PrivateKey) > 0 { + dAtA[i] = 0x1a + i++ + i = encodeVarintCrypto(dAtA, i, uint64(len(m.PrivateKey))) + i += copy(dAtA[i:], m.PrivateKey) + } + return i, nil +} + +func encodeVarintCrypto(dAtA []byte, offset int, v uint64) int { + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return offset + 1 +} +func (m *PublicKey) Size() (n int) { + var l int + _ = l + if m.CurveType != 0 { + n += 1 + sovCrypto(uint64(m.CurveType)) + } + l = len(m.PublicKey) + if l > 0 { + n += 1 + l + sovCrypto(uint64(l)) + } + return n +} + +func (m *PrivateKey) Size() (n int) { + var l int + _ = l + if m.CurveType != 0 { + n += 1 + sovCrypto(uint64(m.CurveType)) + } + l = len(m.PublicKey) + if l > 0 { + n += 1 + l + sovCrypto(uint64(l)) + } + l = len(m.PrivateKey) + if l > 0 { + n += 1 + l + sovCrypto(uint64(l)) + } + return n +} + +func sovCrypto(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n +} +func sozCrypto(x uint64) (n int) { + return sovCrypto(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *PublicKey) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCrypto + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PublicKey: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PublicKey: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field CurveType", wireType) + } + m.CurveType = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCrypto + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.CurveType |= (CurveType(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PublicKey", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCrypto + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthCrypto + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PublicKey = append(m.PublicKey[:0], dAtA[iNdEx:postIndex]...) + if m.PublicKey == nil { + m.PublicKey = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipCrypto(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthCrypto + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PrivateKey) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCrypto + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PrivateKey: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PrivateKey: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field CurveType", wireType) + } + m.CurveType = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCrypto + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.CurveType |= (CurveType(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PublicKey", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCrypto + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthCrypto + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PublicKey = append(m.PublicKey[:0], dAtA[iNdEx:postIndex]...) + if m.PublicKey == nil { + m.PublicKey = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PrivateKey", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCrypto + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthCrypto + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PrivateKey = append(m.PrivateKey[:0], dAtA[iNdEx:postIndex]...) + if m.PrivateKey == nil { + m.PrivateKey = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipCrypto(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthCrypto + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipCrypto(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowCrypto + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowCrypto + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowCrypto + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + iNdEx += length + if length < 0 { + return 0, ErrInvalidLengthCrypto + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowCrypto + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipCrypto(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} + +var ( + ErrInvalidLengthCrypto = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowCrypto = fmt.Errorf("proto: integer overflow") +) + +func init() { proto.RegisterFile("crypto.proto", fileDescriptorCrypto) } +func init() { golang_proto.RegisterFile("crypto.proto", fileDescriptorCrypto) } + +var fileDescriptorCrypto = []byte{ + // 221 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x49, 0x2e, 0xaa, 0x2c, + 0x28, 0xc9, 0xd7, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x83, 0xf0, 0xa4, 0x74, 0xd3, 0x33, + 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, 0xd3, 0xf3, 0xd3, 0xf3, 0xf5, 0xc1, 0xd2, + 0x49, 0xa5, 0x69, 0x60, 0x1e, 0x98, 0x03, 0x66, 0x41, 0xb4, 0x29, 0xc5, 0x70, 0x71, 0x06, 0x94, + 0x26, 0xe5, 0x64, 0x26, 0x7b, 0xa7, 0x56, 0x0a, 0x69, 0x73, 0x71, 0x3a, 0x97, 0x16, 0x95, 0xa5, + 0x86, 0x54, 0x16, 0xa4, 0x4a, 0x30, 0x2a, 0x30, 0x6a, 0xf0, 0x3a, 0xf1, 0xfe, 0xba, 0x27, 0x8f, + 0x10, 0x0c, 0x42, 0x30, 0x85, 0x64, 0x90, 0x74, 0x4a, 0x30, 0x29, 0x30, 0x6a, 0xf0, 0x04, 0x21, + 0x04, 0xac, 0x58, 0x66, 0x2c, 0x90, 0x67, 0x50, 0x6a, 0x64, 0xe4, 0xe2, 0x0a, 0x28, 0xca, 0x2c, + 0x4b, 0x2c, 0x49, 0xa5, 0xae, 0xf9, 0x42, 0x72, 0xc8, 0x06, 0x4b, 0x30, 0x83, 0xa5, 0x91, 0x44, + 0xac, 0x38, 0x3a, 0x16, 0xc8, 0x33, 0x80, 0xdc, 0xe0, 0x64, 0x75, 0xe2, 0x91, 0x1c, 0xe3, 0x85, + 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x1e, 0x78, 0x2c, 0xc7, 0x78, 0xe2, 0xb1, 0x1c, 0x63, + 0x94, 0x0a, 0x52, 0x30, 0x65, 0x54, 0x16, 0xa4, 0x16, 0xe5, 0xa4, 0xa6, 0xa4, 0xa7, 0x16, 0xe9, + 0x27, 0x95, 0x16, 0x15, 0xe5, 0x97, 0xeb, 0x43, 0x02, 0x33, 0x89, 0x0d, 0x1c, 0x48, 0xc6, 0x80, + 0x00, 0x00, 0x00, 0xff, 0xff, 0x5f, 0x49, 0x55, 0xc8, 0x6b, 0x01, 0x00, 0x00, +} diff --git a/crypto/private_key.go b/crypto/private_key.go index f1bad1896..91252e09f 100644 --- a/crypto/private_key.go +++ b/crypto/private_key.go @@ -11,12 +11,6 @@ import ( "golang.org/x/crypto/ed25519" ) -type PrivateKey struct { - CurveType CurveType - PublicKey []byte - PrivateKey []byte -} - // Currently this is a stub that reads the raw bytes returned by key_client and returns // an ed25519 public key. func PublicKeyFromBytes(bs []byte, curveType CurveType) (PublicKey, error) { @@ -46,25 +40,25 @@ func (p PrivateKey) Sign(msg []byte) (Signature, error) { switch p.CurveType { case CurveTypeEd25519: if len(p.PrivateKey) != ed25519.PrivateKeySize { - return Signature{}, fmt.Errorf("bytes passed have length %v but ed25519 private keys have %v bytes", + return nil, fmt.Errorf("bytes passed have length %v but ed25519 private keys have %v bytes", len(p.PrivateKey), ed25519.PrivateKeySize) } privKey := ed25519.PrivateKey(p.PrivateKey) - return Signature{ed25519.Sign(privKey, msg)}, nil + return ed25519.Sign(privKey, msg), nil case CurveTypeSecp256k1: if len(p.PrivateKey) != btcec.PrivKeyBytesLen { - return Signature{}, fmt.Errorf("bytes passed have length %v but secp256k1 private keys have %v bytes", + return nil, fmt.Errorf("bytes passed have length %v but secp256k1 private keys have %v bytes", len(p.PrivateKey), btcec.PrivKeyBytesLen) } privKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), p.PrivateKey) sig, err := privKey.Sign(msg) if err != nil { - return Signature{}, err + return nil, err } - return Signature{Signature: sig.Serialize()}, nil + return sig.Serialize(), nil default: - return Signature{}, ErrInvalidCurve(p.CurveType) + return nil, ErrInvalidCurve(p.CurveType) } } @@ -72,6 +66,20 @@ func (p PrivateKey) GetPublicKey() PublicKey { return PublicKey{CurveType: p.CurveType, PublicKey: p.PublicKey} } +// Reinitialise after serialisation +func (p *PrivateKey) Reinitialise() error { + initP, err := PrivateKeyFromRawBytes(p.RawBytes(), p.CurveType) + if err != nil { + return err + } + *p = initP + return nil +} + +func (p PrivateKey) String() string { + return fmt.Sprintf("PrivateKey", p.PublicKey) +} + func PrivateKeyFromRawBytes(privKeyBytes []byte, curveType CurveType) (PrivateKey, error) { switch curveType { case CurveTypeEd25519: @@ -86,7 +94,10 @@ func PrivateKeyFromRawBytes(privKeyBytes []byte, curveType CurveType) (PrivateKe len(privKeyBytes), btcec.PrivKeyBytesLen) } privKey, pubKey := btcec.PrivKeyFromBytes(btcec.S256(), privKeyBytes) - return PrivateKey{PrivateKey: privKey.Serialize(), PublicKey: pubKey.SerializeCompressed(), CurveType: CurveTypeSecp256k1}, nil + if !bytes.Equal(privKey.Serialize(), privKeyBytes) { + return PrivateKey{}, fmt.Errorf("serialisation of Secp256k1 private key bytes does not equal") + } + return PrivateKey{PrivateKey: privKeyBytes, PublicKey: pubKey.SerializeCompressed(), CurveType: CurveTypeSecp256k1}, nil default: return PrivateKey{}, ErrInvalidCurve(curveType) } diff --git a/crypto/public_key.go b/crypto/public_key.go index b3281c61f..f837b38d1 100644 --- a/crypto/public_key.go +++ b/crypto/public_key.go @@ -13,14 +13,6 @@ import ( "golang.org/x/crypto/ripemd160" ) -// PublicKey -type PublicKey struct { - CurveType CurveType - PublicKey []byte - // memoised address - address *Address -} - type PublicKeyJSON struct { CurveType string PublicKey string @@ -83,13 +75,13 @@ func (p PublicKey) IsValid() bool { func (p PublicKey) Verify(msg []byte, signature Signature) bool { switch p.CurveType { case CurveTypeEd25519: - return ed25519.Verify(p.PublicKey, msg, signature.Signature[:]) + return ed25519.Verify(p.PublicKey, msg, signature) case CurveTypeSecp256k1: pub, err := btcec.ParsePubKey(p.PublicKey, btcec.S256()) if err != nil { return false } - sig, err := btcec.ParseDERSignature(signature.Signature, btcec.S256()) + sig, err := btcec.ParseDERSignature(signature, btcec.S256()) if err != nil { return false } @@ -100,14 +92,6 @@ func (p PublicKey) Verify(msg []byte, signature Signature) bool { } func (p PublicKey) Address() Address { - if p.address == nil { - address := p.computeAddress() - p.address = &address - } - return *p.address -} - -func (p PublicKey) computeAddress() Address { switch p.CurveType { case CurveTypeEd25519: // FIMXE: tendermint go-crypto-0.5.0 uses weird scheme, this is fixed in 0.6.0 diff --git a/crypto/public_key_test.go b/crypto/public_key_test.go new file mode 100644 index 000000000..f6c211a35 --- /dev/null +++ b/crypto/public_key_test.go @@ -0,0 +1,30 @@ +package crypto + +import ( + "encoding/json" + "testing" + + "github.com/gogo/protobuf/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestPublicKeySerialisation(t *testing.T) { + priv := PrivateKeyFromSecret("foo", CurveTypeEd25519) + pub := priv.GetPublicKey() + expectedAddress := Address{ + 0x83, 0x20, 0x78, 0x17, 0xdc, 0x38, 0x14, 0xb9, 0x6f, 0x57, + 0xef, 0xf9, 0x25, 0xf4, 0x67, 0xe0, 0x7c, 0xaa, 0x91, 0x38, + } + assert.Equal(t, expectedAddress, pub.Address()) + bs, err := proto.Marshal(&pub) + require.NoError(t, err) + var pubOut PublicKey + err = proto.Unmarshal(bs, &pubOut) + assert.Equal(t, pub, pubOut) + + bs, err = json.Marshal(pub) + require.NoError(t, err) + assert.Equal(t, `{"CurveType":"ed25519","PublicKey":"34D26579DBB456693E540672CF922F52DDE0D6532E35BF06BE013A7C532F20E0"}`, + string(bs)) +} diff --git a/crypto/signature.go b/crypto/signature.go index 0ef84f461..be11336ee 100644 --- a/crypto/signature.go +++ b/crypto/signature.go @@ -3,37 +3,64 @@ package crypto import ( "fmt" - "github.com/hyperledger/burrow/binary" + "github.com/tmthrgd/go-hex" "golang.org/x/crypto/ed25519" ) -type Signature struct { - Signature binary.HexBytes -} +type Signature []byte -// Currently this is a stub that reads the raw bytes returned by key_client and returns -// an ed25519 signature. func SignatureFromBytes(bs []byte, curveType CurveType) (Signature, error) { switch curveType { case CurveTypeEd25519: - signatureEd25519 := Signature{} + var signatureEd25519 Signature if len(bs) != ed25519.SignatureSize { - return Signature{}, fmt.Errorf("bytes passed have length %v by ed25519 signatures have %v bytes", + return nil, fmt.Errorf("bytes passed have length %v by ed25519 signatures have %v bytes", len(bs), ed25519.SignatureSize) } - copy(signatureEd25519.Signature[:], bs) - return Signature{ - Signature: bs, - }, nil + copy(signatureEd25519, bs) + return bs, nil case CurveTypeSecp256k1: - return Signature{ - Signature: bs, - }, nil + return bs, nil default: - return Signature{}, nil + return nil, nil } } func (sig Signature) RawBytes() []byte { - return sig.Signature + return sig +} + +func (sig *Signature) UnmarshalText(hexBytes []byte) error { + bs, err := hex.DecodeString(string(hexBytes)) + if err != nil { + return err + } + *sig = bs + return nil +} + +func (sig Signature) MarshalText() ([]byte, error) { + return []byte(sig.String()), nil +} + +func (sig Signature) String() string { + return hex.EncodeUpperToString(sig) +} + +// Protobuf support +func (sig Signature) Marshal() ([]byte, error) { + return sig, nil +} + +func (sig *Signature) Unmarshal(data []byte) error { + *sig = data + return nil +} + +func (sig Signature) MarshalTo(data []byte) (int, error) { + return copy(data, sig), nil +} + +func (sig Signature) Size() int { + return len(sig) } diff --git a/deployment/config.go b/deployment/config.go index dc70796d6..ff935f05d 100644 --- a/deployment/config.go +++ b/deployment/config.go @@ -11,8 +11,8 @@ import ( "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/genesis" "github.com/pkg/errors" - "github.com/tmthrgd/go-hex" - "gopkg.in/yaml.v2" + hex "github.com/tmthrgd/go-hex" + yaml "gopkg.in/yaml.v2" ) type Validator struct { diff --git a/event/cache.go b/event/cache.go deleted file mode 100644 index 75f676cfc..000000000 --- a/event/cache.go +++ /dev/null @@ -1,88 +0,0 @@ -package event - -import ( - "context" -) - -// When exceeded we will trim the buffer's backing array capacity to avoid excessive -// allocation -const maximumBufferCapacityToLengthRatio = 2 - -// A Cache buffers events for a Publisher. -type Cache struct { - events []messageInfo -} - -// If message implement this interface we will provide them with an index in the cache -type Indexable interface { - ProvideIndex(index uint64) -} - -var _ Publisher = &Cache{} - -// Create a new Cache with an EventSwitch as backend -func NewCache() *Cache { - return &Cache{} -} - -// a cached event -type messageInfo struct { - // Hmm... might be unintended interactions with pushing a deadline into a cache - though usually we publish with an - // empty context - ctx context.Context - message interface{} - tags Tags -} - -// Cache an event to be fired upon finality. -func (evc *Cache) Publish(ctx context.Context, message interface{}, tags Tags) error { - // append to list (go will grow our backing array exponentially) - evc.events = append(evc.events, messageInfo{ - ctx: ctx, - message: evc.provideIndex(message), - tags: tags, - }) - return nil -} - -func (evc *Cache) Flush(publisher Publisher) error { - err := evc.Sync(publisher) - if err != nil { - return err - } - evc.Reset() - return nil -} - -// Clears cached events by flushing them to Publisher -func (evc *Cache) Sync(publisher Publisher) error { - var err error - for _, mi := range evc.events { - publishErr := publisher.Publish(mi.ctx, mi.message, mi.tags) - // Capture first by try to sync the rest - if publishErr != nil && err == nil { - err = publishErr - } - } - return err -} - -func (evc *Cache) Reset() { - // Clear the buffer by re-slicing its length to zero - if cap(evc.events) > len(evc.events)*maximumBufferCapacityToLengthRatio { - // Trim the backing array capacity when it is more than double the length of the slice to avoid tying up memory - // after a spike in the number of events to buffer - evc.events = evc.events[:0:len(evc.events)] - } else { - // Re-slice the length to 0 to clear buffer but hang on to spare capacity in backing array that has been added - // in previous cache round - evc.events = evc.events[:0] - } -} - -func (evc *Cache) provideIndex(message interface{}) interface{} { - if im, ok := message.(Indexable); ok { - im.ProvideIndex(uint64(len(evc.events))) - } - return message -} diff --git a/event/cache_test.go b/event/cache_test.go deleted file mode 100644 index 52bcbd664..000000000 --- a/event/cache_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package event - -import ( - "context" - "fmt" - "testing" - "time" - - "github.com/hyperledger/burrow/event/query" - "github.com/hyperledger/burrow/logging" - "github.com/stretchr/testify/assert" -) - -func TestEventCache_Flush(t *testing.T) { - //ctx, cancel := context.WithTimeout(context.Background(), 5 * time.Second) - //defer cancel() - ctx := context.Background() - errCh := make(chan error) - flushed := false - - em := NewEmitter(logging.NewNoopLogger()) - SubscribeCallback(ctx, em, "nothingness", query.NewBuilder(), func(message interface{}) (stop bool) { - // Check against sending a buffer of zeroed messages - if message == nil { - errCh <- fmt.Errorf("recevied empty message but none sent") - } - return true - }) - evc := NewCache() - evc.Flush(em) - // Check after reset - evc.Flush(em) - SubscribeCallback(ctx, em, "somethingness", query.NewBuilder().AndEquals("foo", "bar"), - func(interface{}) (stop bool) { - if flushed { - errCh <- nil - return false - } else { - errCh <- fmt.Errorf("callback was run before messages were flushed") - return true - } - }) - - numMessages := 3 - tags := TagMap{"foo": "bar"} - for i := 0; i < numMessages; i++ { - evc.Publish(ctx, fmt.Sprintf("something_%v", i), tags) - } - flushed = true - evc.Flush(em) - for i := 0; i < numMessages; i++ { - select { - case <-time.After(2 * time.Second): - t.Fatalf("callback did not run before timeout after messages were sent") - case err := <-errCh: - if err != nil { - t.Error(err) - } - } - } -} - -func TestEventCacheGrowth(t *testing.T) { - em := NewEmitter(logging.NewNoopLogger()) - evc := NewCache() - - fireNEvents(evc, 100) - c := cap(evc.events) - evc.Flush(em) - assert.Equal(t, c, cap(evc.events), "cache cap should remain the same after flushing events") - - fireNEvents(evc, c/maximumBufferCapacityToLengthRatio+1) - evc.Flush(em) - assert.Equal(t, c, cap(evc.events), "cache cap should remain the same after flushing more than half "+ - "the number of events as last time") - - fireNEvents(evc, c/maximumBufferCapacityToLengthRatio-1) - evc.Flush(em) - assert.True(t, c > cap(evc.events), "cache cap should drop after flushing fewer than half "+ - "the number of events as last time") - - fireNEvents(evc, c*2*maximumBufferCapacityToLengthRatio) - evc.Flush(em) - assert.True(t, c < cap(evc.events), "cache cap should grow after flushing more events than seen before") - - for numEvents := 100; numEvents >= 0; numEvents-- { - fireNEvents(evc, numEvents) - evc.Flush(em) - assert.True(t, cap(evc.events) <= maximumBufferCapacityToLengthRatio*numEvents, - "cap (%v) should be at most twice numEvents (%v)", cap(evc.events), numEvents) - } -} - -func fireNEvents(evc *Cache, n int) { - for i := 0; i < n; i++ { - evc.Publish(context.Background(), "something", nil) - } -} diff --git a/event/convention.go b/event/convention.go index dede8493b..4f586c152 100644 --- a/event/convention.go +++ b/event/convention.go @@ -1,12 +1,6 @@ package event import ( - "context" - - "time" - - "fmt" - "github.com/hyperledger/burrow/event/query" ) @@ -14,88 +8,15 @@ const ( EventTypeKey = "EventType" EventIDKey = "EventID" MessageTypeKey = "MessageType" - TxTypeKey = "TxType" TxHashKey = "TxHash" HeightKey = "Height" IndexKey = "Index" - NameKey = "Name" - PermissionKey = "Permission" StackDepthKey = "StackDepth" AddressKey = "Address" - OriginKey = "Origin" - CalleeKey = "Callee" - CallerKey = "Caller" - ValueKey = "Value" - GasKey = "Gas" - ExceptionKey = "Exception" - LogNKeyPrefix = "Log" ) -func LogNKey(topic int) string { - return fmt.Sprintf("%s%d", LogNKeyPrefix, topic) -} - -func LogNTextKey(topic int) string { - return fmt.Sprintf("%s%dText", LogNKeyPrefix, topic) -} - -const SubscribeCallbackTimeout = 2 * time.Second - // Get a query that matches events with a specific eventID func QueryForEventID(eventID string) *query.Builder { // Since we're accepting external output here there is a chance it won't parse... return query.NewBuilder().AndEquals(EventIDKey, eventID) } - -// Subscribe to messages matching query and launch a goroutine to run a callback for each one. The goroutine will exit -// if the callback returns true for 'stop' and clean up the subscription and channel. -func SubscribeCallback(ctx context.Context, subscribable Subscribable, subscriber string, queryable query.Queryable, - callback func(message interface{}) (stop bool)) error { - - out := make(chan interface{}, 1) - stopCh := make(chan bool) - - go func() { - for msg := range out { - go func() { - stopCh <- callback(msg) - }() - - // Stop unless the callback returns - stop := true - select { - case stop = <-stopCh: - case <-time.After(SubscribeCallbackTimeout): - } - - if stop { - // Callback is requesting stop so unsubscribe and drain channel - subscribable.Unsubscribe(context.Background(), subscriber, queryable) - // Not draining channel can starve other subscribers - for range out { - } - return - } - } - }() - err := subscribable.Subscribe(ctx, subscriber, queryable, out) - if err != nil { - // To clean up goroutine - otherwise subscribable should close channel for us - close(out) - } - return err -} - -func PublishAll(ctx context.Context, subscribable Subscribable, subscriber string, queryable query.Queryable, - publisher Publisher, extraTags map[string]interface{}) error { - - return SubscribeCallback(ctx, subscribable, subscriber, queryable, func(message interface{}) (stop bool) { - tags := make(map[string]interface{}) - for k, v := range extraTags { - tags[k] = v - } - // Help! I can't tell which tags the original publisher used - so I can't forward them on - publisher.Publish(ctx, message, TagMap(tags)) - return - }) -} diff --git a/event/convention_test.go b/event/convention_test.go deleted file mode 100644 index 2fd0202de..000000000 --- a/event/convention_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package event - -import ( - "context" - "testing" - "time" - - "github.com/hyperledger/burrow/event/query" - "github.com/hyperledger/burrow/logging" - "github.com/stretchr/testify/assert" -) - -func TestSubscribeCallback(t *testing.T) { - ctx := context.Background() - em := NewEmitter(logging.NewNoopLogger()) - ch := make(chan interface{}) - SubscribeCallback(ctx, em, "TestSubscribeCallback", query.MatchAllQueryable(), - func(msg interface{}) (stop bool) { - ch <- msg - return - }) - - sent := "FROTHY" - - n := 10 - for i := 0; i < n; i++ { - - em.Publish(ctx, sent, nil) - } - - for i := 0; i < n; i++ { - select { - case <-time.After(2 * time.Second): - t.Fatalf("Timed out waiting for event") - case msg := <-ch: - assert.Equal(t, sent, msg) - } - } -} diff --git a/event/emitter.go b/event/emitter.go index 1fd09e81a..c4d1fd413 100644 --- a/event/emitter.go +++ b/event/emitter.go @@ -16,17 +16,15 @@ package event import ( "context" - "crypto/rand" - "encoding/hex" - "fmt" - "strings" + "math/rand" + "github.com/hyperledger/burrow/event/pubsub" "github.com/hyperledger/burrow/event/query" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" "github.com/hyperledger/burrow/process" - "github.com/tendermint/tendermint/libs/pubsub" "github.com/tendermint/tmlibs/common" + "github.com/tmthrgd/go-hex" ) const DefaultEventBufferCapacity = 2 << 10 @@ -36,21 +34,21 @@ const DefaultEventBufferCapacity = 2 << 10 type Subscribable interface { // Subscribe to all events matching query, which is a valid tmlibs Query. Blocking the out channel blocks the entire // pubsub. - Subscribe(ctx context.Context, subscriber string, queryable query.Queryable, out chan<- interface{}) error + Subscribe(ctx context.Context, subscriber string, queryable query.Queryable, bufferSize int) (out <-chan interface{}, err error) // Unsubscribe subscriber from a specific query string. Note the subscribe channel must be drained. Unsubscribe(ctx context.Context, subscriber string, queryable query.Queryable) error UnsubscribeAll(ctx context.Context, subscriber string) error } type Publisher interface { - Publish(ctx context.Context, message interface{}, tag Tags) error + Publish(ctx context.Context, message interface{}, tag query.Tagged) error } var _ Publisher = PublisherFunc(nil) -type PublisherFunc func(ctx context.Context, message interface{}, tags Tags) error +type PublisherFunc func(ctx context.Context, message interface{}, tags query.Tagged) error -func (pf PublisherFunc) Publish(ctx context.Context, message interface{}, tags Tags) error { +func (pf PublisherFunc) Publish(ctx context.Context, message interface{}, tags query.Tagged) error { return pf(ctx, message, tags) } @@ -83,17 +81,17 @@ func (em *emitter) Shutdown(ctx context.Context) error { } // Publisher -func (em *emitter) Publish(ctx context.Context, message interface{}, tags Tags) error { +func (em *emitter) Publish(ctx context.Context, message interface{}, tags query.Tagged) error { return em.pubsubServer.PublishWithTags(ctx, message, tags) } // Subscribable -func (em *emitter) Subscribe(ctx context.Context, subscriber string, queryable query.Queryable, out chan<- interface{}) error { - pubsubQuery, err := queryable.Query() +func (em *emitter) Subscribe(ctx context.Context, subscriber string, queryable query.Queryable, bufferSize int) (<-chan interface{}, error) { + qry, err := queryable.Query() if err != nil { - return nil + return nil, err } - return em.pubsubServer.Subscribe(ctx, subscriber, pubsubQuery, out) + return em.pubsubServer.Subscribe(ctx, subscriber, qry, bufferSize) } func (em *emitter) Unsubscribe(ctx context.Context, subscriber string, queryable query.Queryable) error { @@ -116,20 +114,15 @@ func NewNoOpPublisher() Publisher { type noOpPublisher struct { } -func (nop *noOpPublisher) Publish(ctx context.Context, message interface{}, tags Tags) error { +func (nop *noOpPublisher) Publish(ctx context.Context, message interface{}, tags query.Tagged) error { return nil } // ************************************************************************************** // Helper function -func GenerateSubscriptionID() (string, error) { - b := make([]byte, 32) - _, err := rand.Read(b) - if err != nil { - return "", fmt.Errorf("could not generate random bytes for a subscription"+ - " id: %v", err) - } - rStr := hex.EncodeToString(b) - return strings.ToUpper(rStr), nil +func GenSubID() string { + bs := make([]byte, 32) + rand.Read(bs) + return hex.EncodeUpperToString(bs) } diff --git a/event/emitter_test.go b/event/emitter_test.go index 8325456db..99d8fc760 100644 --- a/event/emitter_test.go +++ b/event/emitter_test.go @@ -5,6 +5,8 @@ import ( "testing" "time" + "strings" + "github.com/hyperledger/burrow/event/query" "github.com/hyperledger/burrow/logging" "github.com/stretchr/testify/assert" @@ -14,17 +16,16 @@ import ( func TestEmitter(t *testing.T) { em := NewEmitter(logging.NewNoopLogger()) ctx := context.Background() - out := make(chan interface{}) - err := em.Subscribe(ctx, "TestEmitter", query.NewBuilder().AndStrictlyGreaterThan("foo", 10), out) + out, err := em.Subscribe(ctx, "TestEmitter", query.NewBuilder().AndStrictlyGreaterThan("foo", 10), 1) require.NoError(t, err) msgMiss := struct{ flob string }{"flib"} - err = em.Publish(ctx, msgMiss, TagMap(map[string]interface{}{"foo": 10})) + err = em.Publish(ctx, msgMiss, query.TagMap{"foo": 10}) assert.NoError(t, err) msgHit := struct{ blib string }{"blab"} - err = em.Publish(ctx, msgHit, TagMap(map[string]interface{}{"foo": 11})) + err = em.Publish(ctx, msgHit, query.TagMap{"foo": 11}) assert.NoError(t, err) select { @@ -38,16 +39,15 @@ func TestEmitter(t *testing.T) { func TestOrdering(t *testing.T) { em := NewEmitter(logging.NewNoopLogger()) ctx := context.Background() - out := make(chan interface{}) - err := em.Subscribe(ctx, "TestOrdering1", query.NewBuilder().AndEquals("foo", "bar"), out) + out1, err := em.Subscribe(ctx, "TestOrdering1", query.NewBuilder().AndEquals("foo", "bar"), 10) require.NoError(t, err) - err = em.Subscribe(ctx, "TestOrdering2", query.NewBuilder().AndEquals("foo", "baz"), out) + out2, err := em.Subscribe(ctx, "TestOrdering2", query.NewBuilder().AndEquals("foo", "baz"), 10) require.NoError(t, err) - barTag := TagMap{"foo": "bar"} - bazTag := TagMap{"foo": "baz"} + barTag := query.TagMap{"foo": "bar"} + bazTag := query.TagMap{"foo": "baz"} msgs := [][]interface{}{ {"baz1", bazTag}, @@ -61,12 +61,17 @@ func TestOrdering(t *testing.T) { go func() { for _, msg := range msgs { - em.Publish(ctx, msg[0], msg[1].(TagMap)) + em.Publish(ctx, msg[0], msg[1].(query.TagMap)) } em.Publish(ctx, "stop", bazTag) }() for _, msg := range msgs { - assert.Equal(t, msg[0], <-out) + str := msg[0].(string) + if strings.HasPrefix(str, "bar") { + assert.Equal(t, str, <-out1) + } else { + assert.Equal(t, str, <-out2) + } } } diff --git a/event/pubsub/example_test.go b/event/pubsub/example_test.go new file mode 100644 index 000000000..68772bd14 --- /dev/null +++ b/event/pubsub/example_test.go @@ -0,0 +1,23 @@ +package pubsub_test + +import ( + "context" + "testing" + + "github.com/hyperledger/burrow/event/pubsub" + "github.com/hyperledger/burrow/event/query" + "github.com/stretchr/testify/require" +) + +func TestExample(t *testing.T) { + s := pubsub.NewServer() + s.Start() + defer s.Stop() + + ctx := context.Background() + ch, err := s.Subscribe(ctx, "example-client", query.MustParse("abci.account.name='John'"), 1) + require.NoError(t, err) + err = s.PublishWithTags(ctx, "Tombstone", query.TagMap(map[string]interface{}{"abci.account.name": "John"})) + require.NoError(t, err) + assertReceive(t, "Tombstone", ch) +} diff --git a/event/pubsub/pubsub.go b/event/pubsub/pubsub.go new file mode 100644 index 000000000..8d7107730 --- /dev/null +++ b/event/pubsub/pubsub.go @@ -0,0 +1,330 @@ +// This package was extracted from Tendermint +// +// Package pubsub implements a pub-sub model with a single publisher (Server) +// and multiple subscribers (clients). +// +// Though you can have multiple publishers by sharing a pointer to a server or +// by giving the same channel to each publisher and publishing messages from +// that channel (fan-in). +// +// Clients subscribe for messages, which could be of any type, using a query. +// When some message is published, we match it with all queries. If there is a +// match, this message will be pushed to all clients, subscribed to that query. +// See query subpackage for our implementation. +package pubsub + +import ( + "context" + "errors" + "sync" + + "github.com/hyperledger/burrow/event/query" + "github.com/tendermint/tmlibs/common" +) + +type operation int + +const ( + sub operation = iota + pub + unsub + shutdown +) + +var ( + // ErrSubscriptionNotFound is returned when a client tries to unsubscribe + // from not existing subscription. + ErrSubscriptionNotFound = errors.New("subscription not found") + + // ErrAlreadySubscribed is returned when a client tries to subscribe twice or + // more using the same query. + ErrAlreadySubscribed = errors.New("already subscribed") +) + +type cmd struct { + op operation + query query.Query + ch chan interface{} + clientID string + msg interface{} + tags query.Tagged +} + +// Server allows clients to subscribe/unsubscribe for messages, publishing +// messages with or without tags, and manages internal state. +type Server struct { + common.BaseService + + cmds chan cmd + cmdsCap int + + mtx sync.RWMutex + subscriptions map[string]map[string]query.Query // subscriber -> query (string) -> query.Query +} + +// Option sets a parameter for the server. +type Option func(*Server) + +// NewServer returns a new server. See the commentary on the Option functions +// for a detailed description of how to configure buffering. If no options are +// provided, the resulting server's queue is unbuffered. +func NewServer(options ...Option) *Server { + s := &Server{ + subscriptions: make(map[string]map[string]query.Query), + } + s.BaseService = *common.NewBaseService(nil, "PubSub", s) + + for _, option := range options { + option(s) + } + + // if BufferCapacity option was not set, the channel is unbuffered + s.cmds = make(chan cmd, s.cmdsCap) + + return s +} + +// BufferCapacity allows you to specify capacity for the internal server's +// queue. Since the server, given Y subscribers, could only process X messages, +// this option could be used to survive spikes (e.g. high amount of +// transactions during peak hours). +func BufferCapacity(cap int) Option { + return func(s *Server) { + if cap > 0 { + s.cmdsCap = cap + } + } +} + +// BufferCapacity returns capacity of the internal server's queue. +func (s *Server) BufferCapacity() int { + return s.cmdsCap +} + +// Subscribe creates a subscription for the given client. It accepts a channel +// on which messages matching the given query can be received. An error will be +// returned to the caller if the context is canceled or if subscription already +// exist for pair clientID and query. +func (s *Server) Subscribe(ctx context.Context, clientID string, qry query.Query, outBuffer int) (<-chan interface{}, error) { + s.mtx.RLock() + clientSubscriptions, ok := s.subscriptions[clientID] + if ok { + _, ok = clientSubscriptions[qry.String()] + } + s.mtx.RUnlock() + if ok { + return nil, ErrAlreadySubscribed + } + // We are responsible for closing this channel so we create it + out := make(chan interface{}, outBuffer) + select { + case s.cmds <- cmd{op: sub, clientID: clientID, query: qry, ch: out}: + s.mtx.Lock() + if _, ok = s.subscriptions[clientID]; !ok { + s.subscriptions[clientID] = make(map[string]query.Query) + } + // preserve original query + // see Unsubscribe + s.subscriptions[clientID][qry.String()] = qry + s.mtx.Unlock() + return out, nil + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +// Unsubscribe removes the subscription on the given query. An error will be +// returned to the caller if the context is canceled or if subscription does +// not exist. +func (s *Server) Unsubscribe(ctx context.Context, clientID string, qry query.Query) error { + var origQuery query.Query + s.mtx.RLock() + clientSubscriptions, ok := s.subscriptions[clientID] + if ok { + origQuery, ok = clientSubscriptions[qry.String()] + } + s.mtx.RUnlock() + if !ok { + return ErrSubscriptionNotFound + } + + // original query is used here because we're using pointers as map keys + select { + case s.cmds <- cmd{op: unsub, clientID: clientID, query: origQuery}: + s.mtx.Lock() + delete(clientSubscriptions, qry.String()) + s.mtx.Unlock() + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +// UnsubscribeAll removes all client subscriptions. An error will be returned +// to the caller if the context is canceled or if subscription does not exist. +func (s *Server) UnsubscribeAll(ctx context.Context, clientID string) error { + s.mtx.RLock() + _, ok := s.subscriptions[clientID] + s.mtx.RUnlock() + if !ok { + return ErrSubscriptionNotFound + } + + select { + case s.cmds <- cmd{op: unsub, clientID: clientID}: + s.mtx.Lock() + delete(s.subscriptions, clientID) + s.mtx.Unlock() + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +// Publish publishes the given message. An error will be returned to the caller +// if the context is canceled. +func (s *Server) Publish(ctx context.Context, msg interface{}) error { + return s.PublishWithTags(ctx, msg, query.TagMap(make(map[string]interface{}))) +} + +// PublishWithTags publishes the given message with the set of tags. The set is +// matched with clients queries. If there is a match, the message is sent to +// the client. +func (s *Server) PublishWithTags(ctx context.Context, msg interface{}, tags query.Tagged) error { + select { + case s.cmds <- cmd{op: pub, msg: msg, tags: tags}: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +// OnStop implements Service.OnStop by shutting down the server. +func (s *Server) OnStop() { + s.cmds <- cmd{op: shutdown} +} + +// NOTE: not goroutine safe +type state struct { + // query -> client -> ch + queries map[query.Query]map[string]chan interface{} + // client -> query -> struct{} + clients map[string]map[query.Query]struct{} +} + +// OnStart implements Service.OnStart by starting the server. +func (s *Server) OnStart() error { + go s.loop(state{ + queries: make(map[query.Query]map[string]chan interface{}), + clients: make(map[string]map[query.Query]struct{}), + }) + return nil +} + +// OnReset implements Service.OnReset +func (s *Server) OnReset() error { + return nil +} + +func (s *Server) loop(state state) { +loop: + for cmd := range s.cmds { + switch cmd.op { + case unsub: + if cmd.query != nil { + state.remove(cmd.clientID, cmd.query) + } else { + state.removeAll(cmd.clientID) + } + case shutdown: + for clientID := range state.clients { + state.removeAll(clientID) + } + break loop + case sub: + state.add(cmd.clientID, cmd.query, cmd.ch) + case pub: + state.send(cmd.msg, cmd.tags) + } + } +} + +func (state *state) add(clientID string, q query.Query, ch chan interface{}) { + // add query if needed + if _, ok := state.queries[q]; !ok { + state.queries[q] = make(map[string]chan interface{}) + } + + // create subscription + state.queries[q][clientID] = ch + + // add client if needed + if _, ok := state.clients[clientID]; !ok { + state.clients[clientID] = make(map[query.Query]struct{}) + } + state.clients[clientID][q] = struct{}{} +} + +func (state *state) remove(clientID string, q query.Query) { + clientToChannelMap, ok := state.queries[q] + if !ok { + return + } + + ch, ok := clientToChannelMap[clientID] + if ok { + closeAndDrain(ch) + + delete(state.clients[clientID], q) + + // if it not subscribed to anything else, remove the client + if len(state.clients[clientID]) == 0 { + delete(state.clients, clientID) + } + + delete(state.queries[q], clientID) + if len(state.queries[q]) == 0 { + delete(state.queries, q) + } + } +} + +func (state *state) removeAll(clientID string) { + queryMap, ok := state.clients[clientID] + if !ok { + return + } + + for q := range queryMap { + ch := state.queries[q][clientID] + closeAndDrain(ch) + + delete(state.queries[q], clientID) + if len(state.queries[q]) == 0 { + delete(state.queries, q) + } + } + delete(state.clients, clientID) +} + +func closeAndDrain(ch chan interface{}) { + close(ch) + for range ch { + } +} + +func (state *state) send(msg interface{}, tags query.Tagged) { + for q, clientToChannelMap := range state.queries { + if q.Matches(tags) { + for _, ch := range clientToChannelMap { + select { + case ch <- msg: + default: + // It's difficult to do anything sensible here with retries/times outs since we may reorder a client's + // view of events by sending a later message before an earlier message we retry. If per-client order + // matters then we need a queue per client. Possible for us it does not... + } + } + } + } +} diff --git a/event/pubsub/pubsub_test.go b/event/pubsub/pubsub_test.go new file mode 100644 index 000000000..ec777450c --- /dev/null +++ b/event/pubsub/pubsub_test.go @@ -0,0 +1,237 @@ +package pubsub_test + +import ( + "context" + "fmt" + "runtime/debug" + "testing" + "time" + + "github.com/hyperledger/burrow/event/pubsub" + "github.com/hyperledger/burrow/event/query" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + clientID = "test-client" +) + +func TestSubscribe(t *testing.T) { + s := pubsub.NewServer() + s.Start() + defer s.Stop() + + ctx := context.Background() + ch, err := s.Subscribe(ctx, clientID, query.Empty{}, 1) + require.NoError(t, err) + err = s.Publish(ctx, "Ka-Zar") + require.NoError(t, err) + assertReceive(t, "Ka-Zar", ch) + + err = s.Publish(ctx, "Quicksilver") + require.NoError(t, err) + assertReceive(t, "Quicksilver", ch) +} + +func TestDifferentClients(t *testing.T) { + s := pubsub.NewServer() + s.Start() + defer s.Stop() + + ctx := context.Background() + ch1, err := s.Subscribe(ctx, "client-1", query.MustParse("tm.events.type='NewBlock'"), 1) + require.NoError(t, err) + err = s.PublishWithTags(ctx, "Iceman", query.TagMap{"tm.events.type": "NewBlock"}) + require.NoError(t, err) + assertReceive(t, "Iceman", ch1) + + ch2, err := s.Subscribe(ctx, "client-2", query.MustParse("tm.events.type='NewBlock' AND abci.account.name='Igor'"), 1) + require.NoError(t, err) + err = s.PublishWithTags(ctx, "Ultimo", query.TagMap{"tm.events.type": "NewBlock", "abci.account.name": "Igor"}) + require.NoError(t, err) + assertReceive(t, "Ultimo", ch1) + assertReceive(t, "Ultimo", ch2) + + ch3, err := s.Subscribe(ctx, "client-3", query.MustParse("tm.events.type='NewRoundStep' AND abci.account.name='Igor' AND abci.invoice.number = 10"), 1) + require.NoError(t, err) + err = s.PublishWithTags(ctx, "Valeria Richards", query.TagMap{"tm.events.type": "NewRoundStep"}) + require.NoError(t, err) + assert.Zero(t, len(ch3)) +} + +func TestClientSubscribesTwice(t *testing.T) { + s := pubsub.NewServer() + + s.Start() + defer s.Stop() + + ctx := context.Background() + q := query.MustParse("tm.events.type='NewBlock'") + + ch1, err := s.Subscribe(ctx, clientID, q, 1) + require.NoError(t, err) + err = s.PublishWithTags(ctx, "Goblin Queen", query.TagMap{"tm.events.type": "NewBlock"}) + require.NoError(t, err) + assertReceive(t, "Goblin Queen", ch1) + + _, err = s.Subscribe(ctx, clientID, q, 1) + require.Error(t, err) + + err = s.PublishWithTags(ctx, "Spider-Man", query.TagMap{"tm.events.type": "NewBlock"}) + require.NoError(t, err) + assertReceive(t, "Spider-Man", ch1) +} + +func TestUnsubscribe(t *testing.T) { + s := pubsub.NewServer() + + s.Start() + defer s.Stop() + + ctx := context.Background() + ch, err := s.Subscribe(ctx, clientID, query.MustParse("tm.events.type='NewBlock'"), 0) + require.NoError(t, err) + err = s.Unsubscribe(ctx, clientID, query.MustParse("tm.events.type='NewBlock'")) + require.NoError(t, err) + + err = s.Publish(ctx, "Nick Fury") + require.NoError(t, err) + assert.Zero(t, len(ch), "Should not receive anything after Unsubscribe") + + _, ok := <-ch + assert.False(t, ok) +} + +func TestResubscribe(t *testing.T) { + s := pubsub.NewServer() + + s.Start() + defer s.Stop() + + ctx := context.Background() + ch, err := s.Subscribe(ctx, clientID, query.Empty{}, 0) + require.NoError(t, err) + err = s.Unsubscribe(ctx, clientID, query.Empty{}) + require.NoError(t, err) + ch, err = s.Subscribe(ctx, clientID, query.Empty{}, 0) + require.NoError(t, err) + + err = s.Publish(ctx, "Cable") + require.NoError(t, err) + assertReceive(t, "Cable", ch) +} + +func TestUnsubscribeAll(t *testing.T) { + s := pubsub.NewServer() + + s.Start() + defer s.Stop() + + ctx := context.Background() + ch1, err := s.Subscribe(ctx, clientID, query.MustParse("tm.events.type='NewBlock'"), 1) + require.NoError(t, err) + ch2, err := s.Subscribe(ctx, clientID, query.MustParse("tm.events.type='NewBlockHeader'"), 1) + require.NoError(t, err) + + err = s.UnsubscribeAll(ctx, clientID) + require.NoError(t, err) + + err = s.Publish(ctx, "Nick Fury") + require.NoError(t, err) + assert.Zero(t, len(ch1), "Should not receive anything after UnsubscribeAll") + assert.Zero(t, len(ch2), "Should not receive anything after UnsubscribeAll") + + _, ok := <-ch1 + assert.False(t, ok) + _, ok = <-ch2 + assert.False(t, ok) +} + +func TestBufferCapacity(t *testing.T) { + s := pubsub.NewServer(pubsub.BufferCapacity(2)) + + assert.Equal(t, 2, s.BufferCapacity()) + + ctx := context.Background() + err := s.Publish(ctx, "Nighthawk") + require.NoError(t, err) + err = s.Publish(ctx, "Sage") + require.NoError(t, err) + + ctx, cancel := context.WithTimeout(ctx, 10*time.Millisecond) + defer cancel() + err = s.Publish(ctx, "Ironclad") + if assert.Error(t, err) { + assert.Equal(t, context.DeadlineExceeded, err) + } +} + +func Benchmark10Clients(b *testing.B) { benchmarkNClients(10, b) } +func Benchmark100Clients(b *testing.B) { benchmarkNClients(100, b) } +func Benchmark1000Clients(b *testing.B) { benchmarkNClients(1000, b) } + +func Benchmark10ClientsOneQuery(b *testing.B) { benchmarkNClientsOneQuery(10, b) } +func Benchmark100ClientsOneQuery(b *testing.B) { benchmarkNClientsOneQuery(100, b) } +func Benchmark1000ClientsOneQuery(b *testing.B) { benchmarkNClientsOneQuery(1000, b) } + +func benchmarkNClients(n int, b *testing.B) { + s := pubsub.NewServer() + s.Start() + defer s.Stop() + + ctx := context.Background() + for i := 0; i < n; i++ { + ch, err := s.Subscribe(ctx, clientID, query.MustParse(fmt.Sprintf("abci.Account.Owner = 'Ivan' AND abci.Invoices.Number = %d", i)), 0) + require.NoError(b, err) + go func() { + for range ch { + } + }() + } + + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.PublishWithTags(ctx, "Gamora", query.TagMap{"abci.Account.Owner": "Ivan", "abci.Invoices.Number": string(i)}) + } +} + +func benchmarkNClientsOneQuery(n int, b *testing.B) { + s := pubsub.NewServer() + s.Start() + defer s.Stop() + + ctx := context.Background() + q := query.MustParse("abci.Account.Owner = 'Ivan' AND abci.Invoices.Number = 1") + for i := 0; i < n; i++ { + ch, err := s.Subscribe(ctx, clientID, q, 0) + require.NoError(b, err) + go func() { + for range ch { + } + }() + } + + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.PublishWithTags(ctx, "Gamora", query.TagMap{"abci.Account.Owner": "Ivan", "abci.Invoices.Number": "1"}) + } +} + +/////////////////////////////////////////////////////////////////////////////// +/// HELPERS +/////////////////////////////////////////////////////////////////////////////// + +func assertReceive(t *testing.T, expected interface{}, ch <-chan interface{}, msgAndArgs ...interface{}) { + select { + case actual := <-ch: + if actual != nil { + assert.Equal(t, expected, actual, msgAndArgs...) + } + case <-time.After(1 * time.Second): + t.Errorf("Expected to receive %v from the channel, got nothing after 1s", expected) + debug.PrintStack() + } +} diff --git a/event/query/Makefile b/event/query/Makefile new file mode 100644 index 000000000..91030ef09 --- /dev/null +++ b/event/query/Makefile @@ -0,0 +1,11 @@ +gen_query_parser: + @go get github.com/pointlander/peg + peg -inline -switch query.peg + +fuzzy_test: + @go get github.com/dvyukov/go-fuzz/go-fuzz + @go get github.com/dvyukov/go-fuzz/go-fuzz-build + go-fuzz-build github.com/tendermint/tendermint/libs/pubsub/query/fuzz_test + go-fuzz -bin=./fuzz_test-fuzz.zip -workdir=./fuzz_test/output + +.PHONY: gen_query_parser fuzzy_test diff --git a/event/query/builder.go b/event/query/builder.go new file mode 100644 index 000000000..1395a39aa --- /dev/null +++ b/event/query/builder.go @@ -0,0 +1,263 @@ +package query + +import ( + "bytes" + "fmt" + "reflect" + "strconv" + "strings" + "text/template" + "time" +) + +const ( + MultipleValueTagSeparator = ";" + + // Operators + equalString = "=" + greaterThanString = ">" + lessThanString = "<" + greaterOrEqualString = ">=" + lessOrEqualString = "<=" + containsString = "CONTAINS" + andString = "AND" + + // Values + trueString = "true" + falseString = "false" + emptyString = "empty" + timeString = "TIME" + dateString = "DATE" +) + +type Query interface { + Matches(tags Tagged) bool + String() string +} + +type Queryable interface { + Query() (Query, error) +} + +type parsedQuery struct { + query Query +} + +func AsQueryable(query Query) parsedQuery { + return parsedQuery{query: query} +} + +func (pq parsedQuery) Query() (Query, error) { + return pq.query, nil +} + +// A yet-to-parsed query +type String string + +func Must(qry Query, err error) Query { + if err != nil { + panic(fmt.Errorf("could not compile: %v", qry)) + } + return qry +} + +func (qs String) Query() (Query, error) { + if isEmpty(string(qs)) { + return Empty{}, nil + } + return New(string(qs)) +} + +func MatchAllQueryable() Queryable { + return Empty{} +} + +// A fluent query builder +type Builder struct { + queryString string + condition + // reusable buffer for building queryString + bytes.Buffer + error +} + +// Templates +type condition struct { + Tag string + Op string + Operand string +} + +var conditionTemplate = template.Must(template.New("condition").Parse("{{.Tag}} {{.Op}} {{.Operand}}")) + +// Creates a new query builder with a base query that is the conjunction of all queries passed +func NewBuilder(queries ...string) *Builder { + qb := new(Builder) + qb.queryString = qb.and(stringIterator(queries...)) + return qb +} + +func (qb *Builder) String() string { + return qb.queryString +} + +func (qb *Builder) Query() (Query, error) { + if qb.error != nil { + return nil, qb.error + } + if isEmpty(qb.queryString) { + return Empty{}, nil + } + return New(qb.String()) +} + +// Creates the conjunction of Builder and rightQuery +func (qb *Builder) And(queryBuilders ...*Builder) *Builder { + return NewBuilder(qb.and(queryBuilderIterator(queryBuilders...))) +} + +// Creates the conjunction of Builder and tag = operand +func (qb *Builder) AndEquals(tag string, operand interface{}) *Builder { + qb.condition.Tag = tag + qb.condition.Op = equalString + qb.condition.Operand = operandString(operand) + return NewBuilder(qb.and(stringIterator(qb.conditionString()))) +} + +func (qb *Builder) AndGreaterThanOrEqual(tag string, operand interface{}) *Builder { + qb.condition.Tag = tag + qb.condition.Op = greaterOrEqualString + qb.condition.Operand = operandString(operand) + return NewBuilder(qb.and(stringIterator(qb.conditionString()))) +} + +func (qb *Builder) AndLessThanOrEqual(tag string, operand interface{}) *Builder { + qb.condition.Tag = tag + qb.condition.Op = lessOrEqualString + qb.condition.Operand = operandString(operand) + return NewBuilder(qb.and(stringIterator(qb.conditionString()))) +} + +func (qb *Builder) AndStrictlyGreaterThan(tag string, operand interface{}) *Builder { + qb.condition.Tag = tag + qb.condition.Op = greaterThanString + qb.condition.Operand = operandString(operand) + return NewBuilder(qb.and(stringIterator(qb.conditionString()))) +} + +func (qb *Builder) AndStrictlyLessThan(tag string, operand interface{}) *Builder { + qb.condition.Tag = tag + qb.condition.Op = lessThanString + qb.condition.Operand = operandString(operand) + return NewBuilder(qb.and(stringIterator(qb.conditionString()))) +} + +func (qb *Builder) AndContains(tag string, operand interface{}) *Builder { + qb.condition.Tag = tag + qb.condition.Op = containsString + qb.condition.Operand = operandString(operand) + return NewBuilder(qb.and(stringIterator(qb.conditionString()))) +} + +func (qb *Builder) and(queryIterator func(func(string))) string { + defer qb.Buffer.Reset() + qb.Buffer.WriteString(qb.queryString) + queryIterator(func(q string) { + if !isEmpty(q) { + if qb.Buffer.Len() > 0 { + qb.Buffer.WriteByte(' ') + qb.Buffer.WriteString(andString) + qb.Buffer.WriteByte(' ') + } + qb.Buffer.WriteString(q) + } + }) + return qb.Buffer.String() +} + +func operandString(value interface{}) string { + buf := new(bytes.Buffer) + switch v := value.(type) { + case string: + buf.WriteByte('\'') + buf.WriteString(v) + buf.WriteByte('\'') + return buf.String() + case fmt.Stringer: + return operandString(v.String()) + default: + return StringFromValue(v) + } +} + +func StringFromValue(value interface{}) string { + switch v := value.(type) { + case string: + return v + case fmt.Stringer: + return v.String() + case bool: + if v { + return trueString + } + return falseString + case int: + return strconv.FormatInt(int64(v), 10) + case int32: + return strconv.FormatInt(int64(v), 10) + case int64: + return strconv.FormatInt(v, 10) + case uint: + return strconv.FormatUint(uint64(v), 10) + case uint32: + return strconv.FormatUint(uint64(v), 10) + case uint64: + return strconv.FormatUint(v, 10) + case float32: + return strconv.FormatFloat(float64(v), 'f', -1, 32) + case float64: + return strconv.FormatFloat(float64(v), 'f', -1, 64) + case time.Time: + return timeString + " " + v.Format(time.RFC3339) + default: + rv := reflect.ValueOf(v) + if rv.Kind() == reflect.Slice { + values := make([]string, rv.Len()) + for i := 0; i < rv.Len(); i++ { + values[i] = StringFromValue(rv.Index(i).Interface()) + } + return strings.Join(values, MultipleValueTagSeparator) + } + return fmt.Sprintf("%v", v) + } +} + +func (qb *Builder) conditionString() string { + defer qb.Buffer.Reset() + err := conditionTemplate.Execute(&qb.Buffer, qb.condition) + if err != nil && qb.error == nil { + qb.error = err + } + return qb.Buffer.String() +} + +func isEmpty(queryString string) bool { + return queryString == "" || queryString == emptyString +} + +// Iterators over some strings +func stringIterator(strs ...string) func(func(string)) { + return func(callback func(string)) { + for _, s := range strs { + callback(s) + } + } +} + +func queryBuilderIterator(qbs ...*Builder) func(func(string)) { + return func(callback func(string)) { + for _, qb := range qbs { + callback(qb.String()) + } + } +} diff --git a/event/query/builder_test.go b/event/query/builder_test.go new file mode 100644 index 000000000..15da502d0 --- /dev/null +++ b/event/query/builder_test.go @@ -0,0 +1,52 @@ +package query + +import ( + "testing" + + "github.com/hyperledger/burrow/logging/structure" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestQueryBuilder(t *testing.T) { + qb := NewBuilder() + qry, err := qb.Query() + require.NoError(t, err) + assert.Equal(t, emptyString, qry.String()) + + qb = qb.AndGreaterThanOrEqual("foo.size", 45) + qry, err = qb.Query() + require.NoError(t, err) + assert.Equal(t, "foo.size >= 45", qry.String()) + + qb = qb.AndEquals("bar.name", "marmot") + qry, err = qb.Query() + require.NoError(t, err) + assert.Equal(t, "foo.size >= 45 AND bar.name = 'marmot'", qry.String()) + + assert.True(t, qry.Matches(makeTagMap("foo.size", 80, "bar.name", "marmot"))) + assert.False(t, qry.Matches(makeTagMap("foo.size", 8, "bar.name", "marmot"))) + assert.False(t, qry.Matches(makeTagMap("foo.size", 80, "bar.name", "marot"))) + + qb = qb.AndContains("bar.desc", "burrow") + qry, err = qb.Query() + require.NoError(t, err) + assert.Equal(t, "foo.size >= 45 AND bar.name = 'marmot' AND bar.desc CONTAINS 'burrow'", qry.String()) + + assert.True(t, qry.Matches(makeTagMap("foo.size", 80, "bar.name", "marmot", "bar.desc", "lives in a burrow"))) + assert.False(t, qry.Matches(makeTagMap("foo.size", 80, "bar.name", "marmot", "bar.desc", "lives in a shoe"))) + + qb = NewBuilder().AndEquals("foo", "bar") + qb = qb.And(NewBuilder().AndGreaterThanOrEqual("frogs", 4)) + qry, err = qb.Query() + require.NoError(t, err) + assert.Equal(t, "foo = 'bar' AND frogs >= 4", qry.String()) +} + +func makeTagMap(keyvals ...interface{}) TagMap { + tmap := make(TagMap) + for i := 0; i < len(keyvals); i += 2 { + tmap[keyvals[i].(string)] = structure.StringifyKey(keyvals[i+1]) + } + return tmap +} diff --git a/event/query/empty.go b/event/query/empty.go index c83169e18..5d10ce4c7 100644 --- a/event/query/empty.go +++ b/event/query/empty.go @@ -1,13 +1,21 @@ package query -import ( - "github.com/tendermint/tendermint/libs/pubsub" - "github.com/tendermint/tendermint/libs/pubsub/query" -) +// Empty query matches any set of tags. +type Empty struct { +} + +var _ Query = Empty{} +var _ Queryable = Empty{} -// Matches everything -type Empty query.Empty +// Matches always returns true. +func (Empty) Matches(tags Tagged) bool { + return true +} + +func (Empty) String() string { + return "empty" +} -func (Empty) Query() (pubsub.Query, error) { - return query.Empty{}, nil +func (Empty) Query() (Query, error) { + return Empty{}, nil } diff --git a/event/query/empty_test.go b/event/query/empty_test.go new file mode 100644 index 000000000..d7237112f --- /dev/null +++ b/event/query/empty_test.go @@ -0,0 +1,15 @@ +package query + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestEmptyQueryMatchesAnything(t *testing.T) { + q := Empty{} + assert.True(t, q.Matches(TagMap{})) + assert.True(t, q.Matches(TagMap{"Asher": "Roth"})) + assert.True(t, q.Matches(TagMap{"Route": "66"})) + assert.True(t, q.Matches(TagMap{"Route": "66", "Billy": "Blue"})) +} diff --git a/event/query/parser_test.go b/event/query/parser_test.go new file mode 100644 index 000000000..dca8b1ed2 --- /dev/null +++ b/event/query/parser_test.go @@ -0,0 +1,90 @@ +package query + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +// TODO: fuzzy testing? +func TestParser(t *testing.T) { + cases := []struct { + query string + valid bool + }{ + {"tm.events.type='NewBlock'", true}, + {"tm.events.type = 'NewBlock'", true}, + {"tm.events.name = ''", true}, + {"tm.events.type='TIME'", true}, + {"tm.events.type='DATE'", true}, + {"tm.events.type='='", true}, + {"tm.events.type='TIME", false}, + {"tm.events.type=TIME'", false}, + {"tm.events.type==", false}, + {"tm.events.type=NewBlock", false}, + {">==", false}, + {"tm.events.type 'NewBlock' =", false}, + {"tm.events.type>'NewBlock'", false}, + {"", false}, + {"=", false}, + {"='NewBlock'", false}, + {"tm.events.type=", false}, + + {"tm.events.typeNewBlock", false}, + {"tm.events.type'NewBlock'", false}, + {"'NewBlock'", false}, + {"NewBlock", false}, + {"", false}, + + {"tm.events.type='NewBlock' AND abci.account.name='Igor'", true}, + {"tm.events.type='NewBlock' AND", false}, + {"tm.events.type='NewBlock' AN", false}, + {"tm.events.type='NewBlock' AN tm.events.type='NewBlockHeader'", false}, + {"AND tm.events.type='NewBlock' ", false}, + + {"abci.account.name CONTAINS 'Igor'", true}, + + {"tx.date > DATE 2013-05-03", true}, + {"tx.date < DATE 2013-05-03", true}, + {"tx.date <= DATE 2013-05-03", true}, + {"tx.date >= DATE 2013-05-03", true}, + {"tx.date >= DAT 2013-05-03", false}, + {"tx.date <= DATE2013-05-03", false}, + {"tx.date <= DATE -05-03", false}, + {"tx.date >= DATE 20130503", false}, + {"tx.date >= DATE 2013+01-03", false}, + // incorrect year, month, day + {"tx.date >= DATE 0013-01-03", false}, + {"tx.date >= DATE 2013-31-03", false}, + {"tx.date >= DATE 2013-01-83", false}, + + {"tx.date > TIME 2013-05-03T14:45:00+07:00", true}, + {"tx.date < TIME 2013-05-03T14:45:00-02:00", true}, + {"tx.date <= TIME 2013-05-03T14:45:00Z", true}, + {"tx.date >= TIME 2013-05-03T14:45:00Z", true}, + {"tx.date >= TIME2013-05-03T14:45:00Z", false}, + {"tx.date = IME 2013-05-03T14:45:00Z", false}, + {"tx.date = TIME 2013-05-:45:00Z", false}, + {"tx.date >= TIME 2013-05-03T14:45:00", false}, + {"tx.date >= TIME 0013-00-00T14:45:00Z", false}, + {"tx.date >= TIME 2013+05=03T14:45:00Z", false}, + + {"account.balance=100", true}, + {"account.balance >= 200", true}, + {"account.balance >= -300", false}, + {"account.balance >>= 400", false}, + {"account.balance=33.22.1", false}, + + {"hash='136E18F7E4C348B780CF873A0BF43922E5BAFA63'", true}, + {"hash=136E18F7E4C348B780CF873A0BF43922E5BAFA63", false}, + } + + for _, c := range cases { + _, err := New(c.query) + if c.valid { + assert.NoErrorf(t, err, "Query was '%s'", c.query) + } else { + assert.Errorf(t, err, "Query was '%s'", c.query) + } + } +} diff --git a/event/query/query.go b/event/query/query.go index fc107968b..17946b770 100644 --- a/event/query/query.go +++ b/event/query/query.go @@ -1,250 +1,344 @@ +// Package query provides a parser for a custom query format: +// +// abci.invoice.number=22 AND abci.invoice.owner=Ivan +// +// See query.peg for the grammar, which is a https://en.wikipedia.org/wiki/Parsing_expression_grammar. +// More: https://github.com/PhilippeSigaud/Pegged/wiki/PEG-Basics +// +// It has a support for numbers (integer and floating point), dates and times. package query import ( - "bytes" "fmt" + "reflect" "strconv" - "text/template" + "strings" "time" - - "github.com/tendermint/tendermint/libs/pubsub" - "github.com/tendermint/tendermint/libs/pubsub/query" ) -const ( - // Operators - equalString = "=" - greaterThanString = ">" - lessThanString = "<" - greaterOrEqualString = ">=" - lessOrEqualString = "<=" - containsString = "CONTAINS" - andString = "AND" - - // Values - trueString = "true" - falseString = "false" - emptyString = "empty" - timeString = "TIME" - dateString = "DATE" -) - -type Queryable interface { - Query() (pubsub.Query, error) -} - -// A yet-to-parsed query -type String string - -func Must(qry pubsub.Query, err error) Query { - if err != nil { - panic(fmt.Errorf("could not compile: %v", qry)) - } - return WrapQuery(qry) -} - -func (qs String) Query() (pubsub.Query, error) { - if isEmpty(string(qs)) { - return query.Empty{}, nil - } - return query.New(string(qs)) -} +var _ Query = &query{} +var _ Queryable = &query{} -func MatchAllQueryable() Queryable { - return WrapQuery(query.Empty{}) +// Query holds the query string and the query parser. +type query struct { + str string + parser *QueryParser } -// A pre-parsed query -type Query struct { - query pubsub.Query -} - -func WrapQuery(qry pubsub.Query) Query { - return Query{qry} -} - -func (q Query) Query() (pubsub.Query, error) { - return q.query, nil -} - -// A fluent query builder -type Builder struct { - queryString string - condition - // reusable buffer for building queryString - bytes.Buffer - error -} - -// Templates -type condition struct { +// Condition represents a single condition within a query and consists of tag +// (e.g. "tx.gas"), operator (e.g. "=") and operand (e.g. "7"). +type Condition struct { Tag string - Op string - Operand string + Op Operator + Operand interface{} } -var conditionTemplate = template.Must(template.New("condition").Parse("{{.Tag}} {{.Op}} {{.Operand}}")) - -// Creates a new query builder with a base query that is the conjunction of all queries passed -func NewBuilder(queries ...string) *Builder { - qb := new(Builder) - qb.queryString = qb.and(stringIterator(queries...)) - return qb -} - -func (qb *Builder) String() string { - return qb.queryString -} - -func (qb *Builder) Query() (pubsub.Query, error) { - if qb.error != nil { - return nil, qb.error - } - if isEmpty(qb.queryString) { - return query.Empty{}, nil +// New parses the given string and returns a query or error if the string is +// invalid. +func New(s string) (*query, error) { + p := &QueryParser{Buffer: fmt.Sprintf(`"%s"`, s)} + p.Init() + if err := p.Parse(); err != nil { + return nil, err } - return query.New(qb.String()) + return &query{str: s, parser: p}, nil } -// Creates the conjunction of Builder and rightQuery -func (qb *Builder) And(queryBuilders ...*Builder) *Builder { - return NewBuilder(qb.and(queryBuilderIterator(queryBuilders...))) -} - -// Creates the conjunction of Builder and tag = operand -func (qb *Builder) AndEquals(tag string, operand interface{}) *Builder { - qb.condition.Tag = tag - qb.condition.Op = equalString - qb.condition.Operand = operandString(operand) - return NewBuilder(qb.and(stringIterator(qb.conditionString()))) +// MustParse turns the given string into a query or panics; for tests or others +// cases where you know the string is valid. +func MustParse(s string) *query { + q, err := New(s) + if err != nil { + panic(fmt.Sprintf("failed to parse %s: %v", s, err)) + } + return q } -func (qb *Builder) AndGreaterThanOrEqual(tag string, operand interface{}) *Builder { - qb.condition.Tag = tag - qb.condition.Op = greaterOrEqualString - qb.condition.Operand = operandString(operand) - return NewBuilder(qb.and(stringIterator(qb.conditionString()))) +// String returns the original string. +func (q *query) String() string { + return q.str } -func (qb *Builder) AndLessThanOrEqual(tag string, operand interface{}) *Builder { - qb.condition.Tag = tag - qb.condition.Op = lessOrEqualString - qb.condition.Operand = operandString(operand) - return NewBuilder(qb.and(stringIterator(qb.conditionString()))) +func (q *query) Query() (Query, error) { + return q, nil } -func (qb *Builder) AndStrictlyGreaterThan(tag string, operand interface{}) *Builder { - qb.condition.Tag = tag - qb.condition.Op = greaterThanString - qb.condition.Operand = operandString(operand) - return NewBuilder(qb.and(stringIterator(qb.conditionString()))) -} +// Operator is an operator that defines some kind of relation between tag and +// operand (equality, etc.). +type Operator uint8 -func (qb *Builder) AndStrictlyLessThan(tag string, operand interface{}) *Builder { - qb.condition.Tag = tag - qb.condition.Op = lessThanString - qb.condition.Operand = operandString(operand) - return NewBuilder(qb.and(stringIterator(qb.conditionString()))) -} +const ( + // "<=" + OpLessEqual Operator = iota + // ">=" + OpGreaterEqual + // "<" + OpLess + // ">" + OpGreater + // "=" + OpEqual + // "CONTAINS"; used to check if a string contains a certain sub string. + OpContains +) -func (qb *Builder) AndContains(tag string, operand interface{}) *Builder { - qb.condition.Tag = tag - qb.condition.Op = containsString - qb.condition.Operand = operandString(operand) - return NewBuilder(qb.and(stringIterator(qb.conditionString()))) -} +const ( + // DateLayout defines a layout for all dates (`DATE date`) + DateLayout = "2006-01-02" + // TimeLayout defines a layout for all times (`TIME time`) + TimeLayout = time.RFC3339 +) -func (qb *Builder) and(queryIterator func(func(string))) string { - defer qb.Buffer.Reset() - qb.Buffer.WriteString(qb.queryString) - queryIterator(func(q string) { - if !isEmpty(q) { - if qb.Buffer.Len() > 0 { - qb.Buffer.WriteByte(' ') - qb.Buffer.WriteString(andString) - qb.Buffer.WriteByte(' ') +// Conditions returns a list of conditions. +func (q *query) Conditions() []Condition { + conditions := make([]Condition, 0) + + buffer, begin, end := q.parser.Buffer, 0, 0 + + var tag string + var op Operator + + // tokens must be in the following order: tag ("tx.gas") -> operator ("=") -> operand ("7") + for _, token := range q.parser.Tokens() { + switch token.pegRule { + + case rulePegText: + begin, end = int(token.begin), int(token.end) + case ruletag: + tag = buffer[begin:end] + case rulele: + op = OpLessEqual + case rulege: + op = OpGreaterEqual + case rulel: + op = OpLess + case ruleg: + op = OpGreater + case ruleequal: + op = OpEqual + case rulecontains: + op = OpContains + case rulevalue: + // strip single quotes from value (i.e. "'NewBlock'" -> "NewBlock") + valueWithoutSingleQuotes := buffer[begin+1 : end-1] + conditions = append(conditions, Condition{tag, op, valueWithoutSingleQuotes}) + case rulenumber: + number := buffer[begin:end] + if strings.ContainsAny(number, ".") { // if it looks like a floating-point number + value, err := strconv.ParseFloat(number, 64) + if err != nil { + panic(fmt.Sprintf("got %v while trying to parse %s as float64 (should never happen if the grammar is correct)", err, number)) + } + conditions = append(conditions, Condition{tag, op, value}) + } else { + value, err := strconv.ParseInt(number, 10, 64) + if err != nil { + panic(fmt.Sprintf("got %v while trying to parse %s as int64 (should never happen if the grammar is correct)", err, number)) + } + conditions = append(conditions, Condition{tag, op, value}) + } + case ruletime: + value, err := time.Parse(TimeLayout, buffer[begin:end]) + if err != nil { + panic(fmt.Sprintf("got %v while trying to parse %s as time.Time / RFC3339 (should never happen if the grammar is correct)", err, buffer[begin:end])) + } + conditions = append(conditions, Condition{tag, op, value}) + case ruledate: + value, err := time.Parse("2006-01-02", buffer[begin:end]) + if err != nil { + panic(fmt.Sprintf("got %v while trying to parse %s as time.Time / '2006-01-02' (should never happen if the grammar is correct)", err, buffer[begin:end])) } - qb.Buffer.WriteString(q) + conditions = append(conditions, Condition{tag, op, value}) } - }) - return qb.Buffer.String() -} - -func operandString(value interface{}) string { - buf := new(bytes.Buffer) - switch v := value.(type) { - case string: - buf.WriteByte('\'') - buf.WriteString(v) - buf.WriteByte('\'') - return buf.String() - case fmt.Stringer: - return operandString(v.String()) - default: - return StringFromValue(v) } -} -func StringFromValue(value interface{}) string { - switch v := value.(type) { - case string: - return v - case fmt.Stringer: - return v.String() - case bool: - if v { - return trueString - } - return falseString - case int: - return strconv.FormatInt(int64(v), 10) - case int32: - return strconv.FormatInt(int64(v), 10) - case int64: - return strconv.FormatInt(v, 10) - case uint: - return strconv.FormatUint(uint64(v), 10) - case uint32: - return strconv.FormatUint(uint64(v), 10) - case uint64: - return strconv.FormatUint(v, 10) - case float32: - return strconv.FormatFloat(float64(v), 'f', -1, 32) - case float64: - return strconv.FormatFloat(float64(v), 'f', -1, 64) - case time.Time: - return timeString + " " + v.Format(time.RFC3339) - default: - return fmt.Sprintf("%v", v) - } + return conditions } -func (qb *Builder) conditionString() string { - defer qb.Buffer.Reset() - err := conditionTemplate.Execute(&qb.Buffer, qb.condition) - if err != nil && qb.error == nil { - qb.error = err +// Matches returns true if the query matches the given set of tags, false otherwise. +// +// For example, query "name=John" matches tags = {"name": "John"}. More +// examples could be found in parser_test.go and query_test.go. +func (q *query) Matches(tags Tagged) bool { + if tags.Len() == 0 { + return false } - return qb.Buffer.String() -} -func isEmpty(queryString string) bool { - return queryString == "" || queryString == emptyString -} - -// Iterators over some strings -func stringIterator(strs ...string) func(func(string)) { - return func(callback func(string)) { - for _, s := range strs { - callback(s) + buffer, begin, end := q.parser.Buffer, 0, 0 + + var tag string + var op Operator + + // tokens must be in the following order: tag ("tx.gas") -> operator ("=") -> operand ("7") + for _, token := range q.parser.Tokens() { + switch token.pegRule { + + case rulePegText: + begin, end = int(token.begin), int(token.end) + case ruletag: + tag = buffer[begin:end] + case rulele: + op = OpLessEqual + case rulege: + op = OpGreaterEqual + case rulel: + op = OpLess + case ruleg: + op = OpGreater + case ruleequal: + op = OpEqual + case rulecontains: + op = OpContains + case rulevalue: + // strip single quotes from value (i.e. "'NewBlock'" -> "NewBlock") + valueWithoutSingleQuotes := buffer[begin+1 : end-1] + + // see if the triplet (tag, operator, operand) matches any tag + // "tx.gas", "=", "7", { "tx.gas": 7, "tx.ID": "4AE393495334" } + if !match(tag, op, reflect.ValueOf(valueWithoutSingleQuotes), tags) { + return false + } + case rulenumber: + number := buffer[begin:end] + if strings.ContainsAny(number, ".") { // if it looks like a floating-point number + value, err := strconv.ParseFloat(number, 64) + if err != nil { + panic(fmt.Sprintf("got %v while trying to parse %s as float64 (should never happen if the grammar is correct)", err, number)) + } + if !match(tag, op, reflect.ValueOf(value), tags) { + return false + } + } else { + value, err := strconv.ParseInt(number, 10, 64) + if err != nil { + panic(fmt.Sprintf("got %v while trying to parse %s as int64 (should never happen if the grammar is correct)", err, number)) + } + if !match(tag, op, reflect.ValueOf(value), tags) { + return false + } + } + case ruletime: + value, err := time.Parse(TimeLayout, buffer[begin:end]) + if err != nil { + panic(fmt.Sprintf("got %v while trying to parse %s as time.Time / RFC3339 (should never happen if the grammar is correct)", err, buffer[begin:end])) + } + if !match(tag, op, reflect.ValueOf(value), tags) { + return false + } + case ruledate: + value, err := time.Parse("2006-01-02", buffer[begin:end]) + if err != nil { + panic(fmt.Sprintf("got %v while trying to parse %s as time.Time / '2006-01-02' (should never happen if the grammar is correct)", err, buffer[begin:end])) + } + if !match(tag, op, reflect.ValueOf(value), tags) { + return false + } } } + + return true } -func queryBuilderIterator(qbs ...*Builder) func(func(string)) { - return func(callback func(string)) { - for _, qb := range qbs { - callback(qb.String()) +// match returns true if the given triplet (tag, operator, operand) matches any tag. +// +// First, it looks up the tag in tags and if it finds one, tries to compare the +// value from it to the operand using the operator. +// +// "tx.gas", "=", "7", { "tx.gas": 7, "tx.ID": "4AE393495334" } +func match(tag string, op Operator, operand reflect.Value, tags Tagged) bool { + // look up the tag from the query in tags + value, ok := tags.Get(tag) + if !ok { + return false + } + switch operand.Kind() { + case reflect.Struct: // time + operandAsTime := operand.Interface().(time.Time) + // try our best to convert value from tags to time.Time + var ( + v time.Time + err error + ) + if strings.ContainsAny(value, "T") { + v, err = time.Parse(TimeLayout, value) + } else { + v, err = time.Parse(DateLayout, value) + } + if err != nil { + panic(fmt.Sprintf("Failed to convert value %v from tag to time.Time: %v", value, err)) + } + switch op { + case OpLessEqual: + return v.Before(operandAsTime) || v.Equal(operandAsTime) + case OpGreaterEqual: + return v.Equal(operandAsTime) || v.After(operandAsTime) + case OpLess: + return v.Before(operandAsTime) + case OpGreater: + return v.After(operandAsTime) + case OpEqual: + return v.Equal(operandAsTime) + } + case reflect.Float64: + operandFloat64 := operand.Interface().(float64) + var v float64 + // try our best to convert value from tags to float64 + v, err := strconv.ParseFloat(value, 64) + if err != nil { + panic(fmt.Sprintf("Failed to convert value %v from tag to float64: %v", value, err)) } + switch op { + case OpLessEqual: + return v <= operandFloat64 + case OpGreaterEqual: + return v >= operandFloat64 + case OpLess: + return v < operandFloat64 + case OpGreater: + return v > operandFloat64 + case OpEqual: + return v == operandFloat64 + } + case reflect.Int64: + operandInt := operand.Interface().(int64) + var v int64 + // if value looks like float, we try to parse it as float + if strings.ContainsAny(value, ".") { + v1, err := strconv.ParseFloat(value, 64) + if err != nil { + panic(fmt.Sprintf("Failed to convert value %v from tag to float64: %v", value, err)) + } + v = int64(v1) + } else { + var err error + // try our best to convert value from tags to int64 + v, err = strconv.ParseInt(value, 10, 64) + if err != nil { + panic(fmt.Sprintf("Failed to convert value %v from tag to int64: %v", value, err)) + } + } + switch op { + case OpLessEqual: + return v <= operandInt + case OpGreaterEqual: + return v >= operandInt + case OpLess: + return v < operandInt + case OpGreater: + return v > operandInt + case OpEqual: + return v == operandInt + } + case reflect.String: + switch op { + case OpEqual: + return value == operand.String() + case OpContains: + return strings.Contains(value, operand.String()) + } + default: + panic(fmt.Sprintf("Unknown kind of operand %v", operand.Kind())) } + + return false } diff --git a/event/query/query.peg b/event/query/query.peg new file mode 100644 index 000000000..739892e4f --- /dev/null +++ b/event/query/query.peg @@ -0,0 +1,33 @@ +package query + +type QueryParser Peg { +} + +e <- '\"' condition ( ' '+ and ' '+ condition )* '\"' !. + +condition <- tag ' '* (le ' '* (number / time / date) + / ge ' '* (number / time / date) + / l ' '* (number / time / date) + / g ' '* (number / time / date) + / equal ' '* (number / time / date / value) + / contains ' '* value + ) + +tag <- < (![ \t\n\r\\()"'=><] .)+ > +value <- < '\'' (!["'] .)* '\''> +number <- < ('0' + / [1-9] digit* ('.' digit*)?) > +digit <- [0-9] +time <- "TIME " < year '-' month '-' day 'T' digit digit ':' digit digit ':' digit digit (('-' / '+') digit digit ':' digit digit / 'Z') > +date <- "DATE " < year '-' month '-' day > +year <- ('1' / '2') digit digit digit +month <- ('0' / '1') digit +day <- ('0' / '1' / '2' / '3') digit +and <- "AND" + +equal <- "=" +contains <- "CONTAINS" +le <- "<=" +ge <- ">=" +l <- "<" +g <- ">" diff --git a/event/query/query.peg.go b/event/query/query.peg.go new file mode 100644 index 000000000..c86e4a47f --- /dev/null +++ b/event/query/query.peg.go @@ -0,0 +1,1553 @@ +// nolint +package query + +import ( + "fmt" + "math" + "sort" + "strconv" +) + +const endSymbol rune = 1114112 + +/* The rule types inferred from the grammar are below. */ +type pegRule uint8 + +const ( + ruleUnknown pegRule = iota + rulee + rulecondition + ruletag + rulevalue + rulenumber + ruledigit + ruletime + ruledate + ruleyear + rulemonth + ruleday + ruleand + ruleequal + rulecontains + rulele + rulege + rulel + ruleg + rulePegText +) + +var rul3s = [...]string{ + "Unknown", + "e", + "condition", + "tag", + "value", + "number", + "digit", + "time", + "date", + "year", + "month", + "day", + "and", + "equal", + "contains", + "le", + "ge", + "l", + "g", + "PegText", +} + +type token32 struct { + pegRule + begin, end uint32 +} + +func (t *token32) String() string { + return fmt.Sprintf("\x1B[34m%v\x1B[m %v %v", rul3s[t.pegRule], t.begin, t.end) +} + +type node32 struct { + token32 + up, next *node32 +} + +func (node *node32) print(pretty bool, buffer string) { + var print func(node *node32, depth int) + print = func(node *node32, depth int) { + for node != nil { + for c := 0; c < depth; c++ { + fmt.Printf(" ") + } + rule := rul3s[node.pegRule] + quote := strconv.Quote(string(([]rune(buffer)[node.begin:node.end]))) + if !pretty { + fmt.Printf("%v %v\n", rule, quote) + } else { + fmt.Printf("\x1B[34m%v\x1B[m %v\n", rule, quote) + } + if node.up != nil { + print(node.up, depth+1) + } + node = node.next + } + } + print(node, 0) +} + +func (node *node32) Print(buffer string) { + node.print(false, buffer) +} + +func (node *node32) PrettyPrint(buffer string) { + node.print(true, buffer) +} + +type tokens32 struct { + tree []token32 +} + +func (t *tokens32) Trim(length uint32) { + t.tree = t.tree[:length] +} + +func (t *tokens32) Print() { + for _, token := range t.tree { + fmt.Println(token.String()) + } +} + +func (t *tokens32) AST() *node32 { + type element struct { + node *node32 + down *element + } + tokens := t.Tokens() + var stack *element + for _, token := range tokens { + if token.begin == token.end { + continue + } + node := &node32{token32: token} + for stack != nil && stack.node.begin >= token.begin && stack.node.end <= token.end { + stack.node.next = node.up + node.up = stack.node + stack = stack.down + } + stack = &element{node: node, down: stack} + } + if stack != nil { + return stack.node + } + return nil +} + +func (t *tokens32) PrintSyntaxTree(buffer string) { + t.AST().Print(buffer) +} + +func (t *tokens32) PrettyPrintSyntaxTree(buffer string) { + t.AST().PrettyPrint(buffer) +} + +func (t *tokens32) Add(rule pegRule, begin, end, index uint32) { + if tree := t.tree; int(index) >= len(tree) { + expanded := make([]token32, 2*len(tree)) + copy(expanded, tree) + t.tree = expanded + } + t.tree[index] = token32{ + pegRule: rule, + begin: begin, + end: end, + } +} + +func (t *tokens32) Tokens() []token32 { + return t.tree +} + +type QueryParser struct { + Buffer string + buffer []rune + rules [20]func() bool + parse func(rule ...int) error + reset func() + Pretty bool + tokens32 +} + +func (p *QueryParser) Parse(rule ...int) error { + return p.parse(rule...) +} + +func (p *QueryParser) Reset() { + p.reset() +} + +type textPosition struct { + line, symbol int +} + +type textPositionMap map[int]textPosition + +func translatePositions(buffer []rune, positions []int) textPositionMap { + length, translations, j, line, symbol := len(positions), make(textPositionMap, len(positions)), 0, 1, 0 + sort.Ints(positions) + +search: + for i, c := range buffer { + if c == '\n' { + line, symbol = line+1, 0 + } else { + symbol++ + } + if i == positions[j] { + translations[positions[j]] = textPosition{line, symbol} + for j++; j < length; j++ { + if i != positions[j] { + continue search + } + } + break search + } + } + + return translations +} + +type parseError struct { + p *QueryParser + max token32 +} + +func (e *parseError) Error() string { + tokens, error := []token32{e.max}, "\n" + positions, p := make([]int, 2*len(tokens)), 0 + for _, token := range tokens { + positions[p], p = int(token.begin), p+1 + positions[p], p = int(token.end), p+1 + } + translations := translatePositions(e.p.buffer, positions) + format := "parse error near %v (line %v symbol %v - line %v symbol %v):\n%v\n" + if e.p.Pretty { + format = "parse error near \x1B[34m%v\x1B[m (line %v symbol %v - line %v symbol %v):\n%v\n" + } + for _, token := range tokens { + begin, end := int(token.begin), int(token.end) + error += fmt.Sprintf(format, + rul3s[token.pegRule], + translations[begin].line, translations[begin].symbol, + translations[end].line, translations[end].symbol, + strconv.Quote(string(e.p.buffer[begin:end]))) + } + + return error +} + +func (p *QueryParser) PrintSyntaxTree() { + if p.Pretty { + p.tokens32.PrettyPrintSyntaxTree(p.Buffer) + } else { + p.tokens32.PrintSyntaxTree(p.Buffer) + } +} + +func (p *QueryParser) Init() { + var ( + max token32 + position, tokenIndex uint32 + buffer []rune + ) + p.reset = func() { + max = token32{} + position, tokenIndex = 0, 0 + + p.buffer = []rune(p.Buffer) + if len(p.buffer) == 0 || p.buffer[len(p.buffer)-1] != endSymbol { + p.buffer = append(p.buffer, endSymbol) + } + buffer = p.buffer + } + p.reset() + + _rules := p.rules + tree := tokens32{tree: make([]token32, math.MaxInt16)} + p.parse = func(rule ...int) error { + r := 1 + if len(rule) > 0 { + r = rule[0] + } + matches := p.rules[r]() + p.tokens32 = tree + if matches { + p.Trim(tokenIndex) + return nil + } + return &parseError{p, max} + } + + add := func(rule pegRule, begin uint32) { + tree.Add(rule, begin, position, tokenIndex) + tokenIndex++ + if begin != position && position > max.end { + max = token32{rule, begin, position} + } + } + + matchDot := func() bool { + if buffer[position] != endSymbol { + position++ + return true + } + return false + } + + /*matchChar := func(c byte) bool { + if buffer[position] == c { + position++ + return true + } + return false + }*/ + + /*matchRange := func(lower byte, upper byte) bool { + if c := buffer[position]; c >= lower && c <= upper { + position++ + return true + } + return false + }*/ + + _rules = [...]func() bool{ + nil, + /* 0 e <- <('"' condition (' '+ and ' '+ condition)* '"' !.)> */ + func() bool { + position0, tokenIndex0 := position, tokenIndex + { + position1 := position + if buffer[position] != rune('"') { + goto l0 + } + position++ + if !_rules[rulecondition]() { + goto l0 + } + l2: + { + position3, tokenIndex3 := position, tokenIndex + if buffer[position] != rune(' ') { + goto l3 + } + position++ + l4: + { + position5, tokenIndex5 := position, tokenIndex + if buffer[position] != rune(' ') { + goto l5 + } + position++ + goto l4 + l5: + position, tokenIndex = position5, tokenIndex5 + } + { + position6 := position + { + position7, tokenIndex7 := position, tokenIndex + if buffer[position] != rune('a') { + goto l8 + } + position++ + goto l7 + l8: + position, tokenIndex = position7, tokenIndex7 + if buffer[position] != rune('A') { + goto l3 + } + position++ + } + l7: + { + position9, tokenIndex9 := position, tokenIndex + if buffer[position] != rune('n') { + goto l10 + } + position++ + goto l9 + l10: + position, tokenIndex = position9, tokenIndex9 + if buffer[position] != rune('N') { + goto l3 + } + position++ + } + l9: + { + position11, tokenIndex11 := position, tokenIndex + if buffer[position] != rune('d') { + goto l12 + } + position++ + goto l11 + l12: + position, tokenIndex = position11, tokenIndex11 + if buffer[position] != rune('D') { + goto l3 + } + position++ + } + l11: + add(ruleand, position6) + } + if buffer[position] != rune(' ') { + goto l3 + } + position++ + l13: + { + position14, tokenIndex14 := position, tokenIndex + if buffer[position] != rune(' ') { + goto l14 + } + position++ + goto l13 + l14: + position, tokenIndex = position14, tokenIndex14 + } + if !_rules[rulecondition]() { + goto l3 + } + goto l2 + l3: + position, tokenIndex = position3, tokenIndex3 + } + if buffer[position] != rune('"') { + goto l0 + } + position++ + { + position15, tokenIndex15 := position, tokenIndex + if !matchDot() { + goto l15 + } + goto l0 + l15: + position, tokenIndex = position15, tokenIndex15 + } + add(rulee, position1) + } + return true + l0: + position, tokenIndex = position0, tokenIndex0 + return false + }, + /* 1 condition <- <(tag ' '* ((le ' '* ((&('D' | 'd') date) | (&('T' | 't') time) | (&('0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9') number))) / (ge ' '* ((&('D' | 'd') date) | (&('T' | 't') time) | (&('0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9') number))) / ((&('=') (equal ' '* ((&('\'') value) | (&('D' | 'd') date) | (&('T' | 't') time) | (&('0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9') number)))) | (&('>') (g ' '* ((&('D' | 'd') date) | (&('T' | 't') time) | (&('0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9') number)))) | (&('<') (l ' '* ((&('D' | 'd') date) | (&('T' | 't') time) | (&('0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9') number)))) | (&('C' | 'c') (contains ' '* value)))))> */ + func() bool { + position16, tokenIndex16 := position, tokenIndex + { + position17 := position + { + position18 := position + { + position19 := position + { + position22, tokenIndex22 := position, tokenIndex + { + switch buffer[position] { + case '<': + if buffer[position] != rune('<') { + goto l22 + } + position++ + break + case '>': + if buffer[position] != rune('>') { + goto l22 + } + position++ + break + case '=': + if buffer[position] != rune('=') { + goto l22 + } + position++ + break + case '\'': + if buffer[position] != rune('\'') { + goto l22 + } + position++ + break + case '"': + if buffer[position] != rune('"') { + goto l22 + } + position++ + break + case ')': + if buffer[position] != rune(')') { + goto l22 + } + position++ + break + case '(': + if buffer[position] != rune('(') { + goto l22 + } + position++ + break + case '\\': + if buffer[position] != rune('\\') { + goto l22 + } + position++ + break + case '\r': + if buffer[position] != rune('\r') { + goto l22 + } + position++ + break + case '\n': + if buffer[position] != rune('\n') { + goto l22 + } + position++ + break + case '\t': + if buffer[position] != rune('\t') { + goto l22 + } + position++ + break + default: + if buffer[position] != rune(' ') { + goto l22 + } + position++ + break + } + } + + goto l16 + l22: + position, tokenIndex = position22, tokenIndex22 + } + if !matchDot() { + goto l16 + } + l20: + { + position21, tokenIndex21 := position, tokenIndex + { + position24, tokenIndex24 := position, tokenIndex + { + switch buffer[position] { + case '<': + if buffer[position] != rune('<') { + goto l24 + } + position++ + break + case '>': + if buffer[position] != rune('>') { + goto l24 + } + position++ + break + case '=': + if buffer[position] != rune('=') { + goto l24 + } + position++ + break + case '\'': + if buffer[position] != rune('\'') { + goto l24 + } + position++ + break + case '"': + if buffer[position] != rune('"') { + goto l24 + } + position++ + break + case ')': + if buffer[position] != rune(')') { + goto l24 + } + position++ + break + case '(': + if buffer[position] != rune('(') { + goto l24 + } + position++ + break + case '\\': + if buffer[position] != rune('\\') { + goto l24 + } + position++ + break + case '\r': + if buffer[position] != rune('\r') { + goto l24 + } + position++ + break + case '\n': + if buffer[position] != rune('\n') { + goto l24 + } + position++ + break + case '\t': + if buffer[position] != rune('\t') { + goto l24 + } + position++ + break + default: + if buffer[position] != rune(' ') { + goto l24 + } + position++ + break + } + } + + goto l21 + l24: + position, tokenIndex = position24, tokenIndex24 + } + if !matchDot() { + goto l21 + } + goto l20 + l21: + position, tokenIndex = position21, tokenIndex21 + } + add(rulePegText, position19) + } + add(ruletag, position18) + } + l26: + { + position27, tokenIndex27 := position, tokenIndex + if buffer[position] != rune(' ') { + goto l27 + } + position++ + goto l26 + l27: + position, tokenIndex = position27, tokenIndex27 + } + { + position28, tokenIndex28 := position, tokenIndex + { + position30 := position + if buffer[position] != rune('<') { + goto l29 + } + position++ + if buffer[position] != rune('=') { + goto l29 + } + position++ + add(rulele, position30) + } + l31: + { + position32, tokenIndex32 := position, tokenIndex + if buffer[position] != rune(' ') { + goto l32 + } + position++ + goto l31 + l32: + position, tokenIndex = position32, tokenIndex32 + } + { + switch buffer[position] { + case 'D', 'd': + if !_rules[ruledate]() { + goto l29 + } + break + case 'T', 't': + if !_rules[ruletime]() { + goto l29 + } + break + default: + if !_rules[rulenumber]() { + goto l29 + } + break + } + } + + goto l28 + l29: + position, tokenIndex = position28, tokenIndex28 + { + position35 := position + if buffer[position] != rune('>') { + goto l34 + } + position++ + if buffer[position] != rune('=') { + goto l34 + } + position++ + add(rulege, position35) + } + l36: + { + position37, tokenIndex37 := position, tokenIndex + if buffer[position] != rune(' ') { + goto l37 + } + position++ + goto l36 + l37: + position, tokenIndex = position37, tokenIndex37 + } + { + switch buffer[position] { + case 'D', 'd': + if !_rules[ruledate]() { + goto l34 + } + break + case 'T', 't': + if !_rules[ruletime]() { + goto l34 + } + break + default: + if !_rules[rulenumber]() { + goto l34 + } + break + } + } + + goto l28 + l34: + position, tokenIndex = position28, tokenIndex28 + { + switch buffer[position] { + case '=': + { + position40 := position + if buffer[position] != rune('=') { + goto l16 + } + position++ + add(ruleequal, position40) + } + l41: + { + position42, tokenIndex42 := position, tokenIndex + if buffer[position] != rune(' ') { + goto l42 + } + position++ + goto l41 + l42: + position, tokenIndex = position42, tokenIndex42 + } + { + switch buffer[position] { + case '\'': + if !_rules[rulevalue]() { + goto l16 + } + break + case 'D', 'd': + if !_rules[ruledate]() { + goto l16 + } + break + case 'T', 't': + if !_rules[ruletime]() { + goto l16 + } + break + default: + if !_rules[rulenumber]() { + goto l16 + } + break + } + } + + break + case '>': + { + position44 := position + if buffer[position] != rune('>') { + goto l16 + } + position++ + add(ruleg, position44) + } + l45: + { + position46, tokenIndex46 := position, tokenIndex + if buffer[position] != rune(' ') { + goto l46 + } + position++ + goto l45 + l46: + position, tokenIndex = position46, tokenIndex46 + } + { + switch buffer[position] { + case 'D', 'd': + if !_rules[ruledate]() { + goto l16 + } + break + case 'T', 't': + if !_rules[ruletime]() { + goto l16 + } + break + default: + if !_rules[rulenumber]() { + goto l16 + } + break + } + } + + break + case '<': + { + position48 := position + if buffer[position] != rune('<') { + goto l16 + } + position++ + add(rulel, position48) + } + l49: + { + position50, tokenIndex50 := position, tokenIndex + if buffer[position] != rune(' ') { + goto l50 + } + position++ + goto l49 + l50: + position, tokenIndex = position50, tokenIndex50 + } + { + switch buffer[position] { + case 'D', 'd': + if !_rules[ruledate]() { + goto l16 + } + break + case 'T', 't': + if !_rules[ruletime]() { + goto l16 + } + break + default: + if !_rules[rulenumber]() { + goto l16 + } + break + } + } + + break + default: + { + position52 := position + { + position53, tokenIndex53 := position, tokenIndex + if buffer[position] != rune('c') { + goto l54 + } + position++ + goto l53 + l54: + position, tokenIndex = position53, tokenIndex53 + if buffer[position] != rune('C') { + goto l16 + } + position++ + } + l53: + { + position55, tokenIndex55 := position, tokenIndex + if buffer[position] != rune('o') { + goto l56 + } + position++ + goto l55 + l56: + position, tokenIndex = position55, tokenIndex55 + if buffer[position] != rune('O') { + goto l16 + } + position++ + } + l55: + { + position57, tokenIndex57 := position, tokenIndex + if buffer[position] != rune('n') { + goto l58 + } + position++ + goto l57 + l58: + position, tokenIndex = position57, tokenIndex57 + if buffer[position] != rune('N') { + goto l16 + } + position++ + } + l57: + { + position59, tokenIndex59 := position, tokenIndex + if buffer[position] != rune('t') { + goto l60 + } + position++ + goto l59 + l60: + position, tokenIndex = position59, tokenIndex59 + if buffer[position] != rune('T') { + goto l16 + } + position++ + } + l59: + { + position61, tokenIndex61 := position, tokenIndex + if buffer[position] != rune('a') { + goto l62 + } + position++ + goto l61 + l62: + position, tokenIndex = position61, tokenIndex61 + if buffer[position] != rune('A') { + goto l16 + } + position++ + } + l61: + { + position63, tokenIndex63 := position, tokenIndex + if buffer[position] != rune('i') { + goto l64 + } + position++ + goto l63 + l64: + position, tokenIndex = position63, tokenIndex63 + if buffer[position] != rune('I') { + goto l16 + } + position++ + } + l63: + { + position65, tokenIndex65 := position, tokenIndex + if buffer[position] != rune('n') { + goto l66 + } + position++ + goto l65 + l66: + position, tokenIndex = position65, tokenIndex65 + if buffer[position] != rune('N') { + goto l16 + } + position++ + } + l65: + { + position67, tokenIndex67 := position, tokenIndex + if buffer[position] != rune('s') { + goto l68 + } + position++ + goto l67 + l68: + position, tokenIndex = position67, tokenIndex67 + if buffer[position] != rune('S') { + goto l16 + } + position++ + } + l67: + add(rulecontains, position52) + } + l69: + { + position70, tokenIndex70 := position, tokenIndex + if buffer[position] != rune(' ') { + goto l70 + } + position++ + goto l69 + l70: + position, tokenIndex = position70, tokenIndex70 + } + if !_rules[rulevalue]() { + goto l16 + } + break + } + } + + } + l28: + add(rulecondition, position17) + } + return true + l16: + position, tokenIndex = position16, tokenIndex16 + return false + }, + /* 2 tag <- <<(!((&('<') '<') | (&('>') '>') | (&('=') '=') | (&('\'') '\'') | (&('"') '"') | (&(')') ')') | (&('(') '(') | (&('\\') '\\') | (&('\r') '\r') | (&('\n') '\n') | (&('\t') '\t') | (&(' ') ' ')) .)+>> */ + nil, + /* 3 value <- <<('\'' (!('"' / '\'') .)* '\'')>> */ + func() bool { + position72, tokenIndex72 := position, tokenIndex + { + position73 := position + { + position74 := position + if buffer[position] != rune('\'') { + goto l72 + } + position++ + l75: + { + position76, tokenIndex76 := position, tokenIndex + { + position77, tokenIndex77 := position, tokenIndex + { + position78, tokenIndex78 := position, tokenIndex + if buffer[position] != rune('"') { + goto l79 + } + position++ + goto l78 + l79: + position, tokenIndex = position78, tokenIndex78 + if buffer[position] != rune('\'') { + goto l77 + } + position++ + } + l78: + goto l76 + l77: + position, tokenIndex = position77, tokenIndex77 + } + if !matchDot() { + goto l76 + } + goto l75 + l76: + position, tokenIndex = position76, tokenIndex76 + } + if buffer[position] != rune('\'') { + goto l72 + } + position++ + add(rulePegText, position74) + } + add(rulevalue, position73) + } + return true + l72: + position, tokenIndex = position72, tokenIndex72 + return false + }, + /* 4 number <- <<('0' / ([1-9] digit* ('.' digit*)?))>> */ + func() bool { + position80, tokenIndex80 := position, tokenIndex + { + position81 := position + { + position82 := position + { + position83, tokenIndex83 := position, tokenIndex + if buffer[position] != rune('0') { + goto l84 + } + position++ + goto l83 + l84: + position, tokenIndex = position83, tokenIndex83 + if c := buffer[position]; c < rune('1') || c > rune('9') { + goto l80 + } + position++ + l85: + { + position86, tokenIndex86 := position, tokenIndex + if !_rules[ruledigit]() { + goto l86 + } + goto l85 + l86: + position, tokenIndex = position86, tokenIndex86 + } + { + position87, tokenIndex87 := position, tokenIndex + if buffer[position] != rune('.') { + goto l87 + } + position++ + l89: + { + position90, tokenIndex90 := position, tokenIndex + if !_rules[ruledigit]() { + goto l90 + } + goto l89 + l90: + position, tokenIndex = position90, tokenIndex90 + } + goto l88 + l87: + position, tokenIndex = position87, tokenIndex87 + } + l88: + } + l83: + add(rulePegText, position82) + } + add(rulenumber, position81) + } + return true + l80: + position, tokenIndex = position80, tokenIndex80 + return false + }, + /* 5 digit <- <[0-9]> */ + func() bool { + position91, tokenIndex91 := position, tokenIndex + { + position92 := position + if c := buffer[position]; c < rune('0') || c > rune('9') { + goto l91 + } + position++ + add(ruledigit, position92) + } + return true + l91: + position, tokenIndex = position91, tokenIndex91 + return false + }, + /* 6 time <- <(('t' / 'T') ('i' / 'I') ('m' / 'M') ('e' / 'E') ' ' <(year '-' month '-' day 'T' digit digit ':' digit digit ':' digit digit ((('-' / '+') digit digit ':' digit digit) / 'Z'))>)> */ + func() bool { + position93, tokenIndex93 := position, tokenIndex + { + position94 := position + { + position95, tokenIndex95 := position, tokenIndex + if buffer[position] != rune('t') { + goto l96 + } + position++ + goto l95 + l96: + position, tokenIndex = position95, tokenIndex95 + if buffer[position] != rune('T') { + goto l93 + } + position++ + } + l95: + { + position97, tokenIndex97 := position, tokenIndex + if buffer[position] != rune('i') { + goto l98 + } + position++ + goto l97 + l98: + position, tokenIndex = position97, tokenIndex97 + if buffer[position] != rune('I') { + goto l93 + } + position++ + } + l97: + { + position99, tokenIndex99 := position, tokenIndex + if buffer[position] != rune('m') { + goto l100 + } + position++ + goto l99 + l100: + position, tokenIndex = position99, tokenIndex99 + if buffer[position] != rune('M') { + goto l93 + } + position++ + } + l99: + { + position101, tokenIndex101 := position, tokenIndex + if buffer[position] != rune('e') { + goto l102 + } + position++ + goto l101 + l102: + position, tokenIndex = position101, tokenIndex101 + if buffer[position] != rune('E') { + goto l93 + } + position++ + } + l101: + if buffer[position] != rune(' ') { + goto l93 + } + position++ + { + position103 := position + if !_rules[ruleyear]() { + goto l93 + } + if buffer[position] != rune('-') { + goto l93 + } + position++ + if !_rules[rulemonth]() { + goto l93 + } + if buffer[position] != rune('-') { + goto l93 + } + position++ + if !_rules[ruleday]() { + goto l93 + } + if buffer[position] != rune('T') { + goto l93 + } + position++ + if !_rules[ruledigit]() { + goto l93 + } + if !_rules[ruledigit]() { + goto l93 + } + if buffer[position] != rune(':') { + goto l93 + } + position++ + if !_rules[ruledigit]() { + goto l93 + } + if !_rules[ruledigit]() { + goto l93 + } + if buffer[position] != rune(':') { + goto l93 + } + position++ + if !_rules[ruledigit]() { + goto l93 + } + if !_rules[ruledigit]() { + goto l93 + } + { + position104, tokenIndex104 := position, tokenIndex + { + position106, tokenIndex106 := position, tokenIndex + if buffer[position] != rune('-') { + goto l107 + } + position++ + goto l106 + l107: + position, tokenIndex = position106, tokenIndex106 + if buffer[position] != rune('+') { + goto l105 + } + position++ + } + l106: + if !_rules[ruledigit]() { + goto l105 + } + if !_rules[ruledigit]() { + goto l105 + } + if buffer[position] != rune(':') { + goto l105 + } + position++ + if !_rules[ruledigit]() { + goto l105 + } + if !_rules[ruledigit]() { + goto l105 + } + goto l104 + l105: + position, tokenIndex = position104, tokenIndex104 + if buffer[position] != rune('Z') { + goto l93 + } + position++ + } + l104: + add(rulePegText, position103) + } + add(ruletime, position94) + } + return true + l93: + position, tokenIndex = position93, tokenIndex93 + return false + }, + /* 7 date <- <(('d' / 'D') ('a' / 'A') ('t' / 'T') ('e' / 'E') ' ' <(year '-' month '-' day)>)> */ + func() bool { + position108, tokenIndex108 := position, tokenIndex + { + position109 := position + { + position110, tokenIndex110 := position, tokenIndex + if buffer[position] != rune('d') { + goto l111 + } + position++ + goto l110 + l111: + position, tokenIndex = position110, tokenIndex110 + if buffer[position] != rune('D') { + goto l108 + } + position++ + } + l110: + { + position112, tokenIndex112 := position, tokenIndex + if buffer[position] != rune('a') { + goto l113 + } + position++ + goto l112 + l113: + position, tokenIndex = position112, tokenIndex112 + if buffer[position] != rune('A') { + goto l108 + } + position++ + } + l112: + { + position114, tokenIndex114 := position, tokenIndex + if buffer[position] != rune('t') { + goto l115 + } + position++ + goto l114 + l115: + position, tokenIndex = position114, tokenIndex114 + if buffer[position] != rune('T') { + goto l108 + } + position++ + } + l114: + { + position116, tokenIndex116 := position, tokenIndex + if buffer[position] != rune('e') { + goto l117 + } + position++ + goto l116 + l117: + position, tokenIndex = position116, tokenIndex116 + if buffer[position] != rune('E') { + goto l108 + } + position++ + } + l116: + if buffer[position] != rune(' ') { + goto l108 + } + position++ + { + position118 := position + if !_rules[ruleyear]() { + goto l108 + } + if buffer[position] != rune('-') { + goto l108 + } + position++ + if !_rules[rulemonth]() { + goto l108 + } + if buffer[position] != rune('-') { + goto l108 + } + position++ + if !_rules[ruleday]() { + goto l108 + } + add(rulePegText, position118) + } + add(ruledate, position109) + } + return true + l108: + position, tokenIndex = position108, tokenIndex108 + return false + }, + /* 8 year <- <(('1' / '2') digit digit digit)> */ + func() bool { + position119, tokenIndex119 := position, tokenIndex + { + position120 := position + { + position121, tokenIndex121 := position, tokenIndex + if buffer[position] != rune('1') { + goto l122 + } + position++ + goto l121 + l122: + position, tokenIndex = position121, tokenIndex121 + if buffer[position] != rune('2') { + goto l119 + } + position++ + } + l121: + if !_rules[ruledigit]() { + goto l119 + } + if !_rules[ruledigit]() { + goto l119 + } + if !_rules[ruledigit]() { + goto l119 + } + add(ruleyear, position120) + } + return true + l119: + position, tokenIndex = position119, tokenIndex119 + return false + }, + /* 9 month <- <(('0' / '1') digit)> */ + func() bool { + position123, tokenIndex123 := position, tokenIndex + { + position124 := position + { + position125, tokenIndex125 := position, tokenIndex + if buffer[position] != rune('0') { + goto l126 + } + position++ + goto l125 + l126: + position, tokenIndex = position125, tokenIndex125 + if buffer[position] != rune('1') { + goto l123 + } + position++ + } + l125: + if !_rules[ruledigit]() { + goto l123 + } + add(rulemonth, position124) + } + return true + l123: + position, tokenIndex = position123, tokenIndex123 + return false + }, + /* 10 day <- <(((&('3') '3') | (&('2') '2') | (&('1') '1') | (&('0') '0')) digit)> */ + func() bool { + position127, tokenIndex127 := position, tokenIndex + { + position128 := position + { + switch buffer[position] { + case '3': + if buffer[position] != rune('3') { + goto l127 + } + position++ + break + case '2': + if buffer[position] != rune('2') { + goto l127 + } + position++ + break + case '1': + if buffer[position] != rune('1') { + goto l127 + } + position++ + break + default: + if buffer[position] != rune('0') { + goto l127 + } + position++ + break + } + } + + if !_rules[ruledigit]() { + goto l127 + } + add(ruleday, position128) + } + return true + l127: + position, tokenIndex = position127, tokenIndex127 + return false + }, + /* 11 and <- <(('a' / 'A') ('n' / 'N') ('d' / 'D'))> */ + nil, + /* 12 equal <- <'='> */ + nil, + /* 13 contains <- <(('c' / 'C') ('o' / 'O') ('n' / 'N') ('t' / 'T') ('a' / 'A') ('i' / 'I') ('n' / 'N') ('s' / 'S'))> */ + nil, + /* 14 le <- <('<' '=')> */ + nil, + /* 15 ge <- <('>' '=')> */ + nil, + /* 16 l <- <'<'> */ + nil, + /* 17 g <- <'>'> */ + nil, + nil, + } + p.rules = _rules +} diff --git a/event/query/query_test.go b/event/query/query_test.go index a7116b0a8..0951bf434 100644 --- a/event/query/query_test.go +++ b/event/query/query_test.go @@ -1,53 +1,84 @@ package query import ( + "fmt" "testing" + "time" - "github.com/hyperledger/burrow/logging/structure" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/libs/pubsub" ) -func TestQueryBuilder(t *testing.T) { - qb := NewBuilder() - qry, err := qb.Query() - require.NoError(t, err) - assert.Equal(t, emptyString, qry.String()) +func TestMatches(t *testing.T) { + var ( + txDate = "2017-01-01" + txTime = "2018-05-03T14:45:00Z" + ) - qb = qb.AndGreaterThanOrEqual("foo.size", 45) - qry, err = qb.Query() - require.NoError(t, err) - assert.Equal(t, "foo.size >= 45", qry.String()) + testCases := []struct { + s string + tags map[string]interface{} + err bool + matches bool + }{ + {"tm.events.type='NewBlock'", map[string]interface{}{"tm.events.type": "NewBlock"}, false, true}, - qb = qb.AndEquals("bar.name", "marmot") - qry, err = qb.Query() - require.NoError(t, err) - assert.Equal(t, "foo.size >= 45 AND bar.name = 'marmot'", qry.String()) + {"tx.gas > 7", map[string]interface{}{"tx.gas": "8"}, false, true}, + {"tx.gas > 7 AND tx.gas < 9", map[string]interface{}{"tx.gas": "8"}, false, true}, + {"body.weight >= 3.5", map[string]interface{}{"body.weight": "3.5"}, false, true}, + {"account.balance < 1000.0", map[string]interface{}{"account.balance": "900"}, false, true}, + {"apples.kg <= 4", map[string]interface{}{"apples.kg": "4.0"}, false, true}, + {"body.weight >= 4.5", map[string]interface{}{"body.weight": fmt.Sprintf("%v", float32(4.5))}, false, true}, + {"oranges.kg < 4 AND watermellons.kg > 10", map[string]interface{}{"oranges.kg": "3", "watermellons.kg": "12"}, false, true}, + {"peaches.kg < 4", map[string]interface{}{"peaches.kg": "5"}, false, false}, - assert.True(t, qry.Matches(makeTagMap("foo.size", 80, "bar.name", "marmot"))) - assert.False(t, qry.Matches(makeTagMap("foo.size", 8, "bar.name", "marmot"))) - assert.False(t, qry.Matches(makeTagMap("foo.size", 80, "bar.name", "marot"))) + {"tx.date > DATE 2017-01-01", map[string]interface{}{"tx.date": time.Now().Format(DateLayout)}, false, true}, + {"tx.date = DATE 2017-01-01", map[string]interface{}{"tx.date": txDate}, false, true}, + {"tx.date = DATE 2018-01-01", map[string]interface{}{"tx.date": txDate}, false, false}, - qb = qb.AndContains("bar.desc", "burrow") - qry, err = qb.Query() - require.NoError(t, err) - assert.Equal(t, "foo.size >= 45 AND bar.name = 'marmot' AND bar.desc CONTAINS 'burrow'", qry.String()) + {"tx.time >= TIME 2013-05-03T14:45:00Z", map[string]interface{}{"tx.time": time.Now().Format(TimeLayout)}, false, true}, + {"tx.time = TIME 2013-05-03T14:45:00Z", map[string]interface{}{"tx.time": txTime}, false, false}, - assert.True(t, qry.Matches(makeTagMap("foo.size", 80, "bar.name", "marmot", "bar.desc", "lives in a burrow"))) - assert.False(t, qry.Matches(makeTagMap("foo.size", 80, "bar.name", "marmot", "bar.desc", "lives in a shoe"))) + {"abci.owner.name CONTAINS 'Igor'", map[string]interface{}{"abci.owner.name": "Igor,Ivan"}, false, true}, + {"abci.owner.name CONTAINS 'Igor'", map[string]interface{}{"abci.owner.name": "Pavel,Ivan"}, false, false}, + } - qb = NewBuilder().AndEquals("foo", "bar") - qb = qb.And(NewBuilder().AndGreaterThanOrEqual("frogs", 4)) - qry, err = qb.Query() - require.NoError(t, err) - assert.Equal(t, "foo = 'bar' AND frogs >= 4", qry.String()) + for _, tc := range testCases { + q, err := New(tc.s) + if !tc.err { + require.Nil(t, err) + } + + if tc.matches { + assert.True(t, q.Matches(TagMap(tc.tags)), "Query '%s' should match %v", tc.s, tc.tags) + } else { + assert.False(t, q.Matches(TagMap(tc.tags)), "Query '%s' should not match %v", tc.s, tc.tags) + } + } } -func makeTagMap(keyvals ...interface{}) pubsub.TagMap { - tmap := make(map[string]string) - for i := 0; i < len(keyvals); i += 2 { - tmap[keyvals[i].(string)] = structure.StringifyKey(keyvals[i+1]) +func TestMustParse(t *testing.T) { + assert.Panics(t, func() { MustParse("=") }) + assert.NotPanics(t, func() { MustParse("tm.events.type='NewBlock'") }) +} + +func TestConditions(t *testing.T) { + txTime, err := time.Parse(time.RFC3339, "2013-05-03T14:45:00Z") + require.NoError(t, err) + + testCases := []struct { + s string + conditions []Condition + }{ + {s: "tm.events.type='NewBlock'", conditions: []Condition{{Tag: "tm.events.type", Op: OpEqual, Operand: "NewBlock"}}}, + {s: "tx.gas > 7 AND tx.gas < 9", conditions: []Condition{{Tag: "tx.gas", Op: OpGreater, Operand: int64(7)}, {Tag: "tx.gas", Op: OpLess, Operand: int64(9)}}}, + {s: "tx.time >= TIME 2013-05-03T14:45:00Z", conditions: []Condition{{Tag: "tx.time", Op: OpGreaterEqual, Operand: txTime}}}, + } + + for _, tc := range testCases { + q, err := New(tc.s) + require.Nil(t, err) + + assert.Equal(t, tc.conditions, q.Conditions()) } - return pubsub.NewTagMap(tmap) } diff --git a/event/query/reflect_tagged.go b/event/query/reflect_tagged.go new file mode 100644 index 000000000..b5cc63864 --- /dev/null +++ b/event/query/reflect_tagged.go @@ -0,0 +1,99 @@ +package query + +import ( + "fmt" + "reflect" +) + +type ReflectTagged struct { + rv reflect.Value + keys []string + ks map[string]struct{} +} + +var _ Tagged = &ReflectTagged{} + +func MustReflectTags(value interface{}, fieldNames ...string) *ReflectTagged { + rt, err := ReflectTags(value, fieldNames...) + if err != nil { + panic(err) + } + return rt +} + +// ReflectTags provides a query.Tagged on a structs exported fields using query.StringFromValue to derive the string +// values associated with each field. If passed explicit field names will only only provide those fields as tags, +// otherwise all exported fields are provided. +func ReflectTags(value interface{}, fieldNames ...string) (*ReflectTagged, error) { + rv := reflect.ValueOf(value) + if rv.IsNil() { + return &ReflectTagged{}, nil + } + if rv.Kind() != reflect.Ptr { + return nil, fmt.Errorf("ReflectStructTags needs a pointer to a struct but %v is not a pointer", + rv.Interface()) + } + if rv.Elem().Kind() != reflect.Struct { + return nil, fmt.Errorf("ReflectStructTags needs a pointer to a struct but %v does not point to a struct", + rv.Interface()) + } + ty := rv.Elem().Type() + + numField := ty.NumField() + if len(fieldNames) > 0 { + if len(fieldNames) > numField { + return nil, fmt.Errorf("ReflectTags asked to tag %v fields but %v only has %v fields", + len(fieldNames), rv.Interface(), numField) + } + numField = len(fieldNames) + } + rt := &ReflectTagged{ + rv: rv, + ks: make(map[string]struct{}, numField), + keys: make([]string, 0, numField), + } + if len(fieldNames) > 0 { + for _, fieldName := range fieldNames { + field, ok := ty.FieldByName(fieldName) + if !ok { + return nil, fmt.Errorf("ReflectTags asked to tag field named %s by no such field on %v", + fieldName, rv.Interface()) + } + ok = rt.registerField(field) + if !ok { + return nil, fmt.Errorf("field %s of %v is not exported so cannot act as tag", fieldName, + rv.Interface()) + } + } + } else { + for i := 0; i < numField; i++ { + rt.registerField(ty.Field(i)) + } + } + return rt, nil +} + +func (rt *ReflectTagged) registerField(field reflect.StructField) (ok bool) { + // Empty iff struct field is exported + if field.PkgPath == "" { + rt.keys = append(rt.keys, field.Name) + rt.ks[field.Name] = struct{}{} + return true + } + return false +} + +func (rt *ReflectTagged) Keys() []string { + return rt.keys +} + +func (rt *ReflectTagged) Get(key string) (value string, ok bool) { + if _, ok := rt.ks[key]; ok { + return StringFromValue(rt.rv.Elem().FieldByName(key).Interface()), true + } + return "", false +} + +func (rt *ReflectTagged) Len() int { + return len(rt.keys) +} diff --git a/event/query/reflect_tagged_test.go b/event/query/reflect_tagged_test.go new file mode 100644 index 000000000..1a2fe1aa7 --- /dev/null +++ b/event/query/reflect_tagged_test.go @@ -0,0 +1,97 @@ +package query + +import ( + "testing" + + "github.com/hyperledger/burrow/binary" + "github.com/hyperledger/burrow/crypto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type testTaggable struct { + Foo string + Bar string + Baz binary.HexBytes + Address crypto.Address + Indices []int + unexported int +} + +func TestReflectTagged_Keys(t *testing.T) { + rt, err := ReflectTags(&testTaggable{}) + require.NoError(t, err) + assert.Equal(t, []string{"Foo", "Bar", "Baz", "Address", "Indices"}, rt.Keys()) +} + +func TestReflectTagged_Get(t *testing.T) { + tt := testTaggable{ + Foo: "Thumbs", + Bar: "Numbed", + Baz: []byte{255, 255, 255}, + Address: crypto.Address{1, 2, 3}, + Indices: []int{5, 7, 9}, + } + rt, err := ReflectTags(&tt) + require.NoError(t, err) + + value, ok := rt.Get("Foo") + assert.True(t, ok) + assert.Equal(t, tt.Foo, value) + + value, ok = rt.Get("Bar") + assert.True(t, ok) + assert.Equal(t, tt.Bar, value) + + value, ok = rt.Get("Baz") + assert.True(t, ok) + assert.Equal(t, "FFFFFF", value) + + value, ok = rt.Get("Indices") + assert.True(t, ok) + assert.Equal(t, "5;7;9", value) + + value, ok = rt.Get("Address") + assert.True(t, ok) + assert.Equal(t, "0102030000000000000000000000000000000000", value) + + // Make sure we see updates through pointer + tt.Foo = "Plums" + value, ok = rt.Get("Foo") + assert.True(t, ok) + assert.Equal(t, tt.Foo, value) +} + +func TestReflectTagged_Len(t *testing.T) { + rt, err := ReflectTags(&testTaggable{}) + require.NoError(t, err) + assert.Equal(t, 5, rt.Len()) +} + +func TestExplicitFields(t *testing.T) { + tt := testTaggable{ + Foo: "Thumbs", + Bar: "Numbed", + Baz: []byte{255, 255, 255}, + Address: crypto.Address{1, 2, 3}, + } + rt, err := ReflectTags(&tt, "Foo", "Address") + require.NoError(t, err) + + value, ok := rt.Get("Foo") + assert.True(t, ok) + assert.Equal(t, tt.Foo, value) + + value, ok = rt.Get("Address") + assert.True(t, ok) + assert.Equal(t, "0102030000000000000000000000000000000000", value) + + _, ok = rt.Get("Bar") + assert.False(t, ok) + + _, ok = rt.Get("Barsss") + assert.False(t, ok) + + _, err = ReflectTags(&tt, "Foo", "Address", "Balloons") + require.Error(t, err) +} diff --git a/event/query/tags.go b/event/query/tags.go new file mode 100644 index 000000000..d177b1a09 --- /dev/null +++ b/event/query/tags.go @@ -0,0 +1,126 @@ +package query + +import ( + "fmt" + "strings" +) + +type Tagged interface { + Keys() []string + Get(key string) (value string, ok bool) + // Len returns the number of tags. + Len() int +} + +type TagMap map[string]interface{} + +func MapFromTagged(tagged Tagged) map[string]interface{} { + tags := make(map[string]interface{}) + for _, k := range tagged.Keys() { + v, ok := tagged.Get(k) + if ok { + tags[k] = v + } + } + return tags +} + +func (ts TagMap) Get(key string) (value string, ok bool) { + var vint interface{} + vint, ok = ts[key] + if !ok { + return + } + switch v := vint.(type) { + case string: + value = v + case fmt.Stringer: + value = v.String() + default: + value = fmt.Sprintf("%v", v) + } + return +} + +func (ts TagMap) Len() int { + return len(ts) +} + +func (ts TagMap) Map() map[string]interface{} { + return ts +} + +func (ts TagMap) Keys() []string { + keys := make([]string, 0, len(ts)) + for k := range ts { + keys = append(keys, k) + } + return keys +} + +type CombinedTags struct { + keys []string + ks map[string][]Tagged + concat bool +} + +func NewCombinedTags() *CombinedTags { + return &CombinedTags{ + ks: make(map[string][]Tagged), + } +} + +func MergeTags(tags ...Tagged) *CombinedTags { + ct := NewCombinedTags() + ct.AddTags(false, tags...) + return ct +} + +func ConcatTags(tags ...Tagged) *CombinedTags { + ct := NewCombinedTags() + ct.AddTags(true, tags...) + return ct +} + +// Adds each of tagsList to CombinedTags - choosing whether values for the same key should +// be concatenated or whether the first should value should stick +func (ct *CombinedTags) AddTags(concat bool, tagsList ...Tagged) { + for _, t := range tagsList { + for _, k := range t.Keys() { + if len(ct.ks[k]) == 0 { + ct.keys = append(ct.keys, k) + // Store reference to key-holder amongst Taggeds + ct.ks[k] = append(ct.ks[k], t) + } else if concat { + // Store additional tag reference only if concat, otherwise first key-holder wins + ct.ks[k] = append(ct.ks[k], t) + } + } + } +} + +func (ct *CombinedTags) Get(key string) (string, bool) { + ts := ct.ks[key] + if len(ts) == 0 { + return "", false + } + values := make([]string, 0, len(ts)) + for _, t := range ts { + value, ok := t.Get(key) + if ok { + values = append(values, value) + } + } + if len(values) == 0 { + return "", false + } + return strings.Join(values, MultipleValueTagSeparator), true +} + +func (ct *CombinedTags) Len() (length int) { + return len(ct.keys) +} + +func (ct *CombinedTags) Keys() []string { + return ct.keys +} diff --git a/event/tags.go b/event/tags.go deleted file mode 100644 index 759d035d7..000000000 --- a/event/tags.go +++ /dev/null @@ -1,87 +0,0 @@ -package event - -import ( - "fmt" - - "github.com/tendermint/tendermint/libs/pubsub" -) - -type Tags interface { - pubsub.TagMap - Keys() []string -} - -type TagMap map[string]interface{} - -func (ts TagMap) Get(key string) (value string, ok bool) { - var vint interface{} - vint, ok = ts[key] - if !ok { - return - } - switch v := vint.(type) { - case string: - value = v - case fmt.Stringer: - value = v.String() - default: - value = fmt.Sprintf("%v", v) - } - return -} - -func (ts TagMap) Len() int { - return len(ts) -} - -func (ts TagMap) Map() map[string]interface{} { - return ts -} - -func (ts TagMap) Keys() []string { - keys := make([]string, 0, len(ts)) - for k := range ts { - keys = append(keys, k) - } - return keys -} - -type CombinedTags []Tags - -func (ct CombinedTags) Get(key string) (value string, ok bool) { - for _, t := range ct { - value, ok = t.Get(key) - if ok { - return - } - } - return -} - -func (ct CombinedTags) Len() (length int) { - for _, t := range ct { - length += t.Len() - } - return length -} - -func (ct CombinedTags) Map() map[string]interface{} { - tags := make(map[string]interface{}) - for _, t := range ct { - for _, k := range t.Keys() { - v, ok := t.Get(k) - if ok { - tags[k] = v - } - } - } - return tags -} - -func (ct CombinedTags) Keys() []string { - var keys []string - for _, t := range ct { - keys = append(keys, t.Keys()...) - } - return keys -} diff --git a/execution/accounts.go b/execution/accounts.go index 8125ef0a1..396f43302 100644 --- a/execution/accounts.go +++ b/execution/accounts.go @@ -1,11 +1,10 @@ package execution import ( - "fmt" "sync" - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/state" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/keys" burrow_sync "github.com/hyperledger/burrow/sync" @@ -25,6 +24,7 @@ type SigningAccount struct { } type SequentialSigningAccount struct { + Address crypto.Address accountLocker sync.Locker getter func() (*SigningAccount, error) } @@ -37,7 +37,11 @@ func NewAccounts(reader state.Reader, keyClient keys.KeyClient, mutexCount int) keyClient: keyClient, } } -func (accs *Accounts) SigningAccount(address crypto.Address, signer crypto.Signer) (*SigningAccount, error) { +func (accs *Accounts) SigningAccount(address crypto.Address) (*SigningAccount, error) { + signer, err := keys.AddressableSigner(accs.keyClient, address) + if err != nil { + return nil, err + } account, err := state.GetMutableAccount(accs, address) if err != nil { return nil, err @@ -60,50 +64,15 @@ func (accs *Accounts) SigningAccount(address crypto.Address, signer crypto.Signe } func (accs *Accounts) SequentialSigningAccount(address crypto.Address) (*SequentialSigningAccount, error) { - signer, err := keys.AddressableSigner(accs.keyClient, address) - if err != nil { - return nil, err - } return &SequentialSigningAccount{ + Address: address, accountLocker: accs.Mutex(address.Bytes()), getter: func() (*SigningAccount, error) { - return accs.SigningAccount(address, signer) - }, - }, nil -} - -func (accs *Accounts) SequentialSigningAccountFromPrivateKey(privateKeyBytes []byte) (*SequentialSigningAccount, error) { - if len(privateKeyBytes) != 64 { - return nil, fmt.Errorf("private key is not of the right length: %d\n", len(privateKeyBytes)) - } - privateAccount, err := acm.GeneratePrivateAccountFromPrivateKeyBytes(privateKeyBytes) - if err != nil { - return nil, err - } - return &SequentialSigningAccount{ - accountLocker: accs.Mutex(privateAccount.Address().Bytes()), - getter: func() (*SigningAccount, error) { - return accs.SigningAccount(privateAccount.Address(), privateAccount) + return accs.SigningAccount(address) }, }, nil } -// Gets signing account from onr of private key or address - failing if both are provided -func (accs *Accounts) GetSequentialSigningAccount(address, privateKey []byte) (*SequentialSigningAccount, error) { - if len(address) > 0 { - if len(privateKey) > 0 { - return nil, fmt.Errorf("address and private key provided but only one or the other should be given") - } - address, err := crypto.AddressFromBytes(address) - if err != nil { - return nil, err - } - return accs.SequentialSigningAccount(address) - } - - return accs.SequentialSigningAccountFromPrivateKey(privateKey) -} - type UnlockFunc func() func (ssa *SequentialSigningAccount) Lock() (*SigningAccount, UnlockFunc, error) { diff --git a/execution/config.go b/execution/config.go index f90b6a02c..1f61d068f 100644 --- a/execution/config.go +++ b/execution/config.go @@ -21,6 +21,14 @@ func DefaultExecutionConfig() *ExecutionConfig { return &ExecutionConfig{} } +type ExecutionOption func(*executor) + +func VMOptions(vmOptions ...func(*evm.VM)) func(*executor) { + return func(exe *executor) { + exe.vmOptions = vmOptions + } +} + func (ec *ExecutionConfig) ExecutionOptions() ([]ExecutionOption, error) { var exeOptions []ExecutionOption var vmOptions []func(*evm.VM) diff --git a/execution/errors/errors.go b/execution/errors/errors.go index ba15497f0..8e3bd2cc1 100644 --- a/execution/errors/errors.go +++ b/execution/errors/errors.go @@ -1,9 +1,6 @@ package errors -import ( - "encoding/json" - "fmt" -) +import "fmt" type CodedError interface { error @@ -33,6 +30,8 @@ const ( ErrorCodePermissionDenied ErrorCodeNativeFunction ErrorCodeEventPublish + ErrorCodeInvalidString + ErrorCodeEventMapping ) func (c Code) ErrorCode() Code { @@ -77,6 +76,10 @@ func (c Code) Error() string { return "Native function error" case ErrorCodeEventPublish: return "Event publish error" + case ErrorCodeInvalidString: + return "Invalid string" + case ErrorCodeEventMapping: + return "Event mapping error" case ErrorCodeGeneric: return "Generic error" default: @@ -89,15 +92,13 @@ func NewCodedError(errorCode Code, exception string) *Exception { return nil } return &Exception{ - Code: &ErrorCode{ - Code: uint32(errorCode), - }, + Code: errorCode, Exception: exception, } } // Wraps any error as a Exception -func AsCodedError(err error) *Exception { +func AsException(err error) *Exception { if err == nil { return nil } @@ -115,11 +116,11 @@ func Wrap(err CodedError, message string) *Exception { return NewCodedError(err.ErrorCode(), message+": "+err.Error()) } -func Errorf(format string, a ...interface{}) CodedError { +func Errorf(format string, a ...interface{}) *Exception { return ErrorCodef(ErrorCodeGeneric, format, a...) } -func ErrorCodef(errorCode Code, format string, a ...interface{}) CodedError { +func ErrorCodef(errorCode Code, format string, a ...interface{}) *Exception { return NewCodedError(errorCode, fmt.Sprintf(format, a...)) } @@ -132,26 +133,16 @@ func (e *Exception) AsError() error { } func (e *Exception) ErrorCode() Code { - return Code(e.GetCode().Code) + return e.Code +} + +func (e *Exception) String() string { + return e.Error() } func (e *Exception) Error() string { if e == nil { return "" } - return fmt.Sprintf("Error %v: %s", e.Code.Code, e.Exception) -} - -func NewErrorCode(code Code) *ErrorCode { - return &ErrorCode{ - Code: uint32(code), - } -} - -func (e ErrorCode) MarshalJSON() ([]byte, error) { - return json.Marshal(e.Code) -} - -func (e *ErrorCode) UnmarshalJSON(bs []byte) error { - return json.Unmarshal(bs, &(e.Code)) + return fmt.Sprintf("Error %v: %s", e.Code, e.Exception) } diff --git a/execution/errors/errors.pb.go b/execution/errors/errors.pb.go index 14d297a6c..859a4c204 100644 --- a/execution/errors/errors.pb.go +++ b/execution/errors/errors.pb.go @@ -1,14 +1,28 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: github.com/hyperledger/burrow/execution/errors/errors.proto +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: errors.proto +/* + Package errors is a generated protocol buffer package. + + It is generated from these files: + errors.proto + + It has these top-level messages: + Exception +*/ package errors -import proto "github.com/golang/protobuf/proto" +import proto "github.com/gogo/protobuf/proto" +import golang_proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" +import _ "github.com/gogo/protobuf/gogoproto" + +import io "io" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal +var _ = golang_proto.Marshal var _ = fmt.Errorf var _ = math.Inf @@ -16,46 +30,22 @@ var _ = math.Inf // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package +const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package type Exception struct { - Code *ErrorCode `protobuf:"bytes,1,opt,name=Code,proto3" json:"Code,omitempty"` - Exception string `protobuf:"bytes,2,opt,name=Exception,proto3" json:"Exception,omitempty"` - BS []byte `protobuf:"bytes,3,opt,name=BS,proto3" json:"BS,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Exception) Reset() { *m = Exception{} } -func (m *Exception) String() string { return proto.CompactTextString(m) } -func (*Exception) ProtoMessage() {} -func (*Exception) Descriptor() ([]byte, []int) { - return fileDescriptor_errors_e7e9443965b28d5d, []int{0} -} -func (m *Exception) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Exception.Unmarshal(m, b) -} -func (m *Exception) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Exception.Marshal(b, m, deterministic) -} -func (dst *Exception) XXX_Merge(src proto.Message) { - xxx_messageInfo_Exception.Merge(dst, src) -} -func (m *Exception) XXX_Size() int { - return xxx_messageInfo_Exception.Size(m) -} -func (m *Exception) XXX_DiscardUnknown() { - xxx_messageInfo_Exception.DiscardUnknown(m) + Code Code `protobuf:"varint,1,opt,name=Code,proto3,casttype=Code" json:"Code,omitempty"` + Exception string `protobuf:"bytes,2,opt,name=Exception,proto3" json:"Exception,omitempty"` } -var xxx_messageInfo_Exception proto.InternalMessageInfo +func (m *Exception) Reset() { *m = Exception{} } +func (*Exception) ProtoMessage() {} +func (*Exception) Descriptor() ([]byte, []int) { return fileDescriptorErrors, []int{0} } -func (m *Exception) GetCode() *ErrorCode { +func (m *Exception) GetCode() Code { if m != nil { return m.Code } - return nil + return 0 } func (m *Exception) GetException() string { @@ -65,71 +55,295 @@ func (m *Exception) GetException() string { return "" } -func (m *Exception) GetBS() []byte { - if m != nil { - return m.BS +func (*Exception) XXX_MessageName() string { + return "errors.Exception" +} +func init() { + proto.RegisterType((*Exception)(nil), "errors.Exception") + golang_proto.RegisterType((*Exception)(nil), "errors.Exception") +} +func (m *Exception) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err } - return nil + return dAtA[:n], nil } -type ErrorCode struct { - Code uint32 `protobuf:"varint,1,opt,name=Code,proto3" json:"Code,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` +func (m *Exception) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.Code != 0 { + dAtA[i] = 0x8 + i++ + i = encodeVarintErrors(dAtA, i, uint64(m.Code)) + } + if len(m.Exception) > 0 { + dAtA[i] = 0x12 + i++ + i = encodeVarintErrors(dAtA, i, uint64(len(m.Exception))) + i += copy(dAtA[i:], m.Exception) + } + return i, nil } -func (m *ErrorCode) Reset() { *m = ErrorCode{} } -func (m *ErrorCode) String() string { return proto.CompactTextString(m) } -func (*ErrorCode) ProtoMessage() {} -func (*ErrorCode) Descriptor() ([]byte, []int) { - return fileDescriptor_errors_e7e9443965b28d5d, []int{1} -} -func (m *ErrorCode) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ErrorCode.Unmarshal(m, b) -} -func (m *ErrorCode) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ErrorCode.Marshal(b, m, deterministic) +func encodeVarintErrors(dAtA []byte, offset int, v uint64) int { + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return offset + 1 } -func (dst *ErrorCode) XXX_Merge(src proto.Message) { - xxx_messageInfo_ErrorCode.Merge(dst, src) +func (m *Exception) Size() (n int) { + var l int + _ = l + if m.Code != 0 { + n += 1 + sovErrors(uint64(m.Code)) + } + l = len(m.Exception) + if l > 0 { + n += 1 + l + sovErrors(uint64(l)) + } + return n } -func (m *ErrorCode) XXX_Size() int { - return xxx_messageInfo_ErrorCode.Size(m) + +func sovErrors(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n } -func (m *ErrorCode) XXX_DiscardUnknown() { - xxx_messageInfo_ErrorCode.DiscardUnknown(m) +func sozErrors(x uint64) (n int) { + return sovErrors(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } +func (m *Exception) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowErrors + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Exception: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Exception: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Code", wireType) + } + m.Code = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowErrors + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Code |= (Code(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Exception", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowErrors + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthErrors + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Exception = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipErrors(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthErrors + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } -var xxx_messageInfo_ErrorCode proto.InternalMessageInfo - -func (m *ErrorCode) GetCode() uint32 { - if m != nil { - return m.Code + if iNdEx > l { + return io.ErrUnexpectedEOF } - return 0 + return nil } - -func init() { - proto.RegisterType((*Exception)(nil), "errors.Exception") - proto.RegisterType((*ErrorCode)(nil), "errors.ErrorCode") +func skipErrors(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowErrors + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowErrors + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowErrors + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + iNdEx += length + if length < 0 { + return 0, ErrInvalidLengthErrors + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowErrors + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipErrors(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") } -func init() { - proto.RegisterFile("github.com/hyperledger/burrow/execution/errors/errors.proto", fileDescriptor_errors_e7e9443965b28d5d) -} +var ( + ErrInvalidLengthErrors = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowErrors = fmt.Errorf("proto: integer overflow") +) + +func init() { proto.RegisterFile("errors.proto", fileDescriptorErrors) } +func init() { golang_proto.RegisterFile("errors.proto", fileDescriptorErrors) } -var fileDescriptor_errors_e7e9443965b28d5d = []byte{ - // 168 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xb2, 0x4e, 0xcf, 0x2c, 0xc9, - 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0xcf, 0xa8, 0x2c, 0x48, 0x2d, 0xca, 0x49, 0x4d, 0x49, - 0x4f, 0x2d, 0xd2, 0x4f, 0x2a, 0x2d, 0x2a, 0xca, 0x2f, 0xd7, 0x4f, 0xad, 0x48, 0x4d, 0x2e, 0x2d, - 0xc9, 0xcc, 0xcf, 0xd3, 0x4f, 0x2d, 0x2a, 0xca, 0x2f, 0x2a, 0x86, 0x52, 0x7a, 0x05, 0x45, 0xf9, - 0x25, 0xf9, 0x42, 0x6c, 0x10, 0x9e, 0x52, 0x02, 0x17, 0xa7, 0x6b, 0x45, 0x72, 0x6a, 0x01, 0x48, - 0xa1, 0x90, 0x2a, 0x17, 0x8b, 0x73, 0x7e, 0x4a, 0xaa, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0xb7, 0x91, - 0xa0, 0x1e, 0x54, 0x87, 0x2b, 0x88, 0x02, 0x49, 0x04, 0x81, 0xa5, 0x85, 0x64, 0x90, 0xf4, 0x48, - 0x30, 0x29, 0x30, 0x6a, 0x70, 0x06, 0x21, 0x19, 0xc2, 0xc7, 0xc5, 0xe4, 0x14, 0x2c, 0xc1, 0xac, - 0xc0, 0xa8, 0xc1, 0x13, 0xc4, 0xe4, 0x14, 0xac, 0x24, 0xcf, 0xc5, 0x09, 0x37, 0x40, 0x48, 0x08, - 0xc9, 0x06, 0x5e, 0x88, 0x71, 0x49, 0x6c, 0x60, 0x17, 0x19, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, - 0x20, 0x37, 0xb1, 0xd9, 0xd0, 0x00, 0x00, 0x00, +var fileDescriptorErrors = []byte{ + // 190 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x49, 0x2d, 0x2a, 0xca, + 0x2f, 0x2a, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x83, 0xf0, 0xa4, 0x74, 0xd3, 0x33, + 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, 0xd3, 0xf3, 0xd3, 0xf3, 0xf5, 0xc1, 0xd2, + 0x49, 0xa5, 0x69, 0x60, 0x1e, 0x98, 0x03, 0x66, 0x41, 0xb4, 0x29, 0xf9, 0x72, 0x71, 0xba, 0x56, + 0x24, 0xa7, 0x16, 0x94, 0x64, 0xe6, 0xe7, 0x09, 0xc9, 0x70, 0xb1, 0x38, 0xe7, 0xa7, 0xa4, 0x4a, + 0x30, 0x2a, 0x30, 0x6a, 0xf0, 0x3a, 0x71, 0xfc, 0xba, 0x27, 0x0f, 0xe6, 0x07, 0x81, 0x49, 0x21, + 0x19, 0x24, 0xa5, 0x12, 0x4c, 0x0a, 0x8c, 0x1a, 0x9c, 0x41, 0x08, 0x01, 0x2b, 0x96, 0x19, 0x0b, + 0xe4, 0x19, 0x9c, 0x5c, 0x4e, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, + 0xc6, 0x03, 0x8f, 0xe5, 0x18, 0x4f, 0x3c, 0x96, 0x63, 0x8c, 0xd2, 0x43, 0x72, 0x53, 0x46, 0x65, + 0x41, 0x6a, 0x51, 0x4e, 0x6a, 0x4a, 0x7a, 0x6a, 0x91, 0x7e, 0x52, 0x69, 0x51, 0x51, 0x7e, 0xb9, + 0x7e, 0x6a, 0x45, 0x6a, 0x72, 0x29, 0xc8, 0x10, 0x7d, 0x88, 0x1f, 0x92, 0xd8, 0xc0, 0x6e, 0x33, + 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x33, 0x9a, 0x19, 0x05, 0xe2, 0x00, 0x00, 0x00, } diff --git a/execution/errors/errors.proto b/execution/errors/errors.proto deleted file mode 100644 index 2620fdd40..000000000 --- a/execution/errors/errors.proto +++ /dev/null @@ -1,13 +0,0 @@ -syntax = "proto3"; - -package errors; - -message Exception { - ErrorCode Code = 1; - string Exception = 2; - bytes BS = 3; -} - -message ErrorCode { - uint32 Code = 1; -} diff --git a/execution/errors/errors_test.go b/execution/errors/errors_test.go index 3b85c4adb..2a4a0a37b 100644 --- a/execution/errors/errors_test.go +++ b/execution/errors/errors_test.go @@ -4,39 +4,18 @@ import ( "encoding/json" "testing" - "fmt" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tendermint/abci/types" ) func TestErrorCode_MarshalJSON(t *testing.T) { - ec := NewErrorCode(ErrorCodeDataStackOverflow) + ec := NewCodedError(ErrorCodeDataStackOverflow, "arrg") bs, err := json.Marshal(ec) require.NoError(t, err) - ecOut := new(ErrorCode) + ecOut := new(Exception) err = json.Unmarshal(bs, ecOut) require.NoError(t, err) assert.Equal(t, ec, ecOut) } - -func TestException_MarshalJSON(t *testing.T) { - ex := NewCodedError(ErrorCodeExecutionReverted, "Oh noes we reverted") - ex.BS = []byte{2, 3, 4, 5} - bs, err := json.Marshal(ex) - require.NoError(t, err) - fmt.Println(string(bs)) - exOut := new(Exception) - err = json.Unmarshal(bs, exOut) - require.NoError(t, err) - - bb := types.RequestBeginBlock{ - Hash: []byte{2, 3, 4}, - } - bs, err = json.Marshal(bb) - require.NoError(t, err) - fmt.Println(string(bs)) -} diff --git a/execution/errors/vm.go b/execution/errors/vm.go index f2d40983f..7e97d3750 100644 --- a/execution/errors/vm.go +++ b/execution/errors/vm.go @@ -5,11 +5,11 @@ import ( "fmt" "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/permission/types" + "github.com/hyperledger/burrow/permission" ) type PermissionDenied struct { - Perm types.PermFlag + Perm permission.PermFlag } func (err PermissionDenied) ErrorCode() Code { diff --git a/execution/events/call.go b/execution/events/call.go deleted file mode 100644 index 23e047248..000000000 --- a/execution/events/call.go +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package events - -import ( - "context" - "fmt" - - "github.com/hyperledger/burrow/binary" - "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/event" - "github.com/hyperledger/burrow/event/query" - "github.com/hyperledger/burrow/execution/errors" - "github.com/hyperledger/burrow/txs" - hex "github.com/tmthrgd/go-hex" -) - -// Functions to generate eventId strings - -func EventStringAccountCall(addr crypto.Address) string { return fmt.Sprintf("Acc/%s/Call", addr) } - -//---------------------------------------- - -// EventDataCall fires when we call a contract, and when a contract calls another contract -type EventDataCall struct { - CallData *CallData - Origin crypto.Address - StackDepth uint64 - Return binary.HexBytes - Exception *errors.Exception -} - -type CallData struct { - Caller crypto.Address - Callee crypto.Address - Data binary.HexBytes - Value uint64 - Gas uint64 -} - -// Publish/Subscribe -func PublishAccountCall(publisher event.Publisher, tx *txs.Tx, height uint64, call *EventDataCall) error { - eventID := EventStringAccountCall(call.CallData.Callee) - ev := &Event{ - Header: &Header{ - TxType: tx.Type(), - TxHash: tx.Hash(), - EventType: TypeCall, - EventID: eventID, - Height: height, - }, - Call: call, - } - return publisher.Publish(context.Background(), ev, ev.Tags()) -} - -// Subscribe to account call event - if TxHash is provided listens for a specifc Tx otherwise captures all, if -// stackDepth is greater than or equal to 0 captures calls at a specific stack depth (useful for capturing the return -// of the root call over recursive calls -func SubscribeAccountCall(ctx context.Context, subscribable event.Subscribable, subscriber string, address crypto.Address, - txHash []byte, stackDepth int, ch chan<- *EventDataCall) error { - - query := event.QueryForEventID(EventStringAccountCall(address)) - - if len(txHash) > 0 { - query = query.AndEquals(event.TxHashKey, hex.EncodeUpperToString(txHash)) - } - - if stackDepth >= 0 { - query = query.AndEquals(event.StackDepthKey, stackDepth) - } - - return event.SubscribeCallback(ctx, subscribable, subscriber, query, func(message interface{}) (stop bool) { - ev, ok := message.(*Event) - if ok && ev.Call != nil { - ch <- ev.Call - } - return - }) -} - -// Tags - -var callTagKeys = []string{ - event.CalleeKey, - event.CallerKey, - event.ValueKey, - event.GasKey, - event.StackDepthKey, - event.OriginKey, - event.ExceptionKey, -} - -// Implements Tags for events -func (call *EventDataCall) Get(key string) (string, bool) { - var value interface{} - switch key { - case event.CalleeKey: - value = call.CallData.Callee - case event.CallerKey: - value = call.CallData.Caller - case event.ValueKey: - value = call.CallData.Value - case event.GasKey: - value = call.CallData.Gas - case event.StackDepthKey: - value = call.StackDepth - case event.OriginKey: - value = call.Origin - case event.ExceptionKey: - value = call.Exception - default: - return "", false - } - return query.StringFromValue(value), true -} - -func (call *EventDataCall) Len() int { - return len(callTagKeys) -} - -func (call *EventDataCall) Keys() []string { - return callTagKeys -} - -func (call *EventDataCall) Tags(tags map[string]interface{}) map[string]interface{} { - tags[event.CalleeKey] = call.CallData.Callee - tags[event.CallerKey] = call.CallData.Caller - tags[event.ValueKey] = call.CallData.Value - tags[event.GasKey] = call.CallData.Gas - tags[event.StackDepthKey] = call.StackDepth - tags[event.OriginKey] = call.Origin - if call.Exception != nil { - tags[event.ExceptionKey] = call.Exception - } - return tags -} diff --git a/execution/events/event.go b/execution/events/event.go deleted file mode 100644 index 508c96776..000000000 --- a/execution/events/event.go +++ /dev/null @@ -1,121 +0,0 @@ -package events - -import ( - "fmt" - - "reflect" - - "github.com/hyperledger/burrow/event" - "github.com/hyperledger/burrow/txs" -) - -var cdc = txs.NewAminoCodec() - -var eventMessageTag = event.TagMap{event.MessageTypeKey: reflect.TypeOf(&Event{}).String()} - -type Provider interface { - // Get events between startKey (inclusive) and endKey (exclusive) - i.e. the half open interval [start, end) - GetEvents(startKey, endKey Key, consumer func(*Event) (stop bool)) (stopped bool, err error) - LatestEventKey() Key -} - -type Event struct { - Header *Header - Call *EventDataCall `json:",omitempty"` - Log *EventDataLog `json:",omitempty"` - Tx *EventDataTx `json:",omitempty"` - tags event.Tags -} - -func DecodeEvent(bs []byte) (*Event, error) { - ev := new(Event) - err := cdc.UnmarshalBinary(bs, ev) - if err != nil { - return nil, err - } - return ev, nil -} - -func (ev *Event) Key() Key { - return ev.Header.Key() -} - -// Performs a shallow copy of Event -func (ev *Event) Copy() *Event { - h := *ev.Header - evCopy := Event{ - Header: &h, - } - if ev.Tx != nil { - tx := *ev.Tx - evCopy.Tx = &tx - } - if ev.Call != nil { - call := *ev.Call - evCopy.Call = &call - } - if ev.Log != nil { - log := *ev.Log - evCopy.Log = &log - } - return &evCopy -} - -func (ev *Event) Encode() ([]byte, error) { - return cdc.MarshalBinary(ev) -} - -func (ev *Event) Tags() event.Tags { - if ev.tags == nil { - ev.tags = event.CombinedTags{ - ev.Header, - eventMessageTag, - ev.Tx, - ev.Call, - ev.Log, - } - } - return ev.tags -} - -func (ev *Event) Get(key string) (value string, ok bool) { - return ev.Tags().Get(key) -} - -func (ev *Event) Keys() []string { - return ev.Tags().Keys() -} - -func (ev *Event) Len() int { - return ev.Tags().Len() -} - -// event.Cache will provide an index through this methods of Indexable -func (ev *Event) ProvideIndex(index uint64) { - ev.Header.Index = index -} - -func (ev *Event) String() string { - return fmt.Sprintf("%v", ev.Header) -} - -func (ev *Event) GetTx() *EventDataTx { - if ev == nil { - return nil - } - return ev.Tx -} - -func (ev *Event) GetCall() *EventDataCall { - if ev == nil { - return nil - } - return ev.Call -} - -func (ev *Event) GetLog() *EventDataLog { - if ev == nil { - return nil - } - return ev.Log -} diff --git a/execution/events/event_test.go b/execution/events/event_test.go deleted file mode 100644 index 4831edfe2..000000000 --- a/execution/events/event_test.go +++ /dev/null @@ -1,92 +0,0 @@ -package events - -import ( - "testing" - - "github.com/hyperledger/burrow/binary" - "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/event" - "github.com/hyperledger/burrow/event/query" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/tmthrgd/go-hex" -) - -func TestHeader_Key(t *testing.T) { - h := &Header{ - EventID: "Foos", - Height: 2345345232, - Index: 34, - } - key := h.Key() - keyString := hex.EncodeUpperToString(key) - assert.Equal(t, "000000008BCB20D00000000000000022", keyString) - assert.Len(t, keyString, 32, "should be 16 bytes") - assert.Equal(t, h.Height, key.Height()) - assert.Equal(t, h.Index, key.Index()) -} - -func TestKey_IsSuccessorOf(t *testing.T) { - assert.True(t, NewKey(1, 0).IsSuccessorOf(NewKey(0, 1))) - assert.True(t, NewKey(100, 24).IsSuccessorOf(NewKey(100, 23))) - assert.False(t, NewKey(100, 23).IsSuccessorOf(NewKey(100, 25))) - assert.False(t, NewKey(1, 1).IsSuccessorOf(NewKey(0, 25))) - assert.True(t, NewKey(3, 0).IsSuccessorOf(NewKey(2, 0))) -} - -func TestEventTagQueries(t *testing.T) { - addressHex := "DEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF" - address, err := crypto.AddressFromHexString(addressHex) - require.NoError(t, err) - ev := &Event{ - Header: &Header{ - EventType: TypeLog, - EventID: "foo/bar", - TxHash: []byte{2, 3, 4}, - Height: 34, - Index: 2, - }, - Log: &EventDataLog{ - Address: address, - Topics: []binary.Word256{binary.RightPadWord256([]byte("marmot"))}, - }, - } - - qb := query.NewBuilder().AndEquals(event.EventTypeKey, TypeLog.String()) - qry, err := qb.Query() - require.NoError(t, err) - assert.True(t, qry.Matches(ev)) - - qb = qb.AndContains(event.EventIDKey, "bar") - qry, err = qb.Query() - require.NoError(t, err) - assert.True(t, qry.Matches(ev)) - - qb = qb.AndEquals(event.TxHashKey, hex.EncodeUpperToString(ev.Header.TxHash)) - qry, err = qb.Query() - require.NoError(t, err) - assert.True(t, qry.Matches(ev)) - - qb = qb.AndGreaterThanOrEqual(event.HeightKey, ev.Header.Height) - qry, err = qb.Query() - require.NoError(t, err) - assert.True(t, qry.Matches(ev)) - - qb = qb.AndStrictlyLessThan(event.IndexKey, ev.Header.Index+1) - qry, err = qb.Query() - require.NoError(t, err) - assert.True(t, qry.Matches(ev)) - - qb = qb.AndEquals(event.AddressKey, addressHex) - qry, err = qb.Query() - require.NoError(t, err) - assert.True(t, qry.Matches(ev)) - - qb = qb.AndEquals(event.LogNTextKey(0), "marmot") - qry, err = qb.Query() - require.NoError(t, err) - assert.True(t, qry.Matches(ev)) - - t.Logf("Query: %v", qry) - t.Logf("Keys: %v", ev.Keys()) -} diff --git a/execution/events/header.go b/execution/events/header.go deleted file mode 100644 index d5b09749b..000000000 --- a/execution/events/header.go +++ /dev/null @@ -1,76 +0,0 @@ -package events - -import ( - "fmt" - - "github.com/hyperledger/burrow/binary" - "github.com/hyperledger/burrow/event" - "github.com/hyperledger/burrow/event/query" - "github.com/hyperledger/burrow/txs/payload" -) - -type Header struct { - TxType payload.Type - TxHash binary.HexBytes - EventType Type - EventID string - Height uint64 - Index uint64 -} - -var headerTagKeys = []string{ - event.TxTypeKey, - event.TxHashKey, - event.EventTypeKey, - event.EventIDKey, - event.HeightKey, - event.IndexKey, -} - -// Implements Tags for events -func (h *Header) Get(key string) (value string, ok bool) { - var v interface{} - switch key { - case event.TxTypeKey: - v = h.TxType - case event.TxHashKey: - v = h.TxHash - case event.EventTypeKey: - v = h.EventType - case event.EventIDKey: - v = h.EventID - case event.HeightKey: - v = h.Height - case event.IndexKey: - v = h.Index - default: - return "", false - } - return query.StringFromValue(v), true -} - -func (h *Header) Len() int { - return len(headerTagKeys) -} - -func (h *Header) Map() map[string]interface{} { - tags := make(map[string]interface{}) - for _, key := range headerTagKeys { - tags[key], _ = h.Get(key) - } - return tags -} - -func (h *Header) Keys() []string { - return headerTagKeys -} - -// Returns a lexicographically sortable key encoding the height and index of this event -func (h *Header) Key() Key { - return NewKey(h.Height, h.Index) -} - -func (h *Header) String() string { - return fmt.Sprintf("Header{Tx{%v}: %v; Event{%v}: %v; Height: %v; Index: %v}", - h.TxType, h.TxHash, h.EventType, h.EventID, h.Height, h.Index) -} diff --git a/execution/events/key.go b/execution/events/key.go deleted file mode 100644 index 52371518f..000000000 --- a/execution/events/key.go +++ /dev/null @@ -1,57 +0,0 @@ -package events - -import ( - "bytes" - "fmt" - - "github.com/hyperledger/burrow/binary" -) - -type Key []byte - -func NewKey(height, index uint64) Key { - k := make(Key, 16) - // Will order first by height then by index so events from the same block will be consecutive - binary.PutUint64BE(k[:8], height) - binary.PutUint64BE(k[8:], index) - return k -} - -// -1 if k < k2 -// 0 if k == k2 -// 1 if k > k2 -func (k Key) Compare(k2 Key) int { - return bytes.Compare(k, k2) -} - -// Returns true iff k is a valid successor key to p; -// iff (the height is the same and the index is one greater) or (the height is greater and the index is zero) or (p -// is uninitialised) -func (k Key) IsSuccessorOf(p Key) bool { - if len(p) == 0 { - return true - } - ph, kh := p.Height(), k.Height() - pi, ki := p.Index(), k.Index() - return ph == kh && pi+1 == ki || ph < kh && ki == 0 -} - -func (k Key) IncHeight() Key { - return NewKey(k.Height()+1, k.Index()) -} - -func (k Key) Bytes() []byte { - return k -} - -func (k Key) Height() uint64 { - return binary.GetUint64BE(k[:8]) -} - -func (k Key) Index() uint64 { - return binary.GetUint64BE(k[8:]) -} - -func (k Key) String() string { - return fmt.Sprintf("Key{Height: %v; Index: %v}", k.Height(), k.Index()) -} diff --git a/execution/events/pbevents/events.go b/execution/events/pbevents/events.go deleted file mode 100644 index 99bc841b7..000000000 --- a/execution/events/pbevents/events.go +++ /dev/null @@ -1,168 +0,0 @@ -package pbevents - -import ( - "github.com/hyperledger/burrow/binary" - "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/execution/events" - "github.com/hyperledger/burrow/txs/payload" -) - -// this mostly contains tedious mapping between protobuf and our domain objects, but it may be worth -// the pain to avoid complexity and edge cases using gogoproto or other techniques. - -func GetEventDataCall(edt *events.EventDataCall) *EventDataCall { - return &EventDataCall{ - Origin: edt.Origin.Bytes(), - CallData: GetCallData(edt.CallData), - StackDepth: edt.StackDepth, - Return: edt.Return, - Exception: edt.Exception, - } -} - -func GetCallData(cd *events.CallData) *CallData { - return &CallData{ - Caller: cd.Caller.Bytes(), - Callee: cd.Callee.Bytes(), - Data: cd.Data, - Gas: cd.Gas, - } -} - -func GetExecutionEvent(event *events.Event) *ExecutionEvent { - return &ExecutionEvent{ - Header: GetEventHeader(event.Header), - EventData: GetEventData(event), - } -} - -func GetEventHeader(header *events.Header) *EventHeader { - return &EventHeader{ - TxType: header.TxType.String(), - TxHash: header.TxHash, - EventType: header.EventType.String(), - EventID: header.EventID, - Height: header.Height, - Index: header.Index, - } -} - -func GetEventData(ev *events.Event) isExecutionEvent_EventData { - if ev.Call != nil { - return &ExecutionEvent_EventDataCall{ - EventDataCall: &EventDataCall{ - CallData: GetCallData(ev.Call.CallData), - Origin: ev.Call.Origin.Bytes(), - StackDepth: ev.Call.StackDepth, - Return: ev.Call.Return, - Exception: ev.Call.Exception, - }, - } - } - - if ev.Log != nil { - return &ExecutionEvent_EventDataLog{ - EventDataLog: &EventDataLog{ - Address: ev.Log.Address.Bytes(), - Data: ev.Log.Data, - Topics: GetTopic(ev.Log.Topics), - }, - } - } - - if ev.Tx != nil { - return &ExecutionEvent_EventDataTx{ - EventDataTx: &EventDataTx{ - Return: ev.Tx.Return, - Exception: ev.Tx.Exception, - }, - } - } - - return nil -} - -func GetTopic(topics []binary.Word256) [][]byte { - topicBytes := make([][]byte, len(topics)) - for i, t := range topics { - topicBytes[i] = t.Bytes() - } - return topicBytes -} - -func (ee *ExecutionEvent) Event() *events.Event { - return &events.Event{ - Header: ee.GetHeader().Header(), - Tx: ee.GetEventDataTx().Tx(), - Log: ee.GetEventDataLog().Log(ee.Header.Height), - Call: ee.GetEventDataCall().Call(ee.Header.TxHash), - } -} - -func (ee *ExecutionEvent) Key() events.Key { - return ee.Header.Key() -} - -func (h *EventHeader) Key() events.Key { - return events.NewKey(h.Height, h.Index) -} - -func (h *EventHeader) Header() *events.Header { - return &events.Header{ - TxType: payload.TxTypeFromString(h.TxType), - TxHash: h.TxHash, - EventType: events.EventTypeFromString(h.EventType), - EventID: h.EventID, - Height: h.Height, - Index: h.Index, - } -} - -func (tx *EventDataTx) Tx() *events.EventDataTx { - if tx == nil { - return nil - } - return &events.EventDataTx{ - Return: tx.Return, - Exception: tx.Exception, - } -} - -func (log *EventDataLog) Log(height uint64) *events.EventDataLog { - if log == nil { - return nil - } - topicWords := make([]binary.Word256, len(log.Topics)) - for i, bs := range log.Topics { - topicWords[i] = binary.LeftPadWord256(bs) - } - return &events.EventDataLog{ - Height: height, - Topics: topicWords, - Address: crypto.MustAddressFromBytes(log.Address), - Data: log.Data, - } -} - -func (call *EventDataCall) Call(txHash []byte) *events.EventDataCall { - if call == nil { - return nil - } - return &events.EventDataCall{ - Return: call.Return, - CallData: call.CallData.CallData(), - Origin: crypto.MustAddressFromBytes(call.Origin), - StackDepth: call.StackDepth, - Exception: call.Exception, - } -} - -func (cd *CallData) CallData() *events.CallData { - return &events.CallData{ - Caller: crypto.MustAddressFromBytes(cd.Caller), - Callee: crypto.MustAddressFromBytes(cd.Callee), - Value: cd.Value, - Gas: cd.Gas, - Data: cd.Data, - } -} diff --git a/execution/events/pbevents/events.pb.go b/execution/events/pbevents/events.pb.go deleted file mode 100644 index 132817582..000000000 --- a/execution/events/pbevents/events.pb.go +++ /dev/null @@ -1,1403 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: github.com/hyperledger/burrow/execution/events/pbevents/events.proto - -package pbevents // import "github.com/hyperledger/burrow/execution/events/pbevents" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import errors "github.com/hyperledger/burrow/execution/errors" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Bound_BoundType int32 - -const ( - // Index is absolute index of object in collection - Bound_ABSOLUTE Bound_BoundType = 0 - // Index is an offset relative to another bound determined by context - Bound_RELATIVE Bound_BoundType = 1 - // The first block - Bound_FIRST Bound_BoundType = 2 - // Ignore provided index and evaluate to latest index - Bound_LATEST Bound_BoundType = 3 - // Ignore provided index and stream new objects as they are generated - Bound_STREAM Bound_BoundType = 4 -) - -var Bound_BoundType_name = map[int32]string{ - 0: "ABSOLUTE", - 1: "RELATIVE", - 2: "FIRST", - 3: "LATEST", - 4: "STREAM", -} -var Bound_BoundType_value = map[string]int32{ - "ABSOLUTE": 0, - "RELATIVE": 1, - "FIRST": 2, - "LATEST": 3, - "STREAM": 4, -} - -func (x Bound_BoundType) String() string { - return proto.EnumName(Bound_BoundType_name, int32(x)) -} -func (Bound_BoundType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_events_a0e2b84614955cff, []int{7, 0} -} - -// Params -type EventIdParam struct { - EventId string `protobuf:"bytes,1,opt,name=eventId,proto3" json:"eventId,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EventIdParam) Reset() { *m = EventIdParam{} } -func (m *EventIdParam) String() string { return proto.CompactTextString(m) } -func (*EventIdParam) ProtoMessage() {} -func (*EventIdParam) Descriptor() ([]byte, []int) { - return fileDescriptor_events_a0e2b84614955cff, []int{0} -} -func (m *EventIdParam) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EventIdParam.Unmarshal(m, b) -} -func (m *EventIdParam) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EventIdParam.Marshal(b, m, deterministic) -} -func (dst *EventIdParam) XXX_Merge(src proto.Message) { - xxx_messageInfo_EventIdParam.Merge(dst, src) -} -func (m *EventIdParam) XXX_Size() int { - return xxx_messageInfo_EventIdParam.Size(m) -} -func (m *EventIdParam) XXX_DiscardUnknown() { - xxx_messageInfo_EventIdParam.DiscardUnknown(m) -} - -var xxx_messageInfo_EventIdParam proto.InternalMessageInfo - -func (m *EventIdParam) GetEventId() string { - if m != nil { - return m.EventId - } - return "" -} - -type SubIdParam struct { - SubId string `protobuf:"bytes,1,opt,name=subId,proto3" json:"subId,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SubIdParam) Reset() { *m = SubIdParam{} } -func (m *SubIdParam) String() string { return proto.CompactTextString(m) } -func (*SubIdParam) ProtoMessage() {} -func (*SubIdParam) Descriptor() ([]byte, []int) { - return fileDescriptor_events_a0e2b84614955cff, []int{1} -} -func (m *SubIdParam) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SubIdParam.Unmarshal(m, b) -} -func (m *SubIdParam) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SubIdParam.Marshal(b, m, deterministic) -} -func (dst *SubIdParam) XXX_Merge(src proto.Message) { - xxx_messageInfo_SubIdParam.Merge(dst, src) -} -func (m *SubIdParam) XXX_Size() int { - return xxx_messageInfo_SubIdParam.Size(m) -} -func (m *SubIdParam) XXX_DiscardUnknown() { - xxx_messageInfo_SubIdParam.DiscardUnknown(m) -} - -var xxx_messageInfo_SubIdParam proto.InternalMessageInfo - -func (m *SubIdParam) GetSubId() string { - if m != nil { - return m.SubId - } - return "" -} - -// Results -type EventUnSub struct { - Result bool `protobuf:"varint,1,opt,name=result,proto3" json:"result,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EventUnSub) Reset() { *m = EventUnSub{} } -func (m *EventUnSub) String() string { return proto.CompactTextString(m) } -func (*EventUnSub) ProtoMessage() {} -func (*EventUnSub) Descriptor() ([]byte, []int) { - return fileDescriptor_events_a0e2b84614955cff, []int{2} -} -func (m *EventUnSub) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EventUnSub.Unmarshal(m, b) -} -func (m *EventUnSub) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EventUnSub.Marshal(b, m, deterministic) -} -func (dst *EventUnSub) XXX_Merge(src proto.Message) { - xxx_messageInfo_EventUnSub.Merge(dst, src) -} -func (m *EventUnSub) XXX_Size() int { - return xxx_messageInfo_EventUnSub.Size(m) -} -func (m *EventUnSub) XXX_DiscardUnknown() { - xxx_messageInfo_EventUnSub.DiscardUnknown(m) -} - -var xxx_messageInfo_EventUnSub proto.InternalMessageInfo - -func (m *EventUnSub) GetResult() bool { - if m != nil { - return m.Result - } - return false -} - -type PollResponse struct { - Events []*Event `protobuf:"bytes,1,rep,name=events,proto3" json:"events,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PollResponse) Reset() { *m = PollResponse{} } -func (m *PollResponse) String() string { return proto.CompactTextString(m) } -func (*PollResponse) ProtoMessage() {} -func (*PollResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_events_a0e2b84614955cff, []int{3} -} -func (m *PollResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PollResponse.Unmarshal(m, b) -} -func (m *PollResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PollResponse.Marshal(b, m, deterministic) -} -func (dst *PollResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_PollResponse.Merge(dst, src) -} -func (m *PollResponse) XXX_Size() int { - return xxx_messageInfo_PollResponse.Size(m) -} -func (m *PollResponse) XXX_DiscardUnknown() { - xxx_messageInfo_PollResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_PollResponse proto.InternalMessageInfo - -func (m *PollResponse) GetEvents() []*Event { - if m != nil { - return m.Events - } - return nil -} - -type Event struct { - Name string `protobuf:"bytes,1,opt,name=Name,proto3" json:"Name,omitempty"` - // Types that are valid to be assigned to Event: - // *Event_ExecutionEvent - // *Event_TendermintEventJSON - Event isEvent_Event `protobuf_oneof:"Event"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Event) Reset() { *m = Event{} } -func (m *Event) String() string { return proto.CompactTextString(m) } -func (*Event) ProtoMessage() {} -func (*Event) Descriptor() ([]byte, []int) { - return fileDescriptor_events_a0e2b84614955cff, []int{4} -} -func (m *Event) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Event.Unmarshal(m, b) -} -func (m *Event) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Event.Marshal(b, m, deterministic) -} -func (dst *Event) XXX_Merge(src proto.Message) { - xxx_messageInfo_Event.Merge(dst, src) -} -func (m *Event) XXX_Size() int { - return xxx_messageInfo_Event.Size(m) -} -func (m *Event) XXX_DiscardUnknown() { - xxx_messageInfo_Event.DiscardUnknown(m) -} - -var xxx_messageInfo_Event proto.InternalMessageInfo - -type isEvent_Event interface { - isEvent_Event() -} - -type Event_ExecutionEvent struct { - ExecutionEvent *ExecutionEvent `protobuf:"bytes,2,opt,name=ExecutionEvent,proto3,oneof"` -} -type Event_TendermintEventJSON struct { - TendermintEventJSON string `protobuf:"bytes,3,opt,name=TendermintEventJSON,proto3,oneof"` -} - -func (*Event_ExecutionEvent) isEvent_Event() {} -func (*Event_TendermintEventJSON) isEvent_Event() {} - -func (m *Event) GetEvent() isEvent_Event { - if m != nil { - return m.Event - } - return nil -} - -func (m *Event) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Event) GetExecutionEvent() *ExecutionEvent { - if x, ok := m.GetEvent().(*Event_ExecutionEvent); ok { - return x.ExecutionEvent - } - return nil -} - -func (m *Event) GetTendermintEventJSON() string { - if x, ok := m.GetEvent().(*Event_TendermintEventJSON); ok { - return x.TendermintEventJSON - } - return "" -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*Event) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _Event_OneofMarshaler, _Event_OneofUnmarshaler, _Event_OneofSizer, []interface{}{ - (*Event_ExecutionEvent)(nil), - (*Event_TendermintEventJSON)(nil), - } -} - -func _Event_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*Event) - // Event - switch x := m.Event.(type) { - case *Event_ExecutionEvent: - b.EncodeVarint(2<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ExecutionEvent); err != nil { - return err - } - case *Event_TendermintEventJSON: - b.EncodeVarint(3<<3 | proto.WireBytes) - b.EncodeStringBytes(x.TendermintEventJSON) - case nil: - default: - return fmt.Errorf("Event.Event has unexpected type %T", x) - } - return nil -} - -func _Event_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*Event) - switch tag { - case 2: // Event.ExecutionEvent - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ExecutionEvent) - err := b.DecodeMessage(msg) - m.Event = &Event_ExecutionEvent{msg} - return true, err - case 3: // Event.TendermintEventJSON - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Event = &Event_TendermintEventJSON{x} - return true, err - default: - return false, nil - } -} - -func _Event_OneofSizer(msg proto.Message) (n int) { - m := msg.(*Event) - // Event - switch x := m.Event.(type) { - case *Event_ExecutionEvent: - s := proto.Size(x.ExecutionEvent) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *Event_TendermintEventJSON: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.TendermintEventJSON))) - n += len(x.TendermintEventJSON) - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type GetEventsRequest struct { - BlockRange *BlockRange `protobuf:"bytes,1,opt,name=BlockRange,proto3" json:"BlockRange,omitempty"` - // Specify a query on which to match the tags of events. - // Tag | Match type | Values - // ----------------------------------------- - // All events - // ----------------------------------------- - // TxType | String | "UnknownTx", "SendTx", "CallTx", "NameTx", "BondTx", "UnbondTx", "PermissionsTx", "GovernanceTx" - // TxHash | String | bytes - // EventType | String | "CallEvent", "LogEvent", "AccountInputEvent", "AccountOutputEvent" - // EventID | String | string - // Height | Integer | uint64 - // Index | Integer | uint64 - // MessageType | String | Go type name - // ----------------------------------------- - // Log event - // ----------------------------------------- - // Address | String | Address (hex) - // Log<0-4> | String | Word256 (hex) - // Log<0-4>Text | String | string (trimmed) - // ----------------------------------------- - // Call event - // ----------------------------------------- - // Origin | String | Address (hex) - // Callee | String | Address (hex) - // Caller | String | Address (hex) - // Value | Integer | uint64 - // Gas | Integer | uint64 - // StackDepth | Integer | uint64 - // Exception | String | string - // ----------------------------------------- - // Tx event (input/output) - // ----------------------------------------- - // Exception | String | string - // - // For example: - // EventType = 'LogEvent' AND EventID CONTAINS 'bar' AND TxHash = '020304' AND Height >= 34 AND Index < 3 AND Address = 'DEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF' - Query string `protobuf:"bytes,2,opt,name=Query,proto3" json:"Query,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetEventsRequest) Reset() { *m = GetEventsRequest{} } -func (m *GetEventsRequest) String() string { return proto.CompactTextString(m) } -func (*GetEventsRequest) ProtoMessage() {} -func (*GetEventsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_events_a0e2b84614955cff, []int{5} -} -func (m *GetEventsRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetEventsRequest.Unmarshal(m, b) -} -func (m *GetEventsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetEventsRequest.Marshal(b, m, deterministic) -} -func (dst *GetEventsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetEventsRequest.Merge(dst, src) -} -func (m *GetEventsRequest) XXX_Size() int { - return xxx_messageInfo_GetEventsRequest.Size(m) -} -func (m *GetEventsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_GetEventsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_GetEventsRequest proto.InternalMessageInfo - -func (m *GetEventsRequest) GetBlockRange() *BlockRange { - if m != nil { - return m.BlockRange - } - return nil -} - -func (m *GetEventsRequest) GetQuery() string { - if m != nil { - return m.Query - } - return "" -} - -type GetEventsResponse struct { - Events []*ExecutionEvent `protobuf:"bytes,1,rep,name=events,proto3" json:"events,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetEventsResponse) Reset() { *m = GetEventsResponse{} } -func (m *GetEventsResponse) String() string { return proto.CompactTextString(m) } -func (*GetEventsResponse) ProtoMessage() {} -func (*GetEventsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_events_a0e2b84614955cff, []int{6} -} -func (m *GetEventsResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetEventsResponse.Unmarshal(m, b) -} -func (m *GetEventsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetEventsResponse.Marshal(b, m, deterministic) -} -func (dst *GetEventsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetEventsResponse.Merge(dst, src) -} -func (m *GetEventsResponse) XXX_Size() int { - return xxx_messageInfo_GetEventsResponse.Size(m) -} -func (m *GetEventsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_GetEventsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_GetEventsResponse proto.InternalMessageInfo - -func (m *GetEventsResponse) GetEvents() []*ExecutionEvent { - if m != nil { - return m.Events - } - return nil -} - -type Bound struct { - Type Bound_BoundType `protobuf:"varint,1,opt,name=Type,proto3,enum=pbevents.Bound_BoundType" json:"Type,omitempty"` - Index uint64 `protobuf:"varint,2,opt,name=Index,proto3" json:"Index,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Bound) Reset() { *m = Bound{} } -func (m *Bound) String() string { return proto.CompactTextString(m) } -func (*Bound) ProtoMessage() {} -func (*Bound) Descriptor() ([]byte, []int) { - return fileDescriptor_events_a0e2b84614955cff, []int{7} -} -func (m *Bound) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Bound.Unmarshal(m, b) -} -func (m *Bound) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Bound.Marshal(b, m, deterministic) -} -func (dst *Bound) XXX_Merge(src proto.Message) { - xxx_messageInfo_Bound.Merge(dst, src) -} -func (m *Bound) XXX_Size() int { - return xxx_messageInfo_Bound.Size(m) -} -func (m *Bound) XXX_DiscardUnknown() { - xxx_messageInfo_Bound.DiscardUnknown(m) -} - -var xxx_messageInfo_Bound proto.InternalMessageInfo - -func (m *Bound) GetType() Bound_BoundType { - if m != nil { - return m.Type - } - return Bound_ABSOLUTE -} - -func (m *Bound) GetIndex() uint64 { - if m != nil { - return m.Index - } - return 0 -} - -// An inclusive range of blocks to include in output -type BlockRange struct { - // Bounds can be set to: - // absolute: block height - // relative: block height counting back from latest - // latest: latest block when call is processed - // stream: for End keep sending new blocks, for start same as latest - Start *Bound `protobuf:"bytes,1,opt,name=Start,proto3" json:"Start,omitempty"` - End *Bound `protobuf:"bytes,2,opt,name=End,proto3" json:"End,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *BlockRange) Reset() { *m = BlockRange{} } -func (m *BlockRange) String() string { return proto.CompactTextString(m) } -func (*BlockRange) ProtoMessage() {} -func (*BlockRange) Descriptor() ([]byte, []int) { - return fileDescriptor_events_a0e2b84614955cff, []int{8} -} -func (m *BlockRange) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_BlockRange.Unmarshal(m, b) -} -func (m *BlockRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_BlockRange.Marshal(b, m, deterministic) -} -func (dst *BlockRange) XXX_Merge(src proto.Message) { - xxx_messageInfo_BlockRange.Merge(dst, src) -} -func (m *BlockRange) XXX_Size() int { - return xxx_messageInfo_BlockRange.Size(m) -} -func (m *BlockRange) XXX_DiscardUnknown() { - xxx_messageInfo_BlockRange.DiscardUnknown(m) -} - -var xxx_messageInfo_BlockRange proto.InternalMessageInfo - -func (m *BlockRange) GetStart() *Bound { - if m != nil { - return m.Start - } - return nil -} - -func (m *BlockRange) GetEnd() *Bound { - if m != nil { - return m.End - } - return nil -} - -type EventHeader struct { - // Transaction type - TxType string `protobuf:"bytes,1,opt,name=TxType,proto3" json:"TxType,omitempty"` - // The hash of the transaction that caused this event to be generated - TxHash []byte `protobuf:"bytes,2,opt,name=TxHash,proto3" json:"TxHash,omitempty"` - // The type of event - EventType string `protobuf:"bytes,3,opt,name=EventType,proto3" json:"EventType,omitempty"` - // EventID published with event - EventID string `protobuf:"bytes,4,opt,name=EventID,proto3" json:"EventID,omitempty"` - // The block height at which this event was emitted - Height uint64 `protobuf:"varint,5,opt,name=Height,proto3" json:"Height,omitempty"` - // The index amongst all other events in the block of this event - Index uint64 `protobuf:"varint,6,opt,name=Index,proto3" json:"Index,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EventHeader) Reset() { *m = EventHeader{} } -func (m *EventHeader) String() string { return proto.CompactTextString(m) } -func (*EventHeader) ProtoMessage() {} -func (*EventHeader) Descriptor() ([]byte, []int) { - return fileDescriptor_events_a0e2b84614955cff, []int{9} -} -func (m *EventHeader) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EventHeader.Unmarshal(m, b) -} -func (m *EventHeader) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EventHeader.Marshal(b, m, deterministic) -} -func (dst *EventHeader) XXX_Merge(src proto.Message) { - xxx_messageInfo_EventHeader.Merge(dst, src) -} -func (m *EventHeader) XXX_Size() int { - return xxx_messageInfo_EventHeader.Size(m) -} -func (m *EventHeader) XXX_DiscardUnknown() { - xxx_messageInfo_EventHeader.DiscardUnknown(m) -} - -var xxx_messageInfo_EventHeader proto.InternalMessageInfo - -func (m *EventHeader) GetTxType() string { - if m != nil { - return m.TxType - } - return "" -} - -func (m *EventHeader) GetTxHash() []byte { - if m != nil { - return m.TxHash - } - return nil -} - -func (m *EventHeader) GetEventType() string { - if m != nil { - return m.EventType - } - return "" -} - -func (m *EventHeader) GetEventID() string { - if m != nil { - return m.EventID - } - return "" -} - -func (m *EventHeader) GetHeight() uint64 { - if m != nil { - return m.Height - } - return 0 -} - -func (m *EventHeader) GetIndex() uint64 { - if m != nil { - return m.Index - } - return 0 -} - -type ExecutionEvent struct { - Header *EventHeader `protobuf:"bytes,1,opt,name=Header,proto3" json:"Header,omitempty"` - // Types that are valid to be assigned to EventData: - // *ExecutionEvent_EventDataTx - // *ExecutionEvent_EventDataCall - // *ExecutionEvent_EventDataLog - EventData isExecutionEvent_EventData `protobuf_oneof:"EventData"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ExecutionEvent) Reset() { *m = ExecutionEvent{} } -func (m *ExecutionEvent) String() string { return proto.CompactTextString(m) } -func (*ExecutionEvent) ProtoMessage() {} -func (*ExecutionEvent) Descriptor() ([]byte, []int) { - return fileDescriptor_events_a0e2b84614955cff, []int{10} -} -func (m *ExecutionEvent) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ExecutionEvent.Unmarshal(m, b) -} -func (m *ExecutionEvent) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ExecutionEvent.Marshal(b, m, deterministic) -} -func (dst *ExecutionEvent) XXX_Merge(src proto.Message) { - xxx_messageInfo_ExecutionEvent.Merge(dst, src) -} -func (m *ExecutionEvent) XXX_Size() int { - return xxx_messageInfo_ExecutionEvent.Size(m) -} -func (m *ExecutionEvent) XXX_DiscardUnknown() { - xxx_messageInfo_ExecutionEvent.DiscardUnknown(m) -} - -var xxx_messageInfo_ExecutionEvent proto.InternalMessageInfo - -type isExecutionEvent_EventData interface { - isExecutionEvent_EventData() -} - -type ExecutionEvent_EventDataTx struct { - EventDataTx *EventDataTx `protobuf:"bytes,2,opt,name=EventDataTx,proto3,oneof"` -} -type ExecutionEvent_EventDataCall struct { - EventDataCall *EventDataCall `protobuf:"bytes,3,opt,name=EventDataCall,proto3,oneof"` -} -type ExecutionEvent_EventDataLog struct { - EventDataLog *EventDataLog `protobuf:"bytes,4,opt,name=EventDataLog,proto3,oneof"` -} - -func (*ExecutionEvent_EventDataTx) isExecutionEvent_EventData() {} -func (*ExecutionEvent_EventDataCall) isExecutionEvent_EventData() {} -func (*ExecutionEvent_EventDataLog) isExecutionEvent_EventData() {} - -func (m *ExecutionEvent) GetEventData() isExecutionEvent_EventData { - if m != nil { - return m.EventData - } - return nil -} - -func (m *ExecutionEvent) GetHeader() *EventHeader { - if m != nil { - return m.Header - } - return nil -} - -func (m *ExecutionEvent) GetEventDataTx() *EventDataTx { - if x, ok := m.GetEventData().(*ExecutionEvent_EventDataTx); ok { - return x.EventDataTx - } - return nil -} - -func (m *ExecutionEvent) GetEventDataCall() *EventDataCall { - if x, ok := m.GetEventData().(*ExecutionEvent_EventDataCall); ok { - return x.EventDataCall - } - return nil -} - -func (m *ExecutionEvent) GetEventDataLog() *EventDataLog { - if x, ok := m.GetEventData().(*ExecutionEvent_EventDataLog); ok { - return x.EventDataLog - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*ExecutionEvent) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _ExecutionEvent_OneofMarshaler, _ExecutionEvent_OneofUnmarshaler, _ExecutionEvent_OneofSizer, []interface{}{ - (*ExecutionEvent_EventDataTx)(nil), - (*ExecutionEvent_EventDataCall)(nil), - (*ExecutionEvent_EventDataLog)(nil), - } -} - -func _ExecutionEvent_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*ExecutionEvent) - // EventData - switch x := m.EventData.(type) { - case *ExecutionEvent_EventDataTx: - b.EncodeVarint(2<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.EventDataTx); err != nil { - return err - } - case *ExecutionEvent_EventDataCall: - b.EncodeVarint(3<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.EventDataCall); err != nil { - return err - } - case *ExecutionEvent_EventDataLog: - b.EncodeVarint(4<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.EventDataLog); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("ExecutionEvent.EventData has unexpected type %T", x) - } - return nil -} - -func _ExecutionEvent_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*ExecutionEvent) - switch tag { - case 2: // EventData.EventDataTx - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(EventDataTx) - err := b.DecodeMessage(msg) - m.EventData = &ExecutionEvent_EventDataTx{msg} - return true, err - case 3: // EventData.EventDataCall - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(EventDataCall) - err := b.DecodeMessage(msg) - m.EventData = &ExecutionEvent_EventDataCall{msg} - return true, err - case 4: // EventData.EventDataLog - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(EventDataLog) - err := b.DecodeMessage(msg) - m.EventData = &ExecutionEvent_EventDataLog{msg} - return true, err - default: - return false, nil - } -} - -func _ExecutionEvent_OneofSizer(msg proto.Message) (n int) { - m := msg.(*ExecutionEvent) - // EventData - switch x := m.EventData.(type) { - case *ExecutionEvent_EventDataTx: - s := proto.Size(x.EventDataTx) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *ExecutionEvent_EventDataCall: - s := proto.Size(x.EventDataCall) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *ExecutionEvent_EventDataLog: - s := proto.Size(x.EventDataLog) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type EventDataLog struct { - Address []byte `protobuf:"bytes,1,opt,name=Address,proto3" json:"Address,omitempty"` - Data []byte `protobuf:"bytes,2,opt,name=Data,proto3" json:"Data,omitempty"` - Topics [][]byte `protobuf:"bytes,3,rep,name=Topics,proto3" json:"Topics,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EventDataLog) Reset() { *m = EventDataLog{} } -func (m *EventDataLog) String() string { return proto.CompactTextString(m) } -func (*EventDataLog) ProtoMessage() {} -func (*EventDataLog) Descriptor() ([]byte, []int) { - return fileDescriptor_events_a0e2b84614955cff, []int{11} -} -func (m *EventDataLog) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EventDataLog.Unmarshal(m, b) -} -func (m *EventDataLog) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EventDataLog.Marshal(b, m, deterministic) -} -func (dst *EventDataLog) XXX_Merge(src proto.Message) { - xxx_messageInfo_EventDataLog.Merge(dst, src) -} -func (m *EventDataLog) XXX_Size() int { - return xxx_messageInfo_EventDataLog.Size(m) -} -func (m *EventDataLog) XXX_DiscardUnknown() { - xxx_messageInfo_EventDataLog.DiscardUnknown(m) -} - -var xxx_messageInfo_EventDataLog proto.InternalMessageInfo - -func (m *EventDataLog) GetAddress() []byte { - if m != nil { - return m.Address - } - return nil -} - -func (m *EventDataLog) GetData() []byte { - if m != nil { - return m.Data - } - return nil -} - -func (m *EventDataLog) GetTopics() [][]byte { - if m != nil { - return m.Topics - } - return nil -} - -type EventDataTx struct { - Return []byte `protobuf:"bytes,1,opt,name=Return,proto3" json:"Return,omitempty"` - Exception *errors.Exception `protobuf:"bytes,2,opt,name=Exception,proto3" json:"Exception,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EventDataTx) Reset() { *m = EventDataTx{} } -func (m *EventDataTx) String() string { return proto.CompactTextString(m) } -func (*EventDataTx) ProtoMessage() {} -func (*EventDataTx) Descriptor() ([]byte, []int) { - return fileDescriptor_events_a0e2b84614955cff, []int{12} -} -func (m *EventDataTx) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EventDataTx.Unmarshal(m, b) -} -func (m *EventDataTx) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EventDataTx.Marshal(b, m, deterministic) -} -func (dst *EventDataTx) XXX_Merge(src proto.Message) { - xxx_messageInfo_EventDataTx.Merge(dst, src) -} -func (m *EventDataTx) XXX_Size() int { - return xxx_messageInfo_EventDataTx.Size(m) -} -func (m *EventDataTx) XXX_DiscardUnknown() { - xxx_messageInfo_EventDataTx.DiscardUnknown(m) -} - -var xxx_messageInfo_EventDataTx proto.InternalMessageInfo - -func (m *EventDataTx) GetReturn() []byte { - if m != nil { - return m.Return - } - return nil -} - -func (m *EventDataTx) GetException() *errors.Exception { - if m != nil { - return m.Exception - } - return nil -} - -type EventDataCall struct { - CallData *CallData `protobuf:"bytes,1,opt,name=CallData,proto3" json:"CallData,omitempty"` - Origin []byte `protobuf:"bytes,2,opt,name=Origin,proto3" json:"Origin,omitempty"` - StackDepth uint64 `protobuf:"varint,3,opt,name=StackDepth,proto3" json:"StackDepth,omitempty"` - Return []byte `protobuf:"bytes,4,opt,name=Return,proto3" json:"Return,omitempty"` - Exception *errors.Exception `protobuf:"bytes,5,opt,name=Exception,proto3" json:"Exception,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EventDataCall) Reset() { *m = EventDataCall{} } -func (m *EventDataCall) String() string { return proto.CompactTextString(m) } -func (*EventDataCall) ProtoMessage() {} -func (*EventDataCall) Descriptor() ([]byte, []int) { - return fileDescriptor_events_a0e2b84614955cff, []int{13} -} -func (m *EventDataCall) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EventDataCall.Unmarshal(m, b) -} -func (m *EventDataCall) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EventDataCall.Marshal(b, m, deterministic) -} -func (dst *EventDataCall) XXX_Merge(src proto.Message) { - xxx_messageInfo_EventDataCall.Merge(dst, src) -} -func (m *EventDataCall) XXX_Size() int { - return xxx_messageInfo_EventDataCall.Size(m) -} -func (m *EventDataCall) XXX_DiscardUnknown() { - xxx_messageInfo_EventDataCall.DiscardUnknown(m) -} - -var xxx_messageInfo_EventDataCall proto.InternalMessageInfo - -func (m *EventDataCall) GetCallData() *CallData { - if m != nil { - return m.CallData - } - return nil -} - -func (m *EventDataCall) GetOrigin() []byte { - if m != nil { - return m.Origin - } - return nil -} - -func (m *EventDataCall) GetStackDepth() uint64 { - if m != nil { - return m.StackDepth - } - return 0 -} - -func (m *EventDataCall) GetReturn() []byte { - if m != nil { - return m.Return - } - return nil -} - -func (m *EventDataCall) GetException() *errors.Exception { - if m != nil { - return m.Exception - } - return nil -} - -type CallData struct { - Caller []byte `protobuf:"bytes,1,opt,name=Caller,proto3" json:"Caller,omitempty"` - Callee []byte `protobuf:"bytes,2,opt,name=Callee,proto3" json:"Callee,omitempty"` - Data []byte `protobuf:"bytes,3,opt,name=Data,proto3" json:"Data,omitempty"` - Value uint64 `protobuf:"varint,4,opt,name=Value,proto3" json:"Value,omitempty"` - Gas uint64 `protobuf:"varint,5,opt,name=Gas,proto3" json:"Gas,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CallData) Reset() { *m = CallData{} } -func (m *CallData) String() string { return proto.CompactTextString(m) } -func (*CallData) ProtoMessage() {} -func (*CallData) Descriptor() ([]byte, []int) { - return fileDescriptor_events_a0e2b84614955cff, []int{14} -} -func (m *CallData) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CallData.Unmarshal(m, b) -} -func (m *CallData) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CallData.Marshal(b, m, deterministic) -} -func (dst *CallData) XXX_Merge(src proto.Message) { - xxx_messageInfo_CallData.Merge(dst, src) -} -func (m *CallData) XXX_Size() int { - return xxx_messageInfo_CallData.Size(m) -} -func (m *CallData) XXX_DiscardUnknown() { - xxx_messageInfo_CallData.DiscardUnknown(m) -} - -var xxx_messageInfo_CallData proto.InternalMessageInfo - -func (m *CallData) GetCaller() []byte { - if m != nil { - return m.Caller - } - return nil -} - -func (m *CallData) GetCallee() []byte { - if m != nil { - return m.Callee - } - return nil -} - -func (m *CallData) GetData() []byte { - if m != nil { - return m.Data - } - return nil -} - -func (m *CallData) GetValue() uint64 { - if m != nil { - return m.Value - } - return 0 -} - -func (m *CallData) GetGas() uint64 { - if m != nil { - return m.Gas - } - return 0 -} - -func init() { - proto.RegisterType((*EventIdParam)(nil), "pbevents.EventIdParam") - proto.RegisterType((*SubIdParam)(nil), "pbevents.SubIdParam") - proto.RegisterType((*EventUnSub)(nil), "pbevents.EventUnSub") - proto.RegisterType((*PollResponse)(nil), "pbevents.PollResponse") - proto.RegisterType((*Event)(nil), "pbevents.Event") - proto.RegisterType((*GetEventsRequest)(nil), "pbevents.GetEventsRequest") - proto.RegisterType((*GetEventsResponse)(nil), "pbevents.GetEventsResponse") - proto.RegisterType((*Bound)(nil), "pbevents.Bound") - proto.RegisterType((*BlockRange)(nil), "pbevents.BlockRange") - proto.RegisterType((*EventHeader)(nil), "pbevents.EventHeader") - proto.RegisterType((*ExecutionEvent)(nil), "pbevents.ExecutionEvent") - proto.RegisterType((*EventDataLog)(nil), "pbevents.EventDataLog") - proto.RegisterType((*EventDataTx)(nil), "pbevents.EventDataTx") - proto.RegisterType((*EventDataCall)(nil), "pbevents.EventDataCall") - proto.RegisterType((*CallData)(nil), "pbevents.CallData") - proto.RegisterEnum("pbevents.Bound_BoundType", Bound_BoundType_name, Bound_BoundType_value) -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// EventsClient is the client API for Events service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type EventsClient interface { - EventPoll(ctx context.Context, in *SubIdParam, opts ...grpc.CallOption) (*PollResponse, error) - EventSubscribe(ctx context.Context, in *EventIdParam, opts ...grpc.CallOption) (*SubIdParam, error) - EventUnsubscribe(ctx context.Context, in *SubIdParam, opts ...grpc.CallOption) (*EventUnSub, error) -} - -type eventsClient struct { - cc *grpc.ClientConn -} - -func NewEventsClient(cc *grpc.ClientConn) EventsClient { - return &eventsClient{cc} -} - -func (c *eventsClient) EventPoll(ctx context.Context, in *SubIdParam, opts ...grpc.CallOption) (*PollResponse, error) { - out := new(PollResponse) - err := c.cc.Invoke(ctx, "/pbevents.Events/EventPoll", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *eventsClient) EventSubscribe(ctx context.Context, in *EventIdParam, opts ...grpc.CallOption) (*SubIdParam, error) { - out := new(SubIdParam) - err := c.cc.Invoke(ctx, "/pbevents.Events/EventSubscribe", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *eventsClient) EventUnsubscribe(ctx context.Context, in *SubIdParam, opts ...grpc.CallOption) (*EventUnSub, error) { - out := new(EventUnSub) - err := c.cc.Invoke(ctx, "/pbevents.Events/EventUnsubscribe", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// EventsServer is the server API for Events service. -type EventsServer interface { - EventPoll(context.Context, *SubIdParam) (*PollResponse, error) - EventSubscribe(context.Context, *EventIdParam) (*SubIdParam, error) - EventUnsubscribe(context.Context, *SubIdParam) (*EventUnSub, error) -} - -func RegisterEventsServer(s *grpc.Server, srv EventsServer) { - s.RegisterService(&_Events_serviceDesc, srv) -} - -func _Events_EventPoll_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SubIdParam) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(EventsServer).EventPoll(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pbevents.Events/EventPoll", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(EventsServer).EventPoll(ctx, req.(*SubIdParam)) - } - return interceptor(ctx, in, info, handler) -} - -func _Events_EventSubscribe_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(EventIdParam) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(EventsServer).EventSubscribe(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pbevents.Events/EventSubscribe", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(EventsServer).EventSubscribe(ctx, req.(*EventIdParam)) - } - return interceptor(ctx, in, info, handler) -} - -func _Events_EventUnsubscribe_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SubIdParam) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(EventsServer).EventUnsubscribe(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pbevents.Events/EventUnsubscribe", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(EventsServer).EventUnsubscribe(ctx, req.(*SubIdParam)) - } - return interceptor(ctx, in, info, handler) -} - -var _Events_serviceDesc = grpc.ServiceDesc{ - ServiceName: "pbevents.Events", - HandlerType: (*EventsServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "EventPoll", - Handler: _Events_EventPoll_Handler, - }, - { - MethodName: "EventSubscribe", - Handler: _Events_EventSubscribe_Handler, - }, - { - MethodName: "EventUnsubscribe", - Handler: _Events_EventUnsubscribe_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "github.com/hyperledger/burrow/execution/events/pbevents/events.proto", -} - -// ExecutionEventsClient is the client API for ExecutionEvents service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type ExecutionEventsClient interface { - // GetEvents provides events streaming one block at a time - that is all events emitted in a particular block - // are guaranteed to be delivered in each GetEventsResponse - GetEvents(ctx context.Context, in *GetEventsRequest, opts ...grpc.CallOption) (ExecutionEvents_GetEventsClient, error) -} - -type executionEventsClient struct { - cc *grpc.ClientConn -} - -func NewExecutionEventsClient(cc *grpc.ClientConn) ExecutionEventsClient { - return &executionEventsClient{cc} -} - -func (c *executionEventsClient) GetEvents(ctx context.Context, in *GetEventsRequest, opts ...grpc.CallOption) (ExecutionEvents_GetEventsClient, error) { - stream, err := c.cc.NewStream(ctx, &_ExecutionEvents_serviceDesc.Streams[0], "/pbevents.ExecutionEvents/GetEvents", opts...) - if err != nil { - return nil, err - } - x := &executionEventsGetEventsClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type ExecutionEvents_GetEventsClient interface { - Recv() (*GetEventsResponse, error) - grpc.ClientStream -} - -type executionEventsGetEventsClient struct { - grpc.ClientStream -} - -func (x *executionEventsGetEventsClient) Recv() (*GetEventsResponse, error) { - m := new(GetEventsResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// ExecutionEventsServer is the server API for ExecutionEvents service. -type ExecutionEventsServer interface { - // GetEvents provides events streaming one block at a time - that is all events emitted in a particular block - // are guaranteed to be delivered in each GetEventsResponse - GetEvents(*GetEventsRequest, ExecutionEvents_GetEventsServer) error -} - -func RegisterExecutionEventsServer(s *grpc.Server, srv ExecutionEventsServer) { - s.RegisterService(&_ExecutionEvents_serviceDesc, srv) -} - -func _ExecutionEvents_GetEvents_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(GetEventsRequest) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(ExecutionEventsServer).GetEvents(m, &executionEventsGetEventsServer{stream}) -} - -type ExecutionEvents_GetEventsServer interface { - Send(*GetEventsResponse) error - grpc.ServerStream -} - -type executionEventsGetEventsServer struct { - grpc.ServerStream -} - -func (x *executionEventsGetEventsServer) Send(m *GetEventsResponse) error { - return x.ServerStream.SendMsg(m) -} - -var _ExecutionEvents_serviceDesc = grpc.ServiceDesc{ - ServiceName: "pbevents.ExecutionEvents", - HandlerType: (*ExecutionEventsServer)(nil), - Methods: []grpc.MethodDesc{}, - Streams: []grpc.StreamDesc{ - { - StreamName: "GetEvents", - Handler: _ExecutionEvents_GetEvents_Handler, - ServerStreams: true, - }, - }, - Metadata: "github.com/hyperledger/burrow/execution/events/pbevents/events.proto", -} - -func init() { - proto.RegisterFile("github.com/hyperledger/burrow/execution/events/pbevents/events.proto", fileDescriptor_events_a0e2b84614955cff) -} - -var fileDescriptor_events_a0e2b84614955cff = []byte{ - // 907 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x56, 0xdd, 0x6e, 0xdc, 0x44, - 0x14, 0x5e, 0x67, 0x7f, 0x1a, 0x9f, 0x5d, 0x12, 0x77, 0x08, 0xc5, 0x04, 0x84, 0x82, 0x05, 0x22, - 0x37, 0xdd, 0xad, 0x0c, 0x52, 0x15, 0x81, 0x8a, 0x76, 0x89, 0xdb, 0x4d, 0xb5, 0x34, 0x65, 0xec, - 0x46, 0x82, 0x0b, 0x24, 0x7b, 0x3d, 0xda, 0xb5, 0xea, 0xd8, 0x66, 0xc6, 0x2e, 0x9b, 0x17, 0xe0, - 0x19, 0xb8, 0xe0, 0x8e, 0x17, 0x41, 0xe2, 0xc5, 0xd0, 0xfc, 0xf8, 0x97, 0xad, 0x54, 0x71, 0x13, - 0xcf, 0x37, 0xe7, 0x9b, 0x6f, 0xcf, 0xf9, 0xce, 0xfc, 0x04, 0x2e, 0x37, 0x51, 0xbe, 0x2d, 0x82, - 0xe9, 0x3a, 0xbd, 0x9d, 0x6d, 0xef, 0x32, 0x42, 0x63, 0x12, 0x6e, 0x08, 0x9d, 0x05, 0x05, 0xa5, - 0xe9, 0x6f, 0x33, 0xb2, 0x23, 0xeb, 0x22, 0x8f, 0xd2, 0x64, 0x46, 0xde, 0x90, 0x24, 0x67, 0xb3, - 0x2c, 0x50, 0x03, 0xf9, 0x99, 0x66, 0x34, 0xcd, 0x53, 0x74, 0x58, 0x4e, 0x9f, 0x7e, 0xf3, 0xce, - 0x7a, 0x94, 0xa6, 0x94, 0xa9, 0x8f, 0x94, 0xb1, 0xce, 0x61, 0xe2, 0x70, 0x99, 0xab, 0xf0, 0xa5, - 0x4f, 0xfd, 0x5b, 0x64, 0xc2, 0x3d, 0x22, 0xb1, 0xa9, 0x9d, 0x69, 0xe7, 0x3a, 0x2e, 0xa1, 0x65, - 0x01, 0xb8, 0x45, 0x50, 0xf2, 0x4e, 0x60, 0xc8, 0x38, 0x52, 0x2c, 0x09, 0xac, 0xcf, 0x01, 0x84, - 0xda, 0xab, 0xc4, 0x2d, 0x02, 0xf4, 0x00, 0x46, 0x94, 0xb0, 0x22, 0xce, 0x05, 0xe9, 0x10, 0x2b, - 0x64, 0x3d, 0x86, 0xc9, 0xcb, 0x34, 0x8e, 0x31, 0x61, 0x59, 0x9a, 0x30, 0x82, 0xbe, 0x84, 0x91, - 0x2c, 0xc5, 0xd4, 0xce, 0xfa, 0xe7, 0x63, 0xfb, 0x78, 0x5a, 0xd6, 0x36, 0x15, 0x6a, 0x58, 0x85, - 0xad, 0x3f, 0x35, 0x18, 0x8a, 0x19, 0x84, 0x60, 0xf0, 0xc2, 0xbf, 0x25, 0xea, 0xd7, 0xc5, 0x18, - 0x2d, 0xe0, 0xc8, 0x29, 0x6b, 0x15, 0x2c, 0xf3, 0xe0, 0x4c, 0x3b, 0x1f, 0xdb, 0x66, 0x43, 0xae, - 0x15, 0x5f, 0xf6, 0x70, 0x67, 0x05, 0xb2, 0xe1, 0x7d, 0x8f, 0x24, 0x21, 0xa1, 0xb7, 0x51, 0x92, - 0x8b, 0xa9, 0xe7, 0xee, 0xf5, 0x0b, 0xb3, 0xcf, 0x7f, 0x66, 0xd9, 0xc3, 0xfb, 0x82, 0x8b, 0x7b, - 0x2a, 0x29, 0xeb, 0x17, 0x30, 0x9e, 0x11, 0x19, 0x60, 0x98, 0xfc, 0x5a, 0x10, 0x96, 0xa3, 0xaf, - 0x01, 0x16, 0x71, 0xba, 0x7e, 0x8d, 0xfd, 0x64, 0x23, 0xd3, 0x1d, 0xdb, 0x27, 0x75, 0x42, 0x75, - 0x0c, 0x37, 0x78, 0xdc, 0xdd, 0x1f, 0x0b, 0x42, 0xef, 0x44, 0x05, 0x3a, 0x96, 0xc0, 0x72, 0xe0, - 0x7e, 0x43, 0x5f, 0x99, 0xf7, 0xa8, 0x63, 0xde, 0x5b, 0xab, 0xad, 0x5c, 0xfc, 0x43, 0x83, 0xe1, - 0x22, 0x2d, 0x92, 0x10, 0x3d, 0x84, 0x81, 0x77, 0x97, 0xc9, 0xb4, 0x8e, 0xec, 0x8f, 0x1a, 0x69, - 0xf1, 0xb0, 0xfc, 0xcb, 0x09, 0x58, 0xd0, 0x78, 0x56, 0x57, 0x49, 0x48, 0x76, 0x22, 0xab, 0x01, - 0x96, 0xc0, 0x7a, 0x0e, 0x7a, 0x45, 0x44, 0x13, 0x38, 0x9c, 0x2f, 0xdc, 0xeb, 0xd5, 0x2b, 0xcf, - 0x31, 0x7a, 0x1c, 0x61, 0x67, 0x35, 0xf7, 0xae, 0x6e, 0x1c, 0x43, 0x43, 0x3a, 0x0c, 0x9f, 0x5e, - 0x61, 0xd7, 0x33, 0x0e, 0x10, 0xc0, 0x68, 0x35, 0xf7, 0x1c, 0xd7, 0x33, 0xfa, 0x7c, 0xec, 0x7a, - 0xd8, 0x99, 0xff, 0x60, 0x0c, 0xac, 0x9b, 0xa6, 0x5b, 0xe8, 0x0b, 0x18, 0xba, 0xb9, 0x4f, 0x73, - 0x65, 0xdb, 0x71, 0x27, 0x3f, 0x2c, 0xa3, 0xe8, 0x33, 0xe8, 0x3b, 0x49, 0xa8, 0x9a, 0xfd, 0x1f, - 0x12, 0x8f, 0x59, 0x7f, 0x69, 0x30, 0x96, 0x2d, 0x27, 0x7e, 0x48, 0x28, 0xdf, 0x99, 0xde, 0xae, - 0x2a, 0x5d, 0xc7, 0x0a, 0xc9, 0xf9, 0xa5, 0xcf, 0xb6, 0x42, 0x6d, 0x82, 0x15, 0x42, 0x9f, 0x80, - 0x2e, 0x96, 0x8b, 0x25, 0x62, 0x33, 0xe0, 0x7a, 0x82, 0x9f, 0x19, 0x79, 0x86, 0x2e, 0xcd, 0x81, - 0x3c, 0x33, 0x0a, 0x72, 0xbd, 0x25, 0x89, 0x36, 0xdb, 0xdc, 0x1c, 0x0a, 0xcb, 0x14, 0xaa, 0x9d, - 0x1c, 0x35, 0x9d, 0xfc, 0xfd, 0xa0, 0xbb, 0x83, 0xd1, 0x43, 0x2e, 0xc0, 0x53, 0x56, 0x1e, 0x7c, - 0xd0, 0x39, 0x1a, 0x32, 0x88, 0x15, 0x09, 0x5d, 0xa8, 0x32, 0x2f, 0xfd, 0xdc, 0xf7, 0x76, 0xca, - 0x92, 0xee, 0x1a, 0x19, 0x5c, 0xf6, 0x70, 0x93, 0x8b, 0xbe, 0x83, 0xf7, 0x2a, 0xf8, 0xbd, 0x1f, - 0xc7, 0xa2, 0xcc, 0xb1, 0xfd, 0xe1, 0x9e, 0xc5, 0x3c, 0xbc, 0xec, 0xe1, 0x36, 0x1f, 0x7d, 0xab, - 0x6e, 0x12, 0x3e, 0xb1, 0x4a, 0x37, 0xc2, 0x8a, 0xb1, 0xfd, 0x60, 0xcf, 0xfa, 0x55, 0xba, 0x59, - 0xf6, 0x70, 0x8b, 0xbd, 0x18, 0x2b, 0x87, 0x39, 0xb6, 0xbc, 0xb6, 0x14, 0x37, 0x78, 0x1e, 0x86, - 0x94, 0x30, 0x26, 0x6c, 0x98, 0xe0, 0x12, 0xf2, 0x7b, 0x80, 0x93, 0x54, 0xbb, 0xc4, 0x58, 0x34, - 0x31, 0xcd, 0xa2, 0x35, 0x33, 0xfb, 0x67, 0x7d, 0xd1, 0x44, 0x81, 0xac, 0x9b, 0x96, 0x39, 0x9c, - 0x86, 0x49, 0x5e, 0xd0, 0x44, 0x69, 0x2a, 0x84, 0x66, 0xa0, 0x3b, 0xbb, 0x35, 0xc9, 0x78, 0x13, - 0x94, 0x83, 0xf7, 0xa7, 0xea, 0xce, 0xac, 0x02, 0xb8, 0xe6, 0x58, 0x7f, 0x6b, 0x1d, 0xeb, 0xd0, - 0x14, 0x0e, 0xf9, 0x57, 0x64, 0x26, 0xfb, 0x86, 0x6a, 0x1b, 0xca, 0x08, 0xae, 0x38, 0x3c, 0x95, - 0x6b, 0x1a, 0x6d, 0xa2, 0xa4, 0xdc, 0x76, 0x12, 0xa1, 0x4f, 0x01, 0xdc, 0xdc, 0x5f, 0xbf, 0xbe, - 0x24, 0x59, 0xbe, 0x15, 0x0d, 0x19, 0xe0, 0xc6, 0x4c, 0xa3, 0x84, 0xc1, 0xdb, 0x4b, 0x18, 0xbe, - 0x43, 0x09, 0x6f, 0xa0, 0x95, 0x0c, 0x1f, 0xab, 0x2d, 0x37, 0xc1, 0x0a, 0x55, 0xf3, 0xa4, 0x4c, - 0x52, 0xa2, 0xaa, 0x05, 0xfd, 0x46, 0x0b, 0x4e, 0x60, 0x78, 0xe3, 0xc7, 0x05, 0x11, 0x79, 0x0d, - 0xb0, 0x04, 0xc8, 0x80, 0xfe, 0x33, 0x9f, 0xa9, 0xa3, 0xc0, 0x87, 0xf6, 0x3f, 0x1a, 0x8c, 0xe4, - 0x7d, 0x86, 0x2e, 0xd4, 0x06, 0xe0, 0x2f, 0x03, 0x6a, 0xdc, 0x90, 0xf5, 0x9b, 0x73, 0xda, 0xd8, - 0x4b, 0xad, 0xf7, 0xe3, 0x09, 0x1c, 0x89, 0xa5, 0x6e, 0x11, 0xb0, 0x35, 0x8d, 0x02, 0x82, 0xba, - 0xbb, 0xae, 0x54, 0xd8, 0xab, 0x8b, 0x9e, 0x80, 0xa1, 0x5e, 0x2d, 0x56, 0x29, 0xec, 0xcf, 0xe0, - 0xa4, 0xa3, 0x2b, 0xde, 0x39, 0xfb, 0x27, 0x38, 0x6e, 0x1f, 0x5b, 0x86, 0x9e, 0x82, 0x5e, 0x5d, - 0xd5, 0xe8, 0xb4, 0x5e, 0xd5, 0x7d, 0x1f, 0x4e, 0x3f, 0xde, 0x1b, 0x93, 0x85, 0x3d, 0xd2, 0x16, - 0x17, 0x3f, 0x3f, 0xfe, 0x9f, 0xff, 0x2d, 0x04, 0x23, 0xf1, 0xc0, 0x7f, 0xf5, 0x6f, 0x00, 0x00, - 0x00, 0xff, 0xff, 0x6f, 0x28, 0x40, 0xd9, 0x6f, 0x08, 0x00, 0x00, -} diff --git a/execution/events/pbevents/events.proto b/execution/events/pbevents/events.proto deleted file mode 100644 index 67cb46c39..000000000 --- a/execution/events/pbevents/events.proto +++ /dev/null @@ -1,177 +0,0 @@ -syntax = 'proto3'; - -option go_package = "github.com/hyperledger/burrow/execution/events/pbevents"; - -import "github.com/hyperledger/burrow/execution/errors/errors.proto"; - -package pbevents; - -//-------------------------------------------------- -// Event Service Definition -service Events { - rpc EventPoll (SubIdParam) returns (PollResponse); - rpc EventSubscribe (EventIdParam) returns (SubIdParam); - rpc EventUnsubscribe (SubIdParam) returns (EventUnSub); -} - -// Params -message EventIdParam { - string eventId = 1; -} - -message SubIdParam { - string subId = 1; -} - -// Results -message EventUnSub { - bool result = 1; -} - -message PollResponse { - repeated Event events = 1; -} - -message Event { - string Name = 1; - oneof Event { - // Burrow's execution domain events generated deterministically from transactions - ExecutionEvent ExecutionEvent = 2; - // Operational events from tendermint serialised into their standard JSON representation - string TendermintEventJSON = 3; - } -} - -//-------------------------------------------------- -// Execution events -service ExecutionEvents { - // GetEvents provides events streaming one block at a time - that is all events emitted in a particular block - // are guaranteed to be delivered in each GetEventsResponse - rpc GetEvents (GetEventsRequest) returns (stream GetEventsResponse); -} - -message GetEventsRequest { - BlockRange BlockRange = 1; - // Specify a query on which to match the tags of events. - // Tag | Match type | Values - // ----------------------------------------- - // All events - // ----------------------------------------- - // TxType | String | "UnknownTx", "SendTx", "CallTx", "NameTx", "BondTx", "UnbondTx", "PermissionsTx", "GovernanceTx" - // TxHash | String | bytes - // EventType | String | "CallEvent", "LogEvent", "AccountInputEvent", "AccountOutputEvent" - // EventID | String | string - // Height | Integer | uint64 - // Index | Integer | uint64 - // MessageType | String | Go type name - // ----------------------------------------- - // Log event - // ----------------------------------------- - // Address | String | Address (hex) - // Log<0-4> | String | Word256 (hex) - // Log<0-4>Text | String | string (trimmed) - // ----------------------------------------- - // Call event - // ----------------------------------------- - // Origin | String | Address (hex) - // Callee | String | Address (hex) - // Caller | String | Address (hex) - // Value | Integer | uint64 - // Gas | Integer | uint64 - // StackDepth | Integer | uint64 - // Exception | String | string - // ----------------------------------------- - // Tx event (input/output) - // ----------------------------------------- - // Exception | String | string - // - // For example: - // EventType = 'LogEvent' AND EventID CONTAINS 'bar' AND TxHash = '020304' AND Height >= 34 AND Index < 3 AND Address = 'DEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF' - string Query = 2; -} - -message GetEventsResponse { - repeated ExecutionEvent events = 1; -} - -message Bound { - BoundType Type = 1; - uint64 Index = 2; - enum BoundType { - // Index is absolute index of object in collection - ABSOLUTE = 0; - // Index is an offset relative to another bound determined by context - RELATIVE = 1; - // The first block - FIRST = 2; - // Ignore provided index and evaluate to latest index - LATEST = 3; - // Ignore provided index and stream new objects as they are generated - STREAM = 4; - } -} - -// An inclusive range of blocks to include in output -message BlockRange { - // Bounds can be set to: - // absolute: block height - // relative: block height counting back from latest - // latest: latest block when call is processed - // stream: for End keep sending new blocks, for start same as latest - Bound Start = 1; - Bound End = 2; -} - -//-------------------------------------------------- -// Event types - -message EventHeader { - // Transaction type - string TxType = 1; - // The hash of the transaction that caused this event to be generated - bytes TxHash = 2; - // The type of event - string EventType = 3; - // EventID published with event - string EventID = 4; - // The block height at which this event was emitted - uint64 Height = 5; - // The index amongst all other events in the block of this event - uint64 Index = 6; -} - -message ExecutionEvent { - EventHeader Header = 1; - oneof EventData { - EventDataTx EventDataTx = 2; - EventDataCall EventDataCall = 3; - EventDataLog EventDataLog = 4; - } -} - -message EventDataLog { - bytes Address = 1; - bytes Data = 2; - repeated bytes Topics = 3; -} - -message EventDataTx { - bytes Return = 1; - errors.Exception Exception = 2; -} - -message EventDataCall { - CallData CallData = 1; - bytes Origin = 2; - uint64 StackDepth = 3; - bytes Return = 4; - errors.Exception Exception = 5; -} - -message CallData { - bytes Caller = 1; - bytes Callee = 2; - bytes Data = 3; - uint64 Value = 4; - uint64 Gas = 5; -} diff --git a/execution/events/tx.go b/execution/events/tx.go deleted file mode 100644 index c1da5c62d..000000000 --- a/execution/events/tx.go +++ /dev/null @@ -1,134 +0,0 @@ -package events - -import ( - "context" - "fmt" - - "github.com/hyperledger/burrow/binary" - "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/event" - "github.com/hyperledger/burrow/event/query" - "github.com/hyperledger/burrow/execution/errors" - ptypes "github.com/hyperledger/burrow/permission/types" - "github.com/hyperledger/burrow/txs" - "github.com/hyperledger/burrow/txs/payload" - "github.com/tmthrgd/go-hex" -) - -func EventStringAccountInput(addr crypto.Address) string { return fmt.Sprintf("Acc/%s/Input", addr) } -func EventStringAccountOutput(addr crypto.Address) string { return fmt.Sprintf("Acc/%s/Output", addr) } -func EventStringNameReg(name string) string { return fmt.Sprintf("NameReg/%s", name) } -func EventStringPermissions(perm ptypes.PermFlag) string { return fmt.Sprintf("Permissions/%v", perm) } -func EventStringBond() string { return "Bond" } -func EventStringUnbond() string { return "Unbond" } - -// All txs fire EventDataTx, but only CallTx might have Return or Exception -type EventDataTx struct { - Tx *txs.Tx - Return binary.HexBytes - Exception *errors.Exception -} - -// For re-use -var sendTxQuery = query.NewBuilder(). - AndEquals(event.TxTypeKey, payload.TypeSend.String()) - -var callTxQuery = query.NewBuilder(). - AndEquals(event.TxTypeKey, payload.TypeCall.String()) - -// Publish/Subscribe -func PublishAccountInput(publisher event.Publisher, height uint64, address crypto.Address, tx *txs.Tx, ret []byte, - exception *errors.Exception) error { - - ev := txEvent(height, TypeAccountInput, EventStringAccountInput(address), tx, ret, exception) - return publisher.Publish(context.Background(), ev, event.CombinedTags{ev.Tags(), event.TagMap{ - event.AddressKey: address, - }}) -} - -func PublishAccountOutput(publisher event.Publisher, height uint64, address crypto.Address, tx *txs.Tx, ret []byte, - exception *errors.Exception) error { - - ev := txEvent(height, TypeAccountOutput, EventStringAccountOutput(address), tx, ret, exception) - return publisher.Publish(context.Background(), ev, event.CombinedTags{ev.Tags(), event.TagMap{ - event.AddressKey: address, - }}) -} - -func PublishNameReg(publisher event.Publisher, height uint64, tx *txs.Tx) error { - nameTx, ok := tx.Payload.(*payload.NameTx) - if !ok { - return fmt.Errorf("Tx payload must be NameTx to PublishNameReg") - } - ev := txEvent(height, TypeAccountInput, EventStringNameReg(nameTx.Name), tx, nil, nil) - return publisher.Publish(context.Background(), ev, event.CombinedTags{ev.Tags(), event.TagMap{ - event.NameKey: nameTx.Name, - }}) -} - -func PublishPermissions(publisher event.Publisher, height uint64, tx *txs.Tx) error { - permTx, ok := tx.Payload.(*payload.PermissionsTx) - if !ok { - return fmt.Errorf("Tx payload must be PermissionsTx to PublishPermissions") - } - ev := txEvent(height, TypeAccountInput, EventStringPermissions(permTx.PermArgs.PermFlag), tx, nil, nil) - return publisher.Publish(context.Background(), ev, event.CombinedTags{ev.Tags(), event.TagMap{ - event.PermissionKey: permTx.PermArgs.PermFlag.String(), - }}) -} - -func SubscribeAccountOutputSendTx(ctx context.Context, subscribable event.Subscribable, subscriber string, - address crypto.Address, txHash []byte, ch chan<- *payload.SendTx) error { - - qry := sendTxQuery.And(event.QueryForEventID(EventStringAccountOutput(address))). - AndEquals(event.TxHashKey, hex.EncodeUpperToString(txHash)) - - return event.SubscribeCallback(ctx, subscribable, subscriber, qry, func(message interface{}) (stop bool) { - if ev, ok := message.(*Event); ok && ev.Tx != nil { - if sendTx, ok := ev.Tx.Tx.Payload.(*payload.SendTx); ok { - ch <- sendTx - } - } - return - }) -} - -func txEvent(height uint64, eventType Type, eventID string, tx *txs.Tx, ret []byte, exception *errors.Exception) *Event { - return &Event{ - Header: &Header{ - TxType: tx.Type(), - TxHash: tx.Hash(), - EventType: eventType, - EventID: eventID, - Height: height, - }, - Tx: &EventDataTx{ - Tx: tx, - Return: ret, - Exception: exception, - }, - } -} - -// Tags - -var txTagKeys = []string{event.ExceptionKey} - -func (tx *EventDataTx) Get(key string) (string, bool) { - var value interface{} - switch key { - case event.ExceptionKey: - value = tx.Exception - default: - return "", false - } - return query.StringFromValue(value), true -} - -func (tx *EventDataTx) Len() int { - return len(txTagKeys) -} - -func (tx *EventDataTx) Keys() []string { - return txTagKeys -} diff --git a/execution/events/type.go b/execution/events/type.go deleted file mode 100644 index 8fe49f60d..000000000 --- a/execution/events/type.go +++ /dev/null @@ -1,47 +0,0 @@ -package events - -type Type int8 - -// Execution event types -const ( - TypeCall = Type(0x00) - TypeLog = Type(0x01) - TypeAccountInput = Type(0x02) - TypeAccountOutput = Type(0x03) -) - -var nameFromType = map[Type]string{ - TypeCall: "CallEvent", - TypeLog: "LogEvent", - TypeAccountInput: "AccountInputEvent", - TypeAccountOutput: "AccountOutputEvent", -} - -var typeFromName = make(map[string]Type) - -func init() { - for t, n := range nameFromType { - typeFromName[n] = t - } -} - -func EventTypeFromString(name string) Type { - return typeFromName[name] -} - -func (typ Type) String() string { - name, ok := nameFromType[typ] - if ok { - return name - } - return "UnknownTx" -} - -func (typ Type) MarshalText() ([]byte, error) { - return []byte(typ.String()), nil -} - -func (typ *Type) UnmarshalText(data []byte) error { - *typ = EventTypeFromString(string(data)) - return nil -} diff --git a/execution/evm/accounts.go b/execution/evm/accounts.go index 1bd61df33..65c578e37 100644 --- a/execution/evm/accounts.go +++ b/execution/evm/accounts.go @@ -1,16 +1,16 @@ package evm import ( - acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/logging" - ptypes "github.com/hyperledger/burrow/permission/types" + "github.com/hyperledger/burrow/permission" ) // Create a new account from a parent 'creator' account. The creator account will have its // sequence number incremented -func DeriveNewAccount(creator acm.MutableAccount, permissions ptypes.AccountPermissions, - logger *logging.Logger) acm.MutableAccount { +func DeriveNewAccount(creator *acm.MutableAccount, permissions permission.AccountPermissions, + logger *logging.Logger) *acm.MutableAccount { // Generate an address sequence := creator.Sequence() logger.TraceMsg("Incrementing sequence number in DeriveNewAccount()", diff --git a/execution/evm/asm/opcodes.go b/execution/evm/asm/opcodes.go index 3017c2138..4467b7aeb 100644 --- a/execution/evm/asm/opcodes.go +++ b/execution/evm/asm/opcodes.go @@ -368,7 +368,7 @@ func (o OpCode) String() string { func (o OpCode) Name() string { str := opCodeNames[o] if len(str) == 0 { - return fmt.Sprintf("Missing opcode 0x%x", int(o)) + return fmt.Sprintf("Non-opcode 0x%x", int(o)) } return str diff --git a/execution/evm/fake_app_state.go b/execution/evm/fake_app_state.go index 8b1bd9ac4..eb2dbd3ac 100644 --- a/execution/evm/fake_app_state.go +++ b/execution/evm/fake_app_state.go @@ -19,8 +19,8 @@ import ( "bytes" - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/state" . "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/crypto" ) diff --git a/execution/evm/log_event_test.go b/execution/evm/log_event_test.go index 7789c3b96..2d2ba41ef 100644 --- a/execution/evm/log_event_test.go +++ b/execution/evm/log_event_test.go @@ -15,20 +15,17 @@ package evm import ( + "testing" + "bytes" - "context" "reflect" - "testing" - "time" - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/state" . "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/event" - "github.com/hyperledger/burrow/execution/events" . "github.com/hyperledger/burrow/execution/evm/asm" - "github.com/hyperledger/burrow/logging" + "github.com/hyperledger/burrow/execution/exec" "github.com/stretchr/testify/require" ) @@ -56,13 +53,8 @@ func TestLog4(t *testing.T) { ourVm := NewVM(newParams(), crypto.ZeroAddress, nil, logger) - emitter := event.NewEmitter(logging.NewNoopLogger()) - - ch := make(chan *events.EventDataLog) - - require.NoError(t, events.SubscribeLogEvent(context.Background(), emitter, "test", account2.Address(), ch)) - - ourVm.SetPublisher(emitter) + txe := new(exec.TxExecution) + ourVm.SetEventSink(txe) var gas uint64 = 100000 @@ -87,18 +79,20 @@ func TestLog4(t *testing.T) { _, err := ourVm.Call(cache, account1, account2, code, []byte{}, 0, &gas) require.NoError(t, err) - select { - case <-time.After(5 * time.Second): - t.Fatalf("timedout waiting for EventDataLog") - case eventDataLog := <-ch: - if !reflect.DeepEqual(eventDataLog.Topics, expectedTopics) { - t.Errorf("Event topics are wrong. Got: %v. Expected: %v", eventDataLog.Topics, expectedTopics) - } - if !bytes.Equal(eventDataLog.Data, expectedData) { - t.Errorf("Event data is wrong. Got: %s. Expected: %s", eventDataLog.Data, expectedData) - } - if eventDataLog.Height != expectedHeight { - t.Errorf("Event block height is wrong. Got: %d. Expected: %d", eventDataLog.Height, expectedHeight) + + for _, ev := range txe.Events { + if ev.Log != nil { + if !reflect.DeepEqual(ev.Log.Topics, expectedTopics) { + t.Errorf("Event topics are wrong. Got: %v. Expected: %v", ev.Log.Topics, expectedTopics) + } + if !bytes.Equal(ev.Log.Data, expectedData) { + t.Errorf("Event data is wrong. Got: %s. Expected: %s", ev.Log.Data, expectedData) + } + if ev.Header.Height != expectedHeight { + t.Errorf("Event block height is wrong. Got: %d. Expected: %d", ev.Header.Height, expectedHeight) + } + return } } + t.Fatalf("Did not see LogEvent") } diff --git a/execution/evm/native.go b/execution/evm/native.go index c4577ea90..74f072aab 100644 --- a/execution/evm/native.go +++ b/execution/evm/native.go @@ -17,8 +17,8 @@ package evm import ( "crypto/sha256" - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/state" . "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/execution/errors" diff --git a/execution/evm/snative.go b/execution/evm/snative.go index 234cfb1a5..06254915b 100644 --- a/execution/evm/snative.go +++ b/execution/evm/snative.go @@ -19,8 +19,8 @@ import ( "strings" - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/state" . "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/execution/errors" @@ -28,7 +28,7 @@ import ( "github.com/hyperledger/burrow/execution/evm/sha3" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" - ptypes "github.com/hyperledger/burrow/permission/types" + "github.com/hyperledger/burrow/permission" ) // @@ -61,7 +61,7 @@ type SNativeFunctionDescription struct { // Function return value Return abi.Return // Permissions required to call function - PermFlag ptypes.PermFlag + PermFlag permission.PermFlag // Native function to which calls will be dispatched when a containing // contract is called with a FunctionSelector matching this NativeContract F NativeContract @@ -98,7 +98,7 @@ func SNativeContracts() map[string]*SNativeContractDescription { abiArg("_role", roleTypeName), }, abiReturn("result", abi.BoolTypeName), - ptypes.AddRole, + permission.AddRole, addRole}, &SNativeFunctionDescription{` @@ -113,7 +113,7 @@ func SNativeContracts() map[string]*SNativeContractDescription { abiArg("_role", roleTypeName), }, abiReturn("result", abi.BoolTypeName), - ptypes.RemoveRole, + permission.RemoveRole, removeRole}, &SNativeFunctionDescription{` @@ -128,7 +128,7 @@ func SNativeContracts() map[string]*SNativeContractDescription { abiArg("_role", roleTypeName), }, abiReturn("result", abi.BoolTypeName), - ptypes.HasRole, + permission.HasRole, hasRole}, &SNativeFunctionDescription{` @@ -145,7 +145,7 @@ func SNativeContracts() map[string]*SNativeContractDescription { abiArg("_set", abi.BoolTypeName), }, abiReturn("result", permFlagTypeName), - ptypes.SetBase, + permission.SetBase, setBase}, &SNativeFunctionDescription{` @@ -159,7 +159,7 @@ func SNativeContracts() map[string]*SNativeContractDescription { abiArg("_account", abi.AddressTypeName), abiArg("_permission", permFlagTypeName)}, abiReturn("result", permFlagTypeName), - ptypes.UnsetBase, + permission.UnsetBase, unsetBase}, &SNativeFunctionDescription{` @@ -173,7 +173,7 @@ func SNativeContracts() map[string]*SNativeContractDescription { abiArg("_account", abi.AddressTypeName), abiArg("_permission", permFlagTypeName)}, abiReturn("result", abi.BoolTypeName), - ptypes.HasBase, + permission.HasBase, hasBase}, &SNativeFunctionDescription{` @@ -187,7 +187,7 @@ func SNativeContracts() map[string]*SNativeContractDescription { abiArg("_permission", permFlagTypeName), abiArg("_set", abi.BoolTypeName)}, abiReturn("result", permFlagTypeName), - ptypes.SetGlobal, + permission.SetGlobal, setGlobal}, ), } @@ -355,9 +355,9 @@ func hasBase(state state.ReaderWriter, caller acm.Account, args []byte, gas *uin if acc == nil { return nil, fmt.Errorf("unknown account %s", address) } - permN := ptypes.PermFlag(Uint64FromWord256(permNum)) // already shifted + permN := permission.PermFlag(Uint64FromWord256(permNum)) // already shifted if !ValidPermN(permN) { - return nil, ptypes.ErrInvalidPermission(permN) + return nil, permission.ErrInvalidPermission(permN) } hasPermission := HasPermission(state, acc, permN) permInt := byteFromBool(hasPermission) @@ -381,9 +381,9 @@ func setBase(stateWriter state.ReaderWriter, caller acm.Account, args []byte, ga if acc == nil { return nil, fmt.Errorf("unknown account %s", address) } - permN := ptypes.PermFlag(Uint64FromWord256(permNum)) + permN := permission.PermFlag(Uint64FromWord256(permNum)) if !ValidPermN(permN) { - return nil, ptypes.ErrInvalidPermission(permN) + return nil, permission.ErrInvalidPermission(permN) } permV := !permVal.IsZero() if err = acc.MutablePermissions().Base.Set(permN, permV); err != nil { @@ -408,9 +408,9 @@ func unsetBase(stateWriter state.ReaderWriter, caller acm.Account, args []byte, if acc == nil { return nil, fmt.Errorf("unknown account %s", address) } - permN := ptypes.PermFlag(Uint64FromWord256(permNum)) + permN := permission.PermFlag(Uint64FromWord256(permNum)) if !ValidPermN(permN) { - return nil, ptypes.ErrInvalidPermission(permN) + return nil, permission.ErrInvalidPermission(permN) } if err = acc.MutablePermissions().Base.Unset(permN); err != nil { return nil, err @@ -434,9 +434,9 @@ func setGlobal(stateWriter state.ReaderWriter, caller acm.Account, args []byte, if acc == nil { panic("cant find the global permissions account") } - permN := ptypes.PermFlag(Uint64FromWord256(permNum)) + permN := permission.PermFlag(Uint64FromWord256(permNum)) if !ValidPermN(permN) { - return nil, ptypes.ErrInvalidPermission(permN) + return nil, permission.ErrInvalidPermission(permN) } permV := !permVal.IsZero() if err = acc.MutablePermissions().Base.Set(permN, permV); err != nil { @@ -518,23 +518,23 @@ func removeRole(stateWriter state.ReaderWriter, caller acm.Account, args []byte, // Errors and utility funcs // Checks if a permission flag is valid (a known base chain or snative permission) -func ValidPermN(n ptypes.PermFlag) bool { - return n <= ptypes.AllPermFlags +func ValidPermN(n permission.PermFlag) bool { + return n <= permission.AllPermFlags } // Get the global BasePermissions -func globalPerms(stateWriter state.ReaderWriter) ptypes.BasePermissions { +func globalPerms(stateWriter state.ReaderWriter) permission.BasePermissions { return state.GlobalAccountPermissions(stateWriter).Base } // Compute the effective permissions from an acm.Account's BasePermissions by // taking the bitwise or with the global BasePermissions resultant permissions -func effectivePermBytes(basePerms ptypes.BasePermissions, - globalPerms ptypes.BasePermissions) []byte { +func effectivePermBytes(basePerms permission.BasePermissions, + globalPerms permission.BasePermissions) []byte { return permBytes(basePerms.ResultantPerms() | globalPerms.ResultantPerms()) } -func permBytes(basePerms ptypes.PermFlag) []byte { +func permBytes(basePerms permission.PermFlag) []byte { return Uint64ToWord256(uint64(basePerms)).Bytes() } diff --git a/execution/evm/snative_test.go b/execution/evm/snative_test.go index e9b4150db..ed02ab80a 100644 --- a/execution/evm/snative_test.go +++ b/execution/evm/snative_test.go @@ -20,15 +20,14 @@ import ( "strings" - acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/acm" . "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/execution/errors" "github.com/hyperledger/burrow/execution/evm/abi" "github.com/hyperledger/burrow/execution/evm/asm/bc" "github.com/hyperledger/burrow/execution/evm/sha3" - permission "github.com/hyperledger/burrow/permission/types" - ptypes "github.com/hyperledger/burrow/permission/types" + "github.com/hyperledger/burrow/permission" "github.com/stretchr/testify/assert" ) @@ -128,13 +127,13 @@ func funcIDFromHex(t *testing.T, hexString string) abi.FunctionSelector { return abi.FirstFourBytes(bs) } -func permFlagToWord256(permFlag ptypes.PermFlag) Word256 { +func permFlagToWord256(permFlag permission.PermFlag) Word256 { return Uint64ToWord256(uint64(permFlag)) } -func allAccountPermissions() ptypes.AccountPermissions { - return ptypes.AccountPermissions{ - Base: ptypes.BasePermissions{ +func allAccountPermissions() permission.AccountPermissions { + return permission.AccountPermissions{ + Base: permission.BasePermissions{ Perms: permission.AllPermFlags, SetBit: permission.AllPermFlags, }, diff --git a/execution/evm/vm.go b/execution/evm/vm.go index dda39f001..53d9b1ebc 100644 --- a/execution/evm/vm.go +++ b/execution/evm/vm.go @@ -21,17 +21,16 @@ import ( "math/big" "strings" - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/state" . "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/event" "github.com/hyperledger/burrow/execution/errors" - "github.com/hyperledger/burrow/execution/events" . "github.com/hyperledger/burrow/execution/evm/asm" "github.com/hyperledger/burrow/execution/evm/sha3" + "github.com/hyperledger/burrow/execution/exec" "github.com/hyperledger/burrow/logging" - ptypes "github.com/hyperledger/burrow/permission/types" + "github.com/hyperledger/burrow/permission" "github.com/hyperledger/burrow/txs" ) @@ -40,6 +39,16 @@ const ( callStackCapacity = 100 // TODO ensure usage. ) +type EventSink interface { + Call(call *exec.CallEvent, exception *errors.Exception) + Log(log *exec.LogEvent) +} + +type noopEventSink struct{} + +func (*noopEventSink) Call(call *exec.CallEvent, exception *errors.Exception) {} +func (*noopEventSink) Log(log *exec.LogEvent) {} + type Params struct { BlockHeight uint64 BlockHash Word256 @@ -54,7 +63,7 @@ type VM struct { tx *txs.Tx stackDepth uint64 nestedCallErrors []errors.NestedCall - publisher event.Publisher + eventSink EventSink logger *logging.Logger returnData []byte debugOpcodes bool @@ -68,6 +77,7 @@ func NewVM(params Params, origin crypto.Address, tx *txs.Tx, logger *logging.Log origin: origin, stackDepth: 0, tx: tx, + eventSink: &noopEventSink{}, logger: logger.WithScope("NewVM"), } for _, option := range options { @@ -82,9 +92,9 @@ func (vm *VM) Debugf(format string, a ...interface{}) { } } -// satisfies go_events.Eventable -func (vm *VM) SetPublisher(publisher event.Publisher) { - vm.publisher = publisher +// Set EventSink destination for events - can be unset if events generation is not required +func (vm *VM) SetEventSink(em EventSink) { + vm.eventSink = em } // CONTRACT: it is the duty of the contract writer to call known permissions @@ -93,29 +103,25 @@ func (vm *VM) SetPublisher(publisher event.Publisher) { // on known permissions and panics else) // If the perm is not defined in the acc nor set by default in GlobalPermissions, // this function returns false. -func HasPermission(stateWriter state.ReaderWriter, acc acm.Account, perm ptypes.PermFlag) bool { +func HasPermission(stateWriter state.ReaderWriter, acc acm.Account, perm permission.PermFlag) bool { value, _ := acc.Permissions().Base.Compose(state.GlobalAccountPermissions(stateWriter).Base).Get(perm) return value } func (vm *VM) fireCallEvent(exception *errors.CodedError, output *[]byte, callerAddress, calleeAddress crypto.Address, input []byte, value uint64, gas *uint64) { // fire the post call event (including exception if applicable) - if vm.publisher != nil { - events.PublishAccountCall(vm.publisher, vm.tx, vm.params.BlockHeight, - &events.EventDataCall{ - CallData: &events.CallData{ - Caller: callerAddress, - Callee: calleeAddress, - Data: input, - Value: value, - Gas: *gas, - }, - Origin: vm.origin, - StackDepth: vm.stackDepth, - Return: *output, - Exception: errors.AsCodedError(*exception), - }) - } + vm.eventSink.Call(&exec.CallEvent{ + CallData: &exec.CallData{ + Caller: callerAddress, + Callee: calleeAddress, + Data: input, + Value: value, + Gas: *gas, + }, + Origin: vm.origin, + StackDepth: vm.stackDepth, + Return: *output, + }, errors.AsException(*exception)) } // CONTRACT state is aware of caller and callee, so we can just mutate them. @@ -124,7 +130,7 @@ func (vm *VM) fireCallEvent(exception *errors.CodedError, output *[]byte, caller // value: To be transferred from caller to callee. Refunded upon errors.CodedError. // gas: Available gas. No refunds for gas. // code: May be nil, since the CALL opcode may be used to send value from contracts to accounts -func (vm *VM) Call(callState *state.Cache, caller, callee acm.MutableAccount, code, input []byte, value uint64, gas *uint64) (output []byte, err errors.CodedError) { +func (vm *VM) Call(callState *state.Cache, caller, callee *acm.MutableAccount, code, input []byte, value uint64, gas *uint64) (output []byte, err errors.CodedError) { exception := new(errors.CodedError) // fire the post call event (including exception if applicable) @@ -168,7 +174,7 @@ func (vm *VM) Call(callState *state.Cache, caller, callee acm.MutableAccount, co // The intent of delegate call is to run the code of the callee in the storage context of the caller; // while preserving the original caller to the previous callee. // Different to the normal CALL or CALLCODE, the value does not need to be transferred to the callee. -func (vm *VM) DelegateCall(callState *state.Cache, caller acm.Account, callee acm.MutableAccount, code, input []byte, value uint64, gas *uint64) (output []byte, err errors.CodedError) { +func (vm *VM) DelegateCall(callState *state.Cache, caller acm.Account, callee *acm.MutableAccount, code, input []byte, value uint64, gas *uint64) (output []byte, err errors.CodedError) { exception := new(string) // fire the post call event (including exception if applicable) @@ -208,7 +214,7 @@ func useGasNegative(gasLeft *uint64, gasToUse uint64, err *errors.CodedError) bo } // Just like Call() but does not transfer 'value' or modify the callDepth. -func (vm *VM) call(callState *state.Cache, caller acm.Account, callee acm.MutableAccount, code, input []byte, value uint64, gas *uint64) (output []byte, err errors.CodedError) { +func (vm *VM) call(callState *state.Cache, caller acm.Account, callee *acm.MutableAccount, code, input []byte, value uint64, gas *uint64) (output []byte, err errors.CodedError) { vm.Debugf("(%d) (%X) %X (code=%d) gas: %v (d) %X\n", vm.stackDepth, caller.Address().Bytes()[:4], callee.Address(), len(callee.Code()), *gas, input) @@ -838,25 +844,18 @@ func (vm *VM) call(callState *state.Cache, caller acm.Account, callee acm.Mutabl vm.Debugf(" => Memory err: %s", memErr) return nil, firstErr(err, errors.ErrorCodeMemoryOutOfBounds) } - if vm.publisher != nil { - publishErr := events.PublishLogEvent(vm.publisher, vm.tx, &events.EventDataLog{ - Height: vm.params.BlockHeight, - Address: callee.Address(), - Topics: topics, - Data: data, - }) - if publishErr != nil { - vm.Debugf(" => Log event publish err: %s", publishErr) - return nil, firstErr(err, errors.ErrorCodeEventPublish) - } - } + vm.eventSink.Log(&exec.LogEvent{ + Address: callee.Address(), + Topics: topics, + Data: data, + }) vm.Debugf(" => T:%X D:%X\n", topics, data) case CREATE: // 0xF0 vm.returnData = nil - if !HasPermission(callState, callee, ptypes.CreateContract) { - return nil, errors.PermissionDenied{Perm: ptypes.CreateContract} + if !HasPermission(callState, callee, permission.CreateContract) { + return nil, errors.PermissionDenied{Perm: permission.CreateContract} } contractValue, popErr := stack.PopU64() if popErr != nil { @@ -902,8 +901,8 @@ func (vm *VM) call(callState *state.Cache, caller acm.Account, callee acm.Mutabl case CALL, CALLCODE, DELEGATECALL: // 0xF1, 0xF2, 0xF4 vm.returnData = nil - if !HasPermission(callState, callee, ptypes.Call) { - return nil, errors.PermissionDenied{Perm: ptypes.Call} + if !HasPermission(callState, callee, permission.Call) { + return nil, errors.PermissionDenied{Perm: permission.Call} } gasLimit, popErr := stack.PopU64() if popErr != nil { @@ -982,8 +981,8 @@ func (vm *VM) call(callState *state.Cache, caller acm.Account, callee acm.Mutabl } else { // nil account means we're sending funds to a new account if acc == nil { - if !HasPermission(callState, caller, ptypes.CreateAccount) { - return nil, errors.PermissionDenied{Perm: ptypes.CreateAccount} + if !HasPermission(callState, caller, permission.CreateAccount) { + return nil, errors.PermissionDenied{Perm: permission.CreateAccount} } acc = acm.ConcreteAccount{Address: crypto.AddressFromWord256(addr)}.MutableAccount() } @@ -1077,8 +1076,8 @@ func (vm *VM) call(callState *state.Cache, caller acm.Account, callee acm.Mutabl if useGasNegative(gas, GasCreateAccount, &gasErr) { return nil, firstErr(err, gasErr) } - if !HasPermission(callState, callee, ptypes.CreateContract) { - return nil, firstErr(err, errors.PermissionDenied{Perm: ptypes.CreateContract}) + if !HasPermission(callState, callee, permission.CreateContract) { + return nil, firstErr(err, errors.PermissionDenied{Perm: permission.CreateContract}) } var createErr errors.CodedError receiver, createErr = vm.createAccount(callState, callee, logger) @@ -1088,7 +1087,7 @@ func (vm *VM) call(callState *state.Cache, caller acm.Account, callee acm.Mutabl } - receiver, errAdd := receiver.AddToBalance(callee.Balance()) + errAdd := receiver.AddToBalance(callee.Balance()) if errAdd != nil { return nil, firstErr(err, errAdd) } @@ -1101,25 +1100,25 @@ func (vm *VM) call(callState *state.Cache, caller acm.Account, callee acm.Mutabl return nil, nil case STATICCALL, CREATE2: - return nil, errors.Errorf("%s not yet implemented", op.Name()) + return nil, errors.Errorf("%v not yet implemented", op) default: - vm.Debugf("(pc) %-3v Unknown opcode %X\n", pc, op) - return nil, errors.Errorf("unknown opcode %X", op) + vm.Debugf("(pc) %-3v Unknown opcode %v\n", pc, op) + return nil, errors.Errorf("unknown opcode %v", op) } pc++ } } -func (vm *VM) createAccount(callState *state.Cache, callee acm.MutableAccount, logger *logging.Logger) (acm.MutableAccount, errors.CodedError) { +func (vm *VM) createAccount(callState *state.Cache, callee *acm.MutableAccount, logger *logging.Logger) (*acm.MutableAccount, errors.CodedError) { newAccount := DeriveNewAccount(callee, state.GlobalAccountPermissions(callState), logger) err := callState.UpdateAccount(newAccount) if err != nil { - return nil, errors.AsCodedError(err) + return nil, errors.AsException(err) } err = callState.UpdateAccount(callee) if err != nil { - return nil, errors.AsCodedError(err) + return nil, errors.AsException(err) } return newAccount, nil } @@ -1168,20 +1167,20 @@ func (vm *VM) jump(code []byte, to int64, pc *int64) (err errors.CodedError) { func firstErr(errA, errB error) errors.CodedError { if errA != nil { - return errors.AsCodedError(errA) + return errors.AsException(errA) } else { - return errors.AsCodedError(errB) + return errors.AsException(errB) } } -func transfer(from, to acm.MutableAccount, amount uint64) errors.CodedError { +func transfer(from, to *acm.MutableAccount, amount uint64) errors.CodedError { if from.Balance() < amount { return errors.ErrorCodeInsufficientBalance } else { from.SubtractFromBalance(amount) - _, err := to.AddToBalance(amount) + err := to.AddToBalance(amount) if err != nil { - return errors.AsCodedError(err) + return errors.AsException(err) } } return nil diff --git a/execution/evm/vm_test.go b/execution/evm/vm_test.go index 62d1ca3b8..5b7224d17 100644 --- a/execution/evm/vm_test.go +++ b/execution/evm/vm_test.go @@ -15,25 +15,22 @@ package evm import ( - "context" "encoding/hex" "fmt" "strconv" "testing" "time" - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/state" . "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/event" "github.com/hyperledger/burrow/execution/errors" - "github.com/hyperledger/burrow/execution/events" . "github.com/hyperledger/burrow/execution/evm/asm" . "github.com/hyperledger/burrow/execution/evm/asm/bc" + "github.com/hyperledger/burrow/execution/exec" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/permission" - ptypes "github.com/hyperledger/burrow/permission/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "golang.org/x/crypto/ripemd160" @@ -65,7 +62,7 @@ func newParams() Params { } } -func newAccount(seed ...byte) acm.MutableAccount { +func newAccount(seed ...byte) *acm.MutableAccount { hasher := ripemd160.New() hasher.Write(seed) return acm.ConcreteAccount{ @@ -697,14 +694,16 @@ func TestSendCall(t *testing.T) { //---------------------------------------------- // give account2 sufficient balance, should pass - account2, err = newAccount(2).AddToBalance(100000) + account2 = newAccount(2) + err = account2.AddToBalance(100000) require.NoError(t, err) _, err = runVMWaitError(cache, ourVm, account1, account2, addr, contractCode, 1000) assert.NoError(t, err, "Should have sufficient balance") //---------------------------------------------- // insufficient gas, should fail - account2, err = newAccount(2).AddToBalance(100000) + account2 = newAccount(2) + err = account2.AddToBalance(100000) require.NoError(t, err) _, err = runVMWaitError(cache, ourVm, account1, account2, addr, contractCode, 100) assert.NoError(t, err, "Expected insufficient gas error") @@ -996,7 +995,7 @@ func returnWord() []byte { } func makeAccountWithCode(accountUpdater state.AccountUpdater, name string, - code []byte) (acm.MutableAccount, crypto.Address) { + code []byte) (*acm.MutableAccount, crypto.Address) { address, _ := crypto.AddressFromBytes([]byte(name)) account := acm.ConcreteAccount{ Address: address, @@ -1012,43 +1011,34 @@ func makeAccountWithCode(accountUpdater state.AccountUpdater, name string, // and then waits for any exceptions transmitted by Data in the AccCall // event (in the case of no direct error from call we will block waiting for // at least 1 AccCall event) -func runVMWaitError(vmCache *state.Cache, ourVm *VM, caller, callee acm.MutableAccount, subscribeAddr crypto.Address, +func runVMWaitError(vmCache *state.Cache, ourVm *VM, caller, callee *acm.MutableAccount, subscribeAddr crypto.Address, contractCode []byte, gas uint64) ([]byte, error) { - eventCh := make(chan *events.EventDataCall) - output, err := runVM(eventCh, vmCache, ourVm, caller, callee, subscribeAddr, contractCode, gas) + txe := new(exec.TxExecution) + output, err := runVM(txe, vmCache, ourVm, caller, callee, subscribeAddr, contractCode, gas) if err != nil { return output, err } - select { - case eventDataCall := <-eventCh: - if eventDataCall.Exception != nil { - return output, eventDataCall.Exception + if len(txe.Events) > 0 { + ex := txe.Events[0].Header.Exception + if ex != nil { + return output, ex } - return output, nil } + return output, nil } // Subscribes to an AccCall, runs the vm, returns the output and any direct // exception -func runVM(eventCh chan<- *events.EventDataCall, vmCache *state.Cache, ourVm *VM, caller, callee acm.MutableAccount, +func runVM(sink EventSink, vmCache *state.Cache, ourVm *VM, caller, callee *acm.MutableAccount, subscribeAddr crypto.Address, contractCode []byte, gas uint64) ([]byte, error) { - // we need to catch the event from the CALL to check for exceptions - em := event.NewEmitter(logging.NewNoopLogger()) fmt.Printf("subscribe to %s\n", subscribeAddr) - err := events.SubscribeAccountCall(context.Background(), em, "test", subscribeAddr, - nil, -1, eventCh) - if err != nil { - return nil, err - } - evc := event.NewCache() - ourVm.SetPublisher(evc) + ourVm.SetEventSink(sink) start := time.Now() output, err := ourVm.Call(vmCache, caller, callee, contractCode, []byte{}, 0, &gas) fmt.Printf("Output: %v Error: %v\n", output, err) fmt.Println("Call took:", time.Since(start)) - evc.Flush(em) return output, err } @@ -1155,7 +1145,7 @@ func TestSubslice(t *testing.T) { func TestHasPermission(t *testing.T) { st := newAppState() acc := acm.ConcreteAccount{ - Permissions: ptypes.AccountPermissions{ + Permissions: permission.AccountPermissions{ Base: BasePermissionsFromStrings(t, "00100001000111", "11011110111000"), @@ -1165,15 +1155,15 @@ func TestHasPermission(t *testing.T) { assert.True(t, HasPermission(st, acc, PermFlagFromString(t, "100001000110"))) } -func BasePermissionsFromStrings(t *testing.T, perms, setBit string) ptypes.BasePermissions { - return ptypes.BasePermissions{ +func BasePermissionsFromStrings(t *testing.T, perms, setBit string) permission.BasePermissions { + return permission.BasePermissions{ Perms: PermFlagFromString(t, perms), SetBit: PermFlagFromString(t, setBit), } } -func PermFlagFromString(t *testing.T, binaryString string) ptypes.PermFlag { +func PermFlagFromString(t *testing.T, binaryString string) permission.PermFlag { permFlag, err := strconv.ParseUint(binaryString, 2, 64) require.NoError(t, err) - return ptypes.PermFlag(permFlag) + return permission.PermFlag(permFlag) } diff --git a/execution/exec/block_execution.go b/execution/exec/block_execution.go new file mode 100644 index 000000000..3fc8a905d --- /dev/null +++ b/execution/exec/block_execution.go @@ -0,0 +1,99 @@ +package exec + +import ( + "fmt" + + "encoding/json" + + "github.com/gogo/protobuf/proto" + "github.com/hyperledger/burrow/event" + "github.com/hyperledger/burrow/event/query" + "github.com/hyperledger/burrow/txs" + abciTypes "github.com/tendermint/abci/types" +) + +func EventStringBlockExecution(height uint64) string { return fmt.Sprintf("Execution/Block/%v", height) } + +func DecodeBlockExecution(bs []byte) (*BlockExecution, error) { + be := new(BlockExecution) + err := cdc.UnmarshalBinary(bs, be) + if err != nil { + return nil, err + } + return be, nil +} + +func (be *BlockExecution) Encode() ([]byte, error) { + return cdc.MarshalBinary(be) +} + +func (*BlockExecution) EventType() EventType { + return TypeBlockExecution +} + +func (be *BlockExecution) Tx(txEnv *txs.Envelope) *TxExecution { + txe := NewTxExecution(txEnv) + be.Append(txe) + return txe +} + +func (be *BlockExecution) Append(tail ...*TxExecution) { + for i, txe := range tail { + txe.Index = uint64(len(be.TxExecutions) + i) + txe.Height = be.Height + } + be.TxExecutions = append(be.TxExecutions, tail...) +} + +// Tags +type TaggedBlockExecution struct { + query.Tagged + *BlockExecution +} + +func (be *BlockExecution) Tagged() *TaggedBlockExecution { + return &TaggedBlockExecution{ + Tagged: query.MergeTags( + query.TagMap{ + event.EventIDKey: EventStringBlockExecution(be.Height), + event.EventTypeKey: be.EventType(), + }, + query.MustReflectTags(be), + query.MustReflectTags(be.BlockHeader), + ), + BlockExecution: be, + } +} + +// TODO remove when Header gogo protobuf fixed in Tendermint +func BlockHeaderFromHeader(header *abciTypes.Header) *BlockHeader { + if header == nil { + return nil + } + bs, _ := json.Marshal(header) + return &BlockHeader{ + JSON: string(bs), + NumTxs: header.NumTxs, + } +} + +type ABCIHeader struct { + *abciTypes.Header +} + +// Gogo proto support +func (h *ABCIHeader) Marshal() ([]byte, error) { + return proto.Marshal(h.Header) +} + +func (h *ABCIHeader) Unmarshal(data []byte) error { + return proto.Unmarshal(data, h.Header) +} + +func QueryForBlockExecutionFromHeight(height uint64) *query.Builder { + return QueryForBlockExecution().AndGreaterThanOrEqual(event.HeightKey, height) +} + +func QueryForBlockExecution() *query.Builder { + return query.NewBuilder().AndEquals(event.EventTypeKey, TypeBlockExecution) +} diff --git a/execution/exec/block_execution_test.go b/execution/exec/block_execution_test.go new file mode 100644 index 000000000..5a02fd564 --- /dev/null +++ b/execution/exec/block_execution_test.go @@ -0,0 +1,24 @@ +package exec + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestBlockExecution_Marshal(t *testing.T) { + be := &BlockExecution{ + // TODO: reenable when tendermint Header works GRPC + //BlockHeader: &abciTypes.Header{ + // Height: 3, + // AppHash: []byte{2}, + // Proposer: abciTypes.Validator{ + // Power: 34, + // }, + //}, + } + bs, err := be.Marshal() + require.NoError(t, err) + beOut := new(BlockExecution) + require.NoError(t, beOut.Unmarshal(bs)) +} diff --git a/execution/exec/codec.go b/execution/exec/codec.go new file mode 100644 index 000000000..beb9d32a7 --- /dev/null +++ b/execution/exec/codec.go @@ -0,0 +1,5 @@ +package exec + +import "github.com/hyperledger/burrow/txs" + +var cdc = txs.NewAminoCodec() diff --git a/execution/exec/event.go b/execution/exec/event.go new file mode 100644 index 000000000..b629a265c --- /dev/null +++ b/execution/exec/event.go @@ -0,0 +1,120 @@ +package exec + +import ( + "reflect" + + "fmt" + + "github.com/hyperledger/burrow/event" + "github.com/hyperledger/burrow/event/query" +) + +var eventMessageTag = query.TagMap{event.MessageTypeKey: reflect.TypeOf(&Event{}).String()} + +type EventType uint32 + +// Execution event types +const ( + TypeCall = EventType(0x00) + TypeLog = EventType(0x01) + TypeAccountInput = EventType(0x02) + TypeAccountOutput = EventType(0x03) + TypeTxExecution = EventType(0x04) + TypeBlockExecution = EventType(0x05) +) + +var nameFromType = map[EventType]string{ + TypeCall: "CallEvent", + TypeLog: "LogEvent", + TypeAccountInput: "AccountInputEvent", + TypeAccountOutput: "AccountOutputEvent", + TypeTxExecution: "TxExecutionEvent", + TypeBlockExecution: "BlockExecutionEvent", +} + +var typeFromName = make(map[string]EventType) + +func init() { + for t, n := range nameFromType { + typeFromName[n] = t + } +} + +func EventTypeFromString(name string) EventType { + return typeFromName[name] +} + +func (ev *Event) EventType() EventType { + return ev.Header.EventType +} + +func (typ EventType) String() string { + name, ok := nameFromType[typ] + if ok { + return name + } + return "UnknownTx" +} + +func (typ EventType) MarshalText() ([]byte, error) { + return []byte(typ.String()), nil +} + +func (typ *EventType) UnmarshalText(data []byte) error { + *typ = EventTypeFromString(string(data)) + return nil +} + +// Event + +func (ev *Event) String() string { + return fmt.Sprintf("ExecutionEvent{%v: %s}", ev.Header.String(), ev.Body()) +} + +func (ev *Event) Body() string { + if ev.Input != nil { + return ev.Input.String() + } + if ev.Output != nil { + return ev.Output.String() + } + if ev.Log != nil { + return ev.Log.String() + } + if ev.Call != nil { + return ev.Call.String() + } + return "" +} + +// Tags +type TaggedEvent struct { + query.Tagged + *Event +} + +type TaggedEvents []*TaggedEvent + +func (ev *Event) Tagged() *TaggedEvent { + return &TaggedEvent{ + Tagged: query.MergeTags( + query.MustReflectTags(ev.Header), + eventMessageTag, + query.MustReflectTags(ev.Input), + query.MustReflectTags(ev.Output), + query.MustReflectTags(ev.Call), + ev.Log, + ), + Event: ev, + } +} + +func (tevs TaggedEvents) Filter(qry query.Query) TaggedEvents { + var filtered TaggedEvents + for _, tev := range tevs { + if qry.Matches(tev) { + filtered = append(filtered, tev) + } + } + return filtered +} diff --git a/execution/exec/event_test.go b/execution/exec/event_test.go new file mode 100644 index 000000000..e1e12072f --- /dev/null +++ b/execution/exec/event_test.go @@ -0,0 +1,72 @@ +package exec + +import ( + "testing" + + "github.com/hyperledger/burrow/binary" + "github.com/hyperledger/burrow/crypto" + "github.com/hyperledger/burrow/event" + "github.com/hyperledger/burrow/event/query" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/tmthrgd/go-hex" +) + +func TestEventTagQueries(t *testing.T) { + addressHex := "DEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF" + address, err := crypto.AddressFromHexString(addressHex) + require.NoError(t, err) + ev := &Event{ + Header: &Header{ + EventType: TypeLog, + EventID: "foo/bar", + TxHash: []byte{2, 3, 4}, + Height: 34, + Index: 2, + }, + Log: &LogEvent{ + Address: address, + Topics: []binary.Word256{binary.RightPadWord256([]byte("marmot"))}, + }, + } + + tev := ev.Tagged() + + qb := query.NewBuilder().AndEquals(event.EventTypeKey, TypeLog.String()) + qry, err := qb.Query() + require.NoError(t, err) + assert.True(t, qry.Matches(tev)) + + qb = qb.AndContains(event.EventIDKey, "bar") + qry, err = qb.Query() + require.NoError(t, err) + assert.True(t, qry.Matches(tev)) + + qb = qb.AndEquals(event.TxHashKey, hex.EncodeUpperToString(tev.Header.TxHash)) + qry, err = qb.Query() + require.NoError(t, err) + assert.True(t, qry.Matches(tev)) + + qb = qb.AndGreaterThanOrEqual(event.HeightKey, tev.Header.Height) + qry, err = qb.Query() + require.NoError(t, err) + assert.True(t, qry.Matches(tev)) + + qb = qb.AndStrictlyLessThan(event.IndexKey, tev.Header.Index+1) + qry, err = qb.Query() + require.NoError(t, err) + assert.True(t, qry.Matches(tev)) + + qb = qb.AndEquals(event.AddressKey, addressHex) + qry, err = qb.Query() + require.NoError(t, err) + assert.True(t, qry.Matches(tev)) + + qb = qb.AndEquals(LogNTextKey(0), "marmot") + qry, err = qb.Query() + require.NoError(t, err) + assert.True(t, qry.Matches(tev)) + + t.Logf("Query: %v", qry) + t.Logf("Keys: %v", tev.Keys()) +} diff --git a/execution/exec/exec.pb.go b/execution/exec/exec.pb.go new file mode 100644 index 000000000..6c7cfe26c --- /dev/null +++ b/execution/exec/exec.pb.go @@ -0,0 +1,3216 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: exec.proto + +/* + Package exec is a generated protocol buffer package. + + It is generated from these files: + exec.proto + + It has these top-level messages: + BlockExecution + BlockHeader + TxExecution + Header + Event + Result + LogEvent + CallEvent + InputEvent + OutputEvent + CallData +*/ +package exec + +import proto "github.com/gogo/protobuf/proto" +import golang_proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" +import _ "github.com/gogo/protobuf/gogoproto" +import _ "github.com/tendermint/abci/types" +import errors "github.com/hyperledger/burrow/execution/errors" +import names "github.com/hyperledger/burrow/execution/names" +import txs "github.com/hyperledger/burrow/txs" +import permission "github.com/hyperledger/burrow/permission" + +import github_com_hyperledger_burrow_txs_payload "github.com/hyperledger/burrow/txs/payload" +import github_com_hyperledger_burrow_binary "github.com/hyperledger/burrow/binary" +import github_com_hyperledger_burrow_txs "github.com/hyperledger/burrow/txs" +import github_com_hyperledger_burrow_crypto "github.com/hyperledger/burrow/crypto" + +import io "io" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = golang_proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package + +type BlockExecution struct { + // The height of this block + Height uint64 `protobuf:"varint,1,opt,name=Height,proto3" json:"Height,omitempty"` + // TODO: reintroduce this when upstream merges: https://github.com/tendermint/tendermint/pull/1987 + // types.Header BlockHeader = 2; + BlockHeader *BlockHeader `protobuf:"bytes,2,opt,name=BlockHeader" json:"BlockHeader,omitempty"` + TxExecutions []*TxExecution `protobuf:"bytes,3,rep,name=TxExecutions" json:"TxExecutions,omitempty"` +} + +func (m *BlockExecution) Reset() { *m = BlockExecution{} } +func (m *BlockExecution) String() string { return proto.CompactTextString(m) } +func (*BlockExecution) ProtoMessage() {} +func (*BlockExecution) Descriptor() ([]byte, []int) { return fileDescriptorExec, []int{0} } + +func (m *BlockExecution) GetHeight() uint64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *BlockExecution) GetBlockHeader() *BlockHeader { + if m != nil { + return m.BlockHeader + } + return nil +} + +func (m *BlockExecution) GetTxExecutions() []*TxExecution { + if m != nil { + return m.TxExecutions + } + return nil +} + +func (*BlockExecution) XXX_MessageName() string { + return "exec.BlockExecution" +} + +type BlockHeader struct { + JSON string `protobuf:"bytes,1,opt,name=JSON,proto3" json:"JSON,omitempty"` + NumTxs int32 `protobuf:"varint,2,opt,name=NumTxs,proto3" json:"NumTxs,omitempty"` +} + +func (m *BlockHeader) Reset() { *m = BlockHeader{} } +func (m *BlockHeader) String() string { return proto.CompactTextString(m) } +func (*BlockHeader) ProtoMessage() {} +func (*BlockHeader) Descriptor() ([]byte, []int) { return fileDescriptorExec, []int{1} } + +func (m *BlockHeader) GetJSON() string { + if m != nil { + return m.JSON + } + return "" +} + +func (m *BlockHeader) GetNumTxs() int32 { + if m != nil { + return m.NumTxs + } + return 0 +} + +func (*BlockHeader) XXX_MessageName() string { + return "exec.BlockHeader" +} + +type TxExecution struct { + // Transaction type + TxType github_com_hyperledger_burrow_txs_payload.Type `protobuf:"varint,2,opt,name=TxType,proto3,casttype=github.com/hyperledger/burrow/txs/payload.Type" json:"TxType,omitempty"` + // The hash of the transaction that caused this event to be generated + TxHash github_com_hyperledger_burrow_binary.HexBytes `protobuf:"bytes,3,opt,name=TxHash,proto3,customtype=github.com/hyperledger/burrow/binary.HexBytes" json:"TxHash"` + // The block height at which this Tx was included + Height uint64 `protobuf:"varint,4,opt,name=Height,proto3" json:"Height,omitempty"` + // The index of this transaction within the block + Index uint64 `protobuf:"varint,5,opt,name=Index,proto3" json:"Index,omitempty"` + // Signed Tx that triggered this execution + Envelope *github_com_hyperledger_burrow_txs.Envelope `protobuf:"bytes,6,opt,name=Envelope,customtype=github.com/hyperledger/burrow/txs.Envelope" json:"Envelope,omitempty"` + // Execution events + Events []*Event `protobuf:"bytes,7,rep,name=Events" json:"Events,omitempty"` + // The execution results + Result *Result `protobuf:"bytes,8,opt,name=Result" json:"Result,omitempty"` + // The transaction receipt + Receipt *txs.Receipt `protobuf:"bytes,9,opt,name=Receipt" json:"Receipt,omitempty"` + // If execution was an exception + Exception *errors.Exception `protobuf:"bytes,10,opt,name=Exception" json:"Exception,omitempty"` +} + +func (m *TxExecution) Reset() { *m = TxExecution{} } +func (m *TxExecution) String() string { return proto.CompactTextString(m) } +func (*TxExecution) ProtoMessage() {} +func (*TxExecution) Descriptor() ([]byte, []int) { return fileDescriptorExec, []int{2} } + +func (m *TxExecution) GetTxType() github_com_hyperledger_burrow_txs_payload.Type { + if m != nil { + return m.TxType + } + return 0 +} + +func (m *TxExecution) GetHeight() uint64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *TxExecution) GetIndex() uint64 { + if m != nil { + return m.Index + } + return 0 +} + +func (m *TxExecution) GetEvents() []*Event { + if m != nil { + return m.Events + } + return nil +} + +func (m *TxExecution) GetResult() *Result { + if m != nil { + return m.Result + } + return nil +} + +func (m *TxExecution) GetReceipt() *txs.Receipt { + if m != nil { + return m.Receipt + } + return nil +} + +func (m *TxExecution) GetException() *errors.Exception { + if m != nil { + return m.Exception + } + return nil +} + +func (*TxExecution) XXX_MessageName() string { + return "exec.TxExecution" +} + +type Header struct { + // Transaction type + TxType github_com_hyperledger_burrow_txs_payload.Type `protobuf:"varint,1,opt,name=TxType,proto3,casttype=github.com/hyperledger/burrow/txs/payload.Type" json:"TxType,omitempty"` + // The hash of the transaction that caused this event to be generated + TxHash github_com_hyperledger_burrow_binary.HexBytes `protobuf:"bytes,2,opt,name=TxHash,proto3,customtype=github.com/hyperledger/burrow/binary.HexBytes" json:"TxHash"` + // The type of event + EventType EventType `protobuf:"varint,3,opt,name=EventType,proto3,casttype=EventType" json:"EventType,omitempty"` + // EventID published with event + EventID string `protobuf:"bytes,4,opt,name=EventID,proto3" json:"EventID,omitempty"` + // The block height at which this event was emitted + Height uint64 `protobuf:"varint,5,opt,name=Height,proto3" json:"Height,omitempty"` + // The index of this event relative to other events generated by the same transaction + Index uint64 `protobuf:"varint,6,opt,name=Index,proto3" json:"Index,omitempty"` + // If event is exception + Exception *errors.Exception `protobuf:"bytes,7,opt,name=Exception" json:"Exception,omitempty"` +} + +func (m *Header) Reset() { *m = Header{} } +func (*Header) ProtoMessage() {} +func (*Header) Descriptor() ([]byte, []int) { return fileDescriptorExec, []int{3} } + +func (m *Header) GetTxType() github_com_hyperledger_burrow_txs_payload.Type { + if m != nil { + return m.TxType + } + return 0 +} + +func (m *Header) GetEventType() EventType { + if m != nil { + return m.EventType + } + return 0 +} + +func (m *Header) GetEventID() string { + if m != nil { + return m.EventID + } + return "" +} + +func (m *Header) GetHeight() uint64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *Header) GetIndex() uint64 { + if m != nil { + return m.Index + } + return 0 +} + +func (m *Header) GetException() *errors.Exception { + if m != nil { + return m.Exception + } + return nil +} + +func (*Header) XXX_MessageName() string { + return "exec.Header" +} + +type Event struct { + Header *Header `protobuf:"bytes,1,opt,name=Header" json:"Header,omitempty"` + Input *InputEvent `protobuf:"bytes,2,opt,name=Input" json:"Input,omitempty"` + Output *OutputEvent `protobuf:"bytes,3,opt,name=Output" json:"Output,omitempty"` + Call *CallEvent `protobuf:"bytes,4,opt,name=Call" json:"Call,omitempty"` + Log *LogEvent `protobuf:"bytes,5,opt,name=Log" json:"Log,omitempty"` +} + +func (m *Event) Reset() { *m = Event{} } +func (*Event) ProtoMessage() {} +func (*Event) Descriptor() ([]byte, []int) { return fileDescriptorExec, []int{4} } + +func (m *Event) GetHeader() *Header { + if m != nil { + return m.Header + } + return nil +} + +func (m *Event) GetInput() *InputEvent { + if m != nil { + return m.Input + } + return nil +} + +func (m *Event) GetOutput() *OutputEvent { + if m != nil { + return m.Output + } + return nil +} + +func (m *Event) GetCall() *CallEvent { + if m != nil { + return m.Call + } + return nil +} + +func (m *Event) GetLog() *LogEvent { + if m != nil { + return m.Log + } + return nil +} + +func (*Event) XXX_MessageName() string { + return "exec.Event" +} + +// Could structure this further if needed - sum type of various results relevant to different transaction types +type Result struct { + // EVM execution return + Return []byte `protobuf:"bytes,1,opt,name=Return,proto3" json:"Return,omitempty"` + // Gas used in computation + GasUsed uint64 `protobuf:"varint,2,opt,name=GasUsed,proto3" json:"GasUsed,omitempty"` + // Name entry created + NameEntry *names.Entry `protobuf:"bytes,3,opt,name=NameEntry" json:"NameEntry,omitempty"` + // Permission update performed + PermArgs *permission.PermArgs `protobuf:"bytes,4,opt,name=PermArgs" json:"PermArgs,omitempty"` +} + +func (m *Result) Reset() { *m = Result{} } +func (m *Result) String() string { return proto.CompactTextString(m) } +func (*Result) ProtoMessage() {} +func (*Result) Descriptor() ([]byte, []int) { return fileDescriptorExec, []int{5} } + +func (m *Result) GetReturn() []byte { + if m != nil { + return m.Return + } + return nil +} + +func (m *Result) GetGasUsed() uint64 { + if m != nil { + return m.GasUsed + } + return 0 +} + +func (m *Result) GetNameEntry() *names.Entry { + if m != nil { + return m.NameEntry + } + return nil +} + +func (m *Result) GetPermArgs() *permission.PermArgs { + if m != nil { + return m.PermArgs + } + return nil +} + +func (*Result) XXX_MessageName() string { + return "exec.Result" +} + +type LogEvent struct { + Address github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,1,opt,name=Address,proto3,customtype=github.com/hyperledger/burrow/crypto.Address" json:"Address"` + Data github_com_hyperledger_burrow_binary.HexBytes `protobuf:"bytes,2,opt,name=Data,proto3,customtype=github.com/hyperledger/burrow/binary.HexBytes" json:"Data"` + Topics []github_com_hyperledger_burrow_binary.Word256 `protobuf:"bytes,3,rep,name=Topics,customtype=github.com/hyperledger/burrow/binary.Word256" json:"Topics"` +} + +func (m *LogEvent) Reset() { *m = LogEvent{} } +func (m *LogEvent) String() string { return proto.CompactTextString(m) } +func (*LogEvent) ProtoMessage() {} +func (*LogEvent) Descriptor() ([]byte, []int) { return fileDescriptorExec, []int{6} } + +func (*LogEvent) XXX_MessageName() string { + return "exec.LogEvent" +} + +type CallEvent struct { + CallData *CallData `protobuf:"bytes,1,opt,name=CallData" json:"CallData,omitempty"` + Origin github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,2,opt,name=Origin,proto3,customtype=github.com/hyperledger/burrow/crypto.Address" json:"Origin"` + StackDepth uint64 `protobuf:"varint,3,opt,name=StackDepth,proto3" json:"StackDepth,omitempty"` + Return github_com_hyperledger_burrow_binary.HexBytes `protobuf:"bytes,4,opt,name=Return,proto3,customtype=github.com/hyperledger/burrow/binary.HexBytes" json:"Return"` +} + +func (m *CallEvent) Reset() { *m = CallEvent{} } +func (m *CallEvent) String() string { return proto.CompactTextString(m) } +func (*CallEvent) ProtoMessage() {} +func (*CallEvent) Descriptor() ([]byte, []int) { return fileDescriptorExec, []int{7} } + +func (m *CallEvent) GetCallData() *CallData { + if m != nil { + return m.CallData + } + return nil +} + +func (m *CallEvent) GetStackDepth() uint64 { + if m != nil { + return m.StackDepth + } + return 0 +} + +func (*CallEvent) XXX_MessageName() string { + return "exec.CallEvent" +} + +type InputEvent struct { + Address github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,1,opt,name=Address,proto3,customtype=github.com/hyperledger/burrow/crypto.Address" json:"Address"` +} + +func (m *InputEvent) Reset() { *m = InputEvent{} } +func (m *InputEvent) String() string { return proto.CompactTextString(m) } +func (*InputEvent) ProtoMessage() {} +func (*InputEvent) Descriptor() ([]byte, []int) { return fileDescriptorExec, []int{8} } + +func (*InputEvent) XXX_MessageName() string { + return "exec.InputEvent" +} + +type OutputEvent struct { + Address github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,1,opt,name=Address,proto3,customtype=github.com/hyperledger/burrow/crypto.Address" json:"Address"` +} + +func (m *OutputEvent) Reset() { *m = OutputEvent{} } +func (m *OutputEvent) String() string { return proto.CompactTextString(m) } +func (*OutputEvent) ProtoMessage() {} +func (*OutputEvent) Descriptor() ([]byte, []int) { return fileDescriptorExec, []int{9} } + +func (*OutputEvent) XXX_MessageName() string { + return "exec.OutputEvent" +} + +type CallData struct { + Caller github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,1,opt,name=Caller,proto3,customtype=github.com/hyperledger/burrow/crypto.Address" json:"Caller"` + Callee github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,2,opt,name=Callee,proto3,customtype=github.com/hyperledger/burrow/crypto.Address" json:"Callee"` + Data github_com_hyperledger_burrow_binary.HexBytes `protobuf:"bytes,3,opt,name=Data,proto3,customtype=github.com/hyperledger/burrow/binary.HexBytes" json:"Data"` + Value uint64 `protobuf:"varint,4,opt,name=Value,proto3" json:"Value,omitempty"` + Gas uint64 `protobuf:"varint,5,opt,name=Gas,proto3" json:"Gas,omitempty"` +} + +func (m *CallData) Reset() { *m = CallData{} } +func (m *CallData) String() string { return proto.CompactTextString(m) } +func (*CallData) ProtoMessage() {} +func (*CallData) Descriptor() ([]byte, []int) { return fileDescriptorExec, []int{10} } + +func (m *CallData) GetValue() uint64 { + if m != nil { + return m.Value + } + return 0 +} + +func (m *CallData) GetGas() uint64 { + if m != nil { + return m.Gas + } + return 0 +} + +func (*CallData) XXX_MessageName() string { + return "exec.CallData" +} +func init() { + proto.RegisterType((*BlockExecution)(nil), "exec.BlockExecution") + golang_proto.RegisterType((*BlockExecution)(nil), "exec.BlockExecution") + proto.RegisterType((*BlockHeader)(nil), "exec.BlockHeader") + golang_proto.RegisterType((*BlockHeader)(nil), "exec.BlockHeader") + proto.RegisterType((*TxExecution)(nil), "exec.TxExecution") + golang_proto.RegisterType((*TxExecution)(nil), "exec.TxExecution") + proto.RegisterType((*Header)(nil), "exec.Header") + golang_proto.RegisterType((*Header)(nil), "exec.Header") + proto.RegisterType((*Event)(nil), "exec.Event") + golang_proto.RegisterType((*Event)(nil), "exec.Event") + proto.RegisterType((*Result)(nil), "exec.Result") + golang_proto.RegisterType((*Result)(nil), "exec.Result") + proto.RegisterType((*LogEvent)(nil), "exec.LogEvent") + golang_proto.RegisterType((*LogEvent)(nil), "exec.LogEvent") + proto.RegisterType((*CallEvent)(nil), "exec.CallEvent") + golang_proto.RegisterType((*CallEvent)(nil), "exec.CallEvent") + proto.RegisterType((*InputEvent)(nil), "exec.InputEvent") + golang_proto.RegisterType((*InputEvent)(nil), "exec.InputEvent") + proto.RegisterType((*OutputEvent)(nil), "exec.OutputEvent") + golang_proto.RegisterType((*OutputEvent)(nil), "exec.OutputEvent") + proto.RegisterType((*CallData)(nil), "exec.CallData") + golang_proto.RegisterType((*CallData)(nil), "exec.CallData") +} +func (m *BlockExecution) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *BlockExecution) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.Height != 0 { + dAtA[i] = 0x8 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Height)) + } + if m.BlockHeader != nil { + dAtA[i] = 0x12 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.BlockHeader.Size())) + n1, err := m.BlockHeader.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n1 + } + if len(m.TxExecutions) > 0 { + for _, msg := range m.TxExecutions { + dAtA[i] = 0x1a + i++ + i = encodeVarintExec(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + return i, nil +} + +func (m *BlockHeader) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *BlockHeader) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.JSON) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintExec(dAtA, i, uint64(len(m.JSON))) + i += copy(dAtA[i:], m.JSON) + } + if m.NumTxs != 0 { + dAtA[i] = 0x10 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.NumTxs)) + } + return i, nil +} + +func (m *TxExecution) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *TxExecution) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.TxType != 0 { + dAtA[i] = 0x10 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.TxType)) + } + dAtA[i] = 0x1a + i++ + i = encodeVarintExec(dAtA, i, uint64(m.TxHash.Size())) + n2, err := m.TxHash.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n2 + if m.Height != 0 { + dAtA[i] = 0x20 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Height)) + } + if m.Index != 0 { + dAtA[i] = 0x28 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Index)) + } + if m.Envelope != nil { + dAtA[i] = 0x32 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Envelope.Size())) + n3, err := m.Envelope.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n3 + } + if len(m.Events) > 0 { + for _, msg := range m.Events { + dAtA[i] = 0x3a + i++ + i = encodeVarintExec(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + if m.Result != nil { + dAtA[i] = 0x42 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Result.Size())) + n4, err := m.Result.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n4 + } + if m.Receipt != nil { + dAtA[i] = 0x4a + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Receipt.Size())) + n5, err := m.Receipt.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n5 + } + if m.Exception != nil { + dAtA[i] = 0x52 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Exception.Size())) + n6, err := m.Exception.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n6 + } + return i, nil +} + +func (m *Header) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Header) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.TxType != 0 { + dAtA[i] = 0x8 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.TxType)) + } + dAtA[i] = 0x12 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.TxHash.Size())) + n7, err := m.TxHash.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n7 + if m.EventType != 0 { + dAtA[i] = 0x18 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.EventType)) + } + if len(m.EventID) > 0 { + dAtA[i] = 0x22 + i++ + i = encodeVarintExec(dAtA, i, uint64(len(m.EventID))) + i += copy(dAtA[i:], m.EventID) + } + if m.Height != 0 { + dAtA[i] = 0x28 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Height)) + } + if m.Index != 0 { + dAtA[i] = 0x30 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Index)) + } + if m.Exception != nil { + dAtA[i] = 0x3a + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Exception.Size())) + n8, err := m.Exception.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n8 + } + return i, nil +} + +func (m *Event) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Event) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.Header != nil { + dAtA[i] = 0xa + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Header.Size())) + n9, err := m.Header.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n9 + } + if m.Input != nil { + dAtA[i] = 0x12 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Input.Size())) + n10, err := m.Input.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n10 + } + if m.Output != nil { + dAtA[i] = 0x1a + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Output.Size())) + n11, err := m.Output.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n11 + } + if m.Call != nil { + dAtA[i] = 0x22 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Call.Size())) + n12, err := m.Call.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n12 + } + if m.Log != nil { + dAtA[i] = 0x2a + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Log.Size())) + n13, err := m.Log.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n13 + } + return i, nil +} + +func (m *Result) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Result) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Return) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintExec(dAtA, i, uint64(len(m.Return))) + i += copy(dAtA[i:], m.Return) + } + if m.GasUsed != 0 { + dAtA[i] = 0x10 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.GasUsed)) + } + if m.NameEntry != nil { + dAtA[i] = 0x1a + i++ + i = encodeVarintExec(dAtA, i, uint64(m.NameEntry.Size())) + n14, err := m.NameEntry.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n14 + } + if m.PermArgs != nil { + dAtA[i] = 0x22 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.PermArgs.Size())) + n15, err := m.PermArgs.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n15 + } + return i, nil +} + +func (m *LogEvent) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *LogEvent) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + dAtA[i] = 0xa + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Address.Size())) + n16, err := m.Address.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n16 + dAtA[i] = 0x12 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Data.Size())) + n17, err := m.Data.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n17 + if len(m.Topics) > 0 { + for _, msg := range m.Topics { + dAtA[i] = 0x1a + i++ + i = encodeVarintExec(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + return i, nil +} + +func (m *CallEvent) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CallEvent) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.CallData != nil { + dAtA[i] = 0xa + i++ + i = encodeVarintExec(dAtA, i, uint64(m.CallData.Size())) + n18, err := m.CallData.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n18 + } + dAtA[i] = 0x12 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Origin.Size())) + n19, err := m.Origin.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n19 + if m.StackDepth != 0 { + dAtA[i] = 0x18 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.StackDepth)) + } + dAtA[i] = 0x22 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Return.Size())) + n20, err := m.Return.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n20 + return i, nil +} + +func (m *InputEvent) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *InputEvent) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + dAtA[i] = 0xa + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Address.Size())) + n21, err := m.Address.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n21 + return i, nil +} + +func (m *OutputEvent) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *OutputEvent) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + dAtA[i] = 0xa + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Address.Size())) + n22, err := m.Address.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n22 + return i, nil +} + +func (m *CallData) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CallData) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + dAtA[i] = 0xa + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Caller.Size())) + n23, err := m.Caller.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n23 + dAtA[i] = 0x12 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Callee.Size())) + n24, err := m.Callee.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n24 + dAtA[i] = 0x1a + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Data.Size())) + n25, err := m.Data.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n25 + if m.Value != 0 { + dAtA[i] = 0x20 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Value)) + } + if m.Gas != 0 { + dAtA[i] = 0x28 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.Gas)) + } + return i, nil +} + +func encodeVarintExec(dAtA []byte, offset int, v uint64) int { + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return offset + 1 +} +func (m *BlockExecution) Size() (n int) { + var l int + _ = l + if m.Height != 0 { + n += 1 + sovExec(uint64(m.Height)) + } + if m.BlockHeader != nil { + l = m.BlockHeader.Size() + n += 1 + l + sovExec(uint64(l)) + } + if len(m.TxExecutions) > 0 { + for _, e := range m.TxExecutions { + l = e.Size() + n += 1 + l + sovExec(uint64(l)) + } + } + return n +} + +func (m *BlockHeader) Size() (n int) { + var l int + _ = l + l = len(m.JSON) + if l > 0 { + n += 1 + l + sovExec(uint64(l)) + } + if m.NumTxs != 0 { + n += 1 + sovExec(uint64(m.NumTxs)) + } + return n +} + +func (m *TxExecution) Size() (n int) { + var l int + _ = l + if m.TxType != 0 { + n += 1 + sovExec(uint64(m.TxType)) + } + l = m.TxHash.Size() + n += 1 + l + sovExec(uint64(l)) + if m.Height != 0 { + n += 1 + sovExec(uint64(m.Height)) + } + if m.Index != 0 { + n += 1 + sovExec(uint64(m.Index)) + } + if m.Envelope != nil { + l = m.Envelope.Size() + n += 1 + l + sovExec(uint64(l)) + } + if len(m.Events) > 0 { + for _, e := range m.Events { + l = e.Size() + n += 1 + l + sovExec(uint64(l)) + } + } + if m.Result != nil { + l = m.Result.Size() + n += 1 + l + sovExec(uint64(l)) + } + if m.Receipt != nil { + l = m.Receipt.Size() + n += 1 + l + sovExec(uint64(l)) + } + if m.Exception != nil { + l = m.Exception.Size() + n += 1 + l + sovExec(uint64(l)) + } + return n +} + +func (m *Header) Size() (n int) { + var l int + _ = l + if m.TxType != 0 { + n += 1 + sovExec(uint64(m.TxType)) + } + l = m.TxHash.Size() + n += 1 + l + sovExec(uint64(l)) + if m.EventType != 0 { + n += 1 + sovExec(uint64(m.EventType)) + } + l = len(m.EventID) + if l > 0 { + n += 1 + l + sovExec(uint64(l)) + } + if m.Height != 0 { + n += 1 + sovExec(uint64(m.Height)) + } + if m.Index != 0 { + n += 1 + sovExec(uint64(m.Index)) + } + if m.Exception != nil { + l = m.Exception.Size() + n += 1 + l + sovExec(uint64(l)) + } + return n +} + +func (m *Event) Size() (n int) { + var l int + _ = l + if m.Header != nil { + l = m.Header.Size() + n += 1 + l + sovExec(uint64(l)) + } + if m.Input != nil { + l = m.Input.Size() + n += 1 + l + sovExec(uint64(l)) + } + if m.Output != nil { + l = m.Output.Size() + n += 1 + l + sovExec(uint64(l)) + } + if m.Call != nil { + l = m.Call.Size() + n += 1 + l + sovExec(uint64(l)) + } + if m.Log != nil { + l = m.Log.Size() + n += 1 + l + sovExec(uint64(l)) + } + return n +} + +func (m *Result) Size() (n int) { + var l int + _ = l + l = len(m.Return) + if l > 0 { + n += 1 + l + sovExec(uint64(l)) + } + if m.GasUsed != 0 { + n += 1 + sovExec(uint64(m.GasUsed)) + } + if m.NameEntry != nil { + l = m.NameEntry.Size() + n += 1 + l + sovExec(uint64(l)) + } + if m.PermArgs != nil { + l = m.PermArgs.Size() + n += 1 + l + sovExec(uint64(l)) + } + return n +} + +func (m *LogEvent) Size() (n int) { + var l int + _ = l + l = m.Address.Size() + n += 1 + l + sovExec(uint64(l)) + l = m.Data.Size() + n += 1 + l + sovExec(uint64(l)) + if len(m.Topics) > 0 { + for _, e := range m.Topics { + l = e.Size() + n += 1 + l + sovExec(uint64(l)) + } + } + return n +} + +func (m *CallEvent) Size() (n int) { + var l int + _ = l + if m.CallData != nil { + l = m.CallData.Size() + n += 1 + l + sovExec(uint64(l)) + } + l = m.Origin.Size() + n += 1 + l + sovExec(uint64(l)) + if m.StackDepth != 0 { + n += 1 + sovExec(uint64(m.StackDepth)) + } + l = m.Return.Size() + n += 1 + l + sovExec(uint64(l)) + return n +} + +func (m *InputEvent) Size() (n int) { + var l int + _ = l + l = m.Address.Size() + n += 1 + l + sovExec(uint64(l)) + return n +} + +func (m *OutputEvent) Size() (n int) { + var l int + _ = l + l = m.Address.Size() + n += 1 + l + sovExec(uint64(l)) + return n +} + +func (m *CallData) Size() (n int) { + var l int + _ = l + l = m.Caller.Size() + n += 1 + l + sovExec(uint64(l)) + l = m.Callee.Size() + n += 1 + l + sovExec(uint64(l)) + l = m.Data.Size() + n += 1 + l + sovExec(uint64(l)) + if m.Value != 0 { + n += 1 + sovExec(uint64(m.Value)) + } + if m.Gas != 0 { + n += 1 + sovExec(uint64(m.Gas)) + } + return n +} + +func sovExec(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n +} +func sozExec(x uint64) (n int) { + return sovExec(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *BlockExecution) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: BlockExecution: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: BlockExecution: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockHeader", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.BlockHeader == nil { + m.BlockHeader = &BlockHeader{} + } + if err := m.BlockHeader.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TxExecutions", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.TxExecutions = append(m.TxExecutions, &TxExecution{}) + if err := m.TxExecutions[len(m.TxExecutions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipExec(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthExec + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *BlockHeader) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: BlockHeader: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: BlockHeader: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field JSON", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.JSON = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field NumTxs", wireType) + } + m.NumTxs = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.NumTxs |= (int32(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipExec(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthExec + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *TxExecution) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: TxExecution: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: TxExecution: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field TxType", wireType) + } + m.TxType = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.TxType |= (github_com_hyperledger_burrow_txs_payload.Type(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TxHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.TxHash.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) + } + m.Index = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Index |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Envelope", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Envelope == nil { + m.Envelope = &github_com_hyperledger_burrow_txs.Envelope{} + } + if err := m.Envelope.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Events", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Events = append(m.Events, &Event{}) + if err := m.Events[len(m.Events)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Result", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Result == nil { + m.Result = &Result{} + } + if err := m.Result.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Receipt", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Receipt == nil { + m.Receipt = &txs.Receipt{} + } + if err := m.Receipt.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 10: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Exception", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Exception == nil { + m.Exception = &errors.Exception{} + } + if err := m.Exception.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipExec(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthExec + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Header) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Header: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Header: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field TxType", wireType) + } + m.TxType = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.TxType |= (github_com_hyperledger_burrow_txs_payload.Type(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TxHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.TxHash.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field EventType", wireType) + } + m.EventType = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.EventType |= (EventType(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field EventID", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.EventID = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 6: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) + } + m.Index = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Index |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Exception", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Exception == nil { + m.Exception = &errors.Exception{} + } + if err := m.Exception.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipExec(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthExec + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Event) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Event: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Event: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Header", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Header == nil { + m.Header = &Header{} + } + if err := m.Header.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Input", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Input == nil { + m.Input = &InputEvent{} + } + if err := m.Input.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Output", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Output == nil { + m.Output = &OutputEvent{} + } + if err := m.Output.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Call", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Call == nil { + m.Call = &CallEvent{} + } + if err := m.Call.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Log", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Log == nil { + m.Log = &LogEvent{} + } + if err := m.Log.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipExec(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthExec + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Result) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Result: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Result: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Return", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Return = append(m.Return[:0], dAtA[iNdEx:postIndex]...) + if m.Return == nil { + m.Return = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field GasUsed", wireType) + } + m.GasUsed = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.GasUsed |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NameEntry", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.NameEntry == nil { + m.NameEntry = &names.Entry{} + } + if err := m.NameEntry.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PermArgs", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.PermArgs == nil { + m.PermArgs = &permission.PermArgs{} + } + if err := m.PermArgs.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipExec(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthExec + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *LogEvent) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: LogEvent: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: LogEvent: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Address.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Data.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Topics", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + var v github_com_hyperledger_burrow_binary.Word256 + m.Topics = append(m.Topics, v) + if err := m.Topics[len(m.Topics)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipExec(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthExec + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CallEvent) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CallEvent: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CallEvent: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CallData", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.CallData == nil { + m.CallData = &CallData{} + } + if err := m.CallData.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Origin", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Origin.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field StackDepth", wireType) + } + m.StackDepth = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.StackDepth |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Return", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Return.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipExec(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthExec + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *InputEvent) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: InputEvent: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: InputEvent: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Address.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipExec(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthExec + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *OutputEvent) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: OutputEvent: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: OutputEvent: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Address.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipExec(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthExec + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CallData) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CallData: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CallData: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Caller", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Caller.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Callee", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Callee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Data.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) + } + m.Value = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Value |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Gas", wireType) + } + m.Gas = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Gas |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipExec(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthExec + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipExec(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowExec + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowExec + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowExec + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + iNdEx += length + if length < 0 { + return 0, ErrInvalidLengthExec + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowExec + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipExec(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} + +var ( + ErrInvalidLengthExec = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowExec = fmt.Errorf("proto: integer overflow") +) + +func init() { proto.RegisterFile("exec.proto", fileDescriptorExec) } +func init() { golang_proto.RegisterFile("exec.proto", fileDescriptorExec) } + +var fileDescriptorExec = []byte{ + // 963 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x56, 0xcd, 0x6f, 0x1b, 0x45, + 0x14, 0xef, 0xf8, 0x63, 0x6d, 0x3f, 0x3b, 0x25, 0x8c, 0x22, 0xb4, 0xea, 0xc1, 0x6b, 0xa5, 0xa8, + 0x0a, 0xa1, 0x5d, 0x23, 0x97, 0x20, 0xc1, 0xad, 0x26, 0x56, 0x93, 0x2a, 0x24, 0x68, 0x6a, 0x40, + 0x70, 0x5b, 0xef, 0x0e, 0x9b, 0x25, 0xf6, 0xee, 0x6a, 0x76, 0xb6, 0xac, 0x8f, 0x70, 0xe2, 0xc8, + 0x81, 0x03, 0xc7, 0xe6, 0x02, 0xff, 0x06, 0xc7, 0x1c, 0xb9, 0x52, 0x24, 0x0b, 0x25, 0xff, 0x45, + 0x4f, 0x68, 0x3e, 0x76, 0xbd, 0x8e, 0xaa, 0xb6, 0x6a, 0xd2, 0x4b, 0x34, 0xef, 0xbd, 0xdf, 0xfe, + 0xe6, 0x7d, 0xfc, 0xe6, 0xc5, 0x00, 0x34, 0xa3, 0xae, 0x1d, 0xb3, 0x88, 0x47, 0xb8, 0x26, 0xce, + 0xb7, 0xee, 0xf9, 0x01, 0x3f, 0x4e, 0x27, 0xb6, 0x1b, 0xcd, 0xfa, 0x7e, 0xe4, 0x47, 0x7d, 0x19, + 0x9c, 0xa4, 0xdf, 0x4b, 0x4b, 0x1a, 0xf2, 0xa4, 0x3e, 0xba, 0x75, 0xb7, 0x04, 0xe7, 0x34, 0xf4, + 0x28, 0x9b, 0x05, 0x21, 0xef, 0x3b, 0x13, 0x37, 0xe8, 0xf3, 0x79, 0x4c, 0x13, 0xf5, 0x57, 0xa3, + 0x3b, 0x94, 0xb1, 0x88, 0xe5, 0x56, 0x3b, 0x74, 0x66, 0x45, 0xa8, 0xc5, 0xb3, 0xfc, 0xb8, 0x1e, + 0x0b, 0x96, 0x24, 0x09, 0xa2, 0x50, 0x79, 0x36, 0x7f, 0x43, 0x70, 0x73, 0x38, 0x8d, 0xdc, 0x93, + 0x51, 0x46, 0xdd, 0x94, 0x07, 0x51, 0x88, 0xdf, 0x03, 0x63, 0x8f, 0x06, 0xfe, 0x31, 0x37, 0x51, + 0x0f, 0x6d, 0xd5, 0x88, 0xb6, 0xf0, 0x7d, 0x68, 0x4b, 0xe4, 0x1e, 0x75, 0x3c, 0xca, 0xcc, 0x4a, + 0x0f, 0x6d, 0xb5, 0x07, 0xef, 0xda, 0xb2, 0xce, 0x52, 0x80, 0x94, 0x51, 0x78, 0x07, 0x3a, 0xe3, + 0xac, 0xe0, 0x4e, 0xcc, 0x6a, 0xaf, 0xba, 0xfc, 0xaa, 0x14, 0x21, 0x2b, 0xb0, 0xcd, 0x4f, 0x57, + 0xee, 0xc2, 0x18, 0x6a, 0x8f, 0x1e, 0x1f, 0x1d, 0xca, 0x84, 0x5a, 0x44, 0x9e, 0x45, 0x9a, 0x87, + 0xe9, 0x6c, 0x9c, 0x25, 0x32, 0x93, 0x3a, 0xd1, 0xd6, 0xe6, 0x45, 0x15, 0xda, 0x25, 0x2e, 0xfc, + 0x08, 0x8c, 0x71, 0x36, 0x9e, 0xc7, 0x54, 0xe2, 0xd6, 0x86, 0x83, 0xe7, 0x0b, 0xcb, 0x2e, 0xf5, + 0xf6, 0x78, 0x1e, 0x53, 0x36, 0xa5, 0x9e, 0x4f, 0x59, 0x7f, 0x92, 0x32, 0x16, 0xfd, 0xd8, 0xe7, + 0x59, 0xd2, 0x8f, 0x9d, 0xf9, 0x34, 0x72, 0x3c, 0x5b, 0x7c, 0x49, 0x34, 0x03, 0xfe, 0x42, 0x70, + 0xed, 0x39, 0xc9, 0xb1, 0x59, 0xed, 0xa1, 0xad, 0xce, 0x70, 0xe7, 0x6c, 0x61, 0xdd, 0x78, 0xb6, + 0xb0, 0xee, 0xbd, 0x9c, 0x6f, 0x12, 0x84, 0x0e, 0x9b, 0xdb, 0x7b, 0x34, 0x1b, 0xce, 0x39, 0x4d, + 0x88, 0x26, 0x29, 0x75, 0xba, 0xb6, 0xd2, 0xe9, 0x0d, 0xa8, 0xef, 0x87, 0x1e, 0xcd, 0xcc, 0xba, + 0x74, 0x2b, 0x03, 0x7f, 0x0b, 0xcd, 0x51, 0xf8, 0x84, 0x4e, 0xa3, 0x98, 0x9a, 0x86, 0x6c, 0xfe, + 0x9a, 0x2d, 0x46, 0x9b, 0x3b, 0x87, 0xf6, 0xb3, 0x85, 0xb5, 0xfd, 0xca, 0xca, 0x0a, 0x3c, 0x29, + 0xe8, 0xf0, 0x6d, 0x30, 0x46, 0x4f, 0x68, 0xc8, 0x13, 0xb3, 0x21, 0xe7, 0xd3, 0x56, 0xf3, 0x91, + 0x3e, 0xa2, 0x43, 0xf8, 0x7d, 0x30, 0x08, 0x4d, 0xd2, 0x29, 0x37, 0x9b, 0xf2, 0xf6, 0x8e, 0x02, + 0x29, 0x1f, 0xd1, 0x31, 0x7c, 0x07, 0x1a, 0x84, 0xba, 0x34, 0x88, 0xb9, 0xd9, 0xd2, 0x30, 0x71, + 0xa9, 0xf6, 0x91, 0x3c, 0x88, 0xfb, 0xd0, 0x1a, 0x65, 0x2e, 0x8d, 0xc5, 0x8c, 0x4c, 0xc8, 0xb5, + 0xa4, 0x44, 0x5c, 0x04, 0xc8, 0x12, 0xf3, 0x59, 0xe7, 0x97, 0x53, 0x0b, 0xfd, 0x7a, 0x6a, 0xa1, + 0xa7, 0xa7, 0x16, 0xda, 0xfc, 0xb7, 0x22, 0x7a, 0x27, 0xc5, 0xb1, 0x1c, 0x30, 0xba, 0xc6, 0x01, + 0x57, 0xae, 0x63, 0xc0, 0x1f, 0x42, 0x4b, 0x36, 0x4f, 0x66, 0x57, 0x95, 0xd9, 0xad, 0x3d, 0x5f, + 0x58, 0x4b, 0x27, 0x59, 0x1e, 0xb1, 0x09, 0x0d, 0x69, 0xec, 0xef, 0x4a, 0x39, 0xb4, 0x48, 0x6e, + 0x96, 0x74, 0x52, 0x7f, 0xb1, 0x4e, 0x8c, 0xb2, 0x4e, 0x56, 0x3a, 0xdb, 0x78, 0x8d, 0xce, 0xae, + 0xff, 0xfe, 0xd4, 0xba, 0xb1, 0xd2, 0xdd, 0x7f, 0x10, 0xd4, 0xe5, 0xe5, 0x62, 0xe8, 0xfa, 0xbd, + 0xa3, 0xf2, 0xd0, 0xf5, 0x53, 0xcf, 0x47, 0x70, 0x47, 0x24, 0x12, 0xa7, 0x5c, 0x2f, 0x85, 0x75, + 0x05, 0x92, 0x2e, 0xa5, 0x21, 0x15, 0xc6, 0x1f, 0x80, 0x71, 0x94, 0x72, 0x01, 0xac, 0x96, 0xb7, + 0x87, 0xf2, 0x69, 0xb5, 0x29, 0x03, 0xdf, 0x86, 0xda, 0xe7, 0xce, 0x74, 0x2a, 0x5b, 0xd1, 0x1e, + 0xbc, 0xa3, 0x80, 0xc2, 0xa3, 0x60, 0x32, 0x88, 0x7b, 0x50, 0x3d, 0x88, 0x7c, 0xd9, 0x95, 0xf6, + 0xe0, 0xa6, 0xc2, 0x1c, 0x44, 0xbe, 0x82, 0x88, 0xd0, 0x0b, 0x6a, 0xfb, 0x03, 0xe5, 0x3a, 0x16, + 0x7d, 0x25, 0x94, 0xa7, 0x2c, 0x94, 0xc5, 0x75, 0x88, 0xb6, 0xc4, 0x24, 0x1e, 0x3a, 0xc9, 0x57, + 0x09, 0xf5, 0x64, 0x41, 0x35, 0x92, 0x9b, 0x78, 0x1b, 0x5a, 0x87, 0xce, 0x8c, 0x8e, 0x42, 0xce, + 0xe6, 0xba, 0x86, 0x8e, 0xad, 0x96, 0xad, 0xf4, 0x91, 0x65, 0x18, 0x7f, 0x04, 0xcd, 0x2f, 0x29, + 0x9b, 0x3d, 0x60, 0x7e, 0xa2, 0xab, 0xd8, 0xb0, 0x4b, 0xfb, 0x37, 0x8f, 0x91, 0x02, 0x75, 0x49, + 0xe2, 0x3f, 0x55, 0xa0, 0x99, 0x17, 0x83, 0x0f, 0xa1, 0xf1, 0xc0, 0xf3, 0x18, 0x4d, 0x12, 0x95, + 0xeb, 0xf0, 0x63, 0xad, 0xcc, 0xbb, 0x2f, 0x57, 0xa6, 0xcb, 0xe6, 0x31, 0x8f, 0x6c, 0xfd, 0x2d, + 0xc9, 0x49, 0xf0, 0x3e, 0xd4, 0x76, 0x1d, 0xee, 0x5c, 0x4d, 0xe6, 0x92, 0x02, 0x1f, 0x80, 0x31, + 0x8e, 0xe2, 0xc0, 0x55, 0xcb, 0xfd, 0xb5, 0x33, 0xd3, 0x64, 0xdf, 0x44, 0xcc, 0x1b, 0xec, 0x7c, + 0x42, 0x34, 0xc7, 0xa5, 0x1e, 0xfc, 0x5c, 0x81, 0x56, 0x31, 0x74, 0xbc, 0x0d, 0x4d, 0x61, 0xc8, + 0xc4, 0x51, 0x79, 0xe6, 0xb9, 0x97, 0x14, 0x71, 0x91, 0xd5, 0x11, 0x0b, 0xfc, 0x20, 0xd4, 0x25, + 0xbe, 0x59, 0xbf, 0x34, 0x07, 0xee, 0x02, 0x3c, 0xe6, 0x8e, 0x7b, 0xb2, 0x4b, 0x63, 0xae, 0x96, + 0x7f, 0x8d, 0x94, 0x3c, 0x62, 0x6f, 0x68, 0x25, 0xd5, 0xae, 0xb4, 0x37, 0x14, 0xc9, 0xa5, 0x26, + 0xfc, 0x00, 0xb0, 0x7c, 0x4a, 0xd7, 0xad, 0x84, 0x4b, 0x77, 0x9d, 0x40, 0xbb, 0xf4, 0x1a, 0xdf, + 0xf2, 0x65, 0x7f, 0x56, 0x60, 0x65, 0x60, 0xe2, 0xac, 0x37, 0xcd, 0x1b, 0x0f, 0x4c, 0x71, 0x14, + 0x6c, 0xf4, 0x6a, 0xe3, 0x57, 0x1c, 0xc5, 0x6b, 0xa9, 0x5e, 0xfd, 0xb5, 0x6c, 0x40, 0xfd, 0x6b, + 0x67, 0x9a, 0x52, 0xfd, 0x2f, 0x5f, 0x19, 0x78, 0x1d, 0xaa, 0x0f, 0x9d, 0x44, 0xaf, 0x77, 0x71, + 0x5c, 0xed, 0xd4, 0x70, 0x78, 0x76, 0xde, 0x45, 0x7f, 0x9f, 0x77, 0xd1, 0x7f, 0xe7, 0x5d, 0xf4, + 0xd7, 0x45, 0x17, 0x9d, 0x5d, 0x74, 0xd1, 0x77, 0xaf, 0x28, 0x86, 0xe6, 0xbf, 0x81, 0xe4, 0x69, + 0x62, 0xc8, 0x5f, 0x7c, 0xf7, 0xff, 0x0f, 0x00, 0x00, 0xff, 0xff, 0x4c, 0xf0, 0xd7, 0x87, 0x9a, + 0x0a, 0x00, 0x00, +} diff --git a/execution/exec/header.go b/execution/exec/header.go new file mode 100644 index 000000000..1ed0b5aac --- /dev/null +++ b/execution/exec/header.go @@ -0,0 +1,13 @@ +package exec + +import ( + "fmt" +) + +func (h *Header) String() string { + if h == nil { + return fmt.Sprintf("Header{}") + } + return fmt.Sprintf("Header{Tx{%v}: %v; Event{%v}: %v; Height: %v; Index: %v}", + h.TxType, h.TxHash, h.EventType, h.EventID, h.Height, h.Index) +} diff --git a/execution/events/log.go b/execution/exec/log_event.go similarity index 51% rename from execution/events/log.go rename to execution/exec/log_event.go index b41fad89f..ea1aa0229 100644 --- a/execution/events/log.go +++ b/execution/exec/log_event.go @@ -12,78 +12,39 @@ // See the License for the specific language governing permissions and // limitations under the License. -package events +package exec import ( - "context" - "fmt" - "strings" - "github.com/hyperledger/burrow/binary" + "fmt" + . "github.com/hyperledger/burrow/binary" - "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/event" "github.com/hyperledger/burrow/event/query" - "github.com/hyperledger/burrow/txs" "github.com/tmthrgd/go-hex" ) -// Functions to generate eventId strings - -func EventStringLogEvent(addr crypto.Address) string { return fmt.Sprintf("Log/%s", addr) } - -//---------------------------------------- - -// EventDataLog fires when a contract executes the LOG opcode -type EventDataLog struct { - Height uint64 - Address crypto.Address - Topics []Word256 - Data binary.HexBytes -} +const logNTextTopicCutset = "\x00" +const LogNKeyPrefix = "Log" -// Publish/Subscribe -func PublishLogEvent(publisher event.Publisher, tx *txs.Tx, log *EventDataLog) error { - ev := &Event{ - Header: &Header{ - TxType: tx.Type(), - TxHash: tx.Hash(), - EventType: TypeLog, - EventID: EventStringLogEvent(log.Address), - Height: log.Height, - }, - Log: log, - } - return publisher.Publish(context.Background(), ev, ev.Tags()) +func LogNKey(topic int) string { + return fmt.Sprintf("%s%d", LogNKeyPrefix, topic) } -func SubscribeLogEvent(ctx context.Context, subscribable event.Subscribable, subscriber string, address crypto.Address, - ch chan<- *EventDataLog) error { - - qry := event.QueryForEventID(EventStringLogEvent(address)) - - return event.SubscribeCallback(ctx, subscribable, subscriber, qry, func(message interface{}) (stop bool) { - ev, ok := message.(*Event) - if ok && ev.Log != nil { - ch <- ev.Log - } - return - }) +func LogNTextKey(topic int) string { + return fmt.Sprintf("%s%dText", LogNKeyPrefix, topic) } -// Tags -const logNTextTopicCutset = "\x00" - var logTagKeys []string var logNTopicIndex = make(map[string]int, 5) var logNTextTopicIndex = make(map[string]int, 5) func init() { for i := 0; i <= 4; i++ { - logN := event.LogNKey(i) - logTagKeys = append(logTagKeys, event.LogNKey(i)) - logNText := event.LogNTextKey(i) + logN := LogNKey(i) + logTagKeys = append(logTagKeys, LogNKey(i)) + logNText := LogNTextKey(i) logTagKeys = append(logTagKeys, logNText) logNTopicIndex[logN] = i logNTextTopicIndex[logNText] = i @@ -91,7 +52,7 @@ func init() { logTagKeys = append(logTagKeys, event.AddressKey) } -func (log *EventDataLog) Get(key string) (string, bool) { +func (log *LogEvent) Get(key string) (string, bool) { var value interface{} switch key { case event.AddressKey: @@ -108,17 +69,17 @@ func (log *EventDataLog) Get(key string) (string, bool) { return query.StringFromValue(value), true } -func (log *EventDataLog) GetTopic(i int) Word256 { +func (log *LogEvent) GetTopic(i int) Word256 { if i < len(log.Topics) { return log.Topics[i] } return Word256{} } -func (log *EventDataLog) Len() int { +func (log *LogEvent) Len() int { return len(logTagKeys) } -func (log *EventDataLog) Keys() []string { +func (log *LogEvent) Keys() []string { return logTagKeys } diff --git a/execution/exec/tx_execution.go b/execution/exec/tx_execution.go new file mode 100644 index 000000000..493af2920 --- /dev/null +++ b/execution/exec/tx_execution.go @@ -0,0 +1,154 @@ +package exec + +import ( + "fmt" + + "github.com/hyperledger/burrow/crypto" + "github.com/hyperledger/burrow/event" + "github.com/hyperledger/burrow/event/query" + "github.com/hyperledger/burrow/execution/errors" + "github.com/hyperledger/burrow/execution/names" + "github.com/hyperledger/burrow/permission" + "github.com/hyperledger/burrow/txs" +) + +func EventStringAccountInput(addr crypto.Address) string { return fmt.Sprintf("Acc/%s/Input", addr) } +func EventStringAccountOutput(addr crypto.Address) string { return fmt.Sprintf("Acc/%s/Output", addr) } + +func EventStringAccountCall(addr crypto.Address) string { return fmt.Sprintf("Acc/%s/Call", addr) } +func EventStringLogEvent(addr crypto.Address) string { return fmt.Sprintf("Log/%s", addr) } +func EventStringTxExecution(txHash []byte) string { return fmt.Sprintf("Execution/Tx/%X", txHash) } + +func NewTxExecution(txEnv *txs.Envelope) *TxExecution { + return &TxExecution{ + TxHash: txEnv.Tx.Hash(), + TxType: txEnv.Tx.Type(), + Envelope: txEnv, + Receipt: txEnv.Tx.GenerateReceipt(), + } +} + +func DecodeTxExecution(bs []byte) (*TxExecution, error) { + txe := new(TxExecution) + err := cdc.UnmarshalBinary(bs, txe) + if err != nil { + return nil, err + } + return txe, nil +} + +func (txe *TxExecution) Encode() ([]byte, error) { + return cdc.MarshalBinary(txe) +} + +func (*TxExecution) EventType() EventType { + return TypeTxExecution +} + +func (txe *TxExecution) Header(eventType EventType, eventID string, exception *errors.Exception) *Header { + return &Header{ + TxType: txe.TxType, + TxHash: txe.TxHash, + EventType: eventType, + EventID: eventID, + Height: txe.Height, + Exception: exception, + } +} + +// Emit events +func (txe *TxExecution) Input(address crypto.Address, exception *errors.Exception) { + txe.Append(&Event{ + Header: txe.Header(TypeAccountInput, EventStringAccountInput(address), exception), + Input: &InputEvent{ + Address: address, + }, + }) +} + +func (txe *TxExecution) Output(address crypto.Address, exception *errors.Exception) { + txe.Append(&Event{ + Header: txe.Header(TypeAccountOutput, EventStringAccountOutput(address), exception), + Output: &OutputEvent{ + Address: address, + }, + }) +} + +func (txe *TxExecution) Log(log *LogEvent) { + txe.Append(&Event{ + Header: txe.Header(TypeLog, EventStringLogEvent(log.Address), nil), + Log: log, + }) +} + +func (txe *TxExecution) Call(call *CallEvent, exception *errors.Exception) { + txe.Append(&Event{ + Header: txe.Header(TypeCall, EventStringAccountCall(call.CallData.Callee), exception), + Call: call, + }) +} + +// Set result +func (txe *TxExecution) Return(returnValue []byte, gasUsed uint64) { + if txe.Result == nil { + txe.Result = &Result{} + } + txe.Result.Return = returnValue + txe.Result.GasUsed = gasUsed +} + +func (txe *TxExecution) Name(entry *names.Entry) { + if txe.Result == nil { + txe.Result = &Result{} + } + txe.Result.NameEntry = entry +} + +func (txe *TxExecution) Permission(permArgs *permission.PermArgs) { + if txe.Result == nil { + txe.Result = &Result{} + } + txe.Result.PermArgs = permArgs +} + +func (txe *TxExecution) Append(tail ...*Event) { + for i, ev := range tail { + if ev != nil && ev.Header != nil { + ev.Header.Index = uint64(len(txe.Events) + i) + ev.Header.Height = txe.Height + } + } + txe.Events = append(txe.Events, tail...) +} + +// Tags +type TaggedTxExecution struct { + query.Tagged + *TxExecution +} + +func (txe *TxExecution) Tagged() *TaggedTxExecution { + return &TaggedTxExecution{ + Tagged: query.MergeTags( + query.TagMap{ + event.EventIDKey: EventStringTxExecution(txe.TxHash), + event.EventTypeKey: txe.EventType()}, + query.MustReflectTags(txe), + txe.Envelope.Tagged(), + ), + TxExecution: txe, + } +} + +func (txe *TxExecution) TaggedEvents() TaggedEvents { + tevs := make(TaggedEvents, len(txe.Events)) + for i, ev := range txe.Events { + tevs[i] = ev.Tagged() + } + return tevs +} + +func QueryForTxExecution(txHash []byte) query.Queryable { + return query.NewBuilder().AndEquals(event.EventIDKey, EventStringTxExecution(txHash)) +} diff --git a/execution/execution.go b/execution/execution.go index 22eff6e9b..23412014e 100644 --- a/execution/execution.go +++ b/execution/execution.go @@ -19,23 +19,31 @@ import ( "runtime/debug" "sync" - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/account/state" + "context" + + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/state" "github.com/hyperledger/burrow/binary" bcm "github.com/hyperledger/burrow/blockchain" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/event" "github.com/hyperledger/burrow/execution/evm" + "github.com/hyperledger/burrow/execution/exec" "github.com/hyperledger/burrow/execution/executors" "github.com/hyperledger/burrow/execution/names" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" "github.com/hyperledger/burrow/txs" "github.com/hyperledger/burrow/txs/payload" + abciTypes "github.com/tendermint/abci/types" ) type Executor interface { - Execute(txEnv *txs.Envelope) error + Execute(txEnv *txs.Envelope) (*exec.TxExecution, error) +} + +type Context interface { + Execute(txe *exec.TxExecution) error } type ExecutorState interface { @@ -59,20 +67,21 @@ type BatchCommitter interface { BatchExecutor // Commit execution results to underlying State and provide opportunity // to mutate state before it is saved - Commit() (stateHash []byte, err error) + Commit(*abciTypes.Header) (stateHash []byte, err error) } type executor struct { sync.RWMutex - runCall bool - publisher event.Publisher - state ExecutorState - stateCache *state.Cache - nameRegCache *names.Cache - eventCache *event.Cache - logger *logging.Logger - vmOptions []func(*evm.VM) - txExecutors map[payload.Type]Executor + runCall bool + tip bcm.TipInfo + state ExecutorState + stateCache *state.Cache + nameRegCache *names.Cache + publisher event.Publisher + blockExecution *exec.BlockExecution + logger *logging.Logger + vmOptions []func(*evm.VM) + txExecutors map[payload.Type]Context } var _ BatchExecutor = (*executor)(nil) @@ -85,10 +94,10 @@ func NewBatchChecker(backend ExecutorState, tip bcm.TipInfo, logger *logging.Log logger.WithScope("NewBatchExecutor"), options...) } -func NewBatchCommitter(backend ExecutorState, tip bcm.TipInfo, publisher event.Publisher, logger *logging.Logger, +func NewBatchCommitter(backend ExecutorState, tip bcm.TipInfo, emitter event.Publisher, logger *logging.Logger, options ...ExecutionOption) BatchCommitter { - return newExecutor("CommitCache", true, backend, tip, publisher, + return newExecutor("CommitCache", true, backend, tip, emitter, logger.WithScope("NewBatchCommitter"), options...) } @@ -98,42 +107,41 @@ func newExecutor(name string, runCall bool, backend ExecutorState, tip bcm.TipIn exe := &executor{ runCall: runCall, state: backend, - publisher: publisher, + tip: tip, stateCache: state.NewCache(backend, state.Name(name)), - eventCache: event.NewCache(), nameRegCache: names.NewCache(backend), - logger: logger.With(structure.ComponentKey, "Executor"), + publisher: publisher, + blockExecution: &exec.BlockExecution{ + Height: tip.LastBlockHeight() + 1, + }, + logger: logger.With(structure.ComponentKey, "Executor"), } for _, option := range options { option(exe) } - exe.txExecutors = map[payload.Type]Executor{ + exe.txExecutors = map[payload.Type]Context{ payload.TypeSend: &executors.SendContext{ - Tip: tip, - StateWriter: exe.stateCache, - EventPublisher: exe.eventCache, - Logger: exe.logger, + Tip: tip, + StateWriter: exe.stateCache, + Logger: exe.logger, }, payload.TypeCall: &executors.CallContext{ - Tip: tip, - StateWriter: exe.stateCache, - EventPublisher: exe.eventCache, - RunCall: runCall, - VMOptions: exe.vmOptions, - Logger: exe.logger, + Tip: tip, + StateWriter: exe.stateCache, + RunCall: runCall, + VMOptions: exe.vmOptions, + Logger: exe.logger, }, payload.TypeName: &executors.NameContext{ - Tip: tip, - StateWriter: exe.stateCache, - EventPublisher: exe.eventCache, - NameReg: exe.nameRegCache, - Logger: exe.logger, + Tip: tip, + StateWriter: exe.stateCache, + NameReg: exe.nameRegCache, + Logger: exe.logger, }, payload.TypePermissions: &executors.PermissionsContext{ - Tip: tip, - StateWriter: exe.stateCache, - EventPublisher: exe.eventCache, - Logger: exe.logger, + Tip: tip, + StateWriter: exe.stateCache, + Logger: exe.logger, }, } return exe @@ -141,7 +149,7 @@ func newExecutor(name string, runCall bool, backend ExecutorState, tip bcm.TipIn // If the tx is invalid, an error will be returned. // Unlike ExecBlock(), state will not be altered. -func (exe *executor) Execute(txEnv *txs.Envelope) (err error) { +func (exe *executor) Execute(txEnv *txs.Envelope) (txe *exec.TxExecution, err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("recovered from panic in executor.Execute(%s): %v\n%s", txEnv.String(), r, @@ -158,24 +166,53 @@ func (exe *executor) Execute(txEnv *txs.Envelope) (err error) { // Verify transaction signature against inputs err = txEnv.Verify(exe.stateCache) if err != nil { - return err + return nil, err } if txExecutor, ok := exe.txExecutors[txEnv.Tx.Type()]; ok { - return txExecutor.Execute(txEnv) + // Establish new TxExecution + txe := exe.blockExecution.Tx(txEnv) + err = txExecutor.Execute(txe) + if err != nil { + return nil, err + } + // Return execution for this tx + return txe, err + } + return nil, fmt.Errorf("unknown transaction type: %v", txEnv.Tx.Type()) +} + +func (exe *executor) finaliseBlockExecution(header *abciTypes.Header) (*exec.BlockExecution, error) { + if header != nil && uint64(header.Height) != exe.blockExecution.Height { + return nil, fmt.Errorf("trying to finalise block execution with height %v but passed Tendermint"+ + "block header at height %v", exe.blockExecution.Height, header.Height) + } + // Capture BlockExecution to return + be := exe.blockExecution + // Set the header when provided + be.BlockHeader = exec.BlockHeaderFromHeader(header) + // Start new execution for the next height + exe.blockExecution = &exec.BlockExecution{ + Height: exe.blockExecution.Height + 1, } - return fmt.Errorf("unknown transaction type: %v", txEnv.Tx.Type()) + return be, nil } -func (exe *executor) Commit() (_ []byte, err error) { +func (exe *executor) Commit(header *abciTypes.Header) (_ []byte, err error) { // The write lock to the executor is controlled by the caller (e.g. abci.App) so we do not acquire it here to avoid // deadlock defer func() { if r := recover(); r != nil { - err = fmt.Errorf("recovered from panic in executor.Commit(): %v\n%v", r, debug.Stack()) + err = fmt.Errorf("recovered from panic in executor.Commit(): %v\n%s", r, debug.Stack()) } }() - return exe.state.Update(func(ws Updatable) error { + exe.logger.InfoMsg("Executor committing", "height", exe.blockExecution.Height) + // Form BlockExecution for this block from TxExecutions and Tendermint block header + blockExecution, err := exe.finaliseBlockExecution(header) + if err != nil { + return nil, err + } + hash, err := exe.state.Update(func(ws Updatable) error { // flush the caches err := exe.stateCache.Flush(ws, exe.state) if err != nil { @@ -185,17 +222,27 @@ func (exe *executor) Commit() (_ []byte, err error) { if err != nil { return err } - err = exe.eventCache.Sync(ws) - if err != nil { - return err - } - // flush events to listeners - err = exe.eventCache.Flush(exe.publisher) + err = ws.AddBlock(blockExecution) if err != nil { return err } return nil }) + if err != nil { + return nil, err + } + // Now state is committed publish events + for _, txe := range blockExecution.TxExecutions { + publishErr := exe.publisher.Publish(context.Background(), txe, txe.Tagged()) + exe.logger.InfoMsg("Error publishing TxExecution", + "tx_hash", txe.TxHash, + structure.ErrorKey, publishErr) + } + publishErr := exe.publisher.Publish(context.Background(), blockExecution, blockExecution.Tagged()) + exe.logger.InfoMsg("Error publishing TxExecution", + "height", blockExecution.Height, + structure.ErrorKey, publishErr) + return hash, nil } func (exe *executor) Reset() error { diff --git a/execution/execution_test.go b/execution/execution_test.go index 74e5689cc..608da343c 100644 --- a/execution/execution_test.go +++ b/execution/execution_test.go @@ -16,7 +16,6 @@ package execution import ( "bytes" - "context" "fmt" "strconv" "testing" @@ -24,24 +23,22 @@ import ( "runtime/debug" - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/state" . "github.com/hyperledger/burrow/binary" bcm "github.com/hyperledger/burrow/blockchain" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/event" "github.com/hyperledger/burrow/execution/errors" - "github.com/hyperledger/burrow/execution/events" "github.com/hyperledger/burrow/execution/evm" . "github.com/hyperledger/burrow/execution/evm/asm" "github.com/hyperledger/burrow/execution/evm/asm/bc" "github.com/hyperledger/burrow/execution/evm/sha3" + "github.com/hyperledger/burrow/execution/exec" "github.com/hyperledger/burrow/execution/names" "github.com/hyperledger/burrow/genesis" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/permission" - "github.com/hyperledger/burrow/permission/snatives" - ptypes "github.com/hyperledger/burrow/permission/types" "github.com/hyperledger/burrow/txs" "github.com/hyperledger/burrow/txs/payload" "github.com/stretchr/testify/require" @@ -127,7 +124,32 @@ var testChainID = testGenesisDoc.ChainID() type testExecutor struct { *executor blockchain *bcm.Blockchain - event.Emitter +} + +func makeExecutor(state *State) *testExecutor { + blockchain := newBlockchain(testGenesisDoc) + return &testExecutor{ + executor: newExecutor("makeExecutorCache", true, state, blockchain.Tip, event.NewNoOpPublisher(), + logger), + blockchain: blockchain, + } +} + +func (te *testExecutor) signExecuteCommit(tx payload.Payload, signer acm.AddressableSigner) error { + txEnv := txs.Enclose(testChainID, tx) + err := txEnv.Sign(signer) + if err != nil { + return err + } + _, err = te.Execute(txEnv) + if err != nil { + return err + } + appHash, err := te.Commit(nil) + if err != nil { + return err + } + return te.blockchain.CommitBlock(time.Now(), nil, appHash) } func makeUsers(n int) []acm.AddressableSigner { @@ -145,17 +167,7 @@ func newBlockchain(genesisDoc *genesis.GenesisDoc) *bcm.Blockchain { return bc } -func makeExecutor(state *State) *testExecutor { - emitter := event.NewEmitter(logger) - blockchain := newBlockchain(testGenesisDoc) - return &testExecutor{ - executor: newExecutor("makeExecutorCache", true, state, blockchain.Tip, emitter, logger), - blockchain: blockchain, - Emitter: emitter, - } -} - -func newBaseGenDoc(globalPerm, accountPerm ptypes.AccountPermissions) genesis.GenesisDoc { +func newBaseGenDoc(globalPerm, accountPerm permission.AccountPermissions) genesis.GenesisDoc { var genAccounts []genesis.Account for _, user := range users[:5] { accountPermCopy := accountPerm // Create new instance for custom overridability. @@ -189,18 +201,13 @@ func newBaseGenDoc(globalPerm, accountPerm ptypes.AccountPermissions) genesis.Ge } } -//func getAccount(state state.AccountGetter, address acm.Address) acm.MutableAccount { -// acc, _ := state.GetMutableAccount(state, address) -// return acc -//} - func TestSendFails(t *testing.T) { stateDB := dbm.NewDB("state", dbBackend, dbDir) defer stateDB.Close() genDoc := newBaseGenDoc(permission.ZeroAccountPermissions, permission.ZeroAccountPermissions) - genDoc.Accounts[1].Permissions.Base.Set(ptypes.Send, true) - genDoc.Accounts[2].Permissions.Base.Set(ptypes.Call, true) - genDoc.Accounts[3].Permissions.Base.Set(ptypes.CreateContract, true) + genDoc.Accounts[1].Permissions.Base.Set(permission.Send, true) + genDoc.Accounts[2].Permissions.Base.Set(permission.Call, true) + genDoc.Accounts[3].Permissions.Base.Set(permission.CreateContract, true) st, err := MakeGenesisState(stateDB, &genDoc) require.NoError(t, err) exe := makeExecutor(st) @@ -235,7 +242,7 @@ func TestSendFails(t *testing.T) { // simple send tx to unknown account without create_account perm should fail acc := getAccount(exe.stateCache, users[3].Address()) - acc.MutablePermissions().Base.Set(ptypes.Send, true) + acc.MutablePermissions().Base.Set(permission.Send, true) exe.stateCache.UpdateAccount(acc) tx = payload.NewSendTx() if err := tx.AddInput(exe.stateCache, users[3].PublicKey(), 5); err != nil { @@ -249,8 +256,8 @@ func TestName(t *testing.T) { stateDB := dbm.NewDB("state", dbBackend, dbDir) defer stateDB.Close() genDoc := newBaseGenDoc(permission.ZeroAccountPermissions, permission.ZeroAccountPermissions) - genDoc.Accounts[0].Permissions.Base.Set(ptypes.Send, true) - genDoc.Accounts[1].Permissions.Base.Set(ptypes.Name, true) + genDoc.Accounts[0].Permissions.Base.Set(permission.Send, true) + genDoc.Accounts[1].Permissions.Base.Set(permission.Name, true) st, err := MakeGenesisState(stateDB, &genDoc) require.NoError(t, err) batchCommitter := makeExecutor(st) @@ -277,9 +284,9 @@ func TestCallFails(t *testing.T) { stateDB := dbm.NewDB("state", dbBackend, dbDir) defer stateDB.Close() genDoc := newBaseGenDoc(permission.ZeroAccountPermissions, permission.ZeroAccountPermissions) - genDoc.Accounts[1].Permissions.Base.Set(ptypes.Send, true) - genDoc.Accounts[2].Permissions.Base.Set(ptypes.Call, true) - genDoc.Accounts[3].Permissions.Base.Set(ptypes.CreateContract, true) + genDoc.Accounts[1].Permissions.Base.Set(permission.Send, true) + genDoc.Accounts[2].Permissions.Base.Set(permission.Call, true) + genDoc.Accounts[3].Permissions.Base.Set(permission.CreateContract, true) st, err := MakeGenesisState(stateDB, &genDoc) require.NoError(t, err) batchCommitter := makeExecutor(st) @@ -320,7 +327,7 @@ func TestSendPermission(t *testing.T) { stateDB := dbm.NewDB("state", dbBackend, dbDir) defer stateDB.Close() genDoc := newBaseGenDoc(permission.ZeroAccountPermissions, permission.ZeroAccountPermissions) - genDoc.Accounts[0].Permissions.Base.Set(ptypes.Send, true) // give the 0 account permission + genDoc.Accounts[0].Permissions.Base.Set(permission.Send, true) // give the 0 account permission st, err := MakeGenesisState(stateDB, &genDoc) require.NoError(t, err) batchCommitter := makeExecutor(st) @@ -345,7 +352,7 @@ func TestCallPermission(t *testing.T) { stateDB := dbm.NewDB("state", dbBackend, dbDir) defer stateDB.Close() genDoc := newBaseGenDoc(permission.ZeroAccountPermissions, permission.ZeroAccountPermissions) - genDoc.Accounts[0].Permissions.Base.Set(ptypes.Call, true) // give the 0 account permission + genDoc.Accounts[0].Permissions.Base.Set(permission.Call, true) // give the 0 account permission st, err := MakeGenesisState(stateDB, &genDoc) require.NoError(t, err) exe := makeExecutor(st) @@ -361,7 +368,6 @@ func TestCallPermission(t *testing.T) { Balance: 0, Code: []byte{0x60}, Sequence: 0, - StorageRoot: Zero256.Bytes(), Permissions: permission.ZeroAccountPermissions, }.MutableAccount() st.writeState.UpdateAccount(simpleAcc) @@ -382,7 +388,6 @@ func TestCallPermission(t *testing.T) { Balance: 10000, Code: contractCode, Sequence: 0, - StorageRoot: Zero256.Bytes(), Permissions: permission.ZeroAccountPermissions, }.MutableAccount() exe.stateCache.UpdateAccount(caller1Acc) @@ -401,14 +406,14 @@ func TestCallPermission(t *testing.T) { fmt.Println("\n##### CALL TO SIMPLE CONTRACT (PASS)") // A single input, having the permission, and the contract has permission - caller1Acc.MutablePermissions().Base.Set(ptypes.Call, true) + caller1Acc.MutablePermissions().Base.Set(permission.Call, true) exe.stateCache.UpdateAccount(caller1Acc) tx, _ = payload.NewCallTx(exe.stateCache, users[0].PublicKey(), &caller1ContractAddr, nil, 100, 10000, 100) txEnv = txs.Enclose(testChainID, tx) require.NoError(t, txEnv.Sign(users[0])) // we need to subscribe to the Call event to detect the exception - _, err = execTxWaitAccountCall(t, exe, txEnv, caller1ContractAddr) // + _, err = execTxWaitAccountCall(t, exe, txEnv, caller1ContractAddr) require.NoError(t, err) //---------------------------------------------------------- @@ -424,11 +429,10 @@ func TestCallPermission(t *testing.T) { Balance: 1000, Code: contractCode2, Sequence: 0, - StorageRoot: Zero256.Bytes(), Permissions: permission.ZeroAccountPermissions, }.MutableAccount() - caller1Acc.MutablePermissions().Base.Set(ptypes.Call, false) - caller2Acc.MutablePermissions().Base.Set(ptypes.Call, true) + caller1Acc.MutablePermissions().Base.Set(permission.Call, false) + caller2Acc.MutablePermissions().Base.Set(permission.Call, true) exe.stateCache.UpdateAccount(caller1Acc) exe.stateCache.UpdateAccount(caller2Acc) @@ -445,7 +449,7 @@ func TestCallPermission(t *testing.T) { // both caller1 and caller2 have permission fmt.Println("\n##### CALL TO CONTRACT CALLING SIMPLE CONTRACT (PASS)") - caller1Acc.MutablePermissions().Base.Set(ptypes.Call, true) + caller1Acc.MutablePermissions().Base.Set(permission.Call, true) exe.stateCache.UpdateAccount(caller1Acc) tx, _ = payload.NewCallTx(exe.stateCache, users[0].PublicKey(), &caller2ContractAddr, nil, 100, 10000, 100) @@ -461,8 +465,8 @@ func TestCreatePermission(t *testing.T) { stateDB := dbm.NewDB("state", dbBackend, dbDir) defer stateDB.Close() genDoc := newBaseGenDoc(permission.ZeroAccountPermissions, permission.ZeroAccountPermissions) - genDoc.Accounts[0].Permissions.Base.Set(ptypes.CreateContract, true) // give the 0 account permission - genDoc.Accounts[0].Permissions.Base.Set(ptypes.Call, true) // give the 0 account permission + genDoc.Accounts[0].Permissions.Base.Set(permission.CreateContract, true) // give the 0 account permission + genDoc.Accounts[0].Permissions.Base.Set(permission.Call, true) // give the 0 account permission st, err := MakeGenesisState(stateDB, &genDoc) require.NoError(t, err) exe := makeExecutor(st) @@ -527,7 +531,7 @@ func TestCreatePermission(t *testing.T) { // call the contract (should PASS) fmt.Println("\n###### CALL THE FACTORY (PASS)") - contractAcc.MutablePermissions().Base.Set(ptypes.CreateContract, true) + contractAcc.MutablePermissions().Base.Set(permission.CreateContract, true) exe.stateCache.UpdateAccount(contractAcc) // A single input, having the permission, should succeed @@ -548,11 +552,10 @@ func TestCreatePermission(t *testing.T) { Balance: 1000, Code: code, Sequence: 0, - StorageRoot: Zero256.Bytes(), Permissions: permission.ZeroAccountPermissions, }.MutableAccount() - contractAcc.MutablePermissions().Base.Set(ptypes.Call, true) - contractAcc.MutablePermissions().Base.Set(ptypes.CreateContract, true) + contractAcc.MutablePermissions().Base.Set(permission.Call, true) + contractAcc.MutablePermissions().Base.Set(permission.CreateContract, true) exe.stateCache.UpdateAccount(contractAcc) // this should call the 0 address but not create ... @@ -572,9 +575,9 @@ func TestCreateAccountPermission(t *testing.T) { stateDB := dbm.NewDB("state", dbBackend, dbDir) defer stateDB.Close() genDoc := newBaseGenDoc(permission.ZeroAccountPermissions, permission.ZeroAccountPermissions) - genDoc.Accounts[0].Permissions.Base.Set(ptypes.Send, true) // give the 0 account permission - genDoc.Accounts[1].Permissions.Base.Set(ptypes.Send, true) // give the 0 account permission - genDoc.Accounts[0].Permissions.Base.Set(ptypes.CreateAccount, true) // give the 0 account permission + genDoc.Accounts[0].Permissions.Base.Set(permission.Send, true) // give the 0 account permission + genDoc.Accounts[1].Permissions.Base.Set(permission.Send, true) // give the 0 account permission + genDoc.Accounts[0].Permissions.Base.Set(permission.CreateAccount, true) // give the 0 account permission st, err := MakeGenesisState(stateDB, &genDoc) require.NoError(t, err) batchCommitter := makeExecutor(st) @@ -615,7 +618,7 @@ func TestCreateAccountPermission(t *testing.T) { // Two inputs, both with send, both with create, should pass acc := getAccount(batchCommitter.stateCache, users[1].Address()) - acc.MutablePermissions().Base.Set(ptypes.CreateAccount, true) + acc.MutablePermissions().Base.Set(permission.CreateAccount, true) batchCommitter.stateCache.UpdateAccount(acc) tx = payload.NewSendTx() if err := tx.AddInput(batchCommitter.stateCache, users[0].PublicKey(), 5); err != nil { @@ -643,7 +646,7 @@ func TestCreateAccountPermission(t *testing.T) { // CALL to unknown account acc = getAccount(batchCommitter.stateCache, users[0].Address()) - acc.MutablePermissions().Base.Set(ptypes.Call, true) + acc.MutablePermissions().Base.Set(permission.Call, true) batchCommitter.stateCache.UpdateAccount(acc) // call to contract that calls unknown account - without create_account perm @@ -655,7 +658,6 @@ func TestCreateAccountPermission(t *testing.T) { Balance: 0, Code: contractCode, Sequence: 0, - StorageRoot: Zero256.Bytes(), Permissions: permission.ZeroAccountPermissions, }.MutableAccount() batchCommitter.stateCache.UpdateAccount(caller1Acc) @@ -671,8 +673,8 @@ func TestCreateAccountPermission(t *testing.T) { // NOTE: for a contract to be able to CreateAccount, it must be able to call // NOTE: for a users to be able to CreateAccount, it must be able to send! - caller1Acc.MutablePermissions().Base.Set(ptypes.CreateAccount, true) - caller1Acc.MutablePermissions().Base.Set(ptypes.Call, true) + caller1Acc.MutablePermissions().Base.Set(permission.CreateAccount, true) + caller1Acc.MutablePermissions().Base.Set(permission.Call, true) batchCommitter.stateCache.UpdateAccount(caller1Acc) // A single input, having the permission, but the contract doesn't have permission txCall, _ = payload.NewCallTx(batchCommitter.stateCache, users[0].PublicKey(), &caller1ContractAddr, nil, 100, 10000, 100) @@ -696,8 +698,8 @@ func TestSNativeCALL(t *testing.T) { stateDB := dbm.NewDB("state", dbBackend, dbDir) defer stateDB.Close() genDoc := newBaseGenDoc(permission.ZeroAccountPermissions, permission.ZeroAccountPermissions) - genDoc.Accounts[0].Permissions.Base.Set(ptypes.Call, true) // give the 0 account permission - genDoc.Accounts[3].Permissions.Base.Set(ptypes.Bond, true) // some arbitrary permission to play with + genDoc.Accounts[0].Permissions.Base.Set(permission.Call, true) // give the 0 account permission + genDoc.Accounts[3].Permissions.Base.Set(permission.Bond, true) // some arbitrary permission to play with genDoc.Accounts[3].Permissions.AddRole("bumble") genDoc.Accounts[3].Permissions.AddRole("bee") st, err := MakeGenesisState(stateDB, &genDoc) @@ -713,17 +715,16 @@ func TestSNativeCALL(t *testing.T) { Balance: 0, Code: nil, Sequence: 0, - StorageRoot: Zero256.Bytes(), Permissions: permission.ZeroAccountPermissions, }.MutableAccount() - doug.MutablePermissions().Base.Set(ptypes.Call, true) + doug.MutablePermissions().Base.Set(permission.Call, true) //doug.Permissions.Base.Set(permission.HasBase, true) exe.stateCache.UpdateAccount(doug) fmt.Println("\n#### HasBase") // HasBase - snativeAddress, pF, data := snativePermTestInputCALL("hasBase", users[3], ptypes.Bond, false) + snativeAddress, pF, data := snativePermTestInputCALL("hasBase", users[3], permission.Bond, false) testSNativeCALLExpectFail(t, exe, doug, snativeAddress, data) testSNativeCALLExpectPass(t, exe, doug, pF, snativeAddress, data, func(ret []byte) error { // return value should be true or false as a 32 byte array... @@ -735,10 +736,10 @@ func TestSNativeCALL(t *testing.T) { fmt.Println("\n#### SetBase") // SetBase - snativeAddress, pF, data = snativePermTestInputCALL("setBase", users[3], ptypes.Bond, false) + snativeAddress, pF, data = snativePermTestInputCALL("setBase", users[3], permission.Bond, false) testSNativeCALLExpectFail(t, exe, doug, snativeAddress, data) testSNativeCALLExpectPass(t, exe, doug, pF, snativeAddress, data, func(ret []byte) error { return nil }) - snativeAddress, pF, data = snativePermTestInputCALL("hasBase", users[3], ptypes.Bond, false) + snativeAddress, pF, data = snativePermTestInputCALL("hasBase", users[3], permission.Bond, false) testSNativeCALLExpectPass(t, exe, doug, pF, snativeAddress, data, func(ret []byte) error { // return value should be true or false as a 32 byte array... if !IsZeros(ret) { @@ -746,9 +747,9 @@ func TestSNativeCALL(t *testing.T) { } return nil }) - snativeAddress, pF, data = snativePermTestInputCALL("setBase", users[3], ptypes.CreateContract, true) + snativeAddress, pF, data = snativePermTestInputCALL("setBase", users[3], permission.CreateContract, true) testSNativeCALLExpectPass(t, exe, doug, pF, snativeAddress, data, func(ret []byte) error { return nil }) - snativeAddress, pF, data = snativePermTestInputCALL("hasBase", users[3], ptypes.CreateContract, false) + snativeAddress, pF, data = snativePermTestInputCALL("hasBase", users[3], permission.CreateContract, false) testSNativeCALLExpectPass(t, exe, doug, pF, snativeAddress, data, func(ret []byte) error { // return value should be true or false as a 32 byte array... if !IsZeros(ret[:31]) || ret[31] != byte(1) { @@ -759,10 +760,10 @@ func TestSNativeCALL(t *testing.T) { fmt.Println("\n#### UnsetBase") // UnsetBase - snativeAddress, pF, data = snativePermTestInputCALL("unsetBase", users[3], ptypes.CreateContract, false) + snativeAddress, pF, data = snativePermTestInputCALL("unsetBase", users[3], permission.CreateContract, false) testSNativeCALLExpectFail(t, exe, doug, snativeAddress, data) testSNativeCALLExpectPass(t, exe, doug, pF, snativeAddress, data, func(ret []byte) error { return nil }) - snativeAddress, pF, data = snativePermTestInputCALL("hasBase", users[3], ptypes.CreateContract, false) + snativeAddress, pF, data = snativePermTestInputCALL("hasBase", users[3], permission.CreateContract, false) testSNativeCALLExpectPass(t, exe, doug, pF, snativeAddress, data, func(ret []byte) error { if !IsZeros(ret) { return fmt.Errorf("Expected 0. Got %X", ret) @@ -772,10 +773,10 @@ func TestSNativeCALL(t *testing.T) { fmt.Println("\n#### SetGlobal") // SetGlobalPerm - snativeAddress, pF, data = snativePermTestInputCALL("setGlobal", users[3], ptypes.CreateContract, true) + snativeAddress, pF, data = snativePermTestInputCALL("setGlobal", users[3], permission.CreateContract, true) testSNativeCALLExpectFail(t, exe, doug, snativeAddress, data) testSNativeCALLExpectPass(t, exe, doug, pF, snativeAddress, data, func(ret []byte) error { return nil }) - snativeAddress, pF, data = snativePermTestInputCALL("hasBase", users[3], ptypes.CreateContract, false) + snativeAddress, pF, data = snativePermTestInputCALL("hasBase", users[3], permission.CreateContract, false) testSNativeCALLExpectPass(t, exe, doug, pF, snativeAddress, data, func(ret []byte) error { // return value should be true or false as a 32 byte array... if !IsZeros(ret[:31]) || ret[31] != byte(1) { @@ -833,8 +834,8 @@ func TestSNativeTx(t *testing.T) { stateDB := dbm.NewDB("state", dbBackend, dbDir) defer stateDB.Close() genDoc := newBaseGenDoc(permission.ZeroAccountPermissions, permission.ZeroAccountPermissions) - genDoc.Accounts[0].Permissions.Base.Set(ptypes.Call, true) // give the 0 account permission - genDoc.Accounts[3].Permissions.Base.Set(ptypes.Bond, true) // some arbitrary permission to play with + genDoc.Accounts[0].Permissions.Base.Set(permission.Call, true) // give the 0 account permission + genDoc.Accounts[3].Permissions.Base.Set(permission.Bond, true) // some arbitrary permission to play with genDoc.Accounts[3].Permissions.AddRole("bumble") genDoc.Accounts[3].Permissions.AddRole("bee") st, err := MakeGenesisState(stateDB, &genDoc) @@ -846,37 +847,37 @@ func TestSNativeTx(t *testing.T) { fmt.Println("\n#### SetBase") // SetBase - snativeArgs := snativePermTestInputTx("setBase", users[3], ptypes.Bond, false) + snativeArgs := snativePermTestInputTx("setBase", users[3], permission.Bond, false) testSNativeTxExpectFail(t, batchCommitter, snativeArgs) - testSNativeTxExpectPass(t, batchCommitter, ptypes.SetBase, snativeArgs) + testSNativeTxExpectPass(t, batchCommitter, permission.SetBase, snativeArgs) acc := getAccount(batchCommitter.stateCache, users[3].Address()) - if v, _ := acc.MutablePermissions().Base.Get(ptypes.Bond); v { + if v, _ := acc.MutablePermissions().Base.Get(permission.Bond); v { t.Fatal("expected permission to be set false") } - snativeArgs = snativePermTestInputTx("setBase", users[3], ptypes.CreateContract, true) - testSNativeTxExpectPass(t, batchCommitter, ptypes.SetBase, snativeArgs) + snativeArgs = snativePermTestInputTx("setBase", users[3], permission.CreateContract, true) + testSNativeTxExpectPass(t, batchCommitter, permission.SetBase, snativeArgs) acc = getAccount(batchCommitter.stateCache, users[3].Address()) - if v, _ := acc.MutablePermissions().Base.Get(ptypes.CreateContract); !v { + if v, _ := acc.MutablePermissions().Base.Get(permission.CreateContract); !v { t.Fatal("expected permission to be set true") } fmt.Println("\n#### UnsetBase") // UnsetBase - snativeArgs = snativePermTestInputTx("unsetBase", users[3], ptypes.CreateContract, false) + snativeArgs = snativePermTestInputTx("unsetBase", users[3], permission.CreateContract, false) testSNativeTxExpectFail(t, batchCommitter, snativeArgs) - testSNativeTxExpectPass(t, batchCommitter, ptypes.UnsetBase, snativeArgs) + testSNativeTxExpectPass(t, batchCommitter, permission.UnsetBase, snativeArgs) acc = getAccount(batchCommitter.stateCache, users[3].Address()) - if v, _ := acc.MutablePermissions().Base.Get(ptypes.CreateContract); v { + if v, _ := acc.MutablePermissions().Base.Get(permission.CreateContract); v { t.Fatal("expected permission to be set false") } fmt.Println("\n#### SetGlobal") // SetGlobalPerm - snativeArgs = snativePermTestInputTx("setGlobal", users[3], ptypes.CreateContract, true) + snativeArgs = snativePermTestInputTx("setGlobal", users[3], permission.CreateContract, true) testSNativeTxExpectFail(t, batchCommitter, snativeArgs) - testSNativeTxExpectPass(t, batchCommitter, ptypes.SetGlobal, snativeArgs) + testSNativeTxExpectPass(t, batchCommitter, permission.SetGlobal, snativeArgs) acc = getAccount(batchCommitter.stateCache, acm.GlobalPermissionsAddress) - if v, _ := acc.MutablePermissions().Base.Get(ptypes.CreateContract); !v { + if v, _ := acc.MutablePermissions().Base.Get(permission.CreateContract); !v { t.Fatal("expected permission to be set true") } @@ -884,7 +885,7 @@ func TestSNativeTx(t *testing.T) { // AddRole snativeArgs = snativeRoleTestInputTx("addRole", users[3], "chuck") testSNativeTxExpectFail(t, batchCommitter, snativeArgs) - testSNativeTxExpectPass(t, batchCommitter, ptypes.AddRole, snativeArgs) + testSNativeTxExpectPass(t, batchCommitter, permission.AddRole, snativeArgs) acc = getAccount(batchCommitter.stateCache, users[3].Address()) if v := acc.Permissions().HasRole("chuck"); !v { t.Fatal("expected role to be added") @@ -894,7 +895,7 @@ func TestSNativeTx(t *testing.T) { // RemoveRole snativeArgs = snativeRoleTestInputTx("removeRole", users[3], "chuck") testSNativeTxExpectFail(t, batchCommitter, snativeArgs) - testSNativeTxExpectPass(t, batchCommitter, ptypes.RemoveRole, snativeArgs) + testSNativeTxExpectPass(t, batchCommitter, permission.RemoveRole, snativeArgs) acc = getAccount(batchCommitter.stateCache, users[3].Address()) if v := acc.Permissions().HasRole("chuck"); v { t.Fatal("expected role to be removed") @@ -951,8 +952,8 @@ func TestNameTxs(t *testing.T) { st.writeState.save() names.MinNameRegistrationPeriod = 5 - blockchain := newBlockchain(testGenesisDoc) - startingBlock := blockchain.LastBlockHeight() + exe := makeExecutor(st) + startingBlock := exe.blockchain.LastBlockHeight() // try some bad names. these should all fail nameStrings := []string{"", "\n", "123#$%", "\x00", string([]byte{20, 40, 60, 80}), @@ -964,10 +965,8 @@ func TestNameTxs(t *testing.T) { amt := fee + numDesiredBlocks*names.NameByteCostMultiplier*names.NameBlockCostMultiplier* names.NameBaseCost(name, data) tx, _ := payload.NewNameTx(st, testPrivAccounts[0].PublicKey(), name, data, amt, fee) - txEnv := txs.Enclose(testChainID, tx) - txEnv.Sign(testPrivAccounts[0]) - if err := execTxWithState(st, txEnv); err == nil { + if err = exe.signExecuteCommit(tx, testPrivAccounts[0]); err == nil { t.Fatalf("Expected invalid name error from %s", name) } } @@ -979,10 +978,8 @@ func TestNameTxs(t *testing.T) { amt := fee + numDesiredBlocks*names.NameByteCostMultiplier*names.NameBlockCostMultiplier* names.NameBaseCost(name, data) tx, _ := payload.NewNameTx(st, testPrivAccounts[0].PublicKey(), name, data, amt, fee) - txEnv := txs.Enclose(testChainID, tx) - txEnv.Sign(testPrivAccounts[0]) - if err := execTxWithState(st, txEnv); err == nil { + if err = exe.signExecuteCommit(tx, testPrivAccounts[0]); err == nil { t.Fatalf("Expected invalid data error from %s", data) } } @@ -1010,68 +1007,50 @@ func TestNameTxs(t *testing.T) { data = "on this side of neptune there are 1234567890 people: first is OMNIVORE+-3. Or is it. Ok this is pretty restrictive. No exclamations :(. Faces tho :')" amt := fee + numDesiredBlocks*names.NameByteCostMultiplier*names.NameBlockCostMultiplier*names.NameBaseCost(name, data) tx, _ := payload.NewNameTx(st, testPrivAccounts[0].PublicKey(), name, data, amt, fee) - txEnv := txs.Enclose(testChainID, tx) - require.NoError(t, txEnv.Sign(testPrivAccounts[0])) - if err := execTxWithState(st, txEnv); err != nil { - t.Fatal(err) - } - entry, err := st.GetNameEntry(name) + + require.NoError(t, exe.signExecuteCommit(tx, testPrivAccounts[0])) + + entry, err := st.GetName(name) require.NoError(t, err) validateEntry(t, entry, name, data, testPrivAccounts[0].Address(), startingBlock+numDesiredBlocks) // fail to update it as non-owner, in same block tx, _ = payload.NewNameTx(st, testPrivAccounts[1].PublicKey(), name, data, amt, fee) - txEnv = txs.Enclose(testChainID, tx) - require.NoError(t, txEnv.Sign(testPrivAccounts[1])) - if err := execTxWithState(st, txEnv); err == nil { - t.Fatal("Expected error") - } + require.Error(t, exe.signExecuteCommit(tx, testPrivAccounts[1])) // update it as owner, just to increase expiry, in same block // NOTE: we have to resend the data or it will clear it (is this what we want?) tx, _ = payload.NewNameTx(st, testPrivAccounts[0].PublicKey(), name, data, amt, fee) - txEnv = txs.Enclose(testChainID, tx) - require.NoError(t, txEnv.Sign(testPrivAccounts[0])) - if err := execTxWithStateNewBlock(st, blockchain, txEnv); err != nil { - t.Fatal(err) - } - entry, err = st.GetNameEntry(name) + + require.NoError(t, exe.signExecuteCommit(tx, testPrivAccounts[0])) + + entry, err = st.GetName(name) require.NoError(t, err) validateEntry(t, entry, name, data, testPrivAccounts[0].Address(), startingBlock+numDesiredBlocks*2) // update it as owner, just to increase expiry, in next block tx, _ = payload.NewNameTx(st, testPrivAccounts[0].PublicKey(), name, data, amt, fee) - txEnv = txs.Enclose(testChainID, tx) - require.NoError(t, txEnv.Sign(testPrivAccounts[0])) - if err := execTxWithStateNewBlock(st, blockchain, txEnv); err != nil { - t.Fatal(err) - } - entry, err = st.GetNameEntry(name) + require.NoError(t, exe.signExecuteCommit(tx, testPrivAccounts[0])) + + entry, err = st.GetName(name) require.NoError(t, err) validateEntry(t, entry, name, data, testPrivAccounts[0].Address(), startingBlock+numDesiredBlocks*3) // fail to update it as non-owner // Fast forward - for blockchain.Tip.LastBlockHeight() < entry.Expires-1 { - commitNewBlock(st, blockchain) + for exe.blockchain.Tip.LastBlockHeight() < entry.Expires-1 { + commitNewBlock(st, exe.blockchain) } tx, _ = payload.NewNameTx(st, testPrivAccounts[1].PublicKey(), name, data, amt, fee) - txEnv = txs.Enclose(testChainID, tx) - require.NoError(t, txEnv.Sign(testPrivAccounts[1])) - if err := execTxWithStateAndBlockchain(st, blockchain, txEnv); err == nil { - t.Fatal("Expected error") - } - commitNewBlock(st, blockchain) + require.Error(t, exe.signExecuteCommit(tx, testPrivAccounts[1])) + commitNewBlock(st, exe.blockchain) // once expires, non-owner succeeds - startingBlock = blockchain.LastBlockHeight() + startingBlock = exe.blockchain.LastBlockHeight() tx, _ = payload.NewNameTx(st, testPrivAccounts[1].PublicKey(), name, data, amt, fee) - txEnv = txs.Enclose(testChainID, tx) - require.NoError(t, txEnv.Sign(testPrivAccounts[1])) - if err := execTxWithStateAndBlockchain(st, blockchain, txEnv); err != nil { - t.Fatal(err) - } - entry, err = st.GetNameEntry(name) + require.NoError(t, exe.signExecuteCommit(tx, testPrivAccounts[1])) + + entry, err = st.GetName(name) require.NoError(t, err) validateEntry(t, entry, name, data, testPrivAccounts[1].Address(), startingBlock+numDesiredBlocks) @@ -1081,12 +1060,9 @@ func TestNameTxs(t *testing.T) { numDesiredBlocks = 10 amt = fee + numDesiredBlocks*names.NameByteCostMultiplier*names.NameBlockCostMultiplier*names.NameBaseCost(name, data) - oldCredit tx, _ = payload.NewNameTx(st, testPrivAccounts[1].PublicKey(), name, data, amt, fee) - txEnv = txs.Enclose(testChainID, tx) - require.NoError(t, txEnv.Sign(testPrivAccounts[1])) - if err := execTxWithStateAndBlockchain(st, blockchain, txEnv); err != nil { - t.Fatal(err) - } - entry, err = st.GetNameEntry(name) + require.NoError(t, exe.signExecuteCommit(tx, testPrivAccounts[1])) + + entry, err = st.GetName(name) require.NoError(t, err) validateEntry(t, entry, name, data, testPrivAccounts[1].Address(), startingBlock+numDesiredBlocks) @@ -1094,12 +1070,9 @@ func TestNameTxs(t *testing.T) { amt = fee data = "" tx, _ = payload.NewNameTx(st, testPrivAccounts[1].PublicKey(), name, data, amt, fee) - txEnv = txs.Enclose(testChainID, tx) - require.NoError(t, txEnv.Sign(testPrivAccounts[1])) - if err := execTxWithStateNewBlock(st, blockchain, txEnv); err != nil { - t.Fatal(err) - } - entry, err = st.GetNameEntry(name) + require.NoError(t, exe.signExecuteCommit(tx, testPrivAccounts[1])) + + entry, err = st.GetName(name) require.NoError(t, err) if entry != nil { t.Fatal("Expected removed entry to be nil") @@ -1107,33 +1080,27 @@ func TestNameTxs(t *testing.T) { // create entry by key0, // test removal by key1 after expiry - startingBlock = blockchain.LastBlockHeight() + startingBlock = exe.blockchain.LastBlockHeight() name = "looking_good/karaoke_bar" data = "some data" amt = fee + numDesiredBlocks*names.NameByteCostMultiplier*names.NameBlockCostMultiplier*names.NameBaseCost(name, data) tx, _ = payload.NewNameTx(st, testPrivAccounts[0].PublicKey(), name, data, amt, fee) - txEnv = txs.Enclose(testChainID, tx) - require.NoError(t, txEnv.Sign(testPrivAccounts[0])) - if err := execTxWithStateAndBlockchain(st, blockchain, txEnv); err != nil { - t.Fatal(err) - } - entry, err = st.GetNameEntry(name) + require.NoError(t, exe.signExecuteCommit(tx, testPrivAccounts[0])) + + entry, err = st.GetName(name) require.NoError(t, err) validateEntry(t, entry, name, data, testPrivAccounts[0].Address(), startingBlock+numDesiredBlocks) // Fast forward - for blockchain.Tip.LastBlockHeight() < entry.Expires { - commitNewBlock(st, blockchain) + for exe.blockchain.Tip.LastBlockHeight() < entry.Expires { + commitNewBlock(st, exe.blockchain) } amt = fee data = "" tx, _ = payload.NewNameTx(st, testPrivAccounts[1].PublicKey(), name, data, amt, fee) - txEnv = txs.Enclose(testChainID, tx) - require.NoError(t, txEnv.Sign(testPrivAccounts[1])) - if err := execTxWithStateNewBlock(st, blockchain, txEnv); err != nil { - t.Fatal(err) - } - entry, err = st.GetNameEntry(name) + require.NoError(t, exe.signExecuteCommit(tx, testPrivAccounts[1])) + + entry, err = st.GetName(name) require.NoError(t, err) if entry != nil { t.Fatal("Expected removed entry to be nil") @@ -1166,20 +1133,22 @@ var createData, _ = hex.DecodeString("9ed93318") func TestCreates(t *testing.T) { //evm.SetDebug(true) - state, privAccounts := makeGenesisState(3, true, 1000, 1, true, 1000) + st, privAccounts := makeGenesisState(3, true, 1000, 1, true, 1000) //val0 := state.GetValidatorInfo(privValidators[0].Address()) - acc0 := getAccount(state, privAccounts[0].Address()) - acc1 := getAccount(state, privAccounts[1].Address()) - acc2 := getAccount(state, privAccounts[2].Address()) + acc0 := getAccount(st, privAccounts[0].Address()) + acc1 := getAccount(st, privAccounts[1].Address()) + acc2 := getAccount(st, privAccounts[2].Address()) - newAcc1 := getAccount(state, acc1.Address()) + exe := makeExecutor(st) + + newAcc1 := getAccount(st, acc1.Address()) newAcc1.SetCode(preFactoryCode) - newAcc2 := getAccount(state, acc2.Address()) + newAcc2 := getAccount(st, acc2.Address()) newAcc2.SetCode(factoryCode) - state.writeState.UpdateAccount(newAcc1) - state.writeState.UpdateAccount(newAcc2) + st.writeState.UpdateAccount(newAcc1) + st.writeState.UpdateAccount(newAcc2) createData = append(createData, acc2.Address().Word256().Bytes()...) @@ -1195,39 +1164,29 @@ func TestCreates(t *testing.T) { Data: createData, } - txEnv := txs.Enclose(testChainID, tx) - require.NoError(t, txEnv.Sign(privAccounts[0])) - err := execTxWithState(state, txEnv) - if err != nil { - t.Errorf("Got error in executing call transaction, %v", err) - } + require.NoError(t, exe.signExecuteCommit(tx, privAccounts[0])) - acc1 = getAccount(state, acc1.Address()) - firstCreatedAddress, err := state.GetStorage(acc1.Address(), LeftPadWord256(nil)) + acc1 = getAccount(st, acc1.Address()) + firstCreatedAddress, err := st.GetStorage(acc1.Address(), LeftPadWord256(nil)) require.NoError(t, err) - acc0 = getAccount(state, acc0.Address()) + acc0 = getAccount(st, acc0.Address()) // call the pre-factory, triggering the factory to run a create tx = &payload.CallTx{ Input: &payload.TxInput{ Address: acc0.Address(), Amount: 1, - Sequence: acc0.Sequence() + 1, + Sequence: tx.Input.Sequence + 1, }, Address: addressPtr(acc1), GasLimit: 100000, Data: createData, } - txEnv = txs.Enclose(testChainID, tx) - require.NoError(t, txEnv.Sign(privAccounts[0])) - err = execTxWithState(state, txEnv) - if err != nil { - t.Errorf("Got error in executing call transaction, %v", err) - } + require.NoError(t, exe.signExecuteCommit(tx, privAccounts[0])) - acc1 = getAccount(state, acc1.Address()) - secondCreatedAddress, err := state.GetStorage(acc1.Address(), LeftPadWord256(nil)) + acc1 = getAccount(st, acc1.Address()) + secondCreatedAddress, err := st.GetStorage(acc1.Address(), LeftPadWord256(nil)) require.NoError(t, err) if firstCreatedAddress == secondCreatedAddress { @@ -1487,7 +1446,7 @@ proof-of-work chain as proof of what happened while they were gone ` t.Errorf("Unexpected newAcc0 balance. Expected %v, got %v", acc0.Balance()-entryAmount, newAcc0.Balance()) } - entry, err := stateNameTx.GetNameEntry(entryName) + entry, err := stateNameTx.GetName(entryName) require.NoError(t, err) if entry == nil { t.Errorf("Expected an entry but got nil") @@ -1502,8 +1461,8 @@ proof-of-work chain as proof of what happened while they were gone ` txEnv = txs.Enclose(testChainID, tx) require.NoError(t, txEnv.Sign(privAccounts[0])) err = execTxWithState(stateNameTx, txEnv) - if _, ok := err.(payload.ErrTxInvalidString); !ok { - t.Errorf("Expected invalid string error. Got: %s", err.Error()) + if errors.AsException(err).ErrorCode() != errors.ErrorCodeInvalidString { + t.Errorf("Expected invalid string error. Got: %v", err) } } @@ -1596,7 +1555,7 @@ func TestSelfDestruct(t *testing.T) { signAndExecute(t, false, exe, testChainID, tx, privAccounts[0]) // commit the block - exe.Commit() + exe.Commit(nil) // acc2 should receive the sent funds and the contracts balance newAcc2 := getAccount(st, acc2.Address()) @@ -1616,10 +1575,11 @@ func signAndExecute(t *testing.T, shouldFail bool, exe BatchExecutor, chainID st env := txs.Enclose(chainID, tx) require.NoError(t, env.Sign(signers...), "Could not sign tx in call: %s", debug.Stack()) + _, err := exe.Execute(env) if shouldFail { - require.Error(t, exe.Execute(env), "Tx should fail in call: %s", debug.Stack()) + require.Error(t, err, "Tx should fail in call: %s", debug.Stack()) } else { - require.NoError(t, exe.Execute(env), "Could not execute tx in call: %s", debug.Stack()) + require.NoError(t, err, "Could not execute tx in call: %s", debug.Stack()) } return env } @@ -1627,10 +1587,13 @@ func signAndExecute(t *testing.T, shouldFail bool, exe BatchExecutor, chainID st func execTxWithStateAndBlockchain(state *State, blockchain *bcm.Blockchain, txEnv *txs.Envelope) error { exe := newExecutor("execTxWithStateAndBlockchainCache", true, state, blockchain.Tip, event.NewNoOpPublisher(), logger) - if err := exe.Execute(txEnv); err != nil { + if _, err := exe.Execute(txEnv); err != nil { return err } else { - exe.Commit() + _, err := exe.Commit(nil) + if err != nil { + return err + } commitNewBlock(state, blockchain) return nil } @@ -1665,7 +1628,7 @@ func makeGenesisState(numAccounts int, randBalance bool, minBalance uint64, numV return s0, privAccounts } -func getAccount(accountGetter state.AccountGetter, address crypto.Address) acm.MutableAccount { +func getAccount(accountGetter state.AccountGetter, address crypto.Address) *acm.MutableAccount { acc, _ := state.GetMutableAccount(accountGetter, address) return acc } @@ -1686,46 +1649,44 @@ var ExceptionTimeOut = errors.NewCodedError(errors.ErrorCodeGeneric, "timed out // run ExecTx and wait for the Call event on given addr // returns the msg data and an error/exception func execTxWaitAccountCall(t *testing.T, exe *testExecutor, txEnv *txs.Envelope, - address crypto.Address) (*events.EventDataCall, error) { - - ch := make(chan *events.EventDataCall) - ctx := context.Background() - const subscriber = "execTxWaitEvent" - events.SubscribeAccountCall(ctx, exe, subscriber, address, txEnv.Tx.Hash(), -1, ch) - defer exe.UnsubscribeAll(ctx, subscriber) - err := exe.Execute(txEnv) + address crypto.Address) (*exec.CallEvent, error) { + + qry, err := event.QueryForEventID(exec.EventStringAccountCall(address)). + AndEquals(event.TxHashKey, txEnv.Tx.Hash()).Query() if err != nil { return nil, err } - exe.Commit() - exe.blockchain.CommitBlock(time.Time{}, nil, nil) - ticker := time.NewTicker(5 * time.Second) - - select { - case eventDataCall := <-ch: - fmt.Println("MSG: ", eventDataCall) - return eventDataCall, eventDataCall.Exception.AsError() - - case <-ticker.C: - return nil, ExceptionTimeOut + evs, err := exe.Execute(txEnv) + if err != nil { + return nil, err } + _, err = exe.Commit(nil) + require.NoError(t, err) + err = exe.blockchain.CommitBlock(time.Time{}, nil, nil) + require.NoError(t, err) + for _, ev := range evs.TaggedEvents().Filter(qry) { + if ev.Call != nil { + return ev.Call, ev.Header.Exception.AsError() + } + } + return nil, fmt.Errorf("did not receive EventDataCall execution event from execTxWaitAccountCall") } // give a contract perms for an snative, call it, it calls the snative, but shouldn't have permission -func testSNativeCALLExpectFail(t *testing.T, exe *testExecutor, doug acm.MutableAccount, +func testSNativeCALLExpectFail(t *testing.T, exe *testExecutor, doug *acm.MutableAccount, snativeAddress crypto.Address, data []byte) { testSNativeCALL(t, false, exe, doug, 0, snativeAddress, data, nil) } // give a contract perms for an snative, call it, it calls the snative, ensure the check funciton (f) succeeds -func testSNativeCALLExpectPass(t *testing.T, exe *testExecutor, doug acm.MutableAccount, snativePerm ptypes.PermFlag, +func testSNativeCALLExpectPass(t *testing.T, exe *testExecutor, doug *acm.MutableAccount, snativePerm permission.PermFlag, snativeAddress crypto.Address, data []byte, f func([]byte) error) { testSNativeCALL(t, true, exe, doug, snativePerm, snativeAddress, data, f) } -func testSNativeCALL(t *testing.T, expectPass bool, exe *testExecutor, doug acm.MutableAccount, - snativePerm ptypes.PermFlag, snativeAddress crypto.Address, data []byte, f func([]byte) error) { +func testSNativeCALL(t *testing.T, expectPass bool, exe *testExecutor, doug *acm.MutableAccount, + snativePerm permission.PermFlag, snativeAddress crypto.Address, data []byte, f func([]byte) error) { if expectPass { doug.MutablePermissions().Base.Set(snativePerm, true) } @@ -1737,7 +1698,6 @@ func testSNativeCALL(t *testing.T, expectPass bool, exe *testExecutor, doug acm. tx, _ := payload.NewCallTx(exe.stateCache, users[0].PublicKey(), &dougAddress, data, 100, 10000, 100) txEnv := txs.Enclose(testChainID, tx) require.NoError(t, txEnv.Sign(users[0])) - t.Logf("subscribing to %v", events.EventStringAccountCall(snativeAddress)) ev, err := execTxWaitAccountCall(t, exe, txEnv, snativeAddress) if err == ExceptionTimeOut { t.Fatal("Timed out waiting for event") @@ -1753,17 +1713,17 @@ func testSNativeCALL(t *testing.T, expectPass bool, exe *testExecutor, doug acm. } } -func testSNativeTxExpectFail(t *testing.T, batchCommitter *testExecutor, snativeArgs snatives.PermArgs) { +func testSNativeTxExpectFail(t *testing.T, batchCommitter *testExecutor, snativeArgs permission.PermArgs) { testSNativeTx(t, false, batchCommitter, 0, snativeArgs) } -func testSNativeTxExpectPass(t *testing.T, batchCommitter *testExecutor, perm ptypes.PermFlag, - snativeArgs snatives.PermArgs) { +func testSNativeTxExpectPass(t *testing.T, batchCommitter *testExecutor, perm permission.PermFlag, + snativeArgs permission.PermArgs) { testSNativeTx(t, true, batchCommitter, perm, snativeArgs) } -func testSNativeTx(t *testing.T, expectPass bool, batchCommitter *testExecutor, perm ptypes.PermFlag, - snativeArgs snatives.PermArgs) { +func testSNativeTx(t *testing.T, expectPass bool, batchCommitter *testExecutor, perm permission.PermFlag, + snativeArgs permission.PermArgs) { if expectPass { acc := getAccount(batchCommitter.stateCache, users[0].Address()) acc.MutablePermissions().Base.Set(perm, true) @@ -1772,7 +1732,7 @@ func testSNativeTx(t *testing.T, expectPass bool, batchCommitter *testExecutor, tx, _ := payload.NewPermissionsTx(batchCommitter.stateCache, users[0].PublicKey(), snativeArgs) txEnv := txs.Enclose(testChainID, tx) require.NoError(t, txEnv.Sign(users[0])) - err := batchCommitter.Execute(txEnv) + _, err := batchCommitter.Execute(txEnv) if expectPass { if err != nil { t.Fatal("Unexpected exception", err) @@ -1803,8 +1763,8 @@ func permNameToFuncID(name string) []byte { return id[:] } -func snativePermTestInputCALL(name string, user acm.AddressableSigner, perm ptypes.PermFlag, - val bool) (addr crypto.Address, pF ptypes.PermFlag, data []byte) { +func snativePermTestInputCALL(name string, user acm.AddressableSigner, perm permission.PermFlag, + val bool) (addr crypto.Address, pF permission.PermFlag, data []byte) { addr = permissionsContract.Address() switch name { case "hasBase", "unsetBase": @@ -1820,50 +1780,50 @@ func snativePermTestInputCALL(name string, user acm.AddressableSigner, perm ptyp } data = append(permNameToFuncID(name), data...) var err error - if pF, err = ptypes.PermStringToFlag(name); err != nil { + if pF, err = permission.PermStringToFlag(name); err != nil { panic(fmt.Sprintf("failed to convert perm string (%s) to flag", name)) } return } -func snativePermTestInputTx(name string, user acm.AddressableSigner, perm ptypes.PermFlag, - val bool) (snativeArgs snatives.PermArgs) { +func snativePermTestInputTx(name string, user acm.AddressableSigner, perm permission.PermFlag, + val bool) (snativeArgs permission.PermArgs) { switch name { case "hasBase": - snativeArgs = snatives.HasBaseArgs(user.Address(), perm) + snativeArgs = permission.HasBaseArgs(user.Address(), perm) case "unsetBase": - snativeArgs = snatives.UnsetBaseArgs(user.Address(), perm) + snativeArgs = permission.UnsetBaseArgs(user.Address(), perm) case "setBase": - snativeArgs = snatives.SetBaseArgs(user.Address(), perm, val) + snativeArgs = permission.SetBaseArgs(user.Address(), perm, val) case "setGlobal": - snativeArgs = snatives.SetGlobalArgs(perm, val) + snativeArgs = permission.SetGlobalArgs(perm, val) } return } func snativeRoleTestInputCALL(name string, user acm.AddressableSigner, - role string) (addr crypto.Address, pF ptypes.PermFlag, data []byte) { + role string) (addr crypto.Address, pF permission.PermFlag, data []byte) { addr = permissionsContract.Address() data = user.Address().Word256().Bytes() data = append(data, RightPadBytes([]byte(role), 32)...) data = append(permNameToFuncID(name), data...) var err error - if pF, err = ptypes.PermStringToFlag(name); err != nil { + if pF, err = permission.PermStringToFlag(name); err != nil { panic(fmt.Sprintf("failed to convert perm string (%s) to flag", name)) } return } -func snativeRoleTestInputTx(name string, user acm.AddressableSigner, role string) (snativeArgs snatives.PermArgs) { +func snativeRoleTestInputTx(name string, user acm.AddressableSigner, role string) (snativeArgs permission.PermArgs) { switch name { case "hasRole": - snativeArgs = snatives.HasRoleArgs(user.Address(), role) + snativeArgs = permission.HasRoleArgs(user.Address(), role) case "addRole": - snativeArgs = snatives.AddRoleArgs(user.Address(), role) + snativeArgs = permission.AddRoleArgs(user.Address(), role) case "removeRole": - snativeArgs = snatives.RemoveRoleArgs(user.Address(), role) + snativeArgs = permission.RemoveRoleArgs(user.Address(), role) } return } diff --git a/execution/executors/call.go b/execution/executors/call_context.go similarity index 73% rename from execution/executors/call.go rename to execution/executors/call_context.go index ce79fc5c2..78fa25e4a 100644 --- a/execution/executors/call.go +++ b/execution/executors/call_context.go @@ -3,17 +3,15 @@ package executors import ( "fmt" - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/state" "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/blockchain" - "github.com/hyperledger/burrow/event" "github.com/hyperledger/burrow/execution/errors" - "github.com/hyperledger/burrow/execution/events" "github.com/hyperledger/burrow/execution/evm" + "github.com/hyperledger/burrow/execution/exec" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" - "github.com/hyperledger/burrow/txs" "github.com/hyperledger/burrow/txs/payload" ) @@ -21,23 +19,22 @@ import ( const GasLimit = uint64(1000000) type CallContext struct { - Tip blockchain.TipInfo - StateWriter state.ReaderWriter - EventPublisher event.Publisher - RunCall bool - VMOptions []func(*evm.VM) - Logger *logging.Logger - tx *payload.CallTx - txEnv *txs.Envelope + Tip blockchain.TipInfo + StateWriter state.ReaderWriter + RunCall bool + VMOptions []func(*evm.VM) + Logger *logging.Logger + tx *payload.CallTx + txe *exec.TxExecution } -func (ctx *CallContext) Execute(txEnv *txs.Envelope) error { +func (ctx *CallContext) Execute(txe *exec.TxExecution) error { var ok bool - ctx.tx, ok = txEnv.Tx.Payload.(*payload.CallTx) + ctx.tx, ok = txe.Envelope.Tx.Payload.(*payload.CallTx) if !ok { - return fmt.Errorf("payload must be CallTx, but is: %v", txEnv.Tx.Payload) + return fmt.Errorf("payload must be CallTx, but is: %v", txe.Envelope.Tx.Payload) } - ctx.txEnv = txEnv + ctx.txe = txe inAcc, outAcc, err := ctx.Precheck() if err != nil { return err @@ -46,15 +43,12 @@ func (ctx *CallContext) Execute(txEnv *txs.Envelope) error { value := ctx.tx.Input.Amount - ctx.tx.Fee if ctx.RunCall { - ctx.Deliver(inAcc, outAcc, value) - } else { - ctx.Check(inAcc, value) + return ctx.Deliver(inAcc, outAcc, value) } - - return nil + return ctx.Check(inAcc, value) } -func (ctx *CallContext) Precheck() (acm.MutableAccount, acm.Account, error) { +func (ctx *CallContext) Precheck() (*acm.MutableAccount, acm.Account, error) { var outAcc acm.Account // Validate input inAcc, err := state.GetMutableAccount(ctx.StateWriter, ctx.tx.Input.Address) @@ -85,7 +79,8 @@ func (ctx *CallContext) Precheck() (acm.MutableAccount, acm.Account, error) { "old_sequence", inAcc.Sequence(), "new_sequence", inAcc.Sequence()+1) - inAcc, err = inAcc.IncSequence().SubtractFromBalance(ctx.tx.Fee) + inAcc.IncSequence() + err = inAcc.SubtractFromBalance(ctx.tx.Fee) if err != nil { return nil, nil, err } @@ -126,13 +121,13 @@ func (ctx *CallContext) Precheck() (acm.MutableAccount, acm.Account, error) { return inAcc, outAcc, nil } -func (ctx *CallContext) Check(inAcc acm.MutableAccount, value uint64) error { +func (ctx *CallContext) Check(inAcc *acm.MutableAccount, value uint64) error { createContract := ctx.tx.Address == nil // The mempool does not call txs until // the proposer determines the order of txs. // So mempool will skip the actual .Call(), // and only deduct from the caller's balance. - inAcc, err := inAcc.SubtractFromBalance(value) + err := inAcc.SubtractFromBalance(value) if err != nil { return err } @@ -145,20 +140,24 @@ func (ctx *CallContext) Check(inAcc acm.MutableAccount, value uint64) error { "new_sequence", inAcc.Sequence()+1) inAcc.IncSequence() } - return ctx.StateWriter.UpdateAccount(inAcc) + err = ctx.StateWriter.UpdateAccount(inAcc) + if err != nil { + return err + } + return nil } func (ctx *CallContext) Deliver(inAcc, outAcc acm.Account, value uint64) error { createContract := ctx.tx.Address == nil // VM call variables var ( - gas uint64 = ctx.tx.GasLimit - caller acm.MutableAccount = acm.AsMutableAccount(inAcc) - callee acm.MutableAccount = nil // initialized below - code []byte = nil - ret []byte = nil - txCache = state.NewCache(ctx.StateWriter, state.Name("TxCache")) - params = evm.Params{ + gas uint64 = ctx.tx.GasLimit + caller *acm.MutableAccount = acm.AsMutableAccount(inAcc) + callee *acm.MutableAccount = nil // initialized below + code []byte = nil + ret []byte = nil + txCache = state.NewCache(ctx.StateWriter, state.Name("TxCache")) + params = evm.Params{ BlockHeight: ctx.Tip.LastBlockHeight(), BlockHash: binary.LeftPadWord256(ctx.Tip.LastBlockHash()), BlockTime: ctx.Tip.LastBlockTime().Unix(), @@ -192,7 +191,7 @@ func (ctx *CallContext) Deliver(inAcc, outAcc acm.Account, value uint64) error { "caller_address", inAcc.Address(), "callee_address", ctx.tx.Address) } - ctx.FireCallEvents(nil, payload.ErrTxInvalidAddress) + ctx.CallEvents(payload.ErrTxInvalidAddress) return nil } callee = acm.AsMutableAccount(outAcc) @@ -206,8 +205,8 @@ func (ctx *CallContext) Deliver(inAcc, outAcc acm.Account, value uint64) error { txCache.UpdateAccount(caller) txCache.UpdateAccount(callee) - vmach := evm.NewVM(params, caller.Address(), ctx.txEnv.Tx, ctx.Logger, ctx.VMOptions...) - vmach.SetPublisher(ctx.EventPublisher) + vmach := evm.NewVM(params, caller.Address(), ctx.txe.Envelope.Tx, ctx.Logger, ctx.VMOptions...) + vmach.SetEventSink(ctx.txe) // NOTE: Call() transfers the value from caller to callee iff call succeeds. ret, exception := vmach.Call(txCache, caller, callee, code, ctx.tx.Data, value, &gas) if exception != nil { @@ -224,25 +223,21 @@ func (ctx *CallContext) Deliver(inAcc, outAcc acm.Account, value uint64) error { return err } } + ctx.CallEvents(exception) + ctx.txe.Return(ret, ctx.tx.GasLimit-gas) // Create a receipt from the ret and whether it erred. ctx.Logger.TraceMsg("VM call complete", "caller", caller, "callee", callee, "return", ret, structure.ErrorKey, exception) - ctx.FireCallEvents(ret, exception) return nil } -func (ctx *CallContext) FireCallEvents(ret []byte, err error) { - // Fire Events for sender and receiver - // a separate event will be fired from vm for each additional call - if ctx.EventPublisher != nil { - events.PublishAccountInput(ctx.EventPublisher, ctx.Tip.LastBlockHeight(), ctx.tx.Input.Address, ctx.txEnv.Tx, - ret, errors.AsCodedError(err)) - if ctx.tx.Address != nil { - events.PublishAccountOutput(ctx.EventPublisher, ctx.Tip.LastBlockHeight(), *ctx.tx.Address, ctx.txEnv.Tx, - ret, errors.AsCodedError(err)) - } +func (ctx *CallContext) CallEvents(err error) { + // Fire Events for sender and receiver a separate event will be fired from vm for each additional call + ctx.txe.Input(ctx.tx.Input.Address, errors.AsException(err)) + if ctx.tx.Address != nil { + ctx.txe.Input(*ctx.tx.Address, errors.AsException(err)) } } diff --git a/execution/executors/name.go b/execution/executors/name_context.go similarity index 67% rename from execution/executors/name.go rename to execution/executors/name_context.go index 658992d53..ce8396704 100644 --- a/execution/executors/name.go +++ b/execution/executors/name_context.go @@ -3,31 +3,36 @@ package executors import ( "fmt" - "github.com/hyperledger/burrow/account/state" + "regexp" + + "github.com/hyperledger/burrow/acm/state" "github.com/hyperledger/burrow/blockchain" - "github.com/hyperledger/burrow/event" - "github.com/hyperledger/burrow/execution/events" + "github.com/hyperledger/burrow/execution/errors" + "github.com/hyperledger/burrow/execution/exec" "github.com/hyperledger/burrow/execution/names" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" - "github.com/hyperledger/burrow/txs" "github.com/hyperledger/burrow/txs/payload" ) +// Name should be file system like +// Data should be anything permitted in JSON +var regexpAlphaNum = regexp.MustCompile("^[a-zA-Z0-9._/-@]*$") +var regexpJSON = regexp.MustCompile(`^[a-zA-Z0-9_/ \-+"':,\n\t.{}()\[\]]*$`) + type NameContext struct { - Tip blockchain.TipInfo - StateWriter state.ReaderWriter - EventPublisher event.Publisher - NameReg names.ReaderWriter - Logger *logging.Logger - tx *payload.NameTx + Tip blockchain.TipInfo + StateWriter state.ReaderWriter + NameReg names.ReaderWriter + Logger *logging.Logger + tx *payload.NameTx } -func (ctx *NameContext) Execute(txEnv *txs.Envelope) error { +func (ctx *NameContext) Execute(txe *exec.TxExecution) error { var ok bool - ctx.tx, ok = txEnv.Tx.Payload.(*payload.NameTx) + ctx.tx, ok = txe.Envelope.Tx.Payload.(*payload.NameTx) if !ok { - return fmt.Errorf("payload must be NameTx, but is: %v", txEnv.Tx.Payload) + return fmt.Errorf("payload must be NameTx, but is: %v", txe.Envelope.Tx.Payload) } // Validate input inAcc, err := state.GetMutableAccount(ctx.StateWriter, ctx.tx.Input.Address) @@ -56,7 +61,7 @@ func (ctx *NameContext) Execute(txEnv *txs.Envelope) error { } // validate the input strings - if err := ctx.tx.ValidateStrings(); err != nil { + if err := validateStrings(ctx.tx); err != nil { return err } @@ -74,7 +79,7 @@ func (ctx *NameContext) Execute(txEnv *txs.Envelope) error { "last_block_height", lastBlockHeight) // check if the name exists - entry, err := ctx.NameReg.GetNameEntry(ctx.tx.Name) + entry, err := ctx.NameReg.GetName(ctx.tx.Name) if err != nil { return err } @@ -99,7 +104,7 @@ func (ctx *NameContext) Execute(txEnv *txs.Envelope) error { // (owners if not expired, anyone if expired) ctx.Logger.TraceMsg("Removing NameReg entry (no value and empty data in tx requests this)", "name", entry.Name) - err := ctx.NameReg.RemoveNameEntry(entry.Name) + err := ctx.NameReg.RemoveName(entry.Name) if err != nil { return err } @@ -134,7 +139,7 @@ func (ctx *NameContext) Execute(txEnv *txs.Envelope) error { "credit", credit) } entry.Data = ctx.tx.Data - err := ctx.NameReg.UpdateNameEntry(entry) + err := ctx.NameReg.UpdateName(entry) if err != nil { return err } @@ -153,7 +158,7 @@ func (ctx *NameContext) Execute(txEnv *txs.Envelope) error { ctx.Logger.TraceMsg("Creating NameReg entry", "name", entry.Name, "expires_in", expiresIn) - err := ctx.NameReg.UpdateNameEntry(entry) + err := ctx.NameReg.UpdateName(entry) if err != nil { return err } @@ -168,18 +173,51 @@ func (ctx *NameContext) Execute(txEnv *txs.Envelope) error { "old_sequence", inAcc.Sequence(), "new_sequence", inAcc.Sequence()+1) inAcc.IncSequence() - inAcc, err = inAcc.SubtractFromBalance(value) + err = inAcc.SubtractFromBalance(value) + if err != nil { + return err + } + err = ctx.StateWriter.UpdateAccount(inAcc) if err != nil { return err } - ctx.StateWriter.UpdateAccount(inAcc) // TODO: maybe we want to take funds on error and allow txs in that don't do anythingi? - if ctx.EventPublisher != nil { - events.PublishAccountInput(ctx.EventPublisher, ctx.Tip.LastBlockHeight(), ctx.tx.Input.Address, txEnv.Tx, nil, nil) - events.PublishNameReg(ctx.EventPublisher, ctx.Tip.LastBlockHeight(), txEnv.Tx) + txe.Input(ctx.tx.Input.Address, nil) + txe.Name(entry) + return nil +} + +func validateStrings(tx *payload.NameTx) error { + if len(tx.Name) == 0 { + return errors.ErrorCodef(errors.ErrorCodeInvalidString, "name must not be empty") + } + if len(tx.Name) > names.MaxNameLength { + return errors.ErrorCodef(errors.ErrorCodeInvalidString, "Name is too long. Max %d bytes", names.MaxNameLength) + } + if len(tx.Data) > names.MaxDataLength { + return errors.ErrorCodef(errors.ErrorCodeInvalidString, "Data is too long. Max %d bytes", names.MaxDataLength) + } + + if !validateNameRegEntryName(tx.Name) { + return errors.ErrorCodef(errors.ErrorCodeInvalidString, + "Invalid characters found in NameTx.Name (%s). Only alphanumeric, underscores, dashes, forward slashes, and @ are allowed", tx.Name) + } + + if !validateNameRegEntryData(tx.Data) { + return errors.ErrorCodef(errors.ErrorCodeInvalidString, + "Invalid characters found in NameTx.Data (%s). Only the kind of things found in a JSON file are allowed", tx.Data) } return nil } + +// filter strings +func validateNameRegEntryName(name string) bool { + return regexpAlphaNum.Match([]byte(name)) +} + +func validateNameRegEntryData(data string) bool { + return regexpJSON.Match([]byte(data)) +} diff --git a/execution/executors/permissions.go b/execution/executors/permissions_context.go similarity index 72% rename from execution/executors/permissions.go rename to execution/executors/permissions_context.go index 0ccc62040..39292a3b0 100644 --- a/execution/executors/permissions.go +++ b/execution/executors/permissions_context.go @@ -3,32 +3,29 @@ package executors import ( "fmt" - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/state" "github.com/hyperledger/burrow/blockchain" "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/event" - "github.com/hyperledger/burrow/execution/events" + "github.com/hyperledger/burrow/execution/exec" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" - ptypes "github.com/hyperledger/burrow/permission/types" - "github.com/hyperledger/burrow/txs" + "github.com/hyperledger/burrow/permission" "github.com/hyperledger/burrow/txs/payload" ) type PermissionsContext struct { - Tip blockchain.TipInfo - StateWriter state.ReaderWriter - EventPublisher event.Publisher - Logger *logging.Logger - tx *payload.PermissionsTx + Tip blockchain.TipInfo + StateWriter state.ReaderWriter + Logger *logging.Logger + tx *payload.PermissionsTx } -func (ctx *PermissionsContext) Execute(txEnv *txs.Envelope) error { +func (ctx *PermissionsContext) Execute(txe *exec.TxExecution) error { var ok bool - ctx.tx, ok = txEnv.Tx.Payload.(*payload.PermissionsTx) + ctx.tx, ok = txe.Envelope.Tx.Payload.(*payload.PermissionsTx) if !ok { - return fmt.Errorf("payload must be PermissionsTx, but is: %v", txEnv.Tx.Payload) + return fmt.Errorf("payload must be PermissionsTx, but is: %v", txe.Envelope.Tx.Payload) } // Validate input inAcc, err := state.GetMutableAccount(ctx.StateWriter, ctx.tx.Input.Address) @@ -68,38 +65,38 @@ func (ctx *PermissionsContext) Execute(txEnv *txs.Envelope) error { var permAcc acm.Account switch ctx.tx.PermArgs.PermFlag { - case ptypes.HasBase: + case permission.HasBase: // this one doesn't make sense from txs return fmt.Errorf("HasBase is for contracts, not humans. Just look at the blockchain") - case ptypes.SetBase: + case permission.SetBase: permAcc, err = mutatePermissions(ctx.StateWriter, *ctx.tx.PermArgs.Address, - func(perms *ptypes.AccountPermissions) error { + func(perms *permission.AccountPermissions) error { return perms.Base.Set(*ctx.tx.PermArgs.Permission, *ctx.tx.PermArgs.Value) }) - case ptypes.UnsetBase: + case permission.UnsetBase: permAcc, err = mutatePermissions(ctx.StateWriter, *ctx.tx.PermArgs.Address, - func(perms *ptypes.AccountPermissions) error { + func(perms *permission.AccountPermissions) error { return perms.Base.Unset(*ctx.tx.PermArgs.Permission) }) - case ptypes.SetGlobal: + case permission.SetGlobal: permAcc, err = mutatePermissions(ctx.StateWriter, acm.GlobalPermissionsAddress, - func(perms *ptypes.AccountPermissions) error { + func(perms *permission.AccountPermissions) error { return perms.Base.Set(*ctx.tx.PermArgs.Permission, *ctx.tx.PermArgs.Value) }) - case ptypes.HasRole: + case permission.HasRole: return fmt.Errorf("HasRole is for contracts, not humans. Just look at the blockchain") - case ptypes.AddRole: + case permission.AddRole: permAcc, err = mutatePermissions(ctx.StateWriter, *ctx.tx.PermArgs.Address, - func(perms *ptypes.AccountPermissions) error { + func(perms *permission.AccountPermissions) error { if !perms.AddRole(*ctx.tx.PermArgs.Role) { return fmt.Errorf("role (%s) already exists for account %s", *ctx.tx.PermArgs.Role, *ctx.tx.PermArgs.Address) } return nil }) - case ptypes.RemoveRole: + case permission.RemoveRole: permAcc, err = mutatePermissions(ctx.StateWriter, *ctx.tx.PermArgs.Address, - func(perms *ptypes.AccountPermissions) error { + func(perms *permission.AccountPermissions) error { if !perms.RmRole(*ctx.tx.PermArgs.Role) { return fmt.Errorf("role (%s) does not exist for account %s", *ctx.tx.PermArgs.Role, *ctx.tx.PermArgs.Address) @@ -122,7 +119,7 @@ func (ctx *PermissionsContext) Execute(txEnv *txs.Envelope) error { "old_sequence", inAcc.Sequence(), "new_sequence", inAcc.Sequence()+1) inAcc.IncSequence() - inAcc, err = inAcc.SubtractFromBalance(value) + err = inAcc.SubtractFromBalance(value) if err != nil { return err } @@ -131,16 +128,13 @@ func (ctx *PermissionsContext) Execute(txEnv *txs.Envelope) error { ctx.StateWriter.UpdateAccount(permAcc) } - if ctx.EventPublisher != nil { - events.PublishAccountInput(ctx.EventPublisher, ctx.Tip.LastBlockHeight(), ctx.tx.Input.Address, txEnv.Tx, nil, nil) - events.PublishPermissions(ctx.EventPublisher, ctx.Tip.LastBlockHeight(), txEnv.Tx) - } - + txe.Input(ctx.tx.Input.Address, nil) + txe.Permission(&ctx.tx.PermArgs) return nil } func mutatePermissions(stateReader state.Reader, address crypto.Address, - mutator func(*ptypes.AccountPermissions) error) (acm.Account, error) { + mutator func(*permission.AccountPermissions) error) (acm.Account, error) { account, err := stateReader.GetAccount(address) if err != nil { diff --git a/execution/executors/send.go b/execution/executors/send_context.go similarity index 59% rename from execution/executors/send.go rename to execution/executors/send_context.go index f7e9f752b..5cad86303 100644 --- a/execution/executors/send.go +++ b/execution/executors/send_context.go @@ -3,28 +3,25 @@ package executors import ( "fmt" - "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/acm/state" "github.com/hyperledger/burrow/blockchain" - "github.com/hyperledger/burrow/event" - "github.com/hyperledger/burrow/execution/events" + "github.com/hyperledger/burrow/execution/exec" "github.com/hyperledger/burrow/logging" - "github.com/hyperledger/burrow/txs" "github.com/hyperledger/burrow/txs/payload" ) type SendContext struct { - Tip blockchain.TipInfo - StateWriter state.ReaderWriter - EventPublisher event.Publisher - Logger *logging.Logger - tx *payload.SendTx + Tip blockchain.TipInfo + StateWriter state.ReaderWriter + Logger *logging.Logger + tx *payload.SendTx } -func (ctx *SendContext) Execute(txEnv *txs.Envelope) error { +func (ctx *SendContext) Execute(txe *exec.TxExecution) error { var ok bool - ctx.tx, ok = txEnv.Tx.Payload.(*payload.SendTx) + ctx.tx, ok = txe.Envelope.Tx.Payload.(*payload.SendTx) if !ok { - return fmt.Errorf("payload must be NameTx, but is: %v", txEnv.Tx.Payload) + return fmt.Errorf("payload must be NameTx, but is: %v", txe.Envelope.Tx.Payload) } accounts, err := getInputs(ctx.StateWriter, ctx.tx.Inputs) if err != nil { @@ -70,14 +67,13 @@ func (ctx *SendContext) Execute(txEnv *txs.Envelope) error { ctx.StateWriter.UpdateAccount(acc) } - if ctx.EventPublisher != nil { - for _, i := range ctx.tx.Inputs { - events.PublishAccountInput(ctx.EventPublisher, ctx.Tip.LastBlockHeight(), i.Address, txEnv.Tx, nil, nil) - } + for _, i := range ctx.tx.Inputs { + txe.Input(i.Address, nil) + } - for _, o := range ctx.tx.Outputs { - events.PublishAccountOutput(ctx.EventPublisher, ctx.Tip.LastBlockHeight(), o.Address, txEnv.Tx, nil, nil) - } + for _, o := range ctx.tx.Outputs { + txe.Output(o.Address, nil) } + return nil } diff --git a/execution/executors/shared.go b/execution/executors/shared.go index 8843249b1..58904bb98 100644 --- a/execution/executors/shared.go +++ b/execution/executors/shared.go @@ -3,13 +3,12 @@ package executors import ( "fmt" - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/state" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" "github.com/hyperledger/burrow/permission" - ptypes "github.com/hyperledger/burrow/permission/types" "github.com/hyperledger/burrow/txs/payload" ) @@ -18,9 +17,9 @@ import ( // or it must be specified in the TxInput. If redeclared, // the TxInput is modified and input.PublicKey() set to nil. func getInputs(accountGetter state.AccountGetter, - ins []*payload.TxInput) (map[crypto.Address]acm.MutableAccount, error) { + ins []*payload.TxInput) (map[crypto.Address]*acm.MutableAccount, error) { - accounts := map[crypto.Address]acm.MutableAccount{} + accounts := map[crypto.Address]*acm.MutableAccount{} for _, in := range ins { // Account shouldn't be duplicated if _, ok := accounts[in.Address]; ok { @@ -38,10 +37,10 @@ func getInputs(accountGetter state.AccountGetter, return accounts, nil } -func getOrMakeOutputs(accountGetter state.AccountGetter, accs map[crypto.Address]acm.MutableAccount, - outs []*payload.TxOutput, logger *logging.Logger) (map[crypto.Address]acm.MutableAccount, error) { +func getOrMakeOutputs(accountGetter state.AccountGetter, accs map[crypto.Address]*acm.MutableAccount, + outs []*payload.TxOutput, logger *logging.Logger) (map[crypto.Address]*acm.MutableAccount, error) { if accs == nil { - accs = make(map[crypto.Address]acm.MutableAccount) + accs = make(map[crypto.Address]*acm.MutableAccount) } // we should err if an account is being created but the inputs don't have permission @@ -75,7 +74,7 @@ func getOrMakeOutputs(accountGetter state.AccountGetter, accs map[crypto.Address return accs, nil } -func validateInputs(accs map[crypto.Address]acm.MutableAccount, ins []*payload.TxInput) (uint64, error) { +func validateInputs(accs map[crypto.Address]*acm.MutableAccount, ins []*payload.TxInput) (uint64, error) { total := uint64(0) for _, in := range ins { acc := accs[in.Address] @@ -92,7 +91,7 @@ func validateInputs(accs map[crypto.Address]acm.MutableAccount, ins []*payload.T return total, nil } -func validateInput(acc acm.MutableAccount, in *payload.TxInput) error { +func validateInput(acc *acm.MutableAccount, in *payload.TxInput) error { // Check TxInput basic if err := in.ValidateBasic(); err != nil { return err @@ -124,7 +123,7 @@ func validateOutputs(outs []*payload.TxOutput) (uint64, error) { return total, nil } -func adjustByInputs(accs map[crypto.Address]acm.MutableAccount, ins []*payload.TxInput, logger *logging.Logger) error { +func adjustByInputs(accs map[crypto.Address]*acm.MutableAccount, ins []*payload.TxInput, logger *logging.Logger) error { for _, in := range ins { acc := accs[in.Address] if acc == nil { @@ -135,7 +134,7 @@ func adjustByInputs(accs map[crypto.Address]acm.MutableAccount, ins []*payload.T return fmt.Errorf("adjustByInputs() expects sufficient funds but account %s only has balance %v and "+ "we are deducting %v", in.Address, acc.Balance(), in.Amount) } - acc, err := acc.SubtractFromBalance(in.Amount) + err := acc.SubtractFromBalance(in.Amount) if err != nil { return err } @@ -149,14 +148,14 @@ func adjustByInputs(accs map[crypto.Address]acm.MutableAccount, ins []*payload.T return nil } -func adjustByOutputs(accs map[crypto.Address]acm.MutableAccount, outs []*payload.TxOutput) error { +func adjustByOutputs(accs map[crypto.Address]*acm.MutableAccount, outs []*payload.TxOutput) error { for _, out := range outs { acc := accs[out.Address] if acc == nil { return fmt.Errorf("adjustByOutputs() expects account in accounts, but account %s not found", out.Address) } - _, err := acc.AddToBalance(out.Amount) + err := acc.AddToBalance(out.Amount) if err != nil { return err } @@ -167,13 +166,13 @@ func adjustByOutputs(accs map[crypto.Address]acm.MutableAccount, outs []*payload //--------------------------------------------------------------- // Get permission on an account or fall back to global value -func HasPermission(accountGetter state.AccountGetter, acc acm.Account, perm ptypes.PermFlag, logger *logging.Logger) bool { - if perm > ptypes.AllPermFlags { +func HasPermission(accountGetter state.AccountGetter, acc acm.Account, perm permission.PermFlag, logger *logging.Logger) bool { + if perm > permission.AllPermFlags { logger.InfoMsg( fmt.Sprintf("HasPermission called on invalid permission 0b%b (invalid) > 0b%b (maximum) ", - perm, ptypes.AllPermFlags), + perm, permission.AllPermFlags), "invalid_permission", perm, - "maximum_permission", ptypes.AllPermFlags) + "maximum_permission", permission.AllPermFlags) return false } @@ -197,10 +196,10 @@ func HasPermission(accountGetter state.AccountGetter, acc acm.Account, perm ptyp } // TODO: for debug log the failed accounts -func hasSendPermission(accountGetter state.AccountGetter, accs map[crypto.Address]acm.MutableAccount, +func hasSendPermission(accountGetter state.AccountGetter, accs map[crypto.Address]*acm.MutableAccount, logger *logging.Logger) bool { for _, acc := range accs { - if !HasPermission(accountGetter, acc, ptypes.Send, logger) { + if !HasPermission(accountGetter, acc, permission.Send, logger) { return false } } @@ -209,23 +208,23 @@ func hasSendPermission(accountGetter state.AccountGetter, accs map[crypto.Addres func hasNamePermission(accountGetter state.AccountGetter, acc acm.Account, logger *logging.Logger) bool { - return HasPermission(accountGetter, acc, ptypes.Name, logger) + return HasPermission(accountGetter, acc, permission.Name, logger) } func hasCallPermission(accountGetter state.AccountGetter, acc acm.Account, logger *logging.Logger) bool { - return HasPermission(accountGetter, acc, ptypes.Call, logger) + return HasPermission(accountGetter, acc, permission.Call, logger) } func hasCreateContractPermission(accountGetter state.AccountGetter, acc acm.Account, logger *logging.Logger) bool { - return HasPermission(accountGetter, acc, ptypes.CreateContract, logger) + return HasPermission(accountGetter, acc, permission.CreateContract, logger) } -func hasCreateAccountPermission(accountGetter state.AccountGetter, accs map[crypto.Address]acm.MutableAccount, +func hasCreateAccountPermission(accountGetter state.AccountGetter, accs map[crypto.Address]*acm.MutableAccount, logger *logging.Logger) bool { for _, acc := range accs { - if !HasPermission(accountGetter, acc, ptypes.CreateAccount, logger) { + if !HasPermission(accountGetter, acc, permission.CreateAccount, logger) { return false } } @@ -234,14 +233,14 @@ func hasCreateAccountPermission(accountGetter state.AccountGetter, accs map[cryp func hasBondPermission(accountGetter state.AccountGetter, acc acm.Account, logger *logging.Logger) bool { - return HasPermission(accountGetter, acc, ptypes.Bond, logger) + return HasPermission(accountGetter, acc, permission.Bond, logger) } func hasBondOrSendPermission(accountGetter state.AccountGetter, accs map[crypto.Address]acm.Account, logger *logging.Logger) bool { for _, acc := range accs { - if !HasPermission(accountGetter, acc, ptypes.Bond, logger) { - if !HasPermission(accountGetter, acc, ptypes.Send, logger) { + if !HasPermission(accountGetter, acc, permission.Bond, logger) { + if !HasPermission(accountGetter, acc, permission.Send, logger) { return false } } diff --git a/execution/names/cache.go b/execution/names/cache.go index 7b8e060f1..6513f702e 100644 --- a/execution/names/cache.go +++ b/execution/names/cache.go @@ -46,7 +46,7 @@ func NewCache(backend Reader) *Cache { } } -func (cache *Cache) GetNameEntry(name string) (*Entry, error) { +func (cache *Cache) GetName(name string) (*Entry, error) { nameInfo, err := cache.get(name) if err != nil { return nil, err @@ -59,7 +59,7 @@ func (cache *Cache) GetNameEntry(name string) (*Entry, error) { return nameInfo.entry, nil } -func (cache *Cache) UpdateNameEntry(entry *Entry) error { +func (cache *Cache) UpdateName(entry *Entry) error { nameInfo, err := cache.get(entry.Name) if err != nil { return err @@ -67,7 +67,7 @@ func (cache *Cache) UpdateNameEntry(entry *Entry) error { nameInfo.Lock() defer nameInfo.Unlock() if nameInfo.removed { - return fmt.Errorf("UpdateNameEntry on a removed name: %s", nameInfo.entry.Name) + return fmt.Errorf("UpdateName on a removed name: %s", nameInfo.entry.Name) } nameInfo.entry = entry @@ -75,7 +75,7 @@ func (cache *Cache) UpdateNameEntry(entry *Entry) error { return nil } -func (cache *Cache) RemoveNameEntry(name string) error { +func (cache *Cache) RemoveName(name string) error { nameInfo, err := cache.get(name) if err != nil { return err @@ -83,7 +83,7 @@ func (cache *Cache) RemoveNameEntry(name string) error { nameInfo.Lock() defer nameInfo.Unlock() if nameInfo.removed { - return fmt.Errorf("RemoveNameEntry on removed name: %s", name) + return fmt.Errorf("RemoveName on removed name: %s", name) } nameInfo.removed = true return nil @@ -107,13 +107,13 @@ func (cache *Cache) Sync(state Writer) error { nameInfo := cache.names[name] nameInfo.RLock() if nameInfo.removed { - err := state.RemoveNameEntry(name) + err := state.RemoveName(name) if err != nil { nameInfo.RUnlock() return err } } else if nameInfo.updated { - err := state.UpdateNameEntry(nameInfo.entry) + err := state.UpdateName(nameInfo.entry) if err != nil { nameInfo.RUnlock() return err @@ -156,7 +156,7 @@ func (cache *Cache) get(name string) (*nameInfo, error) { defer cache.Unlock() nmeInfo = cache.names[name] if nmeInfo == nil { - entry, err := cache.backend.GetNameEntry(name) + entry, err := cache.backend.GetName(name) if err != nil { return nil, err } diff --git a/execution/names/names.go b/execution/names/names.go index 1732575f0..81d83b176 100644 --- a/execution/names/names.go +++ b/execution/names/names.go @@ -15,12 +15,15 @@ package names import ( - "github.com/hyperledger/burrow/crypto" + "fmt" + + "github.com/hyperledger/burrow/event/query" "github.com/tendermint/go-amino" ) -var ( - MinNameRegistrationPeriod uint64 = 5 +var MinNameRegistrationPeriod uint64 = 5 + +const ( // NOTE: base costs and validity checks are here so clients // can use them without importing state @@ -34,25 +37,28 @@ var ( MaxDataLength = 1 << 16 ) -// NameReg provides a global key value store based on Name, Data pairs that are subject to expiry and ownership by an -// account. -type Entry struct { - // registered name for the entry - Name string - // address that created the entry - Owner crypto.Address - // data to store under this name - Data string - // block at which this entry expires - Expires uint64 -} - var cdc = amino.NewCodec() func (e *Entry) Encode() ([]byte, error) { return cdc.MarshalBinary(e) } +func (e *Entry) String() string { + return fmt.Sprintf("NameEntry{%v -> %v; Expires: %v, Owner: %v}", e.Name, e.Data, e.Expires, e.Owner) +} + +type TaggedEntry struct { + *Entry + query.Tagged +} + +func (e *Entry) Tagged() *TaggedEntry { + return &TaggedEntry{ + Entry: e, + Tagged: query.MustReflectTags(e), + } +} + func DecodeEntry(entryBytes []byte) (*Entry, error) { entry := new(Entry) err := cdc.UnmarshalBinary(entryBytes, entry) @@ -63,14 +69,14 @@ func DecodeEntry(entryBytes []byte) (*Entry, error) { } type Reader interface { - GetNameEntry(name string) (*Entry, error) + GetName(name string) (*Entry, error) } type Writer interface { // Updates the name entry creating it if it does not exist - UpdateNameEntry(entry *Entry) error + UpdateName(entry *Entry) error // Remove the name entry - RemoveNameEntry(name string) error + RemoveName(name string) error } type ReaderWriter interface { @@ -79,7 +85,7 @@ type ReaderWriter interface { } type Iterable interface { - IterateNameEntries(consumer func(*Entry) (stop bool)) (stopped bool, err error) + IterateNames(consumer func(*Entry) (stop bool)) (stopped bool, err error) } type IterableReader interface { @@ -100,3 +106,7 @@ func NameBaseCost(name, data string) uint64 { func NameCostPerBlock(baseCost uint64) uint64 { return NameBlockCostMultiplier * NameByteCostMultiplier * baseCost } + +func NameCostForExpiryIn(name, data string, expiresIn uint64) uint64 { + return NameCostPerBlock(NameBaseCost(name, data)) * expiresIn +} diff --git a/execution/names/names.pb.go b/execution/names/names.pb.go new file mode 100644 index 000000000..64cd40e92 --- /dev/null +++ b/execution/names/names.pb.go @@ -0,0 +1,449 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: names.proto + +/* + Package names is a generated protocol buffer package. + + It is generated from these files: + names.proto + + It has these top-level messages: + Entry +*/ +package names + +import proto "github.com/gogo/protobuf/proto" +import golang_proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" +import _ "github.com/gogo/protobuf/gogoproto" + +import github_com_hyperledger_burrow_crypto "github.com/hyperledger/burrow/crypto" + +import io "io" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = golang_proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package + +// NameReg provides a global key value store based on Name, Data pairs that are subject to expiry and ownership by an +// account. +type Entry struct { + // registered name for the entry + Name string `protobuf:"bytes,1,opt,name=Name,proto3" json:"Name,omitempty"` + // address that created the entry + Owner github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,2,opt,name=Owner,proto3,customtype=github.com/hyperledger/burrow/crypto.Address" json:"Owner"` + // data to store under this name + Data string `protobuf:"bytes,3,opt,name=Data,proto3" json:"Data,omitempty"` + // block at which this entry expires + Expires uint64 `protobuf:"varint,4,opt,name=Expires,proto3" json:"Expires,omitempty"` +} + +func (m *Entry) Reset() { *m = Entry{} } +func (*Entry) ProtoMessage() {} +func (*Entry) Descriptor() ([]byte, []int) { return fileDescriptorNames, []int{0} } + +func (m *Entry) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *Entry) GetData() string { + if m != nil { + return m.Data + } + return "" +} + +func (m *Entry) GetExpires() uint64 { + if m != nil { + return m.Expires + } + return 0 +} + +func (*Entry) XXX_MessageName() string { + return "names.Entry" +} +func init() { + proto.RegisterType((*Entry)(nil), "names.Entry") + golang_proto.RegisterType((*Entry)(nil), "names.Entry") +} +func (m *Entry) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Entry) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Name) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintNames(dAtA, i, uint64(len(m.Name))) + i += copy(dAtA[i:], m.Name) + } + dAtA[i] = 0x12 + i++ + i = encodeVarintNames(dAtA, i, uint64(m.Owner.Size())) + n1, err := m.Owner.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n1 + if len(m.Data) > 0 { + dAtA[i] = 0x1a + i++ + i = encodeVarintNames(dAtA, i, uint64(len(m.Data))) + i += copy(dAtA[i:], m.Data) + } + if m.Expires != 0 { + dAtA[i] = 0x20 + i++ + i = encodeVarintNames(dAtA, i, uint64(m.Expires)) + } + return i, nil +} + +func encodeVarintNames(dAtA []byte, offset int, v uint64) int { + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return offset + 1 +} +func (m *Entry) Size() (n int) { + var l int + _ = l + l = len(m.Name) + if l > 0 { + n += 1 + l + sovNames(uint64(l)) + } + l = m.Owner.Size() + n += 1 + l + sovNames(uint64(l)) + l = len(m.Data) + if l > 0 { + n += 1 + l + sovNames(uint64(l)) + } + if m.Expires != 0 { + n += 1 + sovNames(uint64(m.Expires)) + } + return n +} + +func sovNames(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n +} +func sozNames(x uint64) (n int) { + return sovNames(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Entry) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowNames + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Entry: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Entry: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowNames + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthNames + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowNames + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthNames + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Owner.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowNames + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthNames + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Data = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Expires", wireType) + } + m.Expires = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowNames + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Expires |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipNames(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthNames + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipNames(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowNames + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowNames + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowNames + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + iNdEx += length + if length < 0 { + return 0, ErrInvalidLengthNames + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowNames + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipNames(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} + +var ( + ErrInvalidLengthNames = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowNames = fmt.Errorf("proto: integer overflow") +) + +func init() { proto.RegisterFile("names.proto", fileDescriptorNames) } +func init() { golang_proto.RegisterFile("names.proto", fileDescriptorNames) } + +var fileDescriptorNames = []byte{ + // 245 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0xce, 0x4b, 0xcc, 0x4d, + 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x05, 0x73, 0xa4, 0x74, 0xd3, 0x33, 0x4b, + 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, 0xd3, 0xf3, 0xd3, 0xf3, 0xf5, 0xc1, 0xb2, 0x49, + 0xa5, 0x69, 0x60, 0x1e, 0x98, 0x03, 0x66, 0x41, 0x74, 0x29, 0xcd, 0x66, 0xe4, 0x62, 0x75, 0xcd, + 0x2b, 0x29, 0xaa, 0x14, 0x12, 0xe2, 0x62, 0xf1, 0x4b, 0xcc, 0x4d, 0x95, 0x60, 0x54, 0x60, 0xd4, + 0xe0, 0x0c, 0x02, 0xb3, 0x85, 0xbc, 0xb8, 0x58, 0xfd, 0xcb, 0xf3, 0x52, 0x8b, 0x24, 0x98, 0x14, + 0x18, 0x35, 0x78, 0x9c, 0x4c, 0x4e, 0xdc, 0x93, 0x67, 0xb8, 0x75, 0x4f, 0x5e, 0x07, 0xc9, 0x8e, + 0x8c, 0xca, 0x82, 0xd4, 0xa2, 0x9c, 0xd4, 0x94, 0xf4, 0xd4, 0x22, 0xfd, 0xa4, 0xd2, 0xa2, 0xa2, + 0xfc, 0x72, 0xfd, 0xe4, 0xa2, 0xca, 0x82, 0x92, 0x7c, 0x3d, 0xc7, 0x94, 0x94, 0xa2, 0xd4, 0xe2, + 0xe2, 0x20, 0x88, 0x11, 0x20, 0xf3, 0x5d, 0x12, 0x4b, 0x12, 0x25, 0x98, 0x21, 0xe6, 0x83, 0xd8, + 0x42, 0x12, 0x5c, 0xec, 0xae, 0x15, 0x05, 0x99, 0x45, 0xa9, 0xc5, 0x12, 0x2c, 0x0a, 0x8c, 0x1a, + 0x2c, 0x41, 0x30, 0xae, 0x15, 0xcb, 0x8c, 0x05, 0xf2, 0x0c, 0x4e, 0xce, 0x27, 0x1e, 0xc9, 0x31, + 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x81, 0xc7, 0x72, 0x8c, 0x27, 0x1e, 0xcb, + 0x31, 0x46, 0xe9, 0xe2, 0xb7, 0x3e, 0xb5, 0x22, 0x35, 0xb9, 0xb4, 0x24, 0x33, 0x3f, 0x4f, 0x1f, + 0x1c, 0x22, 0x49, 0x6c, 0x60, 0x9f, 0x1a, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x03, 0xd1, 0x42, + 0x7f, 0x2e, 0x01, 0x00, 0x00, +} diff --git a/execution/names/names_test.go b/execution/names/names_test.go new file mode 100644 index 000000000..3ee467ddc --- /dev/null +++ b/execution/names/names_test.go @@ -0,0 +1,39 @@ +package names + +import ( + "testing" + + "github.com/gogo/protobuf/proto" + "github.com/hyperledger/burrow/crypto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestEncodeAmino(t *testing.T) { + entry := &Entry{ + Name: "Foo", + Data: "oh noes", + Expires: 24423432, + Owner: crypto.Address{1, 2, 0, 9, 8, 8, 1, 2}, + } + encoded, err := entry.Encode() + require.NoError(t, err) + entryOut, err := DecodeEntry(encoded) + require.NoError(t, err) + assert.Equal(t, entry, entryOut) +} + +func TestEncodeProtobuf(t *testing.T) { + entry := &Entry{ + Name: "Foo", + Data: "oh noes", + Expires: 24423432, + Owner: crypto.Address{1, 2, 0, 9, 8, 8, 1, 2}, + } + encoded, err := proto.Marshal(entry) + require.NoError(t, err) + entryOut := new(Entry) + err = proto.Unmarshal(encoded, entryOut) + require.NoError(t, err) + assert.Equal(t, entry, entryOut) +} diff --git a/execution/options.go b/execution/options.go deleted file mode 100644 index 8b6e458b8..000000000 --- a/execution/options.go +++ /dev/null @@ -1,11 +0,0 @@ -package execution - -import "github.com/hyperledger/burrow/execution/evm" - -type ExecutionOption func(*executor) - -func VMOptions(vmOptions ...func(*evm.VM)) func(*executor) { - return func(exe *executor) { - exe.vmOptions = vmOptions - } -} diff --git a/execution/pbtransactor/transactor.pb.go b/execution/pbtransactor/transactor.pb.go deleted file mode 100644 index e5c7a8934..000000000 --- a/execution/pbtransactor/transactor.pb.go +++ /dev/null @@ -1,960 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: github.com/hyperledger/burrow/execution/pbtransactor/transactor.proto - -package pbtransactor // import "github.com/hyperledger/burrow/execution/pbtransactor" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import pbevents "github.com/hyperledger/burrow/execution/events/pbevents" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// Params -type CallParam struct { - From []byte `protobuf:"bytes,1,opt,name=from,proto3" json:"from,omitempty"` - Address []byte `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` - Data []byte `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CallParam) Reset() { *m = CallParam{} } -func (m *CallParam) String() string { return proto.CompactTextString(m) } -func (*CallParam) ProtoMessage() {} -func (*CallParam) Descriptor() ([]byte, []int) { - return fileDescriptor_transactor_97142763aca9e238, []int{0} -} -func (m *CallParam) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CallParam.Unmarshal(m, b) -} -func (m *CallParam) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CallParam.Marshal(b, m, deterministic) -} -func (dst *CallParam) XXX_Merge(src proto.Message) { - xxx_messageInfo_CallParam.Merge(dst, src) -} -func (m *CallParam) XXX_Size() int { - return xxx_messageInfo_CallParam.Size(m) -} -func (m *CallParam) XXX_DiscardUnknown() { - xxx_messageInfo_CallParam.DiscardUnknown(m) -} - -var xxx_messageInfo_CallParam proto.InternalMessageInfo - -func (m *CallParam) GetFrom() []byte { - if m != nil { - return m.From - } - return nil -} - -func (m *CallParam) GetAddress() []byte { - if m != nil { - return m.Address - } - return nil -} - -func (m *CallParam) GetData() []byte { - if m != nil { - return m.Data - } - return nil -} - -type CallCodeParam struct { - From []byte `protobuf:"bytes,1,opt,name=from,proto3" json:"from,omitempty"` - Code []byte `protobuf:"bytes,2,opt,name=code,proto3" json:"code,omitempty"` - Data []byte `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CallCodeParam) Reset() { *m = CallCodeParam{} } -func (m *CallCodeParam) String() string { return proto.CompactTextString(m) } -func (*CallCodeParam) ProtoMessage() {} -func (*CallCodeParam) Descriptor() ([]byte, []int) { - return fileDescriptor_transactor_97142763aca9e238, []int{1} -} -func (m *CallCodeParam) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CallCodeParam.Unmarshal(m, b) -} -func (m *CallCodeParam) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CallCodeParam.Marshal(b, m, deterministic) -} -func (dst *CallCodeParam) XXX_Merge(src proto.Message) { - xxx_messageInfo_CallCodeParam.Merge(dst, src) -} -func (m *CallCodeParam) XXX_Size() int { - return xxx_messageInfo_CallCodeParam.Size(m) -} -func (m *CallCodeParam) XXX_DiscardUnknown() { - xxx_messageInfo_CallCodeParam.DiscardUnknown(m) -} - -var xxx_messageInfo_CallCodeParam proto.InternalMessageInfo - -func (m *CallCodeParam) GetFrom() []byte { - if m != nil { - return m.From - } - return nil -} - -func (m *CallCodeParam) GetCode() []byte { - if m != nil { - return m.Code - } - return nil -} - -func (m *CallCodeParam) GetData() []byte { - if m != nil { - return m.Data - } - return nil -} - -type TransactParam struct { - // The input account to sign with - InputAccount *InputAccount `protobuf:"bytes,1,opt,name=inputAccount,proto3" json:"inputAccount,omitempty"` - // The address of the contract to call, or omitted if creating a new contract - Address []byte `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` - // EVM bytecode payload to deliver - Data []byte `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"` - // The maximum gas to provide to the EVM when running any code - provided in order to bound the computation time - GasLimit uint64 `protobuf:"varint,4,opt,name=gasLimit,proto3" json:"gasLimit,omitempty"` - // Value to transfer, where amount = value + fee - Value uint64 `protobuf:"varint,5,opt,name=value,proto3" json:"value,omitempty"` - // Fee to offer validators for processing transaction - Fee uint64 `protobuf:"varint,6,opt,name=fee,proto3" json:"fee,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *TransactParam) Reset() { *m = TransactParam{} } -func (m *TransactParam) String() string { return proto.CompactTextString(m) } -func (*TransactParam) ProtoMessage() {} -func (*TransactParam) Descriptor() ([]byte, []int) { - return fileDescriptor_transactor_97142763aca9e238, []int{2} -} -func (m *TransactParam) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_TransactParam.Unmarshal(m, b) -} -func (m *TransactParam) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_TransactParam.Marshal(b, m, deterministic) -} -func (dst *TransactParam) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactParam.Merge(dst, src) -} -func (m *TransactParam) XXX_Size() int { - return xxx_messageInfo_TransactParam.Size(m) -} -func (m *TransactParam) XXX_DiscardUnknown() { - xxx_messageInfo_TransactParam.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactParam proto.InternalMessageInfo - -func (m *TransactParam) GetInputAccount() *InputAccount { - if m != nil { - return m.InputAccount - } - return nil -} - -func (m *TransactParam) GetAddress() []byte { - if m != nil { - return m.Address - } - return nil -} - -func (m *TransactParam) GetData() []byte { - if m != nil { - return m.Data - } - return nil -} - -func (m *TransactParam) GetGasLimit() uint64 { - if m != nil { - return m.GasLimit - } - return 0 -} - -func (m *TransactParam) GetValue() uint64 { - if m != nil { - return m.Value - } - return 0 -} - -func (m *TransactParam) GetFee() uint64 { - if m != nil { - return m.Fee - } - return 0 -} - -type SendParam struct { - InputAccount *InputAccount `protobuf:"bytes,1,opt,name=inputAccount,proto3" json:"inputAccount,omitempty"` - ToAddress []byte `protobuf:"bytes,2,opt,name=toAddress,proto3" json:"toAddress,omitempty"` - Amount uint64 `protobuf:"varint,3,opt,name=amount,proto3" json:"amount,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SendParam) Reset() { *m = SendParam{} } -func (m *SendParam) String() string { return proto.CompactTextString(m) } -func (*SendParam) ProtoMessage() {} -func (*SendParam) Descriptor() ([]byte, []int) { - return fileDescriptor_transactor_97142763aca9e238, []int{3} -} -func (m *SendParam) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SendParam.Unmarshal(m, b) -} -func (m *SendParam) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SendParam.Marshal(b, m, deterministic) -} -func (dst *SendParam) XXX_Merge(src proto.Message) { - xxx_messageInfo_SendParam.Merge(dst, src) -} -func (m *SendParam) XXX_Size() int { - return xxx_messageInfo_SendParam.Size(m) -} -func (m *SendParam) XXX_DiscardUnknown() { - xxx_messageInfo_SendParam.DiscardUnknown(m) -} - -var xxx_messageInfo_SendParam proto.InternalMessageInfo - -func (m *SendParam) GetInputAccount() *InputAccount { - if m != nil { - return m.InputAccount - } - return nil -} - -func (m *SendParam) GetToAddress() []byte { - if m != nil { - return m.ToAddress - } - return nil -} - -func (m *SendParam) GetAmount() uint64 { - if m != nil { - return m.Amount - } - return 0 -} - -type TxParam struct { - Tx []byte `protobuf:"bytes,1,opt,name=tx,proto3" json:"tx,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *TxParam) Reset() { *m = TxParam{} } -func (m *TxParam) String() string { return proto.CompactTextString(m) } -func (*TxParam) ProtoMessage() {} -func (*TxParam) Descriptor() ([]byte, []int) { - return fileDescriptor_transactor_97142763aca9e238, []int{4} -} -func (m *TxParam) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_TxParam.Unmarshal(m, b) -} -func (m *TxParam) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_TxParam.Marshal(b, m, deterministic) -} -func (dst *TxParam) XXX_Merge(src proto.Message) { - xxx_messageInfo_TxParam.Merge(dst, src) -} -func (m *TxParam) XXX_Size() int { - return xxx_messageInfo_TxParam.Size(m) -} -func (m *TxParam) XXX_DiscardUnknown() { - xxx_messageInfo_TxParam.DiscardUnknown(m) -} - -var xxx_messageInfo_TxParam proto.InternalMessageInfo - -func (m *TxParam) GetTx() []byte { - if m != nil { - return m.Tx - } - return nil -} - -type SignTxParam struct { - Tx []byte `protobuf:"bytes,1,opt,name=tx,proto3" json:"tx,omitempty"` - PrivateAccounts []*PrivateAccount `protobuf:"bytes,2,rep,name=privateAccounts,proto3" json:"privateAccounts,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SignTxParam) Reset() { *m = SignTxParam{} } -func (m *SignTxParam) String() string { return proto.CompactTextString(m) } -func (*SignTxParam) ProtoMessage() {} -func (*SignTxParam) Descriptor() ([]byte, []int) { - return fileDescriptor_transactor_97142763aca9e238, []int{5} -} -func (m *SignTxParam) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SignTxParam.Unmarshal(m, b) -} -func (m *SignTxParam) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SignTxParam.Marshal(b, m, deterministic) -} -func (dst *SignTxParam) XXX_Merge(src proto.Message) { - xxx_messageInfo_SignTxParam.Merge(dst, src) -} -func (m *SignTxParam) XXX_Size() int { - return xxx_messageInfo_SignTxParam.Size(m) -} -func (m *SignTxParam) XXX_DiscardUnknown() { - xxx_messageInfo_SignTxParam.DiscardUnknown(m) -} - -var xxx_messageInfo_SignTxParam proto.InternalMessageInfo - -func (m *SignTxParam) GetTx() []byte { - if m != nil { - return m.Tx - } - return nil -} - -func (m *SignTxParam) GetPrivateAccounts() []*PrivateAccount { - if m != nil { - return m.PrivateAccounts - } - return nil -} - -// Results -type SignedTx struct { - Tx []byte `protobuf:"bytes,1,opt,name=tx,proto3" json:"tx,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SignedTx) Reset() { *m = SignedTx{} } -func (m *SignedTx) String() string { return proto.CompactTextString(m) } -func (*SignedTx) ProtoMessage() {} -func (*SignedTx) Descriptor() ([]byte, []int) { - return fileDescriptor_transactor_97142763aca9e238, []int{6} -} -func (m *SignedTx) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SignedTx.Unmarshal(m, b) -} -func (m *SignedTx) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SignedTx.Marshal(b, m, deterministic) -} -func (dst *SignedTx) XXX_Merge(src proto.Message) { - xxx_messageInfo_SignedTx.Merge(dst, src) -} -func (m *SignedTx) XXX_Size() int { - return xxx_messageInfo_SignedTx.Size(m) -} -func (m *SignedTx) XXX_DiscardUnknown() { - xxx_messageInfo_SignedTx.DiscardUnknown(m) -} - -var xxx_messageInfo_SignedTx proto.InternalMessageInfo - -func (m *SignedTx) GetTx() []byte { - if m != nil { - return m.Tx - } - return nil -} - -type CallResult struct { - Return []byte `protobuf:"bytes,1,opt,name=Return,proto3" json:"Return,omitempty"` - GasUsed uint64 `protobuf:"varint,2,opt,name=GasUsed,proto3" json:"GasUsed,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CallResult) Reset() { *m = CallResult{} } -func (m *CallResult) String() string { return proto.CompactTextString(m) } -func (*CallResult) ProtoMessage() {} -func (*CallResult) Descriptor() ([]byte, []int) { - return fileDescriptor_transactor_97142763aca9e238, []int{7} -} -func (m *CallResult) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CallResult.Unmarshal(m, b) -} -func (m *CallResult) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CallResult.Marshal(b, m, deterministic) -} -func (dst *CallResult) XXX_Merge(src proto.Message) { - xxx_messageInfo_CallResult.Merge(dst, src) -} -func (m *CallResult) XXX_Size() int { - return xxx_messageInfo_CallResult.Size(m) -} -func (m *CallResult) XXX_DiscardUnknown() { - xxx_messageInfo_CallResult.DiscardUnknown(m) -} - -var xxx_messageInfo_CallResult proto.InternalMessageInfo - -func (m *CallResult) GetReturn() []byte { - if m != nil { - return m.Return - } - return nil -} - -func (m *CallResult) GetGasUsed() uint64 { - if m != nil { - return m.GasUsed - } - return 0 -} - -type TxReceipt struct { - TxHash []byte `protobuf:"bytes,1,opt,name=TxHash,proto3" json:"TxHash,omitempty"` - CreatesContract bool `protobuf:"varint,2,opt,name=CreatesContract,proto3" json:"CreatesContract,omitempty"` - ContractAddress []byte `protobuf:"bytes,3,opt,name=ContractAddress,proto3" json:"ContractAddress,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *TxReceipt) Reset() { *m = TxReceipt{} } -func (m *TxReceipt) String() string { return proto.CompactTextString(m) } -func (*TxReceipt) ProtoMessage() {} -func (*TxReceipt) Descriptor() ([]byte, []int) { - return fileDescriptor_transactor_97142763aca9e238, []int{8} -} -func (m *TxReceipt) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_TxReceipt.Unmarshal(m, b) -} -func (m *TxReceipt) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_TxReceipt.Marshal(b, m, deterministic) -} -func (dst *TxReceipt) XXX_Merge(src proto.Message) { - xxx_messageInfo_TxReceipt.Merge(dst, src) -} -func (m *TxReceipt) XXX_Size() int { - return xxx_messageInfo_TxReceipt.Size(m) -} -func (m *TxReceipt) XXX_DiscardUnknown() { - xxx_messageInfo_TxReceipt.DiscardUnknown(m) -} - -var xxx_messageInfo_TxReceipt proto.InternalMessageInfo - -func (m *TxReceipt) GetTxHash() []byte { - if m != nil { - return m.TxHash - } - return nil -} - -func (m *TxReceipt) GetCreatesContract() bool { - if m != nil { - return m.CreatesContract - } - return false -} - -func (m *TxReceipt) GetContractAddress() []byte { - if m != nil { - return m.ContractAddress - } - return nil -} - -type InputAccount struct { - PrivateKey []byte `protobuf:"bytes,1,opt,name=privateKey,proto3" json:"privateKey,omitempty"` - Address []byte `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InputAccount) Reset() { *m = InputAccount{} } -func (m *InputAccount) String() string { return proto.CompactTextString(m) } -func (*InputAccount) ProtoMessage() {} -func (*InputAccount) Descriptor() ([]byte, []int) { - return fileDescriptor_transactor_97142763aca9e238, []int{9} -} -func (m *InputAccount) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InputAccount.Unmarshal(m, b) -} -func (m *InputAccount) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InputAccount.Marshal(b, m, deterministic) -} -func (dst *InputAccount) XXX_Merge(src proto.Message) { - xxx_messageInfo_InputAccount.Merge(dst, src) -} -func (m *InputAccount) XXX_Size() int { - return xxx_messageInfo_InputAccount.Size(m) -} -func (m *InputAccount) XXX_DiscardUnknown() { - xxx_messageInfo_InputAccount.DiscardUnknown(m) -} - -var xxx_messageInfo_InputAccount proto.InternalMessageInfo - -func (m *InputAccount) GetPrivateKey() []byte { - if m != nil { - return m.PrivateKey - } - return nil -} - -func (m *InputAccount) GetAddress() []byte { - if m != nil { - return m.Address - } - return nil -} - -type PrivateAccount struct { - PrivateKey []byte `protobuf:"bytes,1,opt,name=PrivateKey,proto3" json:"PrivateKey,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PrivateAccount) Reset() { *m = PrivateAccount{} } -func (m *PrivateAccount) String() string { return proto.CompactTextString(m) } -func (*PrivateAccount) ProtoMessage() {} -func (*PrivateAccount) Descriptor() ([]byte, []int) { - return fileDescriptor_transactor_97142763aca9e238, []int{10} -} -func (m *PrivateAccount) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PrivateAccount.Unmarshal(m, b) -} -func (m *PrivateAccount) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PrivateAccount.Marshal(b, m, deterministic) -} -func (dst *PrivateAccount) XXX_Merge(src proto.Message) { - xxx_messageInfo_PrivateAccount.Merge(dst, src) -} -func (m *PrivateAccount) XXX_Size() int { - return xxx_messageInfo_PrivateAccount.Size(m) -} -func (m *PrivateAccount) XXX_DiscardUnknown() { - xxx_messageInfo_PrivateAccount.DiscardUnknown(m) -} - -var xxx_messageInfo_PrivateAccount proto.InternalMessageInfo - -func (m *PrivateAccount) GetPrivateKey() []byte { - if m != nil { - return m.PrivateKey - } - return nil -} - -func init() { - proto.RegisterType((*CallParam)(nil), "pbtransactor.CallParam") - proto.RegisterType((*CallCodeParam)(nil), "pbtransactor.CallCodeParam") - proto.RegisterType((*TransactParam)(nil), "pbtransactor.TransactParam") - proto.RegisterType((*SendParam)(nil), "pbtransactor.SendParam") - proto.RegisterType((*TxParam)(nil), "pbtransactor.TxParam") - proto.RegisterType((*SignTxParam)(nil), "pbtransactor.SignTxParam") - proto.RegisterType((*SignedTx)(nil), "pbtransactor.SignedTx") - proto.RegisterType((*CallResult)(nil), "pbtransactor.CallResult") - proto.RegisterType((*TxReceipt)(nil), "pbtransactor.TxReceipt") - proto.RegisterType((*InputAccount)(nil), "pbtransactor.InputAccount") - proto.RegisterType((*PrivateAccount)(nil), "pbtransactor.PrivateAccount") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// TransactorClient is the client API for Transactor service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type TransactorClient interface { - // Broadcast a signed and serialised transaction to the mempool - BroadcastTx(ctx context.Context, in *TxParam, opts ...grpc.CallOption) (*TxReceipt, error) - // Perform a 'simulated' call of a contract against the current committed EVM state without any changes been saved - Call(ctx context.Context, in *CallParam, opts ...grpc.CallOption) (*CallResult, error) - // Perform a 'simulated' execution of provided code against the current committed EVM state without any changes been saved - CallCode(ctx context.Context, in *CallCodeParam, opts ...grpc.CallOption) (*CallResult, error) - // Formulate a CallTx transaction signed server-side - Transact(ctx context.Context, in *TransactParam, opts ...grpc.CallOption) (*TxReceipt, error) - // Formulate a CallTx transaction signed server-side and wait for it to be included in a block, retrieving response - TransactAndHold(ctx context.Context, in *TransactParam, opts ...grpc.CallOption) (*pbevents.EventDataCall, error) - // Formulate a SendTx transaction signed server-side - Send(ctx context.Context, in *SendParam, opts ...grpc.CallOption) (*TxReceipt, error) - // Formulate a SendTx transaction signed server-side and wait for it to be included in a block, retrieving response - SendAndHold(ctx context.Context, in *SendParam, opts ...grpc.CallOption) (*TxReceipt, error) - // Sign a transaction server-side - SignTx(ctx context.Context, in *SignTxParam, opts ...grpc.CallOption) (*SignedTx, error) -} - -type transactorClient struct { - cc *grpc.ClientConn -} - -func NewTransactorClient(cc *grpc.ClientConn) TransactorClient { - return &transactorClient{cc} -} - -func (c *transactorClient) BroadcastTx(ctx context.Context, in *TxParam, opts ...grpc.CallOption) (*TxReceipt, error) { - out := new(TxReceipt) - err := c.cc.Invoke(ctx, "/pbtransactor.Transactor/BroadcastTx", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *transactorClient) Call(ctx context.Context, in *CallParam, opts ...grpc.CallOption) (*CallResult, error) { - out := new(CallResult) - err := c.cc.Invoke(ctx, "/pbtransactor.Transactor/Call", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *transactorClient) CallCode(ctx context.Context, in *CallCodeParam, opts ...grpc.CallOption) (*CallResult, error) { - out := new(CallResult) - err := c.cc.Invoke(ctx, "/pbtransactor.Transactor/CallCode", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *transactorClient) Transact(ctx context.Context, in *TransactParam, opts ...grpc.CallOption) (*TxReceipt, error) { - out := new(TxReceipt) - err := c.cc.Invoke(ctx, "/pbtransactor.Transactor/Transact", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *transactorClient) TransactAndHold(ctx context.Context, in *TransactParam, opts ...grpc.CallOption) (*pbevents.EventDataCall, error) { - out := new(pbevents.EventDataCall) - err := c.cc.Invoke(ctx, "/pbtransactor.Transactor/TransactAndHold", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *transactorClient) Send(ctx context.Context, in *SendParam, opts ...grpc.CallOption) (*TxReceipt, error) { - out := new(TxReceipt) - err := c.cc.Invoke(ctx, "/pbtransactor.Transactor/Send", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *transactorClient) SendAndHold(ctx context.Context, in *SendParam, opts ...grpc.CallOption) (*TxReceipt, error) { - out := new(TxReceipt) - err := c.cc.Invoke(ctx, "/pbtransactor.Transactor/SendAndHold", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *transactorClient) SignTx(ctx context.Context, in *SignTxParam, opts ...grpc.CallOption) (*SignedTx, error) { - out := new(SignedTx) - err := c.cc.Invoke(ctx, "/pbtransactor.Transactor/SignTx", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// TransactorServer is the server API for Transactor service. -type TransactorServer interface { - // Broadcast a signed and serialised transaction to the mempool - BroadcastTx(context.Context, *TxParam) (*TxReceipt, error) - // Perform a 'simulated' call of a contract against the current committed EVM state without any changes been saved - Call(context.Context, *CallParam) (*CallResult, error) - // Perform a 'simulated' execution of provided code against the current committed EVM state without any changes been saved - CallCode(context.Context, *CallCodeParam) (*CallResult, error) - // Formulate a CallTx transaction signed server-side - Transact(context.Context, *TransactParam) (*TxReceipt, error) - // Formulate a CallTx transaction signed server-side and wait for it to be included in a block, retrieving response - TransactAndHold(context.Context, *TransactParam) (*pbevents.EventDataCall, error) - // Formulate a SendTx transaction signed server-side - Send(context.Context, *SendParam) (*TxReceipt, error) - // Formulate a SendTx transaction signed server-side and wait for it to be included in a block, retrieving response - SendAndHold(context.Context, *SendParam) (*TxReceipt, error) - // Sign a transaction server-side - SignTx(context.Context, *SignTxParam) (*SignedTx, error) -} - -func RegisterTransactorServer(s *grpc.Server, srv TransactorServer) { - s.RegisterService(&_Transactor_serviceDesc, srv) -} - -func _Transactor_BroadcastTx_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(TxParam) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TransactorServer).BroadcastTx(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pbtransactor.Transactor/BroadcastTx", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TransactorServer).BroadcastTx(ctx, req.(*TxParam)) - } - return interceptor(ctx, in, info, handler) -} - -func _Transactor_Call_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(CallParam) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TransactorServer).Call(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pbtransactor.Transactor/Call", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TransactorServer).Call(ctx, req.(*CallParam)) - } - return interceptor(ctx, in, info, handler) -} - -func _Transactor_CallCode_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(CallCodeParam) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TransactorServer).CallCode(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pbtransactor.Transactor/CallCode", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TransactorServer).CallCode(ctx, req.(*CallCodeParam)) - } - return interceptor(ctx, in, info, handler) -} - -func _Transactor_Transact_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(TransactParam) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TransactorServer).Transact(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pbtransactor.Transactor/Transact", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TransactorServer).Transact(ctx, req.(*TransactParam)) - } - return interceptor(ctx, in, info, handler) -} - -func _Transactor_TransactAndHold_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(TransactParam) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TransactorServer).TransactAndHold(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pbtransactor.Transactor/TransactAndHold", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TransactorServer).TransactAndHold(ctx, req.(*TransactParam)) - } - return interceptor(ctx, in, info, handler) -} - -func _Transactor_Send_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SendParam) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TransactorServer).Send(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pbtransactor.Transactor/Send", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TransactorServer).Send(ctx, req.(*SendParam)) - } - return interceptor(ctx, in, info, handler) -} - -func _Transactor_SendAndHold_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SendParam) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TransactorServer).SendAndHold(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pbtransactor.Transactor/SendAndHold", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TransactorServer).SendAndHold(ctx, req.(*SendParam)) - } - return interceptor(ctx, in, info, handler) -} - -func _Transactor_SignTx_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SignTxParam) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TransactorServer).SignTx(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pbtransactor.Transactor/SignTx", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TransactorServer).SignTx(ctx, req.(*SignTxParam)) - } - return interceptor(ctx, in, info, handler) -} - -var _Transactor_serviceDesc = grpc.ServiceDesc{ - ServiceName: "pbtransactor.Transactor", - HandlerType: (*TransactorServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "BroadcastTx", - Handler: _Transactor_BroadcastTx_Handler, - }, - { - MethodName: "Call", - Handler: _Transactor_Call_Handler, - }, - { - MethodName: "CallCode", - Handler: _Transactor_CallCode_Handler, - }, - { - MethodName: "Transact", - Handler: _Transactor_Transact_Handler, - }, - { - MethodName: "TransactAndHold", - Handler: _Transactor_TransactAndHold_Handler, - }, - { - MethodName: "Send", - Handler: _Transactor_Send_Handler, - }, - { - MethodName: "SendAndHold", - Handler: _Transactor_SendAndHold_Handler, - }, - { - MethodName: "SignTx", - Handler: _Transactor_SignTx_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "github.com/hyperledger/burrow/execution/pbtransactor/transactor.proto", -} - -func init() { - proto.RegisterFile("github.com/hyperledger/burrow/execution/pbtransactor/transactor.proto", fileDescriptor_transactor_97142763aca9e238) -} - -var fileDescriptor_transactor_97142763aca9e238 = []byte{ - // 625 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x55, 0x4f, 0x6f, 0xd3, 0x30, - 0x14, 0x57, 0xd7, 0xac, 0x6b, 0x5f, 0xbb, 0x0d, 0x59, 0x30, 0xb2, 0x30, 0xa1, 0x29, 0xa7, 0x9e, - 0x5a, 0x34, 0x10, 0x02, 0x21, 0x06, 0x5d, 0x37, 0x36, 0x34, 0x90, 0xa6, 0x2c, 0x5c, 0xb8, 0xb9, - 0xf1, 0x5b, 0x17, 0xa9, 0x8d, 0x23, 0xc7, 0xd9, 0xb2, 0x23, 0x77, 0xbe, 0x14, 0xdf, 0x0c, 0xd9, - 0x71, 0xda, 0x26, 0xa5, 0xc0, 0x10, 0xa7, 0xbc, 0x3f, 0x3f, 0xff, 0xde, 0x3f, 0x3f, 0x07, 0x4e, - 0xc6, 0xa1, 0xbc, 0x4e, 0x47, 0xbd, 0x80, 0x4f, 0xfb, 0xd7, 0x77, 0x31, 0x8a, 0x09, 0xb2, 0x31, - 0x8a, 0xfe, 0x28, 0x15, 0x82, 0xdf, 0xf6, 0x31, 0xc3, 0x20, 0x95, 0x21, 0x8f, 0xfa, 0xf1, 0x48, - 0x0a, 0x1a, 0x25, 0x34, 0x90, 0x5c, 0xf4, 0xe7, 0x62, 0x2f, 0x16, 0x5c, 0x72, 0xd2, 0x59, 0x74, - 0x3b, 0xc7, 0x7f, 0x4b, 0x8a, 0x37, 0x18, 0xc9, 0xa4, 0x1f, 0x8f, 0x8c, 0x90, 0x7f, 0x72, 0x4e, - 0xf7, 0x33, 0xb4, 0x86, 0x74, 0x32, 0xb9, 0xa0, 0x82, 0x4e, 0x09, 0x01, 0xeb, 0x4a, 0xf0, 0xa9, - 0x5d, 0xdb, 0xaf, 0x75, 0x3b, 0x9e, 0x96, 0x89, 0x0d, 0x1b, 0x94, 0x31, 0x81, 0x49, 0x62, 0xaf, - 0x69, 0x73, 0xa1, 0x2a, 0x34, 0xa3, 0x92, 0xda, 0xf5, 0x1c, 0xad, 0x64, 0xf7, 0x1c, 0x36, 0x15, - 0xdd, 0x90, 0x33, 0x5c, 0x4d, 0x49, 0xc0, 0x0a, 0x38, 0x43, 0xc3, 0xa7, 0xe5, 0x5f, 0x92, 0xfd, - 0xa8, 0xc1, 0xa6, 0x6f, 0x0a, 0xce, 0xd9, 0x0e, 0xa1, 0x13, 0x46, 0x71, 0x2a, 0x07, 0x41, 0xc0, - 0xd3, 0x48, 0x6a, 0xd6, 0xf6, 0x81, 0xd3, 0x5b, 0x6c, 0x4c, 0xef, 0xe3, 0x02, 0xc2, 0x2b, 0xe1, - 0xef, 0x57, 0x0c, 0x71, 0xa0, 0x39, 0xa6, 0xc9, 0xa7, 0x70, 0x1a, 0x4a, 0xdb, 0xda, 0xaf, 0x75, - 0x2d, 0x6f, 0xa6, 0x93, 0x87, 0xb0, 0x7e, 0x43, 0x27, 0x29, 0xda, 0xeb, 0xda, 0x91, 0x2b, 0xe4, - 0x01, 0xd4, 0xaf, 0x10, 0xed, 0x86, 0xb6, 0x29, 0xd1, 0xfd, 0x56, 0x83, 0xd6, 0x25, 0x46, 0xec, - 0xff, 0xe4, 0xbf, 0x07, 0x2d, 0xc9, 0x07, 0xa5, 0x0a, 0xe6, 0x06, 0xb2, 0x03, 0x0d, 0x3a, 0xd5, - 0xbc, 0x75, 0x9d, 0x80, 0xd1, 0xdc, 0x5d, 0xd8, 0xf0, 0xb3, 0x3c, 0x81, 0x2d, 0x58, 0x93, 0x99, - 0x19, 0xc6, 0x9a, 0xcc, 0x5c, 0x84, 0xf6, 0x65, 0x38, 0x8e, 0x56, 0xb8, 0xc9, 0x07, 0xd8, 0x8e, - 0x45, 0x78, 0x43, 0x25, 0x9a, 0x0c, 0x54, 0xd4, 0x7a, 0xb7, 0x7d, 0xb0, 0x57, 0x4e, 0xf9, 0xa2, - 0x04, 0xf2, 0xaa, 0x87, 0x5c, 0x07, 0x9a, 0x2a, 0x0c, 0x32, 0x3f, 0x5b, 0x4a, 0xe1, 0x10, 0x40, - 0x5d, 0x19, 0x0f, 0x93, 0x74, 0x22, 0x55, 0x0d, 0x1e, 0xca, 0x54, 0x44, 0x06, 0x61, 0x34, 0x35, - 0xb9, 0x53, 0x9a, 0x7c, 0x49, 0x90, 0xe9, 0xba, 0x2d, 0xaf, 0x50, 0xdd, 0x5b, 0x68, 0xf9, 0x99, - 0x87, 0x01, 0x86, 0xb1, 0x3e, 0xee, 0x67, 0x67, 0x34, 0xb9, 0x2e, 0x8e, 0xe7, 0x1a, 0xe9, 0xc2, - 0xf6, 0x50, 0x20, 0x95, 0x98, 0x0c, 0x79, 0x24, 0x05, 0x0d, 0xa4, 0xa6, 0x69, 0x7a, 0x55, 0xb3, - 0x46, 0x1a, 0xb9, 0x68, 0x74, 0x7e, 0x27, 0xaa, 0x66, 0xf7, 0x0c, 0x3a, 0x8b, 0xa3, 0x22, 0x4f, - 0x01, 0x4c, 0xdd, 0xe7, 0x78, 0x67, 0xe2, 0x2f, 0x58, 0x56, 0x5f, 0x3e, 0xf7, 0x19, 0x6c, 0x95, - 0x3b, 0xa8, 0xb8, 0x2e, 0x96, 0xb8, 0xe6, 0x96, 0x83, 0xef, 0x16, 0x80, 0x3f, 0xeb, 0x3f, 0x79, - 0x0b, 0xed, 0x23, 0xc1, 0x29, 0x0b, 0x68, 0x22, 0xfd, 0x8c, 0x3c, 0x2a, 0x4f, 0xc7, 0x4c, 0xd7, - 0x79, 0x5c, 0x35, 0x17, 0x5d, 0x7b, 0x0d, 0x96, 0x1a, 0x01, 0xa9, 0x00, 0x66, 0x0f, 0x83, 0x63, - 0x2f, 0x3b, 0xcc, 0xbc, 0x06, 0xd0, 0x2c, 0x16, 0x9e, 0x3c, 0x59, 0x46, 0xcd, 0x1e, 0x82, 0xdf, - 0x50, 0xbc, 0x87, 0x66, 0x51, 0x4a, 0x95, 0xa2, 0xb4, 0xfd, 0xab, 0xf3, 0x3f, 0x85, 0xed, 0x02, - 0x39, 0x88, 0xd8, 0x19, 0x9f, 0xb0, 0x3f, 0x13, 0x99, 0x57, 0xf0, 0x44, 0x7d, 0x8e, 0xa9, 0xa4, - 0xba, 0x01, 0xaf, 0xc0, 0x52, 0xcb, 0x5a, 0x6d, 0xc4, 0x6c, 0x81, 0x57, 0xa7, 0xf0, 0x0e, 0xda, - 0x0a, 0x55, 0x84, 0xbf, 0x3f, 0xc1, 0x1b, 0x68, 0xe4, 0x9b, 0x48, 0x76, 0x2b, 0x67, 0xe7, 0xfb, - 0xe9, 0xec, 0x2c, 0xbb, 0xd4, 0x4e, 0x1d, 0xbd, 0xfc, 0xfa, 0xe2, 0x5f, 0x7e, 0x31, 0xa3, 0x86, - 0xfe, 0x09, 0x3c, 0xff, 0x19, 0x00, 0x00, 0xff, 0xff, 0x51, 0xbd, 0x3d, 0xf0, 0xa1, 0x06, 0x00, - 0x00, -} diff --git a/execution/pbtransactor/transactor.proto b/execution/pbtransactor/transactor.proto deleted file mode 100644 index dd058388d..000000000 --- a/execution/pbtransactor/transactor.proto +++ /dev/null @@ -1,96 +0,0 @@ -syntax = 'proto3'; - -package pbtransactor; - -option go_package = "github.com/hyperledger/burrow/execution/pbtransactor"; - -import "github.com/hyperledger/burrow/execution/events/pbevents/events.proto"; - -// Transaction Service Definition -service Transactor { - // Broadcast a signed and serialised transaction to the mempool - rpc BroadcastTx (TxParam) returns (TxReceipt); - // Perform a 'simulated' call of a contract against the current committed EVM state without any changes been saved - rpc Call (CallParam) returns (CallResult); - // Perform a 'simulated' execution of provided code against the current committed EVM state without any changes been saved - rpc CallCode (CallCodeParam) returns (CallResult); - // Formulate a CallTx transaction signed server-side - rpc Transact (TransactParam) returns (TxReceipt); - // Formulate a CallTx transaction signed server-side and wait for it to be included in a block, retrieving response - rpc TransactAndHold (TransactParam) returns (pbevents.EventDataCall); - // Formulate a SendTx transaction signed server-side - rpc Send (SendParam) returns (TxReceipt); - // Formulate a SendTx transaction signed server-side and wait for it to be included in a block, retrieving response - rpc SendAndHold (SendParam) returns (TxReceipt); - // Sign a transaction server-side - rpc SignTx (SignTxParam) returns (SignedTx); -} - -// Params -message CallParam { - bytes from = 1; - bytes address = 2; - bytes data = 3; -} - -message CallCodeParam { - bytes from = 1; - bytes code = 2; - bytes data = 3; -} - -message TransactParam { - // The input account to sign with - InputAccount inputAccount = 1; - // The address of the contract to call, or omitted if creating a new contract - bytes address = 2; - // EVM bytecode payload to deliver - bytes data = 3; - // The maximum gas to provide to the EVM when running any code - provided in order to bound the computation time - uint64 gasLimit = 4; - // Value to transfer, where amount = value + fee - uint64 value = 5; - // Fee to offer validators for processing transaction - uint64 fee = 6; -} - -message SendParam { - InputAccount inputAccount = 1; - bytes toAddress = 2; - uint64 amount = 3; -} - -message TxParam { - bytes tx = 1; -} - -message SignTxParam { - bytes tx = 1; - repeated PrivateAccount privateAccounts = 2; -} - -// Results -message SignedTx { - bytes tx = 1; -} - -message CallResult { - bytes Return = 1; - uint64 GasUsed = 2; -} - -message TxReceipt { - bytes TxHash = 1; - bool CreatesContract = 2; - bytes ContractAddress = 3; -} - -message InputAccount { - bytes privateKey = 1; - bytes address = 2; -} - -message PrivateAccount { - bytes PrivateKey = 1; -} -//-------------------------------------------------- \ No newline at end of file diff --git a/execution/simulated_call.go b/execution/simulated_call.go new file mode 100644 index 000000000..fc7156a41 --- /dev/null +++ b/execution/simulated_call.go @@ -0,0 +1,75 @@ +package execution + +import ( + "fmt" + "runtime/debug" + + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/state" + "github.com/hyperledger/burrow/binary" + "github.com/hyperledger/burrow/blockchain" + "github.com/hyperledger/burrow/crypto" + "github.com/hyperledger/burrow/execution/evm" + "github.com/hyperledger/burrow/execution/exec" + "github.com/hyperledger/burrow/execution/executors" + "github.com/hyperledger/burrow/logging" +) + +// Run a contract's code on an isolated and unpersisted state +// Cannot be used to create new contracts +func CallSim(reader state.Reader, tip blockchain.TipInfo, fromAddress, address crypto.Address, data []byte, + logger *logging.Logger) (*exec.TxExecution, error) { + + if evm.IsRegisteredNativeContract(address.Word256()) { + return nil, fmt.Errorf("attempt to call native contract at address "+ + "%X, but native contracts can not be called directly. Use a deployed "+ + "contract that calls the native function instead", address) + } + // This was being run against CheckTx cache, need to understand the reasoning + callee, err := state.GetMutableAccount(reader, address) + if err != nil { + return nil, err + } + if callee == nil { + return nil, fmt.Errorf("account %s does not exist", address) + } + return CallCodeSim(reader, tip, fromAddress, address, callee.Code(), data, logger) +} + +// Run the given code on an isolated and unpersisted state +// Cannot be used to create new contracts. +func CallCodeSim(reader state.Reader, tip blockchain.TipInfo, fromAddress, address crypto.Address, code, data []byte, + logger *logging.Logger) (_ *exec.TxExecution, err error) { + // This was being run against CheckTx cache, need to understand the reasoning + caller := acm.ConcreteAccount{Address: fromAddress}.MutableAccount() + callee := acm.ConcreteAccount{Address: address}.MutableAccount() + + txCache := state.NewCache(reader) + + params := vmParams(tip) + vmach := evm.NewVM(params, caller.Address(), nil, logger.WithScope("CallCode")) + + txe := &exec.TxExecution{} + vmach.SetEventSink(txe) + gas := params.GasLimit + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("panic from VM in simulated call: %v\n%s", r, debug.Stack()) + } + }() + ret, err := vmach.Call(txCache, caller, callee, code, data, 0, &gas) + if err != nil { + return nil, err + } + txe.Return(ret, params.GasLimit-gas) + return txe, nil +} + +func vmParams(tip blockchain.TipInfo) evm.Params { + return evm.Params{ + BlockHeight: tip.LastBlockHeight(), + BlockHash: binary.LeftPadWord256(tip.LastBlockHash()), + BlockTime: tip.LastBlockTime().Unix(), + GasLimit: executors.GasLimit, + } +} diff --git a/execution/state.go b/execution/state.go index 8418c836f..12460d783 100644 --- a/execution/state.go +++ b/execution/state.go @@ -15,22 +15,19 @@ package execution import ( - "context" "fmt" "sync" "time" - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/state" "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/event" - "github.com/hyperledger/burrow/execution/events" + "github.com/hyperledger/burrow/execution/exec" "github.com/hyperledger/burrow/execution/names" "github.com/hyperledger/burrow/genesis" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/permission" - ptypes "github.com/hyperledger/burrow/permission/types" "github.com/tendermint/iavl" dbm "github.com/tendermint/tmlibs/db" ) @@ -49,13 +46,15 @@ const ( accountsPrefix = "a/" storagePrefix = "s/" nameRegPrefix = "n/" - eventPrefix = "e/" + blockPrefix = "b/" + txPrefix = "t/" ) var ( accountsStart, accountsEnd []byte = prefixKeyRange(accountsPrefix) storageStart, storageEnd []byte = prefixKeyRange(storagePrefix) nameRegStart, nameRegEnd []byte = prefixKeyRange(nameRegPrefix) + lastBlockHeightKey = []byte("h") ) // Implements account and blockchain state @@ -66,7 +65,7 @@ var _ Updatable = &writeState{} type Updatable interface { state.Writer names.Writer - event.Publisher + AddBlock(blockExecution *exec.BlockExecution) error } // Wraps state to give access to writer methods @@ -86,8 +85,6 @@ type State struct { // Values may be reassigned (mutex protected) // Previous version of IAVL tree for concurrent read-only access readTree *iavl.Tree - // High water mark for height/index - make sure we do not overwrite events - should only increase - eventKeyHighWatermark events.Key // Last state hash hash []byte } @@ -139,7 +136,7 @@ func MakeGenesisState(db dbm.DB, genesisDoc *genesis.GenesisDoc) (*State, error) globalPerms = genesisDoc.GlobalPermissions // XXX: make sure the set bits are all true // Without it the HasPermission() functions will fail - globalPerms.Base.SetBit = ptypes.AllPermFlags + globalPerms.Base.SetBit = permission.AllPermFlags permsAcc := &acm.ConcreteAccount{ Address: acm.GlobalPermissionsAddress, @@ -195,7 +192,10 @@ func LoadState(db dbm.DB, hash []byte) (*State, error) { func (s *State) Update(updater func(up Updatable) error) ([]byte, error) { s.Lock() defer s.Unlock() - updater(s.writeState) + err := updater(s.writeState) + if err != nil { + return nil, err + } return s.writeState.save() } @@ -244,12 +244,12 @@ func (s *State) GetAccount(address crypto.Address) (acm.Account, error) { func (ws *writeState) UpdateAccount(account acm.Account) error { if account == nil { - return fmt.Errorf("UpdateAccount passed nil account in execution.State") + return fmt.Errorf("UpdateAccount passed nil account in State") } // TODO: find a way to implement something equivalent to this so we can set the account StorageRoot //storageRoot := s.tree.SubTreeHash(prefixedKey(storagePrefix, account.Address().Bytes())) // Alternatively just abandon and - accountWithStorageRoot := acm.AsMutableAccount(account).SetStorageRoot(nil) + accountWithStorageRoot := acm.AsMutableAccount(account) encodedAccount, err := accountWithStorageRoot.Encode() if err != nil { return err @@ -313,40 +313,68 @@ func (s *State) IterateStorage(address crypto.Address, // Events // Execution events -func (ws *writeState) Publish(ctx context.Context, msg interface{}, tags event.Tags) error { - if exeEvent, ok := msg.(*events.Event); ok { - key := exeEvent.Header.Key() - if !key.IsSuccessorOf(ws.state.eventKeyHighWatermark) { - return fmt.Errorf("received event with non-increasing key compared with current high watermark %v: %v", - ws.state.eventKeyHighWatermark, exeEvent) - } - ws.state.eventKeyHighWatermark = key - if exeEvent.Tx != nil { - // Don't serialise the tx (for now) we should normalise and store against tx hash - exeEvent = exeEvent.Copy() - // The header still contains the tx hash - exeEvent.Tx.Tx = nil - } - bs, err := exeEvent.Encode() - if err != nil { - return err - } - ws.state.tree.Set(eventKey(key), bs) +func (ws *writeState) AddBlock(be *exec.BlockExecution) error { + lastBlockHeight, ok := ws.lastBlockHeight() + if ok && be.Height != lastBlockHeight+1 { + return fmt.Errorf("AddBlock received block for height %v but last block height was %v", + be.Height, lastBlockHeight) + } + ws.setLastBlockHeight(be.Height) + // Index transactions so they can be retrieved by their TxHash + for i, txe := range be.TxExecutions { + ws.addTx(txe.TxHash, be.Height, uint64(i)) + } + bs, err := be.Encode() + if err != nil { + return err } + key := blockKey(be.Height) + ws.state.tree.Set(key, bs) return nil } -func (s *State) GetEvents(startKey, endKey events.Key, consumer func(ev *events.Event) (stop bool)) (stopped bool, err error) { - return s.tree.IterateRange(eventKey(startKey), eventKey(endKey), true, +func (ws *writeState) addTx(txHash []byte, height, index uint64) { + ws.state.tree.Set(txKey(txHash), encodeTxRef(height, index)) +} + +func (s *State) GetTx(txHash []byte) (*exec.TxExecution, error) { + _, bs := s.readTree.Get(txKey(txHash)) + if len(bs) == 0 { + return nil, nil + } + height, index, err := decodeTxRef(bs) + if err != nil { + return nil, fmt.Errorf("error decoding database reference to tx %X: %v", txHash, err) + } + be, err := s.GetBlock(height) + if err != nil { + return nil, fmt.Errorf("error getting block %v containing tx %X", height, txHash) + } + if index < uint64(len(be.TxExecutions)) { + return be.TxExecutions[index], nil + } + return nil, fmt.Errorf("retrieved index %v in block %v for tx %X but block only contains %v TxExecutions", + index, height, txHash, len(be.TxExecutions)) +} + +func (s *State) GetBlock(height uint64) (*exec.BlockExecution, error) { + _, bs := s.readTree.Get(blockKey(height)) + if len(bs) == 0 { + return nil, nil + } + return exec.DecodeBlockExecution(bs) +} + +func (s *State) GetBlocks(startHeight, endHeight uint64, consumer func(*exec.BlockExecution) (stop bool)) (stopped bool, err error) { + return s.readTree.IterateRange(blockKey(startHeight), blockKey(endHeight), true, func(_, value []byte) bool { - var exeEvent *events.Event - exeEvent, err = events.DecodeEvent(value) + block, err := exec.DecodeBlockExecution(value) if err != nil { err = fmt.Errorf("error unmarshalling ExecutionEvent in GetEvents: %v", err) // stop iteration on error return true } - return consumer(exeEvent) + return consumer(block) }), err } @@ -356,10 +384,18 @@ func (s *State) Hash() []byte { return s.hash } -func (s *State) LatestEventKey() events.Key { - s.RLock() - defer s.RUnlock() - return s.eventKeyHighWatermark +func (s *writeState) lastBlockHeight() (uint64, bool) { + _, bs := s.state.tree.Get(lastBlockHeightKey) + if len(bs) == 0 { + return 0, false + } + return binary.GetUint64BE(bs), true +} + +func (s *writeState) setLastBlockHeight(height uint64) { + bs := make([]byte, 8) + binary.PutUint64BE(bs, height) + s.state.tree.Set(lastBlockHeightKey, bs) } // Events @@ -368,7 +404,7 @@ func (s *State) LatestEventKey() events.Key { var _ names.IterableReader = &State{} -func (s *State) GetNameEntry(name string) (*names.Entry, error) { +func (s *State) GetName(name string) (*names.Entry, error) { _, entryBytes := s.readTree.Get(prefixedKey(nameRegPrefix, []byte(name))) if entryBytes == nil { return nil, nil @@ -377,7 +413,7 @@ func (s *State) GetNameEntry(name string) (*names.Entry, error) { return names.DecodeEntry(entryBytes) } -func (s *State) IterateNameEntries(consumer func(*names.Entry) (stop bool)) (stopped bool, err error) { +func (s *State) IterateNames(consumer func(*names.Entry) (stop bool)) (stopped bool, err error) { return s.readTree.IterateRange(nameRegStart, nameRegEnd, true, func(key []byte, value []byte) (stop bool) { var entry *names.Entry entry, err = names.DecodeEntry(value) @@ -388,7 +424,7 @@ func (s *State) IterateNameEntries(consumer func(*names.Entry) (stop bool)) (sto }), err } -func (ws *writeState) UpdateNameEntry(entry *names.Entry) error { +func (ws *writeState) UpdateName(entry *names.Entry) error { bs, err := entry.Encode() if err != nil { return err @@ -397,7 +433,7 @@ func (ws *writeState) UpdateNameEntry(entry *names.Entry) error { return nil } -func (ws *writeState) RemoveNameEntry(name string) error { +func (ws *writeState) RemoveName(name string) error { ws.state.tree.Remove(prefixedKey(nameRegPrefix, []byte(name))) return nil } @@ -416,8 +452,32 @@ func (s *State) Copy(db dbm.DB) (*State, error) { return stateCopy, nil } -func eventKey(key events.Key) []byte { - return prefixedKey(eventPrefix, key) +// Key and value helpers + +func encodeTxRef(height, index uint64) []byte { + bs := make([]byte, 16) + binary.PutUint64BE(bs[:8], height) + binary.PutUint64BE(bs[8:], index) + return bs +} + +func decodeTxRef(bs []byte) (height, index uint64, _ error) { + if len(bs) != 16 { + return 0, 0, fmt.Errorf("tx reference must have 16 bytes but '%X' does not", bs) + } + height = binary.GetUint64BE(bs[:8]) + index = binary.GetUint64BE(bs[8:]) + return +} + +func txKey(txHash []byte) []byte { + return prefixedKey(txPrefix, txHash) +} + +func blockKey(height uint64) []byte { + bs := make([]byte, 8) + binary.PutUint64BE(bs, height) + return prefixedKey(blockPrefix, bs) } func prefixedKey(prefix string, suffices ...[]byte) []byte { diff --git a/execution/state_test.go b/execution/state_test.go index 360910ba9..7a821c340 100644 --- a/execution/state_test.go +++ b/execution/state_test.go @@ -15,21 +15,16 @@ package execution import ( - "context" "encoding/json" "fmt" "testing" - "github.com/golang/protobuf/proto" - acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/execution/events" - "github.com/hyperledger/burrow/execution/events/pbevents" "github.com/hyperledger/burrow/execution/evm/sha3" - permission "github.com/hyperledger/burrow/permission/types" - "github.com/hyperledger/burrow/txs" - "github.com/hyperledger/burrow/txs/payload" + "github.com/hyperledger/burrow/execution/exec" + "github.com/hyperledger/burrow/permission" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tendermint/tmlibs/db" @@ -50,63 +45,58 @@ func TestState_UpdateAccount(t *testing.T) { assert.Equal(t, account, accountOut) } -func TestState_Publish(t *testing.T) { +func TestWriteState_AddBlock(t *testing.T) { s := NewState(db.NewMemDB()) - ctx := context.Background() - evs := []*events.Event{ - mkEvent(100, 0), - mkEvent(100, 1), - } + height := uint64(100) + txs := uint64(5) + events := uint64(10) _, err := s.Update(func(ws Updatable) error { - for _, ev := range evs { - require.NoError(t, ws.Publish(ctx, ev, nil)) - } - return nil + return ws.AddBlock(mkBlock(height, txs, events)) }) require.NoError(t, err) - i := 0 - _, err = s.GetEvents(events.NewKey(100, 0), events.NewKey(100, 0), - func(ev *events.Event) (stop bool) { - assert.Equal(t, evs[i], ev) - i++ + _, err = s.GetBlocks(height, height+1, + func(be *exec.BlockExecution) (stop bool) { + for ti := uint64(0); ti < txs; ti++ { + for e := uint64(0); e < events; e++ { + assert.Equal(t, mkEvent(height, ti, e).Header.TxHash.String(), + be.TxExecutions[ti].Events[e].Header.TxHash.String()) + } + } return false }) require.NoError(t, err) // non-increasing events _, err = s.Update(func(ws Updatable) error { - require.Error(t, ws.Publish(ctx, mkEvent(100, 0), nil)) - require.Error(t, ws.Publish(ctx, mkEvent(100, 1), nil)) - require.Error(t, ws.Publish(ctx, mkEvent(99, 1324234), nil)) - require.NoError(t, ws.Publish(ctx, mkEvent(100, 2), nil)) - require.NoError(t, ws.Publish(ctx, mkEvent(101, 0), nil)) return nil }) require.NoError(t, err) } -func TestProtobufEventSerialisation(t *testing.T) { - ev := mkEvent(112, 23) - pbEvent := pbevents.GetExecutionEvent(ev) - bs, err := proto.Marshal(pbEvent) - require.NoError(t, err) - pbEventOut := new(pbevents.ExecutionEvent) - require.NoError(t, proto.Unmarshal(bs, pbEventOut)) - fmt.Println(pbEventOut) - assert.Equal(t, asJSON(t, pbEvent), asJSON(t, pbEventOut)) +func mkBlock(height, txs, events uint64) *exec.BlockExecution { + be := &exec.BlockExecution{ + Height: height, + } + for ti := uint64(0); ti < txs; ti++ { + txe := &exec.TxExecution{ + Height: height, + } + for e := uint64(0); e < events; e++ { + txe.Events = append(txe.Events, mkEvent(height, ti, e)) + } + be.TxExecutions = append(be.TxExecutions, txe) + } + return be } -func mkEvent(height, index uint64) *events.Event { - return &events.Event{ - Header: &events.Header{ +func mkEvent(height, tx, index uint64) *exec.Event { + return &exec.Event{ + Header: &exec.Header{ Height: height, Index: index, - TxHash: sha3.Sha3([]byte(fmt.Sprintf("txhash%v%v", height, index))), - EventID: fmt.Sprintf("eventID: %v%v", height, index), - }, - Tx: &events.EventDataTx{ - Tx: txs.Enclose("foo", &payload.CallTx{}).Tx, + TxHash: sha3.Sha3([]byte(fmt.Sprintf("txhash%v%v%v", height, tx, index))), + EventID: fmt.Sprintf("eventID: %v%v%v", height, tx, index), }, - Log: &events.EventDataLog{ + Log: &exec.LogEvent{ Address: crypto.Address{byte(height), byte(index)}, Topics: []binary.Word256{{1, 2, 3}}, }, diff --git a/execution/transactor.go b/execution/transactor.go index c4d57bba1..3a5cbd274 100644 --- a/execution/transactor.go +++ b/execution/transactor.go @@ -15,414 +15,232 @@ package execution import ( - "bytes" "context" - "encoding/json" "fmt" - "runtime/debug" "time" - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/account/state" - "github.com/hyperledger/burrow/binary" + "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/blockchain" "github.com/hyperledger/burrow/consensus/tendermint/codes" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/event" - "github.com/hyperledger/burrow/execution/errors" - "github.com/hyperledger/burrow/execution/events" - "github.com/hyperledger/burrow/execution/evm" - "github.com/hyperledger/burrow/execution/executors" + "github.com/hyperledger/burrow/execution/exec" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" "github.com/hyperledger/burrow/txs" - "github.com/hyperledger/burrow/txs/payload" abciTypes "github.com/tendermint/abci/types" tmTypes "github.com/tendermint/tendermint/types" ) -const BlockingTimeoutSeconds = 30 - -type Call struct { - Return binary.HexBytes - GasUsed uint64 -} +const ( + BlockingTimeout = 10 * time.Second + SubscribeBufferSize = 10 +) -// Transactor is the controller/middleware for the v0 RPC +// Transactor is responsible for helping to formulate, sign, and broadcast transactions to tendermint +// +// The BroadcastTx* methods are able to work against the mempool Accounts (pending) state rather than the +// committed (final) Accounts state and can assign a sequence number based on all of the txs +// seen since the last block - provided these transactions are successfully committed (via DeliverTx) then +// subsequent transactions will have valid sequence numbers. This allows Burrow to coordinate sequencing and signing +// for a key it holds or is provided - it is down to the key-holder to manage the mutual information between transactions +// concurrent within a new block window. type Transactor struct { - tip *blockchain.Tip - eventEmitter event.Emitter - broadcastTxAsync func(tx tmTypes.Tx, cb func(*abciTypes.Response)) error - txEncoder txs.Encoder - logger *logging.Logger + Tip blockchain.TipInfo + Subscribable event.Subscribable + MempoolAccounts *Accounts + checkTxAsync func(tx tmTypes.Tx, cb func(*abciTypes.Response)) error + txEncoder txs.Encoder + logger *logging.Logger } -func NewTransactor(tip *blockchain.Tip, eventEmitter event.Emitter, - broadcastTxAsync func(tx tmTypes.Tx, cb func(*abciTypes.Response)) error, txEncoder txs.Encoder, +func NewTransactor(tip blockchain.TipInfo, subscribable event.Subscribable, mempoolAccounts *Accounts, + checkTxAsync func(tx tmTypes.Tx, cb func(*abciTypes.Response)) error, txEncoder txs.Encoder, logger *logging.Logger) *Transactor { return &Transactor{ - tip: tip, - eventEmitter: eventEmitter, - broadcastTxAsync: broadcastTxAsync, - txEncoder: txEncoder, - logger: logger.With(structure.ComponentKey, "Transactor"), - } -} - -// Run a contract's code on an isolated and unpersisted state -// Cannot be used to create new contracts -func (trans *Transactor) Call(reader state.Reader, fromAddress, address crypto.Address, - data []byte) (call *Call, err error) { - - if evm.IsRegisteredNativeContract(address.Word256()) { - return nil, fmt.Errorf("attempt to call native contract at address "+ - "%X, but native contracts can not be called directly. Use a deployed "+ - "contract that calls the native function instead", address) - } - // This was being run against CheckTx cache, need to understand the reasoning - callee, err := state.GetMutableAccount(reader, address) - if err != nil { - return nil, err - } - if callee == nil { - return nil, fmt.Errorf("account %s does not exist", address) - } - caller := acm.ConcreteAccount{Address: fromAddress}.MutableAccount() - txCache := state.NewCache(reader) - params := vmParams(trans.tip) - - vmach := evm.NewVM(params, caller.Address(), nil, trans.logger.WithScope("Call")) - vmach.SetPublisher(trans.eventEmitter) - - gas := params.GasLimit - defer func() { - if r := recover(); r != nil { - err = fmt.Errorf("panic from VM in simulated call: %v\n%s", r, debug.Stack()) - } - }() - ret, err := vmach.Call(txCache, caller, callee, callee.Code(), data, 0, &gas) - if err != nil { - return nil, err - } - gasUsed := params.GasLimit - gas - return &Call{Return: ret, GasUsed: gasUsed}, nil -} - -// Run the given code on an isolated and unpersisted state -// Cannot be used to create new contracts. -func (trans *Transactor) CallCode(reader state.Reader, fromAddress crypto.Address, code, data []byte) (*Call, error) { - // This was being run against CheckTx cache, need to understand the reasoning - callee := acm.ConcreteAccount{Address: fromAddress}.MutableAccount() - caller := acm.ConcreteAccount{Address: fromAddress}.MutableAccount() - txCache := state.NewCache(reader) - params := vmParams(trans.tip) - - vmach := evm.NewVM(params, caller.Address(), nil, trans.logger.WithScope("CallCode")) - gas := params.GasLimit - ret, err := vmach.Call(txCache, caller, callee, code, data, 0, &gas) - if err != nil { - return nil, err - } - gasUsed := params.GasLimit - gas - return &Call{Return: ret, GasUsed: gasUsed}, nil -} - -func (trans *Transactor) BroadcastTxAsyncRaw(txBytes []byte, callback func(res *abciTypes.Response)) error { - return trans.broadcastTxAsync(txBytes, callback) -} - -func (trans *Transactor) BroadcastTxAsync(txEnv *txs.Envelope, callback func(res *abciTypes.Response)) error { - err := txEnv.Validate() - if err != nil { - return err - } - txBytes, err := trans.txEncoder.EncodeTx(txEnv) - if err != nil { - return fmt.Errorf("error encoding transaction: %v", err) - } - return trans.BroadcastTxAsyncRaw(txBytes, callback) -} - -// Broadcast a transaction and waits for a response from the mempool. Transactions to BroadcastTx will block during -// various mempool operations (managed by Tendermint) including mempool Reap, Commit, and recheckTx. -func (trans *Transactor) BroadcastTx(txEnv *txs.Envelope) (*txs.Receipt, error) { - trans.logger.Trace.Log("method", "BroadcastTx", - "tx_hash", txEnv.Tx.Hash(), - "tx", txEnv.String()) - err := txEnv.Validate() - if err != nil { - return nil, err - } - txBytes, err := trans.txEncoder.EncodeTx(txEnv) - if err != nil { - return nil, err - } - return trans.BroadcastTxRaw(txBytes) -} - -func (trans *Transactor) BroadcastTxRaw(txBytes []byte) (*txs.Receipt, error) { - responseCh := make(chan *abciTypes.Response, 1) - err := trans.BroadcastTxAsyncRaw(txBytes, func(res *abciTypes.Response) { - responseCh <- res - }) - - if err != nil { - return nil, err - } - response := <-responseCh - checkTxResponse := response.GetCheckTx() - if checkTxResponse == nil { - return nil, fmt.Errorf("application did not return CheckTx response") - } - - switch checkTxResponse.Code { - case codes.TxExecutionSuccessCode: - receipt := new(txs.Receipt) - err := json.Unmarshal(checkTxResponse.Data, receipt) + Tip: tip, + Subscribable: subscribable, + MempoolAccounts: mempoolAccounts, + checkTxAsync: checkTxAsync, + txEncoder: txEncoder, + logger: logger.With(structure.ComponentKey, "Transactor"), + } +} + +func (trans *Transactor) BroadcastTxSync(ctx context.Context, txEnv *txs.Envelope) (*exec.TxExecution, error) { + // Subscribe to TX + // Sign if needed - must do before we sign in order to get correct TxHash + if len(txEnv.Signatories) == 0 { + var err error + var unlock UnlockFunc + txEnv, unlock, err = trans.SignTxMempool(txEnv) if err != nil { - return nil, fmt.Errorf("could not deserialise transaction receipt: %s", err) + return nil, fmt.Errorf("error signing trnasction: %v", err) } - return receipt, nil - default: - return nil, fmt.Errorf("error returned by Tendermint in BroadcastTxSync "+ - "ABCI code: %v, ABCI log: %v", checkTxResponse.Code, checkTxResponse.Log) - } -} - -// Orders calls to BroadcastTx using lock (waits for response from core before releasing) -func (trans *Transactor) Transact(sequentialSigningAccount *SequentialSigningAccount, address *crypto.Address, data []byte, - gasLimit, value, fee uint64) (*txs.Receipt, error) { - - // Use the get the freshest sequence numbers from mempool state and hold the lock until we get a response from - // CheckTx - inputAccount, unlock, err := sequentialSigningAccount.Lock() - if err != nil { - return nil, err - } - defer unlock() - if binary.IsUint64SumOverflow(value, fee) { - return nil, fmt.Errorf("amount to transfer overflows uint64 amount = %v (value) + %v (fee)", value, fee) - } - txEnv, err := trans.formulateCallTx(inputAccount, address, data, gasLimit, value+fee, fee) - if err != nil { - return nil, err - } - return trans.BroadcastTx(txEnv) -} - -func (trans *Transactor) TransactAndHold(ctx context.Context, sequentialSigningAccount *SequentialSigningAccount, - address *crypto.Address, data []byte, gasLimit, value, fee uint64) (*events.EventDataCall, error) { - - inputAccount, unlock, err := sequentialSigningAccount.Lock() - if err != nil { - return nil, err - } - defer unlock() - if binary.IsUint64SumOverflow(value, fee) { - return nil, fmt.Errorf("amount to transfer overflows uint64 amount = %v (value) + %v (fee)", value, fee) - } - callTxEnv, err := trans.formulateCallTx(inputAccount, address, data, gasLimit, value+fee, fee) - if err != nil { - return nil, err + defer unlock() } - expectedReceipt := callTxEnv.Tx.GenerateReceipt() - - subID, err := event.GenerateSubscriptionID() + txHash := txEnv.Tx.Hash() + subID := event.GenSubID() + out, err := trans.Subscribable.Subscribe(ctx, subID, exec.QueryForTxExecution(txHash), SubscribeBufferSize) if err != nil { return nil, err } + defer trans.Subscribable.UnsubscribeAll(context.Background(), subID) - // We want non-blocking on the first event received (but buffer the value), - // after which we want to block (and then discard the value - see below) - ch := make(chan *events.EventDataCall, 1) - - err = events.SubscribeAccountCall(context.Background(), trans.eventEmitter, subID, expectedReceipt.ContractAddress, - expectedReceipt.TxHash, 0, ch) + checkTxReceipt, err := trans.CheckTxSync(txEnv) if err != nil { return nil, err } - // Will clean up callback goroutine and subscription in pubsub - defer trans.eventEmitter.UnsubscribeAll(context.Background(), subID) - - receipt, err := trans.BroadcastTx(callTxEnv) - if err != nil { - return nil, err - } - if !bytes.Equal(receipt.TxHash, expectedReceipt.TxHash) { - return nil, fmt.Errorf("BroadcastTx received TxHash %X but %X was expected", - receipt.TxHash, expectedReceipt.TxHash) - } - - timer := time.NewTimer(BlockingTimeoutSeconds * time.Second) + // Wait for all responses + timer := time.NewTimer(BlockingTimeout) defer timer.Stop() + // Get all the execution events for this Tx select { case <-ctx.Done(): return nil, ctx.Err() case <-timer.C: - return nil, fmt.Errorf("transaction timed out TxHash: %X", expectedReceipt.TxHash) - case eventDataCall := <-ch: - if eventDataCall.Exception != nil && eventDataCall.Exception.ErrorCode() != errors.ErrorCodeExecutionReverted { - return nil, fmt.Errorf("error when transacting: %v", eventDataCall.Exception) - } else { - return eventDataCall, nil - } + return nil, fmt.Errorf("timed out waiting for transaction with hash %v timed out after %v", + checkTxReceipt.TxHash, BlockingTimeout) + case msg := <-out: + return msg.(*exec.TxExecution), nil } } -func (trans *Transactor) formulateCallTx(inputAccount *SigningAccount, address *crypto.Address, data []byte, - gasLimit, amount, fee uint64) (*txs.Envelope, error) { - - txInput := &payload.TxInput{ - Address: inputAccount.Address(), - Amount: amount, - Sequence: inputAccount.Sequence() + 1, - } - tx := &payload.CallTx{ - Input: txInput, - Address: address, - GasLimit: gasLimit, - Fee: fee, - Data: data, - } - env := txs.Enclose(trans.tip.ChainID(), tx) - // Got ourselves a tx. - err := env.Sign(inputAccount) - if err != nil { - return nil, err +// Broadcast a transaction without waiting for confirmation - will attempt to sign server-side and set sequence numbers +// if no signatures are provided +func (trans *Transactor) BroadcastTxAsync(txEnv *txs.Envelope) (*txs.Receipt, error) { + // Attempt to sign unless signatures provided + if len(txEnv.Signatories) == 0 { + var err error + var unlock UnlockFunc + txEnv, unlock, err = trans.SignTxMempool(txEnv) + if err != nil { + return nil, err + } + defer unlock() } - return env, nil + return trans.CheckTxSync(txEnv) } -func (trans *Transactor) Send(sequentialSigningAccount *SequentialSigningAccount, toAddress crypto.Address, - amount uint64) (*txs.Receipt, error) { - - inputAccount, unlock, err := sequentialSigningAccount.Lock() - if err != nil { - return nil, err +func (trans *Transactor) SignTxMempool(txEnv *txs.Envelope) (*txs.Envelope, UnlockFunc, error) { + inputs := txEnv.Tx.GetInputs() + signers := make([]acm.AddressableSigner, len(inputs)) + unlockers := make([]UnlockFunc, len(inputs)) + for i, input := range inputs { + ssa, err := trans.MempoolAccounts.SequentialSigningAccount(input.Address) + if err != nil { + return nil, nil, err + } + sa, unlock, err := ssa.Lock() + if err != nil { + return nil, nil, err + } + // Hold lock until safely in mempool - important that this is held until after CheckTxSync returns + unlockers[i] = unlock + signers[i] = sa + // Set sequence number consecutively from mempool + input.Sequence = sa.Sequence() + 1 } - defer unlock() - sendTxEnv, err := trans.formulateSendTx(inputAccount, toAddress, amount) + err := txEnv.Sign(signers...) if err != nil { - return nil, err + return nil, nil, err } - - return trans.BroadcastTx(sendTxEnv) + return txEnv, UnlockFunc(func() { + for _, unlock := range unlockers { + defer unlock() + } + }), nil } -func (trans *Transactor) SendAndHold(ctx context.Context, sequentialSigningAccount *SequentialSigningAccount, - toAddress crypto.Address, amount uint64) (*txs.Receipt, error) { - - inputAccount, unlock, err := sequentialSigningAccount.Lock() - if err != nil { - return nil, err +func (trans *Transactor) SignTx(txEnv *txs.Envelope) (*txs.Envelope, error) { + var err error + inputs := txEnv.Tx.GetInputs() + signers := make([]acm.AddressableSigner, len(inputs)) + for i, input := range inputs { + signers[i], err = trans.MempoolAccounts.SigningAccount(input.Address) } - defer unlock() - - sendTxEnv, err := trans.formulateSendTx(inputAccount, toAddress, amount) + err = txEnv.Sign(signers...) if err != nil { return nil, err } - expectedReceipt := sendTxEnv.Tx.GenerateReceipt() + return txEnv, nil +} - subID, err := event.GenerateSubscriptionID() +// Broadcast a transaction and waits for a response from the mempool. Transactions to BroadcastTx will block during +// various mempool operations (managed by Tendermint) including mempool Reap, Commit, and recheckTx. +func (trans *Transactor) CheckTxSync(txEnv *txs.Envelope) (*txs.Receipt, error) { + trans.logger.Trace.Log("method", "CheckTxSync", + "tx_hash", txEnv.Tx.Hash(), + "tx", txEnv.String()) + err := txEnv.Validate() if err != nil { return nil, err } - - wc := make(chan *payload.SendTx) - err = events.SubscribeAccountOutputSendTx(context.Background(), trans.eventEmitter, subID, toAddress, - expectedReceipt.TxHash, wc) + txBytes, err := trans.txEncoder.EncodeTx(txEnv) if err != nil { return nil, err } - defer trans.eventEmitter.UnsubscribeAll(context.Background(), subID) + return trans.CheckTxSyncRaw(txBytes) +} - receipt, err := trans.BroadcastTx(sendTxEnv) +func (trans *Transactor) CheckTxSyncRaw(txBytes []byte) (*txs.Receipt, error) { + responseCh := make(chan *abciTypes.Response, 1) + err := trans.CheckTxAsyncRaw(txBytes, func(res *abciTypes.Response) { + responseCh <- res + }) if err != nil { return nil, err } - if !bytes.Equal(receipt.TxHash, expectedReceipt.TxHash) { - return nil, fmt.Errorf("BroadcastTx received TxHash %X but %X was expected", - receipt.TxHash, expectedReceipt.TxHash) - } - - timer := time.NewTimer(BlockingTimeoutSeconds * time.Second) + timer := time.NewTimer(BlockingTimeout) defer timer.Stop() select { - case <-ctx.Done(): - return nil, ctx.Err() case <-timer.C: - return nil, fmt.Errorf("transaction timed out TxHash: %X", expectedReceipt.TxHash) - case sendTx := <-wc: - // This is a double check - we subscribed to this tx's hash so something has gone wrong if the amounts don't match - if sendTx.Inputs[0].Amount == amount { - return expectedReceipt, nil + return nil, fmt.Errorf("timed out waiting for CheckTx response in CheckTxSyncRaw") + case response := <-responseCh: + checkTxResponse := response.GetCheckTx() + if checkTxResponse == nil { + return nil, fmt.Errorf("application did not return CheckTx response") } - return nil, fmt.Errorf("received SendTx but hash doesn't seem to match what we subscribed to, "+ - "received SendTx: %v which does not match receipt on sending: %v", sendTx, expectedReceipt) - } -} - -func (trans *Transactor) formulateSendTx(inputAccount *SigningAccount, toAddress crypto.Address, - amount uint64) (*txs.Envelope, error) { - sendTx := payload.NewSendTx() - txInput := &payload.TxInput{ - Address: inputAccount.Address(), - Amount: amount, - Sequence: inputAccount.Sequence() + 1, - } - sendTx.Inputs = append(sendTx.Inputs, txInput) - txOutput := &payload.TxOutput{Address: toAddress, Amount: amount} - sendTx.Outputs = append(sendTx.Outputs, txOutput) - - env := txs.Enclose(trans.tip.ChainID(), sendTx) - err := env.Sign(inputAccount) - if err != nil { - return nil, err + switch checkTxResponse.Code { + case codes.TxExecutionSuccessCode: + receipt, err := txs.DecodeReceipt(checkTxResponse.Data) + if err != nil { + return nil, fmt.Errorf("could not deserialise transaction receipt: %s", err) + } + return receipt, nil + default: + return nil, fmt.Errorf("error returned by Tendermint in BroadcastTxSync "+ + "ABCI code: %v, ABCI log: %v", checkTxResponse.Code, checkTxResponse.Log) + } } - - return env, nil } -func (trans *Transactor) TransactNameReg(sequentialSigningAccount *SequentialSigningAccount, name, data string, amount, - fee uint64) (*txs.Receipt, error) { +func (trans *Transactor) CheckTxAsyncRaw(txBytes []byte, callback func(res *abciTypes.Response)) error { + return trans.checkTxAsync(txBytes, callback) +} - inputAccount, unlock, err := sequentialSigningAccount.Lock() +func (trans *Transactor) CheckTxAsync(txEnv *txs.Envelope, callback func(res *abciTypes.Response)) error { + err := txEnv.Validate() if err != nil { - return nil, err + return err } - defer unlock() - // Formulate and sign - tx := payload.NewNameTxWithSequence(inputAccount.PublicKey(), name, data, amount, fee, inputAccount.Sequence()+1) - env := txs.Enclose(trans.tip.ChainID(), tx) - err = env.Sign(inputAccount) + txBytes, err := trans.txEncoder.EncodeTx(txEnv) if err != nil { - return nil, err + return fmt.Errorf("error encoding transaction: %v", err) } - return trans.BroadcastTx(env) + return trans.CheckTxAsyncRaw(txBytes, callback) } -// Sign a transaction -func (trans *Transactor) SignTx(txEnv *txs.Envelope, signingAccounts []acm.AddressableSigner) (*txs.Envelope, error) { - // more checks? - err := txEnv.Sign(signingAccounts...) - if err != nil { - return nil, err - } - return txEnv, nil +func (trans *Transactor) CallCodeSim(fromAddress crypto.Address, code, data []byte) (*exec.TxExecution, error) { + return CallCodeSim(trans.MempoolAccounts, trans.Tip, fromAddress, fromAddress, code, data, trans.logger) } -func vmParams(tip *blockchain.Tip) evm.Params { - return evm.Params{ - BlockHeight: tip.LastBlockHeight(), - BlockHash: binary.LeftPadWord256(tip.LastBlockHash()), - BlockTime: tip.LastBlockTime().Unix(), - GasLimit: executors.GasLimit, - } +func (trans *Transactor) CallSim(fromAddress, address crypto.Address, data []byte) (*exec.TxExecution, error) { + return CallSim(trans.MempoolAccounts, trans.Tip, fromAddress, address, data, trans.logger) } diff --git a/execution/transactor_test.go b/execution/transactor_test.go new file mode 100644 index 000000000..f8c638954 --- /dev/null +++ b/execution/transactor_test.go @@ -0,0 +1,77 @@ +// Copyright 2017 Monax Industries Limited +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package execution + +import ( + "context" + "testing" + "time" + + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/state" + "github.com/hyperledger/burrow/blockchain" + "github.com/hyperledger/burrow/consensus/tendermint/codes" + "github.com/hyperledger/burrow/crypto" + "github.com/hyperledger/burrow/event" + "github.com/hyperledger/burrow/execution/exec" + "github.com/hyperledger/burrow/keys/mock" + "github.com/hyperledger/burrow/logging" + "github.com/hyperledger/burrow/txs" + "github.com/hyperledger/burrow/txs/payload" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/abci/types" + tmTypes "github.com/tendermint/tendermint/types" +) + +func TestTransactor_BroadcastTxSync(t *testing.T) { + chainID := "TestChain" + tip := blockchain.NewTip(chainID, time.Time{}, []byte("genesis")) + logger := logging.NewNoopLogger() + evc := event.NewEmitter(logger) + txCodec := txs.NewAminoCodec() + privAccount := acm.GeneratePrivateAccountFromSecret("frogs") + tx := &payload.CallTx{ + Input: &payload.TxInput{ + Address: privAccount.Address(), + }, + Address: &crypto.Address{1, 2, 3}, + } + txEnv := txs.Enclose(chainID, tx) + err := txEnv.Sign(privAccount) + require.NoError(t, err) + height := uint64(35) + trans := NewTransactor(tip, evc, NewAccounts(state.NewMemoryState(), mock.NewKeyClient(privAccount), 100), + func(tx tmTypes.Tx, cb func(*abciTypes.Response)) error { + txe := exec.NewTxExecution(txEnv) + txe.Height = height + err := evc.Publish(context.Background(), txe, txe.Tagged()) + if err != nil { + return err + } + bs, err := txe.Receipt.Encode() + if err != nil { + return err + } + cb(abciTypes.ToResponseCheckTx(abciTypes.ResponseCheckTx{ + Code: codes.TxExecutionSuccessCode, + Data: bs, + })) + return nil + }, txCodec, logger) + txe, err := trans.BroadcastTxSync(context.Background(), txEnv) + require.NoError(t, err) + assert.Equal(t, height, txe.Height) +} diff --git a/genesis/deterministic_genesis.go b/genesis/deterministic_genesis.go index ca023f261..6c4e6a209 100644 --- a/genesis/deterministic_genesis.go +++ b/genesis/deterministic_genesis.go @@ -5,7 +5,7 @@ import ( "math/rand" "time" - acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/permission" ) diff --git a/genesis/genesis.go b/genesis/genesis.go index d60564415..6d91fd472 100644 --- a/genesis/genesis.go +++ b/genesis/genesis.go @@ -21,10 +21,9 @@ import ( "sort" "time" - acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/permission" - ptypes "github.com/hyperledger/burrow/permission/types" ) // How many bytes to take from the front of the GenesisDoc hash to append @@ -45,7 +44,7 @@ type BasicAccount struct { type Account struct { BasicAccount Name string - Permissions ptypes.AccountPermissions + Permissions permission.AccountPermissions } type Validator struct { @@ -62,7 +61,7 @@ type GenesisDoc struct { GenesisTime time.Time ChainName string Salt []byte `json:",omitempty" toml:",omitempty"` - GlobalPermissions ptypes.AccountPermissions + GlobalPermissions permission.AccountPermissions Accounts []Account Validators []Validator } diff --git a/genesis/genesis_test.go b/genesis/genesis_test.go index 0c5021bb0..640bf18d9 100644 --- a/genesis/genesis_test.go +++ b/genesis/genesis_test.go @@ -5,7 +5,7 @@ import ( "testing" "time" - acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/permission" "github.com/stretchr/testify/assert" ) diff --git a/genesis/spec/genesis_spec.go b/genesis/spec/genesis_spec.go index 3f3aba5f3..cb4fb76cf 100644 --- a/genesis/spec/genesis_spec.go +++ b/genesis/spec/genesis_spec.go @@ -10,7 +10,6 @@ import ( "github.com/hyperledger/burrow/genesis" "github.com/hyperledger/burrow/keys" "github.com/hyperledger/burrow/permission" - ptypes "github.com/hyperledger/burrow/permission/types" ) const DefaultAmount uint64 = 1000000 @@ -62,7 +61,7 @@ func (gs *GenesisSpec) GenesisDoc(keyClient keys.KeyClient, generateNodeKeys boo if err != nil { return nil, err } - genesisDoc.GlobalPermissions = ptypes.AccountPermissions{ + genesisDoc.GlobalPermissions = permission.AccountPermissions{ Base: basePerms, } } diff --git a/genesis/spec/genesis_spec_test.go b/genesis/spec/genesis_spec_test.go index 0a9aeb7af..98665055d 100644 --- a/genesis/spec/genesis_spec_test.go +++ b/genesis/spec/genesis_spec_test.go @@ -5,7 +5,7 @@ import ( "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/keys/mock" - permission "github.com/hyperledger/burrow/permission/types" + "github.com/hyperledger/burrow/permission" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/genesis/spec/presets.go b/genesis/spec/presets.go index 30e6c08a1..3025d98c0 100644 --- a/genesis/spec/presets.go +++ b/genesis/spec/presets.go @@ -3,7 +3,7 @@ package spec import ( "sort" - permission "github.com/hyperledger/burrow/permission/types" + "github.com/hyperledger/burrow/permission" ) // Files here can be used as starting points for building various 'chain types' but are otherwise diff --git a/genesis/spec/presets_test.go b/genesis/spec/presets_test.go index df77f9bdb..762e397bd 100644 --- a/genesis/spec/presets_test.go +++ b/genesis/spec/presets_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/hyperledger/burrow/keys/mock" - permission "github.com/hyperledger/burrow/permission/types" + "github.com/hyperledger/burrow/permission" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/genesis/spec/spec.pb.go b/genesis/spec/spec.pb.go new file mode 100644 index 000000000..9d568bfd4 --- /dev/null +++ b/genesis/spec/spec.pb.go @@ -0,0 +1,662 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: spec.proto + +/* + Package spec is a generated protocol buffer package. + + It is generated from these files: + spec.proto + + It has these top-level messages: + TemplateAccount +*/ +package spec + +import proto "github.com/gogo/protobuf/proto" +import golang_proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" +import _ "github.com/gogo/protobuf/gogoproto" +import crypto "github.com/hyperledger/burrow/crypto" + +import github_com_hyperledger_burrow_crypto "github.com/hyperledger/burrow/crypto" + +import io "io" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = golang_proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package + +type TemplateAccount struct { + Name string `protobuf:"bytes,1,opt,name=Name" json:"Name"` + Address *github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,2,opt,name=Address,customtype=github.com/hyperledger/burrow/crypto.Address" json:",omitempty" toml:",omitempty"` + NodeAddress *github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,3,opt,name=NodeAddress,customtype=github.com/hyperledger/burrow/crypto.Address" json:",omitempty" toml:",omitempty"` + PublicKey *crypto.PublicKey `protobuf:"bytes,4,opt,name=PublicKey" json:",omitempty" toml:",omitempty"` + Amount *uint64 `protobuf:"varint,5,opt,name=Amount" json:",omitempty" toml:",omitempty"` + Power *uint64 `protobuf:"varint,6,opt,name=Power" json:",omitempty" toml:",omitempty"` + Permissions []string `protobuf:"bytes,7,rep,name=Permissions" json:",omitempty" toml:",omitempty"` + Roles []string `protobuf:"bytes,8,rep,name=Roles" json:",omitempty" toml:",omitempty"` +} + +func (m *TemplateAccount) Reset() { *m = TemplateAccount{} } +func (m *TemplateAccount) String() string { return proto.CompactTextString(m) } +func (*TemplateAccount) ProtoMessage() {} +func (*TemplateAccount) Descriptor() ([]byte, []int) { return fileDescriptorSpec, []int{0} } + +func (m *TemplateAccount) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *TemplateAccount) GetPublicKey() *crypto.PublicKey { + if m != nil { + return m.PublicKey + } + return nil +} + +func (m *TemplateAccount) GetAmount() uint64 { + if m != nil && m.Amount != nil { + return *m.Amount + } + return 0 +} + +func (m *TemplateAccount) GetPower() uint64 { + if m != nil && m.Power != nil { + return *m.Power + } + return 0 +} + +func (m *TemplateAccount) GetPermissions() []string { + if m != nil { + return m.Permissions + } + return nil +} + +func (m *TemplateAccount) GetRoles() []string { + if m != nil { + return m.Roles + } + return nil +} + +func (*TemplateAccount) XXX_MessageName() string { + return "spec.TemplateAccount" +} +func init() { + proto.RegisterType((*TemplateAccount)(nil), "spec.TemplateAccount") + golang_proto.RegisterType((*TemplateAccount)(nil), "spec.TemplateAccount") +} +func (m *TemplateAccount) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *TemplateAccount) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + dAtA[i] = 0xa + i++ + i = encodeVarintSpec(dAtA, i, uint64(len(m.Name))) + i += copy(dAtA[i:], m.Name) + if m.Address != nil { + dAtA[i] = 0x12 + i++ + i = encodeVarintSpec(dAtA, i, uint64(m.Address.Size())) + n1, err := m.Address.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n1 + } + if m.NodeAddress != nil { + dAtA[i] = 0x1a + i++ + i = encodeVarintSpec(dAtA, i, uint64(m.NodeAddress.Size())) + n2, err := m.NodeAddress.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n2 + } + if m.PublicKey != nil { + dAtA[i] = 0x22 + i++ + i = encodeVarintSpec(dAtA, i, uint64(m.PublicKey.Size())) + n3, err := m.PublicKey.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n3 + } + if m.Amount != nil { + dAtA[i] = 0x28 + i++ + i = encodeVarintSpec(dAtA, i, uint64(*m.Amount)) + } + if m.Power != nil { + dAtA[i] = 0x30 + i++ + i = encodeVarintSpec(dAtA, i, uint64(*m.Power)) + } + if len(m.Permissions) > 0 { + for _, s := range m.Permissions { + dAtA[i] = 0x3a + i++ + l = len(s) + for l >= 1<<7 { + dAtA[i] = uint8(uint64(l)&0x7f | 0x80) + l >>= 7 + i++ + } + dAtA[i] = uint8(l) + i++ + i += copy(dAtA[i:], s) + } + } + if len(m.Roles) > 0 { + for _, s := range m.Roles { + dAtA[i] = 0x42 + i++ + l = len(s) + for l >= 1<<7 { + dAtA[i] = uint8(uint64(l)&0x7f | 0x80) + l >>= 7 + i++ + } + dAtA[i] = uint8(l) + i++ + i += copy(dAtA[i:], s) + } + } + return i, nil +} + +func encodeVarintSpec(dAtA []byte, offset int, v uint64) int { + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return offset + 1 +} +func (m *TemplateAccount) Size() (n int) { + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovSpec(uint64(l)) + if m.Address != nil { + l = m.Address.Size() + n += 1 + l + sovSpec(uint64(l)) + } + if m.NodeAddress != nil { + l = m.NodeAddress.Size() + n += 1 + l + sovSpec(uint64(l)) + } + if m.PublicKey != nil { + l = m.PublicKey.Size() + n += 1 + l + sovSpec(uint64(l)) + } + if m.Amount != nil { + n += 1 + sovSpec(uint64(*m.Amount)) + } + if m.Power != nil { + n += 1 + sovSpec(uint64(*m.Power)) + } + if len(m.Permissions) > 0 { + for _, s := range m.Permissions { + l = len(s) + n += 1 + l + sovSpec(uint64(l)) + } + } + if len(m.Roles) > 0 { + for _, s := range m.Roles { + l = len(s) + n += 1 + l + sovSpec(uint64(l)) + } + } + return n +} + +func sovSpec(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n +} +func sozSpec(x uint64) (n int) { + return sovSpec(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *TemplateAccount) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowSpec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: TemplateAccount: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: TemplateAccount: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowSpec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthSpec + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowSpec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthSpec + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + var v github_com_hyperledger_burrow_crypto.Address + m.Address = &v + if err := m.Address.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NodeAddress", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowSpec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthSpec + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + var v github_com_hyperledger_burrow_crypto.Address + m.NodeAddress = &v + if err := m.NodeAddress.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PublicKey", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowSpec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthSpec + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.PublicKey == nil { + m.PublicKey = &crypto.PublicKey{} + } + if err := m.PublicKey.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) + } + var v uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowSpec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + m.Amount = &v + case 6: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Power", wireType) + } + var v uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowSpec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + m.Power = &v + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Permissions", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowSpec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthSpec + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Permissions = append(m.Permissions, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Roles", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowSpec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthSpec + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Roles = append(m.Roles, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipSpec(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthSpec + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipSpec(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowSpec + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowSpec + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowSpec + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + iNdEx += length + if length < 0 { + return 0, ErrInvalidLengthSpec + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowSpec + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipSpec(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} + +var ( + ErrInvalidLengthSpec = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowSpec = fmt.Errorf("proto: integer overflow") +) + +func init() { proto.RegisterFile("spec.proto", fileDescriptorSpec) } +func init() { golang_proto.RegisterFile("spec.proto", fileDescriptorSpec) } + +var fileDescriptorSpec = []byte{ + // 359 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x92, 0x3f, 0x6f, 0xe2, 0x30, + 0x18, 0x87, 0xf1, 0x11, 0xe0, 0x30, 0x48, 0x27, 0x3c, 0x59, 0x0c, 0x49, 0xc4, 0x2d, 0xd1, 0x89, + 0x23, 0xd2, 0x6d, 0x47, 0x97, 0x12, 0xa9, 0x53, 0x25, 0x84, 0x28, 0x53, 0x37, 0x92, 0xbc, 0x0d, + 0x91, 0x62, 0x1c, 0xd9, 0x8e, 0x50, 0x3e, 0x4e, 0xbf, 0x49, 0x47, 0x46, 0xe6, 0x0e, 0x51, 0x05, + 0x43, 0xa5, 0x8e, 0xfd, 0x04, 0x55, 0x42, 0x28, 0x4c, 0x55, 0x96, 0x6e, 0xef, 0x1f, 0x3d, 0xbf, + 0xc7, 0xb2, 0x8d, 0xb1, 0x8c, 0xc1, 0x1b, 0xc5, 0x82, 0x2b, 0x4e, 0xb4, 0xbc, 0xee, 0xff, 0x0d, + 0x42, 0xb5, 0x4a, 0xdc, 0x91, 0xc7, 0x99, 0x1d, 0xf0, 0x80, 0xdb, 0xc5, 0xd2, 0x4d, 0x1e, 0x8a, + 0xae, 0x68, 0x8a, 0xea, 0x08, 0xf5, 0xbb, 0x9e, 0x48, 0x63, 0x55, 0x76, 0x83, 0x57, 0x0d, 0xff, + 0x5a, 0x00, 0x8b, 0xa3, 0xa5, 0x82, 0x89, 0xe7, 0xf1, 0x64, 0xad, 0x08, 0xc5, 0xda, 0x74, 0xc9, + 0x80, 0x22, 0x13, 0x59, 0x6d, 0x47, 0xdb, 0x66, 0x46, 0x6d, 0x5e, 0x4c, 0x08, 0xc3, 0xad, 0x89, + 0xef, 0x0b, 0x90, 0x92, 0xfe, 0x30, 0x91, 0xd5, 0x75, 0xee, 0x9e, 0x33, 0x63, 0x78, 0xe1, 0x5f, + 0xa5, 0x31, 0x88, 0x08, 0xfc, 0x00, 0x84, 0xed, 0x26, 0x42, 0xf0, 0x8d, 0x5d, 0xea, 0x4a, 0xee, + 0x2d, 0x33, 0xf0, 0x90, 0xb3, 0x50, 0x01, 0x8b, 0x55, 0xfa, 0x9e, 0x19, 0x3d, 0xc5, 0x59, 0x34, + 0x1e, 0x9c, 0x67, 0x83, 0xf9, 0xc9, 0x41, 0x12, 0xdc, 0x99, 0x72, 0x1f, 0x4e, 0xca, 0xfa, 0xf7, + 0x29, 0x2f, 0x3d, 0x64, 0x81, 0xdb, 0xb3, 0xc4, 0x8d, 0x42, 0xef, 0x16, 0x52, 0xaa, 0x99, 0xc8, + 0xea, 0xfc, 0xeb, 0x8d, 0xca, 0xcc, 0xcf, 0x85, 0xf3, 0xbb, 0x4a, 0xee, 0x39, 0x88, 0x5c, 0xe1, + 0xe6, 0x84, 0xe5, 0xf7, 0x4b, 0x1b, 0x26, 0xb2, 0xb4, 0x6a, 0x7c, 0x89, 0x90, 0xff, 0xb8, 0x31, + 0xe3, 0x1b, 0x10, 0xb4, 0x59, 0x9d, 0x3d, 0x12, 0xe4, 0x06, 0x77, 0x66, 0x20, 0x58, 0x28, 0x65, + 0xc8, 0xd7, 0x92, 0xb6, 0xcc, 0xba, 0xd5, 0xae, 0x16, 0x70, 0xc9, 0xe5, 0x27, 0x98, 0xf3, 0x08, + 0x24, 0xfd, 0x59, 0x3d, 0xe0, 0x48, 0x8c, 0xb5, 0xdd, 0xa3, 0x51, 0x73, 0xae, 0xb7, 0x7b, 0x1d, + 0xed, 0xf6, 0x3a, 0x7a, 0xd9, 0xeb, 0xe8, 0xe9, 0xa0, 0xa3, 0xed, 0x41, 0x47, 0xf7, 0x7f, 0xbe, + 0x7e, 0xc9, 0x00, 0xd6, 0x20, 0x43, 0x69, 0xe7, 0x1f, 0xfd, 0x23, 0x00, 0x00, 0xff, 0xff, 0x4b, + 0xcc, 0xe3, 0x66, 0xfb, 0x02, 0x00, 0x00, +} diff --git a/genesis/spec/template_account.go b/genesis/spec/template_account.go index 9d3c2acc4..1362ec117 100644 --- a/genesis/spec/template_account.go +++ b/genesis/spec/template_account.go @@ -7,22 +7,8 @@ import ( "github.com/hyperledger/burrow/genesis" "github.com/hyperledger/burrow/keys" "github.com/hyperledger/burrow/permission" - ptypes "github.com/hyperledger/burrow/permission/types" ) -type TemplateAccount struct { - // Template accounts sharing a name will be merged when merging genesis specs - Name string `json:",omitempty" toml:",omitempty"` - // Address is convenient to have in file for reference, but otherwise ignored since derived from PublicKey - Address *crypto.Address `json:",omitempty" toml:",omitempty"` - NodeAddress *crypto.Address `json:",omitempty" toml:",omitempty"` - PublicKey *crypto.PublicKey `json:",omitempty" toml:",omitempty"` - Amount *uint64 `json:",omitempty" toml:",omitempty"` - Power *uint64 `json:",omitempty" toml:",omitempty"` - Permissions []string `json:",omitempty" toml:",omitempty"` - Roles []string `json:",omitempty" toml:",omitempty"` -} - func (ta TemplateAccount) Validator(keyClient keys.KeyClient, index int, generateNodeKeys bool) (*genesis.Validator, error) { var err error gv := new(genesis.Validator) @@ -58,12 +44,12 @@ func (ta TemplateAccount) Validator(keyClient keys.KeyClient, index int, generat return gv, nil } -func (ta TemplateAccount) AccountPermissions() (ptypes.AccountPermissions, error) { +func (ta TemplateAccount) AccountPermissions() (permission.AccountPermissions, error) { basePerms, err := permission.BasePermissionsFromStringList(ta.Permissions) if err != nil { return permission.ZeroAccountPermissions, nil } - return ptypes.AccountPermissions{ + return permission.AccountPermissions{ Base: basePerms, Roles: ta.Roles, }, nil diff --git a/core/kernel_test.go b/integration/core/kernel_test.go similarity index 61% rename from core/kernel_test.go rename to integration/core/kernel_test.go index be0c51068..d4003e212 100644 --- a/core/kernel_test.go +++ b/integration/core/kernel_test.go @@ -1,3 +1,5 @@ +// +build integration + package core import ( @@ -7,12 +9,15 @@ import ( "testing" "time" - "github.com/hyperledger/burrow/consensus/tendermint" + "github.com/hyperledger/burrow/config" "github.com/hyperledger/burrow/consensus/tendermint/validator" + "github.com/hyperledger/burrow/core" + "github.com/hyperledger/burrow/event" + "github.com/hyperledger/burrow/execution/exec" "github.com/hyperledger/burrow/genesis" + "github.com/hyperledger/burrow/integration" "github.com/hyperledger/burrow/keys" "github.com/hyperledger/burrow/logging" - "github.com/hyperledger/burrow/rpc" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" tmConfig "github.com/tendermint/tendermint/config" @@ -30,7 +35,7 @@ func TestBootThenShutdown(t *testing.T) { logger := logging.NewNoopLogger() genesisDoc, _, privateValidators := genesis.NewDeterministicGenesis(123).GenesisDoc(1, true, 1000, 1, true, 1000) privValidator := validator.NewPrivValidatorMemory(privateValidators[0], privateValidators[0]) - assert.NoError(t, bootWaitBlocksShutdown(privValidator, genesisDoc, tmConf, logger, nil)) + assert.NoError(t, bootWaitBlocksShutdown(privValidator, integration.NewTestConfig(genesisDoc), tmConf, logger, nil)) } func TestBootShutdownResume(t *testing.T) { @@ -43,31 +48,36 @@ func TestBootShutdownResume(t *testing.T) { genesisDoc, _, privateValidators := genesis.NewDeterministicGenesis(123).GenesisDoc(1, true, 1000, 1, true, 1000) privValidator := validator.NewPrivValidatorMemory(privateValidators[0], privateValidators[0]) - i := int64(0) + i := uint64(0) // asserts we get a consecutive run of blocks - blockChecker := func(block *tmTypes.EventDataNewBlock) bool { - assert.Equal(t, i+1, block.Block.Height) + blockChecker := func(block *exec.BlockExecution) bool { + assert.Equal(t, i+1, block.Height) i++ // stop every third block return i%3 != 0 } + testConfig := integration.NewTestConfig(genesisDoc) // First run - require.NoError(t, bootWaitBlocksShutdown(privValidator, genesisDoc, tmConf, logger, blockChecker)) + require.NoError(t, bootWaitBlocksShutdown(privValidator, testConfig, tmConf, logger, blockChecker)) // Resume and check we pick up where we left off - require.NoError(t, bootWaitBlocksShutdown(privValidator, genesisDoc, tmConf, logger, blockChecker)) + require.NoError(t, bootWaitBlocksShutdown(privValidator, testConfig, tmConf, logger, blockChecker)) // Resuming with mismatched genesis should fail genesisDoc.Salt = []byte("foo") - assert.Error(t, bootWaitBlocksShutdown(privValidator, genesisDoc, tmConf, logger, blockChecker)) + assert.Error(t, bootWaitBlocksShutdown(privValidator, testConfig, tmConf, logger, blockChecker)) } -func bootWaitBlocksShutdown(privValidator tmTypes.PrivValidator, genesisDoc *genesis.GenesisDoc, +func bootWaitBlocksShutdown(privValidator tmTypes.PrivValidator, testConfig *config.BurrowConfig, tmConf *tmConfig.Config, logger *logging.Logger, - blockChecker func(block *tmTypes.EventDataNewBlock) (cont bool)) error { + blockChecker func(block *exec.BlockExecution) (cont bool)) error { keyStore := keys.NewKeyStore(keys.DefaultKeysDir, false, logger) keyClient := keys.NewLocalKeyClient(keyStore, logging.NewNoopLogger()) - kern, err := NewKernel(context.Background(), keyClient, privValidator, genesisDoc, tmConf, - rpc.DefaultRPCConfig(), keys.DefaultKeysConfig(), keyStore, nil, logger) + kern, err := core.NewKernel(context.Background(), keyClient, privValidator, + testConfig.GenesisDoc, + testConfig.Tendermint.TendermintConfig(), + testConfig.RPC, + testConfig.Keys, + keyStore, nil, logger) if err != nil { return err } @@ -77,10 +87,12 @@ func bootWaitBlocksShutdown(privValidator tmTypes.PrivValidator, genesisDoc *gen return err } - ch, err := tendermint.SubscribeNewBlock(context.Background(), kern.Emitter) + subID := event.GenSubID() + ch, err := kern.Emitter.Subscribe(context.Background(), subID, exec.QueryForBlockExecution(), 10) if err != nil { return err } + defer kern.Emitter.UnsubscribeAll(context.Background(), subID) cont := true for cont { select { @@ -88,11 +100,11 @@ func bootWaitBlocksShutdown(privValidator tmTypes.PrivValidator, genesisDoc *gen if err != nil { return fmt.Errorf("timed out waiting for block") } - case ednb := <-ch: + case msg := <-ch: if blockChecker == nil { cont = false } else { - cont = blockChecker(ednb) + cont = blockChecker(msg.(*exec.BlockExecution)) } } } diff --git a/rpc/tm/integration/main_test.go b/integration/core/main_test.go similarity index 75% rename from rpc/tm/integration/main_test.go rename to integration/core/main_test.go index 9833d45c9..af90e852e 100644 --- a/rpc/tm/integration/main_test.go +++ b/integration/core/main_test.go @@ -15,23 +15,19 @@ // See the License for the specific language governing permissions and // limitations under the License. -package integration +package core import ( "os" "testing" - "time" - "github.com/hyperledger/burrow/core" - "github.com/hyperledger/burrow/core/integration" + "github.com/hyperledger/burrow/integration" ) +var _ = integration.ClaimPorts() + // Needs to be in a _test.go file to be picked up func TestMain(m *testing.M) { - returnValue := integration.TestWrapper(privateAccounts, genesisDoc, func(*core.Kernel) int { - return m.Run() - }) - - time.Sleep(3 * time.Second) + returnValue := m.Run() os.Exit(returnValue) } diff --git a/core/integration/test_wrapper.go b/integration/integration.go similarity index 53% rename from core/integration/test_wrapper.go rename to integration/integration.go index 79b5db460..388cae7d6 100644 --- a/core/integration/test_wrapper.go +++ b/integration/integration.go @@ -1,6 +1,3 @@ -// +build integration - -// Space above here matters // Copyright 2017 Monax Industries Limited // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -19,24 +16,26 @@ package integration import ( "context" + "encoding/binary" "fmt" "os" + "runtime" "strconv" + "sync/atomic" "time" - acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/config" "github.com/hyperledger/burrow/consensus/tendermint/validator" "github.com/hyperledger/burrow/core" + "github.com/hyperledger/burrow/execution/evm/sha3" "github.com/hyperledger/burrow/genesis" - "github.com/hyperledger/burrow/keys" "github.com/hyperledger/burrow/keys/mock" "github.com/hyperledger/burrow/logging" - "github.com/hyperledger/burrow/logging/config" + lConfig "github.com/hyperledger/burrow/logging/config" "github.com/hyperledger/burrow/logging/lifecycle" "github.com/hyperledger/burrow/logging/structure" "github.com/hyperledger/burrow/permission" - "github.com/hyperledger/burrow/rpc" - tm_config "github.com/tendermint/tendermint/config" ) const ( @@ -48,31 +47,42 @@ const ( //var debugLogging = true var debugLogging = false +// Starting point for assigning range of ports for tests +// Start at unprivileged port (hoping for the best) +const startingPort uint16 = 1024 + +// For each port claimant assign a bucket +const startingPortSeparation uint16 = 10 +const startingPortBuckets = 1000 + +// Mutable port to assign to next claimant +var port = uint32(startingPort) + // We use this to wrap tests -func TestWrapper(privateAccounts []acm.PrivateAccount, genesisDoc *genesis.GenesisDoc, runner func(*core.Kernel) int) int { - fmt.Println("Running with integration TestWrapper (core/integration/test_wrapper.go)...") +func TestWrapper(privateAccounts []*acm.PrivateAccount, testConfig *config.BurrowConfig, runner func(*core.Kernel) int) int { + fmt.Println("Running with integration TestWrapper (core/integration/integration.go)...") os.RemoveAll(testDir) os.MkdirAll(testDir, 0777) os.Chdir(testDir) - tmConf := tm_config.DefaultConfig() os.MkdirAll("config", 0777) + logger := logging.NewNoopLogger() if debugLogging { var err error // Change config as needed - logger, err = lifecycle.NewLoggerFromLoggingConfig(&config.LoggingConfig{ + logger, err = lifecycle.NewLoggerFromLoggingConfig(&lConfig.LoggingConfig{ ExcludeTrace: false, - RootSink: config.Sink(). - SetTransform(config.FilterTransform(config.IncludeWhenAnyMatches, + RootSink: lConfig.Sink(). + SetTransform(lConfig.FilterTransform(lConfig.IncludeWhenAnyMatches, structure.ComponentKey, "Tendermint", structure.ScopeKey, "executor.Execute\\(tx txs.Tx\\)", )). //AddSinks(config.Sink().SetTransform(config.FilterTransform(config.ExcludeWhenAnyMatches, "run_call", "false")). - AddSinks(config.Sink().SetTransform(config.PruneTransform("log_channel", "trace", "scope", "returns", "run_id", "args")). - AddSinks(config.Sink().SetTransform(config.SortTransform("tx_hash", "time", "message", "method")). - SetOutput(config.StdoutOutput()))), + AddSinks(lConfig.Sink().SetTransform(lConfig.PruneTransform("log_channel", "trace", "scope", "returns", "run_id", "args")). + AddSinks(lConfig.Sink().SetTransform(lConfig.SortTransform("tx_hash", "time", "message", "method")). + SetOutput(lConfig.StdoutOutput()))), }) if err != nil { panic(err) @@ -82,14 +92,18 @@ func TestWrapper(privateAccounts []acm.PrivateAccount, genesisDoc *genesis.Genes validatorAccount := privateAccounts[0] privValidator := validator.NewPrivValidatorMemory(validatorAccount, validatorAccount) keyClient := mock.NewKeyClient(privateAccounts...) - kernel, err := core.NewKernel(context.Background(), keyClient, privValidator, genesisDoc, tmConf, rpc.DefaultRPCConfig(), keys.DefaultKeysConfig(), + kernel, err := core.NewKernel(context.Background(), keyClient, privValidator, + testConfig.GenesisDoc, + testConfig.Tendermint.TendermintConfig(), + testConfig.RPC, + testConfig.Keys, nil, nil, logger) if err != nil { panic(err) } // Sometimes better to not shutdown as logging errors on shutdown may obscure real issue defer func() { - //kernel.Shutdown(context.Background()) + kernel.Shutdown(context.Background()) }() err = kernel.Boot() @@ -100,7 +114,7 @@ func TestWrapper(privateAccounts []acm.PrivateAccount, genesisDoc *genesis.Genes return runner(kernel) } -func TestGenesisDoc(addressables []acm.PrivateAccount) *genesis.GenesisDoc { +func TestGenesisDoc(addressables []*acm.PrivateAccount) *genesis.GenesisDoc { accounts := make(map[string]acm.Account, len(addressables)) for i, pa := range addressables { account := acm.FromAddressable(pa) @@ -119,10 +133,48 @@ func TestGenesisDoc(addressables []acm.PrivateAccount) *genesis.GenesisDoc { } // Deterministic account generation helper. Pass number of accounts to make -func MakePrivateAccounts(n int) []acm.PrivateAccount { - accounts := make([]acm.PrivateAccount, n) +func MakePrivateAccounts(n int) []*acm.PrivateAccount { + accounts := make([]*acm.PrivateAccount, n) for i := 0; i < n; i++ { accounts[i] = acm.GeneratePrivateAccountFromSecret("mysecret" + strconv.Itoa(i)) } return accounts } + +// Some helpers for setting Burrow's various ports in non-colliding ranges for tests +func ClaimPorts() uint16 { + _, file, _, _ := runtime.Caller(1) + startIndex := uint16(binary.LittleEndian.Uint16(sha3.Sha3([]byte(file)))) % startingPortBuckets + newPort := startingPort + startIndex*startingPortSeparation + // In case overflow + if newPort < startingPort { + newPort += startingPort + } + if !atomic.CompareAndSwapUint32(&port, uint32(startingPort), uint32(newPort)) { + panic("GetPort() called before ClaimPorts() or ClaimPorts() called twice") + } + return uint16(atomic.LoadUint32(&port)) +} + +func GetPort() uint16 { + return uint16(atomic.AddUint32(&port, 1)) +} + +func GetLocalAddress() string { + return fmt.Sprintf("localhost:%v", GetPort()) +} + +func GetTCPLocalAddress() string { + return fmt.Sprintf("tcp://localhost:%v", GetPort()) +} + +func NewTestConfig(genesisDoc *genesis.GenesisDoc) *config.BurrowConfig { + cnf := config.DefaultBurrowConfig() + cnf.GenesisDoc = genesisDoc + cnf.Tendermint.ListenAddress = GetTCPLocalAddress() + cnf.RPC.GRPC.ListenAddress = GetLocalAddress() + cnf.RPC.Metrics.ListenAddress = GetTCPLocalAddress() + cnf.RPC.TM.ListenAddress = GetTCPLocalAddress() + cnf.Keys.RemoteAddress = "" + return cnf +} diff --git a/integration/rpcevents/execution_events_server_test.go b/integration/rpcevents/execution_events_server_test.go new file mode 100644 index 000000000..19c96d3bb --- /dev/null +++ b/integration/rpcevents/execution_events_server_test.go @@ -0,0 +1,192 @@ +// +build integration + +// Space above here matters +// Copyright 2017 Monax Industries Limited +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package rpcevents + +import ( + "context" + "io" + "testing" + + "time" + + "strconv" + + "github.com/hyperledger/burrow/event" + "github.com/hyperledger/burrow/event/query" + "github.com/hyperledger/burrow/execution/exec" + "github.com/hyperledger/burrow/integration/rpctest" + "github.com/hyperledger/burrow/rpc/rpcevents" + "github.com/hyperledger/burrow/rpc/rpctransact" + "github.com/hyperledger/burrow/txs/payload" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestGetBlocks(t *testing.T) { + request := &rpcevents.BlocksRequest{ + BlockRange: rpcevents.NewBlockRange(rpcevents.LatestBound(), rpcevents.StreamBound()), + } + tcli := rpctest.NewTransactClient(t, testConfig.RPC.GRPC.ListenAddress) + ecli := rpctest.NewExecutionEventsClient(t, testConfig.RPC.GRPC.ListenAddress) + stream, err := ecli.GetBlocks(context.Background(), request) + require.NoError(t, err) + pulls := 3 + sendsPerPull := 4 + var blocks []*exec.BlockExecution + for i := 0; i < pulls; i++ { + doSends(t, sendsPerPull, tcli) + block, err := stream.Recv() + require.NoError(t, err) + blocks = append(blocks, block) + } + assert.True(t, len(blocks) > 0, "should see at least one block (height 2)") + var height uint64 + for _, b := range blocks { + if height > 0 { + assert.Equal(t, height+1, b.Height) + } + height = b.Height + } + require.NoError(t, stream.CloseSend()) +} +func TestGetBlocksContains2(t *testing.T) { + request := &rpcevents.BlocksRequest{ + BlockRange: rpcevents.NewBlockRange(rpcevents.LatestBound(), rpcevents.StreamBound()), + Query: "Height CONTAINS '2'", + } + tcli := rpctest.NewTransactClient(t, testConfig.RPC.GRPC.ListenAddress) + ecli := rpctest.NewExecutionEventsClient(t, testConfig.RPC.GRPC.ListenAddress) + stream, err := ecli.GetBlocks(context.Background(), request) + require.NoError(t, err) + pulls := 2 + sendsPerPull := 4 + var blocks []*exec.BlockExecution + for i := 0; i < pulls; i++ { + doSends(t, sendsPerPull, tcli) + block, err := stream.Recv() + require.NoError(t, err) + blocks = append(blocks, block) + assert.Contains(t, strconv.FormatUint(block.Height, 10), "2") + } + assert.True(t, len(blocks) > 0, "should see at least one block (height 2)") + require.NoError(t, stream.CloseSend()) +} + +func TestGetEventsSend(t *testing.T) { + request := &rpcevents.BlocksRequest{ + BlockRange: rpcevents.NewBlockRange(rpcevents.AbsoluteBound(kern.Blockchain.LastBlockHeight()), + rpcevents.LatestBound()), + } + numSends := 1100 + responses := testGetEventsSend(t, numSends, request) + assert.Equal(t, numSends*2, countEventsAndCheckConsecutive(t, responses), + "should receive 1 input, 1 output per send") +} + +func TestGetEventsSendContainsAA(t *testing.T) { + request := &rpcevents.BlocksRequest{ + BlockRange: rpcevents.NewBlockRange(rpcevents.AbsoluteBound(kern.Blockchain.LastBlockHeight()), + rpcevents.LatestBound()), + Query: "TxHash CONTAINS 'AA'", + } + numSends := 1100 + responses := testGetEventsSend(t, numSends, request) + for _, response := range responses { + for _, ev := range response.Events { + require.Contains(t, ev.Header.TxHash.String(), "AA") + } + } +} + +func TestGetEventsSendFiltered(t *testing.T) { + request := &rpcevents.BlocksRequest{ + BlockRange: rpcevents.NewBlockRange(rpcevents.AbsoluteBound(kern.Blockchain.LastBlockHeight()), + rpcevents.LatestBound()), + Query: query.NewBuilder().AndEquals(event.EventTypeKey, exec.TypeAccountInput.String()).String(), + } + numSends := 500 + responses := testGetEventsSend(t, numSends, request) + assert.Equal(t, numSends, countEventsAndCheckConsecutive(t, responses), "should receive a single input event per send") +} + +func testGetEventsSend(t *testing.T, numSends int, request *rpcevents.BlocksRequest) []*rpcevents.GetEventsResponse { + + doSends(t, numSends, rpctest.NewTransactClient(t, testConfig.RPC.GRPC.ListenAddress)) + ecli := rpctest.NewExecutionEventsClient(t, testConfig.RPC.GRPC.ListenAddress) + evs, err := ecli.GetEvents(context.Background(), request) + require.NoError(t, err) + var responses []*rpcevents.GetEventsResponse + for { + resp, err := evs.Recv() + if err != nil { + if err == io.EOF { + break + } + require.NoError(t, err) + } + responses = append(responses, resp) + } + return responses +} + +func doSends(t *testing.T, numSends int, cli rpctransact.TransactClient) { + countCh := rpctest.CommittedTxCount(t, kern.Emitter) + amt := uint64(2004) + for i := 0; i < numSends; i++ { + // Slow us down a bit to ensure spread across blocks + time.Sleep(time.Millisecond) + receipt, err := cli.SendTxAsync(context.Background(), + &payload.SendTx{ + Inputs: []*payload.TxInput{{ + Address: inputAddress, + Amount: amt, + }}, + Outputs: []*payload.TxOutput{{ + Address: rpctest.PrivateAccounts[4].Address(), + Amount: amt, + }}, + }) + require.NoError(t, err) + assert.False(t, receipt.CreatesContract) + } + require.Equal(t, numSends, <-countCh) +} + +func countEventsAndCheckConsecutive(t *testing.T, respones []*rpcevents.GetEventsResponse) int { + i := 0 + var height uint64 + var index uint64 + txHash := "" + for _, resp := range respones { + require.True(t, resp.Height > height, "must not receive multiple GetEventsResponses for the same block") + height := resp.Height + for _, ev := range resp.Events { + require.Equal(t, ev.Header.Height, height, "height of event headers much match height of GetEventsResponse") + if txHash != ev.Header.TxHash.String() { + txHash = ev.Header.TxHash.String() + index = 0 + } + if ev.Header.Index > index { + require.Equal(t, index+1, ev.Header.Index) + index++ + } + i++ + } + } + return i +} diff --git a/rpc/rpcevents/integration/main_test.go b/integration/rpcevents/main_test.go similarity index 62% rename from rpc/rpcevents/integration/main_test.go rename to integration/rpcevents/main_test.go index 338b53345..8418fbd74 100644 --- a/rpc/rpcevents/integration/main_test.go +++ b/integration/rpcevents/main_test.go @@ -15,30 +15,29 @@ // See the License for the specific language governing permissions and // limitations under the License. -package integration +package rpcevents import ( "os" "testing" - "time" "github.com/hyperledger/burrow/core" - "github.com/hyperledger/burrow/core/integration" - "github.com/hyperledger/burrow/execution/pbtransactor" + "github.com/hyperledger/burrow/integration" + "github.com/hyperledger/burrow/integration/rpctest" ) -var privateAccounts = integration.MakePrivateAccounts(5) // make keys -var genesisDoc = integration.TestGenesisDoc(privateAccounts) -var inputAccount = &pbtransactor.InputAccount{Address: privateAccounts[0].Address().Bytes()} +var _ = integration.ClaimPorts() +var inputAddress = rpctest.PrivateAccounts[0].Address() +var testConfig = integration.NewTestConfig(rpctest.GenesisDoc) var kern *core.Kernel // Needs to be in a _test.go file to be picked up func TestMain(m *testing.M) { - returnValue := integration.TestWrapper(privateAccounts, genesisDoc, func(k *core.Kernel) int { - kern = k - return m.Run() - }) + returnValue := integration.TestWrapper(rpctest.PrivateAccounts, testConfig, + func(k *core.Kernel) int { + kern = k + return m.Run() + }) - time.Sleep(3 * time.Second) os.Exit(returnValue) } diff --git a/rpc/rpctransactor/integration/main_test.go b/integration/rpcquery/main_test.go similarity index 69% rename from rpc/rpctransactor/integration/main_test.go rename to integration/rpcquery/main_test.go index a83a08b51..423a22bd5 100644 --- a/rpc/rpctransactor/integration/main_test.go +++ b/integration/rpcquery/main_test.go @@ -15,28 +15,28 @@ // See the License for the specific language governing permissions and // limitations under the License. -package integration +package rpcquery import ( "os" "testing" - "time" "github.com/hyperledger/burrow/core" - "github.com/hyperledger/burrow/core/integration" + "github.com/hyperledger/burrow/integration" + "github.com/hyperledger/burrow/integration/rpctest" ) -var privateAccounts = integration.MakePrivateAccounts(5) // make keys -var genesisDoc = integration.TestGenesisDoc(privateAccounts) +var _ = integration.ClaimPorts() +var testConfig = integration.NewTestConfig(rpctest.GenesisDoc) var kern *core.Kernel // Needs to be in a _test.go file to be picked up func TestMain(m *testing.M) { - returnValue := integration.TestWrapper(privateAccounts, genesisDoc, func(k *core.Kernel) int { - kern = k - return m.Run() - }) + returnValue := integration.TestWrapper(rpctest.PrivateAccounts, testConfig, + func(k *core.Kernel) int { + kern = k + return m.Run() + }) - time.Sleep(3 * time.Second) os.Exit(returnValue) } diff --git a/integration/rpcquery/query_server_test.go b/integration/rpcquery/query_server_test.go new file mode 100644 index 000000000..05bb7e858 --- /dev/null +++ b/integration/rpcquery/query_server_test.go @@ -0,0 +1,87 @@ +// +build integration + +package rpcquery + +import ( + "context" + "fmt" + "io" + "testing" + + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/event/query" + "github.com/hyperledger/burrow/execution/names" + "github.com/hyperledger/burrow/genesis" + "github.com/hyperledger/burrow/integration/rpctest" + "github.com/hyperledger/burrow/rpc/rpcquery" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestGetAccount(t *testing.T) { + cli := rpctest.NewQueryClient(t, testConfig.RPC.GRPC.ListenAddress) + ca, err := cli.GetAccount(context.Background(), &rpcquery.GetAccountParam{ + Address: rpctest.PrivateAccounts[2].Address(), + }) + require.NoError(t, err) + genAcc := rpctest.GenesisDoc.Accounts[2] + genAccOut := genesis.GenesisAccountFromAccount(rpctest.GenesisDoc.Accounts[2].Name, ca.Account()) + // Normalise + genAcc.Permissions.Roles = nil + genAccOut.Permissions.Roles = nil + assert.Equal(t, genAcc, genAccOut) +} + +func TestListAccounts(t *testing.T) { + cli := rpctest.NewQueryClient(t, testConfig.RPC.GRPC.ListenAddress) + stream, err := cli.ListAccounts(context.Background(), &rpcquery.ListAccountsParam{}) + require.NoError(t, err) + var accs []acm.Account + acc, err := stream.Recv() + for err == nil { + accs = append(accs, acc.Account()) + acc, err = stream.Recv() + } + if err != nil && err != io.EOF { + t.Fatalf("unexpected error: %v", err) + } + assert.Len(t, accs, len(rpctest.GenesisDoc.Accounts)+1) +} + +func TestListNames(t *testing.T) { + tcli := rpctest.NewTransactClient(t, testConfig.RPC.GRPC.ListenAddress) + dataA, dataB := "NO TAMBOURINES", "ELEPHANTS WELCOME" + n := 8 + for i := 0; i < n; i++ { + name := fmt.Sprintf("Flub/%v", i) + if i%2 == 0 { + rpctest.UpdateName(t, tcli, rpctest.PrivateAccounts[0].Address(), name, dataA, 200) + } else { + rpctest.UpdateName(t, tcli, rpctest.PrivateAccounts[1].Address(), name, dataB, 200) + } + } + qcli := rpctest.NewQueryClient(t, testConfig.RPC.GRPC.ListenAddress) + entries := receiveNames(t, qcli, "") + assert.Len(t, entries, n) + entries = receiveNames(t, qcli, query.NewBuilder().AndEquals("Data", dataA).String()) + if assert.Len(t, entries, n/2) { + assert.Equal(t, dataA, entries[0].Data) + } +} + +func receiveNames(t testing.TB, qcli rpcquery.QueryClient, query string) []*names.Entry { + stream, err := qcli.ListNames(context.Background(), &rpcquery.ListNamesParam{ + Query: query, + }) + require.NoError(t, err) + var entries []*names.Entry + entry, err := stream.Recv() + for err == nil { + entries = append(entries, entry) + entry, err = stream.Recv() + } + if err != nil && err != io.EOF { + t.Fatalf("unexpected error: %v", err) + } + return entries +} diff --git a/integration/rpctest/helpers.go b/integration/rpctest/helpers.go new file mode 100644 index 000000000..9fb660f0d --- /dev/null +++ b/integration/rpctest/helpers.go @@ -0,0 +1,188 @@ +package rpctest + +import ( + "context" + "fmt" + "testing" + + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/crypto" + "github.com/hyperledger/burrow/event" + "github.com/hyperledger/burrow/execution/evm/abi" + "github.com/hyperledger/burrow/execution/exec" + "github.com/hyperledger/burrow/execution/names" + "github.com/hyperledger/burrow/integration" + "github.com/hyperledger/burrow/rpc" + "github.com/hyperledger/burrow/rpc/rpcevents" + "github.com/hyperledger/burrow/rpc/rpcquery" + "github.com/hyperledger/burrow/rpc/rpctransact" + "github.com/hyperledger/burrow/rpc/tm/tmclient" + "github.com/hyperledger/burrow/txs" + "github.com/hyperledger/burrow/txs/payload" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" +) + +// Recursive call count for UpsieDownsie() function call from strange_loop.sol +// Equals initial call, then depth from 17 -> 34, one for the bounce, then depth from 34 -> 23, +// so... (I didn't say it had to make sense): +const UpsieDownsieCallCount = 1 + (34 - 17) + 1 + (34 - 23) + +var i = UpsieDownsieCallCount + +var PrivateAccounts = integration.MakePrivateAccounts(10) // make keys +var GenesisDoc = integration.TestGenesisDoc(PrivateAccounts) + +// Helpers +func NewTransactClient(t testing.TB, listenAddress string) rpctransact.TransactClient { + conn, err := grpc.Dial(listenAddress, grpc.WithInsecure()) + require.NoError(t, err) + return rpctransact.NewTransactClient(conn) +} + +func NewExecutionEventsClient(t testing.TB, listenAddress string) rpcevents.ExecutionEventsClient { + conn, err := grpc.Dial(listenAddress, grpc.WithInsecure()) + require.NoError(t, err) + return rpcevents.NewExecutionEventsClient(conn) +} + +func NewQueryClient(t testing.TB, listenAddress string) rpcquery.QueryClient { + conn, err := grpc.Dial(listenAddress, grpc.WithInsecure()) + require.NoError(t, err) + return rpcquery.NewQueryClient(conn) +} + +func CommittedTxCount(t *testing.T, em event.Emitter) chan int { + var numTxs int32 + emptyBlocks := 0 + maxEmptyBlocks := 2 + outCh := make(chan int) + subID := event.GenSubID() + ch, err := em.Subscribe(context.Background(), subID, exec.QueryForBlockExecution(), 1) + require.NoError(t, err) + + go func() { + defer em.UnsubscribeAll(context.Background(), subID) + for msg := range ch { + be := msg.(*exec.BlockExecution) + if be.BlockHeader.NumTxs == 0 { + emptyBlocks++ + } else { + emptyBlocks = 0 + } + if emptyBlocks > maxEmptyBlocks { + break + } + numTxs += be.BlockHeader.NumTxs + fmt.Printf("Total TXs committed at block %v: %v (+%v)\n", be.Height, numTxs, be.BlockHeader.NumTxs) + } + outCh <- int(numTxs) + }() + return outCh +} + +func CreateContract(t testing.TB, cli rpctransact.TransactClient, inputAddress crypto.Address) *exec.TxExecution { + txe, err := cli.CallTxSync(context.Background(), &payload.CallTx{ + Input: &payload.TxInput{ + Address: inputAddress, + Amount: 2, + }, + Address: nil, + Data: Bytecode_strange_loop, + Fee: 2, + GasLimit: 10000, + }) + require.NoError(t, err) + return txe +} + +func CallContract(t testing.TB, cli rpctransact.TransactClient, inputAddress, + contractAddress crypto.Address) *exec.TxExecution { + + functionID := abi.FunctionID("UpsieDownsie()") + txe, err := cli.CallTxSync(context.Background(), &payload.CallTx{ + Input: &payload.TxInput{ + Address: inputAddress, + Amount: 2, + }, + Address: &contractAddress, + Data: functionID[:], + Fee: 2, + GasLimit: 10000, + }) + require.NoError(t, err) + return txe +} + +func UpdateName(t testing.TB, cli rpctransact.TransactClient, inputAddress crypto.Address, name, data string, + expiresIn uint64) *exec.TxExecution { + + txe, err := cli.NameTxSync(context.Background(), &payload.NameTx{ + Input: &payload.TxInput{ + Address: inputAddress, + Amount: names.NameCostForExpiryIn(name, data, expiresIn), + }, + Name: name, + Data: data, + }) + require.NoError(t, err) + return txe +} + +//------------------------------------------------------------------------------- +// some default transaction functions + +func MakeDefaultCallTx(t *testing.T, client tmclient.RPCClient, addr *crypto.Address, code []byte, amt, gasLim, + fee uint64) *txs.Envelope { + sequence := GetSequence(t, client, PrivateAccounts[0].Address()) + tx := payload.NewCallTxWithSequence(PrivateAccounts[0].PublicKey(), addr, code, amt, gasLim, fee, sequence+1) + txEnv := txs.Enclose(GenesisDoc.ChainID(), tx) + require.NoError(t, txEnv.Sign(PrivateAccounts[0])) + return txEnv +} + +//------------------------------------------------------------------------------- +// rpc call wrappers (fail on err) + +// get an account's sequence number +func GetSequence(t *testing.T, client tmclient.RPCClient, addr crypto.Address) uint64 { + acc, err := tmclient.GetAccount(client, addr) + if err != nil { + t.Fatal(err) + } + if acc == nil { + return 0 + } + return acc.Sequence() +} + +// get the account +func GetAccount(t *testing.T, client tmclient.RPCClient, addr crypto.Address) acm.Account { + ac, err := tmclient.GetAccount(client, addr) + if err != nil { + t.Fatal(err) + } + return ac +} + +// dump all storage for an account. currently unused +func DumpStorage(t *testing.T, client tmclient.RPCClient, addr crypto.Address) *rpc.ResultDumpStorage { + resp, err := tmclient.DumpStorage(client, addr) + if err != nil { + t.Fatal(err) + } + return resp +} + +func GetStorage(t *testing.T, client tmclient.RPCClient, addr crypto.Address, key []byte) []byte { + resp, err := tmclient.GetStorage(client, addr, key) + if err != nil { + t.Fatal(err) + } + return resp +} + +//-------------------------------------------------------------------------------- +// utility verification function + +// simple call contract calls another contract diff --git a/rpc/test/strange_loop.sol b/integration/rpctest/strange_loop.sol similarity index 100% rename from rpc/test/strange_loop.sol rename to integration/rpctest/strange_loop.sol diff --git a/rpc/test/strange_loop.sol.go b/integration/rpctest/strange_loop.sol.go similarity index 99% rename from rpc/test/strange_loop.sol.go rename to integration/rpctest/strange_loop.sol.go index 57a1f061f..d01c57b63 100644 --- a/rpc/test/strange_loop.sol.go +++ b/integration/rpctest/strange_loop.sol.go @@ -1,4 +1,4 @@ -package test +package rpctest import "github.com/tmthrgd/go-hex" diff --git a/integration/rpctransact/call_test.go b/integration/rpctransact/call_test.go new file mode 100644 index 000000000..fca4a232d --- /dev/null +++ b/integration/rpctransact/call_test.go @@ -0,0 +1,343 @@ +// +build integration + +package rpctransact + +import ( + "context" + "sync" + "testing" + + "strings" + + "fmt" + + "github.com/hyperledger/burrow/binary" + "github.com/hyperledger/burrow/crypto" + "github.com/hyperledger/burrow/execution/evm/asm" + "github.com/hyperledger/burrow/execution/evm/asm/bc" + "github.com/hyperledger/burrow/execution/exec" + "github.com/hyperledger/burrow/integration/rpctest" + "github.com/hyperledger/burrow/rpc/rpctransact" + "github.com/hyperledger/burrow/txs/payload" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCallTxNoCode(t *testing.T) { + cli := rpctest.NewTransactClient(t, testConfig.RPC.GRPC.ListenAddress) + + // Flip flops between sending private key and input address to test private key and address based signing + toAddress := rpctest.PrivateAccounts[2].Address() + + numCreates := 1000 + countCh := rpctest.CommittedTxCount(t, kern.Emitter) + for i := 0; i < numCreates; i++ { + receipt, err := cli.CallTxAsync(context.Background(), &payload.CallTx{ + Input: &payload.TxInput{ + Address: inputAddress, + Amount: 2, + }, + Address: &toAddress, + Data: []byte{}, + Fee: 2, + GasLimit: 10000 + uint64(i), + }) + require.NoError(t, err) + assert.False(t, receipt.CreatesContract) + assert.Equal(t, toAddress, receipt.ContractAddress) + } + require.Equal(t, numCreates, <-countCh) +} + +func TestCreateContract(t *testing.T) { + cli := rpctest.NewTransactClient(t, testConfig.RPC.GRPC.ListenAddress) + numGoroutines := 100 + numCreates := 50 + wg := new(sync.WaitGroup) + wg.Add(numGoroutines) + countCh := rpctest.CommittedTxCount(t, kern.Emitter) + for i := 0; i < numGoroutines; i++ { + go func() { + for j := 0; j < numCreates; j++ { + receipt, err := cli.CallTxAsync(context.Background(), &payload.CallTx{ + Input: &payload.TxInput{ + Address: inputAddress, + Amount: 2, + }, + Address: nil, + Data: rpctest.Bytecode_strange_loop, + Fee: 2, + GasLimit: 10000, + }) + if assert.NoError(t, err) { + assert.True(t, receipt.CreatesContract) + } + } + wg.Done() + }() + } + wg.Wait() + + require.Equal(t, numGoroutines*numCreates, <-countCh) +} + +func BenchmarkCreateContract(b *testing.B) { + cli := rpctest.NewTransactClient(b, testConfig.RPC.GRPC.ListenAddress) + for i := 0; i < b.N; i++ { + create, err := cli.CallTxAsync(context.Background(), &payload.CallTx{ + Input: &payload.TxInput{ + Address: inputAddress, + Amount: 2, + }, + Address: nil, + Data: rpctest.Bytecode_strange_loop, + Fee: 2, + GasLimit: 10000, + }) + require.NoError(b, err) + assert.True(b, create.CreatesContract) + } +} + +func TestCallTxSync(t *testing.T) { + cli := rpctest.NewTransactClient(t, testConfig.RPC.GRPC.ListenAddress) + numGoroutines := 3 + numRuns := 2 + countCh := rpctest.CommittedTxCount(t, kern.Emitter) + for i := 0; i < numGoroutines; i++ { + for j := 0; j < numRuns; j++ { + createTxe := rpctest.CreateContract(t, cli, inputAddress) + callTxe := rpctest.CallContract(t, cli, inputAddress, lastCall(createTxe.Events).CallData.Callee) + depth := binary.Uint64FromWord256(binary.LeftPadWord256(lastCall(callTxe.Events).Return)) + // Would give 23 if taken from wrong frame (i.e. not the outer stackdepth == 0 one) + assert.Equal(t, 18, int(depth)) + } + } + require.Equal(t, numGoroutines*numRuns*2, <-countCh) +} + +func TestSendTxAsync(t *testing.T) { + cli := rpctest.NewTransactClient(t, testConfig.RPC.GRPC.ListenAddress) + numSends := 1000 + countCh := rpctest.CommittedTxCount(t, kern.Emitter) + for i := 0; i < numSends; i++ { + receipt, err := cli.SendTxAsync(context.Background(), &payload.SendTx{ + Inputs: []*payload.TxInput{{ + Address: inputAddress, + Amount: 2003, + }}, + Outputs: []*payload.TxOutput{{ + Address: rpctest.PrivateAccounts[3].Address(), + Amount: 2003, + }}, + }) + require.NoError(t, err) + assert.False(t, receipt.CreatesContract) + } + require.Equal(t, numSends, <-countCh) +} + +func TestCallCode(t *testing.T) { + cli := rpctest.NewTransactClient(t, testConfig.RPC.GRPC.ListenAddress) + // add two integers and return the result + var i, j byte = 123, 21 + _, contractCode, expectedReturn := simpleContract(i, j) + txe, err := cli.CallCodeSim(context.Background(), &rpctransact.CallCodeParam{ + FromAddress: inputAddress, + Code: contractCode, + }) + require.NoError(t, err) + assert.Equal(t, expectedReturn, txe.Result.Return) + + // pass two ints as calldata, add, and return the result + txe, err = cli.CallCodeSim(context.Background(), &rpctransact.CallCodeParam{ + FromAddress: inputAddress, + Code: bc.MustSplice(asm.PUSH1, 0x0, asm.CALLDATALOAD, asm.PUSH1, 0x20, asm.CALLDATALOAD, asm.ADD, asm.PUSH1, + 0x0, asm.MSTORE, asm.PUSH1, 0x20, asm.PUSH1, 0x0, asm.RETURN), + Data: bc.MustSplice(binary.LeftPadWord256([]byte{i}), binary.LeftPadWord256([]byte{j})), + }) + require.NoError(t, err) + assert.Equal(t, expectedReturn, txe.Result.Return) +} + +func TestCallContract(t *testing.T) { + initCode, _, expectedReturn := simpleContract(43, 1) + cli := rpctest.NewTransactClient(t, testConfig.RPC.GRPC.ListenAddress) + txe, err := cli.CallTxSync(context.Background(), &payload.CallTx{ + Input: &payload.TxInput{ + Address: inputAddress, + Amount: uint64(6969), + }, + Address: nil, + Data: initCode, + Fee: uint64(1000), + GasLimit: uint64(1000), + }) + require.NoError(t, err) + assert.Equal(t, true, txe.Receipt.CreatesContract, "This transaction should"+ + " create a contract") + assert.NotEqual(t, 0, len(txe.TxHash), "Receipt should contain a"+ + " transaction hash") + contractAddress := txe.Receipt.ContractAddress + assert.NotEqual(t, 0, len(contractAddress), "Transactions claims to have"+ + " created a contract but the contract address is empty") + + txe, err = cli.CallTxSync(context.Background(), &payload.CallTx{ + Input: &payload.TxInput{ + Address: inputAddress, + Amount: uint64(6969), + }, + Address: &contractAddress, + Fee: uint64(1000), + GasLimit: uint64(1000), + }) + require.NoError(t, err) + + assert.Equal(t, expectedReturn, txe.Result.Return) +} + +// create two contracts, one of which calls the other +func TestNestedCall(t *testing.T) { + code, _, expectedReturn := simpleContract(5, 6) + + // Deploy callee contract + cli := rpctest.NewTransactClient(t, testConfig.RPC.GRPC.ListenAddress) + txe, err := cli.CallTxSync(context.Background(), &payload.CallTx{ + Input: &payload.TxInput{ + Address: inputAddress, + Amount: uint64(6969), + }, + Data: code, + GasLimit: 10000, + }) + require.NoError(t, err) + assert.True(t, txe.Receipt.CreatesContract) + calleeContractAddress := txe.Receipt.ContractAddress + + // Deploy caller contract + code, _, _ = simpleCallContract(calleeContractAddress) + txe, err = cli.CallTxSync(context.Background(), &payload.CallTx{ + Input: &payload.TxInput{ + Address: inputAddress, + Amount: uint64(6969), + }, + Data: code, + GasLimit: 10000, + }) + require.NoError(t, err) + assert.True(t, txe.Receipt.CreatesContract) + callerContractAddress := txe.Receipt.ContractAddress + + // Call caller contract + txe, err = cli.CallTxSync(context.Background(), &payload.CallTx{ + Input: &payload.TxInput{ + Address: inputAddress, + Amount: uint64(6969), + }, + Address: &callerContractAddress, + GasLimit: 10000, + }) + require.NoError(t, err) + assert.Equal(t, expectedReturn, txe.Result.Return) +} + +func TestCallEvents(t *testing.T) { + cli := rpctest.NewTransactClient(t, testConfig.RPC.GRPC.ListenAddress) + createTxe := rpctest.CreateContract(t, cli, inputAddress) + address := lastCall(createTxe.Events).CallData.Callee + callTxe := rpctest.CallContract(t, cli, inputAddress, address) + callEvents := filterCalls(callTxe.Events) + require.Len(t, callEvents, rpctest.UpsieDownsieCallCount, "should see 30 recursive call events") + for i, ev := range callEvents { + assert.Equal(t, uint64(rpctest.UpsieDownsieCallCount-i-1), ev.StackDepth) + } +} + +func TestLogEvents(t *testing.T) { + cli := rpctest.NewTransactClient(t, testConfig.RPC.GRPC.ListenAddress) + createTxe := rpctest.CreateContract(t, cli, inputAddress) + address := lastCall(createTxe.Events).CallData.Callee + callTxe := rpctest.CallContract(t, cli, inputAddress, address) + evs := filterLogs(callTxe.Events) + require.Len(t, evs, rpctest.UpsieDownsieCallCount-2) + log := evs[0] + depth := binary.Int64FromWord256(log.Topics[2]) + direction := strings.TrimRight(string(log.Topics[1][:]), "\x00") + assert.Equal(t, int64(18), depth) + assert.Equal(t, "Upsie!", direction) +} + +func filterCalls(evs []*exec.Event) []*exec.CallEvent { + var callEvs []*exec.CallEvent + for _, ev := range evs { + if ev.Call != nil { + callEvs = append(callEvs, ev.Call) + } + } + return callEvs +} + +func filterLogs(evs []*exec.Event) []*exec.LogEvent { + var logEvs []*exec.LogEvent + for _, ev := range evs { + if ev.Log != nil { + logEvs = append(logEvs, ev.Log) + } + } + return logEvs +} + +func lastCall(evs []*exec.Event) *exec.CallEvent { + callEvs := filterCalls(evs) + return callEvs[len(callEvs)-1] +} + +func TestName(t *testing.T) { + initcode, contractcode, returncode := simpleContract(5, 6) + fmt.Println(asm.OpCode(0x7f).Name(), initcode, contractcode, returncode) + +} + +// simple contract returns 5 + 6 = 0xb +func simpleContract(i, j byte) ([]byte, []byte, []byte) { + // this is the code we want to run when the contract is called + contractCode := bc.MustSplice(asm.PUSH1, i, asm.PUSH1, j, asm.ADD, asm.PUSH1, 0x0, asm.MSTORE, asm.PUSH1, 0x20, asm.PUSH1, + 0x0, asm.RETURN) + // the is the code we need to return the contractCode when the contract is initialized + lenCode := len(contractCode) + // push code to the stack + initCode := bc.MustSplice(asm.PUSH32, binary.RightPadWord256(contractCode), + // store it in memory + asm.PUSH1, 0x0, asm.MSTORE, + // return whats in memory + asm.PUSH1, lenCode, asm.PUSH1, 0x0, asm.RETURN) + // return init code, contract code, expected return + return initCode, contractCode, binary.LeftPadBytes([]byte{i + j}, 32) +} + +func simpleCallContract(address crypto.Address) ([]byte, []byte, []byte) { + gas1, gas2 := byte(0x1), byte(0x1) + value := byte(0x1) + inOff, inSize := byte(0x0), byte(0x0) // no call data + retOff, retSize := byte(0x0), byte(0x20) + // this is the code we want to run (call a contract and return) + contractCode := []byte{0x60, retSize, 0x60, retOff, 0x60, inSize, 0x60, inOff, + 0x60, value, 0x73} + contractCode = append(contractCode, address.Bytes()...) + contractCode = append(contractCode, []byte{0x61, gas1, gas2, 0xf1, 0x60, 0x20, + 0x60, 0x0, 0xf3}...) + + // the is the code we need to return; the contractCode when the contract is initialized + // it should copy the code from the input into memory + lenCode := len(contractCode) + memOff := byte(0x0) + inOff = byte(0xc) // length of code before codeContract + length := byte(lenCode) + + code := []byte{0x60, length, 0x60, inOff, 0x60, memOff, 0x37} + // return whats in memory + code = append(code, []byte{0x60, byte(lenCode), 0x60, 0x0, 0xf3}...) + code = append(code, contractCode...) + // return init code, contract code, expected return + return code, contractCode, binary.LeftPadBytes([]byte{0xb}, 32) +} diff --git a/rpc/v0/integration/main_test.go b/integration/rpctransact/main_test.go similarity index 69% rename from rpc/v0/integration/main_test.go rename to integration/rpctransact/main_test.go index a83a08b51..bda89290e 100644 --- a/rpc/v0/integration/main_test.go +++ b/integration/rpctransact/main_test.go @@ -15,28 +15,28 @@ // See the License for the specific language governing permissions and // limitations under the License. -package integration +package rpctransact import ( "os" "testing" - "time" "github.com/hyperledger/burrow/core" - "github.com/hyperledger/burrow/core/integration" + "github.com/hyperledger/burrow/integration" + "github.com/hyperledger/burrow/integration/rpctest" ) -var privateAccounts = integration.MakePrivateAccounts(5) // make keys -var genesisDoc = integration.TestGenesisDoc(privateAccounts) +var _ = integration.ClaimPorts() +var testConfig = integration.NewTestConfig(rpctest.GenesisDoc) var kern *core.Kernel // Needs to be in a _test.go file to be picked up func TestMain(m *testing.M) { - returnValue := integration.TestWrapper(privateAccounts, genesisDoc, func(k *core.Kernel) int { - kern = k - return m.Run() - }) + returnValue := integration.TestWrapper(rpctest.PrivateAccounts, testConfig, + func(k *core.Kernel) int { + kern = k + return m.Run() + }) - time.Sleep(3 * time.Second) os.Exit(returnValue) } diff --git a/integration/rpctransact/name_test.go b/integration/rpctransact/name_test.go new file mode 100644 index 000000000..3ba4a77f5 --- /dev/null +++ b/integration/rpctransact/name_test.go @@ -0,0 +1,117 @@ +// +build integration + +package rpctransact + +import ( + "context" + "testing" + + "github.com/hyperledger/burrow/event" + "github.com/hyperledger/burrow/execution/exec" + "github.com/hyperledger/burrow/execution/names" + "github.com/hyperledger/burrow/integration/rpctest" + "github.com/hyperledger/burrow/rpc/rpcquery" + "github.com/hyperledger/burrow/txs/payload" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNameTxSync(t *testing.T) { + cli := rpctest.NewTransactClient(t, testConfig.RPC.GRPC.ListenAddress) + name := "Flub" + data := "floooo" + expiresIn := uint64(100) + _, err := cli.NameTxSync(context.Background(), &payload.NameTx{ + Input: &payload.TxInput{ + Address: inputAddress, + Amount: names.NameCostForExpiryIn(name, data, expiresIn), + }, + Name: name, + Data: data, + }) + require.NoError(t, err) + + qcli := rpctest.NewQueryClient(t, testConfig.RPC.GRPC.ListenAddress) + entry, err := qcli.GetName(context.Background(), &rpcquery.GetNameParam{ + Name: name, + }) + require.NoError(t, err) + assert.Equal(t, name, entry.Name) + assert.Equal(t, data, entry.Data) + assert.Equal(t, inputAddress, entry.Owner) + assert.True(t, entry.Expires >= expiresIn, "expiry should be later than expiresIn") +} + +func TestNameReg(t *testing.T) { + tcli := rpctest.NewTransactClient(t, testConfig.RPC.GRPC.ListenAddress) + qcli := rpctest.NewQueryClient(t, testConfig.RPC.GRPC.ListenAddress) + names.MinNameRegistrationPeriod = 1 + + // register a new name, check if its there + // since entries ought to be unique and these run against different clients, we append the client + name := "ye_old_domain_name" + const data = "if not now, when" + numDesiredBlocks := uint64(2) + + txe := rpctest.UpdateName(t, tcli, inputAddress, name, data, numDesiredBlocks) + + entry := txe.Result.NameEntry + assert.NotNil(t, entry, "name shoudl return") + _, ok := txe.Envelope.Tx.Payload.(*payload.NameTx) + require.True(t, ok, "should be NameTx: %v", txe.Envelope.Tx.Payload) + + assert.Equal(t, name, entry.Name) + assert.Equal(t, data, entry.Data) + + entryQuery, err := qcli.GetName(context.Background(), &rpcquery.GetNameParam{Name: name}) + require.NoError(t, err) + + assert.Equal(t, entry, entryQuery) + + // update the data as the owner, make sure still there + numDesiredBlocks = uint64(3) + const updatedData = "these are amongst the things I wish to bestow upon " + + "the youth of generations come: a safe supply of honey, and a better " + + "money. For what else shall they need" + rpctest.UpdateName(t, tcli, inputAddress, name, updatedData, numDesiredBlocks) + + entry, err = qcli.GetName(context.Background(), &rpcquery.GetNameParam{Name: name}) + require.NoError(t, err) + + assert.Equal(t, updatedData, entry.Data) + + // try to update as non owner, should fail + txe, err = tcli.NameTxSync(context.Background(), &payload.NameTx{ + Input: &payload.TxInput{ + Address: rpctest.PrivateAccounts[1].Address(), + Amount: names.NameCostForExpiryIn(name, data, numDesiredBlocks), + }, + Name: name, + Data: "flub flub floo", + }) + require.Error(t, err, "updating as non-owner on non-expired name should fail") + assert.Contains(t, err.Error(), "permission denied") + + waitNBlocks(t, numDesiredBlocks) + //now the entry should be expired, so we can update as non owner + const data2 = "this is not my beautiful house" + owner := rpctest.PrivateAccounts[3].Address() + txe = rpctest.UpdateName(t, tcli, owner, name, data2, numDesiredBlocks) + entry = txe.Result.NameEntry + + entryQuery, err = qcli.GetName(context.Background(), &rpcquery.GetNameParam{Name: name}) + require.NoError(t, err) + assert.Equal(t, entry, entryQuery) + assert.Equal(t, data2, entry.Data) + assert.Equal(t, owner, entry.Owner) +} + +func waitNBlocks(t testing.TB, n uint64) { + subID := event.GenSubID() + ch, err := kern.Emitter.Subscribe(context.Background(), subID, exec.QueryForBlockExecution(), 10) + require.NoError(t, err) + defer kern.Emitter.UnsubscribeAll(context.Background(), subID) + for i := uint64(0); i < n; i++ { + <-ch + } +} diff --git a/integration/rpctransact/send_test.go b/integration/rpctransact/send_test.go new file mode 100644 index 000000000..4b465dbc9 --- /dev/null +++ b/integration/rpctransact/send_test.go @@ -0,0 +1,31 @@ +// +build integration + +package rpctransact + +import ( + "context" + "testing" + + "github.com/hyperledger/burrow/integration/rpctest" + "github.com/hyperledger/burrow/txs/payload" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestSendTxSync(t *testing.T) { + cli := rpctest.NewTransactClient(t, testConfig.RPC.GRPC.ListenAddress) + for i := 0; i < 2; i++ { + txe, err := cli.SendTxSync(context.Background(), &payload.SendTx{ + Inputs: []*payload.TxInput{{ + Address: inputAddress, + Amount: 2003, + }}, + Outputs: []*payload.TxOutput{{ + Address: rpctest.PrivateAccounts[3].Address(), + Amount: 2003, + }}, + }) + require.NoError(t, err) + assert.False(t, txe.Receipt.CreatesContract) + } +} diff --git a/integration/rpctransact/transact_server_test.go b/integration/rpctransact/transact_server_test.go new file mode 100644 index 000000000..6ab30c545 --- /dev/null +++ b/integration/rpctransact/transact_server_test.go @@ -0,0 +1,109 @@ +// +build integration + +// Space above here matters +// Copyright 2017 Monax Industries Limited +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package rpctransact + +import ( + "context" + "fmt" + "testing" + + "time" + + "github.com/hyperledger/burrow/execution/exec" + "github.com/hyperledger/burrow/integration/rpctest" + "github.com/hyperledger/burrow/rpc/rpcevents" + "github.com/hyperledger/burrow/rpc/rpcquery" + "github.com/hyperledger/burrow/rpc/rpctransact" + "github.com/hyperledger/burrow/txs" + "github.com/hyperledger/burrow/txs/payload" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +var inputAccount = rpctest.PrivateAccounts[0] +var inputAddress = inputAccount.Address() + +func TestBroadcastTxLocallySigned(t *testing.T) { + qcli := rpctest.NewQueryClient(t, testConfig.RPC.GRPC.ListenAddress) + acc, err := qcli.GetAccount(context.Background(), &rpcquery.GetAccountParam{ + Address: inputAddress, + }) + require.NoError(t, err) + amount := uint64(2123) + txEnv := txs.Enclose(rpctest.GenesisDoc.ChainID(), &payload.SendTx{ + Inputs: []*payload.TxInput{{ + Address: inputAddress, + Sequence: acc.Sequence + 1, + Amount: amount, + }}, + Outputs: []*payload.TxOutput{{ + Address: rpctest.PrivateAccounts[1].Address(), + Amount: amount, + }}, + }) + require.NoError(t, txEnv.Sign(inputAccount)) + + // Test subscribing to transaction before sending it + ch := make(chan *exec.TxExecution) + go func() { + ecli := rpctest.NewExecutionEventsClient(t, testConfig.RPC.GRPC.ListenAddress) + txe, err := ecli.GetTx(context.Background(), &rpcevents.GetTxRequest{ + TxHash: txEnv.Tx.Hash(), + Wait: true, + }) + require.NoError(t, err) + ch <- txe + }() + + // Make it wait + time.Sleep(time.Second) + + // No broadcast + cli := rpctest.NewTransactClient(t, testConfig.RPC.GRPC.ListenAddress) + receipt, err := cli.BroadcastTxAsync(context.Background(), &rpctransact.TxEnvelopeParam{Envelope: txEnv}) + require.NoError(t, err) + assert.False(t, receipt.CreatesContract, "This tx should not create a contract") + require.NotEmpty(t, receipt.TxHash, "Failed to compute tx hash") + assert.Equal(t, txEnv.Tx.Hash(), receipt.TxHash) + + txe := <-ch + require.True(t, len(txe.Events) > 0) + assert.NotNil(t, txe.Events[0].Input) +} + +func TestFormulateTx(t *testing.T) { + cli := rpctest.NewTransactClient(t, testConfig.RPC.GRPC.ListenAddress) + txEnv, err := cli.FormulateTx(context.Background(), &rpctransact.PayloadParam{ + CallTx: &payload.CallTx{ + Input: &payload.TxInput{ + Address: inputAddress, + Amount: 230, + }, + Data: []byte{2, 3, 6, 4, 3}, + }, + }) + require.NoError(t, err) + bs, err := txEnv.Marshal() + require.NoError(t, err) + // We should see the sign bytes embedded + if !assert.Contains(t, string(bs), fmt.Sprintf("{\"ChainID\":\"%s\",\"Type\":\"CallTx\","+ + "\"Payload\":{\"Input\":{\"Address\":\"4A6DFB649EF0D50780998A686BD69AB175C08E26\",\"Amount\":230},"+ + "\"Data\":\"0203060403\"}}", rpctest.GenesisDoc.ChainID())) { + fmt.Println(string(bs)) + } +} diff --git a/integration/tm/main_test.go b/integration/tm/main_test.go new file mode 100644 index 000000000..cdee8c090 --- /dev/null +++ b/integration/tm/main_test.go @@ -0,0 +1,49 @@ +// +build integration + +// Space above here matters +// Copyright 2017 Monax Industries Limited +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package tm + +import ( + "os" + "testing" + + "github.com/hyperledger/burrow/core" + "github.com/hyperledger/burrow/integration" + "github.com/hyperledger/burrow/integration/rpctest" + rpcClient "github.com/hyperledger/burrow/rpc/lib/client" + tmClient "github.com/hyperledger/burrow/rpc/tm/tmclient" +) + +var kern *core.Kernel +var _ = integration.ClaimPorts() +var testConfig = integration.NewTestConfig(rpctest.GenesisDoc) +var jsonRpcClient = rpcClient.NewJSONRPCClient(testConfig.RPC.TM.ListenAddress) +var httpClient = rpcClient.NewURIClient(testConfig.RPC.TM.ListenAddress) +var clients = map[string]tmClient.RPCClient{ + "JSONRPC": jsonRpcClient, + "HTTP": httpClient, +} + +// Needs to be in a _test.go file to be picked up +func TestMain(m *testing.M) { + returnValue := integration.TestWrapper(rpctest.PrivateAccounts, testConfig, func(k *core.Kernel) int { + kern = k + return m.Run() + }) + + os.Exit(returnValue) +} diff --git a/integration/tm/tm_server_test.go b/integration/tm/tm_server_test.go new file mode 100644 index 000000000..09ce3b581 --- /dev/null +++ b/integration/tm/tm_server_test.go @@ -0,0 +1,224 @@ +// +build integration + +// Space above here matters +// Copyright 2017 Monax Industries Limited +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package tm + +import ( + "context" + "fmt" + "strings" + "testing" + "time" + + "github.com/hyperledger/burrow/binary" + "github.com/hyperledger/burrow/event" + "github.com/hyperledger/burrow/execution/exec" + "github.com/hyperledger/burrow/integration/rpctest" + "github.com/hyperledger/burrow/rpc/rpctransact" + "github.com/hyperledger/burrow/rpc/tm/tmclient" + "github.com/hyperledger/burrow/txs" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/tendermint/tendermint/consensus/types" +) + +const timeout = 5 * time.Second + +func testWithAllClients(t *testing.T, testFunction func(*testing.T, string, tmclient.RPCClient)) { + for clientName, client := range clients { + testFunction(t, clientName, client) + } +} + +//-------------------------------------------------------------------------------- +func TestStatus(t *testing.T) { + testWithAllClients(t, func(t *testing.T, clientName string, client tmclient.RPCClient) { + resp, err := tmclient.Status(client) + assert.NoError(t, err) + assert.Equal(t, rpctest.GenesisDoc.ChainID(), resp.NodeInfo.Network, + "ChainID should match NodeInfo.Network") + }) +} + +func TestGetAccount(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + testWithAllClients(t, func(t *testing.T, clientName string, client tmclient.RPCClient) { + acc := rpctest.GetAccount(t, client, rpctest.PrivateAccounts[0].Address()) + if acc == nil { + t.Fatal("Account was nil") + } + if acc.Address() != rpctest.PrivateAccounts[0].Address() { + t.Fatalf("Failed to get correct account. Got %s, expected %s", acc.Address(), + rpctest.PrivateAccounts[0].Address()) + } + }) +} + +func TestGetStorage(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + testWithAllClients(t, func(t *testing.T, clientName string, client tmclient.RPCClient) { + amt, gasLim, fee := uint64(1100), uint64(1000), uint64(1000) + code := []byte{0x60, 0x5, 0x60, 0x1, 0x55} + // Call with nil address will create a contract + tx := rpctest.MakeDefaultCallTx(t, client, nil, code, amt, gasLim, fee) + txe := broadcastTxSync(t, tx) + assert.Equal(t, true, txe.Receipt.CreatesContract, "This transaction should"+ + " create a contract") + assert.NotEqual(t, 0, len(txe.TxHash), "Receipt should contain a"+ + " transaction hash") + contractAddr := txe.Receipt.ContractAddress + assert.NotEqual(t, 0, len(contractAddr), "Transactions claims to have"+ + " created a contract but the contract address is empty") + + v := rpctest.GetStorage(t, client, contractAddr, []byte{0x1}) + got := binary.LeftPadWord256(v) + expected := binary.LeftPadWord256([]byte{0x5}) + if got.Compare(expected) != 0 { + t.Fatalf("Wrong storage value. Got %x, expected %x", got.Bytes(), + expected.Bytes()) + } + }) +} + +func TestWaitBlocks(t *testing.T) { + waitNBlocks(t, 5) +} + +func TestBlockchainInfo(t *testing.T) { + testWithAllClients(t, func(t *testing.T, clientName string, client tmclient.RPCClient) { + // wait a mimimal number of blocks to ensure that the later query for block + // headers has a non-trivial length + nBlocks := 4 + waitNBlocks(t, nBlocks) + + resp, err := tmclient.ListBlocks(client, 0, 0) + if err != nil { + t.Fatalf("Failed to get blockchain info: %v", err) + } + lastBlockHeight := resp.LastHeight + nMetaBlocks := len(resp.BlockMetas) + assert.True(t, uint64(nMetaBlocks) <= lastBlockHeight, + "Logically number of block metas should be equal or less than block height.") + assert.True(t, nBlocks <= len(resp.BlockMetas), + "Should see at least %v BlockMetas after waiting for %v blocks but saw %v", + nBlocks, nBlocks, len(resp.BlockMetas)) + // For the maximum number (default to 20) of retrieved block headers, + // check that they correctly chain to each other. + lastBlockHash := resp.BlockMetas[nMetaBlocks-1].Header.Hash() + for i := nMetaBlocks - 2; i >= 0; i-- { + // the blockhash in header of height h should be identical to the hash + // in the LastBlockID of the header of block height h+1. + assert.Equal(t, lastBlockHash, resp.BlockMetas[i].Header.LastBlockID.Hash, + "Blockchain should be a hash tree!") + lastBlockHash = resp.BlockMetas[i].Header.Hash() + } + + // Now retrieve only two blockheaders (h=1, and h=2) and check that we got + // two results. + resp, err = tmclient.ListBlocks(client, 1, 2) + assert.NoError(t, err) + assert.Equal(t, 2, len(resp.BlockMetas), + "Should see 2 BlockMetas after extracting 2 blocks") + }) +} + +func TestListUnconfirmedTxs(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + testWithAllClients(t, func(t *testing.T, clientName string, client tmclient.RPCClient) { + amt, gasLim, fee := uint64(1100), uint64(1000), uint64(1000) + code := []byte{0x60, 0x5, 0x60, 0x1, 0x55} + // Call with nil address will create a contract + txEnv := rpctest.MakeDefaultCallTx(t, client, nil, code, amt, gasLim, fee) + txChan := make(chan []*txs.Envelope) + + // We want to catch the Tx in mempool before it gets reaped by tendermint + // consensus. We should be able to do this almost always if we broadcast our + // transaction immediately after a block has been committed. There is about + // 1 second between blocks, and we will have the lock on Reap + // So we wait for a block here + waitNBlocks(t, 1) + + go func() { + for { + resp, err := tmclient.ListUnconfirmedTxs(client, -1) + if err != nil { + // We get an error on exit + return + } + if resp.NumTxs > 0 { + txChan <- resp.Txs + } + } + }() + + broadcastTxSync(t, txEnv) + select { + case <-time.After(time.Second * timeout): + t.Fatal("Timeout out waiting for unconfirmed transactions to appear") + case transactions := <-txChan: + assert.Len(t, transactions, 1, "There should only be a single transaction in the "+ + "mempool during this test (previous txs should have made it into a block)") + assert.Contains(t, transactions, txEnv, "Transaction should be returned by ListUnconfirmedTxs") + } + }) +} + +func TestListValidators(t *testing.T) { + testWithAllClients(t, func(t *testing.T, clientName string, client tmclient.RPCClient) { + resp, err := tmclient.ListValidators(client) + assert.NoError(t, err) + assert.Len(t, resp.BondedValidators, 1) + validator := resp.BondedValidators[0] + assert.Equal(t, rpctest.GenesisDoc.Validators[0].PublicKey, validator.PublicKey) + }) +} + +func TestDumpConsensusState(t *testing.T) { + startTime := time.Now() + testWithAllClients(t, func(t *testing.T, clientName string, client tmclient.RPCClient) { + resp, err := tmclient.DumpConsensusState(client) + assert.NoError(t, err) + assert.NotZero(t, startTime) + assert.Equal(t, fmt.Sprintf("/0/%d", types.RoundStepNewHeight), + strings.TrimLeft(resp.RoundState.HeightRoundStep, "0123456789")) + }) +} + +func waitNBlocks(t testing.TB, n int) { + subID := event.GenSubID() + ch, err := kern.Emitter.Subscribe(context.Background(), subID, exec.QueryForBlockExecution(), 10) + require.NoError(t, err) + defer kern.Emitter.UnsubscribeAll(context.Background(), subID) + for i := 0; i < n; i++ { + <-ch + } +} + +func broadcastTxSync(t testing.TB, txEnv *txs.Envelope) *exec.TxExecution { + cli := rpctest.NewTransactClient(t, testConfig.RPC.GRPC.ListenAddress) + txe, err := cli.BroadcastTxSync(context.Background(), &rpctransact.TxEnvelopeParam{ + Envelope: txEnv, + }) + require.NoError(t, err) + return txe +} diff --git a/keys/key_client.go b/keys/key_client.go index bae1d0ae7..ae6a92c7a 100644 --- a/keys/key_client.go +++ b/keys/key_client.go @@ -20,7 +20,6 @@ import ( "time" "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/keys/pbkeys" "github.com/hyperledger/burrow/logging" "google.golang.org/grpc" ) @@ -49,16 +48,16 @@ type localKeyClient struct { type remoteKeyClient struct { rpcAddress string - kc pbkeys.KeysClient + kc KeysClient logger *logging.Logger } func (l *localKeyClient) Sign(signAddress crypto.Address, message []byte) (signature crypto.Signature, err error) { - resp, err := l.ks.Sign(nil, &pbkeys.SignRequest{Address: signAddress.String(), Message: message}) + resp, err := l.ks.Sign(nil, &SignRequest{Address: signAddress.String(), Message: message}) if err != nil { return crypto.Signature{}, err } - curveType, err := crypto.CurveTypeFromString(resp.GetCurvetype()) + curveType, err := crypto.CurveTypeFromString(resp.GetCurveType()) if err != nil { return crypto.Signature{}, err } @@ -66,20 +65,20 @@ func (l *localKeyClient) Sign(signAddress crypto.Address, message []byte) (signa } func (l *localKeyClient) PublicKey(address crypto.Address) (publicKey crypto.PublicKey, err error) { - resp, err := l.ks.PublicKey(nil, &pbkeys.PubRequest{Address: address.String()}) + resp, err := l.ks.PublicKey(nil, &PubRequest{Address: address.String()}) if err != nil { return crypto.PublicKey{}, err } - curveType, err := crypto.CurveTypeFromString(resp.GetCurvetype()) + curveType, err := crypto.CurveTypeFromString(resp.GetCurveType()) if err != nil { return crypto.PublicKey{}, err } - return crypto.PublicKeyFromBytes(resp.GetPub(), curveType) + return crypto.PublicKeyFromBytes(resp.GetPublicKey(), curveType) } // Generate requests that a key be generate within the keys instance and returns the address func (l *localKeyClient) Generate(keyName string, curveType crypto.CurveType) (keyAddress crypto.Address, err error) { - resp, err := l.ks.GenerateKey(nil, &pbkeys.GenRequest{Keyname: keyName, Curvetype: curveType.String()}) + resp, err := l.ks.GenerateKey(nil, &GenRequest{KeyName: keyName, CurveType: curveType.String()}) if err != nil { return crypto.Address{}, err } @@ -94,7 +93,7 @@ func (l *localKeyClient) HealthCheck() error { func (l *remoteKeyClient) Sign(signAddress crypto.Address, message []byte) (signature crypto.Signature, err error) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - req := pbkeys.SignRequest{Address: signAddress.String(), Message: message} + req := SignRequest{Address: signAddress.String(), Message: message} l.logger.TraceMsg("Sending Sign request to remote key server: ", fmt.Sprintf("%v", req)) resp, err := l.kc.Sign(ctx, &req) if err != nil { @@ -102,7 +101,7 @@ func (l *remoteKeyClient) Sign(signAddress crypto.Address, message []byte) (sign return crypto.Signature{}, err } l.logger.TraceMsg("Received Sign response to remote key server: %v", resp) - curveType, err := crypto.CurveTypeFromString(resp.GetCurvetype()) + curveType, err := crypto.CurveTypeFromString(resp.GetCurveType()) if err != nil { return crypto.Signature{}, err } @@ -112,26 +111,26 @@ func (l *remoteKeyClient) Sign(signAddress crypto.Address, message []byte) (sign func (l *remoteKeyClient) PublicKey(address crypto.Address) (publicKey crypto.PublicKey, err error) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - req := pbkeys.PubRequest{Address: address.String()} + req := PubRequest{Address: address.String()} l.logger.TraceMsg("Sending PublicKey request to remote key server: ", fmt.Sprintf("%v", req)) resp, err := l.kc.PublicKey(ctx, &req) if err != nil { l.logger.TraceMsg("Received PublicKey error response: ", err) return crypto.PublicKey{}, err } - curveType, err := crypto.CurveTypeFromString(resp.GetCurvetype()) + curveType, err := crypto.CurveTypeFromString(resp.GetCurveType()) if err != nil { return crypto.PublicKey{}, err } l.logger.TraceMsg("Received PublicKey response to remote key server: ", fmt.Sprintf("%v", resp)) - return crypto.PublicKeyFromBytes(resp.GetPub(), curveType) + return crypto.PublicKeyFromBytes(resp.GetPublicKey(), curveType) } // Generate requests that a key be generate within the keys instance and returns the address func (l *remoteKeyClient) Generate(keyName string, curveType crypto.CurveType) (keyAddress crypto.Address, err error) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - req := pbkeys.GenRequest{Keyname: keyName, Curvetype: curveType.String()} + req := GenRequest{KeyName: keyName, CurveType: curveType.String()} l.logger.TraceMsg("Sending Generate request to remote key server: ", fmt.Sprintf("%v", req)) resp, err := l.kc.GenerateKey(ctx, &req) if err != nil { @@ -146,7 +145,7 @@ func (l *remoteKeyClient) Generate(keyName string, curveType crypto.CurveType) ( func (l *remoteKeyClient) HealthCheck() error { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - _, err := l.kc.List(ctx, &pbkeys.ListRequest{}) + _, err := l.kc.List(ctx, &ListRequest{}) return err } @@ -160,7 +159,7 @@ func NewRemoteKeyClient(rpcAddress string, logger *logging.Logger) (KeyClient, e if err != nil { return nil, err } - kc := pbkeys.NewKeysClient(conn) + kc := NewKeysClient(conn) return &remoteKeyClient{kc: kc, rpcAddress: rpcAddress, logger: logger}, nil } diff --git a/keys/key_store.go b/keys/key_store.go index 0a8a1cf5a..c2326cf38 100644 --- a/keys/key_store.go +++ b/keys/key_store.go @@ -15,8 +15,8 @@ import ( "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" - "github.com/tmthrgd/go-hex" + "github.com/tmthrgd/go-hex" "golang.org/x/crypto/scrypt" ) diff --git a/keys/keys.pb.go b/keys/keys.pb.go new file mode 100644 index 000000000..6d8212e6a --- /dev/null +++ b/keys/keys.pb.go @@ -0,0 +1,4538 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: keys.proto + +/* + Package keys is a generated protocol buffer package. + + It is generated from these files: + keys.proto + + It has these top-level messages: + ListRequest + VerifyResponse + RemoveNameResponse + AddNameResponse + RemoveNameRequest + GenRequest + GenResponse + PubRequest + PubResponse + ImportJSONRequest + ImportResponse + ImportRequest + ExportRequest + ExportResponse + SignRequest + SignResponse + VerifyRequest + HashRequest + HashResponse + KeyID + ListResponse + AddNameRequest +*/ +package keys + +import proto "github.com/gogo/protobuf/proto" +import golang_proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" +import _ "github.com/gogo/protobuf/gogoproto" + +import context "golang.org/x/net/context" +import grpc "google.golang.org/grpc" + +import io "io" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = golang_proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package + +type ListRequest struct { +} + +func (m *ListRequest) Reset() { *m = ListRequest{} } +func (m *ListRequest) String() string { return proto.CompactTextString(m) } +func (*ListRequest) ProtoMessage() {} +func (*ListRequest) Descriptor() ([]byte, []int) { return fileDescriptorKeys, []int{0} } + +func (*ListRequest) XXX_MessageName() string { + return "keys.ListRequest" +} + +type VerifyResponse struct { +} + +func (m *VerifyResponse) Reset() { *m = VerifyResponse{} } +func (m *VerifyResponse) String() string { return proto.CompactTextString(m) } +func (*VerifyResponse) ProtoMessage() {} +func (*VerifyResponse) Descriptor() ([]byte, []int) { return fileDescriptorKeys, []int{1} } + +func (*VerifyResponse) XXX_MessageName() string { + return "keys.VerifyResponse" +} + +type RemoveNameResponse struct { +} + +func (m *RemoveNameResponse) Reset() { *m = RemoveNameResponse{} } +func (m *RemoveNameResponse) String() string { return proto.CompactTextString(m) } +func (*RemoveNameResponse) ProtoMessage() {} +func (*RemoveNameResponse) Descriptor() ([]byte, []int) { return fileDescriptorKeys, []int{2} } + +func (*RemoveNameResponse) XXX_MessageName() string { + return "keys.RemoveNameResponse" +} + +type AddNameResponse struct { +} + +func (m *AddNameResponse) Reset() { *m = AddNameResponse{} } +func (m *AddNameResponse) String() string { return proto.CompactTextString(m) } +func (*AddNameResponse) ProtoMessage() {} +func (*AddNameResponse) Descriptor() ([]byte, []int) { return fileDescriptorKeys, []int{3} } + +func (*AddNameResponse) XXX_MessageName() string { + return "keys.AddNameResponse" +} + +type RemoveNameRequest struct { + KeyName string `protobuf:"bytes,1,opt,name=KeyName,proto3" json:"KeyName,omitempty"` +} + +func (m *RemoveNameRequest) Reset() { *m = RemoveNameRequest{} } +func (m *RemoveNameRequest) String() string { return proto.CompactTextString(m) } +func (*RemoveNameRequest) ProtoMessage() {} +func (*RemoveNameRequest) Descriptor() ([]byte, []int) { return fileDescriptorKeys, []int{4} } + +func (m *RemoveNameRequest) GetKeyName() string { + if m != nil { + return m.KeyName + } + return "" +} + +func (*RemoveNameRequest) XXX_MessageName() string { + return "keys.RemoveNameRequest" +} + +type GenRequest struct { + Passphrase string `protobuf:"bytes,1,opt,name=Passphrase,proto3" json:"Passphrase,omitempty"` + CurveType string `protobuf:"bytes,2,opt,name=CurveType,proto3" json:"CurveType,omitempty"` + KeyName string `protobuf:"bytes,3,opt,name=KeyName,proto3" json:"KeyName,omitempty"` +} + +func (m *GenRequest) Reset() { *m = GenRequest{} } +func (m *GenRequest) String() string { return proto.CompactTextString(m) } +func (*GenRequest) ProtoMessage() {} +func (*GenRequest) Descriptor() ([]byte, []int) { return fileDescriptorKeys, []int{5} } + +func (m *GenRequest) GetPassphrase() string { + if m != nil { + return m.Passphrase + } + return "" +} + +func (m *GenRequest) GetCurveType() string { + if m != nil { + return m.CurveType + } + return "" +} + +func (m *GenRequest) GetKeyName() string { + if m != nil { + return m.KeyName + } + return "" +} + +func (*GenRequest) XXX_MessageName() string { + return "keys.GenRequest" +} + +type GenResponse struct { + Address string `protobuf:"bytes,1,opt,name=Address,proto3" json:"Address,omitempty"` +} + +func (m *GenResponse) Reset() { *m = GenResponse{} } +func (m *GenResponse) String() string { return proto.CompactTextString(m) } +func (*GenResponse) ProtoMessage() {} +func (*GenResponse) Descriptor() ([]byte, []int) { return fileDescriptorKeys, []int{6} } + +func (m *GenResponse) GetAddress() string { + if m != nil { + return m.Address + } + return "" +} + +func (*GenResponse) XXX_MessageName() string { + return "keys.GenResponse" +} + +type PubRequest struct { + Address string `protobuf:"bytes,1,opt,name=Address,proto3" json:"Address,omitempty"` + Name string `protobuf:"bytes,2,opt,name=Name,proto3" json:"Name,omitempty"` +} + +func (m *PubRequest) Reset() { *m = PubRequest{} } +func (m *PubRequest) String() string { return proto.CompactTextString(m) } +func (*PubRequest) ProtoMessage() {} +func (*PubRequest) Descriptor() ([]byte, []int) { return fileDescriptorKeys, []int{7} } + +func (m *PubRequest) GetAddress() string { + if m != nil { + return m.Address + } + return "" +} + +func (m *PubRequest) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (*PubRequest) XXX_MessageName() string { + return "keys.PubRequest" +} + +type PubResponse struct { + PublicKey []byte `protobuf:"bytes,1,opt,name=PublicKey,proto3" json:"PublicKey,omitempty"` + CurveType string `protobuf:"bytes,2,opt,name=CurveType,proto3" json:"CurveType,omitempty"` +} + +func (m *PubResponse) Reset() { *m = PubResponse{} } +func (m *PubResponse) String() string { return proto.CompactTextString(m) } +func (*PubResponse) ProtoMessage() {} +func (*PubResponse) Descriptor() ([]byte, []int) { return fileDescriptorKeys, []int{8} } + +func (m *PubResponse) GetPublicKey() []byte { + if m != nil { + return m.PublicKey + } + return nil +} + +func (m *PubResponse) GetCurveType() string { + if m != nil { + return m.CurveType + } + return "" +} + +func (*PubResponse) XXX_MessageName() string { + return "keys.PubResponse" +} + +type ImportJSONRequest struct { + Passphrase string `protobuf:"bytes,1,opt,name=Passphrase,proto3" json:"Passphrase,omitempty"` + JSON string `protobuf:"bytes,2,opt,name=JSON,proto3" json:"JSON,omitempty"` +} + +func (m *ImportJSONRequest) Reset() { *m = ImportJSONRequest{} } +func (m *ImportJSONRequest) String() string { return proto.CompactTextString(m) } +func (*ImportJSONRequest) ProtoMessage() {} +func (*ImportJSONRequest) Descriptor() ([]byte, []int) { return fileDescriptorKeys, []int{9} } + +func (m *ImportJSONRequest) GetPassphrase() string { + if m != nil { + return m.Passphrase + } + return "" +} + +func (m *ImportJSONRequest) GetJSON() string { + if m != nil { + return m.JSON + } + return "" +} + +func (*ImportJSONRequest) XXX_MessageName() string { + return "keys.ImportJSONRequest" +} + +type ImportResponse struct { + Address string `protobuf:"bytes,1,opt,name=Address,proto3" json:"Address,omitempty"` +} + +func (m *ImportResponse) Reset() { *m = ImportResponse{} } +func (m *ImportResponse) String() string { return proto.CompactTextString(m) } +func (*ImportResponse) ProtoMessage() {} +func (*ImportResponse) Descriptor() ([]byte, []int) { return fileDescriptorKeys, []int{10} } + +func (m *ImportResponse) GetAddress() string { + if m != nil { + return m.Address + } + return "" +} + +func (*ImportResponse) XXX_MessageName() string { + return "keys.ImportResponse" +} + +type ImportRequest struct { + Passphrase string `protobuf:"bytes,1,opt,name=Passphrase,proto3" json:"Passphrase,omitempty"` + Name string `protobuf:"bytes,2,opt,name=Name,proto3" json:"Name,omitempty"` + CurveType string `protobuf:"bytes,3,opt,name=CurveType,proto3" json:"CurveType,omitempty"` + KeyBytes []byte `protobuf:"bytes,4,opt,name=KeyBytes,proto3" json:"KeyBytes,omitempty"` +} + +func (m *ImportRequest) Reset() { *m = ImportRequest{} } +func (m *ImportRequest) String() string { return proto.CompactTextString(m) } +func (*ImportRequest) ProtoMessage() {} +func (*ImportRequest) Descriptor() ([]byte, []int) { return fileDescriptorKeys, []int{11} } + +func (m *ImportRequest) GetPassphrase() string { + if m != nil { + return m.Passphrase + } + return "" +} + +func (m *ImportRequest) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *ImportRequest) GetCurveType() string { + if m != nil { + return m.CurveType + } + return "" +} + +func (m *ImportRequest) GetKeyBytes() []byte { + if m != nil { + return m.KeyBytes + } + return nil +} + +func (*ImportRequest) XXX_MessageName() string { + return "keys.ImportRequest" +} + +type ExportRequest struct { + Passphrase string `protobuf:"bytes,1,opt,name=Passphrase,proto3" json:"Passphrase,omitempty"` + Name string `protobuf:"bytes,2,opt,name=Name,proto3" json:"Name,omitempty"` + Address string `protobuf:"bytes,3,opt,name=Address,proto3" json:"Address,omitempty"` +} + +func (m *ExportRequest) Reset() { *m = ExportRequest{} } +func (m *ExportRequest) String() string { return proto.CompactTextString(m) } +func (*ExportRequest) ProtoMessage() {} +func (*ExportRequest) Descriptor() ([]byte, []int) { return fileDescriptorKeys, []int{12} } + +func (m *ExportRequest) GetPassphrase() string { + if m != nil { + return m.Passphrase + } + return "" +} + +func (m *ExportRequest) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *ExportRequest) GetAddress() string { + if m != nil { + return m.Address + } + return "" +} + +func (*ExportRequest) XXX_MessageName() string { + return "keys.ExportRequest" +} + +type ExportResponse struct { + Publickey []byte `protobuf:"bytes,1,opt,name=Publickey,proto3" json:"Publickey,omitempty"` + Privatekey []byte `protobuf:"bytes,2,opt,name=Privatekey,proto3" json:"Privatekey,omitempty"` + Address []byte `protobuf:"bytes,3,opt,name=Address,proto3" json:"Address,omitempty"` + CurveType string `protobuf:"bytes,4,opt,name=CurveType,proto3" json:"CurveType,omitempty"` +} + +func (m *ExportResponse) Reset() { *m = ExportResponse{} } +func (m *ExportResponse) String() string { return proto.CompactTextString(m) } +func (*ExportResponse) ProtoMessage() {} +func (*ExportResponse) Descriptor() ([]byte, []int) { return fileDescriptorKeys, []int{13} } + +func (m *ExportResponse) GetPublickey() []byte { + if m != nil { + return m.Publickey + } + return nil +} + +func (m *ExportResponse) GetPrivatekey() []byte { + if m != nil { + return m.Privatekey + } + return nil +} + +func (m *ExportResponse) GetAddress() []byte { + if m != nil { + return m.Address + } + return nil +} + +func (m *ExportResponse) GetCurveType() string { + if m != nil { + return m.CurveType + } + return "" +} + +func (*ExportResponse) XXX_MessageName() string { + return "keys.ExportResponse" +} + +type SignRequest struct { + Passphrase string `protobuf:"bytes,1,opt,name=Passphrase,proto3" json:"Passphrase,omitempty"` + Address string `protobuf:"bytes,2,opt,name=Address,proto3" json:"Address,omitempty"` + Name string `protobuf:"bytes,3,opt,name=Name,proto3" json:"Name,omitempty"` + Message []byte `protobuf:"bytes,4,opt,name=Message,proto3" json:"Message,omitempty"` +} + +func (m *SignRequest) Reset() { *m = SignRequest{} } +func (m *SignRequest) String() string { return proto.CompactTextString(m) } +func (*SignRequest) ProtoMessage() {} +func (*SignRequest) Descriptor() ([]byte, []int) { return fileDescriptorKeys, []int{14} } + +func (m *SignRequest) GetPassphrase() string { + if m != nil { + return m.Passphrase + } + return "" +} + +func (m *SignRequest) GetAddress() string { + if m != nil { + return m.Address + } + return "" +} + +func (m *SignRequest) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *SignRequest) GetMessage() []byte { + if m != nil { + return m.Message + } + return nil +} + +func (*SignRequest) XXX_MessageName() string { + return "keys.SignRequest" +} + +type SignResponse struct { + Signature []byte `protobuf:"bytes,1,opt,name=Signature,proto3" json:"Signature,omitempty"` + CurveType string `protobuf:"bytes,2,opt,name=CurveType,proto3" json:"CurveType,omitempty"` +} + +func (m *SignResponse) Reset() { *m = SignResponse{} } +func (m *SignResponse) String() string { return proto.CompactTextString(m) } +func (*SignResponse) ProtoMessage() {} +func (*SignResponse) Descriptor() ([]byte, []int) { return fileDescriptorKeys, []int{15} } + +func (m *SignResponse) GetSignature() []byte { + if m != nil { + return m.Signature + } + return nil +} + +func (m *SignResponse) GetCurveType() string { + if m != nil { + return m.CurveType + } + return "" +} + +func (*SignResponse) XXX_MessageName() string { + return "keys.SignResponse" +} + +type VerifyRequest struct { + CurveType string `protobuf:"bytes,1,opt,name=CurveType,proto3" json:"CurveType,omitempty"` + PublicKey []byte `protobuf:"bytes,2,opt,name=PublicKey,proto3" json:"PublicKey,omitempty"` + Message []byte `protobuf:"bytes,3,opt,name=Message,proto3" json:"Message,omitempty"` + Signature []byte `protobuf:"bytes,4,opt,name=Signature,proto3" json:"Signature,omitempty"` +} + +func (m *VerifyRequest) Reset() { *m = VerifyRequest{} } +func (m *VerifyRequest) String() string { return proto.CompactTextString(m) } +func (*VerifyRequest) ProtoMessage() {} +func (*VerifyRequest) Descriptor() ([]byte, []int) { return fileDescriptorKeys, []int{16} } + +func (m *VerifyRequest) GetCurveType() string { + if m != nil { + return m.CurveType + } + return "" +} + +func (m *VerifyRequest) GetPublicKey() []byte { + if m != nil { + return m.PublicKey + } + return nil +} + +func (m *VerifyRequest) GetMessage() []byte { + if m != nil { + return m.Message + } + return nil +} + +func (m *VerifyRequest) GetSignature() []byte { + if m != nil { + return m.Signature + } + return nil +} + +func (*VerifyRequest) XXX_MessageName() string { + return "keys.VerifyRequest" +} + +type HashRequest struct { + Hashtype string `protobuf:"bytes,1,opt,name=Hashtype,proto3" json:"Hashtype,omitempty"` + Message []byte `protobuf:"bytes,2,opt,name=Message,proto3" json:"Message,omitempty"` +} + +func (m *HashRequest) Reset() { *m = HashRequest{} } +func (m *HashRequest) String() string { return proto.CompactTextString(m) } +func (*HashRequest) ProtoMessage() {} +func (*HashRequest) Descriptor() ([]byte, []int) { return fileDescriptorKeys, []int{17} } + +func (m *HashRequest) GetHashtype() string { + if m != nil { + return m.Hashtype + } + return "" +} + +func (m *HashRequest) GetMessage() []byte { + if m != nil { + return m.Message + } + return nil +} + +func (*HashRequest) XXX_MessageName() string { + return "keys.HashRequest" +} + +type HashResponse struct { + Hash string `protobuf:"bytes,1,opt,name=Hash,proto3" json:"Hash,omitempty"` +} + +func (m *HashResponse) Reset() { *m = HashResponse{} } +func (m *HashResponse) String() string { return proto.CompactTextString(m) } +func (*HashResponse) ProtoMessage() {} +func (*HashResponse) Descriptor() ([]byte, []int) { return fileDescriptorKeys, []int{18} } + +func (m *HashResponse) GetHash() string { + if m != nil { + return m.Hash + } + return "" +} + +func (*HashResponse) XXX_MessageName() string { + return "keys.HashResponse" +} + +type KeyID struct { + Address string `protobuf:"bytes,1,opt,name=Address,proto3" json:"Address,omitempty"` + KeyName string `protobuf:"bytes,2,opt,name=KeyName,proto3" json:"KeyName,omitempty"` +} + +func (m *KeyID) Reset() { *m = KeyID{} } +func (m *KeyID) String() string { return proto.CompactTextString(m) } +func (*KeyID) ProtoMessage() {} +func (*KeyID) Descriptor() ([]byte, []int) { return fileDescriptorKeys, []int{19} } + +func (m *KeyID) GetAddress() string { + if m != nil { + return m.Address + } + return "" +} + +func (m *KeyID) GetKeyName() string { + if m != nil { + return m.KeyName + } + return "" +} + +func (*KeyID) XXX_MessageName() string { + return "keys.KeyID" +} + +type ListResponse struct { + Key []*KeyID `protobuf:"bytes,1,rep,name=key" json:"key,omitempty"` +} + +func (m *ListResponse) Reset() { *m = ListResponse{} } +func (m *ListResponse) String() string { return proto.CompactTextString(m) } +func (*ListResponse) ProtoMessage() {} +func (*ListResponse) Descriptor() ([]byte, []int) { return fileDescriptorKeys, []int{20} } + +func (m *ListResponse) GetKey() []*KeyID { + if m != nil { + return m.Key + } + return nil +} + +func (*ListResponse) XXX_MessageName() string { + return "keys.ListResponse" +} + +type AddNameRequest struct { + Keyname string `protobuf:"bytes,1,opt,name=Keyname,proto3" json:"Keyname,omitempty"` + Address string `protobuf:"bytes,2,opt,name=Address,proto3" json:"Address,omitempty"` +} + +func (m *AddNameRequest) Reset() { *m = AddNameRequest{} } +func (m *AddNameRequest) String() string { return proto.CompactTextString(m) } +func (*AddNameRequest) ProtoMessage() {} +func (*AddNameRequest) Descriptor() ([]byte, []int) { return fileDescriptorKeys, []int{21} } + +func (m *AddNameRequest) GetKeyname() string { + if m != nil { + return m.Keyname + } + return "" +} + +func (m *AddNameRequest) GetAddress() string { + if m != nil { + return m.Address + } + return "" +} + +func (*AddNameRequest) XXX_MessageName() string { + return "keys.AddNameRequest" +} +func init() { + proto.RegisterType((*ListRequest)(nil), "keys.ListRequest") + golang_proto.RegisterType((*ListRequest)(nil), "keys.ListRequest") + proto.RegisterType((*VerifyResponse)(nil), "keys.VerifyResponse") + golang_proto.RegisterType((*VerifyResponse)(nil), "keys.VerifyResponse") + proto.RegisterType((*RemoveNameResponse)(nil), "keys.RemoveNameResponse") + golang_proto.RegisterType((*RemoveNameResponse)(nil), "keys.RemoveNameResponse") + proto.RegisterType((*AddNameResponse)(nil), "keys.AddNameResponse") + golang_proto.RegisterType((*AddNameResponse)(nil), "keys.AddNameResponse") + proto.RegisterType((*RemoveNameRequest)(nil), "keys.RemoveNameRequest") + golang_proto.RegisterType((*RemoveNameRequest)(nil), "keys.RemoveNameRequest") + proto.RegisterType((*GenRequest)(nil), "keys.GenRequest") + golang_proto.RegisterType((*GenRequest)(nil), "keys.GenRequest") + proto.RegisterType((*GenResponse)(nil), "keys.GenResponse") + golang_proto.RegisterType((*GenResponse)(nil), "keys.GenResponse") + proto.RegisterType((*PubRequest)(nil), "keys.PubRequest") + golang_proto.RegisterType((*PubRequest)(nil), "keys.PubRequest") + proto.RegisterType((*PubResponse)(nil), "keys.PubResponse") + golang_proto.RegisterType((*PubResponse)(nil), "keys.PubResponse") + proto.RegisterType((*ImportJSONRequest)(nil), "keys.ImportJSONRequest") + golang_proto.RegisterType((*ImportJSONRequest)(nil), "keys.ImportJSONRequest") + proto.RegisterType((*ImportResponse)(nil), "keys.ImportResponse") + golang_proto.RegisterType((*ImportResponse)(nil), "keys.ImportResponse") + proto.RegisterType((*ImportRequest)(nil), "keys.ImportRequest") + golang_proto.RegisterType((*ImportRequest)(nil), "keys.ImportRequest") + proto.RegisterType((*ExportRequest)(nil), "keys.ExportRequest") + golang_proto.RegisterType((*ExportRequest)(nil), "keys.ExportRequest") + proto.RegisterType((*ExportResponse)(nil), "keys.ExportResponse") + golang_proto.RegisterType((*ExportResponse)(nil), "keys.ExportResponse") + proto.RegisterType((*SignRequest)(nil), "keys.SignRequest") + golang_proto.RegisterType((*SignRequest)(nil), "keys.SignRequest") + proto.RegisterType((*SignResponse)(nil), "keys.SignResponse") + golang_proto.RegisterType((*SignResponse)(nil), "keys.SignResponse") + proto.RegisterType((*VerifyRequest)(nil), "keys.VerifyRequest") + golang_proto.RegisterType((*VerifyRequest)(nil), "keys.VerifyRequest") + proto.RegisterType((*HashRequest)(nil), "keys.HashRequest") + golang_proto.RegisterType((*HashRequest)(nil), "keys.HashRequest") + proto.RegisterType((*HashResponse)(nil), "keys.HashResponse") + golang_proto.RegisterType((*HashResponse)(nil), "keys.HashResponse") + proto.RegisterType((*KeyID)(nil), "keys.KeyID") + golang_proto.RegisterType((*KeyID)(nil), "keys.KeyID") + proto.RegisterType((*ListResponse)(nil), "keys.ListResponse") + golang_proto.RegisterType((*ListResponse)(nil), "keys.ListResponse") + proto.RegisterType((*AddNameRequest)(nil), "keys.AddNameRequest") + golang_proto.RegisterType((*AddNameRequest)(nil), "keys.AddNameRequest") +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// Client API for Keys service + +type KeysClient interface { + GenerateKey(ctx context.Context, in *GenRequest, opts ...grpc.CallOption) (*GenResponse, error) + PublicKey(ctx context.Context, in *PubRequest, opts ...grpc.CallOption) (*PubResponse, error) + Sign(ctx context.Context, in *SignRequest, opts ...grpc.CallOption) (*SignResponse, error) + Verify(ctx context.Context, in *VerifyRequest, opts ...grpc.CallOption) (*VerifyResponse, error) + Import(ctx context.Context, in *ImportRequest, opts ...grpc.CallOption) (*ImportResponse, error) + ImportJSON(ctx context.Context, in *ImportJSONRequest, opts ...grpc.CallOption) (*ImportResponse, error) + Export(ctx context.Context, in *ExportRequest, opts ...grpc.CallOption) (*ExportResponse, error) + Hash(ctx context.Context, in *HashRequest, opts ...grpc.CallOption) (*HashResponse, error) + RemoveName(ctx context.Context, in *RemoveNameRequest, opts ...grpc.CallOption) (*RemoveNameResponse, error) + List(ctx context.Context, in *ListRequest, opts ...grpc.CallOption) (*ListResponse, error) + AddName(ctx context.Context, in *AddNameRequest, opts ...grpc.CallOption) (*AddNameResponse, error) +} + +type keysClient struct { + cc *grpc.ClientConn +} + +func NewKeysClient(cc *grpc.ClientConn) KeysClient { + return &keysClient{cc} +} + +func (c *keysClient) GenerateKey(ctx context.Context, in *GenRequest, opts ...grpc.CallOption) (*GenResponse, error) { + out := new(GenResponse) + err := grpc.Invoke(ctx, "/keys.Keys/GenerateKey", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *keysClient) PublicKey(ctx context.Context, in *PubRequest, opts ...grpc.CallOption) (*PubResponse, error) { + out := new(PubResponse) + err := grpc.Invoke(ctx, "/keys.Keys/PublicKey", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *keysClient) Sign(ctx context.Context, in *SignRequest, opts ...grpc.CallOption) (*SignResponse, error) { + out := new(SignResponse) + err := grpc.Invoke(ctx, "/keys.Keys/Sign", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *keysClient) Verify(ctx context.Context, in *VerifyRequest, opts ...grpc.CallOption) (*VerifyResponse, error) { + out := new(VerifyResponse) + err := grpc.Invoke(ctx, "/keys.Keys/Verify", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *keysClient) Import(ctx context.Context, in *ImportRequest, opts ...grpc.CallOption) (*ImportResponse, error) { + out := new(ImportResponse) + err := grpc.Invoke(ctx, "/keys.Keys/Import", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *keysClient) ImportJSON(ctx context.Context, in *ImportJSONRequest, opts ...grpc.CallOption) (*ImportResponse, error) { + out := new(ImportResponse) + err := grpc.Invoke(ctx, "/keys.Keys/ImportJSON", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *keysClient) Export(ctx context.Context, in *ExportRequest, opts ...grpc.CallOption) (*ExportResponse, error) { + out := new(ExportResponse) + err := grpc.Invoke(ctx, "/keys.Keys/Export", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *keysClient) Hash(ctx context.Context, in *HashRequest, opts ...grpc.CallOption) (*HashResponse, error) { + out := new(HashResponse) + err := grpc.Invoke(ctx, "/keys.Keys/Hash", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *keysClient) RemoveName(ctx context.Context, in *RemoveNameRequest, opts ...grpc.CallOption) (*RemoveNameResponse, error) { + out := new(RemoveNameResponse) + err := grpc.Invoke(ctx, "/keys.Keys/RemoveName", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *keysClient) List(ctx context.Context, in *ListRequest, opts ...grpc.CallOption) (*ListResponse, error) { + out := new(ListResponse) + err := grpc.Invoke(ctx, "/keys.Keys/List", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *keysClient) AddName(ctx context.Context, in *AddNameRequest, opts ...grpc.CallOption) (*AddNameResponse, error) { + out := new(AddNameResponse) + err := grpc.Invoke(ctx, "/keys.Keys/AddName", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// Server API for Keys service + +type KeysServer interface { + GenerateKey(context.Context, *GenRequest) (*GenResponse, error) + PublicKey(context.Context, *PubRequest) (*PubResponse, error) + Sign(context.Context, *SignRequest) (*SignResponse, error) + Verify(context.Context, *VerifyRequest) (*VerifyResponse, error) + Import(context.Context, *ImportRequest) (*ImportResponse, error) + ImportJSON(context.Context, *ImportJSONRequest) (*ImportResponse, error) + Export(context.Context, *ExportRequest) (*ExportResponse, error) + Hash(context.Context, *HashRequest) (*HashResponse, error) + RemoveName(context.Context, *RemoveNameRequest) (*RemoveNameResponse, error) + List(context.Context, *ListRequest) (*ListResponse, error) + AddName(context.Context, *AddNameRequest) (*AddNameResponse, error) +} + +func RegisterKeysServer(s *grpc.Server, srv KeysServer) { + s.RegisterService(&_Keys_serviceDesc, srv) +} + +func _Keys_GenerateKey_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GenRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(KeysServer).GenerateKey(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/keys.Keys/GenerateKey", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(KeysServer).GenerateKey(ctx, req.(*GenRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Keys_PublicKey_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(PubRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(KeysServer).PublicKey(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/keys.Keys/PublicKey", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(KeysServer).PublicKey(ctx, req.(*PubRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Keys_Sign_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SignRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(KeysServer).Sign(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/keys.Keys/Sign", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(KeysServer).Sign(ctx, req.(*SignRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Keys_Verify_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(VerifyRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(KeysServer).Verify(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/keys.Keys/Verify", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(KeysServer).Verify(ctx, req.(*VerifyRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Keys_Import_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ImportRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(KeysServer).Import(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/keys.Keys/Import", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(KeysServer).Import(ctx, req.(*ImportRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Keys_ImportJSON_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ImportJSONRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(KeysServer).ImportJSON(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/keys.Keys/ImportJSON", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(KeysServer).ImportJSON(ctx, req.(*ImportJSONRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Keys_Export_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ExportRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(KeysServer).Export(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/keys.Keys/Export", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(KeysServer).Export(ctx, req.(*ExportRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Keys_Hash_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(HashRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(KeysServer).Hash(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/keys.Keys/Hash", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(KeysServer).Hash(ctx, req.(*HashRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Keys_RemoveName_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RemoveNameRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(KeysServer).RemoveName(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/keys.Keys/RemoveName", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(KeysServer).RemoveName(ctx, req.(*RemoveNameRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Keys_List_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ListRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(KeysServer).List(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/keys.Keys/List", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(KeysServer).List(ctx, req.(*ListRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Keys_AddName_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(AddNameRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(KeysServer).AddName(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/keys.Keys/AddName", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(KeysServer).AddName(ctx, req.(*AddNameRequest)) + } + return interceptor(ctx, in, info, handler) +} + +var _Keys_serviceDesc = grpc.ServiceDesc{ + ServiceName: "keys.Keys", + HandlerType: (*KeysServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "GenerateKey", + Handler: _Keys_GenerateKey_Handler, + }, + { + MethodName: "PublicKey", + Handler: _Keys_PublicKey_Handler, + }, + { + MethodName: "Sign", + Handler: _Keys_Sign_Handler, + }, + { + MethodName: "Verify", + Handler: _Keys_Verify_Handler, + }, + { + MethodName: "Import", + Handler: _Keys_Import_Handler, + }, + { + MethodName: "ImportJSON", + Handler: _Keys_ImportJSON_Handler, + }, + { + MethodName: "Export", + Handler: _Keys_Export_Handler, + }, + { + MethodName: "Hash", + Handler: _Keys_Hash_Handler, + }, + { + MethodName: "RemoveName", + Handler: _Keys_RemoveName_Handler, + }, + { + MethodName: "List", + Handler: _Keys_List_Handler, + }, + { + MethodName: "AddName", + Handler: _Keys_AddName_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "keys.proto", +} + +func (m *ListRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ListRequest) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + return i, nil +} + +func (m *VerifyResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *VerifyResponse) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + return i, nil +} + +func (m *RemoveNameResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RemoveNameResponse) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + return i, nil +} + +func (m *AddNameResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *AddNameResponse) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + return i, nil +} + +func (m *RemoveNameRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *RemoveNameRequest) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.KeyName) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.KeyName))) + i += copy(dAtA[i:], m.KeyName) + } + return i, nil +} + +func (m *GenRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GenRequest) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Passphrase) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Passphrase))) + i += copy(dAtA[i:], m.Passphrase) + } + if len(m.CurveType) > 0 { + dAtA[i] = 0x12 + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.CurveType))) + i += copy(dAtA[i:], m.CurveType) + } + if len(m.KeyName) > 0 { + dAtA[i] = 0x1a + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.KeyName))) + i += copy(dAtA[i:], m.KeyName) + } + return i, nil +} + +func (m *GenResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GenResponse) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Address) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Address))) + i += copy(dAtA[i:], m.Address) + } + return i, nil +} + +func (m *PubRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PubRequest) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Address) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Address))) + i += copy(dAtA[i:], m.Address) + } + if len(m.Name) > 0 { + dAtA[i] = 0x12 + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Name))) + i += copy(dAtA[i:], m.Name) + } + return i, nil +} + +func (m *PubResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PubResponse) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.PublicKey) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.PublicKey))) + i += copy(dAtA[i:], m.PublicKey) + } + if len(m.CurveType) > 0 { + dAtA[i] = 0x12 + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.CurveType))) + i += copy(dAtA[i:], m.CurveType) + } + return i, nil +} + +func (m *ImportJSONRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ImportJSONRequest) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Passphrase) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Passphrase))) + i += copy(dAtA[i:], m.Passphrase) + } + if len(m.JSON) > 0 { + dAtA[i] = 0x12 + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.JSON))) + i += copy(dAtA[i:], m.JSON) + } + return i, nil +} + +func (m *ImportResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ImportResponse) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Address) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Address))) + i += copy(dAtA[i:], m.Address) + } + return i, nil +} + +func (m *ImportRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ImportRequest) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Passphrase) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Passphrase))) + i += copy(dAtA[i:], m.Passphrase) + } + if len(m.Name) > 0 { + dAtA[i] = 0x12 + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Name))) + i += copy(dAtA[i:], m.Name) + } + if len(m.CurveType) > 0 { + dAtA[i] = 0x1a + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.CurveType))) + i += copy(dAtA[i:], m.CurveType) + } + if len(m.KeyBytes) > 0 { + dAtA[i] = 0x22 + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.KeyBytes))) + i += copy(dAtA[i:], m.KeyBytes) + } + return i, nil +} + +func (m *ExportRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ExportRequest) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Passphrase) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Passphrase))) + i += copy(dAtA[i:], m.Passphrase) + } + if len(m.Name) > 0 { + dAtA[i] = 0x12 + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Name))) + i += copy(dAtA[i:], m.Name) + } + if len(m.Address) > 0 { + dAtA[i] = 0x1a + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Address))) + i += copy(dAtA[i:], m.Address) + } + return i, nil +} + +func (m *ExportResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ExportResponse) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Publickey) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Publickey))) + i += copy(dAtA[i:], m.Publickey) + } + if len(m.Privatekey) > 0 { + dAtA[i] = 0x12 + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Privatekey))) + i += copy(dAtA[i:], m.Privatekey) + } + if len(m.Address) > 0 { + dAtA[i] = 0x1a + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Address))) + i += copy(dAtA[i:], m.Address) + } + if len(m.CurveType) > 0 { + dAtA[i] = 0x22 + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.CurveType))) + i += copy(dAtA[i:], m.CurveType) + } + return i, nil +} + +func (m *SignRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *SignRequest) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Passphrase) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Passphrase))) + i += copy(dAtA[i:], m.Passphrase) + } + if len(m.Address) > 0 { + dAtA[i] = 0x12 + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Address))) + i += copy(dAtA[i:], m.Address) + } + if len(m.Name) > 0 { + dAtA[i] = 0x1a + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Name))) + i += copy(dAtA[i:], m.Name) + } + if len(m.Message) > 0 { + dAtA[i] = 0x22 + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Message))) + i += copy(dAtA[i:], m.Message) + } + return i, nil +} + +func (m *SignResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *SignResponse) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Signature) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Signature))) + i += copy(dAtA[i:], m.Signature) + } + if len(m.CurveType) > 0 { + dAtA[i] = 0x12 + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.CurveType))) + i += copy(dAtA[i:], m.CurveType) + } + return i, nil +} + +func (m *VerifyRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *VerifyRequest) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.CurveType) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.CurveType))) + i += copy(dAtA[i:], m.CurveType) + } + if len(m.PublicKey) > 0 { + dAtA[i] = 0x12 + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.PublicKey))) + i += copy(dAtA[i:], m.PublicKey) + } + if len(m.Message) > 0 { + dAtA[i] = 0x1a + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Message))) + i += copy(dAtA[i:], m.Message) + } + if len(m.Signature) > 0 { + dAtA[i] = 0x22 + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Signature))) + i += copy(dAtA[i:], m.Signature) + } + return i, nil +} + +func (m *HashRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *HashRequest) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Hashtype) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Hashtype))) + i += copy(dAtA[i:], m.Hashtype) + } + if len(m.Message) > 0 { + dAtA[i] = 0x12 + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Message))) + i += copy(dAtA[i:], m.Message) + } + return i, nil +} + +func (m *HashResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *HashResponse) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Hash) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Hash))) + i += copy(dAtA[i:], m.Hash) + } + return i, nil +} + +func (m *KeyID) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *KeyID) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Address) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Address))) + i += copy(dAtA[i:], m.Address) + } + if len(m.KeyName) > 0 { + dAtA[i] = 0x12 + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.KeyName))) + i += copy(dAtA[i:], m.KeyName) + } + return i, nil +} + +func (m *ListResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ListResponse) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Key) > 0 { + for _, msg := range m.Key { + dAtA[i] = 0xa + i++ + i = encodeVarintKeys(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + return i, nil +} + +func (m *AddNameRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *AddNameRequest) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Keyname) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Keyname))) + i += copy(dAtA[i:], m.Keyname) + } + if len(m.Address) > 0 { + dAtA[i] = 0x12 + i++ + i = encodeVarintKeys(dAtA, i, uint64(len(m.Address))) + i += copy(dAtA[i:], m.Address) + } + return i, nil +} + +func encodeVarintKeys(dAtA []byte, offset int, v uint64) int { + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return offset + 1 +} +func (m *ListRequest) Size() (n int) { + var l int + _ = l + return n +} + +func (m *VerifyResponse) Size() (n int) { + var l int + _ = l + return n +} + +func (m *RemoveNameResponse) Size() (n int) { + var l int + _ = l + return n +} + +func (m *AddNameResponse) Size() (n int) { + var l int + _ = l + return n +} + +func (m *RemoveNameRequest) Size() (n int) { + var l int + _ = l + l = len(m.KeyName) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + return n +} + +func (m *GenRequest) Size() (n int) { + var l int + _ = l + l = len(m.Passphrase) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.CurveType) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.KeyName) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + return n +} + +func (m *GenResponse) Size() (n int) { + var l int + _ = l + l = len(m.Address) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + return n +} + +func (m *PubRequest) Size() (n int) { + var l int + _ = l + l = len(m.Address) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.Name) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + return n +} + +func (m *PubResponse) Size() (n int) { + var l int + _ = l + l = len(m.PublicKey) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.CurveType) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + return n +} + +func (m *ImportJSONRequest) Size() (n int) { + var l int + _ = l + l = len(m.Passphrase) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.JSON) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + return n +} + +func (m *ImportResponse) Size() (n int) { + var l int + _ = l + l = len(m.Address) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + return n +} + +func (m *ImportRequest) Size() (n int) { + var l int + _ = l + l = len(m.Passphrase) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.Name) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.CurveType) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.KeyBytes) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + return n +} + +func (m *ExportRequest) Size() (n int) { + var l int + _ = l + l = len(m.Passphrase) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.Name) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.Address) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + return n +} + +func (m *ExportResponse) Size() (n int) { + var l int + _ = l + l = len(m.Publickey) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.Privatekey) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.Address) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.CurveType) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + return n +} + +func (m *SignRequest) Size() (n int) { + var l int + _ = l + l = len(m.Passphrase) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.Address) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.Name) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.Message) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + return n +} + +func (m *SignResponse) Size() (n int) { + var l int + _ = l + l = len(m.Signature) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.CurveType) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + return n +} + +func (m *VerifyRequest) Size() (n int) { + var l int + _ = l + l = len(m.CurveType) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.PublicKey) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.Message) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.Signature) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + return n +} + +func (m *HashRequest) Size() (n int) { + var l int + _ = l + l = len(m.Hashtype) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.Message) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + return n +} + +func (m *HashResponse) Size() (n int) { + var l int + _ = l + l = len(m.Hash) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + return n +} + +func (m *KeyID) Size() (n int) { + var l int + _ = l + l = len(m.Address) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.KeyName) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + return n +} + +func (m *ListResponse) Size() (n int) { + var l int + _ = l + if len(m.Key) > 0 { + for _, e := range m.Key { + l = e.Size() + n += 1 + l + sovKeys(uint64(l)) + } + } + return n +} + +func (m *AddNameRequest) Size() (n int) { + var l int + _ = l + l = len(m.Keyname) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + l = len(m.Address) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + return n +} + +func sovKeys(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n +} +func sozKeys(x uint64) (n int) { + return sovKeys(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *ListRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ListRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ListRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *VerifyResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: VerifyResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: VerifyResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *RemoveNameResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RemoveNameResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RemoveNameResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *AddNameResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: AddNameResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: AddNameResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *RemoveNameRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: RemoveNameRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: RemoveNameRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field KeyName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.KeyName = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *GenRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GenRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GenRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Passphrase", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Passphrase = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CurveType", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.CurveType = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field KeyName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.KeyName = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *GenResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GenResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GenResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PubRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PubRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PubRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PubResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PubResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PubResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PublicKey", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PublicKey = append(m.PublicKey[:0], dAtA[iNdEx:postIndex]...) + if m.PublicKey == nil { + m.PublicKey = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CurveType", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.CurveType = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ImportJSONRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ImportJSONRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ImportJSONRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Passphrase", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Passphrase = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field JSON", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.JSON = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ImportResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ImportResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ImportResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ImportRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ImportRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ImportRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Passphrase", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Passphrase = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CurveType", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.CurveType = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field KeyBytes", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.KeyBytes = append(m.KeyBytes[:0], dAtA[iNdEx:postIndex]...) + if m.KeyBytes == nil { + m.KeyBytes = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ExportRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ExportRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ExportRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Passphrase", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Passphrase = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ExportResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ExportResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ExportResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Publickey", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Publickey = append(m.Publickey[:0], dAtA[iNdEx:postIndex]...) + if m.Publickey == nil { + m.Publickey = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Privatekey", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Privatekey = append(m.Privatekey[:0], dAtA[iNdEx:postIndex]...) + if m.Privatekey == nil { + m.Privatekey = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = append(m.Address[:0], dAtA[iNdEx:postIndex]...) + if m.Address == nil { + m.Address = []byte{} + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CurveType", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.CurveType = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *SignRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: SignRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SignRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Passphrase", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Passphrase = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Message = append(m.Message[:0], dAtA[iNdEx:postIndex]...) + if m.Message == nil { + m.Message = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *SignResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: SignResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SignResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Signature", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Signature = append(m.Signature[:0], dAtA[iNdEx:postIndex]...) + if m.Signature == nil { + m.Signature = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CurveType", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.CurveType = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *VerifyRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: VerifyRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: VerifyRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CurveType", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.CurveType = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PublicKey", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PublicKey = append(m.PublicKey[:0], dAtA[iNdEx:postIndex]...) + if m.PublicKey == nil { + m.PublicKey = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Message = append(m.Message[:0], dAtA[iNdEx:postIndex]...) + if m.Message == nil { + m.Message = []byte{} + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Signature", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Signature = append(m.Signature[:0], dAtA[iNdEx:postIndex]...) + if m.Signature == nil { + m.Signature = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *HashRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: HashRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: HashRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Hashtype", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Hashtype = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Message = append(m.Message[:0], dAtA[iNdEx:postIndex]...) + if m.Message == nil { + m.Message = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *HashResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: HashResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: HashResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Hash", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Hash = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *KeyID) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: KeyID: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: KeyID: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field KeyName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.KeyName = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ListResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ListResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ListResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Key = append(m.Key, &KeyID{}) + if err := m.Key[len(m.Key)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *AddNameRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: AddNameRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: AddNameRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Keyname", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Keyname = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipKeys(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowKeys + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowKeys + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowKeys + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + iNdEx += length + if length < 0 { + return 0, ErrInvalidLengthKeys + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowKeys + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipKeys(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} + +var ( + ErrInvalidLengthKeys = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowKeys = fmt.Errorf("proto: integer overflow") +) + +func init() { proto.RegisterFile("keys.proto", fileDescriptorKeys) } +func init() { golang_proto.RegisterFile("keys.proto", fileDescriptorKeys) } + +var fileDescriptorKeys = []byte{ + // 759 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x56, 0x4d, 0x6f, 0xd3, 0x4c, + 0x10, 0x96, 0x63, 0xbf, 0x7d, 0xdb, 0x71, 0x92, 0xb7, 0xf1, 0x5b, 0x44, 0x64, 0x95, 0x08, 0xed, + 0x85, 0x0a, 0x29, 0x0d, 0x6a, 0x25, 0x84, 0xe8, 0x01, 0xf5, 0x03, 0x95, 0x36, 0x50, 0xaa, 0x14, + 0x71, 0x40, 0xe2, 0xe0, 0x34, 0xd3, 0x24, 0x6a, 0x13, 0x87, 0x5d, 0xbb, 0xe0, 0x03, 0x27, 0x24, + 0x7e, 0x17, 0xc7, 0x9e, 0x10, 0x3f, 0x01, 0xb5, 0x7f, 0x04, 0xed, 0xae, 0x37, 0xde, 0xdd, 0x96, + 0x12, 0x89, 0xdb, 0xce, 0xec, 0xcc, 0x3e, 0xf3, 0xf1, 0xe4, 0x71, 0x00, 0x4e, 0x31, 0x63, 0xab, + 0x13, 0x1a, 0x27, 0x71, 0xe0, 0xf1, 0x73, 0xd8, 0xec, 0x0f, 0x93, 0x41, 0xda, 0x5d, 0x3d, 0x8e, + 0x47, 0xad, 0x7e, 0xdc, 0x8f, 0x5b, 0xe2, 0xb2, 0x9b, 0x9e, 0x08, 0x4b, 0x18, 0xe2, 0x24, 0x93, + 0x48, 0x05, 0xfc, 0x97, 0x43, 0x96, 0x74, 0xf0, 0x43, 0x8a, 0x2c, 0x21, 0x8b, 0x50, 0x7d, 0x8b, + 0x74, 0x78, 0x92, 0x75, 0x90, 0x4d, 0xe2, 0x31, 0x43, 0xb2, 0x04, 0x41, 0x07, 0x47, 0xf1, 0x39, + 0x1e, 0x44, 0x23, 0x9c, 0x7a, 0x6b, 0xf0, 0xdf, 0x66, 0xaf, 0x67, 0xb8, 0x9a, 0x50, 0xd3, 0x03, + 0xc5, 0x7b, 0x41, 0x1d, 0xfe, 0x6d, 0x63, 0xc6, 0x3d, 0x75, 0xe7, 0xbe, 0xb3, 0xb2, 0xd0, 0x51, + 0x26, 0xe9, 0x01, 0xec, 0xe2, 0x58, 0xc5, 0x35, 0x00, 0x0e, 0x23, 0xc6, 0x26, 0x03, 0x1a, 0x31, + 0x15, 0xaa, 0x79, 0x82, 0x65, 0x58, 0xd8, 0x4e, 0xe9, 0x39, 0xbe, 0xc9, 0x26, 0x58, 0x2f, 0x89, + 0xeb, 0xc2, 0xa1, 0xa3, 0xb8, 0x26, 0xca, 0x03, 0xf0, 0x05, 0x8a, 0xac, 0x91, 0x07, 0x6e, 0xf6, + 0x7a, 0x14, 0x19, 0x53, 0xe5, 0xe4, 0x26, 0x79, 0x0a, 0x70, 0x98, 0x76, 0xb5, 0xb2, 0x6f, 0x8e, + 0x0b, 0x02, 0xf0, 0x04, 0x8e, 0xac, 0x41, 0x9c, 0xc9, 0x1e, 0xf8, 0x22, 0x37, 0x07, 0x59, 0x86, + 0x85, 0xc3, 0xb4, 0x7b, 0x36, 0x3c, 0x6e, 0x63, 0x26, 0xd2, 0xcb, 0x9d, 0xc2, 0x71, 0x7b, 0x27, + 0x64, 0x17, 0x6a, 0x7b, 0xa3, 0x49, 0x4c, 0x93, 0xfd, 0xa3, 0xd7, 0x07, 0xb3, 0x0e, 0x27, 0x00, + 0x8f, 0x87, 0xab, 0x9a, 0xf8, 0x99, 0x3c, 0x84, 0xaa, 0x7c, 0x68, 0x86, 0xde, 0x3f, 0x43, 0x45, + 0xc5, 0xce, 0x0c, 0x68, 0x0f, 0xc1, 0xec, 0xcb, 0xb5, 0x37, 0x14, 0xc2, 0x7c, 0x1b, 0xb3, 0xad, + 0x2c, 0x41, 0x56, 0xf7, 0xc4, 0x48, 0xa6, 0x36, 0x79, 0x0f, 0x95, 0xe7, 0x9f, 0xfe, 0x16, 0x5e, + 0xeb, 0xce, 0x35, 0xbb, 0xfb, 0xea, 0x40, 0x55, 0xbd, 0x6f, 0x6f, 0xe8, 0xd4, 0xde, 0xd0, 0x29, + 0x66, 0x02, 0x9e, 0x0e, 0xcf, 0xa3, 0x04, 0xf9, 0x75, 0x49, 0x5c, 0x6b, 0x1e, 0x1b, 0xaa, 0x5c, + 0x90, 0xc3, 0x98, 0x81, 0x67, 0xef, 0x36, 0x05, 0xff, 0x68, 0xd8, 0x9f, 0x99, 0xf2, 0x1a, 0x4c, + 0xe9, 0x66, 0x0e, 0xba, 0x66, 0xff, 0xaf, 0x90, 0xb1, 0xa8, 0x8f, 0xf9, 0x7c, 0x95, 0x49, 0xf6, + 0xa1, 0x2c, 0x61, 0x8b, 0xe6, 0xb9, 0x1d, 0x25, 0x29, 0x45, 0xd5, 0xfc, 0xd4, 0xf1, 0x07, 0x7a, + 0x7e, 0x71, 0xa0, 0xa2, 0xf4, 0x41, 0x76, 0x61, 0xc4, 0x3b, 0xf6, 0xda, 0x8d, 0x9f, 0x42, 0xc9, + 0xfe, 0x29, 0x68, 0x35, 0xbb, 0x46, 0xcd, 0x66, 0x8d, 0x9e, 0x55, 0x23, 0xd9, 0x06, 0xff, 0x45, + 0xc4, 0x06, 0xaa, 0x84, 0x10, 0xe6, 0xb9, 0x99, 0x14, 0x15, 0x4c, 0x6d, 0x1d, 0xa2, 0x64, 0x8e, + 0x85, 0x40, 0x59, 0x3e, 0x92, 0x8f, 0x25, 0x00, 0x8f, 0xdb, 0xf9, 0x0b, 0xe2, 0x4c, 0x36, 0xe0, + 0x9f, 0x36, 0x66, 0x7b, 0x3b, 0xb7, 0xe8, 0x81, 0x26, 0x3d, 0x25, 0x53, 0x7a, 0x9a, 0x50, 0x96, + 0xca, 0x9a, 0x03, 0xdc, 0x03, 0x57, 0xd2, 0xcd, 0x5d, 0xf1, 0xd7, 0xfc, 0x55, 0x21, 0xdc, 0xe2, + 0xf5, 0x0e, 0xf7, 0x93, 0x1d, 0xa8, 0x4e, 0x15, 0x55, 0xd7, 0xce, 0xb1, 0xa9, 0x9d, 0x63, 0x8b, + 0xec, 0x26, 0x35, 0xd6, 0xbe, 0x7b, 0xe0, 0xb5, 0x31, 0x63, 0xc1, 0x9a, 0x10, 0x3e, 0xa4, 0x51, + 0x82, 0x7c, 0xd4, 0x8b, 0x12, 0xaf, 0x50, 0xdc, 0xb0, 0xa6, 0x79, 0xf2, 0x0a, 0x1f, 0x69, 0xdb, + 0x52, 0x19, 0x85, 0x28, 0xaa, 0x0c, 0x5d, 0xea, 0x9a, 0xe0, 0xf1, 0xb5, 0x04, 0xf9, 0x95, 0x46, + 0xef, 0x30, 0xd0, 0x5d, 0x79, 0xf8, 0x3a, 0xcc, 0x49, 0xf6, 0x04, 0xff, 0xcb, 0x5b, 0x83, 0x4b, + 0xe1, 0x92, 0xe9, 0x2c, 0x92, 0xa4, 0x3a, 0xa9, 0x24, 0x43, 0xab, 0x54, 0x92, 0x25, 0x76, 0x1b, + 0x00, 0x85, 0x8e, 0x06, 0x77, 0xf5, 0x18, 0x4d, 0x59, 0x7f, 0x93, 0xbc, 0x0e, 0x73, 0x52, 0x30, + 0x14, 0xa2, 0x21, 0x4f, 0x2a, 0xc9, 0xd2, 0x94, 0xa6, 0xe4, 0x8f, 0x1a, 0x85, 0x46, 0x50, 0x35, + 0x0a, 0x83, 0x6e, 0xcf, 0x00, 0x8a, 0xaf, 0xa5, 0x2a, 0xf0, 0xda, 0xf7, 0x33, 0xac, 0x5f, 0xbf, + 0x28, 0xf0, 0x38, 0xbd, 0x14, 0x9e, 0xf6, 0x11, 0x57, 0x78, 0x06, 0xfb, 0x1e, 0x0b, 0xca, 0x08, + 0xb0, 0xbc, 0x7e, 0x93, 0x6d, 0xe1, 0x1d, 0xcb, 0x2b, 0xf3, 0xb6, 0x9e, 0x5c, 0x5c, 0x36, 0x9c, + 0x1f, 0x97, 0x0d, 0xe7, 0xe7, 0x65, 0xc3, 0xf9, 0x76, 0xd5, 0x70, 0x2e, 0xae, 0x1a, 0xce, 0x3b, + 0xa2, 0xfd, 0xc9, 0x18, 0x64, 0x13, 0xa4, 0x67, 0xd8, 0xeb, 0x23, 0x6d, 0x75, 0x53, 0x4a, 0xe3, + 0x8f, 0x2d, 0xfe, 0x52, 0x77, 0x4e, 0xfc, 0xc1, 0x58, 0xff, 0x15, 0x00, 0x00, 0xff, 0xff, 0xa9, + 0x48, 0xf7, 0x08, 0xa3, 0x08, 0x00, 0x00, +} diff --git a/keys/mock/key.go b/keys/mock/key.go index 83a7f0010..c3e0ca683 100644 --- a/keys/mock/key.go +++ b/keys/mock/key.go @@ -5,7 +5,7 @@ import ( "encoding/json" "fmt" - acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/crypto" "github.com/pkg/errors" @@ -55,7 +55,7 @@ func newKey(name string) (*Key, error) { return key, nil } -func mockKeyFromPrivateAccount(privateAccount acm.PrivateAccount) *Key { +func mockKeyFromPrivateAccount(privateAccount *acm.PrivateAccount) *Key { if privateAccount.PrivateKey().CurveType != crypto.CurveTypeEd25519 { panic(fmt.Errorf("mock key client only supports ed25519 private keys at present")) } diff --git a/keys/mock/key_client.go b/keys/mock/key_client.go index a9c646704..de5527ef9 100644 --- a/keys/mock/key_client.go +++ b/keys/mock/key_client.go @@ -17,7 +17,7 @@ package mock import ( "fmt" - acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/keys" ) @@ -32,7 +32,7 @@ type KeyClient struct { knownKeys map[crypto.Address]*Key } -func NewKeyClient(privateAccounts ...acm.PrivateAccount) *KeyClient { +func NewKeyClient(privateAccounts ...*acm.PrivateAccount) *KeyClient { client := &KeyClient{ knownKeys: make(map[crypto.Address]*Key), } diff --git a/keys/pbkeys/keys.pb.go b/keys/pbkeys/keys.pb.go deleted file mode 100644 index 320ab0419..000000000 --- a/keys/pbkeys/keys.pb.go +++ /dev/null @@ -1,1492 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: github.com/hyperledger/burrow/keys/pbkeys/keys.proto - -package pbkeys - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type ListRequest struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListRequest) Reset() { *m = ListRequest{} } -func (m *ListRequest) String() string { return proto.CompactTextString(m) } -func (*ListRequest) ProtoMessage() {} -func (*ListRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_keys_ff2cb7ec9ea3671c, []int{0} -} -func (m *ListRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListRequest.Unmarshal(m, b) -} -func (m *ListRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListRequest.Marshal(b, m, deterministic) -} -func (dst *ListRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListRequest.Merge(dst, src) -} -func (m *ListRequest) XXX_Size() int { - return xxx_messageInfo_ListRequest.Size(m) -} -func (m *ListRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ListRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ListRequest proto.InternalMessageInfo - -type VerifyResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *VerifyResponse) Reset() { *m = VerifyResponse{} } -func (m *VerifyResponse) String() string { return proto.CompactTextString(m) } -func (*VerifyResponse) ProtoMessage() {} -func (*VerifyResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_keys_ff2cb7ec9ea3671c, []int{1} -} -func (m *VerifyResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_VerifyResponse.Unmarshal(m, b) -} -func (m *VerifyResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_VerifyResponse.Marshal(b, m, deterministic) -} -func (dst *VerifyResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_VerifyResponse.Merge(dst, src) -} -func (m *VerifyResponse) XXX_Size() int { - return xxx_messageInfo_VerifyResponse.Size(m) -} -func (m *VerifyResponse) XXX_DiscardUnknown() { - xxx_messageInfo_VerifyResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_VerifyResponse proto.InternalMessageInfo - -type RemoveNameResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *RemoveNameResponse) Reset() { *m = RemoveNameResponse{} } -func (m *RemoveNameResponse) String() string { return proto.CompactTextString(m) } -func (*RemoveNameResponse) ProtoMessage() {} -func (*RemoveNameResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_keys_ff2cb7ec9ea3671c, []int{2} -} -func (m *RemoveNameResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_RemoveNameResponse.Unmarshal(m, b) -} -func (m *RemoveNameResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_RemoveNameResponse.Marshal(b, m, deterministic) -} -func (dst *RemoveNameResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_RemoveNameResponse.Merge(dst, src) -} -func (m *RemoveNameResponse) XXX_Size() int { - return xxx_messageInfo_RemoveNameResponse.Size(m) -} -func (m *RemoveNameResponse) XXX_DiscardUnknown() { - xxx_messageInfo_RemoveNameResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_RemoveNameResponse proto.InternalMessageInfo - -type AddNameResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *AddNameResponse) Reset() { *m = AddNameResponse{} } -func (m *AddNameResponse) String() string { return proto.CompactTextString(m) } -func (*AddNameResponse) ProtoMessage() {} -func (*AddNameResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_keys_ff2cb7ec9ea3671c, []int{3} -} -func (m *AddNameResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_AddNameResponse.Unmarshal(m, b) -} -func (m *AddNameResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_AddNameResponse.Marshal(b, m, deterministic) -} -func (dst *AddNameResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_AddNameResponse.Merge(dst, src) -} -func (m *AddNameResponse) XXX_Size() int { - return xxx_messageInfo_AddNameResponse.Size(m) -} -func (m *AddNameResponse) XXX_DiscardUnknown() { - xxx_messageInfo_AddNameResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_AddNameResponse proto.InternalMessageInfo - -type RemoveNameRequest struct { - Keyname string `protobuf:"bytes,1,opt,name=keyname,proto3" json:"keyname,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *RemoveNameRequest) Reset() { *m = RemoveNameRequest{} } -func (m *RemoveNameRequest) String() string { return proto.CompactTextString(m) } -func (*RemoveNameRequest) ProtoMessage() {} -func (*RemoveNameRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_keys_ff2cb7ec9ea3671c, []int{4} -} -func (m *RemoveNameRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_RemoveNameRequest.Unmarshal(m, b) -} -func (m *RemoveNameRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_RemoveNameRequest.Marshal(b, m, deterministic) -} -func (dst *RemoveNameRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_RemoveNameRequest.Merge(dst, src) -} -func (m *RemoveNameRequest) XXX_Size() int { - return xxx_messageInfo_RemoveNameRequest.Size(m) -} -func (m *RemoveNameRequest) XXX_DiscardUnknown() { - xxx_messageInfo_RemoveNameRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_RemoveNameRequest proto.InternalMessageInfo - -func (m *RemoveNameRequest) GetKeyname() string { - if m != nil { - return m.Keyname - } - return "" -} - -type GenRequest struct { - Passphrase string `protobuf:"bytes,1,opt,name=passphrase,proto3" json:"passphrase,omitempty"` - Curvetype string `protobuf:"bytes,2,opt,name=curvetype,proto3" json:"curvetype,omitempty"` - Keyname string `protobuf:"bytes,3,opt,name=keyname,proto3" json:"keyname,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GenRequest) Reset() { *m = GenRequest{} } -func (m *GenRequest) String() string { return proto.CompactTextString(m) } -func (*GenRequest) ProtoMessage() {} -func (*GenRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_keys_ff2cb7ec9ea3671c, []int{5} -} -func (m *GenRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GenRequest.Unmarshal(m, b) -} -func (m *GenRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GenRequest.Marshal(b, m, deterministic) -} -func (dst *GenRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenRequest.Merge(dst, src) -} -func (m *GenRequest) XXX_Size() int { - return xxx_messageInfo_GenRequest.Size(m) -} -func (m *GenRequest) XXX_DiscardUnknown() { - xxx_messageInfo_GenRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_GenRequest proto.InternalMessageInfo - -func (m *GenRequest) GetPassphrase() string { - if m != nil { - return m.Passphrase - } - return "" -} - -func (m *GenRequest) GetCurvetype() string { - if m != nil { - return m.Curvetype - } - return "" -} - -func (m *GenRequest) GetKeyname() string { - if m != nil { - return m.Keyname - } - return "" -} - -type GenResponse struct { - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GenResponse) Reset() { *m = GenResponse{} } -func (m *GenResponse) String() string { return proto.CompactTextString(m) } -func (*GenResponse) ProtoMessage() {} -func (*GenResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_keys_ff2cb7ec9ea3671c, []int{6} -} -func (m *GenResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GenResponse.Unmarshal(m, b) -} -func (m *GenResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GenResponse.Marshal(b, m, deterministic) -} -func (dst *GenResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenResponse.Merge(dst, src) -} -func (m *GenResponse) XXX_Size() int { - return xxx_messageInfo_GenResponse.Size(m) -} -func (m *GenResponse) XXX_DiscardUnknown() { - xxx_messageInfo_GenResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_GenResponse proto.InternalMessageInfo - -func (m *GenResponse) GetAddress() string { - if m != nil { - return m.Address - } - return "" -} - -type PubRequest struct { - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PubRequest) Reset() { *m = PubRequest{} } -func (m *PubRequest) String() string { return proto.CompactTextString(m) } -func (*PubRequest) ProtoMessage() {} -func (*PubRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_keys_ff2cb7ec9ea3671c, []int{7} -} -func (m *PubRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PubRequest.Unmarshal(m, b) -} -func (m *PubRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PubRequest.Marshal(b, m, deterministic) -} -func (dst *PubRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_PubRequest.Merge(dst, src) -} -func (m *PubRequest) XXX_Size() int { - return xxx_messageInfo_PubRequest.Size(m) -} -func (m *PubRequest) XXX_DiscardUnknown() { - xxx_messageInfo_PubRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_PubRequest proto.InternalMessageInfo - -func (m *PubRequest) GetAddress() string { - if m != nil { - return m.Address - } - return "" -} - -func (m *PubRequest) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -type PubResponse struct { - Pub []byte `protobuf:"bytes,1,opt,name=pub,proto3" json:"pub,omitempty"` - Curvetype string `protobuf:"bytes,2,opt,name=curvetype,proto3" json:"curvetype,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PubResponse) Reset() { *m = PubResponse{} } -func (m *PubResponse) String() string { return proto.CompactTextString(m) } -func (*PubResponse) ProtoMessage() {} -func (*PubResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_keys_ff2cb7ec9ea3671c, []int{8} -} -func (m *PubResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PubResponse.Unmarshal(m, b) -} -func (m *PubResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PubResponse.Marshal(b, m, deterministic) -} -func (dst *PubResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_PubResponse.Merge(dst, src) -} -func (m *PubResponse) XXX_Size() int { - return xxx_messageInfo_PubResponse.Size(m) -} -func (m *PubResponse) XXX_DiscardUnknown() { - xxx_messageInfo_PubResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_PubResponse proto.InternalMessageInfo - -func (m *PubResponse) GetPub() []byte { - if m != nil { - return m.Pub - } - return nil -} - -func (m *PubResponse) GetCurvetype() string { - if m != nil { - return m.Curvetype - } - return "" -} - -type ImportJSONRequest struct { - Passphrase string `protobuf:"bytes,1,opt,name=passphrase,proto3" json:"passphrase,omitempty"` - JSON string `protobuf:"bytes,2,opt,name=JSON,proto3" json:"JSON,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ImportJSONRequest) Reset() { *m = ImportJSONRequest{} } -func (m *ImportJSONRequest) String() string { return proto.CompactTextString(m) } -func (*ImportJSONRequest) ProtoMessage() {} -func (*ImportJSONRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_keys_ff2cb7ec9ea3671c, []int{9} -} -func (m *ImportJSONRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ImportJSONRequest.Unmarshal(m, b) -} -func (m *ImportJSONRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ImportJSONRequest.Marshal(b, m, deterministic) -} -func (dst *ImportJSONRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ImportJSONRequest.Merge(dst, src) -} -func (m *ImportJSONRequest) XXX_Size() int { - return xxx_messageInfo_ImportJSONRequest.Size(m) -} -func (m *ImportJSONRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ImportJSONRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ImportJSONRequest proto.InternalMessageInfo - -func (m *ImportJSONRequest) GetPassphrase() string { - if m != nil { - return m.Passphrase - } - return "" -} - -func (m *ImportJSONRequest) GetJSON() string { - if m != nil { - return m.JSON - } - return "" -} - -type ImportResponse struct { - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ImportResponse) Reset() { *m = ImportResponse{} } -func (m *ImportResponse) String() string { return proto.CompactTextString(m) } -func (*ImportResponse) ProtoMessage() {} -func (*ImportResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_keys_ff2cb7ec9ea3671c, []int{10} -} -func (m *ImportResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ImportResponse.Unmarshal(m, b) -} -func (m *ImportResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ImportResponse.Marshal(b, m, deterministic) -} -func (dst *ImportResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ImportResponse.Merge(dst, src) -} -func (m *ImportResponse) XXX_Size() int { - return xxx_messageInfo_ImportResponse.Size(m) -} -func (m *ImportResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ImportResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ImportResponse proto.InternalMessageInfo - -func (m *ImportResponse) GetAddress() string { - if m != nil { - return m.Address - } - return "" -} - -type ImportRequest struct { - Passphrase string `protobuf:"bytes,1,opt,name=passphrase,proto3" json:"passphrase,omitempty"` - Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` - Curvetype string `protobuf:"bytes,3,opt,name=curvetype,proto3" json:"curvetype,omitempty"` - Keybytes []byte `protobuf:"bytes,4,opt,name=keybytes,proto3" json:"keybytes,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ImportRequest) Reset() { *m = ImportRequest{} } -func (m *ImportRequest) String() string { return proto.CompactTextString(m) } -func (*ImportRequest) ProtoMessage() {} -func (*ImportRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_keys_ff2cb7ec9ea3671c, []int{11} -} -func (m *ImportRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ImportRequest.Unmarshal(m, b) -} -func (m *ImportRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ImportRequest.Marshal(b, m, deterministic) -} -func (dst *ImportRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ImportRequest.Merge(dst, src) -} -func (m *ImportRequest) XXX_Size() int { - return xxx_messageInfo_ImportRequest.Size(m) -} -func (m *ImportRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ImportRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ImportRequest proto.InternalMessageInfo - -func (m *ImportRequest) GetPassphrase() string { - if m != nil { - return m.Passphrase - } - return "" -} - -func (m *ImportRequest) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *ImportRequest) GetCurvetype() string { - if m != nil { - return m.Curvetype - } - return "" -} - -func (m *ImportRequest) GetKeybytes() []byte { - if m != nil { - return m.Keybytes - } - return nil -} - -type ExportRequest struct { - Passphrase string `protobuf:"bytes,1,opt,name=passphrase,proto3" json:"passphrase,omitempty"` - Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` - Address string `protobuf:"bytes,3,opt,name=address,proto3" json:"address,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ExportRequest) Reset() { *m = ExportRequest{} } -func (m *ExportRequest) String() string { return proto.CompactTextString(m) } -func (*ExportRequest) ProtoMessage() {} -func (*ExportRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_keys_ff2cb7ec9ea3671c, []int{12} -} -func (m *ExportRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ExportRequest.Unmarshal(m, b) -} -func (m *ExportRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ExportRequest.Marshal(b, m, deterministic) -} -func (dst *ExportRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ExportRequest.Merge(dst, src) -} -func (m *ExportRequest) XXX_Size() int { - return xxx_messageInfo_ExportRequest.Size(m) -} -func (m *ExportRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ExportRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ExportRequest proto.InternalMessageInfo - -func (m *ExportRequest) GetPassphrase() string { - if m != nil { - return m.Passphrase - } - return "" -} - -func (m *ExportRequest) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *ExportRequest) GetAddress() string { - if m != nil { - return m.Address - } - return "" -} - -type ExportResponse struct { - Publickey []byte `protobuf:"bytes,1,opt,name=publickey,proto3" json:"publickey,omitempty"` - Privatekey []byte `protobuf:"bytes,2,opt,name=privatekey,proto3" json:"privatekey,omitempty"` - Address []byte `protobuf:"bytes,3,opt,name=address,proto3" json:"address,omitempty"` - Curvetype string `protobuf:"bytes,4,opt,name=curvetype,proto3" json:"curvetype,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ExportResponse) Reset() { *m = ExportResponse{} } -func (m *ExportResponse) String() string { return proto.CompactTextString(m) } -func (*ExportResponse) ProtoMessage() {} -func (*ExportResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_keys_ff2cb7ec9ea3671c, []int{13} -} -func (m *ExportResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ExportResponse.Unmarshal(m, b) -} -func (m *ExportResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ExportResponse.Marshal(b, m, deterministic) -} -func (dst *ExportResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ExportResponse.Merge(dst, src) -} -func (m *ExportResponse) XXX_Size() int { - return xxx_messageInfo_ExportResponse.Size(m) -} -func (m *ExportResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ExportResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ExportResponse proto.InternalMessageInfo - -func (m *ExportResponse) GetPublickey() []byte { - if m != nil { - return m.Publickey - } - return nil -} - -func (m *ExportResponse) GetPrivatekey() []byte { - if m != nil { - return m.Privatekey - } - return nil -} - -func (m *ExportResponse) GetAddress() []byte { - if m != nil { - return m.Address - } - return nil -} - -func (m *ExportResponse) GetCurvetype() string { - if m != nil { - return m.Curvetype - } - return "" -} - -type SignRequest struct { - Passphrase string `protobuf:"bytes,1,opt,name=passphrase,proto3" json:"passphrase,omitempty"` - Address string `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` - Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` - Message []byte `protobuf:"bytes,4,opt,name=message,proto3" json:"message,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SignRequest) Reset() { *m = SignRequest{} } -func (m *SignRequest) String() string { return proto.CompactTextString(m) } -func (*SignRequest) ProtoMessage() {} -func (*SignRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_keys_ff2cb7ec9ea3671c, []int{14} -} -func (m *SignRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SignRequest.Unmarshal(m, b) -} -func (m *SignRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SignRequest.Marshal(b, m, deterministic) -} -func (dst *SignRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_SignRequest.Merge(dst, src) -} -func (m *SignRequest) XXX_Size() int { - return xxx_messageInfo_SignRequest.Size(m) -} -func (m *SignRequest) XXX_DiscardUnknown() { - xxx_messageInfo_SignRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_SignRequest proto.InternalMessageInfo - -func (m *SignRequest) GetPassphrase() string { - if m != nil { - return m.Passphrase - } - return "" -} - -func (m *SignRequest) GetAddress() string { - if m != nil { - return m.Address - } - return "" -} - -func (m *SignRequest) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *SignRequest) GetMessage() []byte { - if m != nil { - return m.Message - } - return nil -} - -type SignResponse struct { - Signature []byte `protobuf:"bytes,1,opt,name=signature,proto3" json:"signature,omitempty"` - Curvetype string `protobuf:"bytes,2,opt,name=curvetype,proto3" json:"curvetype,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SignResponse) Reset() { *m = SignResponse{} } -func (m *SignResponse) String() string { return proto.CompactTextString(m) } -func (*SignResponse) ProtoMessage() {} -func (*SignResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_keys_ff2cb7ec9ea3671c, []int{15} -} -func (m *SignResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SignResponse.Unmarshal(m, b) -} -func (m *SignResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SignResponse.Marshal(b, m, deterministic) -} -func (dst *SignResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_SignResponse.Merge(dst, src) -} -func (m *SignResponse) XXX_Size() int { - return xxx_messageInfo_SignResponse.Size(m) -} -func (m *SignResponse) XXX_DiscardUnknown() { - xxx_messageInfo_SignResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_SignResponse proto.InternalMessageInfo - -func (m *SignResponse) GetSignature() []byte { - if m != nil { - return m.Signature - } - return nil -} - -func (m *SignResponse) GetCurvetype() string { - if m != nil { - return m.Curvetype - } - return "" -} - -type VerifyRequest struct { - Curvetype string `protobuf:"bytes,1,opt,name=curvetype,proto3" json:"curvetype,omitempty"` - Pub []byte `protobuf:"bytes,2,opt,name=pub,proto3" json:"pub,omitempty"` - Message []byte `protobuf:"bytes,3,opt,name=message,proto3" json:"message,omitempty"` - Signature []byte `protobuf:"bytes,4,opt,name=signature,proto3" json:"signature,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *VerifyRequest) Reset() { *m = VerifyRequest{} } -func (m *VerifyRequest) String() string { return proto.CompactTextString(m) } -func (*VerifyRequest) ProtoMessage() {} -func (*VerifyRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_keys_ff2cb7ec9ea3671c, []int{16} -} -func (m *VerifyRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_VerifyRequest.Unmarshal(m, b) -} -func (m *VerifyRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_VerifyRequest.Marshal(b, m, deterministic) -} -func (dst *VerifyRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_VerifyRequest.Merge(dst, src) -} -func (m *VerifyRequest) XXX_Size() int { - return xxx_messageInfo_VerifyRequest.Size(m) -} -func (m *VerifyRequest) XXX_DiscardUnknown() { - xxx_messageInfo_VerifyRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_VerifyRequest proto.InternalMessageInfo - -func (m *VerifyRequest) GetCurvetype() string { - if m != nil { - return m.Curvetype - } - return "" -} - -func (m *VerifyRequest) GetPub() []byte { - if m != nil { - return m.Pub - } - return nil -} - -func (m *VerifyRequest) GetMessage() []byte { - if m != nil { - return m.Message - } - return nil -} - -func (m *VerifyRequest) GetSignature() []byte { - if m != nil { - return m.Signature - } - return nil -} - -type HashRequest struct { - Hashtype string `protobuf:"bytes,1,opt,name=hashtype,proto3" json:"hashtype,omitempty"` - Message []byte `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *HashRequest) Reset() { *m = HashRequest{} } -func (m *HashRequest) String() string { return proto.CompactTextString(m) } -func (*HashRequest) ProtoMessage() {} -func (*HashRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_keys_ff2cb7ec9ea3671c, []int{17} -} -func (m *HashRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_HashRequest.Unmarshal(m, b) -} -func (m *HashRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_HashRequest.Marshal(b, m, deterministic) -} -func (dst *HashRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_HashRequest.Merge(dst, src) -} -func (m *HashRequest) XXX_Size() int { - return xxx_messageInfo_HashRequest.Size(m) -} -func (m *HashRequest) XXX_DiscardUnknown() { - xxx_messageInfo_HashRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_HashRequest proto.InternalMessageInfo - -func (m *HashRequest) GetHashtype() string { - if m != nil { - return m.Hashtype - } - return "" -} - -func (m *HashRequest) GetMessage() []byte { - if m != nil { - return m.Message - } - return nil -} - -type HashResponse struct { - Hash string `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *HashResponse) Reset() { *m = HashResponse{} } -func (m *HashResponse) String() string { return proto.CompactTextString(m) } -func (*HashResponse) ProtoMessage() {} -func (*HashResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_keys_ff2cb7ec9ea3671c, []int{18} -} -func (m *HashResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_HashResponse.Unmarshal(m, b) -} -func (m *HashResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_HashResponse.Marshal(b, m, deterministic) -} -func (dst *HashResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_HashResponse.Merge(dst, src) -} -func (m *HashResponse) XXX_Size() int { - return xxx_messageInfo_HashResponse.Size(m) -} -func (m *HashResponse) XXX_DiscardUnknown() { - xxx_messageInfo_HashResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_HashResponse proto.InternalMessageInfo - -func (m *HashResponse) GetHash() string { - if m != nil { - return m.Hash - } - return "" -} - -type Key struct { - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - Keyname string `protobuf:"bytes,2,opt,name=keyname,proto3" json:"keyname,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Key) Reset() { *m = Key{} } -func (m *Key) String() string { return proto.CompactTextString(m) } -func (*Key) ProtoMessage() {} -func (*Key) Descriptor() ([]byte, []int) { - return fileDescriptor_keys_ff2cb7ec9ea3671c, []int{19} -} -func (m *Key) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Key.Unmarshal(m, b) -} -func (m *Key) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Key.Marshal(b, m, deterministic) -} -func (dst *Key) XXX_Merge(src proto.Message) { - xxx_messageInfo_Key.Merge(dst, src) -} -func (m *Key) XXX_Size() int { - return xxx_messageInfo_Key.Size(m) -} -func (m *Key) XXX_DiscardUnknown() { - xxx_messageInfo_Key.DiscardUnknown(m) -} - -var xxx_messageInfo_Key proto.InternalMessageInfo - -func (m *Key) GetAddress() string { - if m != nil { - return m.Address - } - return "" -} - -func (m *Key) GetKeyname() string { - if m != nil { - return m.Keyname - } - return "" -} - -type ListResponse struct { - Key []*Key `protobuf:"bytes,1,rep,name=key,proto3" json:"key,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListResponse) Reset() { *m = ListResponse{} } -func (m *ListResponse) String() string { return proto.CompactTextString(m) } -func (*ListResponse) ProtoMessage() {} -func (*ListResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_keys_ff2cb7ec9ea3671c, []int{20} -} -func (m *ListResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListResponse.Unmarshal(m, b) -} -func (m *ListResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListResponse.Marshal(b, m, deterministic) -} -func (dst *ListResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListResponse.Merge(dst, src) -} -func (m *ListResponse) XXX_Size() int { - return xxx_messageInfo_ListResponse.Size(m) -} -func (m *ListResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ListResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ListResponse proto.InternalMessageInfo - -func (m *ListResponse) GetKey() []*Key { - if m != nil { - return m.Key - } - return nil -} - -type AddNameRequest struct { - Keyname string `protobuf:"bytes,1,opt,name=keyname,proto3" json:"keyname,omitempty"` - Address string `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *AddNameRequest) Reset() { *m = AddNameRequest{} } -func (m *AddNameRequest) String() string { return proto.CompactTextString(m) } -func (*AddNameRequest) ProtoMessage() {} -func (*AddNameRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_keys_ff2cb7ec9ea3671c, []int{21} -} -func (m *AddNameRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_AddNameRequest.Unmarshal(m, b) -} -func (m *AddNameRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_AddNameRequest.Marshal(b, m, deterministic) -} -func (dst *AddNameRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_AddNameRequest.Merge(dst, src) -} -func (m *AddNameRequest) XXX_Size() int { - return xxx_messageInfo_AddNameRequest.Size(m) -} -func (m *AddNameRequest) XXX_DiscardUnknown() { - xxx_messageInfo_AddNameRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_AddNameRequest proto.InternalMessageInfo - -func (m *AddNameRequest) GetKeyname() string { - if m != nil { - return m.Keyname - } - return "" -} - -func (m *AddNameRequest) GetAddress() string { - if m != nil { - return m.Address - } - return "" -} - -func init() { - proto.RegisterType((*ListRequest)(nil), "pbkeys.ListRequest") - proto.RegisterType((*VerifyResponse)(nil), "pbkeys.VerifyResponse") - proto.RegisterType((*RemoveNameResponse)(nil), "pbkeys.RemoveNameResponse") - proto.RegisterType((*AddNameResponse)(nil), "pbkeys.AddNameResponse") - proto.RegisterType((*RemoveNameRequest)(nil), "pbkeys.RemoveNameRequest") - proto.RegisterType((*GenRequest)(nil), "pbkeys.GenRequest") - proto.RegisterType((*GenResponse)(nil), "pbkeys.GenResponse") - proto.RegisterType((*PubRequest)(nil), "pbkeys.PubRequest") - proto.RegisterType((*PubResponse)(nil), "pbkeys.PubResponse") - proto.RegisterType((*ImportJSONRequest)(nil), "pbkeys.ImportJSONRequest") - proto.RegisterType((*ImportResponse)(nil), "pbkeys.ImportResponse") - proto.RegisterType((*ImportRequest)(nil), "pbkeys.ImportRequest") - proto.RegisterType((*ExportRequest)(nil), "pbkeys.ExportRequest") - proto.RegisterType((*ExportResponse)(nil), "pbkeys.ExportResponse") - proto.RegisterType((*SignRequest)(nil), "pbkeys.SignRequest") - proto.RegisterType((*SignResponse)(nil), "pbkeys.SignResponse") - proto.RegisterType((*VerifyRequest)(nil), "pbkeys.VerifyRequest") - proto.RegisterType((*HashRequest)(nil), "pbkeys.HashRequest") - proto.RegisterType((*HashResponse)(nil), "pbkeys.HashResponse") - proto.RegisterType((*Key)(nil), "pbkeys.Key") - proto.RegisterType((*ListResponse)(nil), "pbkeys.ListResponse") - proto.RegisterType((*AddNameRequest)(nil), "pbkeys.AddNameRequest") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// KeysClient is the client API for Keys service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type KeysClient interface { - GenerateKey(ctx context.Context, in *GenRequest, opts ...grpc.CallOption) (*GenResponse, error) - PublicKey(ctx context.Context, in *PubRequest, opts ...grpc.CallOption) (*PubResponse, error) - Sign(ctx context.Context, in *SignRequest, opts ...grpc.CallOption) (*SignResponse, error) - Verify(ctx context.Context, in *VerifyRequest, opts ...grpc.CallOption) (*VerifyResponse, error) - Import(ctx context.Context, in *ImportRequest, opts ...grpc.CallOption) (*ImportResponse, error) - ImportJSON(ctx context.Context, in *ImportJSONRequest, opts ...grpc.CallOption) (*ImportResponse, error) - Export(ctx context.Context, in *ExportRequest, opts ...grpc.CallOption) (*ExportResponse, error) - Hash(ctx context.Context, in *HashRequest, opts ...grpc.CallOption) (*HashResponse, error) - RemoveName(ctx context.Context, in *RemoveNameRequest, opts ...grpc.CallOption) (*RemoveNameResponse, error) - List(ctx context.Context, in *ListRequest, opts ...grpc.CallOption) (*ListResponse, error) - AddName(ctx context.Context, in *AddNameRequest, opts ...grpc.CallOption) (*AddNameResponse, error) -} - -type keysClient struct { - cc *grpc.ClientConn -} - -func NewKeysClient(cc *grpc.ClientConn) KeysClient { - return &keysClient{cc} -} - -func (c *keysClient) GenerateKey(ctx context.Context, in *GenRequest, opts ...grpc.CallOption) (*GenResponse, error) { - out := new(GenResponse) - err := c.cc.Invoke(ctx, "/pbkeys.Keys/GenerateKey", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *keysClient) PublicKey(ctx context.Context, in *PubRequest, opts ...grpc.CallOption) (*PubResponse, error) { - out := new(PubResponse) - err := c.cc.Invoke(ctx, "/pbkeys.Keys/PublicKey", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *keysClient) Sign(ctx context.Context, in *SignRequest, opts ...grpc.CallOption) (*SignResponse, error) { - out := new(SignResponse) - err := c.cc.Invoke(ctx, "/pbkeys.Keys/Sign", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *keysClient) Verify(ctx context.Context, in *VerifyRequest, opts ...grpc.CallOption) (*VerifyResponse, error) { - out := new(VerifyResponse) - err := c.cc.Invoke(ctx, "/pbkeys.Keys/Verify", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *keysClient) Import(ctx context.Context, in *ImportRequest, opts ...grpc.CallOption) (*ImportResponse, error) { - out := new(ImportResponse) - err := c.cc.Invoke(ctx, "/pbkeys.Keys/Import", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *keysClient) ImportJSON(ctx context.Context, in *ImportJSONRequest, opts ...grpc.CallOption) (*ImportResponse, error) { - out := new(ImportResponse) - err := c.cc.Invoke(ctx, "/pbkeys.Keys/ImportJSON", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *keysClient) Export(ctx context.Context, in *ExportRequest, opts ...grpc.CallOption) (*ExportResponse, error) { - out := new(ExportResponse) - err := c.cc.Invoke(ctx, "/pbkeys.Keys/Export", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *keysClient) Hash(ctx context.Context, in *HashRequest, opts ...grpc.CallOption) (*HashResponse, error) { - out := new(HashResponse) - err := c.cc.Invoke(ctx, "/pbkeys.Keys/Hash", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *keysClient) RemoveName(ctx context.Context, in *RemoveNameRequest, opts ...grpc.CallOption) (*RemoveNameResponse, error) { - out := new(RemoveNameResponse) - err := c.cc.Invoke(ctx, "/pbkeys.Keys/RemoveName", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *keysClient) List(ctx context.Context, in *ListRequest, opts ...grpc.CallOption) (*ListResponse, error) { - out := new(ListResponse) - err := c.cc.Invoke(ctx, "/pbkeys.Keys/List", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *keysClient) AddName(ctx context.Context, in *AddNameRequest, opts ...grpc.CallOption) (*AddNameResponse, error) { - out := new(AddNameResponse) - err := c.cc.Invoke(ctx, "/pbkeys.Keys/AddName", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// KeysServer is the server API for Keys service. -type KeysServer interface { - GenerateKey(context.Context, *GenRequest) (*GenResponse, error) - PublicKey(context.Context, *PubRequest) (*PubResponse, error) - Sign(context.Context, *SignRequest) (*SignResponse, error) - Verify(context.Context, *VerifyRequest) (*VerifyResponse, error) - Import(context.Context, *ImportRequest) (*ImportResponse, error) - ImportJSON(context.Context, *ImportJSONRequest) (*ImportResponse, error) - Export(context.Context, *ExportRequest) (*ExportResponse, error) - Hash(context.Context, *HashRequest) (*HashResponse, error) - RemoveName(context.Context, *RemoveNameRequest) (*RemoveNameResponse, error) - List(context.Context, *ListRequest) (*ListResponse, error) - AddName(context.Context, *AddNameRequest) (*AddNameResponse, error) -} - -func RegisterKeysServer(s *grpc.Server, srv KeysServer) { - s.RegisterService(&_Keys_serviceDesc, srv) -} - -func _Keys_GenerateKey_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GenRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(KeysServer).GenerateKey(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pbkeys.Keys/GenerateKey", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(KeysServer).GenerateKey(ctx, req.(*GenRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Keys_PublicKey_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(PubRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(KeysServer).PublicKey(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pbkeys.Keys/PublicKey", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(KeysServer).PublicKey(ctx, req.(*PubRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Keys_Sign_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SignRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(KeysServer).Sign(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pbkeys.Keys/Sign", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(KeysServer).Sign(ctx, req.(*SignRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Keys_Verify_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(VerifyRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(KeysServer).Verify(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pbkeys.Keys/Verify", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(KeysServer).Verify(ctx, req.(*VerifyRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Keys_Import_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ImportRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(KeysServer).Import(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pbkeys.Keys/Import", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(KeysServer).Import(ctx, req.(*ImportRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Keys_ImportJSON_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ImportJSONRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(KeysServer).ImportJSON(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pbkeys.Keys/ImportJSON", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(KeysServer).ImportJSON(ctx, req.(*ImportJSONRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Keys_Export_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ExportRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(KeysServer).Export(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pbkeys.Keys/Export", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(KeysServer).Export(ctx, req.(*ExportRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Keys_Hash_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(HashRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(KeysServer).Hash(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pbkeys.Keys/Hash", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(KeysServer).Hash(ctx, req.(*HashRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Keys_RemoveName_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(RemoveNameRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(KeysServer).RemoveName(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pbkeys.Keys/RemoveName", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(KeysServer).RemoveName(ctx, req.(*RemoveNameRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Keys_List_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ListRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(KeysServer).List(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pbkeys.Keys/List", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(KeysServer).List(ctx, req.(*ListRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Keys_AddName_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(AddNameRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(KeysServer).AddName(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/pbkeys.Keys/AddName", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(KeysServer).AddName(ctx, req.(*AddNameRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Keys_serviceDesc = grpc.ServiceDesc{ - ServiceName: "pbkeys.Keys", - HandlerType: (*KeysServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "GenerateKey", - Handler: _Keys_GenerateKey_Handler, - }, - { - MethodName: "PublicKey", - Handler: _Keys_PublicKey_Handler, - }, - { - MethodName: "Sign", - Handler: _Keys_Sign_Handler, - }, - { - MethodName: "Verify", - Handler: _Keys_Verify_Handler, - }, - { - MethodName: "Import", - Handler: _Keys_Import_Handler, - }, - { - MethodName: "ImportJSON", - Handler: _Keys_ImportJSON_Handler, - }, - { - MethodName: "Export", - Handler: _Keys_Export_Handler, - }, - { - MethodName: "Hash", - Handler: _Keys_Hash_Handler, - }, - { - MethodName: "RemoveName", - Handler: _Keys_RemoveName_Handler, - }, - { - MethodName: "List", - Handler: _Keys_List_Handler, - }, - { - MethodName: "AddName", - Handler: _Keys_AddName_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "github.com/hyperledger/burrow/keys/pbkeys/keys.proto", -} - -func init() { - proto.RegisterFile("github.com/hyperledger/burrow/keys/pbkeys/keys.proto", fileDescriptor_keys_ff2cb7ec9ea3671c) -} - -var fileDescriptor_keys_ff2cb7ec9ea3671c = []byte{ - // 716 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x56, 0xd1, 0x6f, 0xd3, 0x3c, - 0x10, 0x57, 0x9b, 0xa8, 0x5b, 0x2f, 0x6d, 0xbf, 0xcd, 0xdf, 0xbe, 0x8f, 0x12, 0x0d, 0x84, 0xfc, - 0xc2, 0x84, 0xb4, 0x56, 0x1b, 0x13, 0x13, 0x93, 0x10, 0x42, 0x03, 0x0d, 0x36, 0x34, 0xa6, 0x4e, - 0xe2, 0x8d, 0x87, 0x64, 0x3d, 0xda, 0xa8, 0x6b, 0x13, 0xec, 0x64, 0x23, 0x0f, 0xbc, 0xf2, 0x47, - 0xf3, 0x84, 0x62, 0xc7, 0xb1, 0x9d, 0x6d, 0xac, 0x12, 0x2f, 0xad, 0x7d, 0xbe, 0xbb, 0xdf, 0xdd, - 0xf9, 0xd7, 0x9f, 0x0b, 0x7b, 0x93, 0x28, 0x9d, 0x66, 0xe1, 0xe0, 0x22, 0x9e, 0x0f, 0xa7, 0x79, - 0x82, 0xec, 0x12, 0xc7, 0x13, 0x64, 0xc3, 0x30, 0x63, 0x2c, 0xbe, 0x1e, 0xce, 0x30, 0xe7, 0xc3, - 0x24, 0x14, 0x5f, 0xc5, 0xc7, 0x20, 0x61, 0x71, 0x1a, 0x93, 0x96, 0x34, 0xd1, 0x2e, 0x78, 0x1f, - 0x23, 0x9e, 0x8e, 0xf0, 0x5b, 0x86, 0x3c, 0xa5, 0x6b, 0xd0, 0xfb, 0x8c, 0x2c, 0xfa, 0x9a, 0x8f, - 0x90, 0x27, 0xf1, 0x82, 0x23, 0xdd, 0x00, 0x32, 0xc2, 0x79, 0x7c, 0x85, 0xa7, 0xc1, 0x1c, 0x2b, - 0xeb, 0x3a, 0xfc, 0xf3, 0x66, 0x3c, 0xb6, 0x4c, 0xdb, 0xb0, 0x6e, 0x3a, 0x8a, 0x7c, 0xa4, 0x0f, - 0x2b, 0x33, 0xcc, 0x17, 0xc1, 0x1c, 0xfb, 0x8d, 0x27, 0x8d, 0xad, 0xf6, 0x48, 0x6d, 0xe9, 0x18, - 0xe0, 0x08, 0x17, 0xca, 0xef, 0x31, 0x40, 0x12, 0x70, 0x9e, 0x4c, 0x59, 0xc0, 0x95, 0xab, 0x61, - 0x21, 0x9b, 0xd0, 0xbe, 0xc8, 0xd8, 0x15, 0xa6, 0x79, 0x82, 0xfd, 0xa6, 0x38, 0xd6, 0x06, 0x13, - 0xc5, 0xb1, 0x51, 0x9e, 0x82, 0x27, 0x50, 0x64, 0x8d, 0x85, 0x63, 0x30, 0x1e, 0x33, 0xe4, 0x5c, - 0x95, 0x53, 0x6e, 0xe9, 0x01, 0xc0, 0x59, 0x16, 0x1a, 0x65, 0xdf, 0xee, 0x47, 0x08, 0xb8, 0x02, - 0x47, 0xd6, 0x20, 0xd6, 0xf4, 0x15, 0x78, 0x22, 0xb6, 0x04, 0x59, 0x03, 0x27, 0xc9, 0x42, 0x11, - 0xd8, 0x19, 0x15, 0xcb, 0x3f, 0x57, 0x4f, 0x8f, 0x60, 0xfd, 0xc3, 0x3c, 0x89, 0x59, 0x7a, 0x7c, - 0xfe, 0xe9, 0x74, 0xd9, 0x81, 0x10, 0x70, 0x0b, 0x77, 0x55, 0x47, 0xb1, 0xa6, 0xcf, 0xa0, 0x27, - 0x13, 0x2d, 0xd1, 0xef, 0x0f, 0xe8, 0x2a, 0xdf, 0xa5, 0x01, 0xeb, 0x8d, 0xdb, 0x7d, 0x39, 0xf5, - 0x5b, 0xf1, 0x61, 0x75, 0x86, 0x79, 0x98, 0xa7, 0xc8, 0xfb, 0xae, 0x18, 0x46, 0xb5, 0xa7, 0x5f, - 0xa0, 0xfb, 0xee, 0xfb, 0xdf, 0xc2, 0x1b, 0xdd, 0x39, 0x76, 0x77, 0x3f, 0x1b, 0xd0, 0x53, 0xf9, - 0xcb, 0x51, 0x6c, 0x42, 0x3b, 0xc9, 0xc2, 0xcb, 0xe8, 0x62, 0x86, 0x79, 0x79, 0x37, 0xda, 0x20, - 0xe0, 0x59, 0x74, 0x15, 0xa4, 0x58, 0x1c, 0x37, 0xc5, 0xb1, 0x61, 0xa9, 0x43, 0x75, 0x34, 0x21, - 0xac, 0x19, 0xb8, 0xf5, 0xbb, 0xcd, 0xc0, 0x3b, 0x8f, 0x26, 0x4b, 0xd3, 0xdc, 0x80, 0x69, 0xde, - 0xce, 0x3b, 0xc7, 0xee, 0x7f, 0x8e, 0x9c, 0x07, 0x13, 0x2c, 0xe7, 0xab, 0xb6, 0xf4, 0x18, 0x3a, - 0x12, 0x56, 0x37, 0xcf, 0xa3, 0xc9, 0x22, 0x48, 0x33, 0x86, 0xaa, 0xf9, 0xca, 0x70, 0x0f, 0x3d, - 0xaf, 0xa1, 0xab, 0x24, 0x41, 0x36, 0x61, 0xb9, 0x37, 0xea, 0xb7, 0x5e, 0xb2, 0xbf, 0xa9, 0xd9, - 0x6f, 0x94, 0xe9, 0x58, 0x65, 0xda, 0x65, 0xb9, 0xb5, 0xb2, 0xe8, 0x21, 0x78, 0xef, 0x03, 0x3e, - 0x55, 0xb0, 0x3e, 0xac, 0x4e, 0x03, 0x3e, 0x35, 0x50, 0xab, 0xbd, 0x09, 0xd1, 0xb4, 0x27, 0x41, - 0xa1, 0x23, 0x93, 0x94, 0x93, 0x20, 0xe0, 0x16, 0x51, 0x65, 0x06, 0xb1, 0xa6, 0x2f, 0xc1, 0x39, - 0xb1, 0xef, 0xb8, 0xf6, 0xa3, 0x37, 0xf4, 0xa5, 0x69, 0xeb, 0xcb, 0x36, 0x74, 0xa4, 0x7c, 0x96, - 0xe9, 0x1f, 0x81, 0x23, 0xf9, 0xe5, 0x6c, 0x79, 0xbb, 0xde, 0x40, 0x8a, 0xec, 0xe0, 0x04, 0xf3, - 0x51, 0x61, 0xa7, 0x6f, 0xa1, 0x57, 0xc9, 0xe6, 0x3d, 0x02, 0x79, 0x37, 0x17, 0x76, 0x7f, 0xb9, - 0xe0, 0x9e, 0x60, 0xce, 0xc9, 0x0b, 0xa1, 0x6e, 0xc8, 0x82, 0x14, 0x8b, 0x06, 0x88, 0xc2, 0xd3, - 0xc2, 0xea, 0xff, 0x6b, 0xd9, 0xca, 0x2a, 0xf7, 0xa0, 0x7d, 0x26, 0xa8, 0x6f, 0x45, 0x69, 0xfd, - 0xd3, 0x51, 0xa6, 0xae, 0xed, 0x80, 0x5b, 0x90, 0x8a, 0x54, 0x87, 0x06, 0xb3, 0xfd, 0x0d, 0xdb, - 0x58, 0x86, 0xec, 0x43, 0x4b, 0x72, 0x87, 0xfc, 0xa7, 0xce, 0x2d, 0x2e, 0xf9, 0xff, 0xd7, 0xcd, - 0x3a, 0x50, 0xca, 0x93, 0x0e, 0xb4, 0xe4, 0x4a, 0x07, 0xd6, 0x14, 0xef, 0x35, 0x80, 0x16, 0x53, - 0xf2, 0xd0, 0xf6, 0x32, 0x04, 0xf6, 0xce, 0x04, 0xfb, 0xd0, 0x92, 0xca, 0xa1, 0x91, 0x2d, 0xa5, - 0xd2, 0x81, 0x35, 0x81, 0xd9, 0x01, 0xb7, 0x60, 0x9a, 0x1e, 0x8f, 0x41, 0x5e, 0x3d, 0x1e, 0x8b, - 0x8c, 0x87, 0x00, 0xfa, 0xc9, 0xd4, 0xc5, 0xde, 0x78, 0x46, 0x7d, 0xff, 0xb6, 0x23, 0x8d, 0x5b, - 0x50, 0x50, 0xe3, 0x1a, 0xef, 0xb9, 0xc6, 0xb5, 0x58, 0x7a, 0x00, 0x2b, 0x25, 0x0d, 0x49, 0xd5, - 0x8d, 0xcd, 0x4b, 0xff, 0xc1, 0x0d, 0xbb, 0x8c, 0x0d, 0x5b, 0xe2, 0xff, 0xc3, 0xf3, 0xdf, 0x01, - 0x00, 0x00, 0xff, 0xff, 0x73, 0x20, 0x9f, 0xdf, 0x77, 0x08, 0x00, 0x00, -} diff --git a/keys/pbkeys/keys.proto b/keys/pbkeys/keys.proto deleted file mode 100644 index b1ceeb4cd..000000000 --- a/keys/pbkeys/keys.proto +++ /dev/null @@ -1,131 +0,0 @@ -syntax = "proto3"; - -package pbkeys; - -service Keys { - rpc GenerateKey(GenRequest) returns (GenResponse); - rpc PublicKey(PubRequest) returns (PubResponse); - rpc Sign(SignRequest) returns (SignResponse); - rpc Verify(VerifyRequest) returns (VerifyResponse); - rpc Import(ImportRequest) returns (ImportResponse); - rpc ImportJSON(ImportJSONRequest) returns (ImportResponse); - rpc Export(ExportRequest) returns (ExportResponse); - rpc Hash(HashRequest) returns (HashResponse); - rpc RemoveName(RemoveNameRequest) returns (RemoveNameResponse); - rpc List(ListRequest) returns (ListResponse); - rpc AddName(AddNameRequest) returns (AddNameResponse); -} - -// Some empty types we may define later - -message ListRequest { - -} - -message VerifyResponse { - -} - -message RemoveNameResponse { - -} - -message AddNameResponse { - -} - -message RemoveNameRequest { - string keyname = 1; -} - - -message GenRequest { - string passphrase = 1; - string curvetype = 2; - string keyname = 3; -} - -message GenResponse { - string address = 1; -} - -message PubRequest { - string address = 1; - string name = 2; -} - -message PubResponse { - bytes pub = 1; - string curvetype = 2; -} - -message ImportJSONRequest { - string passphrase = 1; - string JSON = 2; -} - -message ImportResponse { - string address = 1; -} - -message ImportRequest { - string passphrase = 1; - string name = 2; - string curvetype = 3; - bytes keybytes = 4; -} - -message ExportRequest { - string passphrase = 1; - string name = 2; - string address = 3; -} - -message ExportResponse { - bytes publickey = 1; - bytes privatekey = 2; - bytes address = 3; - string curvetype = 4; -} - -message SignRequest { - string passphrase = 1; - string address = 2; - string name = 3; - bytes message = 4; -} - -message SignResponse { - bytes signature = 1; - string curvetype = 2; -} - -message VerifyRequest { - string curvetype = 1; - bytes pub = 2; - bytes message = 3; - bytes signature = 4; -} - -message HashRequest { - string hashtype = 1; - bytes message = 2; -} - -message HashResponse { - string hash = 1; -} - -message Key { - string address = 1; - string keyname = 2; -} - -message ListResponse { - repeated Key key = 1; -} - -message AddNameRequest { - string keyname = 1; - string address = 2; -} diff --git a/keys/server.go b/keys/server.go index 576c819c6..5613a7b52 100644 --- a/keys/server.go +++ b/keys/server.go @@ -9,7 +9,6 @@ import ( "strings" "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/keys/pbkeys" "github.com/hyperledger/burrow/logging" "github.com/tmthrgd/go-hex" "golang.org/x/crypto/ripemd160" @@ -26,15 +25,15 @@ func StartStandAloneServer(keysDir, host, port string, AllowBadFilePermissions b return err } grpcServer := grpc.NewServer() - pbkeys.RegisterKeysServer(grpcServer, NewKeyStore(keysDir, AllowBadFilePermissions, logger)) + RegisterKeysServer(grpcServer, NewKeyStore(keysDir, AllowBadFilePermissions, logger)) return grpcServer.Serve(listen) } //------------------------------------------------------------------------ // handlers -func (k *KeyStore) GenerateKey(ctx context.Context, in *pbkeys.GenRequest) (*pbkeys.GenResponse, error) { - curveT, err := crypto.CurveTypeFromString(in.Curvetype) +func (k *KeyStore) GenerateKey(ctx context.Context, in *GenRequest) (*GenResponse, error) { + curveT, err := crypto.CurveTypeFromString(in.CurveType) if err != nil { return nil, err } @@ -45,17 +44,17 @@ func (k *KeyStore) GenerateKey(ctx context.Context, in *pbkeys.GenRequest) (*pbk } addrH := key.Address.String() - if in.Keyname != "" { - err = coreNameAdd(k.keysDirPath, in.Keyname, addrH) + if in.KeyName != "" { + err = coreNameAdd(k.keysDirPath, in.KeyName, addrH) if err != nil { return nil, err } } - return &pbkeys.GenResponse{Address: addrH}, nil + return &GenResponse{Address: addrH}, nil } -func (k *KeyStore) Export(ctx context.Context, in *pbkeys.ExportRequest) (*pbkeys.ExportResponse, error) { +func (k *KeyStore) Export(ctx context.Context, in *ExportRequest) (*ExportResponse, error) { addr, err := getNameAddr(k.keysDirPath, in.GetName(), in.GetAddress()) if err != nil { @@ -73,15 +72,15 @@ func (k *KeyStore) Export(ctx context.Context, in *pbkeys.ExportRequest) (*pbkey return nil, err } - return &pbkeys.ExportResponse{ + return &ExportResponse{ Address: addrB[:], - Curvetype: key.CurveType.String(), + CurveType: key.CurveType.String(), Publickey: key.PublicKey.PublicKey[:], Privatekey: key.PrivateKey.PrivateKey[:], }, nil } -func (k *KeyStore) PublicKey(ctx context.Context, in *pbkeys.PubRequest) (*pbkeys.PubResponse, error) { +func (k *KeyStore) PublicKey(ctx context.Context, in *PubRequest) (*PubResponse, error) { addr, err := getNameAddr(k.keysDirPath, in.GetName(), in.GetAddress()) if err != nil { return nil, err @@ -98,10 +97,10 @@ func (k *KeyStore) PublicKey(ctx context.Context, in *pbkeys.PubRequest) (*pbkey return nil, err } - return &pbkeys.PubResponse{Curvetype: key.CurveType.String(), Pub: key.Pubkey()}, nil + return &PubResponse{CurveType: key.CurveType.String(), PublicKey: key.Pubkey()}, nil } -func (k *KeyStore) Sign(ctx context.Context, in *pbkeys.SignRequest) (*pbkeys.SignResponse, error) { +func (k *KeyStore) Sign(ctx context.Context, in *SignRequest) (*SignResponse, error) { addr, err := getNameAddr(k.keysDirPath, in.GetName(), in.GetAddress()) if err != nil { return nil, err @@ -119,11 +118,11 @@ func (k *KeyStore) Sign(ctx context.Context, in *pbkeys.SignRequest) (*pbkeys.Si sig, err := key.Sign(in.GetMessage()) - return &pbkeys.SignResponse{Signature: sig, Curvetype: key.CurveType.String()}, nil + return &SignResponse{Signature: sig, CurveType: key.CurveType.String()}, nil } -func (k *KeyStore) Verify(ctx context.Context, in *pbkeys.VerifyRequest) (*pbkeys.VerifyResponse, error) { - if in.GetPub() == nil { +func (k *KeyStore) Verify(ctx context.Context, in *VerifyRequest) (*VerifyResponse, error) { + if in.GetPublicKey() == nil { return nil, fmt.Errorf("must provide a pubkey") } if in.GetMessage() == nil { @@ -133,7 +132,7 @@ func (k *KeyStore) Verify(ctx context.Context, in *pbkeys.VerifyRequest) (*pbkey return nil, fmt.Errorf("must provide a signature") } - curveT, err := crypto.CurveTypeFromString(in.GetCurvetype()) + curveT, err := crypto.CurveTypeFromString(in.GetCurveType()) if err != nil { return nil, err } @@ -141,7 +140,7 @@ func (k *KeyStore) Verify(ctx context.Context, in *pbkeys.VerifyRequest) (*pbkey if err != nil { return nil, err } - pubkey, err := crypto.PublicKeyFromBytes(in.GetPub(), curveT) + pubkey, err := crypto.PublicKeyFromBytes(in.GetPublicKey(), curveT) if err != nil { return nil, err } @@ -150,10 +149,10 @@ func (k *KeyStore) Verify(ctx context.Context, in *pbkeys.VerifyRequest) (*pbkey return nil, fmt.Errorf("Signature does not match") } - return &pbkeys.VerifyResponse{}, nil + return &VerifyResponse{}, nil } -func (k *KeyStore) Hash(ctx context.Context, in *pbkeys.HashRequest) (*pbkeys.HashResponse, error) { +func (k *KeyStore) Hash(ctx context.Context, in *HashRequest) (*HashResponse, error) { var hasher hash.Hash switch in.GetHashtype() { case "ripemd160": @@ -167,10 +166,10 @@ func (k *KeyStore) Hash(ctx context.Context, in *pbkeys.HashRequest) (*pbkeys.Ha hasher.Write(in.GetMessage()) - return &pbkeys.HashResponse{Hash: hex.EncodeUpperToString(hasher.Sum(nil))}, nil + return &HashResponse{Hash: hex.EncodeUpperToString(hasher.Sum(nil))}, nil } -func (k *KeyStore) ImportJSON(ctx context.Context, in *pbkeys.ImportJSONRequest) (*pbkeys.ImportResponse, error) { +func (k *KeyStore) ImportJSON(ctx context.Context, in *ImportJSONRequest) (*ImportResponse, error) { keyJSON := []byte(in.GetJSON()) var err error addr := IsValidKeyJson(keyJSON) @@ -182,15 +181,15 @@ func (k *KeyStore) ImportJSON(ctx context.Context, in *pbkeys.ImportJSONRequest) if err != nil { return nil, err } - return &pbkeys.ImportResponse{Address: hex.EncodeUpperToString(addr)}, nil + return &ImportResponse{Address: hex.EncodeUpperToString(addr)}, nil } -func (k *KeyStore) Import(ctx context.Context, in *pbkeys.ImportRequest) (*pbkeys.ImportResponse, error) { - curveT, err := crypto.CurveTypeFromString(in.GetCurvetype()) +func (k *KeyStore) Import(ctx context.Context, in *ImportRequest) (*ImportResponse, error) { + curveT, err := crypto.CurveTypeFromString(in.GetCurveType()) if err != nil { return nil, err } - key, err := NewKeyFromPriv(curveT, in.GetKeybytes()) + key, err := NewKeyFromPriv(curveT, in.GetKeyBytes()) if err != nil { return nil, err } @@ -205,33 +204,33 @@ func (k *KeyStore) Import(ctx context.Context, in *pbkeys.ImportRequest) (*pbkey return nil, err } } - return &pbkeys.ImportResponse{Address: hex.EncodeUpperToString(key.Address[:])}, nil + return &ImportResponse{Address: hex.EncodeUpperToString(key.Address[:])}, nil } -func (k *KeyStore) List(ctx context.Context, in *pbkeys.ListRequest) (*pbkeys.ListResponse, error) { +func (k *KeyStore) List(ctx context.Context, in *ListRequest) (*ListResponse, error) { names, err := coreNameList(k.keysDirPath) if err != nil { return nil, err } - var list []*pbkeys.Key + var list []*KeyID for name, addr := range names { - list = append(list, &pbkeys.Key{Keyname: name, Address: addr}) + list = append(list, &KeyID{KeyName: name, Address: addr}) } - return &pbkeys.ListResponse{Key: list}, nil + return &ListResponse{Key: list}, nil } -func (k *KeyStore) RemoveName(ctx context.Context, in *pbkeys.RemoveNameRequest) (*pbkeys.RemoveNameResponse, error) { - if in.GetKeyname() == "" { +func (k *KeyStore) RemoveName(ctx context.Context, in *RemoveNameRequest) (*RemoveNameResponse, error) { + if in.GetKeyName() == "" { return nil, fmt.Errorf("please specify a name") } - return &pbkeys.RemoveNameResponse{}, coreNameRm(k.keysDirPath, in.GetKeyname()) + return &RemoveNameResponse{}, coreNameRm(k.keysDirPath, in.GetKeyName()) } -func (k *KeyStore) AddName(ctx context.Context, in *pbkeys.AddNameRequest) (*pbkeys.AddNameResponse, error) { +func (k *KeyStore) AddName(ctx context.Context, in *AddNameRequest) (*AddNameResponse, error) { if in.GetKeyname() == "" { return nil, fmt.Errorf("please specify a name") } @@ -240,5 +239,5 @@ func (k *KeyStore) AddName(ctx context.Context, in *pbkeys.AddNameRequest) (*pbk return nil, fmt.Errorf("please specify an address") } - return &pbkeys.AddNameResponse{}, coreNameAdd(k.keysDirPath, in.GetKeyname(), strings.ToUpper(in.GetAddress())) + return &AddNameResponse{}, coreNameAdd(k.keysDirPath, in.GetKeyname(), strings.ToUpper(in.GetAddress())) } diff --git a/keys/server_test.go b/keys/server_test.go index 5ee1e204f..68ed229b2 100644 --- a/keys/server_test.go +++ b/keys/server_test.go @@ -13,7 +13,6 @@ import ( "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/execution/evm/sha3" - "github.com/hyperledger/burrow/keys/pbkeys" "github.com/hyperledger/burrow/logging" tm_crypto "github.com/tendermint/go-crypto" "google.golang.org/grpc" @@ -52,7 +51,7 @@ func init() { } } -func grpcKeysClient() pbkeys.KeysClient { +func grpcKeysClient() KeysClient { var opts []grpc.DialOption opts = append(opts, grpc.WithInsecure()) conn, err := grpc.Dial(DefaultHost+":"+TestPort, opts...) @@ -60,7 +59,7 @@ func grpcKeysClient() pbkeys.KeysClient { fmt.Printf("Failed to connect to grpc server: %v\n", err) os.Exit(1) } - return pbkeys.NewKeysClient(conn) + return NewKeysClient(conn) } func checkAddrFromPub(typ string, pub, addr []byte) error { @@ -90,12 +89,12 @@ func testServerKeygenAndPub(t *testing.T, typ string) { c := grpcKeysClient() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - genresp, err := c.GenerateKey(ctx, &pbkeys.GenRequest{Curvetype: typ}) + genresp, err := c.GenerateKey(ctx, &GenRequest{CurveType: typ}) if err != nil { t.Fatal(err) } addr := genresp.Address - resp, err := c.PublicKey(ctx, &pbkeys.PubRequest{Address: addr}) + resp, err := c.PublicKey(ctx, &PubRequest{Address: addr}) if err != nil { t.Fatal(err) } @@ -103,7 +102,7 @@ func testServerKeygenAndPub(t *testing.T, typ string) { if err != nil { t.Fatal(err) } - if err = checkAddrFromPub(typ, resp.GetPub(), addrB[:]); err != nil { + if err = checkAddrFromPub(typ, resp.GetPublicKey(), addrB[:]); err != nil { t.Fatal(err) } } @@ -118,23 +117,27 @@ func testServerSignAndVerify(t *testing.T, typ string) { c := grpcKeysClient() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - genresp, err := c.GenerateKey(ctx, &pbkeys.GenRequest{Curvetype: typ}) + genresp, err := c.GenerateKey(ctx, &GenRequest{CurveType: typ}) if err != nil { t.Fatal(err) } addr := genresp.Address - resp, err := c.PublicKey(ctx, &pbkeys.PubRequest{Address: addr}) + resp, err := c.PublicKey(ctx, &PubRequest{Address: addr}) if err != nil { t.Fatal(err) } hash := sha3.Sha3([]byte("the hash of something!")) - sig, err := c.Sign(ctx, &pbkeys.SignRequest{Address: addr, Message: hash}) + sig, err := c.Sign(ctx, &SignRequest{Address: addr, Message: hash}) if err != nil { t.Fatal(err) } - _, err = c.Verify(ctx, &pbkeys.VerifyRequest{Signature: sig.GetSignature(), Pub: resp.GetPub(), Message: hash, Curvetype: typ}) + _, err = c.Verify(ctx, &VerifyRequest{ + Signature: sig.GetSignature(), + PublicKey: resp.GetPublicKey(), + Message: hash, + CurveType: typ}) if err != nil { t.Fatal(err) } @@ -153,7 +156,7 @@ func testServerHash(t *testing.T, typ string) { c := grpcKeysClient() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - resp, err := c.Hash(ctx, &pbkeys.HashRequest{Hashtype: typ, Message: []byte(data)}) + resp, err := c.Hash(ctx, &HashRequest{Hashtype: typ, Message: []byte(data)}) if err != nil { t.Fatal(err) } diff --git a/permission/types/account_permissions.go b/permission/account_permissions.go similarity index 93% rename from permission/types/account_permissions.go rename to permission/account_permissions.go index 91bee5f81..6de0a4431 100644 --- a/permission/types/account_permissions.go +++ b/permission/account_permissions.go @@ -1,12 +1,7 @@ -package types +package permission import "github.com/hyperledger/burrow/binary" -type AccountPermissions struct { - Base BasePermissions - Roles []string -} - // Returns true if the role is found func (ap AccountPermissions) HasRole(role string) bool { role = string(binary.RightPadBytes([]byte(role), 32)) diff --git a/permission/types/base_permissions.go b/permission/base_permissions.go similarity index 83% rename from permission/types/base_permissions.go rename to permission/base_permissions.go index 401f46d12..8aa80cd47 100644 --- a/permission/types/base_permissions.go +++ b/permission/base_permissions.go @@ -1,16 +1,7 @@ -package types +package permission import "fmt" -// Base chain permissions struct -type BasePermissions struct { - // bit array with "has"/"doesn't have" for each permission - Perms PermFlag - - // bit array with "set"/"not set" for each permission (not-set should fall back to global) - SetBit PermFlag -} - // Gets the permission value. // ErrValueNotSet is returned if the permission's set bits are not all on, // and should be caught by caller so the global permission can be fetched @@ -74,5 +65,3 @@ func (bp BasePermissions) Compose(bpFallthrough BasePermissions) BasePermissions func (bp BasePermissions) String() string { return fmt.Sprintf("Base: %b; Set: %b", bp.Perms, bp.SetBit) } - -//--------------------------------------------------------------------------------------------- diff --git a/permission/types/base_permissions_test.go b/permission/base_permissions_test.go similarity index 99% rename from permission/types/base_permissions_test.go rename to permission/base_permissions_test.go index 700006c45..9d0b8f288 100644 --- a/permission/types/base_permissions_test.go +++ b/permission/base_permissions_test.go @@ -1,4 +1,4 @@ -package types +package permission import ( "strconv" diff --git a/permission/types/errors.go b/permission/errors.go similarity index 98% rename from permission/types/errors.go rename to permission/errors.go index 0b022277e..316ee913d 100644 --- a/permission/types/errors.go +++ b/permission/errors.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package types +package permission import ( "fmt" diff --git a/permission/types/perm_flag.go b/permission/perm_flag.go similarity index 99% rename from permission/types/perm_flag.go rename to permission/perm_flag.go index c749aa308..617aa561f 100644 --- a/permission/types/perm_flag.go +++ b/permission/perm_flag.go @@ -1,4 +1,4 @@ -package types +package permission import ( "fmt" diff --git a/permission/types/perm_flag_test.go b/permission/perm_flag_test.go similarity index 91% rename from permission/types/perm_flag_test.go rename to permission/perm_flag_test.go index 2ec7a6edb..5d930a7c7 100644 --- a/permission/types/perm_flag_test.go +++ b/permission/perm_flag_test.go @@ -1,4 +1,4 @@ -package types +package permission import ( "testing" diff --git a/permission/permission.pb.go b/permission/permission.pb.go new file mode 100644 index 000000000..b72986011 --- /dev/null +++ b/permission/permission.pb.go @@ -0,0 +1,844 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: permission.proto + +/* + Package permission is a generated protocol buffer package. + + It is generated from these files: + permission.proto + + It has these top-level messages: + AccountPermissions + BasePermissions + PermArgs +*/ +package permission + +import proto "github.com/gogo/protobuf/proto" +import golang_proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" +import _ "github.com/gogo/protobuf/gogoproto" + +import github_com_hyperledger_burrow_crypto "github.com/hyperledger/burrow/crypto" + +import io "io" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = golang_proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package + +type AccountPermissions struct { + Base BasePermissions `protobuf:"bytes,1,opt,name=Base" json:"Base"` + Roles []string `protobuf:"bytes,2,rep,name=Roles" json:"Roles,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *AccountPermissions) Reset() { *m = AccountPermissions{} } +func (m *AccountPermissions) String() string { return proto.CompactTextString(m) } +func (*AccountPermissions) ProtoMessage() {} +func (*AccountPermissions) Descriptor() ([]byte, []int) { return fileDescriptorPermission, []int{0} } + +func (m *AccountPermissions) GetBase() BasePermissions { + if m != nil { + return m.Base + } + return BasePermissions{} +} + +func (m *AccountPermissions) GetRoles() []string { + if m != nil { + return m.Roles + } + return nil +} + +func (*AccountPermissions) XXX_MessageName() string { + return "permission.AccountPermissions" +} + +type BasePermissions struct { + Perms PermFlag `protobuf:"varint,1,opt,name=Perms,casttype=PermFlag" json:"Perms"` + SetBit PermFlag `protobuf:"varint,2,opt,name=SetBit,casttype=PermFlag" json:"SetBit"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *BasePermissions) Reset() { *m = BasePermissions{} } +func (*BasePermissions) ProtoMessage() {} +func (*BasePermissions) Descriptor() ([]byte, []int) { return fileDescriptorPermission, []int{1} } + +func (m *BasePermissions) GetPerms() PermFlag { + if m != nil { + return m.Perms + } + return 0 +} + +func (m *BasePermissions) GetSetBit() PermFlag { + if m != nil { + return m.SetBit + } + return 0 +} + +func (*BasePermissions) XXX_MessageName() string { + return "permission.BasePermissions" +} + +type PermArgs struct { + PermFlag PermFlag `protobuf:"varint,1,opt,name=PermFlag,casttype=PermFlag" json:"PermFlag"` + Address *github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,2,opt,name=Address,customtype=github.com/hyperledger/burrow/crypto.Address" json:"Address,omitempty"` + Permission *PermFlag `protobuf:"varint,3,opt,name=Permission,casttype=PermFlag" json:"Permission,omitempty"` + Role *string `protobuf:"bytes,4,opt,name=Role" json:"Role,omitempty"` + Value *bool `protobuf:"varint,5,opt,name=Value" json:"Value,omitempty"` +} + +func (m *PermArgs) Reset() { *m = PermArgs{} } +func (*PermArgs) ProtoMessage() {} +func (*PermArgs) Descriptor() ([]byte, []int) { return fileDescriptorPermission, []int{2} } + +func (m *PermArgs) GetPermFlag() PermFlag { + if m != nil { + return m.PermFlag + } + return 0 +} + +func (m *PermArgs) GetPermission() PermFlag { + if m != nil && m.Permission != nil { + return *m.Permission + } + return 0 +} + +func (m *PermArgs) GetRole() string { + if m != nil && m.Role != nil { + return *m.Role + } + return "" +} + +func (m *PermArgs) GetValue() bool { + if m != nil && m.Value != nil { + return *m.Value + } + return false +} + +func (*PermArgs) XXX_MessageName() string { + return "permission.PermArgs" +} +func init() { + proto.RegisterType((*AccountPermissions)(nil), "permission.AccountPermissions") + golang_proto.RegisterType((*AccountPermissions)(nil), "permission.AccountPermissions") + proto.RegisterType((*BasePermissions)(nil), "permission.BasePermissions") + golang_proto.RegisterType((*BasePermissions)(nil), "permission.BasePermissions") + proto.RegisterType((*PermArgs)(nil), "permission.PermArgs") + golang_proto.RegisterType((*PermArgs)(nil), "permission.PermArgs") +} +func (m *AccountPermissions) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *AccountPermissions) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + dAtA[i] = 0xa + i++ + i = encodeVarintPermission(dAtA, i, uint64(m.Base.Size())) + n1, err := m.Base.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n1 + if len(m.Roles) > 0 { + for _, s := range m.Roles { + dAtA[i] = 0x12 + i++ + l = len(s) + for l >= 1<<7 { + dAtA[i] = uint8(uint64(l)&0x7f | 0x80) + l >>= 7 + i++ + } + dAtA[i] = uint8(l) + i++ + i += copy(dAtA[i:], s) + } + } + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } + return i, nil +} + +func (m *BasePermissions) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *BasePermissions) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + dAtA[i] = 0x8 + i++ + i = encodeVarintPermission(dAtA, i, uint64(m.Perms)) + dAtA[i] = 0x10 + i++ + i = encodeVarintPermission(dAtA, i, uint64(m.SetBit)) + if m.XXX_unrecognized != nil { + i += copy(dAtA[i:], m.XXX_unrecognized) + } + return i, nil +} + +func (m *PermArgs) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PermArgs) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + dAtA[i] = 0x8 + i++ + i = encodeVarintPermission(dAtA, i, uint64(m.PermFlag)) + if m.Address != nil { + dAtA[i] = 0x12 + i++ + i = encodeVarintPermission(dAtA, i, uint64(m.Address.Size())) + n2, err := m.Address.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n2 + } + if m.Permission != nil { + dAtA[i] = 0x18 + i++ + i = encodeVarintPermission(dAtA, i, uint64(*m.Permission)) + } + if m.Role != nil { + dAtA[i] = 0x22 + i++ + i = encodeVarintPermission(dAtA, i, uint64(len(*m.Role))) + i += copy(dAtA[i:], *m.Role) + } + if m.Value != nil { + dAtA[i] = 0x28 + i++ + if *m.Value { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i++ + } + return i, nil +} + +func encodeVarintPermission(dAtA []byte, offset int, v uint64) int { + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return offset + 1 +} +func (m *AccountPermissions) Size() (n int) { + var l int + _ = l + l = m.Base.Size() + n += 1 + l + sovPermission(uint64(l)) + if len(m.Roles) > 0 { + for _, s := range m.Roles { + l = len(s) + n += 1 + l + sovPermission(uint64(l)) + } + } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } + return n +} + +func (m *BasePermissions) Size() (n int) { + var l int + _ = l + n += 1 + sovPermission(uint64(m.Perms)) + n += 1 + sovPermission(uint64(m.SetBit)) + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } + return n +} + +func (m *PermArgs) Size() (n int) { + var l int + _ = l + n += 1 + sovPermission(uint64(m.PermFlag)) + if m.Address != nil { + l = m.Address.Size() + n += 1 + l + sovPermission(uint64(l)) + } + if m.Permission != nil { + n += 1 + sovPermission(uint64(*m.Permission)) + } + if m.Role != nil { + l = len(*m.Role) + n += 1 + l + sovPermission(uint64(l)) + } + if m.Value != nil { + n += 2 + } + return n +} + +func sovPermission(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n +} +func sozPermission(x uint64) (n int) { + return sovPermission(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *AccountPermissions) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPermission + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: AccountPermissions: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: AccountPermissions: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Base", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPermission + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPermission + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Base.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Roles", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPermission + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthPermission + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Roles = append(m.Roles, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipPermission(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthPermission + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *BasePermissions) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPermission + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: BasePermissions: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: BasePermissions: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Perms", wireType) + } + m.Perms = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPermission + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Perms |= (PermFlag(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field SetBit", wireType) + } + m.SetBit = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPermission + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.SetBit |= (PermFlag(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipPermission(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthPermission + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PermArgs) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPermission + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PermArgs: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PermArgs: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PermFlag", wireType) + } + m.PermFlag = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPermission + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PermFlag |= (PermFlag(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPermission + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthPermission + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + var v github_com_hyperledger_burrow_crypto.Address + m.Address = &v + if err := m.Address.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Permission", wireType) + } + var v PermFlag + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPermission + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= (PermFlag(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + m.Permission = &v + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Role", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPermission + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthPermission + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := string(dAtA[iNdEx:postIndex]) + m.Role = &s + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPermission + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + b := bool(v != 0) + m.Value = &b + default: + iNdEx = preIndex + skippy, err := skipPermission(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthPermission + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipPermission(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowPermission + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowPermission + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowPermission + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + iNdEx += length + if length < 0 { + return 0, ErrInvalidLengthPermission + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowPermission + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipPermission(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} + +var ( + ErrInvalidLengthPermission = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowPermission = fmt.Errorf("proto: integer overflow") +) + +func init() { proto.RegisterFile("permission.proto", fileDescriptorPermission) } +func init() { golang_proto.RegisterFile("permission.proto", fileDescriptorPermission) } + +var fileDescriptorPermission = []byte{ + // 351 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x51, 0x31, 0x4b, 0xc3, 0x40, + 0x14, 0xee, 0xb5, 0xa9, 0xb6, 0xcf, 0x82, 0xe5, 0x70, 0x08, 0x0a, 0x49, 0xe8, 0x20, 0x19, 0x6a, + 0x22, 0x82, 0x4b, 0x07, 0xa1, 0x19, 0x1c, 0x9c, 0xe4, 0x04, 0x07, 0xb7, 0x34, 0x3d, 0xd3, 0x40, + 0xda, 0x0b, 0x77, 0x17, 0xa4, 0xff, 0xc4, 0x51, 0xff, 0x89, 0x63, 0xc7, 0xce, 0x0e, 0x45, 0x5a, + 0xf0, 0x47, 0x38, 0xc9, 0x5d, 0x6a, 0x1b, 0x85, 0xba, 0xbd, 0xef, 0x7d, 0xdf, 0x7b, 0xdf, 0xbd, + 0xef, 0xa0, 0x9d, 0x51, 0x3e, 0x4e, 0x84, 0x48, 0xd8, 0xc4, 0xcb, 0x38, 0x93, 0x0c, 0xc3, 0xb6, + 0x73, 0x7c, 0x16, 0x27, 0x72, 0x94, 0x0f, 0xbc, 0x88, 0x8d, 0xfd, 0x98, 0xc5, 0xcc, 0xd7, 0x92, + 0x41, 0xfe, 0xa8, 0x91, 0x06, 0xba, 0x2a, 0x46, 0x3b, 0x21, 0xe0, 0x7e, 0x14, 0xb1, 0x7c, 0x22, + 0x6f, 0x37, 0x3b, 0x04, 0xbe, 0x04, 0x23, 0x08, 0x05, 0x35, 0x91, 0x83, 0xdc, 0x83, 0x8b, 0x13, + 0xaf, 0xe4, 0xa8, 0xfa, 0x25, 0x69, 0x60, 0xcc, 0x16, 0x76, 0x85, 0x68, 0x39, 0x3e, 0x82, 0x3a, + 0x61, 0x29, 0x15, 0x66, 0xd5, 0xa9, 0xb9, 0x4d, 0x52, 0x80, 0x4e, 0x02, 0x87, 0x7f, 0x86, 0xf0, + 0x29, 0xd4, 0x15, 0x14, 0xda, 0xc0, 0x08, 0xda, 0x6a, 0xc7, 0xd7, 0xc2, 0x6e, 0xa8, 0xe6, 0x75, + 0x1a, 0xc6, 0xa4, 0xa0, 0xb1, 0x0b, 0x7b, 0x77, 0x54, 0x06, 0x89, 0x34, 0xab, 0x3b, 0x84, 0x6b, + 0xbe, 0x67, 0x3c, 0xbf, 0xd8, 0x95, 0xce, 0x27, 0x02, 0x4d, 0xf5, 0x79, 0x2c, 0x70, 0x17, 0x36, + 0xb2, 0x9d, 0x3e, 0x9b, 0x0a, 0xdf, 0xc0, 0x7e, 0x7f, 0x38, 0xe4, 0x54, 0x08, 0xed, 0xd5, 0x0a, + 0xce, 0xdf, 0x17, 0x76, 0xb7, 0x14, 0xe6, 0x68, 0x9a, 0x51, 0x9e, 0xd2, 0x61, 0x4c, 0xb9, 0x3f, + 0xc8, 0x39, 0x67, 0x4f, 0x7e, 0xc4, 0xa7, 0x99, 0x64, 0xde, 0x7a, 0x8e, 0xfc, 0x2c, 0xc0, 0x5d, + 0x80, 0xed, 0xb5, 0x66, 0x4d, 0x7b, 0xb7, 0x7e, 0xf9, 0x96, 0x78, 0x8c, 0xc1, 0x50, 0x41, 0x99, + 0x86, 0x83, 0xdc, 0x26, 0xd1, 0xb5, 0x4a, 0xf2, 0x3e, 0x4c, 0x73, 0x6a, 0xd6, 0x1d, 0xe4, 0x36, + 0x48, 0x01, 0x7a, 0x0d, 0x75, 0xe4, 0xfc, 0xd5, 0xae, 0x04, 0x57, 0xb3, 0xa5, 0x85, 0xe6, 0x4b, + 0x0b, 0x7d, 0x2c, 0x2d, 0xf4, 0xb6, 0xb2, 0xd0, 0x6c, 0x65, 0xa1, 0x07, 0xf7, 0xff, 0xe7, 0x6e, + 0x7f, 0xf1, 0x3b, 0x00, 0x00, 0xff, 0xff, 0x75, 0xf4, 0x5f, 0xe9, 0x44, 0x02, 0x00, 0x00, +} diff --git a/permission/permissions.go b/permission/permissions.go index 48b5bd9dd..3cac17d4e 100644 --- a/permission/permissions.go +++ b/permission/permissions.go @@ -14,26 +14,25 @@ package permission -import ( - "github.com/hyperledger/burrow/permission/types" -) - var ( - ZeroBasePermissions = types.BasePermissions{0, 0} - ZeroAccountPermissions = types.AccountPermissions{ + ZeroBasePermissions = BasePermissions{ + Perms: 0, + SetBit: 0, + } + ZeroAccountPermissions = AccountPermissions{ Base: ZeroBasePermissions, } - DefaultAccountPermissions = types.AccountPermissions{ - Base: types.BasePermissions{ - Perms: types.DefaultPermFlags, - SetBit: types.AllPermFlags, + DefaultAccountPermissions = AccountPermissions{ + Base: BasePermissions{ + Perms: DefaultPermFlags, + SetBit: AllPermFlags, }, Roles: []string{}, } - AllAccountPermissions = types.AccountPermissions{ - Base: types.BasePermissions{ - Perms: types.AllPermFlags, - SetBit: types.AllPermFlags, + AllAccountPermissions = AccountPermissions{ + Base: BasePermissions{ + Perms: AllPermFlags, + SetBit: AllPermFlags, }, Roles: []string{}, } diff --git a/permission/snatives/snatives.go b/permission/snatives.go similarity index 65% rename from permission/snatives/snatives.go rename to permission/snatives.go index 5b47b8af5..6f3df0a1e 100644 --- a/permission/snatives/snatives.go +++ b/permission/snatives.go @@ -12,37 +12,26 @@ // See the License for the specific language governing permissions and // limitations under the License. -package snatives +package permission import ( "fmt" "strings" "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/permission" - "github.com/hyperledger/burrow/permission/types" - ptypes "github.com/hyperledger/burrow/permission/types" ) //--------------------------------------------------------------------------------------------------- // PermissionsTx.PermArgs interface and argument encoding -type PermArgs struct { - PermFlag types.PermFlag - Address *crypto.Address `json:",omitempty"` - Permission *types.PermFlag `json:",omitempty"` - Role *string `json:",omitempty"` - Value *bool `json:",omitempty"` -} - func (pa PermArgs) String() string { body := make([]string, 0, 5) - body = append(body, fmt.Sprintf("PermFlag: %v", permission.String(pa.PermFlag))) + body = append(body, fmt.Sprintf("PermFlag: %v", String(pa.PermFlag))) if pa.Address != nil { body = append(body, fmt.Sprintf("Address: %s", *pa.Address)) } if pa.Permission != nil { - body = append(body, fmt.Sprintf("Permission: %v", permission.String(*pa.Permission))) + body = append(body, fmt.Sprintf("Permission: %v", String(*pa.Permission))) } if pa.Role != nil { body = append(body, fmt.Sprintf("Role: %s", *pa.Role)) @@ -56,10 +45,10 @@ func (pa PermArgs) String() string { func (pa PermArgs) EnsureValid() error { pf := pa.PermFlag // Address - if pa.Address == nil && pf != ptypes.SetGlobal { + if pa.Address == nil && pf != SetGlobal { return fmt.Errorf("PermArgs for PermFlag %v requires Address to be provided but was nil", pf) } - if pf == ptypes.HasRole || pf == ptypes.AddRole || pf == ptypes.RemoveRole { + if pf == HasRole || pf == AddRole || pf == RemoveRole { // Role if pa.Role == nil { return fmt.Errorf("PermArgs for PermFlag %v requires Role to be provided but was nil", pf) @@ -68,40 +57,40 @@ func (pa PermArgs) EnsureValid() error { } else if pa.Permission == nil { return fmt.Errorf("PermArgs for PermFlag %v requires Permission to be provided but was nil", pf) // Value - } else if (pf == ptypes.SetBase || pf == ptypes.SetGlobal) && pa.Value == nil { + } else if (pf == SetBase || pf == SetGlobal) && pa.Value == nil { return fmt.Errorf("PermArgs for PermFlag %v requires Value to be provided but was nil", pf) } return nil } -func HasBaseArgs(address crypto.Address, permFlag types.PermFlag) PermArgs { +func HasBaseArgs(address crypto.Address, permFlag PermFlag) PermArgs { return PermArgs{ - PermFlag: ptypes.HasBase, + PermFlag: HasBase, Address: &address, Permission: &permFlag, } } -func SetBaseArgs(address crypto.Address, permFlag types.PermFlag, value bool) PermArgs { +func SetBaseArgs(address crypto.Address, permFlag PermFlag, value bool) PermArgs { return PermArgs{ - PermFlag: ptypes.SetBase, + PermFlag: SetBase, Address: &address, Permission: &permFlag, Value: &value, } } -func UnsetBaseArgs(address crypto.Address, permFlag types.PermFlag) PermArgs { +func UnsetBaseArgs(address crypto.Address, permFlag PermFlag) PermArgs { return PermArgs{ - PermFlag: ptypes.UnsetBase, + PermFlag: UnsetBase, Address: &address, Permission: &permFlag, } } -func SetGlobalArgs(permFlag types.PermFlag, value bool) PermArgs { +func SetGlobalArgs(permFlag PermFlag, value bool) PermArgs { return PermArgs{ - PermFlag: ptypes.SetGlobal, + PermFlag: SetGlobal, Permission: &permFlag, Value: &value, } @@ -109,7 +98,7 @@ func SetGlobalArgs(permFlag types.PermFlag, value bool) PermArgs { func HasRoleArgs(address crypto.Address, role string) PermArgs { return PermArgs{ - PermFlag: ptypes.HasRole, + PermFlag: HasRole, Address: &address, Role: &role, } @@ -117,7 +106,7 @@ func HasRoleArgs(address crypto.Address, role string) PermArgs { func AddRoleArgs(address crypto.Address, role string) PermArgs { return PermArgs{ - PermFlag: ptypes.AddRole, + PermFlag: AddRole, Address: &address, Role: &role, } @@ -125,7 +114,7 @@ func AddRoleArgs(address crypto.Address, role string) PermArgs { func RemoveRoleArgs(address crypto.Address, role string) PermArgs { return PermArgs{ - PermFlag: ptypes.RemoveRole, + PermFlag: RemoveRole, Address: &address, Role: &role, } diff --git a/permission/snatives/snatives_test.go b/permission/snatives/snatives_test.go deleted file mode 100644 index 9441ed15e..000000000 --- a/permission/snatives/snatives_test.go +++ /dev/null @@ -1,22 +0,0 @@ -package snatives - -import ( - "testing" - - permission "github.com/hyperledger/burrow/permission/types" - "github.com/stretchr/testify/assert" -) - -func TestPermArgs_String(t *testing.T) { - role := "foo" - value := true - permFlag := permission.AddRole | permission.RemoveRole - permArgs := PermArgs{ - PermFlag: permission.SetBase, - Permission: &permFlag, - Role: &role, - Value: &value, - } - assert.Equal(t, "PermArgs{PermFlag: setBase, Permission: addRole | removeRole, Role: foo, Value: true}", - permArgs.String()) -} diff --git a/permission/util.go b/permission/util.go index 7470b94d9..6f4ba1ebe 100644 --- a/permission/util.go +++ b/permission/util.go @@ -17,8 +17,6 @@ package permission import ( "fmt" "strings" - - "github.com/hyperledger/burrow/permission/types" ) // ConvertMapStringIntToPermissions converts a map of string-bool pairs and a slice of @@ -27,9 +25,9 @@ import ( // will be set in the AccountsPermissions. For all unmentioned permissions the // ZeroBasePermissions is defaulted to. func ConvertPermissionsMapAndRolesToAccountPermissions(permissions map[string]bool, - roles []string) (*types.AccountPermissions, error) { + roles []string) (*AccountPermissions, error) { var err error - accountPermissions := &types.AccountPermissions{} + accountPermissions := &AccountPermissions{} accountPermissions.Base, err = convertPermissionsMapStringIntToBasePermissions(permissions) if err != nil { return nil, err @@ -40,12 +38,12 @@ func ConvertPermissionsMapAndRolesToAccountPermissions(permissions map[string]bo // convertPermissionsMapStringIntToBasePermissions converts a map of string-bool // pairs to BasePermissions. -func convertPermissionsMapStringIntToBasePermissions(permissions map[string]bool) (types.BasePermissions, error) { +func convertPermissionsMapStringIntToBasePermissions(permissions map[string]bool) (BasePermissions, error) { // initialise basePermissions as ZeroBasePermissions basePermissions := ZeroBasePermissions for permissionName, value := range permissions { - permissionsFlag, err := types.PermStringToFlag(permissionName) + permissionsFlag, err := PermStringToFlag(permissionName) if err != nil { return basePermissions, err } @@ -58,12 +56,12 @@ func convertPermissionsMapStringIntToBasePermissions(permissions map[string]bool // Builds a composite BasePermission by creating a PermFlag from permissions strings and // setting them all -func BasePermissionsFromStringList(permissions []string) (types.BasePermissions, error) { +func BasePermissionsFromStringList(permissions []string) (BasePermissions, error) { permFlag, err := PermFlagFromStringList(permissions) if err != nil { return ZeroBasePermissions, err } - return types.BasePermissions{ + return BasePermissions{ Perms: permFlag, SetBit: permFlag, }, nil @@ -71,10 +69,10 @@ func BasePermissionsFromStringList(permissions []string) (types.BasePermissions, // Builds a composite PermFlag by mapping each permission string in permissions to its // flag and composing them with binary or -func PermFlagFromStringList(permissions []string) (types.PermFlag, error) { - var permFlag types.PermFlag +func PermFlagFromStringList(permissions []string) (PermFlag, error) { + var permFlag PermFlag for _, perm := range permissions { - flag, err := types.PermStringToFlag(perm) + flag, err := PermStringToFlag(perm) if err != nil { return permFlag, err } @@ -85,19 +83,19 @@ func PermFlagFromStringList(permissions []string) (types.PermFlag, error) { // Builds a list of set permissions from a BasePermission by creating a list of permissions strings // from the resultant permissions of basePermissions -func BasePermissionsToStringList(basePermissions types.BasePermissions) ([]string, error) { +func BasePermissionsToStringList(basePermissions BasePermissions) ([]string, error) { return PermFlagToStringList(basePermissions.ResultantPerms()) } // Creates a list of individual permission flag strings from a possibly composite PermFlag // by projecting out each bit and adding its permission string if it is set -func PermFlagToStringList(permFlag types.PermFlag) ([]string, error) { - permStrings := make([]string, 0, types.NumPermissions) - if permFlag > types.AllPermFlags { +func PermFlagToStringList(permFlag PermFlag) ([]string, error) { + permStrings := make([]string, 0, NumPermissions) + if permFlag > AllPermFlags { return nil, fmt.Errorf("resultant permission 0b%b is invalid: has permission flag set above top flag 0b%b", - permFlag, types.TopPermFlag) + permFlag, TopPermFlag) } - for i := uint(0); i < types.NumPermissions; i++ { + for i := uint(0); i < NumPermissions; i++ { permFlag := permFlag & (1 << i) if permFlag > 0 { permStrings = append(permStrings, permFlag.String()) @@ -107,18 +105,18 @@ func PermFlagToStringList(permFlag types.PermFlag) ([]string, error) { } // Generates a human readable string from the resultant permissions of basePermission -func BasePermissionsString(basePermissions types.BasePermissions) string { +func BasePermissionsString(basePermissions BasePermissions) string { permStrings, err := BasePermissionsToStringList(basePermissions) if err != nil { - return types.UnknownString + return UnknownString } return strings.Join(permStrings, " | ") } -func String(permFlag types.PermFlag) string { +func String(permFlag PermFlag) string { permStrings, err := PermFlagToStringList(permFlag) if err != nil { - return types.UnknownString + return UnknownString } return strings.Join(permStrings, " | ") } diff --git a/permission/util_test.go b/permission/util_test.go index 780c1651c..105536120 100644 --- a/permission/util_test.go +++ b/permission/util_test.go @@ -3,21 +3,20 @@ package permission import ( "testing" - "github.com/hyperledger/burrow/permission/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestBasePermissionsFromStringList(t *testing.T) { - basePerms, err := BasePermissionsFromStringList([]string{types.HasRoleString, types.CreateContractString, types.SendString}) + basePerms, err := BasePermissionsFromStringList([]string{HasRoleString, CreateContractString, SendString}) require.NoError(t, err) - permFlag := types.HasRole | types.CreateContract | types.Send + permFlag := HasRole | CreateContract | Send assert.Equal(t, permFlag, basePerms.Perms) assert.Equal(t, permFlag, basePerms.SetBit) - basePerms, err = BasePermissionsFromStringList([]string{types.AllString}) + basePerms, err = BasePermissionsFromStringList([]string{AllString}) require.NoError(t, err) - permFlag = types.AllPermFlags + permFlag = AllPermFlags assert.Equal(t, permFlag, basePerms.Perms) assert.Equal(t, permFlag, basePerms.SetBit) @@ -26,27 +25,27 @@ func TestBasePermissionsFromStringList(t *testing.T) { } func TestBasePermissionsToStringList(t *testing.T) { - permStrings, err := BasePermissionsToStringList(allSetBasePermission(types.Root | types.HasRole | types.SetBase | types.Call)) + permStrings, err := BasePermissionsToStringList(allSetBasePermission(Root | HasRole | SetBase | Call)) require.NoError(t, err) assert.Equal(t, []string{"root", "call", "setBase", "hasRole"}, permStrings) - permStrings, err = BasePermissionsToStringList(allSetBasePermission(types.AllPermFlags)) + permStrings, err = BasePermissionsToStringList(allSetBasePermission(AllPermFlags)) require.NoError(t, err) assert.Equal(t, []string{"root", "send", "call", "createContract", "createAccount", "bond", "name", "hasBase", "setBase", "unsetBase", "setGlobal", "hasRole", "addRole", "removeRole"}, permStrings) - permStrings, err = BasePermissionsToStringList(allSetBasePermission(types.AllPermFlags + 1)) + permStrings, err = BasePermissionsToStringList(allSetBasePermission(AllPermFlags + 1)) assert.Error(t, err) } func TestBasePermissionsString(t *testing.T) { - permissionString := BasePermissionsString(allSetBasePermission(types.AllPermFlags &^ types.Root)) + permissionString := BasePermissionsString(allSetBasePermission(AllPermFlags &^ Root)) assert.Equal(t, "send | call | createContract | createAccount | bond | name | hasBase | "+ "setBase | unsetBase | setGlobal | hasRole | addRole | removeRole", permissionString) } -func allSetBasePermission(perms types.PermFlag) types.BasePermissions { - return types.BasePermissions{ +func allSetBasePermission(perms PermFlag) BasePermissions { + return BasePermissions{ Perms: perms, SetBit: perms, } diff --git a/rpc/config.go b/rpc/config.go index 549961f34..ef5095817 100644 --- a/rpc/config.go +++ b/rpc/config.go @@ -1,9 +1,6 @@ package rpc -import "github.com/hyperledger/burrow/rpc/v0/server" - type RPCConfig struct { - V0 *V0Config `json:",omitempty" toml:",omitempty"` TM *ServerConfig `json:",omitempty" toml:",omitempty"` Profiler *ServerConfig `json:",omitempty" toml:",omitempty"` GRPC *ServerConfig `json:",omitempty" toml:",omitempty"` @@ -15,11 +12,6 @@ type ServerConfig struct { ListenAddress string } -type V0Config struct { - Enabled bool - Server *server.ServerConfig -} - type ProfilerConfig struct { Enabled bool ListenAddress string @@ -40,20 +32,12 @@ type MetricsConfig struct { func DefaultRPCConfig() *RPCConfig { return &RPCConfig{ TM: DefaultTMConfig(), - V0: DefaultV0Config(), Profiler: DefaultProfilerConfig(), GRPC: DefaultGRPCConfig(), Metrics: DefaultMetricsConfig(), } } -func DefaultV0Config() *V0Config { - return &V0Config{ - Enabled: true, - Server: server.DefaultServerConfig(), - } -} - func DefaultTMConfig() *ServerConfig { return &ServerConfig{ Enabled: true, diff --git a/rpc/filters/accounts.go b/rpc/filters/accounts.go deleted file mode 100644 index d1cad4a30..000000000 --- a/rpc/filters/accounts.go +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package filters - -// Accounts is part of the pipe for BurrowMint and provides the implementation -// for the pipe to call into the BurrowMint application - -import ( - "bytes" - "encoding/hex" - "fmt" - "sync" - - acm "github.com/hyperledger/burrow/account" -) - -// TODO: [Silas] there are various notes about using mempool (which I guess translates to CheckTx cache). We need -// to understand if this is the right thing to do, since we cannot guarantee stability of the check cache it doesn't -// seem like the right thing to do.... -func NewAccountFilterFactory() *FilterFactory { - filterFactory := NewFilterFactory() - - filterFactory.RegisterFilterPool("code", &sync.Pool{ - New: func() interface{} { - return &AccountCodeFilter{} - }, - }) - - filterFactory.RegisterFilterPool("balance", &sync.Pool{ - New: func() interface{} { - return &AccountBalanceFilter{} - }, - }) - - return filterFactory -} - -// Filter for account code. -// Ops: == or != -// Could be used to match against nil, to see if an account is a contract account. -type AccountCodeFilter struct { - op string - value []byte - match func([]byte, []byte) bool -} - -func (acf *AccountCodeFilter) Configure(fd *FilterData) error { - op := fd.Op - val, err := hex.DecodeString(fd.Value) - - if err != nil { - return fmt.Errorf("Wrong value type.") - } - if op == "==" { - acf.match = func(a, b []byte) bool { - return bytes.Equal(a, b) - } - } else if op == "!=" { - acf.match = func(a, b []byte) bool { - return !bytes.Equal(a, b) - } - } else { - return fmt.Errorf("Op: " + acf.op + " is not supported for 'code' filtering") - } - acf.op = op - acf.value = val - return nil -} - -func (acf *AccountCodeFilter) Match(v interface{}) bool { - acc, ok := v.(acm.Account) - if !ok { - return false - } - return acf.match(acc.Code(), acf.value) -} - -// Filter for account balance. -// Ops: All -type AccountBalanceFilter struct { - op string - value uint64 - match func(uint64, uint64) bool -} - -func (abf *AccountBalanceFilter) Configure(fd *FilterData) error { - val, err := ParseNumberValue(fd.Value) - if err != nil { - return err - } - match, err2 := GetRangeFilter(fd.Op, "balance") - if err2 != nil { - return err2 - } - abf.match = match - abf.op = fd.Op - abf.value = uint64(val) - return nil -} - -func (abf *AccountBalanceFilter) Match(v interface{}) bool { - acc, ok := v.(acm.Account) - if !ok { - return false - } - return abf.match(acc.Balance(), abf.value) -} diff --git a/rpc/filters/filter.go b/rpc/filters/filter.go deleted file mode 100644 index ae9c2d785..000000000 --- a/rpc/filters/filter.go +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package filters - -import ( - "fmt" - "math" - "strconv" - "strings" -) - -// TODO add generic filters for various different kinds of matching. - -// Filters based on fields. -type Filter interface { - Match(v interface{}) bool -} - -// A filter that can be configured with in-data. -type ConfigurableFilter interface { - Filter - Configure(*FilterData) error -} - -// Used to filter. -// Op can be any of the following: -// The usual relative operators: <, >, <=, >=, ==, != (where applicable) -// A range parameter (see: https://help.github.com/articles/search-syntax/) -type FilterData struct { - Field string `json:"field"` - Op string `json:"op"` - Value string `json:"value"` -} - -// Filter made up of many filters. -type CompositeFilter struct { - filters []Filter -} - -func (cf *CompositeFilter) SetData(filters []Filter) { - cf.filters = filters -} - -func (cf *CompositeFilter) Match(v interface{}) bool { - for _, f := range cf.filters { - if !f.Match(v) { - return false - } - } - return true -} - -// Rubberstamps everything. -type MatchAllFilter struct{} - -func (maf *MatchAllFilter) Match(v interface{}) bool { return true } - -// Some standard value parsing functions. - -func ParseNumberValue(value string) (uint64, error) { - var val uint64 - // Check for wildcards. - if value == "min" { - val = 0 - } else if value == "max" { - val = math.MaxUint64 - } else { - tv, err := strconv.ParseUint(value, 10, 64) - - if err != nil { - return 0, fmt.Errorf("Wrong value type.") - } - val = tv - } - return val, nil -} - -// Some standard filtering functions. - -func GetRangeFilter(op, fName string) (func(a, b uint64) bool, error) { - if op == "==" { - return func(a, b uint64) bool { - return a == b - }, nil - } else if op == "!=" { - return func(a, b uint64) bool { - return a != b - }, nil - } else if op == "<=" { - return func(a, b uint64) bool { - return a <= b - }, nil - } else if op == ">=" { - return func(a, b uint64) bool { - return a >= b - }, nil - } else if op == "<" { - return func(a, b uint64) bool { - return a < b - }, nil - } else if op == ">" { - return func(a, b uint64) bool { - return a > b - }, nil - } else { - return nil, fmt.Errorf("Op: " + op + " is not supported for '" + fName + "' filtering") - } -} - -func GetStringFilter(op, fName string) (func(s0, s1 string) bool, error) { - if op == "==" { - return func(s0, s1 string) bool { - return strings.EqualFold(s0, s1) - }, nil - } else if op == "!=" { - return func(s0, s1 string) bool { - return !strings.EqualFold(s0, s1) - }, nil - } else { - return nil, fmt.Errorf("Op: " + op + " is not supported for '" + fName + "' filtering.") - } -} diff --git a/rpc/filters/filter_factory.go b/rpc/filters/filter_factory.go deleted file mode 100644 index 02a4016a9..000000000 --- a/rpc/filters/filter_factory.go +++ /dev/null @@ -1,78 +0,0 @@ -package filters - -import ( - "fmt" - "strings" - "sync" -) - -// Used to generate filters based on filter data. -// Keeping separate pools for "edge cases" (Composite and MatchAll) -type FilterFactory struct { - filterPools map[string]*sync.Pool - compositeFilterPool *sync.Pool - matchAllFilterPool *sync.Pool -} - -func NewFilterFactory() *FilterFactory { - aff := &FilterFactory{} - // Match all. - aff.matchAllFilterPool = &sync.Pool{ - New: func() interface{} { - return &MatchAllFilter{} - }, - } - // Composite. - aff.compositeFilterPool = &sync.Pool{ - New: func() interface{} { - return &CompositeFilter{} - }, - } - // Regular. - aff.filterPools = make(map[string]*sync.Pool) - - return aff -} - -func (ff *FilterFactory) RegisterFilterPool(fieldName string, pool *sync.Pool) { - ff.filterPools[strings.ToLower(fieldName)] = pool -} - -// Creates a new filter given the input data array. If the array is zero length or nil, an empty -// filter will be returned that returns true on all matches. If the array is of size 1, a regular -// filter is returned, otherwise a CompositeFieldFilter is returned, which is a special filter that -// contains a number of other filters. It implements AccountFieldFilter, and will match an account -// only if all the sub-filters matches. -func (ff *FilterFactory) NewFilter(fdArr []*FilterData) (Filter, error) { - - if len(fdArr) == 0 { - return &MatchAllFilter{}, nil - } - if len(fdArr) == 1 { - return ff.newSingleFilter(fdArr[0]) - } - filters := []Filter{} - for _, fd := range fdArr { - f, err := ff.newSingleFilter(fd) - if err != nil { - return nil, err - } - filters = append(filters, f) - } - cf := ff.compositeFilterPool.Get().(*CompositeFilter) - cf.filters = filters - return cf, nil -} - -func (ff *FilterFactory) newSingleFilter(fd *FilterData) (ConfigurableFilter, error) { - fp, ok := ff.filterPools[strings.ToLower(fd.Field)] - if !ok { - return nil, fmt.Errorf("Field is not supported: " + fd.Field) - } - f := fp.Get().(ConfigurableFilter) - err := f.Configure(fd) - if err != nil { - return nil, err - } - return f, nil -} diff --git a/rpc/filters/filter_test.go b/rpc/filters/filter_test.go deleted file mode 100644 index b635c0296..000000000 --- a/rpc/filters/filter_test.go +++ /dev/null @@ -1,258 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package filters - -import ( - "fmt" - "sync" - "testing" - - "github.com/stretchr/testify/suite" -) - -const OBJECTS = 100 - -type FilterableObject struct { - Integer int - String string -} - -// Filter for integer value. -// Ops: All -type IntegerFilter struct { - op string - value uint64 - match func(uint64, uint64) bool -} - -func (this *IntegerFilter) Configure(fd *FilterData) error { - val, err := ParseNumberValue(fd.Value) - if err != nil { - return err - } - match, err2 := GetRangeFilter(fd.Op, "integer") - if err2 != nil { - return err2 - } - this.match = match - this.op = fd.Op - this.value = val - return nil -} - -func (this *IntegerFilter) Match(v interface{}) bool { - fo, ok := v.(FilterableObject) - if !ok { - return false - } - return this.match(uint64(fo.Integer), this.value) -} - -// Filter for integer value. -// Ops: All -type StringFilter struct { - op string - value string - match func(string, string) bool -} - -func (this *StringFilter) Configure(fd *FilterData) error { - match, err := GetStringFilter(fd.Op, "string") - if err != nil { - return err - } - this.match = match - this.op = fd.Op - this.value = fd.Value - return nil -} - -func (this *StringFilter) Match(v interface{}) bool { - fo, ok := v.(FilterableObject) - if !ok { - return false - } - return this.match(fo.String, this.value) -} - -// Test suite -type FilterSuite struct { - suite.Suite - objects []FilterableObject - filterFactory *FilterFactory -} - -func (fs *FilterSuite) SetupSuite() { - objects := make([]FilterableObject, OBJECTS) - - for i := 0; i < 100; i++ { - objects[i] = FilterableObject{i, fmt.Sprintf("string%d", i)} - } - - ff := NewFilterFactory() - - ff.RegisterFilterPool("integer", &sync.Pool{ - New: func() interface{} { - return &IntegerFilter{} - }, - }) - - ff.RegisterFilterPool("string", &sync.Pool{ - New: func() interface{} { - return &StringFilter{} - }, - }) - - fs.objects = objects - fs.filterFactory = ff -} - -func (fs *FilterSuite) TearDownSuite() { - -} - -// ********************************************* Tests ********************************************* - -func (fs *FilterSuite) Test_FilterIntegersEquals() { - fd := &FilterData{"integer", "==", "5"} - filter, err := fs.filterFactory.NewFilter([]*FilterData{fd}) - fs.NoError(err) - arr := []FilterableObject{} - for _, o := range fs.objects { - if filter.Match(o) { - arr = append(arr, o) - break - } - } - fs.Equal(arr, fs.objects[5:6]) -} - -func (fs *FilterSuite) Test_FilterIntegersLT() { - fd := &FilterData{"integer", "<", "5"} - filter, err := fs.filterFactory.NewFilter([]*FilterData{fd}) - fs.NoError(err) - arr := []FilterableObject{} - for _, o := range fs.objects { - if filter.Match(o) { - arr = append(arr, o) - } - } - fs.Equal(arr, fs.objects[:5]) -} - -func (fs *FilterSuite) Test_FilterIntegersLTEQ() { - fd := &FilterData{"integer", "<=", "10"} - filter, err := fs.filterFactory.NewFilter([]*FilterData{fd}) - fs.NoError(err) - arr := []FilterableObject{} - for _, o := range fs.objects { - if filter.Match(o) { - arr = append(arr, o) - } - } - fs.Equal(arr, fs.objects[:11]) -} - -func (fs *FilterSuite) Test_FilterIntegersGT() { - fd := &FilterData{"integer", ">", "50"} - filter, err := fs.filterFactory.NewFilter([]*FilterData{fd}) - fs.NoError(err) - arr := []FilterableObject{} - for _, o := range fs.objects { - if filter.Match(o) { - arr = append(arr, o) - } - } - fs.Equal(arr, fs.objects[51:]) -} - -func (fs *FilterSuite) Test_FilterIntegersRange() { - fd0 := &FilterData{"integer", ">", "5"} - fd1 := &FilterData{"integer", "<", "38"} - filter, err := fs.filterFactory.NewFilter([]*FilterData{fd0, fd1}) - fs.NoError(err) - arr := []FilterableObject{} - for _, o := range fs.objects { - if filter.Match(o) { - arr = append(arr, o) - } - } - fs.Equal(arr, fs.objects[6:38]) -} - -func (fs *FilterSuite) Test_FilterIntegersGTEQ() { - fd := &FilterData{"integer", ">=", "77"} - filter, err := fs.filterFactory.NewFilter([]*FilterData{fd}) - fs.NoError(err) - arr := []FilterableObject{} - for _, o := range fs.objects { - if filter.Match(o) { - arr = append(arr, o) - } - } - fs.Equal(arr, fs.objects[77:]) -} - -func (fs *FilterSuite) Test_FilterIntegersNEQ() { - fd := &FilterData{"integer", "!=", "50"} - filter, err := fs.filterFactory.NewFilter([]*FilterData{fd}) - fs.NoError(err) - arr := []FilterableObject{} - for _, o := range fs.objects { - if filter.Match(o) { - arr = append(arr, o) - } - } - res := make([]FilterableObject, OBJECTS) - copy(res, fs.objects) - res = append(res[:50], res[51:]...) - fs.Equal(arr, res) -} - -func (fs *FilterSuite) Test_FilterStringEquals() { - fd := &FilterData{"string", "==", "string7"} - filter, err := fs.filterFactory.NewFilter([]*FilterData{fd}) - fs.NoError(err) - arr := []FilterableObject{} - for _, o := range fs.objects { - if filter.Match(o) { - arr = append(arr, o) - } - } - fs.Equal(arr, fs.objects[7:8]) -} - -func (fs *FilterSuite) Test_FilterStringNEQ() { - fd := &FilterData{"string", "!=", "string50"} - filter, err := fs.filterFactory.NewFilter([]*FilterData{fd}) - fs.NoError(err) - arr := []FilterableObject{} - - for _, o := range fs.objects { - if filter.Match(o) { - arr = append(arr, o) - } - } - res := make([]FilterableObject, OBJECTS) - copy(res, fs.objects) - res = append(res[:50], res[51:]...) - fs.Equal(arr, res) -} - -// ********************************************* Entrypoint ********************************************* - -func TestFilterSuite(t *testing.T) { - suite.Run(t, &FilterSuite{}) -} diff --git a/rpc/filters/namereg.go b/rpc/filters/namereg.go deleted file mode 100644 index 6d822fb17..000000000 --- a/rpc/filters/namereg.go +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package filters - -import ( - "bytes" - "encoding/hex" - "fmt" - "sync" - - "github.com/hyperledger/burrow/execution/names" -) - -func NewNameRegFilterFactory() *FilterFactory { - filterFactory := NewFilterFactory() - - filterFactory.RegisterFilterPool("name", &sync.Pool{ - New: func() interface{} { - return &NameRegNameFilter{} - }, - }) - - filterFactory.RegisterFilterPool("owner", &sync.Pool{ - New: func() interface{} { - return &NameRegOwnerFilter{} - }, - }) - - filterFactory.RegisterFilterPool("data", &sync.Pool{ - New: func() interface{} { - return &NameRegDataFilter{} - }, - }) - - filterFactory.RegisterFilterPool("expires", &sync.Pool{ - New: func() interface{} { - return &NameRegExpiresFilter{} - }, - }) - - return filterFactory -} - -// Filter for namereg name. This should not be used to get individual entries by name. -// Ops: == or != -type NameRegNameFilter struct { - op string - value string - match func(string, string) bool -} - -func (nrnf *NameRegNameFilter) Configure(fd *FilterData) error { - op := fd.Op - val := fd.Value - - if op == "==" { - nrnf.match = func(a, b string) bool { - return a == b - } - } else if op == "!=" { - nrnf.match = func(a, b string) bool { - return a != b - } - } else { - return fmt.Errorf("Op: " + nrnf.op + " is not supported for 'name' filtering") - } - nrnf.op = op - nrnf.value = val - return nil -} - -func (nrnf *NameRegNameFilter) Match(v interface{}) bool { - nre, ok := v.(*names.Entry) - if !ok { - return false - } - return nrnf.match(nre.Name, nrnf.value) -} - -// Filter for owner. -// Ops: == or != -type NameRegOwnerFilter struct { - op string - value []byte - match func([]byte, []byte) bool -} - -func (nrof *NameRegOwnerFilter) Configure(fd *FilterData) error { - op := fd.Op - val, err := hex.DecodeString(fd.Value) - - if err != nil { - return fmt.Errorf("wrong value type.") - } - if op == "==" { - nrof.match = func(a, b []byte) bool { - return bytes.Equal(a, b) - } - } else if op == "!=" { - nrof.match = func(a, b []byte) bool { - return !bytes.Equal(a, b) - } - } else { - return fmt.Errorf("Op: " + nrof.op + " is not supported for 'owner' filtering") - } - nrof.op = op - nrof.value = val - return nil -} - -func (nrof *NameRegOwnerFilter) Match(v interface{}) bool { - nre, ok := v.(*names.Entry) - if !ok { - return false - } - return nrof.match(nre.Owner.Bytes(), nrof.value) -} - -// Filter for namereg data. Useful for example if you store an ipfs hash and know the hash but need the key. -// Ops: == or != -type NameRegDataFilter struct { - op string - value string - match func(string, string) bool -} - -func (nrdf *NameRegDataFilter) Configure(fd *FilterData) error { - op := fd.Op - val := fd.Value - - if op == "==" { - nrdf.match = func(a, b string) bool { - return a == b - } - } else if op == "!=" { - nrdf.match = func(a, b string) bool { - return a != b - } - } else { - return fmt.Errorf("Op: " + nrdf.op + " is not supported for 'data' filtering") - } - nrdf.op = op - nrdf.value = val - return nil -} - -func (nrdf *NameRegDataFilter) Match(v interface{}) bool { - nre, ok := v.(*names.Entry) - if !ok { - return false - } - return nrdf.match(nre.Data, nrdf.value) -} - -// Filter for expires. -// Ops: All -type NameRegExpiresFilter struct { - op string - value uint64 - match func(uint64, uint64) bool -} - -func (nref *NameRegExpiresFilter) Configure(fd *FilterData) error { - val, err := ParseNumberValue(fd.Value) - if err != nil { - return err - } - match, err2 := GetRangeFilter(fd.Op, "expires") - if err2 != nil { - return err2 - } - nref.match = match - nref.op = fd.Op - nref.value = val - return nil -} - -func (nref *NameRegExpiresFilter) Match(v interface{}) bool { - nre, ok := v.(*names.Entry) - if !ok { - return false - } - return nref.match(nre.Expires, nref.value) -} diff --git a/rpc/grpc.go b/rpc/grpc.go index a30bdad14..c1a17233c 100644 --- a/rpc/grpc.go +++ b/rpc/grpc.go @@ -2,7 +2,6 @@ package rpc import ( "fmt" - "runtime/debug" "github.com/hyperledger/burrow/logging" @@ -25,7 +24,7 @@ func unaryInterceptor(logger *logging.Logger) grpc.UnaryServerInterceptor { defer func() { if r := recover(); r != nil { logger.InfoMsg("panic in GRPC unary call", structure.ErrorKey, fmt.Sprintf("%v", r)) - err = fmt.Errorf("panic in GRPC unary call %s: %v", info.FullMethod, r) + err = fmt.Errorf("panic in GRPC unary call %s: %v: %s", info.FullMethod, r, debug.Stack()) } }() logger.TraceMsg("GRPC unary call") diff --git a/rpc/lib/client/ws_client.go b/rpc/lib/client/ws_client.go index e18a6cfb6..e93f06908 100644 --- a/rpc/lib/client/ws_client.go +++ b/rpc/lib/client/ws_client.go @@ -12,7 +12,7 @@ import ( "github.com/gorilla/websocket" "github.com/hyperledger/burrow/rpc/lib/types" "github.com/pkg/errors" - "github.com/rcrowley/go-metrics" + metrics "github.com/rcrowley/go-metrics" cmn "github.com/tendermint/tmlibs/common" ) diff --git a/rpc/lib/server/http_params.go b/rpc/lib/server/http_params.go index 248e451b2..cd18cd102 100644 --- a/rpc/lib/server/http_params.go +++ b/rpc/lib/server/http_params.go @@ -1,12 +1,12 @@ package server import ( + "encoding/hex" "net/http" "regexp" "strconv" "github.com/pkg/errors" - "github.com/tmthrgd/go-hex" ) var ( diff --git a/rpc/result.go b/rpc/result.go index 44a61c1d7..af777d940 100644 --- a/rpc/result.go +++ b/rpc/result.go @@ -15,17 +15,11 @@ package rpc import ( - "encoding/json" - "fmt" - "time" - acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/execution" - "github.com/hyperledger/burrow/execution/events" - "github.com/hyperledger/burrow/execution/events/pbevents" "github.com/hyperledger/burrow/execution/names" "github.com/hyperledger/burrow/genesis" "github.com/hyperledger/burrow/txs" @@ -50,25 +44,12 @@ type ResultGetStorage struct { Value binary.HexBytes } -type ResultCall struct { - execution.Call -} - -func (rc ResultCall) MarshalJSON() ([]byte, error) { - return json.Marshal(rc.Call) -} - -func (rc *ResultCall) UnmarshalJSON(data []byte) (err error) { - return json.Unmarshal(data, &rc.Call) -} - type ResultListAccounts struct { BlockHeight uint64 Accounts []*acm.ConcreteAccount } type ResultDumpStorage struct { - StorageRoot binary.HexBytes StorageItems []StorageItem } @@ -188,7 +169,6 @@ type AccountHumanReadable struct { Sequence uint64 Balance uint64 Code []string - StorageRoot string Permissions []string Roles []string } @@ -197,18 +177,6 @@ type ResultGetAccountHumanReadable struct { Account *AccountHumanReadable } -type ResultBroadcastTx struct { - txs.Receipt -} - -func (rbt ResultBroadcastTx) MarshalJSON() ([]byte, error) { - return json.Marshal(rbt.Receipt) -} - -func (rbt ResultBroadcastTx) UnmarshalJSON(data []byte) (err error) { - return json.Unmarshal(data, &rbt.Receipt) -} - type ResultListUnconfirmedTxs struct { NumTxs int Txs []*txs.Envelope @@ -225,67 +193,3 @@ type ResultGenesis struct { type ResultSignTx struct { Tx *txs.Envelope } - -type TendermintEvent struct { - tmTypes.TMEventData -} - -func (te TendermintEvent) MarshalJSON() ([]byte, error) { - return aminoCodec.MarshalJSON(te.TMEventData) -} - -func (te *TendermintEvent) UnmarshalJSON(data []byte) (err error) { - return aminoCodec.UnmarshalJSON(data, &te.TMEventData) -} - -func (te *TendermintEvent) EventDataNewBlock() *tmTypes.EventDataNewBlock { - if te != nil { - eventData, _ := te.TMEventData.(tmTypes.EventDataNewBlock) - return &eventData - } - return nil -} - -type ResultEvent struct { - Event string - Tendermint *TendermintEvent `json:",omitempty"` - Execution *events.Event `json:",omitempty"` -} - -// Map any supported event data element to our ResultEvent sum type -func NewResultEvent(event string, eventData interface{}) (*ResultEvent, error) { - res := &ResultEvent{ - Event: event, - } - switch ed := eventData.(type) { - case tmTypes.TMEventData: - res.Tendermint = &TendermintEvent{ed} - case *events.Event: - res.Execution = ed - default: - return nil, fmt.Errorf("could not map event data of type %T to ResultEvent", eventData) - } - return res, nil -} - -func (re *ResultEvent) GetEvent() (*pbevents.Event, error) { - ev := &pbevents.Event{ - Name: re.Event, - } - if re.Tendermint != nil { - bs, err := json.Marshal(re.Tendermint) - if err != nil { - return nil, err - } - ev.Event = &pbevents.Event_TendermintEventJSON{ - TendermintEventJSON: string(bs), - } - } else if re.Execution != nil { - ev.Event = &pbevents.Event_ExecutionEvent{ - ExecutionEvent: pbevents.GetExecutionEvent(re.Execution), - } - } else { - return nil, fmt.Errorf("ResultEvent is empty") - } - return ev, nil -} diff --git a/rpc/result_test.go b/rpc/result_test.go index ade8a6157..ca972de49 100644 --- a/rpc/result_test.go +++ b/rpc/result_test.go @@ -22,12 +22,8 @@ import ( "fmt" - acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/binary" - "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/execution" - "github.com/hyperledger/burrow/txs" - "github.com/hyperledger/burrow/txs/payload" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" goCrypto "github.com/tendermint/go-crypto" @@ -36,36 +32,6 @@ import ( "github.com/tendermint/tmlibs/common" ) -func TestResultBroadcastTx(t *testing.T) { - // Make sure these are unpacked as expected - res := ResultBroadcastTx{ - Receipt: txs.Receipt{ - ContractAddress: crypto.Address{0, 2, 3}, - CreatesContract: true, - TxHash: []byte("foo"), - }, - } - - bs, err := json.Marshal(res) - require.NoError(t, err) - assert.Equal(t, `{"TxHash":"666F6F","CreatesContract":true,"ContractAddress":"0002030000000000000000000000000000000000"}`, string(bs)) -} - -func TestListUnconfirmedTxs(t *testing.T) { - res := &ResultListUnconfirmedTxs{ - NumTxs: 3, - Txs: []*txs.Envelope{ - txs.Enclose("testChain", &payload.CallTx{ - Address: &crypto.Address{1}, - }), - }, - } - bs, err := json.Marshal(res) - require.NoError(t, err) - assert.Equal(t, "{\"NumTxs\":3,\"Txs\":[{\"Signatories\":null,\"Tx\":{\"ChainID\":\"testChain\",\"Type\":\"CallTx\",\"Payload\":{\"Input\":null,\"Address\":\"0100000000000000000000000000000000000000\",\"GasLimit\":0,\"Fee\":0}}}]}", - string(bs)) -} - func TestResultListAccounts(t *testing.T) { concreteAcc := acm.AsConcreteAccount(acm.FromAddressable( acm.GeneratePrivateAccountFromSecret("Super Semi Secret"))) @@ -83,56 +49,6 @@ func TestResultListAccounts(t *testing.T) { assert.Equal(t, string(bs), string(bsOut)) } -func TestResultCall_MarshalJSON(t *testing.T) { - res := ResultCall{ - Call: execution.Call{ - Return: []byte("hi"), - GasUsed: 1, - }, - } - bs, err := json.Marshal(res) - require.NoError(t, err) - - resOut := new(ResultCall) - json.Unmarshal(bs, resOut) - bsOut, err := json.Marshal(resOut) - require.NoError(t, err) - assert.Equal(t, string(bs), string(bsOut)) -} - -func TestResultEvent(t *testing.T) { - eventDataNewBlock := tmTypes.EventDataNewBlock{ - Block: &tmTypes.Block{ - Header: &tmTypes.Header{ - ChainID: "chainy", - NumTxs: 30, - }, - LastCommit: &tmTypes.Commit{ - Precommits: []*tmTypes.Vote{ - { - Signature: goCrypto.SignatureEd25519{1, 2, 3}, - }, - }, - }, - }, - } - res := ResultEvent{ - Tendermint: &TendermintEvent{ - TMEventData: &eventDataNewBlock, - }, - } - bs, err := json.Marshal(res) - require.NoError(t, err) - - resOut := new(ResultEvent) - require.NoError(t, json.Unmarshal(bs, resOut)) - bsOut, err := json.Marshal(resOut) - require.NoError(t, err) - assert.Equal(t, string(bs), string(bsOut)) - //fmt.Println(string(bs)) - //fmt.Println(string(bsOut)) -} - func TestResultGetBlock(t *testing.T) { res := &ResultGetBlock{ Block: &Block{&tmTypes.Block{ diff --git a/execution/events/pbevents/blocks.go b/rpc/rpcevents/blocks.go similarity index 72% rename from execution/events/pbevents/blocks.go rename to rpc/rpcevents/blocks.go index b2df626d2..b016207fe 100644 --- a/execution/events/pbevents/blocks.go +++ b/rpc/rpcevents/blocks.go @@ -1,18 +1,12 @@ -package pbevents - -import "github.com/hyperledger/burrow/execution/events" +package rpcevents // Get bounds suitable for events.Provider -func (br *BlockRange) Bounds(latestBlockHeight uint64) (startKey, endKey events.Key, streaming bool) { +func (br *BlockRange) Bounds(latestBlockHeight uint64) (startHeight, endHeight uint64, streaming bool) { // End bound is exclusive in state.GetEvents so we increment the height - return br.GetStart().Key(latestBlockHeight), br.GetEnd().Key(latestBlockHeight).IncHeight(), + return br.GetStart().Bound(latestBlockHeight), br.GetEnd().Bound(latestBlockHeight) + 1, br.GetEnd().GetType() == Bound_STREAM } -func (b *Bound) Key(latestBlockHeight uint64) events.Key { - return events.NewKey(b.Bound(latestBlockHeight), 0) -} - func (b *Bound) Bound(latestBlockHeight uint64) uint64 { if b == nil { return latestBlockHeight diff --git a/execution/events/pbevents/blocks_test.go b/rpc/rpcevents/blocks_test.go similarity index 56% rename from execution/events/pbevents/blocks_test.go rename to rpc/rpcevents/blocks_test.go index a7a05b47e..e773a84e7 100644 --- a/execution/events/pbevents/blocks_test.go +++ b/rpc/rpcevents/blocks_test.go @@ -1,9 +1,8 @@ -package pbevents +package rpcevents import ( "testing" - "github.com/hyperledger/burrow/execution/events" "github.com/stretchr/testify/assert" ) @@ -11,7 +10,7 @@ func TestBlockRange_Bounds(t *testing.T) { latestHeight := uint64(2344) br := &BlockRange{} start, end, streaming := br.Bounds(latestHeight) - assert.Equal(t, events.NewKey(latestHeight, 0), start) - assert.Equal(t, events.NewKey(latestHeight+1, 0), end) + assert.Equal(t, latestHeight, start) + assert.Equal(t, latestHeight+1, end) assert.False(t, streaming) } diff --git a/rpc/rpcevents/events_server.go b/rpc/rpcevents/events_server.go deleted file mode 100644 index 699edcbff..000000000 --- a/rpc/rpcevents/events_server.go +++ /dev/null @@ -1,57 +0,0 @@ -package rpcevents - -import ( - "github.com/hyperledger/burrow/execution/events/pbevents" - "github.com/hyperledger/burrow/rpc" - "golang.org/x/net/context" -) - -type eventServer struct { - subscriptions *rpc.Subscriptions -} - -func NewEventsServer(subscriptions *rpc.Subscriptions) pbevents.EventsServer { - return &eventServer{ - subscriptions: subscriptions, - } -} - -func (es *eventServer) EventPoll(ctx context.Context, param *pbevents.SubIdParam) (*pbevents.PollResponse, error) { - msgs, err := es.subscriptions.Poll(param.GetSubId()) - if err != nil { - return nil, err - } - resp := &pbevents.PollResponse{ - Events: make([]*pbevents.Event, 0, len(msgs)), - } - for _, msg := range msgs { - if resultEvent, ok := msg.(*rpc.ResultEvent); ok { - ev, err := resultEvent.GetEvent() - if err != nil { - return nil, err - } - resp.Events = append(resp.Events, ev) - } - } - return resp, nil -} - -func (es *eventServer) EventSubscribe(ctx context.Context, param *pbevents.EventIdParam) (*pbevents.SubIdParam, error) { - subID, err := es.subscriptions.Add(param.GetEventId()) - if err != nil { - return nil, err - } - return &pbevents.SubIdParam{ - SubId: subID, - }, nil -} - -func (es *eventServer) EventUnsubscribe(ctx context.Context, param *pbevents.SubIdParam) (*pbevents.EventUnSub, error) { - err := es.subscriptions.Remove(param.GetSubId()) - if err != nil { - return nil, err - } - return &pbevents.EventUnSub{ - Result: true, - }, nil -} diff --git a/rpc/rpcevents/execution_events_server.go b/rpc/rpcevents/execution_events_server.go index 57645b8bb..2b042c77f 100644 --- a/rpc/rpcevents/execution_events_server.go +++ b/rpc/rpcevents/execution_events_server.go @@ -1,113 +1,270 @@ package rpcevents import ( + "context" "fmt" - "context" + "io" + "github.com/gogo/protobuf/proto" bcm "github.com/hyperledger/burrow/blockchain" - "github.com/hyperledger/burrow/consensus/tendermint" "github.com/hyperledger/burrow/event" "github.com/hyperledger/burrow/event/query" - "github.com/hyperledger/burrow/execution/events" - "github.com/hyperledger/burrow/execution/events/pbevents" - "github.com/tendermint/tendermint/libs/pubsub" + "github.com/hyperledger/burrow/execution/exec" + "github.com/hyperledger/burrow/logging" + "google.golang.org/grpc" ) +const SubscribeBufferSize = 100 + +type Provider interface { + // Get a particular BlockExecution + GetBlock(height uint64) (*exec.BlockExecution, error) + // Get a partiualr TxExecution by hash + GetTx(txHash []byte) (*exec.TxExecution, error) + // Get events between startKey (inclusive) and endKey (exclusive) - i.e. the half open interval [start, end) + GetBlocks(startHeight, endHeight uint64, consumer func(*exec.BlockExecution) (stop bool)) (stopped bool, err error) +} + type executionEventsServer struct { - eventsProvider events.Provider - emitter event.Emitter + eventsProvider Provider + subscribable event.Subscribable tip bcm.TipInfo + logger *logging.Logger } -func NewExecutionEventsServer(eventsProvider events.Provider, emitter event.Emitter, - tip bcm.TipInfo) pbevents.ExecutionEventsServer { +func NewExecutionEventsServer(eventsProvider Provider, subscribable event.Subscribable, + tip bcm.TipInfo, logger *logging.Logger) ExecutionEventsServer { return &executionEventsServer{ eventsProvider: eventsProvider, - emitter: emitter, + subscribable: subscribable, tip: tip, + logger: logger.WithScope("NewExecutionEventsServer"), } } -func (ees *executionEventsServer) GetEvents(request *pbevents.GetEventsRequest, - stream pbevents.ExecutionEvents_GetEventsServer) error { +func (ees *executionEventsServer) GetBlock(ctx context.Context, request *GetBlockRequest) (*exec.BlockExecution, error) { + be, err := ees.eventsProvider.GetBlock(request.GetHeight()) + if err != nil { + return nil, err + } + if be != nil { + return be, nil + } + if !request.Wait { + if ees.tip.LastBlockHeight() < request.Height { + return nil, fmt.Errorf("block at height %v not yet produced (last block height: %v)", + request.Height, ees.tip.LastBlockHeight()) + } + return nil, fmt.Errorf("block at height %v not found in state but should have been! (last block height: %v)", + request.Height, ees.tip.LastBlockHeight()) + } + err = ees.streamBlocks(ctx, &BlockRange{End: StreamBound()}, func(block *exec.BlockExecution) error { + if block.Height == request.Height { + be = block + return io.EOF + } + return nil + }) + if err != io.EOF { + return nil, err + } + return be, nil +} - blockRange := request.GetBlockRange() - start, end, streaming := blockRange.Bounds(ees.tip.LastBlockHeight()) +func (ees *executionEventsServer) GetBlocks(request *BlocksRequest, stream ExecutionEvents_GetBlocksServer) error { qry, err := query.NewBuilder(request.Query).Query() if err != nil { - return fmt.Errorf("could not parse event query: %v", err) + return fmt.Errorf("could not parse BlockExecution query: %v", err) + } + return ees.streamBlocks(stream.Context(), request.BlockRange, func(block *exec.BlockExecution) error { + if qry.Matches(block.Tagged()) { + return flush(stream, block) + } + return nil + }) +} + +func (ees *executionEventsServer) GetTx(ctx context.Context, request *GetTxRequest) (*exec.TxExecution, error) { + txe, err := ees.eventsProvider.GetTx(request.TxHash) + if err != nil { + return nil, err + } + if txe != nil { + return txe, nil + } + if !request.Wait { + return nil, fmt.Errorf("transaction with hash %v not found in state", request.TxHash) + } + subID := event.GenSubID() + out, err := ees.subscribable.Subscribe(ctx, subID, exec.QueryForTxExecution(request.TxHash), SubscribeBufferSize) + if err != nil { + return nil, err + } + defer ees.subscribable.UnsubscribeAll(ctx, subID) + for msg := range out { + select { + case <-ctx.Done(): + return nil, ctx.Err() + default: + return msg.(*exec.TxExecution), nil + } } + return nil, fmt.Errorf("subscription waiting for tx %v ended prematurely", request.TxHash) +} - if !streaming { - return ees.steamEvents(stream, start, end, 1, qry) +func (ees *executionEventsServer) GetTxs(request *BlocksRequest, stream ExecutionEvents_GetTxsServer) error { + qry, err := query.NewBuilder(request.Query).Query() + if err != nil { + return fmt.Errorf("could not parse TxExecution query: %v", err) } + return ees.streamBlocks(stream.Context(), request.BlockRange, func(block *exec.BlockExecution) error { + txs := filterTxs(block, qry) + if len(txs) > 0 { + response := &GetTxsResponse{ + Height: block.Height, + TxExecutions: txs, + } + return flush(stream, response) + } + return nil + }) +} - // Streaming +func (ees *executionEventsServer) GetEvents(request *BlocksRequest, stream ExecutionEvents_GetEventsServer) error { + qry, err := query.NewBuilder(request.Query).Query() if err != nil { + return fmt.Errorf("could not parse Event query: %v", err) + } + return ees.streamBlocks(stream.Context(), request.BlockRange, func(block *exec.BlockExecution) error { + evs := filterEvents(block, qry) + if len(evs) == 0 { + return nil + } + response := &GetEventsResponse{ + Height: block.Height, + Events: evs, + } + return flush(stream, response) + }) +} + +func (ees *executionEventsServer) streamBlocks(ctx context.Context, blockRange *BlockRange, + consumer func(*exec.BlockExecution) error) error { + + // Converts the bounds to half-open interval needed + start, end, streaming := blockRange.Bounds(ees.tip.LastBlockHeight()) + ees.logger.TraceMsg("Streaming blocks", "start", start, "end", end, "streaming", streaming) + + // Pull blocks from state and receive the upper bound (exclusive) on the what we were able to send + // Set this to start since it will be the start of next streaming batch (if needed) + start, err := ees.iterateBlocks(start, end, consumer) + + // If we are not streaming and all blocks requested were retrieved from state then we are done + if !streaming && start == end { return err } - out, err := tendermint.SubscribeNewBlock(context.Background(), ees.emitter) + // Otherwise we need to begin streaming blocks as they are produced + subID := event.GenSubID() + // Subscribe to BlockExecution events + out, err := ees.subscribable.Subscribe(ctx, subID, exec.QueryForBlockExecutionFromHeight(end), + SubscribeBufferSize) if err != nil { return err } + defer ees.subscribable.UnsubscribeAll(context.Background(), subID) - for newBlock := range out { - if newBlock == nil { - return fmt.Errorf("received non-new-block event when subscribed with query") - } - if newBlock.Block == nil { - return fmt.Errorf("new block contains no block info: %v", newBlock) - } - height := uint64(newBlock.Block.Height) - start = end - end = events.NewKey(height, 0) - err := ees.steamEvents(stream, start, end, 1, qry) - if err != nil { - return err + for msg := range out { + select { + case <-ctx.Done(): + return ctx.Err() + default: + block := msg.(*exec.BlockExecution) + streamEnd := block.Height + + finished := !streaming && streamEnd >= end + if finished { + // Truncate streamEnd to final end to get exactly the blocks we want from state + streamEnd = end + } + if start < streamEnd { + // This implies there are some blocks between the previous batchEnd (now start) and the current BlockExecution that + // we have not emitted so we will pull them from state. This can occur if a block is emitted during/after + // the initial streaming but before we have subscribed to block events or if we spill BlockExecutions + // when streaming them and need to catch up + _, err := ees.iterateBlocks(start, streamEnd, consumer) + if err != nil { + return err + } + } + if finished { + return nil + } + err = consumer(block) + if err != nil { + return err + } + // We've just streamed block so our next start marker is the next block + start = block.Height + 1 } } return nil } -func (ees *executionEventsServer) steamEvents(stream pbevents.ExecutionEvents_GetEventsServer, start, end events.Key, - batchSize uint64, qry pubsub.Query) error { - +// Converts blocks into responses and streams them returning the height one greater than the last seen block +// that can be used as next start point (half-open interval) +func (ees *executionEventsServer) iterateBlocks(start, end uint64, consumer func(*exec.BlockExecution) error) (uint64, error) { var streamErr error - buf := new(pbevents.GetEventsResponse) - - batchStart := start.Height() - _, err := ees.eventsProvider.GetEvents(start, end, func(ev *events.Event) (stop bool) { - if qry.Matches(ev) { - // Start a new batch, flush the last lot - if ev.Header.Index == 0 && (ev.Header.Height-batchStart)%batchSize == 0 { - streamErr = flush(stream, buf) - if streamErr != nil { - return true - } - batchStart = ev.Header.Height - buf = new(pbevents.GetEventsResponse) + var lastHeightSeen uint64 + + _, err := ees.eventsProvider.GetBlocks(start, end, + func(be *exec.BlockExecution) (stop bool) { + lastHeightSeen = be.Height + streamErr = consumer(be) + if streamErr != nil { + return true } - buf.Events = append(buf.Events, pbevents.GetExecutionEvent(ev)) - } - return false - }) + return false + }) + if err != nil { - return err + return 0, err } if streamErr != nil { - return streamErr + return 0, streamErr + } + // Returns the appropriate starting block for the next stream + return lastHeightSeen + 1, nil +} + +func filterTxs(be *exec.BlockExecution, qry query.Query) []*exec.TxExecution { + var txs []*exec.TxExecution + for _, txe := range be.TxExecutions { + if qry.Matches(txe.Tagged()) { + txs = append(txs, txe) + } + } + return txs +} + +func filterEvents(be *exec.BlockExecution, qry query.Query) []*exec.Event { + var evs []*exec.Event + for _, txe := range be.TxExecutions { + for _, ev := range txe.Events { + if qry.Matches(ev.Tagged()) { + evs = append(evs, ev) + } + } } - // Flush any remaining events not filling batchSize many blocks - return flush(stream, buf) + return evs } -func flush(stream pbevents.ExecutionEvents_GetEventsServer, buf *pbevents.GetEventsResponse) error { - if len(buf.Events) > 0 { - err := stream.Send(buf) +func flush(stream grpc.Stream, buf proto.Message) error { + if buf != nil { + err := stream.SendMsg(buf) if err != nil { return err } diff --git a/rpc/rpcevents/integration/events_server_test.go b/rpc/rpcevents/integration/events_server_test.go deleted file mode 100644 index 0e8aebb14..000000000 --- a/rpc/rpcevents/integration/events_server_test.go +++ /dev/null @@ -1,130 +0,0 @@ -// +build integration - -// Space above here matters -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package integration - -import ( - "context" - "testing" - "time" - - "encoding/json" - - "strings" - - "github.com/hyperledger/burrow/binary" - "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/execution/events" - "github.com/hyperledger/burrow/execution/events/pbevents" - "github.com/hyperledger/burrow/rpc" - "github.com/hyperledger/burrow/rpc/test" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - tmTypes "github.com/tendermint/tendermint/types" -) - -const eventWait = 2 * time.Second - -func TestEventSubscribeNewBlock(t *testing.T) { - testEventSubscribe(t, tmTypes.EventNewBlock, nil, func(evs []*pbevents.Event) { - require.True(t, len(evs) > 0, "event poll should return at least 1 event") - tendermintEvent := new(rpc.TendermintEvent) - tendermintEventJSON := evs[0].GetTendermintEventJSON() - require.NoError(t, json.Unmarshal([]byte(tendermintEventJSON), tendermintEvent)) - newBlock, ok := tendermintEvent.TMEventData.(tmTypes.EventDataNewBlock) - require.True(t, ok, "new block event expected") - assert.Equal(t, genesisDoc.ChainID(), newBlock.Block.ChainID) - }) -} - -func TestEventSubscribeCall(t *testing.T) { - cli := test.NewTransactorClient(t) - create := test.CreateContract(t, cli, inputAccount) - address, err := crypto.AddressFromBytes(create.CallData.Callee) - require.NoError(t, err) - testEventSubscribe(t, events.EventStringAccountCall(address), - func() { - t.Logf("Calling contract at: %v", address) - test.CallContract(t, cli, inputAccount, address.Bytes()) - }, - func(evs []*pbevents.Event) { - require.Len(t, evs, test.UpsieDownsieCallCount, "should see 30 recursive call events") - for i, ev := range evs { - assert.Equal(t, uint64(test.UpsieDownsieCallCount-i-1), ev.GetExecutionEvent().GetEventDataCall().GetStackDepth()) - } - }) -} - -func TestEventSubscribeLog(t *testing.T) { - cli := test.NewTransactorClient(t) - create := test.CreateContract(t, cli, inputAccount) - address, err := crypto.AddressFromBytes(create.CallData.Callee) - require.NoError(t, err) - testEventSubscribe(t, events.EventStringLogEvent(address), - func() { - t.Logf("Calling contract at: %v", address) - test.CallContract(t, cli, inputAccount, address.Bytes()) - }, - func(evs []*pbevents.Event) { - require.Len(t, evs, test.UpsieDownsieCallCount-2) - log := evs[0].GetExecutionEvent().GetEventDataLog() - depth := binary.Int64FromWord256(binary.LeftPadWord256(log.Topics[2])) - direction := strings.TrimRight(string(log.Topics[1]), "\x00") - assert.Equal(t, int64(18), depth) - assert.Equal(t, "Upsie!", direction) - }) -} - -func testEventSubscribe(t *testing.T, eventID string, runner func(), eventsCallback func(evs []*pbevents.Event)) { - cli := test.NewEventsClient(t) - t.Logf("Subscribing to event: %s", eventID) - sub, err := cli.EventSubscribe(context.Background(), &pbevents.EventIdParam{ - EventId: eventID, - }) - require.NoError(t, err) - defer cli.EventUnsubscribe(context.Background(), sub) - - if runner != nil { - go runner() - } - - pollCh := make(chan *pbevents.PollResponse) - errCh := make(chan error) - // Catch a single block of events - go func() { - for { - time.Sleep(eventWait) - poll, err := cli.EventPoll(context.Background(), sub) - if err != nil { - errCh <- err - return - } - if len(poll.Events) > 0 { - pollCh <- poll - } - } - }() - //var evs []*pbevents.Event - select { - case err := <-errCh: - require.NoError(t, err, "should be no error from EventPoll") - case poll := <-pollCh: - eventsCallback(poll.Events) - case <-time.After(2 * eventWait): - t.Fatal("timed out waiting for poll event") - } -} diff --git a/rpc/rpcevents/integration/execution_events_server_test.go b/rpc/rpcevents/integration/execution_events_server_test.go deleted file mode 100644 index cdd80b1df..000000000 --- a/rpc/rpcevents/integration/execution_events_server_test.go +++ /dev/null @@ -1,118 +0,0 @@ -// +build integration - -// Space above here matters -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package integration - -import ( - "context" - "testing" - - "io" - - "github.com/hyperledger/burrow/event" - "github.com/hyperledger/burrow/event/query" - "github.com/hyperledger/burrow/execution/events" - "github.com/hyperledger/burrow/execution/events/pbevents" - "github.com/hyperledger/burrow/execution/pbtransactor" - "github.com/hyperledger/burrow/rpc/test" - "github.com/hyperledger/burrow/txs/payload" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestExecutionEventsSendStream(t *testing.T) { - request := &pbevents.GetEventsRequest{ - BlockRange: pbevents.NewBlockRange(pbevents.LatestBound(), pbevents.StreamBound()), - } - tcli := test.NewTransactorClient(t) - ecli := test.NewExecutionEventsClient(t) - stream, err := ecli.GetEvents(context.Background(), request) - require.NoError(t, err) - numSends := 1 - for i := 0; i < numSends; i++ { - doSends(t, 2, tcli) - response, err := stream.Recv() - require.NoError(t, err) - require.Len(t, response.Events, 4, "expect multiple events") - assert.Equal(t, payload.TypeSend.String(), response.Events[0].GetHeader().GetTxType()) - assert.Equal(t, payload.TypeSend.String(), response.Events[1].GetHeader().GetTxType()) - } - require.NoError(t, stream.CloseSend()) -} - -func TestExecutionEventsSend(t *testing.T) { - request := &pbevents.GetEventsRequest{ - BlockRange: pbevents.NewBlockRange(pbevents.AbsoluteBound(kern.Blockchain.LastBlockHeight()), - pbevents.AbsoluteBound(300)), - } - numSends := 1100 - responses := testExecutionEventsSend(t, numSends, request) - assert.Equal(t, numSends*2, totalEvents(responses), "should receive and input and output event per send") -} - -func TestExecutionEventsSendFiltered(t *testing.T) { - request := &pbevents.GetEventsRequest{ - BlockRange: pbevents.NewBlockRange(pbevents.AbsoluteBound(kern.Blockchain.LastBlockHeight()), - pbevents.AbsoluteBound(300)), - Query: query.NewBuilder().AndEquals(event.EventTypeKey, events.TypeAccountInput.String()).String(), - } - numSends := 500 - responses := testExecutionEventsSend(t, numSends, request) - assert.Equal(t, numSends, totalEvents(responses), "should receive a single input event per send") -} - -func testExecutionEventsSend(t *testing.T, numSends int, request *pbevents.GetEventsRequest) []*pbevents.GetEventsResponse { - doSends(t, numSends, test.NewTransactorClient(t)) - ecli := test.NewExecutionEventsClient(t) - - evs, err := ecli.GetEvents(context.Background(), request) - require.NoError(t, err) - var responses []*pbevents.GetEventsResponse - for { - resp, err := evs.Recv() - if err != nil { - if err == io.EOF { - break - } - require.NoError(t, err) - } - responses = append(responses, resp) - } - return responses -} - -func doSends(t *testing.T, numSends int, cli pbtransactor.TransactorClient) { - countCh := test.CommittedTxCount(t, kern.Emitter) - for i := 0; i < numSends; i++ { - send, err := cli.Send(context.Background(), &pbtransactor.SendParam{ - InputAccount: inputAccount, - Amount: 2003, - ToAddress: privateAccounts[3].Address().Bytes(), - }) - require.NoError(t, err) - assert.Equal(t, false, send.CreatesContract) - } - require.Equal(t, numSends, <-countCh) -} - -func totalEvents(respones []*pbevents.GetEventsResponse) int { - i := 0 - for _, resp := range respones { - i += len(resp.Events) - } - return i -} diff --git a/rpc/rpcevents/rpcevents.pb.go b/rpc/rpcevents/rpcevents.pb.go new file mode 100644 index 000000000..d7b9f9368 --- /dev/null +++ b/rpc/rpcevents/rpcevents.pb.go @@ -0,0 +1,1838 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: rpcevents.proto + +/* + Package rpcevents is a generated protocol buffer package. + + It is generated from these files: + rpcevents.proto + + It has these top-level messages: + GetBlockRequest + GetTxRequest + BlocksRequest + GetEventsResponse + GetTxsResponse + Bound + BlockRange +*/ +package rpcevents + +import proto "github.com/gogo/protobuf/proto" +import golang_proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" +import _ "github.com/gogo/protobuf/gogoproto" +import exec "github.com/hyperledger/burrow/execution/exec" + +import github_com_hyperledger_burrow_binary "github.com/hyperledger/burrow/binary" + +import context "golang.org/x/net/context" +import grpc "google.golang.org/grpc" + +import io "io" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = golang_proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package + +type Bound_BoundType int32 + +const ( + // Index is absolute index of an item + Bound_ABSOLUTE Bound_BoundType = 0 + // Index is an offset relative to last item + Bound_RELATIVE Bound_BoundType = 1 + // The first block + Bound_FIRST Bound_BoundType = 2 + // Ignore provided index and evaluate to latest index + Bound_LATEST Bound_BoundType = 3 + // Ignore provided index and stream new objects as they are generated + Bound_STREAM Bound_BoundType = 4 +) + +var Bound_BoundType_name = map[int32]string{ + 0: "ABSOLUTE", + 1: "RELATIVE", + 2: "FIRST", + 3: "LATEST", + 4: "STREAM", +} +var Bound_BoundType_value = map[string]int32{ + "ABSOLUTE": 0, + "RELATIVE": 1, + "FIRST": 2, + "LATEST": 3, + "STREAM": 4, +} + +func (x Bound_BoundType) String() string { + return proto.EnumName(Bound_BoundType_name, int32(x)) +} +func (Bound_BoundType) EnumDescriptor() ([]byte, []int) { return fileDescriptorRpcevents, []int{5, 0} } + +type GetBlockRequest struct { + // Height of block required + Height uint64 `protobuf:"varint,1,opt,name=Height,proto3" json:"Height,omitempty"` + // Whether to wait for the block to become available + Wait bool `protobuf:"varint,2,opt,name=Wait,proto3" json:"Wait,omitempty"` +} + +func (m *GetBlockRequest) Reset() { *m = GetBlockRequest{} } +func (m *GetBlockRequest) String() string { return proto.CompactTextString(m) } +func (*GetBlockRequest) ProtoMessage() {} +func (*GetBlockRequest) Descriptor() ([]byte, []int) { return fileDescriptorRpcevents, []int{0} } + +func (m *GetBlockRequest) GetHeight() uint64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *GetBlockRequest) GetWait() bool { + if m != nil { + return m.Wait + } + return false +} + +func (*GetBlockRequest) XXX_MessageName() string { + return "rpcevents.GetBlockRequest" +} + +type GetTxRequest struct { + // Height of block required + TxHash github_com_hyperledger_burrow_binary.HexBytes `protobuf:"bytes,1,opt,name=TxHash,proto3,customtype=github.com/hyperledger/burrow/binary.HexBytes" json:"TxHash"` + // Whether to wait for the block to become available + Wait bool `protobuf:"varint,2,opt,name=Wait,proto3" json:"Wait,omitempty"` +} + +func (m *GetTxRequest) Reset() { *m = GetTxRequest{} } +func (m *GetTxRequest) String() string { return proto.CompactTextString(m) } +func (*GetTxRequest) ProtoMessage() {} +func (*GetTxRequest) Descriptor() ([]byte, []int) { return fileDescriptorRpcevents, []int{1} } + +func (m *GetTxRequest) GetWait() bool { + if m != nil { + return m.Wait + } + return false +} + +func (*GetTxRequest) XXX_MessageName() string { + return "rpcevents.GetTxRequest" +} + +type BlocksRequest struct { + BlockRange *BlockRange `protobuf:"bytes,1,opt,name=BlockRange" json:"BlockRange,omitempty"` + // Specify a query on which to match the tags of events. + // Tag | Match type | Values + // ----------------------------------------- + // All events + // ----------------------------------------- + // TxType | String | "UnknownTx", "SendTx", "CallTx", "NameTx", "BondTx", "UnbondTx", "PermissionsTx", "GovernanceTx" + // TxHash | String | bytes + // EventType | String | "CallEvent", "LogEvent", "AccountInputEvent", "AccountOutputEvent" + // EventID | String | string + // Height | Integer | uint64 + // Index | Integer | uint64 + // MessageType | String | Go type name + // ----------------------------------------- + // Log event + // ----------------------------------------- + // Address | String | Address (hex) + // Log<0-4> | String | Word256 (hex) + // Log<0-4>Text | String | string (trimmed) + // ----------------------------------------- + // Call event + // ----------------------------------------- + // Origin | String | Address (hex) + // Callee | String | Address (hex) + // Caller | String | Address (hex) + // Value | Integer | uint64 + // Gas | Integer | uint64 + // StackDepth | Integer | uint64 + // Exception | String | string + // ----------------------------------------- + // Tx event (input/output) + // ----------------------------------------- + // Exception | String | string + // + // For example: + // EventType = 'LogEvent' AND EventID CONTAINS 'bar' AND TxHash = '020304' AND Height >= 34 AND Index < 3 AND Address = 'DEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF' + Query string `protobuf:"bytes,2,opt,name=Query,proto3" json:"Query,omitempty"` +} + +func (m *BlocksRequest) Reset() { *m = BlocksRequest{} } +func (m *BlocksRequest) String() string { return proto.CompactTextString(m) } +func (*BlocksRequest) ProtoMessage() {} +func (*BlocksRequest) Descriptor() ([]byte, []int) { return fileDescriptorRpcevents, []int{2} } + +func (m *BlocksRequest) GetBlockRange() *BlockRange { + if m != nil { + return m.BlockRange + } + return nil +} + +func (m *BlocksRequest) GetQuery() string { + if m != nil { + return m.Query + } + return "" +} + +func (*BlocksRequest) XXX_MessageName() string { + return "rpcevents.BlocksRequest" +} + +type GetEventsResponse struct { + Height uint64 `protobuf:"varint,1,opt,name=Height,proto3" json:"Height,omitempty"` + Events []*exec.Event `protobuf:"bytes,2,rep,name=Events" json:"Events,omitempty"` +} + +func (m *GetEventsResponse) Reset() { *m = GetEventsResponse{} } +func (m *GetEventsResponse) String() string { return proto.CompactTextString(m) } +func (*GetEventsResponse) ProtoMessage() {} +func (*GetEventsResponse) Descriptor() ([]byte, []int) { return fileDescriptorRpcevents, []int{3} } + +func (m *GetEventsResponse) GetHeight() uint64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *GetEventsResponse) GetEvents() []*exec.Event { + if m != nil { + return m.Events + } + return nil +} + +func (*GetEventsResponse) XXX_MessageName() string { + return "rpcevents.GetEventsResponse" +} + +type GetTxsResponse struct { + Height uint64 `protobuf:"varint,1,opt,name=Height,proto3" json:"Height,omitempty"` + TxExecutions []*exec.TxExecution `protobuf:"bytes,2,rep,name=TxExecutions" json:"TxExecutions,omitempty"` +} + +func (m *GetTxsResponse) Reset() { *m = GetTxsResponse{} } +func (m *GetTxsResponse) String() string { return proto.CompactTextString(m) } +func (*GetTxsResponse) ProtoMessage() {} +func (*GetTxsResponse) Descriptor() ([]byte, []int) { return fileDescriptorRpcevents, []int{4} } + +func (m *GetTxsResponse) GetHeight() uint64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *GetTxsResponse) GetTxExecutions() []*exec.TxExecution { + if m != nil { + return m.TxExecutions + } + return nil +} + +func (*GetTxsResponse) XXX_MessageName() string { + return "rpcevents.GetTxsResponse" +} + +type Bound struct { + Type Bound_BoundType `protobuf:"varint,1,opt,name=Type,proto3,enum=rpcevents.Bound_BoundType" json:"Type,omitempty"` + Index uint64 `protobuf:"varint,2,opt,name=Index,proto3" json:"Index,omitempty"` +} + +func (m *Bound) Reset() { *m = Bound{} } +func (m *Bound) String() string { return proto.CompactTextString(m) } +func (*Bound) ProtoMessage() {} +func (*Bound) Descriptor() ([]byte, []int) { return fileDescriptorRpcevents, []int{5} } + +func (m *Bound) GetType() Bound_BoundType { + if m != nil { + return m.Type + } + return Bound_ABSOLUTE +} + +func (m *Bound) GetIndex() uint64 { + if m != nil { + return m.Index + } + return 0 +} + +func (*Bound) XXX_MessageName() string { + return "rpcevents.Bound" +} + +// An inclusive range of blocks to include in output +type BlockRange struct { + // Bounds can be set to: + // absolute: block height + // relative: block height counting back from latest + // latest: latest block when call is processed + // stream: for End keep sending new blocks, for start same as latest + Start *Bound `protobuf:"bytes,1,opt,name=Start" json:"Start,omitempty"` + End *Bound `protobuf:"bytes,2,opt,name=End" json:"End,omitempty"` +} + +func (m *BlockRange) Reset() { *m = BlockRange{} } +func (m *BlockRange) String() string { return proto.CompactTextString(m) } +func (*BlockRange) ProtoMessage() {} +func (*BlockRange) Descriptor() ([]byte, []int) { return fileDescriptorRpcevents, []int{6} } + +func (m *BlockRange) GetStart() *Bound { + if m != nil { + return m.Start + } + return nil +} + +func (m *BlockRange) GetEnd() *Bound { + if m != nil { + return m.End + } + return nil +} + +func (*BlockRange) XXX_MessageName() string { + return "rpcevents.BlockRange" +} +func init() { + proto.RegisterType((*GetBlockRequest)(nil), "rpcevents.GetBlockRequest") + golang_proto.RegisterType((*GetBlockRequest)(nil), "rpcevents.GetBlockRequest") + proto.RegisterType((*GetTxRequest)(nil), "rpcevents.GetTxRequest") + golang_proto.RegisterType((*GetTxRequest)(nil), "rpcevents.GetTxRequest") + proto.RegisterType((*BlocksRequest)(nil), "rpcevents.BlocksRequest") + golang_proto.RegisterType((*BlocksRequest)(nil), "rpcevents.BlocksRequest") + proto.RegisterType((*GetEventsResponse)(nil), "rpcevents.GetEventsResponse") + golang_proto.RegisterType((*GetEventsResponse)(nil), "rpcevents.GetEventsResponse") + proto.RegisterType((*GetTxsResponse)(nil), "rpcevents.GetTxsResponse") + golang_proto.RegisterType((*GetTxsResponse)(nil), "rpcevents.GetTxsResponse") + proto.RegisterType((*Bound)(nil), "rpcevents.Bound") + golang_proto.RegisterType((*Bound)(nil), "rpcevents.Bound") + proto.RegisterType((*BlockRange)(nil), "rpcevents.BlockRange") + golang_proto.RegisterType((*BlockRange)(nil), "rpcevents.BlockRange") + proto.RegisterEnum("rpcevents.Bound_BoundType", Bound_BoundType_name, Bound_BoundType_value) + golang_proto.RegisterEnum("rpcevents.Bound_BoundType", Bound_BoundType_name, Bound_BoundType_value) +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// Client API for ExecutionEvents service + +type ExecutionEventsClient interface { + // Get Blockexecution at particular height + GetBlock(ctx context.Context, in *GetBlockRequest, opts ...grpc.CallOption) (*exec.BlockExecution, error) + // Get BlockExecutions for a range of blocks + GetBlocks(ctx context.Context, in *BlocksRequest, opts ...grpc.CallOption) (ExecutionEvents_GetBlocksClient, error) + // Get a particular TxExecution + GetTx(ctx context.Context, in *GetTxRequest, opts ...grpc.CallOption) (*exec.TxExecution, error) + // Get TxExecutions for a range of block + GetTxs(ctx context.Context, in *BlocksRequest, opts ...grpc.CallOption) (ExecutionEvents_GetTxsClient, error) + // GetEvents provides events streaming one block at a time - that is all events emitted in a particular block + // are guaranteed to be delivered in each GetEventsResponse + GetEvents(ctx context.Context, in *BlocksRequest, opts ...grpc.CallOption) (ExecutionEvents_GetEventsClient, error) +} + +type executionEventsClient struct { + cc *grpc.ClientConn +} + +func NewExecutionEventsClient(cc *grpc.ClientConn) ExecutionEventsClient { + return &executionEventsClient{cc} +} + +func (c *executionEventsClient) GetBlock(ctx context.Context, in *GetBlockRequest, opts ...grpc.CallOption) (*exec.BlockExecution, error) { + out := new(exec.BlockExecution) + err := grpc.Invoke(ctx, "/rpcevents.ExecutionEvents/GetBlock", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *executionEventsClient) GetBlocks(ctx context.Context, in *BlocksRequest, opts ...grpc.CallOption) (ExecutionEvents_GetBlocksClient, error) { + stream, err := grpc.NewClientStream(ctx, &_ExecutionEvents_serviceDesc.Streams[0], c.cc, "/rpcevents.ExecutionEvents/GetBlocks", opts...) + if err != nil { + return nil, err + } + x := &executionEventsGetBlocksClient{stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +type ExecutionEvents_GetBlocksClient interface { + Recv() (*exec.BlockExecution, error) + grpc.ClientStream +} + +type executionEventsGetBlocksClient struct { + grpc.ClientStream +} + +func (x *executionEventsGetBlocksClient) Recv() (*exec.BlockExecution, error) { + m := new(exec.BlockExecution) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +func (c *executionEventsClient) GetTx(ctx context.Context, in *GetTxRequest, opts ...grpc.CallOption) (*exec.TxExecution, error) { + out := new(exec.TxExecution) + err := grpc.Invoke(ctx, "/rpcevents.ExecutionEvents/GetTx", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *executionEventsClient) GetTxs(ctx context.Context, in *BlocksRequest, opts ...grpc.CallOption) (ExecutionEvents_GetTxsClient, error) { + stream, err := grpc.NewClientStream(ctx, &_ExecutionEvents_serviceDesc.Streams[1], c.cc, "/rpcevents.ExecutionEvents/GetTxs", opts...) + if err != nil { + return nil, err + } + x := &executionEventsGetTxsClient{stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +type ExecutionEvents_GetTxsClient interface { + Recv() (*GetTxsResponse, error) + grpc.ClientStream +} + +type executionEventsGetTxsClient struct { + grpc.ClientStream +} + +func (x *executionEventsGetTxsClient) Recv() (*GetTxsResponse, error) { + m := new(GetTxsResponse) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +func (c *executionEventsClient) GetEvents(ctx context.Context, in *BlocksRequest, opts ...grpc.CallOption) (ExecutionEvents_GetEventsClient, error) { + stream, err := grpc.NewClientStream(ctx, &_ExecutionEvents_serviceDesc.Streams[2], c.cc, "/rpcevents.ExecutionEvents/GetEvents", opts...) + if err != nil { + return nil, err + } + x := &executionEventsGetEventsClient{stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +type ExecutionEvents_GetEventsClient interface { + Recv() (*GetEventsResponse, error) + grpc.ClientStream +} + +type executionEventsGetEventsClient struct { + grpc.ClientStream +} + +func (x *executionEventsGetEventsClient) Recv() (*GetEventsResponse, error) { + m := new(GetEventsResponse) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +// Server API for ExecutionEvents service + +type ExecutionEventsServer interface { + // Get Blockexecution at particular height + GetBlock(context.Context, *GetBlockRequest) (*exec.BlockExecution, error) + // Get BlockExecutions for a range of blocks + GetBlocks(*BlocksRequest, ExecutionEvents_GetBlocksServer) error + // Get a particular TxExecution + GetTx(context.Context, *GetTxRequest) (*exec.TxExecution, error) + // Get TxExecutions for a range of block + GetTxs(*BlocksRequest, ExecutionEvents_GetTxsServer) error + // GetEvents provides events streaming one block at a time - that is all events emitted in a particular block + // are guaranteed to be delivered in each GetEventsResponse + GetEvents(*BlocksRequest, ExecutionEvents_GetEventsServer) error +} + +func RegisterExecutionEventsServer(s *grpc.Server, srv ExecutionEventsServer) { + s.RegisterService(&_ExecutionEvents_serviceDesc, srv) +} + +func _ExecutionEvents_GetBlock_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetBlockRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ExecutionEventsServer).GetBlock(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/rpcevents.ExecutionEvents/GetBlock", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ExecutionEventsServer).GetBlock(ctx, req.(*GetBlockRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ExecutionEvents_GetBlocks_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(BlocksRequest) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(ExecutionEventsServer).GetBlocks(m, &executionEventsGetBlocksServer{stream}) +} + +type ExecutionEvents_GetBlocksServer interface { + Send(*exec.BlockExecution) error + grpc.ServerStream +} + +type executionEventsGetBlocksServer struct { + grpc.ServerStream +} + +func (x *executionEventsGetBlocksServer) Send(m *exec.BlockExecution) error { + return x.ServerStream.SendMsg(m) +} + +func _ExecutionEvents_GetTx_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetTxRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ExecutionEventsServer).GetTx(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/rpcevents.ExecutionEvents/GetTx", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ExecutionEventsServer).GetTx(ctx, req.(*GetTxRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ExecutionEvents_GetTxs_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(BlocksRequest) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(ExecutionEventsServer).GetTxs(m, &executionEventsGetTxsServer{stream}) +} + +type ExecutionEvents_GetTxsServer interface { + Send(*GetTxsResponse) error + grpc.ServerStream +} + +type executionEventsGetTxsServer struct { + grpc.ServerStream +} + +func (x *executionEventsGetTxsServer) Send(m *GetTxsResponse) error { + return x.ServerStream.SendMsg(m) +} + +func _ExecutionEvents_GetEvents_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(BlocksRequest) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(ExecutionEventsServer).GetEvents(m, &executionEventsGetEventsServer{stream}) +} + +type ExecutionEvents_GetEventsServer interface { + Send(*GetEventsResponse) error + grpc.ServerStream +} + +type executionEventsGetEventsServer struct { + grpc.ServerStream +} + +func (x *executionEventsGetEventsServer) Send(m *GetEventsResponse) error { + return x.ServerStream.SendMsg(m) +} + +var _ExecutionEvents_serviceDesc = grpc.ServiceDesc{ + ServiceName: "rpcevents.ExecutionEvents", + HandlerType: (*ExecutionEventsServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "GetBlock", + Handler: _ExecutionEvents_GetBlock_Handler, + }, + { + MethodName: "GetTx", + Handler: _ExecutionEvents_GetTx_Handler, + }, + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "GetBlocks", + Handler: _ExecutionEvents_GetBlocks_Handler, + ServerStreams: true, + }, + { + StreamName: "GetTxs", + Handler: _ExecutionEvents_GetTxs_Handler, + ServerStreams: true, + }, + { + StreamName: "GetEvents", + Handler: _ExecutionEvents_GetEvents_Handler, + ServerStreams: true, + }, + }, + Metadata: "rpcevents.proto", +} + +func (m *GetBlockRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GetBlockRequest) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.Height != 0 { + dAtA[i] = 0x8 + i++ + i = encodeVarintRpcevents(dAtA, i, uint64(m.Height)) + } + if m.Wait { + dAtA[i] = 0x10 + i++ + if m.Wait { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i++ + } + return i, nil +} + +func (m *GetTxRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GetTxRequest) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + dAtA[i] = 0xa + i++ + i = encodeVarintRpcevents(dAtA, i, uint64(m.TxHash.Size())) + n1, err := m.TxHash.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n1 + if m.Wait { + dAtA[i] = 0x10 + i++ + if m.Wait { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i++ + } + return i, nil +} + +func (m *BlocksRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *BlocksRequest) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.BlockRange != nil { + dAtA[i] = 0xa + i++ + i = encodeVarintRpcevents(dAtA, i, uint64(m.BlockRange.Size())) + n2, err := m.BlockRange.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n2 + } + if len(m.Query) > 0 { + dAtA[i] = 0x12 + i++ + i = encodeVarintRpcevents(dAtA, i, uint64(len(m.Query))) + i += copy(dAtA[i:], m.Query) + } + return i, nil +} + +func (m *GetEventsResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GetEventsResponse) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.Height != 0 { + dAtA[i] = 0x8 + i++ + i = encodeVarintRpcevents(dAtA, i, uint64(m.Height)) + } + if len(m.Events) > 0 { + for _, msg := range m.Events { + dAtA[i] = 0x12 + i++ + i = encodeVarintRpcevents(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + return i, nil +} + +func (m *GetTxsResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GetTxsResponse) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.Height != 0 { + dAtA[i] = 0x8 + i++ + i = encodeVarintRpcevents(dAtA, i, uint64(m.Height)) + } + if len(m.TxExecutions) > 0 { + for _, msg := range m.TxExecutions { + dAtA[i] = 0x12 + i++ + i = encodeVarintRpcevents(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + return i, nil +} + +func (m *Bound) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Bound) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.Type != 0 { + dAtA[i] = 0x8 + i++ + i = encodeVarintRpcevents(dAtA, i, uint64(m.Type)) + } + if m.Index != 0 { + dAtA[i] = 0x10 + i++ + i = encodeVarintRpcevents(dAtA, i, uint64(m.Index)) + } + return i, nil +} + +func (m *BlockRange) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *BlockRange) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.Start != nil { + dAtA[i] = 0xa + i++ + i = encodeVarintRpcevents(dAtA, i, uint64(m.Start.Size())) + n3, err := m.Start.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n3 + } + if m.End != nil { + dAtA[i] = 0x12 + i++ + i = encodeVarintRpcevents(dAtA, i, uint64(m.End.Size())) + n4, err := m.End.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n4 + } + return i, nil +} + +func encodeVarintRpcevents(dAtA []byte, offset int, v uint64) int { + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return offset + 1 +} +func (m *GetBlockRequest) Size() (n int) { + var l int + _ = l + if m.Height != 0 { + n += 1 + sovRpcevents(uint64(m.Height)) + } + if m.Wait { + n += 2 + } + return n +} + +func (m *GetTxRequest) Size() (n int) { + var l int + _ = l + l = m.TxHash.Size() + n += 1 + l + sovRpcevents(uint64(l)) + if m.Wait { + n += 2 + } + return n +} + +func (m *BlocksRequest) Size() (n int) { + var l int + _ = l + if m.BlockRange != nil { + l = m.BlockRange.Size() + n += 1 + l + sovRpcevents(uint64(l)) + } + l = len(m.Query) + if l > 0 { + n += 1 + l + sovRpcevents(uint64(l)) + } + return n +} + +func (m *GetEventsResponse) Size() (n int) { + var l int + _ = l + if m.Height != 0 { + n += 1 + sovRpcevents(uint64(m.Height)) + } + if len(m.Events) > 0 { + for _, e := range m.Events { + l = e.Size() + n += 1 + l + sovRpcevents(uint64(l)) + } + } + return n +} + +func (m *GetTxsResponse) Size() (n int) { + var l int + _ = l + if m.Height != 0 { + n += 1 + sovRpcevents(uint64(m.Height)) + } + if len(m.TxExecutions) > 0 { + for _, e := range m.TxExecutions { + l = e.Size() + n += 1 + l + sovRpcevents(uint64(l)) + } + } + return n +} + +func (m *Bound) Size() (n int) { + var l int + _ = l + if m.Type != 0 { + n += 1 + sovRpcevents(uint64(m.Type)) + } + if m.Index != 0 { + n += 1 + sovRpcevents(uint64(m.Index)) + } + return n +} + +func (m *BlockRange) Size() (n int) { + var l int + _ = l + if m.Start != nil { + l = m.Start.Size() + n += 1 + l + sovRpcevents(uint64(l)) + } + if m.End != nil { + l = m.End.Size() + n += 1 + l + sovRpcevents(uint64(l)) + } + return n +} + +func sovRpcevents(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n +} +func sozRpcevents(x uint64) (n int) { + return sovRpcevents(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *GetBlockRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcevents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GetBlockRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GetBlockRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcevents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Wait", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcevents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + m.Wait = bool(v != 0) + default: + iNdEx = preIndex + skippy, err := skipRpcevents(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthRpcevents + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *GetTxRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcevents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GetTxRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GetTxRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TxHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcevents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthRpcevents + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.TxHash.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Wait", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcevents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + m.Wait = bool(v != 0) + default: + iNdEx = preIndex + skippy, err := skipRpcevents(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthRpcevents + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *BlocksRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcevents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: BlocksRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: BlocksRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockRange", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcevents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthRpcevents + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.BlockRange == nil { + m.BlockRange = &BlockRange{} + } + if err := m.BlockRange.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Query", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcevents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthRpcevents + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Query = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipRpcevents(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthRpcevents + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *GetEventsResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcevents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GetEventsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GetEventsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcevents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Events", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcevents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthRpcevents + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Events = append(m.Events, &exec.Event{}) + if err := m.Events[len(m.Events)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipRpcevents(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthRpcevents + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *GetTxsResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcevents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GetTxsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GetTxsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcevents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TxExecutions", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcevents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthRpcevents + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.TxExecutions = append(m.TxExecutions, &exec.TxExecution{}) + if err := m.TxExecutions[len(m.TxExecutions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipRpcevents(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthRpcevents + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Bound) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcevents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Bound: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Bound: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) + } + m.Type = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcevents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Type |= (Bound_BoundType(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) + } + m.Index = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcevents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Index |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipRpcevents(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthRpcevents + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *BlockRange) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcevents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: BlockRange: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: BlockRange: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Start", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcevents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthRpcevents + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Start == nil { + m.Start = &Bound{} + } + if err := m.Start.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field End", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcevents + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthRpcevents + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.End == nil { + m.End = &Bound{} + } + if err := m.End.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipRpcevents(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthRpcevents + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipRpcevents(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowRpcevents + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowRpcevents + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowRpcevents + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + iNdEx += length + if length < 0 { + return 0, ErrInvalidLengthRpcevents + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowRpcevents + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipRpcevents(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} + +var ( + ErrInvalidLengthRpcevents = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowRpcevents = fmt.Errorf("proto: integer overflow") +) + +func init() { proto.RegisterFile("rpcevents.proto", fileDescriptorRpcevents) } +func init() { golang_proto.RegisterFile("rpcevents.proto", fileDescriptorRpcevents) } + +var fileDescriptorRpcevents = []byte{ + // 584 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x54, 0x5f, 0x8f, 0xd2, 0x40, + 0x10, 0xbf, 0xe5, 0x4f, 0x03, 0x03, 0x1e, 0xbd, 0xcd, 0xa9, 0x48, 0x0c, 0x47, 0x6a, 0x62, 0x48, + 0x8c, 0x85, 0x70, 0xe1, 0xcd, 0x8b, 0xa1, 0x49, 0x05, 0x0c, 0x17, 0x75, 0xa9, 0x7f, 0x62, 0x4c, + 0x0c, 0x94, 0xb5, 0x10, 0xcf, 0xb6, 0xd7, 0x6e, 0xb5, 0x7c, 0x14, 0xbf, 0x8d, 0x8f, 0x24, 0xbe, + 0xf8, 0xec, 0xc3, 0xc5, 0x70, 0x5f, 0xc4, 0x74, 0x17, 0x7a, 0x05, 0xef, 0xf0, 0xa5, 0x99, 0xd9, + 0xf9, 0xcd, 0x6f, 0x66, 0x7f, 0x33, 0x5b, 0x28, 0x79, 0xae, 0x49, 0xbf, 0x52, 0x9b, 0xf9, 0xaa, + 0xeb, 0x39, 0xcc, 0xc1, 0xf9, 0xf8, 0xa0, 0xf2, 0xd8, 0x9a, 0xb1, 0x69, 0x30, 0x56, 0x4d, 0xe7, + 0x4b, 0xc3, 0x72, 0x2c, 0xa7, 0xc1, 0x11, 0xe3, 0xe0, 0x13, 0xf7, 0xb8, 0xc3, 0x2d, 0x91, 0x59, + 0x01, 0x1a, 0x52, 0x53, 0xd8, 0xca, 0x09, 0x94, 0xba, 0x94, 0x69, 0x67, 0x8e, 0xf9, 0x99, 0xd0, + 0xf3, 0x80, 0xfa, 0x0c, 0xdf, 0x01, 0xa9, 0x47, 0x67, 0xd6, 0x94, 0x95, 0x51, 0x0d, 0xd5, 0x33, + 0x64, 0xe5, 0x61, 0x0c, 0x99, 0xb7, 0xa3, 0x19, 0x2b, 0xa7, 0x6a, 0xa8, 0x9e, 0x23, 0xdc, 0x56, + 0xce, 0xa1, 0xd8, 0xa5, 0xcc, 0x08, 0xd7, 0xb9, 0xa7, 0x20, 0x19, 0x61, 0x6f, 0xe4, 0x4f, 0x79, + 0x6e, 0x51, 0x6b, 0x2f, 0x2e, 0x8e, 0xf6, 0x7e, 0x5f, 0x1c, 0x25, 0x3b, 0x9c, 0xce, 0x5d, 0xea, + 0x9d, 0xd1, 0x89, 0x45, 0xbd, 0xc6, 0x38, 0xf0, 0x3c, 0xe7, 0x5b, 0x63, 0x3c, 0xb3, 0x47, 0xde, + 0x5c, 0xed, 0xd1, 0x50, 0x9b, 0x33, 0xea, 0x93, 0x15, 0xc9, 0xb5, 0x25, 0x3f, 0xc0, 0x2d, 0xde, + 0xae, 0xbf, 0xae, 0xd9, 0x06, 0x10, 0xfd, 0x8f, 0x6c, 0x8b, 0xf2, 0xba, 0x85, 0xd6, 0x6d, 0xf5, + 0x4a, 0xae, 0xab, 0x20, 0x49, 0x00, 0xf1, 0x21, 0x64, 0x5f, 0x05, 0xd4, 0x9b, 0x73, 0xf2, 0x3c, + 0x11, 0x8e, 0xf2, 0x12, 0x0e, 0xba, 0x94, 0xe9, 0x3c, 0x93, 0x50, 0xdf, 0x75, 0x6c, 0x9f, 0xde, + 0xa8, 0xc8, 0x03, 0x90, 0x04, 0xb2, 0x9c, 0xaa, 0xa5, 0xeb, 0x85, 0x56, 0x41, 0xe5, 0xca, 0xf2, + 0x33, 0xb2, 0x0a, 0x29, 0x1f, 0x61, 0x9f, 0x4b, 0xf4, 0x7f, 0xba, 0x36, 0x14, 0x8d, 0x50, 0x0f, + 0xa9, 0x19, 0xb0, 0x99, 0x63, 0xaf, 0x49, 0x0f, 0x04, 0x69, 0x22, 0x42, 0x36, 0x60, 0xca, 0x77, + 0x04, 0x59, 0xcd, 0x09, 0xec, 0x09, 0x56, 0x21, 0x63, 0xcc, 0x5d, 0xa1, 0xc1, 0x7e, 0xab, 0x92, + 0xd4, 0x20, 0x8a, 0x8b, 0x6f, 0x84, 0x20, 0x1c, 0x17, 0x49, 0xd0, 0xb7, 0x27, 0x34, 0xe4, 0x12, + 0x64, 0x88, 0x70, 0x94, 0xe7, 0x90, 0x8f, 0x81, 0xb8, 0x08, 0xb9, 0x8e, 0x36, 0x7c, 0x31, 0x78, + 0x6d, 0xe8, 0xf2, 0x5e, 0xe4, 0x11, 0x7d, 0xd0, 0x31, 0xfa, 0x6f, 0x74, 0x19, 0xe1, 0x3c, 0x64, + 0x9f, 0xf5, 0xc9, 0xd0, 0x90, 0x53, 0x18, 0x40, 0x1a, 0x74, 0x0c, 0x7d, 0x68, 0xc8, 0xe9, 0xc8, + 0x1e, 0x1a, 0x44, 0xef, 0x9c, 0xca, 0x19, 0xe5, 0x5d, 0x72, 0x36, 0xf8, 0x21, 0x64, 0x87, 0x6c, + 0xe4, 0xb1, 0xd5, 0x90, 0xe4, 0xed, 0x06, 0x89, 0x08, 0x63, 0x05, 0xd2, 0xba, 0x3d, 0xe1, 0x5d, + 0x5d, 0x87, 0x8a, 0x82, 0xad, 0x9f, 0x29, 0x28, 0xc5, 0x22, 0x08, 0xa9, 0xf1, 0x13, 0xc8, 0xad, + 0x97, 0x19, 0x27, 0x6f, 0xbf, 0xb5, 0xe1, 0x95, 0x43, 0x21, 0x29, 0x3f, 0x8b, 0x39, 0xf0, 0x09, + 0xe4, 0xd7, 0x40, 0x1f, 0x97, 0xb7, 0x17, 0xc8, 0xdf, 0x99, 0xdc, 0x44, 0xf8, 0x18, 0xb2, 0x7c, + 0xce, 0xf8, 0xee, 0x66, 0xe5, 0xf8, 0x71, 0x54, 0xfe, 0x9d, 0x24, 0x7e, 0x0a, 0x92, 0x58, 0x8e, + 0x1d, 0x05, 0xef, 0x6d, 0xf3, 0xc5, 0x9b, 0xd4, 0x44, 0x58, 0xe7, 0x4d, 0xaf, 0xee, 0x7f, 0x33, + 0xc7, 0xfd, 0x4d, 0x8e, 0xcd, 0xfd, 0x6e, 0x22, 0xad, 0xb3, 0x58, 0x56, 0xd1, 0xaf, 0x65, 0x15, + 0xfd, 0x59, 0x56, 0xd1, 0x8f, 0xcb, 0x2a, 0x5a, 0x5c, 0x56, 0xd1, 0xfb, 0x47, 0xbb, 0x5f, 0xad, + 0xe7, 0x9a, 0x8d, 0x98, 0x76, 0x2c, 0xf1, 0x1f, 0xca, 0xf1, 0xdf, 0x00, 0x00, 0x00, 0xff, 0xff, + 0x5d, 0x9d, 0x65, 0x82, 0xa9, 0x04, 0x00, 0x00, +} diff --git a/rpc/rpcquery/query_server.go b/rpc/rpcquery/query_server.go new file mode 100644 index 000000000..edcb968b6 --- /dev/null +++ b/rpc/rpcquery/query_server.go @@ -0,0 +1,76 @@ +package rpcquery + +import ( + "context" + + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/state" + "github.com/hyperledger/burrow/event/query" + "github.com/hyperledger/burrow/execution/names" +) + +type queryServer struct { + accounts state.IterableReader + nameReg names.IterableReader +} + +var _ QueryServer = &queryServer{} + +func NewQueryServer(state state.IterableReader, nameReg names.IterableReader) *queryServer { + return &queryServer{ + accounts: state, + nameReg: nameReg, + } +} + +func (qs *queryServer) GetAccount(ctx context.Context, param *GetAccountParam) (*acm.ConcreteAccount, error) { + acc, err := qs.accounts.GetAccount(param.Address) + if err != nil { + return nil, err + } + return acm.AsConcreteAccount(acc), nil +} + +func (qs *queryServer) ListAccounts(param *ListAccountsParam, stream Query_ListAccountsServer) error { + qry, err := query.NewBuilder(param.Query).Query() + var streamErr error + _, err = qs.accounts.IterateAccounts(func(acc acm.Account) (stop bool) { + if qry.Matches(acc.Tagged()) { + streamErr = stream.Send(acm.AsConcreteAccount(acc)) + if streamErr != nil { + return true + } + } + return + }) + if err != nil { + return err + } + return streamErr +} + +// Name registry +func (qs *queryServer) GetName(ctx context.Context, param *GetNameParam) (*names.Entry, error) { + return qs.nameReg.GetName(param.Name) +} + +func (qs *queryServer) ListNames(param *ListNamesParam, stream Query_ListNamesServer) error { + qry, err := query.NewBuilder(param.Query).Query() + if err != nil { + return err + } + var streamErr error + _, err = qs.nameReg.IterateNames(func(entry *names.Entry) (stop bool) { + if qry.Matches(entry.Tagged()) { + streamErr = stream.Send(entry) + if streamErr != nil { + return true + } + } + return + }) + if err != nil { + return err + } + return streamErr +} diff --git a/rpc/rpcquery/rpcquery.pb.go b/rpc/rpcquery/rpcquery.pb.go new file mode 100644 index 000000000..ce9b9f17d --- /dev/null +++ b/rpc/rpcquery/rpcquery.pb.go @@ -0,0 +1,961 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: rpcquery.proto + +/* + Package rpcquery is a generated protocol buffer package. + + It is generated from these files: + rpcquery.proto + + It has these top-level messages: + GetAccountParam + ListAccountsParam + GetNameParam + ListNamesParam +*/ +package rpcquery + +import proto "github.com/gogo/protobuf/proto" +import golang_proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" +import _ "github.com/gogo/protobuf/gogoproto" +import names "github.com/hyperledger/burrow/execution/names" +import acm "github.com/hyperledger/burrow/acm" + +import github_com_hyperledger_burrow_crypto "github.com/hyperledger/burrow/crypto" + +import context "golang.org/x/net/context" +import grpc "google.golang.org/grpc" + +import io "io" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = golang_proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package + +type GetAccountParam struct { + Address github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,1,opt,name=Address,proto3,customtype=github.com/hyperledger/burrow/crypto.Address" json:"Address"` +} + +func (m *GetAccountParam) Reset() { *m = GetAccountParam{} } +func (m *GetAccountParam) String() string { return proto.CompactTextString(m) } +func (*GetAccountParam) ProtoMessage() {} +func (*GetAccountParam) Descriptor() ([]byte, []int) { return fileDescriptorRpcquery, []int{0} } + +func (*GetAccountParam) XXX_MessageName() string { + return "rpcquery.GetAccountParam" +} + +type ListAccountsParam struct { + Query string `protobuf:"bytes,1,opt,name=Query,proto3" json:"Query,omitempty"` +} + +func (m *ListAccountsParam) Reset() { *m = ListAccountsParam{} } +func (m *ListAccountsParam) String() string { return proto.CompactTextString(m) } +func (*ListAccountsParam) ProtoMessage() {} +func (*ListAccountsParam) Descriptor() ([]byte, []int) { return fileDescriptorRpcquery, []int{1} } + +func (m *ListAccountsParam) GetQuery() string { + if m != nil { + return m.Query + } + return "" +} + +func (*ListAccountsParam) XXX_MessageName() string { + return "rpcquery.ListAccountsParam" +} + +type GetNameParam struct { + Name string `protobuf:"bytes,1,opt,name=Name,proto3" json:"Name,omitempty"` +} + +func (m *GetNameParam) Reset() { *m = GetNameParam{} } +func (m *GetNameParam) String() string { return proto.CompactTextString(m) } +func (*GetNameParam) ProtoMessage() {} +func (*GetNameParam) Descriptor() ([]byte, []int) { return fileDescriptorRpcquery, []int{2} } + +func (m *GetNameParam) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (*GetNameParam) XXX_MessageName() string { + return "rpcquery.GetNameParam" +} + +type ListNamesParam struct { + Query string `protobuf:"bytes,1,opt,name=Query,proto3" json:"Query,omitempty"` +} + +func (m *ListNamesParam) Reset() { *m = ListNamesParam{} } +func (m *ListNamesParam) String() string { return proto.CompactTextString(m) } +func (*ListNamesParam) ProtoMessage() {} +func (*ListNamesParam) Descriptor() ([]byte, []int) { return fileDescriptorRpcquery, []int{3} } + +func (m *ListNamesParam) GetQuery() string { + if m != nil { + return m.Query + } + return "" +} + +func (*ListNamesParam) XXX_MessageName() string { + return "rpcquery.ListNamesParam" +} +func init() { + proto.RegisterType((*GetAccountParam)(nil), "rpcquery.GetAccountParam") + golang_proto.RegisterType((*GetAccountParam)(nil), "rpcquery.GetAccountParam") + proto.RegisterType((*ListAccountsParam)(nil), "rpcquery.ListAccountsParam") + golang_proto.RegisterType((*ListAccountsParam)(nil), "rpcquery.ListAccountsParam") + proto.RegisterType((*GetNameParam)(nil), "rpcquery.GetNameParam") + golang_proto.RegisterType((*GetNameParam)(nil), "rpcquery.GetNameParam") + proto.RegisterType((*ListNamesParam)(nil), "rpcquery.ListNamesParam") + golang_proto.RegisterType((*ListNamesParam)(nil), "rpcquery.ListNamesParam") +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// Client API for Query service + +type QueryClient interface { + GetAccount(ctx context.Context, in *GetAccountParam, opts ...grpc.CallOption) (*acm.ConcreteAccount, error) + ListAccounts(ctx context.Context, in *ListAccountsParam, opts ...grpc.CallOption) (Query_ListAccountsClient, error) + GetName(ctx context.Context, in *GetNameParam, opts ...grpc.CallOption) (*names.Entry, error) + ListNames(ctx context.Context, in *ListNamesParam, opts ...grpc.CallOption) (Query_ListNamesClient, error) +} + +type queryClient struct { + cc *grpc.ClientConn +} + +func NewQueryClient(cc *grpc.ClientConn) QueryClient { + return &queryClient{cc} +} + +func (c *queryClient) GetAccount(ctx context.Context, in *GetAccountParam, opts ...grpc.CallOption) (*acm.ConcreteAccount, error) { + out := new(acm.ConcreteAccount) + err := grpc.Invoke(ctx, "/rpcquery.Query/GetAccount", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) ListAccounts(ctx context.Context, in *ListAccountsParam, opts ...grpc.CallOption) (Query_ListAccountsClient, error) { + stream, err := grpc.NewClientStream(ctx, &_Query_serviceDesc.Streams[0], c.cc, "/rpcquery.Query/ListAccounts", opts...) + if err != nil { + return nil, err + } + x := &queryListAccountsClient{stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +type Query_ListAccountsClient interface { + Recv() (*acm.ConcreteAccount, error) + grpc.ClientStream +} + +type queryListAccountsClient struct { + grpc.ClientStream +} + +func (x *queryListAccountsClient) Recv() (*acm.ConcreteAccount, error) { + m := new(acm.ConcreteAccount) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +func (c *queryClient) GetName(ctx context.Context, in *GetNameParam, opts ...grpc.CallOption) (*names.Entry, error) { + out := new(names.Entry) + err := grpc.Invoke(ctx, "/rpcquery.Query/GetName", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) ListNames(ctx context.Context, in *ListNamesParam, opts ...grpc.CallOption) (Query_ListNamesClient, error) { + stream, err := grpc.NewClientStream(ctx, &_Query_serviceDesc.Streams[1], c.cc, "/rpcquery.Query/ListNames", opts...) + if err != nil { + return nil, err + } + x := &queryListNamesClient{stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +type Query_ListNamesClient interface { + Recv() (*names.Entry, error) + grpc.ClientStream +} + +type queryListNamesClient struct { + grpc.ClientStream +} + +func (x *queryListNamesClient) Recv() (*names.Entry, error) { + m := new(names.Entry) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +// Server API for Query service + +type QueryServer interface { + GetAccount(context.Context, *GetAccountParam) (*acm.ConcreteAccount, error) + ListAccounts(*ListAccountsParam, Query_ListAccountsServer) error + GetName(context.Context, *GetNameParam) (*names.Entry, error) + ListNames(*ListNamesParam, Query_ListNamesServer) error +} + +func RegisterQueryServer(s *grpc.Server, srv QueryServer) { + s.RegisterService(&_Query_serviceDesc, srv) +} + +func _Query_GetAccount_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetAccountParam) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).GetAccount(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/rpcquery.Query/GetAccount", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).GetAccount(ctx, req.(*GetAccountParam)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_ListAccounts_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(ListAccountsParam) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(QueryServer).ListAccounts(m, &queryListAccountsServer{stream}) +} + +type Query_ListAccountsServer interface { + Send(*acm.ConcreteAccount) error + grpc.ServerStream +} + +type queryListAccountsServer struct { + grpc.ServerStream +} + +func (x *queryListAccountsServer) Send(m *acm.ConcreteAccount) error { + return x.ServerStream.SendMsg(m) +} + +func _Query_GetName_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetNameParam) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).GetName(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/rpcquery.Query/GetName", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).GetName(ctx, req.(*GetNameParam)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_ListNames_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(ListNamesParam) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(QueryServer).ListNames(m, &queryListNamesServer{stream}) +} + +type Query_ListNamesServer interface { + Send(*names.Entry) error + grpc.ServerStream +} + +type queryListNamesServer struct { + grpc.ServerStream +} + +func (x *queryListNamesServer) Send(m *names.Entry) error { + return x.ServerStream.SendMsg(m) +} + +var _Query_serviceDesc = grpc.ServiceDesc{ + ServiceName: "rpcquery.Query", + HandlerType: (*QueryServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "GetAccount", + Handler: _Query_GetAccount_Handler, + }, + { + MethodName: "GetName", + Handler: _Query_GetName_Handler, + }, + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "ListAccounts", + Handler: _Query_ListAccounts_Handler, + ServerStreams: true, + }, + { + StreamName: "ListNames", + Handler: _Query_ListNames_Handler, + ServerStreams: true, + }, + }, + Metadata: "rpcquery.proto", +} + +func (m *GetAccountParam) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GetAccountParam) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + dAtA[i] = 0xa + i++ + i = encodeVarintRpcquery(dAtA, i, uint64(m.Address.Size())) + n1, err := m.Address.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n1 + return i, nil +} + +func (m *ListAccountsParam) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ListAccountsParam) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Query) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintRpcquery(dAtA, i, uint64(len(m.Query))) + i += copy(dAtA[i:], m.Query) + } + return i, nil +} + +func (m *GetNameParam) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GetNameParam) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Name) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintRpcquery(dAtA, i, uint64(len(m.Name))) + i += copy(dAtA[i:], m.Name) + } + return i, nil +} + +func (m *ListNamesParam) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ListNamesParam) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Query) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintRpcquery(dAtA, i, uint64(len(m.Query))) + i += copy(dAtA[i:], m.Query) + } + return i, nil +} + +func encodeVarintRpcquery(dAtA []byte, offset int, v uint64) int { + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return offset + 1 +} +func (m *GetAccountParam) Size() (n int) { + var l int + _ = l + l = m.Address.Size() + n += 1 + l + sovRpcquery(uint64(l)) + return n +} + +func (m *ListAccountsParam) Size() (n int) { + var l int + _ = l + l = len(m.Query) + if l > 0 { + n += 1 + l + sovRpcquery(uint64(l)) + } + return n +} + +func (m *GetNameParam) Size() (n int) { + var l int + _ = l + l = len(m.Name) + if l > 0 { + n += 1 + l + sovRpcquery(uint64(l)) + } + return n +} + +func (m *ListNamesParam) Size() (n int) { + var l int + _ = l + l = len(m.Query) + if l > 0 { + n += 1 + l + sovRpcquery(uint64(l)) + } + return n +} + +func sovRpcquery(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n +} +func sozRpcquery(x uint64) (n int) { + return sovRpcquery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *GetAccountParam) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcquery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GetAccountParam: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GetAccountParam: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcquery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthRpcquery + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Address.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipRpcquery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthRpcquery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ListAccountsParam) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcquery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ListAccountsParam: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ListAccountsParam: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Query", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcquery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthRpcquery + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Query = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipRpcquery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthRpcquery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *GetNameParam) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcquery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GetNameParam: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GetNameParam: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcquery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthRpcquery + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipRpcquery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthRpcquery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ListNamesParam) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcquery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ListNamesParam: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ListNamesParam: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Query", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcquery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthRpcquery + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Query = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipRpcquery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthRpcquery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipRpcquery(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowRpcquery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowRpcquery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowRpcquery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + iNdEx += length + if length < 0 { + return 0, ErrInvalidLengthRpcquery + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowRpcquery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipRpcquery(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} + +var ( + ErrInvalidLengthRpcquery = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowRpcquery = fmt.Errorf("proto: integer overflow") +) + +func init() { proto.RegisterFile("rpcquery.proto", fileDescriptorRpcquery) } +func init() { golang_proto.RegisterFile("rpcquery.proto", fileDescriptorRpcquery) } + +var fileDescriptorRpcquery = []byte{ + // 349 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x92, 0xcd, 0x4a, 0xc3, 0x40, + 0x14, 0x85, 0x1d, 0x50, 0x6b, 0xaf, 0xa1, 0xe2, 0x50, 0xa4, 0x46, 0x48, 0x25, 0x0b, 0x51, 0xd1, + 0xa4, 0xf8, 0xb3, 0x14, 0x6c, 0x8b, 0x74, 0x23, 0x45, 0xbb, 0x74, 0x97, 0x4c, 0xc7, 0xb4, 0x60, + 0x32, 0xf1, 0x66, 0x82, 0xe4, 0xed, 0x5c, 0x76, 0xe9, 0xda, 0x45, 0x91, 0xf6, 0x11, 0x7c, 0x01, + 0xc9, 0x24, 0xe9, 0x8f, 0x4a, 0x77, 0xf7, 0x84, 0x7b, 0xce, 0x99, 0x6f, 0x26, 0x50, 0xc1, 0x90, + 0xbd, 0xc6, 0x1c, 0x13, 0x2b, 0x44, 0x21, 0x05, 0xdd, 0x2a, 0xb4, 0x7e, 0xee, 0x0d, 0xe5, 0x20, + 0x76, 0x2d, 0x26, 0x7c, 0xdb, 0x13, 0x9e, 0xb0, 0xd5, 0x82, 0x1b, 0x3f, 0x2b, 0xa5, 0x84, 0x9a, + 0x32, 0xa3, 0xbe, 0x1d, 0x38, 0x3e, 0x8f, 0x72, 0x51, 0x76, 0x98, 0x9f, 0x8d, 0xa6, 0x03, 0x3b, + 0x1d, 0x2e, 0x9b, 0x8c, 0x89, 0x38, 0x90, 0x0f, 0x0e, 0x3a, 0x3e, 0xed, 0x42, 0xa9, 0xd9, 0xef, + 0x23, 0x8f, 0xa2, 0x1a, 0x39, 0x24, 0xc7, 0x5a, 0xeb, 0x6a, 0x34, 0xae, 0xaf, 0x7d, 0x8e, 0xeb, + 0x67, 0x0b, 0x95, 0x83, 0x24, 0xe4, 0xf8, 0xc2, 0xfb, 0x1e, 0x47, 0xdb, 0x8d, 0x11, 0xc5, 0x9b, + 0xcd, 0x30, 0x09, 0xa5, 0xb0, 0x72, 0x6f, 0xaf, 0x08, 0x31, 0x4f, 0x60, 0xf7, 0x7e, 0x18, 0x15, + 0x1d, 0x51, 0x56, 0x52, 0x85, 0x8d, 0xc7, 0x94, 0x43, 0x55, 0x94, 0x7b, 0x99, 0x30, 0x4d, 0xd0, + 0x3a, 0x5c, 0x76, 0x1d, 0x9f, 0x67, 0x5b, 0x14, 0xd6, 0x53, 0x91, 0x2f, 0xa9, 0xd9, 0x3c, 0x82, + 0x4a, 0x1a, 0x97, 0xce, 0xab, 0xb2, 0x2e, 0xbe, 0x49, 0xfe, 0x99, 0xde, 0x00, 0xcc, 0x19, 0xe9, + 0xbe, 0x35, 0xbb, 0xd3, 0x5f, 0xe4, 0x7a, 0xd5, 0x4a, 0x2f, 0xa6, 0x2d, 0x02, 0x86, 0x5c, 0xf2, + 0xc2, 0xd0, 0x06, 0x6d, 0xf1, 0xfc, 0xf4, 0x60, 0x1e, 0xf0, 0x87, 0xeb, 0xff, 0x88, 0x06, 0xa1, + 0x36, 0x94, 0x72, 0x32, 0xba, 0xb7, 0x74, 0x80, 0x19, 0xac, 0xae, 0x59, 0xd9, 0x1b, 0xdd, 0x05, + 0x12, 0x13, 0x7a, 0x0d, 0xe5, 0x19, 0x26, 0xad, 0x2d, 0x57, 0xce, 0xd9, 0x97, 0x4d, 0x0d, 0xd2, + 0xba, 0x1d, 0x4d, 0x0c, 0xf2, 0x31, 0x31, 0xc8, 0xd7, 0xc4, 0x20, 0xef, 0x53, 0x83, 0x8c, 0xa6, + 0x06, 0x79, 0x3a, 0x5d, 0xfd, 0x72, 0x18, 0x32, 0xbb, 0x28, 0x70, 0x37, 0xd5, 0x8f, 0x71, 0xf9, + 0x13, 0x00, 0x00, 0xff, 0xff, 0xfa, 0xef, 0x21, 0x21, 0x7b, 0x02, 0x00, 0x00, +} diff --git a/rpc/rpctransact/rpctransact.pb.go b/rpc/rpctransact/rpctransact.pb.go new file mode 100644 index 000000000..903e977b4 --- /dev/null +++ b/rpc/rpctransact/rpctransact.pb.go @@ -0,0 +1,1488 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: rpctransact.proto + +/* + Package rpctransact is a generated protocol buffer package. + + It is generated from these files: + rpctransact.proto + + It has these top-level messages: + CallCodeParam + PayloadParam + TxEnvelope + TxEnvelopeParam +*/ +package rpctransact + +import proto "github.com/gogo/protobuf/proto" +import golang_proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" +import _ "github.com/gogo/protobuf/gogoproto" +import exec "github.com/hyperledger/burrow/execution/exec" +import payload "github.com/hyperledger/burrow/txs/payload" +import txs "github.com/hyperledger/burrow/txs" + +import github_com_hyperledger_burrow_crypto "github.com/hyperledger/burrow/crypto" +import github_com_hyperledger_burrow_txs "github.com/hyperledger/burrow/txs" + +import context "golang.org/x/net/context" +import grpc "google.golang.org/grpc" + +import io "io" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = golang_proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package + +type CallCodeParam struct { + FromAddress github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,1,opt,name=FromAddress,proto3,customtype=github.com/hyperledger/burrow/crypto.Address" json:"FromAddress"` + Code []byte `protobuf:"bytes,2,opt,name=Code,proto3" json:"Code,omitempty"` + Data []byte `protobuf:"bytes,3,opt,name=Data,proto3" json:"Data,omitempty"` +} + +func (m *CallCodeParam) Reset() { *m = CallCodeParam{} } +func (m *CallCodeParam) String() string { return proto.CompactTextString(m) } +func (*CallCodeParam) ProtoMessage() {} +func (*CallCodeParam) Descriptor() ([]byte, []int) { return fileDescriptorRpctransact, []int{0} } + +func (m *CallCodeParam) GetCode() []byte { + if m != nil { + return m.Code + } + return nil +} + +func (m *CallCodeParam) GetData() []byte { + if m != nil { + return m.Data + } + return nil +} + +func (*CallCodeParam) XXX_MessageName() string { + return "rpctransact.CallCodeParam" +} + +type PayloadParam struct { + CallTx *payload.CallTx `protobuf:"bytes,1,opt,name=CallTx" json:"CallTx,omitempty"` + SendTx *payload.SendTx `protobuf:"bytes,2,opt,name=SendTx" json:"SendTx,omitempty"` + NameTx *payload.NameTx `protobuf:"bytes,3,opt,name=NameTx" json:"NameTx,omitempty"` +} + +func (m *PayloadParam) Reset() { *m = PayloadParam{} } +func (m *PayloadParam) String() string { return proto.CompactTextString(m) } +func (*PayloadParam) ProtoMessage() {} +func (*PayloadParam) Descriptor() ([]byte, []int) { return fileDescriptorRpctransact, []int{1} } + +func (m *PayloadParam) GetCallTx() *payload.CallTx { + if m != nil { + return m.CallTx + } + return nil +} + +func (m *PayloadParam) GetSendTx() *payload.SendTx { + if m != nil { + return m.SendTx + } + return nil +} + +func (m *PayloadParam) GetNameTx() *payload.NameTx { + if m != nil { + return m.NameTx + } + return nil +} + +func (*PayloadParam) XXX_MessageName() string { + return "rpctransact.PayloadParam" +} + +type TxEnvelope struct { + Envelope *github_com_hyperledger_burrow_txs.Envelope `protobuf:"bytes,1,opt,name=Envelope,customtype=github.com/hyperledger/burrow/txs.Envelope" json:"Envelope,omitempty"` +} + +func (m *TxEnvelope) Reset() { *m = TxEnvelope{} } +func (m *TxEnvelope) String() string { return proto.CompactTextString(m) } +func (*TxEnvelope) ProtoMessage() {} +func (*TxEnvelope) Descriptor() ([]byte, []int) { return fileDescriptorRpctransact, []int{2} } + +func (*TxEnvelope) XXX_MessageName() string { + return "rpctransact.TxEnvelope" +} + +type TxEnvelopeParam struct { + // An existing Envelope - either signed or unsigned - if the latter will be signed server-side + Envelope *github_com_hyperledger_burrow_txs.Envelope `protobuf:"bytes,1,opt,name=Envelope,customtype=github.com/hyperledger/burrow/txs.Envelope" json:"Envelope,omitempty"` + // If no Envelope provided then one will be generated from the provided payload and signed server-side + Payload *PayloadParam `protobuf:"bytes,2,opt,name=Payload" json:"Payload,omitempty"` +} + +func (m *TxEnvelopeParam) Reset() { *m = TxEnvelopeParam{} } +func (m *TxEnvelopeParam) String() string { return proto.CompactTextString(m) } +func (*TxEnvelopeParam) ProtoMessage() {} +func (*TxEnvelopeParam) Descriptor() ([]byte, []int) { return fileDescriptorRpctransact, []int{3} } + +func (m *TxEnvelopeParam) GetPayload() *PayloadParam { + if m != nil { + return m.Payload + } + return nil +} + +func (*TxEnvelopeParam) XXX_MessageName() string { + return "rpctransact.TxEnvelopeParam" +} +func init() { + proto.RegisterType((*CallCodeParam)(nil), "rpctransact.CallCodeParam") + golang_proto.RegisterType((*CallCodeParam)(nil), "rpctransact.CallCodeParam") + proto.RegisterType((*PayloadParam)(nil), "rpctransact.PayloadParam") + golang_proto.RegisterType((*PayloadParam)(nil), "rpctransact.PayloadParam") + proto.RegisterType((*TxEnvelope)(nil), "rpctransact.TxEnvelope") + golang_proto.RegisterType((*TxEnvelope)(nil), "rpctransact.TxEnvelope") + proto.RegisterType((*TxEnvelopeParam)(nil), "rpctransact.TxEnvelopeParam") + golang_proto.RegisterType((*TxEnvelopeParam)(nil), "rpctransact.TxEnvelopeParam") +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// Client API for Transact service + +type TransactClient interface { + // Broadcast a transaction to the mempool - if the transaction is not signed signing will be attempted server-side + // and wait for it to be included in block + BroadcastTxSync(ctx context.Context, in *TxEnvelopeParam, opts ...grpc.CallOption) (*exec.TxExecution, error) + // Broadcast a transaction to the mempool - if the transaction is not signed signing will be attempted server-side + BroadcastTxAsync(ctx context.Context, in *TxEnvelopeParam, opts ...grpc.CallOption) (*txs.Receipt, error) + // Sign transaction server-side + SignTx(ctx context.Context, in *TxEnvelopeParam, opts ...grpc.CallOption) (*TxEnvelope, error) + // Formulate a transaction from a Payload and retrun the envelop with the Tx bytes ready to sign + FormulateTx(ctx context.Context, in *PayloadParam, opts ...grpc.CallOption) (*TxEnvelope, error) + // Formulate and sign a CallTx transaction signed server-side and wait for it to be included in a block, retrieving response + CallTxSync(ctx context.Context, in *payload.CallTx, opts ...grpc.CallOption) (*exec.TxExecution, error) + // Formulate and sign a CallTx transaction signed server-side + CallTxAsync(ctx context.Context, in *payload.CallTx, opts ...grpc.CallOption) (*txs.Receipt, error) + // Perform a 'simulated' call of a contract against the current committed EVM state without any changes been saved + // and wait for the transaction to be included in a block + CallTxSim(ctx context.Context, in *payload.CallTx, opts ...grpc.CallOption) (*exec.TxExecution, error) + // Perform a 'simulated' execution of provided code against the current committed EVM state without any changes been saved + CallCodeSim(ctx context.Context, in *CallCodeParam, opts ...grpc.CallOption) (*exec.TxExecution, error) + // Formulate a SendTx transaction signed server-side and wait for it to be included in a block, retrieving response + SendTxSync(ctx context.Context, in *payload.SendTx, opts ...grpc.CallOption) (*exec.TxExecution, error) + // Formulate and SendTx transaction signed server-side + SendTxAsync(ctx context.Context, in *payload.SendTx, opts ...grpc.CallOption) (*txs.Receipt, error) + // Formualte a NameTx signed server-side and wait for it to be included in a block returning the registered name + NameTxSync(ctx context.Context, in *payload.NameTx, opts ...grpc.CallOption) (*exec.TxExecution, error) + // Formulate a NameTx signed server-side + NameTxAsync(ctx context.Context, in *payload.NameTx, opts ...grpc.CallOption) (*txs.Receipt, error) +} + +type transactClient struct { + cc *grpc.ClientConn +} + +func NewTransactClient(cc *grpc.ClientConn) TransactClient { + return &transactClient{cc} +} + +func (c *transactClient) BroadcastTxSync(ctx context.Context, in *TxEnvelopeParam, opts ...grpc.CallOption) (*exec.TxExecution, error) { + out := new(exec.TxExecution) + err := grpc.Invoke(ctx, "/rpctransact.Transact/BroadcastTxSync", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *transactClient) BroadcastTxAsync(ctx context.Context, in *TxEnvelopeParam, opts ...grpc.CallOption) (*txs.Receipt, error) { + out := new(txs.Receipt) + err := grpc.Invoke(ctx, "/rpctransact.Transact/BroadcastTxAsync", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *transactClient) SignTx(ctx context.Context, in *TxEnvelopeParam, opts ...grpc.CallOption) (*TxEnvelope, error) { + out := new(TxEnvelope) + err := grpc.Invoke(ctx, "/rpctransact.Transact/SignTx", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *transactClient) FormulateTx(ctx context.Context, in *PayloadParam, opts ...grpc.CallOption) (*TxEnvelope, error) { + out := new(TxEnvelope) + err := grpc.Invoke(ctx, "/rpctransact.Transact/FormulateTx", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *transactClient) CallTxSync(ctx context.Context, in *payload.CallTx, opts ...grpc.CallOption) (*exec.TxExecution, error) { + out := new(exec.TxExecution) + err := grpc.Invoke(ctx, "/rpctransact.Transact/CallTxSync", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *transactClient) CallTxAsync(ctx context.Context, in *payload.CallTx, opts ...grpc.CallOption) (*txs.Receipt, error) { + out := new(txs.Receipt) + err := grpc.Invoke(ctx, "/rpctransact.Transact/CallTxAsync", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *transactClient) CallTxSim(ctx context.Context, in *payload.CallTx, opts ...grpc.CallOption) (*exec.TxExecution, error) { + out := new(exec.TxExecution) + err := grpc.Invoke(ctx, "/rpctransact.Transact/CallTxSim", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *transactClient) CallCodeSim(ctx context.Context, in *CallCodeParam, opts ...grpc.CallOption) (*exec.TxExecution, error) { + out := new(exec.TxExecution) + err := grpc.Invoke(ctx, "/rpctransact.Transact/CallCodeSim", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *transactClient) SendTxSync(ctx context.Context, in *payload.SendTx, opts ...grpc.CallOption) (*exec.TxExecution, error) { + out := new(exec.TxExecution) + err := grpc.Invoke(ctx, "/rpctransact.Transact/SendTxSync", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *transactClient) SendTxAsync(ctx context.Context, in *payload.SendTx, opts ...grpc.CallOption) (*txs.Receipt, error) { + out := new(txs.Receipt) + err := grpc.Invoke(ctx, "/rpctransact.Transact/SendTxAsync", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *transactClient) NameTxSync(ctx context.Context, in *payload.NameTx, opts ...grpc.CallOption) (*exec.TxExecution, error) { + out := new(exec.TxExecution) + err := grpc.Invoke(ctx, "/rpctransact.Transact/NameTxSync", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *transactClient) NameTxAsync(ctx context.Context, in *payload.NameTx, opts ...grpc.CallOption) (*txs.Receipt, error) { + out := new(txs.Receipt) + err := grpc.Invoke(ctx, "/rpctransact.Transact/NameTxAsync", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// Server API for Transact service + +type TransactServer interface { + // Broadcast a transaction to the mempool - if the transaction is not signed signing will be attempted server-side + // and wait for it to be included in block + BroadcastTxSync(context.Context, *TxEnvelopeParam) (*exec.TxExecution, error) + // Broadcast a transaction to the mempool - if the transaction is not signed signing will be attempted server-side + BroadcastTxAsync(context.Context, *TxEnvelopeParam) (*txs.Receipt, error) + // Sign transaction server-side + SignTx(context.Context, *TxEnvelopeParam) (*TxEnvelope, error) + // Formulate a transaction from a Payload and retrun the envelop with the Tx bytes ready to sign + FormulateTx(context.Context, *PayloadParam) (*TxEnvelope, error) + // Formulate and sign a CallTx transaction signed server-side and wait for it to be included in a block, retrieving response + CallTxSync(context.Context, *payload.CallTx) (*exec.TxExecution, error) + // Formulate and sign a CallTx transaction signed server-side + CallTxAsync(context.Context, *payload.CallTx) (*txs.Receipt, error) + // Perform a 'simulated' call of a contract against the current committed EVM state without any changes been saved + // and wait for the transaction to be included in a block + CallTxSim(context.Context, *payload.CallTx) (*exec.TxExecution, error) + // Perform a 'simulated' execution of provided code against the current committed EVM state without any changes been saved + CallCodeSim(context.Context, *CallCodeParam) (*exec.TxExecution, error) + // Formulate a SendTx transaction signed server-side and wait for it to be included in a block, retrieving response + SendTxSync(context.Context, *payload.SendTx) (*exec.TxExecution, error) + // Formulate and SendTx transaction signed server-side + SendTxAsync(context.Context, *payload.SendTx) (*txs.Receipt, error) + // Formualte a NameTx signed server-side and wait for it to be included in a block returning the registered name + NameTxSync(context.Context, *payload.NameTx) (*exec.TxExecution, error) + // Formulate a NameTx signed server-side + NameTxAsync(context.Context, *payload.NameTx) (*txs.Receipt, error) +} + +func RegisterTransactServer(s *grpc.Server, srv TransactServer) { + s.RegisterService(&_Transact_serviceDesc, srv) +} + +func _Transact_BroadcastTxSync_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(TxEnvelopeParam) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(TransactServer).BroadcastTxSync(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/rpctransact.Transact/BroadcastTxSync", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(TransactServer).BroadcastTxSync(ctx, req.(*TxEnvelopeParam)) + } + return interceptor(ctx, in, info, handler) +} + +func _Transact_BroadcastTxAsync_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(TxEnvelopeParam) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(TransactServer).BroadcastTxAsync(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/rpctransact.Transact/BroadcastTxAsync", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(TransactServer).BroadcastTxAsync(ctx, req.(*TxEnvelopeParam)) + } + return interceptor(ctx, in, info, handler) +} + +func _Transact_SignTx_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(TxEnvelopeParam) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(TransactServer).SignTx(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/rpctransact.Transact/SignTx", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(TransactServer).SignTx(ctx, req.(*TxEnvelopeParam)) + } + return interceptor(ctx, in, info, handler) +} + +func _Transact_FormulateTx_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(PayloadParam) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(TransactServer).FormulateTx(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/rpctransact.Transact/FormulateTx", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(TransactServer).FormulateTx(ctx, req.(*PayloadParam)) + } + return interceptor(ctx, in, info, handler) +} + +func _Transact_CallTxSync_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(payload.CallTx) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(TransactServer).CallTxSync(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/rpctransact.Transact/CallTxSync", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(TransactServer).CallTxSync(ctx, req.(*payload.CallTx)) + } + return interceptor(ctx, in, info, handler) +} + +func _Transact_CallTxAsync_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(payload.CallTx) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(TransactServer).CallTxAsync(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/rpctransact.Transact/CallTxAsync", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(TransactServer).CallTxAsync(ctx, req.(*payload.CallTx)) + } + return interceptor(ctx, in, info, handler) +} + +func _Transact_CallTxSim_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(payload.CallTx) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(TransactServer).CallTxSim(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/rpctransact.Transact/CallTxSim", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(TransactServer).CallTxSim(ctx, req.(*payload.CallTx)) + } + return interceptor(ctx, in, info, handler) +} + +func _Transact_CallCodeSim_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(CallCodeParam) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(TransactServer).CallCodeSim(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/rpctransact.Transact/CallCodeSim", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(TransactServer).CallCodeSim(ctx, req.(*CallCodeParam)) + } + return interceptor(ctx, in, info, handler) +} + +func _Transact_SendTxSync_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(payload.SendTx) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(TransactServer).SendTxSync(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/rpctransact.Transact/SendTxSync", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(TransactServer).SendTxSync(ctx, req.(*payload.SendTx)) + } + return interceptor(ctx, in, info, handler) +} + +func _Transact_SendTxAsync_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(payload.SendTx) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(TransactServer).SendTxAsync(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/rpctransact.Transact/SendTxAsync", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(TransactServer).SendTxAsync(ctx, req.(*payload.SendTx)) + } + return interceptor(ctx, in, info, handler) +} + +func _Transact_NameTxSync_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(payload.NameTx) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(TransactServer).NameTxSync(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/rpctransact.Transact/NameTxSync", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(TransactServer).NameTxSync(ctx, req.(*payload.NameTx)) + } + return interceptor(ctx, in, info, handler) +} + +func _Transact_NameTxAsync_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(payload.NameTx) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(TransactServer).NameTxAsync(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/rpctransact.Transact/NameTxAsync", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(TransactServer).NameTxAsync(ctx, req.(*payload.NameTx)) + } + return interceptor(ctx, in, info, handler) +} + +var _Transact_serviceDesc = grpc.ServiceDesc{ + ServiceName: "rpctransact.Transact", + HandlerType: (*TransactServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "BroadcastTxSync", + Handler: _Transact_BroadcastTxSync_Handler, + }, + { + MethodName: "BroadcastTxAsync", + Handler: _Transact_BroadcastTxAsync_Handler, + }, + { + MethodName: "SignTx", + Handler: _Transact_SignTx_Handler, + }, + { + MethodName: "FormulateTx", + Handler: _Transact_FormulateTx_Handler, + }, + { + MethodName: "CallTxSync", + Handler: _Transact_CallTxSync_Handler, + }, + { + MethodName: "CallTxAsync", + Handler: _Transact_CallTxAsync_Handler, + }, + { + MethodName: "CallTxSim", + Handler: _Transact_CallTxSim_Handler, + }, + { + MethodName: "CallCodeSim", + Handler: _Transact_CallCodeSim_Handler, + }, + { + MethodName: "SendTxSync", + Handler: _Transact_SendTxSync_Handler, + }, + { + MethodName: "SendTxAsync", + Handler: _Transact_SendTxAsync_Handler, + }, + { + MethodName: "NameTxSync", + Handler: _Transact_NameTxSync_Handler, + }, + { + MethodName: "NameTxAsync", + Handler: _Transact_NameTxAsync_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "rpctransact.proto", +} + +func (m *CallCodeParam) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CallCodeParam) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + dAtA[i] = 0xa + i++ + i = encodeVarintRpctransact(dAtA, i, uint64(m.FromAddress.Size())) + n1, err := m.FromAddress.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n1 + if len(m.Code) > 0 { + dAtA[i] = 0x12 + i++ + i = encodeVarintRpctransact(dAtA, i, uint64(len(m.Code))) + i += copy(dAtA[i:], m.Code) + } + if len(m.Data) > 0 { + dAtA[i] = 0x1a + i++ + i = encodeVarintRpctransact(dAtA, i, uint64(len(m.Data))) + i += copy(dAtA[i:], m.Data) + } + return i, nil +} + +func (m *PayloadParam) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PayloadParam) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.CallTx != nil { + dAtA[i] = 0xa + i++ + i = encodeVarintRpctransact(dAtA, i, uint64(m.CallTx.Size())) + n2, err := m.CallTx.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n2 + } + if m.SendTx != nil { + dAtA[i] = 0x12 + i++ + i = encodeVarintRpctransact(dAtA, i, uint64(m.SendTx.Size())) + n3, err := m.SendTx.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n3 + } + if m.NameTx != nil { + dAtA[i] = 0x1a + i++ + i = encodeVarintRpctransact(dAtA, i, uint64(m.NameTx.Size())) + n4, err := m.NameTx.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n4 + } + return i, nil +} + +func (m *TxEnvelope) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *TxEnvelope) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.Envelope != nil { + dAtA[i] = 0xa + i++ + i = encodeVarintRpctransact(dAtA, i, uint64(m.Envelope.Size())) + n5, err := m.Envelope.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n5 + } + return i, nil +} + +func (m *TxEnvelopeParam) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *TxEnvelopeParam) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.Envelope != nil { + dAtA[i] = 0xa + i++ + i = encodeVarintRpctransact(dAtA, i, uint64(m.Envelope.Size())) + n6, err := m.Envelope.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n6 + } + if m.Payload != nil { + dAtA[i] = 0x12 + i++ + i = encodeVarintRpctransact(dAtA, i, uint64(m.Payload.Size())) + n7, err := m.Payload.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n7 + } + return i, nil +} + +func encodeVarintRpctransact(dAtA []byte, offset int, v uint64) int { + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return offset + 1 +} +func (m *CallCodeParam) Size() (n int) { + var l int + _ = l + l = m.FromAddress.Size() + n += 1 + l + sovRpctransact(uint64(l)) + l = len(m.Code) + if l > 0 { + n += 1 + l + sovRpctransact(uint64(l)) + } + l = len(m.Data) + if l > 0 { + n += 1 + l + sovRpctransact(uint64(l)) + } + return n +} + +func (m *PayloadParam) Size() (n int) { + var l int + _ = l + if m.CallTx != nil { + l = m.CallTx.Size() + n += 1 + l + sovRpctransact(uint64(l)) + } + if m.SendTx != nil { + l = m.SendTx.Size() + n += 1 + l + sovRpctransact(uint64(l)) + } + if m.NameTx != nil { + l = m.NameTx.Size() + n += 1 + l + sovRpctransact(uint64(l)) + } + return n +} + +func (m *TxEnvelope) Size() (n int) { + var l int + _ = l + if m.Envelope != nil { + l = m.Envelope.Size() + n += 1 + l + sovRpctransact(uint64(l)) + } + return n +} + +func (m *TxEnvelopeParam) Size() (n int) { + var l int + _ = l + if m.Envelope != nil { + l = m.Envelope.Size() + n += 1 + l + sovRpctransact(uint64(l)) + } + if m.Payload != nil { + l = m.Payload.Size() + n += 1 + l + sovRpctransact(uint64(l)) + } + return n +} + +func sovRpctransact(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n +} +func sozRpctransact(x uint64) (n int) { + return sovRpctransact(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *CallCodeParam) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpctransact + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CallCodeParam: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CallCodeParam: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field FromAddress", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpctransact + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthRpctransact + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.FromAddress.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Code", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpctransact + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthRpctransact + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Code = append(m.Code[:0], dAtA[iNdEx:postIndex]...) + if m.Code == nil { + m.Code = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpctransact + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthRpctransact + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) + if m.Data == nil { + m.Data = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipRpctransact(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthRpctransact + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PayloadParam) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpctransact + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PayloadParam: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PayloadParam: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CallTx", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpctransact + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthRpctransact + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.CallTx == nil { + m.CallTx = &payload.CallTx{} + } + if err := m.CallTx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SendTx", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpctransact + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthRpctransact + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.SendTx == nil { + m.SendTx = &payload.SendTx{} + } + if err := m.SendTx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NameTx", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpctransact + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthRpctransact + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.NameTx == nil { + m.NameTx = &payload.NameTx{} + } + if err := m.NameTx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipRpctransact(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthRpctransact + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *TxEnvelope) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpctransact + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: TxEnvelope: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: TxEnvelope: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Envelope", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpctransact + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthRpctransact + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Envelope == nil { + m.Envelope = &github_com_hyperledger_burrow_txs.Envelope{} + } + if err := m.Envelope.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipRpctransact(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthRpctransact + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *TxEnvelopeParam) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpctransact + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: TxEnvelopeParam: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: TxEnvelopeParam: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Envelope", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpctransact + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthRpctransact + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Envelope == nil { + m.Envelope = &github_com_hyperledger_burrow_txs.Envelope{} + } + if err := m.Envelope.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Payload", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpctransact + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthRpctransact + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Payload == nil { + m.Payload = &PayloadParam{} + } + if err := m.Payload.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipRpctransact(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthRpctransact + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipRpctransact(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowRpctransact + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowRpctransact + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowRpctransact + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + iNdEx += length + if length < 0 { + return 0, ErrInvalidLengthRpctransact + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowRpctransact + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipRpctransact(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} + +var ( + ErrInvalidLengthRpctransact = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowRpctransact = fmt.Errorf("proto: integer overflow") +) + +func init() { proto.RegisterFile("rpctransact.proto", fileDescriptorRpctransact) } +func init() { golang_proto.RegisterFile("rpctransact.proto", fileDescriptorRpctransact) } + +var fileDescriptorRpctransact = []byte{ + // 552 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x54, 0xcd, 0x6e, 0xd3, 0x40, + 0x10, 0xc6, 0xfc, 0x84, 0x76, 0x92, 0x28, 0x74, 0x2f, 0x84, 0x08, 0x25, 0x28, 0x17, 0x10, 0x6a, + 0xed, 0xa8, 0xe5, 0x88, 0x40, 0x49, 0x68, 0x8f, 0xa8, 0x72, 0x2c, 0x24, 0xb8, 0x6d, 0xec, 0xc5, + 0x8d, 0x64, 0x7b, 0xad, 0xf5, 0x06, 0x36, 0x8f, 0xc0, 0x89, 0x67, 0xe8, 0x9b, 0x70, 0xcc, 0x91, + 0x73, 0x0f, 0x11, 0x4a, 0x5f, 0x04, 0xed, 0x4f, 0x60, 0x6d, 0x9a, 0x96, 0x4b, 0x6f, 0xe3, 0x6f, + 0x66, 0xbe, 0x99, 0xef, 0xd3, 0x8e, 0x61, 0x8f, 0xe5, 0x21, 0x67, 0x38, 0x2b, 0x70, 0xc8, 0xdd, + 0x9c, 0x51, 0x4e, 0x51, 0xdd, 0x82, 0x3a, 0x07, 0xf1, 0x8c, 0x9f, 0xcd, 0xa7, 0x6e, 0x48, 0x53, + 0x2f, 0xa6, 0x31, 0xf5, 0x54, 0xcd, 0x74, 0xfe, 0x59, 0x7d, 0xa9, 0x0f, 0x15, 0xe9, 0xde, 0x0e, + 0x10, 0x41, 0x42, 0x13, 0x37, 0x73, 0xbc, 0x48, 0x28, 0x8e, 0xcc, 0xe7, 0x2e, 0x17, 0x85, 0x0e, + 0xfb, 0xdf, 0x1d, 0x68, 0x8e, 0x71, 0x92, 0x8c, 0x69, 0x44, 0x4e, 0x31, 0xc3, 0x29, 0xfa, 0x00, + 0xf5, 0x13, 0x46, 0xd3, 0x61, 0x14, 0x31, 0x52, 0x14, 0x6d, 0xe7, 0x99, 0xf3, 0xa2, 0x31, 0x7a, + 0xb5, 0x5c, 0xf5, 0xee, 0x5c, 0xac, 0x7a, 0xfb, 0xd6, 0x0e, 0x67, 0x8b, 0x9c, 0xb0, 0x84, 0x44, + 0x31, 0x61, 0xde, 0x74, 0xce, 0x18, 0xfd, 0xea, 0x85, 0x6c, 0x91, 0x73, 0xea, 0x9a, 0x5e, 0xdf, + 0x26, 0x42, 0x08, 0xee, 0xcb, 0x21, 0xed, 0xbb, 0x92, 0xd0, 0x57, 0xb1, 0xc4, 0xde, 0x61, 0x8e, + 0xdb, 0xf7, 0x34, 0x26, 0xe3, 0xfe, 0x37, 0x07, 0x1a, 0xa7, 0x7a, 0x5d, 0xbd, 0xd0, 0x73, 0xa8, + 0xc9, 0x0d, 0x03, 0xa1, 0x76, 0xa9, 0x1f, 0xb6, 0xdc, 0x8d, 0x1a, 0x0d, 0xfb, 0x26, 0x2d, 0x0b, + 0x27, 0x24, 0x8b, 0x02, 0xa1, 0x66, 0xd8, 0x85, 0x1a, 0xf6, 0x4d, 0x5a, 0x16, 0xbe, 0xc7, 0x29, + 0x09, 0x84, 0x1a, 0x6c, 0x17, 0x6a, 0xd8, 0x37, 0xe9, 0x7e, 0x0c, 0x10, 0x88, 0xe3, 0xec, 0x0b, + 0x49, 0x68, 0x4e, 0xd0, 0x47, 0xd8, 0xd9, 0xc4, 0x66, 0x95, 0xa6, 0x2b, 0x9d, 0xdc, 0x80, 0x23, + 0xf7, 0x62, 0xd5, 0x7b, 0x79, 0xbd, 0x43, 0x76, 0xbd, 0xff, 0x87, 0xae, 0x7f, 0xee, 0x40, 0xeb, + 0xef, 0x24, 0xad, 0xfb, 0xf6, 0xc6, 0xa1, 0x23, 0x78, 0x68, 0x2c, 0x36, 0x56, 0x3d, 0x71, 0xed, + 0xc7, 0x67, 0xdb, 0xef, 0x6f, 0x2a, 0x0f, 0xcf, 0x1f, 0xc0, 0x4e, 0x60, 0x4a, 0xd0, 0x08, 0x5a, + 0x23, 0x46, 0x71, 0x14, 0xe2, 0x82, 0x07, 0x62, 0xb2, 0xc8, 0x42, 0xf4, 0xb4, 0xc4, 0x51, 0x51, + 0xd3, 0xd9, 0x73, 0xd5, 0x7b, 0x0c, 0xc4, 0xb1, 0x20, 0xe1, 0x9c, 0xcf, 0x68, 0x86, 0xde, 0xc0, + 0x23, 0x8b, 0x63, 0x58, 0xdc, 0x4c, 0xd2, 0x50, 0x06, 0xf8, 0x24, 0x24, 0xb3, 0x9c, 0xa3, 0xb7, + 0x50, 0x9b, 0xcc, 0xe2, 0x2c, 0x10, 0x37, 0x74, 0x3d, 0xde, 0x92, 0x45, 0x43, 0xa8, 0x9f, 0x50, + 0x96, 0xce, 0x13, 0xcc, 0x49, 0x20, 0xd0, 0x76, 0x13, 0xb6, 0x53, 0x0c, 0x00, 0xf4, 0xeb, 0x53, + 0x16, 0x54, 0x9f, 0xe6, 0x55, 0xaa, 0xf7, 0xa1, 0xae, 0x93, 0x5a, 0xf0, 0x3f, 0x2d, 0x65, 0x8d, + 0x1e, 0xec, 0x1a, 0xfe, 0x59, 0xfa, 0x5f, 0xf4, 0xaf, 0x35, 0xbd, 0x3c, 0x2f, 0xd9, 0xd2, 0x29, + 0x2d, 0x5e, 0xba, 0xf4, 0xab, 0xba, 0x07, 0x00, 0xfa, 0x46, 0x2a, 0x72, 0x34, 0xb8, 0x45, 0x8e, + 0x4e, 0x56, 0xe5, 0x98, 0x96, 0xb2, 0x9c, 0x01, 0x80, 0x3e, 0xad, 0x0a, 0xbf, 0x06, 0xb7, 0xf0, + 0xeb, 0x64, 0x95, 0xdf, 0xb4, 0x94, 0xf8, 0x47, 0xe3, 0xe5, 0xba, 0xeb, 0xfc, 0x5c, 0x77, 0x9d, + 0x5f, 0xeb, 0xae, 0xf3, 0xe3, 0xb2, 0xeb, 0x2c, 0x2f, 0xbb, 0xce, 0xa7, 0x83, 0xeb, 0x8f, 0x84, + 0xe5, 0xa1, 0x67, 0xb9, 0x34, 0xad, 0xa9, 0x5f, 0xe3, 0xd1, 0xef, 0x00, 0x00, 0x00, 0xff, 0xff, + 0x0f, 0x15, 0x24, 0xfe, 0x91, 0x05, 0x00, 0x00, +} diff --git a/rpc/rpctransact/transact_server.go b/rpc/rpctransact/transact_server.go new file mode 100644 index 000000000..ab3a8c6ea --- /dev/null +++ b/rpc/rpctransact/transact_server.go @@ -0,0 +1,148 @@ +package rpctransact + +import ( + "fmt" + + "github.com/hyperledger/burrow/execution" + "github.com/hyperledger/burrow/execution/exec" + "github.com/hyperledger/burrow/txs" + "github.com/hyperledger/burrow/txs/payload" + "golang.org/x/net/context" +) + +type transactServer struct { + transactor *execution.Transactor + txCodec txs.Codec +} + +func NewTransactServer(transactor *execution.Transactor, txCodec txs.Codec) TransactServer { + return &transactServer{ + transactor: transactor, + txCodec: txCodec, + } +} + +func (ts *transactServer) BroadcastTxSync(ctx context.Context, param *TxEnvelopeParam) (*exec.TxExecution, error) { + txEnv := param.GetEnvelope(ts.transactor.Tip.ChainID()) + if txEnv == nil { + return nil, fmt.Errorf("no transaction envelope or payload provided") + } + return ts.transactor.BroadcastTxSync(ctx, txEnv) +} + +func (ts *transactServer) BroadcastTxAsync(ctx context.Context, param *TxEnvelopeParam) (*txs.Receipt, error) { + txEnv := param.GetEnvelope(ts.transactor.Tip.ChainID()) + if txEnv == nil { + return nil, fmt.Errorf("no transaction envelope or payload provided") + } + return ts.transactor.BroadcastTxAsync(txEnv) +} + +func (ts *transactServer) SignTx(ctx context.Context, param *TxEnvelopeParam) (*TxEnvelope, error) { + txEnv := param.GetEnvelope(ts.transactor.Tip.ChainID()) + if txEnv == nil { + return nil, fmt.Errorf("no transaction envelope or payload provided") + } + txEnv, err := ts.transactor.SignTx(txEnv) + if err != nil { + return nil, err + } + return &TxEnvelope{ + Envelope: txEnv, + }, nil +} + +func (ts *transactServer) FormulateTx(ctx context.Context, param *PayloadParam) (*TxEnvelope, error) { + txEnv := param.Envelope(ts.transactor.Tip.ChainID()) + if txEnv == nil { + return nil, fmt.Errorf("no payload provided to FormulateTx") + } + return &TxEnvelope{ + Envelope: txEnv, + }, nil +} + +func (ts *transactServer) CallTxSync(ctx context.Context, param *payload.CallTx) (*exec.TxExecution, error) { + return ts.BroadcastTxSync(ctx, txEnvelopeParam(param)) +} + +func (ts *transactServer) CallTxAsync(ctx context.Context, param *payload.CallTx) (*txs.Receipt, error) { + return ts.BroadcastTxAsync(ctx, txEnvelopeParam(param)) +} + +func (ts *transactServer) CallTxSim(ctx context.Context, param *payload.CallTx) (*exec.TxExecution, error) { + if param.Address == nil { + return nil, fmt.Errorf("CallSim requires a non-nil address from which to retrieve code") + } + return ts.transactor.CallSim(param.Input.Address, *param.Address, param.Data) +} + +func (ts *transactServer) CallCodeSim(ctx context.Context, param *CallCodeParam) (*exec.TxExecution, error) { + return ts.transactor.CallCodeSim(param.FromAddress, param.Code, param.Data) +} + +func (ts *transactServer) SendTxSync(ctx context.Context, param *payload.SendTx) (*exec.TxExecution, error) { + return ts.BroadcastTxSync(ctx, txEnvelopeParam(param)) +} + +func (ts *transactServer) SendTxAsync(ctx context.Context, param *payload.SendTx) (*txs.Receipt, error) { + return ts.BroadcastTxAsync(ctx, txEnvelopeParam(param)) +} + +func (ts *transactServer) NameTxSync(ctx context.Context, param *payload.NameTx) (*exec.TxExecution, error) { + return ts.BroadcastTxSync(ctx, txEnvelopeParam(param)) +} + +func (ts *transactServer) NameTxAsync(ctx context.Context, param *payload.NameTx) (*txs.Receipt, error) { + return ts.BroadcastTxAsync(ctx, txEnvelopeParam(param)) +} + +func (te *TxEnvelopeParam) GetEnvelope(chainID string) *txs.Envelope { + if te == nil { + return nil + } + if te.Envelope != nil { + return te.Envelope + } + if te.Payload != nil { + return te.Payload.Envelope(chainID) + } + return nil +} + +func (pp *PayloadParam) Envelope(chainID string) *txs.Envelope { + if pp.CallTx != nil { + return txs.Enclose(chainID, pp.CallTx) + } + if pp.SendTx != nil { + return txs.Enclose(chainID, pp.SendTx) + } + if pp.NameTx != nil { + return txs.Enclose(chainID, pp.NameTx) + } + return nil +} + +func txEnvelopeParam(pl payload.Payload) *TxEnvelopeParam { + switch tx := pl.(type) { + case *payload.CallTx: + return &TxEnvelopeParam{ + Payload: &PayloadParam{ + CallTx: tx, + }, + } + case *payload.SendTx: + return &TxEnvelopeParam{ + Payload: &PayloadParam{ + SendTx: tx, + }, + } + case *payload.NameTx: + return &TxEnvelopeParam{ + Payload: &PayloadParam{ + NameTx: tx, + }, + } + } + return nil +} diff --git a/rpc/rpctransactor/integration/transactor_server_test.go b/rpc/rpctransactor/integration/transactor_server_test.go deleted file mode 100644 index cbb1a1c75..000000000 --- a/rpc/rpctransactor/integration/transactor_server_test.go +++ /dev/null @@ -1,168 +0,0 @@ -// +build integration - -// Space above here matters -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package integration - -import ( - "context" - "sync" - "testing" - - "github.com/hyperledger/burrow/binary" - "github.com/hyperledger/burrow/execution/pbtransactor" - "github.com/hyperledger/burrow/rpc" - "github.com/hyperledger/burrow/rpc/test" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "google.golang.org/grpc" -) - -func TestTransactCallNoCode(t *testing.T) { - cli := newClient(t) - - // Flip flops between sending private key and input address to test private key and address based signing - toAddress := privateAccounts[2].Address() - - numCreates := 1000 - countCh := test.CommittedTxCount(t, kern.Emitter) - for i := 0; i < numCreates; i++ { - receipt, err := cli.Transact(context.Background(), &pbtransactor.TransactParam{ - InputAccount: inputAccount(i), - Address: toAddress.Bytes(), - Data: []byte{}, - Value: 0, - Fee: 2, - GasLimit: 10000 + uint64(i), - }) - require.NoError(t, err) - assert.False(t, receipt.CreatesContract) - assert.Equal(t, toAddress.Bytes(), receipt.ContractAddress) - } - require.Equal(t, numCreates, <-countCh) -} - -func TestTransactCreate(t *testing.T) { - cli := newClient(t) - numGoroutines := 100 - numCreates := 50 - wg := new(sync.WaitGroup) - wg.Add(numGoroutines) - countCh := test.CommittedTxCount(t, kern.Emitter) - for i := 0; i < numGoroutines; i++ { - go func() { - for j := 0; j < numCreates; j++ { - create, err := cli.Transact(context.Background(), &pbtransactor.TransactParam{ - InputAccount: inputAccount(i), - Address: nil, - Data: test.Bytecode_strange_loop, - Value: 0, - Fee: 2, - GasLimit: 10000, - }) - if assert.NoError(t, err) { - assert.True(t, create.CreatesContract) - } - } - wg.Done() - }() - } - wg.Wait() - - require.Equal(t, numGoroutines*numCreates, <-countCh) -} - -func BenchmarkTransactCreateContract(b *testing.B) { - cli := newClient(b) - for i := 0; i < b.N; i++ { - create, err := cli.Transact(context.Background(), &pbtransactor.TransactParam{ - InputAccount: inputAccount(i), - Address: nil, - Data: test.Bytecode_strange_loop, - Value: 0, - Fee: 2, - GasLimit: 10000, - }) - require.NoError(b, err) - assert.True(b, create.CreatesContract) - } -} - -func TestTransactAndHold(t *testing.T) { - cli := newClient(t) - numGoroutines := 5 - numRuns := 2 - countCh := test.CommittedTxCount(t, kern.Emitter) - for i := 0; i < numGoroutines; i++ { - for j := 0; j < numRuns; j++ { - create := test.CreateContract(t, cli, inputAccount(i)) - call := test.CallContract(t, cli, inputAccount(i), create.CallData.Callee) - depth := binary.Uint64FromWord256(binary.LeftPadWord256(call.Return)) - // Would give 23 if taken from wrong frame - assert.Equal(t, 18, int(depth)) - } - } - require.Equal(t, numGoroutines*numRuns*2, <-countCh) -} - -func TestSend(t *testing.T) { - cli := newClient(t) - numSends := 1000 - countCh := test.CommittedTxCount(t, kern.Emitter) - for i := 0; i < numSends; i++ { - send, err := cli.Send(context.Background(), &pbtransactor.SendParam{ - InputAccount: inputAccount(i), - Amount: 2003, - ToAddress: privateAccounts[3].Address().Bytes(), - }) - require.NoError(t, err) - assert.Equal(t, false, send.CreatesContract) - } - require.Equal(t, numSends, <-countCh) -} - -func TestSendAndHold(t *testing.T) { - cli := newClient(t) - for i := 0; i < 2; i++ { - send, err := cli.SendAndHold(context.Background(), &pbtransactor.SendParam{ - InputAccount: inputAccount(i), - Amount: 2003, - ToAddress: privateAccounts[3].Address().Bytes(), - }) - require.NoError(t, err) - assert.Equal(t, false, send.CreatesContract) - } -} - -// Helpers -func newClient(t testing.TB) pbtransactor.TransactorClient { - conn, err := grpc.Dial(rpc.DefaultGRPCConfig().ListenAddress, grpc.WithInsecure()) - require.NoError(t, err) - return pbtransactor.NewTransactorClient(conn) -} - -var inputPrivateKey = privateAccounts[0].PrivateKey().RawBytes() -var inputAddress = privateAccounts[0].Address().Bytes() - -func inputAccount(i int) *pbtransactor.InputAccount { - ia := new(pbtransactor.InputAccount) - if i%2 == 0 { - ia.PrivateKey = inputPrivateKey - } else { - ia.Address = inputAddress - } - return ia -} diff --git a/rpc/rpctransactor/transactor_server.go b/rpc/rpctransactor/transactor_server.go deleted file mode 100644 index aeed1c4b0..000000000 --- a/rpc/rpctransactor/transactor_server.go +++ /dev/null @@ -1,190 +0,0 @@ -package rpctransactor - -import ( - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/account/state" - "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/execution" - "github.com/hyperledger/burrow/execution/events/pbevents" - "github.com/hyperledger/burrow/execution/pbtransactor" - "github.com/hyperledger/burrow/txs" - "golang.org/x/net/context" -) - -type transactorServer struct { - transactor *execution.Transactor - accounts *execution.Accounts - txCodec txs.Codec - reader state.Reader -} - -func NewTransactorServer(transactor *execution.Transactor, accounts *execution.Accounts, reader state.Reader, - txCodec txs.Codec) pbtransactor.TransactorServer { - return &transactorServer{ - transactor: transactor, - accounts: accounts, - reader: reader, - txCodec: txCodec, - } -} - -func (ts *transactorServer) BroadcastTx(ctx context.Context, param *pbtransactor.TxParam) (*pbtransactor.TxReceipt, error) { - receipt, err := ts.transactor.BroadcastTxRaw(param.GetTx()) - if err != nil { - return nil, err - } - return txReceipt(receipt), nil -} - -func (ts *transactorServer) Call(ctx context.Context, param *pbtransactor.CallParam) (*pbtransactor.CallResult, error) { - fromAddress, err := crypto.AddressFromBytes(param.GetFrom()) - if err != nil { - return nil, err - } - address, err := crypto.AddressFromBytes(param.GetAddress()) - if err != nil { - return nil, err - } - call, err := ts.transactor.Call(ts.reader, fromAddress, address, param.GetData()) - return &pbtransactor.CallResult{ - Return: call.Return, - GasUsed: call.GasUsed, - }, nil -} - -func (ts *transactorServer) CallCode(ctx context.Context, param *pbtransactor.CallCodeParam) (*pbtransactor.CallResult, error) { - fromAddress, err := crypto.AddressFromBytes(param.GetFrom()) - if err != nil { - return nil, err - } - call, err := ts.transactor.CallCode(ts.reader, fromAddress, param.GetCode(), param.GetData()) - return &pbtransactor.CallResult{ - Return: call.Return, - GasUsed: call.GasUsed, - }, nil -} - -func (ts *transactorServer) Transact(ctx context.Context, param *pbtransactor.TransactParam) (*pbtransactor.TxReceipt, error) { - inputAccount, err := ts.inputAccount(param.GetInputAccount()) - if err != nil { - return nil, err - } - address, err := crypto.MaybeAddressFromBytes(param.GetAddress()) - if err != nil { - return nil, err - } - receipt, err := ts.transactor.Transact(inputAccount, address, param.GetData(), param.GetGasLimit(), param.GetValue(), - param.GetFee()) - if err != nil { - return nil, err - } - return txReceipt(receipt), nil -} - -func (ts *transactorServer) TransactAndHold(ctx context.Context, param *pbtransactor.TransactParam) (*pbevents.EventDataCall, error) { - inputAccount, err := ts.inputAccount(param.GetInputAccount()) - if err != nil { - return nil, err - } - address, err := crypto.MaybeAddressFromBytes(param.GetAddress()) - if err != nil { - return nil, err - } - edt, err := ts.transactor.TransactAndHold(ctx, inputAccount, address, param.GetData(), param.GetGasLimit(), - param.GetValue(), param.GetFee()) - if err != nil { - return nil, err - } - return pbevents.GetEventDataCall(edt), nil -} - -func (ts *transactorServer) Send(ctx context.Context, param *pbtransactor.SendParam) (*pbtransactor.TxReceipt, error) { - inputAccount, err := ts.inputAccount(param.GetInputAccount()) - if err != nil { - return nil, err - } - toAddress, err := crypto.AddressFromBytes(param.GetToAddress()) - if err != nil { - return nil, err - } - receipt, err := ts.transactor.Send(inputAccount, toAddress, param.GetAmount()) - if err != nil { - return nil, err - } - return txReceipt(receipt), nil -} - -func (ts *transactorServer) SendAndHold(ctx context.Context, param *pbtransactor.SendParam) (*pbtransactor.TxReceipt, error) { - inputAccount, err := ts.inputAccount(param.GetInputAccount()) - if err != nil { - return nil, err - } - toAddress, err := crypto.AddressFromBytes(param.GetToAddress()) - if err != nil { - return nil, err - } - receipt, err := ts.transactor.SendAndHold(ctx, inputAccount, toAddress, param.GetAmount()) - if err != nil { - return nil, err - } - return txReceipt(receipt), nil -} - -func (ts *transactorServer) SignTx(ctx context.Context, param *pbtransactor.SignTxParam) (*pbtransactor.SignedTx, error) { - txEnv, err := ts.txCodec.DecodeTx(param.GetTx()) - if err != nil { - return nil, err - } - signers, err := signersFromPrivateAccounts(param.GetPrivateAccounts()) - if err != nil { - return nil, err - } - txEnvSigned, err := ts.transactor.SignTx(txEnv, signers) - if err != nil { - return nil, err - } - bs, err := ts.txCodec.EncodeTx(txEnvSigned) - if err != nil { - return nil, err - } - return &pbtransactor.SignedTx{ - Tx: bs, - }, nil -} - -func (ts *transactorServer) inputAccount(inAcc *pbtransactor.InputAccount) (*execution.SequentialSigningAccount, error) { - return ts.accounts.GetSequentialSigningAccount(inAcc.GetAddress(), inAcc.GetPrivateKey()) -} - -func txReceipt(receipt *txs.Receipt) *pbtransactor.TxReceipt { - return &pbtransactor.TxReceipt{ - ContractAddress: receipt.ContractAddress.Bytes(), - CreatesContract: receipt.CreatesContract, - TxHash: receipt.TxHash, - } -} - -func signersFromPrivateAccounts(privateAccounts []*pbtransactor.PrivateAccount) ([]acm.AddressableSigner, error) { - signers := make([]acm.AddressableSigner, len(privateAccounts)) - var err error - for i, pa := range privateAccounts { - signers[i], err = privateAccount(pa) - if err != nil { - return nil, err - } - } - return signers, nil -} - -func privateAccount(privateAccount *pbtransactor.PrivateAccount) (acm.PrivateAccount, error) { - privateKey, err := crypto.PrivateKeyFromRawBytes(privateAccount.PrivateKey, crypto.CurveTypeEd25519) - if err != nil { - return nil, err - } - publicKey := privateKey.GetPublicKey() - return acm.ConcretePrivateAccount{ - Address: publicKey.Address(), - PrivateKey: privateKey, - PublicKey: publicKey, - }.PrivateAccount(), nil -} diff --git a/rpc/service.go b/rpc/service.go index 0863a65a4..098dd1503 100644 --- a/rpc/service.go +++ b/rpc/service.go @@ -15,73 +15,51 @@ package rpc import ( - "context" + "encoding/json" "fmt" - "time" - "encoding/json" - - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/state" "github.com/hyperledger/burrow/binary" bcm "github.com/hyperledger/burrow/blockchain" "github.com/hyperledger/burrow/consensus/tendermint/query" "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/event" "github.com/hyperledger/burrow/execution" "github.com/hyperledger/burrow/execution/names" - "github.com/hyperledger/burrow/keys" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" "github.com/hyperledger/burrow/permission" "github.com/hyperledger/burrow/project" "github.com/hyperledger/burrow/txs" - tm_types "github.com/tendermint/tendermint/types" - "github.com/tmthrgd/go-hex" + tmTypes "github.com/tendermint/tendermint/types" ) // Magic! Should probably be configurable, but not shouldn't be so huge we // end up DoSing ourselves. const MaxBlockLookback = 1000 -const AccountsRingMutexCount = 100 // Base service that provides implementation for all underlying RPC methods type Service struct { - ctx context.Context - state state.IterableReader - nameReg names.IterableReader - mempoolAccounts *execution.Accounts - subscribable event.Subscribable - blockchain bcm.BlockchainInfo - transactor *execution.Transactor - nodeView *query.NodeView - logger *logging.Logger + state state.IterableReader + nameReg names.IterableReader + blockchain bcm.BlockchainInfo + transactor *execution.Transactor + nodeView *query.NodeView + logger *logging.Logger } -func NewService(ctx context.Context, state state.IterableReader, nameReg names.IterableReader, - checker state.Reader, subscribable event.Subscribable, blockchain bcm.BlockchainInfo, keyClient keys.KeyClient, - transactor *execution.Transactor, nodeView *query.NodeView, logger *logging.Logger) *Service { - - return &Service{ - ctx: ctx, - state: state, - mempoolAccounts: execution.NewAccounts(checker, keyClient, AccountsRingMutexCount), - nameReg: nameReg, - subscribable: subscribable, - blockchain: blockchain, - transactor: transactor, - nodeView: nodeView, - logger: logger.With(structure.ComponentKey, "Service"), - } -} +func NewService(state state.IterableReader, nameReg names.IterableReader, + blockchain bcm.BlockchainInfo, transactor *execution.Transactor, nodeView *query.NodeView, + logger *logging.Logger) *Service { -// Provides a sub-service with only the subscriptions methods -func NewSubscribableService(subscribable event.Subscribable, logger *logging.Logger) *Service { return &Service{ - ctx: context.Background(), - subscribable: subscribable, - logger: logger.With(structure.ComponentKey, "Service"), + state: state, + nameReg: nameReg, + blockchain: blockchain, + transactor: transactor, + nodeView: nodeView, + logger: logger.With(structure.ComponentKey, "Service"), } } @@ -91,18 +69,6 @@ func (s *Service) Transactor() *execution.Transactor { return s.transactor } -// By providing certain methods on the Transactor (such as Transact, Send, etc) with the (non-final) MempoolAccounts -// rather than the committed (final) Accounts state the transactor can assign a sequence number based on all of the txs -// it has seen since the last block - provided these transactions are successfully committed (via DeliverTx) then -// subsequent transactions will have valid sequence numbers. This allows Burrow to coordinate sequencing and signing -// for a key it holds or is provided - it is down to the key-holder to manage the mutual information between transactions -// concurrent within a new block window. - -// Get pending account state residing in the mempool -func (s *Service) MempoolAccounts() *execution.Accounts { - return s.mempoolAccounts -} - func (s *Service) State() state.Reader { return s.state } @@ -111,6 +77,10 @@ func (s *Service) BlockchainInfo() bcm.BlockchainInfo { return s.blockchain } +func (s *Service) ChainID() string { + return s.blockchain.ChainID() +} + func (s *Service) ListUnconfirmedTxs(maxTxs int) (*ResultListUnconfirmedTxs, error) { // Get all transactions for now transactions, err := s.nodeView.MempoolTransactions(maxTxs) @@ -127,42 +97,10 @@ func (s *Service) ListUnconfirmedTxs(maxTxs int) (*ResultListUnconfirmedTxs, err }, nil } -func (s *Service) Subscribe(ctx context.Context, subscriptionID string, eventID string, - callback func(resultEvent *ResultEvent) (stop bool)) error { - - queryBuilder := event.QueryForEventID(eventID) - s.logger.InfoMsg("Subscribing to events", - "query", queryBuilder.String(), - "subscription_id", subscriptionID, - "event_id", eventID) - return event.SubscribeCallback(ctx, s.subscribable, subscriptionID, queryBuilder, - func(message interface{}) (stop bool) { - resultEvent, err := NewResultEvent(eventID, message) - if err != nil { - s.logger.InfoMsg("Received event that could not be mapped to ResultEvent", - structure.ErrorKey, err, - "subscription_id", subscriptionID, - "event_id", eventID) - return false - } - return callback(resultEvent) - }) -} - -func (s *Service) Unsubscribe(ctx context.Context, subscriptionID string) error { - s.logger.InfoMsg("Unsubscribing from events", - "subscription_id", subscriptionID) - err := s.subscribable.UnsubscribeAll(ctx, subscriptionID) - if err != nil { - return fmt.Errorf("error unsubscribing from event with subscriptionID '%s': %v", subscriptionID, err) - } - return nil -} - func (s *Service) Status() (*ResultStatus, error) { latestHeight := s.blockchain.LastBlockHeight() var ( - latestBlockMeta *tm_types.BlockMeta + latestBlockMeta *tmTypes.BlockMeta latestBlockHash []byte latestBlockTime int64 ) @@ -287,7 +225,6 @@ func (s *Service) DumpStorage(address crypto.Address) (*ResultDumpStorage, error return }) return &ResultDumpStorage{ - StorageRoot: account.StorageRoot(), StorageItems: storageItems, }, nil } @@ -315,7 +252,6 @@ func (s *Service) GetAccountHumanReadable(address crypto.Address) (*ResultGetAcc Sequence: acc.Sequence(), Balance: acc.Balance(), Code: tokens, - StorageRoot: hex.EncodeUpperToString(acc.StorageRoot()), Permissions: perms, Roles: acc.Permissions().Roles, }, @@ -324,7 +260,7 @@ func (s *Service) GetAccountHumanReadable(address crypto.Address) (*ResultGetAcc // Name registry func (s *Service) GetName(name string) (*ResultGetName, error) { - entry, err := s.nameReg.GetNameEntry(name) + entry, err := s.nameReg.GetName(name) if err != nil { return nil, err } @@ -336,7 +272,7 @@ func (s *Service) GetName(name string) (*ResultGetName, error) { func (s *Service) ListNames(predicate func(*names.Entry) bool) (*ResultListNames, error) { var nms []*names.Entry - s.nameReg.IterateNameEntries(func(entry *names.Entry) (stop bool) { + s.nameReg.IterateNames(func(entry *names.Entry) (stop bool) { if predicate(entry) { nms = append(nms, entry) } @@ -373,7 +309,7 @@ func (s *Service) ListBlocks(minHeight, maxHeight uint64) (*ResultListBlocks, er minHeight = maxHeight - MaxBlockLookback } - var blockMetas []*tm_types.BlockMeta + var blockMetas []*tmTypes.BlockMeta for height := maxHeight; height >= minHeight; height-- { blockMeta := s.nodeView.BlockStore().LoadBlockMeta(int64(height)) blockMetas = append(blockMetas, blockMeta) @@ -419,7 +355,7 @@ func (s *Service) GeneratePrivateAccount() (*ResultGeneratePrivateAccount, error return nil, err } return &ResultGeneratePrivateAccount{ - PrivateAccount: acm.AsConcretePrivateAccount(privateAccount), + PrivateAccount: privateAccount.ConcretePrivateAccount(), }, nil } diff --git a/rpc/subscriptions.go b/rpc/subscriptions.go deleted file mode 100644 index 35808890b..000000000 --- a/rpc/subscriptions.go +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package rpc - -import ( - "context" - "fmt" - "sync" - "time" - - "github.com/hyperledger/burrow/event" -) - -var ( - reaperPeriod = 5 * time.Second - reaperThreshold = 20 * time.Second -) - -// Catches events that callers subscribe to and adds them to an array ready to be polled. -type Subscriptions struct { - mtx *sync.RWMutex - service *Service - subs map[string]*SubscriptionsCache - reap bool -} - -type SubscriptionsCache struct { - mtx *sync.Mutex - events []interface{} - ts time.Time - subID string -} - -func NewSubscriptions(service *Service) *Subscriptions { - es := &Subscriptions{ - mtx: &sync.RWMutex{}, - service: service, - subs: make(map[string]*SubscriptionsCache), - reap: true, - } - if es.reap { - go reap(es) - } - return es -} - -func newSubscriptionsCache(subID string) *SubscriptionsCache { - return &SubscriptionsCache{ - subID: subID, - mtx: &sync.Mutex{}, - events: make([]interface{}, 0), - ts: time.Now(), - } -} - -func (subsCache *SubscriptionsCache) poll() []interface{} { - subsCache.mtx.Lock() - defer subsCache.mtx.Unlock() - var evts []interface{} - if len(subsCache.events) > 0 { - evts = subsCache.events - subsCache.events = []interface{}{} - } else { - evts = []interface{}{} - } - subsCache.ts = time.Now() - return evts -} - -// Remove old subscriptions not recently polled -func reap(es *Subscriptions) { - for { - time.Sleep(reaperPeriod) - for id, sub := range es.subs { - if time.Since(sub.ts) > reaperThreshold { - es.mtx.Lock() - delete(es.subs, id) - es.service.Unsubscribe(context.Background(), id) - es.mtx.Unlock() - } - } - } -} - -// Add a subscription and return the generated id. Note event dispatcher -// has to call func which involves acquiring a mutex lock, so might be -// a delay - though a conflict is practically impossible, and if it does -// happen it's for an insignificant amount of time (the time it takes to -// carry out SubscriptionsCache.poll() ). -func (subs *Subscriptions) Add(eventId string) (string, error) { - subID, err := event.GenerateSubscriptionID() - if err != nil { - return "", err - } - subs.mtx.Lock() - defer subs.mtx.Unlock() - cache := newSubscriptionsCache(subID) - subs.subs[subID] = cache - - err = subs.service.Subscribe(context.Background(), subID, eventId, func(resultEvent *ResultEvent) (stop bool) { - cache.mtx.Lock() - defer cache.mtx.Unlock() - cache.events = append(cache.events, resultEvent) - return - }) - if err != nil { - return "", err - } - - return subID, nil -} - -func (subs *Subscriptions) Poll(subId string) ([]interface{}, error) { - subs.mtx.RLock() - defer subs.mtx.RUnlock() - sub, ok := subs.subs[subId] - if !ok { - return nil, fmt.Errorf("Subscription not active. ID: " + subId) - } - return sub.poll(), nil -} - -func (subs *Subscriptions) Remove(subId string) error { - subs.mtx.Lock() - defer subs.mtx.Unlock() - _, ok := subs.subs[subId] - if !ok { - return fmt.Errorf("Subscription not active. ID: " + subId) - } - delete(subs.subs, subId) - return nil -} diff --git a/rpc/subscriptions_test.go b/rpc/subscriptions_test.go deleted file mode 100644 index fa67f6cf7..000000000 --- a/rpc/subscriptions_test.go +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package rpc - -import ( - "encoding/hex" - "fmt" - "testing" - "time" - - "github.com/hyperledger/burrow/event" - "github.com/hyperledger/burrow/logging" - "github.com/stretchr/testify/assert" -) - -var mockInterval = 20 * time.Millisecond - -// Test that event subscriptions can be added manually and then automatically reaped. -func TestSubReaping(t *testing.T) { - NUM_SUBS := 100 - reaperThreshold = 200 * time.Millisecond - reaperPeriod = 100 * time.Millisecond - - mee := event.NewEmitter(logging.NewNoopLogger()) - eSubs := NewSubscriptions(NewSubscribableService(mee, logging.NewNoopLogger())) - doneChan := make(chan error) - go func() { - for i := 0; i < NUM_SUBS; i++ { - time.Sleep(2 * time.Millisecond) - go func() { - id, err := eSubs.Add("WeirdEvent") - if err != nil { - doneChan <- err - return - } - if len(id) != 64 { - doneChan <- fmt.Errorf("Id not of length 64") - return - } - _, err2 := hex.DecodeString(id) - if err2 != nil { - doneChan <- err2 - } - - doneChan <- nil - }() - } - }() - k := 0 - for k < NUM_SUBS { - err := <-doneChan - assert.NoError(t, err) - k++ - } - time.Sleep(1100 * time.Millisecond) - - assert.Len(t, eSubs.subs, 0) - t.Logf("Added %d subs that were all automatically reaped.", NUM_SUBS) -} - -// Test that event subscriptions can be added and removed manually. -func TestSubManualClose(t *testing.T) { - NUM_SUBS := 100 - // Keep the reaper out of this. - reaperThreshold = 10000 * time.Millisecond - reaperPeriod = 10000 * time.Millisecond - - mee := event.NewEmitter(logging.NewNoopLogger()) - eSubs := NewSubscriptions(NewSubscribableService(mee, logging.NewNoopLogger())) - doneChan := make(chan error) - go func() { - for i := 0; i < NUM_SUBS; i++ { - time.Sleep(2 * time.Millisecond) - go func() { - id, err := eSubs.Add("WeirdEvent") - if err != nil { - doneChan <- err - return - } - if len(id) != 64 { - doneChan <- fmt.Errorf("Id not of length 64") - return - } - _, err2 := hex.DecodeString(id) - if err2 != nil { - doneChan <- err2 - } - time.Sleep(100 * time.Millisecond) - err3 := eSubs.Remove(id) - if err3 != nil { - doneChan <- err3 - } - doneChan <- nil - }() - } - }() - k := 0 - for k < NUM_SUBS { - err := <-doneChan - assert.NoError(t, err) - k++ - } - - assert.Len(t, eSubs.subs, 0) - t.Logf("Added %d subs that were all closed down by unsubscribing.", NUM_SUBS) -} - -// Test that the system doesn't fail under high pressure. -func TestSubFlooding(t *testing.T) { - NUM_SUBS := 100 - // Keep the reaper out of this. - reaperThreshold = 10000 * time.Millisecond - reaperPeriod = 10000 * time.Millisecond - // Crank it up. Now pressure is 10 times higher on each sub. - mockInterval = 1 * time.Millisecond - mee := event.NewEmitter(logging.NewNoopLogger()) - eSubs := NewSubscriptions(NewSubscribableService(mee, logging.NewNoopLogger())) - doneChan := make(chan error) - go func() { - for i := 0; i < NUM_SUBS; i++ { - time.Sleep(1 * time.Millisecond) - go func() { - id, err := eSubs.Add("WeirdEvent") - if err != nil { - doneChan <- err - return - } - if len(id) != 64 { - doneChan <- fmt.Errorf("Id not of length 64") - return - } - _, err2 := hex.DecodeString(id) - if err2 != nil { - doneChan <- err2 - } - time.Sleep(1000 * time.Millisecond) - err3 := eSubs.Remove(id) - if err3 != nil { - doneChan <- err3 - } - doneChan <- nil - }() - } - }() - k := 0 - for k < NUM_SUBS { - err := <-doneChan - assert.NoError(t, err) - k++ - } - - assert.Len(t, eSubs.subs, 0) - t.Logf("Added %d subs that all received 1000 events each. They were all closed down by unsubscribing.", NUM_SUBS) -} diff --git a/rpc/test/helpers.go b/rpc/test/helpers.go deleted file mode 100644 index 0e7d934f5..000000000 --- a/rpc/test/helpers.go +++ /dev/null @@ -1,99 +0,0 @@ -package test - -import ( - "context" - "testing" - - "github.com/hyperledger/burrow/consensus/tendermint" - "github.com/hyperledger/burrow/event" - "github.com/hyperledger/burrow/execution/events/pbevents" - "github.com/hyperledger/burrow/execution/evm/abi" - "github.com/hyperledger/burrow/execution/pbtransactor" - "github.com/hyperledger/burrow/rpc" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "google.golang.org/grpc" -) - -// Recursive call count for UpsieDownsie() function call from strange_loop.sol -// Equals initial call, then depth from 17 -> 34, one for the bounce, then depth from 34 -> 23, -// so... (I didn't say it had to make sense): -const UpsieDownsieCallCount = 1 + (34 - 17) + 1 + (34 - 23) - -// Helpers -func NewTransactorClient(t testing.TB) pbtransactor.TransactorClient { - conn, err := grpc.Dial(rpc.DefaultGRPCConfig().ListenAddress, grpc.WithInsecure()) - require.NoError(t, err) - return pbtransactor.NewTransactorClient(conn) -} - -func NewExecutionEventsClient(t testing.TB) pbevents.ExecutionEventsClient { - conn, err := grpc.Dial(rpc.DefaultGRPCConfig().ListenAddress, grpc.WithInsecure()) - require.NoError(t, err) - return pbevents.NewExecutionEventsClient(conn) -} - -func NewEventsClient(t testing.TB) pbevents.EventsClient { - conn, err := grpc.Dial(rpc.DefaultGRPCConfig().ListenAddress, grpc.WithInsecure()) - require.NoError(t, err) - return pbevents.NewEventsClient(conn) -} - -func CommittedTxCount(t *testing.T, em event.Emitter) chan int { - var numTxs int64 - emptyBlocks := 0 - maxEmptyBlocks := 2 - outCh := make(chan int) - ctx := context.Background() - ch, err := tendermint.SubscribeNewBlock(ctx, em) - require.NoError(t, err) - - go func() { - for ed := range ch { - if ed.Block.NumTxs == 0 { - emptyBlocks++ - } else { - emptyBlocks = 0 - } - if emptyBlocks > maxEmptyBlocks { - break - } - numTxs += ed.Block.NumTxs - t.Logf("Total TXs committed at block %v: %v (+%v)\n", ed.Block.Height, numTxs, ed.Block.NumTxs) - } - outCh <- int(numTxs) - }() - return outCh -} - -func CreateContract(t testing.TB, cli pbtransactor.TransactorClient, - inputAccount *pbtransactor.InputAccount) *pbevents.EventDataCall { - - create, err := cli.TransactAndHold(context.Background(), &pbtransactor.TransactParam{ - InputAccount: inputAccount, - Address: nil, - Data: Bytecode_strange_loop, - Value: 0, - Fee: 2, - GasLimit: 10000, - }) - require.NoError(t, err) - assert.Equal(t, uint64(0), create.StackDepth) - return create -} - -func CallContract(t testing.TB, cli pbtransactor.TransactorClient, - inputAccount *pbtransactor.InputAccount, contractAddress []byte) (call *pbevents.EventDataCall) { - - functionID := abi.FunctionID("UpsieDownsie()") - call, err := cli.TransactAndHold(context.Background(), &pbtransactor.TransactParam{ - InputAccount: inputAccount, - Address: contractAddress, - Data: functionID[:], - Value: 0, - Fee: 2, - GasLimit: 10000, - }) - require.NoError(t, err) - return call -} diff --git a/rpc/tm/client/websocket_client.go b/rpc/tm/client/websocket_client.go deleted file mode 100644 index d07f05f1d..000000000 --- a/rpc/tm/client/websocket_client.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package client - -import ( - "context" - - "github.com/hyperledger/burrow/rpc/lib/types" - "github.com/hyperledger/burrow/rpc/tm" -) - -type WebsocketClient interface { - Send(ctx context.Context, request types.RPCRequest) error -} - -const SubscribeRequestID = "Subscribe" -const UnsubscribeRequestID = "Unsubscribe" - -func EventResponseID(eventID string) string { - return tm.EventResponseID(SubscribeRequestID, eventID) -} - -func Subscribe(wsc WebsocketClient, eventID string) error { - req, err := types.MapToRequest(SubscribeRequestID, - "subscribe", map[string]interface{}{"eventID": eventID}) - if err != nil { - return err - } - return wsc.Send(context.Background(), req) -} - -func Unsubscribe(websocketClient WebsocketClient, subscriptionID string) error { - req, err := types.MapToRequest(UnsubscribeRequestID, - "unsubscribe", map[string]interface{}{"subscriptionID": subscriptionID}) - if err != nil { - return err - } - return websocketClient.Send(context.Background(), req) -} diff --git a/rpc/tm/integration/server_test.go b/rpc/tm/integration/server_test.go deleted file mode 100644 index b30a66ec1..000000000 --- a/rpc/tm/integration/server_test.go +++ /dev/null @@ -1,398 +0,0 @@ -// +build integration - -// Space above here matters -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package integration - -import ( - "bytes" - "testing" - "time" - - "fmt" - "strings" - - "github.com/hyperledger/burrow/binary" - exe_events "github.com/hyperledger/burrow/execution/events" - "github.com/hyperledger/burrow/execution/names" - "github.com/hyperledger/burrow/rpc" - tm_client "github.com/hyperledger/burrow/rpc/tm/client" - "github.com/hyperledger/burrow/txs" - "github.com/hyperledger/burrow/txs/payload" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/consensus/types" - "golang.org/x/crypto/ripemd160" -) - -func testWithAllClients(t *testing.T, testFunction func(*testing.T, string, tm_client.RPCClient)) { - for clientName, client := range clients { - testFunction(t, clientName, client) - } -} - -//-------------------------------------------------------------------------------- -func TestStatus(t *testing.T) { - testWithAllClients(t, func(t *testing.T, clientName string, client tm_client.RPCClient) { - resp, err := tm_client.Status(client) - assert.NoError(t, err) - assert.Equal(t, genesisDoc.ChainID(), resp.NodeInfo.Network, "ChainID should match NodeInfo.Network") - }) -} - -func TestBroadcastTx(t *testing.T) { - testWithAllClients(t, func(t *testing.T, clientName string, client tm_client.RPCClient) { - // Avoid duplicate Tx in mempool - amt := hashString(clientName) % 1000 - toAddr := privateAccounts[1].Address() - txEnv := makeDefaultSendTxSigned(t, client, toAddr, amt) - receipt, err := broadcastTxAndWait(t, client, txEnv) - require.NoError(t, err) - assert.False(t, receipt.CreatesContract, "This tx should not create a contract") - assert.NotEmpty(t, receipt.TxHash, "Failed to compute tx hash") - - hasher := ripemd160.New() - txSignBytes, err := txEnv.Tx.SignBytes() - require.NoError(t, err) - hasher.Write(txSignBytes) - txHashExpected := hasher.Sum(nil) - - if bytes.Compare(receipt.TxHash, txHashExpected) != 0 { - t.Fatalf("The receipt hash '%x' does not equal the ripemd160 hash of the "+ - "transaction signed bytes calculated in the test: '%x'", - receipt.TxHash, txHashExpected) - } - }) -} - -func TestGetAccount(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - testWithAllClients(t, func(t *testing.T, clientName string, client tm_client.RPCClient) { - acc := getAccount(t, client, privateAccounts[0].Address()) - if acc == nil { - t.Fatal("Account was nil") - } - if acc.Address() != privateAccounts[0].Address() { - t.Fatalf("Failed to get correct account. Got %s, expected %s", acc.Address(), - privateAccounts[0].Address()) - } - }) -} - -func TestGetStorage(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - testWithAllClients(t, func(t *testing.T, clientName string, client tm_client.RPCClient) { - amt, gasLim, fee := uint64(1100), uint64(1000), uint64(1000) - code := []byte{0x60, 0x5, 0x60, 0x1, 0x55} - // Call with nil address will create a contract - tx := makeDefaultCallTx(t, client, nil, code, amt, gasLim, fee) - receipt, err := broadcastTxAndWait(t, client, tx) - assert.NoError(t, err) - assert.Equal(t, true, receipt.CreatesContract, "This transaction should"+ - " create a contract") - assert.NotEqual(t, 0, len(receipt.TxHash), "Receipt should contain a"+ - " transaction hash") - contractAddr := receipt.ContractAddress - assert.NotEqual(t, 0, len(contractAddr), "Transactions claims to have"+ - " created a contract but the contract address is empty") - - v := getStorage(t, client, contractAddr, []byte{0x1}) - got := binary.LeftPadWord256(v) - expected := binary.LeftPadWord256([]byte{0x5}) - if got.Compare(expected) != 0 { - t.Fatalf("Wrong storage value. Got %x, expected %x", got.Bytes(), - expected.Bytes()) - } - }) -} - -func TestCallCode(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - - testWithAllClients(t, func(t *testing.T, clientName string, client tm_client.RPCClient) { - // add two integers and return the result - code := []byte{0x60, 0x5, 0x60, 0x6, 0x1, 0x60, 0x0, 0x52, 0x60, 0x20, 0x60, - 0x0, 0xf3} - data := []byte{} - expected := []byte{0xb} - callCode(t, client, privateAccounts[0].Address(), code, data, expected) - - // pass two ints as calldata, add, and return the result - code = []byte{0x60, 0x0, 0x35, 0x60, 0x20, 0x35, 0x1, 0x60, 0x0, 0x52, 0x60, - 0x20, 0x60, 0x0, 0xf3} - data = append(binary.LeftPadWord256([]byte{0x5}).Bytes(), - binary.LeftPadWord256([]byte{0x6}).Bytes()...) - expected = []byte{0xb} - callCode(t, client, privateAccounts[0].Address(), code, data, expected) - }) -} - -func TestCallContract(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - testWithAllClients(t, func(t *testing.T, clientName string, client tm_client.RPCClient) { - // create the contract - amt, gasLim, fee := uint64(6969), uint64(1000), uint64(1000) - code, _, _ := simpleContract() - tx := makeDefaultCallTx(t, client, nil, code, amt, gasLim, fee) - receipt, err := broadcastTxAndWait(t, client, tx) - assert.NoError(t, err) - if err != nil { - t.Fatalf("Problem broadcasting transaction: %v", err) - } - assert.Equal(t, true, receipt.CreatesContract, "This transaction should"+ - " create a contract") - assert.NotEqual(t, 0, len(receipt.TxHash), "Receipt should contain a"+ - " transaction hash") - contractAddr := receipt.ContractAddress - assert.NotEqual(t, 0, len(contractAddr), "Transactions claims to have"+ - " created a contract but the contract address is empty") - - // run a call through the contract - data := []byte{} - expected := []byte{0xb} - callContract(t, client, privateAccounts[0].Address(), contractAddr, data, expected) - }) -} - -func TestNameReg(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - wsc := newWSClient() - defer stopWSClient(wsc) - testWithAllClients(t, func(t *testing.T, clientName string, client tm_client.RPCClient) { - names.MinNameRegistrationPeriod = 1 - - // register a new name, check if its there - // since entries ought to be unique and these run against different clients, we append the client - name := "ye_old_domain_name_" + clientName - const data = "if not now, when" - fee := uint64(1000) - numDesiredBlocks := uint64(2) - amt := fee + numDesiredBlocks*names.NameByteCostMultiplier*names.NameBlockCostMultiplier*names.NameBaseCost(name, data) - - txEnv := makeDefaultNameTx(t, client, name, data, amt, fee) - // verify the name by both using the event and by checking get_name - subscribeAndWaitForNext(t, wsc, exe_events.EventStringNameReg(name), - func() { - broadcastTx(t, client, txEnv) - }, - func(eventID string, resultEvent *rpc.ResultEvent) (bool, error) { - - eventDataTx := resultEvent.Execution.GetTx() - assert.NotNil(t, eventDataTx, "could not convert %s to EventDataTx", resultEvent) - tx, ok := eventDataTx.Tx.Payload.(*payload.NameTx) - if !ok { - t.Fatalf("Could not convert %v to *NameTx", eventDataTx) - } - assert.Equal(t, name, tx.Name) - assert.Equal(t, data, tx.Data) - return true, nil - }) - - entry := getNameRegEntry(t, client, name) - assert.Equal(t, data, entry.Data) - assert.Equal(t, privateAccounts[0].Address(), entry.Owner) - - // update the data as the owner, make sure still there - numDesiredBlocks = uint64(5) - const updatedData = "these are amongst the things I wish to bestow upon " + - "the youth of generations come: a safe supply of honey, and a better " + - "money. For what else shall they need" - amt = fee + numDesiredBlocks*names.NameByteCostMultiplier* - names.NameBlockCostMultiplier*names.NameBaseCost(name, updatedData) - txEnv = makeDefaultNameTx(t, client, name, updatedData, amt, fee) - broadcastTxAndWait(t, client, txEnv) - entry = getNameRegEntry(t, client, name) - - assert.Equal(t, updatedData, entry.Data) - - // try to update as non owner, should fail - tx := payload.NewNameTxWithSequence(privateAccounts[1].PublicKey(), name, "never mind", amt, fee, - getSequence(t, client, privateAccounts[1].Address())+1) - txEnv = txs.Enclose(genesisDoc.ChainID(), tx) - require.NoError(t, txEnv.Sign(privateAccounts[1])) - - _, err := tm_client.BroadcastTx(client, txEnv) - assert.Error(t, err, "Expected error when updating someone else's unexpired"+ - " name registry entry") - if err != nil { - assert.Contains(t, err.Error(), "permission denied", "Error should be "+ - "permission denied") - } - - // Wait a couple of blocks to make sure name registration expires - waitNBlocks(t, wsc, 5) - - //now the entry should be expired, so we can update as non owner - const data2 = "this is not my beautiful house" - tx = payload.NewNameTxWithSequence(privateAccounts[1].PublicKey(), name, data2, amt, fee, - getSequence(t, client, privateAccounts[1].Address())+1) - txEnv = txs.Enclose(genesisDoc.ChainID(), tx) - require.NoError(t, txEnv.Sign(privateAccounts[1])) - - //_, err = tm_client.BroadcastTx(client, tx) - require.NoError(t, subscribeAndWaitForNext(t, wsc, exe_events.EventStringNameReg(name), - func() { - _, err = tm_client.BroadcastTx(client, txEnv) - assert.NoError(t, err, "Should be able to update a previously expired name"+ - " registry entry as a different address") - }, - func(eventID string, resultEvent *rpc.ResultEvent) (bool, error) { - return true, nil - })) - entry = getNameRegEntry(t, client, name) - assert.Equal(t, data2, entry.Data) - assert.Equal(t, privateAccounts[1].Address(), entry.Owner) - }) -} - -func TestWaitBlocks(t *testing.T) { - wsc := newWSClient() - defer stopWSClient(wsc) - waitNBlocks(t, wsc, 5) -} - -func TestBlockchainInfo(t *testing.T) { - wsc := newWSClient() - defer stopWSClient(wsc) - testWithAllClients(t, func(t *testing.T, clientName string, client tm_client.RPCClient) { - // wait a mimimal number of blocks to ensure that the later query for block - // headers has a non-trivial length - nBlocks := 4 - waitNBlocks(t, wsc, nBlocks) - - resp, err := tm_client.ListBlocks(client, 0, 0) - if err != nil { - t.Fatalf("Failed to get blockchain info: %v", err) - } - lastBlockHeight := resp.LastHeight - nMetaBlocks := len(resp.BlockMetas) - assert.True(t, uint64(nMetaBlocks) <= lastBlockHeight, - "Logically number of block metas should be equal or less than block height.") - assert.True(t, nBlocks <= len(resp.BlockMetas), - "Should see at least %v BlockMetas after waiting for %v blocks but saw %v", - nBlocks, nBlocks, len(resp.BlockMetas)) - // For the maximum number (default to 20) of retrieved block headers, - // check that they correctly chain to each other. - lastBlockHash := resp.BlockMetas[nMetaBlocks-1].Header.Hash() - for i := nMetaBlocks - 2; i >= 0; i-- { - // the blockhash in header of height h should be identical to the hash - // in the LastBlockID of the header of block height h+1. - assert.Equal(t, lastBlockHash, resp.BlockMetas[i].Header.LastBlockID.Hash, - "Blockchain should be a hash tree!") - lastBlockHash = resp.BlockMetas[i].Header.Hash() - } - - // Now retrieve only two blockheaders (h=1, and h=2) and check that we got - // two results. - resp, err = tm_client.ListBlocks(client, 1, 2) - assert.NoError(t, err) - assert.Equal(t, 2, len(resp.BlockMetas), - "Should see 2 BlockMetas after extracting 2 blocks") - }) -} - -func TestListUnconfirmedTxs(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - wsc := newWSClient() - defer stopWSClient(wsc) - testWithAllClients(t, func(t *testing.T, clientName string, client tm_client.RPCClient) { - amt, gasLim, fee := uint64(1100), uint64(1000), uint64(1000) - code := []byte{0x60, 0x5, 0x60, 0x1, 0x55} - // Call with nil address will create a contract - txEnv := makeDefaultCallTx(t, client, nil, code, amt, gasLim, fee) - txChan := make(chan []*txs.Envelope) - - // We want to catch the Tx in mempool before it gets reaped by tendermint - // consensus. We should be able to do this almost always if we broadcast our - // transaction immediately after a block has been committed. There is about - // 1 second between blocks, and we will have the lock on Reap - // So we wait for a block here - waitNBlocks(t, wsc, 1) - - go func() { - for { - resp, err := tm_client.ListUnconfirmedTxs(client, -1) - if resp != nil { - - } - require.NoError(t, err) - if resp.NumTxs > 0 { - txChan <- resp.Txs - } - } - }() - - require.NoError(t, runThenWaitForBlock(t, wsc, nextBlockPredicateFn(), func() { - broadcastTx(t, client, txEnv) - select { - case <-time.After(time.Second * timeoutSeconds * 10): - t.Fatal("Timeout out waiting for unconfirmed transactions to appear") - case transactions := <-txChan: - assert.Len(t, transactions, 1, "There should only be a single transaction in the "+ - "mempool during this test (previous txs should have made it into a block)") - assert.Contains(t, transactions, txEnv, "Transaction should be returned by ListUnconfirmedTxs") - } - })) - }) -} - -func TestGetBlock(t *testing.T) { - wsc := newWSClient() - testWithAllClients(t, func(t *testing.T, clientName string, client tm_client.RPCClient) { - waitNBlocks(t, wsc, 3) - resp, err := tm_client.GetBlock(client, 2) - assert.NoError(t, err) - assert.Equal(t, int64(2), resp.Block.Height) - assert.Equal(t, int64(2), resp.BlockMeta.Header.Height) - }) -} - -func TestListValidators(t *testing.T) { - wsc := newWSClient() - testWithAllClients(t, func(t *testing.T, clientName string, client tm_client.RPCClient) { - waitNBlocks(t, wsc, 3) - resp, err := tm_client.ListValidators(client) - assert.NoError(t, err) - assert.Len(t, resp.BondedValidators, 1) - validator := resp.BondedValidators[0] - assert.Equal(t, genesisDoc.Validators[0].PublicKey, validator.PublicKey) - }) -} - -func TestDumpConsensusState(t *testing.T) { - wsc := newWSClient() - startTime := time.Now() - testWithAllClients(t, func(t *testing.T, clientName string, client tm_client.RPCClient) { - waitNBlocks(t, wsc, 3) - resp, err := tm_client.DumpConsensusState(client) - assert.NoError(t, err) - assert.NotZero(t, startTime) - assert.Equal(t, fmt.Sprintf("/0/%d", types.RoundStepNewHeight), - strings.TrimLeft(resp.RoundState.HeightRoundStep, "0123456789")) - }) -} diff --git a/rpc/tm/integration/shared.go b/rpc/tm/integration/shared.go deleted file mode 100644 index 8b33acc3b..000000000 --- a/rpc/tm/integration/shared.go +++ /dev/null @@ -1,240 +0,0 @@ -// +build integration - -// Space above here matters -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package integration - -import ( - "bytes" - "hash/fnv" - "testing" - - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/binary" - "github.com/hyperledger/burrow/core/integration" - "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/execution/names" - "github.com/hyperledger/burrow/rpc" - rpcClient "github.com/hyperledger/burrow/rpc/lib/client" - tmClient "github.com/hyperledger/burrow/rpc/tm/client" - "github.com/hyperledger/burrow/txs" - "github.com/hyperledger/burrow/txs/payload" - "github.com/stretchr/testify/require" -) - -const ( - rpcAddr = "0.0.0.0:46657" - websocketAddr = rpcAddr - websocketEndpoint = "/websocket" -) - -// global variables for use across all tests -var ( - privateAccounts = integration.MakePrivateAccounts(5) // make keys - jsonRpcClient = rpcClient.NewJSONRPCClient(rpcAddr) - httpClient = rpcClient.NewURIClient(rpcAddr) - clients = map[string]tmClient.RPCClient{ - "JSONRPC": jsonRpcClient, - "HTTP": httpClient, - } - genesisDoc = integration.TestGenesisDoc(privateAccounts) -) - -//------------------------------------------------------------------------------- -// some default transaction functions - -func makeDefaultSendTx(t *testing.T, client tmClient.RPCClient, addr crypto.Address, amt uint64) *payload.SendTx { - sequence := getSequence(t, client, privateAccounts[0].Address()) - tx := payload.NewSendTx() - tx.AddInputWithSequence(privateAccounts[0].PublicKey(), amt, sequence+1) - tx.AddOutput(addr, amt) - return tx -} - -func makeDefaultSendTxSigned(t *testing.T, client tmClient.RPCClient, addr crypto.Address, amt uint64) *txs.Envelope { - txEnv := txs.Enclose(genesisDoc.ChainID(), makeDefaultSendTx(t, client, addr, amt)) - require.NoError(t, txEnv.Sign(privateAccounts[0])) - return txEnv -} - -func makeDefaultCallTx(t *testing.T, client tmClient.RPCClient, addr *crypto.Address, code []byte, amt, gasLim, - fee uint64) *txs.Envelope { - sequence := getSequence(t, client, privateAccounts[0].Address()) - tx := payload.NewCallTxWithSequence(privateAccounts[0].PublicKey(), addr, code, amt, gasLim, fee, sequence+1) - txEnv := txs.Enclose(genesisDoc.ChainID(), tx) - require.NoError(t, txEnv.Sign(privateAccounts[0])) - return txEnv -} - -func makeDefaultNameTx(t *testing.T, client tmClient.RPCClient, name, value string, amt, fee uint64) *txs.Envelope { - sequence := getSequence(t, client, privateAccounts[0].Address()) - tx := payload.NewNameTxWithSequence(privateAccounts[0].PublicKey(), name, value, amt, fee, sequence+1) - txEnv := txs.Enclose(genesisDoc.ChainID(), tx) - require.NoError(t, txEnv.Sign(privateAccounts[0])) - return txEnv -} - -//------------------------------------------------------------------------------- -// rpc call wrappers (fail on err) - -// get an account's sequence number -func getSequence(t *testing.T, client tmClient.RPCClient, addr crypto.Address) uint64 { - acc, err := tmClient.GetAccount(client, addr) - if err != nil { - t.Fatal(err) - } - if acc == nil { - return 0 - } - return acc.Sequence() -} - -// get the account -func getAccount(t *testing.T, client tmClient.RPCClient, addr crypto.Address) acm.Account { - ac, err := tmClient.GetAccount(client, addr) - if err != nil { - t.Fatal(err) - } - return ac -} - -// sign transaction -func signTx(t *testing.T, client tmClient.RPCClient, tx txs.Tx, - privAcc *acm.ConcretePrivateAccount) *txs.Envelope { - signedTx, err := tmClient.SignTx(client, tx, []*acm.ConcretePrivateAccount{privAcc}) - if err != nil { - t.Fatal(err) - } - return signedTx -} - -// broadcast transaction -func broadcastTx(t *testing.T, client tmClient.RPCClient, txEnv *txs.Envelope) *txs.Receipt { - rec, err := tmClient.BroadcastTx(client, txEnv) - require.NoError(t, err) - return rec -} - -// dump all storage for an account. currently unused -func dumpStorage(t *testing.T, addr crypto.Address) *rpc.ResultDumpStorage { - client := clients["HTTP"] - resp, err := tmClient.DumpStorage(client, addr) - if err != nil { - t.Fatal(err) - } - return resp -} - -func getStorage(t *testing.T, client tmClient.RPCClient, addr crypto.Address, key []byte) []byte { - resp, err := tmClient.GetStorage(client, addr, key) - if err != nil { - t.Fatal(err) - } - return resp -} - -func callCode(t *testing.T, client tmClient.RPCClient, fromAddress crypto.Address, code, data, - expected []byte) { - resp, err := tmClient.CallCode(client, fromAddress, code, data) - if err != nil { - t.Fatal(err) - } - ret := resp.Return - // NOTE: we don't flip memory when it comes out of RETURN (?!) - if bytes.Compare(ret, binary.LeftPadWord256(expected).Bytes()) != 0 { - t.Fatalf("Conflicting return value. Got %x, expected %x", ret, expected) - } -} - -func callContract(t *testing.T, client tmClient.RPCClient, fromAddress, toAddress crypto.Address, - data, expected []byte) { - resp, err := tmClient.Call(client, fromAddress, toAddress, data) - if err != nil { - t.Fatal(err) - } - ret := resp.Return - // NOTE: we don't flip memory when it comes out of RETURN (?!) - if bytes.Compare(ret, binary.LeftPadWord256(expected).Bytes()) != 0 { - t.Fatalf("Conflicting return value. Got %x, expected %x", ret, expected) - } -} - -// get the namereg entry -func getNameRegEntry(t *testing.T, client tmClient.RPCClient, name string) *names.Entry { - entry, err := tmClient.GetName(client, name) - if err != nil { - t.Fatal(err) - } - return entry -} - -// Returns a positive int64 hash of text (consumers want int64 instead of uint64) -func hashString(text string) uint64 { - hasher := fnv.New64() - hasher.Write([]byte(text)) - return uint64(hasher.Sum64()) -} - -//-------------------------------------------------------------------------------- -// utility verification function - -// simple contract returns 5 + 6 = 0xb -func simpleContract() ([]byte, []byte, []byte) { - // this is the code we want to run when the contract is called - contractCode := []byte{0x60, 0x5, 0x60, 0x6, 0x1, 0x60, 0x0, 0x52, 0x60, 0x20, - 0x60, 0x0, 0xf3} - // the is the code we need to return the contractCode when the contract is initialized - lenCode := len(contractCode) - // push code to the stack - //code := append([]byte{byte(0x60 + lenCode - 1)}, RightPadWord256(contractCode).Bytes()...) - code := append([]byte{0x7f}, - binary.RightPadWord256(contractCode).Bytes()...) - // store it in memory - code = append(code, []byte{0x60, 0x0, 0x52}...) - // return whats in memory - //code = append(code, []byte{0x60, byte(32 - lenCode), 0x60, byte(lenCode), 0xf3}...) - code = append(code, []byte{0x60, byte(lenCode), 0x60, 0x0, 0xf3}...) - // return init code, contract code, expected return - return code, contractCode, binary.LeftPadBytes([]byte{0xb}, 32) -} - -// simple call contract calls another contract -func simpleCallContract(addr crypto.Address) ([]byte, []byte, []byte) { - gas1, gas2 := byte(0x1), byte(0x1) - value := byte(0x1) - inOff, inSize := byte(0x0), byte(0x0) // no call data - retOff, retSize := byte(0x0), byte(0x20) - // this is the code we want to run (call a contract and return) - contractCode := []byte{0x60, retSize, 0x60, retOff, 0x60, inSize, 0x60, inOff, - 0x60, value, 0x73} - contractCode = append(contractCode, addr.Bytes()...) - contractCode = append(contractCode, []byte{0x61, gas1, gas2, 0xf1, 0x60, 0x20, - 0x60, 0x0, 0xf3}...) - - // the is the code we need to return; the contractCode when the contract is initialized - // it should copy the code from the input into memory - lenCode := len(contractCode) - memOff := byte(0x0) - inOff = byte(0xc) // length of code before codeContract - length := byte(lenCode) - - code := []byte{0x60, length, 0x60, inOff, 0x60, memOff, 0x37} - // return whats in memory - code = append(code, []byte{0x60, byte(lenCode), 0x60, 0x0, 0xf3}...) - code = append(code, contractCode...) - // return init code, contract code, expected return - return code, contractCode, binary.LeftPadBytes([]byte{0xb}, 32) -} diff --git a/rpc/tm/integration/websocket_client_test.go b/rpc/tm/integration/websocket_client_test.go deleted file mode 100644 index 2c996ac1e..000000000 --- a/rpc/tm/integration/websocket_client_test.go +++ /dev/null @@ -1,337 +0,0 @@ -// +build integration - -// Space above here matters -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package integration - -import ( - "encoding/json" - "fmt" - "testing" - "time" - - "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/execution/events" - "github.com/hyperledger/burrow/rpc" - tmClient "github.com/hyperledger/burrow/rpc/tm/client" - "github.com/hyperledger/burrow/txs" - "github.com/hyperledger/burrow/txs/payload" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - tmTypes "github.com/tendermint/tendermint/types" -) - -//-------------------------------------------------------------------------------- -// Test the websocket service - -// make a simple connection to the server -func TestWSConnect(t *testing.T) { - wsc := newWSClient() - stopWSClient(wsc) -} - -// receive a new block message -func TestWSNewBlock(t *testing.T) { - wsc := newWSClient() - eid := tmTypes.EventNewBlock - subId := subscribeAndGetSubscriptionId(t, wsc, eid) - defer func() { - unsubscribe(t, wsc, subId) - stopWSClient(wsc) - }() - waitForEvent(t, wsc, eid, func() {}, - func(eventID string, resultEvent *rpc.ResultEvent) (bool, error) { - fmt.Println("Check: ", resultEvent.Tendermint.EventDataNewBlock().Block) - return true, nil - }) -} - -// receive a few new block messages in a row, with increasing height -func TestWSBlockchainGrowth(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - wsc := newWSClient() - eid := tmTypes.EventNewBlock - subId := subscribeAndGetSubscriptionId(t, wsc, eid) - defer func() { - unsubscribe(t, wsc, subId) - stopWSClient(wsc) - }() - // listen for NewBlock, ensure height increases by 1 - var initBlockN int64 - for i := int64(0); i < 2; i++ { - waitForEvent(t, wsc, eid, func() {}, - func(eventID string, resultEvent *rpc.ResultEvent) (bool, error) { - eventDataNewBlock := resultEvent.Tendermint.EventDataNewBlock() - if eventDataNewBlock == nil { - t.Fatalf("Was expecting EventDataNewBlock but got %v", resultEvent) - } - block := eventDataNewBlock.Block - if i == 0 { - initBlockN = block.Height - } else { - if block.Header.Height != initBlockN+i { - return true, fmt.Errorf("Expected block %d, got block %d", i, - block.Header.Height) - } - } - return true, nil - }) - } -} - -// send a transaction and validate the events from listening for both sender and receiver -func TestWSSend(t *testing.T) { - wsc := newWSClient() - toAddr := privateAccounts[1].Address() - amt := uint64(100) - eidInput := events.EventStringAccountInput(privateAccounts[0].Address()) - eidOutput := events.EventStringAccountOutput(toAddr) - subIdInput := subscribeAndGetSubscriptionId(t, wsc, eidInput) - subIdOutput := subscribeAndGetSubscriptionId(t, wsc, eidOutput) - defer func() { - unsubscribe(t, wsc, subIdInput) - unsubscribe(t, wsc, subIdOutput) - stopWSClient(wsc) - }() - - tx := makeDefaultSendTxSigned(t, jsonRpcClient, toAddr, amt) - broadcastTx(t, jsonRpcClient, tx) - - // Set of response IDs we expect - rids := map[string]struct{}{tmClient.EventResponseID(eidInput): {}, tmClient.EventResponseID(eidOutput): {}} - - r := <-wsc.ResponsesCh - result, err := readResponse(r) - assert.NoError(t, err) - assert.NoError(t, unmarshalValidateSend(amt, toAddr, result)) - delete(rids, r.ID) - - r = <-wsc.ResponsesCh - result, err = readResponse(r) - assert.NoError(t, err) - assert.NoError(t, unmarshalValidateSend(amt, toAddr, result)) - delete(rids, r.ID) - - // Note currently we cannot guarantee order with pubsub event system - assert.Empty(t, rids, "Should receive input and output event") -} - -// ensure events are only fired once for a given transaction -func TestWSDoubleFire(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - wsc := newWSClient() - eid := events.EventStringAccountInput(privateAccounts[0].Address()) - subId := subscribeAndGetSubscriptionId(t, wsc, eid) - defer func() { - unsubscribe(t, wsc, subId) - stopWSClient(wsc) - }() - amt := uint64(100) - toAddr := privateAccounts[1].Address() - // broadcast the transaction, wait to hear about it - waitForEvent(t, wsc, eid, func() { - tx := makeDefaultSendTxSigned(t, jsonRpcClient, toAddr, amt) - broadcastTx(t, jsonRpcClient, tx) - }, func(eventID string, resultEvent *rpc.ResultEvent) (bool, error) { - return true, nil - }) - select { - case <-wsc.ResponsesCh: - t.Fatal("Should time out waiting for second event") - case <-time.After(timeoutSeconds * time.Second): - - } -} - -// create a contract, wait for the event, and send it a msg, validate the return -func TestWSCallWait(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - wsc := newWSClient() - defer stopWSClient(wsc) - // Mini soak test - for i := 0; i < 20; i++ { - amt, gasLim, fee := uint64(10000), uint64(1000), uint64(1000) - code, returnCode, returnVal := simpleContract() - var contractAddr crypto.Address - eid1 := events.EventStringAccountInput(privateAccounts[0].Address()) - subId1 := subscribeAndGetSubscriptionId(t, wsc, eid1) - // wait for the contract to be created - waitForEvent(t, wsc, eid1, func() { - tx := makeDefaultCallTx(t, jsonRpcClient, nil, code, amt, gasLim, fee) - receipt := broadcastTx(t, jsonRpcClient, tx) - contractAddr = receipt.ContractAddress - }, unmarshalValidateTx(amt, returnCode)) - - unsubscribe(t, wsc, subId1) - - // susbscribe to the new contract - amt = uint64(10001) - eid2 := events.EventStringAccountOutput(contractAddr) - subId2 := subscribeAndGetSubscriptionId(t, wsc, eid2) - // get the return value from a call - data := []byte{0x1} - waitForEvent(t, wsc, eid2, func() { - tx := makeDefaultCallTx(t, jsonRpcClient, &contractAddr, data, amt, gasLim, fee) - receipt := broadcastTx(t, jsonRpcClient, tx) - contractAddr = receipt.ContractAddress - }, unmarshalValidateTx(amt, returnVal)) - unsubscribe(t, wsc, subId2) - } -} - -// create a contract and send it a msg without waiting. wait for contract event -// and validate return -func TestWSCallNoWait(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - wsc := newWSClient() - defer stopWSClient(wsc) - amt, gasLim, fee := uint64(10000), uint64(1000), uint64(1000) - code, _, returnVal := simpleContract() - - sequence := getSequence(t, jsonRpcClient, privateAccounts[0].Address()) - txEnv := makeDefaultCallTx(t, jsonRpcClient, nil, code, amt, gasLim, fee) - receipt := broadcastTx(t, jsonRpcClient, txEnv) - contractAddr := receipt.ContractAddress - - // susbscribe to the new contract - amt = uint64(10001) - eid := events.EventStringAccountOutput(contractAddr) - subId := subscribeAndGetSubscriptionId(t, wsc, eid) - defer unsubscribe(t, wsc, subId) - - data := []byte{0x1} - waitForEvent(t, wsc, eid, func() { - tx := payload.NewCallTxWithSequence(privateAccounts[0].PublicKey(), &contractAddr, data, amt, gasLim, fee, - sequence+3) - txEnv = txs.Enclose(genesisDoc.ChainID(), tx) - require.NoError(t, txEnv.Sign(privateAccounts[0])) - broadcastTx(t, jsonRpcClient, txEnv) - }, unmarshalValidateTx(amt, returnVal)) -} - -// create two contracts, one of which calls the other -func TestWSCallCall(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - wsc := newWSClient() - defer stopWSClient(wsc) - amt, gasLim, fee := uint64(10000), uint64(1000), uint64(1000) - code, _, returnVal := simpleContract() - TxHash := new([]byte) - - // deploy the two contracts - txEnv := makeDefaultCallTx(t, jsonRpcClient, nil, code, amt, gasLim, fee) - receipt := txEnv.Tx.GenerateReceipt() - contractAddr1 := receipt.ContractAddress - // subscribe to the new contracts - eid := events.EventStringAccountCall(contractAddr1) - subId := subscribeAndGetSubscriptionId(t, wsc, eid) - defer unsubscribe(t, wsc, subId) - - _, err := broadcastTxAndWait(t, jsonRpcClient, txEnv) - require.NoError(t, err) - - // call contract2, which should call contract1, and wait for ev1 - code, _, _ = simpleCallContract(contractAddr1) - txEnv = makeDefaultCallTx(t, jsonRpcClient, nil, code, amt, gasLim, fee) - receipt2, err := broadcastTxAndWait(t, jsonRpcClient, txEnv) - require.NoError(t, err) - contractAddr2 := receipt2.ContractAddress - - // let the contract get created first - waitForEvent(t, wsc, eid, - // Runner - func() { - }, - // Event Checker - func(eventID string, resultEvent *rpc.ResultEvent) (bool, error) { - return true, nil - }) - // call it - waitForEvent(t, wsc, eid, - // Runner - func() { - txEnv := makeDefaultCallTx(t, jsonRpcClient, &contractAddr2, nil, amt, gasLim, fee) - broadcastTx(t, jsonRpcClient, txEnv) - *TxHash = txEnv.Tx.Hash() - }, - // Event checker - unmarshalValidateCall(privateAccounts[0].Address(), returnVal, TxHash)) -} - -func TestSubscribe(t *testing.T) { - wsc := newWSClient() - var subId string - subscribe(t, wsc, tmTypes.EventNewBlock) - -Subscribe: - for { - select { - case <-time.After(timeoutSeconds * time.Second): - t.Fatal("Timed out waiting for subscription result") - - case response := <-wsc.ResponsesCh: - require.Nil(t, response.Error) - res := new(rpc.ResultSubscribe) - require.NoError(t, json.Unmarshal(response.Result, res)) - assert.Equal(t, tmTypes.EventNewBlock, res.EventID) - subId = res.SubscriptionID - break Subscribe - } - } - - blocksSeen := 0 - for { - select { - // wait long enough to check we don't see another new block event even though - // a block will have come - case <-time.After(expectBlockInSeconds * time.Second): - if blocksSeen == 0 { - t.Fatal("Timed out without seeing a NewBlock event") - } - return - - case response := <-wsc.ResponsesCh: - require.Nil(t, response.Error) - - if response.ID == tmClient.EventResponseID(tmTypes.EventNewBlock) { - res := new(rpc.ResultEvent) - json.Unmarshal(response.Result, res) - enb := res.Tendermint.EventDataNewBlock() - if enb != nil { - assert.Equal(t, genesisDoc.ChainID(), enb.Block.ChainID) - if blocksSeen > 1 { - t.Fatal("Continued to see NewBlock event after unsubscribing") - } else { - if blocksSeen == 0 { - unsubscribe(t, wsc, subId) - } - blocksSeen++ - } - } - } - } - } -} diff --git a/rpc/tm/integration/websocket_helpers.go b/rpc/tm/integration/websocket_helpers.go deleted file mode 100644 index 6e19d8fee..000000000 --- a/rpc/tm/integration/websocket_helpers.go +++ /dev/null @@ -1,323 +0,0 @@ -// +build integration - -// Space above here matters -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package integration - -import ( - "bytes" - "encoding/json" - "fmt" - "runtime/debug" - "testing" - "time" - - "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/execution/events" - "github.com/hyperledger/burrow/rpc" - rpcClient "github.com/hyperledger/burrow/rpc/lib/client" - rpcTypes "github.com/hyperledger/burrow/rpc/lib/types" - tmClient "github.com/hyperledger/burrow/rpc/tm/client" - "github.com/hyperledger/burrow/txs" - "github.com/hyperledger/burrow/txs/payload" - "github.com/stretchr/testify/require" - tmTypes "github.com/tendermint/tendermint/types" -) - -const ( - timeoutSeconds = 8 - expectBlockInSeconds = 2 -) - -//-------------------------------------------------------------------------------- -// Utilities for testing the websocket service -type blockPredicate func(block *tmTypes.Block) bool -type resultEventChecker func(eventID string, resultEvent *rpc.ResultEvent) (bool, error) - -// create a new connection -func newWSClient() *rpcClient.WSClient { - wsc := rpcClient.NewWSClient(websocketAddr, websocketEndpoint) - if err := wsc.Start(); err != nil { - panic(err) - } - return wsc -} - -func stopWSClient(wsc *rpcClient.WSClient) { - wsc.Stop() -} - -// subscribe to an event -func subscribe(t *testing.T, wsc *rpcClient.WSClient, eventId string) { - if err := tmClient.Subscribe(wsc, eventId); err != nil { - t.Fatal(err) - } -} - -func subscribeAndGetSubscriptionId(t *testing.T, wsc *rpcClient.WSClient, eventId string) string { - if err := tmClient.Subscribe(wsc, eventId); err != nil { - t.Fatal(err) - } - - timeout := time.NewTimer(timeoutSeconds * time.Second) - for { - select { - case <-timeout.C: - t.Fatal("Timeout waiting for subscription result") - case response := <-wsc.ResponsesCh: - require.Nil(t, response.Error, "Got error response from websocket channel: %v", response.Error) - if response.ID == tmClient.SubscribeRequestID { - res := new(rpc.ResultSubscribe) - err := json.Unmarshal(response.Result, res) - if err == nil { - return res.SubscriptionID - } - } - } - } -} - -// unsubscribe from an event -func unsubscribe(t *testing.T, wsc *rpcClient.WSClient, subscriptionId string) { - if err := tmClient.Unsubscribe(wsc, subscriptionId); err != nil { - t.Fatal(err) - } -} - -// broadcast transaction and wait for new block -func broadcastTxAndWait(t *testing.T, client tmClient.RPCClient, txEnv *txs.Envelope) (*txs.Receipt, error) { - wsc := newWSClient() - defer stopWSClient(wsc) - inputs := txEnv.Tx.GetInputs() - if len(inputs) == 0 { - t.Fatalf("cannot broadcastAndWait fot Tx with no inputs") - } - address := inputs[0].Address - - var rec *txs.Receipt - var err error - - err = subscribeAndWaitForNext(t, wsc, events.EventStringAccountInput(address), - func() { - rec, err = tmClient.BroadcastTx(client, txEnv) - }, func(eventID string, resultEvent *rpc.ResultEvent) (bool, error) { - return true, nil - }) - if err != nil { - return nil, err - } - return rec, err -} - -func nextBlockPredicateFn() blockPredicate { - initialHeight := int64(-1) - return func(block *tmTypes.Block) bool { - if initialHeight <= 0 { - initialHeight = block.Height - return false - } else { - // TODO: [Silas] remove the + 1 here. It is a workaround for the fact - // that tendermint fires the NewBlock event before it has finalised its - // state updates, so we have to wait for the block after the block we - // want in order for the Tx to be genuinely final. - // This should be addressed by: https://github.com/tendermint/tendermint/pull/265 - return block.Height > initialHeight+1 - } - } -} - -func waitNBlocks(t *testing.T, wsc *rpcClient.WSClient, n int) { - i := 0 - require.NoError(t, runThenWaitForBlock(t, wsc, - func(block *tmTypes.Block) bool { - i++ - return i >= n - }, - func() {})) -} - -func runThenWaitForBlock(t *testing.T, wsc *rpcClient.WSClient, predicate blockPredicate, runner func()) error { - eventDataChecker := func(event string, eventData *rpc.ResultEvent) (bool, error) { - eventDataNewBlock := eventData.Tendermint.EventDataNewBlock() - if eventDataNewBlock == nil { - return false, fmt.Errorf("could not convert %#v to EventDataNewBlock", eventData) - } - return predicate(eventDataNewBlock.Block), nil - } - return subscribeAndWaitForNext(t, wsc, tmTypes.EventNewBlock, runner, eventDataChecker) -} - -func subscribeAndWaitForNext(t *testing.T, wsc *rpcClient.WSClient, event string, runner func(), - checker resultEventChecker) error { - - subId := subscribeAndGetSubscriptionId(t, wsc, event) - defer unsubscribe(t, wsc, subId) - return waitForEvent(t, wsc, event, runner, checker) -} - -// waitForEvent executes runner that is expected to trigger events. It then -// waits for any events on the supplies WSClient and checks the eventData with -// the eventDataChecker which is a function that is passed the event name -// and the Data and returns the pair of stopWaiting, err. Where if -// stopWaiting is true waitForEvent will return or if stopWaiting is false -// waitForEvent will keep listening for new events. If an error is returned -// waitForEvent will fail the test. -func waitForEvent(t *testing.T, wsc *rpcClient.WSClient, eventID string, runner func(), - checker resultEventChecker) error { - - // go routine to wait for websocket msg - eventsCh := make(chan *rpc.ResultEvent) - shutdownEventsCh := make(chan bool, 1) - errCh := make(chan error) - - // do stuff (transactions) - runner() - - // Read message - go func() { - for { - select { - case <-shutdownEventsCh: - return - case r := <-wsc.ResponsesCh: - if r.Error != nil { - errCh <- r.Error - return - } - if r.ID == tmClient.EventResponseID(eventID) { - resultEvent, err := readResponse(r) - if err != nil { - errCh <- err - } else { - eventsCh <- resultEvent - } - } - case <-wsc.Quit(): - return - } - } - }() - - // Don't block up WSClient - defer func() { shutdownEventsCh <- true }() - - for { - select { - // wait for an event or timeout - case <-time.After(timeoutSeconds * time.Second): - t.Fatalf("waitForEvent timed out: %s", debug.Stack()) - case eventData := <-eventsCh: - // run the check - stopWaiting, err := checker(eventID, eventData) - if err != nil { - return err - } - if stopWaiting { - return nil - } - case err := <-errCh: - return err - } - } - return nil -} - -func readResponse(r rpcTypes.RPCResponse) (*rpc.ResultEvent, error) { - if r.Error != nil { - return nil, r.Error - } - resultEvent := new(rpc.ResultEvent) - err := json.Unmarshal(r.Result, resultEvent) - if err != nil { - return nil, err - } - return resultEvent, nil -} - -//-------------------------------------------------------------------------------- - -func unmarshalValidateSend(amt uint64, toAddr crypto.Address, resultEvent *rpc.ResultEvent) error { - data := resultEvent.Execution.GetTx() - if data == nil { - return fmt.Errorf("event data %v is not EventDataTx", resultEvent) - } - if data.Exception == nil { - return data.Exception.AsError() - } - tx := data.Tx.Payload.(*payload.SendTx) - if tx.Inputs[0].Address != privateAccounts[0].Address() { - return fmt.Errorf("senders do not match up! Got %s, expected %s", tx.Inputs[0].Address, - privateAccounts[0].Address()) - } - if tx.Inputs[0].Amount != amt { - return fmt.Errorf("amt does not match up! Got %d, expected %d", tx.Inputs[0].Amount, amt) - } - if tx.Outputs[0].Address != toAddr { - return fmt.Errorf("receivers do not match up! Got %s, expected %s", tx.Outputs[0].Address, - privateAccounts[0].Address()) - } - return nil -} - -func unmarshalValidateTx(amt uint64, returnCode []byte) resultEventChecker { - return func(eventID string, resultEvent *rpc.ResultEvent) (bool, error) { - data := resultEvent.Execution.GetTx() - if data == nil { - return true, fmt.Errorf("event data %v is not EventDataTx", *resultEvent) - } - if data.Exception != nil { - return true, data.Exception.AsError() - } - tx := data.Tx.Payload.(*payload.CallTx) - if tx.Input.Address != privateAccounts[0].Address() { - return true, fmt.Errorf("senders do not match up! Got %s, expected %s", - tx.Input.Address, privateAccounts[0].Address()) - } - if tx.Input.Amount != amt { - return true, fmt.Errorf("amount does not match up! Got %d, expected %d", - tx.Input.Amount, amt) - } - ret := data.Return - if !bytes.Equal(ret, returnCode) { - return true, fmt.Errorf("tx did not return correctly. Got %x, expected %x", ret, returnCode) - } - return true, nil - } -} - -func unmarshalValidateCall(origin crypto.Address, returnCode []byte, txid *[]byte) resultEventChecker { - return func(eventID string, resultEvent *rpc.ResultEvent) (bool, error) { - data := resultEvent.Execution.Call - if data == nil { - return true, fmt.Errorf("event data %v is not EventDataTx", *resultEvent) - } - if data.Exception != nil { - return true, data.Exception.AsError() - } - if data.Origin != origin { - return true, fmt.Errorf("origin does not match up! Got %s, expected %s", data.Origin, origin) - } - ret := data.Return - if !bytes.Equal(ret, returnCode) { - return true, fmt.Errorf("call did not return correctly. Got %x, expected %x", ret, returnCode) - } - if !bytes.Equal(resultEvent.Execution.Header.TxHash, *txid) { - return true, fmt.Errorf("TxIDs do not match up! Got %x, expected %x", - resultEvent.Execution.Header.TxHash, *txid) - } - return true, nil - } -} diff --git a/rpc/tm/methods.go b/rpc/tm/methods.go index 017cf29c9..e28e7d862 100644 --- a/rpc/tm/methods.go +++ b/rpc/tm/methods.go @@ -1,27 +1,16 @@ package tm import ( - "context" "fmt" - "time" - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/event" - "github.com/hyperledger/burrow/execution/names" + "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/rpc" "github.com/hyperledger/burrow/rpc/lib/server" - "github.com/hyperledger/burrow/rpc/lib/types" - "github.com/hyperledger/burrow/txs" ) // Method names const ( - BroadcastTx = "broadcast_tx" - Subscribe = "subscribe" - Unsubscribe = "unsubscribe" - // Status Status = "status" NetInfo = "net_info" @@ -60,87 +49,9 @@ const ( LastBlockInfo = "last_block_info" ) -const SubscriptionTimeout = 5 * time.Second - func GetRoutes(service *rpc.Service, logger *logging.Logger) map[string]*server.RPCFunc { logger = logger.WithScope("GetRoutes") return map[string]*server.RPCFunc{ - // Transact - BroadcastTx: server.NewRPCFunc(func(txEnv *txs.Envelope) (*rpc.ResultBroadcastTx, error) { - receipt, err := service.Transactor().BroadcastTx(txEnv) - if err != nil { - return nil, err - } - return &rpc.ResultBroadcastTx{ - Receipt: *receipt, - }, nil - }, "tx"), - - SignTx: server.NewRPCFunc(func(txEnv *txs.Envelope, concretePrivateAccounts []*acm.ConcretePrivateAccount) (*rpc.ResultSignTx, error) { - txEnv, err := service.Transactor().SignTx(txEnv, acm.SigningAccounts(concretePrivateAccounts)) - return &rpc.ResultSignTx{Tx: txEnv}, err - - }, "tx,privAccounts"), - - // Simulated call - Call: server.NewRPCFunc(func(fromAddress, toAddress crypto.Address, data []byte) (*rpc.ResultCall, error) { - call, err := service.Transactor().Call(service.State(), fromAddress, toAddress, data) - if err != nil { - return nil, err - } - return &rpc.ResultCall{Call: *call}, nil - }, "fromAddress,toAddress,data"), - - CallCode: server.NewRPCFunc(func(fromAddress crypto.Address, code, data []byte) (*rpc.ResultCall, error) { - call, err := service.Transactor().CallCode(service.State(), fromAddress, code, data) - if err != nil { - return nil, err - } - return &rpc.ResultCall{Call: *call}, nil - }, "fromAddress,code,data"), - - // Events - Subscribe: server.NewWSRPCFunc(func(wsCtx types.WSRPCContext, eventID string) (*rpc.ResultSubscribe, error) { - subscriptionID, err := event.GenerateSubscriptionID() - if err != nil { - return nil, err - } - - ctx, cancel := context.WithTimeout(context.Background(), SubscriptionTimeout) - defer cancel() - - err = service.Subscribe(ctx, subscriptionID, eventID, func(resultEvent *rpc.ResultEvent) (stop bool) { - keepAlive := wsCtx.TryWriteRPCResponse(types.NewRPCSuccessResponse( - EventResponseID(wsCtx.Request.ID, eventID), resultEvent)) - if !keepAlive { - logger.InfoMsg("dropping subscription because could not write to websocket", - "subscription_id", subscriptionID, - "event_id", eventID) - } - return !keepAlive - }) - if err != nil { - return nil, err - } - return &rpc.ResultSubscribe{ - EventID: eventID, - SubscriptionID: subscriptionID, - }, nil - }, "eventID"), - - Unsubscribe: server.NewWSRPCFunc(func(wsCtx types.WSRPCContext, subscriptionID string) (*rpc.ResultUnsubscribe, error) { - ctx, cancel := context.WithTimeout(context.Background(), SubscriptionTimeout) - defer cancel() - // Since our model uses a random subscription ID per request we just drop all matching requests - err := service.Unsubscribe(ctx, subscriptionID) - if err != nil { - return nil, err - } - return &rpc.ResultUnsubscribe{ - SubscriptionID: subscriptionID, - }, nil - }, "subscriptionID"), - // Status Status: server.NewRPCFunc(service.Status, ""), NetInfo: server.NewRPCFunc(service.NetInfo, ""), @@ -169,12 +80,8 @@ func GetRoutes(service *rpc.Service, logger *logging.Logger) map[string]*server. DumpConsensusState: server.NewRPCFunc(service.DumpConsensusState, ""), // Names - GetName: server.NewRPCFunc(service.GetName, "name"), - ListNames: server.NewRPCFunc(func() (*rpc.ResultListNames, error) { - return service.ListNames(func(*names.Entry) bool { - return true - }) - }, ""), + GetName: server.NewRPCFunc(service.GetName, "name"), + ListNames: server.NewRPCFunc(service.ListNames, ""), // Private account GeneratePrivateAccount: server.NewRPCFunc(service.GeneratePrivateAccount, ""), diff --git a/rpc/tm/server.go b/rpc/tm/tm_server.go similarity index 75% rename from rpc/tm/server.go rename to rpc/tm/tm_server.go index 2baf381b6..2944606ec 100644 --- a/rpc/tm/server.go +++ b/rpc/tm/tm_server.go @@ -17,26 +17,22 @@ package tm import ( "net/http" - "github.com/hyperledger/burrow/consensus/tendermint" - "github.com/hyperledger/burrow/event" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" "github.com/hyperledger/burrow/rpc" "github.com/hyperledger/burrow/rpc/lib/server" ) -func StartServer(service *rpc.Service, pattern, listenAddress string, emitter event.Emitter, - logger *logging.Logger) (*http.Server, error) { - +func StartServer(service *rpc.Service, pattern, listenAddress string, logger *logging.Logger) (*http.Server, error) { logger = logger.With(structure.ComponentKey, "RPC_TM") routes := GetRoutes(service, logger) mux := http.NewServeMux() - wm := server.NewWebsocketManager(routes, logger, server.EventSubscriber(tendermint.SubscribableAsEventBus(emitter))) + wm := server.NewWebsocketManager(routes, logger) mux.HandleFunc(pattern, wm.WebsocketHandler) server.RegisterRPCFuncs(mux, routes, logger) - server, err := server.StartHTTPServer(listenAddress, mux, logger) + srv, err := server.StartHTTPServer(listenAddress, mux, logger) if err != nil { return nil, err } - return server, nil + return srv, nil } diff --git a/rpc/tm/client/client.go b/rpc/tm/tmclient/client.go similarity index 84% rename from rpc/tm/client/client.go rename to rpc/tm/tmclient/client.go index 1b03a76e3..f0fa4d43d 100644 --- a/rpc/tm/client/client.go +++ b/rpc/tm/tmclient/client.go @@ -12,13 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -package client +package tmclient import ( "errors" "fmt" - acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/execution/names" "github.com/hyperledger/burrow/rpc" @@ -30,15 +30,6 @@ type RPCClient interface { Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) } -func BroadcastTx(client RPCClient, txEnv *txs.Envelope) (*txs.Receipt, error) { - res := new(txs.Receipt) - _, err := client.Call(tm.BroadcastTx, pmap("tx", txEnv), res) - if err != nil { - return nil, err - } - return res, nil -} - func Status(client RPCClient) (*rpc.ResultStatus, error) { res := new(rpc.ResultStatus) _, err := client.Call(tm.Status, pmap(), res) @@ -106,25 +97,6 @@ func GetStorage(client RPCClient, address crypto.Address, key []byte) ([]byte, e return res.Value, nil } -func CallCode(client RPCClient, fromAddress crypto.Address, code, data []byte) (*rpc.ResultCall, error) { - res := new(rpc.ResultCall) - _, err := client.Call(tm.CallCode, pmap("fromAddress", fromAddress, "code", code, "data", data), res) - if err != nil { - return nil, err - } - return res, nil -} - -func Call(client RPCClient, fromAddress, toAddress crypto.Address, data []byte) (*rpc.ResultCall, error) { - res := new(rpc.ResultCall) - _, err := client.Call(tm.Call, pmap("fromAddress", fromAddress, "toAddress", toAddress, - "data", data), res) - if err != nil { - return nil, err - } - return res, nil -} - func GetName(client RPCClient, name string) (*names.Entry, error) { res := new(rpc.ResultGetName) _, err := client.Call(tm.GetName, pmap("name", name), res) diff --git a/rpc/tm/client/client_test.go b/rpc/tm/tmclient/client_test.go similarity index 97% rename from rpc/tm/client/client_test.go rename to rpc/tm/tmclient/client_test.go index b8c322d59..3adeec8d3 100644 --- a/rpc/tm/client/client_test.go +++ b/rpc/tm/tmclient/client_test.go @@ -1,4 +1,4 @@ -package client +package tmclient import ( "testing" diff --git a/rpc/v0/client.go b/rpc/v0/client.go deleted file mode 100644 index f663a7993..000000000 --- a/rpc/v0/client.go +++ /dev/null @@ -1,127 +0,0 @@ -package v0 - -import ( - "bytes" - "encoding/json" - "io/ioutil" - "net/http" - "time" - - "github.com/hyperledger/burrow/execution" - "github.com/hyperledger/burrow/execution/events" - "github.com/hyperledger/burrow/rpc" - "github.com/hyperledger/burrow/txs" -) - -type V0Client struct { - url string - codec rpc.Codec - client *http.Client -} - -type RPCResponse struct { - Result json.RawMessage `json:"result"` - Error *rpc.RPCError `json:"error"` - Id string `json:"id"` - JSONRPC string `json:"jsonrpc"` -} - -func NewV0Client(url string) *V0Client { - return &V0Client{ - url: url, - codec: NewTCodec(), - client: &http.Client{ - Timeout: 1000 * time.Second, - }, - } -} - -func (vc *V0Client) Transact(param TransactParam) (*txs.Receipt, error) { - receipt := new(txs.Receipt) - err := vc.CallMethod(TRANSACT, param, receipt) - if err != nil { - return nil, err - } - return receipt, nil -} - -func (vc *V0Client) TransactAndHold(param TransactParam) (*events.EventDataCall, error) { - eventDataCall := new(events.EventDataCall) - err := vc.CallMethod(TRANSACT_AND_HOLD, param, eventDataCall) - if err != nil { - return nil, err - } - return eventDataCall, nil -} - -func (vc *V0Client) Send(param SendParam) (*txs.Receipt, error) { - receipt := new(txs.Receipt) - err := vc.CallMethod(SEND, param, receipt) - if err != nil { - return nil, err - } - return receipt, nil -} - -func (vc *V0Client) SendAndHold(param SendParam) (*txs.Receipt, error) { - receipt := new(txs.Receipt) - err := vc.CallMethod(SEND_AND_HOLD, param, receipt) - if err != nil { - return nil, err - } - return receipt, nil -} - -func (vc *V0Client) Call(param CallParam) (*execution.Call, error) { - call := new(execution.Call) - err := vc.CallMethod(CALL, param, call) - if err != nil { - return nil, err - } - return call, nil -} - -func (vc *V0Client) CallCode(param CallCodeParam) (*execution.Call, error) { - call := new(execution.Call) - err := vc.CallMethod(CALL_CODE, param, call) - if err != nil { - return nil, err - } - return call, nil -} - -func (vc *V0Client) CallMethod(method string, param interface{}, result interface{}) error { - // Marhsal into JSONRPC request object - bs, err := vc.codec.EncodeBytes(param) - if err != nil { - return err - } - request := rpc.NewRPCRequest("test", method, bs) - bs, err = json.Marshal(request) - if err != nil { - return err - } - // Post to JSONService - resp, err := vc.client.Post(vc.url, "application/json", bytes.NewBuffer(bs)) - if err != nil { - return err - } - // Marshal into JSONRPC response object - bs, err = ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - rpcResponse := new(RPCResponse) - err = json.Unmarshal(bs, rpcResponse) - if err != nil { - return err - } - if rpcResponse.Error != nil { - return rpcResponse.Error - } - vc.codec.DecodeBytes(result, rpcResponse.Result) - if err != nil { - return err - } - return nil -} diff --git a/rpc/v0/codec.go b/rpc/v0/codec.go deleted file mode 100644 index dc29f3e2f..000000000 --- a/rpc/v0/codec.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package v0 - -import ( - "io" - "io/ioutil" - - "encoding/json" - - "github.com/hyperledger/burrow/rpc" -) - -// Codec that uses tendermints 'binary' package for JSON. -type TCodec struct { -} - -// Get a new codec. -func NewTCodec() rpc.Codec { - return &TCodec{} -} - -// Encode to an io.Writer. -func (codec *TCodec) Encode(v interface{}, w io.Writer) error { - bs, err := codec.EncodeBytes(v) - if err != nil { - return err - } - _, err = w.Write(bs) - return err -} - -// Encode to a byte array. -func (codec *TCodec) EncodeBytes(v interface{}) ([]byte, error) { - return json.Marshal(v) -} - -// Decode from an io.Reader. -func (codec *TCodec) Decode(v interface{}, r io.Reader) error { - bs, err := ioutil.ReadAll(r) - if err != nil { - return err - } - return codec.DecodeBytes(v, bs) -} - -// Decode from a byte array. -func (codec *TCodec) DecodeBytes(v interface{}, bs []byte) error { - return json.Unmarshal(bs, v) -} diff --git a/rpc/v0/codec_test.go b/rpc/v0/codec_test.go deleted file mode 100644 index 500afb1e5..000000000 --- a/rpc/v0/codec_test.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package v0 - -import ( - "testing" - - "github.com/hyperledger/burrow/crypto" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestKeysEncoding(t *testing.T) { - codec := NewTCodec() - privateKey := crypto.PrivateKeyFromSecret("foo", crypto.CurveTypeEd25519) - type keyPair struct { - PrivateKey crypto.PrivateKey - PublicKey crypto.PublicKey - } - - kp := keyPair{ - PrivateKey: privateKey, - PublicKey: privateKey.GetPublicKey(), - } - - bs, err := codec.EncodeBytes(kp) - require.NoError(t, err) - - kpOut := keyPair{} - codec.DecodeBytes(&kpOut, bs) - - assert.Equal(t, kp, kpOut) -} diff --git a/rpc/v0/integration/v0_test.go b/rpc/v0/integration/v0_test.go deleted file mode 100644 index 563512eb7..000000000 --- a/rpc/v0/integration/v0_test.go +++ /dev/null @@ -1,178 +0,0 @@ -// +build integration - -// Space above here matters -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package integration - -import ( - "sync" - "testing" - - "github.com/hyperledger/burrow/binary" - "github.com/hyperledger/burrow/execution/evm/abi" - "github.com/hyperledger/burrow/rpc/test" - "github.com/hyperledger/burrow/rpc/v0" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestTransactCallNoCode(t *testing.T) { - cli := v0.NewV0Client("http://localhost:1337/rpc") - - // Flip flops between sending private key and input address to test private key and address based signing - toAddress := privateAccounts[2].Address() - - numCreates := 1000 - countCh := test.CommittedTxCount(t, kern.Emitter) - for i := 0; i < numCreates; i++ { - receipt, err := cli.Transact(v0.TransactParam{ - InputAccount: inputAccount(i), - Address: toAddress.Bytes(), - Data: []byte{}, - Fee: 2, - GasLimit: 10000 + uint64(i), - }) - require.NoError(t, err) - assert.False(t, receipt.CreatesContract) - assert.Equal(t, toAddress, receipt.ContractAddress) - } - require.Equal(t, numCreates, <-countCh) -} - -func TestTransactCreate(t *testing.T) { - numGoroutines := 100 - numCreates := 50 - wg := new(sync.WaitGroup) - wg.Add(numGoroutines) - cli := v0.NewV0Client("http://localhost:1337/rpc") - // Flip flops between sending private key and input address to test private key and address based signing - countCh := test.CommittedTxCount(t, kern.Emitter) - for i := 0; i < numGoroutines; i++ { - go func() { - for j := 0; j < numCreates; j++ { - create, err := cli.Transact(v0.TransactParam{ - InputAccount: inputAccount(i), - Address: nil, - Data: test.Bytecode_strange_loop, - Fee: 2, - GasLimit: 10000, - }) - if assert.NoError(t, err) { - assert.True(t, create.CreatesContract) - } - } - wg.Done() - }() - } - wg.Wait() - - require.Equal(t, numGoroutines*numCreates, <-countCh) -} - -func BenchmarkTransactCreateContract(b *testing.B) { - cli := v0.NewV0Client("http://localhost:1337/rpc") - - for i := 0; i < b.N; i++ { - create, err := cli.Transact(v0.TransactParam{ - InputAccount: inputAccount(i), - Address: nil, - Data: test.Bytecode_strange_loop, - Fee: 2, - GasLimit: 10000, - }) - require.NoError(b, err) - assert.True(b, create.CreatesContract) - } -} - -func TestTransactAndHold(t *testing.T) { - cli := v0.NewV0Client("http://localhost:1337/rpc") - - numGoroutines := 5 - numRuns := 2 - countCh := test.CommittedTxCount(t, kern.Emitter) - for i := 0; i < numGoroutines; i++ { - for j := 0; j < numRuns; j++ { - create, err := cli.TransactAndHold(v0.TransactParam{ - InputAccount: inputAccount(i), - Address: nil, - Data: test.Bytecode_strange_loop, - Fee: 2, - GasLimit: 10000, - }) - require.NoError(t, err) - assert.Equal(t, uint64(0), create.StackDepth) - functionID := abi.FunctionID("UpsieDownsie()") - call, err := cli.TransactAndHold(v0.TransactParam{ - InputAccount: inputAccount(i), - Address: create.CallData.Callee.Bytes(), - Data: functionID[:], - Fee: 2, - GasLimit: 10000, - }) - require.NoError(t, err) - depth := binary.Uint64FromWord256(binary.LeftPadWord256(call.Return)) - // Would give 23 if taken from wrong frame - assert.Equal(t, 18, int(depth)) - } - } - require.Equal(t, numGoroutines*numRuns*2, <-countCh) -} - -func TestSend(t *testing.T) { - cli := v0.NewV0Client("http://localhost:1337/rpc") - numSends := 1000 - countCh := test.CommittedTxCount(t, kern.Emitter) - for i := 0; i < numSends; i++ { - send, err := cli.Send(v0.SendParam{ - InputAccount: inputAccount(i), - Amount: 2003, - ToAddress: privateAccounts[3].Address().Bytes(), - }) - require.NoError(t, err) - assert.Equal(t, false, send.CreatesContract) - } - require.Equal(t, numSends, <-countCh) -} - -func TestSendAndHold(t *testing.T) { - cli := v0.NewV0Client("http://localhost:1337/rpc") - - for i := 0; i < 2; i++ { - send, err := cli.SendAndHold(v0.SendParam{ - InputAccount: inputAccount(i), - Amount: 2003, - ToAddress: privateAccounts[3].Address().Bytes(), - }) - require.NoError(t, err) - assert.Equal(t, false, send.CreatesContract) - } -} - -// Helpers - -var inputPrivateKey = privateAccounts[0].PrivateKey().RawBytes() -var inputAddress = privateAccounts[0].Address().Bytes() - -func inputAccount(i int) v0.InputAccount { - ia := v0.InputAccount{} - if i%2 == 0 { - ia.PrivateKey = inputPrivateKey - } else { - ia.Address = inputAddress - } - return ia -} diff --git a/rpc/v0/json_service.go b/rpc/v0/json_service.go deleted file mode 100644 index 41595de66..000000000 --- a/rpc/v0/json_service.go +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package v0 - -import ( - "context" - "encoding/json" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/hyperledger/burrow/logging" - "github.com/hyperledger/burrow/rpc" - "github.com/hyperledger/burrow/rpc/v0/server" -) - -// EventSubscribe -type EventSub struct { - SubId string `json:"subId"` -} - -// EventUnsubscribe -type EventUnsub struct { - Result bool `json:"result"` -} - -// EventPoll -type PollResponse struct { - Events []interface{} `json:"events"` -} - -// Server used to handle JSON-RPC 2.0 requests. Implements server.Server -type JsonRpcServer struct { - service server.HttpService - running bool -} - -// Create a new JsonRpcServer -func NewJSONServer(service server.HttpService) *JsonRpcServer { - return &JsonRpcServer{service: service} -} - -// Start adds the rpc path to the router. -func (jrs *JsonRpcServer) Start(config *server.ServerConfig, router *gin.Engine) { - router.POST(config.HTTP.JsonRpcEndpoint, jrs.handleFunc) - jrs.running = true -} - -// Is the server currently running? -func (jrs *JsonRpcServer) Running() bool { - return jrs.running -} - -// Shut the server down. Does nothing. -func (jrs *JsonRpcServer) Shutdown(ctx context.Context) error { - jrs.running = false - return nil -} - -// Handler passes message on directly to the service which expects -// a normal http request and response writer. -func (jrs *JsonRpcServer) handleFunc(c *gin.Context) { - r := c.Request - w := c.Writer - - jrs.service.Process(r, w) -} - -// Used for Burrow. Implements server.HttpService -type JSONService struct { - codec rpc.Codec - service *rpc.Service - eventSubs *rpc.Subscriptions - defaultHandlers map[string]RequestHandlerFunc - logger *logging.Logger -} - -// Create a new JSON-RPC 2.0 service for burrow (tendermint). -func NewJSONService(codec rpc.Codec, service *rpc.Service, logger *logging.Logger) server.HttpService { - - tmhttps := &JSONService{ - codec: codec, - service: service, - eventSubs: rpc.NewSubscriptions(service), - logger: logger.WithScope("NewJSONService"), - } - - dhMap := GetMethods(codec, service, tmhttps.logger) - // Events - dhMap[EVENT_SUBSCRIBE] = tmhttps.EventSubscribe - dhMap[EVENT_UNSUBSCRIBE] = tmhttps.EventUnsubscribe - dhMap[EVENT_POLL] = tmhttps.EventPoll - tmhttps.defaultHandlers = dhMap - return tmhttps -} - -// Process a request. -func (js *JSONService) Process(r *http.Request, w http.ResponseWriter) { - - // Create new request object and unmarshal. - req := &rpc.RPCRequest{} - decoder := json.NewDecoder(r.Body) - errU := decoder.Decode(req) - - // Error when decoding. - if errU != nil { - js.writeError("Failed to parse request: "+errU.Error(), "", - rpc.PARSE_ERROR, w) - return - } - - // Wrong protocol version. - if req.JSONRPC != "2.0" { - js.writeError("Wrong protocol version: "+req.JSONRPC, req.Id, - rpc.INVALID_REQUEST, w) - return - } - - mName := req.Method - - if handler, ok := js.defaultHandlers[mName]; ok { - js.logger.TraceMsg("Request received", - "id", req.Id, - "method", req.Method) - resp, errCode, err := handler(req, w) - if err != nil { - js.writeError(err.Error(), req.Id, errCode, w) - } else { - js.writeResponse(req.Id, resp, w) - } - } else { - js.writeError("Method not found: "+mName, req.Id, rpc.METHOD_NOT_FOUND, w) - } -} - -// Helper for writing error responses. -func (js *JSONService) writeError(msg, id string, code int, w http.ResponseWriter) { - response := rpc.NewRPCErrorResponse(id, code, msg) - err := js.codec.Encode(response, w) - // If there's an error here all bets are off. - if err != nil { - http.Error(w, "Failed to marshal standard error response: "+err.Error(), 500) - return - } - w.WriteHeader(200) -} - -// Helper for writing responses. -func (js *JSONService) writeResponse(id string, result interface{}, w http.ResponseWriter) { - response := rpc.NewRPCResponse(id, result) - err := js.codec.Encode(response, w) - if err != nil { - js.writeError("Internal error: "+err.Error(), id, rpc.INTERNAL_ERROR, w) - return - } - w.WriteHeader(200) -} - -// *************************************** Events ************************************ - -// Subscribe to an -func (js *JSONService) EventSubscribe(request *rpc.RPCRequest, - requester interface{}) (interface{}, int, error) { - param := &EventIdParam{} - err := json.Unmarshal(request.Params, param) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - eventId := param.EventId - subId, errC := js.eventSubs.Add(eventId) - if errC != nil { - return nil, rpc.INTERNAL_ERROR, errC - } - return &EventSub{subId}, 0, nil -} - -// Un-subscribe from an -func (js *JSONService) EventUnsubscribe(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - param := &SubIdParam{} - err := json.Unmarshal(request.Params, param) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - subId := param.SubId - - err = js.service.Unsubscribe(context.Background(), subId) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return &EventUnsub{true}, 0, nil -} - -// Check subscription event cache for new data. -func (js *JSONService) EventPoll(request *rpc.RPCRequest, - requester interface{}) (interface{}, int, error) { - param := &SubIdParam{} - err := json.Unmarshal(request.Params, param) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - subId := param.SubId - - result, errC := js.eventSubs.Poll(subId) - if errC != nil { - return nil, rpc.INTERNAL_ERROR, errC - } - return &PollResponse{result}, 0, nil -} diff --git a/rpc/v0/json_service_data_test.go b/rpc/v0/json_service_data_test.go deleted file mode 100644 index c258c4c2c..000000000 --- a/rpc/v0/json_service_data_test.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package v0 - -import ( - "encoding/json" - "fmt" - "testing" - - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/rpc" - "github.com/hyperledger/burrow/txs" - "github.com/hyperledger/burrow/txs/payload" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var txEnvelopeString = `{"Signatories":[{"Address":"83207817DC3814B96F57EFF925F467E07CAA9138","PublicKey":{"CurveType":"ed25519",` + - `"PublicKey":"34D26579DBB456693E540672CF922F52DDE0D6532E35BF06BE013A7C532F20E0"},` + - `"Signature":"5042F208824AA5AF8E03B2F11FB8CFCDDAE4F889B2F720714627395406E00D7740B2DB5B5F93BD6C13DED9B7C1FD5FB0DB4ECA31E6DA0B81033A72922076E90C"}],` + - `"Tx":{"ChainID":"testChain","Type":"CallTx","Payload":{"Input":{"Address":"83207817DC3814B96F57EFF925F467E07CAA9138","Amount":343,"Sequence":3},` + - `"Address":"AC280D53FD359D9FF11F19D0796D9B89907F3B53","GasLimit":2323,"Fee":12,"Data":"03040505"}}}` - -var testBroadcastCallTxJsonRequest = []byte(` -{ - "id": "57EC1D39-7B3D-4F96-B286-8FC128177AFC4", - "jsonrpc": "2.0", - "method": "burrow.broadcastTx", - "params": ` + txEnvelopeString + ` -}`) - -// strictly test the codec for go-wire encoding of the Json format, -// This should restore compatibility with the format on v0.11.4 -// (which was broken on v0.12) -func fixTestCallTxJsonFormatCodec(t *testing.T) { - codec := NewTCodec() - txEnv := new(txs.Envelope) - // Create new request object and unmarshal. - request := &rpc.RPCRequest{} - assert.NoError(t, json.Unmarshal(testBroadcastCallTxJsonRequest, request), - "Provided JSON test data does not unmarshal to rpc.RPCRequest object.") - assert.NoError(t, codec.DecodeBytes(txEnv, request.Params), - "RPC codec failed to decode params as transaction type.") - _, ok := txEnv.Tx.Payload.(*payload.CallTx) - assert.True(t, ok, "Type byte 0x02 should unmarshal into CallTx.") -} - -func TestGenTxEnvelope(t *testing.T) { - codec := NewTCodec() - privAccFrom := acm.GeneratePrivateAccountFromSecret("foo") - privAccTo := acm.GeneratePrivateAccountFromSecret("bar") - toAddress := privAccTo.Address() - txEnv := txs.Enclose("testChain", payload.NewCallTxWithSequence(privAccFrom.PublicKey(), &toAddress, - []byte{3, 4, 5, 5}, 343, 2323, 12, 3)) - err := txEnv.Sign(privAccFrom) - require.NoError(t, err) - bs, err := codec.EncodeBytes(txEnv) - require.NoError(t, err) - if !assert.Equal(t, txEnvelopeString, string(bs)) { - fmt.Println(string(bs)) - } -} diff --git a/rpc/v0/json_service_test.go b/rpc/v0/json_service_test.go deleted file mode 100644 index 23ec76209..000000000 --- a/rpc/v0/json_service_test.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package v0 - -import ( - "encoding/json" - "fmt" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestPollResponse(t *testing.T) { - pr := PollResponse{} - bs, err := json.Marshal(pr) - require.NoError(t, err) - fmt.Println(string(bs)) -} diff --git a/rpc/v0/methods.go b/rpc/v0/methods.go deleted file mode 100644 index 7b510f23c..000000000 --- a/rpc/v0/methods.go +++ /dev/null @@ -1,455 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package v0 - -import ( - "context" - - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/execution/names" - "github.com/hyperledger/burrow/logging" - "github.com/hyperledger/burrow/rpc" - "github.com/hyperledger/burrow/rpc/filters" - "github.com/hyperledger/burrow/txs" -) - -// TODO use the method name definition file. -const ( - SERVICE_NAME = "burrow" - - GET_ACCOUNTS = SERVICE_NAME + ".getAccounts" // Accounts - GET_ACCOUNT = SERVICE_NAME + ".getAccount" - GET_STORAGE = SERVICE_NAME + ".getStorage" - GET_STORAGE_AT = SERVICE_NAME + ".getStorageAt" - GEN_PRIV_ACCOUNT = SERVICE_NAME + ".genPrivAccount" - GEN_PRIV_ACCOUNT_FROM_KEY = SERVICE_NAME + ".genPrivAccountFromKey" - GET_BLOCKCHAIN_INFO = SERVICE_NAME + ".getBlockchainInfo" // Blockchain - GET_LATEST_BLOCK = SERVICE_NAME + ".getLatestBlock" - GET_BLOCKS = SERVICE_NAME + ".getBlocks" - GET_BLOCK = SERVICE_NAME + ".getBlock" - GET_CONSENSUS_STATE = SERVICE_NAME + ".getConsensusState" // Consensus - GET_VALIDATORS = SERVICE_NAME + ".getValidators" - GET_NETWORK_INFO = SERVICE_NAME + ".getNetworkInfo" // Net - GET_CHAIN_ID = SERVICE_NAME + ".getChainId" - GET_PEERS = SERVICE_NAME + ".getPeers" - CALL = SERVICE_NAME + ".call" // Tx - CALL_CODE = SERVICE_NAME + ".callCode" - BROADCAST_TX = SERVICE_NAME + ".broadcastTx" - GET_UNCONFIRMED_TXS = SERVICE_NAME + ".getUnconfirmedTxs" - SIGN_TX = SERVICE_NAME + ".signTx" - TRANSACT = SERVICE_NAME + ".transact" - TRANSACT_AND_HOLD = SERVICE_NAME + ".transactAndHold" - SEND = SERVICE_NAME + ".send" - SEND_AND_HOLD = SERVICE_NAME + ".sendAndHold" - TRANSACT_NAMEREG = SERVICE_NAME + ".transactNameReg" - EVENT_SUBSCRIBE = SERVICE_NAME + ".eventSubscribe" // Events - EVENT_UNSUBSCRIBE = SERVICE_NAME + ".eventUnsubscribe" - EVENT_POLL = SERVICE_NAME + ".eventPoll" - GET_NAMEREG_ENTRY = SERVICE_NAME + ".getNameRegEntry" // Namereg - GET_NAMEREG_ENTRIES = SERVICE_NAME + ".getNameRegEntries" -) - -// Used to handle requests. interface{} param is a wildcard used for example with socket events. -type RequestHandlerFunc func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) - -// Private. Create a method name -> method handler map. -func GetMethods(codec rpc.Codec, service *rpc.Service, logger *logging.Logger) map[string]RequestHandlerFunc { - accountFilterFactory := filters.NewAccountFilterFactory() - nameRegFilterFactory := filters.NewNameRegFilterFactory() - return map[string]RequestHandlerFunc{ - // Accounts - GET_ACCOUNTS: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - param := &FilterListParam{} - if len(request.Params) > 0 { - err := codec.DecodeBytes(param, request.Params) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - } - filter, err := accountFilterFactory.NewFilter(param.Filters) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - list, err := service.ListAccounts(func(account acm.Account) bool { - return filter.Match(account) - - }) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return list, 0, nil - }, - GET_ACCOUNT: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - param := &AddressParam{} - err := codec.DecodeBytes(param, request.Params) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - address, err := crypto.AddressFromBytes(param.Address) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - account, err := service.GetAccount(address) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return account, 0, nil - }, - GET_STORAGE: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - param := &AddressParam{} - err := codec.DecodeBytes(param, request.Params) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - address, err := crypto.AddressFromBytes(param.Address) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - storage, err := service.DumpStorage(address) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return storage, 0, nil - }, - GET_STORAGE_AT: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - param := &StorageAtParam{} - err := codec.DecodeBytes(param, request.Params) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - address, err := crypto.AddressFromBytes(param.Address) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - storageItem, err := service.GetStorage(address, param.Key) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return storageItem, 0, nil - }, - GEN_PRIV_ACCOUNT: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - pa, err := acm.GeneratePrivateAccount() - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return acm.AsConcretePrivateAccount(pa), 0, nil - }, - GEN_PRIV_ACCOUNT_FROM_KEY: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - param := &PrivateKeyParam{} - err := codec.DecodeBytes(param, request.Params) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - pa, err := acm.GeneratePrivateAccountFromPrivateKeyBytes(param.PrivateKey) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return acm.AsConcretePrivateAccount(pa), 0, nil - }, - // Txs - CALL: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - param := &CallParam{} - err := codec.DecodeBytes(param, request.Params) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - from, err := crypto.AddressFromBytes(param.From) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - address, err := crypto.AddressFromBytes(param.Address) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - call, err := service.Transactor().Call(service.MempoolAccounts(), from, address, param.Data) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return call, 0, nil - }, - CALL_CODE: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - param := &CallCodeParam{} - err := codec.DecodeBytes(param, request.Params) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - from, err := crypto.AddressFromBytes(param.From) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - call, err := service.Transactor().CallCode(service.MempoolAccounts(), from, param.Code, param.Data) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return call, 0, nil - }, - BROADCAST_TX: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - // Accept all transaction types as parameter for broadcast. - txEnv := new(txs.Envelope) - err := codec.DecodeBytes(txEnv, request.Params) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - receipt, err := service.Transactor().BroadcastTx(txEnv) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return receipt, 0, nil - }, - SIGN_TX: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - param := &SignTxParam{} - err := codec.DecodeBytes(param, request.Params) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - txRet, err := service.Transactor().SignTx(txs.Enclose(service.BlockchainInfo().ChainID(), param.Tx), - acm.SigningAccounts(param.PrivateAccounts)) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return txRet, 0, nil - }, - TRANSACT: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - param := &TransactParam{} - err := codec.DecodeBytes(param, request.Params) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - address, err := crypto.MaybeAddressFromBytes(param.Address) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - // Use mempool state so that transact can generate a run of sequence numbers when formulating transactions - inputAccount, err := service.MempoolAccounts().GetSequentialSigningAccount(param.InputAccount.Address, - param.InputAccount.PrivateKey) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - // We ensure zero value transfer for legacy compatibility reason (i.e. we always have) - receipt, err := service.Transactor().Transact(inputAccount, address, param.Data, param.GasLimit, 0, - param.Fee) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return receipt, 0, nil - }, - TRANSACT_AND_HOLD: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - param := &TransactParam{} - err := codec.DecodeBytes(param, request.Params) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - address, err := crypto.MaybeAddressFromBytes(param.Address) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - inputAccount, err := service.MempoolAccounts().GetSequentialSigningAccount(param.InputAccount.Address, - param.InputAccount.PrivateKey) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - // We ensure zero value transfer for legacy compatibility reason (i.e. we always have) - eventDataCall, err := service.Transactor().TransactAndHold(context.Background(), inputAccount, address, - param.Data, param.GasLimit, 0, param.Fee) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return eventDataCall, 0, nil - }, - SEND: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - param := &SendParam{} - err := codec.DecodeBytes(param, request.Params) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - toAddress, err := crypto.AddressFromBytes(param.ToAddress) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - // Run Send against mempool state - inputAccount, err := service.MempoolAccounts().GetSequentialSigningAccount(param.InputAccount.Address, - param.InputAccount.PrivateKey) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - receipt, err := service.Transactor().Send(inputAccount, toAddress, param.Amount) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return receipt, 0, nil - }, - SEND_AND_HOLD: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - param := &SendParam{} - err := codec.DecodeBytes(param, request.Params) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - toAddress, err := crypto.AddressFromBytes(param.ToAddress) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - // Run Send against mempool state - inputAccount, err := service.MempoolAccounts().GetSequentialSigningAccount(param.InputAccount.Address, - param.InputAccount.PrivateKey) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - rec, err := service.Transactor().SendAndHold(context.Background(), inputAccount, toAddress, param.Amount) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return rec, 0, nil - }, - TRANSACT_NAMEREG: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - param := &TransactNameRegParam{} - err := codec.DecodeBytes(param, request.Params) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - inputAccount, err := service.MempoolAccounts().GetSequentialSigningAccount(param.InputAccount.Address, - param.InputAccount.PrivateKey) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - receipt, err := service.Transactor().TransactNameReg(inputAccount, param.Name, param.Data, param.Amount, param.Fee) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return receipt, 0, nil - }, - - // Namereg - GET_NAMEREG_ENTRY: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - param := &NameRegEntryParam{} - err := codec.DecodeBytes(param, request.Params) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - name := param.Name - // TODO is address check? - resultGetName, err := service.GetName(name) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return resultGetName.Entry, 0, nil - }, - GET_NAMEREG_ENTRIES: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - param := &FilterListParam{} - err := codec.DecodeBytes(param, request.Params) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - filter, err := nameRegFilterFactory.NewFilter(param.Filters) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - list, err := service.ListNames(func(entry *names.Entry) bool { - return filter.Match(entry) - }) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return list, 0, nil - }, - // Blockchain - GET_BLOCKCHAIN_INFO: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - resultStatus, err := service.Status() - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return resultStatus, 0, nil - }, - GET_LATEST_BLOCK: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - stat, err := service.Status() - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - resultGetBlock, err := service.GetBlock(stat.LatestBlockHeight) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return resultGetBlock, 0, nil - }, - GET_BLOCKS: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - param := &BlocksParam{} - err := codec.DecodeBytes(param, request.Params) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - blocks, err := service.ListBlocks(param.MinHeight, param.MaxHeight) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return blocks, 0, nil - }, - GET_BLOCK: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - param := &HeightParam{} - err := codec.DecodeBytes(param, request.Params) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - block, err := service.GetBlock(param.Height) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return block, 0, nil - }, - GET_UNCONFIRMED_TXS: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - trans, err := service.ListUnconfirmedTxs(-1) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return trans, 0, nil - }, - // Consensus - GET_CONSENSUS_STATE: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - resultDumpConsensusState, err := service.DumpConsensusState() - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return resultDumpConsensusState, 0, nil - }, - GET_VALIDATORS: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - resultListValidators, err := service.ListValidators() - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return resultListValidators, 0, nil - }, - // Network - GET_NETWORK_INFO: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - resultNetInfo, err := service.NetInfo() - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return resultNetInfo, 0, nil - }, - GET_CHAIN_ID: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - resultChainID, err := service.ChainIdentifiers() - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return resultChainID, 0, nil - }, - GET_PEERS: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - resultPeers, err := service.Peers() - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return resultPeers, 0, nil - }, - } -} diff --git a/rpc/v0/params.go b/rpc/v0/params.go deleted file mode 100644 index b84c131e1..000000000 --- a/rpc/v0/params.go +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package v0 - -import ( - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/binary" - "github.com/hyperledger/burrow/rpc/filters" - "github.com/hyperledger/burrow/txs/payload" -) - -type ( - // Used to send an address. The address should be hex and properly formatted. - AddressParam struct { - Address binary.HexBytes `json:"address"` - } - - // Used to send an address - FilterListParam struct { - Filters []*filters.FilterData `json:"filters"` - } - - PrivateKeyParam struct { - PrivateKey binary.HexBytes `json:"privateKey"` - } - - InputAccount struct { - PrivateKey binary.HexBytes `json:"privateKey"` - Address binary.HexBytes `json:"address"` - } - - // StorageAt - StorageAtParam struct { - Address binary.HexBytes `json:"address"` - Key binary.HexBytes `json:"key"` - } - - // Get a block - HeightParam struct { - Height uint64 `json:"height"` - } - - BlocksParam struct { - MinHeight uint64 `json:"minHeight"` - MaxHeight uint64 `json:"maxHeight"` - } - - // Event Id - EventIdParam struct { - EventId string `json:"eventId"` - } - - // Event Id - SubIdParam struct { - SubId string `json:"subId"` - } - - PeerParam struct { - Address string `json:"address"` - } - - // Used when doing calls - CallParam struct { - Address binary.HexBytes `json:"address"` - From binary.HexBytes `json:"from"` - Data binary.HexBytes `json:"data"` - } - - // Used when doing code calls - CallCodeParam struct { - From binary.HexBytes `json:"from"` - Code binary.HexBytes `json:"code"` - Data binary.HexBytes `json:"data"` - } - - // Used when signing a tx. Uses placeholders just like TxParam - SignTxParam struct { - Tx *payload.CallTx `json:"tx"` - PrivateAccounts []*acm.ConcretePrivateAccount `json:"privateAccounts"` - } - - // Used when sending a transaction to be created and signed on the server - // (using the private key). This only uses the standard key type for now. - TransactParam struct { - InputAccount InputAccount `json:"inputAccount"` - Data binary.HexBytes `json:"data"` - Address binary.HexBytes `json:"address"` - Fee uint64 `json:"fee"` - GasLimit uint64 `json:"gasLimit"` - } - - // Used when sending a 'Send' transaction. - SendParam struct { - InputAccount InputAccount `json:"inputAccount"` - ToAddress binary.HexBytes `json:"toAddress"` - Amount uint64 `json:"amount"` - } - - NameRegEntryParam struct { - Name string `json:"name"` - } - - // Used when sending a namereg transaction to be created and signed on the server - // (using the private key). This only uses the standard key type for now. - TransactNameRegParam struct { - InputAccount InputAccount `json:"inputAccount"` - Name string `json:"name"` - Data string `json:"data"` - Fee uint64 `json:"fee"` - Amount uint64 `json:"amount"` - } -) diff --git a/rpc/v0/server/README.md b/rpc/v0/server/README.md deleted file mode 100644 index 14526e2b6..000000000 --- a/rpc/v0/server/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# Server - -This package contains classes for starting and running HTTP and websocket servers. - -## Server interface - -Servers implements the `Server` interface. A 'ServerConfig' and 'gin.Engine' object is supplied in the 'Start' method, so that they may set themselves up and set up the routes etc. - -``` -type Server interface { - Start(*ServerConfig, *gin.Engine) - Running() bool - ShutDown() -} -``` - -The `Server` interface can be found in `server.go`. - -## ServeProcess - -The `ServeProcess` does the port binding and listening. You may attach any number of servers to the serve-process, and it will automatically call their 'Start' and 'ShutDown' methods when starting up and shutting down. You may also attach start and shutdown listeners to the `ServeProcess`. - -The `ServeProcess` class can be found in `server.go`. - -## WebSocketServer - -The `WebSocketServer` is a template for servers that use websocket connections rather then HTTP. It will - -## Config - -The config assumes that there is a default HTTP and Websocket server for RPC, and some other fields. See the main README.md for details. - -While the system is generic (i.e. it does not care what a `Server` is or does), the configuration file is not. The reason is that the server is written specifically for burrow, and I do not want to manage generic config files (or perhaps even one per server). \ No newline at end of file diff --git a/rpc/v0/server/config.go b/rpc/v0/server/config.go deleted file mode 100644 index 6db3bdbe8..000000000 --- a/rpc/v0/server/config.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package server - -type ( - ServerConfig struct { - Bind Bind `toml:"bind"` - TLS TLS `toml:"TLS"` - CORS CORS `toml:"CORS"` - HTTP HTTP `toml:"HTTP"` - WebSocket WebSocket `toml:"web_socket"` - } - - Bind struct { - Address string `toml:"address"` - Port uint16 `toml:"port"` - } - - TLS struct { - TLS bool `toml:"tls"` - CertPath string `toml:"cert_path"` - KeyPath string `toml:"key_path"` - } - - // Options stores configurations - CORS struct { - Enable bool `toml:"enable"` - AllowOrigins []string `toml:"allow_origins"` - AllowCredentials bool `toml:"allow_credentials"` - AllowMethods []string `toml:"allow_methods"` - AllowHeaders []string `toml:"allow_headers"` - ExposeHeaders []string `toml:"expose_headers"` - MaxAge uint64 `toml:"max_age"` - } - - HTTP struct { - JsonRpcEndpoint string `toml:"json_rpc_endpoint"` - } - - WebSocket struct { - WebSocketEndpoint string `toml:"websocket_endpoint"` - MaxWebSocketSessions uint16 `toml:"max_websocket_sessions"` - ReadBufferSize uint64 `toml:"read_buffer_size"` - WriteBufferSize uint64 `toml:"write_buffer_size"` - } -) - -func DefaultServerConfig() *ServerConfig { - cp := "" - kp := "" - return &ServerConfig{ - Bind: Bind{ - Address: "localhost", - Port: 1337, - }, - TLS: TLS{TLS: false, - CertPath: cp, - KeyPath: kp, - }, - CORS: CORS{}, - HTTP: HTTP{ - JsonRpcEndpoint: "/rpc", - }, - WebSocket: WebSocket{ - WebSocketEndpoint: "/socketrpc", - MaxWebSocketSessions: 50, - ReadBufferSize: 4096, - WriteBufferSize: 4096, - }, - } -} diff --git a/rpc/v0/server/idpool.go b/rpc/v0/server/idpool.go deleted file mode 100644 index 44a72cba4..000000000 --- a/rpc/v0/server/idpool.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package server - -import ( - "container/list" - "fmt" -) - -// Simple id pool. Lets you get and release uints. Will panic -// if trying to get an id and it's empty. -type IdPool struct { - ids *list.List -} - -func NewIdPool(totNum uint) *IdPool { - idPool := &IdPool{} - idPool.init(totNum) - return idPool -} - -// We start from 1, so that 0 is not used as an id. -func (idp *IdPool) init(totNum uint) { - idp.ids = list.New() - for i := uint(1); i <= totNum; i++ { - idp.ids.PushBack(i) - } -} - -// Get an id from the pool. -func (idp *IdPool) GetId() (uint, error) { - if idp.ids.Len() == 0 { - return 0, fmt.Errorf("Out of IDs") - } - val := idp.ids.Front() - idp.ids.Remove(val) - num, _ := val.Value.(uint) - return num, nil -} - -// Release an id back into the pool. -func (idp *IdPool) ReleaseId(id uint) { - idp.ids.PushBack(id) -} diff --git a/rpc/v0/server/server.go b/rpc/v0/server/server.go deleted file mode 100644 index ec4c89c2e..000000000 --- a/rpc/v0/server/server.go +++ /dev/null @@ -1,264 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package server - -import ( - "context" - "crypto/tls" - "fmt" - "net" - "net/http" - "time" - - "github.com/gin-gonic/gin" - "github.com/hyperledger/burrow/logging" - "github.com/tommy351/gin-cors" - "gopkg.in/tylerb/graceful.v1" -) - -var ( - killTime = 100 * time.Millisecond -) - -type HttpService interface { - Process(*http.Request, http.ResponseWriter) -} - -// A server serves a number of different http calls. -type Server interface { - Start(*ServerConfig, *gin.Engine) - Running() bool - Shutdown(ctx context.Context) error -} - -// The ServeProcess wraps all the Servers. Starting it will -// add all the server handlers to the router and start listening -// for incoming requests. There is also startup and shutdown events -// that can be listened to, on top of any events that the servers -// may have (the default websocket server has events for monitoring -// sessions. Startup event listeners should be added before calling -// 'Start()'. Stop event listeners can be added up to the point where -// the server is stopped and the event is fired. -type ServeProcess struct { - config *ServerConfig - servers []Server - stopChan chan struct{} - startListenChans []chan struct{} - stopListenChans []chan struct{} - srv *graceful.Server - logger *logging.Logger -} - -// Initializes all the servers and starts listening for connections. -func (serveProcess *ServeProcess) Start() error { - gin.SetMode(gin.ReleaseMode) - router := gin.New() - config := serveProcess.config - - ch := NewCORSMiddleware(config.CORS) - router.Use(gin.Recovery(), logHandler(serveProcess.logger), contentTypeMW, ch) - - address := config.Bind.Address - port := config.Bind.Port - - if port == 0 { - return fmt.Errorf("0 is not a valid port.") - } - - listenAddress := address + ":" + fmt.Sprintf("%d", port) - srv := &graceful.Server{ - Server: &http.Server{ - Handler: router, - }, - } - - // Start the servers/handlers. - for _, s := range serveProcess.servers { - s.Start(config, router) - } - - var lst net.Listener - l, lErr := net.Listen("tcp", listenAddress) - if lErr != nil { - return lErr - } - - // For secure connections. - if config.TLS.TLS { - addr := srv.Addr - if addr == "" { - addr = ":https" - } - - tConfig := &tls.Config{} - if tConfig.NextProtos == nil { - tConfig.NextProtos = []string{"http/1.1"} - } - - var tErr error - tConfig.Certificates = make([]tls.Certificate, 1) - tConfig.Certificates[0], tErr = tls.LoadX509KeyPair(config.TLS.CertPath, config.TLS.KeyPath) - if tErr != nil { - return tErr - } - - lst = tls.NewListener(l, tConfig) - } else { - lst = l - } - serveProcess.srv = srv - serveProcess.logger.InfoMsg("Server started.", - "address", serveProcess.config.Bind.Address, - "port", serveProcess.config.Bind.Port) - for _, c := range serveProcess.startListenChans { - c <- struct{}{} - } - // Start the serve routine. - go func() { - serveProcess.srv.Serve(lst) - for _, s := range serveProcess.servers { - s.Shutdown(context.Background()) - } - }() - // Listen to the process stop event, it will call 'Stop' - // on the graceful Server. This happens when someone - // calls 'Stop' on the process. - go func() { - <-serveProcess.stopChan - serveProcess.logger.InfoMsg("Close signal sent to server.") - serveProcess.srv.Stop(killTime) - }() - // Listen to the servers stop event. It is triggered when - // the server has been fully shut down. - go func() { - <-serveProcess.srv.StopChan() - serveProcess.logger.InfoMsg("Server stop event fired. Good bye.") - for _, c := range serveProcess.stopListenChans { - c <- struct{}{} - } - }() - return nil -} - -// Stop will release the port, process any remaining requests -// up until the timeout duration is passed, at which point it -// will abort them and shut down. -func (serveProcess *ServeProcess) Shutdown(ctx context.Context) error { - var err error - for _, s := range serveProcess.servers { - serr := s.Shutdown(ctx) - if serr != nil && err == nil { - err = serr - } - } - - lChan := serveProcess.StopEventChannel() - serveProcess.stopChan <- struct{}{} - select { - case <-lChan: - return err - case <-ctx.Done(): - return ctx.Err() - } -} - -// Get a start-event channel from the server. The start event -// is fired after the Start() function is called, and after -// the server has started listening for incoming connections. -// An error here . -func (serveProcess *ServeProcess) StartEventChannel() <-chan struct{} { - lChan := make(chan struct{}, 1) - serveProcess.startListenChans = append(serveProcess.startListenChans, lChan) - return lChan -} - -// Get a stop-event channel from the server. The event happens -// after the Stop() function has been called, and after the -// timeout has passed. When the timeout has passed it will wait -// for confirmation from the http.Server, which normally takes -// a very short time (milliseconds). -func (serveProcess *ServeProcess) StopEventChannel() <-chan struct{} { - lChan := make(chan struct{}, 1) - serveProcess.stopListenChans = append(serveProcess.stopListenChans, lChan) - return lChan -} - -// Creates a new serve process. -func NewServeProcess(config *ServerConfig, logger *logging.Logger, - servers ...Server) (*ServeProcess, error) { - var scfg ServerConfig - if config == nil { - return nil, fmt.Errorf("Nil passed as server configuration") - } else { - scfg = *config - } - stopChan := make(chan struct{}, 1) - startListeners := make([]chan struct{}, 0) - stopListeners := make([]chan struct{}, 0) - sp := &ServeProcess{ - config: &scfg, - servers: servers, - stopChan: stopChan, - startListenChans: startListeners, - stopListenChans: stopListeners, - srv: nil, - logger: logger.WithScope("ServeProcess"), - } - return sp, nil -} - -// Used to enable log15 logging instead of the default Gin logging. -func logHandler(logger *logging.Logger) gin.HandlerFunc { - logger = logger.WithScope("ginLogHandler") - return func(c *gin.Context) { - - path := c.Request.URL.Path - - // Process request - c.Next() - - clientIP := c.ClientIP() - method := c.Request.Method - statusCode := c.Writer.Status() - comment := c.Errors.String() - - logger.Info.Log("client_ip", clientIP, - "status_code", statusCode, - "method", method, - "path", path, - "error", comment) - } -} - -func NewCORSMiddleware(options CORS) gin.HandlerFunc { - o := cors.Options{ - AllowCredentials: options.AllowCredentials, - AllowHeaders: options.AllowHeaders, - AllowMethods: options.AllowMethods, - AllowOrigins: options.AllowOrigins, - ExposeHeaders: options.ExposeHeaders, - MaxAge: time.Duration(options.MaxAge), - } - return cors.Middleware(o) -} - -// Just a catch-all for POST requests right now. Only allow default charset (utf8). -func contentTypeMW(c *gin.Context) { - if c.Request.Method == "POST" && c.ContentType() != "application/json" { - c.AbortWithError(415, fmt.Errorf("Media type not supported: "+c.ContentType())) - } else { - c.Next() - } -} diff --git a/rpc/v0/server/server_test.go b/rpc/v0/server/server_test.go deleted file mode 100644 index 5efdad268..000000000 --- a/rpc/v0/server/server_test.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package server - -import ( - //"fmt" - "testing" - - "github.com/stretchr/testify/assert" -) - -// Unit tests for server components goes here. Full-on client-server tests -// can be found in the test folder. - -func TestIdGet(t *testing.T) { - idPool := NewIdPool(100) - idparr := make([]uint, 100) - arr := make([]uint, 100) - for i := 0; i < 100; i++ { - idparr[i] = uint(i + 1) - arr[i], _ = idPool.GetId() - } - assert.Equal(t, idparr, arr, "Array of gotten id's is not [1, 2, ..., 101] as expected") -} - -func TestIdPut(t *testing.T) { - idPool := NewIdPool(10) - for i := 0; i < 10; i++ { - idPool.GetId() - } - idPool.ReleaseId(5) - id, _ := idPool.GetId() - assert.Equal(t, id, uint(5), "Id gotten is not 5.") -} - -func TestIdFull(t *testing.T) { - idPool := NewIdPool(10) - for i := 0; i < 10; i++ { - idPool.GetId() - } - _, err := idPool.GetId() - assert.Error(t, err) -} diff --git a/rpc/v0/server/websocket.go b/rpc/v0/server/websocket.go deleted file mode 100644 index cda4f7def..000000000 --- a/rpc/v0/server/websocket.go +++ /dev/null @@ -1,440 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package server - -import ( - "context" - "fmt" - "net/http" - "sync" - "time" - - "github.com/gin-gonic/gin" - "github.com/gorilla/websocket" - "github.com/hyperledger/burrow/logging" -) - -// TODO too much fluff. Should probably phase gorilla out and move closer -// to net in connections/session management. At some point... - -const ( - // Time allowed to write a message to the peer. - writeWait = 0 * time.Second - // Maximum message size allowed from a peer. - maxMessageSize = 1000000 -) - -// Services requests. Message bytes are passed along with the session -// object. The service is expected to write any response back using -// the Write function on WSSession, which passes the message over -// a channel to the write pump. -type WebSocketService interface { - Process([]byte, *WSSession) -} - -// The websocket server handles incoming websocket connection requests, -// upgrading, reading, writing, and session management. Handling the -// actual requests is delegated to a websocket service. -type WebSocketServer struct { - upgrader websocket.Upgrader - running bool - maxSessions uint16 - sessionManager *SessionManager - config *ServerConfig - allOrigins bool - logger *logging.Logger -} - -// Create a new server. -// maxSessions is the maximum number of active websocket connections that is allowed. -// NOTE: This is not the total number of connections allowed - only those that are -// upgraded to websockets. Requesting a websocket connection will fail with a 503 if -// the server is at capacity. -func NewWebSocketServer(maxSessions uint16, service WebSocketService, - logger *logging.Logger) *WebSocketServer { - return &WebSocketServer{ - maxSessions: maxSessions, - sessionManager: NewSessionManager(maxSessions, service, logger), - logger: logger.WithScope("WebSocketServer"), - } -} - -// Start the server. Adds the handler to the router and sets everything up. -func (wsServer *WebSocketServer) Start(config *ServerConfig, router *gin.Engine) { - - wsServer.config = config - - wsServer.upgrader = websocket.Upgrader{ - ReadBufferSize: int(config.WebSocket.ReadBufferSize), - // TODO Will this be enough for massive "get blockchain" requests? - WriteBufferSize: int(config.WebSocket.WriteBufferSize), - } - wsServer.upgrader.CheckOrigin = func(r *http.Request) bool { return true } - router.GET(config.WebSocket.WebSocketEndpoint, wsServer.handleFunc) - wsServer.running = true -} - -// Is the server currently running. -func (wsServer *WebSocketServer) Running() bool { - return wsServer.running -} - -// Shut the server down. -func (wsServer *WebSocketServer) Shutdown(ctx context.Context) error { - wsServer.sessionManager.Shutdown() - wsServer.running = false - return nil -} - -// Get the session-manager. -func (wsServer *WebSocketServer) SessionManager() *SessionManager { - return wsServer.sessionManager -} - -// Handler for websocket requests. -func (wsServer *WebSocketServer) handleFunc(c *gin.Context) { - r := c.Request - w := c.Writer - // Upgrade to websocket. - wsConn, uErr := wsServer.upgrader.Upgrade(w, r, nil) - - if uErr != nil { - errMsg := "Failed to upgrade to websocket connection" - http.Error(w, fmt.Sprintf("%s: %s", errMsg, uErr.Error()), 400) - wsServer.logger.InfoMsg(errMsg, "error", uErr) - return - } - - session, cErr := wsServer.sessionManager.createSession(wsConn) - - if cErr != nil { - errMsg := "Failed to establish websocket connection" - http.Error(w, fmt.Sprintf("%s: %s", errMsg, cErr.Error()), 503) - wsServer.logger.InfoMsg(errMsg, "error", cErr) - return - } - - // Start the connection. - wsServer.logger.InfoMsg("New websocket connection", - "session_id", session.id) - session.Open() -} - -// Used to track sessions. Will notify when a session are opened -// and closed. -type SessionObserver interface { - NotifyOpened(*WSSession) - NotifyClosed(*WSSession) -} - -// WSSession wraps a gorilla websocket.Conn, which in turn wraps a -// net.Conn object. Writing is done using the 'Write([]byte)' method, -// which passes the bytes on to the write pump over a channel. -type WSSession struct { - sessionManager *SessionManager - id uint - wsConn *websocket.Conn - writeChan chan []byte - writeCloseChan chan struct{} - service WebSocketService - opened bool - closed bool - logger *logging.Logger -} - -// Write a text message to the client. -func (wsSession *WSSession) Write(msg []byte) error { - if wsSession.closed { - wsSession.logger.InfoMsg("Attempting to write to closed session.") - return fmt.Errorf("Session is closed") - } - wsSession.writeChan <- msg - return nil -} - -// Private. Helper for writing control messages. -func (wsSession *WSSession) write(mt int, payload []byte) error { - wsSession.wsConn.SetWriteDeadline(time.Now().Add(writeWait)) - return wsSession.wsConn.WriteMessage(mt, payload) -} - -// Get the session id number. -func (wsSession *WSSession) Id() uint { - return wsSession.id -} - -// Starts the read and write pumps. Blocks on the former. -// Notifies all the observers. -func (wsSession *WSSession) Open() { - wsSession.opened = true - wsSession.sessionManager.notifyOpened(wsSession) - go wsSession.writePump() - wsSession.readPump() -} - -// Closes the net connection and cleans up. Notifies all the observers. -func (wsSession *WSSession) Close() { - if !wsSession.closed { - wsSession.closed = true - wsSession.wsConn.Close() - wsSession.sessionManager.removeSession(wsSession.id) - wsSession.logger.InfoMsg("Closing websocket connection.", - "remaining_active_sessions", len(wsSession.sessionManager.activeSessions)) - wsSession.sessionManager.notifyClosed(wsSession) - } -} - -// Has the session been opened? -func (wsSession *WSSession) Opened() bool { - return wsSession.opened -} - -// Has the session been closed? -func (wsSession *WSSession) Closed() bool { - return wsSession.closed -} - -// Pump debugging -/* -var rp int = 0 -var wp int = 0 -var rpm *sync.Mutex = &sync.Mutex{} -var wpm *sync.Mutex = &sync.Mutex{} -*/ - -// Read loop. Will terminate on a failed read. -func (wsSession *WSSession) readPump() { - /* - rpm.Lock() - rp++ - log.Debug("readpump created", "total", rp) - rpm.Unlock() - defer func(){ - rpm.Lock() - rp-- - log.Debug("readpump removed", "total", rp) - rpm.Unlock() - }() - */ - wsSession.wsConn.SetReadLimit(maxMessageSize) - // this.wsConn.SetReadDeadline(time.Now().Add(pongWait)) - // this.wsConn.SetPongHandler(func(string) error { this.wsConn.SetReadDeadline(time.Now().Add(pongWait)); return nil }) - - for { - // Read - msgType, msg, err := wsSession.wsConn.ReadMessage() - - // Read error. - if err != nil { - // Socket could have been gracefully closed, so not really an error. - wsSession.logger.InfoMsg( - "Socket closed. Removing.", "error", err) - wsSession.writeCloseChan <- struct{}{} - return - } - - if msgType != websocket.TextMessage { - wsSession.logger.InfoMsg( - "Receiving non text-message from client, closing.") - wsSession.writeCloseChan <- struct{}{} - return - } - - go func() { - // Process the request. - wsSession.service.Process(msg, wsSession) - }() - } -} - -// Writes messages coming in on the write channel. Will terminate on failed writes, -// if pings are not responded to, or if a message comes in on the write close channel. -func (wsSession *WSSession) writePump() { - /* - wpm.Lock() - wp++ - log.Debug("writepump created", "total", wp) - wpm.Unlock() - defer func() { - wpm.Lock() - wp-- - log.Debug("writepump removed", "total", wp) - wpm.Unlock() - }() - */ - // ticker := time.NewTicker(pingPeriod) - - defer func() { - // ticker.Stop() - wsSession.Close() - }() - - // Write loop. Blocks while waiting for data to come in over a channel. - for { - select { - // Write request. - case msg := <-wsSession.writeChan: - - // Write the bytes to the socket. - err := wsSession.wsConn.WriteMessage(websocket.TextMessage, msg) - if err != nil { - // Could be due to the socket being closed so not really an error. - wsSession.logger.InfoMsg( - "Writing to socket failed. Closing.") - return - } - case <-wsSession.writeCloseChan: - return - // Ticker run out. Time for another ping message. - /* - case <-ticker.C: - if err := this.write(websocket.PingMessage, []byte{}); err != nil { - log.Debug("Failed to write ping message to socket. Closing.") - return - } - */ - } - - } -} - -// Session manager handles the adding, tracking and removing of session objects. -type SessionManager struct { - maxSessions uint16 - activeSessions map[uint]*WSSession - idPool *IdPool - mtx *sync.Mutex - service WebSocketService - openEventChans []chan *WSSession - closeEventChans []chan *WSSession - logger *logging.Logger -} - -// Create a new WebsocketManager. -func NewSessionManager(maxSessions uint16, wss WebSocketService, - logger *logging.Logger) *SessionManager { - return &SessionManager{ - maxSessions: maxSessions, - activeSessions: make(map[uint]*WSSession), - idPool: NewIdPool(uint(maxSessions)), - mtx: &sync.Mutex{}, - service: wss, - openEventChans: []chan *WSSession{}, - closeEventChans: []chan *WSSession{}, - logger: logger.WithScope("SessionManager"), - } -} - -// TODO -func (sessionManager *SessionManager) Shutdown() { - sessionManager.activeSessions = nil -} - -// Add a listener to session open events. -func (sessionManager *SessionManager) SessionOpenEventChannel() <-chan *WSSession { - lChan := make(chan *WSSession, 1) - sessionManager.openEventChans = append(sessionManager.openEventChans, lChan) - return lChan -} - -// Remove a listener from session open events. -func (sessionManager *SessionManager) RemoveSessionOpenEventChannel(lChan chan *WSSession) bool { - ec := sessionManager.openEventChans - if len(ec) == 0 { - return false - } - for _, c := range ec { - if lChan == c { - return true - } - } - return false -} - -// Add a listener to session close events -func (sessionManager *SessionManager) SessionCloseEventChannel() <-chan *WSSession { - lChan := make(chan *WSSession, 1) - sessionManager.closeEventChans = append(sessionManager.closeEventChans, lChan) - return lChan -} - -// Remove a listener from session close events. -func (sessionManager *SessionManager) RemoveSessionCloseEventChannel(lChan chan *WSSession) bool { - ec := sessionManager.closeEventChans - if len(ec) == 0 { - return false - } - for _, c := range ec { - if lChan == c { - return true - } - } - return false -} - -// Used to notify all observers that a new session was opened. -func (sessionManager *SessionManager) notifyOpened(session *WSSession) { - for _, lChan := range sessionManager.openEventChans { - lChan <- session - } -} - -// Used to notify all observers that a new session was closed. -func (sessionManager *SessionManager) notifyClosed(session *WSSession) { - for _, lChan := range sessionManager.closeEventChans { - lChan <- session - } -} - -// Creates a new session and adds it to the manager. -func (sessionManager *SessionManager) createSession(wsConn *websocket.Conn) (*WSSession, error) { - // Check that the capacity hasn't been exceeded. - sessionManager.mtx.Lock() - defer sessionManager.mtx.Unlock() - if sessionManager.atCapacity() { - return nil, fmt.Errorf("Already at capacity") - } - - // Create and start - newId, _ := sessionManager.idPool.GetId() - conn := &WSSession{ - sessionManager: sessionManager, - id: newId, - wsConn: wsConn, - writeChan: make(chan []byte, maxMessageSize), - writeCloseChan: make(chan struct{}), - service: sessionManager.service, - logger: sessionManager.logger.WithScope("WSSession").With("session_id", newId), - } - sessionManager.activeSessions[conn.id] = conn - return conn, nil -} - -// Remove a session from the list. -func (sessionManager *SessionManager) removeSession(id uint) { - sessionManager.mtx.Lock() - defer sessionManager.mtx.Unlock() - // Check that it exists. - _, ok := sessionManager.activeSessions[id] - if ok { - delete(sessionManager.activeSessions, id) - sessionManager.idPool.ReleaseId(id) - } -} - -// True if the number of active connections is at the maximum. -func (sessionManager *SessionManager) atCapacity() bool { - return len(sessionManager.activeSessions) >= int(sessionManager.maxSessions) -} diff --git a/rpc/v0/websocket_service.go b/rpc/v0/websocket_service.go deleted file mode 100644 index 259a3f13d..000000000 --- a/rpc/v0/websocket_service.go +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright 2017 Monax Industries Limited -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package v0 - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/hyperledger/burrow/event" - "github.com/hyperledger/burrow/logging" - "github.com/hyperledger/burrow/logging/structure" - "github.com/hyperledger/burrow/rpc" - "github.com/hyperledger/burrow/rpc/v0/server" -) - -// Used for Burrow. Implements WebSocketService. -type WebsocketService struct { - codec rpc.Codec - service *rpc.Service - defaultHandlers map[string]RequestHandlerFunc - logger *logging.Logger -} - -// Create a new websocket service. -func NewWebsocketService(codec rpc.Codec, service *rpc.Service, logger *logging.Logger) server.WebSocketService { - tmwss := &WebsocketService{ - codec: codec, - service: service, - logger: logger.WithScope("NewWebsocketService"), - } - dhMap := GetMethods(codec, service, tmwss.logger) - // Events - dhMap[EVENT_SUBSCRIBE] = tmwss.EventSubscribe - dhMap[EVENT_UNSUBSCRIBE] = tmwss.EventUnsubscribe - tmwss.defaultHandlers = dhMap - return tmwss -} - -// Process a request. -func (ws *WebsocketService) Process(msg []byte, session *server.WSSession) { - defer func() { - if r := recover(); r != nil { - err := fmt.Errorf("panic in WebsocketService.Process(): %v", r) - ws.logger.InfoMsg("Panic in WebsocketService.Process()", structure.ErrorKey, err) - if !session.Closed() { - ws.writeError(err.Error(), "", rpc.INTERNAL_ERROR, session) - } - } - }() - // Create new request object and unmarshal. - req := &rpc.RPCRequest{} - errU := json.Unmarshal(msg, req) - - // Error when unmarshaling. - if errU != nil { - ws.writeError("Failed to parse request: "+errU.Error()+" . Raw: "+string(msg), - "", rpc.PARSE_ERROR, session) - return - } - - // Wrong protocol version. - if req.JSONRPC != "2.0" { - ws.writeError("Wrong protocol version: "+req.JSONRPC, req.Id, - rpc.INVALID_REQUEST, session) - return - } - - mName := req.Method - - if handler, ok := ws.defaultHandlers[mName]; ok { - resp, errCode, err := handler(req, session) - if err != nil { - ws.writeError(err.Error(), req.Id, errCode, session) - } else { - ws.writeResponse(req.Id, resp, session) - } - } else { - ws.writeError("Method not found: "+mName, req.Id, - rpc.METHOD_NOT_FOUND, session) - } -} - -// Convenience method for writing error responses. -func (ws *WebsocketService) writeError(msg, id string, code int, - session *server.WSSession) { - response := rpc.NewRPCErrorResponse(id, code, msg) - bts, err := ws.codec.EncodeBytes(response) - // If there's an error here all bets are off. - if err != nil { - panic("Failed to marshal standard error response." + err.Error()) - } - session.Write(bts) -} - -// Convenience method for writing responses. -func (ws *WebsocketService) writeResponse(id string, result interface{}, - session *server.WSSession) error { - response := rpc.NewRPCResponse(id, result) - bts, err := ws.codec.EncodeBytes(response) - if err != nil { - ws.writeError("Internal error: "+err.Error(), id, rpc.INTERNAL_ERROR, session) - return err - } - return session.Write(bts) -} - -// *************************************** Events ************************************ - -func (ws *WebsocketService) EventSubscribe(request *rpc.RPCRequest, - requester interface{}) (interface{}, int, error) { - session, ok := requester.(*server.WSSession) - if !ok { - return 0, rpc.INTERNAL_ERROR, - fmt.Errorf("Passing wrong object to websocket events") - } - param := &EventIdParam{} - err := ws.codec.DecodeBytes(param, request.Params) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - eventId := param.EventId - subId, err := event.GenerateSubscriptionID() - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - - err = ws.service.Subscribe(context.Background(), subId, eventId, func(resultEvent *rpc.ResultEvent) (stop bool) { - ws.writeResponse(subId, resultEvent, session) - return - }) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return &EventSub{SubId: subId}, 0, nil -} - -func (ws *WebsocketService) EventUnsubscribe(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - param := &SubIdParam{} - err := ws.codec.DecodeBytes(param, request.Params) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - - err = ws.service.Unsubscribe(context.Background(), param.SubId) - if err != nil { - return nil, rpc.INTERNAL_ERROR, err - } - return &EventUnsub{Result: true}, 0, nil -} - -func (ws *WebsocketService) EventPoll(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - return nil, rpc.INTERNAL_ERROR, fmt.Errorf("Cannot poll with websockets") -} diff --git a/txs/amino_codec_test.go b/txs/amino_codec_test.go index 41c3e4885..536bfc06d 100644 --- a/txs/amino_codec_test.go +++ b/txs/amino_codec_test.go @@ -3,7 +3,7 @@ package txs import ( "testing" - acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/txs/payload" "github.com/stretchr/testify/assert" diff --git a/txs/envelope.go b/txs/envelope.go index 107c7a677..06ed3832a 100644 --- a/txs/envelope.go +++ b/txs/envelope.go @@ -3,9 +3,10 @@ package txs import ( "fmt" - acm "github.com/hyperledger/burrow/account" - "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/state" "github.com/hyperledger/burrow/crypto" + "github.com/hyperledger/burrow/event/query" "github.com/hyperledger/burrow/txs/payload" ) @@ -22,12 +23,6 @@ type Decoder interface { DecodeTx(txBytes []byte) (*Envelope, error) } -// An envelope contains both the signable Tx and the signatures for each input (in signatories) -type Envelope struct { - Signatories []Signatory - Tx *Tx -} - // Enclose a Payload in an Envelope so it is ready to be signed by first wrapping the Payload // as a Tx (including ChainID) and writing it to the Tx field of the Envelope func Enclose(chainID string, payload payload.Payload) *Envelope { @@ -40,13 +35,6 @@ func (txEnv *Envelope) String() string { return fmt.Sprintf("TxEnvelope{Signatures: %v, Tx: %s}", len(txEnv.Signatories), txEnv.Tx) } -// Signatory contains signature and one or both of Address and PublicKey to identify the signer -type Signatory struct { - Address *crypto.Address - PublicKey *crypto.PublicKey - crypto.Signature -} - // Attempts to 'realise' the PublicKey and Address of a Signatory possibly referring to state // in the case where the Signatory contains an Address by no PublicKey. Checks consistency in other // cases, possibly generating the Address from the PublicKey @@ -150,3 +138,7 @@ func (txEnv *Envelope) Sign(signingAccounts ...acm.AddressableSigner) error { } return nil } + +func (txEnv *Envelope) Tagged() query.Tagged { + return query.MergeTags(query.MustReflectTags(txEnv, "Signatories"), txEnv.Tx.Tagged()) +} diff --git a/txs/json_codec_test.go b/txs/json_codec_test.go index f0056290c..2a4527f49 100644 --- a/txs/json_codec_test.go +++ b/txs/json_codec_test.go @@ -3,7 +3,7 @@ package txs import ( "testing" - "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/txs/payload" "github.com/stretchr/testify/assert" @@ -39,7 +39,7 @@ func TestJSONEncodeTxDecodeTx(t *testing.T) { func TestJSONEncodeTxDecodeTx_CallTx(t *testing.T) { codec := NewJSONCodec() - inputAccount := account.GeneratePrivateAccountFromSecret("fooo") + inputAccount := acm.GeneratePrivateAccountFromSecret("fooo") amount := uint64(2) sequence := uint64(3) tx := &payload.CallTx{ @@ -66,7 +66,7 @@ func TestJSONEncodeTxDecodeTx_CallTx(t *testing.T) { func TestJSONEncodeTxDecodeTx_CallTxNoData(t *testing.T) { codec := NewJSONCodec() - inputAccount := account.GeneratePrivateAccountFromSecret("fooo") + inputAccount := acm.GeneratePrivateAccountFromSecret("fooo") amount := uint64(2) sequence := uint64(3) tx := &payload.CallTx{ @@ -88,5 +88,11 @@ func TestJSONEncodeTxDecodeTx_CallTxNoData(t *testing.T) { } txEnvOut, err := codec.DecodeTx(txBytes) assert.NoError(t, err, "DecodeTx error") - assert.Equal(t, txEnv, txEnvOut) + + bs, err := codec.EncodeTx(txEnv) + require.NoError(t, err) + bsOut, err := codec.EncodeTx(txEnvOut) + require.NoError(t, err) + + assert.Equal(t, bs, bsOut) } diff --git a/txs/payload/bond_tx.go b/txs/payload/bond_tx.go index 7752b9411..59585b6e0 100644 --- a/txs/payload/bond_tx.go +++ b/txs/payload/bond_tx.go @@ -3,16 +3,10 @@ package payload import ( "fmt" - "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/acm/state" "github.com/hyperledger/burrow/crypto" ) -type BondTx struct { - // At least one should have bond permission (even if 0 amount transfer) - Inputs []*TxInput - UnbondTo []*TxOutput -} - func NewBondTx(pubkey crypto.PublicKey) (*BondTx, error) { return &BondTx{ Inputs: []*TxInput{}, diff --git a/txs/payload/call_tx.go b/txs/payload/call_tx.go index 559e72e13..68638de3e 100644 --- a/txs/payload/call_tx.go +++ b/txs/payload/call_tx.go @@ -3,21 +3,10 @@ package payload import ( "fmt" - "github.com/hyperledger/burrow/account/state" - "github.com/hyperledger/burrow/binary" + "github.com/hyperledger/burrow/acm/state" "github.com/hyperledger/burrow/crypto" ) -type CallTx struct { - Input *TxInput - // Pointer since CallTx defines unset 'to' address as inducing account creation - Address *crypto.Address - GasLimit uint64 - Fee uint64 - // Signing normalisation needs omitempty - Data binary.HexBytes `json:",omitempty"` -} - func NewCallTx(st state.AccountGetter, from crypto.PublicKey, to *crypto.Address, data []byte, amt, gasLimit, fee uint64) (*CallTx, error) { @@ -59,5 +48,14 @@ func (tx *CallTx) GetInputs() []*TxInput { } func (tx *CallTx) String() string { - return fmt.Sprintf("CallTx{%v -> %s: %X}", tx.Input, tx.Address, tx.Data) + return fmt.Sprintf("CallTx{%v -> %s: %v}", tx.Input, tx.Address, tx.Data) +} + +// Returns the contract address that this CallTx would create if CallTx.Address == nil otherwise returns nil +func (tx *CallTx) CreatesContractAddress() *crypto.Address { + if tx.Address != nil { + return nil + } + address := crypto.NewContractAddress(tx.Input.Address, tx.Input.Sequence) + return &address } diff --git a/txs/payload/errors.go b/txs/payload/errors.go index 93a7f2fee..affd56437 100644 --- a/txs/payload/errors.go +++ b/txs/payload/errors.go @@ -15,14 +15,6 @@ var ( ErrTxInvalidSignature = errors.New("error invalid signature") ) -type ErrTxInvalidString struct { - Msg string -} - -func (e ErrTxInvalidString) Error() string { - return e.Msg -} - type ErrTxInvalidSequence struct { Got uint64 Expected uint64 diff --git a/txs/payload/governance_tx.go b/txs/payload/governance_tx.go index 24c0cb48a..046f91291 100644 --- a/txs/payload/governance_tx.go +++ b/txs/payload/governance_tx.go @@ -3,17 +3,12 @@ package payload import ( "fmt" - "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/acm/state" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/genesis/spec" ) -type GovernanceTx struct { - Input *TxInput - AccountUpdates []spec.TemplateAccount -} - -func NewGovTx(st state.AccountGetter, from crypto.Address, accounts ...spec.TemplateAccount) (*GovernanceTx, error) { +func NewGovTx(st state.AccountGetter, from crypto.Address, accounts ...*spec.TemplateAccount) (*GovernanceTx, error) { acc, err := st.GetAccount(from) if err != nil { return nil, err @@ -26,12 +21,12 @@ func NewGovTx(st state.AccountGetter, from crypto.Address, accounts ...spec.Temp return NewGovTxWithSequence(from, sequence, accounts), nil } -func NewGovTxWithSequence(from crypto.Address, sequence uint64, accounts []spec.TemplateAccount) *GovernanceTx { +func NewGovTxWithSequence(from crypto.Address, sequence uint64, accounts []*spec.TemplateAccount) *GovernanceTx { return &GovernanceTx{ - Input: &TxInput{ + Inputs: []*TxInput{{ Address: from, Sequence: sequence, - }, + }}, AccountUpdates: accounts, } } @@ -41,9 +36,9 @@ func (tx *GovernanceTx) Type() Type { } func (tx *GovernanceTx) GetInputs() []*TxInput { - return []*TxInput{tx.Input} + return tx.Inputs } func (tx *GovernanceTx) String() string { - return fmt.Sprintf("GovernanceTx{%v -> %v}", tx.Input, tx.AccountUpdates) + return fmt.Sprintf("GovernanceTx{%v -> %v}", tx.Inputs, tx.AccountUpdates) } diff --git a/txs/payload/name_tx.go b/txs/payload/name_tx.go index a1037fc5a..334fa6df3 100644 --- a/txs/payload/name_tx.go +++ b/txs/payload/name_tx.go @@ -2,25 +2,11 @@ package payload import ( "fmt" - "regexp" - "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/acm/state" "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/execution/names" ) -// Name should be file system lik -// Data should be anything permitted in JSON -var regexpAlphaNum = regexp.MustCompile("^[a-zA-Z0-9._/-@]*$") -var regexpJSON = regexp.MustCompile(`^[a-zA-Z0-9_/ \-+"':,\n\t.{}()\[\]]*$`) - -type NameTx struct { - Input *TxInput - Name string - Data string - Fee uint64 -} - func NewNameTx(st state.AccountGetter, from crypto.PublicKey, name, data string, amt, fee uint64) (*NameTx, error) { addr := from.Address() acc, err := st.GetAccount(addr) @@ -58,37 +44,6 @@ func (tx *NameTx) GetInputs() []*TxInput { return []*TxInput{tx.Input} } -func (tx *NameTx) ValidateStrings() error { - if len(tx.Name) == 0 { - return ErrTxInvalidString{"Name must not be empty"} - } - if len(tx.Name) > names.MaxNameLength { - return ErrTxInvalidString{fmt.Sprintf("Name is too long. Max %d bytes", names.MaxNameLength)} - } - if len(tx.Data) > names.MaxDataLength { - return ErrTxInvalidString{fmt.Sprintf("Data is too long. Max %d bytes", names.MaxDataLength)} - } - - if !validateNameRegEntryName(tx.Name) { - return ErrTxInvalidString{fmt.Sprintf("Invalid characters found in NameTx.Name (%s). Only alphanumeric, underscores, dashes, forward slashes, and @ are allowed", tx.Name)} - } - - if !validateNameRegEntryData(tx.Data) { - return ErrTxInvalidString{fmt.Sprintf("Invalid characters found in NameTx.Data (%s). Only the kind of things found in a JSON file are allowed", tx.Data)} - } - - return nil -} - func (tx *NameTx) String() string { return fmt.Sprintf("NameTx{%v -> %s: %s}", tx.Input, tx.Name, tx.Data) } - -// filter strings -func validateNameRegEntryName(name string) bool { - return regexpAlphaNum.Match([]byte(name)) -} - -func validateNameRegEntryData(data string) bool { - return regexpJSON.Match([]byte(data)) -} diff --git a/txs/payload/payload.go b/txs/payload/payload.go index cc0c5e181..f415d8f83 100644 --- a/txs/payload/payload.go +++ b/txs/payload/payload.go @@ -16,7 +16,7 @@ Admin Txs: - PermissionsTx */ -type Type int8 +type Type uint32 // Types of Payload implementations const ( @@ -75,10 +75,21 @@ func (typ *Type) UnmarshalText(data []byte) error { return nil } +// Protobuf support +func (typ Type) Marshal() ([]byte, error) { + return typ.MarshalText() +} + +func (typ *Type) Unmarshal(data []byte) error { + return typ.UnmarshalText(data) +} + type Payload interface { String() string GetInputs() []*TxInput Type() Type + // The serialised size in bytes + Size() int } func New(txType Type) Payload { diff --git a/txs/payload/payload.pb.go b/txs/payload/payload.pb.go new file mode 100644 index 000000000..a5e27c742 --- /dev/null +++ b/txs/payload/payload.pb.go @@ -0,0 +1,2498 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: payload.proto + +/* + Package payload is a generated protocol buffer package. + + It is generated from these files: + payload.proto + + It has these top-level messages: + AnyPayload + TxInput + TxOutput + CallTx + SendTx + PermissionsTx + NameTx + BondTx + UnbondTx + GovernanceTx +*/ +package payload + +import proto "github.com/gogo/protobuf/proto" +import golang_proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" +import _ "github.com/gogo/protobuf/gogoproto" +import permission "github.com/hyperledger/burrow/permission" +import spec "github.com/hyperledger/burrow/genesis/spec" + +import github_com_hyperledger_burrow_crypto "github.com/hyperledger/burrow/crypto" +import github_com_hyperledger_burrow_binary "github.com/hyperledger/burrow/binary" + +import io "io" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = golang_proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package + +type AnyPayload struct { + CallTx *CallTx `protobuf:"bytes,1,opt,name=CallTx" json:"CallTx,omitempty"` + SendTx *SendTx `protobuf:"bytes,2,opt,name=SendTx" json:"SendTx,omitempty"` + NameTx *NameTx `protobuf:"bytes,3,opt,name=NameTx" json:"NameTx,omitempty"` + PermissionsTx *PermissionsTx `protobuf:"bytes,4,opt,name=PermissionsTx" json:"PermissionsTx,omitempty"` + GovernanceTx *GovernanceTx `protobuf:"bytes,5,opt,name=GovernanceTx" json:"GovernanceTx,omitempty"` +} + +func (m *AnyPayload) Reset() { *m = AnyPayload{} } +func (m *AnyPayload) String() string { return proto.CompactTextString(m) } +func (*AnyPayload) ProtoMessage() {} +func (*AnyPayload) Descriptor() ([]byte, []int) { return fileDescriptorPayload, []int{0} } + +func (m *AnyPayload) GetCallTx() *CallTx { + if m != nil { + return m.CallTx + } + return nil +} + +func (m *AnyPayload) GetSendTx() *SendTx { + if m != nil { + return m.SendTx + } + return nil +} + +func (m *AnyPayload) GetNameTx() *NameTx { + if m != nil { + return m.NameTx + } + return nil +} + +func (m *AnyPayload) GetPermissionsTx() *PermissionsTx { + if m != nil { + return m.PermissionsTx + } + return nil +} + +func (m *AnyPayload) GetGovernanceTx() *GovernanceTx { + if m != nil { + return m.GovernanceTx + } + return nil +} + +func (*AnyPayload) XXX_MessageName() string { + return "payload.AnyPayload" +} + +// An input to a transaction that may carry an Amount as a charge and whose sequence number must be one greater than +// that associated with the account at Address at the time of being received +type TxInput struct { + // The address from which this input flows + Address github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,1,opt,name=Address,proto3,customtype=github.com/hyperledger/burrow/crypto.Address" json:"Address"` + // The amount of native token to transfer from the input address + Amount uint64 `protobuf:"varint,2,opt,name=Amount,proto3" json:"Amount,omitempty"` + // The sequence number that this transaction will induce (i.e. one greater than the input account's current sequence) + Sequence uint64 `protobuf:"varint,3,opt,name=Sequence,proto3" json:"Sequence,omitempty"` +} + +func (m *TxInput) Reset() { *m = TxInput{} } +func (*TxInput) ProtoMessage() {} +func (*TxInput) Descriptor() ([]byte, []int) { return fileDescriptorPayload, []int{1} } + +func (m *TxInput) GetAmount() uint64 { + if m != nil { + return m.Amount + } + return 0 +} + +func (m *TxInput) GetSequence() uint64 { + if m != nil { + return m.Sequence + } + return 0 +} + +func (*TxInput) XXX_MessageName() string { + return "payload.TxInput" +} + +// An output from a transaction that may carry an amount as a charge +type TxOutput struct { + // The address to which this output flows + Address github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,1,opt,name=Address,proto3,customtype=github.com/hyperledger/burrow/crypto.Address" json:"Address"` + // The amount of native token to transfer to the output address + Amount uint64 `protobuf:"varint,2,opt,name=Amount,proto3" json:"Amount,omitempty"` +} + +func (m *TxOutput) Reset() { *m = TxOutput{} } +func (*TxOutput) ProtoMessage() {} +func (*TxOutput) Descriptor() ([]byte, []int) { return fileDescriptorPayload, []int{2} } + +func (m *TxOutput) GetAmount() uint64 { + if m != nil { + return m.Amount + } + return 0 +} + +func (*TxOutput) XXX_MessageName() string { + return "payload.TxOutput" +} + +// A instruction to run smart contract code in the EVM +type CallTx struct { + // The caller's input + Input *TxInput `protobuf:"bytes,1,opt,name=Input" json:"Input,omitempty"` + // The contract address to call or nil if we are creating a contract + Address *github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,2,opt,name=Address,proto3,customtype=github.com/hyperledger/burrow/crypto.Address" json:"Address,omitempty"` + // The upper bound on the amount of gas (and therefore EVM execution steps) this CallTx may generate + GasLimit uint64 `protobuf:"varint,3,opt,name=GasLimit,proto3" json:"GasLimit,omitempty"` + // Fee to offer validators for processing transaction + Fee uint64 `protobuf:"varint,4,opt,name=Fee,proto3" json:"Fee,omitempty"` + // EVM bytecode payload + Data github_com_hyperledger_burrow_binary.HexBytes `protobuf:"bytes,5,opt,name=Data,proto3,customtype=github.com/hyperledger/burrow/binary.HexBytes" json:"Data"` +} + +func (m *CallTx) Reset() { *m = CallTx{} } +func (*CallTx) ProtoMessage() {} +func (*CallTx) Descriptor() ([]byte, []int) { return fileDescriptorPayload, []int{3} } + +func (m *CallTx) GetInput() *TxInput { + if m != nil { + return m.Input + } + return nil +} + +func (m *CallTx) GetGasLimit() uint64 { + if m != nil { + return m.GasLimit + } + return 0 +} + +func (m *CallTx) GetFee() uint64 { + if m != nil { + return m.Fee + } + return 0 +} + +func (*CallTx) XXX_MessageName() string { + return "payload.CallTx" +} + +// A payment between two sets of parties +type SendTx struct { + // The payers + Inputs []*TxInput `protobuf:"bytes,1,rep,name=Inputs" json:"Inputs,omitempty"` + // The payees + Outputs []*TxOutput `protobuf:"bytes,2,rep,name=Outputs" json:"Outputs,omitempty"` +} + +func (m *SendTx) Reset() { *m = SendTx{} } +func (*SendTx) ProtoMessage() {} +func (*SendTx) Descriptor() ([]byte, []int) { return fileDescriptorPayload, []int{4} } + +func (*SendTx) XXX_MessageName() string { + return "payload.SendTx" +} + +// An update to the on-chain permissions +type PermissionsTx struct { + // The permission moderator + Input *TxInput `protobuf:"bytes,1,opt,name=Input" json:"Input,omitempty"` + // The modified permissions + PermArgs permission.PermArgs `protobuf:"bytes,2,opt,name=PermArgs" json:"PermArgs"` +} + +func (m *PermissionsTx) Reset() { *m = PermissionsTx{} } +func (*PermissionsTx) ProtoMessage() {} +func (*PermissionsTx) Descriptor() ([]byte, []int) { return fileDescriptorPayload, []int{5} } + +func (m *PermissionsTx) GetInput() *TxInput { + if m != nil { + return m.Input + } + return nil +} + +func (m *PermissionsTx) GetPermArgs() permission.PermArgs { + if m != nil { + return m.PermArgs + } + return permission.PermArgs{} +} + +func (*PermissionsTx) XXX_MessageName() string { + return "payload.PermissionsTx" +} + +// A request to claim a globally unique name across the entire chain with some optional data storage leased for a fee +type NameTx struct { + // The name updater + Input *TxInput `protobuf:"bytes,1,opt,name=Input" json:"Input,omitempty"` + // The name to update or create + Name string `protobuf:"bytes,2,opt,name=Name,proto3" json:"Name,omitempty"` + // The data to store against the name + Data string `protobuf:"bytes,3,opt,name=Data,proto3" json:"Data,omitempty"` + // The fee to provide that will determine the lenght of the name lease + Fee uint64 `protobuf:"varint,4,opt,name=Fee,proto3" json:"Fee,omitempty"` +} + +func (m *NameTx) Reset() { *m = NameTx{} } +func (*NameTx) ProtoMessage() {} +func (*NameTx) Descriptor() ([]byte, []int) { return fileDescriptorPayload, []int{6} } + +func (m *NameTx) GetInput() *TxInput { + if m != nil { + return m.Input + } + return nil +} + +func (m *NameTx) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *NameTx) GetData() string { + if m != nil { + return m.Data + } + return "" +} + +func (m *NameTx) GetFee() uint64 { + if m != nil { + return m.Fee + } + return 0 +} + +func (*NameTx) XXX_MessageName() string { + return "payload.NameTx" +} + +type BondTx struct { + Inputs []*TxInput `protobuf:"bytes,1,rep,name=Inputs" json:"Inputs,omitempty"` + UnbondTo []*TxOutput `protobuf:"bytes,2,rep,name=UnbondTo" json:"UnbondTo,omitempty"` +} + +func (m *BondTx) Reset() { *m = BondTx{} } +func (*BondTx) ProtoMessage() {} +func (*BondTx) Descriptor() ([]byte, []int) { return fileDescriptorPayload, []int{7} } + +func (*BondTx) XXX_MessageName() string { + return "payload.BondTx" +} + +type UnbondTx struct { + Input *TxInput `protobuf:"bytes,1,opt,name=Input" json:"Input,omitempty"` + Address github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,2,opt,name=Address,proto3,customtype=github.com/hyperledger/burrow/crypto.Address" json:"Address"` + Height uint64 `protobuf:"varint,3,opt,name=Height,proto3" json:"Height,omitempty"` +} + +func (m *UnbondTx) Reset() { *m = UnbondTx{} } +func (*UnbondTx) ProtoMessage() {} +func (*UnbondTx) Descriptor() ([]byte, []int) { return fileDescriptorPayload, []int{8} } + +func (*UnbondTx) XXX_MessageName() string { + return "payload.UnbondTx" +} + +type GovernanceTx struct { + Inputs []*TxInput `protobuf:"bytes,1,rep,name=Inputs" json:"Inputs,omitempty"` + AccountUpdates []*spec.TemplateAccount `protobuf:"bytes,2,rep,name=AccountUpdates" json:"AccountUpdates,omitempty"` +} + +func (m *GovernanceTx) Reset() { *m = GovernanceTx{} } +func (*GovernanceTx) ProtoMessage() {} +func (*GovernanceTx) Descriptor() ([]byte, []int) { return fileDescriptorPayload, []int{9} } + +func (*GovernanceTx) XXX_MessageName() string { + return "payload.GovernanceTx" +} +func init() { + proto.RegisterType((*AnyPayload)(nil), "payload.AnyPayload") + golang_proto.RegisterType((*AnyPayload)(nil), "payload.AnyPayload") + proto.RegisterType((*TxInput)(nil), "payload.TxInput") + golang_proto.RegisterType((*TxInput)(nil), "payload.TxInput") + proto.RegisterType((*TxOutput)(nil), "payload.TxOutput") + golang_proto.RegisterType((*TxOutput)(nil), "payload.TxOutput") + proto.RegisterType((*CallTx)(nil), "payload.CallTx") + golang_proto.RegisterType((*CallTx)(nil), "payload.CallTx") + proto.RegisterType((*SendTx)(nil), "payload.SendTx") + golang_proto.RegisterType((*SendTx)(nil), "payload.SendTx") + proto.RegisterType((*PermissionsTx)(nil), "payload.PermissionsTx") + golang_proto.RegisterType((*PermissionsTx)(nil), "payload.PermissionsTx") + proto.RegisterType((*NameTx)(nil), "payload.NameTx") + golang_proto.RegisterType((*NameTx)(nil), "payload.NameTx") + proto.RegisterType((*BondTx)(nil), "payload.BondTx") + golang_proto.RegisterType((*BondTx)(nil), "payload.BondTx") + proto.RegisterType((*UnbondTx)(nil), "payload.UnbondTx") + golang_proto.RegisterType((*UnbondTx)(nil), "payload.UnbondTx") + proto.RegisterType((*GovernanceTx)(nil), "payload.GovernanceTx") + golang_proto.RegisterType((*GovernanceTx)(nil), "payload.GovernanceTx") +} +func (m *AnyPayload) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *AnyPayload) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.CallTx != nil { + dAtA[i] = 0xa + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.CallTx.Size())) + n1, err := m.CallTx.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n1 + } + if m.SendTx != nil { + dAtA[i] = 0x12 + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.SendTx.Size())) + n2, err := m.SendTx.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n2 + } + if m.NameTx != nil { + dAtA[i] = 0x1a + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.NameTx.Size())) + n3, err := m.NameTx.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n3 + } + if m.PermissionsTx != nil { + dAtA[i] = 0x22 + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.PermissionsTx.Size())) + n4, err := m.PermissionsTx.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n4 + } + if m.GovernanceTx != nil { + dAtA[i] = 0x2a + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.GovernanceTx.Size())) + n5, err := m.GovernanceTx.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n5 + } + return i, nil +} + +func (m *TxInput) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *TxInput) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + dAtA[i] = 0xa + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.Address.Size())) + n6, err := m.Address.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n6 + if m.Amount != 0 { + dAtA[i] = 0x10 + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.Amount)) + } + if m.Sequence != 0 { + dAtA[i] = 0x18 + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.Sequence)) + } + return i, nil +} + +func (m *TxOutput) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *TxOutput) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + dAtA[i] = 0xa + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.Address.Size())) + n7, err := m.Address.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n7 + if m.Amount != 0 { + dAtA[i] = 0x10 + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.Amount)) + } + return i, nil +} + +func (m *CallTx) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CallTx) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.Input != nil { + dAtA[i] = 0xa + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.Input.Size())) + n8, err := m.Input.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n8 + } + if m.Address != nil { + dAtA[i] = 0x12 + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.Address.Size())) + n9, err := m.Address.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n9 + } + if m.GasLimit != 0 { + dAtA[i] = 0x18 + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.GasLimit)) + } + if m.Fee != 0 { + dAtA[i] = 0x20 + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.Fee)) + } + dAtA[i] = 0x2a + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.Data.Size())) + n10, err := m.Data.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n10 + return i, nil +} + +func (m *SendTx) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *SendTx) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Inputs) > 0 { + for _, msg := range m.Inputs { + dAtA[i] = 0xa + i++ + i = encodeVarintPayload(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + if len(m.Outputs) > 0 { + for _, msg := range m.Outputs { + dAtA[i] = 0x12 + i++ + i = encodeVarintPayload(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + return i, nil +} + +func (m *PermissionsTx) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PermissionsTx) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.Input != nil { + dAtA[i] = 0xa + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.Input.Size())) + n11, err := m.Input.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n11 + } + dAtA[i] = 0x12 + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.PermArgs.Size())) + n12, err := m.PermArgs.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n12 + return i, nil +} + +func (m *NameTx) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *NameTx) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.Input != nil { + dAtA[i] = 0xa + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.Input.Size())) + n13, err := m.Input.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n13 + } + if len(m.Name) > 0 { + dAtA[i] = 0x12 + i++ + i = encodeVarintPayload(dAtA, i, uint64(len(m.Name))) + i += copy(dAtA[i:], m.Name) + } + if len(m.Data) > 0 { + dAtA[i] = 0x1a + i++ + i = encodeVarintPayload(dAtA, i, uint64(len(m.Data))) + i += copy(dAtA[i:], m.Data) + } + if m.Fee != 0 { + dAtA[i] = 0x20 + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.Fee)) + } + return i, nil +} + +func (m *BondTx) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *BondTx) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Inputs) > 0 { + for _, msg := range m.Inputs { + dAtA[i] = 0xa + i++ + i = encodeVarintPayload(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + if len(m.UnbondTo) > 0 { + for _, msg := range m.UnbondTo { + dAtA[i] = 0x12 + i++ + i = encodeVarintPayload(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + return i, nil +} + +func (m *UnbondTx) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *UnbondTx) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.Input != nil { + dAtA[i] = 0xa + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.Input.Size())) + n14, err := m.Input.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n14 + } + dAtA[i] = 0x12 + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.Address.Size())) + n15, err := m.Address.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n15 + if m.Height != 0 { + dAtA[i] = 0x18 + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.Height)) + } + return i, nil +} + +func (m *GovernanceTx) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GovernanceTx) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Inputs) > 0 { + for _, msg := range m.Inputs { + dAtA[i] = 0xa + i++ + i = encodeVarintPayload(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + if len(m.AccountUpdates) > 0 { + for _, msg := range m.AccountUpdates { + dAtA[i] = 0x12 + i++ + i = encodeVarintPayload(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + return i, nil +} + +func encodeVarintPayload(dAtA []byte, offset int, v uint64) int { + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return offset + 1 +} +func (m *AnyPayload) Size() (n int) { + var l int + _ = l + if m.CallTx != nil { + l = m.CallTx.Size() + n += 1 + l + sovPayload(uint64(l)) + } + if m.SendTx != nil { + l = m.SendTx.Size() + n += 1 + l + sovPayload(uint64(l)) + } + if m.NameTx != nil { + l = m.NameTx.Size() + n += 1 + l + sovPayload(uint64(l)) + } + if m.PermissionsTx != nil { + l = m.PermissionsTx.Size() + n += 1 + l + sovPayload(uint64(l)) + } + if m.GovernanceTx != nil { + l = m.GovernanceTx.Size() + n += 1 + l + sovPayload(uint64(l)) + } + return n +} + +func (m *TxInput) Size() (n int) { + var l int + _ = l + l = m.Address.Size() + n += 1 + l + sovPayload(uint64(l)) + if m.Amount != 0 { + n += 1 + sovPayload(uint64(m.Amount)) + } + if m.Sequence != 0 { + n += 1 + sovPayload(uint64(m.Sequence)) + } + return n +} + +func (m *TxOutput) Size() (n int) { + var l int + _ = l + l = m.Address.Size() + n += 1 + l + sovPayload(uint64(l)) + if m.Amount != 0 { + n += 1 + sovPayload(uint64(m.Amount)) + } + return n +} + +func (m *CallTx) Size() (n int) { + var l int + _ = l + if m.Input != nil { + l = m.Input.Size() + n += 1 + l + sovPayload(uint64(l)) + } + if m.Address != nil { + l = m.Address.Size() + n += 1 + l + sovPayload(uint64(l)) + } + if m.GasLimit != 0 { + n += 1 + sovPayload(uint64(m.GasLimit)) + } + if m.Fee != 0 { + n += 1 + sovPayload(uint64(m.Fee)) + } + l = m.Data.Size() + n += 1 + l + sovPayload(uint64(l)) + return n +} + +func (m *SendTx) Size() (n int) { + var l int + _ = l + if len(m.Inputs) > 0 { + for _, e := range m.Inputs { + l = e.Size() + n += 1 + l + sovPayload(uint64(l)) + } + } + if len(m.Outputs) > 0 { + for _, e := range m.Outputs { + l = e.Size() + n += 1 + l + sovPayload(uint64(l)) + } + } + return n +} + +func (m *PermissionsTx) Size() (n int) { + var l int + _ = l + if m.Input != nil { + l = m.Input.Size() + n += 1 + l + sovPayload(uint64(l)) + } + l = m.PermArgs.Size() + n += 1 + l + sovPayload(uint64(l)) + return n +} + +func (m *NameTx) Size() (n int) { + var l int + _ = l + if m.Input != nil { + l = m.Input.Size() + n += 1 + l + sovPayload(uint64(l)) + } + l = len(m.Name) + if l > 0 { + n += 1 + l + sovPayload(uint64(l)) + } + l = len(m.Data) + if l > 0 { + n += 1 + l + sovPayload(uint64(l)) + } + if m.Fee != 0 { + n += 1 + sovPayload(uint64(m.Fee)) + } + return n +} + +func (m *BondTx) Size() (n int) { + var l int + _ = l + if len(m.Inputs) > 0 { + for _, e := range m.Inputs { + l = e.Size() + n += 1 + l + sovPayload(uint64(l)) + } + } + if len(m.UnbondTo) > 0 { + for _, e := range m.UnbondTo { + l = e.Size() + n += 1 + l + sovPayload(uint64(l)) + } + } + return n +} + +func (m *UnbondTx) Size() (n int) { + var l int + _ = l + if m.Input != nil { + l = m.Input.Size() + n += 1 + l + sovPayload(uint64(l)) + } + l = m.Address.Size() + n += 1 + l + sovPayload(uint64(l)) + if m.Height != 0 { + n += 1 + sovPayload(uint64(m.Height)) + } + return n +} + +func (m *GovernanceTx) Size() (n int) { + var l int + _ = l + if len(m.Inputs) > 0 { + for _, e := range m.Inputs { + l = e.Size() + n += 1 + l + sovPayload(uint64(l)) + } + } + if len(m.AccountUpdates) > 0 { + for _, e := range m.AccountUpdates { + l = e.Size() + n += 1 + l + sovPayload(uint64(l)) + } + } + return n +} + +func sovPayload(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n +} +func sozPayload(x uint64) (n int) { + return sovPayload(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *AnyPayload) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: AnyPayload: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: AnyPayload: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CallTx", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.CallTx == nil { + m.CallTx = &CallTx{} + } + if err := m.CallTx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SendTx", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.SendTx == nil { + m.SendTx = &SendTx{} + } + if err := m.SendTx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NameTx", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.NameTx == nil { + m.NameTx = &NameTx{} + } + if err := m.NameTx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PermissionsTx", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.PermissionsTx == nil { + m.PermissionsTx = &PermissionsTx{} + } + if err := m.PermissionsTx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field GovernanceTx", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.GovernanceTx == nil { + m.GovernanceTx = &GovernanceTx{} + } + if err := m.GovernanceTx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipPayload(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthPayload + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *TxInput) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: TxInput: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: TxInput: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Address.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) + } + m.Amount = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Amount |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Sequence", wireType) + } + m.Sequence = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Sequence |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipPayload(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthPayload + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *TxOutput) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: TxOutput: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: TxOutput: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Address.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) + } + m.Amount = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Amount |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipPayload(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthPayload + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CallTx) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CallTx: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CallTx: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Input", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Input == nil { + m.Input = &TxInput{} + } + if err := m.Input.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + var v github_com_hyperledger_burrow_crypto.Address + m.Address = &v + if err := m.Address.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field GasLimit", wireType) + } + m.GasLimit = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.GasLimit |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Fee", wireType) + } + m.Fee = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Fee |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Data.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipPayload(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthPayload + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *SendTx) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: SendTx: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SendTx: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Inputs", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Inputs = append(m.Inputs, &TxInput{}) + if err := m.Inputs[len(m.Inputs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Outputs", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Outputs = append(m.Outputs, &TxOutput{}) + if err := m.Outputs[len(m.Outputs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipPayload(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthPayload + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PermissionsTx) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PermissionsTx: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PermissionsTx: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Input", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Input == nil { + m.Input = &TxInput{} + } + if err := m.Input.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PermArgs", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.PermArgs.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipPayload(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthPayload + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *NameTx) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: NameTx: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: NameTx: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Input", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Input == nil { + m.Input = &TxInput{} + } + if err := m.Input.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Data = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Fee", wireType) + } + m.Fee = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Fee |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipPayload(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthPayload + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *BondTx) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: BondTx: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: BondTx: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Inputs", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Inputs = append(m.Inputs, &TxInput{}) + if err := m.Inputs[len(m.Inputs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field UnbondTo", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.UnbondTo = append(m.UnbondTo, &TxOutput{}) + if err := m.UnbondTo[len(m.UnbondTo)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipPayload(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthPayload + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *UnbondTx) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: UnbondTx: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: UnbondTx: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Input", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Input == nil { + m.Input = &TxInput{} + } + if err := m.Input.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Address.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipPayload(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthPayload + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *GovernanceTx) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GovernanceTx: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GovernanceTx: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Inputs", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Inputs = append(m.Inputs, &TxInput{}) + if err := m.Inputs[len(m.Inputs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AccountUpdates", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.AccountUpdates = append(m.AccountUpdates, &spec.TemplateAccount{}) + if err := m.AccountUpdates[len(m.AccountUpdates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipPayload(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthPayload + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipPayload(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowPayload + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowPayload + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowPayload + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + iNdEx += length + if length < 0 { + return 0, ErrInvalidLengthPayload + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowPayload + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipPayload(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} + +var ( + ErrInvalidLengthPayload = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowPayload = fmt.Errorf("proto: integer overflow") +) + +func init() { proto.RegisterFile("payload.proto", fileDescriptorPayload) } +func init() { golang_proto.RegisterFile("payload.proto", fileDescriptorPayload) } + +var fileDescriptorPayload = []byte{ + // 652 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x55, 0xbf, 0x6f, 0xd3, 0x40, + 0x14, 0xee, 0x35, 0x6e, 0x62, 0x8e, 0x16, 0xca, 0x89, 0x56, 0x51, 0x86, 0x04, 0x75, 0x80, 0x22, + 0xa8, 0x83, 0xf8, 0x25, 0x51, 0x21, 0xa1, 0xb8, 0x88, 0xb6, 0x08, 0x85, 0xea, 0xea, 0x2e, 0x6c, + 0xfe, 0x71, 0x38, 0x16, 0xb1, 0xcf, 0xd8, 0x67, 0xb0, 0x37, 0x36, 0xd8, 0x59, 0x18, 0x3b, 0xf0, + 0x87, 0x30, 0x66, 0x64, 0x66, 0xa8, 0x50, 0xfa, 0x67, 0xb0, 0xa0, 0x3b, 0x9f, 0x5d, 0x27, 0x40, + 0x95, 0x82, 0xc4, 0x76, 0xef, 0x7d, 0xdf, 0xbb, 0xf7, 0xde, 0x77, 0xef, 0xd9, 0x70, 0x29, 0x34, + 0xb3, 0x21, 0x35, 0x1d, 0x2d, 0x8c, 0x28, 0xa3, 0xa8, 0x21, 0xcd, 0xd6, 0x86, 0xeb, 0xb1, 0x41, + 0x62, 0x69, 0x36, 0xf5, 0xbb, 0x2e, 0x75, 0x69, 0x57, 0xe0, 0x56, 0xf2, 0x52, 0x58, 0xc2, 0x10, + 0xa7, 0x3c, 0xae, 0xb5, 0x1c, 0x92, 0xc8, 0xf7, 0xe2, 0xd8, 0xa3, 0x81, 0xf4, 0xc0, 0x38, 0x24, + 0x76, 0x7e, 0x5e, 0x7b, 0x37, 0x0f, 0x61, 0x2f, 0xc8, 0xf6, 0xf2, 0xbb, 0xd1, 0x35, 0x58, 0xdf, + 0x32, 0x87, 0x43, 0x23, 0x6d, 0x82, 0x2b, 0x60, 0xfd, 0xfc, 0xed, 0x8b, 0x5a, 0x51, 0x44, 0xee, + 0xc6, 0x12, 0xe6, 0xc4, 0x7d, 0x12, 0x38, 0x46, 0xda, 0x9c, 0x9f, 0x22, 0xe6, 0x6e, 0x2c, 0x61, + 0x4e, 0xec, 0x9b, 0x3e, 0x31, 0xd2, 0x66, 0x6d, 0x8a, 0x98, 0xbb, 0xb1, 0x84, 0xd1, 0x43, 0xb8, + 0xb4, 0x57, 0x56, 0x1a, 0x1b, 0x69, 0x53, 0x11, 0xfc, 0xd5, 0x92, 0x3f, 0x81, 0xe2, 0x49, 0x32, + 0x7a, 0x00, 0x17, 0xb7, 0xe9, 0x1b, 0x12, 0x05, 0x66, 0x60, 0xf3, 0x64, 0x0b, 0x22, 0x78, 0xa5, + 0x0c, 0xae, 0x82, 0x78, 0x82, 0xba, 0xf6, 0x11, 0xc0, 0x86, 0x91, 0xee, 0x06, 0x61, 0xc2, 0x50, + 0x1f, 0x36, 0x7a, 0x8e, 0x13, 0x91, 0x38, 0x16, 0x02, 0x2c, 0xea, 0x77, 0x47, 0x47, 0x9d, 0xb9, + 0x6f, 0x47, 0x9d, 0x9b, 0x15, 0xd1, 0x07, 0x59, 0x48, 0xa2, 0x21, 0x71, 0x5c, 0x12, 0x75, 0xad, + 0x24, 0x8a, 0xe8, 0xdb, 0xae, 0x1d, 0x65, 0x21, 0xa3, 0x9a, 0x8c, 0xc5, 0xc5, 0x25, 0x68, 0x15, + 0xd6, 0x7b, 0x3e, 0x4d, 0x02, 0x26, 0x64, 0x52, 0xb0, 0xb4, 0x50, 0x0b, 0xaa, 0xfb, 0xe4, 0x75, + 0x42, 0x02, 0x9b, 0x08, 0x5d, 0x14, 0x5c, 0xda, 0x9b, 0xca, 0xa7, 0xc3, 0xce, 0xdc, 0x5a, 0x0a, + 0x55, 0x23, 0x7d, 0x9e, 0xb0, 0xff, 0x58, 0x95, 0xcc, 0xfc, 0x03, 0x14, 0x43, 0x80, 0xae, 0xc2, + 0x05, 0xa1, 0x8b, 0x9c, 0x86, 0xe5, 0x52, 0x4e, 0xa9, 0x17, 0xce, 0x61, 0xf4, 0xf4, 0xa4, 0xc0, + 0x79, 0x51, 0xe0, 0xad, 0xbf, 0x2f, 0xae, 0x05, 0xd5, 0x6d, 0x33, 0x7e, 0xe6, 0xf9, 0x1e, 0x2b, + 0xa4, 0x29, 0x6c, 0xb4, 0x0c, 0x6b, 0x4f, 0x08, 0x11, 0x93, 0xa1, 0x60, 0x7e, 0x44, 0xbb, 0x50, + 0x79, 0x6c, 0x32, 0x53, 0xbc, 0xf7, 0xa2, 0x7e, 0x4f, 0xea, 0xb2, 0x71, 0x7a, 0x6a, 0xcb, 0x0b, + 0xcc, 0x28, 0xd3, 0x76, 0x48, 0xaa, 0x67, 0x8c, 0xc4, 0x58, 0x5c, 0x21, 0xbb, 0xf7, 0x8a, 0xc1, + 0x46, 0xeb, 0xb0, 0x2e, 0xba, 0xe3, 0xa2, 0xd7, 0x7e, 0xdb, 0xbd, 0xc4, 0xd1, 0x0d, 0xd8, 0xc8, + 0x5f, 0x8a, 0xb7, 0xcf, 0xa9, 0x97, 0x2a, 0xd4, 0x1c, 0xc1, 0x05, 0x63, 0x53, 0xfd, 0x70, 0xd8, + 0x99, 0x13, 0xa9, 0x92, 0xa9, 0x89, 0x9f, 0x59, 0xee, 0xfb, 0x50, 0xe5, 0x81, 0xbd, 0xc8, 0x8d, + 0xe5, 0xfa, 0x5d, 0xd6, 0x2a, 0x5b, 0x5e, 0x60, 0xba, 0xc2, 0xe5, 0xc0, 0x25, 0x57, 0x76, 0x18, + 0x16, 0x1b, 0x39, 0x73, 0x3e, 0x04, 0x15, 0x1e, 0x21, 0x72, 0x9d, 0xc3, 0xe2, 0xcc, 0x7d, 0x42, + 0xf8, 0x5a, 0xee, 0xe3, 0xe7, 0x5f, 0x9f, 0x47, 0x66, 0x7c, 0x05, 0xeb, 0x3a, 0x3d, 0xa3, 0xa6, + 0x1b, 0x50, 0x3d, 0x08, 0x2c, 0x1e, 0x45, 0xff, 0x2c, 0x6a, 0x49, 0xa9, 0xa8, 0xfa, 0x19, 0x94, + 0x91, 0xb3, 0x77, 0xd8, 0x9f, 0x1e, 0xe0, 0x7f, 0xdf, 0xb0, 0x1d, 0xe2, 0xb9, 0x83, 0x62, 0x84, + 0xa5, 0x55, 0x29, 0xf3, 0x3d, 0x98, 0xfc, 0x62, 0x9d, 0x41, 0x9a, 0x2d, 0x78, 0xa1, 0x67, 0xdb, + 0x7c, 0x63, 0x0f, 0x42, 0xc7, 0x64, 0xa4, 0x98, 0xba, 0x15, 0x4d, 0x7c, 0xd8, 0x0d, 0xe2, 0x87, + 0x43, 0x93, 0x11, 0xc9, 0x11, 0x53, 0x00, 0xf0, 0x54, 0xc8, 0x49, 0x25, 0xfa, 0xa3, 0xd1, 0xb8, + 0x0d, 0xbe, 0x8e, 0xdb, 0xe0, 0xfb, 0xb8, 0x0d, 0xbe, 0x1c, 0xb7, 0xc1, 0xe8, 0xb8, 0x0d, 0x5e, + 0x5c, 0x3f, 0xbd, 0x71, 0x96, 0xc6, 0x5d, 0x59, 0x9f, 0x55, 0x17, 0xbf, 0x92, 0x3b, 0x3f, 0x03, + 0x00, 0x00, 0xff, 0xff, 0xac, 0xa5, 0xe3, 0x1c, 0xb1, 0x06, 0x00, 0x00, +} diff --git a/txs/payload/permission_tx.go b/txs/payload/permission_tx.go index 9c219eecb..d22984f93 100644 --- a/txs/payload/permission_tx.go +++ b/txs/payload/permission_tx.go @@ -3,31 +3,26 @@ package payload import ( "fmt" - "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/acm/state" "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/permission/snatives" + "github.com/hyperledger/burrow/permission" ) -type PermissionsTx struct { - Input *TxInput - PermArgs snatives.PermArgs -} - -func NewPermissionsTx(st state.AccountGetter, from crypto.PublicKey, args snatives.PermArgs) (*PermissionsTx, error) { +func NewPermissionsTx(st state.AccountGetter, from crypto.PublicKey, args permission.PermArgs) (*PermissionsTx, error) { addr := from.Address() acc, err := st.GetAccount(addr) if err != nil { return nil, err } if acc == nil { - return nil, fmt.Errorf("Invalid address %s from pubkey %s", addr, from) + return nil, fmt.Errorf("invalid address %s from pubkey %s", addr, from) } sequence := acc.Sequence() + 1 return NewPermissionsTxWithSequence(from, args, sequence), nil } -func NewPermissionsTxWithSequence(from crypto.PublicKey, args snatives.PermArgs, sequence uint64) *PermissionsTx { +func NewPermissionsTxWithSequence(from crypto.PublicKey, args permission.PermArgs, sequence uint64) *PermissionsTx { input := &TxInput{ Address: from.Address(), Amount: 1, // NOTE: amounts can't be 0 ... diff --git a/txs/payload/send_tx.go b/txs/payload/send_tx.go index 12dd7a547..f83fcf953 100644 --- a/txs/payload/send_tx.go +++ b/txs/payload/send_tx.go @@ -3,15 +3,10 @@ package payload import ( "fmt" - "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/acm/state" "github.com/hyperledger/burrow/crypto" ) -type SendTx struct { - Inputs []*TxInput - Outputs []*TxOutput -} - func NewSendTx() *SendTx { return &SendTx{ Inputs: []*TxInput{}, diff --git a/txs/payload/tx_input.go b/txs/payload/tx_input.go index f435475f5..0a69fa2c4 100644 --- a/txs/payload/tx_input.go +++ b/txs/payload/tx_input.go @@ -6,12 +6,6 @@ import ( "github.com/hyperledger/burrow/crypto" ) -type TxInput struct { - Address crypto.Address - Amount uint64 - Sequence uint64 -} - func (txIn *TxInput) ValidateBasic() error { if txIn.Address == crypto.ZeroAddress { return ErrTxInvalidAddress @@ -23,5 +17,5 @@ func (txIn *TxInput) ValidateBasic() error { } func (txIn *TxInput) String() string { - return fmt.Sprintf("TxInput{%s, Amt: %v, Seq:%v}", txIn.Address, txIn.Amount, txIn.Sequence) + return fmt.Sprintf("TxInput{%s, Amount: %v, Sequence:%v}", txIn.Address, txIn.Amount, txIn.Sequence) } diff --git a/txs/payload/tx_output.go b/txs/payload/tx_output.go index 0dbd6c685..dcd6d73ce 100644 --- a/txs/payload/tx_output.go +++ b/txs/payload/tx_output.go @@ -2,15 +2,8 @@ package payload import ( "fmt" - - "github.com/hyperledger/burrow/crypto" ) -type TxOutput struct { - Address crypto.Address - Amount uint64 -} - func (txOut *TxOutput) ValidateBasic() error { if len(txOut.Address) != 20 { return ErrTxInvalidAddress @@ -22,5 +15,5 @@ func (txOut *TxOutput) ValidateBasic() error { } func (txOut *TxOutput) String() string { - return fmt.Sprintf("TxOutput{%s,%v}", txOut.Address, txOut.Amount) + return fmt.Sprintf("TxOutput{%s, Amount: %v}", txOut.Address, txOut.Amount) } diff --git a/txs/payload/unbond_tx.go b/txs/payload/unbond_tx.go index 9975d590c..c6fe036fa 100644 --- a/txs/payload/unbond_tx.go +++ b/txs/payload/unbond_tx.go @@ -6,15 +6,9 @@ import ( "github.com/hyperledger/burrow/crypto" ) -type UnbondTx struct { - Input *TxInput - Address crypto.Address - Height int -} - -func NewUnbondTx(addr crypto.Address, height int) *UnbondTx { +func NewUnbondTx(address crypto.Address, height uint64) *UnbondTx { return &UnbondTx{ - Address: addr, + Address: address, Height: height, } } diff --git a/txs/tx.go b/txs/tx.go index d099c892d..ee773c3cc 100644 --- a/txs/tx.go +++ b/txs/tx.go @@ -18,9 +18,10 @@ import ( "encoding/json" "fmt" - acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/crypto" + "github.com/hyperledger/burrow/event/query" "github.com/hyperledger/burrow/txs/payload" "golang.org/x/crypto/ripemd160" ) @@ -53,6 +54,7 @@ func (tx *Tx) Sign(signingAccounts ...acm.AddressableSigner) (*Envelope, error) if err != nil { return nil, err } + tx.Rehash() return env, nil } @@ -105,6 +107,34 @@ func (tx *Tx) UnmarshalJSON(data []byte) error { return json.Unmarshal(w.Payload, tx.Payload) } +// Protobuf support +func (tx *Tx) Marshal() ([]byte, error) { + if tx == nil { + return nil, nil + } + return tx.MarshalJSON() +} + +func (tx *Tx) Unmarshal(data []byte) error { + if len(data) == 0 { + return nil + } + return tx.UnmarshalJSON(data) +} + +func (tx *Tx) MarshalTo(data []byte) (int, error) { + bs, err := tx.Marshal() + if err != nil { + return 0, err + } + return copy(data, bs), nil +} + +func (tx *Tx) Size() int { + bs, _ := tx.Marshal() + return len(bs) +} + func (tx *Tx) Type() payload.Type { if tx == nil { return payload.TypeUnknown @@ -114,7 +144,7 @@ func (tx *Tx) Type() payload.Type { // Generate a Hash for this transaction based on the SignBytes. The hash is memoized over the lifetime // of the Tx so repeated calls to Hash() are effectively free -func (tx *Tx) Hash() []byte { +func (tx *Tx) Hash() binary.HexBytes { if tx == nil { return nil } @@ -139,17 +169,15 @@ func (tx *Tx) Rehash() []byte { return tx.txHash } -// BroadcastTx or Transaction receipt -type Receipt struct { - TxHash binary.HexBytes - CreatesContract bool - ContractAddress crypto.Address +func (tx *Tx) Tagged() query.Tagged { + return query.MergeTags(query.MustReflectTags(tx), query.MustReflectTags(tx.Payload)) } // Generate a transaction Receipt containing the Tx hash and other information if the Tx is call. // Returned by ABCI methods. func (tx *Tx) GenerateReceipt() *Receipt { receipt := &Receipt{ + TxType: tx.Type(), TxHash: tx.Hash(), } if callTx, ok := tx.Payload.(*payload.CallTx); ok { @@ -162,3 +190,18 @@ func (tx *Tx) GenerateReceipt() *Receipt { } return receipt } + +var cdc = NewAminoCodec() + +func DecodeReceipt(bs []byte) (*Receipt, error) { + receipt := new(Receipt) + err := cdc.UnmarshalBinary(bs, receipt) + if err != nil { + return nil, err + } + return receipt, nil +} + +func (receipt *Receipt) Encode() ([]byte, error) { + return cdc.MarshalBinary(receipt) +} diff --git a/txs/tx_test.go b/txs/tx_test.go index bb916e86a..4716bc28d 100644 --- a/txs/tx_test.go +++ b/txs/tx_test.go @@ -19,10 +19,12 @@ import ( "runtime/debug" "testing" - acm "github.com/hyperledger/burrow/account" + "fmt" + + "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/permission/snatives" - ptypes "github.com/hyperledger/burrow/permission/types" + "github.com/hyperledger/burrow/event/query" + "github.com/hyperledger/burrow/permission" "github.com/hyperledger/burrow/txs/payload" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -32,13 +34,13 @@ var chainID = "myChainID" var privateAccounts = make(map[crypto.Address]acm.AddressableSigner) -func makePrivateAccount(str string) acm.PrivateAccount { +func makePrivateAccount(str string) *acm.PrivateAccount { acc := acm.GeneratePrivateAccountFromSecret(str) privateAccounts[acc.Address()] = acc return acc } -func TestSendTxSignable(t *testing.T) { +func TestSendTx(t *testing.T) { sendTx := &payload.SendTx{ Inputs: []*payload.TxInput{ { @@ -65,6 +67,16 @@ func TestSendTxSignable(t *testing.T) { } testTxMarshalJSON(t, sendTx) testTxSignVerify(t, sendTx) + + tx := Enclose("Foo", sendTx).Tx + value, ok := tx.Tagged().Get("Inputs") + require.True(t, ok) + assert.Equal(t, fmt.Sprintf("%v%s%v", sendTx.Inputs[0], query.MultipleValueTagSeparator, sendTx.Inputs[1]), + value) + + value, ok = tx.Tagged().Get("ChainID") + require.True(t, ok) + assert.Equal(t, "Foo", value) } func TestCallTxSignable(t *testing.T) { @@ -147,7 +159,7 @@ func TestPermissionsTxSignable(t *testing.T) { Amount: 12345, Sequence: 250, }, - PermArgs: snatives.SetBaseArgs(makePrivateAccount("address1").Address(), 1, true), + PermArgs: permission.SetBaseArgs(makePrivateAccount("address1").Address(), 1, true), } testTxMarshalJSON(t, permsTx) @@ -169,11 +181,16 @@ func TestTxWrapper_MarshalJSON(t *testing.T) { } testTxMarshalJSON(t, callTx) testTxSignVerify(t, callTx) + + tx := Enclose("Foo", callTx).Tx + value, ok := tx.Tagged().Get("Input") + require.True(t, ok) + assert.Equal(t, callTx.Input.String(), value) } func TestNewPermissionsTxWithSequence(t *testing.T) { privateAccount := makePrivateAccount("shhhhh") - args := snatives.SetBaseArgs(privateAccount.PublicKey().Address(), ptypes.HasRole, true) + args := permission.SetBaseArgs(privateAccount.PublicKey().Address(), permission.HasRole, true) permTx := payload.NewPermissionsTxWithSequence(privateAccount.PublicKey(), args, 1) testTxMarshalJSON(t, permTx) testTxSignVerify(t, permTx) diff --git a/txs/txs.pb.go b/txs/txs.pb.go new file mode 100644 index 000000000..ba524fc45 --- /dev/null +++ b/txs/txs.pb.go @@ -0,0 +1,878 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: txs.proto + +/* + Package txs is a generated protocol buffer package. + + It is generated from these files: + txs.proto + + It has these top-level messages: + Envelope + Signatory + Receipt +*/ +package txs + +import proto "github.com/gogo/protobuf/proto" +import golang_proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" +import _ "github.com/gogo/protobuf/gogoproto" +import crypto "github.com/hyperledger/burrow/crypto" + +import github_com_hyperledger_burrow_crypto "github.com/hyperledger/burrow/crypto" +import github_com_hyperledger_burrow_txs_payload "github.com/hyperledger/burrow/txs/payload" +import github_com_hyperledger_burrow_binary "github.com/hyperledger/burrow/binary" + +import io "io" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = golang_proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package + +// An envelope contains both the signable Tx and the signatures for each input (in signatories) +type Envelope struct { + Signatories []Signatory `protobuf:"bytes,1,rep,name=Signatories" json:"Signatories"` + // Canonical bytes of the Tx ready to be signed + Tx *Tx `protobuf:"bytes,2,opt,name=Tx,proto3,customtype=Tx" json:"Tx,omitempty"` +} + +func (m *Envelope) Reset() { *m = Envelope{} } +func (*Envelope) ProtoMessage() {} +func (*Envelope) Descriptor() ([]byte, []int) { return fileDescriptorTxs, []int{0} } + +func (m *Envelope) GetSignatories() []Signatory { + if m != nil { + return m.Signatories + } + return nil +} + +func (*Envelope) XXX_MessageName() string { + return "txs.Envelope" +} + +// Signatory contains signature and one or both of Address and PublicKey to identify the signer +type Signatory struct { + Address *github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,1,opt,name=Address,proto3,customtype=github.com/hyperledger/burrow/crypto.Address" json:"Address,omitempty"` + PublicKey *crypto.PublicKey `protobuf:"bytes,2,opt,name=PublicKey" json:"PublicKey,omitempty"` + Signature github_com_hyperledger_burrow_crypto.Signature `protobuf:"bytes,3,opt,name=Signature,proto3,customtype=github.com/hyperledger/burrow/crypto.Signature" json:"Signature"` +} + +func (m *Signatory) Reset() { *m = Signatory{} } +func (m *Signatory) String() string { return proto.CompactTextString(m) } +func (*Signatory) ProtoMessage() {} +func (*Signatory) Descriptor() ([]byte, []int) { return fileDescriptorTxs, []int{1} } + +func (m *Signatory) GetPublicKey() *crypto.PublicKey { + if m != nil { + return m.PublicKey + } + return nil +} + +func (*Signatory) XXX_MessageName() string { + return "txs.Signatory" +} + +// BroadcastTx or Transaction receipt +type Receipt struct { + // Transaction type + TxType github_com_hyperledger_burrow_txs_payload.Type `protobuf:"varint,1,opt,name=TxType,proto3,casttype=github.com/hyperledger/burrow/txs/payload.Type" json:"TxType,omitempty"` + // The hash of the transaction that caused this event to be generated + TxHash github_com_hyperledger_burrow_binary.HexBytes `protobuf:"bytes,2,opt,name=TxHash,proto3,customtype=github.com/hyperledger/burrow/binary.HexBytes" json:"TxHash"` + // Whether the transaction creates a contract + CreatesContract bool `protobuf:"varint,3,opt,name=CreatesContract,proto3" json:"CreatesContract,omitempty"` + // The address of the contract being called + ContractAddress github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,4,opt,name=ContractAddress,proto3,customtype=github.com/hyperledger/burrow/crypto.Address" json:"ContractAddress"` +} + +func (m *Receipt) Reset() { *m = Receipt{} } +func (m *Receipt) String() string { return proto.CompactTextString(m) } +func (*Receipt) ProtoMessage() {} +func (*Receipt) Descriptor() ([]byte, []int) { return fileDescriptorTxs, []int{2} } + +func (m *Receipt) GetTxType() github_com_hyperledger_burrow_txs_payload.Type { + if m != nil { + return m.TxType + } + return 0 +} + +func (m *Receipt) GetCreatesContract() bool { + if m != nil { + return m.CreatesContract + } + return false +} + +func (*Receipt) XXX_MessageName() string { + return "txs.Receipt" +} +func init() { + proto.RegisterType((*Envelope)(nil), "txs.Envelope") + golang_proto.RegisterType((*Envelope)(nil), "txs.Envelope") + proto.RegisterType((*Signatory)(nil), "txs.Signatory") + golang_proto.RegisterType((*Signatory)(nil), "txs.Signatory") + proto.RegisterType((*Receipt)(nil), "txs.Receipt") + golang_proto.RegisterType((*Receipt)(nil), "txs.Receipt") +} +func (m *Envelope) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Envelope) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Signatories) > 0 { + for _, msg := range m.Signatories { + dAtA[i] = 0xa + i++ + i = encodeVarintTxs(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + if m.Tx != nil { + dAtA[i] = 0x12 + i++ + i = encodeVarintTxs(dAtA, i, uint64(m.Tx.Size())) + n1, err := m.Tx.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n1 + } + return i, nil +} + +func (m *Signatory) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Signatory) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.Address != nil { + dAtA[i] = 0xa + i++ + i = encodeVarintTxs(dAtA, i, uint64(m.Address.Size())) + n2, err := m.Address.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n2 + } + if m.PublicKey != nil { + dAtA[i] = 0x12 + i++ + i = encodeVarintTxs(dAtA, i, uint64(m.PublicKey.Size())) + n3, err := m.PublicKey.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n3 + } + dAtA[i] = 0x1a + i++ + i = encodeVarintTxs(dAtA, i, uint64(m.Signature.Size())) + n4, err := m.Signature.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n4 + return i, nil +} + +func (m *Receipt) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Receipt) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.TxType != 0 { + dAtA[i] = 0x8 + i++ + i = encodeVarintTxs(dAtA, i, uint64(m.TxType)) + } + dAtA[i] = 0x12 + i++ + i = encodeVarintTxs(dAtA, i, uint64(m.TxHash.Size())) + n5, err := m.TxHash.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n5 + if m.CreatesContract { + dAtA[i] = 0x18 + i++ + if m.CreatesContract { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i++ + } + dAtA[i] = 0x22 + i++ + i = encodeVarintTxs(dAtA, i, uint64(m.ContractAddress.Size())) + n6, err := m.ContractAddress.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n6 + return i, nil +} + +func encodeVarintTxs(dAtA []byte, offset int, v uint64) int { + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return offset + 1 +} +func (m *Envelope) Size() (n int) { + var l int + _ = l + if len(m.Signatories) > 0 { + for _, e := range m.Signatories { + l = e.Size() + n += 1 + l + sovTxs(uint64(l)) + } + } + if m.Tx != nil { + l = m.Tx.Size() + n += 1 + l + sovTxs(uint64(l)) + } + return n +} + +func (m *Signatory) Size() (n int) { + var l int + _ = l + if m.Address != nil { + l = m.Address.Size() + n += 1 + l + sovTxs(uint64(l)) + } + if m.PublicKey != nil { + l = m.PublicKey.Size() + n += 1 + l + sovTxs(uint64(l)) + } + l = m.Signature.Size() + n += 1 + l + sovTxs(uint64(l)) + return n +} + +func (m *Receipt) Size() (n int) { + var l int + _ = l + if m.TxType != 0 { + n += 1 + sovTxs(uint64(m.TxType)) + } + l = m.TxHash.Size() + n += 1 + l + sovTxs(uint64(l)) + if m.CreatesContract { + n += 2 + } + l = m.ContractAddress.Size() + n += 1 + l + sovTxs(uint64(l)) + return n +} + +func sovTxs(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n +} +func sozTxs(x uint64) (n int) { + return sovTxs(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Envelope) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTxs + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Envelope: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Envelope: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Signatories", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTxs + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTxs + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Signatories = append(m.Signatories, Signatory{}) + if err := m.Signatories[len(m.Signatories)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Tx", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTxs + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTxs + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + var v Tx + m.Tx = &v + if err := m.Tx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTxs(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTxs + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Signatory) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTxs + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Signatory: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Signatory: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTxs + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTxs + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + var v github_com_hyperledger_burrow_crypto.Address + m.Address = &v + if err := m.Address.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PublicKey", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTxs + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTxs + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.PublicKey == nil { + m.PublicKey = &crypto.PublicKey{} + } + if err := m.PublicKey.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Signature", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTxs + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTxs + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Signature.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTxs(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTxs + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Receipt) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTxs + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Receipt: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Receipt: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field TxType", wireType) + } + m.TxType = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTxs + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.TxType |= (github_com_hyperledger_burrow_txs_payload.Type(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TxHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTxs + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTxs + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.TxHash.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field CreatesContract", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTxs + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + m.CreatesContract = bool(v != 0) + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ContractAddress", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTxs + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTxs + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ContractAddress.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTxs(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTxs + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTxs(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTxs + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTxs + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTxs + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + iNdEx += length + if length < 0 { + return 0, ErrInvalidLengthTxs + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTxs + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipTxs(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} + +var ( + ErrInvalidLengthTxs = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTxs = fmt.Errorf("proto: integer overflow") +) + +func init() { proto.RegisterFile("txs.proto", fileDescriptorTxs) } +func init() { golang_proto.RegisterFile("txs.proto", fileDescriptorTxs) } + +var fileDescriptorTxs = []byte{ + // 422 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x92, 0xcf, 0x6e, 0xd4, 0x30, + 0x10, 0xc6, 0xeb, 0xec, 0x6a, 0xdb, 0xf5, 0x16, 0x2a, 0x7c, 0x40, 0xab, 0x1e, 0x92, 0xb2, 0xa7, + 0x3d, 0xd0, 0x04, 0x2d, 0x50, 0x24, 0x6e, 0xa4, 0x42, 0xaa, 0x8a, 0x90, 0x90, 0xc9, 0x89, 0x03, + 0x22, 0x7f, 0x86, 0x6c, 0xa4, 0x10, 0x47, 0xb6, 0x03, 0xf6, 0x9b, 0x70, 0xe4, 0x09, 0x78, 0x06, + 0x8e, 0x7b, 0xe4, 0xbc, 0x87, 0x08, 0x6d, 0xdf, 0x82, 0x13, 0x8a, 0x71, 0xb6, 0x55, 0x0f, 0x94, + 0xde, 0x3c, 0xf6, 0x7c, 0xbf, 0xf9, 0x66, 0xc6, 0x78, 0x2c, 0x95, 0xf0, 0x6b, 0xce, 0x24, 0x23, + 0x03, 0xa9, 0xc4, 0xe1, 0x71, 0x5e, 0xc8, 0x65, 0x93, 0xf8, 0x29, 0xfb, 0x14, 0xe4, 0x2c, 0x67, + 0x81, 0x79, 0x4b, 0x9a, 0x8f, 0x26, 0x32, 0x81, 0x39, 0xfd, 0xd5, 0x1c, 0xee, 0xa7, 0x5c, 0xd7, + 0xd2, 0x46, 0xb3, 0x0f, 0x78, 0xef, 0x65, 0xf5, 0x19, 0x4a, 0x56, 0x03, 0x39, 0xc1, 0x93, 0xb7, + 0x45, 0x5e, 0xc5, 0x92, 0xf1, 0x02, 0xc4, 0x14, 0x1d, 0x0d, 0xe6, 0x93, 0xc5, 0x5d, 0xbf, 0x2b, + 0xd7, 0xdf, 0xeb, 0x70, 0xb8, 0x6a, 0xbd, 0x1d, 0x7a, 0x35, 0x91, 0xdc, 0xc7, 0x4e, 0xa4, 0xa6, + 0xce, 0x11, 0x9a, 0xef, 0x87, 0xa3, 0x75, 0xeb, 0x39, 0x91, 0xa2, 0x4e, 0xa4, 0x9e, 0x0f, 0xbf, + 0x7e, 0xf3, 0x76, 0x66, 0x2d, 0xc2, 0xe3, 0xad, 0x9c, 0x9c, 0xe3, 0xdd, 0x17, 0x59, 0xc6, 0x41, + 0x74, 0xfc, 0x4e, 0xf0, 0x68, 0xdd, 0x7a, 0x0f, 0xaf, 0x74, 0xb0, 0xd4, 0x35, 0xf0, 0x12, 0xb2, + 0x1c, 0x78, 0x90, 0x34, 0x9c, 0xb3, 0x2f, 0x81, 0x35, 0x6c, 0x75, 0xb4, 0x07, 0x90, 0x00, 0x8f, + 0xdf, 0x34, 0x49, 0x59, 0xa4, 0xaf, 0x40, 0x9b, 0xf2, 0x93, 0xc5, 0x3d, 0xdf, 0x26, 0x6f, 0x1f, + 0xe8, 0x65, 0x0e, 0x89, 0x7a, 0x27, 0x0d, 0x87, 0xe9, 0xc0, 0x94, 0x3f, 0xe9, 0xda, 0x59, 0xb7, + 0x9e, 0xff, 0x5f, 0x16, 0xb6, 0x6a, 0x7a, 0x09, 0x9a, 0x7d, 0x77, 0xf0, 0x2e, 0x85, 0x14, 0x8a, + 0x5a, 0x92, 0x73, 0x3c, 0x8a, 0x54, 0xa4, 0x6b, 0x30, 0xdd, 0xdd, 0x09, 0x17, 0xbf, 0x6f, 0x44, + 0x4b, 0x25, 0x82, 0x3a, 0xd6, 0x25, 0x8b, 0x33, 0xbf, 0x53, 0x52, 0x4b, 0x20, 0xaf, 0x3b, 0xd6, + 0x59, 0x2c, 0x96, 0x76, 0xb4, 0x4f, 0xad, 0xd5, 0xe3, 0x7f, 0xf3, 0x92, 0xa2, 0x8a, 0xb9, 0xf6, + 0xcf, 0x40, 0x85, 0x5a, 0x82, 0xa0, 0x16, 0x42, 0xe6, 0xf8, 0xe0, 0x94, 0x43, 0x2c, 0x41, 0x9c, + 0xb2, 0x4a, 0xf2, 0x38, 0x95, 0x66, 0x04, 0x7b, 0xf4, 0xfa, 0x35, 0x79, 0x8f, 0x0f, 0xfa, 0x73, + 0xbf, 0xab, 0xa1, 0x71, 0xf0, 0xc4, 0x3a, 0xb8, 0xdd, 0xbe, 0xae, 0xc3, 0xc2, 0x67, 0xab, 0x8d, + 0x8b, 0x7e, 0x6e, 0x5c, 0xf4, 0x6b, 0xe3, 0xa2, 0x1f, 0x17, 0x2e, 0x5a, 0x5d, 0xb8, 0xe8, 0xdd, + 0x83, 0x1b, 0xc7, 0x94, 0x8c, 0xcc, 0x9f, 0x7d, 0xfc, 0x27, 0x00, 0x00, 0xff, 0xff, 0xcd, 0x2f, + 0x9b, 0x0b, 0x02, 0x03, 0x00, 0x00, +} From ae45563e713f1e02b86a508c07cee17b915b1f71 Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Wed, 18 Jul 2018 18:16:34 +0100 Subject: [PATCH 12/28] Update CI image and add commands to Makefile Signed-off-by: Silas Davis --- .circleci/Dockerfile | 4 ++-- Dockerfile | 12 ++++++------ Makefile | 14 +++++++++++++- rpc/config.go | 2 +- 4 files changed, 22 insertions(+), 10 deletions(-) diff --git a/.circleci/Dockerfile b/.circleci/Dockerfile index 62926585e..b5e2b325d 100644 --- a/.circleci/Dockerfile +++ b/.circleci/Dockerfile @@ -1,11 +1,11 @@ # docker build -t quay.io/monax/build:burrow-ci . -FROM golang:1.10.1-alpine3.7 +FROM golang:1.10.3-alpine3.8 MAINTAINER Monax ENV DOCKER_VERSION "17.12.1-ce" # This is the image used by the Circle CI config in this directory pushed to quay.io/monax/bosmarmot:ci # docker build -t quay.io/monax/build:burrow-ci -f ./.circleci/Dockerfile . -RUN apk add --update --no-cache nodejs netcat-openbsd git openssh-client openssl make bash gcc g++ jq curl +RUN apk add --update --no-cache nodejs npm netcat-openbsd git openssh-client openssl make bash gcc g++ jq curl # get docker client RUN curl -L -o /tmp/docker-$DOCKER_VERSION.tgz https://download.docker.com/linux/static/stable/x86_64/docker-$DOCKER_VERSION.tgz \ && tar -xz -C /tmp -f /tmp/docker-$DOCKER_VERSION.tgz \ diff --git a/Dockerfile b/Dockerfile index edb83bbcf..77186ef57 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,5 @@ # We use a multistage build to avoid bloating our deployment image with build dependencies -FROM golang:1.10.1-alpine3.7 as builder +FROM golang:1.10.3-alpine3.8 as builder MAINTAINER Monax RUN apk add --no-cache --update git bash make @@ -12,7 +12,7 @@ WORKDIR $REPO RUN make build # This will be our base container image -FROM alpine:3.7 +FROM alpine:3.8 ARG REPO=/go/src/github.com/hyperledger/burrow @@ -26,9 +26,9 @@ USER $USER:$USER COPY --from=builder $REPO/bin/* /usr/local/bin/ #RUN chown $USER:$USER /usr/local/bin/burrow* -# Expose ports for 1337:burrow API; 46656:tendermint-peer; 46657:tendermint-rpc -EXPOSE 1337 -EXPOSE 46656 -EXPOSE 46657 +# Expose ports for 26656:tendermint-peer; 26658: tm; 10997 GRPC +EXPOSE 26656 +EXPOSE 26658 +EXPOSE 10997 CMD [ "burrow" ] diff --git a/Makefile b/Makefile index ffa4a8d41..fcc9956dd 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,6 @@ # REQUIREMENTS # - go installed locally -# - for build_docker: docker installed locally # ---------------------------------------------------------- @@ -24,6 +23,8 @@ PROTO_GO_FILES_REAL = $(shell find . -path ./vendor -prune -o -type f -name '*.p SOLIDITY_FILES = $(shell find . -path ./vendor -prune -o -type f -name '*.sol' -print) SOLIDITY_GO_FILES = $(patsubst %.sol, %.sol.go, $(SOLIDITY_FILES)) +CI_IMAGE="quay.io/monax/build:burrow-ci" + ### Formatting, linting and vetting # check the code for style standards; currently enforces go formatting. @@ -230,3 +231,14 @@ docs: CHANGELOG.md NOTES.md tag_release: test check CHANGELOG.md NOTES.md build @scripts/tag_release.sh +.PHONY: docker_build_ci_rebuild +docker_build_ci_rebuild: + docker build --no-cache -t ${CI_IMAGE} -f ./.circleci/Dockerfile . + +.PHONY: docker_build_ci +docker_build_ci: + docker build -t ${CI_IMAGE} -f ./.circleci/Dockerfile . + +.PHONY: docker_push_ci +docker_push_ci: docker_build_ci + docker push ${CI_IMAGE} diff --git a/rpc/config.go b/rpc/config.go index ef5095817..44acb5555 100644 --- a/rpc/config.go +++ b/rpc/config.go @@ -41,7 +41,7 @@ func DefaultRPCConfig() *RPCConfig { func DefaultTMConfig() *ServerConfig { return &ServerConfig{ Enabled: true, - ListenAddress: "tcp://localhost:46657", + ListenAddress: "tcp://localhost:26658", } } From c7a21b9dffd77a9c49c8d38e53f4f4efc24386e6 Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Fri, 20 Jul 2018 10:24:32 +0100 Subject: [PATCH 13/28] Remove redundant validation, allow 0 amount inputs, code payload errors and prevent SendTx overpayment Signed-off-by: Silas Davis --- execution/errors/errors.go | 22 +++++++++++++++++++++ execution/errors/errors_test.go | 8 +++++++- execution/executors/call_context.go | 6 +++--- execution/executors/name_context.go | 4 ++-- execution/executors/permissions_context.go | 3 ++- execution/executors/send_context.go | 9 ++++++++- execution/executors/shared.go | 21 +++++++------------- txs/payload/errors.go | 23 ++++++++++------------ txs/payload/tx_input.go | 12 ----------- txs/payload/tx_output.go | 10 ---------- 10 files changed, 61 insertions(+), 57 deletions(-) diff --git a/execution/errors/errors.go b/execution/errors/errors.go index 8e3bd2cc1..b3bc55416 100644 --- a/execution/errors/errors.go +++ b/execution/errors/errors.go @@ -32,6 +32,12 @@ const ( ErrorCodeEventPublish ErrorCodeInvalidString ErrorCodeEventMapping + ErrorCodeInvalidAddress + ErrorCodeDuplicateAddress + ErrorCodeInsufficientFunds + ErrorCodeOverpayment + ErrorCodeZeroPayment + ErrorCodeInvalidSequence ) func (c Code) ErrorCode() Code { @@ -39,6 +45,10 @@ func (c Code) ErrorCode() Code { } func (c Code) Error() string { + return fmt.Sprintf("Error %d: %s", c, c.String()) +} + +func (c Code) String() string { switch c { case ErrorCodeUnknownAddress: return "Unknown address" @@ -82,6 +92,18 @@ func (c Code) Error() string { return "Event mapping error" case ErrorCodeGeneric: return "Generic error" + case ErrorCodeInvalidAddress: + return "Invalid address" + case ErrorCodeDuplicateAddress: + return "Duplicate address" + case ErrorCodeInsufficientFunds: + return "Insufficient funds" + case ErrorCodeOverpayment: + return "Overpayment" + case ErrorCodeZeroPayment: + return "Zero payment error" + case ErrorCodeInvalidSequence: + return "Invalid sequence number" default: return "Unknown error" } diff --git a/execution/errors/errors_test.go b/execution/errors/errors_test.go index 2a4a0a37b..c80c05722 100644 --- a/execution/errors/errors_test.go +++ b/execution/errors/errors_test.go @@ -2,6 +2,7 @@ package errors import ( "encoding/json" + "fmt" "testing" "github.com/stretchr/testify/assert" @@ -9,7 +10,7 @@ import ( ) func TestErrorCode_MarshalJSON(t *testing.T) { - ec := NewCodedError(ErrorCodeDataStackOverflow, "arrg") + ec := NewCodedError(ErrorCodeDataStackOverflow, "arrgh") bs, err := json.Marshal(ec) require.NoError(t, err) @@ -19,3 +20,8 @@ func TestErrorCode_MarshalJSON(t *testing.T) { assert.Equal(t, ec, ecOut) } + +func TestCode_String(t *testing.T) { + err := ErrorCodeCodeOutOfBounds + fmt.Println(err.Error()) +} diff --git a/execution/executors/call_context.go b/execution/executors/call_context.go index 78fa25e4a..0f343819c 100644 --- a/execution/executors/call_context.go +++ b/execution/executors/call_context.go @@ -58,7 +58,7 @@ func (ctx *CallContext) Precheck() (*acm.MutableAccount, acm.Account, error) { if inAcc == nil { ctx.Logger.InfoMsg("Cannot find input account", "tx_input", ctx.tx.Input) - return nil, nil, payload.ErrTxInvalidAddress + return nil, nil, errors.ErrorCodeInvalidAddress } err = validateInput(inAcc, ctx.tx.Input) @@ -70,7 +70,7 @@ func (ctx *CallContext) Precheck() (*acm.MutableAccount, acm.Account, error) { if ctx.tx.Input.Amount < ctx.tx.Fee { ctx.Logger.InfoMsg("Sender did not send enough to cover the fee", "tx_input", ctx.tx.Input) - return nil, nil, payload.ErrTxInsufficientFunds + return nil, nil, errors.ErrorCodeInsufficientFunds } ctx.Logger.TraceMsg("Incrementing sequence number for CallTx", @@ -191,7 +191,7 @@ func (ctx *CallContext) Deliver(inAcc, outAcc acm.Account, value uint64) error { "caller_address", inAcc.Address(), "callee_address", ctx.tx.Address) } - ctx.CallEvents(payload.ErrTxInvalidAddress) + ctx.CallEvents(errors.ErrorCodeInvalidAddress) return nil } callee = acm.AsMutableAccount(outAcc) diff --git a/execution/executors/name_context.go b/execution/executors/name_context.go index ce8396704..3be220f9f 100644 --- a/execution/executors/name_context.go +++ b/execution/executors/name_context.go @@ -42,7 +42,7 @@ func (ctx *NameContext) Execute(txe *exec.TxExecution) error { if inAcc == nil { ctx.Logger.InfoMsg("Cannot find input account", "tx_input", ctx.tx.Input) - return payload.ErrTxInvalidAddress + return errors.ErrorCodeInvalidAddress } // check permission if !hasNamePermission(ctx.StateWriter, inAcc, ctx.Logger) { @@ -57,7 +57,7 @@ func (ctx *NameContext) Execute(txe *exec.TxExecution) error { if ctx.tx.Input.Amount < ctx.tx.Fee { ctx.Logger.InfoMsg("Sender did not send enough to cover the fee", "tx_input", ctx.tx.Input) - return payload.ErrTxInsufficientFunds + return errors.ErrorCodeInsufficientFunds } // validate the input strings diff --git a/execution/executors/permissions_context.go b/execution/executors/permissions_context.go index 39292a3b0..11730e137 100644 --- a/execution/executors/permissions_context.go +++ b/execution/executors/permissions_context.go @@ -7,6 +7,7 @@ import ( "github.com/hyperledger/burrow/acm/state" "github.com/hyperledger/burrow/blockchain" "github.com/hyperledger/burrow/crypto" + "github.com/hyperledger/burrow/execution/errors" "github.com/hyperledger/burrow/execution/exec" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" @@ -35,7 +36,7 @@ func (ctx *PermissionsContext) Execute(txe *exec.TxExecution) error { if inAcc == nil { ctx.Logger.InfoMsg("Cannot find input account", "tx_input", ctx.tx.Input) - return payload.ErrTxInvalidAddress + return errors.ErrorCodeInvalidAddress } err = ctx.tx.PermArgs.EnsureValid() diff --git a/execution/executors/send_context.go b/execution/executors/send_context.go index 5cad86303..813a433bf 100644 --- a/execution/executors/send_context.go +++ b/execution/executors/send_context.go @@ -5,6 +5,7 @@ import ( "github.com/hyperledger/burrow/acm/state" "github.com/hyperledger/burrow/blockchain" + "github.com/hyperledger/burrow/execution/errors" "github.com/hyperledger/burrow/execution/exec" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/txs/payload" @@ -49,7 +50,13 @@ func (ctx *SendContext) Execute(txe *exec.TxExecution) error { return err } if outTotal > inTotal { - return payload.ErrTxInsufficientFunds + return errors.ErrorCodeInsufficientFunds + } + if outTotal < inTotal { + return errors.ErrorCodeOverpayment + } + if outTotal == 0 { + return errors.ErrorCodeZeroPayment } // Good! Adjust accounts diff --git a/execution/executors/shared.go b/execution/executors/shared.go index 58904bb98..33ad90a0d 100644 --- a/execution/executors/shared.go +++ b/execution/executors/shared.go @@ -6,6 +6,7 @@ import ( "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/acm/state" "github.com/hyperledger/burrow/crypto" + "github.com/hyperledger/burrow/execution/errors" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" "github.com/hyperledger/burrow/permission" @@ -23,14 +24,14 @@ func getInputs(accountGetter state.AccountGetter, for _, in := range ins { // Account shouldn't be duplicated if _, ok := accounts[in.Address]; ok { - return nil, payload.ErrTxDuplicateAddress + return nil, errors.ErrorCodeDuplicateAddress } acc, err := state.GetMutableAccount(accountGetter, in.Address) if err != nil { return nil, err } if acc == nil { - return nil, payload.ErrTxInvalidAddress + return nil, errors.ErrorCodeInvalidAddress } accounts[in.Address] = acc } @@ -48,7 +49,7 @@ func getOrMakeOutputs(accountGetter state.AccountGetter, accs map[crypto.Address for _, out := range outs { // Account shouldn't be duplicated if _, ok := accs[out.Address]; ok { - return nil, payload.ErrTxDuplicateAddress + return nil, errors.ErrorCodeDuplicateAddress } acc, err := state.GetMutableAccount(accountGetter, out.Address) if err != nil { @@ -92,20 +93,16 @@ func validateInputs(accs map[crypto.Address]*acm.MutableAccount, ins []*payload. } func validateInput(acc *acm.MutableAccount, in *payload.TxInput) error { - // Check TxInput basic - if err := in.ValidateBasic(); err != nil { - return err - } // Check sequences if acc.Sequence()+1 != uint64(in.Sequence) { return payload.ErrTxInvalidSequence{ - Got: in.Sequence, - Expected: acc.Sequence() + uint64(1), + Input: in, + Account: acc, } } // Check amount if acc.Balance() < uint64(in.Amount) { - return payload.ErrTxInsufficientFunds + return errors.ErrorCodeInsufficientFunds } return nil } @@ -113,10 +110,6 @@ func validateInput(acc *acm.MutableAccount, in *payload.TxInput) error { func validateOutputs(outs []*payload.TxOutput) (uint64, error) { total := uint64(0) for _, out := range outs { - // Check TxOutput basic - if err := out.ValidateBasic(); err != nil { - return 0, err - } // Good. Add amount to total total += out.Amount } diff --git a/txs/payload/errors.go b/txs/payload/errors.go index affd56437..0c056c4f3 100644 --- a/txs/payload/errors.go +++ b/txs/payload/errors.go @@ -1,25 +1,22 @@ package payload import ( - "errors" "fmt" -) -var ( - ErrTxInvalidAddress = errors.New("error invalid address") - ErrTxDuplicateAddress = errors.New("error duplicate address") - ErrTxInvalidAmount = errors.New("error invalid amount") - ErrTxInsufficientFunds = errors.New("error insufficient funds") - ErrTxUnknownPubKey = errors.New("error unknown pubkey") - ErrTxInvalidPubKey = errors.New("error invalid pubkey") - ErrTxInvalidSignature = errors.New("error invalid signature") + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/execution/errors" ) type ErrTxInvalidSequence struct { - Got uint64 - Expected uint64 + Input *TxInput + Account acm.Account } func (e ErrTxInvalidSequence) Error() string { - return fmt.Sprintf("Error invalid sequence. Got %d, expected %d", e.Got, e.Expected) + return fmt.Sprintf("Error invalid sequence in input %v: input has sequence %d, but account has expected "+ + "%d, so expected input to have sequence %d", e.Input, e.Input.Sequence, e.Account.Sequence(), e.Account.Sequence()+1) +} + +func (e ErrTxInvalidSequence) ErrorCode() errors.Code { + return errors.ErrorCodeInvalidSequence } diff --git a/txs/payload/tx_input.go b/txs/payload/tx_input.go index 0a69fa2c4..ff02d7cf9 100644 --- a/txs/payload/tx_input.go +++ b/txs/payload/tx_input.go @@ -2,20 +2,8 @@ package payload import ( "fmt" - - "github.com/hyperledger/burrow/crypto" ) -func (txIn *TxInput) ValidateBasic() error { - if txIn.Address == crypto.ZeroAddress { - return ErrTxInvalidAddress - } - if txIn.Amount == 0 { - return ErrTxInvalidAmount - } - return nil -} - func (txIn *TxInput) String() string { return fmt.Sprintf("TxInput{%s, Amount: %v, Sequence:%v}", txIn.Address, txIn.Amount, txIn.Sequence) } diff --git a/txs/payload/tx_output.go b/txs/payload/tx_output.go index dcd6d73ce..f32a29f7a 100644 --- a/txs/payload/tx_output.go +++ b/txs/payload/tx_output.go @@ -4,16 +4,6 @@ import ( "fmt" ) -func (txOut *TxOutput) ValidateBasic() error { - if len(txOut.Address) != 20 { - return ErrTxInvalidAddress - } - if txOut.Amount == 0 { - return ErrTxInvalidAmount - } - return nil -} - func (txOut *TxOutput) String() string { return fmt.Sprintf("TxOutput{%s, Amount: %v}", txOut.Address, txOut.Amount) } From 7b8e4cde2442c6c8098a60aa32b2ac99cac0fee9 Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Thu, 19 Jul 2018 00:33:13 +0100 Subject: [PATCH 14/28] Implemented GovernanceContext to implement GovernanceTX used ValidatorRing to control validator power flow Signed-off-by: Silas Davis --- acm/account.go | 25 +- acm/private_account.go | 2 +- acm/validator.go | 2 +- blockchain/blockchain.go | 74 ++-- blockchain/blockchain_test.go | 46 +++ blockchain/validators.go | 213 ++++++---- blockchain/validators_ring.go | 198 +++++++++ blockchain/validators_ring_test.go | 121 ++++++ blockchain/validators_test.go | 39 +- blockchain/validators_window.go | 64 --- cmd/burrow/commands/configure.go | 2 +- consensus/tendermint/abci/app.go | 81 ++-- .../validator/priv_validator_memory.go | 5 +- core/kernel.go | 5 +- crypto/address.go | 34 ++ crypto/crypto.go | 10 + crypto/crypto.pb.go | 62 +-- crypto/private_key.go | 22 +- crypto/public_key.go | 58 +-- .../{executors => contexts}/call_context.go | 2 +- execution/contexts/governance_context.go | 130 ++++++ .../{executors => contexts}/name_context.go | 2 +- .../permissions_context.go | 2 +- .../{executors => contexts}/send_context.go | 5 +- execution/{executors => contexts}/shared.go | 8 +- execution/evm/snative.go | 13 +- execution/exec/event.go | 2 + execution/exec/exec.pb.go | 390 +++++++++++++----- execution/exec/govern_account_event.go | 1 + execution/exec/tx_execution.go | 14 +- execution/execution.go | 57 ++- execution/execution_test.go | 22 +- execution/simulated_call.go | 4 +- execution/transactor_test.go | 2 +- genesis/deterministic_genesis.go | 2 +- genesis/genesis.go | 6 +- genesis/spec/genesis_spec.go | 2 +- genesis/spec/template_account.go | 2 +- integration/governance/main_test.go | 47 +++ integration/governance/validators_test.go | 7 + integration/integration.go | 13 +- integration/rpcevents/main_test.go | 18 +- integration/rpcquery/main_test.go | 18 +- integration/rpctransact/main_test.go | 18 +- integration/tm/main_test.go | 17 +- keys/server.go | 4 +- permission/perm_flag.go | 5 + protobuf/crypto.proto | 4 +- protobuf/exec.proto | 33 +- rpc/service.go | 9 +- txs/payload/governance_tx.go | 27 -- 51 files changed, 1377 insertions(+), 572 deletions(-) create mode 100644 blockchain/blockchain_test.go create mode 100644 blockchain/validators_ring.go create mode 100644 blockchain/validators_ring_test.go delete mode 100644 blockchain/validators_window.go rename execution/{executors => contexts}/call_context.go (99%) create mode 100644 execution/contexts/governance_context.go rename execution/{executors => contexts}/name_context.go (99%) rename execution/{executors => contexts}/permissions_context.go (99%) rename execution/{executors => contexts}/send_context.go (93%) rename execution/{executors => contexts}/shared.go (96%) create mode 100644 execution/exec/govern_account_event.go create mode 100644 integration/governance/main_test.go create mode 100644 integration/governance/validators_test.go diff --git a/acm/account.go b/acm/account.go index 4c3b11700..73d1a0a38 100644 --- a/acm/account.go +++ b/acm/account.go @@ -27,16 +27,9 @@ import ( var GlobalPermissionsAddress = crypto.Address(binary.Zero160) -type Addressable interface { - // Get the 20 byte EVM address of this account - Address() crypto.Address - // Public key from which the Address is derived - PublicKey() crypto.PublicKey -} - // The default immutable interface to an account type Account interface { - Addressable + crypto.Addressable // The value held by this account in terms of the chain-native token Balance() uint64 // The EVM byte code held by this account (or equivalently, this contract) @@ -117,7 +110,7 @@ func AsConcreteAccount(account Account) *ConcreteAccount { } // Creates an otherwise zeroed Account from an Addressable and returns it as MutableAccount -func FromAddressable(addressable Addressable) *MutableAccount { +func FromAddressable(addressable crypto.Addressable) *MutableAccount { ca := &ConcreteAccount{ Address: addressable.Address(), PublicKey: addressable.PublicKey(), @@ -138,6 +131,8 @@ func AsMutableAccount(account Account) *MutableAccount { return AsConcreteAccount(account).MutableAccount() } +var _ Account = &MutableAccount{} + func (acc ConcreteAccount) String() string { return fmt.Sprintf("ConcreteAccount{Address: %s; Sequence: %v; PublicKey: %v Balance: %v; CodeLength: %v; Permissions: %s}", acc.Address, acc.Sequence, acc.PublicKey, acc.Balance, len(acc.Code), acc.Permissions) @@ -177,6 +172,11 @@ func (acc *MutableAccount) AddToBalance(amount uint64) error { return nil } +func (acc *MutableAccount) SetBalance(amount uint64) error { + acc.concreteAccount.Balance = amount + return nil +} + func (acc *MutableAccount) SetCode(code []byte) error { acc.concreteAccount.Code = code return nil @@ -186,8 +186,11 @@ func (acc *MutableAccount) IncSequence() { acc.concreteAccount.Sequence++ } -func (acc *MutableAccount) SetPermissions(permissions permission.AccountPermissions) error { - acc.concreteAccount.Permissions = permissions +func (acc *MutableAccount) SetPermissions(accPerms permission.AccountPermissions) error { + if !accPerms.Base.Perms.IsValid() { + return fmt.Errorf("attempt to set invalid perm 0%b on account %v", accPerms.Base.Perms, acc) + } + acc.concreteAccount.Permissions = accPerms return nil } diff --git a/acm/private_account.go b/acm/private_account.go index f9cf705d5..f6f80ba33 100644 --- a/acm/private_account.go +++ b/acm/private_account.go @@ -23,7 +23,7 @@ import ( ) type AddressableSigner interface { - Addressable + crypto.Addressable crypto.Signer } diff --git a/acm/validator.go b/acm/validator.go index 51027539d..ddf471ecd 100644 --- a/acm/validator.go +++ b/acm/validator.go @@ -7,7 +7,7 @@ import ( ) type Validator interface { - Addressable + crypto.Addressable // The validator's voting power Power() uint64 } diff --git a/blockchain/blockchain.go b/blockchain/blockchain.go index 2d1f3553f..4d8e2c942 100644 --- a/blockchain/blockchain.go +++ b/blockchain/blockchain.go @@ -16,15 +16,15 @@ package blockchain import ( "bytes" - "encoding/json" "fmt" - "time" - + "math/big" "sync" + "time" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/genesis" "github.com/hyperledger/burrow/logging" + "github.com/tendermint/go-amino" dbm "github.com/tendermint/tmlibs/db" ) @@ -39,7 +39,7 @@ type TipInfo interface { LastBlockTime() time.Time LastBlockHash() []byte AppHashAfterLastBlock() []byte - IterateValidators(iter func(publicKey crypto.PublicKey, power uint64) (stop bool)) (stopped bool) + IterateValidators(iter func(id crypto.Addressable, power *big.Int) (stop bool)) (stopped bool) NumValidators() int } @@ -60,8 +60,7 @@ type Tip struct { lastBlockTime time.Time lastBlockHash []byte appHashAfterLastBlock []byte - validators Validators - validatorsWindow ValidatorsWindow + validators *ValidatorsRing } type Blockchain struct { @@ -71,10 +70,13 @@ type Blockchain struct { db dbm.DB } +var _ TipInfo = &Blockchain{} + type PersistedState struct { AppHashAfterLastBlock []byte LastBlockHeight uint64 GenesisDoc genesis.GenesisDoc + Validators PersistedValidatorsRing } func LoadOrNewBlockchain(db dbm.DB, genesisDoc *genesis.GenesisDoc, @@ -103,13 +105,15 @@ func LoadOrNewBlockchain(db dbm.DB, genesisDoc *genesis.GenesisDoc, // Pointer to blockchain state initialised from genesis func newBlockchain(db dbm.DB, genesisDoc *genesis.GenesisDoc) *Blockchain { + vs := NewValidators() + for _, gv := range genesisDoc.Validators { + vs.AlterPower(gv.PublicKey, new(big.Int).SetUint64(gv.Amount)) + } + root := NewRoot(genesisDoc) bc := &Blockchain{ db: db, - Root: NewRoot(genesisDoc), - Tip: NewTip(genesisDoc.ChainID(), NewRoot(genesisDoc).genesisDoc.GenesisTime, NewRoot(genesisDoc).genesisHash), - } - for _, gv := range genesisDoc.Validators { - bc.validators.AlterPower(gv.PublicKey, gv.Amount) + Root: root, + Tip: NewTip(genesisDoc.ChainID(), root.genesisDoc.GenesisTime, root.genesisHash, vs), } return bc } @@ -119,13 +123,11 @@ func loadBlockchain(db dbm.DB) (*Blockchain, error) { if len(buf) == 0 { return nil, nil } - persistedState, err := Decode(buf) + bc, err := DecodeBlockchain(buf) if err != nil { return nil, err } - bc := newBlockchain(db, &persistedState.GenesisDoc) - bc.lastBlockHeight = persistedState.LastBlockHeight - bc.appHashAfterLastBlock = persistedState.AppHashAfterLastBlock + bc.db = db return bc, nil } @@ -137,16 +139,19 @@ func NewRoot(genesisDoc *genesis.GenesisDoc) *Root { } // Create genesis Tip -func NewTip(chainID string, genesisTime time.Time, genesisHash []byte) *Tip { +func NewTip(chainID string, genesisTime time.Time, genesisHash []byte, initialValidators *Validators) *Tip { return &Tip{ chainID: chainID, lastBlockTime: genesisTime, appHashAfterLastBlock: genesisHash, - validators: NewValidators(), - validatorsWindow: NewValidatorsWindow(DefaultValidatorsWindowSize), + validators: NewValidatorsRing(initialValidators, DefaultValidatorsWindowSize), } } +func (bc *Blockchain) AlterPower(id crypto.Addressable, power *big.Int) (*big.Int, error) { + return bc.validators.AlterPower(id, power) +} + func (bc *Blockchain) CommitBlock(blockTime time.Time, blockHash, appHash []byte) error { bc.Lock() defer bc.Unlock() @@ -157,6 +162,14 @@ func (bc *Blockchain) CommitBlock(blockTime time.Time, blockHash, appHash []byte if err != nil { return err } + maxFlow := bc.validators.MaxFlow() + // Update validator set + _, totalFlow := bc.validators.Rotate() + if totalFlow.Cmp(maxFlow) == 1 { + return fmt.Errorf("total flow during block was %v exceeding the maximum allowablw flow of %v - this "+ + "should have been prevented on a per transaction basis - we cannot continue", + totalFlow, maxFlow) + } bc.lastBlockHeight += 1 bc.lastBlockTime = blockTime bc.lastBlockHash = blockHash @@ -175,26 +188,33 @@ func (bc *Blockchain) save() error { return nil } +var cdc = amino.NewCodec() + func (bc *Blockchain) Encode() ([]byte, error) { persistedState := &PersistedState{ GenesisDoc: bc.genesisDoc, AppHashAfterLastBlock: bc.appHashAfterLastBlock, LastBlockHeight: bc.lastBlockHeight, + Validators: bc.validators.Persistable(), } - encodedState, err := json.Marshal(persistedState) + encodedState, err := cdc.MarshalBinary(persistedState) if err != nil { return nil, err } return encodedState, nil } -func Decode(encodedState []byte) (*PersistedState, error) { +func DecodeBlockchain(encodedState []byte) (*Blockchain, error) { persistedState := new(PersistedState) - err := json.Unmarshal(encodedState, persistedState) + err := cdc.UnmarshalBinary(encodedState, persistedState) if err != nil { return nil, err } - return persistedState, nil + bc := newBlockchain(nil, &persistedState.GenesisDoc) + bc.lastBlockHeight = persistedState.LastBlockHeight + bc.appHashAfterLastBlock = persistedState.AppHashAfterLastBlock + bc.validators = UnpersistValidatorsRing(persistedState.Validators) + return bc, nil } func (r *Root) GenesisHash() []byte { @@ -225,10 +245,14 @@ func (t *Tip) AppHashAfterLastBlock() []byte { return t.appHashAfterLastBlock } -func (t *Tip) IterateValidators(iter func(publicKey crypto.PublicKey, power uint64) (stop bool)) (stopped bool) { - return t.validators.Iterate(iter) +func (t *Tip) Validators() *Validators { + return t.validators.Prev().Copy() +} + +func (t *Tip) IterateValidators(iter func(id crypto.Addressable, power *big.Int) (stop bool)) (stopped bool) { + return t.validators.Prev().Copy().Iterate(iter) } func (t *Tip) NumValidators() int { - return t.validators.Length() + return t.validators.Prev().Count() } diff --git a/blockchain/blockchain_test.go b/blockchain/blockchain_test.go new file mode 100644 index 000000000..53d74be30 --- /dev/null +++ b/blockchain/blockchain_test.go @@ -0,0 +1,46 @@ +package blockchain + +import ( + "fmt" + "math/big" + "testing" + "time" + + "github.com/hyperledger/burrow/genesis" + "github.com/hyperledger/burrow/logging/config" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/tendermint/tmlibs/db" +) + +func TestBlockchain_Encode(t *testing.T) { + genesisDoc, _, validators := genesis.NewDeterministicGenesis(234). + GenesisDoc(5, true, 232, 3, true, 34) + bc := newBlockchain(db.NewMemDB(), genesisDoc) + bs, err := bc.Encode() + require.NoError(t, err) + bcOut, err := DecodeBlockchain(bs) + require.True(t, bc.validators.Equal(bcOut.validators)) + require.Equal(t, bc.genesisDoc.GenesisTime, bcOut.genesisDoc.GenesisTime) + assert.Equal(t, config.JSONString(bc.genesisDoc), config.JSONString(bcOut.genesisDoc)) + require.Equal(t, bc.genesisDoc.Hash(), bcOut.genesisDoc.Hash()) + power := new(big.Int).SetUint64(genesisDoc.Validators[1].Amount) + id1 := validators[1].PublicKey() + var flow *big.Int + for i := 0; i < 100; i++ { + power := power.Div(power, big.NewInt(2)) + flow, err = bc.AlterPower(id1, power) + fmt.Println(flow) + require.NoError(t, err) + err = bc.CommitBlock(time.Now(), []byte("blockhash"), []byte("apphash")) + require.NoError(t, err) + bs, err = bc.Encode() + require.NoError(t, err) + bcOut, err = DecodeBlockchain(bs) + require.True(t, bc.validators.Equal(bcOut.validators)) + } + + // Should have exponentially decayed to 0 + assertZero(t, flow) + assertZero(t, bc.validators.Prev().Power(id1)) +} diff --git a/blockchain/validators.go b/blockchain/validators.go index 0ba398af0..ea2ddfd47 100644 --- a/blockchain/validators.go +++ b/blockchain/validators.go @@ -2,121 +2,174 @@ package blockchain import ( "fmt" - + "math/big" "sort" + "strings" - "bytes" - "encoding/binary" - - burrowBinary "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/crypto" ) -// A Validator multiset +var big0 = big.NewInt(0) + +// A Validator multiset - can be used to capture the global state of validators or as an accumulator each block type Validators struct { - power map[crypto.Address]uint64 - publicKey map[crypto.Address]crypto.PublicKey - totalPower uint64 + powers map[crypto.Address]*big.Int + publicKeys map[crypto.Address]crypto.Addressable + totalPower *big.Int } -func NewValidators() Validators { - return Validators{ - power: make(map[crypto.Address]uint64), - publicKey: make(map[crypto.Address]crypto.PublicKey), +type ValidatorSet interface { + AlterPower(id crypto.Addressable, power *big.Int) (flow *big.Int, err error) +} + +// Create a new Validators which can act as an accumulator for validator power changes +func NewValidators() *Validators { + return &Validators{ + totalPower: new(big.Int), + powers: make(map[crypto.Address]*big.Int), + publicKeys: make(map[crypto.Address]crypto.Addressable), } } -// Add the power of a validator -func (vs *Validators) AlterPower(publicKey crypto.PublicKey, power uint64) error { - address := publicKey.Address() - // Remove existing power (possibly 0) from total - vs.totalPower -= vs.power[address] - if burrowBinary.IsUint64SumOverflow(vs.totalPower, power) { - // Undo removing existing power - vs.totalPower += vs.power[address] - return fmt.Errorf("could not increase total validator power by %v from %v since that would overflow "+ - "uint64", power, vs.totalPower) +// Add the power of a validator and returns the flow into that validator +func (vs *Validators) AlterPower(id crypto.Addressable, power *big.Int) *big.Int { + if power.Sign() == -1 { + panic("ASRRRH") } - vs.publicKey[address] = publicKey - vs.power[address] = power - // Note we are adjusting by the difference in power (+/-) since we subtracted the previous amount above - vs.totalPower += power - return nil -} - -func (vs *Validators) AddPower(publicKey crypto.PublicKey, power uint64) error { - currentPower := vs.power[publicKey.Address()] - if burrowBinary.IsUint64SumOverflow(currentPower, power) { - return fmt.Errorf("could add power %v to validator %v with power %v because that would overflow uint64", - power, publicKey.Address(), currentPower) + address := id.Address() + // Calculcate flow into this validator (postive means in, negative means out) + flow := new(big.Int).Sub(power, vs.Power(id)) + vs.totalPower.Add(vs.totalPower, flow) + if power.Cmp(big0) == 0 { + // Remove from set so that we return an accurate length + delete(vs.publicKeys, address) + delete(vs.powers, address) + return flow } - return vs.AlterPower(publicKey, vs.power[publicKey.Address()]+power) + vs.publicKeys[address] = crypto.MemoizeAddressable(id) + vs.powers[address] = new(big.Int).Set(power) + return flow +} + +// Adds vsOther to vs +func (vs *Validators) Add(vsOther *Validators) { + vsOther.Iterate(func(id crypto.Addressable, power *big.Int) (stop bool) { + vs.AddPower(id, power) + return + }) +} + +func (vs *Validators) AddPower(id crypto.Addressable, power *big.Int) { + // Current power + power + vs.AlterPower(id, new(big.Int).Add(vs.Power(id), power)) } -func (vs *Validators) SubtractPower(publicKey crypto.PublicKey, power uint64) error { - currentPower := vs.power[publicKey.Address()] - if currentPower < power { - return fmt.Errorf("could subtract power %v from validator %v with power %v because that would "+ - "underflow uint64", power, publicKey.Address(), currentPower) +// Subtracts vsOther from vs +func (vs *Validators) Subtract(vsOther *Validators) { + vsOther.Iterate(func(id crypto.Addressable, power *big.Int) (stop bool) { + vs.SubtractPower(id, power) + return + }) +} + +func (vs *Validators) SubtractPower(id crypto.Addressable, power *big.Int) { + // Current power - power + thisPower := vs.Power(id) + vs.AlterPower(id, new(big.Int).Sub(thisPower, power)) +} + +func (vs *Validators) Power(id crypto.Addressable) *big.Int { + if vs.powers[id.Address()] == nil { + return new(big.Int) } - return vs.AlterPower(publicKey, vs.power[publicKey.Address()]-power) + return new(big.Int).Set(vs.powers[id.Address()]) +} + +func (vs *Validators) Equal(vsOther *Validators) bool { + if vs.Count() != vsOther.Count() { + return false + } + // Stop iteration IFF we find a non-matching validator + return !vs.Iterate(func(id crypto.Addressable, power *big.Int) (stop bool) { + otherPower := vsOther.Power(id) + if otherPower.Cmp(power) != 0 { + return true + } + return false + }) } // Iterates over validators sorted by address -func (vs *Validators) Iterate(iter func(publicKey crypto.PublicKey, power uint64) (stop bool)) (stopped bool) { - addresses := make(crypto.Addresses, 0, len(vs.power)) - for address := range vs.power { +func (vs *Validators) Iterate(iter func(id crypto.Addressable, power *big.Int) (stop bool)) (stopped bool) { + if vs == nil { + return + } + addresses := make(crypto.Addresses, 0, len(vs.powers)) + for address := range vs.powers { addresses = append(addresses, address) } sort.Sort(addresses) for _, address := range addresses { - if iter(vs.publicKey[address], vs.power[address]) { + if iter(vs.publicKeys[address], new(big.Int).Set(vs.powers[address])) { return true } } - return false + return } -func (vs *Validators) Length() int { - return len(vs.power) +func (vs *Validators) Count() int { + return len(vs.publicKeys) } -func (vs *Validators) TotalPower() uint64 { - return vs.totalPower +func (vs *Validators) TotalPower() *big.Int { + return new(big.Int).Set(vs.totalPower) } -// Uses the fixed width public key encoding to -func (vs *Validators) Encode() []byte { - buffer := new(bytes.Buffer) - // varint buffer - buf := make([]byte, 8) - vs.Iterate(func(publicKey crypto.PublicKey, power uint64) (stop bool) { - buffer.Write(publicKey.Encode()) - buffer.Write(buf[:binary.PutUvarint(buf, power)]) +func (vs *Validators) Copy() *Validators { + vsCopy := NewValidators() + vs.Iterate(func(id crypto.Addressable, power *big.Int) (stop bool) { + vsCopy.AlterPower(id, power) return }) - return buffer.Bytes() + return vsCopy } -// Decodes validators encoded with Encode - expects the exact encoded size with no trailing bytes -func DecodeValidators(encoded []byte, validators *Validators) error { - publicKey := new(crypto.PublicKey) - i := 0 - for i < len(encoded) { - n, err := crypto.DecodePublicKeyFixedWidth(encoded[i:], publicKey) - if err != nil { - return err - } - i += n - power, n := binary.Uvarint(encoded[i:]) - if n <= 0 { - return fmt.Errorf("error decoding uint64 from validators binary encoding") - } - i += n - err = validators.AlterPower(*publicKey, power) - if err != nil { - return err - } +type PersistedValidator struct { + PublicKey crypto.PublicKey + PowerBytes []byte +} + +func (vs *Validators) Persistable() []PersistedValidator { + if vs == nil { + return nil + } + pvs := make([]PersistedValidator, 0, vs.Count()) + vs.Iterate(func(id crypto.Addressable, power *big.Int) (stop bool) { + pvs = append(pvs, PersistedValidator{PublicKey: id.PublicKey(), PowerBytes: power.Bytes()}) + return + }) + return pvs +} + +func UnpersistValidators(pvs []PersistedValidator) *Validators { + vs := NewValidators() + for _, pv := range pvs { + power := new(big.Int).SetBytes(pv.PowerBytes) + vs.AlterPower(pv.PublicKey, power) } - return nil + return vs +} + +func (vs *Validators) String() string { + return fmt.Sprintf("Validators{TotalPower: %v; Count: %v; %v}", vs.TotalPower(), vs.Count(), + vs.ValidatorStrings()) +} + +func (vs *Validators) ValidatorStrings() string { + strs := make([]string, 0, vs.Count()) + vs.Iterate(func(id crypto.Addressable, power *big.Int) (stop bool) { + strs = append(strs, fmt.Sprintf("%v->%v", id.Address(), power)) + return + }) + return strings.Join(strs, ", ") } diff --git a/blockchain/validators_ring.go b/blockchain/validators_ring.go new file mode 100644 index 000000000..2709b27c7 --- /dev/null +++ b/blockchain/validators_ring.go @@ -0,0 +1,198 @@ +package blockchain + +import ( + "fmt" + "math/big" + + "github.com/hyperledger/burrow/crypto" +) + +type ValidatorsRing struct { + buckets []*Validators + // Totals for each validator across all buckets + power *Validators + // Current flow totals for each validator in the Head bucket + flow *Validators + // Index of current head bucekt + head int64 + size int64 +} + +var big1 = big.NewInt(1) +var big3 = big.NewInt(3) + +// Provides a sliding window over the last size buckets of validator power changes +func NewValidatorsRing(initialValidators *Validators, size int) *ValidatorsRing { + if size < 2 { + size = 2 + } + vw := &ValidatorsRing{ + buckets: make([]*Validators, size), + power: NewValidators(), + flow: NewValidators(), + size: int64(size), + } + for i := 0; i < size; i++ { + vw.buckets[i] = NewValidators() + } + + initialValidators.Iterate(func(id crypto.Addressable, power *big.Int) (stop bool) { + // Existing set + vw.buckets[vw.index(-1)].AlterPower(id, power) + // Current accumulator + vw.buckets[vw.head].AlterPower(id, power) + + vw.power.AddPower(id, power.Add(power, power)) + return + }) + + return vw +} + +// Updates the current head bucket (accumulator) with some safety checks +func (vw *ValidatorsRing) AlterPower(id crypto.Addressable, power *big.Int) (*big.Int, error) { + if power.Sign() == -1 { + return nil, fmt.Errorf("cannot set negative validator power: %v", power) + } + // if flow > maxflow then we cannot alter the power + flow := vw.Flow(id, power) + maxFlow := vw.MaxFlow() + // Set flow to update total flow + vw.flow.AlterPower(id, flow) + if vw.flow.totalPower.Cmp(maxFlow) == 1 { + // Reset flow to previous value + vw.flow.AlterPower(id, vw.Flow(id, vw.Head().Power(id))) + allowable := new(big.Int).Sub(maxFlow, vw.flow.totalPower) + return nil, fmt.Errorf("cannot change validator power of %v from %v to %v because that would result in a flow "+ + "greater than or equal to 1/3 of total power for the next commit: flow induced by change: %v, "+ + "current total flow: %v/%v (cumulative/max), remaining allowable flow: %v", + id.Address(), vw.Prev().Power(id), power, flow, vw.flow.totalPower, maxFlow, allowable) + } + // Add to total power + vw.Head().AlterPower(id, power) + return flow, nil +} + +// Returns the flow that would be induced by a validator change by comparing the current accumulator with the previous +// bucket +func (vw *ValidatorsRing) Flow(id crypto.Addressable, power *big.Int) *big.Int { + flow := new(big.Int) + prevPower := vw.Prev().Power(id) + return flow.Abs(flow.Sub(power, prevPower)) +} + +// To ensure that in the maximum valildator shift at least one unit +// of validator power in the intersection of last block validators and this block validators must have at least one +// non-byzantine validator who can tell you if you've been lied to about the validator set +// So need at most ceiling((Total Power)/3) - 1, in integer division we have ceiling(X*p/q) = (p(X+1)-1)/q +// For p = 1 just X/q +// So we want (Total Power)/3 - 1 +func (vw *ValidatorsRing) MaxFlow() *big.Int { + max := vw.Prev().TotalPower() + return max.Sub(max.Div(max, big3), big1) +} + +// Advance the current head bucket to the next bucket and returns the change in total power between the previous bucket +// and the current head, and the total flow which is the sum of absolute values of all changes each validator's power +// after rotation the next head is a copy of the current head +func (vw *ValidatorsRing) Rotate() (totalPowerChange *big.Int, totalFlow *big.Int) { + // Subtract the previous bucket total power so we can add on the current buckets power after this + totalPowerChange = new(big.Int).Sub(vw.Head().totalPower, vw.Prev().totalPower) + // Capture flow before we wipe it + totalFlow = vw.flow.totalPower + // Subtract the tail bucket (if any) from the total + vw.power.Subtract(vw.Next()) + // Copy head bucket + headCopy := vw.Head().Copy() + // add it to total + vw.power.Add(headCopy) + // move the ring buffer on + vw.head = vw.index(1) + // Overwrite new head bucket (previous tail) with previous bucket copy updated with current head + vw.buckets[vw.head] = headCopy + // New flow accumulator1 + vw.flow = NewValidators() + // Advance the ring + return totalPowerChange, totalFlow +} + +func (vw *ValidatorsRing) Prev() *Validators { + return vw.buckets[vw.index(-1)] +} + +func (vw *ValidatorsRing) Head() *Validators { + return vw.buckets[vw.head] +} + +func (vw *ValidatorsRing) Next() *Validators { + return vw.buckets[vw.index(1)] +} + +func (vw *ValidatorsRing) index(i int64) int64 { + return (vw.size + vw.head + i) % vw.size +} + +func (vw *ValidatorsRing) Size() int64 { + return vw.size +} + +// Returns buckets in order head, previous, ... +func (vw *ValidatorsRing) OrderedBuckets() []*Validators { + buckets := make([]*Validators, len(vw.buckets)) + for i := int64(0); i < vw.size; i++ { + buckets[i] = vw.buckets[vw.index(-i)] + } + return buckets +} + +func (vw *ValidatorsRing) String() string { + return fmt.Sprintf("ValidatorsWindow{Total: %v; Buckets: Head->%v<-Tail}", vw.power, vw.OrderedBuckets()) +} + +func (vw *ValidatorsRing) Equal(vwOther *ValidatorsRing) bool { + if vw.size != vwOther.size || vw.head != vwOther.head || len(vw.buckets) != len(vwOther.buckets) || + !vw.flow.Equal(vwOther.flow) || !vw.power.Equal(vwOther.power) { + return false + } + for i, b := range vw.buckets { + if !b.Equal(vwOther.buckets[i]) { + return false + } + } + return true +} + +type PersistedValidatorsRing struct { + Buckets [][]PersistedValidator + Power []PersistedValidator + Flow []PersistedValidator + Head int64 +} + +func (vw *ValidatorsRing) Persistable() PersistedValidatorsRing { + buckets := make([][]PersistedValidator, len(vw.buckets)) + for i, vs := range vw.buckets { + buckets[i] = vs.Persistable() + } + return PersistedValidatorsRing{ + Buckets: buckets, + Power: vw.power.Persistable(), + Flow: vw.flow.Persistable(), + Head: vw.head, + } +} + +func UnpersistValidatorsRing(pvr PersistedValidatorsRing) *ValidatorsRing { + buckets := make([]*Validators, len(pvr.Buckets)) + for i, pv := range pvr.Buckets { + buckets[i] = UnpersistValidators(pv) + } + + return &ValidatorsRing{ + buckets: buckets, + head: pvr.Head, + power: UnpersistValidators(pvr.Power), + flow: UnpersistValidators(pvr.Flow), + size: int64(len(buckets)), + } +} diff --git a/blockchain/validators_ring_test.go b/blockchain/validators_ring_test.go new file mode 100644 index 000000000..d0c816288 --- /dev/null +++ b/blockchain/validators_ring_test.go @@ -0,0 +1,121 @@ +package blockchain + +import ( + "fmt" + "math/big" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +var pubA = pubKey(1) +var pubB = pubKey(2) +var pubC = pubKey(3) + +func TestValidatorsWindow_AlterPower(t *testing.T) { + vs := NewValidators() + powAInitial := int64(10000) + vs.AlterPower(pubA, big.NewInt(powAInitial)) + vw := NewValidatorsRing(vs, 3) + + // Just allowable validator tide + var powA, powB, powC int64 = 7000, 23, 309 + powerChange, totalFlow, err := alterPowers(t, vw, powA, powB, powC) + require.NoError(t, err) + assert.Equal(t, big.NewInt(powA+powB+powC-powAInitial), powerChange) + assert.Equal(t, big.NewInt(powAInitial/3-1), totalFlow) + + // This one is not + vw = NewValidatorsRing(vs, 5) + powA, powB, powC = 7000, 23, 310 + powerChange, totalFlow, err = alterPowers(t, vw, powA, powB, powC) + require.Error(t, err) + + powA, powB, powC = 7000, 23, 309 + powerChange, totalFlow, err = alterPowers(t, vw, powA, powB, powC) + require.NoError(t, err) + assert.Equal(t, big.NewInt(powA+powB+powC-powAInitial), powerChange) + assert.Equal(t, big.NewInt(powAInitial/3-1), totalFlow) + + powA, powB, powC = 7000, 23, 309 + powerChange, totalFlow, err = alterPowers(t, vw, powA, powB, powC) + require.NoError(t, err) + assertZero(t, powerChange) + assertZero(t, totalFlow) + + _, err = vw.AlterPower(pubA, big.NewInt(8000)) + assert.NoError(t, err) + + // Should fail - not enough flow left + _, err = vw.AlterPower(pubB, big.NewInt(2000)) + assert.Error(t, err) + + // Take a bit off shouhd work + _, err = vw.AlterPower(pubA, big.NewInt(7000)) + assert.NoError(t, err) + + _, err = vw.AlterPower(pubB, big.NewInt(2000)) + assert.NoError(t, err) + vw.Rotate() + + powerChange, totalFlow, err = alterPowers(t, vw, powA, powB, powC) + require.NoError(t, err) + assert.Equal(t, big.NewInt(-1977), powerChange) + assert.Equal(t, big.NewInt(1977), totalFlow) + + powerChange, totalFlow, err = alterPowers(t, vw, powA, powB, powC) + require.NoError(t, err) + assertZero(t, powerChange) + assert.Equal(t, big0, totalFlow) + + powerChange, totalFlow, err = alterPowers(t, vw, powA, powB, powC) + require.NoError(t, err) + assertZero(t, powerChange) + assert.Equal(t, big0, totalFlow) +} + +func TestValidatorsRing_Persistable(t *testing.T) { + + vs := NewValidators() + powAInitial := int64(10000) + vs.AlterPower(pubA, big.NewInt(powAInitial)) + vw := NewValidatorsRing(vs, 30) + + for i := int64(0); i < 61; i++ { + _, _, err := alterPowers(t, vw, 10000, 200*i, 200*((i+1)%4)) + require.NoError(t, err) + } + + vwOut := UnpersistValidatorsRing(vw.Persistable()) + assert.True(t, vw.Equal(vwOut), "should re equal across persistence") +} + +func alterPowers(t testing.TB, vw *ValidatorsRing, powA, powB, powC int64) (powerChange, totalFlow *big.Int, err error) { + fmt.Println(vw) + _, err = vw.AlterPower(pubA, big.NewInt(powA)) + if err != nil { + return nil, nil, err + } + _, err = vw.AlterPower(pubB, big.NewInt(powB)) + if err != nil { + return nil, nil, err + } + _, err = vw.AlterPower(pubC, big.NewInt(powC)) + if err != nil { + return nil, nil, err + } + maxFlow := vw.MaxFlow() + powerChange, totalFlow = vw.Rotate() + // totalFlow > maxFlow + if totalFlow.Cmp(maxFlow) == 1 { + return powerChange, totalFlow, fmt.Errorf("totalFlow (%v) exceeds maxFlow (%v)", totalFlow, maxFlow) + } + + return powerChange, totalFlow, nil +} + +// Since we have -0 and 0 with big.Int due to its representation with a neg flag +func assertZero(t testing.TB, i *big.Int) { + assert.True(t, big0.Cmp(i) == 0, "expected 0 but got %v", i) +} diff --git a/blockchain/validators_test.go b/blockchain/validators_test.go index 433db89eb..1bc7970e4 100644 --- a/blockchain/validators_test.go +++ b/blockchain/validators_test.go @@ -1,48 +1,23 @@ package blockchain import ( - "testing" - "fmt" - - "math/rand" + "math/big" + "testing" "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/crypto" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func TestValidators_AlterPower(t *testing.T) { vs := NewValidators() - pow1 := uint64(2312312321) - assert.NoError(t, vs.AlterPower(pubKey(1), pow1)) + pow1 := big.NewInt(2312312321) + pubA := pubKey(1) + vs.AlterPower(pubA, pow1) assert.Equal(t, pow1, vs.TotalPower()) -} - -func TestValidators_Encode(t *testing.T) { - vs := NewValidators() - rnd := rand.New(rand.NewSource(43534543)) - for i := 0; i < 100; i++ { - power := uint64(rnd.Intn(10)) - require.NoError(t, vs.AlterPower(pubKey(rnd.Int63()), power)) - } - encoded := vs.Encode() - vsOut := NewValidators() - require.NoError(t, DecodeValidators(encoded, &vsOut)) - // Check decoded matches encoded - var publicKeyPower []interface{} - vs.Iterate(func(publicKey crypto.PublicKey, power uint64) (stop bool) { - publicKeyPower = append(publicKeyPower, publicKey, power) - return - }) - vsOut.Iterate(func(publicKey crypto.PublicKey, power uint64) (stop bool) { - assert.Equal(t, publicKeyPower[0], publicKey) - assert.Equal(t, publicKeyPower[1], power) - publicKeyPower = publicKeyPower[2:] - return - }) - assert.Len(t, publicKeyPower, 0, "should exhaust all validators in decoded multiset") + vs.AlterPower(pubA, big.NewInt(0)) + assertZero(t, vs.TotalPower()) } func pubKey(secret interface{}) crypto.PublicKey { diff --git a/blockchain/validators_window.go b/blockchain/validators_window.go deleted file mode 100644 index 11ebf209b..000000000 --- a/blockchain/validators_window.go +++ /dev/null @@ -1,64 +0,0 @@ -package blockchain - -import ( - "github.com/hyperledger/burrow/crypto" -) - -type ValidatorsWindow struct { - Buckets []Validators - Total Validators - head int -} - -// Provides a sliding window over the last size buckets of validator power changes -func NewValidatorsWindow(size int) ValidatorsWindow { - if size < 1 { - size = 1 - } - vw := ValidatorsWindow{ - Buckets: make([]Validators, size), - Total: NewValidators(), - } - vw.Buckets[vw.head] = NewValidators() - return vw -} - -// Updates the current head bucket (accumulator) -func (vw *ValidatorsWindow) AlterPower(publicKey crypto.PublicKey, power uint64) error { - return vw.Buckets[vw.head].AlterPower(publicKey, power) -} - -func (vw *ValidatorsWindow) CommitInto(validatorsToUpdate *Validators) error { - var err error - if vw.Buckets[vw.head].Iterate(func(publicKey crypto.PublicKey, power uint64) (stop bool) { - // Update the sink validators - err = validatorsToUpdate.AlterPower(publicKey, power) - if err != nil { - return true - } - // Add to total power - err = vw.Total.AddPower(publicKey, power) - if err != nil { - return true - } - return false - }) { - // If iteration stopped there was an error - return err - } - // move the ring buffer on - vw.head = (vw.head + 1) % len(vw.Buckets) - // Subtract the tail bucket (if any) from the total - if vw.Buckets[vw.head].Iterate(func(publicKey crypto.PublicKey, power uint64) (stop bool) { - err = vw.Total.SubtractPower(publicKey, power) - if err != nil { - return false - } - return true - }) { - return err - } - // Clear new head bucket (and possibly previous tail) - vw.Buckets[vw.head] = NewValidators() - return nil -} diff --git a/cmd/burrow/commands/configure.go b/cmd/burrow/commands/configure.go index c64d4c72a..d45ed4d3a 100644 --- a/cmd/burrow/commands/configure.go +++ b/cmd/burrow/commands/configure.go @@ -155,7 +155,7 @@ func Configure(output Output) func(cmd *cli.Cmd) { if nodeKey { privKey := tm_crypto.GenPrivKeyEd25519() - copy(privKey[:], key.PrivateKey.PrivateKey) + copy(privKey[:], key.PrivateKey.Key) nodeKey := &p2p.NodeKey{ PrivKey: privKey, } diff --git a/consensus/tendermint/abci/app.go b/consensus/tendermint/abci/app.go index 6c5247481..41aed6b42 100644 --- a/consensus/tendermint/abci/app.go +++ b/consensus/tendermint/abci/app.go @@ -2,6 +2,7 @@ package abci import ( "fmt" + "math/big" "sync" "time" @@ -82,15 +83,57 @@ func (app *App) Query(reqQuery abciTypes.RequestQuery) (respQuery abciTypes.Resp } func (app *App) InitChain(chain abciTypes.RequestInitChain) (respInitChain abciTypes.ResponseInitChain) { - // Could verify agreement on initial validator set here + defer func() { + if r := recover(); r != nil { + app.panicFunc(fmt.Errorf("panic occurred in abci.App/InitChain: %v\n%s", r, debug.Stack())) + } + }() + err := app.checkValidatorsMatch(chain.Validators) + if err != nil { + app.logger.InfoMsg("Initial validator set mistmatch", structure.ErrorKey, err) + panic(err) + } + app.logger.InfoMsg("Initial validator set matches") return } func (app *App) BeginBlock(block abciTypes.RequestBeginBlock) (respBeginBlock abciTypes.ResponseBeginBlock) { app.block = &block + defer func() { + if r := recover(); r != nil { + app.panicFunc(fmt.Errorf("panic occurred in abci.App/BeginBlock: %v\n%s", r, debug.Stack())) + } + }() + if block.Header.Height > 1 { + validators := make([]abciTypes.Validator, len(block.Validators)) + for i, v := range block.Validators { + validators[i] = v.Validator + } + err := app.checkValidatorsMatch(validators) + if err != nil { + panic(err) + } + } return } +func (app *App) checkValidatorsMatch(validators []abciTypes.Validator) error { + tendermintValidators := bcm.NewValidators() + for _, v := range validators { + publicKey, err := crypto.PublicKeyFromABCIPubKey(v.PubKey) + if err != nil { + panic(err) + } + tendermintValidators.AlterPower(publicKey, big.NewInt(v.Power)) + } + burrowValidators := app.blockchain.Validators() + if !burrowValidators.Equal(tendermintValidators) { + return fmt.Errorf("validators provided by Tendermint at InitChain do not match those held by Burrow: "+ + "Tendermint gives: %v, Burrow gives: %v", tendermintValidators, burrowValidators) + } + return nil +} + func (app *App) CheckTx(txBytes []byte) abciTypes.ResponseCheckTx { defer func() { if r := recover(); r != nil { @@ -163,13 +206,13 @@ func txExecutor(executor execution.BatchExecutor, txDecoder txs.Decoder, logger } func (app *App) EndBlock(reqEndBlock abciTypes.RequestEndBlock) abciTypes.ResponseEndBlock { - // Validator mutation goes here var validatorUpdates abciTypes.Validators - app.blockchain.IterateValidators(func(publicKey crypto.PublicKey, power uint64) (stop bool) { + app.blockchain.IterateValidators(func(id crypto.Addressable, power *big.Int) (stop bool) { validatorUpdates = append(validatorUpdates, abciTypes.Validator{ - Address: publicKey.Address().Bytes(), - PubKey: publicKey.ABCIPubKey(), - Power: int64(power), + Address: id.Address().Bytes(), + PubKey: id.PublicKey().ABCIPubKey(), + // Must be ensured during execution + Power: power.Int64(), }) return }) @@ -184,13 +227,14 @@ func (app *App) Commit() abciTypes.ResponseCommit { app.panicFunc(fmt.Errorf("panic occurred in abci.App/Commit: %v\n%s", r, debug.Stack())) } }() + blockTime := time.Unix(app.block.Header.Time, 0) app.logger.InfoMsg("Committing block", "tag", "Commit", structure.ScopeKey, "Commit()", "height", app.block.Header.Height, "hash", app.block.Hash, "txs", app.block.Header.NumTxs, - "block_time", app.block.Header.Time, // [CSK] this sends a fairly non-sensical number; should be human readable + "block_time", blockTime, "last_block_time", app.blockchain.Tip.LastBlockTime(), "last_block_hash", app.blockchain.Tip.LastBlockHash()) @@ -219,37 +263,16 @@ func (app *App) Commit() abciTypes.ResponseCommit { } }() - // First commit the app start, this app hash will not get checkpointed until the next block when we are sure - // that nothing in the downstream commit process could have failed. At worst we go back one block. - blockHeader := app.block.Header - appHash, err := app.committer.Commit(&blockHeader) + appHash, err := app.committer.Commit(app.block.Hash, blockTime, &app.block.Header) if err != nil { panic(errors.Wrap(err, "Could not commit transactions in block to execution state")) } - // Commit to our blockchain state which will checkpoint the previous app hash by saving it to the database - // (we know the previous app hash is safely committed because we are about to commit the next) - err = app.blockchain.CommitBlock(time.Unix(int64(app.block.Header.Time), 0), app.block.Hash, appHash) - if err != nil { - panic(errors.Wrap(err, "could not commit block to blockchain state")) - } - err = app.checker.Reset() if err != nil { panic(errors.Wrap(err, "could not reset check cache during commit")) } - // Perform a sanity check our block height - if app.blockchain.LastBlockHeight() != uint64(app.block.Header.Height) { - app.logger.InfoMsg("Burrow block height disagrees with Tendermint block height", - structure.ScopeKey, "Commit()", - "burrow_height", app.blockchain.LastBlockHeight(), - "tendermint_height", app.block.Header.Height) - - panic(fmt.Errorf("burrow has recorded a block height of %v, "+ - "but Tendermint reports a block height of %v, and the two should agree", - app.blockchain.LastBlockHeight(), app.block.Header.Height)) - } return abciTypes.ResponseCommit{ Data: appHash, } diff --git a/consensus/tendermint/validator/priv_validator_memory.go b/consensus/tendermint/validator/priv_validator_memory.go index 05455cba2..3a5b6db35 100644 --- a/consensus/tendermint/validator/priv_validator_memory.go +++ b/consensus/tendermint/validator/priv_validator_memory.go @@ -1,14 +1,13 @@ package validator import ( - "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/crypto" tm_crypto "github.com/tendermint/go-crypto" tm_types "github.com/tendermint/tendermint/types" ) type privValidatorMemory struct { - acm.Addressable + crypto.Addressable signer goCryptoSigner lastSignedInfo *LastSignedInfo } @@ -17,7 +16,7 @@ var _ tm_types.PrivValidator = &privValidatorMemory{} // Create a PrivValidator with in-memory state that takes an addressable representing the validator identity // and a signer providing private signing for that identity. -func NewPrivValidatorMemory(addressable acm.Addressable, signer crypto.Signer) *privValidatorMemory { +func NewPrivValidatorMemory(addressable crypto.Addressable, signer crypto.Signer) *privValidatorMemory { return &privValidatorMemory{ Addressable: addressable, signer: asTendermintSigner(signer), diff --git a/core/kernel.go b/core/kernel.go index fee805da8..ab44c0262 100644 --- a/core/kernel.go +++ b/core/kernel.go @@ -102,10 +102,10 @@ func NewKernel(ctx context.Context, keyClient keys.KeyClient, privValidator tmTy txCodec := txs.NewAminoCodec() tmGenesisDoc := tendermint.DeriveGenesisDoc(genesisDoc) - checker := execution.NewBatchChecker(state, blockchain.Tip, logger) + checker := execution.NewBatchChecker(state, blockchain, logger) emitter := event.NewEmitter(logger) - committer := execution.NewBatchCommitter(state, blockchain.Tip, emitter, logger, exeOptions...) + committer := execution.NewBatchCommitter(state, blockchain, emitter, logger, exeOptions...) tmNode, err := tendermint.NewNode(tmConf, privValidator, tmGenesisDoc, blockchain, checker, committer, txCodec, kern.Panic, tmLogger) if err != nil { @@ -204,7 +204,6 @@ func NewKernel(ctx context.Context, keyClient keys.KeyClient, privValidator tmTy if err != nil { return nil, err } - listen.Addr() grpcServer := rpc.NewGRPCServer(logger) var ks *keys.KeyStore diff --git a/crypto/address.go b/crypto/address.go index 9dab20155..69bd9af69 100644 --- a/crypto/address.go +++ b/crypto/address.go @@ -10,6 +10,40 @@ import ( "golang.org/x/crypto/ripemd160" ) +type Addressable interface { + // Get the 20 byte EVM address of this account + Address() Address + // Public key from which the Address is derived + PublicKey() PublicKey +} + +func NewAddressable(address Address, publicKey PublicKey) Addressable { + return &memoizedAddressable{ + address: address, + publicKey: publicKey, + } +} + +type memoizedAddressable struct { + publicKey PublicKey + address Address +} + +func MemoizeAddressable(addressable Addressable) Addressable { + if a, ok := addressable.(*memoizedAddressable); ok { + return a + } + return NewAddressable(addressable.Address(), addressable.PublicKey()) +} + +func (a *memoizedAddressable) PublicKey() PublicKey { + return a.publicKey +} + +func (a *memoizedAddressable) Address() Address { + return a.address +} + type Address binary.Word160 type Addresses []Address diff --git a/crypto/crypto.go b/crypto/crypto.go index e5f62db10..eab93deac 100644 --- a/crypto/crypto.go +++ b/crypto/crypto.go @@ -21,6 +21,16 @@ func (k CurveType) String() string { return "unknown" } } +func (k CurveType) ABCIType() string { + switch k { + case CurveTypeSecp256k1: + return "secp256k1" + case CurveTypeEd25519: + return "ed25519" + default: + return "unknown" + } +} // Get this CurveType's 8 bit identifier as a byte func (k CurveType) Byte() byte { diff --git a/crypto/crypto.pb.go b/crypto/crypto.pb.go index 230f0f5e5..2a8e152bb 100644 --- a/crypto/crypto.pb.go +++ b/crypto/crypto.pb.go @@ -36,7 +36,7 @@ const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package // PublicKey type PublicKey struct { CurveType CurveType `protobuf:"varint,1,opt,name=CurveType,proto3,casttype=CurveType" json:"CurveType,omitempty"` - PublicKey []byte `protobuf:"bytes,2,opt,name=PublicKey,proto3" json:"PublicKey,omitempty"` + Key []byte `protobuf:"bytes,2,opt,name=Key,proto3" json:"Key,omitempty"` } func (m *PublicKey) Reset() { *m = PublicKey{} } @@ -50,9 +50,9 @@ func (m *PublicKey) GetCurveType() CurveType { return 0 } -func (m *PublicKey) GetPublicKey() []byte { +func (m *PublicKey) GetKey() []byte { if m != nil { - return m.PublicKey + return m.Key } return nil } @@ -64,8 +64,8 @@ func (*PublicKey) XXX_MessageName() string { type PrivateKey struct { CurveType CurveType `protobuf:"varint,1,opt,name=CurveType,proto3,casttype=CurveType" json:"CurveType,omitempty"` // Note may need initialisation - PublicKey []byte `protobuf:"bytes,2,opt,name=PublicKey,proto3" json:"PublicKey,omitempty"` - PrivateKey []byte `protobuf:"bytes,3,opt,name=PrivateKey,proto3" json:"PrivateKey,omitempty"` + PublicKey []byte `protobuf:"bytes,2,opt,name=PublicKey,proto3" json:"PublicKey,omitempty"` + Key []byte `protobuf:"bytes,3,opt,name=Key,proto3" json:"Key,omitempty"` } func (m *PrivateKey) Reset() { *m = PrivateKey{} } @@ -101,11 +101,11 @@ func (m *PublicKey) MarshalTo(dAtA []byte) (int, error) { i++ i = encodeVarintCrypto(dAtA, i, uint64(m.CurveType)) } - if len(m.PublicKey) > 0 { + if len(m.Key) > 0 { dAtA[i] = 0x12 i++ - i = encodeVarintCrypto(dAtA, i, uint64(len(m.PublicKey))) - i += copy(dAtA[i:], m.PublicKey) + i = encodeVarintCrypto(dAtA, i, uint64(len(m.Key))) + i += copy(dAtA[i:], m.Key) } return i, nil } @@ -136,11 +136,11 @@ func (m *PrivateKey) MarshalTo(dAtA []byte) (int, error) { i = encodeVarintCrypto(dAtA, i, uint64(len(m.PublicKey))) i += copy(dAtA[i:], m.PublicKey) } - if len(m.PrivateKey) > 0 { + if len(m.Key) > 0 { dAtA[i] = 0x1a i++ - i = encodeVarintCrypto(dAtA, i, uint64(len(m.PrivateKey))) - i += copy(dAtA[i:], m.PrivateKey) + i = encodeVarintCrypto(dAtA, i, uint64(len(m.Key))) + i += copy(dAtA[i:], m.Key) } return i, nil } @@ -160,7 +160,7 @@ func (m *PublicKey) Size() (n int) { if m.CurveType != 0 { n += 1 + sovCrypto(uint64(m.CurveType)) } - l = len(m.PublicKey) + l = len(m.Key) if l > 0 { n += 1 + l + sovCrypto(uint64(l)) } @@ -177,7 +177,7 @@ func (m *PrivateKey) Size() (n int) { if l > 0 { n += 1 + l + sovCrypto(uint64(l)) } - l = len(m.PrivateKey) + l = len(m.Key) if l > 0 { n += 1 + l + sovCrypto(uint64(l)) } @@ -247,7 +247,7 @@ func (m *PublicKey) Unmarshal(dAtA []byte) error { } case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PublicKey", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { @@ -271,9 +271,9 @@ func (m *PublicKey) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.PublicKey = append(m.PublicKey[:0], dAtA[iNdEx:postIndex]...) - if m.PublicKey == nil { - m.PublicKey = []byte{} + m.Key = append(m.Key[:0], dAtA[iNdEx:postIndex]...) + if m.Key == nil { + m.Key = []byte{} } iNdEx = postIndex default: @@ -378,7 +378,7 @@ func (m *PrivateKey) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PrivateKey", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { @@ -402,9 +402,9 @@ func (m *PrivateKey) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.PrivateKey = append(m.PrivateKey[:0], dAtA[iNdEx:postIndex]...) - if m.PrivateKey == nil { - m.PrivateKey = []byte{} + m.Key = append(m.Key[:0], dAtA[iNdEx:postIndex]...) + if m.Key == nil { + m.Key = []byte{} } iNdEx = postIndex default: @@ -537,19 +537,19 @@ func init() { proto.RegisterFile("crypto.proto", fileDescriptorCrypto) } func init() { golang_proto.RegisterFile("crypto.proto", fileDescriptorCrypto) } var fileDescriptorCrypto = []byte{ - // 221 bytes of a gzipped FileDescriptorProto + // 224 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x49, 0x2e, 0xaa, 0x2c, 0x28, 0xc9, 0xd7, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x83, 0xf0, 0xa4, 0x74, 0xd3, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, 0xd3, 0xf3, 0xd3, 0xf3, 0xf5, 0xc1, 0xd2, - 0x49, 0xa5, 0x69, 0x60, 0x1e, 0x98, 0x03, 0x66, 0x41, 0xb4, 0x29, 0xc5, 0x70, 0x71, 0x06, 0x94, + 0x49, 0xa5, 0x69, 0x60, 0x1e, 0x98, 0x03, 0x66, 0x41, 0xb4, 0x29, 0x05, 0x70, 0x71, 0x06, 0x94, 0x26, 0xe5, 0x64, 0x26, 0x7b, 0xa7, 0x56, 0x0a, 0x69, 0x73, 0x71, 0x3a, 0x97, 0x16, 0x95, 0xa5, 0x86, 0x54, 0x16, 0xa4, 0x4a, 0x30, 0x2a, 0x30, 0x6a, 0xf0, 0x3a, 0xf1, 0xfe, 0xba, 0x27, 0x8f, - 0x10, 0x0c, 0x42, 0x30, 0x85, 0x64, 0x90, 0x74, 0x4a, 0x30, 0x29, 0x30, 0x6a, 0xf0, 0x04, 0x21, - 0x04, 0xac, 0x58, 0x66, 0x2c, 0x90, 0x67, 0x50, 0x6a, 0x64, 0xe4, 0xe2, 0x0a, 0x28, 0xca, 0x2c, - 0x4b, 0x2c, 0x49, 0xa5, 0xae, 0xf9, 0x42, 0x72, 0xc8, 0x06, 0x4b, 0x30, 0x83, 0xa5, 0x91, 0x44, - 0xac, 0x38, 0x3a, 0x16, 0xc8, 0x33, 0x80, 0xdc, 0xe0, 0x64, 0x75, 0xe2, 0x91, 0x1c, 0xe3, 0x85, - 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x1e, 0x78, 0x2c, 0xc7, 0x78, 0xe2, 0xb1, 0x1c, 0x63, - 0x94, 0x0a, 0x52, 0x30, 0x65, 0x54, 0x16, 0xa4, 0x16, 0xe5, 0xa4, 0xa6, 0xa4, 0xa7, 0x16, 0xe9, - 0x27, 0x95, 0x16, 0x15, 0xe5, 0x97, 0xeb, 0x43, 0x02, 0x33, 0x89, 0x0d, 0x1c, 0x48, 0xc6, 0x80, - 0x00, 0x00, 0x00, 0xff, 0xff, 0x5f, 0x49, 0x55, 0xc8, 0x6b, 0x01, 0x00, 0x00, + 0x10, 0x0c, 0x42, 0x30, 0x85, 0x04, 0xb8, 0x98, 0xbd, 0x53, 0x2b, 0x25, 0x98, 0x14, 0x18, 0x35, + 0x78, 0x82, 0x40, 0x4c, 0x2b, 0x96, 0x19, 0x0b, 0xe4, 0x19, 0x94, 0x8a, 0xb9, 0xb8, 0x02, 0x8a, + 0x32, 0xcb, 0x12, 0x4b, 0x52, 0x49, 0x36, 0x52, 0x06, 0xc9, 0x31, 0x50, 0x83, 0x91, 0x5c, 0x07, + 0xb5, 0x90, 0x19, 0x61, 0x21, 0x47, 0xc7, 0x02, 0x79, 0x06, 0x90, 0xa5, 0x4e, 0x56, 0x27, 0x1e, + 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x81, 0xc7, 0x72, 0x8c, 0x27, + 0x1e, 0xcb, 0x31, 0x46, 0xa9, 0x20, 0x85, 0x45, 0x46, 0x65, 0x41, 0x6a, 0x51, 0x4e, 0x6a, 0x4a, + 0x7a, 0x6a, 0x91, 0x7e, 0x52, 0x69, 0x51, 0x51, 0x7e, 0xb9, 0x3e, 0x24, 0xc4, 0x92, 0xd8, 0xc0, + 0x21, 0x61, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0x1f, 0x6f, 0x9c, 0xc7, 0x50, 0x01, 0x00, 0x00, } diff --git a/crypto/private_key.go b/crypto/private_key.go index 91252e09f..fddafda0b 100644 --- a/crypto/private_key.go +++ b/crypto/private_key.go @@ -29,28 +29,28 @@ func PublicKeyFromBytes(bs []byte, curveType CurveType) (PublicKey, error) { return PublicKey{}, ErrInvalidCurve(curveType) } - return PublicKey{PublicKey: bs, CurveType: curveType}, nil + return PublicKey{Key: bs, CurveType: curveType}, nil } func (p PrivateKey) RawBytes() []byte { - return p.PrivateKey + return p.Key } func (p PrivateKey) Sign(msg []byte) (Signature, error) { switch p.CurveType { case CurveTypeEd25519: - if len(p.PrivateKey) != ed25519.PrivateKeySize { + if len(p.Key) != ed25519.PrivateKeySize { return nil, fmt.Errorf("bytes passed have length %v but ed25519 private keys have %v bytes", - len(p.PrivateKey), ed25519.PrivateKeySize) + len(p.Key), ed25519.PrivateKeySize) } - privKey := ed25519.PrivateKey(p.PrivateKey) + privKey := ed25519.PrivateKey(p.Key) return ed25519.Sign(privKey, msg), nil case CurveTypeSecp256k1: - if len(p.PrivateKey) != btcec.PrivKeyBytesLen { + if len(p.Key) != btcec.PrivKeyBytesLen { return nil, fmt.Errorf("bytes passed have length %v but secp256k1 private keys have %v bytes", - len(p.PrivateKey), btcec.PrivKeyBytesLen) + len(p.Key), btcec.PrivKeyBytesLen) } - privKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), p.PrivateKey) + privKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), p.Key) sig, err := privKey.Sign(msg) if err != nil { @@ -63,7 +63,7 @@ func (p PrivateKey) Sign(msg []byte) (Signature, error) { } func (p PrivateKey) GetPublicKey() PublicKey { - return PublicKey{CurveType: p.CurveType, PublicKey: p.PublicKey} + return PublicKey{CurveType: p.CurveType, Key: p.PublicKey} } // Reinitialise after serialisation @@ -87,7 +87,7 @@ func PrivateKeyFromRawBytes(privKeyBytes []byte, curveType CurveType) (PrivateKe return PrivateKey{}, fmt.Errorf("bytes passed have length %v but ed25519 private keys have %v bytes", len(privKeyBytes), ed25519.PrivateKeySize) } - return PrivateKey{PrivateKey: privKeyBytes, PublicKey: privKeyBytes[32:], CurveType: CurveTypeEd25519}, nil + return PrivateKey{Key: privKeyBytes, PublicKey: privKeyBytes[32:], CurveType: CurveTypeEd25519}, nil case CurveTypeSecp256k1: if len(privKeyBytes) != btcec.PrivKeyBytesLen { return PrivateKey{}, fmt.Errorf("bytes passed have length %v but secp256k1 private keys have %v bytes", @@ -97,7 +97,7 @@ func PrivateKeyFromRawBytes(privKeyBytes []byte, curveType CurveType) (PrivateKe if !bytes.Equal(privKey.Serialize(), privKeyBytes) { return PrivateKey{}, fmt.Errorf("serialisation of Secp256k1 private key bytes does not equal") } - return PrivateKey{PrivateKey: privKeyBytes, PublicKey: pubKey.SerializeCompressed(), CurveType: CurveTypeSecp256k1}, nil + return PrivateKey{Key: privKeyBytes, PublicKey: pubKey.SerializeCompressed(), CurveType: CurveTypeSecp256k1}, nil default: return PrivateKey{}, ErrInvalidCurve(curveType) } diff --git a/crypto/public_key.go b/crypto/public_key.go index f837b38d1..2d3da8262 100644 --- a/crypto/public_key.go +++ b/crypto/public_key.go @@ -34,7 +34,7 @@ func PublicKeyLength(curveType CurveType) int { func (p PublicKey) MarshalJSON() ([]byte, error) { jStruct := PublicKeyJSON{ CurveType: p.CurveType.String(), - PublicKey: hex.EncodeUpperToString(p.PublicKey), + PublicKey: hex.EncodeUpperToString(p.Key), } txt, err := json.Marshal(jStruct) return txt, err @@ -59,7 +59,7 @@ func (p *PublicKey) UnmarshalJSON(text []byte) error { return err } p.CurveType = CurveType - p.PublicKey = bs + p.Key = bs return nil } @@ -69,15 +69,15 @@ func (p *PublicKey) UnmarshalText(text []byte) error { func (p PublicKey) IsValid() bool { publicKeyLength := PublicKeyLength(p.CurveType) - return publicKeyLength != 0 && publicKeyLength == len(p.PublicKey) + return publicKeyLength != 0 && publicKeyLength == len(p.Key) } func (p PublicKey) Verify(msg []byte, signature Signature) bool { switch p.CurveType { case CurveTypeEd25519: - return ed25519.Verify(p.PublicKey, msg, signature) + return ed25519.Verify(p.Key, msg, signature) case CurveTypeSecp256k1: - pub, err := btcec.ParsePubKey(p.PublicKey, btcec.S256()) + pub, err := btcec.ParsePubKey(p.Key, btcec.S256()) if err != nil { return false } @@ -91,17 +91,21 @@ func (p PublicKey) Verify(msg []byte, signature Signature) bool { } } +func (p PublicKey) PublicKey() PublicKey { + return p +} + func (p PublicKey) Address() Address { switch p.CurveType { case CurveTypeEd25519: // FIMXE: tendermint go-crypto-0.5.0 uses weird scheme, this is fixed in 0.6.0 tmPubKey := new(tmCrypto.PubKeyEd25519) - copy(tmPubKey[:], p.PublicKey) + copy(tmPubKey[:], p.Key) addr, _ := AddressFromBytes(tmPubKey.Address()) return addr case CurveTypeSecp256k1: sha := sha256.New() - sha.Write(p.PublicKey[:]) + sha.Write(p.Key[:]) hash := ripemd160.New() hash.Write(sha.Sum(nil)) @@ -124,29 +128,35 @@ func (p PublicKey) AddressHashType() string { } func (p PublicKey) RawBytes() []byte { - return p.PublicKey[:] + return p.Key[:] } // Return the ABCI PubKey. See Tendermint protobuf.go for the go-crypto conversion this is based on func (p PublicKey) ABCIPubKey() abci.PubKey { - switch p.CurveType { - case CurveTypeEd25519: - return abci.PubKey{ - Type: "ed25519", - Data: p.RawBytes(), - } - case CurveTypeSecp256k1: - return abci.PubKey{ - Type: "secp256k1", - Data: p.RawBytes(), - } - default: - return abci.PubKey{} + return abci.PubKey{ + Type: p.CurveType.ABCIType(), + Data: p.RawBytes(), + } +} + +func PublicKeyFromABCIPubKey(pubKey abci.PubKey) (PublicKey, error) { + switch pubKey.Type { + case CurveTypeEd25519.ABCIType(): + return PublicKey{ + CurveType: CurveTypeEd25519, + Key: pubKey.Data, + }, nil + case CurveTypeSecp256k1.ABCIType(): + return PublicKey{ + CurveType: CurveTypeEd25519, + Key: pubKey.Data, + }, nil } + return PublicKey{}, fmt.Errorf("did not recognise ABCI PubKey type: %s", pubKey.Type) } func (p PublicKey) String() string { - return hex.EncodeUpperToString(p.PublicKey) + return hex.EncodeUpperToString(p.Key) } // Produces a binary encoding of the CurveType byte plus @@ -154,7 +164,7 @@ func (p PublicKey) String() string { func (p PublicKey) Encode() []byte { encoded := make([]byte, PublicKeyLength(p.CurveType)+1) encoded[0] = p.CurveType.Byte() - copy(encoded[1:], p.PublicKey) + copy(encoded[1:], p.Key) return encoded } @@ -174,7 +184,7 @@ func DecodePublicKeyFixedWidth(buf []byte, publicKey *PublicKey) (int, error) { } publicKey.CurveType = curveType - publicKey.PublicKey = buf[1:publicKeyEnd] + publicKey.Key = buf[1:publicKeyEnd] if !publicKey.IsValid() { return publicKeyEnd, fmt.Errorf("decoded public key %v is not valid", publicKey) } diff --git a/execution/executors/call_context.go b/execution/contexts/call_context.go similarity index 99% rename from execution/executors/call_context.go rename to execution/contexts/call_context.go index 0f343819c..5278b21cc 100644 --- a/execution/executors/call_context.go +++ b/execution/contexts/call_context.go @@ -1,4 +1,4 @@ -package executors +package contexts import ( "fmt" diff --git a/execution/contexts/governance_context.go b/execution/contexts/governance_context.go new file mode 100644 index 000000000..dd0a8afe9 --- /dev/null +++ b/execution/contexts/governance_context.go @@ -0,0 +1,130 @@ +package contexts + +import ( + "fmt" + "math/big" + + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/state" + "github.com/hyperledger/burrow/blockchain" + "github.com/hyperledger/burrow/execution/errors" + "github.com/hyperledger/burrow/execution/exec" + "github.com/hyperledger/burrow/genesis/spec" + "github.com/hyperledger/burrow/logging" + "github.com/hyperledger/burrow/permission" + "github.com/hyperledger/burrow/txs/payload" +) + +type GovernanceContext struct { + StateWriter state.ReaderWriter + ValidatorSet blockchain.ValidatorSet + Logger *logging.Logger + tx *payload.GovernanceTx + txe *exec.TxExecution +} + +// GovernanceTx provides a set of TemplateAccounts and GovernanceContext tries to alter the chain state to match the +// specification given +func (ctx *GovernanceContext) Execute(txe *exec.TxExecution) error { + var ok bool + ctx.txe = txe + ctx.tx, ok = txe.Envelope.Tx.Payload.(*payload.GovernanceTx) + if !ok { + return fmt.Errorf("payload must be NameTx, but is: %v", txe.Envelope.Tx.Payload) + } + accounts, err := getInputs(ctx.StateWriter, ctx.tx.Inputs) + if err != nil { + return err + } + + // ensure all inputs have root permissions + if !allHavePermission(ctx.StateWriter, permission.Root, accounts, ctx.Logger) { + return fmt.Errorf("at least one input lacks Root permission needed for GovernanceTx") + } + + for _, i := range ctx.tx.Inputs { + txe.Input(i.Address, nil) + } + + for _, update := range ctx.tx.AccountUpdates { + if update.Address == nil && update.PublicKey == nil { + // We do not want to generate a key + return fmt.Errorf("could not execution GovernanceTx since account template %v contains neither "+ + "address or public key", update) + } + if update.PublicKey != nil { + address := update.PublicKey.Address() + if update.Address != nil && address != *update.Address { + return fmt.Errorf("supplied public key %v whose address %v does not match %v provided by"+ + "GovernanceTx", update.PublicKey, address, update.Address) + } + update.Address = &address + } + if update.PublicKey == nil && update.Power != nil { + // If we are updating power we will need the key + return fmt.Errorf("GovernanceTx must be provided with public key when updating validator power") + } + account, err := state.GetMutableAccount(ctx.StateWriter, *update.Address) + if err != nil { + return err + } + if account == nil { + return fmt.Errorf("account %v not found so cannot update using template %v", update.Address, update) + } + governAccountEvent, err := ctx.updateAccount(account, update) + if err != nil { + txe.GovernAccount(governAccountEvent, errors.AsException(err)) + return err + } + txe.GovernAccount(governAccountEvent, nil) + } + return nil +} + +func (ctx *GovernanceContext) updateAccount(account *acm.MutableAccount, update *spec.TemplateAccount) (ev *exec.GovernAccountEvent, err error) { + ev = &exec.GovernAccountEvent{ + AccountUpdate: update, + } + if update.Amount != nil { + err = account.SetBalance(*update.Amount) + if err != nil { + return + } + } + if update.NodeAddress != nil { + // TODO: can we do something useful if provided with a NodeAddress for an account about to become a validator + // like add it to persistent peers or pre gossip so it gets inbound connections? If so under which circumstances? + } + if update.Power != nil { + if update.PublicKey == nil { + err = fmt.Errorf("updateAccount should have PublicKey by this point but appears not to for "+ + "template account: %v", update) + return + } + power := new(big.Int).SetUint64(*update.Power) + if !power.IsInt64() { + err = fmt.Errorf("power supplied in update to validator power for %v does not fit into int64 and "+ + "so is not supported by Tendermint", update.Address) + } + _, err := ctx.ValidatorSet.AlterPower(*update.PublicKey, power) + if err != nil { + return ev, err + } + } + perms := account.Permissions() + if len(update.Permissions) > 0 { + perms.Base, err = permission.BasePermissionsFromStringList(update.Permissions) + if err != nil { + return + } + } + if len(update.Roles) > 0 { + perms.Roles = update.Roles + } + err = account.SetPermissions(perms) + if err != nil { + return + } + err = ctx.StateWriter.UpdateAccount(account) + return +} diff --git a/execution/executors/name_context.go b/execution/contexts/name_context.go similarity index 99% rename from execution/executors/name_context.go rename to execution/contexts/name_context.go index 3be220f9f..b5ba18a83 100644 --- a/execution/executors/name_context.go +++ b/execution/contexts/name_context.go @@ -1,4 +1,4 @@ -package executors +package contexts import ( "fmt" diff --git a/execution/executors/permissions_context.go b/execution/contexts/permissions_context.go similarity index 99% rename from execution/executors/permissions_context.go rename to execution/contexts/permissions_context.go index 11730e137..4572e41cf 100644 --- a/execution/executors/permissions_context.go +++ b/execution/contexts/permissions_context.go @@ -1,4 +1,4 @@ -package executors +package contexts import ( "fmt" diff --git a/execution/executors/send_context.go b/execution/contexts/send_context.go similarity index 93% rename from execution/executors/send_context.go rename to execution/contexts/send_context.go index 813a433bf..592cb6c40 100644 --- a/execution/executors/send_context.go +++ b/execution/contexts/send_context.go @@ -1,4 +1,4 @@ -package executors +package contexts import ( "fmt" @@ -8,6 +8,7 @@ import ( "github.com/hyperledger/burrow/execution/errors" "github.com/hyperledger/burrow/execution/exec" "github.com/hyperledger/burrow/logging" + "github.com/hyperledger/burrow/permission" "github.com/hyperledger/burrow/txs/payload" ) @@ -30,7 +31,7 @@ func (ctx *SendContext) Execute(txe *exec.TxExecution) error { } // ensure all inputs have send permissions - if !hasSendPermission(ctx.StateWriter, accounts, ctx.Logger) { + if !allHavePermission(ctx.StateWriter, permission.Send, accounts, ctx.Logger) { return fmt.Errorf("at least one input lacks permission for SendTx") } diff --git a/execution/executors/shared.go b/execution/contexts/shared.go similarity index 96% rename from execution/executors/shared.go rename to execution/contexts/shared.go index 33ad90a0d..ed97bbd15 100644 --- a/execution/executors/shared.go +++ b/execution/contexts/shared.go @@ -1,4 +1,4 @@ -package executors +package contexts import ( "fmt" @@ -189,10 +189,10 @@ func HasPermission(accountGetter state.AccountGetter, acc acm.Account, perm perm } // TODO: for debug log the failed accounts -func hasSendPermission(accountGetter state.AccountGetter, accs map[crypto.Address]*acm.MutableAccount, - logger *logging.Logger) bool { +func allHavePermission(accountGetter state.AccountGetter, perm permission.PermFlag, + accs map[crypto.Address]*acm.MutableAccount, logger *logging.Logger) bool { for _, acc := range accs { - if !HasPermission(accountGetter, acc, permission.Send, logger) { + if !HasPermission(accountGetter, acc, perm, logger) { return false } } diff --git a/execution/evm/snative.go b/execution/evm/snative.go index 06254915b..d10b851df 100644 --- a/execution/evm/snative.go +++ b/execution/evm/snative.go @@ -356,7 +356,7 @@ func hasBase(state state.ReaderWriter, caller acm.Account, args []byte, gas *uin return nil, fmt.Errorf("unknown account %s", address) } permN := permission.PermFlag(Uint64FromWord256(permNum)) // already shifted - if !ValidPermN(permN) { + if !permN.IsValid() { return nil, permission.ErrInvalidPermission(permN) } hasPermission := HasPermission(state, acc, permN) @@ -382,7 +382,7 @@ func setBase(stateWriter state.ReaderWriter, caller acm.Account, args []byte, ga return nil, fmt.Errorf("unknown account %s", address) } permN := permission.PermFlag(Uint64FromWord256(permNum)) - if !ValidPermN(permN) { + if !permN.IsValid() { return nil, permission.ErrInvalidPermission(permN) } permV := !permVal.IsZero() @@ -409,7 +409,7 @@ func unsetBase(stateWriter state.ReaderWriter, caller acm.Account, args []byte, return nil, fmt.Errorf("unknown account %s", address) } permN := permission.PermFlag(Uint64FromWord256(permNum)) - if !ValidPermN(permN) { + if !permN.IsValid() { return nil, permission.ErrInvalidPermission(permN) } if err = acc.MutablePermissions().Base.Unset(permN); err != nil { @@ -435,7 +435,7 @@ func setGlobal(stateWriter state.ReaderWriter, caller acm.Account, args []byte, panic("cant find the global permissions account") } permN := permission.PermFlag(Uint64FromWord256(permNum)) - if !ValidPermN(permN) { + if !permN.IsValid() { return nil, permission.ErrInvalidPermission(permN) } permV := !permVal.IsZero() @@ -517,11 +517,6 @@ func removeRole(stateWriter state.ReaderWriter, caller acm.Account, args []byte, //------------------------------------------------------------------------------------------------ // Errors and utility funcs -// Checks if a permission flag is valid (a known base chain or snative permission) -func ValidPermN(n permission.PermFlag) bool { - return n <= permission.AllPermFlags -} - // Get the global BasePermissions func globalPerms(stateWriter state.ReaderWriter) permission.BasePermissions { return state.GlobalAccountPermissions(stateWriter).Base diff --git a/execution/exec/event.go b/execution/exec/event.go index b629a265c..eb320f07a 100644 --- a/execution/exec/event.go +++ b/execution/exec/event.go @@ -21,6 +21,7 @@ const ( TypeAccountOutput = EventType(0x03) TypeTxExecution = EventType(0x04) TypeBlockExecution = EventType(0x05) + TypeGovernAccount = EventType(0x06) ) var nameFromType = map[EventType]string{ @@ -30,6 +31,7 @@ var nameFromType = map[EventType]string{ TypeAccountOutput: "AccountOutputEvent", TypeTxExecution: "TxExecutionEvent", TypeBlockExecution: "BlockExecutionEvent", + TypeGovernAccount: "GovernAccountEvent", } var typeFromName = make(map[string]EventType) diff --git a/execution/exec/exec.pb.go b/execution/exec/exec.pb.go index 6c7cfe26c..5b4a82c98 100644 --- a/execution/exec/exec.pb.go +++ b/execution/exec/exec.pb.go @@ -16,6 +16,7 @@ Result LogEvent CallEvent + GovernAccountEvent InputEvent OutputEvent CallData @@ -32,6 +33,7 @@ import errors "github.com/hyperledger/burrow/execution/errors" import names "github.com/hyperledger/burrow/execution/names" import txs "github.com/hyperledger/burrow/txs" import permission "github.com/hyperledger/burrow/permission" +import spec "github.com/hyperledger/burrow/genesis/spec" import github_com_hyperledger_burrow_txs_payload "github.com/hyperledger/burrow/txs/payload" import github_com_hyperledger_burrow_binary "github.com/hyperledger/burrow/binary" @@ -266,11 +268,12 @@ func (*Header) XXX_MessageName() string { } type Event struct { - Header *Header `protobuf:"bytes,1,opt,name=Header" json:"Header,omitempty"` - Input *InputEvent `protobuf:"bytes,2,opt,name=Input" json:"Input,omitempty"` - Output *OutputEvent `protobuf:"bytes,3,opt,name=Output" json:"Output,omitempty"` - Call *CallEvent `protobuf:"bytes,4,opt,name=Call" json:"Call,omitempty"` - Log *LogEvent `protobuf:"bytes,5,opt,name=Log" json:"Log,omitempty"` + Header *Header `protobuf:"bytes,1,opt,name=Header" json:"Header,omitempty"` + Input *InputEvent `protobuf:"bytes,2,opt,name=Input" json:"Input,omitempty"` + Output *OutputEvent `protobuf:"bytes,3,opt,name=Output" json:"Output,omitempty"` + Call *CallEvent `protobuf:"bytes,4,opt,name=Call" json:"Call,omitempty"` + Log *LogEvent `protobuf:"bytes,5,opt,name=Log" json:"Log,omitempty"` + GovernAccount *GovernAccountEvent `protobuf:"bytes,6,opt,name=GovernAccount" json:"GovernAccount,omitempty"` } func (m *Event) Reset() { *m = Event{} } @@ -312,6 +315,13 @@ func (m *Event) GetLog() *LogEvent { return nil } +func (m *Event) GetGovernAccount() *GovernAccountEvent { + if m != nil { + return m.GovernAccount + } + return nil +} + func (*Event) XXX_MessageName() string { return "exec.Event" } @@ -410,6 +420,26 @@ func (*CallEvent) XXX_MessageName() string { return "exec.CallEvent" } +type GovernAccountEvent struct { + AccountUpdate *spec.TemplateAccount `protobuf:"bytes,1,opt,name=AccountUpdate" json:"AccountUpdate,omitempty"` +} + +func (m *GovernAccountEvent) Reset() { *m = GovernAccountEvent{} } +func (m *GovernAccountEvent) String() string { return proto.CompactTextString(m) } +func (*GovernAccountEvent) ProtoMessage() {} +func (*GovernAccountEvent) Descriptor() ([]byte, []int) { return fileDescriptorExec, []int{8} } + +func (m *GovernAccountEvent) GetAccountUpdate() *spec.TemplateAccount { + if m != nil { + return m.AccountUpdate + } + return nil +} + +func (*GovernAccountEvent) XXX_MessageName() string { + return "exec.GovernAccountEvent" +} + type InputEvent struct { Address github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,1,opt,name=Address,proto3,customtype=github.com/hyperledger/burrow/crypto.Address" json:"Address"` } @@ -417,7 +447,7 @@ type InputEvent struct { func (m *InputEvent) Reset() { *m = InputEvent{} } func (m *InputEvent) String() string { return proto.CompactTextString(m) } func (*InputEvent) ProtoMessage() {} -func (*InputEvent) Descriptor() ([]byte, []int) { return fileDescriptorExec, []int{8} } +func (*InputEvent) Descriptor() ([]byte, []int) { return fileDescriptorExec, []int{9} } func (*InputEvent) XXX_MessageName() string { return "exec.InputEvent" @@ -430,7 +460,7 @@ type OutputEvent struct { func (m *OutputEvent) Reset() { *m = OutputEvent{} } func (m *OutputEvent) String() string { return proto.CompactTextString(m) } func (*OutputEvent) ProtoMessage() {} -func (*OutputEvent) Descriptor() ([]byte, []int) { return fileDescriptorExec, []int{9} } +func (*OutputEvent) Descriptor() ([]byte, []int) { return fileDescriptorExec, []int{10} } func (*OutputEvent) XXX_MessageName() string { return "exec.OutputEvent" @@ -447,7 +477,7 @@ type CallData struct { func (m *CallData) Reset() { *m = CallData{} } func (m *CallData) String() string { return proto.CompactTextString(m) } func (*CallData) ProtoMessage() {} -func (*CallData) Descriptor() ([]byte, []int) { return fileDescriptorExec, []int{10} } +func (*CallData) Descriptor() ([]byte, []int) { return fileDescriptorExec, []int{11} } func (m *CallData) GetValue() uint64 { if m != nil { @@ -483,6 +513,8 @@ func init() { golang_proto.RegisterType((*LogEvent)(nil), "exec.LogEvent") proto.RegisterType((*CallEvent)(nil), "exec.CallEvent") golang_proto.RegisterType((*CallEvent)(nil), "exec.CallEvent") + proto.RegisterType((*GovernAccountEvent)(nil), "exec.GovernAccountEvent") + golang_proto.RegisterType((*GovernAccountEvent)(nil), "exec.GovernAccountEvent") proto.RegisterType((*InputEvent)(nil), "exec.InputEvent") golang_proto.RegisterType((*InputEvent)(nil), "exec.InputEvent") proto.RegisterType((*OutputEvent)(nil), "exec.OutputEvent") @@ -784,6 +816,16 @@ func (m *Event) MarshalTo(dAtA []byte) (int, error) { } i += n13 } + if m.GovernAccount != nil { + dAtA[i] = 0x32 + i++ + i = encodeVarintExec(dAtA, i, uint64(m.GovernAccount.Size())) + n14, err := m.GovernAccount.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n14 + } return i, nil } @@ -817,21 +859,21 @@ func (m *Result) MarshalTo(dAtA []byte) (int, error) { dAtA[i] = 0x1a i++ i = encodeVarintExec(dAtA, i, uint64(m.NameEntry.Size())) - n14, err := m.NameEntry.MarshalTo(dAtA[i:]) + n15, err := m.NameEntry.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n14 + i += n15 } if m.PermArgs != nil { dAtA[i] = 0x22 i++ i = encodeVarintExec(dAtA, i, uint64(m.PermArgs.Size())) - n15, err := m.PermArgs.MarshalTo(dAtA[i:]) + n16, err := m.PermArgs.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n15 + i += n16 } return i, nil } @@ -854,19 +896,19 @@ func (m *LogEvent) MarshalTo(dAtA []byte) (int, error) { dAtA[i] = 0xa i++ i = encodeVarintExec(dAtA, i, uint64(m.Address.Size())) - n16, err := m.Address.MarshalTo(dAtA[i:]) + n17, err := m.Address.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n16 + i += n17 dAtA[i] = 0x12 i++ i = encodeVarintExec(dAtA, i, uint64(m.Data.Size())) - n17, err := m.Data.MarshalTo(dAtA[i:]) + n18, err := m.Data.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n17 + i += n18 if len(m.Topics) > 0 { for _, msg := range m.Topics { dAtA[i] = 0x1a @@ -901,20 +943,20 @@ func (m *CallEvent) MarshalTo(dAtA []byte) (int, error) { dAtA[i] = 0xa i++ i = encodeVarintExec(dAtA, i, uint64(m.CallData.Size())) - n18, err := m.CallData.MarshalTo(dAtA[i:]) + n19, err := m.CallData.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n18 + i += n19 } dAtA[i] = 0x12 i++ i = encodeVarintExec(dAtA, i, uint64(m.Origin.Size())) - n19, err := m.Origin.MarshalTo(dAtA[i:]) + n20, err := m.Origin.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n19 + i += n20 if m.StackDepth != 0 { dAtA[i] = 0x18 i++ @@ -923,11 +965,39 @@ func (m *CallEvent) MarshalTo(dAtA []byte) (int, error) { dAtA[i] = 0x22 i++ i = encodeVarintExec(dAtA, i, uint64(m.Return.Size())) - n20, err := m.Return.MarshalTo(dAtA[i:]) + n21, err := m.Return.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n20 + i += n21 + return i, nil +} + +func (m *GovernAccountEvent) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GovernAccountEvent) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.AccountUpdate != nil { + dAtA[i] = 0xa + i++ + i = encodeVarintExec(dAtA, i, uint64(m.AccountUpdate.Size())) + n22, err := m.AccountUpdate.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n22 + } return i, nil } @@ -949,11 +1019,11 @@ func (m *InputEvent) MarshalTo(dAtA []byte) (int, error) { dAtA[i] = 0xa i++ i = encodeVarintExec(dAtA, i, uint64(m.Address.Size())) - n21, err := m.Address.MarshalTo(dAtA[i:]) + n23, err := m.Address.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n21 + i += n23 return i, nil } @@ -975,11 +1045,11 @@ func (m *OutputEvent) MarshalTo(dAtA []byte) (int, error) { dAtA[i] = 0xa i++ i = encodeVarintExec(dAtA, i, uint64(m.Address.Size())) - n22, err := m.Address.MarshalTo(dAtA[i:]) + n24, err := m.Address.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n22 + i += n24 return i, nil } @@ -1001,27 +1071,27 @@ func (m *CallData) MarshalTo(dAtA []byte) (int, error) { dAtA[i] = 0xa i++ i = encodeVarintExec(dAtA, i, uint64(m.Caller.Size())) - n23, err := m.Caller.MarshalTo(dAtA[i:]) + n25, err := m.Caller.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n23 + i += n25 dAtA[i] = 0x12 i++ i = encodeVarintExec(dAtA, i, uint64(m.Callee.Size())) - n24, err := m.Callee.MarshalTo(dAtA[i:]) + n26, err := m.Callee.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n24 + i += n26 dAtA[i] = 0x1a i++ i = encodeVarintExec(dAtA, i, uint64(m.Data.Size())) - n25, err := m.Data.MarshalTo(dAtA[i:]) + n27, err := m.Data.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n25 + i += n27 if m.Value != 0 { dAtA[i] = 0x20 i++ @@ -1166,6 +1236,10 @@ func (m *Event) Size() (n int) { l = m.Log.Size() n += 1 + l + sovExec(uint64(l)) } + if m.GovernAccount != nil { + l = m.GovernAccount.Size() + n += 1 + l + sovExec(uint64(l)) + } return n } @@ -1223,6 +1297,16 @@ func (m *CallEvent) Size() (n int) { return n } +func (m *GovernAccountEvent) Size() (n int) { + var l int + _ = l + if m.AccountUpdate != nil { + l = m.AccountUpdate.Size() + n += 1 + l + sovExec(uint64(l)) + } + return n +} + func (m *InputEvent) Size() (n int) { var l int _ = l @@ -2213,6 +2297,39 @@ func (m *Event) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field GovernAccount", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.GovernAccount == nil { + m.GovernAccount = &GovernAccountEvent{} + } + if err := m.GovernAccount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipExec(dAtA[iNdEx:]) @@ -2704,6 +2821,89 @@ func (m *CallEvent) Unmarshal(dAtA []byte) error { } return nil } +func (m *GovernAccountEvent) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GovernAccountEvent: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GovernAccountEvent: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AccountUpdate", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowExec + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthExec + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.AccountUpdate == nil { + m.AccountUpdate = &spec.TemplateAccount{} + } + if err := m.AccountUpdate.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipExec(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthExec + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func (m *InputEvent) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -3151,66 +3351,68 @@ func init() { proto.RegisterFile("exec.proto", fileDescriptorExec) } func init() { golang_proto.RegisterFile("exec.proto", fileDescriptorExec) } var fileDescriptorExec = []byte{ - // 963 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x56, 0xcd, 0x6f, 0x1b, 0x45, - 0x14, 0xef, 0xf8, 0x63, 0x6d, 0x3f, 0x3b, 0x25, 0x8c, 0x22, 0xb4, 0xea, 0xc1, 0x6b, 0xa5, 0xa8, - 0x0a, 0xa1, 0x5d, 0x23, 0x97, 0x20, 0xc1, 0xad, 0x26, 0x56, 0x93, 0x2a, 0x24, 0x68, 0x6a, 0x40, - 0x70, 0x5b, 0xef, 0x0e, 0x9b, 0x25, 0xf6, 0xee, 0x6a, 0x76, 0xb6, 0xac, 0x8f, 0x70, 0xe2, 0xc8, - 0x81, 0x03, 0xc7, 0xe6, 0x02, 0xff, 0x06, 0xc7, 0x1c, 0xb9, 0x52, 0x24, 0x0b, 0x25, 0xff, 0x45, - 0x4f, 0x68, 0x3e, 0x76, 0xbd, 0x8e, 0xaa, 0xb6, 0x6a, 0xd2, 0x4b, 0x34, 0xef, 0xbd, 0xdf, 0xfe, - 0xe6, 0x7d, 0xfc, 0xe6, 0xc5, 0x00, 0x34, 0xa3, 0xae, 0x1d, 0xb3, 0x88, 0x47, 0xb8, 0x26, 0xce, - 0xb7, 0xee, 0xf9, 0x01, 0x3f, 0x4e, 0x27, 0xb6, 0x1b, 0xcd, 0xfa, 0x7e, 0xe4, 0x47, 0x7d, 0x19, - 0x9c, 0xa4, 0xdf, 0x4b, 0x4b, 0x1a, 0xf2, 0xa4, 0x3e, 0xba, 0x75, 0xb7, 0x04, 0xe7, 0x34, 0xf4, - 0x28, 0x9b, 0x05, 0x21, 0xef, 0x3b, 0x13, 0x37, 0xe8, 0xf3, 0x79, 0x4c, 0x13, 0xf5, 0x57, 0xa3, - 0x3b, 0x94, 0xb1, 0x88, 0xe5, 0x56, 0x3b, 0x74, 0x66, 0x45, 0xa8, 0xc5, 0xb3, 0xfc, 0xb8, 0x1e, - 0x0b, 0x96, 0x24, 0x09, 0xa2, 0x50, 0x79, 0x36, 0x7f, 0x43, 0x70, 0x73, 0x38, 0x8d, 0xdc, 0x93, - 0x51, 0x46, 0xdd, 0x94, 0x07, 0x51, 0x88, 0xdf, 0x03, 0x63, 0x8f, 0x06, 0xfe, 0x31, 0x37, 0x51, - 0x0f, 0x6d, 0xd5, 0x88, 0xb6, 0xf0, 0x7d, 0x68, 0x4b, 0xe4, 0x1e, 0x75, 0x3c, 0xca, 0xcc, 0x4a, - 0x0f, 0x6d, 0xb5, 0x07, 0xef, 0xda, 0xb2, 0xce, 0x52, 0x80, 0x94, 0x51, 0x78, 0x07, 0x3a, 0xe3, - 0xac, 0xe0, 0x4e, 0xcc, 0x6a, 0xaf, 0xba, 0xfc, 0xaa, 0x14, 0x21, 0x2b, 0xb0, 0xcd, 0x4f, 0x57, - 0xee, 0xc2, 0x18, 0x6a, 0x8f, 0x1e, 0x1f, 0x1d, 0xca, 0x84, 0x5a, 0x44, 0x9e, 0x45, 0x9a, 0x87, - 0xe9, 0x6c, 0x9c, 0x25, 0x32, 0x93, 0x3a, 0xd1, 0xd6, 0xe6, 0x45, 0x15, 0xda, 0x25, 0x2e, 0xfc, - 0x08, 0x8c, 0x71, 0x36, 0x9e, 0xc7, 0x54, 0xe2, 0xd6, 0x86, 0x83, 0xe7, 0x0b, 0xcb, 0x2e, 0xf5, - 0xf6, 0x78, 0x1e, 0x53, 0x36, 0xa5, 0x9e, 0x4f, 0x59, 0x7f, 0x92, 0x32, 0x16, 0xfd, 0xd8, 0xe7, - 0x59, 0xd2, 0x8f, 0x9d, 0xf9, 0x34, 0x72, 0x3c, 0x5b, 0x7c, 0x49, 0x34, 0x03, 0xfe, 0x42, 0x70, - 0xed, 0x39, 0xc9, 0xb1, 0x59, 0xed, 0xa1, 0xad, 0xce, 0x70, 0xe7, 0x6c, 0x61, 0xdd, 0x78, 0xb6, - 0xb0, 0xee, 0xbd, 0x9c, 0x6f, 0x12, 0x84, 0x0e, 0x9b, 0xdb, 0x7b, 0x34, 0x1b, 0xce, 0x39, 0x4d, - 0x88, 0x26, 0x29, 0x75, 0xba, 0xb6, 0xd2, 0xe9, 0x0d, 0xa8, 0xef, 0x87, 0x1e, 0xcd, 0xcc, 0xba, - 0x74, 0x2b, 0x03, 0x7f, 0x0b, 0xcd, 0x51, 0xf8, 0x84, 0x4e, 0xa3, 0x98, 0x9a, 0x86, 0x6c, 0xfe, - 0x9a, 0x2d, 0x46, 0x9b, 0x3b, 0x87, 0xf6, 0xb3, 0x85, 0xb5, 0xfd, 0xca, 0xca, 0x0a, 0x3c, 0x29, - 0xe8, 0xf0, 0x6d, 0x30, 0x46, 0x4f, 0x68, 0xc8, 0x13, 0xb3, 0x21, 0xe7, 0xd3, 0x56, 0xf3, 0x91, - 0x3e, 0xa2, 0x43, 0xf8, 0x7d, 0x30, 0x08, 0x4d, 0xd2, 0x29, 0x37, 0x9b, 0xf2, 0xf6, 0x8e, 0x02, - 0x29, 0x1f, 0xd1, 0x31, 0x7c, 0x07, 0x1a, 0x84, 0xba, 0x34, 0x88, 0xb9, 0xd9, 0xd2, 0x30, 0x71, - 0xa9, 0xf6, 0x91, 0x3c, 0x88, 0xfb, 0xd0, 0x1a, 0x65, 0x2e, 0x8d, 0xc5, 0x8c, 0x4c, 0xc8, 0xb5, - 0xa4, 0x44, 0x5c, 0x04, 0xc8, 0x12, 0xf3, 0x59, 0xe7, 0x97, 0x53, 0x0b, 0xfd, 0x7a, 0x6a, 0xa1, - 0xa7, 0xa7, 0x16, 0xda, 0xfc, 0xb7, 0x22, 0x7a, 0x27, 0xc5, 0xb1, 0x1c, 0x30, 0xba, 0xc6, 0x01, - 0x57, 0xae, 0x63, 0xc0, 0x1f, 0x42, 0x4b, 0x36, 0x4f, 0x66, 0x57, 0x95, 0xd9, 0xad, 0x3d, 0x5f, - 0x58, 0x4b, 0x27, 0x59, 0x1e, 0xb1, 0x09, 0x0d, 0x69, 0xec, 0xef, 0x4a, 0x39, 0xb4, 0x48, 0x6e, - 0x96, 0x74, 0x52, 0x7f, 0xb1, 0x4e, 0x8c, 0xb2, 0x4e, 0x56, 0x3a, 0xdb, 0x78, 0x8d, 0xce, 0xae, - 0xff, 0xfe, 0xd4, 0xba, 0xb1, 0xd2, 0xdd, 0x7f, 0x10, 0xd4, 0xe5, 0xe5, 0x62, 0xe8, 0xfa, 0xbd, - 0xa3, 0xf2, 0xd0, 0xf5, 0x53, 0xcf, 0x47, 0x70, 0x47, 0x24, 0x12, 0xa7, 0x5c, 0x2f, 0x85, 0x75, - 0x05, 0x92, 0x2e, 0xa5, 0x21, 0x15, 0xc6, 0x1f, 0x80, 0x71, 0x94, 0x72, 0x01, 0xac, 0x96, 0xb7, - 0x87, 0xf2, 0x69, 0xb5, 0x29, 0x03, 0xdf, 0x86, 0xda, 0xe7, 0xce, 0x74, 0x2a, 0x5b, 0xd1, 0x1e, - 0xbc, 0xa3, 0x80, 0xc2, 0xa3, 0x60, 0x32, 0x88, 0x7b, 0x50, 0x3d, 0x88, 0x7c, 0xd9, 0x95, 0xf6, - 0xe0, 0xa6, 0xc2, 0x1c, 0x44, 0xbe, 0x82, 0x88, 0xd0, 0x0b, 0x6a, 0xfb, 0x03, 0xe5, 0x3a, 0x16, - 0x7d, 0x25, 0x94, 0xa7, 0x2c, 0x94, 0xc5, 0x75, 0x88, 0xb6, 0xc4, 0x24, 0x1e, 0x3a, 0xc9, 0x57, - 0x09, 0xf5, 0x64, 0x41, 0x35, 0x92, 0x9b, 0x78, 0x1b, 0x5a, 0x87, 0xce, 0x8c, 0x8e, 0x42, 0xce, - 0xe6, 0xba, 0x86, 0x8e, 0xad, 0x96, 0xad, 0xf4, 0x91, 0x65, 0x18, 0x7f, 0x04, 0xcd, 0x2f, 0x29, - 0x9b, 0x3d, 0x60, 0x7e, 0xa2, 0xab, 0xd8, 0xb0, 0x4b, 0xfb, 0x37, 0x8f, 0x91, 0x02, 0x75, 0x49, - 0xe2, 0x3f, 0x55, 0xa0, 0x99, 0x17, 0x83, 0x0f, 0xa1, 0xf1, 0xc0, 0xf3, 0x18, 0x4d, 0x12, 0x95, - 0xeb, 0xf0, 0x63, 0xad, 0xcc, 0xbb, 0x2f, 0x57, 0xa6, 0xcb, 0xe6, 0x31, 0x8f, 0x6c, 0xfd, 0x2d, - 0xc9, 0x49, 0xf0, 0x3e, 0xd4, 0x76, 0x1d, 0xee, 0x5c, 0x4d, 0xe6, 0x92, 0x02, 0x1f, 0x80, 0x31, - 0x8e, 0xe2, 0xc0, 0x55, 0xcb, 0xfd, 0xb5, 0x33, 0xd3, 0x64, 0xdf, 0x44, 0xcc, 0x1b, 0xec, 0x7c, - 0x42, 0x34, 0xc7, 0xa5, 0x1e, 0xfc, 0x5c, 0x81, 0x56, 0x31, 0x74, 0xbc, 0x0d, 0x4d, 0x61, 0xc8, - 0xc4, 0x51, 0x79, 0xe6, 0xb9, 0x97, 0x14, 0x71, 0x91, 0xd5, 0x11, 0x0b, 0xfc, 0x20, 0xd4, 0x25, - 0xbe, 0x59, 0xbf, 0x34, 0x07, 0xee, 0x02, 0x3c, 0xe6, 0x8e, 0x7b, 0xb2, 0x4b, 0x63, 0xae, 0x96, - 0x7f, 0x8d, 0x94, 0x3c, 0x62, 0x6f, 0x68, 0x25, 0xd5, 0xae, 0xb4, 0x37, 0x14, 0xc9, 0xa5, 0x26, - 0xfc, 0x00, 0xb0, 0x7c, 0x4a, 0xd7, 0xad, 0x84, 0x4b, 0x77, 0x9d, 0x40, 0xbb, 0xf4, 0x1a, 0xdf, - 0xf2, 0x65, 0x7f, 0x56, 0x60, 0x65, 0x60, 0xe2, 0xac, 0x37, 0xcd, 0x1b, 0x0f, 0x4c, 0x71, 0x14, - 0x6c, 0xf4, 0x6a, 0xe3, 0x57, 0x1c, 0xc5, 0x6b, 0xa9, 0x5e, 0xfd, 0xb5, 0x6c, 0x40, 0xfd, 0x6b, - 0x67, 0x9a, 0x52, 0xfd, 0x2f, 0x5f, 0x19, 0x78, 0x1d, 0xaa, 0x0f, 0x9d, 0x44, 0xaf, 0x77, 0x71, - 0x5c, 0xed, 0xd4, 0x70, 0x78, 0x76, 0xde, 0x45, 0x7f, 0x9f, 0x77, 0xd1, 0x7f, 0xe7, 0x5d, 0xf4, - 0xd7, 0x45, 0x17, 0x9d, 0x5d, 0x74, 0xd1, 0x77, 0xaf, 0x28, 0x86, 0xe6, 0xbf, 0x81, 0xe4, 0x69, - 0x62, 0xc8, 0x5f, 0x7c, 0xf7, 0xff, 0x0f, 0x00, 0x00, 0xff, 0xff, 0x4c, 0xf0, 0xd7, 0x87, 0x9a, - 0x0a, 0x00, 0x00, + // 999 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x56, 0x4f, 0x6f, 0x1b, 0x45, + 0x14, 0xef, 0xda, 0xeb, 0x7f, 0xcf, 0x76, 0x09, 0xa3, 0x80, 0x56, 0x3d, 0xd8, 0xd6, 0x16, 0x55, + 0x21, 0xb4, 0x6b, 0xe4, 0x12, 0x24, 0x40, 0x42, 0x8a, 0x89, 0x95, 0xa4, 0x0a, 0x09, 0x4c, 0x5d, + 0x10, 0x08, 0x0e, 0xeb, 0xdd, 0xc1, 0x59, 0xd5, 0xde, 0x59, 0xcd, 0xce, 0x86, 0xf5, 0x87, 0xe0, + 0xc6, 0xa1, 0xdc, 0xf8, 0x28, 0x1c, 0x73, 0x83, 0x0b, 0x97, 0x1e, 0x2c, 0x94, 0x7e, 0x04, 0x38, + 0xf5, 0x84, 0xe6, 0xcf, 0xae, 0xd7, 0x02, 0x35, 0x55, 0x92, 0x8b, 0x35, 0xef, 0xbd, 0xdf, 0xfc, + 0xe6, 0xcd, 0x7b, 0xbf, 0x37, 0x5e, 0x00, 0x92, 0x12, 0xcf, 0x89, 0x18, 0xe5, 0x14, 0x99, 0x62, + 0x7d, 0xe7, 0xc1, 0x34, 0xe0, 0xa7, 0xc9, 0xc4, 0xf1, 0xe8, 0xbc, 0x3f, 0xa5, 0x53, 0xda, 0x97, + 0xc1, 0x49, 0xf2, 0x83, 0xb4, 0xa4, 0x21, 0x57, 0x6a, 0xd3, 0x9d, 0xfb, 0x05, 0x38, 0x27, 0xa1, + 0x4f, 0xd8, 0x3c, 0x08, 0x79, 0xdf, 0x9d, 0x78, 0x41, 0x9f, 0x2f, 0x22, 0x12, 0xab, 0x5f, 0x8d, + 0x6e, 0x11, 0xc6, 0x28, 0xcb, 0xac, 0x66, 0xe8, 0xce, 0xf3, 0x50, 0x83, 0xa7, 0xd9, 0x72, 0x23, + 0x12, 0x2c, 0x71, 0x1c, 0xd0, 0x50, 0x7b, 0x20, 0x8e, 0xb2, 0x34, 0xed, 0x9f, 0x0d, 0xb8, 0x3d, + 0x9c, 0x51, 0xef, 0xe9, 0x28, 0x25, 0x5e, 0xc2, 0x03, 0x1a, 0xa2, 0xb7, 0xa1, 0x7a, 0x40, 0x82, + 0xe9, 0x29, 0xb7, 0x8c, 0x9e, 0xb1, 0x65, 0x62, 0x6d, 0xa1, 0x87, 0xd0, 0x94, 0xc8, 0x03, 0xe2, + 0xfa, 0x84, 0x59, 0xa5, 0x9e, 0xb1, 0xd5, 0x1c, 0xbc, 0xe9, 0xc8, 0x3b, 0x17, 0x02, 0xb8, 0x88, + 0x42, 0x3b, 0xd0, 0x1a, 0xa7, 0x39, 0x77, 0x6c, 0x95, 0x7b, 0xe5, 0xd5, 0xae, 0x42, 0x04, 0xaf, + 0xc1, 0xec, 0x8f, 0xd6, 0xce, 0x42, 0x08, 0xcc, 0x47, 0x8f, 0x4f, 0x8e, 0x65, 0x42, 0x0d, 0x2c, + 0xd7, 0x22, 0xcd, 0xe3, 0x64, 0x3e, 0x4e, 0x63, 0x99, 0x49, 0x05, 0x6b, 0xcb, 0xfe, 0xb3, 0x0c, + 0xcd, 0x02, 0x17, 0x7a, 0x04, 0xd5, 0x71, 0x3a, 0x5e, 0x44, 0x44, 0xe2, 0xda, 0xc3, 0xc1, 0xcb, + 0x65, 0xd7, 0x29, 0xd4, 0xf9, 0x74, 0x11, 0x11, 0x36, 0x23, 0xfe, 0x94, 0xb0, 0xfe, 0x24, 0x61, + 0x8c, 0xfe, 0xd8, 0xe7, 0x69, 0xdc, 0x8f, 0xdc, 0xc5, 0x8c, 0xba, 0xbe, 0x23, 0x76, 0x62, 0xcd, + 0x80, 0x3e, 0x17, 0x5c, 0x07, 0x6e, 0x7c, 0x6a, 0x95, 0x7b, 0xc6, 0x56, 0x6b, 0xb8, 0x73, 0xbe, + 0xec, 0xde, 0x7a, 0xbe, 0xec, 0x3e, 0x78, 0x35, 0xdf, 0x24, 0x08, 0x5d, 0xb6, 0x70, 0x0e, 0x48, + 0x3a, 0x5c, 0x70, 0x12, 0x63, 0x4d, 0x52, 0xa8, 0xb4, 0xb9, 0x56, 0xe9, 0x4d, 0xa8, 0x1c, 0x86, + 0x3e, 0x49, 0xad, 0x8a, 0x74, 0x2b, 0x03, 0x7d, 0x03, 0xf5, 0x51, 0x78, 0x46, 0x66, 0x34, 0x22, + 0x56, 0x55, 0x16, 0xbf, 0xed, 0x88, 0x36, 0x67, 0xce, 0xa1, 0xf3, 0x7c, 0xd9, 0xdd, 0xbe, 0xf4, + 0x66, 0x39, 0x1e, 0xe7, 0x74, 0xe8, 0x2e, 0x54, 0x47, 0x67, 0x24, 0xe4, 0xb1, 0x55, 0x93, 0xfd, + 0x69, 0xaa, 0xfe, 0x48, 0x1f, 0xd6, 0x21, 0xf4, 0x0e, 0x54, 0x31, 0x89, 0x93, 0x19, 0xb7, 0xea, + 0xf2, 0xf4, 0x96, 0x02, 0x29, 0x1f, 0xd6, 0x31, 0x74, 0x0f, 0x6a, 0x98, 0x78, 0x24, 0x88, 0xb8, + 0xd5, 0xd0, 0x30, 0x71, 0xa8, 0xf6, 0xe1, 0x2c, 0x88, 0xfa, 0xd0, 0x18, 0xa5, 0x1e, 0x89, 0x44, + 0x8f, 0x2c, 0xc8, 0xb4, 0xa4, 0x04, 0x9d, 0x07, 0xf0, 0x0a, 0x63, 0xff, 0x5e, 0x12, 0xd5, 0x92, + 0x72, 0x58, 0xb5, 0xd4, 0xb8, 0xc1, 0x96, 0x96, 0x6e, 0xa2, 0xa5, 0xef, 0x41, 0x43, 0x96, 0x4b, + 0x66, 0x57, 0x96, 0xd9, 0xb5, 0x5f, 0x2e, 0xbb, 0x2b, 0x27, 0x5e, 0x2d, 0x91, 0x05, 0x35, 0x69, + 0x1c, 0xee, 0x49, 0x01, 0x34, 0x70, 0x66, 0x16, 0x94, 0x51, 0xf9, 0x7f, 0x65, 0x54, 0x8b, 0xca, + 0x58, 0xab, 0x65, 0xed, 0xf2, 0x5a, 0x7e, 0x6c, 0x3e, 0xfb, 0xb5, 0x7b, 0xcb, 0xfe, 0xa9, 0x04, + 0x15, 0x79, 0xa0, 0x68, 0xad, 0x9e, 0x6a, 0xa3, 0xd8, 0x5a, 0x3d, 0xd0, 0x59, 0xd9, 0xef, 0x89, + 0xc3, 0xa3, 0x84, 0xeb, 0xd1, 0xdf, 0x50, 0x20, 0xe9, 0x52, 0x4a, 0x51, 0x61, 0xf4, 0x2e, 0x54, + 0x4f, 0x12, 0x2e, 0x80, 0xe5, 0xe2, 0x1b, 0xa1, 0x7c, 0x5a, 0x53, 0xca, 0x40, 0x77, 0xc1, 0xfc, + 0xcc, 0x9d, 0xcd, 0xe4, 0xf5, 0x9b, 0x83, 0x37, 0x14, 0x50, 0x78, 0x14, 0x4c, 0x06, 0x51, 0x0f, + 0xca, 0x47, 0x74, 0x2a, 0x2b, 0xd1, 0x1c, 0xdc, 0x56, 0x98, 0x23, 0x3a, 0x55, 0x10, 0x11, 0x42, + 0x9f, 0x42, 0x7b, 0x9f, 0x9e, 0x11, 0x16, 0xee, 0x7a, 0x1e, 0x4d, 0x42, 0xae, 0xe7, 0xc3, 0x52, + 0xd8, 0xb5, 0x90, 0xda, 0xb5, 0x0e, 0xd7, 0xf5, 0x78, 0x66, 0x64, 0x0a, 0x17, 0xf5, 0xc7, 0x84, + 0x27, 0x2c, 0x94, 0x05, 0x69, 0x61, 0x6d, 0x89, 0x8e, 0xed, 0xbb, 0xf1, 0x93, 0x98, 0xf8, 0xb2, + 0x08, 0x26, 0xce, 0x4c, 0xb4, 0x0d, 0x8d, 0x63, 0x77, 0x4e, 0x46, 0x21, 0x67, 0x0b, 0x7d, 0xef, + 0x96, 0xa3, 0x9e, 0x64, 0xe9, 0xc3, 0xab, 0x30, 0x7a, 0x1f, 0xea, 0x5f, 0x10, 0x36, 0xdf, 0x65, + 0xd3, 0x58, 0xdf, 0x7c, 0xd3, 0x29, 0xbc, 0xd2, 0x59, 0x0c, 0xe7, 0x28, 0xfb, 0x6f, 0x03, 0xea, + 0xd9, 0x95, 0xd1, 0x31, 0xd4, 0x76, 0x7d, 0x9f, 0x91, 0x38, 0x56, 0xd9, 0x0d, 0x3f, 0xd0, 0x9a, + 0xbd, 0xff, 0x6a, 0xcd, 0x7a, 0x6c, 0x11, 0x71, 0xea, 0xe8, 0xbd, 0x38, 0x23, 0x41, 0x87, 0x60, + 0xee, 0xb9, 0xdc, 0xbd, 0xde, 0x00, 0x48, 0x0a, 0x74, 0x04, 0xd5, 0x31, 0x8d, 0x02, 0x4f, 0x3d, + 0xf4, 0xaf, 0x9d, 0x99, 0x26, 0xfb, 0x9a, 0x32, 0x7f, 0xb0, 0xf3, 0x21, 0xd6, 0x1c, 0xf6, 0x3f, + 0x06, 0x34, 0x72, 0x31, 0xa0, 0x6d, 0xa8, 0x0b, 0x43, 0xa6, 0x6a, 0x14, 0xb5, 0x90, 0x79, 0x71, + 0x1e, 0x17, 0x79, 0x9c, 0xb0, 0x60, 0x1a, 0x84, 0xfa, 0x52, 0x57, 0xab, 0x90, 0xe6, 0x40, 0x1d, + 0x80, 0xc7, 0xdc, 0xf5, 0x9e, 0xee, 0x91, 0x88, 0xab, 0xa7, 0xdf, 0xc4, 0x05, 0x8f, 0x78, 0x43, + 0xb4, 0x5a, 0xcc, 0x6b, 0xbd, 0x21, 0x8a, 0xc4, 0xfe, 0x12, 0xd0, 0x7f, 0x25, 0x8b, 0x3e, 0x81, + 0xb6, 0xb6, 0x9f, 0x44, 0xbe, 0xcb, 0x89, 0xae, 0xc1, 0x5b, 0x8e, 0xfc, 0x37, 0x1f, 0x93, 0x79, + 0x34, 0x73, 0x39, 0xd1, 0x10, 0xbc, 0x8e, 0xb5, 0xbf, 0x03, 0x58, 0xcd, 0xe9, 0x4d, 0x0b, 0xc8, + 0xfe, 0x1e, 0x9a, 0x85, 0xe1, 0xbe, 0x71, 0xfa, 0x5f, 0x4a, 0xb0, 0xd6, 0x59, 0xb1, 0xd6, 0x4f, + 0xd5, 0x95, 0x3b, 0xab, 0x38, 0x72, 0x36, 0x72, 0x3d, 0x9d, 0x28, 0x8e, 0x7c, 0x90, 0xca, 0xd7, + 0x1f, 0xa4, 0x4d, 0xa8, 0x7c, 0xe5, 0xce, 0x12, 0xa2, 0xbf, 0x0c, 0x94, 0x81, 0x36, 0xa0, 0xbc, + 0xef, 0xc6, 0xfa, 0x3f, 0x41, 0x2c, 0x87, 0xc3, 0xf3, 0x8b, 0x8e, 0xf1, 0xc7, 0x45, 0xc7, 0xf8, + 0xeb, 0xa2, 0x63, 0xfc, 0xf6, 0xa2, 0x63, 0x9c, 0xbf, 0xe8, 0x18, 0xdf, 0x5e, 0x92, 0x3e, 0xc9, + 0x3e, 0x8e, 0xe4, 0x6a, 0x52, 0x95, 0x9f, 0x82, 0x0f, 0xff, 0x0d, 0x00, 0x00, 0xff, 0xff, 0x47, + 0x90, 0xbb, 0xef, 0xbf, 0x0a, 0x00, 0x00, } diff --git a/execution/exec/govern_account_event.go b/execution/exec/govern_account_event.go new file mode 100644 index 000000000..81c33c44f --- /dev/null +++ b/execution/exec/govern_account_event.go @@ -0,0 +1 @@ +package exec diff --git a/execution/exec/tx_execution.go b/execution/exec/tx_execution.go index 493af2920..9de377ffe 100644 --- a/execution/exec/tx_execution.go +++ b/execution/exec/tx_execution.go @@ -15,9 +15,10 @@ import ( func EventStringAccountInput(addr crypto.Address) string { return fmt.Sprintf("Acc/%s/Input", addr) } func EventStringAccountOutput(addr crypto.Address) string { return fmt.Sprintf("Acc/%s/Output", addr) } -func EventStringAccountCall(addr crypto.Address) string { return fmt.Sprintf("Acc/%s/Call", addr) } -func EventStringLogEvent(addr crypto.Address) string { return fmt.Sprintf("Log/%s", addr) } -func EventStringTxExecution(txHash []byte) string { return fmt.Sprintf("Execution/Tx/%X", txHash) } +func EventStringAccountCall(addr crypto.Address) string { return fmt.Sprintf("Acc/%s/Call", addr) } +func EventStringLogEvent(addr crypto.Address) string { return fmt.Sprintf("Log/%s", addr) } +func EventStringTxExecution(txHash []byte) string { return fmt.Sprintf("Execution/Tx/%X", txHash) } +func EventStringGovernAccount(addr *crypto.Address) string { return fmt.Sprintf("Govern/Acc/%v", addr) } func NewTxExecution(txEnv *txs.Envelope) *TxExecution { return &TxExecution{ @@ -89,6 +90,13 @@ func (txe *TxExecution) Call(call *CallEvent, exception *errors.Exception) { }) } +func (txe *TxExecution) GovernAccount(governAccount *GovernAccountEvent, exception *errors.Exception) { + txe.Append(&Event{ + Header: txe.Header(TypeCall, EventStringGovernAccount(governAccount.AccountUpdate.Address), exception), + GovernAccount: governAccount, + }) +} + // Set result func (txe *TxExecution) Return(returnValue []byte, gasUsed uint64) { if txe.Result == nil { diff --git a/execution/execution.go b/execution/execution.go index 23412014e..d88d45bc2 100644 --- a/execution/execution.go +++ b/execution/execution.go @@ -18,6 +18,7 @@ import ( "fmt" "runtime/debug" "sync" + "time" "context" @@ -27,14 +28,15 @@ import ( bcm "github.com/hyperledger/burrow/blockchain" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/event" + "github.com/hyperledger/burrow/execution/contexts" "github.com/hyperledger/burrow/execution/evm" "github.com/hyperledger/burrow/execution/exec" - "github.com/hyperledger/burrow/execution/executors" "github.com/hyperledger/burrow/execution/names" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" "github.com/hyperledger/burrow/txs" "github.com/hyperledger/burrow/txs/payload" + "github.com/pkg/errors" abciTypes "github.com/tendermint/abci/types" ) @@ -67,13 +69,13 @@ type BatchCommitter interface { BatchExecutor // Commit execution results to underlying State and provide opportunity // to mutate state before it is saved - Commit(*abciTypes.Header) (stateHash []byte, err error) + Commit(blockHash []byte, blockTime time.Time, header *abciTypes.Header) (stateHash []byte, err error) } type executor struct { sync.RWMutex runCall bool - tip bcm.TipInfo + blockchain *bcm.Blockchain state ExecutorState stateCache *state.Cache nameRegCache *names.Cache @@ -87,32 +89,32 @@ type executor struct { var _ BatchExecutor = (*executor)(nil) // Wraps a cache of what is variously known as the 'check cache' and 'mempool' -func NewBatchChecker(backend ExecutorState, tip bcm.TipInfo, logger *logging.Logger, +func NewBatchChecker(backend ExecutorState, blockchain *bcm.Blockchain, logger *logging.Logger, options ...ExecutionOption) BatchExecutor { - return newExecutor("CheckCache", false, backend, tip, event.NewNoOpPublisher(), + return newExecutor("CheckCache", false, backend, blockchain, event.NewNoOpPublisher(), logger.WithScope("NewBatchExecutor"), options...) } -func NewBatchCommitter(backend ExecutorState, tip bcm.TipInfo, emitter event.Publisher, logger *logging.Logger, +func NewBatchCommitter(backend ExecutorState, blockchain *bcm.Blockchain, emitter event.Publisher, logger *logging.Logger, options ...ExecutionOption) BatchCommitter { - return newExecutor("CommitCache", true, backend, tip, emitter, + return newExecutor("CommitCache", true, backend, blockchain, emitter, logger.WithScope("NewBatchCommitter"), options...) } -func newExecutor(name string, runCall bool, backend ExecutorState, tip bcm.TipInfo, publisher event.Publisher, +func newExecutor(name string, runCall bool, backend ExecutorState, blockchain *bcm.Blockchain, publisher event.Publisher, logger *logging.Logger, options ...ExecutionOption) *executor { exe := &executor{ runCall: runCall, state: backend, - tip: tip, + blockchain: blockchain, stateCache: state.NewCache(backend, state.Name(name)), nameRegCache: names.NewCache(backend), publisher: publisher, blockExecution: &exec.BlockExecution{ - Height: tip.LastBlockHeight() + 1, + Height: blockchain.LastBlockHeight() + 1, }, logger: logger.With(structure.ComponentKey, "Executor"), } @@ -120,29 +122,34 @@ func newExecutor(name string, runCall bool, backend ExecutorState, tip bcm.TipIn option(exe) } exe.txExecutors = map[payload.Type]Context{ - payload.TypeSend: &executors.SendContext{ - Tip: tip, + payload.TypeSend: &contexts.SendContext{ + Tip: blockchain, StateWriter: exe.stateCache, Logger: exe.logger, }, - payload.TypeCall: &executors.CallContext{ - Tip: tip, + payload.TypeCall: &contexts.CallContext{ + Tip: blockchain, StateWriter: exe.stateCache, RunCall: runCall, VMOptions: exe.vmOptions, Logger: exe.logger, }, - payload.TypeName: &executors.NameContext{ - Tip: tip, + payload.TypeName: &contexts.NameContext{ + Tip: blockchain, StateWriter: exe.stateCache, NameReg: exe.nameRegCache, Logger: exe.logger, }, - payload.TypePermissions: &executors.PermissionsContext{ - Tip: tip, + payload.TypePermissions: &contexts.PermissionsContext{ + Tip: blockchain, StateWriter: exe.stateCache, Logger: exe.logger, }, + payload.TypeGovernance: &contexts.GovernanceContext{ + ValidatorSet: blockchain, + StateWriter: exe.stateCache, + Logger: exe.logger, + }, } return exe } @@ -198,7 +205,8 @@ func (exe *executor) finaliseBlockExecution(header *abciTypes.Header) (*exec.Blo return be, nil } -func (exe *executor) Commit(header *abciTypes.Header) (_ []byte, err error) { +func (exe *executor) Commit(blockHash []byte, blockTime time.Time, header *abciTypes.Header) (_ []byte, err error) { + // The write lock to the executor is controlled by the caller (e.g. abci.App) so we do not acquire it here to avoid // deadlock defer func() { @@ -212,6 +220,9 @@ func (exe *executor) Commit(header *abciTypes.Header) (_ []byte, err error) { if err != nil { return nil, err } + + // First commit the app state, this app hash will not get checkpointed until the next block when we are sure + // that nothing in the downstream commit process could have failed. At worst we go back one block. hash, err := exe.state.Update(func(ws Updatable) error { // flush the caches err := exe.stateCache.Flush(ws, exe.state) @@ -242,6 +253,14 @@ func (exe *executor) Commit(header *abciTypes.Header) (_ []byte, err error) { exe.logger.InfoMsg("Error publishing TxExecution", "height", blockExecution.Height, structure.ErrorKey, publishErr) + + // Commit to our blockchain state which will checkpoint the previous app hash by saving it to the database + // (we know the previous app hash is safely committed because we are about to commit the next) + err = exe.blockchain.CommitBlock(blockTime, blockHash, hash) + if err != nil { + panic(errors.Wrap(err, "could not commit block to blockchain state")) + } + return hash, nil } diff --git a/execution/execution_test.go b/execution/execution_test.go index 608da343c..033c55412 100644 --- a/execution/execution_test.go +++ b/execution/execution_test.go @@ -123,15 +123,13 @@ var testChainID = testGenesisDoc.ChainID() type testExecutor struct { *executor - blockchain *bcm.Blockchain } func makeExecutor(state *State) *testExecutor { blockchain := newBlockchain(testGenesisDoc) return &testExecutor{ - executor: newExecutor("makeExecutorCache", true, state, blockchain.Tip, event.NewNoOpPublisher(), + executor: newExecutor("makeExecutorCache", true, state, blockchain, event.NewNoOpPublisher(), logger), - blockchain: blockchain, } } @@ -145,11 +143,8 @@ func (te *testExecutor) signExecuteCommit(tx payload.Payload, signer acm.Address if err != nil { return err } - appHash, err := te.Commit(nil) - if err != nil { - return err - } - return te.blockchain.CommitBlock(time.Now(), nil, appHash) + _, err = te.Commit(nil, time.Now(), nil) + return err } func makeUsers(n int) []acm.AddressableSigner { @@ -1546,7 +1541,7 @@ func TestSelfDestruct(t *testing.T) { tx := payload.NewCallTxWithSequence(acc0PubKey, addressPtr(acc1), nil, sendingAmount, 1000, 0, acc0.Sequence()+1) // we use cache instead of execTxWithState so we can run the tx twice - exe := NewBatchCommitter(st, newBlockchain(testGenesisDoc).Tip, event.NewNoOpPublisher(), logger) + exe := NewBatchCommitter(st, newBlockchain(testGenesisDoc), event.NewNoOpPublisher(), logger) signAndExecute(t, false, exe, testChainID, tx, privAccounts[0]) // if we do it again, we won't get an error, but the self-destruct @@ -1555,7 +1550,8 @@ func TestSelfDestruct(t *testing.T) { signAndExecute(t, false, exe, testChainID, tx, privAccounts[0]) // commit the block - exe.Commit(nil) + _, err = exe.Commit([]byte("Blocky McHash"), time.Now(), nil) + require.NoError(t, err) // acc2 should receive the sent funds and the contracts balance newAcc2 := getAccount(st, acc2.Address()) @@ -1585,12 +1581,12 @@ func signAndExecute(t *testing.T, shouldFail bool, exe BatchExecutor, chainID st } func execTxWithStateAndBlockchain(state *State, blockchain *bcm.Blockchain, txEnv *txs.Envelope) error { - exe := newExecutor("execTxWithStateAndBlockchainCache", true, state, blockchain.Tip, + exe := newExecutor("execTxWithStateAndBlockchainCache", true, state, blockchain, event.NewNoOpPublisher(), logger) if _, err := exe.Execute(txEnv); err != nil { return err } else { - _, err := exe.Commit(nil) + _, err = exe.Commit([]byte("Blocky McHash"), time.Now(), nil) if err != nil { return err } @@ -1660,7 +1656,7 @@ func execTxWaitAccountCall(t *testing.T, exe *testExecutor, txEnv *txs.Envelope, if err != nil { return nil, err } - _, err = exe.Commit(nil) + _, err = exe.Commit([]byte("Blocky McHash"), time.Now(), nil) require.NoError(t, err) err = exe.blockchain.CommitBlock(time.Time{}, nil, nil) require.NoError(t, err) diff --git a/execution/simulated_call.go b/execution/simulated_call.go index fc7156a41..d921b5e45 100644 --- a/execution/simulated_call.go +++ b/execution/simulated_call.go @@ -9,9 +9,9 @@ import ( "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/blockchain" "github.com/hyperledger/burrow/crypto" + "github.com/hyperledger/burrow/execution/contexts" "github.com/hyperledger/burrow/execution/evm" "github.com/hyperledger/burrow/execution/exec" - "github.com/hyperledger/burrow/execution/executors" "github.com/hyperledger/burrow/logging" ) @@ -70,6 +70,6 @@ func vmParams(tip blockchain.TipInfo) evm.Params { BlockHeight: tip.LastBlockHeight(), BlockHash: binary.LeftPadWord256(tip.LastBlockHash()), BlockTime: tip.LastBlockTime().Unix(), - GasLimit: executors.GasLimit, + GasLimit: contexts.GasLimit, } } diff --git a/execution/transactor_test.go b/execution/transactor_test.go index f8c638954..0d6df572d 100644 --- a/execution/transactor_test.go +++ b/execution/transactor_test.go @@ -38,7 +38,7 @@ import ( func TestTransactor_BroadcastTxSync(t *testing.T) { chainID := "TestChain" - tip := blockchain.NewTip(chainID, time.Time{}, []byte("genesis")) + tip := blockchain.NewTip(chainID, time.Time{}, []byte("genesis"), blockchain.NewValidators()) logger := logging.NewNoopLogger() evc := event.NewEmitter(logger) txCodec := txs.NewAminoCodec() diff --git a/genesis/deterministic_genesis.go b/genesis/deterministic_genesis.go index 6c4e6a209..15708c9e6 100644 --- a/genesis/deterministic_genesis.go +++ b/genesis/deterministic_genesis.go @@ -59,7 +59,7 @@ func (dg *deterministicGenesis) GenesisDoc(numAccounts int, randBalance bool, mi } return &GenesisDoc{ ChainName: "TestChain", - GenesisTime: time.Unix(1506172037, 0), + GenesisTime: time.Unix(1506172037, 0).UTC(), Accounts: accounts, Validators: validators, }, privAccounts, privValidators diff --git a/genesis/genesis.go b/genesis/genesis.go index 6d91fd472..c98607e1b 100644 --- a/genesis/genesis.go +++ b/genesis/genesis.go @@ -66,10 +66,10 @@ type GenesisDoc struct { Validators []Validator } -// JSONBytes returns the JSON (not-yet) canonical bytes for a given -// GenesisDoc or an error. +// JSONBytes returns the JSON canonical bytes for a given GenesisDoc or an error. func (genesisDoc *GenesisDoc) JSONBytes() ([]byte, error) { - // TODO: write JSON in canonical order + // Just in case + genesisDoc.GenesisTime = genesisDoc.GenesisTime.UTC() return json.MarshalIndent(genesisDoc, "", "\t") } diff --git a/genesis/spec/genesis_spec.go b/genesis/spec/genesis_spec.go index cb4fb76cf..de96d9a74 100644 --- a/genesis/spec/genesis_spec.go +++ b/genesis/spec/genesis_spec.go @@ -75,7 +75,7 @@ func (gs *GenesisSpec) GenesisDoc(keyClient keys.KeyClient, generateNodeKeys boo } for i, templateAccount := range templateAccounts { - account, err := templateAccount.Account(keyClient, i) + account, err := templateAccount.GenesisAccount(keyClient, i) if err != nil { return nil, fmt.Errorf("could not create Account from template: %v", err) } diff --git a/genesis/spec/template_account.go b/genesis/spec/template_account.go index 1362ec117..b4ce1fa46 100644 --- a/genesis/spec/template_account.go +++ b/genesis/spec/template_account.go @@ -55,7 +55,7 @@ func (ta TemplateAccount) AccountPermissions() (permission.AccountPermissions, e }, nil } -func (ta TemplateAccount) Account(keyClient keys.KeyClient, index int) (*genesis.Account, error) { +func (ta TemplateAccount) GenesisAccount(keyClient keys.KeyClient, index int) (*genesis.Account, error) { var err error ga := new(genesis.Account) ga.PublicKey, ga.Address, err = ta.RealisePubKeyAndAddress(keyClient) diff --git a/integration/governance/main_test.go b/integration/governance/main_test.go new file mode 100644 index 000000000..684d6a13b --- /dev/null +++ b/integration/governance/main_test.go @@ -0,0 +1,47 @@ +// +build integration + +// Space above here matters +// Copyright 2017 Monax Industries Limited +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package governance + +import ( + "context" + "os" + "testing" + + "github.com/hyperledger/burrow/core" + "github.com/hyperledger/burrow/integration" + "github.com/hyperledger/burrow/integration/rpctest" +) + +var _ = integration.ClaimPorts() +var inputAddress = rpctest.PrivateAccounts[0].Address() +var testConfig = integration.NewTestConfig(rpctest.GenesisDoc) +var kern *core.Kernel + +// Needs to be in a _test.go file to be picked up +func TestMain(m *testing.M) { + kern = integration.TestKernel(rpctest.PrivateAccounts, testConfig) + err := kern.Boot() + if err != nil { + panic(err) + } + // Sometimes better to not shutdown as logging errors on shutdown may obscure real issue + defer func() { + kern.Shutdown(context.Background()) + }() + os.Exit(m.Run()) +} diff --git a/integration/governance/validators_test.go b/integration/governance/validators_test.go new file mode 100644 index 000000000..07b8008d0 --- /dev/null +++ b/integration/governance/validators_test.go @@ -0,0 +1,7 @@ +package governance + +import "testing" + +func TestName(t *testing.T) { + +} diff --git a/integration/integration.go b/integration/integration.go index 388cae7d6..cda7523b1 100644 --- a/integration/integration.go +++ b/integration/integration.go @@ -59,7 +59,7 @@ const startingPortBuckets = 1000 var port = uint32(startingPort) // We use this to wrap tests -func TestWrapper(privateAccounts []*acm.PrivateAccount, testConfig *config.BurrowConfig, runner func(*core.Kernel) int) int { +func TestKernel(privateAccounts []*acm.PrivateAccount, testConfig *config.BurrowConfig) *core.Kernel { fmt.Println("Running with integration TestWrapper (core/integration/integration.go)...") os.RemoveAll(testDir) @@ -101,17 +101,8 @@ func TestWrapper(privateAccounts []*acm.PrivateAccount, testConfig *config.Burro if err != nil { panic(err) } - // Sometimes better to not shutdown as logging errors on shutdown may obscure real issue - defer func() { - kernel.Shutdown(context.Background()) - }() - err = kernel.Boot() - if err != nil { - panic(err) - } - - return runner(kernel) + return kernel } func TestGenesisDoc(addressables []*acm.PrivateAccount) *genesis.GenesisDoc { diff --git a/integration/rpcevents/main_test.go b/integration/rpcevents/main_test.go index 8418fbd74..1a842bd95 100644 --- a/integration/rpcevents/main_test.go +++ b/integration/rpcevents/main_test.go @@ -18,6 +18,7 @@ package rpcevents import ( + "context" "os" "testing" @@ -33,11 +34,14 @@ var kern *core.Kernel // Needs to be in a _test.go file to be picked up func TestMain(m *testing.M) { - returnValue := integration.TestWrapper(rpctest.PrivateAccounts, testConfig, - func(k *core.Kernel) int { - kern = k - return m.Run() - }) - - os.Exit(returnValue) + kern = integration.TestKernel(rpctest.PrivateAccounts, testConfig) + err := kern.Boot() + if err != nil { + panic(err) + } + // Sometimes better to not shutdown as logging errors on shutdown may obscure real issue + defer func() { + kern.Shutdown(context.Background()) + }() + os.Exit(m.Run()) } diff --git a/integration/rpcquery/main_test.go b/integration/rpcquery/main_test.go index 423a22bd5..9f13b06be 100644 --- a/integration/rpcquery/main_test.go +++ b/integration/rpcquery/main_test.go @@ -18,6 +18,7 @@ package rpcquery import ( + "context" "os" "testing" @@ -32,11 +33,14 @@ var kern *core.Kernel // Needs to be in a _test.go file to be picked up func TestMain(m *testing.M) { - returnValue := integration.TestWrapper(rpctest.PrivateAccounts, testConfig, - func(k *core.Kernel) int { - kern = k - return m.Run() - }) - - os.Exit(returnValue) + kern = integration.TestKernel(rpctest.PrivateAccounts, testConfig) + err := kern.Boot() + if err != nil { + panic(err) + } + // Sometimes better to not shutdown as logging errors on shutdown may obscure real issue + defer func() { + kern.Shutdown(context.Background()) + }() + os.Exit(m.Run()) } diff --git a/integration/rpctransact/main_test.go b/integration/rpctransact/main_test.go index bda89290e..1f773a001 100644 --- a/integration/rpctransact/main_test.go +++ b/integration/rpctransact/main_test.go @@ -18,6 +18,7 @@ package rpctransact import ( + "context" "os" "testing" @@ -32,11 +33,14 @@ var kern *core.Kernel // Needs to be in a _test.go file to be picked up func TestMain(m *testing.M) { - returnValue := integration.TestWrapper(rpctest.PrivateAccounts, testConfig, - func(k *core.Kernel) int { - kern = k - return m.Run() - }) - - os.Exit(returnValue) + kern = integration.TestKernel(rpctest.PrivateAccounts, testConfig) + err := kern.Boot() + if err != nil { + panic(err) + } + // Sometimes better to not shutdown as logging errors on shutdown may obscure real issue + defer func() { + kern.Shutdown(context.Background()) + }() + os.Exit(m.Run()) } diff --git a/integration/tm/main_test.go b/integration/tm/main_test.go index cdee8c090..627fa6d28 100644 --- a/integration/tm/main_test.go +++ b/integration/tm/main_test.go @@ -18,6 +18,7 @@ package tm import ( + "context" "os" "testing" @@ -40,10 +41,14 @@ var clients = map[string]tmClient.RPCClient{ // Needs to be in a _test.go file to be picked up func TestMain(m *testing.M) { - returnValue := integration.TestWrapper(rpctest.PrivateAccounts, testConfig, func(k *core.Kernel) int { - kern = k - return m.Run() - }) - - os.Exit(returnValue) + kern = integration.TestKernel(rpctest.PrivateAccounts, testConfig) + err := kern.Boot() + if err != nil { + panic(err) + } + // Sometimes better to not shutdown as logging errors on shutdown may obscure real issue + defer func() { + kern.Shutdown(context.Background()) + }() + os.Exit(m.Run()) } diff --git a/keys/server.go b/keys/server.go index 5613a7b52..1ba471afb 100644 --- a/keys/server.go +++ b/keys/server.go @@ -75,8 +75,8 @@ func (k *KeyStore) Export(ctx context.Context, in *ExportRequest) (*ExportRespon return &ExportResponse{ Address: addrB[:], CurveType: key.CurveType.String(), - Publickey: key.PublicKey.PublicKey[:], - Privatekey: key.PrivateKey.PrivateKey[:], + Publickey: key.PublicKey.Key[:], + Privatekey: key.PrivateKey.Key[:], }, nil } diff --git a/permission/perm_flag.go b/permission/perm_flag.go index 617aa561f..2ddece98d 100644 --- a/permission/perm_flag.go +++ b/permission/perm_flag.go @@ -76,6 +76,11 @@ const ( // A particular permission type PermFlag uint64 +// Checks if a permission flag is valid (a known base chain or snative permission) +func (pf PermFlag) IsValid() bool { + return pf <= AllPermFlags +} + // Returns the string name of a single bit non-composite PermFlag, or otherwise UnknownString // See BasePermissionsToStringList to generate a string representation of a composite PermFlag func (pf PermFlag) String() string { diff --git a/protobuf/crypto.proto b/protobuf/crypto.proto index 425236f4c..9b95283b3 100644 --- a/protobuf/crypto.proto +++ b/protobuf/crypto.proto @@ -16,7 +16,7 @@ option (gogoproto.messagename_all) = true; message PublicKey { option (gogoproto.goproto_stringer) = false; uint32 CurveType = 1 [(gogoproto.casttype) = "CurveType"]; - bytes PublicKey = 2; + bytes Key = 2; } message PrivateKey { @@ -25,5 +25,5 @@ message PrivateKey { uint32 CurveType = 1 [(gogoproto.casttype) = "CurveType"]; // Note may need initialisation bytes PublicKey = 2; - bytes PrivateKey = 3; + bytes Key = 3; } diff --git a/protobuf/exec.proto b/protobuf/exec.proto index 6eb935117..58a8b2c98 100644 --- a/protobuf/exec.proto +++ b/protobuf/exec.proto @@ -11,6 +11,7 @@ import "errors.proto"; import "names.proto"; import "txs.proto"; import "permission.proto"; +import "spec.proto"; option (gogoproto.marshaler_all) = true; option (gogoproto.unmarshaler_all) = true; @@ -33,9 +34,6 @@ message BlockHeader { } message TxExecution { - option (gogoproto.sizer) = true; - option (gogoproto.marshaler) = true; - option (gogoproto.unmarshaler) = true; // Transaction type uint32 TxType = 2 [(gogoproto.casttype) = "github.com/hyperledger/burrow/txs/payload.Type"]; // The hash of the transaction that caused this event to be generated @@ -58,9 +56,6 @@ message TxExecution { message Header { option (gogoproto.goproto_stringer) = false; - option (gogoproto.sizer) = true; - option (gogoproto.marshaler) = true; - option (gogoproto.unmarshaler) = true; // Transaction type uint32 TxType = 1 [(gogoproto.casttype) = "github.com/hyperledger/burrow/txs/payload.Type"]; // The hash of the transaction that caused this event to be generated @@ -78,22 +73,17 @@ message Header { } message Event { - option (gogoproto.sizer) = true; - option (gogoproto.marshaler) = true; - option (gogoproto.unmarshaler) = true; option (gogoproto.goproto_stringer) = false; Header Header = 1; InputEvent Input = 2; OutputEvent Output = 3; CallEvent Call = 4; LogEvent Log = 5; + GovernAccountEvent GovernAccount = 6; } // Could structure this further if needed - sum type of various results relevant to different transaction types message Result { - option (gogoproto.sizer) = true; - option (gogoproto.marshaler) = true; - option (gogoproto.unmarshaler) = true; // EVM execution return bytes Return = 1; // Gas used in computation @@ -105,42 +95,31 @@ message Result { } message LogEvent { - option (gogoproto.sizer) = true; - option (gogoproto.marshaler) = true; - option (gogoproto.unmarshaler) = true; bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false]; bytes Data = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false]; repeated bytes Topics = 3 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.Word256", (gogoproto.nullable) = false]; } message CallEvent { - option (gogoproto.sizer) = true; - option (gogoproto.marshaler) = true; - option (gogoproto.unmarshaler) = true; CallData CallData = 1; bytes Origin = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false]; uint64 StackDepth = 3; bytes Return = 4 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false]; } +message GovernAccountEvent { + spec.TemplateAccount AccountUpdate = 1; +} + message InputEvent { - option (gogoproto.sizer) = true; - option (gogoproto.marshaler) = true; - option (gogoproto.unmarshaler) = true; bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false]; } message OutputEvent { - option (gogoproto.sizer) = true; - option (gogoproto.marshaler) = true; - option (gogoproto.unmarshaler) = true; bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false]; } message CallData { - option (gogoproto.sizer) = true; - option (gogoproto.marshaler) = true; - option (gogoproto.unmarshaler) = true; bytes Caller = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false]; bytes Callee = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false]; bytes Data = 3 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false]; diff --git a/rpc/service.go b/rpc/service.go index 098dd1503..42ebc1cf3 100644 --- a/rpc/service.go +++ b/rpc/service.go @@ -17,6 +17,7 @@ package rpc import ( "encoding/json" "fmt" + "math/big" "time" "github.com/hyperledger/burrow/acm" @@ -323,11 +324,11 @@ func (s *Service) ListBlocks(minHeight, maxHeight uint64) (*ResultListBlocks, er func (s *Service) ListValidators() (*ResultListValidators, error) { concreteValidators := make([]*acm.ConcreteValidator, 0, s.blockchain.NumValidators()) - s.blockchain.IterateValidators(func(publicKey crypto.PublicKey, power uint64) (stop bool) { + s.blockchain.IterateValidators(func(id crypto.Addressable, power *big.Int) (stop bool) { concreteValidators = append(concreteValidators, &acm.ConcreteValidator{ - Address: publicKey.Address(), - PublicKey: publicKey, - Power: power, + Address: id.Address(), + PublicKey: id.PublicKey(), + Power: power.Uint64(), }) return }) diff --git a/txs/payload/governance_tx.go b/txs/payload/governance_tx.go index 046f91291..5f8bfdeb4 100644 --- a/txs/payload/governance_tx.go +++ b/txs/payload/governance_tx.go @@ -2,35 +2,8 @@ package payload import ( "fmt" - - "github.com/hyperledger/burrow/acm/state" - "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/genesis/spec" ) -func NewGovTx(st state.AccountGetter, from crypto.Address, accounts ...*spec.TemplateAccount) (*GovernanceTx, error) { - acc, err := st.GetAccount(from) - if err != nil { - return nil, err - } - if acc == nil { - return nil, fmt.Errorf("could not get account %v", from) - } - - sequence := acc.Sequence() + 1 - return NewGovTxWithSequence(from, sequence, accounts), nil -} - -func NewGovTxWithSequence(from crypto.Address, sequence uint64, accounts []*spec.TemplateAccount) *GovernanceTx { - return &GovernanceTx{ - Inputs: []*TxInput{{ - Address: from, - Sequence: sequence, - }}, - AccountUpdates: accounts, - } -} - func (tx *GovernanceTx) Type() Type { return TypeGovernance } From 00fedc6de2a25446b63f532448306436a762dd2a Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Fri, 20 Jul 2018 12:39:33 +0100 Subject: [PATCH 15/28] Upgrade tendermint in vendor Signed-off-by: Silas Davis --- Gopkg.lock | 135 ++-- Gopkg.toml | 23 +- README.md | 2 +- .../github.com/btcsuite/btcd/btcec/pubkey.go | 13 +- .../go-kit/kit/metrics/discard/discard.go | 40 + vendor/github.com/go-kit/kit/metrics/doc.go | 97 +++ .../kit/metrics/internal/lv/labelvalues.go | 14 + .../go-kit/kit/metrics/internal/lv/space.go | 145 ++++ .../github.com/go-kit/kit/metrics/metrics.go | 25 + .../kit/metrics/prometheus/prometheus.go | 165 ++++ vendor/github.com/go-kit/kit/metrics/timer.go | 36 + .../client_golang/prometheus/collector.go | 39 +- .../client_golang/prometheus/doc.go | 12 +- .../prometheus/promhttp/delegator.go | 199 +++++ .../prometheus/promhttp/delegator_1_8.go | 181 +++++ .../prometheus/promhttp/delegator_pre_1_8.go | 44 + .../client_golang/prometheus/promhttp/http.go | 311 +++++++ .../prometheus/promhttp/instrument_client.go | 97 +++ .../promhttp/instrument_client_1_8.go | 144 ++++ .../prometheus/promhttp/instrument_server.go | 447 +++++++++++ .../client_golang/prometheus/registry.go | 120 ++- .../prometheus/client_model/go/metrics.pb.go | 381 +++++++-- .../prometheus/procfs/mountstats.go | 51 +- .../syndtr/goleveldb/leveldb/db_compaction.go | 40 +- .../github.com/tendermint/go-amino/amino.go | 195 +++-- .../tendermint/go-amino/binary-decode.go | 643 ++++++++------- .../tendermint/go-amino/binary-encode.go | 272 ++++--- .../github.com/tendermint/go-amino/codec.go | 207 ++++- .../github.com/tendermint/go-amino/decoder.go | 51 +- .../github.com/tendermint/go-amino/encoder.go | 9 +- .../tendermint/go-amino/json-decode.go | 167 ++-- .../tendermint/go-amino/json-encode.go | 91 +-- .../github.com/tendermint/go-amino/reflect.go | 92 ++- .../github.com/tendermint/go-amino/version.go | 2 +- vendor/github.com/tendermint/go-crypto/doc.go | 48 -- .../tendermint/go-crypto/version.go | 3 - vendor/github.com/tendermint/iavl/amino.go | 5 - vendor/github.com/tendermint/iavl/chunk.go | 185 ----- vendor/github.com/tendermint/iavl/doc.go | 10 +- vendor/github.com/tendermint/iavl/node.go | 314 ++++---- vendor/github.com/tendermint/iavl/nodedb.go | 60 +- .../tendermint/iavl/orphaning_tree.go | 1 + vendor/github.com/tendermint/iavl/path.go | 156 ---- vendor/github.com/tendermint/iavl/proof.go | 263 +++--- .../github.com/tendermint/iavl/proof_key.go | 161 ---- .../github.com/tendermint/iavl/proof_path.go | 167 ++++ .../github.com/tendermint/iavl/proof_range.go | 757 ++++++++++-------- .../github.com/tendermint/iavl/serialize.go | 200 ----- .../iavl/sha256truncated/sha256truncated.go | 44 - vendor/github.com/tendermint/iavl/tree.go | 54 +- .../tendermint/iavl/tree_dotgraph.go | 4 +- vendor/github.com/tendermint/iavl/util.go | 84 +- vendor/github.com/tendermint/iavl/version.go | 3 +- .../tendermint/iavl/versioned_tree.go | 52 +- vendor/github.com/tendermint/iavl/wire.go | 17 + .../{ => tendermint}/abci/client/client.go | 4 +- .../abci/client/grpc_client.go | 4 +- .../abci/client/local_client.go | 4 +- .../abci/client/socket_client.go | 11 +- .../abci/example/code/code.go | 0 .../abci/example/kvstore/README.md | 0 .../abci/example/kvstore/helpers.go | 4 +- .../abci/example/kvstore/kvstore.go | 8 +- .../example/kvstore/persistent_kvstore.go | 10 +- .../abci/types/application.go | 0 .../{ => tendermint}/abci/types/messages.go | 0 .../{ => tendermint}/abci/types/pubkey.go | 0 .../{ => tendermint}/abci/types/result.go | 0 .../{ => tendermint}/abci/types/types.pb.go | 2 +- .../{ => tendermint}/abci/types/types.proto | 0 .../{ => tendermint}/abci/types/util.go | 2 +- .../tendermint/tendermint/blockchain/pool.go | 6 +- .../tendermint/blockchain/reactor.go | 19 +- .../tendermint/tendermint/blockchain/store.go | 4 +- .../tendermint/tendermint/blockchain/wire.go | 2 +- .../tendermint/tendermint/config/config.go | 123 ++- .../tendermint/tendermint/config/toml.go | 60 +- .../tendermint/tendermint/consensus/README.md | 1 + .../tendermint/consensus/metrics.go | 133 +++ .../tendermint/consensus/reactor.go | 15 +- .../tendermint/tendermint/consensus/replay.go | 12 +- .../tendermint/consensus/replay_file.go | 6 +- .../tendermint/tendermint/consensus/state.go | 100 ++- .../tendermint/tendermint/consensus/ticker.go | 4 +- .../consensus/types/height_vote_set.go | 2 +- .../consensus/types/peer_round_state.go | 2 +- .../tendermint/consensus/types/round_state.go | 2 +- .../tendermint/consensus/types/wire.go | 2 +- .../tendermint/consensus/version.go | 2 +- .../tendermint/tendermint/consensus/wal.go | 4 +- .../tendermint/consensus/wal_generator.go | 18 +- .../tendermint/tendermint/consensus/wire.go | 2 +- .../tendermint/tendermint/crypto/CHANGELOG.md | 154 ++++ .../tendermint/tendermint/crypto/README.md | 25 + .../{go-crypto => tendermint/crypto}/amino.go | 5 +- .../{go-crypto => tendermint/crypto}/armor.go | 8 +- .../tendermint/tendermint/crypto/doc.go | 45 ++ .../{go-crypto => tendermint/crypto}/hash.go | 0 .../crypto}/merkle/README.md | 0 .../tendermint/crypto/merkle/doc.go | 31 + .../crypto}/merkle/simple_map.go | 42 +- .../crypto}/merkle/simple_proof.go | 28 +- .../tendermint/crypto/merkle/simple_tree.go | 58 ++ .../crypto}/merkle/types.go | 21 +- .../crypto}/priv_key.go | 44 +- .../crypto}/pub_key.go | 31 +- .../crypto}/random.go | 11 +- .../crypto}/signature.go | 19 +- .../crypto}/symmetric.go | 2 +- .../tendermint/crypto/tmhash/hash.go | 48 ++ .../tendermint/tendermint/crypto/version.go | 3 + .../tendermint/tendermint/evidence/pool.go | 6 +- .../tendermint/tendermint/evidence/reactor.go | 14 +- .../tendermint/tendermint/evidence/store.go | 2 +- .../tendermint/tendermint/evidence/wire.go | 2 +- .../libs}/autofile/README.md | 0 .../libs}/autofile/autofile.go | 2 +- .../libs}/autofile/group.go | 2 +- .../libs}/autofile/sighup_watcher.go | 0 .../libs}/clist/clist.go | 0 .../libs}/common/LICENSE | 0 .../libs}/common/async.go | 18 +- .../libs}/common/bit_array.go | 0 .../libs}/common/bytes.go | 0 .../libs}/common/byteslice.go | 0 .../libs}/common/cmap.go | 0 .../libs}/common/colors.go | 12 + .../libs}/common/date.go | 0 .../libs}/common/errors.go | 173 ++-- .../libs}/common/heap.go | 0 .../{tmlibs => tendermint/libs}/common/int.go | 0 .../{tmlibs => tendermint/libs}/common/io.go | 0 .../libs}/common/kvpair.go | 0 .../libs}/common/math.go | 0 .../{tmlibs => tendermint/libs}/common/net.go | 0 .../{tmlibs => tendermint/libs}/common/nil.go | 0 .../{tmlibs => tendermint/libs}/common/os.go | 0 .../libs}/common/random.go | 0 .../libs}/common/repeat_timer.go | 0 .../libs}/common/service.go | 2 +- .../libs}/common/string.go | 0 .../libs}/common/throttle_timer.go | 0 .../libs}/common/types.pb.go | 31 +- .../libs}/common/types.proto | 7 - .../libs}/common/word.go | 0 .../{tmlibs => tendermint/libs}/db/LICENSE.md | 0 .../{tmlibs => tendermint/libs}/db/README.md | 0 .../libs}/db/c_level_db.go | 45 +- .../{tmlibs => tendermint/libs}/db/db.go | 0 .../libs}/db/debug_db.go | 62 +- .../{tmlibs => tendermint/libs}/db/fsdb.go | 20 +- .../libs}/db/go_level_db.go | 46 +- .../libs}/db/mem_batch.go | 0 .../{tmlibs => tendermint/libs}/db/mem_db.go | 2 +- .../libs}/db/prefix_db.go | 0 .../{tmlibs => tendermint/libs}/db/types.go | 0 .../{tmlibs => tendermint/libs}/db/util.go | 0 .../tendermint/libs/events/Makefile | 9 + .../tendermint/libs/events/README.md | 175 ++++ .../tendermint/libs/events/events.go | 2 +- .../libs}/flowrate/README.md | 0 .../libs}/flowrate/flowrate.go | 0 .../libs}/flowrate/io.go | 0 .../libs}/flowrate/util.go | 0 .../{tmlibs => tendermint/libs}/log/filter.go | 0 .../{tmlibs => tendermint/libs}/log/logger.go | 0 .../libs}/log/nop_logger.go | 0 .../libs}/log/testing_logger.go | 0 .../libs}/log/tm_json_logger.go | 0 .../libs}/log/tm_logger.go | 0 .../libs}/log/tmfmt_logger.go | 0 .../libs}/log/tracing_logger.go | 0 .../tendermint/libs/pubsub/pubsub.go | 10 +- .../tendermint/libs/pubsub/query/Makefile | 11 + .../tendermint/libs/pubsub/query/query.peg | 33 + .../tendermint/libs/pubsub/query/query.peg.go | 2 + .../tendermint/tendermint/mempool/mempool.go | 42 +- .../tendermint/tendermint/mempool/metrics.go | 34 + .../tendermint/tendermint/mempool/reactor.go | 16 +- .../tendermint/tendermint/node/id.go | 2 +- .../tendermint/tendermint/node/node.go | 130 ++- .../tendermint/tendermint/node/wire.go | 2 +- .../tendermint/tendermint/p2p/README.md | 11 + .../tendermint/tendermint/p2p/base_reactor.go | 2 +- .../tendermint/p2p/conn/connection.go | 36 +- .../tendermint/p2p/conn/secret_connection.go | 10 +- .../tendermint/tendermint/p2p/conn/wire.go | 2 +- .../tendermint/tendermint/p2p/fuzz.go | 2 +- .../tendermint/tendermint/p2p/key.go | 4 +- .../tendermint/tendermint/p2p/listener.go | 104 ++- .../tendermint/tendermint/p2p/metrics.go | 33 + .../tendermint/tendermint/p2p/netaddress.go | 2 +- .../tendermint/tendermint/p2p/node_info.go | 2 +- .../tendermint/tendermint/p2p/peer.go | 6 +- .../tendermint/tendermint/p2p/peer_set.go | 11 +- .../tendermint/tendermint/p2p/pex/addrbook.go | 4 +- .../tendermint/tendermint/p2p/pex/file.go | 2 +- .../tendermint/p2p/pex/pex_reactor.go | 24 +- .../tendermint/tendermint/p2p/switch.go | 22 +- .../tendermint/tendermint/p2p/test_util.go | 6 +- .../tendermint/tendermint/p2p/upnp/probe.go | 4 +- .../tendermint/tendermint/p2p/wire.go | 2 +- .../tendermint/privval/priv_validator.go | 24 +- .../tendermint/tendermint/privval/socket.go | 6 +- .../tendermint/tendermint/privval/wire.go | 2 +- .../tendermint/tendermint/proxy/app_conn.go | 4 +- .../tendermint/tendermint/proxy/client.go | 6 +- .../tendermint/proxy/multi_app_conn.go | 2 +- .../tendermint/tendermint/rpc/core/README.md | 20 + .../tendermint/tendermint/rpc/core/abci.go | 4 +- .../tendermint/tendermint/rpc/core/blocks.go | 2 +- .../tendermint/rpc/core/consensus.go | 8 +- .../tendermint/rpc/core/doc_template.txt | 8 + .../tendermint/tendermint/rpc/core/mempool.go | 4 +- .../tendermint/tendermint/rpc/core/pipe.go | 6 +- .../tendermint/tendermint/rpc/core/status.go | 8 +- .../tendermint/tendermint/rpc/core/tx.go | 2 +- .../tendermint/rpc/core/types/responses.go | 8 +- .../tendermint/rpc/core/types/wire.go | 2 +- .../tendermint/tendermint/rpc/grpc/api.go | 2 +- .../tendermint/rpc/grpc/client_server.go | 20 +- .../tendermint/tendermint/rpc/grpc/compile.sh | 3 + .../tendermint/rpc/grpc/types.pb.go | 2 +- .../tendermint/rpc/grpc/types.proto | 36 + .../tendermint/tendermint/rpc/lib/doc.go | 2 +- .../tendermint/rpc/lib/server/handlers.go | 76 +- .../tendermint/rpc/lib/server/http_params.go | 1 + .../tendermint/rpc/lib/server/http_server.go | 84 +- .../tendermint/tendermint/state/errors.go | 2 +- .../tendermint/tendermint/state/execution.go | 24 +- .../tendermint/tendermint/state/services.go | 2 +- .../tendermint/tendermint/state/store.go | 29 +- .../state/txindex/indexer_service.go | 2 +- .../tendermint/state/txindex/kv/kv.go | 4 +- .../tendermint/tendermint/state/validation.go | 2 +- .../tendermint/tendermint/state/wire.go | 2 +- .../{abci => tendermint/tools/build}/LICENSE | 23 +- .../tools/build/basecoind/DEBIAN/copyright | 21 + .../tools/build/ethermint/DEBIAN/copyright | 21 + .../tools/build/gaia/DEBIAN/copyright | 21 + .../tools/build/tendermint/DEBIAN/copyright | 21 + .../tools/mintnet-kubernetes}/LICENSE | 1 - .../tools/tm-bench}/LICENSE | 23 +- .../tendermint/tools/tm-monitor/LICENSE | 204 +++++ .../tendermint/tendermint/types/block.go | 27 +- .../tendermint/types/canonical_json.go | 5 +- .../tendermint/types/event_buffer.go | 50 -- .../tendermint/tendermint/types/event_bus.go | 6 +- .../tendermint/tendermint/types/events.go | 10 - .../tendermint/tendermint/types/evidence.go | 9 +- .../tendermint/tendermint/types/genesis.go | 16 +- .../tendermint/tendermint/types/heartbeat.go | 4 +- .../tendermint/tendermint/types/params.go | 9 +- .../tendermint/tendermint/types/part_set.go | 9 +- .../tendermint/types/priv_validator.go | 17 +- .../tendermint/tendermint/types/proposal.go | 2 +- .../tendermint/tendermint/types/protobuf.go | 10 +- .../tendermint/tendermint/types/results.go | 17 +- .../tendermint/tendermint/types/tx.go | 16 +- .../tendermint/tendermint/types/validator.go | 4 +- .../tendermint/types/validator_set.go | 9 +- .../tendermint/tendermint/types/vote.go | 4 +- .../tendermint/tendermint/types/vote_set.go | 2 +- .../tendermint/tendermint/types/wire.go | 2 +- .../tendermint/tendermint/version/version.go | 6 +- .../tendermint/tmlibs/common/array.go | 5 - .../tendermint/tmlibs/merkle/simple_tree.go | 91 --- .../x/net/http2/client_conn_pool.go | 28 +- vendor/golang.org/x/net/http2/go111.go | 17 + vendor/golang.org/x/net/http2/go17.go | 15 + vendor/golang.org/x/net/http2/not_go111.go | 11 + vendor/golang.org/x/net/http2/not_go17.go | 8 + vendor/golang.org/x/net/http2/server.go | 7 + vendor/golang.org/x/net/http2/transport.go | 120 ++- vendor/golang.org/x/net/netutil/listen.go | 74 ++ vendor/golang.org/x/sys/unix/syscall_bsd.go | 8 +- .../x/sys/unix/syscall_dragonfly.go | 2 +- .../golang.org/x/sys/unix/syscall_freebsd.go | 2 +- vendor/golang.org/x/sys/unix/syscall_linux.go | 75 +- .../golang.org/x/sys/unix/syscall_solaris.go | 8 +- vendor/golang.org/x/sys/unix/syscall_unix.go | 4 +- .../x/sys/unix/zsyscall_linux_ppc64.go | 24 +- .../x/sys/unix/zsyscall_linux_ppc64le.go | 24 +- .../golang.org/x/sys/unix/ztypes_linux_386.go | 8 + .../x/sys/unix/ztypes_linux_amd64.go | 8 + .../golang.org/x/sys/unix/ztypes_linux_arm.go | 8 + .../x/sys/unix/ztypes_linux_arm64.go | 8 + .../x/sys/unix/ztypes_linux_mips.go | 8 + .../x/sys/unix/ztypes_linux_mips64.go | 8 + .../x/sys/unix/ztypes_linux_mips64le.go | 8 + .../x/sys/unix/ztypes_linux_mipsle.go | 8 + .../x/sys/unix/ztypes_linux_ppc64.go | 8 + .../x/sys/unix/ztypes_linux_ppc64le.go | 8 + .../x/sys/unix/ztypes_linux_s390x.go | 8 + .../golang.org/x/sys/windows/types_windows.go | 33 +- 295 files changed, 7558 insertions(+), 3488 deletions(-) create mode 100644 vendor/github.com/go-kit/kit/metrics/discard/discard.go create mode 100644 vendor/github.com/go-kit/kit/metrics/doc.go create mode 100644 vendor/github.com/go-kit/kit/metrics/internal/lv/labelvalues.go create mode 100644 vendor/github.com/go-kit/kit/metrics/internal/lv/space.go create mode 100644 vendor/github.com/go-kit/kit/metrics/metrics.go create mode 100644 vendor/github.com/go-kit/kit/metrics/prometheus/prometheus.go create mode 100644 vendor/github.com/go-kit/kit/metrics/timer.go create mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator.go create mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_1_8.go create mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_pre_1_8.go create mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go create mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go create mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client_1_8.go create mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go delete mode 100644 vendor/github.com/tendermint/go-crypto/doc.go delete mode 100644 vendor/github.com/tendermint/go-crypto/version.go delete mode 100644 vendor/github.com/tendermint/iavl/amino.go delete mode 100644 vendor/github.com/tendermint/iavl/chunk.go delete mode 100644 vendor/github.com/tendermint/iavl/path.go delete mode 100644 vendor/github.com/tendermint/iavl/proof_key.go create mode 100644 vendor/github.com/tendermint/iavl/proof_path.go delete mode 100644 vendor/github.com/tendermint/iavl/serialize.go delete mode 100644 vendor/github.com/tendermint/iavl/sha256truncated/sha256truncated.go create mode 100644 vendor/github.com/tendermint/iavl/wire.go rename vendor/github.com/tendermint/{ => tendermint}/abci/client/client.go (97%) rename vendor/github.com/tendermint/{ => tendermint}/abci/client/grpc_client.go (98%) rename vendor/github.com/tendermint/{ => tendermint}/abci/client/local_client.go (98%) rename vendor/github.com/tendermint/{ => tendermint}/abci/client/socket_client.go (96%) rename vendor/github.com/tendermint/{ => tendermint}/abci/example/code/code.go (100%) rename vendor/github.com/tendermint/{ => tendermint}/abci/example/kvstore/README.md (100%) rename vendor/github.com/tendermint/{ => tendermint}/abci/example/kvstore/helpers.go (90%) rename vendor/github.com/tendermint/{ => tendermint}/abci/example/kvstore/kvstore.go (93%) rename vendor/github.com/tendermint/{ => tendermint}/abci/example/kvstore/persistent_kvstore.go (95%) rename vendor/github.com/tendermint/{ => tendermint}/abci/types/application.go (100%) rename vendor/github.com/tendermint/{ => tendermint}/abci/types/messages.go (100%) rename vendor/github.com/tendermint/{ => tendermint}/abci/types/pubkey.go (100%) rename vendor/github.com/tendermint/{ => tendermint}/abci/types/result.go (100%) rename vendor/github.com/tendermint/{ => tendermint}/abci/types/types.pb.go (99%) rename vendor/github.com/tendermint/{ => tendermint}/abci/types/types.proto (100%) rename vendor/github.com/tendermint/{ => tendermint}/abci/types/util.go (96%) create mode 100644 vendor/github.com/tendermint/tendermint/consensus/README.md create mode 100644 vendor/github.com/tendermint/tendermint/consensus/metrics.go create mode 100644 vendor/github.com/tendermint/tendermint/crypto/CHANGELOG.md create mode 100644 vendor/github.com/tendermint/tendermint/crypto/README.md rename vendor/github.com/tendermint/{go-crypto => tendermint/crypto}/amino.go (85%) rename vendor/github.com/tendermint/{go-crypto => tendermint/crypto}/armor.go (76%) create mode 100644 vendor/github.com/tendermint/tendermint/crypto/doc.go rename vendor/github.com/tendermint/{go-crypto => tendermint/crypto}/hash.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/crypto}/merkle/README.md (100%) create mode 100644 vendor/github.com/tendermint/tendermint/crypto/merkle/doc.go rename vendor/github.com/tendermint/{tmlibs => tendermint/crypto}/merkle/simple_map.go (53%) rename vendor/github.com/tendermint/{tmlibs => tendermint/crypto}/merkle/simple_proof.go (79%) create mode 100644 vendor/github.com/tendermint/tendermint/crypto/merkle/simple_tree.go rename vendor/github.com/tendermint/{tmlibs => tendermint/crypto}/merkle/types.go (72%) rename vendor/github.com/tendermint/{go-crypto => tendermint/crypto}/priv_key.go (84%) rename vendor/github.com/tendermint/{go-crypto => tendermint/crypto}/pub_key.go (83%) rename vendor/github.com/tendermint/{go-crypto => tendermint/crypto}/random.go (89%) rename vendor/github.com/tendermint/{go-crypto => tendermint/crypto}/signature.go (79%) rename vendor/github.com/tendermint/{go-crypto => tendermint/crypto}/symmetric.go (97%) create mode 100644 vendor/github.com/tendermint/tendermint/crypto/tmhash/hash.go create mode 100644 vendor/github.com/tendermint/tendermint/crypto/version.go rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/autofile/README.md (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/autofile/autofile.go (97%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/autofile/group.go (99%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/autofile/sighup_watcher.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/clist/clist.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/LICENSE (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/async.go (95%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/bit_array.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/bytes.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/byteslice.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/cmap.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/colors.go (87%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/date.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/errors.go (53%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/heap.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/int.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/io.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/kvpair.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/math.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/net.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/nil.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/os.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/random.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/repeat_timer.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/service.go (99%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/string.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/throttle_timer.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/types.pb.go (68%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/types.proto (56%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/common/word.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/db/LICENSE.md (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/db/README.md (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/db/c_level_db.go (88%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/db/db.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/db/debug_db.go (68%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/db/fsdb.go (90%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/db/go_level_db.go (88%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/db/mem_batch.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/db/mem_db.go (98%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/db/prefix_db.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/db/types.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/db/util.go (100%) create mode 100644 vendor/github.com/tendermint/tendermint/libs/events/Makefile create mode 100644 vendor/github.com/tendermint/tendermint/libs/events/README.md rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/flowrate/README.md (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/flowrate/flowrate.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/flowrate/io.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/flowrate/util.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/log/filter.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/log/logger.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/log/nop_logger.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/log/testing_logger.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/log/tm_json_logger.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/log/tm_logger.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/log/tmfmt_logger.go (100%) rename vendor/github.com/tendermint/{tmlibs => tendermint/libs}/log/tracing_logger.go (100%) create mode 100644 vendor/github.com/tendermint/tendermint/libs/pubsub/query/Makefile create mode 100644 vendor/github.com/tendermint/tendermint/libs/pubsub/query/query.peg create mode 100644 vendor/github.com/tendermint/tendermint/mempool/metrics.go create mode 100644 vendor/github.com/tendermint/tendermint/p2p/README.md create mode 100644 vendor/github.com/tendermint/tendermint/p2p/metrics.go create mode 100644 vendor/github.com/tendermint/tendermint/rpc/core/README.md create mode 100644 vendor/github.com/tendermint/tendermint/rpc/core/doc_template.txt create mode 100644 vendor/github.com/tendermint/tendermint/rpc/grpc/compile.sh create mode 100644 vendor/github.com/tendermint/tendermint/rpc/grpc/types.proto rename vendor/github.com/tendermint/{abci => tendermint/tools/build}/LICENSE (93%) create mode 100644 vendor/github.com/tendermint/tendermint/tools/build/basecoind/DEBIAN/copyright create mode 100644 vendor/github.com/tendermint/tendermint/tools/build/ethermint/DEBIAN/copyright create mode 100644 vendor/github.com/tendermint/tendermint/tools/build/gaia/DEBIAN/copyright create mode 100644 vendor/github.com/tendermint/tendermint/tools/build/tendermint/DEBIAN/copyright rename vendor/github.com/tendermint/{tmlibs => tendermint/tools/mintnet-kubernetes}/LICENSE (99%) rename vendor/github.com/tendermint/{go-crypto => tendermint/tools/tm-bench}/LICENSE (93%) create mode 100644 vendor/github.com/tendermint/tendermint/tools/tm-monitor/LICENSE delete mode 100644 vendor/github.com/tendermint/tendermint/types/event_buffer.go delete mode 100644 vendor/github.com/tendermint/tmlibs/common/array.go delete mode 100644 vendor/github.com/tendermint/tmlibs/merkle/simple_tree.go create mode 100644 vendor/golang.org/x/net/http2/go111.go create mode 100644 vendor/golang.org/x/net/http2/not_go111.go create mode 100644 vendor/golang.org/x/net/netutil/listen.go diff --git a/Gopkg.lock b/Gopkg.lock index 30b89e8a5..6eb70eacc 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -27,11 +27,11 @@ [[projects]] branch = "master" - digest = "1:8bd66090a4fc1d422f0cb065a3023bf98f07f44920c3f87da5c3107f990434e4" + digest = "1:ad87504ef74b1c36880f9287126dbc8dc4146d86acf902dd776ac6064cc75396" name = "github.com/btcsuite/btcd" packages = ["btcec"] pruneopts = "NUT" - revision = "86fed781132ac890ee03e906e4ecd5d6fa180c64" + revision = "f673a4b563b57b9a95832545c878669a7fa801d9" [[projects]] branch = "master" @@ -66,7 +66,6 @@ version = "v1.1.0" [[projects]] - branch = "master" digest = "1:294576320c5093015ca9130ed928c84b2fdc8b9db6d136505a513795f3a64e3e" name = "github.com/ebuchman/fail-test" packages = ["."] @@ -74,12 +73,16 @@ revision = "95f809107225be108efcf10a3509e4ea6ceef3c4" [[projects]] - digest = "1:5a6f43bb19bea1e7894542a80c6e95bab099c380dd90abebd76d3938e8c66567" + digest = "1:2c03593aec9fa7d6969dc7295c636b46369ec2dd45dcf4acfb298281d62528ff" name = "github.com/go-kit/kit" packages = [ "log", "log/level", "log/term", + "metrics", + "metrics/discard", + "metrics/internal/lv", + "metrics/prometheus", ] pruneopts = "NUT" revision = "4dc7be5d2d12881735283bcab7352178e190fc71" @@ -113,8 +116,8 @@ "types", ] pruneopts = "UT" - revision = "7d68e886eac4f7e34d0d82241a6273d6c304c5cf" - version = "v1.1.0" + revision = "636bf0302bc95575d69441b25a2603156ffdddf1" + version = "v1.1.1" [[projects]] digest = "1:713cc7628304d027a7e9edcb52da888a8912d6405250a8d9c8eff6f41dd54398" @@ -228,20 +231,22 @@ version = "v1.0.0" [[projects]] - branch = "master" - digest = "1:22deec4bab258f99bf1e4394c51d976e04ddf9a52f55b0e2912d9cdd503dff16" + digest = "1:76463f8d9f141bb3673ccece5fb0d1d0f9588395e94d01253667db733f865b18" name = "github.com/prometheus/client_golang" - packages = ["prometheus"] + packages = [ + "prometheus", + "prometheus/promhttp", + ] pruneopts = "NUT" - revision = "d6a9817c4afc94d51115e4a30d449056a3fbf547" + revision = "ae27198cdd90bf12cd134ad79d1366a6cf49f632" [[projects]] branch = "master" - digest = "1:53a76eb11bdc815fcf0c757a9648fda0ab6887da13f07587181ff2223b67956c" + digest = "1:0f37e09b3e92aaeda5991581311f8dbf38944b36a3edec61cc2d1991f527554a" name = "github.com/prometheus/client_model" packages = ["go"] pruneopts = "NUT" - revision = "99fa1f4be8e564e8a6b613da7fa6f46c9edafc6c" + revision = "5c3871d89910bfb32f5fcab2aa4b9ec68e65a99f" [[projects]] branch = "master" @@ -257,7 +262,7 @@ [[projects]] branch = "master" - digest = "1:b161534d0cce842f1e1eaf087e2c5f28191f0bac0c3070fc9a7e1b6269238d88" + digest = "1:37e418257b05a9e9fabbf836df2d8f3613313e80a909da6b9597b759ebca61cd" name = "github.com/prometheus/procfs" packages = [ ".", @@ -266,7 +271,7 @@ "xfs", ] pruneopts = "NUT" - revision = "40f013a808ec4fa79def444a1a56de4d1727efcb" + revision = "ae68e2d4c00fed4943b5f6698d504a5fe083da8a" [[projects]] branch = "master" @@ -297,7 +302,7 @@ [[projects]] branch = "master" - digest = "1:bd62f27525a36697564991b8e6071ff56afa99d3235261924a0212db5ce780bd" + digest = "1:922191411ad8f61bcd8018ac127589bb489712c1d1a0ab2497aca4b16de417d2" name = "github.com/syndtr/goleveldb" packages = [ "leveldb", @@ -314,20 +319,7 @@ "leveldb/util", ] pruneopts = "NUT" - revision = "0d5a0ceb10cf9ab89fdd744cc8c50a83134f6697" - -[[projects]] - digest = "1:b8a05190f9aa37b0ab5b29b480797306b221709ffcb4a0ed9946cc7110849c07" - name = "github.com/tendermint/abci" - packages = [ - "client", - "example/code", - "example/kvstore", - "types", - ] - pruneopts = "UT" - revision = "198dccf0ddfd1bb176f87657e3286a05a6ed9540" - version = "v0.12.0" + revision = "c4c61651e9e37fa117f53c5a906d3b63090d8445" [[projects]] branch = "master" @@ -342,42 +334,44 @@ revision = "d8387025d2b9d158cf4efb07e7ebf814bcce2057" [[projects]] - digest = "1:0457834dfbe7dfd39c9e2d99147bde666094819e85728eb235a122943660256c" + digest = "1:0fbb744c7842baaec7f5b2e0eb9814668bf34c4eb3c4fe6fc9ac856a937a5eff" name = "github.com/tendermint/go-amino" packages = ["."] pruneopts = "NUT" - revision = "ed62928576cfcaf887209dc96142cd79cdfff389" - version = "0.9.9" - -[[projects]] - digest = "1:9b0716c497677d6404499b2931cbfac90943d20302b90128b2979b5e1fcb09f5" - name = "github.com/tendermint/go-crypto" - packages = ["."] - pruneopts = "NUT" - revision = "915416979bf70efa4bcbf1c6cd5d64c5fff9fc19" - version = "v0.6.2" + revision = "2106ca61d91029c931fd54968c2bb02dc96b1412" + version = "0.10.1" [[projects]] - digest = "1:91de33917aa98c06cb0f32867908071dd6992fff80347c37fc592165051957a0" + digest = "1:5a2904670bdaf13e71cd3a726795b2d0ee65a0862d499a1440799bd62618efac" name = "github.com/tendermint/iavl" - packages = [ - ".", - "sha256truncated", - ] + packages = ["."] pruneopts = "NUT" - revision = "c9206995e8f948e99927f5084a88a7e94ca256da" - version = "v0.8.0-rc0" + revision = "35f66e53d9b01e83b30de68b931f54b2477a94c9" + version = "v0.9.2" [[projects]] - digest = "1:0bde6563ae9ebe48770735120ee223a8761e8ec23fde4f36995bbbb4ea69d1ca" + digest = "1:46ac5207f9074a8ca246a3fce7aa576f5c5f43a30c8f3ef833e247777fdb8a4f" name = "github.com/tendermint/tendermint" packages = [ + "abci/client", + "abci/example/code", + "abci/example/kvstore", + "abci/types", "blockchain", "config", "consensus", "consensus/types", + "crypto", + "crypto/merkle", + "crypto/tmhash", "evidence", + "libs/autofile", + "libs/clist", + "libs/common", + "libs/db", "libs/events", + "libs/flowrate", + "libs/log", "libs/pubsub", "libs/pubsub/query", "mempool", @@ -401,25 +395,9 @@ "types", "version", ] - pruneopts = "NUT" - revision = "46369a1ab76f274ab47179c4176221842b8207b4" - version = "v0.21.0" - -[[projects]] - digest = "1:1e17077c52b3c68e5ec1059ed078210e8b1030eb30ad23a69b924e7f30bd0132" - name = "github.com/tendermint/tmlibs" - packages = [ - "autofile", - "clist", - "common", - "db", - "flowrate", - "log", - "merkle", - ] pruneopts = "UT" - revision = "692f1d86a6e2c0efa698fd1e4541b68c74ffaf38" - version = "v0.8.4" + revision = "c64a3c74c870d725ba1356f75b4afadf0928c297" + version = "v0.22.4" [[projects]] branch = "master" @@ -458,11 +436,10 @@ "ssh/terminal", ] pruneopts = "NUT" - revision = "a49355c7e3f8fe157a85be2f77e6e269a0f89602" + revision = "a2144134853fc9a27a7b1e3eb4f19f1a76df13c9" [[projects]] - branch = "master" - digest = "1:cdc8cc9377bcb05ff97816bf398120c0a242f502b5eb2bb27d1d650b523e67e1" + digest = "1:15dbe437d38eb2103f6b55348758958a6f85a400ecc16fcb53b3f271d38cd8ea" name = "golang.org/x/net" packages = [ "context", @@ -471,14 +448,15 @@ "http2/hpack", "idna", "internal/timeseries", + "netutil", "trace", ] pruneopts = "NUT" - revision = "ed29d75add3d7c4bf7ca65aac0c6df3d1420216f" + revision = "292b43bbf7cb8d35ddf40f8d5100ef3837cced3f" [[projects]] branch = "master" - digest = "1:569e1719852f85b01939e6040b3eee417913c9e6d0368d3d1460d0af4eb702bc" + digest = "1:48419582c83b5715e244977ca617a3ff596dc6808368e3c1dcaf1b3ad2218e53" name = "golang.org/x/sys" packages = [ "cpu", @@ -486,7 +464,7 @@ "windows", ] pruneopts = "NUT" - revision = "151529c776cdc58ddbe7963ba9af779f3577b419" + revision = "ac767d655b305d4e9612f5f6e33120b9176c4ad4" [[projects]] digest = "1:a0f29009397dc27c9dc8440f0945d49e5cbb9b72d0b0fc745474d9bfdea2d9f8" @@ -517,7 +495,7 @@ name = "google.golang.org/genproto" packages = ["googleapis/rpc/status"] pruneopts = "NUT" - revision = "ff3583edef7de132f219f0efc00e097cabcc0ec0" + revision = "fedd2861243fd1a8152376292b921b394c7bef7e" [[projects]] digest = "1:f778941d5c2e46da5e0f5d553d3e80bf70eb40d2e80bb4c649b625b9133f3d5f" @@ -586,24 +564,25 @@ "github.com/streadway/simpleuuid", "github.com/stretchr/testify/assert", "github.com/stretchr/testify/require", - "github.com/tendermint/abci/types", "github.com/tendermint/go-amino", - "github.com/tendermint/go-crypto", "github.com/tendermint/iavl", + "github.com/tendermint/tendermint/abci/types", "github.com/tendermint/tendermint/blockchain", "github.com/tendermint/tendermint/config", "github.com/tendermint/tendermint/consensus", "github.com/tendermint/tendermint/consensus/types", + "github.com/tendermint/tendermint/crypto", + "github.com/tendermint/tendermint/libs/common", + "github.com/tendermint/tendermint/libs/db", + "github.com/tendermint/tendermint/libs/log", "github.com/tendermint/tendermint/libs/pubsub", + "github.com/tendermint/tendermint/mempool", "github.com/tendermint/tendermint/node", "github.com/tendermint/tendermint/p2p", "github.com/tendermint/tendermint/proxy", "github.com/tendermint/tendermint/rpc/core/types", "github.com/tendermint/tendermint/state", "github.com/tendermint/tendermint/types", - "github.com/tendermint/tmlibs/common", - "github.com/tendermint/tmlibs/db", - "github.com/tendermint/tmlibs/log", "github.com/tmthrgd/go-hex", "golang.org/x/crypto/ed25519", "golang.org/x/crypto/ripemd160", diff --git a/Gopkg.toml b/Gopkg.toml index d96822fe2..4d10b7e13 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -7,34 +7,21 @@ name = "github.com/gogo/protobuf" non-go = false [[prune.project]] - name = "github.com/tendermint/abci" + name = "github.com/tendermint/tendermint" non-go = false [[prune.project]] name = "github.com/tendermint/tmlibs" non-go = false -# From Tendermint -[[constraint]] +# overriding here because of IAVL +[[override]] name = "github.com/tendermint/tendermint" - version = "=0.21.0" - -[[constraint]] - name = "github.com/tendermint/go-amino" - version = "=0.9.9" + version = "=0.22.4" [[constraint]] name = "github.com/tendermint/iavl" - version = "=0.8.0-rc0" - -[[constraint]] - name = "github.com/prometheus/client_golang" - branch = "master" - -[[override]] - name = "github.com/tendermint/tmlibs" - version = "~0.8.4" + version = "=0.9.2" -# We don't care which version Tendermint wants [[override]] name = "github.com/gogo/protobuf" version = "~1.1.0" diff --git a/README.md b/README.md index 285449c15..2cd557c77 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Hyperledger Burrow is a permissioned Ethereum smart-contract blockchain node. It Hyperledger Burrow is a permissioned blockchain node that executes smart contract code following the Ethereum specification. Burrow is built for a multi-chain universe with application specific optimization in mind. Burrow as a node is constructed out of three main components: the consensus engine, the permissioned Ethereum virtual machine and the rpc gateway. More specifically Burrow consists of the following: - **Consensus Engine:** Transactions are ordered and finalised with the Byzantine fault-tolerant Tendermint protocol. The Tendermint protocol provides high transaction throughput over a set of known validators and prevents the blockchain from forking. -- **Application Blockchain Interface (ABCI):** The smart contract application interfaces with the consensus engine over the [ABCI](https://github.com/tendermint/abci). The ABCI allows for the consensus engine to remain agnostic from the smart contract application. +- **Application Blockchain Interface (ABCI):** The smart contract application interfaces with the consensus engine over the [ABCI](https://github.com/tendermint/tendermint/abci). The ABCI allows for the consensus engine to remain agnostic from the smart contract application. - **Smart Contract Application:** Transactions are validated and applied to the application state in the order that the consensus engine has finalised them. The application state consists of all accounts, the validator set and the name registry. Accounts in Burrow have permissions and either contain smart contract code or correspond to a public-private key pair. A transaction that calls on the smart contract code in a given account will activate the execution of that account’s code in a permissioned virtual machine. - **Permissioned Ethereum Virtual Machine:** This virtual machine is built to observe the Ethereum operation code specification and additionally asserts the correct permissions have been granted. Permissioning is enforced through secure native functions and underlies all smart contract code. An arbitrary but finite amount of gas is handed out for every execution to ensure a finite execution duration - “You don’t need money to play, when you have permission to play”. - **Application Binary Interface (ABI):** Transactions need to be formulated in a binary format that can be processed by the blockchain node. Current tooling provides functionality to compile, deploy and link solidity smart contracts and formulate transactions to call smart contracts on the chain. diff --git a/vendor/github.com/btcsuite/btcd/btcec/pubkey.go b/vendor/github.com/btcsuite/btcd/btcec/pubkey.go index b74917718..cf4980752 100644 --- a/vendor/github.com/btcsuite/btcd/btcec/pubkey.go +++ b/vendor/github.com/btcsuite/btcd/btcec/pubkey.go @@ -32,8 +32,9 @@ func decompressPoint(curve *KoblitzCurve, x *big.Int, ybit bool) (*big.Int, erro x3 := new(big.Int).Mul(x, x) x3.Mul(x3, x) x3.Add(x3, curve.Params().B) + x3.Mod(x3, curve.Params().P) - // now calculate sqrt mod p of x2 + B + // Now calculate sqrt mod p of x^3 + B // This code used to do a full sqrt based on tonelli/shanks, // but this was replaced by the algorithms referenced in // https://bitcointalk.org/index.php?topic=162805.msg1712294#msg1712294 @@ -42,9 +43,19 @@ func decompressPoint(curve *KoblitzCurve, x *big.Int, ybit bool) (*big.Int, erro if ybit != isOdd(y) { y.Sub(curve.Params().P, y) } + + // Check that y is a square root of x^3 + B. + y2 := new(big.Int).Mul(y, y) + y2.Mod(y2, curve.Params().P) + if y2.Cmp(x3) != 0 { + return nil, fmt.Errorf("invalid square root") + } + + // Verify that y-coord has expected parity. if ybit != isOdd(y) { return nil, fmt.Errorf("ybit doesn't match oddness") } + return y, nil } diff --git a/vendor/github.com/go-kit/kit/metrics/discard/discard.go b/vendor/github.com/go-kit/kit/metrics/discard/discard.go new file mode 100644 index 000000000..a0d3b1494 --- /dev/null +++ b/vendor/github.com/go-kit/kit/metrics/discard/discard.go @@ -0,0 +1,40 @@ +// Package discard provides a no-op metrics backend. +package discard + +import "github.com/go-kit/kit/metrics" + +type counter struct{} + +// NewCounter returns a new no-op counter. +func NewCounter() metrics.Counter { return counter{} } + +// With implements Counter. +func (c counter) With(labelValues ...string) metrics.Counter { return c } + +// Add implements Counter. +func (c counter) Add(delta float64) {} + +type gauge struct{} + +// NewGauge returns a new no-op gauge. +func NewGauge() metrics.Gauge { return gauge{} } + +// With implements Gauge. +func (g gauge) With(labelValues ...string) metrics.Gauge { return g } + +// Set implements Gauge. +func (g gauge) Set(value float64) {} + +// Add implements metrics.Gauge. +func (g gauge) Add(delta float64) {} + +type histogram struct{} + +// NewHistogram returns a new no-op histogram. +func NewHistogram() metrics.Histogram { return histogram{} } + +// With implements Histogram. +func (h histogram) With(labelValues ...string) metrics.Histogram { return h } + +// Observe implements histogram. +func (h histogram) Observe(value float64) {} diff --git a/vendor/github.com/go-kit/kit/metrics/doc.go b/vendor/github.com/go-kit/kit/metrics/doc.go new file mode 100644 index 000000000..25cda4f7c --- /dev/null +++ b/vendor/github.com/go-kit/kit/metrics/doc.go @@ -0,0 +1,97 @@ +// Package metrics provides a framework for application instrumentation. It's +// primarily designed to help you get started with good and robust +// instrumentation, and to help you migrate from a less-capable system like +// Graphite to a more-capable system like Prometheus. If your organization has +// already standardized on an instrumentation system like Prometheus, and has no +// plans to change, it may make sense to use that system's instrumentation +// library directly. +// +// This package provides three core metric abstractions (Counter, Gauge, and +// Histogram) and implementations for almost all common instrumentation +// backends. Each metric has an observation method (Add, Set, or Observe, +// respectively) used to record values, and a With method to "scope" the +// observation by various parameters. For example, you might have a Histogram to +// record request durations, parameterized by the method that's being called. +// +// var requestDuration metrics.Histogram +// // ... +// requestDuration.With("method", "MyMethod").Observe(time.Since(begin)) +// +// This allows a single high-level metrics object (requestDuration) to work with +// many code paths somewhat dynamically. The concept of With is fully supported +// in some backends like Prometheus, and not supported in other backends like +// Graphite. So, With may be a no-op, depending on the concrete implementation +// you choose. Please check the implementation to know for sure. For +// implementations that don't provide With, it's necessary to fully parameterize +// each metric in the metric name, e.g. +// +// // Statsd +// c := statsd.NewCounter("request_duration_MyMethod_200") +// c.Add(1) +// +// // Prometheus +// c := prometheus.NewCounter(stdprometheus.CounterOpts{ +// Name: "request_duration", +// ... +// }, []string{"method", "status_code"}) +// c.With("method", "MyMethod", "status_code", strconv.Itoa(code)).Add(1) +// +// Usage +// +// Metrics are dependencies, and should be passed to the components that need +// them in the same way you'd construct and pass a database handle, or reference +// to another component. Metrics should *not* be created in the global scope. +// Instead, instantiate metrics in your func main, using whichever concrete +// implementation is appropriate for your organization. +// +// latency := prometheus.NewSummaryFrom(stdprometheus.SummaryOpts{ +// Namespace: "myteam", +// Subsystem: "foosvc", +// Name: "request_latency_seconds", +// Help: "Incoming request latency in seconds.", +// }, []string{"method", "status_code"}) +// +// Write your components to take the metrics they will use as parameters to +// their constructors. Use the interface types, not the concrete types. That is, +// +// // NewAPI takes metrics.Histogram, not *prometheus.Summary +// func NewAPI(s Store, logger log.Logger, latency metrics.Histogram) *API { +// // ... +// } +// +// func (a *API) ServeFoo(w http.ResponseWriter, r *http.Request) { +// begin := time.Now() +// // ... +// a.latency.Observe(time.Since(begin).Seconds()) +// } +// +// Finally, pass the metrics as dependencies when building your object graph. +// This should happen in func main, not in the global scope. +// +// api := NewAPI(store, logger, latency) +// http.ListenAndServe("/", api) +// +// Note that metrics are "write-only" interfaces. +// +// Implementation details +// +// All metrics are safe for concurrent use. Considerable design influence has +// been taken from https://github.com/codahale/metrics and +// https://prometheus.io. +// +// Each telemetry system has different semantics for label values, push vs. +// pull, support for histograms, etc. These properties influence the design of +// their respective packages. This table attempts to summarize the key points of +// distinction. +// +// SYSTEM DIM COUNTERS GAUGES HISTOGRAMS +// dogstatsd n batch, push-aggregate batch, push-aggregate native, batch, push-each +// statsd 1 batch, push-aggregate batch, push-aggregate native, batch, push-each +// graphite 1 batch, push-aggregate batch, push-aggregate synthetic, batch, push-aggregate +// expvar 1 atomic atomic synthetic, batch, in-place expose +// influx n custom custom custom +// prometheus n native native native +// pcp 1 native native native +// cloudwatch n batch push-aggregate batch push-aggregate synthetic, batch, push-aggregate +// +package metrics diff --git a/vendor/github.com/go-kit/kit/metrics/internal/lv/labelvalues.go b/vendor/github.com/go-kit/kit/metrics/internal/lv/labelvalues.go new file mode 100644 index 000000000..8bb1ba094 --- /dev/null +++ b/vendor/github.com/go-kit/kit/metrics/internal/lv/labelvalues.go @@ -0,0 +1,14 @@ +package lv + +// LabelValues is a type alias that provides validation on its With method. +// Metrics may include it as a member to help them satisfy With semantics and +// save some code duplication. +type LabelValues []string + +// With validates the input, and returns a new aggregate labelValues. +func (lvs LabelValues) With(labelValues ...string) LabelValues { + if len(labelValues)%2 != 0 { + labelValues = append(labelValues, "unknown") + } + return append(lvs, labelValues...) +} diff --git a/vendor/github.com/go-kit/kit/metrics/internal/lv/space.go b/vendor/github.com/go-kit/kit/metrics/internal/lv/space.go new file mode 100644 index 000000000..672c90074 --- /dev/null +++ b/vendor/github.com/go-kit/kit/metrics/internal/lv/space.go @@ -0,0 +1,145 @@ +package lv + +import "sync" + +// NewSpace returns an N-dimensional vector space. +func NewSpace() *Space { + return &Space{} +} + +// Space represents an N-dimensional vector space. Each name and unique label +// value pair establishes a new dimension and point within that dimension. Order +// matters, i.e. [a=1 b=2] identifies a different timeseries than [b=2 a=1]. +type Space struct { + mtx sync.RWMutex + nodes map[string]*node +} + +// Observe locates the time series identified by the name and label values in +// the vector space, and appends the value to the list of observations. +func (s *Space) Observe(name string, lvs LabelValues, value float64) { + s.nodeFor(name).observe(lvs, value) +} + +// Add locates the time series identified by the name and label values in +// the vector space, and appends the delta to the last value in the list of +// observations. +func (s *Space) Add(name string, lvs LabelValues, delta float64) { + s.nodeFor(name).add(lvs, delta) +} + +// Walk traverses the vector space and invokes fn for each non-empty time series +// which is encountered. Return false to abort the traversal. +func (s *Space) Walk(fn func(name string, lvs LabelValues, observations []float64) bool) { + s.mtx.RLock() + defer s.mtx.RUnlock() + for name, node := range s.nodes { + f := func(lvs LabelValues, observations []float64) bool { return fn(name, lvs, observations) } + if !node.walk(LabelValues{}, f) { + return + } + } +} + +// Reset empties the current space and returns a new Space with the old +// contents. Reset a Space to get an immutable copy suitable for walking. +func (s *Space) Reset() *Space { + s.mtx.Lock() + defer s.mtx.Unlock() + n := NewSpace() + n.nodes, s.nodes = s.nodes, n.nodes + return n +} + +func (s *Space) nodeFor(name string) *node { + s.mtx.Lock() + defer s.mtx.Unlock() + if s.nodes == nil { + s.nodes = map[string]*node{} + } + n, ok := s.nodes[name] + if !ok { + n = &node{} + s.nodes[name] = n + } + return n +} + +// node exists at a specific point in the N-dimensional vector space of all +// possible label values. The node collects observations and has child nodes +// with greater specificity. +type node struct { + mtx sync.RWMutex + observations []float64 + children map[pair]*node +} + +type pair struct{ label, value string } + +func (n *node) observe(lvs LabelValues, value float64) { + n.mtx.Lock() + defer n.mtx.Unlock() + if len(lvs) == 0 { + n.observations = append(n.observations, value) + return + } + if len(lvs) < 2 { + panic("too few LabelValues; programmer error!") + } + head, tail := pair{lvs[0], lvs[1]}, lvs[2:] + if n.children == nil { + n.children = map[pair]*node{} + } + child, ok := n.children[head] + if !ok { + child = &node{} + n.children[head] = child + } + child.observe(tail, value) +} + +func (n *node) add(lvs LabelValues, delta float64) { + n.mtx.Lock() + defer n.mtx.Unlock() + if len(lvs) == 0 { + var value float64 + if len(n.observations) > 0 { + value = last(n.observations) + delta + } else { + value = delta + } + n.observations = append(n.observations, value) + return + } + if len(lvs) < 2 { + panic("too few LabelValues; programmer error!") + } + head, tail := pair{lvs[0], lvs[1]}, lvs[2:] + if n.children == nil { + n.children = map[pair]*node{} + } + child, ok := n.children[head] + if !ok { + child = &node{} + n.children[head] = child + } + child.add(tail, delta) +} + +func (n *node) walk(lvs LabelValues, fn func(LabelValues, []float64) bool) bool { + n.mtx.RLock() + defer n.mtx.RUnlock() + if len(n.observations) > 0 && !fn(lvs, n.observations) { + return false + } + for p, child := range n.children { + if !child.walk(append(lvs, p.label, p.value), fn) { + return false + } + } + return true +} + +func last(a []float64) float64 { + return a[len(a)-1] +} diff --git a/vendor/github.com/go-kit/kit/metrics/metrics.go b/vendor/github.com/go-kit/kit/metrics/metrics.go new file mode 100644 index 000000000..a7ba1b1fe --- /dev/null +++ b/vendor/github.com/go-kit/kit/metrics/metrics.go @@ -0,0 +1,25 @@ +package metrics + +// Counter describes a metric that accumulates values monotonically. +// An example of a counter is the number of received HTTP requests. +type Counter interface { + With(labelValues ...string) Counter + Add(delta float64) +} + +// Gauge describes a metric that takes specific values over time. +// An example of a gauge is the current depth of a job queue. +type Gauge interface { + With(labelValues ...string) Gauge + Set(value float64) + Add(delta float64) +} + +// Histogram describes a metric that takes repeated observations of the same +// kind of thing, and produces a statistical summary of those observations, +// typically expressed as quantiles or buckets. An example of a histogram is +// HTTP request latencies. +type Histogram interface { + With(labelValues ...string) Histogram + Observe(value float64) +} diff --git a/vendor/github.com/go-kit/kit/metrics/prometheus/prometheus.go b/vendor/github.com/go-kit/kit/metrics/prometheus/prometheus.go new file mode 100644 index 000000000..7a364c316 --- /dev/null +++ b/vendor/github.com/go-kit/kit/metrics/prometheus/prometheus.go @@ -0,0 +1,165 @@ +// Package prometheus provides Prometheus implementations for metrics. +// Individual metrics are mapped to their Prometheus counterparts, and +// (depending on the constructor used) may be automatically registered in the +// global Prometheus metrics registry. +package prometheus + +import ( + "github.com/prometheus/client_golang/prometheus" + + "github.com/go-kit/kit/metrics" + "github.com/go-kit/kit/metrics/internal/lv" +) + +// Counter implements Counter, via a Prometheus CounterVec. +type Counter struct { + cv *prometheus.CounterVec + lvs lv.LabelValues +} + +// NewCounterFrom constructs and registers a Prometheus CounterVec, +// and returns a usable Counter object. +func NewCounterFrom(opts prometheus.CounterOpts, labelNames []string) *Counter { + cv := prometheus.NewCounterVec(opts, labelNames) + prometheus.MustRegister(cv) + return NewCounter(cv) +} + +// NewCounter wraps the CounterVec and returns a usable Counter object. +func NewCounter(cv *prometheus.CounterVec) *Counter { + return &Counter{ + cv: cv, + } +} + +// With implements Counter. +func (c *Counter) With(labelValues ...string) metrics.Counter { + return &Counter{ + cv: c.cv, + lvs: c.lvs.With(labelValues...), + } +} + +// Add implements Counter. +func (c *Counter) Add(delta float64) { + c.cv.With(makeLabels(c.lvs...)).Add(delta) +} + +// Gauge implements Gauge, via a Prometheus GaugeVec. +type Gauge struct { + gv *prometheus.GaugeVec + lvs lv.LabelValues +} + +// NewGaugeFrom construts and registers a Prometheus GaugeVec, +// and returns a usable Gauge object. +func NewGaugeFrom(opts prometheus.GaugeOpts, labelNames []string) *Gauge { + gv := prometheus.NewGaugeVec(opts, labelNames) + prometheus.MustRegister(gv) + return NewGauge(gv) +} + +// NewGauge wraps the GaugeVec and returns a usable Gauge object. +func NewGauge(gv *prometheus.GaugeVec) *Gauge { + return &Gauge{ + gv: gv, + } +} + +// With implements Gauge. +func (g *Gauge) With(labelValues ...string) metrics.Gauge { + return &Gauge{ + gv: g.gv, + lvs: g.lvs.With(labelValues...), + } +} + +// Set implements Gauge. +func (g *Gauge) Set(value float64) { + g.gv.With(makeLabels(g.lvs...)).Set(value) +} + +// Add is supported by Prometheus GaugeVecs. +func (g *Gauge) Add(delta float64) { + g.gv.With(makeLabels(g.lvs...)).Add(delta) +} + +// Summary implements Histogram, via a Prometheus SummaryVec. The difference +// between a Summary and a Histogram is that Summaries don't require predefined +// quantile buckets, but cannot be statistically aggregated. +type Summary struct { + sv *prometheus.SummaryVec + lvs lv.LabelValues +} + +// NewSummaryFrom constructs and registers a Prometheus SummaryVec, +// and returns a usable Summary object. +func NewSummaryFrom(opts prometheus.SummaryOpts, labelNames []string) *Summary { + sv := prometheus.NewSummaryVec(opts, labelNames) + prometheus.MustRegister(sv) + return NewSummary(sv) +} + +// NewSummary wraps the SummaryVec and returns a usable Summary object. +func NewSummary(sv *prometheus.SummaryVec) *Summary { + return &Summary{ + sv: sv, + } +} + +// With implements Histogram. +func (s *Summary) With(labelValues ...string) metrics.Histogram { + return &Summary{ + sv: s.sv, + lvs: s.lvs.With(labelValues...), + } +} + +// Observe implements Histogram. +func (s *Summary) Observe(value float64) { + s.sv.With(makeLabels(s.lvs...)).Observe(value) +} + +// Histogram implements Histogram via a Prometheus HistogramVec. The difference +// between a Histogram and a Summary is that Histograms require predefined +// quantile buckets, and can be statistically aggregated. +type Histogram struct { + hv *prometheus.HistogramVec + lvs lv.LabelValues +} + +// NewHistogramFrom constructs and registers a Prometheus HistogramVec, +// and returns a usable Histogram object. +func NewHistogramFrom(opts prometheus.HistogramOpts, labelNames []string) *Histogram { + hv := prometheus.NewHistogramVec(opts, labelNames) + prometheus.MustRegister(hv) + return NewHistogram(hv) +} + +// NewHistogram wraps the HistogramVec and returns a usable Histogram object. +func NewHistogram(hv *prometheus.HistogramVec) *Histogram { + return &Histogram{ + hv: hv, + } +} + +// With implements Histogram. +func (h *Histogram) With(labelValues ...string) metrics.Histogram { + return &Histogram{ + hv: h.hv, + lvs: h.lvs.With(labelValues...), + } +} + +// Observe implements Histogram. +func (h *Histogram) Observe(value float64) { + h.hv.With(makeLabels(h.lvs...)).Observe(value) +} + +func makeLabels(labelValues ...string) prometheus.Labels { + labels := prometheus.Labels{} + for i := 0; i < len(labelValues); i += 2 { + labels[labelValues[i]] = labelValues[i+1] + } + return labels +} diff --git a/vendor/github.com/go-kit/kit/metrics/timer.go b/vendor/github.com/go-kit/kit/metrics/timer.go new file mode 100644 index 000000000..e12d9cd5c --- /dev/null +++ b/vendor/github.com/go-kit/kit/metrics/timer.go @@ -0,0 +1,36 @@ +package metrics + +import "time" + +// Timer acts as a stopwatch, sending observations to a wrapped histogram. +// It's a bit of helpful syntax sugar for h.Observe(time.Since(x)). +type Timer struct { + h Histogram + t time.Time + u time.Duration +} + +// NewTimer wraps the given histogram and records the current time. +func NewTimer(h Histogram) *Timer { + return &Timer{ + h: h, + t: time.Now(), + u: time.Second, + } +} + +// ObserveDuration captures the number of seconds since the timer was +// constructed, and forwards that observation to the histogram. +func (t *Timer) ObserveDuration() { + d := float64(time.Since(t.t).Nanoseconds()) / float64(t.u) + if d < 0 { + d = 0 + } + t.h.Observe(d) +} + +// Unit sets the unit of the float64 emitted by the timer. +// By default, the timer emits seconds. +func (t *Timer) Unit(u time.Duration) { + t.u = u +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/collector.go b/vendor/github.com/prometheus/client_golang/prometheus/collector.go index 623d3d83f..3c9bae24b 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/collector.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/collector.go @@ -29,24 +29,35 @@ type Collector interface { // collected by this Collector to the provided channel and returns once // the last descriptor has been sent. The sent descriptors fulfill the // consistency and uniqueness requirements described in the Desc - // documentation. (It is valid if one and the same Collector sends - // duplicate descriptors. Those duplicates are simply ignored. However, - // two different Collectors must not send duplicate descriptors.) This - // method idempotently sends the same descriptors throughout the - // lifetime of the Collector. If a Collector encounters an error while - // executing this method, it must send an invalid descriptor (created - // with NewInvalidDesc) to signal the error to the registry. + // documentation. + // + // It is valid if one and the same Collector sends duplicate + // descriptors. Those duplicates are simply ignored. However, two + // different Collectors must not send duplicate descriptors. + // + // Sending no descriptor at all marks the Collector as “unchecked”, + // i.e. no checks will be performed at registration time, and the + // Collector may yield any Metric it sees fit in its Collect method. + // + // This method idempotently sends the same descriptors throughout the + // lifetime of the Collector. + // + // If a Collector encounters an error while executing this method, it + // must send an invalid descriptor (created with NewInvalidDesc) to + // signal the error to the registry. Describe(chan<- *Desc) // Collect is called by the Prometheus registry when collecting // metrics. The implementation sends each collected metric via the // provided channel and returns once the last metric has been sent. The - // descriptor of each sent metric is one of those returned by - // Describe. Returned metrics that share the same descriptor must differ - // in their variable label values. This method may be called - // concurrently and must therefore be implemented in a concurrency safe - // way. Blocking occurs at the expense of total performance of rendering - // all registered metrics. Ideally, Collector implementations support - // concurrent readers. + // descriptor of each sent metric is one of those returned by Describe + // (unless the Collector is unchecked, see above). Returned metrics that + // share the same descriptor must differ in their variable label + // values. + // + // This method may be called concurrently and must therefore be + // implemented in a concurrency safe way. Blocking occurs at the expense + // of total performance of rendering all registered metrics. Ideally, + // Collector implementations support concurrent readers. Collect(chan<- Metric) } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/doc.go b/vendor/github.com/prometheus/client_golang/prometheus/doc.go index 83c3657d7..5d9525def 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/doc.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/doc.go @@ -121,7 +121,17 @@ // NewConstSummary (and their respective Must… versions). That will happen in // the Collect method. The Describe method has to return separate Desc // instances, representative of the “throw-away” metrics to be created later. -// NewDesc comes in handy to create those Desc instances. +// NewDesc comes in handy to create those Desc instances. Alternatively, you +// could return no Desc at all, which will marke the Collector “unchecked”. No +// checks are porformed at registration time, but metric consistency will still +// be ensured at scrape time, i.e. any inconsistencies will lead to scrape +// errors. Thus, with unchecked Collectors, the responsibility to not collect +// metrics that lead to inconsistencies in the total scrape result lies with the +// implementer of the Collector. While this is not a desirable state, it is +// sometimes necessary. The typical use case is a situatios where the exact +// metrics to be returned by a Collector cannot be predicted at registration +// time, but the implementer has sufficient knowledge of the whole system to +// guarantee metric consistency. // // The Collector example illustrates the use case. You can also look at the // source code of the processCollector (mirroring process metrics), the diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator.go new file mode 100644 index 000000000..9c1c66dcc --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator.go @@ -0,0 +1,199 @@ +// Copyright 2017 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package promhttp + +import ( + "bufio" + "io" + "net" + "net/http" +) + +const ( + closeNotifier = 1 << iota + flusher + hijacker + readerFrom + pusher +) + +type delegator interface { + http.ResponseWriter + + Status() int + Written() int64 +} + +type responseWriterDelegator struct { + http.ResponseWriter + + handler, method string + status int + written int64 + wroteHeader bool + observeWriteHeader func(int) +} + +func (r *responseWriterDelegator) Status() int { + return r.status +} + +func (r *responseWriterDelegator) Written() int64 { + return r.written +} + +func (r *responseWriterDelegator) WriteHeader(code int) { + r.status = code + r.wroteHeader = true + r.ResponseWriter.WriteHeader(code) + if r.observeWriteHeader != nil { + r.observeWriteHeader(code) + } +} + +func (r *responseWriterDelegator) Write(b []byte) (int, error) { + if !r.wroteHeader { + r.WriteHeader(http.StatusOK) + } + n, err := r.ResponseWriter.Write(b) + r.written += int64(n) + return n, err +} + +type closeNotifierDelegator struct{ *responseWriterDelegator } +type flusherDelegator struct{ *responseWriterDelegator } +type hijackerDelegator struct{ *responseWriterDelegator } +type readerFromDelegator struct{ *responseWriterDelegator } + +func (d *closeNotifierDelegator) CloseNotify() <-chan bool { + return d.ResponseWriter.(http.CloseNotifier).CloseNotify() +} +func (d *flusherDelegator) Flush() { + d.ResponseWriter.(http.Flusher).Flush() +} +func (d *hijackerDelegator) Hijack() (net.Conn, *bufio.ReadWriter, error) { + return d.ResponseWriter.(http.Hijacker).Hijack() +} +func (d *readerFromDelegator) ReadFrom(re io.Reader) (int64, error) { + if !d.wroteHeader { + d.WriteHeader(http.StatusOK) + } + n, err := d.ResponseWriter.(io.ReaderFrom).ReadFrom(re) + d.written += n + return n, err +} + +var pickDelegator = make([]func(*responseWriterDelegator) delegator, 32) + +func init() { + // TODO(beorn7): Code generation would help here. + pickDelegator[0] = func(d *responseWriterDelegator) delegator { // 0 + return d + } + pickDelegator[closeNotifier] = func(d *responseWriterDelegator) delegator { // 1 + return &closeNotifierDelegator{d} + } + pickDelegator[flusher] = func(d *responseWriterDelegator) delegator { // 2 + return &flusherDelegator{d} + } + pickDelegator[flusher+closeNotifier] = func(d *responseWriterDelegator) delegator { // 3 + return struct { + *responseWriterDelegator + http.Flusher + http.CloseNotifier + }{d, &flusherDelegator{d}, &closeNotifierDelegator{d}} + } + pickDelegator[hijacker] = func(d *responseWriterDelegator) delegator { // 4 + return &hijackerDelegator{d} + } + pickDelegator[hijacker+closeNotifier] = func(d *responseWriterDelegator) delegator { // 5 + return struct { + *responseWriterDelegator + http.Hijacker + http.CloseNotifier + }{d, &hijackerDelegator{d}, &closeNotifierDelegator{d}} + } + pickDelegator[hijacker+flusher] = func(d *responseWriterDelegator) delegator { // 6 + return struct { + *responseWriterDelegator + http.Hijacker + http.Flusher + }{d, &hijackerDelegator{d}, &flusherDelegator{d}} + } + pickDelegator[hijacker+flusher+closeNotifier] = func(d *responseWriterDelegator) delegator { // 7 + return struct { + *responseWriterDelegator + http.Hijacker + http.Flusher + http.CloseNotifier + }{d, &hijackerDelegator{d}, &flusherDelegator{d}, &closeNotifierDelegator{d}} + } + pickDelegator[readerFrom] = func(d *responseWriterDelegator) delegator { // 8 + return readerFromDelegator{d} + } + pickDelegator[readerFrom+closeNotifier] = func(d *responseWriterDelegator) delegator { // 9 + return struct { + *responseWriterDelegator + io.ReaderFrom + http.CloseNotifier + }{d, &readerFromDelegator{d}, &closeNotifierDelegator{d}} + } + pickDelegator[readerFrom+flusher] = func(d *responseWriterDelegator) delegator { // 10 + return struct { + *responseWriterDelegator + io.ReaderFrom + http.Flusher + }{d, &readerFromDelegator{d}, &flusherDelegator{d}} + } + pickDelegator[readerFrom+flusher+closeNotifier] = func(d *responseWriterDelegator) delegator { // 11 + return struct { + *responseWriterDelegator + io.ReaderFrom + http.Flusher + http.CloseNotifier + }{d, &readerFromDelegator{d}, &flusherDelegator{d}, &closeNotifierDelegator{d}} + } + pickDelegator[readerFrom+hijacker] = func(d *responseWriterDelegator) delegator { // 12 + return struct { + *responseWriterDelegator + io.ReaderFrom + http.Hijacker + }{d, &readerFromDelegator{d}, &hijackerDelegator{d}} + } + pickDelegator[readerFrom+hijacker+closeNotifier] = func(d *responseWriterDelegator) delegator { // 13 + return struct { + *responseWriterDelegator + io.ReaderFrom + http.Hijacker + http.CloseNotifier + }{d, &readerFromDelegator{d}, &hijackerDelegator{d}, &closeNotifierDelegator{d}} + } + pickDelegator[readerFrom+hijacker+flusher] = func(d *responseWriterDelegator) delegator { // 14 + return struct { + *responseWriterDelegator + io.ReaderFrom + http.Hijacker + http.Flusher + }{d, &readerFromDelegator{d}, &hijackerDelegator{d}, &flusherDelegator{d}} + } + pickDelegator[readerFrom+hijacker+flusher+closeNotifier] = func(d *responseWriterDelegator) delegator { // 15 + return struct { + *responseWriterDelegator + io.ReaderFrom + http.Hijacker + http.Flusher + http.CloseNotifier + }{d, &readerFromDelegator{d}, &hijackerDelegator{d}, &flusherDelegator{d}, &closeNotifierDelegator{d}} + } +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_1_8.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_1_8.go new file mode 100644 index 000000000..75a905e2f --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_1_8.go @@ -0,0 +1,181 @@ +// Copyright 2017 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build go1.8 + +package promhttp + +import ( + "io" + "net/http" +) + +type pusherDelegator struct{ *responseWriterDelegator } + +func (d *pusherDelegator) Push(target string, opts *http.PushOptions) error { + return d.ResponseWriter.(http.Pusher).Push(target, opts) +} + +func init() { + pickDelegator[pusher] = func(d *responseWriterDelegator) delegator { // 16 + return &pusherDelegator{d} + } + pickDelegator[pusher+closeNotifier] = func(d *responseWriterDelegator) delegator { // 17 + return struct { + *responseWriterDelegator + http.Pusher + http.CloseNotifier + }{d, &pusherDelegator{d}, &closeNotifierDelegator{d}} + } + pickDelegator[pusher+flusher] = func(d *responseWriterDelegator) delegator { // 18 + return struct { + *responseWriterDelegator + http.Pusher + http.Flusher + }{d, &pusherDelegator{d}, &flusherDelegator{d}} + } + pickDelegator[pusher+flusher+closeNotifier] = func(d *responseWriterDelegator) delegator { // 19 + return struct { + *responseWriterDelegator + http.Pusher + http.Flusher + http.CloseNotifier + }{d, &pusherDelegator{d}, &flusherDelegator{d}, &closeNotifierDelegator{d}} + } + pickDelegator[pusher+hijacker] = func(d *responseWriterDelegator) delegator { // 20 + return struct { + *responseWriterDelegator + http.Pusher + http.Hijacker + }{d, &pusherDelegator{d}, &hijackerDelegator{d}} + } + pickDelegator[pusher+hijacker+closeNotifier] = func(d *responseWriterDelegator) delegator { // 21 + return struct { + *responseWriterDelegator + http.Pusher + http.Hijacker + http.CloseNotifier + }{d, &pusherDelegator{d}, &hijackerDelegator{d}, &closeNotifierDelegator{d}} + } + pickDelegator[pusher+hijacker+flusher] = func(d *responseWriterDelegator) delegator { // 22 + return struct { + *responseWriterDelegator + http.Pusher + http.Hijacker + http.Flusher + }{d, &pusherDelegator{d}, &hijackerDelegator{d}, &flusherDelegator{d}} + } + pickDelegator[pusher+hijacker+flusher+closeNotifier] = func(d *responseWriterDelegator) delegator { //23 + return struct { + *responseWriterDelegator + http.Pusher + http.Hijacker + http.Flusher + http.CloseNotifier + }{d, &pusherDelegator{d}, &hijackerDelegator{d}, &flusherDelegator{d}, &closeNotifierDelegator{d}} + } + pickDelegator[pusher+readerFrom] = func(d *responseWriterDelegator) delegator { // 24 + return struct { + *responseWriterDelegator + http.Pusher + io.ReaderFrom + }{d, &pusherDelegator{d}, &readerFromDelegator{d}} + } + pickDelegator[pusher+readerFrom+closeNotifier] = func(d *responseWriterDelegator) delegator { // 25 + return struct { + *responseWriterDelegator + http.Pusher + io.ReaderFrom + http.CloseNotifier + }{d, &pusherDelegator{d}, &readerFromDelegator{d}, &closeNotifierDelegator{d}} + } + pickDelegator[pusher+readerFrom+flusher] = func(d *responseWriterDelegator) delegator { // 26 + return struct { + *responseWriterDelegator + http.Pusher + io.ReaderFrom + http.Flusher + }{d, &pusherDelegator{d}, &readerFromDelegator{d}, &flusherDelegator{d}} + } + pickDelegator[pusher+readerFrom+flusher+closeNotifier] = func(d *responseWriterDelegator) delegator { // 27 + return struct { + *responseWriterDelegator + http.Pusher + io.ReaderFrom + http.Flusher + http.CloseNotifier + }{d, &pusherDelegator{d}, &readerFromDelegator{d}, &flusherDelegator{d}, &closeNotifierDelegator{d}} + } + pickDelegator[pusher+readerFrom+hijacker] = func(d *responseWriterDelegator) delegator { // 28 + return struct { + *responseWriterDelegator + http.Pusher + io.ReaderFrom + http.Hijacker + }{d, &pusherDelegator{d}, &readerFromDelegator{d}, &hijackerDelegator{d}} + } + pickDelegator[pusher+readerFrom+hijacker+closeNotifier] = func(d *responseWriterDelegator) delegator { // 29 + return struct { + *responseWriterDelegator + http.Pusher + io.ReaderFrom + http.Hijacker + http.CloseNotifier + }{d, &pusherDelegator{d}, &readerFromDelegator{d}, &hijackerDelegator{d}, &closeNotifierDelegator{d}} + } + pickDelegator[pusher+readerFrom+hijacker+flusher] = func(d *responseWriterDelegator) delegator { // 30 + return struct { + *responseWriterDelegator + http.Pusher + io.ReaderFrom + http.Hijacker + http.Flusher + }{d, &pusherDelegator{d}, &readerFromDelegator{d}, &hijackerDelegator{d}, &flusherDelegator{d}} + } + pickDelegator[pusher+readerFrom+hijacker+flusher+closeNotifier] = func(d *responseWriterDelegator) delegator { // 31 + return struct { + *responseWriterDelegator + http.Pusher + io.ReaderFrom + http.Hijacker + http.Flusher + http.CloseNotifier + }{d, &pusherDelegator{d}, &readerFromDelegator{d}, &hijackerDelegator{d}, &flusherDelegator{d}, &closeNotifierDelegator{d}} + } +} + +func newDelegator(w http.ResponseWriter, observeWriteHeaderFunc func(int)) delegator { + d := &responseWriterDelegator{ + ResponseWriter: w, + observeWriteHeader: observeWriteHeaderFunc, + } + + id := 0 + if _, ok := w.(http.CloseNotifier); ok { + id += closeNotifier + } + if _, ok := w.(http.Flusher); ok { + id += flusher + } + if _, ok := w.(http.Hijacker); ok { + id += hijacker + } + if _, ok := w.(io.ReaderFrom); ok { + id += readerFrom + } + if _, ok := w.(http.Pusher); ok { + id += pusher + } + + return pickDelegator[id](d) +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_pre_1_8.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_pre_1_8.go new file mode 100644 index 000000000..8bb9b8b68 --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_pre_1_8.go @@ -0,0 +1,44 @@ +// Copyright 2017 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build !go1.8 + +package promhttp + +import ( + "io" + "net/http" +) + +func newDelegator(w http.ResponseWriter, observeWriteHeaderFunc func(int)) delegator { + d := &responseWriterDelegator{ + ResponseWriter: w, + observeWriteHeader: observeWriteHeaderFunc, + } + + id := 0 + if _, ok := w.(http.CloseNotifier); ok { + id += closeNotifier + } + if _, ok := w.(http.Flusher); ok { + id += flusher + } + if _, ok := w.(http.Hijacker); ok { + id += hijacker + } + if _, ok := w.(io.ReaderFrom); ok { + id += readerFrom + } + + return pickDelegator[id](d) +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go new file mode 100644 index 000000000..01357374f --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go @@ -0,0 +1,311 @@ +// Copyright 2016 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package promhttp provides tooling around HTTP servers and clients. +// +// First, the package allows the creation of http.Handler instances to expose +// Prometheus metrics via HTTP. promhttp.Handler acts on the +// prometheus.DefaultGatherer. With HandlerFor, you can create a handler for a +// custom registry or anything that implements the Gatherer interface. It also +// allows the creation of handlers that act differently on errors or allow to +// log errors. +// +// Second, the package provides tooling to instrument instances of http.Handler +// via middleware. Middleware wrappers follow the naming scheme +// InstrumentHandlerX, where X describes the intended use of the middleware. +// See each function's doc comment for specific details. +// +// Finally, the package allows for an http.RoundTripper to be instrumented via +// middleware. Middleware wrappers follow the naming scheme +// InstrumentRoundTripperX, where X describes the intended use of the +// middleware. See each function's doc comment for specific details. +package promhttp + +import ( + "bytes" + "compress/gzip" + "fmt" + "io" + "net/http" + "strings" + "sync" + "time" + + "github.com/prometheus/common/expfmt" + + "github.com/prometheus/client_golang/prometheus" +) + +const ( + contentTypeHeader = "Content-Type" + contentLengthHeader = "Content-Length" + contentEncodingHeader = "Content-Encoding" + acceptEncodingHeader = "Accept-Encoding" +) + +var bufPool sync.Pool + +func getBuf() *bytes.Buffer { + buf := bufPool.Get() + if buf == nil { + return &bytes.Buffer{} + } + return buf.(*bytes.Buffer) +} + +func giveBuf(buf *bytes.Buffer) { + buf.Reset() + bufPool.Put(buf) +} + +// Handler returns an http.Handler for the prometheus.DefaultGatherer, using +// default HandlerOpts, i.e. it reports the first error as an HTTP error, it has +// no error logging, and it applies compression if requested by the client. +// +// The returned http.Handler is already instrumented using the +// InstrumentMetricHandler function and the prometheus.DefaultRegisterer. If you +// create multiple http.Handlers by separate calls of the Handler function, the +// metrics used for instrumentation will be shared between them, providing +// global scrape counts. +// +// This function is meant to cover the bulk of basic use cases. If you are doing +// anything that requires more customization (including using a non-default +// Gatherer, different instrumentation, and non-default HandlerOpts), use the +// HandlerFor function. See there for details. +func Handler() http.Handler { + return InstrumentMetricHandler( + prometheus.DefaultRegisterer, HandlerFor(prometheus.DefaultGatherer, HandlerOpts{}), + ) +} + +// HandlerFor returns an uninstrumented http.Handler for the provided +// Gatherer. The behavior of the Handler is defined by the provided +// HandlerOpts. Thus, HandlerFor is useful to create http.Handlers for custom +// Gatherers, with non-default HandlerOpts, and/or with custom (or no) +// instrumentation. Use the InstrumentMetricHandler function to apply the same +// kind of instrumentation as it is used by the Handler function. +func HandlerFor(reg prometheus.Gatherer, opts HandlerOpts) http.Handler { + var inFlightSem chan struct{} + if opts.MaxRequestsInFlight > 0 { + inFlightSem = make(chan struct{}, opts.MaxRequestsInFlight) + } + + h := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + if inFlightSem != nil { + select { + case inFlightSem <- struct{}{}: // All good, carry on. + defer func() { <-inFlightSem }() + default: + http.Error(w, fmt.Sprintf( + "Limit of concurrent requests reached (%d), try again later.", opts.MaxRequestsInFlight, + ), http.StatusServiceUnavailable) + return + } + } + + mfs, err := reg.Gather() + if err != nil { + if opts.ErrorLog != nil { + opts.ErrorLog.Println("error gathering metrics:", err) + } + switch opts.ErrorHandling { + case PanicOnError: + panic(err) + case ContinueOnError: + if len(mfs) == 0 { + http.Error(w, "No metrics gathered, last error:\n\n"+err.Error(), http.StatusInternalServerError) + return + } + case HTTPErrorOnError: + http.Error(w, "An error has occurred during metrics gathering:\n\n"+err.Error(), http.StatusInternalServerError) + return + } + } + + contentType := expfmt.Negotiate(req.Header) + buf := getBuf() + defer giveBuf(buf) + writer, encoding := decorateWriter(req, buf, opts.DisableCompression) + enc := expfmt.NewEncoder(writer, contentType) + var lastErr error + for _, mf := range mfs { + if err := enc.Encode(mf); err != nil { + lastErr = err + if opts.ErrorLog != nil { + opts.ErrorLog.Println("error encoding metric family:", err) + } + switch opts.ErrorHandling { + case PanicOnError: + panic(err) + case ContinueOnError: + // Handled later. + case HTTPErrorOnError: + http.Error(w, "An error has occurred during metrics encoding:\n\n"+err.Error(), http.StatusInternalServerError) + return + } + } + } + if closer, ok := writer.(io.Closer); ok { + closer.Close() + } + if lastErr != nil && buf.Len() == 0 { + http.Error(w, "No metrics encoded, last error:\n\n"+lastErr.Error(), http.StatusInternalServerError) + return + } + header := w.Header() + header.Set(contentTypeHeader, string(contentType)) + header.Set(contentLengthHeader, fmt.Sprint(buf.Len())) + if encoding != "" { + header.Set(contentEncodingHeader, encoding) + } + if _, err := w.Write(buf.Bytes()); err != nil && opts.ErrorLog != nil { + opts.ErrorLog.Println("error while sending encoded metrics:", err) + } + // TODO(beorn7): Consider streaming serving of metrics. + }) + + if opts.Timeout <= 0 { + return h + } + return http.TimeoutHandler(h, opts.Timeout, fmt.Sprintf( + "Exceeded configured timeout of %v.\n", + opts.Timeout, + )) +} + +// InstrumentMetricHandler is usually used with an http.Handler returned by the +// HandlerFor function. It instruments the provided http.Handler with two +// metrics: A counter vector "promhttp_metric_handler_requests_total" to count +// scrapes partitioned by HTTP status code, and a gauge +// "promhttp_metric_handler_requests_in_flight" to track the number of +// simultaneous scrapes. This function idempotently registers collectors for +// both metrics with the provided Registerer. It panics if the registration +// fails. The provided metrics are useful to see how many scrapes hit the +// monitored target (which could be from different Prometheus servers or other +// scrapers), and how often they overlap (which would result in more than one +// scrape in flight at the same time). Note that the scrapes-in-flight gauge +// will contain the scrape by which it is exposed, while the scrape counter will +// only get incremented after the scrape is complete (as only then the status +// code is known). For tracking scrape durations, use the +// "scrape_duration_seconds" gauge created by the Prometheus server upon each +// scrape. +func InstrumentMetricHandler(reg prometheus.Registerer, handler http.Handler) http.Handler { + cnt := prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "promhttp_metric_handler_requests_total", + Help: "Total number of scrapes by HTTP status code.", + }, + []string{"code"}, + ) + // Initialize the most likely HTTP status codes. + cnt.WithLabelValues("200") + cnt.WithLabelValues("500") + cnt.WithLabelValues("503") + if err := reg.Register(cnt); err != nil { + if are, ok := err.(prometheus.AlreadyRegisteredError); ok { + cnt = are.ExistingCollector.(*prometheus.CounterVec) + } else { + panic(err) + } + } + + gge := prometheus.NewGauge(prometheus.GaugeOpts{ + Name: "promhttp_metric_handler_requests_in_flight", + Help: "Current number of scrapes being served.", + }) + if err := reg.Register(gge); err != nil { + if are, ok := err.(prometheus.AlreadyRegisteredError); ok { + gge = are.ExistingCollector.(prometheus.Gauge) + } else { + panic(err) + } + } + + return InstrumentHandlerCounter(cnt, InstrumentHandlerInFlight(gge, handler)) +} + +// HandlerErrorHandling defines how a Handler serving metrics will handle +// errors. +type HandlerErrorHandling int + +// These constants cause handlers serving metrics to behave as described if +// errors are encountered. +const ( + // Serve an HTTP status code 500 upon the first error + // encountered. Report the error message in the body. + HTTPErrorOnError HandlerErrorHandling = iota + // Ignore errors and try to serve as many metrics as possible. However, + // if no metrics can be served, serve an HTTP status code 500 and the + // last error message in the body. Only use this in deliberate "best + // effort" metrics collection scenarios. It is recommended to at least + // log errors (by providing an ErrorLog in HandlerOpts) to not mask + // errors completely. + ContinueOnError + // Panic upon the first error encountered (useful for "crash only" apps). + PanicOnError +) + +// Logger is the minimal interface HandlerOpts needs for logging. Note that +// log.Logger from the standard library implements this interface, and it is +// easy to implement by custom loggers, if they don't do so already anyway. +type Logger interface { + Println(v ...interface{}) +} + +// HandlerOpts specifies options how to serve metrics via an http.Handler. The +// zero value of HandlerOpts is a reasonable default. +type HandlerOpts struct { + // ErrorLog specifies an optional logger for errors collecting and + // serving metrics. If nil, errors are not logged at all. + ErrorLog Logger + // ErrorHandling defines how errors are handled. Note that errors are + // logged regardless of the configured ErrorHandling provided ErrorLog + // is not nil. + ErrorHandling HandlerErrorHandling + // If DisableCompression is true, the handler will never compress the + // response, even if requested by the client. + DisableCompression bool + // The number of concurrent HTTP requests is limited to + // MaxRequestsInFlight. Additional requests are responded to with 503 + // Service Unavailable and a suitable message in the body. If + // MaxRequestsInFlight is 0 or negative, no limit is applied. + MaxRequestsInFlight int + // If handling a request takes longer than Timeout, it is responded to + // with 503 ServiceUnavailable and a suitable Message. No timeout is + // applied if Timeout is 0 or negative. Note that with the current + // implementation, reaching the timeout simply ends the HTTP requests as + // described above (and even that only if sending of the body hasn't + // started yet), while the bulk work of gathering all the metrics keeps + // running in the background (with the eventual result to be thrown + // away). Until the implementation is improved, it is recommended to + // implement a separate timeout in potentially slow Collectors. + Timeout time.Duration +} + +// decorateWriter wraps a writer to handle gzip compression if requested. It +// returns the decorated writer and the appropriate "Content-Encoding" header +// (which is empty if no compression is enabled). +func decorateWriter(request *http.Request, writer io.Writer, compressionDisabled bool) (io.Writer, string) { + if compressionDisabled { + return writer, "" + } + header := request.Header.Get(acceptEncodingHeader) + parts := strings.Split(header, ",") + for _, part := range parts { + part = strings.TrimSpace(part) + if part == "gzip" || strings.HasPrefix(part, "gzip;") { + return gzip.NewWriter(writer), "gzip" + } + } + return writer, "" +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go new file mode 100644 index 000000000..86fd56447 --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go @@ -0,0 +1,97 @@ +// Copyright 2017 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package promhttp + +import ( + "net/http" + "time" + + "github.com/prometheus/client_golang/prometheus" +) + +// The RoundTripperFunc type is an adapter to allow the use of ordinary +// functions as RoundTrippers. If f is a function with the appropriate +// signature, RountTripperFunc(f) is a RoundTripper that calls f. +type RoundTripperFunc func(req *http.Request) (*http.Response, error) + +// RoundTrip implements the RoundTripper interface. +func (rt RoundTripperFunc) RoundTrip(r *http.Request) (*http.Response, error) { + return rt(r) +} + +// InstrumentRoundTripperInFlight is a middleware that wraps the provided +// http.RoundTripper. It sets the provided prometheus.Gauge to the number of +// requests currently handled by the wrapped http.RoundTripper. +// +// See the example for ExampleInstrumentRoundTripperDuration for example usage. +func InstrumentRoundTripperInFlight(gauge prometheus.Gauge, next http.RoundTripper) RoundTripperFunc { + return RoundTripperFunc(func(r *http.Request) (*http.Response, error) { + gauge.Inc() + defer gauge.Dec() + return next.RoundTrip(r) + }) +} + +// InstrumentRoundTripperCounter is a middleware that wraps the provided +// http.RoundTripper to observe the request result with the provided CounterVec. +// The CounterVec must have zero, one, or two non-const non-curried labels. For +// those, the only allowed label names are "code" and "method". The function +// panics otherwise. Partitioning of the CounterVec happens by HTTP status code +// and/or HTTP method if the respective instance label names are present in the +// CounterVec. For unpartitioned counting, use a CounterVec with zero labels. +// +// If the wrapped RoundTripper panics or returns a non-nil error, the Counter +// is not incremented. +// +// See the example for ExampleInstrumentRoundTripperDuration for example usage. +func InstrumentRoundTripperCounter(counter *prometheus.CounterVec, next http.RoundTripper) RoundTripperFunc { + code, method := checkLabels(counter) + + return RoundTripperFunc(func(r *http.Request) (*http.Response, error) { + resp, err := next.RoundTrip(r) + if err == nil { + counter.With(labels(code, method, r.Method, resp.StatusCode)).Inc() + } + return resp, err + }) +} + +// InstrumentRoundTripperDuration is a middleware that wraps the provided +// http.RoundTripper to observe the request duration with the provided +// ObserverVec. The ObserverVec must have zero, one, or two non-const +// non-curried labels. For those, the only allowed label names are "code" and +// "method". The function panics otherwise. The Observe method of the Observer +// in the ObserverVec is called with the request duration in +// seconds. Partitioning happens by HTTP status code and/or HTTP method if the +// respective instance label names are present in the ObserverVec. For +// unpartitioned observations, use an ObserverVec with zero labels. Note that +// partitioning of Histograms is expensive and should be used judiciously. +// +// If the wrapped RoundTripper panics or returns a non-nil error, no values are +// reported. +// +// Note that this method is only guaranteed to never observe negative durations +// if used with Go1.9+. +func InstrumentRoundTripperDuration(obs prometheus.ObserverVec, next http.RoundTripper) RoundTripperFunc { + code, method := checkLabels(obs) + + return RoundTripperFunc(func(r *http.Request) (*http.Response, error) { + start := time.Now() + resp, err := next.RoundTrip(r) + if err == nil { + obs.With(labels(code, method, r.Method, resp.StatusCode)).Observe(time.Since(start).Seconds()) + } + return resp, err + }) +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client_1_8.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client_1_8.go new file mode 100644 index 000000000..a034d1ec0 --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client_1_8.go @@ -0,0 +1,144 @@ +// Copyright 2017 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build go1.8 + +package promhttp + +import ( + "context" + "crypto/tls" + "net/http" + "net/http/httptrace" + "time" +) + +// InstrumentTrace is used to offer flexibility in instrumenting the available +// httptrace.ClientTrace hook functions. Each function is passed a float64 +// representing the time in seconds since the start of the http request. A user +// may choose to use separately buckets Histograms, or implement custom +// instance labels on a per function basis. +type InstrumentTrace struct { + GotConn func(float64) + PutIdleConn func(float64) + GotFirstResponseByte func(float64) + Got100Continue func(float64) + DNSStart func(float64) + DNSDone func(float64) + ConnectStart func(float64) + ConnectDone func(float64) + TLSHandshakeStart func(float64) + TLSHandshakeDone func(float64) + WroteHeaders func(float64) + Wait100Continue func(float64) + WroteRequest func(float64) +} + +// InstrumentRoundTripperTrace is a middleware that wraps the provided +// RoundTripper and reports times to hook functions provided in the +// InstrumentTrace struct. Hook functions that are not present in the provided +// InstrumentTrace struct are ignored. Times reported to the hook functions are +// time since the start of the request. Only with Go1.9+, those times are +// guaranteed to never be negative. (Earlier Go versions are not using a +// monotonic clock.) Note that partitioning of Histograms is expensive and +// should be used judiciously. +// +// For hook functions that receive an error as an argument, no observations are +// made in the event of a non-nil error value. +// +// See the example for ExampleInstrumentRoundTripperDuration for example usage. +func InstrumentRoundTripperTrace(it *InstrumentTrace, next http.RoundTripper) RoundTripperFunc { + return RoundTripperFunc(func(r *http.Request) (*http.Response, error) { + start := time.Now() + + trace := &httptrace.ClientTrace{ + GotConn: func(_ httptrace.GotConnInfo) { + if it.GotConn != nil { + it.GotConn(time.Since(start).Seconds()) + } + }, + PutIdleConn: func(err error) { + if err != nil { + return + } + if it.PutIdleConn != nil { + it.PutIdleConn(time.Since(start).Seconds()) + } + }, + DNSStart: func(_ httptrace.DNSStartInfo) { + if it.DNSStart != nil { + it.DNSStart(time.Since(start).Seconds()) + } + }, + DNSDone: func(_ httptrace.DNSDoneInfo) { + if it.DNSDone != nil { + it.DNSDone(time.Since(start).Seconds()) + } + }, + ConnectStart: func(_, _ string) { + if it.ConnectStart != nil { + it.ConnectStart(time.Since(start).Seconds()) + } + }, + ConnectDone: func(_, _ string, err error) { + if err != nil { + return + } + if it.ConnectDone != nil { + it.ConnectDone(time.Since(start).Seconds()) + } + }, + GotFirstResponseByte: func() { + if it.GotFirstResponseByte != nil { + it.GotFirstResponseByte(time.Since(start).Seconds()) + } + }, + Got100Continue: func() { + if it.Got100Continue != nil { + it.Got100Continue(time.Since(start).Seconds()) + } + }, + TLSHandshakeStart: func() { + if it.TLSHandshakeStart != nil { + it.TLSHandshakeStart(time.Since(start).Seconds()) + } + }, + TLSHandshakeDone: func(_ tls.ConnectionState, err error) { + if err != nil { + return + } + if it.TLSHandshakeDone != nil { + it.TLSHandshakeDone(time.Since(start).Seconds()) + } + }, + WroteHeaders: func() { + if it.WroteHeaders != nil { + it.WroteHeaders(time.Since(start).Seconds()) + } + }, + Wait100Continue: func() { + if it.Wait100Continue != nil { + it.Wait100Continue(time.Since(start).Seconds()) + } + }, + WroteRequest: func(_ httptrace.WroteRequestInfo) { + if it.WroteRequest != nil { + it.WroteRequest(time.Since(start).Seconds()) + } + }, + } + r = r.WithContext(httptrace.WithClientTrace(context.Background(), trace)) + + return next.RoundTrip(r) + }) +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go new file mode 100644 index 000000000..9db243805 --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go @@ -0,0 +1,447 @@ +// Copyright 2017 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package promhttp + +import ( + "errors" + "net/http" + "strconv" + "strings" + "time" + + dto "github.com/prometheus/client_model/go" + + "github.com/prometheus/client_golang/prometheus" +) + +// magicString is used for the hacky label test in checkLabels. Remove once fixed. +const magicString = "zZgWfBxLqvG8kc8IMv3POi2Bb0tZI3vAnBx+gBaFi9FyPzB/CzKUer1yufDa" + +// InstrumentHandlerInFlight is a middleware that wraps the provided +// http.Handler. It sets the provided prometheus.Gauge to the number of +// requests currently handled by the wrapped http.Handler. +// +// See the example for InstrumentHandlerDuration for example usage. +func InstrumentHandlerInFlight(g prometheus.Gauge, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + g.Inc() + defer g.Dec() + next.ServeHTTP(w, r) + }) +} + +// InstrumentHandlerDuration is a middleware that wraps the provided +// http.Handler to observe the request duration with the provided ObserverVec. +// The ObserverVec must have zero, one, or two non-const non-curried labels. For +// those, the only allowed label names are "code" and "method". The function +// panics otherwise. The Observe method of the Observer in the ObserverVec is +// called with the request duration in seconds. Partitioning happens by HTTP +// status code and/or HTTP method if the respective instance label names are +// present in the ObserverVec. For unpartitioned observations, use an +// ObserverVec with zero labels. Note that partitioning of Histograms is +// expensive and should be used judiciously. +// +// If the wrapped Handler does not set a status code, a status code of 200 is assumed. +// +// If the wrapped Handler panics, no values are reported. +// +// Note that this method is only guaranteed to never observe negative durations +// if used with Go1.9+. +func InstrumentHandlerDuration(obs prometheus.ObserverVec, next http.Handler) http.HandlerFunc { + code, method := checkLabels(obs) + + if code { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + now := time.Now() + d := newDelegator(w, nil) + next.ServeHTTP(d, r) + + obs.With(labels(code, method, r.Method, d.Status())).Observe(time.Since(now).Seconds()) + }) + } + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + now := time.Now() + next.ServeHTTP(w, r) + obs.With(labels(code, method, r.Method, 0)).Observe(time.Since(now).Seconds()) + }) +} + +// InstrumentHandlerCounter is a middleware that wraps the provided http.Handler +// to observe the request result with the provided CounterVec. The CounterVec +// must have zero, one, or two non-const non-curried labels. For those, the only +// allowed label names are "code" and "method". The function panics +// otherwise. Partitioning of the CounterVec happens by HTTP status code and/or +// HTTP method if the respective instance label names are present in the +// CounterVec. For unpartitioned counting, use a CounterVec with zero labels. +// +// If the wrapped Handler does not set a status code, a status code of 200 is assumed. +// +// If the wrapped Handler panics, the Counter is not incremented. +// +// See the example for InstrumentHandlerDuration for example usage. +func InstrumentHandlerCounter(counter *prometheus.CounterVec, next http.Handler) http.HandlerFunc { + code, method := checkLabels(counter) + + if code { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + d := newDelegator(w, nil) + next.ServeHTTP(d, r) + counter.With(labels(code, method, r.Method, d.Status())).Inc() + }) + } + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + next.ServeHTTP(w, r) + counter.With(labels(code, method, r.Method, 0)).Inc() + }) +} + +// InstrumentHandlerTimeToWriteHeader is a middleware that wraps the provided +// http.Handler to observe with the provided ObserverVec the request duration +// until the response headers are written. The ObserverVec must have zero, one, +// or two non-const non-curried labels. For those, the only allowed label names +// are "code" and "method". The function panics otherwise. The Observe method of +// the Observer in the ObserverVec is called with the request duration in +// seconds. Partitioning happens by HTTP status code and/or HTTP method if the +// respective instance label names are present in the ObserverVec. For +// unpartitioned observations, use an ObserverVec with zero labels. Note that +// partitioning of Histograms is expensive and should be used judiciously. +// +// If the wrapped Handler panics before calling WriteHeader, no value is +// reported. +// +// Note that this method is only guaranteed to never observe negative durations +// if used with Go1.9+. +// +// See the example for InstrumentHandlerDuration for example usage. +func InstrumentHandlerTimeToWriteHeader(obs prometheus.ObserverVec, next http.Handler) http.HandlerFunc { + code, method := checkLabels(obs) + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + now := time.Now() + d := newDelegator(w, func(status int) { + obs.With(labels(code, method, r.Method, status)).Observe(time.Since(now).Seconds()) + }) + next.ServeHTTP(d, r) + }) +} + +// InstrumentHandlerRequestSize is a middleware that wraps the provided +// http.Handler to observe the request size with the provided ObserverVec. The +// ObserverVec must have zero, one, or two non-const non-curried labels. For +// those, the only allowed label names are "code" and "method". The function +// panics otherwise. The Observe method of the Observer in the ObserverVec is +// called with the request size in bytes. Partitioning happens by HTTP status +// code and/or HTTP method if the respective instance label names are present in +// the ObserverVec. For unpartitioned observations, use an ObserverVec with zero +// labels. Note that partitioning of Histograms is expensive and should be used +// judiciously. +// +// If the wrapped Handler does not set a status code, a status code of 200 is assumed. +// +// If the wrapped Handler panics, no values are reported. +// +// See the example for InstrumentHandlerDuration for example usage. +func InstrumentHandlerRequestSize(obs prometheus.ObserverVec, next http.Handler) http.HandlerFunc { + code, method := checkLabels(obs) + + if code { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + d := newDelegator(w, nil) + next.ServeHTTP(d, r) + size := computeApproximateRequestSize(r) + obs.With(labels(code, method, r.Method, d.Status())).Observe(float64(size)) + }) + } + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + next.ServeHTTP(w, r) + size := computeApproximateRequestSize(r) + obs.With(labels(code, method, r.Method, 0)).Observe(float64(size)) + }) +} + +// InstrumentHandlerResponseSize is a middleware that wraps the provided +// http.Handler to observe the response size with the provided ObserverVec. The +// ObserverVec must have zero, one, or two non-const non-curried labels. For +// those, the only allowed label names are "code" and "method". The function +// panics otherwise. The Observe method of the Observer in the ObserverVec is +// called with the response size in bytes. Partitioning happens by HTTP status +// code and/or HTTP method if the respective instance label names are present in +// the ObserverVec. For unpartitioned observations, use an ObserverVec with zero +// labels. Note that partitioning of Histograms is expensive and should be used +// judiciously. +// +// If the wrapped Handler does not set a status code, a status code of 200 is assumed. +// +// If the wrapped Handler panics, no values are reported. +// +// See the example for InstrumentHandlerDuration for example usage. +func InstrumentHandlerResponseSize(obs prometheus.ObserverVec, next http.Handler) http.Handler { + code, method := checkLabels(obs) + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + d := newDelegator(w, nil) + next.ServeHTTP(d, r) + obs.With(labels(code, method, r.Method, d.Status())).Observe(float64(d.Written())) + }) +} + +func checkLabels(c prometheus.Collector) (code bool, method bool) { + // TODO(beorn7): Remove this hacky way to check for instance labels + // once Descriptors can have their dimensionality queried. + var ( + desc *prometheus.Desc + m prometheus.Metric + pm dto.Metric + lvs []string + ) + + // Get the Desc from the Collector. + descc := make(chan *prometheus.Desc, 1) + c.Describe(descc) + + select { + case desc = <-descc: + default: + panic("no description provided by collector") + } + select { + case <-descc: + panic("more than one description provided by collector") + default: + } + + close(descc) + + // Create a ConstMetric with the Desc. Since we don't know how many + // variable labels there are, try for as long as it needs. + for err := errors.New("dummy"); err != nil; lvs = append(lvs, magicString) { + m, err = prometheus.NewConstMetric(desc, prometheus.UntypedValue, 0, lvs...) + } + + // Write out the metric into a proto message and look at the labels. + // If the value is not the magicString, it is a constLabel, which doesn't interest us. + // If the label is curried, it doesn't interest us. + // In all other cases, only "code" or "method" is allowed. + if err := m.Write(&pm); err != nil { + panic("error checking metric for labels") + } + for _, label := range pm.Label { + name, value := label.GetName(), label.GetValue() + if value != magicString || isLabelCurried(c, name) { + continue + } + switch name { + case "code": + code = true + case "method": + method = true + default: + panic("metric partitioned with non-supported labels") + } + } + return +} + +func isLabelCurried(c prometheus.Collector, label string) bool { + // This is even hackier than the label test above. + // We essentially try to curry again and see if it works. + // But for that, we need to type-convert to the two + // types we use here, ObserverVec or *CounterVec. + switch v := c.(type) { + case *prometheus.CounterVec: + if _, err := v.CurryWith(prometheus.Labels{label: "dummy"}); err == nil { + return false + } + case prometheus.ObserverVec: + if _, err := v.CurryWith(prometheus.Labels{label: "dummy"}); err == nil { + return false + } + default: + panic("unsupported metric vec type") + } + return true +} + +// emptyLabels is a one-time allocation for non-partitioned metrics to avoid +// unnecessary allocations on each request. +var emptyLabels = prometheus.Labels{} + +func labels(code, method bool, reqMethod string, status int) prometheus.Labels { + if !(code || method) { + return emptyLabels + } + labels := prometheus.Labels{} + + if code { + labels["code"] = sanitizeCode(status) + } + if method { + labels["method"] = sanitizeMethod(reqMethod) + } + + return labels +} + +func computeApproximateRequestSize(r *http.Request) int { + s := 0 + if r.URL != nil { + s += len(r.URL.String()) + } + + s += len(r.Method) + s += len(r.Proto) + for name, values := range r.Header { + s += len(name) + for _, value := range values { + s += len(value) + } + } + s += len(r.Host) + + // N.B. r.Form and r.MultipartForm are assumed to be included in r.URL. + + if r.ContentLength != -1 { + s += int(r.ContentLength) + } + return s +} + +func sanitizeMethod(m string) string { + switch m { + case "GET", "get": + return "get" + case "PUT", "put": + return "put" + case "HEAD", "head": + return "head" + case "POST", "post": + return "post" + case "DELETE", "delete": + return "delete" + case "CONNECT", "connect": + return "connect" + case "OPTIONS", "options": + return "options" + case "NOTIFY", "notify": + return "notify" + default: + return strings.ToLower(m) + } +} + +// If the wrapped http.Handler has not set a status code, i.e. the value is +// currently 0, santizeCode will return 200, for consistency with behavior in +// the stdlib. +func sanitizeCode(s int) string { + switch s { + case 100: + return "100" + case 101: + return "101" + + case 200, 0: + return "200" + case 201: + return "201" + case 202: + return "202" + case 203: + return "203" + case 204: + return "204" + case 205: + return "205" + case 206: + return "206" + + case 300: + return "300" + case 301: + return "301" + case 302: + return "302" + case 304: + return "304" + case 305: + return "305" + case 307: + return "307" + + case 400: + return "400" + case 401: + return "401" + case 402: + return "402" + case 403: + return "403" + case 404: + return "404" + case 405: + return "405" + case 406: + return "406" + case 407: + return "407" + case 408: + return "408" + case 409: + return "409" + case 410: + return "410" + case 411: + return "411" + case 412: + return "412" + case 413: + return "413" + case 414: + return "414" + case 415: + return "415" + case 416: + return "416" + case 417: + return "417" + case 418: + return "418" + + case 500: + return "500" + case 501: + return "501" + case 502: + return "502" + case 503: + return "503" + case 504: + return "504" + case 505: + return "505" + + case 428: + return "428" + case 429: + return "429" + case 431: + return "431" + case 511: + return "511" + + default: + return strconv.Itoa(s) + } +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/registry.go b/vendor/github.com/prometheus/client_golang/prometheus/registry.go index fdb7badf7..5c5cdfe2a 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/registry.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/registry.go @@ -15,7 +15,6 @@ package prometheus import ( "bytes" - "errors" "fmt" "os" "runtime" @@ -68,7 +67,8 @@ func NewRegistry() *Registry { // NewPedanticRegistry returns a registry that checks during collection if each // collected Metric is consistent with its reported Desc, and if the Desc has -// actually been registered with the registry. +// actually been registered with the registry. Unchecked Collectors (those whose +// Describe methed does not yield any descriptors) are excluded from the check. // // Usually, a Registry will be happy as long as the union of all collected // Metrics is consistent and valid even if some metrics are not consistent with @@ -98,6 +98,14 @@ type Registerer interface { // returned error is an instance of AlreadyRegisteredError, which // contains the previously registered Collector. // + // A Collector whose Describe method does not yield any Desc is treated + // as unchecked. Registration will always succeed. No check for + // re-registering (see previous paragraph) is performed. Thus, the + // caller is responsible for not double-registering the same unchecked + // Collector, and for providing a Collector that will not cause + // inconsistent metrics on collection. (This would lead to scrape + // errors.) + // // It is in general not safe to register the same Collector multiple // times concurrently. Register(Collector) error @@ -108,7 +116,9 @@ type Registerer interface { // Unregister unregisters the Collector that equals the Collector passed // in as an argument. (Two Collectors are considered equal if their // Describe method yields the same set of descriptors.) The function - // returns whether a Collector was unregistered. + // returns whether a Collector was unregistered. Note that an unchecked + // Collector cannot be unregistered (as its Describe method does not + // yield any descriptor). // // Note that even after unregistering, it will not be possible to // register a new Collector that is inconsistent with the unregistered @@ -243,6 +253,7 @@ type Registry struct { collectorsByID map[uint64]Collector // ID is a hash of the descIDs. descIDs map[uint64]struct{} dimHashesByName map[string]uint64 + uncheckedCollectors []Collector pedanticChecksEnabled bool } @@ -300,9 +311,10 @@ func (r *Registry) Register(c Collector) error { } } } - // Did anything happen at all? + // A Collector yielding no Desc at all is considered unchecked. if len(newDescIDs) == 0 { - return errors.New("collector has no descriptors") + r.uncheckedCollectors = append(r.uncheckedCollectors, c) + return nil } if existing, exists := r.collectorsByID[collectorID]; exists { return AlreadyRegisteredError{ @@ -376,19 +388,24 @@ func (r *Registry) MustRegister(cs ...Collector) { // Gather implements Gatherer. func (r *Registry) Gather() ([]*dto.MetricFamily, error) { var ( - metricChan = make(chan Metric, capMetricChan) - metricHashes = map[uint64]struct{}{} - wg sync.WaitGroup - errs MultiError // The collected errors to return in the end. - registeredDescIDs map[uint64]struct{} // Only used for pedantic checks + checkedMetricChan = make(chan Metric, capMetricChan) + uncheckedMetricChan = make(chan Metric, capMetricChan) + metricHashes = map[uint64]struct{}{} + wg sync.WaitGroup + errs MultiError // The collected errors to return in the end. + registeredDescIDs map[uint64]struct{} // Only used for pedantic checks ) r.mtx.RLock() - goroutineBudget := len(r.collectorsByID) + goroutineBudget := len(r.collectorsByID) + len(r.uncheckedCollectors) metricFamiliesByName := make(map[string]*dto.MetricFamily, len(r.dimHashesByName)) - collectors := make(chan Collector, len(r.collectorsByID)) + checkedCollectors := make(chan Collector, len(r.collectorsByID)) + uncheckedCollectors := make(chan Collector, len(r.uncheckedCollectors)) for _, collector := range r.collectorsByID { - collectors <- collector + checkedCollectors <- collector + } + for _, collector := range r.uncheckedCollectors { + uncheckedCollectors <- collector } // In case pedantic checks are enabled, we have to copy the map before // giving up the RLock. @@ -405,12 +422,14 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) { collectWorker := func() { for { select { - case collector := <-collectors: - collector.Collect(metricChan) - wg.Done() + case collector := <-checkedCollectors: + collector.Collect(checkedMetricChan) + case collector := <-uncheckedCollectors: + collector.Collect(uncheckedMetricChan) default: return } + wg.Done() } } @@ -418,51 +437,94 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) { go collectWorker() goroutineBudget-- - // Close the metricChan once all collectors are collected. + // Close checkedMetricChan and uncheckedMetricChan once all collectors + // are collected. go func() { wg.Wait() - close(metricChan) + close(checkedMetricChan) + close(uncheckedMetricChan) }() - // Drain metricChan in case of premature return. + // Drain checkedMetricChan and uncheckedMetricChan in case of premature return. defer func() { - for range metricChan { + if checkedMetricChan != nil { + for range checkedMetricChan { + } + } + if uncheckedMetricChan != nil { + for range uncheckedMetricChan { + } } }() -collectLoop: + // Copy the channel references so we can nil them out later to remove + // them from the select statements below. + cmc := checkedMetricChan + umc := uncheckedMetricChan + for { select { - case metric, ok := <-metricChan: + case metric, ok := <-cmc: if !ok { - // metricChan is closed, we are done. - break collectLoop + cmc = nil + break } errs.Append(processMetric( metric, metricFamiliesByName, metricHashes, registeredDescIDs, )) + case metric, ok := <-umc: + if !ok { + umc = nil + break + } + errs.Append(processMetric( + metric, metricFamiliesByName, + metricHashes, + nil, + )) default: - if goroutineBudget <= 0 || len(collectors) == 0 { + if goroutineBudget <= 0 || len(checkedCollectors)+len(uncheckedCollectors) == 0 { // All collectors are already being worked on or // we have already as many goroutines started as - // there are collectors. Just process metrics - // from now on. - for metric := range metricChan { + // there are collectors. Do the same as above, + // just without the default. + select { + case metric, ok := <-cmc: + if !ok { + cmc = nil + break + } errs.Append(processMetric( metric, metricFamiliesByName, metricHashes, registeredDescIDs, )) + case metric, ok := <-umc: + if !ok { + umc = nil + break + } + errs.Append(processMetric( + metric, metricFamiliesByName, + metricHashes, + nil, + )) } - break collectLoop + break } // Start more workers. go collectWorker() goroutineBudget-- runtime.Gosched() } + // Once both checkedMetricChan and uncheckdMetricChan are closed + // and drained, the contraption above will nil out cmc and umc, + // and then we can leave the collect loop here. + if cmc == nil && umc == nil { + break + } } return normalizeMetricFamilies(metricFamiliesByName), errs.MaybeUnwrap() } diff --git a/vendor/github.com/prometheus/client_model/go/metrics.pb.go b/vendor/github.com/prometheus/client_model/go/metrics.pb.go index b065f8683..9805432c2 100644 --- a/vendor/github.com/prometheus/client_model/go/metrics.pb.go +++ b/vendor/github.com/prometheus/client_model/go/metrics.pb.go @@ -1,34 +1,23 @@ -// Code generated by protoc-gen-go. +// Code generated by protoc-gen-go. DO NOT EDIT. // source: metrics.proto -// DO NOT EDIT! - -/* -Package io_prometheus_client is a generated protocol buffer package. - -It is generated from these files: - metrics.proto - -It has these top-level messages: - LabelPair - Gauge - Counter - Quantile - Summary - Untyped - Histogram - Bucket - Metric - MetricFamily -*/ -package io_prometheus_client + +package io_prometheus_client // import "github.com/prometheus/client_model/go" import proto "github.com/golang/protobuf/proto" +import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal +var _ = fmt.Errorf var _ = math.Inf +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package + type MetricType int32 const ( @@ -70,16 +59,41 @@ func (x *MetricType) UnmarshalJSON(data []byte) error { *x = MetricType(value) return nil } +func (MetricType) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_metrics_c97c9a2b9560cb8f, []int{0} +} type LabelPair struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Value *string `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"` - XXX_unrecognized []byte `json:"-"` + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Value *string `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *LabelPair) Reset() { *m = LabelPair{} } func (m *LabelPair) String() string { return proto.CompactTextString(m) } func (*LabelPair) ProtoMessage() {} +func (*LabelPair) Descriptor() ([]byte, []int) { + return fileDescriptor_metrics_c97c9a2b9560cb8f, []int{0} +} +func (m *LabelPair) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_LabelPair.Unmarshal(m, b) +} +func (m *LabelPair) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_LabelPair.Marshal(b, m, deterministic) +} +func (dst *LabelPair) XXX_Merge(src proto.Message) { + xxx_messageInfo_LabelPair.Merge(dst, src) +} +func (m *LabelPair) XXX_Size() int { + return xxx_messageInfo_LabelPair.Size(m) +} +func (m *LabelPair) XXX_DiscardUnknown() { + xxx_messageInfo_LabelPair.DiscardUnknown(m) +} + +var xxx_messageInfo_LabelPair proto.InternalMessageInfo func (m *LabelPair) GetName() string { if m != nil && m.Name != nil { @@ -96,13 +110,35 @@ func (m *LabelPair) GetValue() string { } type Gauge struct { - Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"` - XXX_unrecognized []byte `json:"-"` + Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *Gauge) Reset() { *m = Gauge{} } func (m *Gauge) String() string { return proto.CompactTextString(m) } func (*Gauge) ProtoMessage() {} +func (*Gauge) Descriptor() ([]byte, []int) { + return fileDescriptor_metrics_c97c9a2b9560cb8f, []int{1} +} +func (m *Gauge) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Gauge.Unmarshal(m, b) +} +func (m *Gauge) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Gauge.Marshal(b, m, deterministic) +} +func (dst *Gauge) XXX_Merge(src proto.Message) { + xxx_messageInfo_Gauge.Merge(dst, src) +} +func (m *Gauge) XXX_Size() int { + return xxx_messageInfo_Gauge.Size(m) +} +func (m *Gauge) XXX_DiscardUnknown() { + xxx_messageInfo_Gauge.DiscardUnknown(m) +} + +var xxx_messageInfo_Gauge proto.InternalMessageInfo func (m *Gauge) GetValue() float64 { if m != nil && m.Value != nil { @@ -112,13 +148,35 @@ func (m *Gauge) GetValue() float64 { } type Counter struct { - Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"` - XXX_unrecognized []byte `json:"-"` + Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *Counter) Reset() { *m = Counter{} } func (m *Counter) String() string { return proto.CompactTextString(m) } func (*Counter) ProtoMessage() {} +func (*Counter) Descriptor() ([]byte, []int) { + return fileDescriptor_metrics_c97c9a2b9560cb8f, []int{2} +} +func (m *Counter) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Counter.Unmarshal(m, b) +} +func (m *Counter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Counter.Marshal(b, m, deterministic) +} +func (dst *Counter) XXX_Merge(src proto.Message) { + xxx_messageInfo_Counter.Merge(dst, src) +} +func (m *Counter) XXX_Size() int { + return xxx_messageInfo_Counter.Size(m) +} +func (m *Counter) XXX_DiscardUnknown() { + xxx_messageInfo_Counter.DiscardUnknown(m) +} + +var xxx_messageInfo_Counter proto.InternalMessageInfo func (m *Counter) GetValue() float64 { if m != nil && m.Value != nil { @@ -128,14 +186,36 @@ func (m *Counter) GetValue() float64 { } type Quantile struct { - Quantile *float64 `protobuf:"fixed64,1,opt,name=quantile" json:"quantile,omitempty"` - Value *float64 `protobuf:"fixed64,2,opt,name=value" json:"value,omitempty"` - XXX_unrecognized []byte `json:"-"` + Quantile *float64 `protobuf:"fixed64,1,opt,name=quantile" json:"quantile,omitempty"` + Value *float64 `protobuf:"fixed64,2,opt,name=value" json:"value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *Quantile) Reset() { *m = Quantile{} } func (m *Quantile) String() string { return proto.CompactTextString(m) } func (*Quantile) ProtoMessage() {} +func (*Quantile) Descriptor() ([]byte, []int) { + return fileDescriptor_metrics_c97c9a2b9560cb8f, []int{3} +} +func (m *Quantile) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Quantile.Unmarshal(m, b) +} +func (m *Quantile) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Quantile.Marshal(b, m, deterministic) +} +func (dst *Quantile) XXX_Merge(src proto.Message) { + xxx_messageInfo_Quantile.Merge(dst, src) +} +func (m *Quantile) XXX_Size() int { + return xxx_messageInfo_Quantile.Size(m) +} +func (m *Quantile) XXX_DiscardUnknown() { + xxx_messageInfo_Quantile.DiscardUnknown(m) +} + +var xxx_messageInfo_Quantile proto.InternalMessageInfo func (m *Quantile) GetQuantile() float64 { if m != nil && m.Quantile != nil { @@ -152,15 +232,37 @@ func (m *Quantile) GetValue() float64 { } type Summary struct { - SampleCount *uint64 `protobuf:"varint,1,opt,name=sample_count" json:"sample_count,omitempty"` - SampleSum *float64 `protobuf:"fixed64,2,opt,name=sample_sum" json:"sample_sum,omitempty"` - Quantile []*Quantile `protobuf:"bytes,3,rep,name=quantile" json:"quantile,omitempty"` - XXX_unrecognized []byte `json:"-"` + SampleCount *uint64 `protobuf:"varint,1,opt,name=sample_count,json=sampleCount" json:"sample_count,omitempty"` + SampleSum *float64 `protobuf:"fixed64,2,opt,name=sample_sum,json=sampleSum" json:"sample_sum,omitempty"` + Quantile []*Quantile `protobuf:"bytes,3,rep,name=quantile" json:"quantile,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *Summary) Reset() { *m = Summary{} } func (m *Summary) String() string { return proto.CompactTextString(m) } func (*Summary) ProtoMessage() {} +func (*Summary) Descriptor() ([]byte, []int) { + return fileDescriptor_metrics_c97c9a2b9560cb8f, []int{4} +} +func (m *Summary) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Summary.Unmarshal(m, b) +} +func (m *Summary) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Summary.Marshal(b, m, deterministic) +} +func (dst *Summary) XXX_Merge(src proto.Message) { + xxx_messageInfo_Summary.Merge(dst, src) +} +func (m *Summary) XXX_Size() int { + return xxx_messageInfo_Summary.Size(m) +} +func (m *Summary) XXX_DiscardUnknown() { + xxx_messageInfo_Summary.DiscardUnknown(m) +} + +var xxx_messageInfo_Summary proto.InternalMessageInfo func (m *Summary) GetSampleCount() uint64 { if m != nil && m.SampleCount != nil { @@ -184,13 +286,35 @@ func (m *Summary) GetQuantile() []*Quantile { } type Untyped struct { - Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"` - XXX_unrecognized []byte `json:"-"` + Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *Untyped) Reset() { *m = Untyped{} } func (m *Untyped) String() string { return proto.CompactTextString(m) } func (*Untyped) ProtoMessage() {} +func (*Untyped) Descriptor() ([]byte, []int) { + return fileDescriptor_metrics_c97c9a2b9560cb8f, []int{5} +} +func (m *Untyped) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Untyped.Unmarshal(m, b) +} +func (m *Untyped) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Untyped.Marshal(b, m, deterministic) +} +func (dst *Untyped) XXX_Merge(src proto.Message) { + xxx_messageInfo_Untyped.Merge(dst, src) +} +func (m *Untyped) XXX_Size() int { + return xxx_messageInfo_Untyped.Size(m) +} +func (m *Untyped) XXX_DiscardUnknown() { + xxx_messageInfo_Untyped.DiscardUnknown(m) +} + +var xxx_messageInfo_Untyped proto.InternalMessageInfo func (m *Untyped) GetValue() float64 { if m != nil && m.Value != nil { @@ -200,15 +324,37 @@ func (m *Untyped) GetValue() float64 { } type Histogram struct { - SampleCount *uint64 `protobuf:"varint,1,opt,name=sample_count" json:"sample_count,omitempty"` - SampleSum *float64 `protobuf:"fixed64,2,opt,name=sample_sum" json:"sample_sum,omitempty"` - Bucket []*Bucket `protobuf:"bytes,3,rep,name=bucket" json:"bucket,omitempty"` - XXX_unrecognized []byte `json:"-"` + SampleCount *uint64 `protobuf:"varint,1,opt,name=sample_count,json=sampleCount" json:"sample_count,omitempty"` + SampleSum *float64 `protobuf:"fixed64,2,opt,name=sample_sum,json=sampleSum" json:"sample_sum,omitempty"` + Bucket []*Bucket `protobuf:"bytes,3,rep,name=bucket" json:"bucket,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *Histogram) Reset() { *m = Histogram{} } func (m *Histogram) String() string { return proto.CompactTextString(m) } func (*Histogram) ProtoMessage() {} +func (*Histogram) Descriptor() ([]byte, []int) { + return fileDescriptor_metrics_c97c9a2b9560cb8f, []int{6} +} +func (m *Histogram) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Histogram.Unmarshal(m, b) +} +func (m *Histogram) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Histogram.Marshal(b, m, deterministic) +} +func (dst *Histogram) XXX_Merge(src proto.Message) { + xxx_messageInfo_Histogram.Merge(dst, src) +} +func (m *Histogram) XXX_Size() int { + return xxx_messageInfo_Histogram.Size(m) +} +func (m *Histogram) XXX_DiscardUnknown() { + xxx_messageInfo_Histogram.DiscardUnknown(m) +} + +var xxx_messageInfo_Histogram proto.InternalMessageInfo func (m *Histogram) GetSampleCount() uint64 { if m != nil && m.SampleCount != nil { @@ -232,14 +378,36 @@ func (m *Histogram) GetBucket() []*Bucket { } type Bucket struct { - CumulativeCount *uint64 `protobuf:"varint,1,opt,name=cumulative_count" json:"cumulative_count,omitempty"` - UpperBound *float64 `protobuf:"fixed64,2,opt,name=upper_bound" json:"upper_bound,omitempty"` - XXX_unrecognized []byte `json:"-"` + CumulativeCount *uint64 `protobuf:"varint,1,opt,name=cumulative_count,json=cumulativeCount" json:"cumulative_count,omitempty"` + UpperBound *float64 `protobuf:"fixed64,2,opt,name=upper_bound,json=upperBound" json:"upper_bound,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *Bucket) Reset() { *m = Bucket{} } func (m *Bucket) String() string { return proto.CompactTextString(m) } func (*Bucket) ProtoMessage() {} +func (*Bucket) Descriptor() ([]byte, []int) { + return fileDescriptor_metrics_c97c9a2b9560cb8f, []int{7} +} +func (m *Bucket) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Bucket.Unmarshal(m, b) +} +func (m *Bucket) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Bucket.Marshal(b, m, deterministic) +} +func (dst *Bucket) XXX_Merge(src proto.Message) { + xxx_messageInfo_Bucket.Merge(dst, src) +} +func (m *Bucket) XXX_Size() int { + return xxx_messageInfo_Bucket.Size(m) +} +func (m *Bucket) XXX_DiscardUnknown() { + xxx_messageInfo_Bucket.DiscardUnknown(m) +} + +var xxx_messageInfo_Bucket proto.InternalMessageInfo func (m *Bucket) GetCumulativeCount() uint64 { if m != nil && m.CumulativeCount != nil { @@ -256,19 +424,41 @@ func (m *Bucket) GetUpperBound() float64 { } type Metric struct { - Label []*LabelPair `protobuf:"bytes,1,rep,name=label" json:"label,omitempty"` - Gauge *Gauge `protobuf:"bytes,2,opt,name=gauge" json:"gauge,omitempty"` - Counter *Counter `protobuf:"bytes,3,opt,name=counter" json:"counter,omitempty"` - Summary *Summary `protobuf:"bytes,4,opt,name=summary" json:"summary,omitempty"` - Untyped *Untyped `protobuf:"bytes,5,opt,name=untyped" json:"untyped,omitempty"` - Histogram *Histogram `protobuf:"bytes,7,opt,name=histogram" json:"histogram,omitempty"` - TimestampMs *int64 `protobuf:"varint,6,opt,name=timestamp_ms" json:"timestamp_ms,omitempty"` - XXX_unrecognized []byte `json:"-"` + Label []*LabelPair `protobuf:"bytes,1,rep,name=label" json:"label,omitempty"` + Gauge *Gauge `protobuf:"bytes,2,opt,name=gauge" json:"gauge,omitempty"` + Counter *Counter `protobuf:"bytes,3,opt,name=counter" json:"counter,omitempty"` + Summary *Summary `protobuf:"bytes,4,opt,name=summary" json:"summary,omitempty"` + Untyped *Untyped `protobuf:"bytes,5,opt,name=untyped" json:"untyped,omitempty"` + Histogram *Histogram `protobuf:"bytes,7,opt,name=histogram" json:"histogram,omitempty"` + TimestampMs *int64 `protobuf:"varint,6,opt,name=timestamp_ms,json=timestampMs" json:"timestamp_ms,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *Metric) Reset() { *m = Metric{} } func (m *Metric) String() string { return proto.CompactTextString(m) } func (*Metric) ProtoMessage() {} +func (*Metric) Descriptor() ([]byte, []int) { + return fileDescriptor_metrics_c97c9a2b9560cb8f, []int{8} +} +func (m *Metric) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Metric.Unmarshal(m, b) +} +func (m *Metric) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Metric.Marshal(b, m, deterministic) +} +func (dst *Metric) XXX_Merge(src proto.Message) { + xxx_messageInfo_Metric.Merge(dst, src) +} +func (m *Metric) XXX_Size() int { + return xxx_messageInfo_Metric.Size(m) +} +func (m *Metric) XXX_DiscardUnknown() { + xxx_messageInfo_Metric.DiscardUnknown(m) +} + +var xxx_messageInfo_Metric proto.InternalMessageInfo func (m *Metric) GetLabel() []*LabelPair { if m != nil { @@ -320,16 +510,38 @@ func (m *Metric) GetTimestampMs() int64 { } type MetricFamily struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Help *string `protobuf:"bytes,2,opt,name=help" json:"help,omitempty"` - Type *MetricType `protobuf:"varint,3,opt,name=type,enum=io.prometheus.client.MetricType" json:"type,omitempty"` - Metric []*Metric `protobuf:"bytes,4,rep,name=metric" json:"metric,omitempty"` - XXX_unrecognized []byte `json:"-"` + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Help *string `protobuf:"bytes,2,opt,name=help" json:"help,omitempty"` + Type *MetricType `protobuf:"varint,3,opt,name=type,enum=io.prometheus.client.MetricType" json:"type,omitempty"` + Metric []*Metric `protobuf:"bytes,4,rep,name=metric" json:"metric,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *MetricFamily) Reset() { *m = MetricFamily{} } func (m *MetricFamily) String() string { return proto.CompactTextString(m) } func (*MetricFamily) ProtoMessage() {} +func (*MetricFamily) Descriptor() ([]byte, []int) { + return fileDescriptor_metrics_c97c9a2b9560cb8f, []int{9} +} +func (m *MetricFamily) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_MetricFamily.Unmarshal(m, b) +} +func (m *MetricFamily) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_MetricFamily.Marshal(b, m, deterministic) +} +func (dst *MetricFamily) XXX_Merge(src proto.Message) { + xxx_messageInfo_MetricFamily.Merge(dst, src) +} +func (m *MetricFamily) XXX_Size() int { + return xxx_messageInfo_MetricFamily.Size(m) +} +func (m *MetricFamily) XXX_DiscardUnknown() { + xxx_messageInfo_MetricFamily.DiscardUnknown(m) +} + +var xxx_messageInfo_MetricFamily proto.InternalMessageInfo func (m *MetricFamily) GetName() string { if m != nil && m.Name != nil { @@ -360,5 +572,58 @@ func (m *MetricFamily) GetMetric() []*Metric { } func init() { + proto.RegisterType((*LabelPair)(nil), "io.prometheus.client.LabelPair") + proto.RegisterType((*Gauge)(nil), "io.prometheus.client.Gauge") + proto.RegisterType((*Counter)(nil), "io.prometheus.client.Counter") + proto.RegisterType((*Quantile)(nil), "io.prometheus.client.Quantile") + proto.RegisterType((*Summary)(nil), "io.prometheus.client.Summary") + proto.RegisterType((*Untyped)(nil), "io.prometheus.client.Untyped") + proto.RegisterType((*Histogram)(nil), "io.prometheus.client.Histogram") + proto.RegisterType((*Bucket)(nil), "io.prometheus.client.Bucket") + proto.RegisterType((*Metric)(nil), "io.prometheus.client.Metric") + proto.RegisterType((*MetricFamily)(nil), "io.prometheus.client.MetricFamily") proto.RegisterEnum("io.prometheus.client.MetricType", MetricType_name, MetricType_value) } + +func init() { proto.RegisterFile("metrics.proto", fileDescriptor_metrics_c97c9a2b9560cb8f) } + +var fileDescriptor_metrics_c97c9a2b9560cb8f = []byte{ + // 591 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x54, 0x4f, 0x4f, 0xdb, 0x4e, + 0x14, 0xfc, 0x99, 0xd8, 0x09, 0x7e, 0x86, 0x5f, 0xad, 0x15, 0x07, 0xab, 0x2d, 0x25, 0xcd, 0x89, + 0xf6, 0x10, 0x54, 0x04, 0xaa, 0x44, 0xdb, 0x03, 0x50, 0x1a, 0x2a, 0xd5, 0x40, 0x37, 0xc9, 0x81, + 0x5e, 0xac, 0x8d, 0x59, 0x25, 0x56, 0xbd, 0xb6, 0x6b, 0xef, 0x22, 0xe5, 0xdc, 0x43, 0xbf, 0x47, + 0xbf, 0x68, 0xab, 0xfd, 0xe3, 0x18, 0x24, 0xc3, 0xa9, 0xb7, 0xb7, 0xf3, 0x66, 0xde, 0x8e, 0x77, + 0xc7, 0x0b, 0x9b, 0x8c, 0xf2, 0x32, 0x89, 0xab, 0x61, 0x51, 0xe6, 0x3c, 0x47, 0x5b, 0x49, 0x2e, + 0x2b, 0x46, 0xf9, 0x82, 0x8a, 0x6a, 0x18, 0xa7, 0x09, 0xcd, 0xf8, 0xe0, 0x10, 0xdc, 0x2f, 0x64, + 0x46, 0xd3, 0x2b, 0x92, 0x94, 0x08, 0x81, 0x9d, 0x11, 0x46, 0x03, 0xab, 0x6f, 0xed, 0xba, 0x58, + 0xd5, 0x68, 0x0b, 0x9c, 0x5b, 0x92, 0x0a, 0x1a, 0xac, 0x29, 0x50, 0x2f, 0x06, 0xdb, 0xe0, 0x8c, + 0x88, 0x98, 0xdf, 0x69, 0x4b, 0x8d, 0x55, 0xb7, 0x77, 0xa0, 0x77, 0x9a, 0x8b, 0x8c, 0xd3, 0xf2, + 0x01, 0xc2, 0x7b, 0x58, 0xff, 0x2a, 0x48, 0xc6, 0x93, 0x94, 0xa2, 0xa7, 0xb0, 0xfe, 0xc3, 0xd4, + 0x86, 0xb4, 0x5a, 0xdf, 0xdf, 0x7d, 0xa5, 0xfe, 0x65, 0x41, 0x6f, 0x2c, 0x18, 0x23, 0xe5, 0x12, + 0xbd, 0x84, 0x8d, 0x8a, 0xb0, 0x22, 0xa5, 0x51, 0x2c, 0x77, 0x54, 0x13, 0x6c, 0xec, 0x69, 0x4c, + 0x99, 0x40, 0xdb, 0x00, 0x86, 0x52, 0x09, 0x66, 0x26, 0xb9, 0x1a, 0x19, 0x0b, 0x86, 0x8e, 0xee, + 0xec, 0xdf, 0xe9, 0x77, 0x76, 0xbd, 0xfd, 0x17, 0xc3, 0xb6, 0xb3, 0x1a, 0xd6, 0x8e, 0x1b, 0x7f, + 0xf2, 0x43, 0xa7, 0x19, 0x5f, 0x16, 0xf4, 0xe6, 0x81, 0x0f, 0xfd, 0x69, 0x81, 0x7b, 0x9e, 0x54, + 0x3c, 0x9f, 0x97, 0x84, 0xfd, 0x03, 0xb3, 0x07, 0xd0, 0x9d, 0x89, 0xf8, 0x3b, 0xe5, 0xc6, 0xea, + 0xf3, 0x76, 0xab, 0x27, 0x8a, 0x83, 0x0d, 0x77, 0x30, 0x81, 0xae, 0x46, 0xd0, 0x2b, 0xf0, 0x63, + 0xc1, 0x44, 0x4a, 0x78, 0x72, 0x7b, 0xdf, 0xc5, 0x93, 0x06, 0xd7, 0x4e, 0x76, 0xc0, 0x13, 0x45, + 0x41, 0xcb, 0x68, 0x96, 0x8b, 0xec, 0xc6, 0x58, 0x01, 0x05, 0x9d, 0x48, 0x64, 0xf0, 0x67, 0x0d, + 0xba, 0xa1, 0xca, 0x18, 0x3a, 0x04, 0x27, 0x95, 0x31, 0x0a, 0x2c, 0xe5, 0x6a, 0xa7, 0xdd, 0xd5, + 0x2a, 0x69, 0x58, 0xb3, 0xd1, 0x1b, 0x70, 0xe6, 0x32, 0x46, 0x6a, 0xb8, 0xb7, 0xff, 0xac, 0x5d, + 0xa6, 0x92, 0x86, 0x35, 0x13, 0xbd, 0x85, 0x5e, 0xac, 0xa3, 0x15, 0x74, 0x94, 0x68, 0xbb, 0x5d, + 0x64, 0xf2, 0x87, 0x6b, 0xb6, 0x14, 0x56, 0x3a, 0x33, 0x81, 0xfd, 0x98, 0xd0, 0x04, 0x0b, 0xd7, + 0x6c, 0x29, 0x14, 0xfa, 0x8e, 0x03, 0xe7, 0x31, 0xa1, 0x09, 0x02, 0xae, 0xd9, 0xe8, 0x03, 0xb8, + 0x8b, 0xfa, 0xea, 0x83, 0x9e, 0x92, 0x3e, 0x70, 0x30, 0xab, 0x84, 0xe0, 0x46, 0x21, 0xc3, 0xc2, + 0x13, 0x46, 0x2b, 0x4e, 0x58, 0x11, 0xb1, 0x2a, 0xe8, 0xf6, 0xad, 0xdd, 0x0e, 0xf6, 0x56, 0x58, + 0x58, 0x0d, 0x7e, 0x5b, 0xb0, 0xa1, 0x6f, 0xe0, 0x13, 0x61, 0x49, 0xba, 0x6c, 0xfd, 0x83, 0x11, + 0xd8, 0x0b, 0x9a, 0x16, 0xe6, 0x07, 0x56, 0x35, 0x3a, 0x00, 0x5b, 0x7a, 0x54, 0x47, 0xf8, 0xff, + 0x7e, 0xbf, 0xdd, 0x95, 0x9e, 0x3c, 0x59, 0x16, 0x14, 0x2b, 0xb6, 0x0c, 0x9f, 0x7e, 0x53, 0x02, + 0xfb, 0xb1, 0xf0, 0x69, 0x1d, 0x36, 0xdc, 0xd7, 0x21, 0x40, 0x33, 0x09, 0x79, 0xd0, 0x3b, 0xbd, + 0x9c, 0x5e, 0x4c, 0xce, 0xb0, 0xff, 0x1f, 0x72, 0xc1, 0x19, 0x1d, 0x4f, 0x47, 0x67, 0xbe, 0x25, + 0xf1, 0xf1, 0x34, 0x0c, 0x8f, 0xf1, 0xb5, 0xbf, 0x26, 0x17, 0xd3, 0x8b, 0xc9, 0xf5, 0xd5, 0xd9, + 0x47, 0xbf, 0x83, 0x36, 0xc1, 0x3d, 0xff, 0x3c, 0x9e, 0x5c, 0x8e, 0xf0, 0x71, 0xe8, 0xdb, 0x27, + 0x18, 0x5a, 0x5f, 0xb2, 0x6f, 0x47, 0xf3, 0x84, 0x2f, 0xc4, 0x6c, 0x18, 0xe7, 0x6c, 0xaf, 0xe9, + 0xee, 0xe9, 0x6e, 0xc4, 0xf2, 0x1b, 0x9a, 0xee, 0xcd, 0xf3, 0x77, 0x49, 0x1e, 0x35, 0xdd, 0x48, + 0x77, 0xff, 0x06, 0x00, 0x00, 0xff, 0xff, 0x45, 0x21, 0x7f, 0x64, 0x2b, 0x05, 0x00, 0x00, +} diff --git a/vendor/github.com/prometheus/procfs/mountstats.go b/vendor/github.com/prometheus/procfs/mountstats.go index e95ddbc67..7a8a1e099 100644 --- a/vendor/github.com/prometheus/procfs/mountstats.go +++ b/vendor/github.com/prometheus/procfs/mountstats.go @@ -39,8 +39,11 @@ const ( statVersion10 = "1.0" statVersion11 = "1.1" - fieldTransport10Len = 10 - fieldTransport11Len = 13 + fieldTransport10TCPLen = 10 + fieldTransport10UDPLen = 7 + + fieldTransport11TCPLen = 13 + fieldTransport11UDPLen = 10 ) // A Mount is a device mount parsed from /proc/[pid]/mountstats. @@ -186,6 +189,8 @@ type NFSOperationStats struct { // A NFSTransportStats contains statistics for the NFS mount RPC requests and // responses. type NFSTransportStats struct { + // The transport protocol used for the NFS mount. + Protocol string // The local port used for the NFS mount. Port uint64 // Number of times the client has had to establish a connection from scratch @@ -360,7 +365,7 @@ func parseMountStatsNFS(s *bufio.Scanner, statVersion string) (*MountStatsNFS, e return nil, fmt.Errorf("not enough information for NFS transport stats: %v", ss) } - tstats, err := parseNFSTransportStats(ss[2:], statVersion) + tstats, err := parseNFSTransportStats(ss[1:], statVersion) if err != nil { return nil, err } @@ -522,13 +527,33 @@ func parseNFSOperationStats(s *bufio.Scanner) ([]NFSOperationStats, error) { // parseNFSTransportStats parses a NFSTransportStats line using an input set of // integer fields matched to a specific stats version. func parseNFSTransportStats(ss []string, statVersion string) (*NFSTransportStats, error) { + // Extract the protocol field. It is the only string value in the line + protocol := ss[0] + ss = ss[1:] + switch statVersion { case statVersion10: - if len(ss) != fieldTransport10Len { + var expectedLength int + if protocol == "tcp" { + expectedLength = fieldTransport10TCPLen + } else if protocol == "udp" { + expectedLength = fieldTransport10UDPLen + } else { + return nil, fmt.Errorf("invalid NFS protocol \"%s\" in stats 1.0 statement: %v", protocol, ss) + } + if len(ss) != expectedLength { return nil, fmt.Errorf("invalid NFS transport stats 1.0 statement: %v", ss) } case statVersion11: - if len(ss) != fieldTransport11Len { + var expectedLength int + if protocol == "tcp" { + expectedLength = fieldTransport11TCPLen + } else if protocol == "udp" { + expectedLength = fieldTransport11UDPLen + } else { + return nil, fmt.Errorf("invalid NFS protocol \"%s\" in stats 1.1 statement: %v", protocol, ss) + } + if len(ss) != expectedLength { return nil, fmt.Errorf("invalid NFS transport stats 1.1 statement: %v", ss) } default: @@ -536,12 +561,13 @@ func parseNFSTransportStats(ss []string, statVersion string) (*NFSTransportStats } // Allocate enough for v1.1 stats since zero value for v1.1 stats will be okay - // in a v1.0 response. + // in a v1.0 response. Since the stat length is bigger for TCP stats, we use + // the TCP length here. // // Note: slice length must be set to length of v1.1 stats to avoid a panic when // only v1.0 stats are present. // See: https://github.com/prometheus/node_exporter/issues/571. - ns := make([]uint64, fieldTransport11Len) + ns := make([]uint64, fieldTransport11TCPLen) for i, s := range ss { n, err := strconv.ParseUint(s, 10, 64) if err != nil { @@ -551,7 +577,18 @@ func parseNFSTransportStats(ss []string, statVersion string) (*NFSTransportStats ns[i] = n } + // The fields differ depending on the transport protocol (TCP or UDP) + // From https://utcc.utoronto.ca/%7Ecks/space/blog/linux/NFSMountstatsXprt + // + // For the udp RPC transport there is no connection count, connect idle time, + // or idle time (fields #3, #4, and #5); all other fields are the same. So + // we set them to 0 here. + if protocol == "udp" { + ns = append(ns[:2], append(make([]uint64, 3), ns[2:]...)...) + } + return &NFSTransportStats{ + Protocol: protocol, Port: ns[0], Bind: ns[1], Connect: ns[2], diff --git a/vendor/github.com/syndtr/goleveldb/leveldb/db_compaction.go b/vendor/github.com/syndtr/goleveldb/leveldb/db_compaction.go index b6563e87e..28e50906a 100644 --- a/vendor/github.com/syndtr/goleveldb/leveldb/db_compaction.go +++ b/vendor/github.com/syndtr/goleveldb/leveldb/db_compaction.go @@ -640,6 +640,16 @@ func (db *DB) tableNeedCompaction() bool { return v.needCompaction() } +// resumeWrite returns an indicator whether we should resume write operation if enough level0 files are compacted. +func (db *DB) resumeWrite() bool { + v := db.s.version() + defer v.release() + if v.tLen(0) < db.s.o.GetWriteL0PauseTrigger() { + return true + } + return false +} + func (db *DB) pauseCompaction(ch chan<- struct{}) { select { case ch <- struct{}{}: @@ -653,6 +663,7 @@ type cCmd interface { } type cAuto struct { + // Note for table compaction, an empty ackC represents it's a compaction waiting command. ackC chan<- error } @@ -765,8 +776,10 @@ func (db *DB) mCompaction() { } func (db *DB) tCompaction() { - var x cCmd - var ackQ []cCmd + var ( + x cCmd + ackQ, waitQ []cCmd + ) defer func() { if x := recover(); x != nil { @@ -778,6 +791,10 @@ func (db *DB) tCompaction() { ackQ[i].ack(ErrClosed) ackQ[i] = nil } + for i := range waitQ { + waitQ[i].ack(ErrClosed) + waitQ[i] = nil + } if x != nil { x.ack(ErrClosed) } @@ -795,12 +812,25 @@ func (db *DB) tCompaction() { return default: } + // Resume write operation as soon as possible. + if len(waitQ) > 0 && db.resumeWrite() { + for i := range waitQ { + waitQ[i].ack(nil) + waitQ[i] = nil + } + waitQ = waitQ[:0] + } } else { for i := range ackQ { ackQ[i].ack(nil) ackQ[i] = nil } ackQ = ackQ[:0] + for i := range waitQ { + waitQ[i].ack(nil) + waitQ[i] = nil + } + waitQ = waitQ[:0] select { case x = <-db.tcompCmdC: case ch := <-db.tcompPauseC: @@ -813,7 +843,11 @@ func (db *DB) tCompaction() { if x != nil { switch cmd := x.(type) { case cAuto: - ackQ = append(ackQ, x) + if cmd.ackC != nil { + waitQ = append(waitQ, x) + } else { + ackQ = append(ackQ, x) + } case cRange: x.ack(db.tableRangeCompaction(cmd.level, cmd.min, cmd.max)) default: diff --git a/vendor/github.com/tendermint/go-amino/amino.go b/vendor/github.com/tendermint/go-amino/amino.go index 93831f074..1f0f2a531 100644 --- a/vendor/github.com/tendermint/go-amino/amino.go +++ b/vendor/github.com/tendermint/go-amino/amino.go @@ -11,62 +11,105 @@ import ( ) //---------------------------------------- -// Typ3 and Typ4 +// Global methods for global sealed codec. +var gcdc *Codec + +func init() { + gcdc = NewCodec().Seal() +} + +func MarshalBinary(o interface{}) ([]byte, error) { + return gcdc.MarshalBinary(o) +} + +func MarshalBinaryWriter(w io.Writer, o interface{}) (n int64, err error) { + return gcdc.MarshalBinaryWriter(w, o) +} + +func MustMarshalBinary(o interface{}) []byte { + return gcdc.MustMarshalBinary(o) +} + +func MarshalBinaryBare(o interface{}) ([]byte, error) { + return gcdc.MarshalBinaryBare(o) +} + +func MustMarshalBinaryBare(o interface{}) []byte { + return gcdc.MustMarshalBinaryBare(o) +} + +func UnmarshalBinary(bz []byte, ptr interface{}) error { + return gcdc.UnmarshalBinary(bz, ptr) +} + +func UnmarshalBinaryReader(r io.Reader, ptr interface{}, maxSize int64) (n int64, err error) { + return gcdc.UnmarshalBinaryReader(r, ptr, maxSize) +} + +func MustUnmarshalBinary(bz []byte, ptr interface{}) { + gcdc.MustUnmarshalBinary(bz, ptr) +} + +func UnmarshalBinaryBare(bz []byte, ptr interface{}) error { + return gcdc.UnmarshalBinaryBare(bz, ptr) +} + +func MustUnmarshalBinaryBare(bz []byte, ptr interface{}) { + gcdc.MustUnmarshalBinaryBare(bz, ptr) +} + +func MarshalJSON(o interface{}) ([]byte, error) { + return gcdc.MarshalJSON(o) +} + +func UnmarshalJSON(bz []byte, ptr interface{}) error { + return gcdc.UnmarshalJSON(bz, ptr) +} + +func MarshalJSONIndent(o interface{}, prefix, indent string) ([]byte, error) { + return gcdc.MarshalJSONIndent(o, prefix, indent) +} + +//---------------------------------------- +// Typ3 type Typ3 uint8 -type Typ4 uint8 // Typ3 | 0x08 (pointer bit) const ( // Typ3 types Typ3_Varint = Typ3(0) Typ3_8Byte = Typ3(1) Typ3_ByteLength = Typ3(2) - Typ3_Struct = Typ3(3) - Typ3_StructTerm = Typ3(4) - Typ3_4Byte = Typ3(5) - Typ3_List = Typ3(6) - Typ3_Interface = Typ3(7) - - // Typ4 bit - Typ4_Pointer = Typ4(0x08) + //Typ3_Struct = Typ3(3) + //Typ3_StructTerm = Typ3(4) + Typ3_4Byte = Typ3(5) + //Typ3_List = Typ3(6) + //Typ3_Interface = Typ3(7) ) func (typ Typ3) String() string { switch typ { case Typ3_Varint: - return "Varint" + return "(U)Varint" case Typ3_8Byte: return "8Byte" case Typ3_ByteLength: return "ByteLength" - case Typ3_Struct: - return "Struct" - case Typ3_StructTerm: - return "StructTerm" + //case Typ3_Struct: + // return "Struct" + //case Typ3_StructTerm: + // return "StructTerm" case Typ3_4Byte: return "4Byte" - case Typ3_List: - return "List" - case Typ3_Interface: - return "Interface" + //case Typ3_List: + // return "List" + //case Typ3_Interface: + // return "Interface" default: return fmt.Sprintf("", byte(typ)) } } -func (typ Typ4) Typ3() Typ3 { return Typ3(typ & 0x07) } -func (typ Typ4) IsPointer() bool { return (typ & 0x08) > 0 } -func (typ Typ4) String() string { - if typ&0xF0 != 0 { - return fmt.Sprintf("", byte(typ)) - } - if typ&0x08 != 0 { - return "*" + Typ3(typ&0x07).String() - } else { - return Typ3(typ).String() - } -} - //---------------------------------------- // *Codec methods @@ -146,12 +189,18 @@ func (cdc *Codec) MarshalBinaryBare(o interface{}) ([]byte, error) { if err != nil { return nil, err } - err = cdc.encodeReflectBinary(buf, info, rv, FieldOptions{}) + err = cdc.encodeReflectBinary(buf, info, rv, FieldOptions{}, true) if err != nil { return nil, err } bz = buf.Bytes() + // If registered concrete, prepend prefix bytes. + if info.Registered { + pb := info.Prefix.Bytes() + bz = append(pb, bz...) + } + return bz, nil } @@ -256,25 +305,34 @@ func (cdc *Codec) MustUnmarshalBinary(bz []byte, ptr interface{}) { // UnmarshalBinaryBare will panic if ptr is a nil-pointer. func (cdc *Codec) UnmarshalBinaryBare(bz []byte, ptr interface{}) error { - if len(bz) == 0 { - return errors.New("UnmarshalBinaryBare cannot decode empty bytes") - } - rv, rt := reflect.ValueOf(ptr), reflect.TypeOf(ptr) + rv := reflect.ValueOf(ptr) if rv.Kind() != reflect.Ptr { panic("Unmarshal expects a pointer") } - rv, rt = rv.Elem(), rt.Elem() + rv = rv.Elem() + rt := rv.Type() info, err := cdc.getTypeInfo_wlock(rt) if err != nil { return err } - n, err := cdc.decodeReflectBinary(bz, info, rv, FieldOptions{}) + // If registered concrete, consume and verify prefix bytes. + if info.Registered { + pb := info.Prefix.Bytes() + if len(bz) < 4 { + return fmt.Errorf("UnmarshalBinaryBare expected to read prefix bytes %X (since it is registered concrete) but got %X", pb, bz) + } else if !bytes.Equal(bz[:4], pb) { + return fmt.Errorf("UnmarshalBinaryBare expected to read prefix bytes %X (since it is registered concrete) but got %X...", pb, bz[:4]) + } + bz = bz[4:] + } + // Decode contents into rv. + n, err := cdc.decodeReflectBinary(bz, info, rv, FieldOptions{}, true) if err != nil { - return err + return fmt.Errorf("unmarshal to %v failed after %d bytes (%v): %X", info.Type, n, err, bz) } if n != len(bz) { - return fmt.Errorf("Unmarshal didn't read all bytes. Expected to read %v, only read %v", len(bz), n) + return fmt.Errorf("unmarshal to %v didn't read all bytes. Expected to read %v, only read %v: %X", info.Type, len(bz), n, bz) } return nil } @@ -293,25 +351,37 @@ func (cdc *Codec) MarshalJSON(o interface{}) ([]byte, error) { return []byte("null"), nil } rt := rv.Type() - - // Note that we can't yet skip directly - // to checking if a type implements - // json.Marshaler because in some cases - // var s GenericInterface = t1(v1) - // var t GenericInterface = t2(v1) - // but we need to be able to encode - // both s and t disambiguated, so: - // {"type":, "value":} - // for the above case. - w := new(bytes.Buffer) info, err := cdc.getTypeInfo_wlock(rt) if err != nil { return nil, err } + + // Write the disfix wrapper if it is a registered concrete type. + if info.Registered { + // Part 1: + err = writeStr(w, _fmt(`{"type":"%s","value":`, info.Name)) + if err != nil { + return nil, err + } + } + + // Write the rest from rv. if err := cdc.encodeReflectJSON(w, info, rv, FieldOptions{}); err != nil { return nil, err } + + // disfix wrapper continued... + if info.Registered { + // Part 2: + if err != nil { + return nil, err + } + err = writeStr(w, `}`) + if err != nil { + return nil, err + } + } return w.Bytes(), nil } @@ -324,20 +394,25 @@ func (cdc *Codec) UnmarshalJSON(bz []byte, ptr interface{}) error { if rv.Kind() != reflect.Ptr { return errors.New("UnmarshalJSON expects a pointer") } - - // If the type implements json.Unmarshaler, just - // automatically respect that and skip to it. - // if rv.Type().Implements(jsonUnmarshalerType) { - // return rv.Interface().(json.Unmarshaler).UnmarshalJSON(bz) - // } - - // 1. Dereference until we find the first addressable type. rv = rv.Elem() rt := rv.Type() info, err := cdc.getTypeInfo_wlock(rt) if err != nil { return err } + // If registered concrete, consume and verify type wrapper. + if info.Registered { + // Consume type wrapper info. + name, bz_, err := decodeInterfaceJSON(bz) + if err != nil { + return err + } + // Check name against info. + if name != info.Name { + return fmt.Errorf("UnmarshalJSON wants to decode a %v but found a %v", info.Name, name) + } + bz = bz_ + } return cdc.decodeReflectJSON(bz, info, rv, FieldOptions{}) } diff --git a/vendor/github.com/tendermint/go-amino/binary-decode.go b/vendor/github.com/tendermint/go-amino/binary-decode.go index c1fac922a..6e18bc371 100644 --- a/vendor/github.com/tendermint/go-amino/binary-decode.go +++ b/vendor/github.com/tendermint/go-amino/binary-decode.go @@ -6,17 +6,18 @@ import ( "reflect" "time" + "encoding/binary" "github.com/davecgh/go-spew/spew" ) //---------------------------------------- // cdc.decodeReflectBinary -// This is the main entrypoint for decoding all types from binary form. This +// This is the main entrypoint for decoding all types from binary form. This // function calls decodeReflectBinary*, and generally those functions should // only call this one, for the prefix bytes are consumed here when present. // CONTRACT: rv.CanAddr() is true. -func (cdc *Codec) decodeReflectBinary(bz []byte, info *TypeInfo, rv reflect.Value, opts FieldOptions) (n int, err error) { +func (cdc *Codec) decodeReflectBinary(bz []byte, info *TypeInfo, rv reflect.Value, fopts FieldOptions, bare bool) (n int, err error) { if !rv.CanAddr() { panic("rv not addressable") } @@ -24,62 +25,12 @@ func (cdc *Codec) decodeReflectBinary(bz []byte, info *TypeInfo, rv reflect.Valu panic("should not happen") } if printLog { - spew.Printf("(D) decodeReflectBinary(bz: %X, info: %v, rv: %#v (%v), opts: %v)\n", - bz, info, rv.Interface(), rv.Type(), opts) + spew.Printf("(D) decodeReflectBinary(bz: %X, info: %v, rv: %#v (%v), fopts: %v)\n", + bz, info, rv.Interface(), rv.Type(), fopts) defer func() { fmt.Printf("(D) -> n: %v, err: %v\n", n, err) }() } - - // TODO Read the disamb bytes here if necessary. - // e.g. rv isn't an interface, and - // info.ConcreteType.AlwaysDisambiguate. But we don't support - // this yet. - - // Read prefix+typ3 bytes if registered. - if info.Registered { - if len(bz) < PrefixBytesLen { - err = errors.New("EOF skipping prefix bytes.") - return - } - // Check prefix bytes. - prefix3 := NewPrefixBytes(bz[:PrefixBytesLen]) - var prefix, typ = prefix3.SplitTyp3() - if info.Prefix != prefix { - panic("should not happen") - } - // Check that typ3 in prefix bytes is correct. - err = checkTyp3(info.Type, typ, opts) - if err != nil { - return - } - // Consume prefix. Yum. - bz = bz[PrefixBytesLen:] - n += PrefixBytesLen - } - - _n := 0 - _n, err = cdc._decodeReflectBinary(bz, info, rv, opts) - slide(&bz, &n, _n) - return -} - -// CONTRACT: any immediate disamb/prefix bytes have been consumed/stripped. -// CONTRACT: rv.CanAddr() is true. -func (cdc *Codec) _decodeReflectBinary(bz []byte, info *TypeInfo, rv reflect.Value, opts FieldOptions) (n int, err error) { - if !rv.CanAddr() { - panic("rv not addressable") - } - if info.Type.Kind() == reflect.Interface && rv.Kind() == reflect.Ptr { - panic("should not happen") - } - if printLog { - spew.Printf("(_) _decodeReflectBinary(bz: %X, info: %v, rv: %#v (%v), opts: %v)\n", - bz, info, rv.Interface(), rv.Type(), opts) - defer func() { - fmt.Printf("(_) -> n: %v, err: %v\n", n, err) - }() - } var _n int // TODO consider the binary equivalent of json.Unmarshaller. @@ -102,7 +53,7 @@ func (cdc *Codec) _decodeReflectBinary(bz []byte, info *TypeInfo, rv reflect.Val if err != nil { return } - _n, err = cdc._decodeReflectBinary(bz, rinfo, rrv, opts) + _n, err = cdc.decodeReflectBinary(bz, rinfo, rrv, fopts, bare) if slide(&bz, &n, _n) && err != nil { return } @@ -122,17 +73,17 @@ func (cdc *Codec) _decodeReflectBinary(bz []byte, info *TypeInfo, rv reflect.Val // Complex case reflect.Interface: - _n, err = cdc.decodeReflectBinaryInterface(bz, info, rv, opts) + _n, err = cdc.decodeReflectBinaryInterface(bz, info, rv, fopts, bare) n += _n return case reflect.Array: ert := info.Type.Elem() if ert.Kind() == reflect.Uint8 { - _n, err = cdc.decodeReflectBinaryByteArray(bz, info, rv, opts) + _n, err = cdc.decodeReflectBinaryByteArray(bz, info, rv, fopts) n += _n } else { - _n, err = cdc.decodeReflectBinaryArray(bz, info, rv, opts) + _n, err = cdc.decodeReflectBinaryArray(bz, info, rv, fopts, bare) n += _n } return @@ -140,16 +91,16 @@ func (cdc *Codec) _decodeReflectBinary(bz []byte, info *TypeInfo, rv reflect.Val case reflect.Slice: ert := info.Type.Elem() if ert.Kind() == reflect.Uint8 { - _n, err = cdc.decodeReflectBinaryByteSlice(bz, info, rv, opts) + _n, err = cdc.decodeReflectBinaryByteSlice(bz, info, rv, fopts) n += _n } else { - _n, err = cdc.decodeReflectBinarySlice(bz, info, rv, opts) + _n, err = cdc.decodeReflectBinarySlice(bz, info, rv, fopts, bare) n += _n } return case reflect.Struct: - _n, err = cdc.decodeReflectBinaryStruct(bz, info, rv, opts) + _n, err = cdc.decodeReflectBinaryStruct(bz, info, rv, fopts, bare) n += _n return @@ -158,14 +109,14 @@ func (cdc *Codec) _decodeReflectBinary(bz []byte, info *TypeInfo, rv reflect.Val case reflect.Int64: var num int64 - if opts.BinVarint { - num, _n, err = DecodeVarint(bz) + if fopts.BinFixed64 { + num, _n, err = DecodeInt64(bz) if slide(&bz, &n, _n) && err != nil { return } rv.SetInt(num) } else { - num, _n, err = DecodeInt64(bz) + num, _n, err = DecodeVarint(bz) if slide(&bz, &n, _n) && err != nil { return } @@ -174,12 +125,21 @@ func (cdc *Codec) _decodeReflectBinary(bz []byte, info *TypeInfo, rv reflect.Val return case reflect.Int32: - var num int32 - num, _n, err = DecodeInt32(bz) - if slide(&bz, &n, _n) && err != nil { - return + if fopts.BinFixed32 { + var num int32 + num, _n, err = DecodeInt32(bz) + if slide(&bz, &n, _n) && err != nil { + return + } + rv.SetInt(int64(num)) + } else { + var num int64 + num, _n, err = DecodeVarint(bz) + if slide(&bz, &n, _n) && err != nil { + return + } + rv.SetInt(int64(num)) } - rv.SetInt(int64(num)) return case reflect.Int16: @@ -214,14 +174,14 @@ func (cdc *Codec) _decodeReflectBinary(bz []byte, info *TypeInfo, rv reflect.Val case reflect.Uint64: var num uint64 - if opts.BinVarint { - num, _n, err = DecodeUvarint(bz) + if fopts.BinFixed64 { + num, _n, err = DecodeUint64(bz) if slide(&bz, &n, _n) && err != nil { return } rv.SetUint(num) } else { - num, _n, err = DecodeUint64(bz) + num, _n, err = DecodeUvarint(bz) if slide(&bz, &n, _n) && err != nil { return } @@ -230,12 +190,21 @@ func (cdc *Codec) _decodeReflectBinary(bz []byte, info *TypeInfo, rv reflect.Val return case reflect.Uint32: - var num uint32 - num, _n, err = DecodeUint32(bz) - if slide(&bz, &n, _n) && err != nil { - return + if fopts.BinFixed32 { + var num uint32 + num, _n, err = DecodeUint32(bz) + if slide(&bz, &n, _n) && err != nil { + return + } + rv.SetUint(uint64(num)) + } else { + var num uint64 + num, _n, err = DecodeUvarint(bz) + if slide(&bz, &n, _n) && err != nil { + return + } + rv.SetUint(uint64(num)) } - rv.SetUint(uint64(num)) return case reflect.Uint16: @@ -279,7 +248,7 @@ func (cdc *Codec) _decodeReflectBinary(bz []byte, info *TypeInfo, rv reflect.Val case reflect.Float64: var f float64 - if !opts.Unsafe { + if !fopts.Unsafe { err = errors.New("Float support requires `amino:\"unsafe\"`.") return } @@ -292,7 +261,7 @@ func (cdc *Codec) _decodeReflectBinary(bz []byte, info *TypeInfo, rv reflect.Val case reflect.Float32: var f float32 - if !opts.Unsafe { + if !fopts.Unsafe { err = errors.New("Float support requires `amino:\"unsafe\"`.") return } @@ -319,7 +288,7 @@ func (cdc *Codec) _decodeReflectBinary(bz []byte, info *TypeInfo, rv reflect.Val } // CONTRACT: rv.CanAddr() is true. -func (cdc *Codec) decodeReflectBinaryInterface(bz []byte, iinfo *TypeInfo, rv reflect.Value, opts FieldOptions) (n int, err error) { +func (cdc *Codec) decodeReflectBinaryInterface(bz []byte, iinfo *TypeInfo, rv reflect.Value, fopts FieldOptions, bare bool) (n int, err error) { if !rv.CanAddr() { panic("rv not addressable") } @@ -337,15 +306,21 @@ func (cdc *Codec) decodeReflectBinaryInterface(bz []byte, iinfo *TypeInfo, rv re return } - // Consume disambiguation / prefix+typ3 bytes. - disamb, hasDisamb, prefix, typ, hasPrefix, isNil, _n, err := DecodeDisambPrefixBytes(bz) - if slide(&bz, &n, _n) && err != nil { - return + if !bare { + // Read byte-length prefixed byteslice. + var buf, _n = []byte(nil), int(0) + buf, _n, err = DecodeByteSlice(bz) + if slide(&bz, nil, _n) && err != nil { + return + } + // This is a trick for debuggability -- we slide on &n more later. + n += UvarintSize(uint64(len(buf))) + bz = buf } - // Special case for nil. - if isNil { - rv.Set(iinfo.ZeroValue) + // Consume disambiguation / prefix bytes. + disamb, hasDisamb, prefix, hasPrefix, _n, err := DecodeDisambPrefixBytes(bz) + if slide(&bz, &n, _n) && err != nil { return } @@ -362,23 +337,23 @@ func (cdc *Codec) decodeReflectBinaryInterface(bz []byte, iinfo *TypeInfo, rv re return } - // Check and consume typ3 byte. - // It cannot be a typ4 byte because it cannot be nil. - err = checkTyp3(cinfo.Type, typ, opts) - if err != nil { - return - } - // Construct the concrete type. var crv, irvSet = constructConcreteType(cinfo) // Decode into the concrete type. - _n, err = cdc._decodeReflectBinary(bz, cinfo, crv, opts) + _n, err = cdc.decodeReflectBinary(bz, cinfo, crv, fopts, true) if slide(&bz, &n, _n) && err != nil { rv.Set(irvSet) // Helps with debugging return } + // Earlier, we set bz to the byteslice read from buf. + // Ensure that all of bz was consumed. + if len(bz) > 0 { + err = errors.New("bytes left over after reading interface contents") + return + } + // We need to set here, for when !PointerPreferred and the type // is say, an array of bytes (e.g. [32]byte), then we must call // rv.Set() *after* the value was acquired. @@ -389,7 +364,7 @@ func (cdc *Codec) decodeReflectBinaryInterface(bz []byte, iinfo *TypeInfo, rv re } // CONTRACT: rv.CanAddr() is true. -func (cdc *Codec) decodeReflectBinaryByteArray(bz []byte, info *TypeInfo, rv reflect.Value, opts FieldOptions) (n int, err error) { +func (cdc *Codec) decodeReflectBinaryByteArray(bz []byte, info *TypeInfo, rv reflect.Value, fopts FieldOptions) (n int, err error) { if !rv.CanAddr() { panic("rv not addressable") } @@ -426,7 +401,7 @@ func (cdc *Codec) decodeReflectBinaryByteArray(bz []byte, info *TypeInfo, rv ref } // CONTRACT: rv.CanAddr() is true. -func (cdc *Codec) decodeReflectBinaryArray(bz []byte, info *TypeInfo, rv reflect.Value, opts FieldOptions) (n int, err error) { +func (cdc *Codec) decodeReflectBinaryArray(bz []byte, info *TypeInfo, rv reflect.Value, fopts FieldOptions, bare bool) (n int, err error) { if !rv.CanAddr() { panic("rv not addressable") } @@ -441,65 +416,106 @@ func (cdc *Codec) decodeReflectBinaryArray(bz []byte, info *TypeInfo, rv reflect panic("should not happen") } length := info.Type.Len() - einfo := (*TypeInfo)(nil) - einfo, err = cdc.getTypeInfo_wlock(ert) + einfo, err := cdc.getTypeInfo_wlock(ert) if err != nil { return } - // Check and consume typ4 byte. - var ptr, _n = false, int(0) - ptr, _n, err = decodeTyp4AndCheck(ert, bz, opts) - if slide(&bz, &n, _n) && err != nil { - return - } - - // Read number of items. - var count = uint64(0) - count, _n, err = DecodeUvarint(bz) - if slide(&bz, &n, _n) && err != nil { - return - } - if int(count) != length { - err = fmt.Errorf("Expected num items of %v, decoded %v", length, count) - return + if !bare { + // Read byte-length prefixed byteslice. + var buf, _n = []byte(nil), int(0) + buf, _n, err = DecodeByteSlice(bz) + if slide(&bz, nil, _n) && err != nil { + return + } + // This is a trick for debuggability -- we slide on &n more later. + n += UvarintSize(uint64(len(buf))) + bz = buf } - // NOTE: Unlike decodeReflectBinarySlice, - // there is nothing special to do for - // zero-length arrays. Is that even possible? - - // Read each item. - for i := 0; i < length; i++ { - var erv, _n = rv.Index(i), int(0) - // Maybe read nil. - if ptr { - numNil := int64(0) - numNil, _n, err = decodeNumNilBytes(bz) + // If elem is not already a ByteLength type, read in packed form. + // This is a Proto wart due to Proto backwards compatibility issues. + // Amino2 will probably migrate to use the List typ3. + typ3 := typeToTyp3(einfo.Type, fopts) + if typ3 != Typ3_ByteLength { + // Read elements in packed form. + for i := 0; i < length; i++ { + var erv, _n = rv.Index(i), int(0) + _n, err = cdc.decodeReflectBinary(bz, einfo, erv, fopts, false) + if slide(&bz, &n, _n) && err != nil { + err = fmt.Errorf("error reading array contents: %v", err) + return + } + // Special case when reading default value, prefer nil. + if erv.Kind() == reflect.Ptr { + _, isDefault := isDefaultValue(erv) + if isDefault { + erv.Set(reflect.Zero(erv.Type())) + continue + } + } + } + // Ensure that we read the whole buffer. + if len(bz) > 0 { + err = errors.New("bytes left over after reading array contents") + return + } + } else { + // Read elements in unpacked form. + for i := 0; i < length; i++ { + // Read field key (number and type). + var fnum, typ, _n = uint32(0), Typ3(0x00), int(0) + fnum, typ, _n, err = decodeFieldNumberAndTyp3(bz) + // Validate field number and typ3. + if fnum != fopts.BinFieldNum { + err = errors.New(fmt.Sprintf("expected repeated field number %v, got %v", fopts.BinFieldNum, fnum)) + return + } + if typ != Typ3_ByteLength { + err = errors.New(fmt.Sprintf("expected repeated field type %v, got %v", Typ3_ByteLength, typ)) + return + } if slide(&bz, &n, _n) && err != nil { return } - if numNil == 0 { - // Good, continue decoding item. - } else if numNil == 1 { - // Set nil/zero. + // Decode the next ByteLength bytes into erv. + var erv = rv.Index(i) + // Special case if next ByteLength bytes are 0x00, set nil. + if len(bz) > 0 && bz[0] == 0x00 { + slide(&bz, &n, 1) erv.Set(reflect.Zero(erv.Type())) continue - } else { - panic("should not happen") + } + // Normal case, read next non-nil element from bz. + // In case of any inner lists in unpacked form. + efopts := fopts + efopts.BinFieldNum = 1 + _n, err = cdc.decodeReflectBinary(bz, einfo, erv, efopts, false) + if slide(&bz, &n, _n) && err != nil { + err = fmt.Errorf("error reading array contents: %v", err) + return } } - // Decode non-nil value. - _n, err = cdc.decodeReflectBinary(bz, einfo, erv, opts) - if slide(&bz, &n, _n) && err != nil { - return + // Ensure that there are no more elements left, + // and no field number regression either. + // This is to provide better error messages. + if len(bz) > 0 { + var fnum = uint32(0) + fnum, _, _, err = decodeFieldNumberAndTyp3(bz) + if err != nil { + return + } + if fnum <= fopts.BinFieldNum { + err = fmt.Errorf("unexpected field number %v after repeated field number %v", fnum, fopts.BinFieldNum) + return + } } } return } // CONTRACT: rv.CanAddr() is true. -func (cdc *Codec) decodeReflectBinaryByteSlice(bz []byte, info *TypeInfo, rv reflect.Value, opts FieldOptions) (n int, err error) { +func (cdc *Codec) decodeReflectBinaryByteSlice(bz []byte, info *TypeInfo, rv reflect.Value, fopts FieldOptions) (n int, err error) { if !rv.CanAddr() { panic("rv not addressable") } @@ -531,7 +547,7 @@ func (cdc *Codec) decodeReflectBinaryByteSlice(bz []byte, info *TypeInfo, rv ref } // CONTRACT: rv.CanAddr() is true. -func (cdc *Codec) decodeReflectBinarySlice(bz []byte, info *TypeInfo, rv reflect.Value, opts FieldOptions) (n int, err error) { +func (cdc *Codec) decodeReflectBinarySlice(bz []byte, info *TypeInfo, rv reflect.Value, fopts FieldOptions, bare bool) (n int, err error) { if !rv.CanAddr() { panic("rv not addressable") } @@ -545,72 +561,98 @@ func (cdc *Codec) decodeReflectBinarySlice(bz []byte, info *TypeInfo, rv reflect if ert.Kind() == reflect.Uint8 { panic("should not happen") } - einfo := (*TypeInfo)(nil) - einfo, err = cdc.getTypeInfo_wlock(ert) + einfo, err := cdc.getTypeInfo_wlock(ert) if err != nil { return } - // Check and consume typ4 byte. - var ptr, _n = false, int(0) - ptr, _n, err = decodeTyp4AndCheck(ert, bz, opts) - if slide(&bz, &n, _n) && err != nil { - return - } + // Construct slice to collect decoded items to. + // NOTE: This is due to Proto3. How to best optimize? + esrt := reflect.SliceOf(ert) + var srv = reflect.Zero(esrt) - // Read number of items. - var count = uint64(0) - count, _n, err = DecodeUvarint(bz) - if slide(&bz, &n, _n) && err != nil { - return - } - if int(count) < 0 { - err = fmt.Errorf("Impossible number of elements (%v)", count) - return - } - if int(count) > len(bz) { // Currently, each item takes at least 1 byte. - err = fmt.Errorf("Impossible number of elements (%v) compared to buffer length (%v)", - count, len(bz)) - return - } - - // Special case when length is 0. - // NOTE: We prefer nil slices. - if count == 0 { - rv.Set(info.ZeroValue) - return + if !bare { + // Read byte-length prefixed byteslice. + var buf, _n = []byte(nil), int(0) + buf, _n, err = DecodeByteSlice(bz) + if slide(&bz, nil, _n) && err != nil { + return + } + // This is a trick for debuggability -- we slide on &n more later. + n += UvarintSize(uint64(len(buf))) + bz = buf } - // Read each item. - // NOTE: Unlike decodeReflectBinaryArray, - // we need to construct a new slice before - // we populate it. Arrays on the other hand - // reserve space in the value itself. - var esrt = reflect.SliceOf(ert) // TODO could be optimized. - var srv = reflect.MakeSlice(esrt, int(count), int(count)) - for i := 0; i < int(count); i++ { - var erv, _n = srv.Index(i), int(0) - // Maybe read nil. - if ptr { - var numNil = int64(0) - numNil, _n, err = decodeNumNilBytes(bz) + // If elem is not already a ByteLength type, read in packed form. + // This is a Proto wart due to Proto backwards compatibility issues. + // Amino2 will probably migrate to use the List typ3. + typ3 := typeToTyp3(einfo.Type, fopts) + if typ3 != Typ3_ByteLength { + // Read elems in packed form. + for { + if len(bz) == 0 { + break + } + erv, _n := reflect.New(ert).Elem(), int(0) + _n, err = cdc.decodeReflectBinary(bz, einfo, erv, fopts, false) if slide(&bz, &n, _n) && err != nil { + err = fmt.Errorf("error reading array contents: %v", err) return } - if numNil == 0 { - // Good, continue decoding item. - } else if numNil == 1 { - // Set nil/zero. + // Special case when reading default value, prefer nil. + if ert.Kind() == reflect.Ptr { + _, isDefault := isDefaultValue(erv) + if isDefault { + srv = reflect.Append(srv, reflect.Zero(ert)) + continue + } + } + // Otherwise append to slice. + srv = reflect.Append(srv, erv) + } + } else { + // Read elements in unpacked form. + for { + if len(bz) == 0 { + break + } + // Read field key (number and type). + var fnum, typ, _n = uint32(0), Typ3(0x00), int(0) + fnum, typ, _n, err = decodeFieldNumberAndTyp3(bz) + // Validate field number and typ3. + if fnum < fopts.BinFieldNum { + err = errors.New(fmt.Sprintf("expected repeated field number %v or greater, got %v", fopts.BinFieldNum, fnum)) + return + } + if fnum > fopts.BinFieldNum { + break + } + if typ != Typ3_ByteLength { + err = errors.New(fmt.Sprintf("expected repeated field type %v, got %v", Typ3_ByteLength, typ)) + return + } + if slide(&bz, &n, _n) && err != nil { + return + } + // Decode the next ByteLength bytes into erv. + erv, _n := reflect.New(ert).Elem(), int(0) + // Special case if next ByteLength bytes are 0x00, set nil. + if len(bz) > 0 && bz[0] == 0x00 { + slide(&bz, &n, 1) erv.Set(reflect.Zero(erv.Type())) + srv = reflect.Append(srv, erv) continue - } else { - panic("should not happen") } - } - // Decode non-nil value. - _n, err = cdc.decodeReflectBinary(bz, einfo, erv, opts) - if slide(&bz, &n, _n) && err != nil { - return + // Normal case, read next non-nil element from bz. + // In case of any inner lists in unpacked form. + efopts := fopts + efopts.BinFieldNum = 1 + _n, err = cdc.decodeReflectBinary(bz, einfo, erv, efopts, false) + if slide(&bz, &n, _n) && err != nil { + err = fmt.Errorf("error reading array contents: %v", err) + return + } + srv = reflect.Append(srv, erv) } } rv.Set(srv) @@ -618,7 +660,7 @@ func (cdc *Codec) decodeReflectBinarySlice(bz []byte, info *TypeInfo, rv reflect } // CONTRACT: rv.CanAddr() is true. -func (cdc *Codec) decodeReflectBinaryStruct(bz []byte, info *TypeInfo, rv reflect.Value, _ FieldOptions) (n int, err error) { +func (cdc *Codec) decodeReflectBinaryStruct(bz []byte, info *TypeInfo, rv reflect.Value, _ FieldOptions, bare bool) (n int, err error) { if !rv.CanAddr() { panic("rv not addressable") } @@ -630,9 +672,21 @@ func (cdc *Codec) decodeReflectBinaryStruct(bz []byte, info *TypeInfo, rv reflec } _n := 0 // nolint: ineffassign - // The "Struct" typ3 doesn't get read here. + // NOTE: The "Struct" typ3 doesn't get read here. // It's already implied, either by struct-key or list-element-type-byte. + if !bare { + // Read byte-length prefixed byteslice. + var buf, _n = []byte(nil), int(0) + buf, _n, err = DecodeByteSlice(bz) + if slide(&bz, nil, _n) && err != nil { + return + } + // This is a trick for debuggability -- we slide on &n more later. + n += UvarintSize(uint64(len(buf))) + bz = buf + } + switch info.Type { case timeType: @@ -643,9 +697,10 @@ func (cdc *Codec) decodeReflectBinaryStruct(bz []byte, info *TypeInfo, rv reflec return } rv.Set(reflect.ValueOf(t)) - return default: + // Track the last seen field number. + var lastFieldNum uint32 // Read each field. for _, field := range info.Fields { @@ -657,81 +712,157 @@ func (cdc *Codec) decodeReflectBinaryStruct(bz []byte, info *TypeInfo, rv reflec return } - // Read field key (number and type). - var fieldNum, typ = uint32(0), Typ3(0x00) - fieldNum, typ, _n, err = decodeFieldNumberAndTyp3(bz) - if field.BinFieldNum < fieldNum { - // Set nil field value. + // We're done if we've consumed all the bytes. + if len(bz) == 0 { frv.Set(reflect.Zero(frv.Type())) continue - // Do not slide, we will read it again. } - if fieldNum == 0 { - // Probably a StructTerm. - break + + if field.UnpackedList { + // This is a list that was encoded unpacked, e.g. + // with repeated field entries for each list item. + _n, err = cdc.decodeReflectBinary(bz, finfo, frv, field.FieldOptions, true) + if slide(&bz, &n, _n) && err != nil { + return + } + } else { + // Read field key (number and type). + var fnum, typ = uint32(0), Typ3(0x00) + fnum, typ, _n, err = decodeFieldNumberAndTyp3(bz) + if field.BinFieldNum < fnum { + // Set zero field value. + frv.Set(reflect.Zero(frv.Type())) + continue + // Do not slide, we will read it again. + } + if fnum <= lastFieldNum { + err = fmt.Errorf("encountered fieldnNum: %v, but we have already seen fnum: %v\nbytes:%X", + fnum, lastFieldNum, bz) + return + } + lastFieldNum = fnum + if slide(&bz, &n, _n) && err != nil { + return + } + + // Validate fnum and typ. + // NOTE: In the future, we'll support upgradeability. + // So in the future, this may not match, + // so we will need to remove this sanity check. + if field.BinFieldNum != fnum { + err = errors.New(fmt.Sprintf("expected field # %v of %v, got %v", + field.BinFieldNum, info.Type, fnum)) + return + } + typWanted := typeToTyp3(finfo.Type, field.FieldOptions) + if typ != typWanted { + err = errors.New(fmt.Sprintf("expected field type %v for # %v of %v, got %v", + typWanted, fnum, info.Type, typ)) + return + } + + // Decode field into frv. + _n, err = cdc.decodeReflectBinary(bz, finfo, frv, field.FieldOptions, false) + if slide(&bz, &n, _n) && err != nil { + return + } } + } + + // Consume any remaining fields. + var _n, fnum = 0, uint32(0) + var typ3 Typ3 + for len(bz) > 0 { + fnum, typ3, _n, err = decodeFieldNumberAndTyp3(bz) if slide(&bz, &n, _n) && err != nil { return } - // NOTE: In the future, we'll support upgradeability. - // So in the future, this may not match, - // so we will need to remove this sanity check. - if field.BinFieldNum != fieldNum { - err = errors.New(fmt.Sprintf("Expected field number %v, got %v", field.BinFieldNum, fieldNum)) - return - } - typWanted := typeToTyp4(field.Type, field.FieldOptions).Typ3() - if typ != typWanted { - err = errors.New(fmt.Sprintf("Expected field type %X, got %X", typWanted, typ)) + if fnum <= lastFieldNum { + err = fmt.Errorf("encountered fieldnNum: %v, but we have already seen fnum: %v\nbytes:%X", + fnum, lastFieldNum, bz) return } + lastFieldNum = fnum - // Decode field into frv. - _n, err = cdc.decodeReflectBinary(bz, finfo, frv, field.FieldOptions) + _n, err = consumeAny(typ3, bz) if slide(&bz, &n, _n) && err != nil { return } } + } + return +} + +//---------------------------------------- +// consume* for skipping struct fields - // Read "StructTerm". - // NOTE: In the future, we'll need to break out of a loop - // when encoutering an StructTerm typ3 byte. - var typ = Typ3(0x00) - typ, _n, err = decodeTyp3(bz) +// Read everything without doing anything with it. Report errors if they occur. +func consumeAny(typ3 Typ3, bz []byte) (n int, err error) { + var _n int + switch typ3 { + case Typ3_Varint: + _, _n, err = DecodeVarint(bz) + case Typ3_8Byte: + _, _n, err = DecodeInt64(bz) + case Typ3_ByteLength: + _, _n, err = DecodeByteSlice(bz) + case Typ3_4Byte: + _, _n, err = DecodeInt32(bz) + default: + err = fmt.Errorf("invalid typ3 bytes %v", typ3) + return + } + if err != nil { + // do not slide + return + } + slide(&bz, &n, _n) + return +} + +func consumeStruct(bz []byte) (n int, err error) { + var _n, typ = int(0), Typ3(0x00) + for { + typ, _n, err = consumeFieldKey(bz) if slide(&bz, &n, _n) && err != nil { return } - if typ != Typ3_StructTerm { - err = errors.New(fmt.Sprintf("Expected StructTerm typ3 byte, got %X", typ)) + _n, err = consumeAny(typ, bz) + if slide(&bz, &n, _n) && err != nil { return } + } + return +} + +func consumeFieldKey(bz []byte) (typ Typ3, n int, err error) { + var u64 uint64 + u64, n = binary.Uvarint(bz) + if n < 0 { + n = 0 + err = errors.New("error decoding uvarint") return } + typ = Typ3(u64 & 0x07) + return } //---------------------------------------- -func DecodeDisambPrefixBytes(bz []byte) (db DisambBytes, hasDb bool, pb PrefixBytes, typ Typ3, hasPb bool, isNil bool, n int, err error) { - // Special case: nil - if len(bz) >= 2 && bz[0] == 0x00 && bz[1] == 0x00 { - isNil = true - n = 2 - return - } +func DecodeDisambPrefixBytes(bz []byte) (db DisambBytes, hasDb bool, pb PrefixBytes, hasPb bool, n int, err error) { // Validate if len(bz) < 4 { - err = errors.New("EOF reading prefix bytes.") + err = errors.New("EOF while reading prefix bytes.") return // hasPb = false } if bz[0] == 0x00 { // Disfix // Validate if len(bz) < 8 { - err = errors.New("EOF reading disamb bytes.") + err = errors.New("EOF while reading disamb bytes.") return // hasPb = false } copy(db[0:3], bz[1:4]) copy(pb[0:4], bz[4:8]) - pb, typ = pb.SplitTyp3() hasDb = true hasPb = true n = 8 @@ -739,7 +870,6 @@ func DecodeDisambPrefixBytes(bz []byte) (db DisambBytes, hasDb bool, pb PrefixBy } else { // Prefix // General case with no disambiguation copy(pb[0:4], bz[0:4]) - pb, typ = pb.SplitTyp3() hasDb = false hasPb = true n = 4 @@ -764,49 +894,18 @@ func decodeFieldNumberAndTyp3(bz []byte) (num uint32, typ Typ3, n int, err error var num64 uint64 num64 = value64 >> 3 if num64 > (1<<29 - 1) { - err = errors.New(fmt.Sprintf("invalid field num %v", num64)) + err = fmt.Errorf("invalid field num %v", num64) return } num = uint32(num64) return } -// Consume typ4 byte and error if it doesn't match rt. -func decodeTyp4AndCheck(rt reflect.Type, bz []byte, opts FieldOptions) (ptr bool, n int, err error) { - var typ = Typ4(0x00) - typ, n, err = decodeTyp4(bz) - if err != nil { - return - } - var typWanted = typeToTyp4(rt, opts) - if typWanted != typ { - err = errors.New(fmt.Sprintf("Typ4 mismatch. Expected %X, got %X", typWanted, typ)) - return - } - ptr = (typ & 0x08) != 0 - return -} - -// Read Typ4 byte. -func decodeTyp4(bz []byte) (typ Typ4, n int, err error) { - if len(bz) == 0 { - err = errors.New(fmt.Sprintf("EOF reading typ4 byte")) - return - } - if bz[0]&0xF0 != 0 { - err = errors.New(fmt.Sprintf("Invalid non-zero nibble reading typ4 byte")) - return - } - typ = Typ4(bz[0]) - n = 1 - return -} - // Error if typ doesn't match rt. -func checkTyp3(rt reflect.Type, typ Typ3, opts FieldOptions) (err error) { - typWanted := typeToTyp3(rt, opts) +func checkTyp3(rt reflect.Type, typ Typ3, fopts FieldOptions) (err error) { + typWanted := typeToTyp3(rt, fopts) if typ != typWanted { - err = fmt.Errorf("Typ3 mismatch. Expected %X, got %X", typWanted, typ) + err = fmt.Errorf("unexpected Typ3. want %v, got %v", typWanted, typ) } return } @@ -814,11 +913,11 @@ func checkTyp3(rt reflect.Type, typ Typ3, opts FieldOptions) (err error) { // Read typ3 byte. func decodeTyp3(bz []byte) (typ Typ3, n int, err error) { if len(bz) == 0 { - err = fmt.Errorf("EOF reading typ3 byte") + err = fmt.Errorf("EOF while reading typ3 byte") return } if bz[0]&0xF8 != 0 { - err = fmt.Errorf("Invalid typ3 byte") + err = fmt.Errorf("invalid typ3 byte: %v", Typ3(bz[0]).String()) return } typ = Typ3(bz[0]) @@ -831,7 +930,7 @@ func decodeTyp3(bz []byte) (typ Typ3, n int, err error) { // other values will error. func decodeNumNilBytes(bz []byte) (numNil int64, n int, err error) { if len(bz) == 0 { - err = errors.New("EOF reading nil byte(s)") + err = errors.New("EOF while reading nil byte(s)") return } if bz[0] == 0x00 { @@ -842,6 +941,6 @@ func decodeNumNilBytes(bz []byte) (numNil int64, n int, err error) { numNil, n = 1, 1 return } - n, err = 0, fmt.Errorf("Unexpected nil byte %X (sparse lists not supported)", bz[0]) + n, err = 0, fmt.Errorf("unexpected nil byte, want: either '0x00' or '0x01' got: %X (sparse lists not supported)", bz[0]) return } diff --git a/vendor/github.com/tendermint/go-amino/binary-encode.go b/vendor/github.com/tendermint/go-amino/binary-encode.go index e141d4d22..9f7e5831a 100644 --- a/vendor/github.com/tendermint/go-amino/binary-encode.go +++ b/vendor/github.com/tendermint/go-amino/binary-encode.go @@ -1,6 +1,7 @@ package amino import ( + "bytes" "encoding/binary" "errors" "fmt" @@ -21,7 +22,7 @@ import ( // The following contracts apply to all similar encode methods. // CONTRACT: rv is not a pointer // CONTRACT: rv is valid. -func (cdc *Codec) encodeReflectBinary(w io.Writer, info *TypeInfo, rv reflect.Value, opts FieldOptions) (err error) { +func (cdc *Codec) encodeReflectBinary(w io.Writer, info *TypeInfo, rv reflect.Value, fopts FieldOptions, bare bool) (err error) { if rv.Kind() == reflect.Ptr { panic("should not happen") } @@ -29,42 +30,13 @@ func (cdc *Codec) encodeReflectBinary(w io.Writer, info *TypeInfo, rv reflect.Va panic("should not happen") } if printLog { - spew.Printf("(E) encodeReflectBinary(info: %v, rv: %#v (%v), opts: %v)\n", - info, rv.Interface(), rv.Type(), opts) + spew.Printf("(E) encodeReflectBinary(info: %v, rv: %#v (%v), fopts: %v)\n", + info, rv.Interface(), rv.Type(), fopts) defer func() { fmt.Printf("(E) -> err: %v\n", err) }() } - // Maybe write prefix+typ3 bytes. - if info.Registered { - var typ = typeToTyp4(info.Type, opts).Typ3() - _, err = w.Write(info.Prefix.WithTyp3(typ).Bytes()) - if err != nil { - return - } - } - - err = cdc._encodeReflectBinary(w, info, rv, opts) - return -} - -// CONTRACT: any disamb/prefix+typ3 bytes have already been written. -func (cdc *Codec) _encodeReflectBinary(w io.Writer, info *TypeInfo, rv reflect.Value, opts FieldOptions) (err error) { - if rv.Kind() == reflect.Ptr { - panic("should not happen") - } - if !rv.IsValid() { - panic("should not happen") - } - if printLog { - spew.Printf("(_) _encodeReflectBinary(info: %v, rv: %#v (%v), opts: %v)\n", - info, rv.Interface(), rv.Type(), opts) - defer func() { - fmt.Printf("(_) -> err: %v\n", err) - }() - } - // Handle override if rv implements json.Marshaler. if info.IsAminoMarshaler { // First, encode rv into repr instance. @@ -78,7 +50,7 @@ func (cdc *Codec) _encodeReflectBinary(w io.Writer, info *TypeInfo, rv reflect.V return } // Then, encode the repr instance. - err = cdc._encodeReflectBinary(w, rinfo, rrv, opts) + err = cdc.encodeReflectBinary(w, rinfo, rrv, fopts, bare) return } @@ -88,37 +60,41 @@ func (cdc *Codec) _encodeReflectBinary(w io.Writer, info *TypeInfo, rv reflect.V // Complex case reflect.Interface: - err = cdc.encodeReflectBinaryInterface(w, info, rv, opts) + err = cdc.encodeReflectBinaryInterface(w, info, rv, fopts, bare) case reflect.Array: if info.Type.Elem().Kind() == reflect.Uint8 { - err = cdc.encodeReflectBinaryByteArray(w, info, rv, opts) + err = cdc.encodeReflectBinaryByteArray(w, info, rv, fopts) } else { - err = cdc.encodeReflectBinaryList(w, info, rv, opts) + err = cdc.encodeReflectBinaryList(w, info, rv, fopts, bare) } case reflect.Slice: if info.Type.Elem().Kind() == reflect.Uint8 { - err = cdc.encodeReflectBinaryByteSlice(w, info, rv, opts) + err = cdc.encodeReflectBinaryByteSlice(w, info, rv, fopts) } else { - err = cdc.encodeReflectBinaryList(w, info, rv, opts) + err = cdc.encodeReflectBinaryList(w, info, rv, fopts, bare) } case reflect.Struct: - err = cdc.encodeReflectBinaryStruct(w, info, rv, opts) + err = cdc.encodeReflectBinaryStruct(w, info, rv, fopts, bare) //---------------------------------------- // Signed case reflect.Int64: - if opts.BinVarint { - err = EncodeVarint(w, rv.Int()) - } else { + if fopts.BinFixed64 { err = EncodeInt64(w, rv.Int()) + } else { + err = EncodeVarint(w, rv.Int()) } case reflect.Int32: - err = EncodeInt32(w, int32(rv.Int())) + if fopts.BinFixed32 { + err = EncodeInt32(w, int32(rv.Int())) + } else { + err = EncodeVarint(w, rv.Int()) + } case reflect.Int16: err = EncodeInt16(w, int16(rv.Int())) @@ -133,14 +109,18 @@ func (cdc *Codec) _encodeReflectBinary(w io.Writer, info *TypeInfo, rv reflect.V // Unsigned case reflect.Uint64: - if opts.BinVarint { - err = EncodeUvarint(w, rv.Uint()) - } else { + if fopts.BinFixed64 { err = EncodeUint64(w, rv.Uint()) + } else { + err = EncodeUvarint(w, rv.Uint()) } case reflect.Uint32: - err = EncodeUint32(w, uint32(rv.Uint())) + if fopts.BinFixed32 { + err = EncodeUint32(w, uint32(rv.Uint())) + } else { + err = EncodeUvarint(w, rv.Uint()) + } case reflect.Uint16: err = EncodeUint16(w, uint16(rv.Uint())) @@ -158,14 +138,14 @@ func (cdc *Codec) _encodeReflectBinary(w io.Writer, info *TypeInfo, rv reflect.V err = EncodeBool(w, rv.Bool()) case reflect.Float64: - if !opts.Unsafe { + if !fopts.Unsafe { err = errors.New("Amino float* support requires `amino:\"unsafe\"`.") return } err = EncodeFloat64(w, rv.Float()) case reflect.Float32: - if !opts.Unsafe { + if !fopts.Unsafe { err = errors.New("Amino float* support requires `amino:\"unsafe\"`.") return } @@ -184,7 +164,7 @@ func (cdc *Codec) _encodeReflectBinary(w io.Writer, info *TypeInfo, rv reflect.V return } -func (cdc *Codec) encodeReflectBinaryInterface(w io.Writer, iinfo *TypeInfo, rv reflect.Value, opts FieldOptions) (err error) { +func (cdc *Codec) encodeReflectBinaryInterface(w io.Writer, iinfo *TypeInfo, rv reflect.Value, fopts FieldOptions, bare bool) (err error) { if printLog { fmt.Println("(e) encodeReflectBinaryInterface") defer func() { @@ -192,9 +172,9 @@ func (cdc *Codec) encodeReflectBinaryInterface(w io.Writer, iinfo *TypeInfo, rv }() } - // Special case when rv is nil, write 0x0000. + // Special case when rv is nil, write 0x00 to denote an empty byteslice. if rv.IsNil() { - _, err = w.Write([]byte{0x00, 0x00}) + _, err = w.Write([]byte{0x00}) return } @@ -221,6 +201,9 @@ func (cdc *Codec) encodeReflectBinaryInterface(w io.Writer, iinfo *TypeInfo, rv return } + // For Proto3 compatibility, encode interfaces as ByteLength. + buf := bytes.NewBuffer(nil) + // Write disambiguation bytes if needed. var needDisamb bool = false if iinfo.AlwaysDisambiguate { @@ -229,25 +212,35 @@ func (cdc *Codec) encodeReflectBinaryInterface(w io.Writer, iinfo *TypeInfo, rv needDisamb = true } if needDisamb { - _, err = w.Write(append([]byte{0x00}, cinfo.Disamb[:]...)) + _, err = buf.Write(append([]byte{0x00}, cinfo.Disamb[:]...)) if err != nil { return } } - // Write prefix+typ3 bytes. - var typ = typeToTyp3(crt, opts) - _, err = w.Write(cinfo.Prefix.WithTyp3(typ).Bytes()) + // Write prefix bytes. + _, err = buf.Write(cinfo.Prefix.Bytes()) if err != nil { return } // Write actual concrete value. - err = cdc._encodeReflectBinary(w, cinfo, crv, opts) + err = cdc.encodeReflectBinary(buf, cinfo, crv, fopts, true) + if err != nil { + return + } + + if bare { + // Write byteslice without byte-length prefixing. + _, err = w.Write(buf.Bytes()) + } else { + // Write byte-length prefixed byteslice. + err = EncodeByteSlice(w, buf.Bytes()) + } return } -func (cdc *Codec) encodeReflectBinaryByteArray(w io.Writer, info *TypeInfo, rv reflect.Value, opts FieldOptions) (err error) { +func (cdc *Codec) encodeReflectBinaryByteArray(w io.Writer, info *TypeInfo, rv reflect.Value, fopts FieldOptions) (err error) { ert := info.Type.Elem() if ert.Kind() != reflect.Uint8 { panic("should not happen") @@ -268,7 +261,7 @@ func (cdc *Codec) encodeReflectBinaryByteArray(w io.Writer, info *TypeInfo, rv r return } -func (cdc *Codec) encodeReflectBinaryList(w io.Writer, info *TypeInfo, rv reflect.Value, opts FieldOptions) (err error) { +func (cdc *Codec) encodeReflectBinaryList(w io.Writer, info *TypeInfo, rv reflect.Value, fopts FieldOptions, bare bool) (err error) { if printLog { fmt.Println("(e) encodeReflectBinaryList") defer func() { @@ -279,57 +272,71 @@ func (cdc *Codec) encodeReflectBinaryList(w io.Writer, info *TypeInfo, rv reflec if ert.Kind() == reflect.Uint8 { panic("should not happen") } - - // Write element Typ4 byte. - var typ = typeToTyp4(ert, opts) - err = EncodeByte(w, byte(typ)) - if err != nil { - return - } - - // Write length. - err = EncodeUvarint(w, uint64(rv.Len())) + einfo, err := cdc.getTypeInfo_wlock(ert) if err != nil { return } - // Write elems. - var einfo *TypeInfo - einfo, err = cdc.getTypeInfo_wlock(ert) - if err != nil { - return - } - for i := 0; i < rv.Len(); i++ { - // Get dereferenced element value and info. - var erv, void = isVoid(rv.Index(i)) - if typ.IsPointer() { - // We must write a byte to denote whether element is nil. - if void { - // Value is nil or empty. - // e.g. nil pointer, nil/empty slice, pointer to nil/empty slice, pointer - // to nil pointer. Write 0x01 for "is nil". - // NOTE: Do not use a pointer to nil/empty slices to denote - // existence or not. We have to make a design choice here, and - // here we discourage using pointers to denote existence. - _, err = w.Write([]byte{0x01}) - continue - } else { - // Value is not nil or empty. Write 0x00 for "not nil/empty". - _, err = w.Write([]byte{0x00}) + // Proto3 byte-length prefixing incurs alloc cost on the encoder. + // Here we incur it for unpacked form for ease of dev. + buf := bytes.NewBuffer(nil) + + // If elem is not already a ByteLength type, write in packed form. + // This is a Proto wart due to Proto backwards compatibility issues. + // Amino2 will probably migrate to use the List typ3. Please? :) + typ3 := typeToTyp3(einfo.Type, fopts) + if typ3 != Typ3_ByteLength { + // Write elems in packed form. + for i := 0; i < rv.Len(); i++ { + // Get dereferenced element value (or zero). + var erv, _, _ = derefPointersZero(rv.Index(i)) + // Write the element value. + err = cdc.encodeReflectBinary(buf, einfo, erv, fopts, false) + if err != nil { + return } } - // Write the element value. - // It may be a nil interface, but not a nil pointer. - err = cdc.encodeReflectBinary(w, einfo, erv, opts) - if err != nil { - return + } else { + // Write elems in unpacked form. + for i := 0; i < rv.Len(); i++ { + // Write elements as repeated fields of the parent struct. + err = encodeFieldNumberAndTyp3(buf, fopts.BinFieldNum, Typ3_ByteLength) + if err != nil { + return + } + // Get dereferenced element value and info. + var erv, isDefault = isDefaultValue(rv.Index(i)) + if isDefault { + // Nothing to encode, so the length is 0. + err = EncodeByte(buf, byte(0x00)) + if err != nil { + return + } + } else { + // Write the element value as a ByteLength. + // In case of any inner lists in unpacked form. + efopts := fopts + efopts.BinFieldNum = 1 + err = cdc.encodeReflectBinary(buf, einfo, erv, efopts, false) + if err != nil { + return + } + } } } + + if bare { + // Write byteslice without byte-length prefixing. + _, err = w.Write(buf.Bytes()) + } else { + // Write byte-length prefixed byteslice. + err = EncodeByteSlice(w, buf.Bytes()) + } return } // CONTRACT: info.Type.Elem().Kind() == reflect.Uint8 -func (cdc *Codec) encodeReflectBinaryByteSlice(w io.Writer, info *TypeInfo, rv reflect.Value, opts FieldOptions) (err error) { +func (cdc *Codec) encodeReflectBinaryByteSlice(w io.Writer, info *TypeInfo, rv reflect.Value, fopts FieldOptions) (err error) { if printLog { fmt.Println("(e) encodeReflectBinaryByteSlice") defer func() { @@ -347,7 +354,7 @@ func (cdc *Codec) encodeReflectBinaryByteSlice(w io.Writer, info *TypeInfo, rv r return } -func (cdc *Codec) encodeReflectBinaryStruct(w io.Writer, info *TypeInfo, rv reflect.Value, opts FieldOptions) (err error) { +func (cdc *Codec) encodeReflectBinaryStruct(w io.Writer, info *TypeInfo, rv reflect.Value, fopts FieldOptions, bare bool) (err error) { if printLog { fmt.Println("(e) encodeReflectBinaryBinaryStruct") defer func() { @@ -355,51 +362,62 @@ func (cdc *Codec) encodeReflectBinaryStruct(w io.Writer, info *TypeInfo, rv refl }() } - // The "Struct" Typ3 doesn't get written here. - // It's already implied, either by struct-key or list-element-type-byte. + // Proto3 incurs a cost in writing non-root structs. + // Here we incur it for root structs as well for ease of dev. + buf := bytes.NewBuffer(nil) switch info.Type { case timeType: // Special case: time.Time - err = EncodeTime(w, rv.Interface().(time.Time)) - return + err = EncodeTime(buf, rv.Interface().(time.Time)) + if err != nil { + return + } default: for _, field := range info.Fields { - // Get dereferenced field value and info. - var frv, void = isVoid(rv.Field(field.Index)) - if void { - // Do not encode nil or empty fields. - continue - } + // Get type info for field. var finfo *TypeInfo finfo, err = cdc.getTypeInfo_wlock(field.Type) if err != nil { return } - // TODO Maybe allow omitempty somehow. - // Write field key (number and type). - err = encodeFieldNumberAndTyp3(w, field.BinFieldNum, field.BinTyp3) - if err != nil { - return + // Get dereferenced field value and info. + var frv, isDefault = isDefaultValue(rv.Field(field.Index)) + if isDefault { + // Do not encode default value fields. + continue } - // Write field from rv. - err = cdc.encodeReflectBinary(w, finfo, frv, field.FieldOptions) - if err != nil { - return + if field.UnpackedList { + // Write repeated field entries for each list item. + err = cdc.encodeReflectBinaryList(buf, finfo, frv, field.FieldOptions, true) + if err != nil { + return + } + } else { + // Write field key (number and type). + err = encodeFieldNumberAndTyp3(buf, field.BinFieldNum, typeToTyp3(finfo.Type, field.FieldOptions)) + if err != nil { + return + } + // Write field from rv. + err = cdc.encodeReflectBinary(buf, finfo, frv, field.FieldOptions, false) + if err != nil { + return + } } } - - // Write "StructTerm". - err = EncodeByte(w, byte(Typ3_StructTerm)) - if err != nil { - return - } - return - } + if bare { + // Write byteslice without byte-length prefixing. + _, err = w.Write(buf.Bytes()) + } else { + // Write byte-length prefixed byteslice. + err = EncodeByteSlice(w, buf.Bytes()) + } + return } //---------------------------------------- @@ -408,7 +426,7 @@ func (cdc *Codec) encodeReflectBinaryStruct(w io.Writer, info *TypeInfo, rv refl // Write field key. func encodeFieldNumberAndTyp3(w io.Writer, num uint32, typ Typ3) (err error) { if (typ & 0xF8) != 0 { - panic(fmt.Sprintf("invalid Typ3 byte %X", typ)) + panic(fmt.Sprintf("invalid Typ3 byte %v", typ)) } if num < 0 || num > (1<<29-1) { panic(fmt.Sprintf("invalid field number %v", num)) diff --git a/vendor/github.com/tendermint/go-amino/codec.go b/vendor/github.com/tendermint/go-amino/codec.go index 30af7e7e8..605b9993a 100644 --- a/vendor/github.com/tendermint/go-amino/codec.go +++ b/vendor/github.com/tendermint/go-amino/codec.go @@ -4,6 +4,7 @@ import ( "bytes" "crypto/sha256" "fmt" + "io" "reflect" "strings" "sync" @@ -34,14 +35,8 @@ func NewPrefixBytes(prefixBytes []byte) PrefixBytes { return pb } -func (pb PrefixBytes) Bytes() []byte { return pb[:] } -func (pb PrefixBytes) EqualBytes(bz []byte) bool { return bytes.Equal(pb[:], bz) } -func (pb PrefixBytes) WithTyp3(typ Typ3) PrefixBytes { pb[3] |= byte(typ); return pb } -func (pb PrefixBytes) SplitTyp3() (PrefixBytes, Typ3) { - typ := Typ3(pb[3] & 0x07) - pb[3] &= 0xF8 - return pb, typ -} +func (pb PrefixBytes) Bytes() []byte { return pb[:] } +func (pb PrefixBytes) EqualBytes(bz []byte) bool { return bytes.Equal(pb[:], bz) } func (db DisambBytes) Bytes() []byte { return db[:] } func (db DisambBytes) EqualBytes(bz []byte) bool { return bytes.Equal(db[:], bz) } func (df DisfixBytes) Bytes() []byte { return df[:] } @@ -79,12 +74,13 @@ type InterfaceOptions struct { type ConcreteInfo struct { // These fields are only set when registered (as implementing an interface). - Registered bool // Registered with RegisterConcrete(). - PointerPreferred bool // Deserialize to pointer type if possible. - Name string // Registered name. - Disamb DisambBytes // Disambiguation bytes derived from name. - Prefix PrefixBytes // Prefix bytes derived from name. - ConcreteOptions // Registration options. + Registered bool // Registered with RegisterConcrete(). + PointerPreferred bool // Deserialize to pointer type if possible. + // NilPreferred bool // Deserialize to nil for empty structs if PointerPreferred. + Name string // Registered name. + Disamb DisambBytes // Disambiguation bytes derived from name. + Prefix PrefixBytes // Prefix bytes derived from name. + ConcreteOptions // Registration options. // These fields get set for all concrete types, // even those not manually registered (e.g. are never interface values). @@ -110,14 +106,15 @@ type FieldInfo struct { Type reflect.Type // Struct field type Index int // Struct field index ZeroValue reflect.Value // Could be nil pointer unlike TypeInfo.ZeroValue. + UnpackedList bool // True iff this field should be encoded as an unpacked list. FieldOptions // Encoding options - BinTyp3 Typ3 // (Binary) Typ3 byte } type FieldOptions struct { JSONName string // (JSON) field name JSONOmitEmpty bool // (JSON) omitempty - BinVarint bool // (Binary) Use length-prefixed encoding for (u)int64. + BinFixed64 bool // (Binary) Encode as fixed64 + BinFixed32 bool // (Binary) Encode as fixed32 BinFieldNum uint32 // (Binary) max 1<<29-1 Unsafe bool // e.g. if this field is a float. } @@ -127,16 +124,20 @@ type FieldOptions struct { type Codec struct { mtx sync.RWMutex + sealed bool typeInfos map[reflect.Type]*TypeInfo interfaceInfos []*TypeInfo concreteInfos []*TypeInfo disfixToTypeInfo map[DisfixBytes]*TypeInfo + nameToTypeInfo map[string]*TypeInfo } func NewCodec() *Codec { cdc := &Codec{ + sealed: false, typeInfos: make(map[reflect.Type]*TypeInfo), disfixToTypeInfo: make(map[DisfixBytes]*TypeInfo), + nameToTypeInfo: make(map[string]*TypeInfo), } return cdc } @@ -145,7 +146,8 @@ func NewCodec() *Codec { // encoded/decoded by go-amino. // Usage: // `amino.RegisterInterface((*MyInterface1)(nil), nil)` -func (cdc *Codec) RegisterInterface(ptr interface{}, opts *InterfaceOptions) { +func (cdc *Codec) RegisterInterface(ptr interface{}, iopts *InterfaceOptions) { + cdc.assertNotSealed() // Get reflect.Type from ptr. rt := getTypeFromPointer(ptr) @@ -154,7 +156,7 @@ func (cdc *Codec) RegisterInterface(ptr interface{}, opts *InterfaceOptions) { } // Construct InterfaceInfo - var info = cdc.newTypeInfoFromInterfaceType(rt, opts) + var info = cdc.newTypeInfoFromInterfaceType(rt, iopts) // Finally, check conflicts and register. func() { @@ -199,7 +201,8 @@ func (cdc *Codec) RegisterInterface(ptr interface{}, opts *InterfaceOptions) { // interface fields/elements to be encoded/decoded by go-amino. // Usage: // `amino.RegisterConcrete(MyStruct1{}, "com.tendermint/MyStruct1", nil)` -func (cdc *Codec) RegisterConcrete(o interface{}, name string, opts *ConcreteOptions) { +func (cdc *Codec) RegisterConcrete(o interface{}, name string, copts *ConcreteOptions) { + cdc.assertNotSealed() var pointerPreferred bool @@ -222,7 +225,7 @@ func (cdc *Codec) RegisterConcrete(o interface{}, name string, opts *ConcreteOpt } // Construct ConcreteInfo. - var info = cdc.newTypeInfoFromRegisteredConcreteType(rt, pointerPreferred, name, opts) + var info = cdc.newTypeInfoFromRegisteredConcreteType(rt, pointerPreferred, name, copts) // Finally, check conflicts and register. func() { @@ -234,8 +237,95 @@ func (cdc *Codec) RegisterConcrete(o interface{}, name string, opts *ConcreteOpt }() } +func (cdc *Codec) Seal() *Codec { + cdc.mtx.Lock() + defer cdc.mtx.Unlock() + + cdc.sealed = true + return cdc +} + +// PrintTypes writes all registered types in a markdown-style table. +// The table's header is: +// +// | Type | Name | Prefix | Notes | +// +// Where Type is the golang type name and Name is the name the type was registered with. +func (cdc Codec) PrintTypes(out io.Writer) error { + cdc.mtx.RLock() + defer cdc.mtx.RUnlock() + // print header + if _, err := io.WriteString(out, "| Type | Name | Prefix | Length | Notes |\n"); err != nil { + return err + } + if _, err := io.WriteString(out, "| ---- | ---- | ------ | ----- | ------ |\n"); err != nil { + return err + } + // only print concrete types for now (if we want everything, we can iterate over the typeInfos map instead) + for _, i := range cdc.concreteInfos { + io.WriteString(out, "| ") + // TODO(ismail): optionally create a link to code on github: + if _, err := io.WriteString(out, i.Type.Name()); err != nil { + return err + } + if _, err := io.WriteString(out, " | "); err != nil { + return err + } + if _, err := io.WriteString(out, i.Name); err != nil { + return err + } + if _, err := io.WriteString(out, " | "); err != nil { + return err + } + if _, err := io.WriteString(out, fmt.Sprintf("0x%X", i.Prefix)); err != nil { + return err + } + if _, err := io.WriteString(out, " | "); err != nil { + return err + } + + if _, err := io.WriteString(out, getLengthStr(i)); err != nil { + return err + } + + if _, err := io.WriteString(out, " | "); err != nil { + return err + } + // empty notes table data by default // TODO(ismail): make this configurable + + io.WriteString(out, " |\n") + } + // finish table + return nil +} + +// A heuristic to guess the size of a registered type and return it as a string. +// If the size is not fixed it returns "variable". +func getLengthStr(info *TypeInfo) string { + switch info.Type.Kind() { + case reflect.Array, + reflect.Int8, + reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Float32, reflect.Float64, + reflect.Complex64, reflect.Complex128: + s := info.Type.Size() + return fmt.Sprintf("0x%X", s) + default: + return "variable" + } +} + //---------------------------------------- +func (cdc *Codec) assertNotSealed() { + cdc.mtx.Lock() + defer cdc.mtx.Unlock() + + if cdc.sealed { + panic("codec sealed") + } +} + func (cdc *Codec) setTypeInfo_nolock(info *TypeInfo) { if info.Type.Kind() == reflect.Ptr { @@ -254,7 +344,11 @@ func (cdc *Codec) setTypeInfo_nolock(info *TypeInfo) { if existing, ok := cdc.disfixToTypeInfo[disfix]; ok { panic(fmt.Sprintf("disfix <%X> already registered for %v", disfix, existing.Type)) } + if existing, ok := cdc.nameToTypeInfo[info.Name]; ok { + panic(fmt.Sprintf("name <%s> already registered for %v", info.Name, existing.Type)) + } cdc.disfixToTypeInfo[disfix] = info + cdc.nameToTypeInfo[info.Name] = info //cdc.prefixToTypeInfos[prefix] = // append(cdc.prefixToTypeInfos[prefix], info) } @@ -294,7 +388,7 @@ func (cdc *Codec) getTypeInfoFromPrefix_rlock(iinfo *TypeInfo, pb PrefixBytes) ( return } if len(infos) > 1 { - err = fmt.Errorf("Conflicting concrete types registered for %X: e.g. %v and %v.", pb, infos[0].Type, infos[1].Type) + err = fmt.Errorf("conflicting concrete types registered for %X: e.g. %v and %v", pb, infos[0].Type, infos[1].Type) return } info = infos[0] @@ -313,6 +407,18 @@ func (cdc *Codec) getTypeInfoFromDisfix_rlock(df DisfixBytes) (info *TypeInfo, e return } +func (cdc *Codec) getTypeInfoFromName_rlock(name string) (info *TypeInfo, err error) { + cdc.mtx.RLock() + defer cdc.mtx.RUnlock() + + info, ok := cdc.nameToTypeInfo[name] + if !ok { + err = fmt.Errorf("unrecognized concrete type name %s", name) + return + } + return +} + func (cdc *Codec) parseStructInfo(rt reflect.Type) (sinfo StructInfo) { if rt.Kind() != reflect.Struct { panic("should not happen") @@ -322,23 +428,40 @@ func (cdc *Codec) parseStructInfo(rt reflect.Type) (sinfo StructInfo) { for i := 0; i < rt.NumField(); i++ { var field = rt.Field(i) var ftype = field.Type + var unpackedList = false if !isExported(field) { continue // field is unexported } - skip, opts := cdc.parseFieldOptions(field) + skip, fopts := cdc.parseFieldOptions(field) if skip { continue // e.g. json:"-" } + if ftype.Kind() == reflect.Array || ftype.Kind() == reflect.Slice { + if ftype.Elem().Kind() == reflect.Uint8 { + // These get handled by our optimized methods, + // encodeReflectBinaryByte[Slice/Array]. + unpackedList = false + } else { + etype := ftype.Elem() + for etype.Kind() == reflect.Ptr { + etype = etype.Elem() + } + typ3 := typeToTyp3(etype, fopts) + if typ3 == Typ3_ByteLength { + unpackedList = true + } + } + } // NOTE: This is going to change a bit. // NOTE: BinFieldNum starts with 1. - opts.BinFieldNum = uint32(len(infos) + 1) + fopts.BinFieldNum = uint32(len(infos) + 1) fieldInfo := FieldInfo{ Name: field.Name, // Mostly for debugging. Index: i, Type: ftype, ZeroValue: reflect.Zero(ftype), - FieldOptions: opts, - BinTyp3: typeToTyp4(ftype, opts).Typ3(), + UnpackedList: unpackedList, + FieldOptions: fopts, } checkUnsafe(fieldInfo) infos = append(infos, fieldInfo) @@ -347,7 +470,7 @@ func (cdc *Codec) parseStructInfo(rt reflect.Type) (sinfo StructInfo) { return } -func (cdc *Codec) parseFieldOptions(field reflect.StructField) (skip bool, opts FieldOptions) { +func (cdc *Codec) parseFieldOptions(field reflect.StructField) (skip bool, fopts FieldOptions) { binTag := field.Tag.Get("binary") aminoTag := field.Tag.Get("amino") jsonTag := field.Tag.Get("json") @@ -362,26 +485,28 @@ func (cdc *Codec) parseFieldOptions(field reflect.StructField) (skip bool, opts // Get JSON field name. jsonTagParts := strings.Split(jsonTag, ",") if jsonTagParts[0] == "" { - opts.JSONName = field.Name + fopts.JSONName = field.Name } else { - opts.JSONName = jsonTagParts[0] + fopts.JSONName = jsonTagParts[0] } // Get JSON omitempty. if len(jsonTagParts) > 1 { if jsonTagParts[1] == "omitempty" { - opts.JSONOmitEmpty = true + fopts.JSONOmitEmpty = true } } // Parse binary tags. - if binTag == "varint" { // TODO: extend - opts.BinVarint = true + if binTag == "fixed64" { // TODO: extend + fopts.BinFixed64 = true + } else if binTag == "fixed32" { + fopts.BinFixed32 = true } // Parse amino tags. if aminoTag == "unsafe" { - opts.Unsafe = true + fopts.Unsafe = true } return @@ -415,7 +540,7 @@ func (cdc *Codec) newTypeInfoUnregistered(rt reflect.Type) *TypeInfo { return info } -func (cdc *Codec) newTypeInfoFromInterfaceType(rt reflect.Type, opts *InterfaceOptions) *TypeInfo { +func (cdc *Codec) newTypeInfoFromInterfaceType(rt reflect.Type, iopts *InterfaceOptions) *TypeInfo { if rt.Kind() != reflect.Interface { panic(fmt.Sprintf("expected interface type, got %v", rt)) } @@ -426,11 +551,11 @@ func (cdc *Codec) newTypeInfoFromInterfaceType(rt reflect.Type, opts *InterfaceO info.ZeroValue = reflect.Zero(rt) info.ZeroProto = reflect.Zero(rt).Interface() info.InterfaceInfo.Implementers = make(map[PrefixBytes][]*TypeInfo) - if opts != nil { - info.InterfaceInfo.InterfaceOptions = *opts - info.InterfaceInfo.Priority = make([]DisfixBytes, len(opts.Priority)) + if iopts != nil { + info.InterfaceInfo.InterfaceOptions = *iopts + info.InterfaceInfo.Priority = make([]DisfixBytes, len(iopts.Priority)) // Construct Priority []DisfixBytes - for i, name := range opts.Priority { + for i, name := range iopts.Priority { disamb, prefix := nameToDisfix(name) disfix := toDisfix(disamb, prefix) info.InterfaceInfo.Priority[i] = disfix @@ -439,7 +564,7 @@ func (cdc *Codec) newTypeInfoFromInterfaceType(rt reflect.Type, opts *InterfaceO return info } -func (cdc *Codec) newTypeInfoFromRegisteredConcreteType(rt reflect.Type, pointerPreferred bool, name string, opts *ConcreteOptions) *TypeInfo { +func (cdc *Codec) newTypeInfoFromRegisteredConcreteType(rt reflect.Type, pointerPreferred bool, name string, copts *ConcreteOptions) *TypeInfo { if rt.Kind() == reflect.Interface || rt.Kind() == reflect.Ptr { panic(fmt.Sprintf("expected non-interface non-pointer concrete type, got %v", rt)) @@ -451,8 +576,8 @@ func (cdc *Codec) newTypeInfoFromRegisteredConcreteType(rt reflect.Type, pointer info.ConcreteInfo.Name = name info.ConcreteInfo.Disamb = nameToDisamb(name) info.ConcreteInfo.Prefix = nameToPrefix(name) - if opts != nil { - info.ConcreteOptions = *opts + if copts != nil { + info.ConcreteOptions = *copts } return info } @@ -603,8 +728,6 @@ func nameToDisfix(name string) (db DisambBytes, pb PrefixBytes) { bz = bz[1:] } copy(pb[:], bz[0:4]) - // Drop the last 3 bits to make room for the Typ3. - pb[3] &= 0xF8 return } diff --git a/vendor/github.com/tendermint/go-amino/decoder.go b/vendor/github.com/tendermint/go-amino/decoder.go index 36a640e82..9464a0c81 100644 --- a/vendor/github.com/tendermint/go-amino/decoder.go +++ b/vendor/github.com/tendermint/go-amino/decoder.go @@ -45,7 +45,7 @@ func DecodeInt32(bz []byte) (i int32, n int, err error) { err = errors.New("EOF decoding int32") return } - i = int32(binary.BigEndian.Uint32(bz[:size])) + i = int32(binary.LittleEndian.Uint32(bz[:size])) n = size return } @@ -56,15 +56,20 @@ func DecodeInt64(bz []byte) (i int64, n int, err error) { err = errors.New("EOF decoding int64") return } - i = int64(binary.BigEndian.Uint64(bz[:size])) + i = int64(binary.LittleEndian.Uint64(bz[:size])) n = size return } func DecodeVarint(bz []byte) (i int64, n int, err error) { i, n = binary.Varint(bz) - if n < 0 { - n = 0 + if n == 0 { + // buf too small + err = errors.New("buffer too small") + } else if n < 0 { + // value larger than 64 bits (overflow) + // and -n is the number of bytes read + n = -n err = errors.New("EOF decoding varint") } return @@ -110,7 +115,7 @@ func DecodeUint32(bz []byte) (u uint32, n int, err error) { err = errors.New("EOF decoding uint32") return } - u = binary.BigEndian.Uint32(bz[:size]) + u = binary.LittleEndian.Uint32(bz[:size]) n = size return } @@ -121,15 +126,20 @@ func DecodeUint64(bz []byte) (u uint64, n int, err error) { err = errors.New("EOF decoding uint64") return } - u = binary.BigEndian.Uint64(bz[:size]) + u = binary.LittleEndian.Uint64(bz[:size]) n = size return } func DecodeUvarint(bz []byte) (u uint64, n int, err error) { u, n = binary.Uvarint(bz) - if n <= 0 { - n = 0 + if n == 0 { + // buf too small + err = errors.New("buffer too small") + } else if n < 0 { + // value larger than 64 bits (overflow) + // and -n is the number of bytes read + n = -n err = errors.New("EOF decoding uvarint") } return @@ -163,7 +173,7 @@ func DecodeFloat32(bz []byte) (f float32, n int, err error) { err = errors.New("EOF decoding float32") return } - i := binary.BigEndian.Uint32(bz[:size]) + i := binary.LittleEndian.Uint32(bz[:size]) f = math.Float32frombits(i) n = size return @@ -176,7 +186,7 @@ func DecodeFloat64(bz []byte) (f float64, n int, err error) { err = errors.New("EOF decoding float64") return } - i := binary.BigEndian.Uint64(bz[:size]) + i := binary.LittleEndian.Uint64(bz[:size]) f = math.Float64frombits(i) n = size return @@ -200,11 +210,11 @@ func DecodeTime(bz []byte) (t time.Time, n int, err error) { return } if fieldNum != 1 { - err = fmt.Errorf("Expected field number 1, got %v", fieldNum) + err = fmt.Errorf("expected field number 1, got %v", fieldNum) return } if typ != Typ3_8Byte { - err = fmt.Errorf("Expected Typ3 bytes <8Bytes> for time field #1, got %X", typ) + err = fmt.Errorf("expected Typ3 bytes <8Bytes> for time field #1, got %v", typ) return } } @@ -222,11 +232,11 @@ func DecodeTime(bz []byte) (t time.Time, n int, err error) { return } if fieldNum != 2 { - err = fmt.Errorf("Expected field number 2, got %v", fieldNum) + err = fmt.Errorf("expected field number 2, got %v", fieldNum) return } if typ != Typ3_4Byte { - err = fmt.Errorf("Expected Typ3 bytes <4Byte> for time field #2, got %X", typ) + err = fmt.Errorf("expected Typ3 bytes <4Byte> for time field #2, got %v", typ) return } } @@ -238,20 +248,9 @@ func DecodeTime(bz []byte) (t time.Time, n int, err error) { } // Validation check. if nsec < 0 || 999999999 < nsec { - err = fmt.Errorf("Invalid time, nanoseconds out of bounds %v", nsec) + err = fmt.Errorf("invalid time, nanoseconds out of bounds %v", nsec) return } - { // Expect "StructTerm" Typ3 byte. - var typ, _n = Typ3(0x00), int(0) - typ, _n, err = decodeTyp3(bz) - if slide(&bz, &n, _n) && err != nil { - return - } - if typ != Typ3_StructTerm { - err = errors.New(fmt.Sprintf("Expected StructTerm Typ3 byte for time, got %X", typ)) - return - } - } // Construct time. t = time.Unix(sec, int64(nsec)) // Strip timezone and monotonic for deep equality. diff --git a/vendor/github.com/tendermint/go-amino/encoder.go b/vendor/github.com/tendermint/go-amino/encoder.go index 29d638309..05fe73c99 100644 --- a/vendor/github.com/tendermint/go-amino/encoder.go +++ b/vendor/github.com/tendermint/go-amino/encoder.go @@ -20,14 +20,14 @@ func EncodeInt16(w io.Writer, i int16) (err error) { func EncodeInt32(w io.Writer, i int32) (err error) { var buf [4]byte - binary.BigEndian.PutUint32(buf[:], uint32(i)) + binary.LittleEndian.PutUint32(buf[:], uint32(i)) _, err = w.Write(buf[:]) return } func EncodeInt64(w io.Writer, i int64) (err error) { var buf [8]byte - binary.BigEndian.PutUint64(buf[:], uint64(i)) + binary.LittleEndian.PutUint64(buf[:], uint64(i)) _, err = w.Write(buf[:]) return err } @@ -62,14 +62,14 @@ func EncodeUint16(w io.Writer, u uint16) (err error) { func EncodeUint32(w io.Writer, u uint32) (err error) { var buf [4]byte - binary.BigEndian.PutUint32(buf[:], u) + binary.LittleEndian.PutUint32(buf[:], u) _, err = w.Write(buf[:]) return } func EncodeUint64(w io.Writer, u uint64) (err error) { var buf [8]byte - binary.BigEndian.PutUint64(buf[:], u) + binary.LittleEndian.PutUint64(buf[:], u) _, err = w.Write(buf[:]) return } @@ -138,7 +138,6 @@ func EncodeTime(w io.Writer, t time.Time) (err error) { return } - err = EncodeByte(w, byte(0x04)) // StructTerm return } diff --git a/vendor/github.com/tendermint/go-amino/json-decode.go b/vendor/github.com/tendermint/go-amino/json-decode.go index 15b70f809..06174bef1 100644 --- a/vendor/github.com/tendermint/go-amino/json-decode.go +++ b/vendor/github.com/tendermint/go-amino/json-decode.go @@ -2,7 +2,6 @@ package amino import ( "bytes" - "encoding/hex" "encoding/json" "errors" "fmt" @@ -15,7 +14,7 @@ import ( // cdc.decodeReflectJSON // CONTRACT: rv.CanAddr() is true. -func (cdc *Codec) decodeReflectJSON(bz []byte, info *TypeInfo, rv reflect.Value, opts FieldOptions) (err error) { +func (cdc *Codec) decodeReflectJSON(bz []byte, info *TypeInfo, rv reflect.Value, fopts FieldOptions) (err error) { if !rv.CanAddr() { panic("rv not addressable") } @@ -23,55 +22,18 @@ func (cdc *Codec) decodeReflectJSON(bz []byte, info *TypeInfo, rv reflect.Value, panic("should not happen") } if printLog { - spew.Printf("(D) decodeReflectJSON(bz: %s, info: %v, rv: %#v (%v), opts: %v)\n", - bz, info, rv.Interface(), rv.Type(), opts) + spew.Printf("(D) decodeReflectJSON(bz: %s, info: %v, rv: %#v (%v), fopts: %v)\n", + bz, info, rv.Interface(), rv.Type(), fopts) defer func() { fmt.Printf("(D) -> err: %v\n", err) }() } - // Read disfix bytes if registered. - if info.Registered { - // Strip the disfix bytes after checking it. - var disfix DisfixBytes - disfix, bz, err = decodeDisfixJSON(bz) - if err != nil { - return - } - if !info.GetDisfix().EqualBytes(disfix[:]) { - err = fmt.Errorf("Expected disfix bytes %X but got %X", info.GetDisfix(), disfix) - return - } - } - - err = cdc._decodeReflectJSON(bz, info, rv, opts) - return -} - -// CONTRACT: rv.CanAddr() is true. -func (cdc *Codec) _decodeReflectJSON(bz []byte, info *TypeInfo, rv reflect.Value, opts FieldOptions) (err error) { - if !rv.CanAddr() { - panic("rv not addressable") - } - if info.Type.Kind() == reflect.Interface && rv.Kind() == reflect.Ptr { - panic("should not happen") - } - if printLog { - spew.Printf("(_) _decodeReflectJSON(bz: %s, info: %v, rv: %#v (%v), opts: %v)\n", - bz, info, rv.Interface(), rv.Type(), opts) - defer func() { - fmt.Printf("(_) -> err: %v\n", err) - }() - } - // Special case for null for either interface, pointer, slice // NOTE: This doesn't match the binary implementation completely. if nullBytes(bz) { - switch rv.Kind() { - case reflect.Ptr, reflect.Interface, reflect.Slice, reflect.Array: - rv.Set(reflect.Zero(rv.Type())) - return - } + rv.Set(reflect.Zero(rv.Type())) + return } // Dereference-and-construct pointers all the way. @@ -84,6 +46,20 @@ func (cdc *Codec) _decodeReflectJSON(bz []byte, info *TypeInfo, rv reflect.Value rv = rv.Elem() } + // Special case: + if rv.Type() == timeType { + // Amino time strips the timezone, so must end with Z. + if len(bz) >= 2 && bz[0] == '"' && bz[len(bz)-1] == '"' { + if bz[len(bz)-2] != 'Z' { + err = fmt.Errorf("Amino:JSON time must be UTC and end with 'Z' but got %s.", bz) + return + } + } else { + err = fmt.Errorf("Amino:JSON time must be an RFC3339Nano string, but got %s.", bz) + return + } + } + // Handle override if a pointer to rv implements json.Unmarshaler. if rv.Addr().Type().Implements(jsonUnmarshalerType) { err = rv.Addr().Interface().(json.Unmarshaler).UnmarshalJSON(bz) @@ -98,7 +74,7 @@ func (cdc *Codec) _decodeReflectJSON(bz []byte, info *TypeInfo, rv reflect.Value if err != nil { return } - err = cdc._decodeReflectJSON(bz, rinfo, rrv, opts) + err = cdc.decodeReflectJSON(bz, rinfo, rrv, fopts) if err != nil { return } @@ -118,37 +94,48 @@ func (cdc *Codec) _decodeReflectJSON(bz []byte, info *TypeInfo, rv reflect.Value // Complex case reflect.Interface: - err = cdc.decodeReflectJSONInterface(bz, info, rv, opts) + err = cdc.decodeReflectJSONInterface(bz, info, rv, fopts) case reflect.Array: - err = cdc.decodeReflectJSONArray(bz, info, rv, opts) + err = cdc.decodeReflectJSONArray(bz, info, rv, fopts) case reflect.Slice: - err = cdc.decodeReflectJSONSlice(bz, info, rv, opts) + err = cdc.decodeReflectJSONSlice(bz, info, rv, fopts) case reflect.Struct: - err = cdc.decodeReflectJSONStruct(bz, info, rv, opts) + err = cdc.decodeReflectJSONStruct(bz, info, rv, fopts) case reflect.Map: - err = cdc.decodeReflectJSONMap(bz, info, rv, opts) + err = cdc.decodeReflectJSONMap(bz, info, rv, fopts) //---------------------------------------- // Signed, Unsigned - case reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8, reflect.Int, - reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uint: - err = invokeStdlibJSONUnmarshal(bz, rv, opts) + case reflect.Int64, reflect.Int: + fallthrough + case reflect.Uint64, reflect.Uint: + if bz[0] != '"' || bz[len(bz)-1] != '"' { + err = fmt.Errorf("invalid character -- Amino:JSON int/int64/uint/uint64 expects quoted values for javascript numeric support, got: %v.", string(bz)) + if err != nil { + return + } + } + bz = bz[1 : len(bz)-1] + fallthrough + case reflect.Int32, reflect.Int16, reflect.Int8, + reflect.Uint32, reflect.Uint16, reflect.Uint8: + err = invokeStdlibJSONUnmarshal(bz, rv, fopts) //---------------------------------------- // Misc case reflect.Float32, reflect.Float64: - if !opts.Unsafe { - return errors.New("Amino.JSON float* support requires `amino:\"unsafe\"`.") + if !fopts.Unsafe { + return errors.New("Amino:JSON float* support requires `amino:\"unsafe\"`.") } fallthrough case reflect.Bool, reflect.String: - err = invokeStdlibJSONUnmarshal(bz, rv, opts) + err = invokeStdlibJSONUnmarshal(bz, rv, fopts) //---------------------------------------- // Default @@ -160,7 +147,7 @@ func (cdc *Codec) _decodeReflectJSON(bz []byte, info *TypeInfo, rv reflect.Value return } -func invokeStdlibJSONUnmarshal(bz []byte, rv reflect.Value, opts FieldOptions) error { +func invokeStdlibJSONUnmarshal(bz []byte, rv reflect.Value, fopts FieldOptions) error { if !rv.CanAddr() && rv.Kind() != reflect.Ptr { panic("rv not addressable nor pointer") } @@ -178,7 +165,7 @@ func invokeStdlibJSONUnmarshal(bz []byte, rv reflect.Value, opts FieldOptions) e } // CONTRACT: rv.CanAddr() is true. -func (cdc *Codec) decodeReflectJSONInterface(bz []byte, iinfo *TypeInfo, rv reflect.Value, opts FieldOptions) (err error) { +func (cdc *Codec) decodeReflectJSONInterface(bz []byte, iinfo *TypeInfo, rv reflect.Value, fopts FieldOptions) (err error) { if !rv.CanAddr() { panic("rv not addressable") } @@ -203,22 +190,21 @@ func (cdc *Codec) decodeReflectJSONInterface(bz []byte, iinfo *TypeInfo, rv refl rv.Set(iinfo.ZeroValue) } - // Consume disambiguation / prefix info. - disfix, bz, err := decodeDisfixJSON(bz) + // Consume type wrapper info. + name, bz, err := decodeInterfaceJSON(bz) if err != nil { return } - - // XXX: Check disfix against interface to make sure that it actually + // XXX: Check name against interface to make sure that it actually // matches, and return an error if it doesn't. - // NOTE: Unlike decodeReflectBinaryInterface, we already dealt with nil in _decodeReflectJSON. - // NOTE: We also "consumed" the disfix wrapper by replacing `bz` above. + // NOTE: Unlike decodeReflectBinaryInterface, we already dealt with nil in decodeReflectJSON. + // NOTE: We also "consumed" the interface wrapper by replacing `bz` above. // Get concrete type info. - // NOTE: Unlike decodeReflectBinaryInterface, always disfix. + // NOTE: Unlike decodeReflectBinaryInterface, uses the full name string. var cinfo *TypeInfo - cinfo, err = cdc.getTypeInfoFromDisfix_rlock(disfix) + cinfo, err = cdc.getTypeInfoFromName_rlock(name) if err != nil { return } @@ -227,7 +213,7 @@ func (cdc *Codec) decodeReflectJSONInterface(bz []byte, iinfo *TypeInfo, rv refl var crv, irvSet = constructConcreteType(cinfo) // Decode into the concrete type. - err = cdc._decodeReflectJSON(bz, cinfo, crv, opts) + err = cdc.decodeReflectJSON(bz, cinfo, crv, fopts) if err != nil { rv.Set(irvSet) // Helps with debugging return @@ -241,7 +227,7 @@ func (cdc *Codec) decodeReflectJSONInterface(bz []byte, iinfo *TypeInfo, rv refl } // CONTRACT: rv.CanAddr() is true. -func (cdc *Codec) decodeReflectJSONArray(bz []byte, info *TypeInfo, rv reflect.Value, opts FieldOptions) (err error) { +func (cdc *Codec) decodeReflectJSONArray(bz []byte, info *TypeInfo, rv reflect.Value, fopts FieldOptions) (err error) { if !rv.CanAddr() { panic("rv not addressable") } @@ -290,7 +276,7 @@ func (cdc *Codec) decodeReflectJSONArray(bz []byte, info *TypeInfo, rv reflect.V for i := 0; i < length; i++ { erv := rv.Index(i) ebz := rawSlice[i] - err = cdc.decodeReflectJSON(ebz, einfo, erv, opts) + err = cdc.decodeReflectJSON(ebz, einfo, erv, fopts) if err != nil { return } @@ -300,7 +286,7 @@ func (cdc *Codec) decodeReflectJSONArray(bz []byte, info *TypeInfo, rv reflect.V } // CONTRACT: rv.CanAddr() is true. -func (cdc *Codec) decodeReflectJSONSlice(bz []byte, info *TypeInfo, rv reflect.Value, opts FieldOptions) (err error) { +func (cdc *Codec) decodeReflectJSONSlice(bz []byte, info *TypeInfo, rv reflect.Value, fopts FieldOptions) (err error) { if !rv.CanAddr() { panic("rv not addressable") } @@ -356,7 +342,7 @@ func (cdc *Codec) decodeReflectJSONSlice(bz []byte, info *TypeInfo, rv reflect.V for i := 0; i < length; i++ { erv := srv.Index(i) ebz := rawSlice[i] - err = cdc.decodeReflectJSON(ebz, einfo, erv, opts) + err = cdc.decodeReflectJSON(ebz, einfo, erv, fopts) if err != nil { return } @@ -369,7 +355,7 @@ func (cdc *Codec) decodeReflectJSONSlice(bz []byte, info *TypeInfo, rv reflect.V } // CONTRACT: rv.CanAddr() is true. -func (cdc *Codec) decodeReflectJSONStruct(bz []byte, info *TypeInfo, rv reflect.Value, opts FieldOptions) (err error) { +func (cdc *Codec) decodeReflectJSONStruct(bz []byte, info *TypeInfo, rv reflect.Value, fopts FieldOptions) (err error) { if !rv.CanAddr() { panic("rv not addressable") } @@ -416,7 +402,7 @@ func (cdc *Codec) decodeReflectJSONStruct(bz []byte, info *TypeInfo, rv reflect. } // Decode into field rv. - err = cdc.decodeReflectJSON(valueBytes, finfo, frv, opts) + err = cdc.decodeReflectJSON(valueBytes, finfo, frv, fopts) if err != nil { return } @@ -426,7 +412,7 @@ func (cdc *Codec) decodeReflectJSONStruct(bz []byte, info *TypeInfo, rv reflect. } // CONTRACT: rv.CanAddr() is true. -func (cdc *Codec) decodeReflectJSONMap(bz []byte, info *TypeInfo, rv reflect.Value, opts FieldOptions) (err error) { +func (cdc *Codec) decodeReflectJSONMap(bz []byte, info *TypeInfo, rv reflect.Value, fopts FieldOptions) (err error) { if !rv.CanAddr() { panic("rv not addressable") } @@ -464,7 +450,7 @@ func (cdc *Codec) decodeReflectJSONMap(bz []byte, info *TypeInfo, rv reflect.Val vrv := reflect.New(mrv.Type().Elem()).Elem() // Decode valueBytes into vrv. - err = cdc.decodeReflectJSON(valueBytes, vinfo, vrv, opts) + err = cdc.decodeReflectJSON(valueBytes, vinfo, vrv, fopts) if err != nil { return } @@ -483,45 +469,34 @@ func (cdc *Codec) decodeReflectJSONMap(bz []byte, info *TypeInfo, rv reflect.Val // Misc. type disfixWrapper struct { - Disfix string `json:"type"` - Data json.RawMessage `json:"value"` + Name string `json:"type"` + Data json.RawMessage `json:"value"` } -// decodeDisfixJSON helps unravel the disfix and +// decodeInterfaceJSON helps unravel the type name and // the stored data, which are expected in the form: // { -// "type": "XXXXXXXXXXXXXXXXX", +// "type": "", // "value": {} // } -func decodeDisfixJSON(bz []byte) (df DisfixBytes, data []byte, err error) { - if string(bz) == "null" { - panic("yay") - } +func decodeInterfaceJSON(bz []byte) (name string, data []byte, err error) { dfw := new(disfixWrapper) err = json.Unmarshal(bz, dfw) if err != nil { - err = fmt.Errorf("Cannot parse disfix JSON wrapper: %v", err) - return - } - dfBytes, err := hex.DecodeString(dfw.Disfix) - if err != nil { + err = fmt.Errorf("cannot parse disfix JSON wrapper: %v", err) return } - // Get disfix. - if g, w := len(dfBytes), DisfixBytesLen; g != w { - err = fmt.Errorf("Disfix length got=%d want=%d data=%s", g, w, bz) - return - } - copy(df[:], dfBytes) - if (DisfixBytes{}).EqualBytes(df[:]) { - err = errors.New("Unexpected zero disfix in JSON") + // Get name. + if dfw.Name == "" { + err = errors.New("JSON encoding of interfaces require non-empty type field.") return } + name = dfw.Name // Get data. if len(dfw.Data) == 0 { - err = errors.New("Disfix JSON wrapper should have non-empty value field") + err = errors.New("interface JSON wrapper should have non-empty value field") return } data = dfw.Data diff --git a/vendor/github.com/tendermint/go-amino/json-encode.go b/vendor/github.com/tendermint/go-amino/json-encode.go index 4ae11f1c2..15b10f21d 100644 --- a/vendor/github.com/tendermint/go-amino/json-encode.go +++ b/vendor/github.com/tendermint/go-amino/json-encode.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "reflect" + "time" "github.com/davecgh/go-spew/spew" ) @@ -18,54 +19,18 @@ import ( // only call this one, for the disfix wrapper is only written here. // NOTE: Unlike encodeReflectBinary, rv may be a pointer. // CONTRACT: rv is valid. -func (cdc *Codec) encodeReflectJSON(w io.Writer, info *TypeInfo, rv reflect.Value, opts FieldOptions) (err error) { +func (cdc *Codec) encodeReflectJSON(w io.Writer, info *TypeInfo, rv reflect.Value, fopts FieldOptions) (err error) { if !rv.IsValid() { panic("should not happen") } if printLog { - spew.Printf("(E) encodeReflectJSON(info: %v, rv: %#v (%v), opts: %v)\n", - info, rv.Interface(), rv.Type(), opts) + spew.Printf("(E) encodeReflectJSON(info: %v, rv: %#v (%v), fopts: %v)\n", + info, rv.Interface(), rv.Type(), fopts) defer func() { fmt.Printf("(E) -> err: %v\n", err) }() } - // Write the disfix wrapper if it is a registered concrete type. - if info.Registered { - // Part 1: - disfix := toDisfix(info.Disamb, info.Prefix) - err = writeStr(w, _fmt(`{"type":"%X","value":`, disfix)) - if err != nil { - return - } - // Part 2: - defer func() { - if err != nil { - return - } - err = writeStr(w, `}`) - }() - } - - err = cdc._encodeReflectJSON(w, info, rv, opts) - return -} - -// NOTE: Unlike _encodeReflectBinary, rv may be a pointer. -// CONTRACT: rv is valid. -// CONTRACT: any disfix wrapper has already been written. -func (cdc *Codec) _encodeReflectJSON(w io.Writer, info *TypeInfo, rv reflect.Value, opts FieldOptions) (err error) { - if !rv.IsValid() { - panic("should not happen") - } - if printLog { - spew.Printf("(_) _encodeReflectJSON(info: %v, rv: %#v (%v), opts: %v)\n", - info, rv.Interface(), rv.Type(), opts) - defer func() { - fmt.Printf("(_) -> err: %v\n", err) - }() - } - // Dereference value if pointer. var isNilPtr bool rv, _, isNilPtr = derefPointers(rv) @@ -76,6 +41,13 @@ func (cdc *Codec) _encodeReflectJSON(w io.Writer, info *TypeInfo, rv reflect.Val return } + // Special case: + if rv.Type() == timeType { + // Amino time strips the timezone. + // NOTE: This must be done before json.Marshaler override below. + ct := rv.Interface().(time.Time).Round(0).UTC() + rv = reflect.ValueOf(ct) + } // Handle override if rv implements json.Marshaler. if rv.CanAddr() { // Try pointer first. if rv.Addr().Type().Implements(jsonMarshalerType) { @@ -100,7 +72,7 @@ func (cdc *Codec) _encodeReflectJSON(w io.Writer, info *TypeInfo, rv reflect.Val return } // Then, encode the repr instance. - err = cdc._encodeReflectJSON(w, rinfo, rrv, opts) + err = cdc.encodeReflectJSON(w, rinfo, rrv, fopts) return } @@ -110,29 +82,37 @@ func (cdc *Codec) _encodeReflectJSON(w io.Writer, info *TypeInfo, rv reflect.Val // Complex case reflect.Interface: - return cdc.encodeReflectJSONInterface(w, info, rv, opts) + return cdc.encodeReflectJSONInterface(w, info, rv, fopts) case reflect.Array, reflect.Slice: - return cdc.encodeReflectJSONList(w, info, rv, opts) + return cdc.encodeReflectJSONList(w, info, rv, fopts) case reflect.Struct: - return cdc.encodeReflectJSONStruct(w, info, rv, opts) + return cdc.encodeReflectJSONStruct(w, info, rv, fopts) case reflect.Map: - return cdc.encodeReflectJSONMap(w, info, rv, opts) + return cdc.encodeReflectJSONMap(w, info, rv, fopts) //---------------------------------------- // Signed, Unsigned - case reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8, reflect.Int, - reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uint: + case reflect.Int64, reflect.Int: + _, err = fmt.Fprintf(w, `"%d"`, rv.Int()) // JS can't handle int64 + return + + case reflect.Uint64, reflect.Uint: + _, err = fmt.Fprintf(w, `"%d"`, rv.Uint()) // JS can't handle uint64 + return + + case reflect.Int32, reflect.Int16, reflect.Int8, + reflect.Uint32, reflect.Uint16, reflect.Uint8: return invokeStdlibJSONMarshal(w, rv.Interface()) //---------------------------------------- // Misc case reflect.Float64, reflect.Float32: - if !opts.Unsafe { + if !fopts.Unsafe { return errors.New("Amino.JSON float* support requires `amino:\"unsafe\"`.") } fallthrough @@ -147,7 +127,7 @@ func (cdc *Codec) _encodeReflectJSON(w io.Writer, info *TypeInfo, rv reflect.Val } } -func (cdc *Codec) encodeReflectJSONInterface(w io.Writer, iinfo *TypeInfo, rv reflect.Value, opts FieldOptions) (err error) { +func (cdc *Codec) encodeReflectJSONInterface(w io.Writer, iinfo *TypeInfo, rv reflect.Value, fopts FieldOptions) (err error) { if printLog { fmt.Println("(e) encodeReflectJSONInterface") defer func() { @@ -184,10 +164,9 @@ func (cdc *Codec) encodeReflectJSONInterface(w io.Writer, iinfo *TypeInfo, rv re return } - // Write disfix wrapper. + // Write interface wrapper. // Part 1: - disfix := toDisfix(cinfo.Disamb, cinfo.Prefix) - err = writeStr(w, _fmt(`{"type":"%X","value":`, disfix)) + err = writeStr(w, _fmt(`{"type":"%s","value":`, cinfo.Name)) if err != nil { return } @@ -204,11 +183,11 @@ func (cdc *Codec) encodeReflectJSONInterface(w io.Writer, iinfo *TypeInfo, rv re // Currently, go-amino JSON *always* writes disfix bytes for // all registered concrete types. - err = cdc._encodeReflectJSON(w, cinfo, crv, opts) + err = cdc.encodeReflectJSON(w, cinfo, crv, fopts) return } -func (cdc *Codec) encodeReflectJSONList(w io.Writer, info *TypeInfo, rv reflect.Value, opts FieldOptions) (err error) { +func (cdc *Codec) encodeReflectJSONList(w io.Writer, info *TypeInfo, rv reflect.Value, fopts FieldOptions) (err error) { if printLog { fmt.Println("(e) encodeReflectJSONList") defer func() { @@ -266,7 +245,7 @@ func (cdc *Codec) encodeReflectJSONList(w io.Writer, info *TypeInfo, rv reflect. if isNil { err = writeStr(w, `null`) } else { - err = cdc.encodeReflectJSON(w, einfo, erv, opts) + err = cdc.encodeReflectJSON(w, einfo, erv, fopts) } if err != nil { return @@ -356,7 +335,7 @@ func (cdc *Codec) encodeReflectJSONStruct(w io.Writer, info *TypeInfo, rv reflec } // TODO: TEST -func (cdc *Codec) encodeReflectJSONMap(w io.Writer, info *TypeInfo, rv reflect.Value, opts FieldOptions) (err error) { +func (cdc *Codec) encodeReflectJSONMap(w io.Writer, info *TypeInfo, rv reflect.Value, fopts FieldOptions) (err error) { if printLog { fmt.Println("(e) encodeReflectJSONMap") defer func() { @@ -414,7 +393,7 @@ func (cdc *Codec) encodeReflectJSONMap(w io.Writer, info *TypeInfo, rv reflect.V if err != nil { return } - err = cdc.encodeReflectJSON(w, vinfo, vrv, opts) // pass through opts + err = cdc.encodeReflectJSON(w, vinfo, vrv, fopts) // pass through fopts } if err != nil { return diff --git a/vendor/github.com/tendermint/go-amino/reflect.go b/vendor/github.com/tendermint/go-amino/reflect.go index 981575239..10a2cea95 100644 --- a/vendor/github.com/tendermint/go-amino/reflect.go +++ b/vendor/github.com/tendermint/go-amino/reflect.go @@ -11,7 +11,6 @@ import ( // Constants const printLog = false -const RFC3339Millis = "2006-01-02T15:04:05.000Z" // forced microseconds var ( timeType = reflect.TypeOf(time.Time{}) @@ -52,7 +51,9 @@ func slide(bz *[]byte, n *int, _n int) bool { panic(fmt.Sprintf("impossible slide: len:%v _n:%v", len(*bz), _n)) } *bz = (*bz)[_n:] - *n += _n + if n != nil { + *n += _n + } return true } @@ -73,14 +74,44 @@ func derefPointers(rv reflect.Value) (drv reflect.Value, isPtr bool, isNilPtr bo return } -// Returns isVoid=true iff is ultimately nil or empty after (recursive) dereferencing. -// If isVoid=false, erv is set to the non-nil non-empty valid dereferenced value. -func isVoid(rv reflect.Value) (erv reflect.Value, isVoid bool) { +// Dereference pointer recursively or return zero value. +// drv: the final non-pointer value (which is never invalid). +// isPtr: whether rv.Kind() == reflect.Ptr. +// isNilPtr: whether a nil pointer at any level. +func derefPointersZero(rv reflect.Value) (drv reflect.Value, isPtr bool, isNilPtr bool) { + for rv.Kind() == reflect.Ptr { + isPtr = true + if rv.IsNil() { + isNilPtr = true + rt := rv.Type().Elem() + for rt.Kind() == reflect.Ptr { + rt = rt.Elem() + } + drv = reflect.New(rt).Elem() + return + } + rv = rv.Elem() + } + drv = rv + return +} + +// Returns isDefaultValue=true iff is ultimately nil or empty after (recursive) +// dereferencing. If isDefaultValue=false, erv is set to the non-nil non-empty +// non-default dereferenced value. +// A zero/empty struct is not considered default. +func isDefaultValue(rv reflect.Value) (erv reflect.Value, isDefaultValue bool) { rv, _, isNilPtr := derefPointers(rv) if isNilPtr { return rv, true } else { switch rv.Kind() { + case reflect.Bool: + return rv, rv.Bool() == false + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return rv, rv.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return rv, rv.Uint() == 0 case reflect.String: return rv, rv.Len() == 0 case reflect.Chan, reflect.Map, reflect.Slice: @@ -118,55 +149,36 @@ func constructConcreteType(cinfo *TypeInfo) (crv, irvSet reflect.Value) { return } -// Like typeToTyp4 but include a pointer bit. -func typeToTyp4(rt reflect.Type, opts FieldOptions) (typ Typ4) { - - // Dereference pointer type. - var pointer = false - for rt.Kind() == reflect.Ptr { - pointer = true - rt = rt.Elem() - } - - // Call actual logic. - typ = Typ4(typeToTyp3(rt, opts)) - - // Set pointer bit to 1 if pointer. - if pointer { - typ |= Typ4_Pointer - } - return -} - // CONTRACT: rt.Kind() != reflect.Ptr func typeToTyp3(rt reflect.Type, opts FieldOptions) Typ3 { switch rt.Kind() { case reflect.Interface: - return Typ3_Interface + return Typ3_ByteLength case reflect.Array, reflect.Slice: - ert := rt.Elem() - switch ert.Kind() { - case reflect.Uint8: - return Typ3_ByteLength - default: - return Typ3_List - } + return Typ3_ByteLength case reflect.String: return Typ3_ByteLength case reflect.Struct, reflect.Map: - return Typ3_Struct + return Typ3_ByteLength case reflect.Int64, reflect.Uint64: - if opts.BinVarint { + if opts.BinFixed64 { + return Typ3_8Byte + } else { + return Typ3_Varint + } + case reflect.Int32, reflect.Uint32: + if opts.BinFixed32 { + return Typ3_4Byte + } else { return Typ3_Varint } - return Typ3_8Byte - case reflect.Float64: - return Typ3_8Byte - case reflect.Int32, reflect.Uint32, reflect.Float32: - return Typ3_4Byte case reflect.Int16, reflect.Int8, reflect.Int, reflect.Uint16, reflect.Uint8, reflect.Uint, reflect.Bool: return Typ3_Varint + case reflect.Float64: + return Typ3_8Byte + case reflect.Float32: + return Typ3_4Byte default: panic(fmt.Sprintf("unsupported field type %v", rt)) } diff --git a/vendor/github.com/tendermint/go-amino/version.go b/vendor/github.com/tendermint/go-amino/version.go index 7f84d3a4a..ed348aaf4 100644 --- a/vendor/github.com/tendermint/go-amino/version.go +++ b/vendor/github.com/tendermint/go-amino/version.go @@ -1,4 +1,4 @@ package amino // Version -const Version = "0.9.9" \ No newline at end of file +const Version = "0.10.1" diff --git a/vendor/github.com/tendermint/go-crypto/doc.go b/vendor/github.com/tendermint/go-crypto/doc.go deleted file mode 100644 index c6701bc58..000000000 --- a/vendor/github.com/tendermint/go-crypto/doc.go +++ /dev/null @@ -1,48 +0,0 @@ -/* -go-crypto is a customized/convenience cryptography package -for supporting Tendermint. - -It wraps select functionality of equivalent functions in the -Go standard library, for easy usage with our libraries. - -Keys: - -All key generation functions return an instance of the PrivKey interface -which implements methods - - AssertIsPrivKeyInner() - Bytes() []byte - Sign(msg []byte) Signature - PubKey() PubKey - Equals(PrivKey) bool - Wrap() PrivKey - -From the above method we can: -a) Retrieve the public key if needed - - pubKey := key.PubKey() - -For example: - privKey, err := crypto.GenPrivKeyEd25519() - if err != nil { - ... - } - pubKey := privKey.PubKey() - ... - // And then you can use the private and public key - doSomething(privKey, pubKey) - - -We also provide hashing wrappers around algorithms: - -Sha256 - sum := crypto.Sha256([]byte("This is Tendermint")) - fmt.Printf("%x\n", sum) - -Ripemd160 - sum := crypto.Ripemd160([]byte("This is consensus")) - fmt.Printf("%x\n", sum) -*/ -package crypto - -// TODO: Add more docs in here diff --git a/vendor/github.com/tendermint/go-crypto/version.go b/vendor/github.com/tendermint/go-crypto/version.go deleted file mode 100644 index aac87c4f3..000000000 --- a/vendor/github.com/tendermint/go-crypto/version.go +++ /dev/null @@ -1,3 +0,0 @@ -package crypto - -const Version = "0.6.2" diff --git a/vendor/github.com/tendermint/iavl/amino.go b/vendor/github.com/tendermint/iavl/amino.go deleted file mode 100644 index 0e80ee6fb..000000000 --- a/vendor/github.com/tendermint/iavl/amino.go +++ /dev/null @@ -1,5 +0,0 @@ -package iavl - -import "github.com/tendermint/go-amino" - -var cdc = amino.NewCodec() diff --git a/vendor/github.com/tendermint/iavl/chunk.go b/vendor/github.com/tendermint/iavl/chunk.go deleted file mode 100644 index b1cbdd226..000000000 --- a/vendor/github.com/tendermint/iavl/chunk.go +++ /dev/null @@ -1,185 +0,0 @@ -package iavl - -import ( - "sort" - - "github.com/pkg/errors" - cmn "github.com/tendermint/tmlibs/common" -) - -// Chunk is a list of ordered nodes. -// It can be sorted, merged, exported from a tree and -// used to generate a new tree. -type Chunk []OrderedNodeData - -// OrderedNodeData is the data to recreate a leaf node, -// along with a SortOrder to define a BFS insertion order. -type OrderedNodeData struct { - SortOrder uint64 - NodeData -} - -// NewOrderedNode creates the data from a leaf node. -func NewOrderedNode(leaf *Node, prefix uint64) OrderedNodeData { - return OrderedNodeData{ - SortOrder: prefix, - NodeData: NodeData{ - Key: leaf.key, - Value: leaf.value, - }, - } -} - -// getChunkHashes returns all the "checksum" hashes for -// the chunks that will be sent. -func getChunkHashes(tree *Tree, depth uint) ([][]byte, [][]byte, uint, error) { - maxDepth := uint(tree.root.height / 2) - if depth > maxDepth { - return nil, nil, 0, errors.New("depth exceeds maximum allowed") - } - - nodes := getNodes(tree, depth) - hashes := make([][]byte, len(nodes)) - keys := make([][]byte, len(nodes)) - for i, n := range nodes { - hashes[i] = n.hash - keys[i] = n.key - } - return hashes, keys, depth, nil -} - -// GetChunkHashesWithProofs takes a tree and returns the list of chunks with -// proofs that can be used to synchronize a tree across the network. -func GetChunkHashesWithProofs(tree *Tree) ([][]byte, []*InnerKeyProof, uint) { - hashes, keys, depth, err := getChunkHashes(tree, uint(tree.root.height/2)) - if err != nil { - cmn.PanicSanity(cmn.Fmt("GetChunkHashes: %s", err)) - } - proofs := make([]*InnerKeyProof, len(keys)) - - for i, k := range keys { - proof, err := tree.getInnerWithProof(k) - if err != nil { - cmn.PanicSanity(cmn.Fmt("Error getting inner key proof: %s", err)) - } - proofs[i] = proof - } - return hashes, proofs, depth -} - -// getNodes returns an array of nodes at the given depth. -func getNodes(tree *Tree, depth uint) []*Node { - nodes := make([]*Node, 0, 1< 0; d-- { - // lowest digit of count * 2^(d-1) - key += uint64((count & 1) << (d - 1)) - count = count >> 1 - } - return -} - -// GetChunk finds the count-th subtree at depth and -// generates a Chunk for that data. -func GetChunk(tree *Tree, depth, count uint) Chunk { - node := getNodes(tree, depth)[count] - prefix := positionToKey(depth, count) - return getChunk(tree, node, prefix, depth) -} - -// getChunk takes a node and serializes all nodes below it -// -// As it is part of a larger tree, prefix defines the path -// up to this point, and depth the current depth -// (which defines where we add to the prefix) -// -// TODO: make this more efficient, *Chunk as arg??? -func getChunk(t *Tree, node *Node, prefix uint64, depth uint) Chunk { - if node.isLeaf() { - return Chunk{NewOrderedNode(node, prefix)} - } - res := make(Chunk, 0, node.size) - if node.leftNode != nil { - left := getChunk(t, node.getLeftNode(t), prefix, depth+1) - res = append(res, left...) - } - if node.rightNode != nil { - offset := prefix + 1< len(left)-1 && j <= len(right)-1 { - slice[k] = right[j] - j++ - } else if j > len(right)-1 && i <= len(left)-1 { - slice[k] = left[i] - i++ - } else if left[i].SortOrder < right[j].SortOrder { - slice[k] = left[i] - i++ - } else { - slice[k] = right[j] - j++ - } - } - return Chunk(slice) -} - -// CalculateRoot creates a temporary in-memory -// iavl tree to calculate the root hash of inserting -// all the nodes. -func (c Chunk) CalculateRoot() []byte { - test := NewTree(nil, 2*len(c)) - c.PopulateTree(test) - return test.Hash() -} - -// PopulateTree adds all the chunks in order to the given tree. -func (c Chunk) PopulateTree(empty *Tree) { - for _, data := range c { - empty.Set(data.Key, data.Value) - } -} diff --git a/vendor/github.com/tendermint/iavl/doc.go b/vendor/github.com/tendermint/iavl/doc.go index d6c38c6c0..7e4891bcb 100644 --- a/vendor/github.com/tendermint/iavl/doc.go +++ b/vendor/github.com/tendermint/iavl/doc.go @@ -1,7 +1,11 @@ +// Package iavl implements a versioned, snapshottable (immutable) AVL+ tree +// for persisting key-value pairs. +// +// // Basic usage of VersionedTree. // // import "github.com/tendermint/iavl" -// import "github.com/tendermint/tmlibs/db" +// import "github.com/tendermint/tendermint/libs/db" // ... // // tree := iavl.NewVersionedTree(db.NewMemDB(), 128) @@ -23,12 +27,12 @@ // Proof of existence: // // root := tree.Hash() -// val, proof, err := tree.GetVersionedWithProof([]byte("bob"), 2) // "xyz", KeyProof, nil +// val, proof, err := tree.GetVersionedWithProof([]byte("bob"), 2) // "xyz", RangeProof, nil // proof.Verify([]byte("bob"), val, root) // nil // // Proof of absence: // -// _, proof, err = tree.GetVersionedWithProof([]byte("tom"), 2) // nil, KeyProof, nil +// _, proof, err = tree.GetVersionedWithProof([]byte("tom"), 2) // nil, RangeProof, nil // proof.Verify([]byte("tom"), nil, root) // nil // // Now we delete an old version: diff --git a/vendor/github.com/tendermint/iavl/node.go b/vendor/github.com/tendermint/iavl/node.go index 995583364..307412c33 100644 --- a/vendor/github.com/tendermint/iavl/node.go +++ b/vendor/github.com/tendermint/iavl/node.go @@ -9,7 +9,8 @@ import ( "io" "github.com/tendermint/go-amino" - "github.com/tendermint/iavl/sha256truncated" + "github.com/tendermint/tendermint/crypto/tmhash" + cmn "github.com/tendermint/tendermint/libs/common" ) // Node represents a node in a Tree. @@ -40,56 +41,60 @@ func NewNode(key []byte, value []byte, version int64) *Node { // MakeNode constructs an *Node from an encoded byte slice. // -// The new node doesn't have its hash saved or set. The caller must set it +// The new node doesn't have its hash saved or set. The caller must set it // afterwards. -func MakeNode(buf []byte) (node *Node, err error) { - node = &Node{} +func MakeNode(buf []byte) (*Node, cmn.Error) { - // Keeps track of bytes read. - n := 0 - - // Read node header. - node.height, n, err = amino.DecodeInt8(buf) - if err != nil { - return nil, err + // Read node header (height, size, version, key). + height, n, cause := amino.DecodeInt8(buf) + if cause != nil { + return nil, cmn.ErrorWrap(cause, "decoding node.height") } buf = buf[n:] - node.size, n, err = amino.DecodeInt64(buf) - if err != nil { - return nil, err + size, n, cause := amino.DecodeVarint(buf) + if cause != nil { + return nil, cmn.ErrorWrap(cause, "decoding node.size") } buf = buf[n:] - node.version, n, err = amino.DecodeInt64(buf) - if err != nil { - return nil, err + ver, n, cause := amino.DecodeVarint(buf) + if cause != nil { + return nil, cmn.ErrorWrap(cause, "decoding node.version") } buf = buf[n:] - node.key, n, err = amino.DecodeByteSlice(buf) - if err != nil { - return nil, err + key, n, cause := amino.DecodeByteSlice(buf) + if cause != nil { + return nil, cmn.ErrorWrap(cause, "decoding node.key") } buf = buf[n:] + node := &Node{ + height: height, + size: size, + version: ver, + key: key, + } + // Read node body. if node.isLeaf() { - node.value, _, err = amino.DecodeByteSlice(buf) - if err != nil { - return nil, err + val, _, cause := amino.DecodeByteSlice(buf) + if cause != nil { + return nil, cmn.ErrorWrap(cause, "decoding node.value") } + node.value = val } else { // Read children. - leftHash, n, err := amino.DecodeByteSlice(buf) - if err != nil { - return nil, err + leftHash, n, cause := amino.DecodeByteSlice(buf) + if cause != nil { + return nil, cmn.ErrorWrap(cause, "deocding node.leftHash") } buf = buf[n:] - rightHash, _, err := amino.DecodeByteSlice(buf) - if err != nil { - return nil, err + rightHash, _, cause := amino.DecodeByteSlice(buf) + if cause != nil { + return nil, cmn.ErrorWrap(cause, "decoding node.rightHash") } node.leftHash = leftHash node.rightHash = rightHash @@ -99,11 +104,16 @@ func MakeNode(buf []byte) (node *Node, err error) { // String returns a string representation of the node. func (node *Node) String() string { - if len(node.hash) == 0 { - return "" - } else { - return fmt.Sprintf("%x", node.hash) - } + hashstr := "" + if len(node.hash) > 0 { + hashstr = fmt.Sprintf("%X", node.hash) + } + return fmt.Sprintf("Node{%s:%s@%d %X;%X}#%s", + cmn.ColoredBytes(node.key, cmn.Green, cmn.Blue), + cmn.ColoredBytes(node.value, cmn.Cyan, cmn.Blue), + node.version, + node.leftHash, node.rightHash, + hashstr) } // clone creates a shallow copy of a node with its hash set to nil. @@ -139,9 +149,8 @@ func (node *Node) has(t *Tree, key []byte) (has bool) { } if bytes.Compare(key, node.key) < 0 { return node.getLeftNode(t).has(t, key) - } else { - return node.getRightNode(t).has(t, key) } + return node.getRightNode(t).has(t, key) } // Get a key under the node. @@ -159,31 +168,28 @@ func (node *Node) get(t *Tree, key []byte) (index int64, value []byte) { if bytes.Compare(key, node.key) < 0 { return node.getLeftNode(t).get(t, key) - } else { - rightNode := node.getRightNode(t) - index, value = rightNode.get(t, key) - index += node.size - rightNode.size - return index, value } + rightNode := node.getRightNode(t) + index, value = rightNode.get(t, key) + index += node.size - rightNode.size + return index, value } func (node *Node) getByIndex(t *Tree, index int64) (key []byte, value []byte) { if node.isLeaf() { if index == 0 { return node.key, node.value - } else { - return nil, nil - } - } else { - // TODO: could improve this by storing the - // sizes as well as left/right hash. - leftNode := node.getLeftNode(t) - if index < leftNode.size { - return leftNode.getByIndex(t, index) - } else { - return node.getRightNode(t).getByIndex(t, index-leftNode.size) } + return nil, nil + } + // TODO: could improve this by storing the + // sizes as well as left/right hash. + leftNode := node.getLeftNode(t) + + if index < leftNode.size { + return leftNode.getByIndex(t, index) } + return node.getRightNode(t).getByIndex(t, index-leftNode.size) } // Computes the hash of the node without computing its descendants. Must be @@ -193,7 +199,7 @@ func (node *Node) _hash() []byte { return node.hash } - h := sha256truncated.New() + h := tmhash.New() buf := new(bytes.Buffer) if err := node.writeHashBytes(buf); err != nil { panic(err) @@ -211,7 +217,7 @@ func (node *Node) hashWithCount() ([]byte, int64) { return node.hash, 0 } - h := sha256truncated.New() + h := tmhash.New() buf := new(bytes.Buffer) hashCount, err := node.writeHashBytesRecursively(buf) if err != nil { @@ -225,41 +231,54 @@ func (node *Node) hashWithCount() ([]byte, int64) { // Writes the node's hash to the given io.Writer. This function expects // child hashes to be already set. -func (node *Node) writeHashBytes(w io.Writer) (err error) { - err = amino.EncodeInt8(w, node.height) - if err == nil { - err = amino.EncodeInt64(w, node.size) +func (node *Node) writeHashBytes(w io.Writer) cmn.Error { + err := amino.EncodeInt8(w, node.height) + if err != nil { + return cmn.ErrorWrap(err, "writing height") + } + err = amino.EncodeVarint(w, node.size) + if err != nil { + return cmn.ErrorWrap(err, "writing size") } - if err == nil { - err = amino.EncodeInt64(w, node.version) + err = amino.EncodeVarint(w, node.version) + if err != nil { + return cmn.ErrorWrap(err, "writing version") } // Key is not written for inner nodes, unlike writeBytes. if node.isLeaf() { - if err == nil { - err = amino.EncodeByteSlice(w, node.key) + err = amino.EncodeByteSlice(w, node.key) + if err != nil { + return cmn.ErrorWrap(err, "writing key") } - if err == nil { - err = amino.EncodeByteSlice(w, node.value) + // Indirection needed to provide proofs without values. + // (e.g. proofLeafNode.ValueHash) + valueHash := tmhash.Sum(node.value) + err = amino.EncodeByteSlice(w, valueHash) + if err != nil { + return cmn.ErrorWrap(err, "writing value") } } else { if node.leftHash == nil || node.rightHash == nil { panic("Found an empty child hash") } - if err == nil { - err = amino.EncodeByteSlice(w, node.leftHash) + err = amino.EncodeByteSlice(w, node.leftHash) + if err != nil { + return cmn.ErrorWrap(err, "writing left hash") } - if err == nil { - err = amino.EncodeByteSlice(w, node.rightHash) + err = amino.EncodeByteSlice(w, node.rightHash) + if err != nil { + return cmn.ErrorWrap(err, "writing right hash") } } - return + + return nil } // Writes the node's hash to the given io.Writer. // This function has the side-effect of calling hashWithCount. -func (node *Node) writeHashBytesRecursively(w io.Writer) (hashCount int64, err error) { +func (node *Node) writeHashBytesRecursively(w io.Writer) (hashCount int64, err cmn.Error) { if node.leftNode != nil { leftHash, leftCount := node.leftNode.hashWithCount() node.leftHash = leftHash @@ -276,40 +295,50 @@ func (node *Node) writeHashBytesRecursively(w io.Writer) (hashCount int64, err e } // Writes the node as a serialized byte slice to the supplied io.Writer. -func (node *Node) writeBytes(w io.Writer) (err error) { - err = amino.EncodeInt8(w, node.height) - if err == nil { - err = amino.EncodeInt64(w, node.size) +func (node *Node) writeBytes(w io.Writer) cmn.Error { + var cause error + cause = amino.EncodeInt8(w, node.height) + if cause != nil { + return cmn.ErrorWrap(cause, "writing height") } - if err == nil { - err = amino.EncodeInt64(w, node.version) + cause = amino.EncodeVarint(w, node.size) + if cause != nil { + return cmn.ErrorWrap(cause, "writing size") + } + cause = amino.EncodeVarint(w, node.version) + if cause != nil { + return cmn.ErrorWrap(cause, "writing version") } // Unlike writeHashBytes, key is written for inner nodes. - if err == nil { - err = amino.EncodeByteSlice(w, node.key) + cause = amino.EncodeByteSlice(w, node.key) + if cause != nil { + return cmn.ErrorWrap(cause, "writing key") } if node.isLeaf() { - if err == nil { - err = amino.EncodeByteSlice(w, node.value) + cause = amino.EncodeByteSlice(w, node.value) + if cause != nil { + return cmn.ErrorWrap(cause, "writing value") } } else { if node.leftHash == nil { panic("node.leftHash was nil in writeBytes") } - if err == nil { - err = amino.EncodeByteSlice(w, node.leftHash) + cause = amino.EncodeByteSlice(w, node.leftHash) + if cause != nil { + return cmn.ErrorWrap(cause, "writing left hash") } if node.rightHash == nil { panic("node.rightHash was nil in writeBytes") } - if err == nil { - err = amino.EncodeByteSlice(w, node.rightHash) + cause = amino.EncodeByteSlice(w, node.rightHash) + if cause != nil { + return cmn.ErrorWrap(cause, "writing right hash") } } - return + return nil } func (node *Node) set(t *Tree, key []byte, value []byte) ( @@ -358,35 +387,33 @@ func (node *Node) set(t *Tree, key []byte, value []byte) ( if updated { return node, updated, orphaned - } else { - node.calcHeightAndSize(t) - newNode, balanceOrphaned := node.balance(t) - return newNode, updated, append(orphaned, balanceOrphaned...) } + node.calcHeightAndSize(t) + newNode, balanceOrphaned := node.balance(t) + return newNode, updated, append(orphaned, balanceOrphaned...) } } -// newHash/newNode: The new hash or node to replace node after remove. -// newKey: new leftmost leaf key for tree after successfully removing 'key' if changed. -// value: removed value. -func (node *Node) remove(t *Tree, key []byte) ( - newHash []byte, newNode *Node, newKey []byte, value []byte, orphaned []*Node, -) { +// removes the node corresponding to the passed key and balances the tree. +// It returns: +// - the hash of the new node (or nil if the node is the one removed) +// - the node that replaces the orig. node after remove +// - new leftmost leaf key for tree after successfully removing 'key' if changed. +// - the removed value +// - the orphaned nodes. +func (node *Node) remove(t *Tree, key []byte) ([]byte, *Node, []byte, []byte, []*Node) { version := t.version + 1 if node.isLeaf() { if bytes.Equal(key, node.key) { return nil, nil, nil, node.value, []*Node{node} } - return node.hash, node, nil, nil, orphaned + return node.hash, node, nil, nil, nil } + // node.key < key; we go to the left to find the key: if bytes.Compare(key, node.key) < 0 { - var newLeftHash []byte - var newLeftNode *Node - - newLeftHash, newLeftNode, newKey, value, orphaned = - node.getLeftNode(t).remove(t, key) + newLeftHash, newLeftNode, newKey, value, orphaned := node.getLeftNode(t).remove(t, key) if len(orphaned) == 0 { return node.hash, node, nil, value, orphaned @@ -401,30 +428,26 @@ func (node *Node) remove(t *Tree, key []byte) ( newNode, balanceOrphaned := newNode.balance(t) return newNode.hash, newNode, newKey, value, append(orphaned, balanceOrphaned...) - } else { - var newRightHash []byte - var newRightNode *Node - - newRightHash, newRightNode, newKey, value, orphaned = - node.getRightNode(t).remove(t, key) - - if len(orphaned) == 0 { - return node.hash, node, nil, value, orphaned - } else if newRightHash == nil && newRightNode == nil { // right node held value, was removed - return node.leftHash, node.leftNode, nil, value, orphaned - } - orphaned = append(orphaned, node) + } + // node.key >= key; either found or look to the right: + newRightHash, newRightNode, newKey, value, orphaned := node.getRightNode(t).remove(t, key) - newNode := node.clone(version) - newNode.rightHash, newNode.rightNode = newRightHash, newRightNode - if newKey != nil { - newNode.key = newKey - } - newNode.calcHeightAndSize(t) - newNode, balanceOrphaned := newNode.balance(t) + if len(orphaned) == 0 { + return node.hash, node, nil, value, orphaned + } else if newRightHash == nil && newRightNode == nil { // right node held value, was removed + return node.leftHash, node.leftNode, nil, value, orphaned + } + orphaned = append(orphaned, node) - return newNode.hash, newNode, nil, value, append(orphaned, balanceOrphaned...) + newNode := node.clone(version) + newNode.rightHash, newNode.rightNode = newRightHash, newRightNode + if newKey != nil { + newNode.key = newKey } + newNode.calcHeightAndSize(t) + newNode, balanceOrphaned := newNode.balance(t) + + return newNode.hash, newNode, nil, value, append(orphaned, balanceOrphaned...) } func (node *Node) getLeftNode(t *Tree) *Node { @@ -502,34 +525,32 @@ func (node *Node) balance(t *Tree) (newSelf *Node, orphaned []*Node) { // Left Left Case newNode, orphaned := node.rotateRight(t) return newNode, []*Node{orphaned} - } else { - // Left Right Case - var leftOrphaned *Node + } + // Left Right Case + var leftOrphaned *Node - left := node.getLeftNode(t) - node.leftHash = nil - node.leftNode, leftOrphaned = left.rotateLeft(t) - newNode, rightOrphaned := node.rotateRight(t) + left := node.getLeftNode(t) + node.leftHash = nil + node.leftNode, leftOrphaned = left.rotateLeft(t) + newNode, rightOrphaned := node.rotateRight(t) - return newNode, []*Node{left, leftOrphaned, rightOrphaned} - } + return newNode, []*Node{left, leftOrphaned, rightOrphaned} } if balance < -1 { if node.getRightNode(t).calcBalance(t) <= 0 { // Right Right Case newNode, orphaned := node.rotateLeft(t) return newNode, []*Node{orphaned} - } else { - // Right Left Case - var rightOrphaned *Node + } + // Right Left Case + var rightOrphaned *Node - right := node.getRightNode(t) - node.rightHash = nil - node.rightNode, rightOrphaned = right.rotateRight(t) - newNode, leftOrphaned := node.rotateLeft(t) + right := node.getRightNode(t) + node.rightHash = nil + node.rightNode, rightOrphaned = right.rotateRight(t) + newNode, leftOrphaned := node.rotateLeft(t) - return newNode, []*Node{right, leftOrphaned, rightOrphaned} - } + return newNode, []*Node{right, leftOrphaned, rightOrphaned} } // Nothing changed return node, []*Node{} @@ -547,19 +568,20 @@ func (node *Node) traverseWithDepth(t *Tree, ascending bool, cb func(*Node, uint } func (node *Node) traverseInRange(t *Tree, start, end []byte, ascending bool, inclusive bool, depth uint8, cb func(*Node, uint8) bool) bool { - afterStart := start == nil || bytes.Compare(start, node.key) <= 0 + afterStart := start == nil || bytes.Compare(start, node.key) < 0 + startOrAfter := start == nil || bytes.Compare(start, node.key) <= 0 beforeEnd := end == nil || bytes.Compare(node.key, end) < 0 if inclusive { beforeEnd = end == nil || bytes.Compare(node.key, end) <= 0 } + // Run callback per inner/leaf node. stop := false - if afterStart && beforeEnd { - // IterateRange ignores this if not leaf + if !node.isLeaf() || (startOrAfter && beforeEnd) { stop = cb(node, depth) - } - if stop { - return stop + if stop { + return stop + } } if node.isLeaf() { return stop diff --git a/vendor/github.com/tendermint/iavl/nodedb.go b/vendor/github.com/tendermint/iavl/nodedb.go index 2f546cb72..d0d3df19c 100644 --- a/vendor/github.com/tendermint/iavl/nodedb.go +++ b/vendor/github.com/tendermint/iavl/nodedb.go @@ -7,14 +7,14 @@ import ( "sort" "sync" - dbm "github.com/tendermint/tmlibs/db" + dbm "github.com/tendermint/tendermint/libs/db" ) var ( // All node keys are prefixed with this. This ensures no collision is // possible with the other keys, and makes them easier to traverse. nodePrefix = "n/" - nodeKeyFmt = "n/%x" + nodeKeyFmt = "n/%X" // Orphans are keyed in the database by their expected lifetime. // The first number represents the *last* version at which the orphan needs @@ -22,12 +22,12 @@ var ( // which it is expected to exist - which starts out by being the version // of the node being orphaned. orphanPrefix = "o/" - orphanPrefixFmt = "o/%d/" // o// - orphanKeyFmt = "o/%d/%d/%x" // o/// + orphanPrefixFmt = "o/%010d/" // o// + orphanKeyFmt = "o/%010d/%010d/%X" // o/// // r/ rootPrefix = "r/" - rootPrefixFmt = "r/%d" + rootPrefixFmt = "r/%010d" ) type nodeDB struct { @@ -35,9 +35,7 @@ type nodeDB struct { db dbm.DB // Persistent node storage. batch dbm.Batch // Batched writing buffer. - versionCache map[int64][]byte // Cache of tree (root) versions. - latestVersion int64 // Latest root version. - + latestVersion int64 nodeCache map[string]*list.Element // Node cache. nodeCacheSize int // Node cache size limit in elements. nodeCacheQueue *list.List // LRU queue of cache elements. Used for deletion. @@ -47,7 +45,6 @@ func newNodeDB(db dbm.DB, cacheSize int) *nodeDB { ndb := &nodeDB{ db: db, batch: db.NewBatch(), - versionCache: map[int64][]byte{}, latestVersion: 0, // initially invalid nodeCache: make(map[string]*list.Element), nodeCacheSize: cacheSize, @@ -171,7 +168,6 @@ func (ndb *nodeDB) SaveOrphans(version int64, orphans map[string]int64) { defer ndb.mtx.Unlock() toVersion := ndb.getPreviousVersion(version) - for hash, fromVersion := range orphans { debug("SAVEORPHAN %v-%v %X\n", fromVersion, toVersion, hash) ndb.saveOrphan([]byte(hash), fromVersion, toVersion) @@ -194,6 +190,7 @@ func (ndb *nodeDB) deleteOrphans(version int64) { predecessor := ndb.getPreviousVersion(version) // Traverse orphans with a lifetime ending at the version specified. + // TODO optimize. ndb.traverseOrphansVersion(version, func(key, hash []byte) { var fromVersion, toVersion int64 @@ -234,38 +231,36 @@ func (ndb *nodeDB) rootKey(version int64) []byte { func (ndb *nodeDB) getLatestVersion() int64 { if ndb.latestVersion == 0 { - ndb.getVersions() + ndb.latestVersion = ndb.getPreviousVersion(1<<63 - 1) } return ndb.latestVersion } -func (ndb *nodeDB) getVersions() map[int64][]byte { - if len(ndb.versionCache) == 0 { - ndb.traversePrefix([]byte(rootPrefix), func(k, hash []byte) { - var version int64 - fmt.Sscanf(string(k), rootPrefixFmt, &version) - ndb.cacheVersion(version, hash) - }) - } - return ndb.versionCache -} - -func (ndb *nodeDB) cacheVersion(version int64, hash []byte) { - ndb.versionCache[version] = hash - - if version > ndb.getLatestVersion() { +func (ndb *nodeDB) updateLatestVersion(version int64) { + if ndb.latestVersion < version { ndb.latestVersion = version } } func (ndb *nodeDB) getPreviousVersion(version int64) int64 { - var result int64 - for v := range ndb.getVersions() { - if v < version && v > result { - result = v + itr := ndb.db.ReverseIterator( + []byte(fmt.Sprintf(rootPrefixFmt, version-1)), + []byte(fmt.Sprintf(rootPrefixFmt, 0)), + ) + defer itr.Close() + + pversion := int64(-1) + for ; itr.Valid(); itr.Next() { + k := itr.Key() + _, err := fmt.Sscanf(string(k), rootPrefixFmt, &pversion) + if err != nil { + panic(err) + } else { + return pversion } } - return result + + return 0 } // deleteRoot deletes the root entry from disk, but not the node it points to. @@ -276,7 +271,6 @@ func (ndb *nodeDB) deleteRoot(version int64) { key := ndb.rootKey(version) ndb.batch.Delete(key) - delete(ndb.versionCache, version) } func (ndb *nodeDB) traverseOrphans(fn func(k, v []byte)) { @@ -373,7 +367,7 @@ func (ndb *nodeDB) saveRoot(hash []byte, version int64) error { key := ndb.rootKey(version) ndb.batch.Set(key, hash) - ndb.cacheVersion(version, hash) + ndb.updateLatestVersion(version) return nil } diff --git a/vendor/github.com/tendermint/iavl/orphaning_tree.go b/vendor/github.com/tendermint/iavl/orphaning_tree.go index 893afeaf8..fb7493f28 100644 --- a/vendor/github.com/tendermint/iavl/orphaning_tree.go +++ b/vendor/github.com/tendermint/iavl/orphaning_tree.go @@ -45,6 +45,7 @@ func (tree *orphaningTree) SaveAs(version int64) { if tree.root == nil { // There can still be orphans, for example if the root is the node being // removed. + debug("SAVE EMPTY TREE %v\n", version) tree.ndb.SaveOrphans(version, tree.orphans) tree.ndb.SaveEmptyRoot(version) } else { diff --git a/vendor/github.com/tendermint/iavl/path.go b/vendor/github.com/tendermint/iavl/path.go deleted file mode 100644 index 7e3bb01d9..000000000 --- a/vendor/github.com/tendermint/iavl/path.go +++ /dev/null @@ -1,156 +0,0 @@ -package iavl - -import ( - "bytes" - - "github.com/pkg/errors" -) - -// PathToKey represents an inner path to a leaf node. -// Note that the nodes are ordered such that the last one is closest -// to the root of the tree. -type PathToKey struct { - InnerNodes []proofInnerNode `json:"inner_nodes"` -} - -func (p *PathToKey) String() string { - str := "" - for i := len(p.InnerNodes) - 1; i >= 0; i-- { - str += p.InnerNodes[i].String() + "\n" - } - return str -} - -// verify check that the leafNode's hash matches the path's LeafHash and that -// the root is the merkle hash of all the inner nodes. -func (p *PathToKey) verify(leafHash []byte, root []byte) error { - hash := leafHash - for _, branch := range p.InnerNodes { - hash = branch.Hash(hash) - } - if !bytes.Equal(root, hash) { - return errors.WithStack(ErrInvalidProof) - } - return nil -} - -func (p *PathToKey) isLeftmost() bool { - for _, node := range p.InnerNodes { - if len(node.Left) > 0 { - return false - } - } - return true -} - -func (p *PathToKey) isRightmost() bool { - for _, node := range p.InnerNodes { - if len(node.Right) > 0 { - return false - } - } - return true -} - -func (p *PathToKey) isEmpty() bool { - return p == nil || len(p.InnerNodes) == 0 -} - -func (p *PathToKey) dropRoot() *PathToKey { - if p.isEmpty() { - return p - } - return &PathToKey{ - InnerNodes: p.InnerNodes[:len(p.InnerNodes)-1], - } -} - -func (p *PathToKey) hasCommonRoot(p2 *PathToKey) bool { - if p.isEmpty() || p2.isEmpty() { - return false - } - leftEnd := p.InnerNodes[len(p.InnerNodes)-1] - rightEnd := p2.InnerNodes[len(p2.InnerNodes)-1] - - return bytes.Equal(leftEnd.Left, rightEnd.Left) && - bytes.Equal(leftEnd.Right, rightEnd.Right) -} - -func (p *PathToKey) isLeftAdjacentTo(p2 *PathToKey) bool { - for p.hasCommonRoot(p2) { - p, p2 = p.dropRoot(), p2.dropRoot() - } - p, p2 = p.dropRoot(), p2.dropRoot() - - return p.isRightmost() && p2.isLeftmost() -} - -// PathWithNode is a path to a key which includes the leaf node at that key. -type pathWithNode struct { - Path *PathToKey `json:"path"` - Node proofLeafNode `json:"node"` -} - -func (p *pathWithNode) verify(root []byte) error { - return p.Path.verify(p.Node.Hash(), root) -} - -// verifyPaths verifies the left and right paths individually, and makes sure -// the ordering is such that left < startKey <= endKey < right. -func verifyPaths(left, right *pathWithNode, startKey, endKey, root []byte) error { - if bytes.Compare(startKey, endKey) == 1 { - return ErrInvalidInputs - } - if left != nil { - if err := left.verify(root); err != nil { - return err - } - if !left.Node.isLesserThan(startKey) { - return errors.WithStack(ErrInvalidProof) - } - } - if right != nil { - if err := right.verify(root); err != nil { - return err - } - if !right.Node.isGreaterThan(endKey) { - return errors.WithStack(ErrInvalidProof) - } - } - return nil -} - -// Checks that all paths are adjacent to one another, ie. that there are no -// keys missing. -func verifyNoMissingKeys(paths []*PathToKey) error { - ps := make([]*PathToKey, 0, len(paths)) - for _, p := range paths { - if p != nil { - ps = append(ps, p) - } - } - for i := 0; i < len(ps)-1; i++ { - // Always check from left to right, since paths are always in ascending order. - if !ps[i].isLeftAdjacentTo(ps[i+1]) { - return errors.Errorf("paths #%d and #%d are not adjacent", i, i+1) - } - } - return nil -} - -// Checks that with the given left and right paths, no keys can exist in between. -// Supports nil paths to signify out-of-range. -func verifyKeyAbsence(left, right *pathWithNode) error { - if left != nil && left.Path.isRightmost() { - // Range starts outside of the right boundary. - return nil - } else if right != nil && right.Path.isLeftmost() { - // Range ends outside of the left boundary. - return nil - } else if left != nil && right != nil && - left.Path.isLeftAdjacentTo(right.Path) { - // Range is between two existing keys. - return nil - } - return errors.WithStack(ErrInvalidProof) -} diff --git a/vendor/github.com/tendermint/iavl/proof.go b/vendor/github.com/tendermint/iavl/proof.go index c770ea96f..a87877048 100644 --- a/vendor/github.com/tendermint/iavl/proof.go +++ b/vendor/github.com/tendermint/iavl/proof.go @@ -4,11 +4,9 @@ import ( "bytes" "fmt" - "github.com/pkg/errors" - "github.com/tendermint/go-amino" - "github.com/tendermint/iavl/sha256truncated" - cmn "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tendermint/crypto/tmhash" + cmn "github.com/tendermint/tendermint/libs/common" ) var ( @@ -25,40 +23,58 @@ var ( ErrNilRoot = fmt.Errorf("tree root is nil") ) +//---------------------------------------- + type proofInnerNode struct { - Height int8 - Size int64 - Version int64 - Left []byte - Right []byte + Height int8 `json:"height"` + Size int64 `json:"size"` + Version int64 `json:"version"` + Left []byte `json:"left"` + Right []byte `json:"right"` +} + +func (pin proofInnerNode) String() string { + return pin.stringIndented("") } -func (n *proofInnerNode) String() string { - return fmt.Sprintf("proofInnerNode[height=%d, ver=%d %x / %x]", n.Height, n.Version, n.Left, n.Right) +func (pin proofInnerNode) stringIndented(indent string) string { + return fmt.Sprintf(`proofInnerNode{ +%s Height: %v +%s Size: %v +%s Version: %v +%s Left: %X +%s Right: %X +%s}`, + indent, pin.Height, + indent, pin.Size, + indent, pin.Version, + indent, pin.Left, + indent, pin.Right, + indent) } -func (branch proofInnerNode) Hash(childHash []byte) []byte { - hasher := sha256truncated.New() +func (pin proofInnerNode) Hash(childHash []byte) []byte { + hasher := tmhash.New() buf := new(bytes.Buffer) - err := amino.EncodeInt8(buf, branch.Height) + err := amino.EncodeInt8(buf, pin.Height) if err == nil { - err = amino.EncodeInt64(buf, branch.Size) + err = amino.EncodeVarint(buf, pin.Size) } if err == nil { - err = amino.EncodeInt64(buf, branch.Version) + err = amino.EncodeVarint(buf, pin.Version) } - if len(branch.Left) == 0 { + if len(pin.Left) == 0 { if err == nil { err = amino.EncodeByteSlice(buf, childHash) } if err == nil { - err = amino.EncodeByteSlice(buf, branch.Right) + err = amino.EncodeByteSlice(buf, pin.Right) } } else { if err == nil { - err = amino.EncodeByteSlice(buf, branch.Left) + err = amino.EncodeByteSlice(buf, pin.Left) } if err == nil { err = amino.EncodeByteSlice(buf, childHash) @@ -67,33 +83,51 @@ func (branch proofInnerNode) Hash(childHash []byte) []byte { if err != nil { panic(fmt.Sprintf("Failed to hash proofInnerNode: %v", err)) } - hasher.Write(buf.Bytes()) + hasher.Write(buf.Bytes()) return hasher.Sum(nil) } +//---------------------------------------- + type proofLeafNode struct { - KeyBytes cmn.HexBytes `json:"key"` - ValueBytes cmn.HexBytes `json:"value"` - Version int64 `json:"version"` + Key cmn.HexBytes `json:"key"` + ValueHash cmn.HexBytes `json:"value"` + Version int64 `json:"version"` } -func (leaf proofLeafNode) Hash() []byte { - hasher := sha256truncated.New() +func (pln proofLeafNode) String() string { + return pln.stringIndented("") +} + +func (pln proofLeafNode) stringIndented(indent string) string { + return fmt.Sprintf(`proofLeafNode{ +%s Key: %v +%s ValueHash: %X +%s Version: %v +%s}`, + indent, pln.Key, + indent, pln.ValueHash, + indent, pln.Version, + indent) +} + +func (pln proofLeafNode) Hash() []byte { + hasher := tmhash.New() buf := new(bytes.Buffer) err := amino.EncodeInt8(buf, 0) if err == nil { - err = amino.EncodeInt64(buf, 1) + err = amino.EncodeVarint(buf, 1) } if err == nil { - err = amino.EncodeInt64(buf, leaf.Version) + err = amino.EncodeVarint(buf, pln.Version) } if err == nil { - err = amino.EncodeByteSlice(buf, leaf.KeyBytes) + err = amino.EncodeByteSlice(buf, pln.Key) } if err == nil { - err = amino.EncodeByteSlice(buf, leaf.ValueBytes) + err = amino.EncodeByteSlice(buf, pln.ValueHash) } if err != nil { panic(fmt.Sprintf("Failed to hash proofLeafNode: %v", err)) @@ -103,157 +137,50 @@ func (leaf proofLeafNode) Hash() []byte { return hasher.Sum(nil) } -func (leaf proofLeafNode) isLesserThan(key []byte) bool { - return bytes.Compare(leaf.KeyBytes, key) == -1 -} - -func (leaf proofLeafNode) isGreaterThan(key []byte) bool { - return bytes.Compare(leaf.KeyBytes, key) == 1 -} +//---------------------------------------- -func (node *Node) pathToInnerKey(t *Tree, key []byte) (*PathToKey, *Node, error) { - path := &PathToKey{} - val, err := node._pathToKey(t, key, false, path) - return path, val, err +// If the key does not exist, returns the path to the next leaf left of key (w/ +// path), except when key is less than the least item, in which case it returns +// a path to the least item. +func (node *Node) PathToLeaf(t *Tree, key []byte) (PathToLeaf, *Node, error) { + path := new(PathToLeaf) + val, err := node.pathToLeaf(t, key, path) + return *path, val, err } -func (node *Node) pathToKey(t *Tree, key []byte) (*PathToKey, *Node, error) { - path := &PathToKey{} - val, err := node._pathToKey(t, key, true, path) - return path, val, err -} -func (node *Node) _pathToKey(t *Tree, key []byte, skipInner bool, path *PathToKey) (*Node, error) { +// pathToLeaf is a helper which recursively constructs the PathToLeaf. +// As an optimization the already constructed path is passed in as an argument +// and is shared among recursive calls. +func (node *Node) pathToLeaf(t *Tree, key []byte, path *PathToLeaf) (*Node, error) { if node.height == 0 { if bytes.Equal(node.key, key) { return node, nil } - return nil, errors.New("key does not exist") - } else if !skipInner && bytes.Equal(node.key, key) { - return node, nil + return node, cmn.NewError("key does not exist") } if bytes.Compare(key, node.key) < 0 { - if n, err := node.getLeftNode(t)._pathToKey(t, key, skipInner, path); err != nil { - return nil, err - } else { - branch := proofInnerNode{ - Height: node.height, - Size: node.size, - Version: node.version, - Left: nil, - Right: node.getRightNode(t).hash, - } - path.InnerNodes = append(path.InnerNodes, branch) - return n, nil - } - } - - if n, err := node.getRightNode(t)._pathToKey(t, key, skipInner, path); err != nil { - return nil, err - } else { - branch := proofInnerNode{ + // left side + pin := proofInnerNode{ Height: node.height, Size: node.size, Version: node.version, - Left: node.getLeftNode(t).hash, - Right: nil, - } - path.InnerNodes = append(path.InnerNodes, branch) - return n, nil - } -} - -func (t *Tree) constructKeyAbsentProof(key []byte, proof *KeyAbsentProof) error { - // Get the index of the first key greater than the requested key, if the key doesn't exist. - idx, val := t.Get64(key) - if val != nil { - return errors.Errorf("couldn't construct non-existence proof: key 0x%x exists", key) - } - - var ( - lkey, lval []byte - rkey, rval []byte - ) - if idx > 0 { - lkey, lval = t.GetByIndex64(idx - 1) - } - if idx <= t.Size64()-1 { - rkey, rval = t.GetByIndex64(idx) - } - - if lkey == nil && rkey == nil { - return errors.New("couldn't get keys required for non-existence proof") - } - - if lkey != nil { - path, node, _ := t.root.pathToKey(t, lkey) - proof.Left = &pathWithNode{ - Path: path, - Node: proofLeafNode{lkey, lval, node.version}, - } - } - if rkey != nil { - path, node, _ := t.root.pathToKey(t, rkey) - proof.Right = &pathWithNode{ - Path: path, - Node: proofLeafNode{rkey, rval, node.version}, + Left: nil, + Right: node.getRightNode(t).hash, } - } - - return nil -} - -func (t *Tree) getWithProof(key []byte) (value []byte, proof *KeyExistsProof, err error) { - if t.root == nil { - return nil, nil, errors.WithStack(ErrNilRoot) - } - t.root.hashWithCount() // Ensure that all hashes are calculated. - - path, node, err := t.root.pathToKey(t, key) - if err != nil { - return nil, nil, errors.Wrap(err, "could not construct path to key") - } - - proof = &KeyExistsProof{ - RootHash: t.root.hash, - PathToKey: path, - Version: node.version, - } - return node.value, proof, nil -} - -func (t *Tree) getInnerWithProof(key []byte) (proof *InnerKeyProof, err error) { - if t.root == nil { - return nil, errors.WithStack(ErrNilRoot) - } - t.root.hashWithCount() // Ensure that all hashes are calculated. - - path, node, err := t.root.pathToInnerKey(t, key) - if err != nil { - return nil, errors.Wrap(err, "could not construct path to key") - } - - proof = &InnerKeyProof{ - &KeyExistsProof{ - RootHash: t.root.hash, - PathToKey: path, - Version: node.version, - }, - } - return proof, nil -} - -func (t *Tree) keyAbsentProof(key []byte) (*KeyAbsentProof, error) { - if t.root == nil { - return nil, errors.WithStack(ErrNilRoot) - } - t.root.hashWithCount() // Ensure that all hashes are calculated. - - proof := &KeyAbsentProof{ - RootHash: t.root.hash, - } - if err := t.constructKeyAbsentProof(key, proof); err != nil { - return nil, errors.Wrap(err, "could not construct proof of non-existence") - } - return proof, nil + *path = append(*path, pin) + n, err := node.getLeftNode(t).pathToLeaf(t, key, path) + return n, err + } + // right side + pin := proofInnerNode{ + Height: node.height, + Size: node.size, + Version: node.version, + Left: node.getLeftNode(t).hash, + Right: nil, + } + *path = append(*path, pin) + n, err := node.getRightNode(t).pathToLeaf(t, key, path) + return n, err } diff --git a/vendor/github.com/tendermint/iavl/proof_key.go b/vendor/github.com/tendermint/iavl/proof_key.go deleted file mode 100644 index e9c900884..000000000 --- a/vendor/github.com/tendermint/iavl/proof_key.go +++ /dev/null @@ -1,161 +0,0 @@ -package iavl - -import ( - "bytes" - "fmt" - - "github.com/pkg/errors" - cmn "github.com/tendermint/tmlibs/common" -) - -// KeyProof represents a proof of existence or absence of a single key. -type KeyProof interface { - // Verify verfies the proof is valid. To verify absence, - // the value should be nil. - Verify(key, value, root []byte) error - - // Root returns the root hash of the proof. - Root() []byte - - // Serialize itself - Bytes() []byte -} - -const ( - // Used for serialization of proofs. - keyExistsMagicNumber = 0x50 - keyAbsentMagicNumber = 0x51 -) - -// KeyExistsProof represents a proof of existence of a single key. -type KeyExistsProof struct { - RootHash cmn.HexBytes `json:"root_hash"` - Version int64 `json:"version"` - - *PathToKey `json:"path"` -} - -func (proof *KeyExistsProof) Root() []byte { - return proof.RootHash -} - -// Verify verifies the proof is valid and returns an error if it isn't. -func (proof *KeyExistsProof) Verify(key []byte, value []byte, root []byte) error { - if !bytes.Equal(proof.RootHash, root) { - return errors.WithStack(ErrInvalidRoot) - } - if key == nil || value == nil { - return errors.WithStack(ErrInvalidInputs) - } - return proof.PathToKey.verify(proofLeafNode{key, value, proof.Version}.Hash(), root) -} - -// Bytes returns a go-amino binary serialization -func (proof *KeyExistsProof) Bytes() []byte { - bz, err := cdc.MarshalBinary(proof) - if err != nil { - panic(fmt.Sprintf("error marshaling proof (%v): %v", proof, err)) - } - return append([]byte{keyExistsMagicNumber}, bz...) -} - -// readKeyExistsProof will deserialize a KeyExistsProof from bytes. -func readKeyExistsProof(data []byte) (*KeyExistsProof, error) { - proof := new(KeyExistsProof) - err := cdc.UnmarshalBinary(data, proof) - return proof, err -} - -/////////////////////////////////////////////////////////////////////////////// - -// KeyAbsentProof represents a proof of the absence of a single key. -type KeyAbsentProof struct { - RootHash cmn.HexBytes `json:"root_hash"` - - Left *pathWithNode `json:"left"` - Right *pathWithNode `json:"right"` -} - -func (proof *KeyAbsentProof) Root() []byte { - return proof.RootHash -} - -func (p *KeyAbsentProof) String() string { - return fmt.Sprintf("KeyAbsentProof\nroot=%s\nleft=%s%#v\nright=%s%#v\n", p.RootHash, p.Left.Path, p.Left.Node, p.Right.Path, p.Right.Node) -} - -// Verify verifies the proof is valid and returns an error if it isn't. -func (proof *KeyAbsentProof) Verify(key, value []byte, root []byte) error { - if !bytes.Equal(proof.RootHash, root) { - return errors.WithStack(ErrInvalidRoot) - } - if key == nil || value != nil { - return ErrInvalidInputs - } - - if proof.Left == nil && proof.Right == nil { - return errors.WithStack(ErrInvalidProof) - } - if err := verifyPaths(proof.Left, proof.Right, key, key, root); err != nil { - return err - } - - return verifyKeyAbsence(proof.Left, proof.Right) -} - -// Bytes returns a go-wire binary serialization -func (proof *KeyAbsentProof) Bytes() []byte { - bz, err := cdc.MarshalBinary(proof) - if err != nil { - panic(fmt.Sprintf("error marshaling proof (%v): %v", proof, err)) - } - return append([]byte{keyAbsentMagicNumber}, bz...) -} - -// readKeyAbsentProof will deserialize a KeyAbsentProof from bytes. -func readKeyAbsentProof(data []byte) (*KeyAbsentProof, error) { - proof := new(KeyAbsentProof) - err := cdc.UnmarshalBinary(data, proof) - return proof, err -} - -// ReadKeyProof reads a KeyProof from a byte-slice. -func ReadKeyProof(data []byte) (KeyProof, error) { - if len(data) == 0 { - return nil, errors.New("proof bytes are empty") - } - b, val := data[0], data[1:] - - switch b { - case keyExistsMagicNumber: - return readKeyExistsProof(val) - case keyAbsentMagicNumber: - return readKeyAbsentProof(val) - } - return nil, errors.New("unrecognized proof") -} - -/////////////////////////////////////////////////////////////////////////////// - -// InnerKeyProof represents a proof of existence of an inner node key. -type InnerKeyProof struct { - *KeyExistsProof -} - -// Verify verifies the proof is valid and returns an error if it isn't. -func (proof *InnerKeyProof) Verify(hash []byte, value []byte, root []byte) error { - if !bytes.Equal(proof.RootHash, root) { - return errors.WithStack(ErrInvalidRoot) - } - if hash == nil || value != nil { - return errors.WithStack(ErrInvalidInputs) - } - return proof.PathToKey.verify(hash, root) -} - -// ReadKeyInnerProof will deserialize a InnerKeyProof from bytes. -func ReadInnerKeyProof(data []byte) (*InnerKeyProof, error) { - proof := new(InnerKeyProof) - err := cdc.UnmarshalBinary(data, proof) - return proof, err -} diff --git a/vendor/github.com/tendermint/iavl/proof_path.go b/vendor/github.com/tendermint/iavl/proof_path.go new file mode 100644 index 000000000..de366f338 --- /dev/null +++ b/vendor/github.com/tendermint/iavl/proof_path.go @@ -0,0 +1,167 @@ +package iavl + +import ( + "bytes" + "fmt" + "strings" + + cmn "github.com/tendermint/tendermint/libs/common" +) + +// pathWithLeaf is a path to a leaf node and the leaf node itself. +type pathWithLeaf struct { + Path PathToLeaf `json:"path"` + Leaf proofLeafNode `json:"leaf"` +} + +func (pwl pathWithLeaf) String() string { + return pwl.StringIndented("") +} + +func (pwl pathWithLeaf) StringIndented(indent string) string { + return fmt.Sprintf(`pathWithLeaf{ +%s Path: %v +%s Leaf: %v +%s}`, + indent, pwl.Path.stringIndented(indent+" "), + indent, pwl.Leaf.stringIndented(indent+" "), + indent) +} + +// `verify` checks that the leaf node's hash + the inner nodes merkle-izes to +// the given root. If it returns an error, it means the leafHash or the +// PathToLeaf is incorrect. +func (pwl pathWithLeaf) verify(root []byte) cmn.Error { + leafHash := pwl.Leaf.Hash() + return pwl.Path.verify(leafHash, root) +} + +// `computeRootHash` computes the root hash with leaf node. +// Does not verify the root hash. +func (pwl pathWithLeaf) computeRootHash() []byte { + leafHash := pwl.Leaf.Hash() + return pwl.Path.computeRootHash(leafHash) +} + +//---------------------------------------- + +// PathToLeaf represents an inner path to a leaf node. +// Note that the nodes are ordered such that the last one is closest +// to the root of the tree. +type PathToLeaf []proofInnerNode + +func (pl PathToLeaf) String() string { + return pl.stringIndented("") +} + +func (pl PathToLeaf) stringIndented(indent string) string { + if len(pl) == 0 { + return "empty-PathToLeaf" + } + strs := make([]string, len(pl)) + for i, pin := range pl { + if i == 20 { + strs[i] = fmt.Sprintf("... (%v total)", len(pl)) + break + } + strs[i] = fmt.Sprintf("%v:%v", i, pin.stringIndented(indent+" ")) + } + return fmt.Sprintf(`PathToLeaf{ +%s %v +%s}`, + indent, strings.Join(strs, "\n"+indent+" "), + indent) +} + +// `verify` checks that the leaf node's hash + the inner nodes merkle-izes to +// the given root. If it returns an error, it means the leafHash or the +// PathToLeaf is incorrect. +func (pl PathToLeaf) verify(leafHash []byte, root []byte) cmn.Error { + hash := leafHash + for i := len(pl) - 1; i >= 0; i-- { + pin := pl[i] + hash = pin.Hash(hash) + } + if !bytes.Equal(root, hash) { + return cmn.ErrorWrap(ErrInvalidProof, "") + } + return nil +} + +// `computeRootHash` computes the root hash assuming some leaf hash. +// Does not verify the root hash. +func (pl PathToLeaf) computeRootHash(leafHash []byte) []byte { + hash := leafHash + for i := len(pl) - 1; i >= 0; i-- { + pin := pl[i] + hash = pin.Hash(hash) + } + return hash +} + +func (pl PathToLeaf) isLeftmost() bool { + for _, node := range pl { + if len(node.Left) > 0 { + return false + } + } + return true +} + +func (pl PathToLeaf) isRightmost() bool { + for _, node := range pl { + if len(node.Right) > 0 { + return false + } + } + return true +} + +func (pl PathToLeaf) isEmpty() bool { + return pl == nil || len(pl) == 0 +} + +func (pl PathToLeaf) dropRoot() PathToLeaf { + if pl.isEmpty() { + return pl + } + return PathToLeaf(pl[:len(pl)-1]) +} + +func (pl PathToLeaf) hasCommonRoot(pl2 PathToLeaf) bool { + if pl.isEmpty() || pl2.isEmpty() { + return false + } + leftEnd := pl[len(pl)-1] + rightEnd := pl2[len(pl2)-1] + + return bytes.Equal(leftEnd.Left, rightEnd.Left) && + bytes.Equal(leftEnd.Right, rightEnd.Right) +} + +func (pl PathToLeaf) isLeftAdjacentTo(pl2 PathToLeaf) bool { + for pl.hasCommonRoot(pl2) { + pl, pl2 = pl.dropRoot(), pl2.dropRoot() + } + pl, pl2 = pl.dropRoot(), pl2.dropRoot() + + return pl.isRightmost() && pl2.isLeftmost() +} + +// returns -1 if invalid. +func (pl PathToLeaf) Index() (idx int64) { + for i, node := range pl { + if node.Left == nil { + continue + } else if node.Right == nil { + if i < len(pl)-1 { + idx += node.Size - pl[i+1].Size + } else { + idx += node.Size - 1 + } + } else { + return -1 + } + } + return idx +} diff --git a/vendor/github.com/tendermint/iavl/proof_range.go b/vendor/github.com/tendermint/iavl/proof_range.go index 403740559..cc12618f9 100644 --- a/vendor/github.com/tendermint/iavl/proof_range.go +++ b/vendor/github.com/tendermint/iavl/proof_range.go @@ -3,445 +3,490 @@ package iavl import ( "bytes" "fmt" + "sort" + "strings" - "github.com/pkg/errors" - cmn "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tendermint/crypto/tmhash" + cmn "github.com/tendermint/tendermint/libs/common" ) -// KeyInRangeProof is an interface which covers both first-in-range and last-in-range proofs. -type KeyInRangeProof interface { - Verify(startKey, endKey, key, value, root []byte) error -} - -// KeyFirstInRangeProof is a proof that a given key is the first in a given range. -type KeyFirstInRangeProof struct { - KeyExistsProof `json:"key_proof"` +type RangeProof struct { + // You don't need the right path because + // it can be derived from what we have. + LeftPath PathToLeaf `json:"left_path"` + InnerNodes []PathToLeaf `json:"inner_nodes"` + Leaves []proofLeafNode `json:"leaves"` - Left *pathWithNode `json:"left"` - Right *pathWithNode `json:"right"` -} + // memoize + rootVerified bool + rootHash []byte // valid iff rootVerified is true + treeEnd bool // valid iff rootVerified is true -// String returns a string representation of the proof. -func (proof *KeyFirstInRangeProof) String() string { - return fmt.Sprintf("%#v", proof) } -// Verify that the first in range proof is valid. -func (proof *KeyFirstInRangeProof) Verify(startKey, endKey, key, value []byte, root []byte) error { - if key != nil { - inputsOutOfRange := bytes.Compare(key, startKey) == -1 || bytes.Compare(key, endKey) == 1 - if inputsOutOfRange { - return ErrInvalidInputs - } - } - if proof.Left == nil && proof.Right == nil && proof.PathToKey == nil { - return errors.WithStack(ErrInvalidProof) - } - if err := verifyPaths(proof.Left, proof.Right, startKey, endKey, root); err != nil { - return err - } - if proof.PathToKey == nil { - // If we don't have an existing key, we effectively have a proof of absence. - return verifyKeyAbsence(proof.Left, proof.Right) - } - - if err := proof.KeyExistsProof.Verify(key, value, root); err != nil { - return errors.Wrap(err, "failed to verify key exists proof") - } - // If the key returned is equal to our start key, and we've verified - // that it exists, there's nothing else to check. - if bytes.Equal(key, startKey) { +// Keys returns all the keys in the RangeProof. NOTE: The keys here may +// include more keys than provided by tree.GetRangeWithProof or +// VersionedTree.GetVersionedRangeWithProof. The keys returned there are only +// in the provided [startKey,endKey){limit} range. The keys returned here may +// include extra keys, such as: +// - the key before startKey if startKey is provided and doesn't exist; +// - the key after a queried key with tree.GetWithProof, when the key is absent. +func (proof *RangeProof) Keys() (keys [][]byte) { + if proof == nil { return nil } - // If the key returned is the smallest in the tree, then it must be - // the smallest in the given range too. - if proof.PathToKey.isLeftmost() { - return nil - } - // The start key is in between the left path and the key returned, - // and the paths are adjacent. Therefore there is nothing between - // the key returned and the start key. - if proof.Left != nil && proof.Left.Path.isLeftAdjacentTo(proof.PathToKey) { - return nil + for _, leaf := range proof.Leaves { + keys = append(keys, leaf.Key) } - return errors.WithStack(ErrInvalidProof) + return keys } -/////////////////////////////////////////////////////////////////////////////// - -// KeyLastInRangeProof is a proof that a given key is the last in a given range. -type KeyLastInRangeProof struct { - KeyExistsProof `json:"key_proof"` - - Left *pathWithNode `json:"left"` - Right *pathWithNode `json:"right"` +// String returns a string representation of the proof. +func (proof *RangeProof) String() string { + if proof == nil { + return "" + } + return proof.StringIndented("") } -// String returns a string representation of the proof. -func (proof *KeyLastInRangeProof) String() string { - // TODO(cloudhead): Needs work. - return fmt.Sprintf("%#v", proof) +func (proof *RangeProof) StringIndented(indent string) string { + istrs := make([]string, 0, len(proof.InnerNodes)) + for _, ptl := range proof.InnerNodes { + istrs = append(istrs, ptl.stringIndented(indent+" ")) + } + lstrs := make([]string, 0, len(proof.Leaves)) + for _, leaf := range proof.Leaves { + lstrs = append(lstrs, leaf.stringIndented(indent+" ")) + } + return fmt.Sprintf(`RangeProof{ +%s LeftPath: %v +%s InnerNodes: +%s %v +%s Leaves: +%s %v +%s (rootVerified): %v +%s (rootHash): %X +%s (treeEnd): %v +%s}`, + indent, proof.LeftPath.stringIndented(indent+" "), + indent, + indent, strings.Join(istrs, "\n"+indent+" "), + indent, + indent, strings.Join(lstrs, "\n"+indent+" "), + indent, proof.rootVerified, + indent, proof.rootHash, + indent, proof.treeEnd, + indent) } -// Verify that the last in range proof is valid. -func (proof *KeyLastInRangeProof) Verify(startKey, endKey, key, value []byte, root []byte) error { - if key != nil && (bytes.Compare(key, startKey) == -1 || bytes.Compare(key, endKey) == 1) { - return ErrInvalidInputs - } - if proof.Left == nil && proof.Right == nil && proof.PathToKey == nil { - return errors.WithStack(ErrInvalidProof) - } - if err := verifyPaths(proof.Left, proof.Right, startKey, endKey, root); err != nil { - return err - } - if proof.PathToKey == nil { - // If we don't have an existing key, we effectively have a proof of absence. - return verifyKeyAbsence(proof.Left, proof.Right) +// The index of the first leaf (of the whole tree). +// Returns -1 if the proof is nil. +func (proof *RangeProof) LeftIndex() int64 { + if proof == nil { + return -1 } + return proof.LeftPath.Index() +} - if err := proof.KeyExistsProof.Verify(key, value, root); err != nil { - return err +// Also see LeftIndex(). +// Verify that a key has some value. +// Does not assume that the proof itself is valid, call Verify() first. +func (proof *RangeProof) VerifyItem(key, value []byte) error { + leaves := proof.Leaves + if proof == nil { + return cmn.ErrorWrap(ErrInvalidProof, "proof is nil") } - if bytes.Equal(key, endKey) { - return nil + if !proof.rootVerified { + return cmn.NewError("must call Verify(root) first.") } - if proof.PathToKey.isRightmost() { - return nil + i := sort.Search(len(leaves), func(i int) bool { + return bytes.Compare(key, leaves[i].Key) <= 0 + }) + if i >= len(leaves) || !bytes.Equal(leaves[i].Key, key) { + return cmn.ErrorWrap(ErrInvalidProof, "leaf key not found in proof") } - if proof.Right != nil && - proof.PathToKey.isLeftAdjacentTo(proof.Right.Path) { - return nil + valueHash := tmhash.Sum(value) + if !bytes.Equal(leaves[i].ValueHash, valueHash) { + return cmn.ErrorWrap(ErrInvalidProof, "leaf value hash not same") } - - return errors.WithStack(ErrInvalidProof) -} - -/////////////////////////////////////////////////////////////////////////////// - -// KeyRangeProof is proof that a range of keys does or does not exist. -type KeyRangeProof struct { - RootHash cmn.HexBytes `json:"root_hash"` - Versions []int64 `json:"versions"` - PathToKeys []*PathToKey `json:"paths"` - - Left *pathWithNode `json:"left"` - Right *pathWithNode `json:"right"` + return nil } -// Verify that a range proof is valid. -// -// This method expects the same parameters passed to query the range. -func (proof *KeyRangeProof) Verify( - startKey, endKey []byte, limit int, keys, values [][]byte, root []byte, -) error { - if len(proof.PathToKeys) != len(keys) || len(values) != len(keys) || len(proof.Versions) != len(keys) { - return errors.WithStack(ErrInvalidInputs) - } - if limit > 0 && len(keys) > limit { - return errors.WithStack(ErrInvalidInputs) +// Verify that proof is valid absence proof for key. +// Does not assume that the proof itself is valid. +// For that, use Verify(root). +func (proof *RangeProof) VerifyAbsence(key []byte) error { + if proof == nil { + return cmn.ErrorWrap(ErrInvalidProof, "proof is nil") } - - // If startKey > endKey, reverse the keys and values, since our proofs are - // always in ascending order. - ascending := bytes.Compare(startKey, endKey) == -1 - if !ascending { - startKey, endKey, keys, values = reverseKeys(startKey, endKey, keys, values) + if !proof.rootVerified { + return cmn.NewError("must call Verify(root) first.") } - - // If the range is empty, we just have to check the left and right paths. - if len(keys) == 0 { - if err := verifyKeyAbsence(proof.Left, proof.Right); err != nil { - return err + cmp := bytes.Compare(key, proof.Leaves[0].Key) + if cmp < 0 { + if proof.LeftPath.isLeftmost() { + return nil } - return verifyPaths(proof.Left, proof.Right, startKey, endKey, root) + return cmn.NewError("absence not proved by left path") + } else if cmp == 0 { + return cmn.NewError("absence disproved via first item #0") } - - // If we hit the limit, one of the two ends doesn't have to match the - // limits of the query, so we adjust the range to match the limit we found. - if limit > 0 && len(keys) == limit { - if ascending { - endKey = keys[len(keys)-1] - } else { - startKey = keys[0] - } + if len(proof.LeftPath) == 0 { + return nil // proof ok } - // Now we know Left < startKey <= endKey < Right. - if err := verifyPaths(proof.Left, proof.Right, startKey, endKey, root); err != nil { - return err + if proof.LeftPath.isRightmost() { + return nil } - if err := verifyNoMissingKeys(proof.paths()); err != nil { - return errors.WithStack(err) - } + // See if any of the leaves are greater than key. + for i := 1; i < len(proof.Leaves); i++ { + leaf := proof.Leaves[i] + cmp := bytes.Compare(key, leaf.Key) + if cmp < 0 { + return nil // proof ok + } else if cmp == 0 { + return cmn.NewError("absence disproved via item #%v", i) + } else { + if i == len(proof.Leaves)-1 { + // If last item, check whether + // it's the last item in the tree. - // If we've reached this point, it means our range isn't empty, and we have - // a list of keys. - for i, path := range proof.PathToKeys { - leafNode := proofLeafNode{ - KeyBytes: keys[i], - ValueBytes: values[i], - Version: proof.Versions[i], - } - if err := path.verify(leafNode.Hash(), root); err != nil { - return errors.WithStack(err) + } + continue } } - // In the case of a descending range, if the left proof is nil and the - // limit wasn't reached, we have to verify that we're not missing any - // keys. Basically, if a key to the left is missing because we've - // reached the limit, then it's fine. But if the key count is smaller - // than the limit, we need a left proof to make sure no keys are - // missing. - if proof.Left == nil && - !bytes.Equal(startKey, keys[0]) && - !proof.PathToKeys[0].isLeftmost() { - return errors.WithStack(ErrInvalidProof) + // It's still a valid proof if our last leaf is the rightmost child. + if proof.treeEnd { + return nil // OK! } - if proof.Right == nil && - !bytes.Equal(endKey, keys[len(keys)-1]) && - !proof.PathToKeys[len(proof.PathToKeys)-1].isRightmost() { - return errors.WithStack(ErrInvalidProof) + // It's not a valid absence proof. + if len(proof.Leaves) < 2 { + return cmn.NewError("absence not proved by right leaf (need another leaf?)") } - return nil + return cmn.NewError("absence not proved by right leaf") } -func (proof *KeyRangeProof) String() string { - // TODO(cloudhead): Needs work. - return fmt.Sprintf("%#v", proof) +// Verify that proof is valid. +func (proof *RangeProof) Verify(root []byte) error { + if proof == nil { + return cmn.ErrorWrap(ErrInvalidProof, "proof is nil") + } + err := proof.verify(root) + return err } -// Returns a list of all paths, in order, with the proof's Left and Right -// paths preprended and appended respectively, if they exist. -func (proof *KeyRangeProof) paths() []*PathToKey { - paths := proof.PathToKeys[:] - if proof.Left != nil { - paths = append([]*PathToKey{proof.Left.Path}, paths...) +func (proof *RangeProof) verify(root []byte) error { + rootHash := proof.rootHash + if rootHash == nil { + derivedHash, err := proof.computeRootHash() + if err != nil { + return err + } + rootHash = derivedHash } - if proof.Right != nil { - paths = append(paths, proof.Right.Path) + if !bytes.Equal(rootHash, root) { + return cmn.ErrorWrap(ErrInvalidRoot, "root hash doesn't match") } - return paths + proof.rootVerified = true + return nil } -/////////////////////////////////////////////////////////////////////////////// - -func (t *Tree) getRangeWithProof(keyStart, keyEnd []byte, limit int) ( - keys, values [][]byte, rangeProof *KeyRangeProof, err error, -) { - if t.root == nil { - return nil, nil, nil, ErrNilRoot +// ComputeRootHash computes the root hash with leaves. +// Returns nil if error or proof is nil. +// Does not verify the root hash. +func (proof *RangeProof) ComputeRootHash() []byte { + if proof == nil { + return nil } - t.root.hashWithCount() // Ensure that all hashes are calculated. + rootHash, _ := proof.computeRootHash() + return rootHash +} - rangeProof = &KeyRangeProof{RootHash: t.root.hash} - rangeStart, rangeEnd := keyStart, keyEnd - ascending := bytes.Compare(keyStart, keyEnd) == -1 - if !ascending { - rangeStart, rangeEnd = rangeEnd, rangeStart +func (proof *RangeProof) computeRootHash() (rootHash []byte, err error) { + rootHash, treeEnd, err := proof._computeRootHash() + if err == nil { + proof.rootHash = rootHash // memoize + proof.treeEnd = treeEnd // memoize } + return rootHash, err +} - versions := []int64{} - limited := t.IterateRangeInclusive(rangeStart, rangeEnd, ascending, func(k, v []byte, version int64) bool { - keys = append(keys, k) - values = append(values, v) - versions = append(versions, version) - return len(keys) == limit - }) - - // Construct the paths such that they are always in ascending order. - rangeProof.PathToKeys = make([]*PathToKey, len(keys)) - rangeProof.Versions = make([]int64, len(keys)) - for i, k := range keys { - path, _, _ := t.root.pathToKey(t, k) - if ascending { - rangeProof.PathToKeys[i] = path - rangeProof.Versions[i] = versions[i] - } else { - rangeProof.PathToKeys[len(keys)-i-1] = path - rangeProof.Versions[len(keys)-i-1] = versions[i] - } +func (proof *RangeProof) _computeRootHash() (rootHash []byte, treeEnd bool, err error) { + if len(proof.Leaves) == 0 { + return nil, false, cmn.ErrorWrap(ErrInvalidProof, "no leaves") + } + if len(proof.InnerNodes)+1 != len(proof.Leaves) { + return nil, false, cmn.ErrorWrap(ErrInvalidProof, "InnerNodes vs Leaves length mismatch, leaves should be 1 more.") } - // - // Figure out which of the left or right paths we need. - // - var needsLeft, needsRight bool + // Start from the left path and prove each leaf. - if len(keys) == 0 { - needsLeft, needsRight = true, true - } else { - first, last := 0, len(keys)-1 - if !ascending { - first, last = last, first - } + // shared across recursive calls + var leaves = proof.Leaves + var innersq = proof.InnerNodes + var COMPUTEHASH func(path PathToLeaf, rightmost bool) (hash []byte, treeEnd bool, done bool, err error) - needsLeft = !bytes.Equal(keys[first], rangeStart) - needsRight = !bytes.Equal(keys[last], rangeEnd) + // rightmost: is the root a rightmost child of the tree? + // treeEnd: true iff the last leaf is the last item of the tree. + // Returns the (possibly intermediate, possibly root) hash. + COMPUTEHASH = func(path PathToLeaf, rightmost bool) (hash []byte, treeEnd bool, done bool, err error) { - // When limited, we can relax the right or left side, depending on - // the direction of the range. - if limited { - if ascending { - needsRight = false - } else { - needsLeft = false - } - } - } + // Pop next leaf. + nleaf, rleaves := leaves[0], leaves[1:] + leaves = rleaves - // So far, we've created proofs of the keys which are within the provided range. - // Next, we need to create a proof that we haven't omitted any keys to the left - // or right of that range. This is relevant in two scenarios: - // - // 1. There are no keys in the range. In this case, include a proof of the key - // to the left and right of that empty range. - // 2. The start or end key do not match the start and end of the keys returned. - // In this case, include proofs of the keys immediately outside of those returned. - // - if needsLeft { - // Find index of first key to the left, and include proof if it isn't the - // leftmost key. - if idx, _ := t.Get64(rangeStart); idx > 0 { - lkey, lval := t.GetByIndex64(idx - 1) - path, node, _ := t.root.pathToKey(t, lkey) - rangeProof.Left = &pathWithNode{ - Path: path, - Node: proofLeafNode{lkey, lval, node.version}, - } - } - } + // Compute hash. + hash = (pathWithLeaf{ + Path: path, + Leaf: nleaf, + }).computeRootHash() - // Proof that the last key is the last value before keyEnd, or that we're limited. - // If len(keys) == limit, it doesn't matter that a key exists to the right of the - // last key, since we aren't interested in it. - if needsRight { - // Find index of first key to the right, and include proof if it isn't the - // rightmost key. - if idx, _ := t.Get64(rangeEnd); idx <= t.Size64()-1 { - rkey, rval := t.GetByIndex64(idx) - path, node, _ := t.root.pathToKey(t, rkey) - rangeProof.Right = &pathWithNode{ - Path: path, - Node: proofLeafNode{rkey, rval, node.version}, - } + // If we don't have any leaves left, we're done. + if len(leaves) == 0 { + rightmost = rightmost && path.isRightmost() + return hash, rightmost, true, nil } - } - - return keys, values, rangeProof, nil -} -func (t *Tree) getFirstInRangeWithProof(keyStart, keyEnd []byte) ( - key, value []byte, proof *KeyFirstInRangeProof, err error, -) { - if t.root == nil { - return nil, nil, nil, ErrNilRoot - } - t.root.hashWithCount() // Ensure that all hashes are calculated. - proof = &KeyFirstInRangeProof{} - proof.RootHash = t.root.hash - proof.Version = t.root.version - - // Get the first value in the range. - t.IterateRangeInclusive(keyStart, keyEnd, true, func(k, v []byte, _ int64) bool { - key, value = k, v - return true - }) + // Prove along path (until we run out of leaves). + for len(path) > 0 { + + // Drop the leaf-most (last-most) inner nodes from path + // until we encounter one with a left hash. + // We assume that the left side is already verified. + // rpath: rest of path + // lpath: last path item + rpath, lpath := path[:len(path)-1], path[len(path)-1] + path = rpath + if len(lpath.Right) == 0 { + continue + } - if len(key) > 0 { - proof.PathToKey, _, _ = t.root.pathToKey(t, key) - } + // Pop next inners, a PathToLeaf (e.g. []proofInnerNode). + inners, rinnersq := innersq[0], innersq[1:] + innersq = rinnersq - if !bytes.Equal(key, keyStart) { - if idx, _ := t.Get64(keyStart); idx-1 >= 0 && idx-1 <= t.Size64()-1 { - k, v := t.GetByIndex64(idx - 1) - path, node, _ := t.root.pathToKey(t, k) - proof.Left = &pathWithNode{ - Path: path, - Node: proofLeafNode{k, v, node.version}, + // Recursively verify inners against remaining leaves. + derivedRoot, treeEnd, done, err := COMPUTEHASH(inners, rightmost && rpath.isRightmost()) + if err != nil { + return nil, treeEnd, false, cmn.ErrorWrap(err, "recursive COMPUTEHASH call") + } + if !bytes.Equal(derivedRoot, lpath.Right) { + return nil, treeEnd, false, cmn.ErrorWrap(ErrInvalidRoot, "intermediate root hash %X doesn't match, got %X", lpath.Right, derivedRoot) + } + if done { + return hash, treeEnd, true, nil } } + + // We're not done yet (leaves left over). No error, not done either. + // Technically if rightmost, we know there's an error "left over leaves + // -- malformed proof", but we return that at the top level, below. + return hash, false, false, nil } - if !bytes.Equal(key, keyEnd) { - if idx, val := t.Get64(keyEnd); idx <= t.Size64()-1 && val == nil { - k, v := t.GetByIndex64(idx) - path, node, _ := t.root.pathToKey(t, k) - proof.Right = &pathWithNode{ - Path: path, - Node: proofLeafNode{k, v, node.version}, - } - } + // Verify! + path := proof.LeftPath + rootHash, treeEnd, done, err := COMPUTEHASH(path, true) + if err != nil { + return nil, treeEnd, cmn.ErrorWrap(err, "root COMPUTEHASH call") + } else if !done { + return nil, treeEnd, cmn.ErrorWrap(ErrInvalidProof, "left over leaves -- malformed proof") } - return key, value, proof, nil + // Ok! + return rootHash, treeEnd, nil } -func (t *Tree) getLastInRangeWithProof(keyStart, keyEnd []byte) ( - key, value []byte, proof *KeyLastInRangeProof, err error, -) { +/////////////////////////////////////////////////////////////////////////////// + +// keyStart is inclusive and keyEnd is exclusive. +// Returns the range-proof and the included keys and values. +// If keyStart or keyEnd don't exist, the leaf before keyStart +// or after keyEnd will also be included, but not be included in values. +// If keyEnd-1 exists, no later leaves will be included. +// If keyStart >= keyEnd and both not nil, panics. +// Limit is never exceeded. +func (t *Tree) getRangeProof(keyStart, keyEnd []byte, limit int) (*RangeProof, [][]byte, [][]byte, error) { + if keyStart != nil && keyEnd != nil && bytes.Compare(keyStart, keyEnd) >= 0 { + panic("if keyStart and keyEnd are present, need keyStart < keyEnd.") + } + if limit < 0 { + panic("limit must be greater or equal to 0 -- 0 means no limit") + } if t.root == nil { - return nil, nil, nil, ErrNilRoot + return nil, nil, nil, cmn.ErrorWrap(ErrNilRoot, "") } t.root.hashWithCount() // Ensure that all hashes are calculated. - proof = &KeyLastInRangeProof{} - proof.RootHash = t.root.hash - proof.Version = t.root.version + // Get the first key/value pair proof, which provides us with the left key. + path, left, err := t.root.PathToLeaf(t, keyStart) + if err != nil { + // Key doesn't exist, but instead we got the prev leaf (or the + // first or last leaf), which provides proof of absence). + // err = nil isn't necessary as we do not use it in the returns below + } + startOK := keyStart == nil || bytes.Compare(keyStart, left.key) <= 0 + endOK := keyEnd == nil || bytes.Compare(left.key, keyEnd) < 0 + // If left.key is in range, add it to key/values. + var keys, values [][]byte + if startOK && endOK { + keys = append(keys, left.key) // == keyStart + values = append(values, left.value) + } + // Either way, add to proof leaves. + var leaves = []proofLeafNode{{ + Key: left.key, + ValueHash: tmhash.Sum(left.value), + Version: left.version, + }} + + // 1: Special case if limit is 1. + // 2: Special case if keyEnd is left.key+1. + _stop := false + if limit == 1 { + _stop = true // case 1 + } else if keyEnd != nil && bytes.Compare(cpIncr(left.key), keyEnd) >= 0 { + _stop = true // case 2 + } + if _stop { + return &RangeProof{ + LeftPath: path, + Leaves: leaves, + }, keys, values, nil + } + + // Get the key after left.key to iterate from. + afterLeft := cpIncr(left.key) + + // Traverse starting from afterLeft, until keyEnd or the next leaf + // after keyEnd. + // nolint + var innersq = []PathToLeaf(nil) + var inners = PathToLeaf(nil) + var lastDepth uint8 = 0 + var leafCount = 1 // from left above. + var pathCount = 0 + // var keys, values [][]byte defined as function outs. + + t.root.traverseInRange(t, afterLeft, nil, true, false, 0, + func(node *Node, depth uint8) (stop bool) { + + // Track when we diverge from path, or when we've exhausted path, + // since the first innersq shouldn't include it. + if pathCount != -1 { + if len(path) <= pathCount { + // We're done with path counting. + pathCount = -1 + } else { + pn := path[pathCount] + if pn.Height != node.height || + pn.Left != nil && !bytes.Equal(pn.Left, node.leftHash) || + pn.Right != nil && !bytes.Equal(pn.Right, node.rightHash) { + + // We've diverged, so start appending to inners. + pathCount-- + } else { + pathCount++ + } + } + } - // Get the last value in the range. - t.IterateRangeInclusive(keyStart, keyEnd, false, func(k, v []byte, _ int64) bool { - key, value = k, v - return true - }) + if node.height == 0 { + // Leaf node. + // Append inners to innersq. + innersq = append(innersq, inners) + inners = PathToLeaf(nil) + // Append leaf to leaves. + leaves = append(leaves, proofLeafNode{ + Key: node.key, + ValueHash: tmhash.Sum(node.value), + Version: node.version, + }) + leafCount++ + // Maybe terminate because we found enough leaves. + if limit > 0 && limit <= leafCount { + return true + } + // Terminate if we've found keyEnd or after. + if keyEnd != nil && bytes.Compare(node.key, keyEnd) >= 0 { + return true + } + // Value is in range, append to keys and values. + keys = append(keys, node.key) + values = append(values, node.value) + // Terminate if we've found keyEnd-1 or after. + // We don't want to fetch any leaves for it. + if keyEnd != nil && bytes.Compare(cpIncr(node.key), keyEnd) >= 0 { + return true + } + } else { + // Inner node. + if pathCount >= 0 { + // Skip redundant path items. + } else { + inners = append(inners, proofInnerNode{ + Height: node.height, + Size: node.size, + Version: node.version, + Left: nil, // left is nil for range proof inners + Right: node.rightHash, + }) + } + } + lastDepth = depth + return false + }, + ) + + return &RangeProof{ + LeftPath: path, + InnerNodes: innersq, + Leaves: leaves, + }, keys, values, nil +} - if len(key) > 0 { - proof.PathToKey, _, _ = t.root.pathToKey(t, key) - } +//---------------------------------------- - if !bytes.Equal(key, keyEnd) { - if idx, _ := t.Get64(keyEnd); idx <= t.Size64()-1 { - k, v := t.GetByIndex64(idx) - path, node, _ := t.root.pathToKey(t, k) - proof.Right = &pathWithNode{ - Path: path, - Node: proofLeafNode{k, v, node.version}, +// GetWithProof gets the value under the key if it exists, or returns nil. +// A proof of existence or absence is returned alongside the value. +func (t *Tree) GetWithProof(key []byte) (value []byte, proof *RangeProof, err error) { + proof, _, values, err := t.getRangeProof(key, cpIncr(key), 2) + if err == nil { + if len(values) > 0 { + if !bytes.Equal(proof.Leaves[0].Key, key) { + return nil, proof, nil } + return values[0], proof, nil } + return nil, proof, nil } + return nil, nil, cmn.ErrorWrap(err, "could not construct any proof") +} - if !bytes.Equal(key, keyStart) { - if idx, _ := t.Get64(keyStart); idx-1 >= 0 && idx-1 <= t.Size64()-1 { - k, v := t.GetByIndex64(idx - 1) - path, node, _ := t.root.pathToKey(t, k) - proof.Left = &pathWithNode{ - Path: path, - Node: proofLeafNode{k, v, node.version}, - } - } - } +// GetRangeWithProof gets key/value pairs within the specified range and limit. +func (t *Tree) GetRangeWithProof(startKey []byte, endKey []byte, limit int) (keys, values [][]byte, proof *RangeProof, err error) { + proof, keys, values, err = t.getRangeProof(startKey, endKey, limit) + return +} - return key, value, proof, nil +// GetVersionedWithProof gets the value under the key at the specified version +// if it exists, or returns nil. +func (tree *VersionedTree) GetVersionedWithProof(key []byte, version int64) ([]byte, *RangeProof, error) { + if t, ok := tree.versions[version]; ok { + return t.GetWithProof(key) + } + return nil, nil, cmn.ErrorWrap(ErrVersionDoesNotExist, "") } -/////////////////////////////////////////////////////////////////////////////// +// GetVersionedRangeWithProof gets key/value pairs within the specified range +// and limit. +func (tree *VersionedTree) GetVersionedRangeWithProof(startKey, endKey []byte, limit int, version int64) ( + keys, values [][]byte, proof *RangeProof, err error) { -// reverseKeys reverses the keys and values and swaps start and end key -// if startKey > endKey. -func reverseKeys(startKey, endKey []byte, keys, values [][]byte) ( - []byte, []byte, [][]byte, [][]byte, -) { - if bytes.Compare(startKey, endKey) == 1 { - startKey, endKey = endKey, startKey - - ks := make([][]byte, len(keys)) - vs := make([][]byte, len(keys)) - for i, _ := range keys { - ks[len(ks)-1-i] = keys[i] - vs[len(vs)-1-i] = values[i] - } - keys, values = ks, vs + if t, ok := tree.versions[version]; ok { + return t.GetRangeWithProof(startKey, endKey, limit) } - return startKey, endKey, keys, values + return nil, nil, nil, cmn.ErrorWrap(ErrVersionDoesNotExist, "") } diff --git a/vendor/github.com/tendermint/iavl/serialize.go b/vendor/github.com/tendermint/iavl/serialize.go deleted file mode 100644 index 3b8564783..000000000 --- a/vendor/github.com/tendermint/iavl/serialize.go +++ /dev/null @@ -1,200 +0,0 @@ -package iavl - -// NodeData groups together a key, value and depth. -type NodeData struct { - Key []byte - Value []byte - Depth uint8 -} - -// SerializeFunc is any implementation that can serialize -// an iavl Node and its descendants. -type SerializeFunc func(*Tree, *Node) []NodeData - -// RestoreFunc is an implementation that can restore an iavl tree from -// NodeData. -type RestoreFunc func(*Tree, []NodeData) - -// Restore will take an (empty) tree restore it -// from the keys returned from a SerializeFunc. -func Restore(empty *Tree, kvs []NodeData) { - for _, kv := range kvs { - empty.Set(kv.Key, kv.Value) - } - empty.Hash() -} - -func RestoreUsingDepth(empty *Tree, kvs []NodeData) { - // Create an array of arrays of nodes. We're going to store each depth in - // here, forming a kind of pyramid. - depths := [][]*Node{} - - // Go through all the leaf nodes, grouping them in pairs and creating their - // parents recursively. - for _, kv := range kvs { - var ( - // Left and right nodes. - l *Node = nil - r *Node = NewNode(kv.Key, kv.Value, 1) - depth uint8 = kv.Depth - ) - // Create depths as needed. - for len(depths) < int(depth)+1 { - depths = append(depths, []*Node{}) - } - depths[depth] = append(depths[depth], r) // Add the leaf node to this depth. - - // If the nodes at this level are uneven after adding a node to it, it - // means we have to wait for another node to be appended before we have - // a pair. If we do have a pair, go up the tree until we don't. - for d := depth; len(depths[d])%2 == 0; d-- { - nodes := depths[d] // List of nodes at this depth. - - l = nodes[len(nodes)-1-1] - r = nodes[len(nodes)-1] - - depths[d-1] = append(depths[d-1], &Node{ - key: leftmost(r).Key, - height: maxInt8(l.height, r.height) + 1, - size: l.size + r.size, - leftNode: l, - rightNode: r, - version: 1, - }) - } - } - empty.root = depths[0][0] - empty.Hash() -} - -// InOrderSerialize returns all key-values in the -// key order (as stored). May be nice to read, but -// when recovering, it will create a different. -func InOrderSerialize(t *Tree, root *Node) []NodeData { - res := make([]NodeData, 0, root.size) - root.traverseWithDepth(t, true, func(node *Node, depth uint8) bool { - if node.height == 0 { - kv := NodeData{Key: node.key, Value: node.value, Depth: depth} - res = append(res, kv) - } - return false - }) - return res -} - -// StableSerializeBFS serializes the tree in a breadth-first manner. -func StableSerializeBFS(t *Tree, root *Node) []NodeData { - if root == nil { - return nil - } - - size := root.size - visited := map[string][]byte{} - keys := make([][]byte, 0, size) - numKeys := -1 - - // Breadth-first search. At every depth, add keys in search order. Keep - // going as long as we find keys at that depth. When we reach a leaf, set - // its value in the visited map. - // Since we have an AVL+ tree, the inner nodes contain only keys and not - // values, while the leaves contain both. Note also that there are N-1 inner - // nodes for N keys, so one of the leaf keys is only set once we reach the leaves - // of the tree. - for depth := uint(0); len(keys) > numKeys; depth++ { - numKeys = len(keys) - root.traverseDepth(t, depth, func(node *Node) { - if _, ok := visited[string(node.key)]; !ok { - keys = append(keys, node.key) - visited[string(node.key)] = nil - } - if node.isLeaf() { - visited[string(node.key)] = node.value - } - }) - } - - nds := make([]NodeData, size) - for i, k := range keys { - nds[i] = NodeData{k, visited[string(k)], 0} - } - return nds -} - -// StableSerializeFrey exports the key value pairs of the tree -// in an order, such that when Restored from those keys, the -// new tree would have the same structure (and thus same -// shape) as the original tree. -// -// the algorithm is basically this: take the leftmost node -// of the left half and the leftmost node of the righthalf. -// Then go down a level... -// each time adding leftmost node of the right side. -// (bredth first search) -// -// Imagine 8 nodes in a balanced tree, split in half each time -// 1 -// 1, 5 -// 1, 5, 3, 7 -// 1, 5, 3, 7, 2, 4, 6, 8 -func StableSerializeFrey(t *Tree, top *Node) []NodeData { - if top == nil { - return nil - } - size := top.size - - // store all pending nodes for depth-first search - queue := make([]*Node, 0, size) - queue = append(queue, top) - - // to store all results - started with - res := make([]NodeData, 0, size) - left := leftmost(top) - if left != nil { - res = append(res, *left) - } - - var n *Node - for len(queue) > 0 { - // pop - n, queue = queue[0], queue[1:] - - // l := n.getLeftNode(tree) - l := n.leftNode - if isInner(l) { - queue = append(queue, l) - } - - // r := n.getRightNode(tree) - r := n.rightNode - if isInner(r) { - queue = append(queue, r) - left = leftmost(r) - if left != nil { - res = append(res, *left) - } - } else if isLeaf(r) { - kv := NodeData{Key: r.key, Value: r.value} - res = append(res, kv) - } - } - - return res -} - -func isInner(n *Node) bool { - return n != nil && !n.isLeaf() -} - -func isLeaf(n *Node) bool { - return n != nil && n.isLeaf() -} - -func leftmost(node *Node) *NodeData { - for isInner(node) { - node = node.leftNode - } - if node == nil { - return nil - } - return &NodeData{Key: node.key, Value: node.value} -} diff --git a/vendor/github.com/tendermint/iavl/sha256truncated/sha256truncated.go b/vendor/github.com/tendermint/iavl/sha256truncated/sha256truncated.go deleted file mode 100644 index f62ff3135..000000000 --- a/vendor/github.com/tendermint/iavl/sha256truncated/sha256truncated.go +++ /dev/null @@ -1,44 +0,0 @@ -// Package sha256truncated provides a sha256 hash.Hash whose output is truncated to 20 bytes (160 bits). -// -// This is the default hashing algorithm used by IAVL+ trees. -// -// s256 := sha256.New() // crypto/sha256 -// s256Truncated := New() // this package -// -// // Use like any other hash.Hash ... -// // Contract: -// s256Trunc.Sum(nil) == s256.Sum(nil)[:20] -package sha256truncated - -import ( - "crypto/sha256" - "hash" -) - -const Size = 20 - -// New returns a new hash.Hash computing the truncated to the first 20 bytes SHA256 checksum. -func New() hash.Hash { - return &digest{sha256.New()} -} - -func (d *digest) Sum(in []byte) []byte { - return d.Hash.Sum(in)[:Size] -} - -func (d *digest) Reset() { - d.Hash.Reset() -} - -func (d *digest) Size() int { - return Size -} - -func (d *digest) BlockSize() int { - return d.Hash.BlockSize() -} - -// digest is just a wrapper around sha256 -type digest struct { - hash.Hash -} diff --git a/vendor/github.com/tendermint/iavl/tree.go b/vendor/github.com/tendermint/iavl/tree.go index 85cf6e21e..c92901532 100644 --- a/vendor/github.com/tendermint/iavl/tree.go +++ b/vendor/github.com/tendermint/iavl/tree.go @@ -4,9 +4,7 @@ import ( "fmt" "strings" - dbm "github.com/tendermint/tmlibs/db" - - "github.com/pkg/errors" + dbm "github.com/tendermint/tendermint/libs/db" ) // Tree is a container for an immutable AVL+ Tree. Changes are performed by @@ -143,39 +141,6 @@ func (t *Tree) GetByIndex64(index int64) (key []byte, value []byte) { return t.root.getByIndex(t, index) } -// GetWithProof gets the value under the key if it exists, or returns nil. -// A proof of existence or absence is returned alongside the value. -func (t *Tree) GetWithProof(key []byte) ([]byte, KeyProof, error) { - value, eproof, err := t.getWithProof(key) - if err == nil { - return value, eproof, nil - } - - aproof, err := t.keyAbsentProof(key) - if err == nil { - return nil, aproof, nil - } - return nil, nil, errors.Wrap(err, "could not construct any proof") -} - -// GetRangeWithProof gets key/value pairs within the specified range and limit. To specify a descending -// range, swap the start and end keys. -// -// Returns a list of keys, a list of values and a proof. -func (t *Tree) GetRangeWithProof(startKey []byte, endKey []byte, limit int) ([][]byte, [][]byte, *KeyRangeProof, error) { - return t.getRangeWithProof(startKey, endKey, limit) -} - -// GetFirstInRangeWithProof gets the first key/value pair in the specified range, with a proof. -func (t *Tree) GetFirstInRangeWithProof(startKey, endKey []byte) ([]byte, []byte, *KeyFirstInRangeProof, error) { - return t.getFirstInRangeWithProof(startKey, endKey) -} - -// GetLastInRangeWithProof gets the last key/value pair in the specified range, with a proof. -func (t *Tree) GetLastInRangeWithProof(startKey, endKey []byte) ([]byte, []byte, *KeyLastInRangeProof, error) { - return t.getLastInRangeWithProof(startKey, endKey) -} - // Remove tries to remove a key from the tree and if removed, returns its // value, and 'true'. func (t *Tree) Remove(key []byte) ([]byte, bool) { @@ -210,9 +175,8 @@ func (t *Tree) Iterate(fn func(key []byte, value []byte) bool) (stopped bool) { return t.root.traverse(t, true, func(node *Node) bool { if node.height == 0 { return fn(node.key, node.value) - } else { - return false } + return false }) } @@ -225,9 +189,8 @@ func (t *Tree) IterateRange(start, end []byte, ascending bool, fn func(key []byt return t.root.traverseInRange(t, start, end, ascending, false, 0, func(node *Node, _ uint8) bool { if node.height == 0 { return fn(node.key, node.value) - } else { - return false } + return false }) } @@ -240,19 +203,18 @@ func (t *Tree) IterateRangeInclusive(start, end []byte, ascending bool, fn func( return t.root.traverseInRange(t, start, end, ascending, true, 0, func(node *Node, _ uint8) bool { if node.height == 0 { return fn(node.key, node.value, node.version) - } else { - return false } + return false }) } // Clone creates a clone of the tree. // Used internally by VersionedTree. -func (tree *Tree) clone() *Tree { +func (t *Tree) clone() *Tree { return &Tree{ - root: tree.root, - ndb: tree.ndb, - version: tree.version, + root: t.root, + ndb: t.ndb, + version: t.version, } } diff --git a/vendor/github.com/tendermint/iavl/tree_dotgraph.go b/vendor/github.com/tendermint/iavl/tree_dotgraph.go index 57fc21678..14294851a 100644 --- a/vendor/github.com/tendermint/iavl/tree_dotgraph.go +++ b/vendor/github.com/tendermint/iavl/tree_dotgraph.go @@ -41,7 +41,7 @@ var defaultGraphNodeAttrs = map[string]string{ "shape": "circle", } -func WriteDOTGraph(w io.Writer, tree *Tree, paths []*PathToKey) { +func WriteDOTGraph(w io.Writer, tree *Tree, paths []PathToLeaf) { ctx := &graphContext{} tree.root.hashWithCount() @@ -69,7 +69,7 @@ func WriteDOTGraph(w io.Writer, tree *Tree, paths []*PathToKey) { } for _, path := range paths { - for _, n := range path.InnerNodes { + for _, n := range path { if bytes.Equal(n.Left, node.hash) || bytes.Equal(n.Right, node.hash) { graphNode.Attrs["peripheries"] = "2" graphNode.Attrs["style"] = "filled" diff --git a/vendor/github.com/tendermint/iavl/util.go b/vendor/github.com/tendermint/iavl/util.go index b28b4877f..96f754189 100644 --- a/vendor/github.com/tendermint/iavl/util.go +++ b/vendor/github.com/tendermint/iavl/util.go @@ -1,27 +1,45 @@ package iavl import ( + "bytes" "fmt" + "sort" ) -func printNode(node *Node, indent int) { +// PrintTree prints the whole tree in an indented form. +func PrintTree(tree *Tree) { + ndb, root := tree.ndb, tree.root + printNode(ndb, root, 0) +} + +func printNode(ndb *nodeDB, node *Node, indent int) { indentPrefix := "" for i := 0; i < indent; i++ { indentPrefix += " " } + if node == nil { + fmt.Printf("%s\n", indentPrefix) + return + } if node.rightNode != nil { - printNode(node.rightNode, indent+1) + printNode(ndb, node.rightNode, indent+1) } else if node.rightHash != nil { - fmt.Printf("%s %X\n", indentPrefix, node.rightHash) + rightNode := ndb.GetNode(node.rightHash) + printNode(ndb, rightNode, indent+1) } - fmt.Printf("%s%v:%v\n", indentPrefix, node.key, node.height) + hash := node._hash() + fmt.Printf("%sh:%X\n", indentPrefix, hash) + if node.isLeaf() { + fmt.Printf("%s%X:%X (%v)\n", indentPrefix, node.key, node.value, node.height) + } if node.leftNode != nil { - printNode(node.leftNode, indent+1) + printNode(ndb, node.leftNode, indent+1) } else if node.leftHash != nil { - fmt.Printf("%s %X\n", indentPrefix, node.leftHash) + leftNode := ndb.GetNode(node.leftHash) + printNode(ndb, leftNode, indent+1) } } @@ -32,3 +50,57 @@ func maxInt8(a, b int8) int8 { } return b } + +func cp(bz []byte) (ret []byte) { + ret = make([]byte, len(bz)) + copy(ret, bz) + return ret +} + +// Returns a slice of the same length (big endian) +// except incremented by one. +// Appends 0x00 if bz is all 0xFF. +// CONTRACT: len(bz) > 0 +func cpIncr(bz []byte) (ret []byte) { + ret = cp(bz) + for i := len(bz) - 1; i >= 0; i-- { + if ret[i] < byte(0xFF) { + ret[i]++ + return + } + ret[i] = byte(0x00) + if i == 0 { + return append(ret, 0x00) + // Overflow + return nil + } + } + return []byte{0x00} +} + +type byteslices [][]byte + +func (bz byteslices) Len() int { + return len(bz) +} + +func (bz byteslices) Less(i, j int) bool { + switch bytes.Compare(bz[i], bz[j]) { + case -1: + return true + case 0, 1: + return false + default: + panic("should not happen") + } +} + +func (bz byteslices) Swap(i, j int) { + bz[j], bz[i] = bz[i], bz[j] +} + +func sortByteSlices(src [][]byte) [][]byte { + bzz := byteslices(src) + sort.Sort(bzz) + return bzz +} diff --git a/vendor/github.com/tendermint/iavl/version.go b/vendor/github.com/tendermint/iavl/version.go index 679f0cc3a..9efd11145 100644 --- a/vendor/github.com/tendermint/iavl/version.go +++ b/vendor/github.com/tendermint/iavl/version.go @@ -1,3 +1,4 @@ package iavl -const Version = "0.8.0-dev" +// Version of iavl. +const Version = "0.9.2" diff --git a/vendor/github.com/tendermint/iavl/versioned_tree.go b/vendor/github.com/tendermint/iavl/versioned_tree.go index 9fef5a154..7d8108ea8 100644 --- a/vendor/github.com/tendermint/iavl/versioned_tree.go +++ b/vendor/github.com/tendermint/iavl/versioned_tree.go @@ -4,10 +4,11 @@ import ( "bytes" "fmt" - "github.com/pkg/errors" - dbm "github.com/tendermint/tmlibs/db" + cmn "github.com/tendermint/tendermint/libs/common" + dbm "github.com/tendermint/tendermint/libs/db" ) +// ErrVersionDoesNotExist is returned if a requested version does not exist. var ErrVersionDoesNotExist = fmt.Errorf("version does not exist") // VersionedTree is a persistent tree which keeps track of versions. @@ -160,7 +161,7 @@ func (tree *VersionedTree) SaveVersion() ([]byte, int64, error) { tree.orphaningTree = newOrphaningTree(tree.versions[version].clone()) return existingHash, version, nil } - return nil, version, errors.Errorf("version %d was already saved to different hash %X (existing hash %X)", + return nil, version, fmt.Errorf("version %d was already saved to different hash %X (existing hash %X)", version, newHash, existingHash) } @@ -178,13 +179,13 @@ func (tree *VersionedTree) SaveVersion() ([]byte, int64, error) { // longer be accessed. func (tree *VersionedTree) DeleteVersion(version int64) error { if version == 0 { - return errors.New("version must be greater than 0") + return cmn.NewError("version must be greater than 0") } if version == tree.version { - return errors.Errorf("cannot delete latest saved version (%d)", version) + return cmn.NewError("cannot delete latest saved version (%d)", version) } if _, ok := tree.versions[version]; !ok { - return errors.WithStack(ErrVersionDoesNotExist) + return cmn.ErrorWrap(ErrVersionDoesNotExist, "") } tree.ndb.DeleteVersion(version) @@ -194,42 +195,3 @@ func (tree *VersionedTree) DeleteVersion(version int64) error { return nil } - -// GetVersionedWithProof gets the value under the key at the specified version -// if it exists, or returns nil. A proof of existence or absence is returned -// alongside the value. -func (tree *VersionedTree) GetVersionedWithProof(key []byte, version int64) ([]byte, KeyProof, error) { - if t, ok := tree.versions[version]; ok { - return t.GetWithProof(key) - } - return nil, nil, errors.WithStack(ErrVersionDoesNotExist) -} - -// GetVersionedRangeWithProof gets key/value pairs within the specified range -// and limit. To specify a descending range, swap the start and end keys. -// -// Returns a list of keys, a list of values and a proof. -func (tree *VersionedTree) GetVersionedRangeWithProof(startKey, endKey []byte, limit int, version int64) ([][]byte, [][]byte, *KeyRangeProof, error) { - if t, ok := tree.versions[version]; ok { - return t.GetRangeWithProof(startKey, endKey, limit) - } - return nil, nil, nil, errors.WithStack(ErrVersionDoesNotExist) -} - -// GetVersionedFirstInRangeWithProof gets the first key/value pair in the -// specified range, with a proof. -func (tree *VersionedTree) GetVersionedFirstInRangeWithProof(startKey, endKey []byte, version int64) ([]byte, []byte, *KeyFirstInRangeProof, error) { - if t, ok := tree.versions[version]; ok { - return t.GetFirstInRangeWithProof(startKey, endKey) - } - return nil, nil, nil, errors.WithStack(ErrVersionDoesNotExist) -} - -// GetVersionedLastInRangeWithProof gets the last key/value pair in the -// specified range, with a proof. -func (tree *VersionedTree) GetVersionedLastInRangeWithProof(startKey, endKey []byte, version int64) ([]byte, []byte, *KeyLastInRangeProof, error) { - if t, ok := tree.versions[version]; ok { - return t.GetLastInRangeWithProof(startKey, endKey) - } - return nil, nil, nil, errors.WithStack(ErrVersionDoesNotExist) -} diff --git a/vendor/github.com/tendermint/iavl/wire.go b/vendor/github.com/tendermint/iavl/wire.go new file mode 100644 index 000000000..8549ae4ab --- /dev/null +++ b/vendor/github.com/tendermint/iavl/wire.go @@ -0,0 +1,17 @@ +package iavl + +import ( + "github.com/tendermint/go-amino" +) + +var cdc = amino.NewCodec() + +func init() { + // NOTE: It's important that there be no conflicts here, + // as that would change the canonical representations. + RegisterWire(cdc) +} + +func RegisterWire(cdc *amino.Codec) { + // TODO +} diff --git a/vendor/github.com/tendermint/abci/client/client.go b/vendor/github.com/tendermint/tendermint/abci/client/client.go similarity index 97% rename from vendor/github.com/tendermint/abci/client/client.go rename to vendor/github.com/tendermint/tendermint/abci/client/client.go index ad0e5a7ab..558588107 100644 --- a/vendor/github.com/tendermint/abci/client/client.go +++ b/vendor/github.com/tendermint/tendermint/abci/client/client.go @@ -4,8 +4,8 @@ import ( "fmt" "sync" - "github.com/tendermint/abci/types" - cmn "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tendermint/abci/types" + cmn "github.com/tendermint/tendermint/libs/common" ) const ( diff --git a/vendor/github.com/tendermint/abci/client/grpc_client.go b/vendor/github.com/tendermint/tendermint/abci/client/grpc_client.go similarity index 98% rename from vendor/github.com/tendermint/abci/client/grpc_client.go rename to vendor/github.com/tendermint/tendermint/abci/client/grpc_client.go index 0f405a9c4..502ee0fcd 100644 --- a/vendor/github.com/tendermint/abci/client/grpc_client.go +++ b/vendor/github.com/tendermint/tendermint/abci/client/grpc_client.go @@ -9,8 +9,8 @@ import ( context "golang.org/x/net/context" grpc "google.golang.org/grpc" - "github.com/tendermint/abci/types" - cmn "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tendermint/abci/types" + cmn "github.com/tendermint/tendermint/libs/common" ) var _ Client = (*grpcClient)(nil) diff --git a/vendor/github.com/tendermint/abci/client/local_client.go b/vendor/github.com/tendermint/tendermint/abci/client/local_client.go similarity index 98% rename from vendor/github.com/tendermint/abci/client/local_client.go rename to vendor/github.com/tendermint/tendermint/abci/client/local_client.go index 64bf5fe08..3d1f8d8e4 100644 --- a/vendor/github.com/tendermint/abci/client/local_client.go +++ b/vendor/github.com/tendermint/tendermint/abci/client/local_client.go @@ -3,8 +3,8 @@ package abcicli import ( "sync" - types "github.com/tendermint/abci/types" - cmn "github.com/tendermint/tmlibs/common" + types "github.com/tendermint/tendermint/abci/types" + cmn "github.com/tendermint/tendermint/libs/common" ) var _ Client = (*localClient)(nil) diff --git a/vendor/github.com/tendermint/abci/client/socket_client.go b/vendor/github.com/tendermint/tendermint/abci/client/socket_client.go similarity index 96% rename from vendor/github.com/tendermint/abci/client/socket_client.go rename to vendor/github.com/tendermint/tendermint/abci/client/socket_client.go index 5c0101685..affea1a9e 100644 --- a/vendor/github.com/tendermint/abci/client/socket_client.go +++ b/vendor/github.com/tendermint/tendermint/abci/client/socket_client.go @@ -10,8 +10,8 @@ import ( "sync" "time" - "github.com/tendermint/abci/types" - cmn "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tendermint/abci/types" + cmn "github.com/tendermint/tendermint/libs/common" ) const reqQueueSize = 256 // TODO make configurable @@ -357,6 +357,13 @@ func (cli *socketClient) queueRequest(req *types.Request) *ReqRes { } func (cli *socketClient) flushQueue() { + // mark all in-flight messages as resolved (they will get cli.Error()) + for req := cli.reqSent.Front(); req != nil; req = req.Next() { + reqres := req.Value.(*ReqRes) + reqres.Done() + } + + // mark all queued messages as resolved LOOP: for { select { diff --git a/vendor/github.com/tendermint/abci/example/code/code.go b/vendor/github.com/tendermint/tendermint/abci/example/code/code.go similarity index 100% rename from vendor/github.com/tendermint/abci/example/code/code.go rename to vendor/github.com/tendermint/tendermint/abci/example/code/code.go diff --git a/vendor/github.com/tendermint/abci/example/kvstore/README.md b/vendor/github.com/tendermint/tendermint/abci/example/kvstore/README.md similarity index 100% rename from vendor/github.com/tendermint/abci/example/kvstore/README.md rename to vendor/github.com/tendermint/tendermint/abci/example/kvstore/README.md diff --git a/vendor/github.com/tendermint/abci/example/kvstore/helpers.go b/vendor/github.com/tendermint/tendermint/abci/example/kvstore/helpers.go similarity index 90% rename from vendor/github.com/tendermint/abci/example/kvstore/helpers.go rename to vendor/github.com/tendermint/tendermint/abci/example/kvstore/helpers.go index 63bc31a63..0e69fab9f 100644 --- a/vendor/github.com/tendermint/abci/example/kvstore/helpers.go +++ b/vendor/github.com/tendermint/tendermint/abci/example/kvstore/helpers.go @@ -1,8 +1,8 @@ package kvstore import ( - "github.com/tendermint/abci/types" - cmn "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tendermint/abci/types" + cmn "github.com/tendermint/tendermint/libs/common" ) // RandVal creates one random validator, with a key derived diff --git a/vendor/github.com/tendermint/abci/example/kvstore/kvstore.go b/vendor/github.com/tendermint/tendermint/abci/example/kvstore/kvstore.go similarity index 93% rename from vendor/github.com/tendermint/abci/example/kvstore/kvstore.go rename to vendor/github.com/tendermint/tendermint/abci/example/kvstore/kvstore.go index 4ccbc56b0..0f72b44ea 100644 --- a/vendor/github.com/tendermint/abci/example/kvstore/kvstore.go +++ b/vendor/github.com/tendermint/tendermint/abci/example/kvstore/kvstore.go @@ -6,10 +6,10 @@ import ( "encoding/json" "fmt" - "github.com/tendermint/abci/example/code" - "github.com/tendermint/abci/types" - cmn "github.com/tendermint/tmlibs/common" - dbm "github.com/tendermint/tmlibs/db" + "github.com/tendermint/tendermint/abci/example/code" + "github.com/tendermint/tendermint/abci/types" + cmn "github.com/tendermint/tendermint/libs/common" + dbm "github.com/tendermint/tendermint/libs/db" ) var ( diff --git a/vendor/github.com/tendermint/abci/example/kvstore/persistent_kvstore.go b/vendor/github.com/tendermint/tendermint/abci/example/kvstore/persistent_kvstore.go similarity index 95% rename from vendor/github.com/tendermint/abci/example/kvstore/persistent_kvstore.go rename to vendor/github.com/tendermint/tendermint/abci/example/kvstore/persistent_kvstore.go index 02f7ce74a..12ccbab78 100644 --- a/vendor/github.com/tendermint/abci/example/kvstore/persistent_kvstore.go +++ b/vendor/github.com/tendermint/tendermint/abci/example/kvstore/persistent_kvstore.go @@ -7,11 +7,11 @@ import ( "strconv" "strings" - "github.com/tendermint/abci/example/code" - "github.com/tendermint/abci/types" - cmn "github.com/tendermint/tmlibs/common" - dbm "github.com/tendermint/tmlibs/db" - "github.com/tendermint/tmlibs/log" + "github.com/tendermint/tendermint/abci/example/code" + "github.com/tendermint/tendermint/abci/types" + cmn "github.com/tendermint/tendermint/libs/common" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" ) const ( diff --git a/vendor/github.com/tendermint/abci/types/application.go b/vendor/github.com/tendermint/tendermint/abci/types/application.go similarity index 100% rename from vendor/github.com/tendermint/abci/types/application.go rename to vendor/github.com/tendermint/tendermint/abci/types/application.go diff --git a/vendor/github.com/tendermint/abci/types/messages.go b/vendor/github.com/tendermint/tendermint/abci/types/messages.go similarity index 100% rename from vendor/github.com/tendermint/abci/types/messages.go rename to vendor/github.com/tendermint/tendermint/abci/types/messages.go diff --git a/vendor/github.com/tendermint/abci/types/pubkey.go b/vendor/github.com/tendermint/tendermint/abci/types/pubkey.go similarity index 100% rename from vendor/github.com/tendermint/abci/types/pubkey.go rename to vendor/github.com/tendermint/tendermint/abci/types/pubkey.go diff --git a/vendor/github.com/tendermint/abci/types/result.go b/vendor/github.com/tendermint/tendermint/abci/types/result.go similarity index 100% rename from vendor/github.com/tendermint/abci/types/result.go rename to vendor/github.com/tendermint/tendermint/abci/types/result.go diff --git a/vendor/github.com/tendermint/abci/types/types.pb.go b/vendor/github.com/tendermint/tendermint/abci/types/types.pb.go similarity index 99% rename from vendor/github.com/tendermint/abci/types/types.pb.go rename to vendor/github.com/tendermint/tendermint/abci/types/types.pb.go index a6b806fe6..8135db50f 100644 --- a/vendor/github.com/tendermint/abci/types/types.pb.go +++ b/vendor/github.com/tendermint/tendermint/abci/types/types.pb.go @@ -50,7 +50,7 @@ import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" import _ "github.com/gogo/protobuf/gogoproto" -import common "github.com/tendermint/tmlibs/common" +import common "github.com/tendermint/tendermint/libs/common" import context "golang.org/x/net/context" import grpc "google.golang.org/grpc" diff --git a/vendor/github.com/tendermint/abci/types/types.proto b/vendor/github.com/tendermint/tendermint/abci/types/types.proto similarity index 100% rename from vendor/github.com/tendermint/abci/types/types.proto rename to vendor/github.com/tendermint/tendermint/abci/types/types.proto diff --git a/vendor/github.com/tendermint/abci/types/util.go b/vendor/github.com/tendermint/tendermint/abci/types/util.go similarity index 96% rename from vendor/github.com/tendermint/abci/types/util.go rename to vendor/github.com/tendermint/tendermint/abci/types/util.go index 0924ab5ff..458024c58 100644 --- a/vendor/github.com/tendermint/abci/types/util.go +++ b/vendor/github.com/tendermint/tendermint/abci/types/util.go @@ -5,7 +5,7 @@ import ( "encoding/json" "sort" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) //------------------------------------------------------------------------------ diff --git a/vendor/github.com/tendermint/tendermint/blockchain/pool.go b/vendor/github.com/tendermint/tendermint/blockchain/pool.go index 8b964e81a..e379d846a 100644 --- a/vendor/github.com/tendermint/tendermint/blockchain/pool.go +++ b/vendor/github.com/tendermint/tendermint/blockchain/pool.go @@ -8,9 +8,9 @@ import ( "sync/atomic" "time" - cmn "github.com/tendermint/tmlibs/common" - flow "github.com/tendermint/tmlibs/flowrate" - "github.com/tendermint/tmlibs/log" + cmn "github.com/tendermint/tendermint/libs/common" + flow "github.com/tendermint/tendermint/libs/flowrate" + "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/types" diff --git a/vendor/github.com/tendermint/tendermint/blockchain/reactor.go b/vendor/github.com/tendermint/tendermint/blockchain/reactor.go index 33dfdd288..449a42ff0 100644 --- a/vendor/github.com/tendermint/tendermint/blockchain/reactor.go +++ b/vendor/github.com/tendermint/tendermint/blockchain/reactor.go @@ -5,12 +5,13 @@ import ( "reflect" "time" - "github.com/tendermint/go-amino" + amino "github.com/tendermint/go-amino" + + cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/p2p" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/log" ) const ( @@ -174,7 +175,7 @@ func (bcR *BlockchainReactor) respondToPeer(msg *bcBlockRequestMessage, // Receive implements Reactor by handling 4 types of messages (look below). func (bcR *BlockchainReactor) Receive(chID byte, src p2p.Peer, msgBytes []byte) { - msg, err := DecodeMessage(msgBytes) + msg, err := decodeMsg(msgBytes) if err != nil { bcR.Logger.Error("Error decoding message", "src", src, "chId", chID, "msg", msg, "err", err, "bytes", msgBytes) bcR.Switch.StopPeerForError(src, err) @@ -342,17 +343,11 @@ func RegisterBlockchainMessages(cdc *amino.Codec) { cdc.RegisterConcrete(&bcStatusRequestMessage{}, "tendermint/mempool/StatusRequest", nil) } -// DecodeMessage decodes BlockchainMessage. -// TODO: ensure that bz is completely read. -func DecodeMessage(bz []byte) (msg BlockchainMessage, err error) { +func decodeMsg(bz []byte) (msg BlockchainMessage, err error) { if len(bz) > maxMsgSize { - return msg, fmt.Errorf("Msg exceeds max size (%d > %d)", - len(bz), maxMsgSize) + return msg, fmt.Errorf("Msg exceeds max size (%d > %d)", len(bz), maxMsgSize) } err = cdc.UnmarshalBinaryBare(bz, &msg) - if err != nil { - err = cmn.ErrorWrap(err, "DecodeMessage() had bytes left over") - } return } diff --git a/vendor/github.com/tendermint/tendermint/blockchain/store.go b/vendor/github.com/tendermint/tendermint/blockchain/store.go index e7608b2cc..f02d4facb 100644 --- a/vendor/github.com/tendermint/tendermint/blockchain/store.go +++ b/vendor/github.com/tendermint/tendermint/blockchain/store.go @@ -4,8 +4,8 @@ import ( "fmt" "sync" - cmn "github.com/tendermint/tmlibs/common" - dbm "github.com/tendermint/tmlibs/db" + cmn "github.com/tendermint/tendermint/libs/common" + dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/types" ) diff --git a/vendor/github.com/tendermint/tendermint/blockchain/wire.go b/vendor/github.com/tendermint/tendermint/blockchain/wire.go index 55b4e60ae..70b50565d 100644 --- a/vendor/github.com/tendermint/tendermint/blockchain/wire.go +++ b/vendor/github.com/tendermint/tendermint/blockchain/wire.go @@ -2,7 +2,7 @@ package blockchain import ( "github.com/tendermint/go-amino" - "github.com/tendermint/go-crypto" + "github.com/tendermint/tendermint/crypto" ) var cdc = amino.NewCodec() diff --git a/vendor/github.com/tendermint/tendermint/config/config.go b/vendor/github.com/tendermint/tendermint/config/config.go index 5ba568f26..2df8eb8e8 100644 --- a/vendor/github.com/tendermint/tendermint/config/config.go +++ b/vendor/github.com/tendermint/tendermint/config/config.go @@ -45,34 +45,37 @@ type Config struct { BaseConfig `mapstructure:",squash"` // Options for services - RPC *RPCConfig `mapstructure:"rpc"` - P2P *P2PConfig `mapstructure:"p2p"` - Mempool *MempoolConfig `mapstructure:"mempool"` - Consensus *ConsensusConfig `mapstructure:"consensus"` - TxIndex *TxIndexConfig `mapstructure:"tx_index"` + RPC *RPCConfig `mapstructure:"rpc"` + P2P *P2PConfig `mapstructure:"p2p"` + Mempool *MempoolConfig `mapstructure:"mempool"` + Consensus *ConsensusConfig `mapstructure:"consensus"` + TxIndex *TxIndexConfig `mapstructure:"tx_index"` + Instrumentation *InstrumentationConfig `mapstructure:"instrumentation"` } // DefaultConfig returns a default configuration for a Tendermint node func DefaultConfig() *Config { return &Config{ - BaseConfig: DefaultBaseConfig(), - RPC: DefaultRPCConfig(), - P2P: DefaultP2PConfig(), - Mempool: DefaultMempoolConfig(), - Consensus: DefaultConsensusConfig(), - TxIndex: DefaultTxIndexConfig(), + BaseConfig: DefaultBaseConfig(), + RPC: DefaultRPCConfig(), + P2P: DefaultP2PConfig(), + Mempool: DefaultMempoolConfig(), + Consensus: DefaultConsensusConfig(), + TxIndex: DefaultTxIndexConfig(), + Instrumentation: DefaultInstrumentationConfig(), } } // TestConfig returns a configuration that can be used for testing func TestConfig() *Config { return &Config{ - BaseConfig: TestBaseConfig(), - RPC: TestRPCConfig(), - P2P: TestP2PConfig(), - Mempool: TestMempoolConfig(), - Consensus: TestConsensusConfig(), - TxIndex: TestTxIndexConfig(), + BaseConfig: TestBaseConfig(), + RPC: TestRPCConfig(), + P2P: TestP2PConfig(), + Mempool: TestMempoolConfig(), + Consensus: TestConsensusConfig(), + TxIndex: TestTxIndexConfig(), + Instrumentation: TestInstrumentationConfig(), } } @@ -221,16 +224,36 @@ type RPCConfig struct { // NOTE: This server only supports /broadcast_tx_commit GRPCListenAddress string `mapstructure:"grpc_laddr"` + // Maximum number of simultaneous connections. + // Does not include RPC (HTTP&WebSocket) connections. See max_open_connections + // If you want to accept more significant number than the default, make sure + // you increase your OS limits. + // 0 - unlimited. + GRPCMaxOpenConnections int `mapstructure:"grpc_max_open_connections"` + // Activate unsafe RPC commands like /dial_persistent_peers and /unsafe_flush_mempool Unsafe bool `mapstructure:"unsafe"` + + // Maximum number of simultaneous connections (including WebSocket). + // Does not include gRPC connections. See grpc_max_open_connections + // If you want to accept more significant number than the default, make sure + // you increase your OS limits. + // 0 - unlimited. + MaxOpenConnections int `mapstructure:"max_open_connections"` } // DefaultRPCConfig returns a default configuration for the RPC server func DefaultRPCConfig() *RPCConfig { return &RPCConfig{ - ListenAddress: "tcp://0.0.0.0:26657", - GRPCListenAddress: "", - Unsafe: false, + ListenAddress: "tcp://0.0.0.0:26657", + + GRPCListenAddress: "", + GRPCMaxOpenConnections: 900, // no ipv4 + + Unsafe: false, + // should be < {ulimit -Sn} - {MaxNumPeers} - {N of wal, db and other open files} + // 1024 - 50 - 50 = 924 = ~900 + MaxOpenConnections: 900, } } @@ -253,6 +276,9 @@ type P2PConfig struct { // Address to listen for incoming connections ListenAddress string `mapstructure:"laddr"` + // Address to advertise to peers for them to dial + ExternalAddress string `mapstructure:"external_address"` + // Comma separated list of seed nodes to connect to // We only use these if we can’t connect to peers in the addrbook Seeds string `mapstructure:"seeds"` @@ -261,8 +287,8 @@ type P2PConfig struct { // Do not add private peers to this list if you don't want them advertised PersistentPeers string `mapstructure:"persistent_peers"` - // Skip UPNP port forwarding - SkipUPNP bool `mapstructure:"skip_upnp"` + // UPNP port forwarding + UPNP bool `mapstructure:"upnp"` // Path to address book AddrBook string `mapstructure:"addr_book_file"` @@ -317,6 +343,8 @@ type P2PConfig struct { func DefaultP2PConfig() *P2PConfig { return &P2PConfig{ ListenAddress: "tcp://0.0.0.0:26656", + ExternalAddress: "", + UPNP: false, AddrBook: defaultAddrBookPath, AddrBookStrict: true, MaxNumPeers: 50, @@ -339,7 +367,6 @@ func DefaultP2PConfig() *P2PConfig { func TestP2PConfig() *P2PConfig { cfg := DefaultP2PConfig() cfg.ListenAddress = "tcp://0.0.0.0:36656" - cfg.SkipUPNP = true cfg.FlushThrottleTimeout = 10 cfg.AllowDuplicateIP = true return cfg @@ -411,7 +438,7 @@ func (cfg *MempoolConfig) WalDir() string { //----------------------------------------------------------------------------- // ConsensusConfig -// ConsensusConfig defines the confuguration for the Tendermint consensus service, +// ConsensusConfig defines the configuration for the Tendermint consensus service, // including timeouts and details about the WAL and the block structure. type ConsensusConfig struct { RootDir string `mapstructure:"home"` @@ -430,10 +457,6 @@ type ConsensusConfig struct { // Make progress as soon as we have all the precommits (as if TimeoutCommit = 0) SkipTimeoutCommit bool `mapstructure:"skip_timeout_commit"` - // BlockSize - MaxBlockSizeTxs int `mapstructure:"max_block_size_txs"` - MaxBlockSizeBytes int `mapstructure:"max_block_size_bytes"` - // EmptyBlocks mode and possible interval between empty blocks in seconds CreateEmptyBlocks bool `mapstructure:"create_empty_blocks"` CreateEmptyBlocksInterval int `mapstructure:"create_empty_blocks_interval"` @@ -455,8 +478,6 @@ func DefaultConsensusConfig() *ConsensusConfig { TimeoutPrecommitDelta: 500, TimeoutCommit: 1000, SkipTimeoutCommit: false, - MaxBlockSizeTxs: 10000, - MaxBlockSizeBytes: 1, // TODO CreateEmptyBlocks: true, CreateEmptyBlocksInterval: 0, PeerGossipSleepDuration: 100, @@ -536,14 +557,14 @@ func (cfg *ConsensusConfig) SetWalFile(walFile string) { //----------------------------------------------------------------------------- // TxIndexConfig -// TxIndexConfig defines the confuguration for the transaction +// TxIndexConfig defines the configuration for the transaction // indexer, including tags to index. type TxIndexConfig struct { // What indexer to use for transactions // // Options: - // 1) "null" (default) - // 2) "kv" - the simplest possible indexer, backed by key-value storage (defaults to levelDB; see DBBackend). + // 1) "null" + // 2) "kv" (default) - the simplest possible indexer, backed by key-value storage (defaults to levelDB; see DBBackend). Indexer string `mapstructure:"indexer"` // Comma-separated list of tags to index (by default the only tag is tx hash) @@ -573,6 +594,42 @@ func TestTxIndexConfig() *TxIndexConfig { return DefaultTxIndexConfig() } +//----------------------------------------------------------------------------- +// InstrumentationConfig + +// InstrumentationConfig defines the configuration for metrics reporting. +type InstrumentationConfig struct { + // When true, Prometheus metrics are served under /metrics on + // PrometheusListenAddr. + // Check out the documentation for the list of available metrics. + Prometheus bool `mapstructure:"prometheus"` + + // Address to listen for Prometheus collector(s) connections. + PrometheusListenAddr string `mapstructure:"prometheus_listen_addr"` + + // Maximum number of simultaneous connections. + // If you want to accept more significant number than the default, make sure + // you increase your OS limits. + // 0 - unlimited. + MaxOpenConnections int `mapstructure:"max_open_connections"` +} + +// DefaultInstrumentationConfig returns a default configuration for metrics +// reporting. +func DefaultInstrumentationConfig() *InstrumentationConfig { + return &InstrumentationConfig{ + Prometheus: false, + PrometheusListenAddr: ":26660", + MaxOpenConnections: 3, + } +} + +// TestInstrumentationConfig returns a default configuration for metrics +// reporting. +func TestInstrumentationConfig() *InstrumentationConfig { + return DefaultInstrumentationConfig() +} + //----------------------------------------------------------------------------- // Utils diff --git a/vendor/github.com/tendermint/tendermint/config/toml.go b/vendor/github.com/tendermint/tendermint/config/toml.go index 7ed3e971d..858d9b31d 100644 --- a/vendor/github.com/tendermint/tendermint/config/toml.go +++ b/vendor/github.com/tendermint/tendermint/config/toml.go @@ -6,7 +6,7 @@ import ( "path/filepath" "text/template" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) var configTemplate *template.Template @@ -119,15 +119,35 @@ laddr = "{{ .RPC.ListenAddress }}" # NOTE: This server only supports /broadcast_tx_commit grpc_laddr = "{{ .RPC.GRPCListenAddress }}" +# Maximum number of simultaneous connections. +# Does not include RPC (HTTP&WebSocket) connections. See max_open_connections +# If you want to accept more significant number than the default, make sure +# you increase your OS limits. +# 0 - unlimited. +grpc_max_open_connections = {{ .RPC.GRPCMaxOpenConnections }} + # Activate unsafe RPC commands like /dial_seeds and /unsafe_flush_mempool unsafe = {{ .RPC.Unsafe }} +# Maximum number of simultaneous connections (including WebSocket). +# Does not include gRPC connections. See grpc_max_open_connections +# If you want to accept more significant number than the default, make sure +# you increase your OS limits. +# 0 - unlimited. +max_open_connections = {{ .RPC.MaxOpenConnections }} + ##### peer to peer configuration options ##### [p2p] # Address to listen for incoming connections laddr = "{{ .P2P.ListenAddress }}" +# Address to advertise to peers for them to dial +# If empty, will use the same port as the laddr, +# and will introspect on the listener or use UPnP +# to figure out the address. +external_address = "{{ .P2P.ExternalAddress }}" + # Comma separated list of seed nodes to connect to seeds = "{{ .P2P.Seeds }}" @@ -135,6 +155,9 @@ seeds = "{{ .P2P.Seeds }}" # Do not add private peers to this list if you don't want them advertised persistent_peers = "{{ .P2P.PersistentPeers }}" +# UPNP port forwarding +upnp = {{ .P2P.UPNP }} + # Path to address book addr_book_file = "{{ js .P2P.AddrBook }}" @@ -199,10 +222,6 @@ timeout_commit = {{ .Consensus.TimeoutCommit }} # Make progress as soon as we have all the precommits (as if TimeoutCommit = 0) skip_timeout_commit = {{ .Consensus.SkipTimeoutCommit }} -# BlockSize -max_block_size_txs = {{ .Consensus.MaxBlockSizeTxs }} -max_block_size_bytes = {{ .Consensus.MaxBlockSizeBytes }} - # EmptyBlocks mode and possible interval between empty blocks in seconds create_empty_blocks = {{ .Consensus.CreateEmptyBlocks }} create_empty_blocks_interval = {{ .Consensus.CreateEmptyBlocksInterval }} @@ -232,6 +251,23 @@ index_tags = "{{ .TxIndex.IndexTags }}" # desirable (see the comment above). IndexTags has a precedence over # IndexAllTags (i.e. when given both, IndexTags will be indexed). index_all_tags = {{ .TxIndex.IndexAllTags }} + +##### instrumentation configuration options ##### +[instrumentation] + +# When true, Prometheus metrics are served under /metrics on +# PrometheusListenAddr. +# Check out the documentation for the list of available metrics. +prometheus = {{ .Instrumentation.Prometheus }} + +# Address to listen for Prometheus collector(s) connections +prometheus_listen_addr = "{{ .Instrumentation.PrometheusListenAddr }}" + +# Maximum number of simultaneous connections. +# If you want to accept more significant number than the default, make sure +# you increase your OS limits. +# 0 - unlimited. +max_open_connections = {{ .Instrumentation.MaxOpenConnections }} ` /****** these are for test settings ***********/ @@ -287,10 +323,10 @@ var testGenesis = `{ "validators": [ { "pub_key": { - "type": "AC26791624DE60", + "type": "tendermint/PubKeyEd25519", "value":"AT/+aaL1eB0477Mud9JMm8Sh8BIvOYlPGC9KkIUmFaE=" }, - "power": 10, + "power": "10", "name": "" } ], @@ -298,16 +334,16 @@ var testGenesis = `{ }` var testPrivValidator = `{ - "address": "849CB2C877F87A20925F35D00AE6688342D25B47", + "address": "A3258DCBF45DCA0DF052981870F2D1441A36D145", "pub_key": { - "type": "AC26791624DE60", + "type": "tendermint/PubKeyEd25519", "value": "AT/+aaL1eB0477Mud9JMm8Sh8BIvOYlPGC9KkIUmFaE=" }, "priv_key": { - "type": "954568A3288910", + "type": "tendermint/PrivKeyEd25519", "value": "EVkqJO/jIXp3rkASXfh9YnyToYXRXhBr6g9cQVxPFnQBP/5povV4HTjvsy530kybxKHwEi85iU8YL0qQhSYVoQ==" }, - "last_height": 0, - "last_round": 0, + "last_height": "0", + "last_round": "0", "last_step": 0 }` diff --git a/vendor/github.com/tendermint/tendermint/consensus/README.md b/vendor/github.com/tendermint/tendermint/consensus/README.md new file mode 100644 index 000000000..1111317d5 --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/consensus/README.md @@ -0,0 +1 @@ +See the [consensus spec](https://github.com/tendermint/tendermint/tree/master/docs/spec/consensus) and the [reactor consensus spec](https://github.com/tendermint/tendermint/tree/master/docs/spec/reactors/consensus) for more information. diff --git a/vendor/github.com/tendermint/tendermint/consensus/metrics.go b/vendor/github.com/tendermint/tendermint/consensus/metrics.go new file mode 100644 index 000000000..253880e84 --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/consensus/metrics.go @@ -0,0 +1,133 @@ +package consensus + +import ( + "github.com/go-kit/kit/metrics" + "github.com/go-kit/kit/metrics/discard" + + prometheus "github.com/go-kit/kit/metrics/prometheus" + stdprometheus "github.com/prometheus/client_golang/prometheus" +) + +// Metrics contains metrics exposed by this package. +type Metrics struct { + // Height of the chain. + Height metrics.Gauge + + // Number of rounds. + Rounds metrics.Gauge + + // Number of validators. + Validators metrics.Gauge + // Total power of all validators. + ValidatorsPower metrics.Gauge + // Number of validators who did not sign. + MissingValidators metrics.Gauge + // Total power of the missing validators. + MissingValidatorsPower metrics.Gauge + // Number of validators who tried to double sign. + ByzantineValidators metrics.Gauge + // Total power of the byzantine validators. + ByzantineValidatorsPower metrics.Gauge + + // Time between this and the last block. + BlockIntervalSeconds metrics.Histogram + + // Number of transactions. + NumTxs metrics.Gauge + // Size of the block. + BlockSizeBytes metrics.Gauge + // Total number of transactions. + TotalTxs metrics.Gauge +} + +// PrometheusMetrics returns Metrics build using Prometheus client library. +func PrometheusMetrics() *Metrics { + return &Metrics{ + Height: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "height", + Help: "Height of the chain.", + }, []string{}), + Rounds: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "rounds", + Help: "Number of rounds.", + }, []string{}), + + Validators: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "validators", + Help: "Number of validators.", + }, []string{}), + ValidatorsPower: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "validators_power", + Help: "Total power of all validators.", + }, []string{}), + MissingValidators: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "missing_validators", + Help: "Number of validators who did not sign.", + }, []string{}), + MissingValidatorsPower: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "missing_validators_power", + Help: "Total power of the missing validators.", + }, []string{}), + ByzantineValidators: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "byzantine_validators", + Help: "Number of validators who tried to double sign.", + }, []string{}), + ByzantineValidatorsPower: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "byzantine_validators_power", + Help: "Total power of the byzantine validators.", + }, []string{}), + + BlockIntervalSeconds: prometheus.NewHistogramFrom(stdprometheus.HistogramOpts{ + Subsystem: "consensus", + Name: "block_interval_seconds", + Help: "Time between this and the last block.", + Buckets: []float64{1, 2.5, 5, 10, 60}, + }, []string{}), + + NumTxs: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "num_txs", + Help: "Number of transactions.", + }, []string{}), + BlockSizeBytes: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "block_size_bytes", + Help: "Size of the block.", + }, []string{}), + TotalTxs: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "total_txs", + Help: "Total number of transactions.", + }, []string{}), + } +} + +// NopMetrics returns no-op Metrics. +func NopMetrics() *Metrics { + return &Metrics{ + Height: discard.NewGauge(), + + Rounds: discard.NewGauge(), + + Validators: discard.NewGauge(), + ValidatorsPower: discard.NewGauge(), + MissingValidators: discard.NewGauge(), + MissingValidatorsPower: discard.NewGauge(), + ByzantineValidators: discard.NewGauge(), + ByzantineValidatorsPower: discard.NewGauge(), + + BlockIntervalSeconds: discard.NewHistogram(), + + NumTxs: discard.NewGauge(), + BlockSizeBytes: discard.NewGauge(), + TotalTxs: discard.NewGauge(), + } +} diff --git a/vendor/github.com/tendermint/tendermint/consensus/reactor.go b/vendor/github.com/tendermint/tendermint/consensus/reactor.go index 2034ad344..3eb1d73aa 100644 --- a/vendor/github.com/tendermint/tendermint/consensus/reactor.go +++ b/vendor/github.com/tendermint/tendermint/consensus/reactor.go @@ -9,11 +9,11 @@ import ( "github.com/pkg/errors" amino "github.com/tendermint/go-amino" - cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/log" cstypes "github.com/tendermint/tendermint/consensus/types" + cmn "github.com/tendermint/tendermint/libs/common" tmevents "github.com/tendermint/tendermint/libs/events" + "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/p2p" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" @@ -80,6 +80,9 @@ func (conR *ConsensusReactor) OnStop() { conR.BaseReactor.OnStop() conR.unsubscribeFromBroadcastEvents() conR.conS.Stop() + if !conR.FastSync() { + conR.conS.Wait() + } } // SwitchToConsensus switches from fast_sync mode to consensus mode. @@ -183,7 +186,7 @@ func (conR *ConsensusReactor) Receive(chID byte, src p2p.Peer, msgBytes []byte) return } - msg, err := DecodeMessage(msgBytes) + msg, err := decodeMsg(msgBytes) if err != nil { conR.Logger.Error("Error decoding message", "src", src, "chId", chID, "msg", msg, "err", err, "bytes", msgBytes) conR.Switch.StopPeerForError(src, err) @@ -1306,11 +1309,9 @@ func RegisterConsensusMessages(cdc *amino.Codec) { cdc.RegisterConcrete(&ProposalHeartbeatMessage{}, "tendermint/ProposalHeartbeat", nil) } -// DecodeMessage decodes the given bytes into a ConsensusMessage. -func DecodeMessage(bz []byte) (msg ConsensusMessage, err error) { +func decodeMsg(bz []byte) (msg ConsensusMessage, err error) { if len(bz) > maxMsgSize { - return msg, fmt.Errorf("Msg exceeds max size (%d > %d)", - len(bz), maxMsgSize) + return msg, fmt.Errorf("Msg exceeds max size (%d > %d)", len(bz), maxMsgSize) } err = cdc.UnmarshalBinaryBare(bz, &msg) return diff --git a/vendor/github.com/tendermint/tendermint/consensus/replay.go b/vendor/github.com/tendermint/tendermint/consensus/replay.go index 13ec9e403..dd940998f 100644 --- a/vendor/github.com/tendermint/tendermint/consensus/replay.go +++ b/vendor/github.com/tendermint/tendermint/consensus/replay.go @@ -10,11 +10,11 @@ import ( //"strings" "time" - abci "github.com/tendermint/abci/types" - //auto "github.com/tendermint/tmlibs/autofile" - cmn "github.com/tendermint/tmlibs/common" - dbm "github.com/tendermint/tmlibs/db" - "github.com/tendermint/tmlibs/log" + abci "github.com/tendermint/tendermint/abci/types" + //auto "github.com/tendermint/tendermint/libs/autofile" + cmn "github.com/tendermint/tendermint/libs/common" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" @@ -273,7 +273,7 @@ func (h *Handshaker) ReplayBlocks(state sm.State, appHash []byte, appBlockHeight ChainId: h.genDoc.ChainID, ConsensusParams: csParams, Validators: validators, - AppStateBytes: h.genDoc.AppStateJSON, + AppStateBytes: h.genDoc.AppState, } res, err := proxyApp.Consensus().InitChainSync(req) if err != nil { diff --git a/vendor/github.com/tendermint/tendermint/consensus/replay_file.go b/vendor/github.com/tendermint/tendermint/consensus/replay_file.go index 57204b01a..0c0b0dcb1 100644 --- a/vendor/github.com/tendermint/tendermint/consensus/replay_file.go +++ b/vendor/github.com/tendermint/tendermint/consensus/replay_file.go @@ -16,9 +16,9 @@ import ( "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tmlibs/common" - dbm "github.com/tendermint/tmlibs/db" - "github.com/tendermint/tmlibs/log" + cmn "github.com/tendermint/tendermint/libs/common" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" ) const ( diff --git a/vendor/github.com/tendermint/tendermint/consensus/state.go b/vendor/github.com/tendermint/tendermint/consensus/state.go index 3834b1515..e4b360e08 100644 --- a/vendor/github.com/tendermint/tendermint/consensus/state.go +++ b/vendor/github.com/tendermint/tendermint/consensus/state.go @@ -10,8 +10,8 @@ import ( "time" fail "github.com/ebuchman/fail-test" - cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/log" + cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/log" cfg "github.com/tendermint/tendermint/config" cstypes "github.com/tendermint/tendermint/consensus/types" @@ -115,10 +115,24 @@ type ConsensusState struct { // synchronous pubsub between consensus state and reactor. // state only emits EventNewRoundStep, EventVote and EventProposalHeartbeat evsw tmevents.EventSwitch + + // for reporting metrics + metrics *Metrics } +// CSOption sets an optional parameter on the ConsensusState. +type CSOption func(*ConsensusState) + // NewConsensusState returns a new ConsensusState. -func NewConsensusState(config *cfg.ConsensusConfig, state sm.State, blockExec *sm.BlockExecutor, blockStore sm.BlockStore, mempool sm.Mempool, evpool sm.EvidencePool) *ConsensusState { +func NewConsensusState( + config *cfg.ConsensusConfig, + state sm.State, + blockExec *sm.BlockExecutor, + blockStore sm.BlockStore, + mempool sm.Mempool, + evpool sm.EvidencePool, + options ...CSOption, +) *ConsensusState { cs := &ConsensusState{ config: config, blockExec: blockExec, @@ -132,6 +146,7 @@ func NewConsensusState(config *cfg.ConsensusConfig, state sm.State, blockExec *s wal: nilWAL{}, evpool: evpool, evsw: tmevents.NewEventSwitch(), + metrics: NopMetrics(), } // set function defaults (may be overwritten before calling Start) cs.decideProposal = cs.defaultDecideProposal @@ -143,6 +158,9 @@ func NewConsensusState(config *cfg.ConsensusConfig, state sm.State, blockExec *s // We do that upon Start(). cs.reconstructLastCommit(state) cs.BaseService = *cmn.NewBaseService(nil, "ConsensusState", cs) + for _, option := range options { + option(cs) + } return cs } @@ -161,6 +179,11 @@ func (cs *ConsensusState) SetEventBus(b *types.EventBus) { cs.blockExec.SetEventBus(b) } +// WithMetrics sets the metrics. +func WithMetrics(metrics *Metrics) CSOption { + return func(cs *ConsensusState) { cs.metrics = metrics } +} + // String returns a string. func (cs *ConsensusState) String() string { // better not to access shared variables @@ -291,16 +314,8 @@ func (cs *ConsensusState) startRoutines(maxSteps int) { // OnStop implements cmn.Service. It stops all routines and waits for the WAL to finish. func (cs *ConsensusState) OnStop() { - cs.BaseService.OnStop() - cs.evsw.Stop() - cs.timeoutTicker.Stop() - - // Make BaseService.Wait() wait until cs.wal.Wait() - if cs.IsRunning() { - cs.wal.Wait() - } } // Wait waits for the the main routine to return. @@ -387,6 +402,7 @@ func (cs *ConsensusState) SetProposalAndBlock(proposal *types.Proposal, block *t // internal functions for managing the state func (cs *ConsensusState) updateHeight(height int64) { + cs.metrics.Height.Set(float64(height)) cs.Height = height } @@ -579,6 +595,7 @@ func (cs *ConsensusState) receiveRoutine(maxSteps int) { // close wal now that we're done writing to it cs.wal.Stop() + cs.wal.Wait() close(cs.done) return @@ -600,7 +617,7 @@ func (cs *ConsensusState) handleMsg(mi msgInfo) { err = cs.setProposal(msg.Proposal) case *BlockPartMessage: // if the proposal is complete, we'll enterPrevote or tryFinalizeCommit - _, err = cs.addProposalBlockPart(msg.Height, msg.Part) + _, err = cs.addProposalBlockPart(msg, peerID) if err != nil && msg.Round != cs.Round { cs.Logger.Debug("Received block part from wrong round", "height", cs.Height, "csRound", cs.Round, "blockRound", msg.Round) err = nil @@ -722,6 +739,7 @@ func (cs *ConsensusState) enterNewRound(height int64, round int) { cs.Votes.SetRound(round + 1) // also track next round (round+1) to allow round-skipping cs.eventBus.PublishEventNewRound(cs.RoundStateEvent()) + cs.metrics.Rounds.Set(float64(round)) // Wait for txs to be available in the mempool // before we enterPropose in round 0. If the last block changed the app hash, @@ -907,7 +925,7 @@ func (cs *ConsensusState) createProposalBlock() (block *types.Block, blockParts } // Mempool validated transactions - txs := cs.mempool.Reap(cs.config.MaxBlockSizeTxs) + txs := cs.mempool.Reap(cs.state.ConsensusParams.BlockSize.MaxTxs) block, parts := cs.state.MakeBlock(cs.Height, txs, commit) evidence := cs.evpool.PendingEvidence() block.AddEvidence(evidence) @@ -1280,6 +1298,9 @@ func (cs *ConsensusState) finalizeCommit(height int64) { fail.Fail() // XXX + // must be called before we update state + cs.recordMetrics(height, block) + // NewHeightStep! cs.updateToState(stateCopy) @@ -1295,6 +1316,44 @@ func (cs *ConsensusState) finalizeCommit(height int64) { // * cs.StartTime is set to when we will start round0. } +func (cs *ConsensusState) recordMetrics(height int64, block *types.Block) { + cs.metrics.Validators.Set(float64(cs.Validators.Size())) + cs.metrics.ValidatorsPower.Set(float64(cs.Validators.TotalVotingPower())) + missingValidators := 0 + missingValidatorsPower := int64(0) + for i, val := range cs.Validators.Validators { + var vote *types.Vote + if i < len(block.LastCommit.Precommits) { + vote = block.LastCommit.Precommits[i] + } + if vote == nil { + missingValidators++ + missingValidatorsPower += val.VotingPower + } + } + cs.metrics.MissingValidators.Set(float64(missingValidators)) + cs.metrics.MissingValidatorsPower.Set(float64(missingValidatorsPower)) + cs.metrics.ByzantineValidators.Set(float64(len(block.Evidence.Evidence))) + byzantineValidatorsPower := int64(0) + for _, ev := range block.Evidence.Evidence { + if _, val := cs.Validators.GetByAddress(ev.Address()); val != nil { + byzantineValidatorsPower += val.VotingPower + } + } + cs.metrics.ByzantineValidatorsPower.Set(float64(byzantineValidatorsPower)) + + if height > 1 { + lastBlockMeta := cs.blockStore.LoadBlockMeta(height - 1) + cs.metrics.BlockIntervalSeconds.Observe( + block.Time.Sub(lastBlockMeta.Header.Time).Seconds(), + ) + } + + cs.metrics.NumTxs.Set(float64(block.NumTxs)) + cs.metrics.BlockSizeBytes.Set(float64(block.Size())) + cs.metrics.TotalTxs.Set(float64(block.TotalTxs)) +} + //----------------------------------------------------------------------------- func (cs *ConsensusState) defaultSetProposal(proposal *types.Proposal) error { @@ -1333,17 +1392,22 @@ func (cs *ConsensusState) defaultSetProposal(proposal *types.Proposal) error { // NOTE: block is not necessarily valid. // Asynchronously triggers either enterPrevote (before we timeout of propose) or tryFinalizeCommit, once we have the full block. -func (cs *ConsensusState) addProposalBlockPart(height int64, part *types.Part) (added bool, err error) { +func (cs *ConsensusState) addProposalBlockPart(msg *BlockPartMessage, peerID p2p.ID) (added bool, err error) { + height, round, part := msg.Height, msg.Round, msg.Part + // Blocks might be reused, so round mismatch is OK if cs.Height != height { - cs.Logger.Debug("Received block part from wrong height", "height", height) + cs.Logger.Debug("Received block part from wrong height", "height", height, "round", round) return false, nil } // We're not expecting a block part. if cs.ProposalBlockParts == nil { - cs.Logger.Info("Received a block part when we're not expecting any", "height", height) - return false, nil // TODO: bad peer? Return error? + // NOTE: this can happen when we've gone to a higher round and + // then receive parts from the previous round - not necessarily a bad peer. + cs.Logger.Info("Received a block part when we're not expecting any", + "height", height, "round", round, "index", part.Index, "peer", peerID) + return false, nil } added, err = cs.ProposalBlockParts.AddPart(part) @@ -1377,7 +1441,7 @@ func (cs *ConsensusState) addProposalBlockPart(height int64, part *types.Part) ( // procedure at this point. } - if cs.Step == cstypes.RoundStepPropose && cs.isProposalComplete() { + if cs.Step <= cstypes.RoundStepPropose && cs.isProposalComplete() { // Move onto the next step cs.enterPrevote(height, cs.Round) } else if cs.Step == cstypes.RoundStepCommit { diff --git a/vendor/github.com/tendermint/tendermint/consensus/ticker.go b/vendor/github.com/tendermint/tendermint/consensus/ticker.go index b37b7c495..a1e2174c3 100644 --- a/vendor/github.com/tendermint/tendermint/consensus/ticker.go +++ b/vendor/github.com/tendermint/tendermint/consensus/ticker.go @@ -3,8 +3,8 @@ package consensus import ( "time" - cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/log" + cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/log" ) var ( diff --git a/vendor/github.com/tendermint/tendermint/consensus/types/height_vote_set.go b/vendor/github.com/tendermint/tendermint/consensus/types/height_vote_set.go index 3c9867940..70a38668f 100644 --- a/vendor/github.com/tendermint/tendermint/consensus/types/height_vote_set.go +++ b/vendor/github.com/tendermint/tendermint/consensus/types/height_vote_set.go @@ -8,7 +8,7 @@ import ( "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) type RoundVoteSet struct { diff --git a/vendor/github.com/tendermint/tendermint/consensus/types/peer_round_state.go b/vendor/github.com/tendermint/tendermint/consensus/types/peer_round_state.go index dcb6c8e02..7a5d69b8e 100644 --- a/vendor/github.com/tendermint/tendermint/consensus/types/peer_round_state.go +++ b/vendor/github.com/tendermint/tendermint/consensus/types/peer_round_state.go @@ -5,7 +5,7 @@ import ( "time" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) //----------------------------------------------------------------------------- diff --git a/vendor/github.com/tendermint/tendermint/consensus/types/round_state.go b/vendor/github.com/tendermint/tendermint/consensus/types/round_state.go index 14da1f149..cca560ccf 100644 --- a/vendor/github.com/tendermint/tendermint/consensus/types/round_state.go +++ b/vendor/github.com/tendermint/tendermint/consensus/types/round_state.go @@ -6,7 +6,7 @@ import ( "time" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) //----------------------------------------------------------------------------- diff --git a/vendor/github.com/tendermint/tendermint/consensus/types/wire.go b/vendor/github.com/tendermint/tendermint/consensus/types/wire.go index bd5c4497d..6342d7eba 100644 --- a/vendor/github.com/tendermint/tendermint/consensus/types/wire.go +++ b/vendor/github.com/tendermint/tendermint/consensus/types/wire.go @@ -2,7 +2,7 @@ package types import ( "github.com/tendermint/go-amino" - "github.com/tendermint/go-crypto" + "github.com/tendermint/tendermint/crypto" ) var cdc = amino.NewCodec() diff --git a/vendor/github.com/tendermint/tendermint/consensus/version.go b/vendor/github.com/tendermint/tendermint/consensus/version.go index 2c137bf7f..5c74a16db 100644 --- a/vendor/github.com/tendermint/tendermint/consensus/version.go +++ b/vendor/github.com/tendermint/tendermint/consensus/version.go @@ -1,7 +1,7 @@ package consensus import ( - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) // kind of arbitrary diff --git a/vendor/github.com/tendermint/tendermint/consensus/wal.go b/vendor/github.com/tendermint/tendermint/consensus/wal.go index 3d9bf8afc..8c4c10bc7 100644 --- a/vendor/github.com/tendermint/tendermint/consensus/wal.go +++ b/vendor/github.com/tendermint/tendermint/consensus/wal.go @@ -12,8 +12,8 @@ import ( amino "github.com/tendermint/go-amino" "github.com/tendermint/tendermint/types" - auto "github.com/tendermint/tmlibs/autofile" - cmn "github.com/tendermint/tmlibs/common" + auto "github.com/tendermint/tendermint/libs/autofile" + cmn "github.com/tendermint/tendermint/libs/common" ) const ( diff --git a/vendor/github.com/tendermint/tendermint/consensus/wal_generator.go b/vendor/github.com/tendermint/tendermint/consensus/wal_generator.go index f61af15f5..f3a365809 100644 --- a/vendor/github.com/tendermint/tendermint/consensus/wal_generator.go +++ b/vendor/github.com/tendermint/tendermint/consensus/wal_generator.go @@ -10,24 +10,24 @@ import ( "time" "github.com/pkg/errors" - "github.com/tendermint/abci/example/kvstore" + "github.com/tendermint/tendermint/abci/example/kvstore" bc "github.com/tendermint/tendermint/blockchain" cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/privval" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" - auto "github.com/tendermint/tmlibs/autofile" - cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/db" - "github.com/tendermint/tmlibs/log" + auto "github.com/tendermint/tendermint/libs/autofile" + cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" ) // WALWithNBlocks generates a consensus WAL. It does this by spining up a // stripped down version of node (proxy app, event bus, consensus state) with a // persistent kvstore application and special consensus wal instance // (byteBufferWAL) and waits until numBlocks are created. Then it returns a WAL -// content. +// content. If the node fails to produce given numBlocks, it returns an error. func WALWithNBlocks(numBlocks int) (data []byte, err error) { config := getConfig() @@ -89,15 +89,15 @@ func WALWithNBlocks(numBlocks int) (data []byte, err error) { if err := consensusState.Start(); err != nil { return nil, errors.Wrap(err, "failed to start consensus state") } - defer consensusState.Stop() select { case <-numBlocksWritten: + consensusState.Stop() wr.Flush() return b.Bytes(), nil case <-time.After(1 * time.Minute): - wr.Flush() - return b.Bytes(), fmt.Errorf("waited too long for tendermint to produce %d blocks (grep logs for `wal_generator`)", numBlocks) + consensusState.Stop() + return []byte{}, fmt.Errorf("waited too long for tendermint to produce %d blocks (grep logs for `wal_generator`)", numBlocks) } } diff --git a/vendor/github.com/tendermint/tendermint/consensus/wire.go b/vendor/github.com/tendermint/tendermint/consensus/wire.go index 81223c689..5f231c0c7 100644 --- a/vendor/github.com/tendermint/tendermint/consensus/wire.go +++ b/vendor/github.com/tendermint/tendermint/consensus/wire.go @@ -2,7 +2,7 @@ package consensus import ( "github.com/tendermint/go-amino" - "github.com/tendermint/go-crypto" + "github.com/tendermint/tendermint/crypto" ) var cdc = amino.NewCodec() diff --git a/vendor/github.com/tendermint/tendermint/crypto/CHANGELOG.md b/vendor/github.com/tendermint/tendermint/crypto/CHANGELOG.md new file mode 100644 index 000000000..dd7c1039f --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/crypto/CHANGELOG.md @@ -0,0 +1,154 @@ +# Changelog + +## 0.9.0 + +BREAKING CHANGES + +- `priv.PubKey()` no longer returns an error. Any applicable errors (such as when fetching the public key from a hardware wallet) should be checked and returned when constructing the private key. + +## 0.8.0 + +**TBD** + +## 0.7.0 + +**May 30th, 2018** + +BREAKING CHANGES + +No breaking changes compared to 0.6.2, but making up for the version bump that +should have happened in 0.6.1. + +We also bring in the `tmlibs/merkle` package with breaking changes: + +- change the hash function from RIPEMD160 to tmhash (first 20-bytes of SHA256) +- remove unused funcs and unexport SimpleMap + +FEATURES + +- [xchacha20poly1305] New authenticated encryption module +- [merkle] Moved in from tmlibs +- [merkle/tmhash] New hash function: the first 20-bytes of SHA256 + +IMPROVEMENTS + +- Remove some dead code +- Use constant-time compare for signatures + +BUG FIXES + +- Fix MixEntropy weakness +- Fix PrivKeyEd25519.Generate() + +## 0.6.2 (April 9, 2018) + +IMPROVEMENTS + +- Update for latest go-amino + +## 0.6.1 (March 26, 2018) + +BREAKING CHANGES + +- Encoding uses MarshalBinaryBare rather than MarshalBinary (which auto-length-prefixes) for pub/priv/sig. + +## 0.6.0 (March 2, 2018) + +BREAKING CHANGES + +- Update Amino names from "com.tendermint/..." to "tendermint/" + +## 0.5.0 (March 2, 2018) + +BREAKING CHANGES + +- nano: moved to `_nano` now while we're having build issues +- bcrypt: moved to `keys/bcrypt` +- hd: moved to `keys/hd`; `BTC` added to some function names; other function cleanup +- keys/cryptostore: moved to `keys`, renamed to `keybase`, and completely refactored +- keys: moved BIP39 related code to `keys/words` + +FEATURE + +- `Address` is a type alias for `cmn.HexBytes` + +BUG FIX + +- PrivKey comparisons done in constant time + +## 0.4.1 (October 27, 2017) + +This release removes support for bcrypt as it was merged too soon without an upgrade plan +for existing keys. + +REVERTS THE FOLLOWING COMMITS: + +- Parameterize and lower bcrypt cost - dfc4cdd2d71513e4a9922d679c74f36357c4c862 +- Upgrade keys to use bcrypt with salts (#38) - 8e7f0e7701f92206679ad093d013b9b162427631 + +## 0.4.0 (October 27, 2017) + +BREAKING CHANGES: + +- `keys`: use bcrypt plus salt + +FEATURES: + +- add support for signing via Ledger Nano + +IMPROVEMENTS: + +- linting and comments + +## 0.3.0 (September 22, 2017) + +BREAKING CHANGES: + +- Remove `cmd` and `keys/tx` packages altogether: move it to the cosmos-sdk +- `cryptostore.Generator` takes a secret +- Remove `String()` from `Signature` interface + +FEATURES: + +- `keys`: add CRC16 error correcting code + +IMPROVEMENTS: + +- Allow no passwords on keys for development convenience + + +## 0.2.1 (June 21, 2017) + +- Improve keys command + - No password prompts in non-interactive mode (echo 'foobar' | keys new foo) + - Added support for seed phrases + - Seed phrase now returned on `keys new` + - Add `keys restore` to restore private key from key phrase + - Checksum to verify typos in the seed phrase (rather than just a useless key) + - Add `keys delete` to remove a key if needed + +## 0.2.0 (May 18, 2017) + +BREAKING CHANGES: + +- [hd] The following functions no longer take a `coin string` as argument: `ComputeAddress`, `AddrFromPubKeyBytes`, `ComputeAddressForPrivKey`, `ComputeWIF`, `WIFFromPrivKeyBytes` +- Changes to `PrivKey`, `PubKey`, and `Signature` (denoted `Xxx` below): + - interfaces are renamed `XxxInner`, and are not for use outside the package, though they must be exposed for sake of serialization. + - `Xxx` is now a struct that wraps the corresponding `XxxInner` interface + +FEATURES: + +- `github.com/tendermint/go-keys -> github.com/tendermint/go-crypto/keys` - command and lib for generating and managing encrypted keys +- [hd] New function `WIFFromPrivKeyBytes(privKeyBytes []byte, compress bool) string` +- Changes to `PrivKey`, `PubKey`, and `Signature` (denoted `Xxx` below): + - Expose a new method `Unwrap() XxxInner` on the `Xxx` struct which returns the corresponding `XxxInner` interface + - Expose a new method `Wrap() Xxx` on the `XxxInner` interface which returns the corresponding `Xxx` struct + +IMPROVEMENTS: + +- Update to use new `tmlibs` repository + +## 0.1.0 (April 14, 2017) + +Initial release + diff --git a/vendor/github.com/tendermint/tendermint/crypto/README.md b/vendor/github.com/tendermint/tendermint/crypto/README.md new file mode 100644 index 000000000..32afde699 --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/crypto/README.md @@ -0,0 +1,25 @@ +# crypto + +crypto is the cryptographic package adapted for Tendermint's uses + +## Importing it +`import "github.com/tendermint/tendermint/crypto"` + +## Binary encoding + +For Binary encoding, please refer to the [Tendermint encoding spec](https://github.com/tendermint/tendermint/blob/master/docs/spec/blockchain/encoding.md). + +## JSON Encoding + +crypto `.Bytes()` uses Amino:binary encoding, but Amino:JSON is also supported. + +```go +Example Amino:JSON encodings: + +crypto.PrivKeyEd25519 - {"type":"954568A3288910","value":"EVkqJO/jIXp3rkASXfh9YnyToYXRXhBr6g9cQVxPFnQBP/5povV4HTjvsy530kybxKHwEi85iU8YL0qQhSYVoQ=="} +crypto.SignatureEd25519 - {"type":"6BF5903DA1DB28","value":"77sQNZOrf7ltExpf7AV1WaYPCHbyRLgjBsoWVzcduuLk+jIGmYk+s5R6Emm29p12HeiNAuhUJgdFGmwkpeGJCA=="} +crypto.PubKeyEd25519 - {"type":"AC26791624DE60","value":"AT/+aaL1eB0477Mud9JMm8Sh8BIvOYlPGC9KkIUmFaE="} +crypto.PrivKeySecp256k1 - {"type":"019E82E1B0F798","value":"zx4Pnh67N+g2V+5vZbQzEyRerX9c4ccNZOVzM9RvJ0Y="} +crypto.SignatureSecp256k1 - {"type":"6D1EA416E1FEE8","value":"MEUCIQCIg5TqS1l7I+MKTrSPIuUN2+4m5tA29dcauqn3NhEJ2wIgICaZ+lgRc5aOTVahU/XoLopXKn8BZcl0bnuYWLvohR8="} +crypto.PubKeySecp256k1 - {"type":"F8CCEAEB5AE980","value":"A8lPKJXcNl5VHt1FK8a244K9EJuS4WX1hFBnwisi0IJx"} +``` diff --git a/vendor/github.com/tendermint/go-crypto/amino.go b/vendor/github.com/tendermint/tendermint/crypto/amino.go similarity index 85% rename from vendor/github.com/tendermint/go-crypto/amino.go rename to vendor/github.com/tendermint/tendermint/crypto/amino.go index 89636895a..6a8703fc9 100644 --- a/vendor/github.com/tendermint/go-crypto/amino.go +++ b/vendor/github.com/tendermint/tendermint/crypto/amino.go @@ -15,6 +15,7 @@ func init() { RegisterAmino(cdc) } +// RegisterAmino registers all crypto related types in the given (amino) codec. func RegisterAmino(cdc *amino.Codec) { cdc.RegisterInterface((*PubKey)(nil), nil) cdc.RegisterConcrete(PubKeyEd25519{}, @@ -30,7 +31,7 @@ func RegisterAmino(cdc *amino.Codec) { cdc.RegisterInterface((*Signature)(nil), nil) cdc.RegisterConcrete(SignatureEd25519{}, - "tendermint/SignatureKeyEd25519", nil) + "tendermint/SignatureEd25519", nil) cdc.RegisterConcrete(SignatureSecp256k1{}, - "tendermint/SignatureKeySecp256k1", nil) + "tendermint/SignatureSecp256k1", nil) } diff --git a/vendor/github.com/tendermint/go-crypto/armor.go b/vendor/github.com/tendermint/tendermint/crypto/armor.go similarity index 76% rename from vendor/github.com/tendermint/go-crypto/armor.go rename to vendor/github.com/tendermint/tendermint/crypto/armor.go index 5f199df43..4146048ad 100644 --- a/vendor/github.com/tendermint/go-crypto/armor.go +++ b/vendor/github.com/tendermint/tendermint/crypto/armor.go @@ -2,9 +2,9 @@ package crypto import ( "bytes" + "fmt" "io/ioutil" - . "github.com/tendermint/tmlibs/common" "golang.org/x/crypto/openpgp/armor" ) @@ -12,15 +12,15 @@ func EncodeArmor(blockType string, headers map[string]string, data []byte) strin buf := new(bytes.Buffer) w, err := armor.Encode(buf, blockType, headers) if err != nil { - PanicSanity("Error encoding ascii armor: " + err.Error()) + panic(fmt.Errorf("could not encode ascii armor: %s", err)) } _, err = w.Write(data) if err != nil { - PanicSanity("Error encoding ascii armor: " + err.Error()) + panic(fmt.Errorf("could not encode ascii armor: %s", err)) } err = w.Close() if err != nil { - PanicSanity("Error encoding ascii armor: " + err.Error()) + panic(fmt.Errorf("could not encode ascii armor: %s", err)) } return buf.String() } diff --git a/vendor/github.com/tendermint/tendermint/crypto/doc.go b/vendor/github.com/tendermint/tendermint/crypto/doc.go new file mode 100644 index 000000000..544e0df36 --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/crypto/doc.go @@ -0,0 +1,45 @@ +// crypto is a customized/convenience cryptography package for supporting +// Tendermint. + +// It wraps select functionality of equivalent functions in the +// Go standard library, for easy usage with our libraries. + +// Keys: + +// All key generation functions return an instance of the PrivKey interface +// which implements methods + +// AssertIsPrivKeyInner() +// Bytes() []byte +// Sign(msg []byte) Signature +// PubKey() PubKey +// Equals(PrivKey) bool +// Wrap() PrivKey + +// From the above method we can: +// a) Retrieve the public key if needed + +// pubKey := key.PubKey() + +// For example: +// privKey, err := crypto.GenPrivKeyEd25519() +// if err != nil { +// ... +// } +// pubKey := privKey.PubKey() +// ... +// // And then you can use the private and public key +// doSomething(privKey, pubKey) + +// We also provide hashing wrappers around algorithms: + +// Sha256 +// sum := crypto.Sha256([]byte("This is Tendermint")) +// fmt.Printf("%x\n", sum) + +// Ripemd160 +// sum := crypto.Ripemd160([]byte("This is consensus")) +// fmt.Printf("%x\n", sum) +package crypto + +// TODO: Add more docs in here diff --git a/vendor/github.com/tendermint/go-crypto/hash.go b/vendor/github.com/tendermint/tendermint/crypto/hash.go similarity index 100% rename from vendor/github.com/tendermint/go-crypto/hash.go rename to vendor/github.com/tendermint/tendermint/crypto/hash.go diff --git a/vendor/github.com/tendermint/tmlibs/merkle/README.md b/vendor/github.com/tendermint/tendermint/crypto/merkle/README.md similarity index 100% rename from vendor/github.com/tendermint/tmlibs/merkle/README.md rename to vendor/github.com/tendermint/tendermint/crypto/merkle/README.md diff --git a/vendor/github.com/tendermint/tendermint/crypto/merkle/doc.go b/vendor/github.com/tendermint/tendermint/crypto/merkle/doc.go new file mode 100644 index 000000000..865c30217 --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/crypto/merkle/doc.go @@ -0,0 +1,31 @@ +/* +Package merkle computes a deterministic minimal height Merkle tree hash. +If the number of items is not a power of two, some leaves +will be at different levels. Tries to keep both sides of +the tree the same size, but the left may be one greater. + +Use this for short deterministic trees, such as the validator list. +For larger datasets, use IAVLTree. + +Be aware that the current implementation by itself does not prevent +second pre-image attacks. Hence, use this library with caution. +Otherwise you might run into similar issues as, e.g., in early Bitcoin: +https://bitcointalk.org/?topic=102395 + + * + / \ + / \ + / \ + / \ + * * + / \ / \ + / \ / \ + / \ / \ + * * * h6 + / \ / \ / \ + h0 h1 h2 h3 h4 h5 + +TODO(ismail): add 2nd pre-image protection or clarify further on how we use this and why this secure. + +*/ +package merkle diff --git a/vendor/github.com/tendermint/tmlibs/merkle/simple_map.go b/vendor/github.com/tendermint/tendermint/crypto/merkle/simple_map.go similarity index 53% rename from vendor/github.com/tendermint/tmlibs/merkle/simple_map.go rename to vendor/github.com/tendermint/tendermint/crypto/merkle/simple_map.go index cd38de761..ba4b9309a 100644 --- a/vendor/github.com/tendermint/tmlibs/merkle/simple_map.go +++ b/vendor/github.com/tendermint/tendermint/crypto/merkle/simple_map.go @@ -1,47 +1,48 @@ package merkle import ( - cmn "github.com/tendermint/tmlibs/common" - "golang.org/x/crypto/ripemd160" + "github.com/tendermint/tendermint/crypto/tmhash" + cmn "github.com/tendermint/tendermint/libs/common" ) -type SimpleMap struct { +// Merkle tree from a map. +// Leaves are `hash(key) | hash(value)`. +// Leaves are sorted before Merkle hashing. +type simpleMap struct { kvs cmn.KVPairs sorted bool } -func NewSimpleMap() *SimpleMap { - return &SimpleMap{ +func newSimpleMap() *simpleMap { + return &simpleMap{ kvs: nil, sorted: false, } } -func (sm *SimpleMap) Set(key string, value Hasher) { +// Set hashes the key and value and appends it to the kv pairs. +func (sm *simpleMap) Set(key string, value Hasher) { sm.sorted = false - // Hash the key to blind it... why not? - khash := SimpleHashFromBytes([]byte(key)) - - // And the value is hashed too, so you can + // The value is hashed, so you can // check for equality with a cached value (say) // and make a determination to fetch or not. vhash := value.Hash() sm.kvs = append(sm.kvs, cmn.KVPair{ - Key: khash, + Key: []byte(key), Value: vhash, }) } -// Merkle root hash of items sorted by key +// Hash Merkle root hash of items sorted by key // (UNSTABLE: and by value too if duplicate key). -func (sm *SimpleMap) Hash() []byte { +func (sm *simpleMap) Hash() []byte { sm.Sort() return hashKVPairs(sm.kvs) } -func (sm *SimpleMap) Sort() { +func (sm *simpleMap) Sort() { if sm.sorted { return } @@ -50,7 +51,8 @@ func (sm *SimpleMap) Sort() { } // Returns a copy of sorted KVPairs. -func (sm *SimpleMap) KVPairs() cmn.KVPairs { +// NOTE these contain the hashed key and value. +func (sm *simpleMap) KVPairs() cmn.KVPairs { sm.Sort() kvs := make(cmn.KVPairs, len(sm.kvs)) copy(kvs, sm.kvs) @@ -60,10 +62,12 @@ func (sm *SimpleMap) KVPairs() cmn.KVPairs { //---------------------------------------- // A local extension to KVPair that can be hashed. +// Key and value are length prefixed and concatenated, +// then hashed. type KVPair cmn.KVPair func (kv KVPair) Hash() []byte { - hasher := ripemd160.New() + hasher := tmhash.New() err := encodeByteSlice(hasher, kv.Key) if err != nil { panic(err) @@ -76,9 +80,9 @@ func (kv KVPair) Hash() []byte { } func hashKVPairs(kvs cmn.KVPairs) []byte { - kvsH := make([]Hasher, 0, len(kvs)) - for _, kvp := range kvs { - kvsH = append(kvsH, KVPair(kvp)) + kvsH := make([]Hasher, len(kvs)) + for i, kvp := range kvs { + kvsH[i] = KVPair(kvp) } return SimpleHashFromHashers(kvsH) } diff --git a/vendor/github.com/tendermint/tmlibs/merkle/simple_proof.go b/vendor/github.com/tendermint/tendermint/crypto/merkle/simple_proof.go similarity index 79% rename from vendor/github.com/tendermint/tmlibs/merkle/simple_proof.go rename to vendor/github.com/tendermint/tendermint/crypto/merkle/simple_proof.go index ca6ccf372..2541b6d38 100644 --- a/vendor/github.com/tendermint/tmlibs/merkle/simple_proof.go +++ b/vendor/github.com/tendermint/tendermint/crypto/merkle/simple_proof.go @@ -5,10 +5,12 @@ import ( "fmt" ) +// SimpleProof represents a simple merkle proof. type SimpleProof struct { Aunts [][]byte `json:"aunts"` // Hashes from leaf's sibling to a root's child. } +// SimpleProofsFromHashers computes inclusion proof for given items. // proofs[0] is the proof for items[0]. func SimpleProofsFromHashers(items []Hasher) (rootHash []byte, proofs []*SimpleProof) { trails, rootSPN := trailsFromHashers(items) @@ -22,8 +24,11 @@ func SimpleProofsFromHashers(items []Hasher) (rootHash []byte, proofs []*SimpleP return } -func SimpleProofsFromMap(m map[string]Hasher) (rootHash []byte, proofs []*SimpleProof) { - sm := NewSimpleMap() +// SimpleProofsFromMap generates proofs from a map. The keys/values of the map will be used as the keys/values +// in the underlying key-value pairs. +// The keys are sorted before the proofs are computed. +func SimpleProofsFromMap(m map[string]Hasher) (rootHash []byte, proofs map[string]*SimpleProof, keys []string) { + sm := newSimpleMap() for k, v := range m { sm.Set(k, v) } @@ -33,7 +38,15 @@ func SimpleProofsFromMap(m map[string]Hasher) (rootHash []byte, proofs []*Simple for _, kvp := range kvs { kvsH = append(kvsH, KVPair(kvp)) } - return SimpleProofsFromHashers(kvsH) + + rootHash, proofList := SimpleProofsFromHashers(kvsH) + proofs = make(map[string]*SimpleProof) + keys = make([]string, len(proofList)) + for i, kvp := range kvs { + proofs[string(kvp.Key)] = proofList[i] + keys[i] = string(kvp.Key) + } + return } // Verify that leafHash is a leaf hash of the simple-merkle-tree @@ -43,10 +56,13 @@ func (sp *SimpleProof) Verify(index int, total int, leafHash []byte, rootHash [] return computedHash != nil && bytes.Equal(computedHash, rootHash) } +// String implements the stringer interface for SimpleProof. +// It is a wrapper around StringIndented. func (sp *SimpleProof) String() string { return sp.StringIndented("") } +// StringIndented generates a canonical string representation of a SimpleProof. func (sp *SimpleProof) StringIndented(indent string) string { return fmt.Sprintf(`SimpleProof{ %s Aunts: %X @@ -90,7 +106,7 @@ func computeHashFromAunts(index int, total int, leafHash []byte, innerHashes [][ } } -// Helper structure to construct merkle proof. +// SimpleProofNode is a helper structure to construct merkle proof. // The node and the tree is thrown away afterwards. // Exactly one of node.Left and node.Right is nil, unless node is the root, in which case both are nil. // node.Parent.Hash = hash(node.Hash, node.Right.Hash) or @@ -102,8 +118,8 @@ type SimpleProofNode struct { Right *SimpleProofNode // Right sibling (only one of Left,Right is set) } -// Starting from a leaf SimpleProofNode, FlattenAunts() will return -// the inner hashes for the item corresponding to the leaf. +// FlattenAunts will return the inner hashes for the item corresponding to the leaf, +// starting from a leaf SimpleProofNode. func (spn *SimpleProofNode) FlattenAunts() [][]byte { // Nonrecursive impl. innerHashes := [][]byte{} diff --git a/vendor/github.com/tendermint/tendermint/crypto/merkle/simple_tree.go b/vendor/github.com/tendermint/tendermint/crypto/merkle/simple_tree.go new file mode 100644 index 000000000..46a075909 --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/crypto/merkle/simple_tree.go @@ -0,0 +1,58 @@ +package merkle + +import ( + "github.com/tendermint/tendermint/crypto/tmhash" +) + +// SimpleHashFromTwoHashes is the basic operation of the Merkle tree: Hash(left | right). +func SimpleHashFromTwoHashes(left, right []byte) []byte { + var hasher = tmhash.New() + err := encodeByteSlice(hasher, left) + if err != nil { + panic(err) + } + err = encodeByteSlice(hasher, right) + if err != nil { + panic(err) + } + return hasher.Sum(nil) +} + +// SimpleHashFromHashers computes a Merkle tree from items that can be hashed. +func SimpleHashFromHashers(items []Hasher) []byte { + hashes := make([][]byte, len(items)) + for i, item := range items { + hash := item.Hash() + hashes[i] = hash + } + return simpleHashFromHashes(hashes) +} + +// SimpleHashFromMap computes a Merkle tree from sorted map. +// Like calling SimpleHashFromHashers with +// `item = []byte(Hash(key) | Hash(value))`, +// sorted by `item`. +func SimpleHashFromMap(m map[string]Hasher) []byte { + sm := newSimpleMap() + for k, v := range m { + sm.Set(k, v) + } + return sm.Hash() +} + +//---------------------------------------------------------------- + +// Expects hashes! +func simpleHashFromHashes(hashes [][]byte) []byte { + // Recursive impl. + switch len(hashes) { + case 0: + return nil + case 1: + return hashes[0] + default: + left := simpleHashFromHashes(hashes[:(len(hashes)+1)/2]) + right := simpleHashFromHashes(hashes[(len(hashes)+1)/2:]) + return SimpleHashFromTwoHashes(left, right) + } +} diff --git a/vendor/github.com/tendermint/tmlibs/merkle/types.go b/vendor/github.com/tendermint/tendermint/crypto/merkle/types.go similarity index 72% rename from vendor/github.com/tendermint/tmlibs/merkle/types.go rename to vendor/github.com/tendermint/tendermint/crypto/merkle/types.go index a0c491a7e..2fcb3f39d 100644 --- a/vendor/github.com/tendermint/tmlibs/merkle/types.go +++ b/vendor/github.com/tendermint/tendermint/crypto/merkle/types.go @@ -1,10 +1,12 @@ package merkle import ( - "encoding/binary" "io" + + amino "github.com/tendermint/go-amino" ) +// Tree is a Merkle tree interface. type Tree interface { Size() (size int) Height() (height int8) @@ -23,25 +25,14 @@ type Tree interface { IterateRange(start []byte, end []byte, ascending bool, fx func(key []byte, value []byte) (stop bool)) (stopped bool) } +// Hasher represents a hashable piece of data which can be hashed in the Tree. type Hasher interface { Hash() []byte } //----------------------------------------------------------------------- -// NOTE: these are duplicated from go-amino so we dont need go-amino as a dep +// Uvarint length prefixed byteslice func encodeByteSlice(w io.Writer, bz []byte) (err error) { - err = encodeUvarint(w, uint64(len(bz))) - if err != nil { - return - } - _, err = w.Write(bz) - return -} - -func encodeUvarint(w io.Writer, i uint64) (err error) { - var buf [10]byte - n := binary.PutUvarint(buf[:], i) - _, err = w.Write(buf[0:n]) - return + return amino.EncodeByteSlice(w, bz) } diff --git a/vendor/github.com/tendermint/go-crypto/priv_key.go b/vendor/github.com/tendermint/tendermint/crypto/priv_key.go similarity index 84% rename from vendor/github.com/tendermint/go-crypto/priv_key.go rename to vendor/github.com/tendermint/tendermint/crypto/priv_key.go index 61d373f60..dbfe64c33 100644 --- a/vendor/github.com/tendermint/go-crypto/priv_key.go +++ b/vendor/github.com/tendermint/tendermint/crypto/priv_key.go @@ -6,7 +6,6 @@ import ( secp256k1 "github.com/btcsuite/btcd/btcec" "github.com/tendermint/ed25519" "github.com/tendermint/ed25519/extra25519" - . "github.com/tendermint/tmlibs/common" ) func PrivKeyFromBytes(privKeyBytes []byte) (privKey PrivKey, err error) { @@ -18,7 +17,7 @@ func PrivKeyFromBytes(privKeyBytes []byte) (privKey PrivKey, err error) { type PrivKey interface { Bytes() []byte - Sign(msg []byte) Signature + Sign(msg []byte) (Signature, error) PubKey() PubKey Equals(PrivKey) bool } @@ -31,17 +30,13 @@ var _ PrivKey = PrivKeyEd25519{} type PrivKeyEd25519 [64]byte func (privKey PrivKeyEd25519) Bytes() []byte { - bz, err := cdc.MarshalBinaryBare(privKey) - if err != nil { - panic(err) - } - return bz + return cdc.MustMarshalBinaryBare(privKey) } -func (privKey PrivKeyEd25519) Sign(msg []byte) Signature { +func (privKey PrivKeyEd25519) Sign(msg []byte) (Signature, error) { privKeyBytes := [64]byte(privKey) signatureBytes := ed25519.Sign(&privKeyBytes, msg) - return SignatureEd25519(*signatureBytes) + return SignatureEd25519(*signatureBytes), nil } func (privKey PrivKeyEd25519) PubKey() PubKey { @@ -67,12 +62,6 @@ func (privKey PrivKeyEd25519) ToCurve25519() *[32]byte { return keyCurve25519 } -/* -func (privKey PrivKeyEd25519) String() string { - return Fmt("PrivKeyEd25519{*****}") -} -*/ - // Deterministically generates new priv-key bytes from key. func (privKey PrivKeyEd25519) Generate(index int) PrivKeyEd25519 { bz, err := cdc.MarshalBinaryBare(struct { @@ -83,9 +72,10 @@ func (privKey PrivKeyEd25519) Generate(index int) PrivKeyEd25519 { panic(err) } newBytes := Sha256(bz) - var newKey [64]byte - copy(newKey[:], newBytes) - return PrivKeyEd25519(newKey) + newKey := new([64]byte) + copy(newKey[:32], newBytes) + ed25519.MakePublicKey(newKey) + return PrivKeyEd25519(*newKey) } func GenPrivKeyEd25519() PrivKeyEd25519 { @@ -113,20 +103,16 @@ var _ PrivKey = PrivKeySecp256k1{} type PrivKeySecp256k1 [32]byte func (privKey PrivKeySecp256k1) Bytes() []byte { - bz, err := cdc.MarshalBinaryBare(privKey) - if err != nil { - panic(err) - } - return bz + return cdc.MustMarshalBinaryBare(privKey) } -func (privKey PrivKeySecp256k1) Sign(msg []byte) Signature { +func (privKey PrivKeySecp256k1) Sign(msg []byte) (Signature, error) { priv__, _ := secp256k1.PrivKeyFromBytes(secp256k1.S256(), privKey[:]) sig__, err := priv__.Sign(Sha256(msg)) if err != nil { - PanicSanity(err) + return nil, err } - return SignatureSecp256k1(sig__.Serialize()) + return SignatureSecp256k1(sig__.Serialize()), nil } func (privKey PrivKeySecp256k1) PubKey() PubKey { @@ -146,12 +132,6 @@ func (privKey PrivKeySecp256k1) Equals(other PrivKey) bool { } } -/* -func (privKey PrivKeySecp256k1) String() string { - return Fmt("PrivKeySecp256k1{*****}") -} -*/ - /* // Deterministically generates new priv-key bytes from key. func (key PrivKeySecp256k1) Generate(index int) PrivKeySecp256k1 { diff --git a/vendor/github.com/tendermint/go-crypto/pub_key.go b/vendor/github.com/tendermint/tendermint/crypto/pub_key.go similarity index 83% rename from vendor/github.com/tendermint/go-crypto/pub_key.go rename to vendor/github.com/tendermint/tendermint/crypto/pub_key.go index 9be64acdf..588c54113 100644 --- a/vendor/github.com/tendermint/go-crypto/pub_key.go +++ b/vendor/github.com/tendermint/tendermint/crypto/pub_key.go @@ -5,11 +5,16 @@ import ( "crypto/sha256" "fmt" + "golang.org/x/crypto/ripemd160" + secp256k1 "github.com/btcsuite/btcd/btcec" + "github.com/tendermint/ed25519" "github.com/tendermint/ed25519/extra25519" - cmn "github.com/tendermint/tmlibs/common" - "golang.org/x/crypto/ripemd160" + + cmn "github.com/tendermint/tendermint/libs/common" + + "github.com/tendermint/tendermint/crypto/tmhash" ) // An address is a []byte, but hex-encoded even in JSON. @@ -35,14 +40,14 @@ type PubKey interface { var _ PubKey = PubKeyEd25519{} +const PubKeyEd25519Size = 32 + // Implements PubKeyInner -type PubKeyEd25519 [32]byte +type PubKeyEd25519 [PubKeyEd25519Size]byte +// Address is the SHA256-20 of the raw pubkey bytes. func (pubKey PubKeyEd25519) Address() Address { - // append type byte - hasher := ripemd160.New() - hasher.Write(pubKey.Bytes()) // does not error - return Address(hasher.Sum(nil)) + return Address(tmhash.Sum(pubKey[:])) } func (pubKey PubKeyEd25519) Bytes() []byte { @@ -59,15 +64,15 @@ func (pubKey PubKeyEd25519) VerifyBytes(msg []byte, sig_ Signature) bool { if !ok { return false } - pubKeyBytes := [32]byte(pubKey) - sigBytes := [64]byte(sig) + pubKeyBytes := [PubKeyEd25519Size]byte(pubKey) + sigBytes := [SignatureEd25519Size]byte(sig) return ed25519.Verify(&pubKeyBytes, msg, &sigBytes) } // For use with golang/crypto/nacl/box // If error, returns nil. -func (pubKey PubKeyEd25519) ToCurve25519() *[32]byte { - keyCurve25519, pubKeyBytes := new([32]byte), [32]byte(pubKey) +func (pubKey PubKeyEd25519) ToCurve25519() *[PubKeyEd25519Size]byte { + keyCurve25519, pubKeyBytes := new([PubKeyEd25519Size]byte), [PubKeyEd25519Size]byte(pubKey) ok := extra25519.PublicKeyToCurve25519(keyCurve25519, &pubKeyBytes) if !ok { return nil @@ -91,10 +96,12 @@ func (pubKey PubKeyEd25519) Equals(other PubKey) bool { var _ PubKey = PubKeySecp256k1{} +const PubKeySecp256k1Size = 33 + // Implements PubKey. // Compressed pubkey (just the x-cord), // prefixed with 0x02 or 0x03, depending on the y-cord. -type PubKeySecp256k1 [33]byte +type PubKeySecp256k1 [PubKeySecp256k1Size]byte // Implements Bitcoin style addresses: RIPEMD160(SHA256(pubkey)) func (pubKey PubKeySecp256k1) Address() Address { diff --git a/vendor/github.com/tendermint/go-crypto/random.go b/vendor/github.com/tendermint/tendermint/crypto/random.go similarity index 89% rename from vendor/github.com/tendermint/go-crypto/random.go rename to vendor/github.com/tendermint/tendermint/crypto/random.go index 46754219d..5c5057d30 100644 --- a/vendor/github.com/tendermint/go-crypto/random.go +++ b/vendor/github.com/tendermint/tendermint/crypto/random.go @@ -4,11 +4,12 @@ import ( "crypto/aes" "crypto/cipher" crand "crypto/rand" + "crypto/sha256" "encoding/hex" "io" "sync" - . "github.com/tendermint/tmlibs/common" + . "github.com/tendermint/tendermint/libs/common" ) var gRandInfo *randInfo @@ -72,8 +73,12 @@ type randInfo struct { func (ri *randInfo) MixEntropy(seedBytes []byte) { ri.mtx.Lock() defer ri.mtx.Unlock() - // Make new ri.seedBytes - hashBytes := Sha256(seedBytes) + // Make new ri.seedBytes using passed seedBytes and current ri.seedBytes: + // ri.seedBytes = sha256( seedBytes || ri.seedBytes ) + h := sha256.New() + h.Write(seedBytes) + h.Write(ri.seedBytes[:]) + hashBytes := h.Sum(nil) hashBytes32 := [32]byte{} copy(hashBytes32[:], hashBytes) ri.seedBytes = xorBytes32(ri.seedBytes, hashBytes32) diff --git a/vendor/github.com/tendermint/go-crypto/signature.go b/vendor/github.com/tendermint/tendermint/crypto/signature.go similarity index 79% rename from vendor/github.com/tendermint/go-crypto/signature.go rename to vendor/github.com/tendermint/tendermint/crypto/signature.go index cfe927137..ae447da64 100644 --- a/vendor/github.com/tendermint/go-crypto/signature.go +++ b/vendor/github.com/tendermint/tendermint/crypto/signature.go @@ -1,10 +1,11 @@ package crypto import ( - "bytes" "fmt" - . "github.com/tendermint/tmlibs/common" + "crypto/subtle" + + . "github.com/tendermint/tendermint/libs/common" ) func SignatureFromBytes(pubKeyBytes []byte) (pubKey Signature, err error) { @@ -24,8 +25,10 @@ type Signature interface { var _ Signature = SignatureEd25519{} +const SignatureEd25519Size = 64 + // Implements Signature -type SignatureEd25519 [64]byte +type SignatureEd25519 [SignatureEd25519Size]byte func (sig SignatureEd25519) Bytes() []byte { bz, err := cdc.MarshalBinaryBare(sig) @@ -41,7 +44,7 @@ func (sig SignatureEd25519) String() string { return fmt.Sprintf("/%X.../", Fing func (sig SignatureEd25519) Equals(other Signature) bool { if otherEd, ok := other.(SignatureEd25519); ok { - return bytes.Equal(sig[:], otherEd[:]) + return subtle.ConstantTimeCompare(sig[:], otherEd[:]) == 1 } else { return false } @@ -74,8 +77,14 @@ func (sig SignatureSecp256k1) String() string { return fmt.Sprintf("/%X.../", Fi func (sig SignatureSecp256k1) Equals(other Signature) bool { if otherSecp, ok := other.(SignatureSecp256k1); ok { - return bytes.Equal(sig[:], otherSecp[:]) + return subtle.ConstantTimeCompare(sig[:], otherSecp[:]) == 1 } else { return false } } + +func SignatureSecp256k1FromBytes(data []byte) Signature { + sig := make(SignatureSecp256k1, len(data)) + copy(sig[:], data) + return sig +} diff --git a/vendor/github.com/tendermint/go-crypto/symmetric.go b/vendor/github.com/tendermint/tendermint/crypto/symmetric.go similarity index 97% rename from vendor/github.com/tendermint/go-crypto/symmetric.go rename to vendor/github.com/tendermint/tendermint/crypto/symmetric.go index d4ac9b55b..62379c15f 100644 --- a/vendor/github.com/tendermint/go-crypto/symmetric.go +++ b/vendor/github.com/tendermint/tendermint/crypto/symmetric.go @@ -3,7 +3,7 @@ package crypto import ( "errors" - . "github.com/tendermint/tmlibs/common" + . "github.com/tendermint/tendermint/libs/common" "golang.org/x/crypto/nacl/secretbox" ) diff --git a/vendor/github.com/tendermint/tendermint/crypto/tmhash/hash.go b/vendor/github.com/tendermint/tendermint/crypto/tmhash/hash.go new file mode 100644 index 000000000..1b29d8680 --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/crypto/tmhash/hash.go @@ -0,0 +1,48 @@ +package tmhash + +import ( + "crypto/sha256" + "hash" +) + +const ( + Size = 20 + BlockSize = sha256.BlockSize +) + +type sha256trunc struct { + sha256 hash.Hash +} + +func (h sha256trunc) Write(p []byte) (n int, err error) { + return h.sha256.Write(p) +} +func (h sha256trunc) Sum(b []byte) []byte { + shasum := h.sha256.Sum(b) + return shasum[:Size] +} + +func (h sha256trunc) Reset() { + h.sha256.Reset() +} + +func (h sha256trunc) Size() int { + return Size +} + +func (h sha256trunc) BlockSize() int { + return h.sha256.BlockSize() +} + +// New returns a new hash.Hash. +func New() hash.Hash { + return sha256trunc{ + sha256: sha256.New(), + } +} + +// Sum returns the first 20 bytes of SHA256 of the bz. +func Sum(bz []byte) []byte { + hash := sha256.Sum256(bz) + return hash[:Size] +} diff --git a/vendor/github.com/tendermint/tendermint/crypto/version.go b/vendor/github.com/tendermint/tendermint/crypto/version.go new file mode 100644 index 000000000..77c0bed8a --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/crypto/version.go @@ -0,0 +1,3 @@ +package crypto + +const Version = "0.9.0-dev" diff --git a/vendor/github.com/tendermint/tendermint/evidence/pool.go b/vendor/github.com/tendermint/tendermint/evidence/pool.go index 4bad355f7..247629b6b 100644 --- a/vendor/github.com/tendermint/tendermint/evidence/pool.go +++ b/vendor/github.com/tendermint/tendermint/evidence/pool.go @@ -4,9 +4,9 @@ import ( "fmt" "sync" - clist "github.com/tendermint/tmlibs/clist" - dbm "github.com/tendermint/tmlibs/db" - "github.com/tendermint/tmlibs/log" + clist "github.com/tendermint/tendermint/libs/clist" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" diff --git a/vendor/github.com/tendermint/tendermint/evidence/reactor.go b/vendor/github.com/tendermint/tendermint/evidence/reactor.go index 5159572e3..bf11ac105 100644 --- a/vendor/github.com/tendermint/tendermint/evidence/reactor.go +++ b/vendor/github.com/tendermint/tendermint/evidence/reactor.go @@ -5,10 +5,10 @@ import ( "reflect" "time" - "github.com/tendermint/go-amino" - clist "github.com/tendermint/tmlibs/clist" - "github.com/tendermint/tmlibs/log" + amino "github.com/tendermint/go-amino" + clist "github.com/tendermint/tendermint/libs/clist" + "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/types" ) @@ -73,7 +73,7 @@ func (evR *EvidenceReactor) RemovePeer(peer p2p.Peer, reason interface{}) { // Receive implements Reactor. // It adds any received evidence to the evpool. func (evR *EvidenceReactor) Receive(chID byte, src p2p.Peer, msgBytes []byte) { - msg, err := DecodeMessage(msgBytes) + msg, err := decodeMsg(msgBytes) if err != nil { evR.Logger.Error("Error decoding message", "src", src, "chId", chID, "msg", msg, "err", err, "bytes", msgBytes) evR.Switch.StopPeerForError(src, err) @@ -204,11 +204,9 @@ func RegisterEvidenceMessages(cdc *amino.Codec) { "tendermint/evidence/EvidenceListMessage", nil) } -// DecodeMessage decodes a byte-array into a EvidenceMessage. -func DecodeMessage(bz []byte) (msg EvidenceMessage, err error) { +func decodeMsg(bz []byte) (msg EvidenceMessage, err error) { if len(bz) > maxMsgSize { - return msg, fmt.Errorf("Msg exceeds max size (%d > %d)", - len(bz), maxMsgSize) + return msg, fmt.Errorf("Msg exceeds max size (%d > %d)", len(bz), maxMsgSize) } err = cdc.UnmarshalBinaryBare(bz, &msg) return diff --git a/vendor/github.com/tendermint/tendermint/evidence/store.go b/vendor/github.com/tendermint/tendermint/evidence/store.go index 6af5d75d8..20b37bdb2 100644 --- a/vendor/github.com/tendermint/tendermint/evidence/store.go +++ b/vendor/github.com/tendermint/tendermint/evidence/store.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/tendermint/tendermint/types" - dbm "github.com/tendermint/tmlibs/db" + dbm "github.com/tendermint/tendermint/libs/db" ) /* diff --git a/vendor/github.com/tendermint/tendermint/evidence/wire.go b/vendor/github.com/tendermint/tendermint/evidence/wire.go index 842e0707a..fb3a177cc 100644 --- a/vendor/github.com/tendermint/tendermint/evidence/wire.go +++ b/vendor/github.com/tendermint/tendermint/evidence/wire.go @@ -2,7 +2,7 @@ package evidence import ( "github.com/tendermint/go-amino" - "github.com/tendermint/go-crypto" + "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/types" ) diff --git a/vendor/github.com/tendermint/tmlibs/autofile/README.md b/vendor/github.com/tendermint/tendermint/libs/autofile/README.md similarity index 100% rename from vendor/github.com/tendermint/tmlibs/autofile/README.md rename to vendor/github.com/tendermint/tendermint/libs/autofile/README.md diff --git a/vendor/github.com/tendermint/tmlibs/autofile/autofile.go b/vendor/github.com/tendermint/tendermint/libs/autofile/autofile.go similarity index 97% rename from vendor/github.com/tendermint/tmlibs/autofile/autofile.go rename to vendor/github.com/tendermint/tendermint/libs/autofile/autofile.go index 790be5224..313da6789 100644 --- a/vendor/github.com/tendermint/tmlibs/autofile/autofile.go +++ b/vendor/github.com/tendermint/tendermint/libs/autofile/autofile.go @@ -5,7 +5,7 @@ import ( "sync" "time" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) /* AutoFile usage diff --git a/vendor/github.com/tendermint/tmlibs/autofile/group.go b/vendor/github.com/tendermint/tendermint/libs/autofile/group.go similarity index 99% rename from vendor/github.com/tendermint/tmlibs/autofile/group.go rename to vendor/github.com/tendermint/tendermint/libs/autofile/group.go index 1ae545032..b4368ed9e 100644 --- a/vendor/github.com/tendermint/tmlibs/autofile/group.go +++ b/vendor/github.com/tendermint/tendermint/libs/autofile/group.go @@ -15,7 +15,7 @@ import ( "sync" "time" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) const ( diff --git a/vendor/github.com/tendermint/tmlibs/autofile/sighup_watcher.go b/vendor/github.com/tendermint/tendermint/libs/autofile/sighup_watcher.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/autofile/sighup_watcher.go rename to vendor/github.com/tendermint/tendermint/libs/autofile/sighup_watcher.go diff --git a/vendor/github.com/tendermint/tmlibs/clist/clist.go b/vendor/github.com/tendermint/tendermint/libs/clist/clist.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/clist/clist.go rename to vendor/github.com/tendermint/tendermint/libs/clist/clist.go diff --git a/vendor/github.com/tendermint/tmlibs/common/LICENSE b/vendor/github.com/tendermint/tendermint/libs/common/LICENSE similarity index 100% rename from vendor/github.com/tendermint/tmlibs/common/LICENSE rename to vendor/github.com/tendermint/tendermint/libs/common/LICENSE diff --git a/vendor/github.com/tendermint/tmlibs/common/async.go b/vendor/github.com/tendermint/tendermint/libs/common/async.go similarity index 95% rename from vendor/github.com/tendermint/tmlibs/common/async.go rename to vendor/github.com/tendermint/tendermint/libs/common/async.go index 7be09a3c1..e3293ab4c 100644 --- a/vendor/github.com/tendermint/tmlibs/common/async.go +++ b/vendor/github.com/tendermint/tendermint/libs/common/async.go @@ -76,17 +76,15 @@ func (trs *TaskResultSet) Reap() *TaskResultSet { func (trs *TaskResultSet) Wait() *TaskResultSet { for i := 0; i < len(trs.results); i++ { var trch = trs.chz[i] - select { - case result, ok := <-trch: - if ok { - // Write result. - trs.results[i] = taskResultOK{ - TaskResult: result, - OK: true, - } - } else { - // We already wrote it. + result, ok := <-trch + if ok { + // Write result. + trs.results[i] = taskResultOK{ + TaskResult: result, + OK: true, } + } else { + // We already wrote it. } } return trs diff --git a/vendor/github.com/tendermint/tmlibs/common/bit_array.go b/vendor/github.com/tendermint/tendermint/libs/common/bit_array.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/common/bit_array.go rename to vendor/github.com/tendermint/tendermint/libs/common/bit_array.go diff --git a/vendor/github.com/tendermint/tmlibs/common/bytes.go b/vendor/github.com/tendermint/tendermint/libs/common/bytes.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/common/bytes.go rename to vendor/github.com/tendermint/tendermint/libs/common/bytes.go diff --git a/vendor/github.com/tendermint/tmlibs/common/byteslice.go b/vendor/github.com/tendermint/tendermint/libs/common/byteslice.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/common/byteslice.go rename to vendor/github.com/tendermint/tendermint/libs/common/byteslice.go diff --git a/vendor/github.com/tendermint/tmlibs/common/cmap.go b/vendor/github.com/tendermint/tendermint/libs/common/cmap.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/common/cmap.go rename to vendor/github.com/tendermint/tendermint/libs/common/cmap.go diff --git a/vendor/github.com/tendermint/tmlibs/common/colors.go b/vendor/github.com/tendermint/tendermint/libs/common/colors.go similarity index 87% rename from vendor/github.com/tendermint/tmlibs/common/colors.go rename to vendor/github.com/tendermint/tendermint/libs/common/colors.go index 85e592248..049ce7a50 100644 --- a/vendor/github.com/tendermint/tmlibs/common/colors.go +++ b/vendor/github.com/tendermint/tendermint/libs/common/colors.go @@ -81,3 +81,15 @@ func Cyan(args ...interface{}) string { func White(args ...interface{}) string { return treatAll(ANSIFgWhite, args...) } + +func ColoredBytes(data []byte, textColor, bytesColor func(...interface{}) string) string { + s := "" + for _, b := range data { + if 0x21 <= b && b < 0x7F { + s += textColor(string(b)) + } else { + s += bytesColor(Fmt("%02X", b)) + } + } + return s +} diff --git a/vendor/github.com/tendermint/tmlibs/common/date.go b/vendor/github.com/tendermint/tendermint/libs/common/date.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/common/date.go rename to vendor/github.com/tendermint/tendermint/libs/common/date.go diff --git a/vendor/github.com/tendermint/tmlibs/common/errors.go b/vendor/github.com/tendermint/tendermint/libs/common/errors.go similarity index 53% rename from vendor/github.com/tendermint/tmlibs/common/errors.go rename to vendor/github.com/tendermint/tendermint/libs/common/errors.go index 5992b2346..5c31b8968 100644 --- a/vendor/github.com/tendermint/tmlibs/common/errors.go +++ b/vendor/github.com/tendermint/tendermint/libs/common/errors.go @@ -6,106 +6,81 @@ import ( ) //---------------------------------------- -// Convenience methods +// Convenience method. -// ErrorWrap will just call .TraceFrom(), or create a new *cmnError. func ErrorWrap(cause interface{}, format string, args ...interface{}) Error { - msg := Fmt(format, args...) if causeCmnError, ok := cause.(*cmnError); ok { - return causeCmnError.TraceFrom(1, msg) + msg := Fmt(format, args...) + return causeCmnError.Stacktrace().Trace(1, msg) + } else if cause == nil { + return newCmnError(FmtError{format, args}).Stacktrace() + } else { + // NOTE: causeCmnError is a typed nil here. + msg := Fmt(format, args...) + return newCmnError(cause).Stacktrace().Trace(1, msg) } - // NOTE: cause may be nil. - // NOTE: do not use causeCmnError here, not the same as nil. - return newError(msg, cause, cause).Stacktrace() } //---------------------------------------- // Error & cmnError /* -Usage: + +Usage with arbitrary error data: ```go // Error construction - var someT = errors.New("Some err type") - var err1 error = NewErrorWithT(someT, "my message") + type MyError struct{} + var err1 error = NewErrorWithData(MyError{}, "my message") ... // Wrapping var err2 error = ErrorWrap(err1, "another message") if (err1 != err2) { panic("should be the same") ... // Error handling - switch err2.T() { - case someT: ... + switch err2.Data().(type){ + case MyError: ... default: ... } ``` - */ type Error interface { Error() string - Message() string Stacktrace() Error - Trace(format string, args ...interface{}) Error - TraceFrom(offset int, format string, args ...interface{}) Error - Cause() interface{} - WithT(t interface{}) Error - T() interface{} - Format(s fmt.State, verb rune) + Trace(offset int, format string, args ...interface{}) Error + Data() interface{} } -// New Error with no cause where the type is the format string of the message.. +// New Error with formatted message. +// The Error's Data will be a FmtError type. func NewError(format string, args ...interface{}) Error { - msg := Fmt(format, args...) - return newError(msg, nil, format) - + err := FmtError{format, args} + return newCmnError(err) } -// New Error with specified type and message. -func NewErrorWithT(t interface{}, format string, args ...interface{}) Error { - msg := Fmt(format, args...) - return newError(msg, nil, t) -} - -// NOTE: The name of a function "NewErrorWithCause()" implies that you are -// creating a new Error, yet, if the cause is an Error, creating a new Error to -// hold a ref to the old Error is probably *not* what you want to do. -// So, use ErrorWrap(cause, format, a...) instead, which returns the same error -// if cause is an Error. -// IF you must set an Error as the cause of an Error, -// then you can use the WithCauser interface to do so manually. -// e.g. (error).(tmlibs.WithCauser).WithCause(causeError) - -type WithCauser interface { - WithCause(cause interface{}) Error +// New Error with specified data. +func NewErrorWithData(data interface{}) Error { + return newCmnError(data) } type cmnError struct { - msg string // first msg which also appears in msg - cause interface{} // underlying cause (or panic object) - t interface{} // for switching on error + data interface{} // associated data msgtraces []msgtraceItem // all messages traced stacktrace []uintptr // first stack trace } -var _ WithCauser = &cmnError{} var _ Error = &cmnError{} // NOTE: do not expose. -func newError(msg string, cause interface{}, t interface{}) *cmnError { +func newCmnError(data interface{}) *cmnError { return &cmnError{ - msg: msg, - cause: cause, - t: t, + data: data, msgtraces: nil, stacktrace: nil, } } -func (err *cmnError) Message() string { - return err.msg -} - +// Implements error. func (err *cmnError) Error() string { return fmt.Sprintf("%v", err) } @@ -121,42 +96,17 @@ func (err *cmnError) Stacktrace() Error { } // Add tracing information with msg. -func (err *cmnError) Trace(format string, args ...interface{}) Error { - msg := Fmt(format, args...) - return err.doTrace(msg, 0) -} - -// Same as Trace, but traces the line `offset` calls out. -// If n == 0, the behavior is identical to Trace(). -func (err *cmnError) TraceFrom(offset int, format string, args ...interface{}) Error { +// Set n=0 unless wrapped with some function, then n > 0. +func (err *cmnError) Trace(offset int, format string, args ...interface{}) Error { msg := Fmt(format, args...) return err.doTrace(msg, offset) } -// Return last known cause. -// NOTE: The meaning of "cause" is left for the caller to define. -// There exists no "canonical" definition of "cause". -// Instead of blaming, try to handle it, or organize it. -func (err *cmnError) Cause() interface{} { - return err.cause -} - -// Overwrites the Error's cause. -func (err *cmnError) WithCause(cause interface{}) Error { - err.cause = cause - return err -} - -// Overwrites the Error's type. -func (err *cmnError) WithT(t interface{}) Error { - err.t = t - return err -} - -// Return the "type" of this message, primarily for switching -// to handle this Error. -func (err *cmnError) T() interface{} { - return err.t +// Return the "data" of this error. +// Data could be used for error handling/switching, +// or for holding general error/debug information. +func (err *cmnError) Data() interface{} { + return err.data } func (err *cmnError) doTrace(msg string, n int) Error { @@ -177,12 +127,8 @@ func (err *cmnError) Format(s fmt.State, verb rune) { default: if s.Flag('#') { s.Write([]byte("--= Error =--\n")) - // Write msg. - s.Write([]byte(fmt.Sprintf("Message: %s\n", err.msg))) - // Write cause. - s.Write([]byte(fmt.Sprintf("Cause: %#v\n", err.cause))) - // Write type. - s.Write([]byte(fmt.Sprintf("T: %#v\n", err.t))) + // Write data. + s.Write([]byte(fmt.Sprintf("Data: %#v\n", err.data))) // Write msg trace items. s.Write([]byte(fmt.Sprintf("Msg Traces:\n"))) for i, msgtrace := range err.msgtraces { @@ -200,11 +146,7 @@ func (err *cmnError) Format(s fmt.State, verb rune) { s.Write([]byte("--= /Error =--\n")) } else { // Write msg. - if err.cause != nil { - s.Write([]byte(fmt.Sprintf("Error{`%s` (cause: %v)}", err.msg, err.cause))) // TODO tick-esc? - } else { - s.Write([]byte(fmt.Sprintf("Error{`%s`}", err.msg))) // TODO tick-esc? - } + s.Write([]byte(fmt.Sprintf("Error{%v}", err.data))) // TODO tick-esc? } } } @@ -232,6 +174,45 @@ func (mti msgtraceItem) String() string { ) } +//---------------------------------------- +// fmt error + +/* + +FmtError is the data type for NewError() (e.g. NewError().Data().(FmtError)) +Theoretically it could be used to switch on the format string. + +```go + // Error construction + var err1 error = NewError("invalid username %v", "BOB") + var err2 error = NewError("another kind of error") + ... + // Error handling + switch err1.Data().(cmn.FmtError).Format() { + case "invalid username %v": ... + case "another kind of error": ... + default: ... + } +``` +*/ +type FmtError struct { + format string + args []interface{} +} + +func (fe FmtError) Error() string { + return fmt.Sprintf(fe.format, fe.args...) +} + +func (fe FmtError) String() string { + return fmt.Sprintf("FmtError{format:%v,args:%v}", + fe.format, fe.args) +} + +func (fe FmtError) Format() string { + return fe.format +} + //---------------------------------------- // Panic wrappers // XXX DEPRECATED diff --git a/vendor/github.com/tendermint/tmlibs/common/heap.go b/vendor/github.com/tendermint/tendermint/libs/common/heap.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/common/heap.go rename to vendor/github.com/tendermint/tendermint/libs/common/heap.go diff --git a/vendor/github.com/tendermint/tmlibs/common/int.go b/vendor/github.com/tendermint/tendermint/libs/common/int.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/common/int.go rename to vendor/github.com/tendermint/tendermint/libs/common/int.go diff --git a/vendor/github.com/tendermint/tmlibs/common/io.go b/vendor/github.com/tendermint/tendermint/libs/common/io.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/common/io.go rename to vendor/github.com/tendermint/tendermint/libs/common/io.go diff --git a/vendor/github.com/tendermint/tmlibs/common/kvpair.go b/vendor/github.com/tendermint/tendermint/libs/common/kvpair.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/common/kvpair.go rename to vendor/github.com/tendermint/tendermint/libs/common/kvpair.go diff --git a/vendor/github.com/tendermint/tmlibs/common/math.go b/vendor/github.com/tendermint/tendermint/libs/common/math.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/common/math.go rename to vendor/github.com/tendermint/tendermint/libs/common/math.go diff --git a/vendor/github.com/tendermint/tmlibs/common/net.go b/vendor/github.com/tendermint/tendermint/libs/common/net.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/common/net.go rename to vendor/github.com/tendermint/tendermint/libs/common/net.go diff --git a/vendor/github.com/tendermint/tmlibs/common/nil.go b/vendor/github.com/tendermint/tendermint/libs/common/nil.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/common/nil.go rename to vendor/github.com/tendermint/tendermint/libs/common/nil.go diff --git a/vendor/github.com/tendermint/tmlibs/common/os.go b/vendor/github.com/tendermint/tendermint/libs/common/os.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/common/os.go rename to vendor/github.com/tendermint/tendermint/libs/common/os.go diff --git a/vendor/github.com/tendermint/tmlibs/common/random.go b/vendor/github.com/tendermint/tendermint/libs/common/random.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/common/random.go rename to vendor/github.com/tendermint/tendermint/libs/common/random.go diff --git a/vendor/github.com/tendermint/tmlibs/common/repeat_timer.go b/vendor/github.com/tendermint/tendermint/libs/common/repeat_timer.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/common/repeat_timer.go rename to vendor/github.com/tendermint/tendermint/libs/common/repeat_timer.go diff --git a/vendor/github.com/tendermint/tmlibs/common/service.go b/vendor/github.com/tendermint/tendermint/libs/common/service.go similarity index 99% rename from vendor/github.com/tendermint/tmlibs/common/service.go rename to vendor/github.com/tendermint/tendermint/libs/common/service.go index 2f90fa4f9..b6f166e77 100644 --- a/vendor/github.com/tendermint/tmlibs/common/service.go +++ b/vendor/github.com/tendermint/tendermint/libs/common/service.go @@ -5,7 +5,7 @@ import ( "fmt" "sync/atomic" - "github.com/tendermint/tmlibs/log" + "github.com/tendermint/tendermint/libs/log" ) var ( diff --git a/vendor/github.com/tendermint/tmlibs/common/string.go b/vendor/github.com/tendermint/tendermint/libs/common/string.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/common/string.go rename to vendor/github.com/tendermint/tendermint/libs/common/string.go diff --git a/vendor/github.com/tendermint/tmlibs/common/throttle_timer.go b/vendor/github.com/tendermint/tendermint/libs/common/throttle_timer.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/common/throttle_timer.go rename to vendor/github.com/tendermint/tendermint/libs/common/throttle_timer.go diff --git a/vendor/github.com/tendermint/tmlibs/common/types.pb.go b/vendor/github.com/tendermint/tendermint/libs/common/types.pb.go similarity index 68% rename from vendor/github.com/tendermint/tmlibs/common/types.pb.go rename to vendor/github.com/tendermint/tendermint/libs/common/types.pb.go index 047b7aee2..f6645602a 100644 --- a/vendor/github.com/tendermint/tmlibs/common/types.pb.go +++ b/vendor/github.com/tendermint/tendermint/libs/common/types.pb.go @@ -1,4 +1,4 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. +// Code generated by protoc-gen-go. DO NOT EDIT. // source: common/types.proto /* @@ -14,10 +14,9 @@ It has these top-level messages: //nolint: gas package common -import proto "github.com/gogo/protobuf/proto" +import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" -import _ "github.com/gogo/protobuf/gogoproto" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal @@ -28,7 +27,7 @@ var _ = math.Inf // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package +const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // Define these here for compatibility but use tmlibs/common.KVPair. type KVPair struct { @@ -39,7 +38,7 @@ type KVPair struct { func (m *KVPair) Reset() { *m = KVPair{} } func (m *KVPair) String() string { return proto.CompactTextString(m) } func (*KVPair) ProtoMessage() {} -func (*KVPair) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{0} } +func (*KVPair) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *KVPair) GetKey() []byte { if m != nil { @@ -58,13 +57,13 @@ func (m *KVPair) GetValue() []byte { // Define these here for compatibility but use tmlibs/common.KI64Pair. type KI64Pair struct { Key []byte `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` - Value int64 `protobuf:"varint,2,opt,name=value,proto3" json:"value,omitempty"` + Value int64 `protobuf:"varint,2,opt,name=value" json:"value,omitempty"` } func (m *KI64Pair) Reset() { *m = KI64Pair{} } func (m *KI64Pair) String() string { return proto.CompactTextString(m) } func (*KI64Pair) ProtoMessage() {} -func (*KI64Pair) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{1} } +func (*KI64Pair) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *KI64Pair) GetKey() []byte { if m != nil { @@ -85,17 +84,15 @@ func init() { proto.RegisterType((*KI64Pair)(nil), "common.KI64Pair") } -func init() { proto.RegisterFile("common/types.proto", fileDescriptorTypes) } +func init() { proto.RegisterFile("common/types.proto", fileDescriptor0) } -var fileDescriptorTypes = []byte{ - // 137 bytes of a gzipped FileDescriptorProto +var fileDescriptor0 = []byte{ + // 107 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4a, 0xce, 0xcf, 0xcd, 0xcd, 0xcf, 0xd3, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, - 0x83, 0x88, 0x49, 0xe9, 0xa6, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0xa7, - 0xe7, 0xa7, 0xe7, 0xeb, 0x83, 0xa5, 0x93, 0x4a, 0xd3, 0xc0, 0x3c, 0x30, 0x07, 0xcc, 0x82, 0x68, - 0x53, 0x32, 0xe0, 0x62, 0xf3, 0x0e, 0x0b, 0x48, 0xcc, 0x2c, 0x12, 0x12, 0xe0, 0x62, 0xce, 0x4e, - 0xad, 0x94, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x09, 0x02, 0x31, 0x85, 0x44, 0xb8, 0x58, 0xcb, 0x12, - 0x73, 0x4a, 0x53, 0x25, 0x98, 0xc0, 0x62, 0x10, 0x8e, 0x92, 0x11, 0x17, 0x87, 0xb7, 0xa7, 0x99, - 0x09, 0x31, 0x7a, 0x98, 0xa1, 0x7a, 0x92, 0xd8, 0xc0, 0x96, 0x19, 0x03, 0x02, 0x00, 0x00, 0xff, - 0xff, 0x5c, 0xb8, 0x46, 0xc5, 0xb9, 0x00, 0x00, 0x00, + 0x83, 0x88, 0x29, 0x19, 0x70, 0xb1, 0x79, 0x87, 0x05, 0x24, 0x66, 0x16, 0x09, 0x09, 0x70, 0x31, + 0x67, 0xa7, 0x56, 0x4a, 0x30, 0x2a, 0x30, 0x6a, 0xf0, 0x04, 0x81, 0x98, 0x42, 0x22, 0x5c, 0xac, + 0x65, 0x89, 0x39, 0xa5, 0xa9, 0x12, 0x4c, 0x60, 0x31, 0x08, 0x47, 0xc9, 0x88, 0x8b, 0xc3, 0xdb, + 0xd3, 0xcc, 0x84, 0x18, 0x3d, 0xcc, 0x50, 0x3d, 0x49, 0x6c, 0x60, 0x4b, 0x8d, 0x01, 0x01, 0x00, + 0x00, 0xff, 0xff, 0xd8, 0xf1, 0xc3, 0x8c, 0x8a, 0x00, 0x00, 0x00, } diff --git a/vendor/github.com/tendermint/tmlibs/common/types.proto b/vendor/github.com/tendermint/tendermint/libs/common/types.proto similarity index 56% rename from vendor/github.com/tendermint/tmlibs/common/types.proto rename to vendor/github.com/tendermint/tendermint/libs/common/types.proto index 94abcccc3..8406fcfdd 100644 --- a/vendor/github.com/tendermint/tmlibs/common/types.proto +++ b/vendor/github.com/tendermint/tendermint/libs/common/types.proto @@ -1,13 +1,6 @@ syntax = "proto3"; package common; -// For more information on gogo.proto, see: -// https://github.com/gogo/protobuf/blob/master/extensions.md -// NOTE: Try really hard not to use custom types, -// it's often complicated, broken, nor not worth it. -import "github.com/gogo/protobuf/gogoproto/gogo.proto"; - - //---------------------------------------- // Abstract types diff --git a/vendor/github.com/tendermint/tmlibs/common/word.go b/vendor/github.com/tendermint/tendermint/libs/common/word.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/common/word.go rename to vendor/github.com/tendermint/tendermint/libs/common/word.go diff --git a/vendor/github.com/tendermint/tmlibs/db/LICENSE.md b/vendor/github.com/tendermint/tendermint/libs/db/LICENSE.md similarity index 100% rename from vendor/github.com/tendermint/tmlibs/db/LICENSE.md rename to vendor/github.com/tendermint/tendermint/libs/db/LICENSE.md diff --git a/vendor/github.com/tendermint/tmlibs/db/README.md b/vendor/github.com/tendermint/tendermint/libs/db/README.md similarity index 100% rename from vendor/github.com/tendermint/tmlibs/db/README.md rename to vendor/github.com/tendermint/tendermint/libs/db/README.md diff --git a/vendor/github.com/tendermint/tmlibs/db/c_level_db.go b/vendor/github.com/tendermint/tendermint/libs/db/c_level_db.go similarity index 88% rename from vendor/github.com/tendermint/tmlibs/db/c_level_db.go rename to vendor/github.com/tendermint/tendermint/libs/db/c_level_db.go index e3e6c1d5d..307461261 100644 --- a/vendor/github.com/tendermint/tmlibs/db/c_level_db.go +++ b/vendor/github.com/tendermint/tendermint/libs/db/c_level_db.go @@ -190,7 +190,8 @@ func (db *CLevelDB) Iterator(start, end []byte) Iterator { } func (db *CLevelDB) ReverseIterator(start, end []byte) Iterator { - panic("not implemented yet") // XXX + itr := db.db.NewIterator(db.ro) + return newCLevelDBIterator(itr, start, end, true) } var _ Iterator = (*cLevelDBIterator)(nil) @@ -204,12 +205,25 @@ type cLevelDBIterator struct { func newCLevelDBIterator(source *levigo.Iterator, start, end []byte, isReverse bool) *cLevelDBIterator { if isReverse { - panic("not implemented yet") // XXX - } - if start != nil { - source.Seek(start) + if start == nil { + source.SeekToLast() + } else { + source.Seek(start) + if source.Valid() { + soakey := source.Key() // start or after key + if bytes.Compare(start, soakey) < 0 { + source.Prev() + } + } else { + source.SeekToLast() + } + } } else { - source.SeekToFirst() + if start == nil { + source.SeekToFirst() + } else { + source.Seek(start) + } } return &cLevelDBIterator{ source: source, @@ -243,9 +257,16 @@ func (itr cLevelDBIterator) Valid() bool { // If key is end or past it, invalid. var end = itr.end var key = itr.source.Key() - if end != nil && bytes.Compare(end, key) <= 0 { - itr.isInvalid = true - return false + if itr.isReverse { + if end != nil && bytes.Compare(key, end) <= 0 { + itr.isInvalid = true + return false + } + } else { + if end != nil && bytes.Compare(end, key) <= 0 { + itr.isInvalid = true + return false + } } // It's valid. @@ -267,7 +288,11 @@ func (itr cLevelDBIterator) Value() []byte { func (itr cLevelDBIterator) Next() { itr.assertNoError() itr.assertIsValid() - itr.source.Next() + if itr.isReverse { + itr.source.Prev() + } else { + itr.source.Next() + } } func (itr cLevelDBIterator) Close() { diff --git a/vendor/github.com/tendermint/tmlibs/db/db.go b/vendor/github.com/tendermint/tendermint/libs/db/db.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/db/db.go rename to vendor/github.com/tendermint/tendermint/libs/db/db.go diff --git a/vendor/github.com/tendermint/tmlibs/db/debug_db.go b/vendor/github.com/tendermint/tendermint/libs/db/debug_db.go similarity index 68% rename from vendor/github.com/tendermint/tmlibs/db/debug_db.go rename to vendor/github.com/tendermint/tendermint/libs/db/debug_db.go index 7666ed9fd..bb361a266 100644 --- a/vendor/github.com/tendermint/tmlibs/db/debug_db.go +++ b/vendor/github.com/tendermint/tendermint/libs/db/debug_db.go @@ -4,13 +4,9 @@ import ( "fmt" "sync" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) -func _fmt(f string, az ...interface{}) string { - return fmt.Sprintf(f, az...) -} - //---------------------------------------- // debugDB @@ -33,7 +29,9 @@ func (ddb debugDB) Mutex() *sync.Mutex { return nil } // Implements DB. func (ddb debugDB) Get(key []byte) (value []byte) { defer func() { - fmt.Printf("%v.Get(%v) %v\n", ddb.label, cmn.Cyan(_fmt("%X", key)), cmn.Blue(_fmt("%X", value))) + fmt.Printf("%v.Get(%v) %v\n", ddb.label, + cmn.ColoredBytes(key, cmn.Cyan, cmn.Blue), + cmn.ColoredBytes(value, cmn.Green, cmn.Blue)) }() value = ddb.db.Get(key) return @@ -42,68 +40,85 @@ func (ddb debugDB) Get(key []byte) (value []byte) { // Implements DB. func (ddb debugDB) Has(key []byte) (has bool) { defer func() { - fmt.Printf("%v.Has(%v) %v\n", ddb.label, cmn.Cyan(_fmt("%X", key)), has) + fmt.Printf("%v.Has(%v) %v\n", ddb.label, + cmn.ColoredBytes(key, cmn.Cyan, cmn.Blue), has) }() return ddb.db.Has(key) } // Implements DB. func (ddb debugDB) Set(key []byte, value []byte) { - fmt.Printf("%v.Set(%v, %v)\n", ddb.label, cmn.Cyan(_fmt("%X", key)), cmn.Yellow(_fmt("%X", value))) + fmt.Printf("%v.Set(%v, %v)\n", ddb.label, + cmn.ColoredBytes(key, cmn.Yellow, cmn.Blue), + cmn.ColoredBytes(value, cmn.Green, cmn.Blue)) ddb.db.Set(key, value) } // Implements DB. func (ddb debugDB) SetSync(key []byte, value []byte) { - fmt.Printf("%v.SetSync(%v, %v)\n", ddb.label, cmn.Cyan(_fmt("%X", key)), cmn.Yellow(_fmt("%X", value))) + fmt.Printf("%v.SetSync(%v, %v)\n", ddb.label, + cmn.ColoredBytes(key, cmn.Yellow, cmn.Blue), + cmn.ColoredBytes(value, cmn.Green, cmn.Blue)) ddb.db.SetSync(key, value) } // Implements atomicSetDeleter. func (ddb debugDB) SetNoLock(key []byte, value []byte) { - fmt.Printf("%v.SetNoLock(%v, %v)\n", ddb.label, cmn.Cyan(_fmt("%X", key)), cmn.Yellow(_fmt("%X", value))) + fmt.Printf("%v.SetNoLock(%v, %v)\n", ddb.label, + cmn.ColoredBytes(key, cmn.Yellow, cmn.Blue), + cmn.ColoredBytes(value, cmn.Green, cmn.Blue)) ddb.db.(atomicSetDeleter).SetNoLock(key, value) } // Implements atomicSetDeleter. func (ddb debugDB) SetNoLockSync(key []byte, value []byte) { - fmt.Printf("%v.SetNoLockSync(%v, %v)\n", ddb.label, cmn.Cyan(_fmt("%X", key)), cmn.Yellow(_fmt("%X", value))) + fmt.Printf("%v.SetNoLockSync(%v, %v)\n", ddb.label, + cmn.ColoredBytes(key, cmn.Yellow, cmn.Blue), + cmn.ColoredBytes(value, cmn.Green, cmn.Blue)) ddb.db.(atomicSetDeleter).SetNoLockSync(key, value) } // Implements DB. func (ddb debugDB) Delete(key []byte) { - fmt.Printf("%v.Delete(%v)\n", ddb.label, cmn.Red(_fmt("%X", key))) + fmt.Printf("%v.Delete(%v)\n", ddb.label, + cmn.ColoredBytes(key, cmn.Red, cmn.Yellow)) ddb.db.Delete(key) } // Implements DB. func (ddb debugDB) DeleteSync(key []byte) { - fmt.Printf("%v.DeleteSync(%v)\n", ddb.label, cmn.Red(_fmt("%X", key))) + fmt.Printf("%v.DeleteSync(%v)\n", ddb.label, + cmn.ColoredBytes(key, cmn.Red, cmn.Yellow)) ddb.db.DeleteSync(key) } // Implements atomicSetDeleter. func (ddb debugDB) DeleteNoLock(key []byte) { - fmt.Printf("%v.DeleteNoLock(%v)\n", ddb.label, cmn.Red(_fmt("%X", key))) + fmt.Printf("%v.DeleteNoLock(%v)\n", ddb.label, + cmn.ColoredBytes(key, cmn.Red, cmn.Yellow)) ddb.db.(atomicSetDeleter).DeleteNoLock(key) } // Implements atomicSetDeleter. func (ddb debugDB) DeleteNoLockSync(key []byte) { - fmt.Printf("%v.DeleteNoLockSync(%v)\n", ddb.label, cmn.Red(_fmt("%X", key))) + fmt.Printf("%v.DeleteNoLockSync(%v)\n", ddb.label, + cmn.ColoredBytes(key, cmn.Red, cmn.Yellow)) ddb.db.(atomicSetDeleter).DeleteNoLockSync(key) } // Implements DB. func (ddb debugDB) Iterator(start, end []byte) Iterator { - fmt.Printf("%v.Iterator(%v, %v)\n", ddb.label, cmn.Cyan(_fmt("%X", start)), cmn.Blue(_fmt("%X", end))) + fmt.Printf("%v.Iterator(%v, %v)\n", ddb.label, + cmn.ColoredBytes(start, cmn.Cyan, cmn.Blue), + cmn.ColoredBytes(end, cmn.Cyan, cmn.Blue)) return NewDebugIterator(ddb.label, ddb.db.Iterator(start, end)) } // Implements DB. func (ddb debugDB) ReverseIterator(start, end []byte) Iterator { - fmt.Printf("%v.ReverseIterator(%v, %v)\n", ddb.label, cmn.Cyan(_fmt("%X", start)), cmn.Blue(_fmt("%X", end))) + fmt.Printf("%v.ReverseIterator(%v, %v)\n", ddb.label, + cmn.ColoredBytes(start, cmn.Cyan, cmn.Blue), + cmn.ColoredBytes(end, cmn.Cyan, cmn.Blue)) return NewDebugIterator(ddb.label, ddb.db.ReverseIterator(start, end)) } @@ -173,15 +188,17 @@ func (ditr debugIterator) Next() { // Implements Iterator. func (ditr debugIterator) Key() (key []byte) { - fmt.Printf("%v.itr.Key() %v\n", ditr.label, cmn.Cyan(_fmt("%X", key))) key = ditr.itr.Key() + fmt.Printf("%v.itr.Key() %v\n", ditr.label, + cmn.ColoredBytes(key, cmn.Cyan, cmn.Blue)) return } // Implements Iterator. func (ditr debugIterator) Value() (value []byte) { - fmt.Printf("%v.itr.Value() %v\n", ditr.label, cmn.Blue(_fmt("%X", value))) value = ditr.itr.Value() + fmt.Printf("%v.itr.Value() %v\n", ditr.label, + cmn.ColoredBytes(value, cmn.Green, cmn.Blue)) return } @@ -209,13 +226,16 @@ func NewDebugBatch(label string, bch Batch) debugBatch { // Implements Batch. func (dbch debugBatch) Set(key, value []byte) { - fmt.Printf("%v.batch.Set(%v, %v)\n", dbch.label, cmn.Cyan(_fmt("%X", key)), cmn.Yellow(_fmt("%X", value))) + fmt.Printf("%v.batch.Set(%v, %v)\n", dbch.label, + cmn.ColoredBytes(key, cmn.Yellow, cmn.Blue), + cmn.ColoredBytes(value, cmn.Green, cmn.Blue)) dbch.bch.Set(key, value) } // Implements Batch. func (dbch debugBatch) Delete(key []byte) { - fmt.Printf("%v.batch.Delete(%v)\n", dbch.label, cmn.Red(_fmt("%X", key))) + fmt.Printf("%v.batch.Delete(%v)\n", dbch.label, + cmn.ColoredBytes(key, cmn.Red, cmn.Yellow)) dbch.bch.Delete(key) } diff --git a/vendor/github.com/tendermint/tmlibs/db/fsdb.go b/vendor/github.com/tendermint/tendermint/libs/db/fsdb.go similarity index 90% rename from vendor/github.com/tendermint/tmlibs/db/fsdb.go rename to vendor/github.com/tendermint/tendermint/libs/db/fsdb.go index 578c1785a..fc861decc 100644 --- a/vendor/github.com/tendermint/tmlibs/db/fsdb.go +++ b/vendor/github.com/tendermint/tendermint/libs/db/fsdb.go @@ -10,7 +10,7 @@ import ( "sync" "github.com/pkg/errors" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) const ( @@ -151,21 +151,29 @@ func (db *FSDB) Mutex() *sync.Mutex { } func (db *FSDB) Iterator(start, end []byte) Iterator { + return db.MakeIterator(start, end, false) +} + +func (db *FSDB) MakeIterator(start, end []byte, isReversed bool) Iterator { db.mtx.Lock() defer db.mtx.Unlock() // We need a copy of all of the keys. // Not the best, but probably not a bottleneck depending. - keys, err := list(db.dir, start, end) + keys, err := list(db.dir, start, end, isReversed) if err != nil { panic(errors.Wrapf(err, "Listing keys in %s", db.dir)) } - sort.Strings(keys) + if isReversed { + sort.Sort(sort.Reverse(sort.StringSlice(keys))) + } else { + sort.Strings(keys) + } return newMemDBIterator(db, keys, start, end) } func (db *FSDB) ReverseIterator(start, end []byte) Iterator { - panic("not implemented yet") // XXX + return db.MakeIterator(start, end, true) } func (db *FSDB) nameToPath(name []byte) string { @@ -213,7 +221,7 @@ func remove(path string) error { // List keys in a directory, stripping of escape sequences and dir portions. // CONTRACT: returns os errors directly without wrapping. -func list(dirPath string, start, end []byte) ([]string, error) { +func list(dirPath string, start, end []byte, isReversed bool) ([]string, error) { dir, err := os.Open(dirPath) if err != nil { return nil, err @@ -231,7 +239,7 @@ func list(dirPath string, start, end []byte) ([]string, error) { return nil, fmt.Errorf("Failed to unescape %s while listing", name) } key := unescapeKey([]byte(n)) - if IsKeyInDomain(key, start, end, false) { + if IsKeyInDomain(key, start, end, isReversed) { keys = append(keys, string(key)) } } diff --git a/vendor/github.com/tendermint/tmlibs/db/go_level_db.go b/vendor/github.com/tendermint/tendermint/libs/db/go_level_db.go similarity index 88% rename from vendor/github.com/tendermint/tmlibs/db/go_level_db.go rename to vendor/github.com/tendermint/tendermint/libs/db/go_level_db.go index 9ff162e38..349e447b2 100644 --- a/vendor/github.com/tendermint/tmlibs/db/go_level_db.go +++ b/vendor/github.com/tendermint/tendermint/libs/db/go_level_db.go @@ -10,7 +10,7 @@ import ( "github.com/syndtr/goleveldb/leveldb/iterator" "github.com/syndtr/goleveldb/leveldb/opt" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) func init() { @@ -193,7 +193,8 @@ func (db *GoLevelDB) Iterator(start, end []byte) Iterator { // Implements DB. func (db *GoLevelDB) ReverseIterator(start, end []byte) Iterator { - panic("not implemented yet") // XXX + itr := db.db.NewIterator(nil, nil) + return newGoLevelDBIterator(itr, start, end, true) } type goLevelDBIterator struct { @@ -208,9 +209,26 @@ var _ Iterator = (*goLevelDBIterator)(nil) func newGoLevelDBIterator(source iterator.Iterator, start, end []byte, isReverse bool) *goLevelDBIterator { if isReverse { - panic("not implemented yet") // XXX + if start == nil { + source.Last() + } else { + valid := source.Seek(start) + if valid { + soakey := source.Key() // start or after key + if bytes.Compare(start, soakey) < 0 { + source.Prev() + } + } else { + source.Last() + } + } + } else { + if start == nil { + source.First() + } else { + source.Seek(start) + } } - source.Seek(start) return &goLevelDBIterator{ source: source, start: start, @@ -245,9 +263,17 @@ func (itr *goLevelDBIterator) Valid() bool { // If key is end or past it, invalid. var end = itr.end var key = itr.source.Key() - if end != nil && bytes.Compare(end, key) <= 0 { - itr.isInvalid = true - return false + + if itr.isReverse { + if end != nil && bytes.Compare(key, end) <= 0 { + itr.isInvalid = true + return false + } + } else { + if end != nil && bytes.Compare(end, key) <= 0 { + itr.isInvalid = true + return false + } } // Valid @@ -276,7 +302,11 @@ func (itr *goLevelDBIterator) Value() []byte { func (itr *goLevelDBIterator) Next() { itr.assertNoError() itr.assertIsValid() - itr.source.Next() + if itr.isReverse { + itr.source.Prev() + } else { + itr.source.Next() + } } // Implements Iterator. diff --git a/vendor/github.com/tendermint/tmlibs/db/mem_batch.go b/vendor/github.com/tendermint/tendermint/libs/db/mem_batch.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/db/mem_batch.go rename to vendor/github.com/tendermint/tendermint/libs/db/mem_batch.go diff --git a/vendor/github.com/tendermint/tmlibs/db/mem_db.go b/vendor/github.com/tendermint/tendermint/libs/db/mem_db.go similarity index 98% rename from vendor/github.com/tendermint/tmlibs/db/mem_db.go rename to vendor/github.com/tendermint/tendermint/libs/db/mem_db.go index 1521f87ac..580123017 100644 --- a/vendor/github.com/tendermint/tmlibs/db/mem_db.go +++ b/vendor/github.com/tendermint/tendermint/libs/db/mem_db.go @@ -114,7 +114,7 @@ func (db *MemDB) Close() { // database, we don't have a destination // to flush contents to nor do we want // any data loss on invoking Close() - // See the discussion in https://github.com/tendermint/tmlibs/pull/56 + // See the discussion in https://github.com/tendermint/tendermint/libs/pull/56 } // Implements DB. diff --git a/vendor/github.com/tendermint/tmlibs/db/prefix_db.go b/vendor/github.com/tendermint/tendermint/libs/db/prefix_db.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/db/prefix_db.go rename to vendor/github.com/tendermint/tendermint/libs/db/prefix_db.go diff --git a/vendor/github.com/tendermint/tmlibs/db/types.go b/vendor/github.com/tendermint/tendermint/libs/db/types.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/db/types.go rename to vendor/github.com/tendermint/tendermint/libs/db/types.go diff --git a/vendor/github.com/tendermint/tmlibs/db/util.go b/vendor/github.com/tendermint/tendermint/libs/db/util.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/db/util.go rename to vendor/github.com/tendermint/tendermint/libs/db/util.go diff --git a/vendor/github.com/tendermint/tendermint/libs/events/Makefile b/vendor/github.com/tendermint/tendermint/libs/events/Makefile new file mode 100644 index 000000000..696aafff1 --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/libs/events/Makefile @@ -0,0 +1,9 @@ +.PHONY: docs +REPO:=github.com/tendermint/tendermint/libs/events + +docs: + @go get github.com/davecheney/godoc2md + godoc2md $(REPO) > README.md + +test: + go test -v ./... diff --git a/vendor/github.com/tendermint/tendermint/libs/events/README.md b/vendor/github.com/tendermint/tendermint/libs/events/README.md new file mode 100644 index 000000000..14aa498ff --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/libs/events/README.md @@ -0,0 +1,175 @@ + + +# events +`import "github.com/tendermint/tendermint/libs/events"` + +* [Overview](#pkg-overview) +* [Index](#pkg-index) + +## Overview +Pub-Sub in go with event caching + + + + +## Index +* [type EventCache](#EventCache) + * [func NewEventCache(evsw Fireable) *EventCache](#NewEventCache) + * [func (evc *EventCache) FireEvent(event string, data EventData)](#EventCache.FireEvent) + * [func (evc *EventCache) Flush()](#EventCache.Flush) +* [type EventCallback](#EventCallback) +* [type EventData](#EventData) +* [type EventSwitch](#EventSwitch) + * [func NewEventSwitch() EventSwitch](#NewEventSwitch) +* [type Eventable](#Eventable) +* [type Fireable](#Fireable) + + +#### Package files +[event_cache.go](/src/github.com/tendermint/tendermint/libs/events/event_cache.go) [events.go](/src/github.com/tendermint/tendermint/libs/events/events.go) + + + + + + +## type [EventCache](/src/target/event_cache.go?s=116:179#L5) +``` go +type EventCache struct { + // contains filtered or unexported fields +} +``` +An EventCache buffers events for a Fireable +All events are cached. Filtering happens on Flush + + + + + + + +### func [NewEventCache](/src/target/event_cache.go?s=239:284#L11) +``` go +func NewEventCache(evsw Fireable) *EventCache +``` +Create a new EventCache with an EventSwitch as backend + + + + + +### func (\*EventCache) [FireEvent](/src/target/event_cache.go?s=449:511#L24) +``` go +func (evc *EventCache) FireEvent(event string, data EventData) +``` +Cache an event to be fired upon finality. + + + + +### func (\*EventCache) [Flush](/src/target/event_cache.go?s=735:765#L31) +``` go +func (evc *EventCache) Flush() +``` +Fire events by running evsw.FireEvent on all cached events. Blocks. +Clears cached events + + + + +## type [EventCallback](/src/target/events.go?s=4201:4240#L185) +``` go +type EventCallback func(data EventData) +``` + + + + + + + + + +## type [EventData](/src/target/events.go?s=243:294#L14) +``` go +type EventData interface { +} +``` +Generic event data can be typed and registered with tendermint/go-amino +via concrete implementation of this interface + + + + + + + + + + +## type [EventSwitch](/src/target/events.go?s=560:771#L29) +``` go +type EventSwitch interface { + cmn.Service + Fireable + + AddListenerForEvent(listenerID, event string, cb EventCallback) + RemoveListenerForEvent(event string, listenerID string) + RemoveListener(listenerID string) +} +``` + + + + + + +### func [NewEventSwitch](/src/target/events.go?s=917:950#L46) +``` go +func NewEventSwitch() EventSwitch +``` + + + + +## type [Eventable](/src/target/events.go?s=378:440#L20) +``` go +type Eventable interface { + SetEventSwitch(evsw EventSwitch) +} +``` +reactors and other modules should export +this interface to become eventable + + + + + + + + + + +## type [Fireable](/src/target/events.go?s=490:558#L25) +``` go +type Fireable interface { + FireEvent(event string, data EventData) +} +``` +an event switch or cache implements fireable + + + + + + + + + + + + + + +- - - +Generated by [godoc2md](http://godoc.org/github.com/davecheney/godoc2md) diff --git a/vendor/github.com/tendermint/tendermint/libs/events/events.go b/vendor/github.com/tendermint/tendermint/libs/events/events.go index 075f9b42b..9c7f0fd05 100644 --- a/vendor/github.com/tendermint/tendermint/libs/events/events.go +++ b/vendor/github.com/tendermint/tendermint/libs/events/events.go @@ -6,7 +6,7 @@ package events import ( "sync" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) // Generic event data can be typed and registered with tendermint/go-amino diff --git a/vendor/github.com/tendermint/tmlibs/flowrate/README.md b/vendor/github.com/tendermint/tendermint/libs/flowrate/README.md similarity index 100% rename from vendor/github.com/tendermint/tmlibs/flowrate/README.md rename to vendor/github.com/tendermint/tendermint/libs/flowrate/README.md diff --git a/vendor/github.com/tendermint/tmlibs/flowrate/flowrate.go b/vendor/github.com/tendermint/tendermint/libs/flowrate/flowrate.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/flowrate/flowrate.go rename to vendor/github.com/tendermint/tendermint/libs/flowrate/flowrate.go diff --git a/vendor/github.com/tendermint/tmlibs/flowrate/io.go b/vendor/github.com/tendermint/tendermint/libs/flowrate/io.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/flowrate/io.go rename to vendor/github.com/tendermint/tendermint/libs/flowrate/io.go diff --git a/vendor/github.com/tendermint/tmlibs/flowrate/util.go b/vendor/github.com/tendermint/tendermint/libs/flowrate/util.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/flowrate/util.go rename to vendor/github.com/tendermint/tendermint/libs/flowrate/util.go diff --git a/vendor/github.com/tendermint/tmlibs/log/filter.go b/vendor/github.com/tendermint/tendermint/libs/log/filter.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/log/filter.go rename to vendor/github.com/tendermint/tendermint/libs/log/filter.go diff --git a/vendor/github.com/tendermint/tmlibs/log/logger.go b/vendor/github.com/tendermint/tendermint/libs/log/logger.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/log/logger.go rename to vendor/github.com/tendermint/tendermint/libs/log/logger.go diff --git a/vendor/github.com/tendermint/tmlibs/log/nop_logger.go b/vendor/github.com/tendermint/tendermint/libs/log/nop_logger.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/log/nop_logger.go rename to vendor/github.com/tendermint/tendermint/libs/log/nop_logger.go diff --git a/vendor/github.com/tendermint/tmlibs/log/testing_logger.go b/vendor/github.com/tendermint/tendermint/libs/log/testing_logger.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/log/testing_logger.go rename to vendor/github.com/tendermint/tendermint/libs/log/testing_logger.go diff --git a/vendor/github.com/tendermint/tmlibs/log/tm_json_logger.go b/vendor/github.com/tendermint/tendermint/libs/log/tm_json_logger.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/log/tm_json_logger.go rename to vendor/github.com/tendermint/tendermint/libs/log/tm_json_logger.go diff --git a/vendor/github.com/tendermint/tmlibs/log/tm_logger.go b/vendor/github.com/tendermint/tendermint/libs/log/tm_logger.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/log/tm_logger.go rename to vendor/github.com/tendermint/tendermint/libs/log/tm_logger.go diff --git a/vendor/github.com/tendermint/tmlibs/log/tmfmt_logger.go b/vendor/github.com/tendermint/tendermint/libs/log/tmfmt_logger.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/log/tmfmt_logger.go rename to vendor/github.com/tendermint/tendermint/libs/log/tmfmt_logger.go diff --git a/vendor/github.com/tendermint/tmlibs/log/tracing_logger.go b/vendor/github.com/tendermint/tendermint/libs/log/tracing_logger.go similarity index 100% rename from vendor/github.com/tendermint/tmlibs/log/tracing_logger.go rename to vendor/github.com/tendermint/tendermint/libs/log/tracing_logger.go diff --git a/vendor/github.com/tendermint/tendermint/libs/pubsub/pubsub.go b/vendor/github.com/tendermint/tendermint/libs/pubsub/pubsub.go index 776e0653b..4c0d97e2f 100644 --- a/vendor/github.com/tendermint/tendermint/libs/pubsub/pubsub.go +++ b/vendor/github.com/tendermint/tendermint/libs/pubsub/pubsub.go @@ -16,7 +16,7 @@ import ( "errors" "sync" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) type operation int @@ -163,6 +163,8 @@ func (s *Server) Subscribe(ctx context.Context, clientID string, query Query, ou return nil case <-ctx.Done(): return ctx.Err() + case <-s.Quit(): + return nil } } @@ -190,6 +192,8 @@ func (s *Server) Unsubscribe(ctx context.Context, clientID string, query Query) return nil case <-ctx.Done(): return ctx.Err() + case <-s.Quit(): + return nil } } @@ -211,6 +215,8 @@ func (s *Server) UnsubscribeAll(ctx context.Context, clientID string) error { return nil case <-ctx.Done(): return ctx.Err() + case <-s.Quit(): + return nil } } @@ -229,6 +235,8 @@ func (s *Server) PublishWithTags(ctx context.Context, msg interface{}, tags TagM return nil case <-ctx.Done(): return ctx.Err() + case <-s.Quit(): + return nil } } diff --git a/vendor/github.com/tendermint/tendermint/libs/pubsub/query/Makefile b/vendor/github.com/tendermint/tendermint/libs/pubsub/query/Makefile new file mode 100644 index 000000000..aef42b2df --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/libs/pubsub/query/Makefile @@ -0,0 +1,11 @@ +gen_query_parser: + go get -u -v github.com/pointlander/peg + peg -inline -switch query.peg + +fuzzy_test: + go get -u -v github.com/dvyukov/go-fuzz/go-fuzz + go get -u -v github.com/dvyukov/go-fuzz/go-fuzz-build + go-fuzz-build github.com/tendermint/tendermint/libs/pubsub/query/fuzz_test + go-fuzz -bin=./fuzz_test-fuzz.zip -workdir=./fuzz_test/output + +.PHONY: gen_query_parser fuzzy_test diff --git a/vendor/github.com/tendermint/tendermint/libs/pubsub/query/query.peg b/vendor/github.com/tendermint/tendermint/libs/pubsub/query/query.peg new file mode 100644 index 000000000..739892e4f --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/libs/pubsub/query/query.peg @@ -0,0 +1,33 @@ +package query + +type QueryParser Peg { +} + +e <- '\"' condition ( ' '+ and ' '+ condition )* '\"' !. + +condition <- tag ' '* (le ' '* (number / time / date) + / ge ' '* (number / time / date) + / l ' '* (number / time / date) + / g ' '* (number / time / date) + / equal ' '* (number / time / date / value) + / contains ' '* value + ) + +tag <- < (![ \t\n\r\\()"'=><] .)+ > +value <- < '\'' (!["'] .)* '\''> +number <- < ('0' + / [1-9] digit* ('.' digit*)?) > +digit <- [0-9] +time <- "TIME " < year '-' month '-' day 'T' digit digit ':' digit digit ':' digit digit (('-' / '+') digit digit ':' digit digit / 'Z') > +date <- "DATE " < year '-' month '-' day > +year <- ('1' / '2') digit digit digit +month <- ('0' / '1') digit +day <- ('0' / '1' / '2' / '3') digit +and <- "AND" + +equal <- "=" +contains <- "CONTAINS" +le <- "<=" +ge <- ">=" +l <- "<" +g <- ">" diff --git a/vendor/github.com/tendermint/tendermint/libs/pubsub/query/query.peg.go b/vendor/github.com/tendermint/tendermint/libs/pubsub/query/query.peg.go index c86e4a47f..c1cc60aa9 100644 --- a/vendor/github.com/tendermint/tendermint/libs/pubsub/query/query.peg.go +++ b/vendor/github.com/tendermint/tendermint/libs/pubsub/query/query.peg.go @@ -1,6 +1,8 @@ // nolint package query +//go:generate peg -inline -switch query.peg + import ( "fmt" "math" diff --git a/vendor/github.com/tendermint/tendermint/mempool/mempool.go b/vendor/github.com/tendermint/tendermint/mempool/mempool.go index 935dfaac7..06852c9af 100644 --- a/vendor/github.com/tendermint/tendermint/mempool/mempool.go +++ b/vendor/github.com/tendermint/tendermint/mempool/mempool.go @@ -10,11 +10,11 @@ import ( "github.com/pkg/errors" - abci "github.com/tendermint/abci/types" - auto "github.com/tendermint/tmlibs/autofile" - "github.com/tendermint/tmlibs/clist" - cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/log" + abci "github.com/tendermint/tendermint/abci/types" + auto "github.com/tendermint/tendermint/libs/autofile" + "github.com/tendermint/tendermint/libs/clist" + cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/log" cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/proxy" @@ -57,6 +57,11 @@ var ( ErrMempoolIsFull = errors.New("Mempool is full") ) +// TxID is the hex encoded hash of the bytes as a types.Tx. +func TxID(tx []byte) string { + return fmt.Sprintf("%X", types.Tx(tx).Hash()) +} + // Mempool is an ordered in-memory pool for transactions before they are proposed in a consensus // round. Transaction validity is checked using the CheckTx abci message before the transaction is // added to the pool. The Mempool uses a concurrent list structure for storing transactions that @@ -83,10 +88,20 @@ type Mempool struct { wal *auto.AutoFile logger log.Logger + + metrics *Metrics } +// MempoolOption sets an optional parameter on the Mempool. +type MempoolOption func(*Mempool) + // NewMempool returns a new Mempool with the given configuration and connection to an application. -func NewMempool(config *cfg.MempoolConfig, proxyAppConn proxy.AppConnMempool, height int64) *Mempool { +func NewMempool( + config *cfg.MempoolConfig, + proxyAppConn proxy.AppConnMempool, + height int64, + options ...MempoolOption, +) *Mempool { mempool := &Mempool{ config: config, proxyAppConn: proxyAppConn, @@ -97,6 +112,7 @@ func NewMempool(config *cfg.MempoolConfig, proxyAppConn proxy.AppConnMempool, he recheckCursor: nil, recheckEnd: nil, logger: log.NewNopLogger(), + metrics: NopMetrics(), } if config.CacheSize > 0 { mempool.cache = newMapTxCache(config.CacheSize) @@ -104,6 +120,9 @@ func NewMempool(config *cfg.MempoolConfig, proxyAppConn proxy.AppConnMempool, he mempool.cache = nopTxCache{} } proxyAppConn.SetResponseCallback(mempool.resCb) + for _, option := range options { + option(mempool) + } return mempool } @@ -119,6 +138,11 @@ func (mem *Mempool) SetLogger(l log.Logger) { mem.logger = l } +// WithMetrics sets the metrics. +func WithMetrics(metrics *Metrics) MempoolOption { + return func(mem *Mempool) { mem.metrics = metrics } +} + // CloseWAL closes and discards the underlying WAL file. // Any further writes will not be relayed to disk. func (mem *Mempool) CloseWAL() bool { @@ -254,6 +278,7 @@ func (mem *Mempool) resCb(req *abci.Request, res *abci.Response) { } else { mem.resCbRecheck(req, res) } + mem.metrics.Size.Set(float64(mem.Size())) } func (mem *Mempool) resCbNormal(req *abci.Request, res *abci.Response) { @@ -268,11 +293,11 @@ func (mem *Mempool) resCbNormal(req *abci.Request, res *abci.Response) { tx: tx, } mem.txs.PushBack(memTx) - mem.logger.Info("Added good transaction", "tx", fmt.Sprintf("%X", types.Tx(tx).Hash()), "res", r) + mem.logger.Info("Added good transaction", "tx", TxID(tx), "res", r, "total", mem.Size()) mem.notifyTxsAvailable() } else { // ignore bad transaction - mem.logger.Info("Rejected bad transaction", "tx", fmt.Sprintf("%X", types.Tx(tx).Hash()), "res", r) + mem.logger.Info("Rejected bad transaction", "tx", TxID(tx), "res", r) // remove from cache (it might be good later) mem.cache.Remove(tx) @@ -397,6 +422,7 @@ func (mem *Mempool) Update(height int64, txs types.Txs) error { // mem.recheckCursor re-scans mem.txs and possibly removes some txs. // Before mem.Reap(), we should wait for mem.recheckCursor to be nil. } + mem.metrics.Size.Set(float64(mem.Size())) return nil } diff --git a/vendor/github.com/tendermint/tendermint/mempool/metrics.go b/vendor/github.com/tendermint/tendermint/mempool/metrics.go new file mode 100644 index 000000000..f381678cb --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/mempool/metrics.go @@ -0,0 +1,34 @@ +package mempool + +import ( + "github.com/go-kit/kit/metrics" + "github.com/go-kit/kit/metrics/discard" + + prometheus "github.com/go-kit/kit/metrics/prometheus" + stdprometheus "github.com/prometheus/client_golang/prometheus" +) + +// Metrics contains metrics exposed by this package. +// see MetricsProvider for descriptions. +type Metrics struct { + // Size of the mempool. + Size metrics.Gauge +} + +// PrometheusMetrics returns Metrics build using Prometheus client library. +func PrometheusMetrics() *Metrics { + return &Metrics{ + Size: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "mempool", + Name: "size", + Help: "Size of the mempool (number of uncommitted transactions).", + }, []string{}), + } +} + +// NopMetrics returns no-op Metrics. +func NopMetrics() *Metrics { + return &Metrics{ + Size: discard.NewGauge(), + } +} diff --git a/vendor/github.com/tendermint/tendermint/mempool/reactor.go b/vendor/github.com/tendermint/tendermint/mempool/reactor.go index 5d1f4e793..96988be78 100644 --- a/vendor/github.com/tendermint/tendermint/mempool/reactor.go +++ b/vendor/github.com/tendermint/tendermint/mempool/reactor.go @@ -5,10 +5,10 @@ import ( "reflect" "time" - abci "github.com/tendermint/abci/types" amino "github.com/tendermint/go-amino" - "github.com/tendermint/tmlibs/clist" - "github.com/tendermint/tmlibs/log" + abci "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/clist" + "github.com/tendermint/tendermint/libs/log" cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/p2p" @@ -78,7 +78,7 @@ func (memR *MempoolReactor) RemovePeer(peer p2p.Peer, reason interface{}) { // Receive implements Reactor. // It adds any received transactions to the mempool. func (memR *MempoolReactor) Receive(chID byte, src p2p.Peer, msgBytes []byte) { - msg, err := DecodeMessage(msgBytes) + msg, err := decodeMsg(msgBytes) if err != nil { memR.Logger.Error("Error decoding message", "src", src, "chId", chID, "msg", msg, "err", err, "bytes", msgBytes) memR.Switch.StopPeerForError(src, err) @@ -90,7 +90,7 @@ func (memR *MempoolReactor) Receive(chID byte, src p2p.Peer, msgBytes []byte) { case *TxMessage: err := memR.Mempool.CheckTx(msg.Tx, nil) if err != nil { - memR.Logger.Info("Could not check tx", "tx", msg.Tx, "err", err) + memR.Logger.Info("Could not check tx", "tx", TxID(msg.Tx), "err", err) } // broadcasting happens from go routines per peer default: @@ -174,11 +174,9 @@ func RegisterMempoolMessages(cdc *amino.Codec) { cdc.RegisterConcrete(&TxMessage{}, "tendermint/mempool/TxMessage", nil) } -// DecodeMessage decodes a byte-array into a MempoolMessage. -func DecodeMessage(bz []byte) (msg MempoolMessage, err error) { +func decodeMsg(bz []byte) (msg MempoolMessage, err error) { if len(bz) > maxMsgSize { - return msg, fmt.Errorf("Msg exceeds max size (%d > %d)", - len(bz), maxMsgSize) + return msg, fmt.Errorf("Msg exceeds max size (%d > %d)", len(bz), maxMsgSize) } err = cdc.UnmarshalBinaryBare(bz, &msg) return diff --git a/vendor/github.com/tendermint/tendermint/node/id.go b/vendor/github.com/tendermint/tendermint/node/id.go index fa391f946..5100597c6 100644 --- a/vendor/github.com/tendermint/tendermint/node/id.go +++ b/vendor/github.com/tendermint/tendermint/node/id.go @@ -3,7 +3,7 @@ package node import ( "time" - "github.com/tendermint/go-crypto" + "github.com/tendermint/tendermint/crypto" ) type NodeID struct { diff --git a/vendor/github.com/tendermint/tendermint/node/node.go b/vendor/github.com/tendermint/tendermint/node/node.go index efeb17ee0..faf33d88a 100644 --- a/vendor/github.com/tendermint/tendermint/node/node.go +++ b/vendor/github.com/tendermint/tendermint/node/node.go @@ -2,21 +2,25 @@ package node import ( "bytes" + "context" "errors" "fmt" "net" "net/http" - abci "github.com/tendermint/abci/types" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + amino "github.com/tendermint/go-amino" - crypto "github.com/tendermint/go-crypto" - cmn "github.com/tendermint/tmlibs/common" - dbm "github.com/tendermint/tmlibs/db" - "github.com/tendermint/tmlibs/log" + abci "github.com/tendermint/tendermint/abci/types" + cmn "github.com/tendermint/tendermint/libs/common" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" bc "github.com/tendermint/tendermint/blockchain" cfg "github.com/tendermint/tendermint/config" cs "github.com/tendermint/tendermint/consensus" + "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/evidence" mempl "github.com/tendermint/tendermint/mempool" "github.com/tendermint/tendermint/p2p" @@ -81,10 +85,25 @@ func DefaultNewNode(config *cfg.Config, logger log.Logger) (*Node, error) { proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir()), DefaultGenesisDocProviderFunc(config), DefaultDBProvider, + DefaultMetricsProvider, logger, ) } +// MetricsProvider returns a consensus, p2p and mempool Metrics. +type MetricsProvider func() (*cs.Metrics, *p2p.Metrics, *mempl.Metrics) + +// DefaultMetricsProvider returns consensus, p2p and mempool Metrics build +// using Prometheus client library. +func DefaultMetricsProvider() (*cs.Metrics, *p2p.Metrics, *mempl.Metrics) { + return cs.PrometheusMetrics(), p2p.PrometheusMetrics(), mempl.PrometheusMetrics() +} + +// NopMetricsProvider returns consensus, p2p and mempool Metrics as no-op. +func NopMetricsProvider() (*cs.Metrics, *p2p.Metrics, *mempl.Metrics) { + return cs.NopMetrics(), p2p.NopMetrics(), mempl.NopMetrics() +} + //------------------------------------------------------------------------------ // Node is the highest level interface to a full Tendermint node. @@ -114,6 +133,7 @@ type Node struct { rpcListeners []net.Listener // rpc servers txIndexer txindex.TxIndexer indexerService *txindex.IndexerService + prometheusSrv *http.Server } // NewNode returns a new, ready to go, Tendermint Node. @@ -122,6 +142,7 @@ func NewNode(config *cfg.Config, clientCreator proxy.ClientCreator, genesisDocProvider GenesisDocProvider, dbProvider DBProvider, + metricsProvider MetricsProvider, logger log.Logger) (*Node, error) { // Get BlockStore @@ -208,11 +229,28 @@ func NewNode(config *cfg.Config, consensusLogger.Info("This node is not a validator", "addr", privValidator.GetAddress(), "pubKey", privValidator.GetPubKey()) } + // metrics + var ( + csMetrics *cs.Metrics + p2pMetrics *p2p.Metrics + memplMetrics *mempl.Metrics + ) + if config.Instrumentation.Prometheus { + csMetrics, p2pMetrics, memplMetrics = metricsProvider() + } else { + csMetrics, p2pMetrics, memplMetrics = NopMetricsProvider() + } + // Make MempoolReactor mempoolLogger := logger.With("module", "mempool") - mempool := mempl.NewMempool(config.Mempool, proxyApp.Mempool(), state.LastBlockHeight) - mempool.InitWAL() // no need to have the mempool wal during tests + mempool := mempl.NewMempool( + config.Mempool, + proxyApp.Mempool(), + state.LastBlockHeight, + mempl.WithMetrics(memplMetrics), + ) mempool.SetLogger(mempoolLogger) + mempool.InitWAL() // no need to have the mempool wal during tests mempoolReactor := mempl.NewMempoolReactor(config.Mempool, mempool) mempoolReactor.SetLogger(mempoolLogger) @@ -241,8 +279,15 @@ func NewNode(config *cfg.Config, bcReactor.SetLogger(logger.With("module", "blockchain")) // Make ConsensusReactor - consensusState := cs.NewConsensusState(config.Consensus, state.Copy(), - blockExec, blockStore, mempool, evidencePool) + consensusState := cs.NewConsensusState( + config.Consensus, + state.Copy(), + blockExec, + blockStore, + mempool, + evidencePool, + cs.WithMetrics(csMetrics), + ) consensusState.SetLogger(consensusLogger) if privValidator != nil { consensusState.SetPrivValidator(privValidator) @@ -252,7 +297,7 @@ func NewNode(config *cfg.Config, p2pLogger := logger.With("module", "p2p") - sw := p2p.NewSwitch(config.P2P) + sw := p2p.NewSwitch(config.P2P, p2p.WithMetrics(p2pMetrics)) sw.SetLogger(p2pLogger) sw.AddReactor("MEMPOOL", mempoolReactor) sw.AddReactor("BLOCKCHAIN", bcReactor) @@ -382,8 +427,11 @@ func (n *Node) OnStart() error { } // Create & add listener - protocol, address := cmn.ProtocolAndAddress(n.config.P2P.ListenAddress) - l := p2p.NewDefaultListener(protocol, address, n.config.P2P.SkipUPNP, n.Logger.With("module", "p2p")) + l := p2p.NewDefaultListener( + n.config.P2P.ListenAddress, + n.config.P2P.ExternalAddress, + n.config.P2P.UPNP, + n.Logger.With("module", "p2p")) n.sw.AddListener(l) // Generate node PrivKey @@ -411,6 +459,10 @@ func (n *Node) OnStart() error { n.rpcListeners = listeners } + if n.config.Instrumentation.Prometheus { + n.prometheusSrv = n.startPrometheusServer(n.config.Instrumentation.PrometheusListenAddr) + } + // Start the switch (the P2P server). err = n.sw.Start() if err != nil { @@ -434,9 +486,16 @@ func (n *Node) OnStop() { n.BaseService.OnStop() n.Logger.Info("Stopping Node") + + // first stop the non-reactor services + n.eventBus.Stop() + n.indexerService.Stop() + + // now stop the reactors // TODO: gracefully disconnect from peers. n.sw.Stop() + // finally stop the listeners / external services for _, l := range n.rpcListeners { n.Logger.Info("Closing rpc listener", "listener", l) if err := l.Close(); err != nil { @@ -444,14 +503,18 @@ func (n *Node) OnStop() { } } - n.eventBus.Stop() - n.indexerService.Stop() - if pvsc, ok := n.privValidator.(*privval.SocketPV); ok { if err := pvsc.Stop(); err != nil { n.Logger.Error("Error stopping priv validator socket client", "err", err) } } + + if n.prometheusSrv != nil { + if err := n.prometheusSrv.Shutdown(context.Background()); err != nil { + // Error from closing listeners, or context timeout: + n.Logger.Error("Prometheus HTTP server Shutdown", "err", err) + } + } } // RunForever waits for an interrupt signal and stops the node. @@ -507,7 +570,12 @@ func (n *Node) startRPC() ([]net.Listener, error) { wm.SetLogger(rpcLogger.With("protocol", "websocket")) mux.HandleFunc("/websocket", wm.WebsocketHandler) rpcserver.RegisterRPCFuncs(mux, rpccore.Routes, coreCodec, rpcLogger) - listener, err := rpcserver.StartHTTPServer(listenAddr, mux, rpcLogger) + listener, err := rpcserver.StartHTTPServer( + listenAddr, + mux, + rpcLogger, + rpcserver.Config{MaxOpenConnections: n.config.RPC.MaxOpenConnections}, + ) if err != nil { return nil, err } @@ -517,7 +585,12 @@ func (n *Node) startRPC() ([]net.Listener, error) { // we expose a simplified api over grpc for convenience to app devs grpcListenAddr := n.config.RPC.GRPCListenAddress if grpcListenAddr != "" { - listener, err := grpccore.StartGRPCServer(grpcListenAddr) + listener, err := grpccore.StartGRPCServer( + grpcListenAddr, + grpccore.Config{ + MaxOpenConnections: n.config.RPC.GRPCMaxOpenConnections, + }, + ) if err != nil { return nil, err } @@ -527,6 +600,27 @@ func (n *Node) startRPC() ([]net.Listener, error) { return listeners, nil } +// startPrometheusServer starts a Prometheus HTTP server, listening for metrics +// collectors on addr. +func (n *Node) startPrometheusServer(addr string) *http.Server { + srv := &http.Server{ + Addr: addr, + Handler: promhttp.InstrumentMetricHandler( + prometheus.DefaultRegisterer, promhttp.HandlerFor( + prometheus.DefaultGatherer, + promhttp.HandlerOpts{MaxRequestsInFlight: n.config.Instrumentation.MaxOpenConnections}, + ), + ), + } + go func() { + if err := srv.ListenAndServe(); err != http.ErrServerClosed { + // Error starting or closing listener: + n.Logger.Error("Prometheus HTTP server ListenAndServe", "err", err) + } + }() + return srv +} + // Switch returns the Node's Switch. func (n *Node) Switch() *p2p.Switch { return n.sw @@ -615,7 +709,7 @@ func (n *Node) makeNodeInfo(nodeID p2p.ID) p2p.NodeInfo { } p2pListener := n.sw.Listeners()[0] - p2pHost := p2pListener.ExternalAddress().IP.String() + p2pHost := p2pListener.ExternalAddressHost() p2pPort := p2pListener.ExternalAddress().Port nodeInfo.ListenAddr = cmn.Fmt("%v:%v", p2pHost, p2pPort) diff --git a/vendor/github.com/tendermint/tendermint/node/wire.go b/vendor/github.com/tendermint/tendermint/node/wire.go index a0d7677df..8b3ae8950 100644 --- a/vendor/github.com/tendermint/tendermint/node/wire.go +++ b/vendor/github.com/tendermint/tendermint/node/wire.go @@ -2,7 +2,7 @@ package node import ( amino "github.com/tendermint/go-amino" - crypto "github.com/tendermint/go-crypto" + crypto "github.com/tendermint/tendermint/crypto" ) var cdc = amino.NewCodec() diff --git a/vendor/github.com/tendermint/tendermint/p2p/README.md b/vendor/github.com/tendermint/tendermint/p2p/README.md new file mode 100644 index 000000000..819a5056b --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/p2p/README.md @@ -0,0 +1,11 @@ +# p2p + +The p2p package provides an abstraction around peer-to-peer communication. + +Docs: + +- [Connection](https://github.com/tendermint/tendermint/blob/master/docs/spec/docs/spec/p2p/connection.md) for details on how connections and multiplexing work +- [Peer](https://github.com/tendermint/tendermint/blob/master/docs/spec/docs/spec/p2p/peer.md) for details on peer ID, handshakes, and peer exchange +- [Node](https://github.com/tendermint/tendermint/blob/master/docs/spec/docs/spec/p2p/node.md) for details about different types of nodes and how they should work +- [Pex](https://github.com/tendermint/tendermint/blob/master/docs/spec/docs/spec/reactors/pex/pex.md) for details on peer discovery and exchange +- [Config](https://github.com/tendermint/tendermint/blob/master/docs/spec/docs/spec/p2p/config.md) for details on some config option diff --git a/vendor/github.com/tendermint/tendermint/p2p/base_reactor.go b/vendor/github.com/tendermint/tendermint/p2p/base_reactor.go index 83c8efa4b..da1296da0 100644 --- a/vendor/github.com/tendermint/tendermint/p2p/base_reactor.go +++ b/vendor/github.com/tendermint/tendermint/p2p/base_reactor.go @@ -2,7 +2,7 @@ package p2p import ( "github.com/tendermint/tendermint/p2p/conn" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) type Reactor interface { diff --git a/vendor/github.com/tendermint/tendermint/p2p/conn/connection.go b/vendor/github.com/tendermint/tendermint/p2p/conn/connection.go index 5c7f19cf7..9672e0117 100644 --- a/vendor/github.com/tendermint/tendermint/p2p/conn/connection.go +++ b/vendor/github.com/tendermint/tendermint/p2p/conn/connection.go @@ -12,14 +12,13 @@ import ( "time" amino "github.com/tendermint/go-amino" - cmn "github.com/tendermint/tmlibs/common" - flow "github.com/tendermint/tmlibs/flowrate" - "github.com/tendermint/tmlibs/log" + cmn "github.com/tendermint/tendermint/libs/common" + flow "github.com/tendermint/tendermint/libs/flowrate" + "github.com/tendermint/tendermint/libs/log" ) const ( - maxPacketMsgPayloadSizeDefault = 1024 // NOTE: Must be below 16,384 bytes for 14 below. - maxPacketMsgOverheadSize = 14 // NOTE: See connection_test for derivation. + defaultMaxPacketMsgPayloadSize = 1024 numBatchPacketMsgs = 10 minReadBufferSize = 1024 @@ -96,6 +95,8 @@ type MConnection struct { chStatsTimer *cmn.RepeatTimer // update channel stats periodically created time.Time // time of creation + + _maxPacketMsgSize int } // MConnConfig is a MConnection configuration. @@ -116,16 +117,12 @@ type MConnConfig struct { PongTimeout time.Duration `mapstructure:"pong_timeout"` } -func (cfg *MConnConfig) maxPacketMsgTotalSize() int { - return cfg.MaxPacketMsgPayloadSize + maxPacketMsgOverheadSize -} - // DefaultMConnConfig returns the default config. func DefaultMConnConfig() MConnConfig { return MConnConfig{ SendRate: defaultSendRate, RecvRate: defaultRecvRate, - MaxPacketMsgPayloadSize: maxPacketMsgPayloadSizeDefault, + MaxPacketMsgPayloadSize: defaultMaxPacketMsgPayloadSize, FlushThrottle: defaultFlushThrottle, PingInterval: defaultPingInterval, PongTimeout: defaultPongTimeout, @@ -175,6 +172,9 @@ func NewMConnectionWithConfig(conn net.Conn, chDescs []*ChannelDescriptor, onRec mconn.BaseService = *cmn.NewBaseService(nil, "MConnection", mconn) + // maxPacketMsgSize() is a bit heavy, so call just once + mconn._maxPacketMsgSize = mconn.maxPacketMsgSize() + return mconn } @@ -399,7 +399,7 @@ func (c *MConnection) sendSomePacketMsgs() bool { // Block until .sendMonitor says we can write. // Once we're ready we send more than we asked for, // but amortized it should even out. - c.sendMonitor.Limit(c.config.maxPacketMsgTotalSize(), atomic.LoadInt64(&c.config.SendRate), true) + c.sendMonitor.Limit(c._maxPacketMsgSize, atomic.LoadInt64(&c.config.SendRate), true) // Now send some PacketMsgs. for i := 0; i < numBatchPacketMsgs; i++ { @@ -457,7 +457,7 @@ func (c *MConnection) recvRoutine() { FOR_LOOP: for { // Block until .recvMonitor says we can read. - c.recvMonitor.Limit(c.config.maxPacketMsgTotalSize(), atomic.LoadInt64(&c.config.RecvRate), true) + c.recvMonitor.Limit(c._maxPacketMsgSize, atomic.LoadInt64(&c.config.RecvRate), true) // Peek into bufConnReader for debugging /* @@ -477,7 +477,7 @@ FOR_LOOP: var packet Packet var _n int64 var err error - _n, err = cdc.UnmarshalBinaryReader(c.bufConnReader, &packet, int64(c.config.maxPacketMsgTotalSize())) + _n, err = cdc.UnmarshalBinaryReader(c.bufConnReader, &packet, int64(c._maxPacketMsgSize)) c.recvMonitor.Update(int(_n)) if err != nil { if c.IsRunning() { @@ -550,6 +550,16 @@ func (c *MConnection) stopPongTimer() { } } +// maxPacketMsgSize returns a maximum size of PacketMsg, including the overhead +// of amino encoding. +func (c *MConnection) maxPacketMsgSize() int { + return len(cdc.MustMarshalBinary(PacketMsg{ + ChannelID: 0x01, + EOF: 1, + Bytes: make([]byte, c.config.MaxPacketMsgPayloadSize), + })) + 10 // leave room for changes in amino +} + type ConnectionStatus struct { Duration time.Duration SendMonitor flow.Status diff --git a/vendor/github.com/tendermint/tendermint/p2p/conn/secret_connection.go b/vendor/github.com/tendermint/tendermint/p2p/conn/secret_connection.go index 2a507f882..a2cbe008d 100644 --- a/vendor/github.com/tendermint/tendermint/p2p/conn/secret_connection.go +++ b/vendor/github.com/tendermint/tendermint/p2p/conn/secret_connection.go @@ -20,8 +20,8 @@ import ( "golang.org/x/crypto/nacl/secretbox" "golang.org/x/crypto/ripemd160" - "github.com/tendermint/go-crypto" - cmn "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tendermint/crypto" + cmn "github.com/tendermint/tendermint/libs/common" ) // 4 + 1024 == 1028 total frame size @@ -267,7 +267,11 @@ func genChallenge(loPubKey, hiPubKey *[32]byte) (challenge *[32]byte) { } func signChallenge(challenge *[32]byte, locPrivKey crypto.PrivKey) (signature crypto.Signature) { - signature = locPrivKey.Sign(challenge[:]) + signature, err := locPrivKey.Sign(challenge[:]) + // TODO(ismail): let signChallenge return an error instead + if err != nil { + panic(err) + } return } diff --git a/vendor/github.com/tendermint/tendermint/p2p/conn/wire.go b/vendor/github.com/tendermint/tendermint/p2p/conn/wire.go index 02d67f6fb..3182fde38 100644 --- a/vendor/github.com/tendermint/tendermint/p2p/conn/wire.go +++ b/vendor/github.com/tendermint/tendermint/p2p/conn/wire.go @@ -2,7 +2,7 @@ package conn import ( "github.com/tendermint/go-amino" - "github.com/tendermint/go-crypto" + "github.com/tendermint/tendermint/crypto" ) var cdc *amino.Codec = amino.NewCodec() diff --git a/vendor/github.com/tendermint/tendermint/p2p/fuzz.go b/vendor/github.com/tendermint/tendermint/p2p/fuzz.go index 8d00ba40d..80e4fed6a 100644 --- a/vendor/github.com/tendermint/tendermint/p2p/fuzz.go +++ b/vendor/github.com/tendermint/tendermint/p2p/fuzz.go @@ -6,7 +6,7 @@ import ( "time" "github.com/tendermint/tendermint/config" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) // FuzzedConnection wraps any net.Conn and depending on the mode either delays diff --git a/vendor/github.com/tendermint/tendermint/p2p/key.go b/vendor/github.com/tendermint/tendermint/p2p/key.go index 73103ebd4..9548d34f0 100644 --- a/vendor/github.com/tendermint/tendermint/p2p/key.go +++ b/vendor/github.com/tendermint/tendermint/p2p/key.go @@ -6,8 +6,8 @@ import ( "fmt" "io/ioutil" - crypto "github.com/tendermint/go-crypto" - cmn "github.com/tendermint/tmlibs/common" + crypto "github.com/tendermint/tendermint/crypto" + cmn "github.com/tendermint/tendermint/libs/common" ) // ID is a hex-encoded crypto.Address diff --git a/vendor/github.com/tendermint/tendermint/p2p/listener.go b/vendor/github.com/tendermint/tendermint/p2p/listener.go index e698765cd..3509ec69c 100644 --- a/vendor/github.com/tendermint/tendermint/p2p/listener.go +++ b/vendor/github.com/tendermint/tendermint/p2p/listener.go @@ -4,22 +4,30 @@ import ( "fmt" "net" "strconv" + "strings" "time" + cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/p2p/upnp" - cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/log" ) +// Listener is a network listener for stream-oriented protocols, providing +// convenient methods to get listener's internal and external addresses. +// Clients are supposed to read incoming connections from a channel, returned +// by Connections() method. type Listener interface { Connections() <-chan net.Conn InternalAddress() *NetAddress ExternalAddress() *NetAddress + ExternalAddressHost() string String() string Stop() error } -// Implements Listener +// DefaultListener is a cmn.Service, running net.Listener underneath. +// Optionally, UPnP is used upon calling NewDefaultListener to resolve external +// address. type DefaultListener struct { cmn.BaseService @@ -29,6 +37,8 @@ type DefaultListener struct { connections chan net.Conn } +var _ Listener = (*DefaultListener)(nil) + const ( numBufferedConnections = 10 defaultExternalPort = 8770 @@ -47,9 +57,16 @@ func splitHostPort(addr string) (host string, port int) { return host, port } -// skipUPNP: If true, does not try getUPNPExternalAddress() -func NewDefaultListener(protocol string, lAddr string, skipUPNP bool, logger log.Logger) Listener { - // Local listen IP & port +// NewDefaultListener creates a new DefaultListener on lAddr, optionally trying +// to determine external address using UPnP. +func NewDefaultListener( + fullListenAddrString string, + externalAddrString string, + useUPnP bool, + logger log.Logger) Listener { + + // Split protocol, address, and port. + protocol, lAddr := cmn.ProtocolAndAddress(fullListenAddrString) lAddrIP, lAddrPort := splitHostPort(lAddr) // Create listener @@ -77,17 +94,28 @@ func NewDefaultListener(protocol string, lAddr string, skipUPNP bool, logger log panic(err) } - // Determine external address... + inAddrAny := lAddrIP == "" || lAddrIP == "0.0.0.0" + + // Determine external address. var extAddr *NetAddress - if !skipUPNP { - // If the lAddrIP is INADDR_ANY, try UPnP - if lAddrIP == "" || lAddrIP == "0.0.0.0" { - extAddr = getUPNPExternalAddress(lAddrPort, listenerPort, logger) + + if externalAddrString != "" { + var err error + extAddr, err = NewNetAddressStringWithOptionalID(externalAddrString) + if err != nil { + panic(fmt.Sprintf("Error in ExternalAddress: %v", err)) } } - // Otherwise just use the local address... + + // If the lAddrIP is INADDR_ANY, try UPnP. + if extAddr == nil && useUPnP && inAddrAny { + extAddr = getUPNPExternalAddress(lAddrPort, listenerPort, logger) + } + + // Otherwise just use the local address. if extAddr == nil { - extAddr = getNaiveExternalAddress(listenerPort, false, logger) + defaultToIPv4 := inAddrAny + extAddr = getNaiveExternalAddress(defaultToIPv4, listenerPort, false, logger) } if extAddr == nil { panic("Could not determine external address!") @@ -107,6 +135,8 @@ func NewDefaultListener(protocol string, lAddr string, skipUPNP bool, logger log return dl } +// OnStart implements cmn.Service by spinning a goroutine, listening for new +// connections. func (l *DefaultListener) OnStart() error { if err := l.BaseService.OnStart(); err != nil { return err @@ -115,6 +145,7 @@ func (l *DefaultListener) OnStart() error { return nil } +// OnStop implements cmn.Service by closing the listener. func (l *DefaultListener) OnStop() { l.BaseService.OnStop() l.listener.Close() // nolint: errcheck @@ -145,24 +176,33 @@ func (l *DefaultListener) listenRoutine() { } } -// A channel of inbound connections. +// Connections returns a channel of inbound connections. // It gets closed when the listener closes. func (l *DefaultListener) Connections() <-chan net.Conn { return l.connections } +// InternalAddress returns the internal NetAddress (address used for +// listening). func (l *DefaultListener) InternalAddress() *NetAddress { return l.intAddr } +// ExternalAddress returns the external NetAddress (publicly available, +// determined using either UPnP or local resolver). func (l *DefaultListener) ExternalAddress() *NetAddress { return l.extAddr } -// NOTE: The returned listener is already Accept()'ing. -// So it's not suitable to pass into http.Serve(). -func (l *DefaultListener) NetListener() net.Listener { - return l.listener +// ExternalAddressHost returns the external NetAddress IP string. If an IP is +// IPv6, it's wrapped in brackets ("[2001:db8:1f70::999:de8:7648:6e8]"). +func (l *DefaultListener) ExternalAddressHost() string { + ip := l.ExternalAddress().IP + if isIpv6(ip) { + // Means it's ipv6, so format it with brackets + return "[" + ip.String() + "]" + } + return ip.String() } func (l *DefaultListener) String() string { @@ -201,8 +241,20 @@ func getUPNPExternalAddress(externalPort, internalPort int, logger log.Logger) * return NewNetAddressIPPort(ext, uint16(externalPort)) } +func isIpv6(ip net.IP) bool { + v4 := ip.To4() + if v4 != nil { + return false + } + + ipString := ip.String() + + // Extra check just to be sure it's IPv6 + return (strings.Contains(ipString, ":") && !strings.Contains(ipString, ".")) +} + // TODO: use syscalls: see issue #712 -func getNaiveExternalAddress(port int, settleForLocal bool, logger log.Logger) *NetAddress { +func getNaiveExternalAddress(defaultToIPv4 bool, port int, settleForLocal bool, logger log.Logger) *NetAddress { addrs, err := net.InterfaceAddrs() if err != nil { panic(cmn.Fmt("Could not fetch interface addresses: %v", err)) @@ -213,14 +265,20 @@ func getNaiveExternalAddress(port int, settleForLocal bool, logger log.Logger) * if !ok { continue } - v4 := ipnet.IP.To4() - if v4 == nil || (!settleForLocal && v4[0] == 127) { + if defaultToIPv4 || !isIpv6(ipnet.IP) { + v4 := ipnet.IP.To4() + if v4 == nil || (!settleForLocal && v4[0] == 127) { + // loopback + continue + } + } else if !settleForLocal && ipnet.IP.IsLoopback() { + // IPv6, check for loopback continue - } // loopback + } return NewNetAddressIPPort(ipnet.IP, uint16(port)) } // try again, but settle for local logger.Info("Node may not be connected to internet. Settling for local address") - return getNaiveExternalAddress(port, true, logger) + return getNaiveExternalAddress(defaultToIPv4, port, true, logger) } diff --git a/vendor/github.com/tendermint/tendermint/p2p/metrics.go b/vendor/github.com/tendermint/tendermint/p2p/metrics.go new file mode 100644 index 000000000..ab876ee7c --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/p2p/metrics.go @@ -0,0 +1,33 @@ +package p2p + +import ( + "github.com/go-kit/kit/metrics" + "github.com/go-kit/kit/metrics/discard" + + prometheus "github.com/go-kit/kit/metrics/prometheus" + stdprometheus "github.com/prometheus/client_golang/prometheus" +) + +// Metrics contains metrics exposed by this package. +type Metrics struct { + // Number of peers. + Peers metrics.Gauge +} + +// PrometheusMetrics returns Metrics build using Prometheus client library. +func PrometheusMetrics() *Metrics { + return &Metrics{ + Peers: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "p2p", + Name: "peers", + Help: "Number of peers.", + }, []string{}), + } +} + +// NopMetrics returns no-op Metrics. +func NopMetrics() *Metrics { + return &Metrics{ + Peers: discard.NewGauge(), + } +} diff --git a/vendor/github.com/tendermint/tendermint/p2p/netaddress.go b/vendor/github.com/tendermint/tendermint/p2p/netaddress.go index 3e0d99d69..ebac8cc82 100644 --- a/vendor/github.com/tendermint/tendermint/p2p/netaddress.go +++ b/vendor/github.com/tendermint/tendermint/p2p/netaddress.go @@ -13,7 +13,7 @@ import ( "strings" "time" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) // NetAddress defines information about a peer on the network diff --git a/vendor/github.com/tendermint/tendermint/p2p/node_info.go b/vendor/github.com/tendermint/tendermint/p2p/node_info.go index 60383bc5e..5e8160a3b 100644 --- a/vendor/github.com/tendermint/tendermint/p2p/node_info.go +++ b/vendor/github.com/tendermint/tendermint/p2p/node_info.go @@ -2,7 +2,7 @@ package p2p import ( "fmt" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" "strings" ) diff --git a/vendor/github.com/tendermint/tendermint/p2p/peer.go b/vendor/github.com/tendermint/tendermint/p2p/peer.go index da69fe74f..5c615275b 100644 --- a/vendor/github.com/tendermint/tendermint/p2p/peer.go +++ b/vendor/github.com/tendermint/tendermint/p2p/peer.go @@ -6,9 +6,9 @@ import ( "sync/atomic" "time" - crypto "github.com/tendermint/go-crypto" - cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/log" + crypto "github.com/tendermint/tendermint/crypto" + cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/config" tmconn "github.com/tendermint/tendermint/p2p/conn" diff --git a/vendor/github.com/tendermint/tendermint/p2p/peer_set.go b/vendor/github.com/tendermint/tendermint/p2p/peer_set.go index e048cf4e3..257856156 100644 --- a/vendor/github.com/tendermint/tendermint/p2p/peer_set.go +++ b/vendor/github.com/tendermint/tendermint/p2p/peer_set.go @@ -55,8 +55,8 @@ func (ps *PeerSet) Add(peer Peer) error { return nil } -// Has returns true iff the PeerSet contains -// the peer referred to by this peerKey. +// Has returns true if the set contains the peer referred to by this +// peerKey, otherwise false. func (ps *PeerSet) Has(peerKey ID) bool { ps.mtx.Lock() _, ok := ps.lookup[peerKey] @@ -64,8 +64,8 @@ func (ps *PeerSet) Has(peerKey ID) bool { return ok } -// HasIP returns true if the PeerSet contains the peer referred to by this IP -// address. +// HasIP returns true if the set contains the peer referred to by this IP +// address, otherwise false. func (ps *PeerSet) HasIP(peerIP net.IP) bool { ps.mtx.Lock() defer ps.mtx.Unlock() @@ -85,7 +85,8 @@ func (ps *PeerSet) hasIP(peerIP net.IP) bool { return false } -// Get looks up a peer by the provided peerKey. +// Get looks up a peer by the provided peerKey. Returns nil if peer is not +// found. func (ps *PeerSet) Get(peerKey ID) Peer { ps.mtx.Lock() defer ps.mtx.Unlock() diff --git a/vendor/github.com/tendermint/tendermint/p2p/pex/addrbook.go b/vendor/github.com/tendermint/tendermint/p2p/pex/addrbook.go index dc51761fe..421aa135a 100644 --- a/vendor/github.com/tendermint/tendermint/p2p/pex/addrbook.go +++ b/vendor/github.com/tendermint/tendermint/p2p/pex/addrbook.go @@ -12,9 +12,9 @@ import ( "sync" "time" - crypto "github.com/tendermint/go-crypto" + crypto "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/p2p" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) const ( diff --git a/vendor/github.com/tendermint/tendermint/p2p/pex/file.go b/vendor/github.com/tendermint/tendermint/p2p/pex/file.go index 38142dd9d..3237e1253 100644 --- a/vendor/github.com/tendermint/tendermint/p2p/pex/file.go +++ b/vendor/github.com/tendermint/tendermint/p2p/pex/file.go @@ -4,7 +4,7 @@ import ( "encoding/json" "os" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) /* Loading & Saving */ diff --git a/vendor/github.com/tendermint/tendermint/p2p/pex/pex_reactor.go b/vendor/github.com/tendermint/tendermint/p2p/pex/pex_reactor.go index 27ed422c5..e90665a37 100644 --- a/vendor/github.com/tendermint/tendermint/p2p/pex/pex_reactor.go +++ b/vendor/github.com/tendermint/tendermint/p2p/pex/pex_reactor.go @@ -8,7 +8,7 @@ import ( "time" amino "github.com/tendermint/go-amino" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/p2p/conn" @@ -77,10 +77,10 @@ type PEXReactor struct { attemptsToDial sync.Map // address (string) -> {number of attempts (int), last time dialed (time.Time)} } -func (pexR *PEXReactor) minReceiveRequestInterval() time.Duration { +func (r *PEXReactor) minReceiveRequestInterval() time.Duration { // NOTE: must be less than ensurePeersPeriod, otherwise we'll request // peers too quickly from others and they'll think we're bad! - return pexR.ensurePeersPeriod / 3 + return r.ensurePeersPeriod / 3 } // PEXReactorConfig holds reactor specific configuration data. @@ -206,7 +206,7 @@ func (r *PEXReactor) RemovePeer(p Peer, reason interface{}) { // Receive implements Reactor by handling incoming PEX messages. func (r *PEXReactor) Receive(chID byte, src Peer, msgBytes []byte) { - msg, err := DecodeMessage(msgBytes) + msg, err := decodeMsg(msgBytes) if err != nil { r.Logger.Error("Error decoding message", "src", src, "chId", chID, "msg", msg, "err", err, "bytes", msgBytes) r.Switch.StopPeerForError(src, err) @@ -287,7 +287,7 @@ func (r *PEXReactor) RequestAddrs(p Peer) { return } r.requestsSent.Set(id, struct{}{}) - p.Send(PexChannel, cdc.MustMarshalBinary(&pexRequestMessage{})) + p.Send(PexChannel, cdc.MustMarshalBinaryBare(&pexRequestMessage{})) } // ReceiveAddrs adds the given addrs to the addrbook if theres an open @@ -324,7 +324,7 @@ func (r *PEXReactor) ReceiveAddrs(addrs []*p2p.NetAddress, src Peer) error { // SendAddrs sends addrs to the peer. func (r *PEXReactor) SendAddrs(p Peer, netAddrs []*p2p.NetAddress) { - p.Send(PexChannel, cdc.MustMarshalBinary(&pexAddrsMessage{Addrs: netAddrs})) + p.Send(PexChannel, cdc.MustMarshalBinaryBare(&pexAddrsMessage{Addrs: netAddrs})) } // SetEnsurePeersPeriod sets period to ensure peers connected. @@ -628,7 +628,9 @@ func (r *PEXReactor) crawlPeers() { } // Ask for more addresses peer := r.Switch.Peers().Get(pi.Addr.ID) - r.RequestAddrs(peer) + if peer != nil { + r.RequestAddrs(peer) + } } } @@ -668,13 +670,11 @@ func RegisterPexMessage(cdc *amino.Codec) { cdc.RegisterConcrete(&pexAddrsMessage{}, "tendermint/p2p/PexAddrsMessage", nil) } -// DecodeMessage implements interface registered above. -func DecodeMessage(bz []byte) (msg PexMessage, err error) { +func decodeMsg(bz []byte) (msg PexMessage, err error) { if len(bz) > maxMsgSize { - return msg, fmt.Errorf("Msg exceeds max size (%d > %d)", - len(bz), maxMsgSize) + return msg, fmt.Errorf("Msg exceeds max size (%d > %d)", len(bz), maxMsgSize) } - err = cdc.UnmarshalBinary(bz, &msg) + err = cdc.UnmarshalBinaryBare(bz, &msg) return } diff --git a/vendor/github.com/tendermint/tendermint/p2p/switch.go b/vendor/github.com/tendermint/tendermint/p2p/switch.go index f1ceee5c6..d1e2ef23b 100644 --- a/vendor/github.com/tendermint/tendermint/p2p/switch.go +++ b/vendor/github.com/tendermint/tendermint/p2p/switch.go @@ -9,7 +9,7 @@ import ( "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/p2p/conn" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) const ( @@ -73,10 +73,15 @@ type Switch struct { mConfig conn.MConnConfig rng *cmn.Rand // seed for randomizing dial times and orders + + metrics *Metrics } +// SwitchOption sets an optional parameter on the Switch. +type SwitchOption func(*Switch) + // NewSwitch creates a new Switch with the given config. -func NewSwitch(cfg *config.P2PConfig) *Switch { +func NewSwitch(cfg *config.P2PConfig, options ...SwitchOption) *Switch { sw := &Switch{ config: cfg, reactors: make(map[string]Reactor), @@ -85,6 +90,7 @@ func NewSwitch(cfg *config.P2PConfig) *Switch { peers: NewPeerSet(), dialing: cmn.NewCMap(), reconnecting: cmn.NewCMap(), + metrics: NopMetrics(), } // Ensure we have a completely undeterministic PRNG. @@ -99,9 +105,19 @@ func NewSwitch(cfg *config.P2PConfig) *Switch { sw.mConfig = mConfig sw.BaseService = *cmn.NewBaseService(nil, "P2P Switch", sw) + + for _, option := range options { + option(sw) + } + return sw } +// WithMetrics sets the metrics. +func WithMetrics(metrics *Metrics) SwitchOption { + return func(sw *Switch) { sw.metrics = metrics } +} + //--------------------------------------------------------------------- // Switch setup @@ -279,6 +295,7 @@ func (sw *Switch) StopPeerGracefully(peer Peer) { func (sw *Switch) stopAndRemovePeer(peer Peer, reason interface{}) { sw.peers.Remove(peer) + sw.metrics.Peers.Add(float64(-1)) peer.Stop() for _, reactor := range sw.reactors { reactor.RemovePeer(peer, reason) @@ -623,6 +640,7 @@ func (sw *Switch) addPeer(pc peerConn) error { if err := sw.peers.Add(peer); err != nil { return err } + sw.metrics.Peers.Add(float64(1)) sw.Logger.Info("Added peer", "peer", peer) return nil diff --git a/vendor/github.com/tendermint/tendermint/p2p/test_util.go b/vendor/github.com/tendermint/tendermint/p2p/test_util.go index 0d2ba6c5e..467532f0f 100644 --- a/vendor/github.com/tendermint/tendermint/p2p/test_util.go +++ b/vendor/github.com/tendermint/tendermint/p2p/test_util.go @@ -4,9 +4,9 @@ import ( "fmt" "net" - crypto "github.com/tendermint/go-crypto" - cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/log" + crypto "github.com/tendermint/tendermint/crypto" + cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/p2p/conn" diff --git a/vendor/github.com/tendermint/tendermint/p2p/upnp/probe.go b/vendor/github.com/tendermint/tendermint/p2p/upnp/probe.go index 55479415f..2de5e7905 100644 --- a/vendor/github.com/tendermint/tendermint/p2p/upnp/probe.go +++ b/vendor/github.com/tendermint/tendermint/p2p/upnp/probe.go @@ -5,8 +5,8 @@ import ( "net" "time" - cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/log" + cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/log" ) type UPNPCapabilities struct { diff --git a/vendor/github.com/tendermint/tendermint/p2p/wire.go b/vendor/github.com/tendermint/tendermint/p2p/wire.go index a90ac851c..b7ae41253 100644 --- a/vendor/github.com/tendermint/tendermint/p2p/wire.go +++ b/vendor/github.com/tendermint/tendermint/p2p/wire.go @@ -2,7 +2,7 @@ package p2p import ( "github.com/tendermint/go-amino" - "github.com/tendermint/go-crypto" + "github.com/tendermint/tendermint/crypto" ) var cdc = amino.NewCodec() diff --git a/vendor/github.com/tendermint/tendermint/privval/priv_validator.go b/vendor/github.com/tendermint/tendermint/privval/priv_validator.go index 2bb5ef323..1e85bf7b3 100644 --- a/vendor/github.com/tendermint/tendermint/privval/priv_validator.go +++ b/vendor/github.com/tendermint/tendermint/privval/priv_validator.go @@ -8,9 +8,9 @@ import ( "sync" "time" - "github.com/tendermint/go-crypto" + "github.com/tendermint/tendermint/crypto" + cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tmlibs/common" ) // TODO: type ? @@ -91,6 +91,10 @@ func LoadFilePV(filePath string) *FilePV { cmn.Exit(cmn.Fmt("Error reading PrivValidator from %v: %v\n", filePath, err)) } + // overwrite pubkey and address for convenience + pv.PubKey = pv.PrivKey.PubKey() + pv.Address = pv.PubKey.Address() + pv.filePath = filePath return pv } @@ -222,7 +226,10 @@ func (pv *FilePV) signVote(chainID string, vote *types.Vote) error { } // It passed the checks. Sign the vote - sig := pv.PrivKey.Sign(signBytes) + sig, err := pv.PrivKey.Sign(signBytes) + if err != nil { + return err + } pv.saveSigned(height, round, step, signBytes, sig) vote.Signature = sig return nil @@ -258,7 +265,10 @@ func (pv *FilePV) signProposal(chainID string, proposal *types.Proposal) error { } // It passed the checks. Sign the proposal - sig := pv.PrivKey.Sign(signBytes) + sig, err := pv.PrivKey.Sign(signBytes) + if err != nil { + return err + } pv.saveSigned(height, round, step, signBytes, sig) proposal.Signature = sig return nil @@ -281,7 +291,11 @@ func (pv *FilePV) saveSigned(height int64, round int, step int8, func (pv *FilePV) SignHeartbeat(chainID string, heartbeat *types.Heartbeat) error { pv.mtx.Lock() defer pv.mtx.Unlock() - heartbeat.Signature = pv.PrivKey.Sign(heartbeat.SignBytes(chainID)) + sig, err := pv.PrivKey.Sign(heartbeat.SignBytes(chainID)) + if err != nil { + return err + } + heartbeat.Signature = sig return nil } diff --git a/vendor/github.com/tendermint/tendermint/privval/socket.go b/vendor/github.com/tendermint/tendermint/privval/socket.go index 9f59a8152..1e8a3807b 100644 --- a/vendor/github.com/tendermint/tendermint/privval/socket.go +++ b/vendor/github.com/tendermint/tendermint/privval/socket.go @@ -8,9 +8,9 @@ import ( "time" "github.com/tendermint/go-amino" - "github.com/tendermint/go-crypto" - cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/log" + "github.com/tendermint/tendermint/crypto" + cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/log" p2pconn "github.com/tendermint/tendermint/p2p/conn" "github.com/tendermint/tendermint/types" diff --git a/vendor/github.com/tendermint/tendermint/privval/wire.go b/vendor/github.com/tendermint/tendermint/privval/wire.go index 688910834..c42ba40d6 100644 --- a/vendor/github.com/tendermint/tendermint/privval/wire.go +++ b/vendor/github.com/tendermint/tendermint/privval/wire.go @@ -2,7 +2,7 @@ package privval import ( "github.com/tendermint/go-amino" - "github.com/tendermint/go-crypto" + "github.com/tendermint/tendermint/crypto" ) var cdc = amino.NewCodec() diff --git a/vendor/github.com/tendermint/tendermint/proxy/app_conn.go b/vendor/github.com/tendermint/tendermint/proxy/app_conn.go index 2319fed82..2f792671e 100644 --- a/vendor/github.com/tendermint/tendermint/proxy/app_conn.go +++ b/vendor/github.com/tendermint/tendermint/proxy/app_conn.go @@ -1,8 +1,8 @@ package proxy import ( - abcicli "github.com/tendermint/abci/client" - "github.com/tendermint/abci/types" + abcicli "github.com/tendermint/tendermint/abci/client" + "github.com/tendermint/tendermint/abci/types" ) //---------------------------------------------------------------------------------------- diff --git a/vendor/github.com/tendermint/tendermint/proxy/client.go b/vendor/github.com/tendermint/tendermint/proxy/client.go index 6c987368a..87f4e716d 100644 --- a/vendor/github.com/tendermint/tendermint/proxy/client.go +++ b/vendor/github.com/tendermint/tendermint/proxy/client.go @@ -5,9 +5,9 @@ import ( "github.com/pkg/errors" - abcicli "github.com/tendermint/abci/client" - "github.com/tendermint/abci/example/kvstore" - "github.com/tendermint/abci/types" + abcicli "github.com/tendermint/tendermint/abci/client" + "github.com/tendermint/tendermint/abci/example/kvstore" + "github.com/tendermint/tendermint/abci/types" ) // NewABCIClient returns newly connected client diff --git a/vendor/github.com/tendermint/tendermint/proxy/multi_app_conn.go b/vendor/github.com/tendermint/tendermint/proxy/multi_app_conn.go index 5d89ef195..279fa42ee 100644 --- a/vendor/github.com/tendermint/tendermint/proxy/multi_app_conn.go +++ b/vendor/github.com/tendermint/tendermint/proxy/multi_app_conn.go @@ -3,7 +3,7 @@ package proxy import ( "github.com/pkg/errors" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) //----------------------------- diff --git a/vendor/github.com/tendermint/tendermint/rpc/core/README.md b/vendor/github.com/tendermint/tendermint/rpc/core/README.md new file mode 100644 index 000000000..9547079b2 --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/rpc/core/README.md @@ -0,0 +1,20 @@ +# Tendermint RPC + +## Generate markdown for [Slate](https://github.com/tendermint/slate) + +We are using [Slate](https://github.com/tendermint/slate) to power our RPC +documentation. For generating markdown use: + +```shell +go get github.com/davecheney/godoc2md + +godoc2md -template rpc/core/doc_template.txt github.com/tendermint/tendermint/rpc/core | grep -v -e "pipe.go" -e "routes.go" -e "dev.go" | sed 's$/src/target$https://github.com/tendermint/tendermint/tree/master/rpc/core$' +``` + +For more information see the [CI script for building the Slate docs](/scripts/slate.sh) + +## Pagination + +Requests that return multiple items will be paginated to 30 items by default. +You can specify further pages with the ?page parameter. You can also set a +custom page size up to 100 with the ?per_page parameter. diff --git a/vendor/github.com/tendermint/tendermint/rpc/core/abci.go b/vendor/github.com/tendermint/tendermint/rpc/core/abci.go index 067108c44..a5eede3fc 100644 --- a/vendor/github.com/tendermint/tendermint/rpc/core/abci.go +++ b/vendor/github.com/tendermint/tendermint/rpc/core/abci.go @@ -1,10 +1,10 @@ package core import ( - abci "github.com/tendermint/abci/types" + abci "github.com/tendermint/tendermint/abci/types" ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/version" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) // Query the application for some information. diff --git a/vendor/github.com/tendermint/tendermint/rpc/core/blocks.go b/vendor/github.com/tendermint/tendermint/rpc/core/blocks.go index a5ad5b4cb..0e8873152 100644 --- a/vendor/github.com/tendermint/tendermint/rpc/core/blocks.go +++ b/vendor/github.com/tendermint/tendermint/rpc/core/blocks.go @@ -6,7 +6,7 @@ import ( ctypes "github.com/tendermint/tendermint/rpc/core/types" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) // Get block headers for minHeight <= height <= maxHeight. diff --git a/vendor/github.com/tendermint/tendermint/rpc/core/consensus.go b/vendor/github.com/tendermint/tendermint/rpc/core/consensus.go index dad64b6b6..c026cd91f 100644 --- a/vendor/github.com/tendermint/tendermint/rpc/core/consensus.go +++ b/vendor/github.com/tendermint/tendermint/rpc/core/consensus.go @@ -87,7 +87,7 @@ func Validators(heightPtr *int64) (*ctypes.ResultValidators, error) { // { // "address": "B5B3D40BE53982AD294EF99FF5A34C0C3E5A3244", // "pub_key": { -// "type": "AC26791624DE60", +// "type": "tendermint/PubKeyEd25519", // "value": "SBctdhRBcXtBgdI/8a/alTsUhGXqGs9k5ylV1u5iKHg=" // }, // "voting_power": 10, @@ -97,7 +97,7 @@ func Validators(heightPtr *int64) (*ctypes.ResultValidators, error) { // "proposer": { // "address": "B5B3D40BE53982AD294EF99FF5A34C0C3E5A3244", // "pub_key": { -// "type": "AC26791624DE60", +// "type": "tendermint/PubKeyEd25519", // "value": "SBctdhRBcXtBgdI/8a/alTsUhGXqGs9k5ylV1u5iKHg=" // }, // "voting_power": 10, @@ -133,7 +133,7 @@ func Validators(heightPtr *int64) (*ctypes.ResultValidators, error) { // { // "address": "B5B3D40BE53982AD294EF99FF5A34C0C3E5A3244", // "pub_key": { -// "type": "AC26791624DE60", +// "type": "tendermint/PubKeyEd25519", // "value": "SBctdhRBcXtBgdI/8a/alTsUhGXqGs9k5ylV1u5iKHg=" // }, // "voting_power": 10, @@ -143,7 +143,7 @@ func Validators(heightPtr *int64) (*ctypes.ResultValidators, error) { // "proposer": { // "address": "B5B3D40BE53982AD294EF99FF5A34C0C3E5A3244", // "pub_key": { -// "type": "AC26791624DE60", +// "type": "tendermint/PubKeyEd25519", // "value": "SBctdhRBcXtBgdI/8a/alTsUhGXqGs9k5ylV1u5iKHg=" // }, // "voting_power": 10, diff --git a/vendor/github.com/tendermint/tendermint/rpc/core/doc_template.txt b/vendor/github.com/tendermint/tendermint/rpc/core/doc_template.txt new file mode 100644 index 000000000..896d0c271 --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/rpc/core/doc_template.txt @@ -0,0 +1,8 @@ +{{with .PDoc}} +{{comment_md .Doc}} +{{example_html $ ""}} + +{{range .Funcs}}{{$name_html := html .Name}}## [{{$name_html}}]({{posLink_url $ .Decl}}) +{{comment_md .Doc}}{{end}} +{{end}} +--- diff --git a/vendor/github.com/tendermint/tendermint/rpc/core/mempool.go b/vendor/github.com/tendermint/tendermint/rpc/core/mempool.go index 515ada87c..ecc41ce12 100644 --- a/vendor/github.com/tendermint/tendermint/rpc/core/mempool.go +++ b/vendor/github.com/tendermint/tendermint/rpc/core/mempool.go @@ -7,10 +7,10 @@ import ( "github.com/pkg/errors" - abci "github.com/tendermint/abci/types" + abci "github.com/tendermint/tendermint/abci/types" ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) //----------------------------------------------------------------------------- diff --git a/vendor/github.com/tendermint/tendermint/rpc/core/pipe.go b/vendor/github.com/tendermint/tendermint/rpc/core/pipe.go index 7a042362f..128b3e9a7 100644 --- a/vendor/github.com/tendermint/tendermint/rpc/core/pipe.go +++ b/vendor/github.com/tendermint/tendermint/rpc/core/pipe.go @@ -3,15 +3,15 @@ package core import ( "time" - crypto "github.com/tendermint/go-crypto" "github.com/tendermint/tendermint/consensus" + crypto "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/state/txindex" "github.com/tendermint/tendermint/types" - dbm "github.com/tendermint/tmlibs/db" - "github.com/tendermint/tmlibs/log" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" ) const ( diff --git a/vendor/github.com/tendermint/tendermint/rpc/core/status.go b/vendor/github.com/tendermint/tendermint/rpc/core/status.go index 044c12899..63e62b2c7 100644 --- a/vendor/github.com/tendermint/tendermint/rpc/core/status.go +++ b/vendor/github.com/tendermint/tendermint/rpc/core/status.go @@ -7,7 +7,7 @@ import ( ctypes "github.com/tendermint/tendermint/rpc/core/types" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) // Get Tendermint status including node info, pubkey, latest block @@ -50,12 +50,12 @@ import ( // "latest_app_hash": "0000000000000000", // "latest_block_height": 231, // "latest_block_time": "2018-04-27T23:18:08.459766485-04:00", -// "syncing": false +// "catching_up": false // }, // "validator_info": { // "address": "5875562FF0FFDECC895C20E32FC14988952E99E7", // "pub_key": { -// "type": "AC26791624DE60", +// "type": "tendermint/PubKeyEd25519", // "value": "PpDJRUrLG2RgFqYYjawfn/AcAgacSXpLFrmfYYQnuzE=" // }, // "voting_power": 10 @@ -92,7 +92,7 @@ func Status() (*ctypes.ResultStatus, error) { LatestAppHash: latestAppHash, LatestBlockHeight: latestHeight, LatestBlockTime: latestBlockTime, - Syncing: consensusReactor.FastSync(), + CatchingUp: consensusReactor.FastSync(), }, ValidatorInfo: ctypes.ValidatorInfo{ Address: pubKey.Address(), diff --git a/vendor/github.com/tendermint/tendermint/rpc/core/tx.go b/vendor/github.com/tendermint/tendermint/rpc/core/tx.go index 2fa7825fd..f53d82f14 100644 --- a/vendor/github.com/tendermint/tendermint/rpc/core/tx.go +++ b/vendor/github.com/tendermint/tendermint/rpc/core/tx.go @@ -3,7 +3,7 @@ package core import ( "fmt" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" tmquery "github.com/tendermint/tendermint/libs/pubsub/query" ctypes "github.com/tendermint/tendermint/rpc/core/types" diff --git a/vendor/github.com/tendermint/tendermint/rpc/core/types/responses.go b/vendor/github.com/tendermint/tendermint/rpc/core/types/responses.go index 5b001d7d3..4fec416ed 100644 --- a/vendor/github.com/tendermint/tendermint/rpc/core/types/responses.go +++ b/vendor/github.com/tendermint/tendermint/rpc/core/types/responses.go @@ -5,9 +5,9 @@ import ( "strings" "time" - abci "github.com/tendermint/abci/types" - crypto "github.com/tendermint/go-crypto" - cmn "github.com/tendermint/tmlibs/common" + abci "github.com/tendermint/tendermint/abci/types" + crypto "github.com/tendermint/tendermint/crypto" + cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/state" @@ -65,7 +65,7 @@ type SyncInfo struct { LatestAppHash cmn.HexBytes `json:"latest_app_hash"` LatestBlockHeight int64 `json:"latest_block_height"` LatestBlockTime time.Time `json:"latest_block_time"` - Syncing bool `json:"syncing"` + CatchingUp bool `json:"catching_up"` } // Info about the node's validator diff --git a/vendor/github.com/tendermint/tendermint/rpc/core/types/wire.go b/vendor/github.com/tendermint/tendermint/rpc/core/types/wire.go index 6648364b1..d3a31dc35 100644 --- a/vendor/github.com/tendermint/tendermint/rpc/core/types/wire.go +++ b/vendor/github.com/tendermint/tendermint/rpc/core/types/wire.go @@ -2,7 +2,7 @@ package core_types import ( "github.com/tendermint/go-amino" - "github.com/tendermint/go-crypto" + "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/types" ) diff --git a/vendor/github.com/tendermint/tendermint/rpc/grpc/api.go b/vendor/github.com/tendermint/tendermint/rpc/grpc/api.go index c0a920046..0b840e3e9 100644 --- a/vendor/github.com/tendermint/tendermint/rpc/grpc/api.go +++ b/vendor/github.com/tendermint/tendermint/rpc/grpc/api.go @@ -3,7 +3,7 @@ package core_grpc import ( "context" - abci "github.com/tendermint/abci/types" + abci "github.com/tendermint/tendermint/abci/types" core "github.com/tendermint/tendermint/rpc/core" ) diff --git a/vendor/github.com/tendermint/tendermint/rpc/grpc/client_server.go b/vendor/github.com/tendermint/tendermint/rpc/grpc/client_server.go index 80d736f57..c88989685 100644 --- a/vendor/github.com/tendermint/tendermint/rpc/grpc/client_server.go +++ b/vendor/github.com/tendermint/tendermint/rpc/grpc/client_server.go @@ -6,13 +6,21 @@ import ( "strings" "time" + "golang.org/x/net/netutil" "google.golang.org/grpc" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) -// Start the grpcServer in a go routine -func StartGRPCServer(protoAddr string) (net.Listener, error) { +// Config is an gRPC server configuration. +type Config struct { + MaxOpenConnections int +} + +// StartGRPCServer starts a new gRPC BroadcastAPIServer, listening on +// protoAddr, in a goroutine. Returns a listener and an error, if it fails to +// parse an address. +func StartGRPCServer(protoAddr string, config Config) (net.Listener, error) { parts := strings.SplitN(protoAddr, "://", 2) if len(parts) != 2 { return nil, fmt.Errorf("Invalid listen address for grpc server (did you forget a tcp:// prefix?) : %s", protoAddr) @@ -22,6 +30,9 @@ func StartGRPCServer(protoAddr string) (net.Listener, error) { if err != nil { return nil, err } + if config.MaxOpenConnections > 0 { + ln = netutil.LimitListener(ln, config.MaxOpenConnections) + } grpcServer := grpc.NewServer() RegisterBroadcastAPIServer(grpcServer, &broadcastAPI{}) @@ -30,7 +41,8 @@ func StartGRPCServer(protoAddr string) (net.Listener, error) { return ln, nil } -// Start the client by dialing the server +// StartGRPCClient dials the gRPC server using protoAddr and returns a new +// BroadcastAPIClient. func StartGRPCClient(protoAddr string) BroadcastAPIClient { conn, err := grpc.Dial(protoAddr, grpc.WithInsecure(), grpc.WithDialer(dialerFunc)) if err != nil { diff --git a/vendor/github.com/tendermint/tendermint/rpc/grpc/compile.sh b/vendor/github.com/tendermint/tendermint/rpc/grpc/compile.sh new file mode 100644 index 000000000..2c4629c8e --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/rpc/grpc/compile.sh @@ -0,0 +1,3 @@ +#! /bin/bash + +protoc --go_out=plugins=grpc:. -I $GOPATH/src/ -I . types.proto diff --git a/vendor/github.com/tendermint/tendermint/rpc/grpc/types.pb.go b/vendor/github.com/tendermint/tendermint/rpc/grpc/types.pb.go index cf7a5ec71..be16b711a 100644 --- a/vendor/github.com/tendermint/tendermint/rpc/grpc/types.pb.go +++ b/vendor/github.com/tendermint/tendermint/rpc/grpc/types.pb.go @@ -19,7 +19,7 @@ package core_grpc import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" -import types "github.com/tendermint/abci/types" +import types "github.com/tendermint/tendermint/abci/types" import ( "context" diff --git a/vendor/github.com/tendermint/tendermint/rpc/grpc/types.proto b/vendor/github.com/tendermint/tendermint/rpc/grpc/types.proto new file mode 100644 index 000000000..d7980d5e0 --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/rpc/grpc/types.proto @@ -0,0 +1,36 @@ +syntax = "proto3"; +package core_grpc; + +import "github.com/tendermint/tendermint/abci/types/types.proto"; + +//---------------------------------------- +// Message types + +//---------------------------------------- +// Request types + +message RequestPing { +} + +message RequestBroadcastTx { + bytes tx = 1; +} + +//---------------------------------------- +// Response types + +message ResponsePing{ +} + +message ResponseBroadcastTx{ + types.ResponseCheckTx check_tx = 1; + types.ResponseDeliverTx deliver_tx = 2; +} + +//---------------------------------------- +// Service Definition + +service BroadcastAPI { + rpc Ping(RequestPing) returns (ResponsePing) ; + rpc BroadcastTx(RequestBroadcastTx) returns (ResponseBroadcastTx) ; +} diff --git a/vendor/github.com/tendermint/tendermint/rpc/lib/doc.go b/vendor/github.com/tendermint/tendermint/rpc/lib/doc.go index 2bc438593..b96b9123c 100644 --- a/vendor/github.com/tendermint/tendermint/rpc/lib/doc.go +++ b/vendor/github.com/tendermint/tendermint/rpc/lib/doc.go @@ -98,6 +98,6 @@ Each route is available as a GET request, as a JSONRPCv2 POST request, and via J # Examples * [Tendermint](https://github.com/tendermint/tendermint/blob/master/rpc/core/routes.go) -* [tm-monitor](https://github.com/tendermint/tools/blob/master/tm-monitor/rpc.go) +* [tm-monitor](https://github.com/tendermint/tendermint/blob/master/tools/tm-monitor/rpc.go) */ package rpc diff --git a/vendor/github.com/tendermint/tendermint/rpc/lib/server/handlers.go b/vendor/github.com/tendermint/tendermint/rpc/lib/server/handlers.go index 6cc03012a..3ec5f81e3 100644 --- a/vendor/github.com/tendermint/tendermint/rpc/lib/server/handlers.go +++ b/vendor/github.com/tendermint/tendermint/rpc/lib/server/handlers.go @@ -18,9 +18,9 @@ import ( "github.com/pkg/errors" amino "github.com/tendermint/go-amino" + cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/log" types "github.com/tendermint/tendermint/rpc/lib/types" - cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/log" ) // RegisterRPCFuncs adds a route for each function in the funcMap, as well as general jsonrpc and websocket handlers for all functions. @@ -294,7 +294,7 @@ func httpParamsToArgs(rpcFunc *RPCFunc, cdc *amino.Codec, r *http.Request) ([]re continue } - v, err, ok := nonJSONToArg(cdc, argType, arg) + v, err, ok := nonJSONStringToArg(cdc, argType, arg) if err != nil { return nil, err } @@ -303,7 +303,7 @@ func httpParamsToArgs(rpcFunc *RPCFunc, cdc *amino.Codec, r *http.Request) ([]re continue } - values[i], err = _jsonStringToArg(cdc, argType, arg) + values[i], err = jsonStringToArg(cdc, argType, arg) if err != nil { return nil, err } @@ -312,26 +312,64 @@ func httpParamsToArgs(rpcFunc *RPCFunc, cdc *amino.Codec, r *http.Request) ([]re return values, nil } -func _jsonStringToArg(cdc *amino.Codec, ty reflect.Type, arg string) (reflect.Value, error) { - v := reflect.New(ty) - err := cdc.UnmarshalJSON([]byte(arg), v.Interface()) +func jsonStringToArg(cdc *amino.Codec, rt reflect.Type, arg string) (reflect.Value, error) { + rv := reflect.New(rt) + err := cdc.UnmarshalJSON([]byte(arg), rv.Interface()) if err != nil { - return v, err + return rv, err } - v = v.Elem() - return v, nil + rv = rv.Elem() + return rv, nil } -func nonJSONToArg(cdc *amino.Codec, ty reflect.Type, arg string) (reflect.Value, error, bool) { +func nonJSONStringToArg(cdc *amino.Codec, rt reflect.Type, arg string) (reflect.Value, error, bool) { + if rt.Kind() == reflect.Ptr { + rv_, err, ok := nonJSONStringToArg(cdc, rt.Elem(), arg) + if err != nil { + return reflect.Value{}, err, false + } else if ok { + rv := reflect.New(rt.Elem()) + rv.Elem().Set(rv_) + return rv, nil, true + } else { + return reflect.Value{}, nil, false + } + } else { + return _nonJSONStringToArg(cdc, rt, arg) + } +} + +// NOTE: rt.Kind() isn't a pointer. +func _nonJSONStringToArg(cdc *amino.Codec, rt reflect.Type, arg string) (reflect.Value, error, bool) { + isIntString := RE_INT.Match([]byte(arg)) isQuotedString := strings.HasPrefix(arg, `"`) && strings.HasSuffix(arg, `"`) isHexString := strings.HasPrefix(strings.ToLower(arg), "0x") - expectingString := ty.Kind() == reflect.String - expectingByteSlice := ty.Kind() == reflect.Slice && ty.Elem().Kind() == reflect.Uint8 + + var expectingString, expectingByteSlice, expectingInt bool + switch rt.Kind() { + case reflect.Int, reflect.Uint, reflect.Int8, reflect.Uint8, reflect.Int16, reflect.Uint16, reflect.Int32, reflect.Uint32, reflect.Int64, reflect.Uint64: + expectingInt = true + case reflect.String: + expectingString = true + case reflect.Slice: + expectingByteSlice = rt.Elem().Kind() == reflect.Uint8 + } + + if isIntString && expectingInt { + qarg := `"` + arg + `"` + // jsonStringToArg + rv, err := jsonStringToArg(cdc, rt, qarg) + if err != nil { + return rv, err, false + } else { + return rv, nil, true + } + } if isHexString { if !expectingString && !expectingByteSlice { err := errors.Errorf("Got a hex string arg, but expected '%s'", - ty.Kind().String()) + rt.Kind().String()) return reflect.ValueOf(nil), err, false } @@ -340,7 +378,7 @@ func nonJSONToArg(cdc *amino.Codec, ty reflect.Type, arg string) (reflect.Value, if err != nil { return reflect.ValueOf(nil), err, false } - if ty.Kind() == reflect.String { + if rt.Kind() == reflect.String { return reflect.ValueOf(string(value)), nil, true } return reflect.ValueOf([]byte(value)), nil, true @@ -406,7 +444,13 @@ type wsConnection struct { // description of how to configure ping period and pong wait time. NOTE: if the // write buffer is full, pongs may be dropped, which may cause clients to // disconnect. see https://github.com/gorilla/websocket/issues/97 -func NewWSConnection(baseConn *websocket.Conn, funcMap map[string]*RPCFunc, cdc *amino.Codec, options ...func(*wsConnection)) *wsConnection { +func NewWSConnection( + baseConn *websocket.Conn, + funcMap map[string]*RPCFunc, + cdc *amino.Codec, + options ...func(*wsConnection), +) *wsConnection { + baseConn.SetReadLimit(maxBodyBytes) wsc := &wsConnection{ remoteAddr: baseConn.RemoteAddr().String(), baseConn: baseConn, diff --git a/vendor/github.com/tendermint/tendermint/rpc/lib/server/http_params.go b/vendor/github.com/tendermint/tendermint/rpc/lib/server/http_params.go index 565060678..3c948c0ba 100644 --- a/vendor/github.com/tendermint/tendermint/rpc/lib/server/http_params.go +++ b/vendor/github.com/tendermint/tendermint/rpc/lib/server/http_params.go @@ -15,6 +15,7 @@ var ( dotAtom = atom + `(?:\.` + atom + `)*` domain = `[A-Z0-9.-]+\.[A-Z]{2,4}` + RE_INT = regexp.MustCompile(`^-?[0-9]+$`) RE_HEX = regexp.MustCompile(`^(?i)[a-f0-9]+$`) RE_EMAIL = regexp.MustCompile(`^(?i)(` + dotAtom + `)@(` + dotAtom + `)$`) RE_ADDRESS = regexp.MustCompile(`^(?i)[a-z0-9]{25,34}$`) diff --git a/vendor/github.com/tendermint/tendermint/rpc/lib/server/http_server.go b/vendor/github.com/tendermint/tendermint/rpc/lib/server/http_server.go index 3f54c61ef..5d816ef22 100644 --- a/vendor/github.com/tendermint/tendermint/rpc/lib/server/http_server.go +++ b/vendor/github.com/tendermint/tendermint/rpc/lib/server/http_server.go @@ -12,16 +12,38 @@ import ( "time" "github.com/pkg/errors" + "golang.org/x/net/netutil" types "github.com/tendermint/tendermint/rpc/lib/types" - "github.com/tendermint/tmlibs/log" + "github.com/tendermint/tendermint/libs/log" ) -func StartHTTPServer(listenAddr string, handler http.Handler, logger log.Logger) (listener net.Listener, err error) { +// Config is an RPC server configuration. +type Config struct { + MaxOpenConnections int +} + +const ( + // maxBodyBytes controls the maximum number of bytes the + // server will read parsing the request body. + maxBodyBytes = int64(1000000) // 1MB +) + +// StartHTTPServer starts an HTTP server on listenAddr with the given handler. +// It wraps handler with RecoverAndLogHandler. +func StartHTTPServer( + listenAddr string, + handler http.Handler, + logger log.Logger, + config Config, +) (listener net.Listener, err error) { var proto, addr string parts := strings.SplitN(listenAddr, "://", 2) if len(parts) != 2 { - return nil, errors.Errorf("Invalid listening address %s (use fully formed addresses, including the tcp:// or unix:// prefix)", listenAddr) + return nil, errors.Errorf( + "Invalid listening address %s (use fully formed addresses, including the tcp:// or unix:// prefix)", + listenAddr, + ) } proto, addr = parts[0], parts[1] @@ -30,35 +52,60 @@ func StartHTTPServer(listenAddr string, handler http.Handler, logger log.Logger) if err != nil { return nil, errors.Errorf("Failed to listen on %v: %v", listenAddr, err) } + if config.MaxOpenConnections > 0 { + listener = netutil.LimitListener(listener, config.MaxOpenConnections) + } go func() { err := http.Serve( listener, - RecoverAndLogHandler(handler, logger), + RecoverAndLogHandler(maxBytesHandler{h: handler, n: maxBodyBytes}, logger), ) logger.Error("RPC HTTP server stopped", "err", err) }() return listener, nil } -func StartHTTPAndTLSServer(listenAddr string, handler http.Handler, certFile, keyFile string, logger log.Logger) (listener net.Listener, err error) { +// StartHTTPAndTLSServer starts an HTTPS server on listenAddr with the given +// handler. +// It wraps handler with RecoverAndLogHandler. +func StartHTTPAndTLSServer( + listenAddr string, + handler http.Handler, + certFile, keyFile string, + logger log.Logger, + config Config, +) (listener net.Listener, err error) { var proto, addr string parts := strings.SplitN(listenAddr, "://", 2) if len(parts) != 2 { - return nil, errors.Errorf("Invalid listening address %s (use fully formed addresses, including the tcp:// or unix:// prefix)", listenAddr) + return nil, errors.Errorf( + "Invalid listening address %s (use fully formed addresses, including the tcp:// or unix:// prefix)", + listenAddr, + ) } proto, addr = parts[0], parts[1] - logger.Info(fmt.Sprintf("Starting RPC HTTPS server on %s (cert: %q, key: %q)", listenAddr, certFile, keyFile)) + logger.Info( + fmt.Sprintf( + "Starting RPC HTTPS server on %s (cert: %q, key: %q)", + listenAddr, + certFile, + keyFile, + ), + ) listener, err = net.Listen(proto, addr) if err != nil { return nil, errors.Errorf("Failed to listen on %v: %v", listenAddr, err) } + if config.MaxOpenConnections > 0 { + listener = netutil.LimitListener(listener, config.MaxOpenConnections) + } go func() { err := http.ServeTLS( listener, - RecoverAndLogHandler(handler, logger), + RecoverAndLogHandler(maxBytesHandler{h: handler, n: maxBodyBytes}, logger), certFile, keyFile, ) @@ -67,7 +114,11 @@ func StartHTTPAndTLSServer(listenAddr string, handler http.Handler, certFile, ke return listener, nil } -func WriteRPCResponseHTTPError(w http.ResponseWriter, httpCode int, res types.RPCResponse) { +func WriteRPCResponseHTTPError( + w http.ResponseWriter, + httpCode int, + res types.RPCResponse, +) { jsonBytes, err := json.MarshalIndent(res, "", " ") if err != nil { panic(err) @@ -117,7 +168,10 @@ func RecoverAndLogHandler(handler http.Handler, logger log.Logger) http.Handler WriteRPCResponseHTTP(rww, res) } else { // For the rest, - logger.Error("Panic in RPC HTTP handler", "err", e, "stack", string(debug.Stack())) + logger.Error( + "Panic in RPC HTTP handler", "err", e, "stack", + string(debug.Stack()), + ) rww.WriteHeader(http.StatusInternalServerError) WriteRPCResponseHTTP(rww, types.RPCInternalError("", e.(error))) } @@ -154,3 +208,13 @@ func (w *ResponseWriterWrapper) WriteHeader(status int) { func (w *ResponseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) { return w.ResponseWriter.(http.Hijacker).Hijack() } + +type maxBytesHandler struct { + h http.Handler + n int64 +} + +func (h maxBytesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + r.Body = http.MaxBytesReader(w, r.Body, h.n) + h.h.ServeHTTP(w, r) +} diff --git a/vendor/github.com/tendermint/tendermint/state/errors.go b/vendor/github.com/tendermint/tendermint/state/errors.go index afb5737d7..d40c7e141 100644 --- a/vendor/github.com/tendermint/tendermint/state/errors.go +++ b/vendor/github.com/tendermint/tendermint/state/errors.go @@ -1,7 +1,7 @@ package state import ( - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) type ( diff --git a/vendor/github.com/tendermint/tendermint/state/execution.go b/vendor/github.com/tendermint/tendermint/state/execution.go index e6b94429e..601abec9e 100644 --- a/vendor/github.com/tendermint/tendermint/state/execution.go +++ b/vendor/github.com/tendermint/tendermint/state/execution.go @@ -4,11 +4,11 @@ import ( "fmt" fail "github.com/ebuchman/fail-test" - abci "github.com/tendermint/abci/types" + abci "github.com/tendermint/tendermint/abci/types" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/proxy" "github.com/tendermint/tendermint/types" - dbm "github.com/tendermint/tmlibs/db" - "github.com/tendermint/tmlibs/log" ) //----------------------------------------------------------------------------- @@ -278,20 +278,24 @@ func updateValidators(currentSet *types.ValidatorSet, abciUpdates []abci.Validat // these are tendermint types now for _, valUpdate := range updates { + if valUpdate.VotingPower < 0 { + return fmt.Errorf("Voting power can't be negative %v", valUpdate) + } + address := valUpdate.Address _, val := currentSet.GetByAddress(address) - if val == nil { - // add val - added := currentSet.Add(valUpdate) - if !added { - return fmt.Errorf("Failed to add new validator %v", valUpdate) - } - } else if valUpdate.VotingPower == 0 { + if valUpdate.VotingPower == 0 { // remove val _, removed := currentSet.Remove(address) if !removed { return fmt.Errorf("Failed to remove validator %X", address) } + } else if val == nil { + // add val + added := currentSet.Add(valUpdate) + if !added { + return fmt.Errorf("Failed to add new validator %v", valUpdate) + } } else { // update val updated := currentSet.Update(valUpdate) diff --git a/vendor/github.com/tendermint/tendermint/state/services.go b/vendor/github.com/tendermint/tendermint/state/services.go index bef286b20..bf0b1a6f4 100644 --- a/vendor/github.com/tendermint/tendermint/state/services.go +++ b/vendor/github.com/tendermint/tendermint/state/services.go @@ -1,7 +1,7 @@ package state import ( - abci "github.com/tendermint/abci/types" + abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/types" ) diff --git a/vendor/github.com/tendermint/tendermint/state/store.go b/vendor/github.com/tendermint/tendermint/state/store.go index 2164d699d..9e94e36fa 100644 --- a/vendor/github.com/tendermint/tendermint/state/store.go +++ b/vendor/github.com/tendermint/tendermint/state/store.go @@ -3,10 +3,10 @@ package state import ( "fmt" - abci "github.com/tendermint/abci/types" + abci "github.com/tendermint/tendermint/abci/types" + cmn "github.com/tendermint/tendermint/libs/common" + dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tmlibs/common" - dbm "github.com/tendermint/tmlibs/db" ) //------------------------------------------------------------------------ @@ -175,8 +175,13 @@ func LoadValidators(db dbm.DB, height int64) (*types.ValidatorSet, error) { if valInfo.ValidatorSet == nil { valInfo2 := loadValidatorsInfo(db, valInfo.LastHeightChanged) if valInfo2 == nil { - cmn.PanicSanity(fmt.Sprintf(`Couldn't find validators at height %d as - last changed from height %d`, valInfo.LastHeightChanged, height)) + panic( + fmt.Sprintf( + "Couldn't find validators at height %d as last changed from height %d", + valInfo.LastHeightChanged, + height, + ), + ) } valInfo = valInfo2 } @@ -239,11 +244,17 @@ func LoadConsensusParams(db dbm.DB, height int64) (types.ConsensusParams, error) } if paramsInfo.ConsensusParams == empty { - paramsInfo = loadConsensusParamsInfo(db, paramsInfo.LastHeightChanged) - if paramsInfo == nil { - cmn.PanicSanity(fmt.Sprintf(`Couldn't find consensus params at height %d as - last changed from height %d`, paramsInfo.LastHeightChanged, height)) + paramsInfo2 := loadConsensusParamsInfo(db, paramsInfo.LastHeightChanged) + if paramsInfo2 == nil { + panic( + fmt.Sprintf( + "Couldn't find consensus params at height %d as last changed from height %d", + paramsInfo.LastHeightChanged, + height, + ), + ) } + paramsInfo = paramsInfo2 } return paramsInfo.ConsensusParams, nil diff --git a/vendor/github.com/tendermint/tendermint/state/txindex/indexer_service.go b/vendor/github.com/tendermint/tendermint/state/txindex/indexer_service.go index 264be1fd8..088252f5e 100644 --- a/vendor/github.com/tendermint/tendermint/state/txindex/indexer_service.go +++ b/vendor/github.com/tendermint/tendermint/state/txindex/indexer_service.go @@ -3,7 +3,7 @@ package txindex import ( "context" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/types" ) diff --git a/vendor/github.com/tendermint/tendermint/state/txindex/kv/kv.go b/vendor/github.com/tendermint/tendermint/state/txindex/kv/kv.go index 718a55d15..707325929 100644 --- a/vendor/github.com/tendermint/tendermint/state/txindex/kv/kv.go +++ b/vendor/github.com/tendermint/tendermint/state/txindex/kv/kv.go @@ -10,8 +10,8 @@ import ( "time" "github.com/pkg/errors" - cmn "github.com/tendermint/tmlibs/common" - dbm "github.com/tendermint/tmlibs/db" + cmn "github.com/tendermint/tendermint/libs/common" + dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/pubsub/query" "github.com/tendermint/tendermint/state/txindex" diff --git a/vendor/github.com/tendermint/tendermint/state/validation.go b/vendor/github.com/tendermint/tendermint/state/validation.go index 84a4cc824..c36339203 100644 --- a/vendor/github.com/tendermint/tendermint/state/validation.go +++ b/vendor/github.com/tendermint/tendermint/state/validation.go @@ -6,7 +6,7 @@ import ( "fmt" "github.com/tendermint/tendermint/types" - dbm "github.com/tendermint/tmlibs/db" + dbm "github.com/tendermint/tendermint/libs/db" ) //----------------------------------------------------- diff --git a/vendor/github.com/tendermint/tendermint/state/wire.go b/vendor/github.com/tendermint/tendermint/state/wire.go index 3e8b544d9..af743c7b8 100644 --- a/vendor/github.com/tendermint/tendermint/state/wire.go +++ b/vendor/github.com/tendermint/tendermint/state/wire.go @@ -2,7 +2,7 @@ package state import ( "github.com/tendermint/go-amino" - "github.com/tendermint/go-crypto" + "github.com/tendermint/tendermint/crypto" ) var cdc = amino.NewCodec() diff --git a/vendor/github.com/tendermint/abci/LICENSE b/vendor/github.com/tendermint/tendermint/tools/build/LICENSE similarity index 93% rename from vendor/github.com/tendermint/abci/LICENSE rename to vendor/github.com/tendermint/tendermint/tools/build/LICENSE index 57951bb8a..bb66bb350 100644 --- a/vendor/github.com/tendermint/abci/LICENSE +++ b/vendor/github.com/tendermint/tendermint/tools/build/LICENSE @@ -1,11 +1,9 @@ -Tendermint ABCI -Copyright (C) 2015 Tendermint - - +Tendermint Core +License: Apache2.0 Apache License Version 2.0, January 2004 - https://www.apache.org/licenses/ + http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION @@ -180,11 +178,24 @@ Copyright (C) 2015 Tendermint END OF TERMS AND CONDITIONS + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2016 All in Bits, Inc + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - https://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, diff --git a/vendor/github.com/tendermint/tendermint/tools/build/basecoind/DEBIAN/copyright b/vendor/github.com/tendermint/tendermint/tools/build/basecoind/DEBIAN/copyright new file mode 100644 index 000000000..fe449650c --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/tools/build/basecoind/DEBIAN/copyright @@ -0,0 +1,21 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: basecoind +Source: https://github.com/cosmos/cosmos-sdk + +Files: * +Copyright: 2017 All In Bits, Inc. +License: Apache-2.0 + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + . + http://www.apache.org/licenses/LICENSE-2.0 + . + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + . + On Debian systems, the full text of the Apache License 2.0 can be found + in the file `/usr/share/common-licenses/Apache-2.0'. diff --git a/vendor/github.com/tendermint/tendermint/tools/build/ethermint/DEBIAN/copyright b/vendor/github.com/tendermint/tendermint/tools/build/ethermint/DEBIAN/copyright new file mode 100644 index 000000000..6d1bab01b --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/tools/build/ethermint/DEBIAN/copyright @@ -0,0 +1,21 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: ethermint +Source: https://github.com/tendermint/ethermint + +Files: * +Copyright: 2017 All In Bits, Inc. +License: Apache-2.0 + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + . + http://www.apache.org/licenses/LICENSE-2.0 + . + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + . + On Debian systems, the full text of the Apache License 2.0 can be found + in the file `/usr/share/common-licenses/Apache-2.0'. diff --git a/vendor/github.com/tendermint/tendermint/tools/build/gaia/DEBIAN/copyright b/vendor/github.com/tendermint/tendermint/tools/build/gaia/DEBIAN/copyright new file mode 100644 index 000000000..ffc230134 --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/tools/build/gaia/DEBIAN/copyright @@ -0,0 +1,21 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: gaia +Source: https://github.com/cosmos/gaia + +Files: * +Copyright: 2017 All In Bits, Inc. +License: Apache-2.0 + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + . + http://www.apache.org/licenses/LICENSE-2.0 + . + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + . + On Debian systems, the full text of the Apache License 2.0 can be found + in the file `/usr/share/common-licenses/Apache-2.0'. diff --git a/vendor/github.com/tendermint/tendermint/tools/build/tendermint/DEBIAN/copyright b/vendor/github.com/tendermint/tendermint/tools/build/tendermint/DEBIAN/copyright new file mode 100644 index 000000000..15ee960dd --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/tools/build/tendermint/DEBIAN/copyright @@ -0,0 +1,21 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: tendermint +Source: https://github.com/tendermint/tendermint + +Files: * +Copyright: 2017 All In Bits, Inc. +License: Apache-2.0 + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + . + http://www.apache.org/licenses/LICENSE-2.0 + . + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + . + On Debian systems, the full text of the Apache License 2.0 can be found + in the file `/usr/share/common-licenses/Apache-2.0'. diff --git a/vendor/github.com/tendermint/tmlibs/LICENSE b/vendor/github.com/tendermint/tendermint/tools/mintnet-kubernetes/LICENSE similarity index 99% rename from vendor/github.com/tendermint/tmlibs/LICENSE rename to vendor/github.com/tendermint/tendermint/tools/mintnet-kubernetes/LICENSE index 06bc5e1c6..64a33ddf1 100644 --- a/vendor/github.com/tendermint/tmlibs/LICENSE +++ b/vendor/github.com/tendermint/tendermint/tools/mintnet-kubernetes/LICENSE @@ -1,4 +1,3 @@ -Tendermint Libraries Copyright (C) 2017 Tendermint diff --git a/vendor/github.com/tendermint/go-crypto/LICENSE b/vendor/github.com/tendermint/tendermint/tools/tm-bench/LICENSE similarity index 93% rename from vendor/github.com/tendermint/go-crypto/LICENSE rename to vendor/github.com/tendermint/tendermint/tools/tm-bench/LICENSE index 3beb77b13..f48913967 100644 --- a/vendor/github.com/tendermint/go-crypto/LICENSE +++ b/vendor/github.com/tendermint/tendermint/tools/tm-bench/LICENSE @@ -1,11 +1,9 @@ -Tendermint Go-Crypto -Copyright (C) 2015 Tendermint - - +Tendermint Bench +Copyright 2017 Tendermint Apache License Version 2.0, January 2004 - https://www.apache.org/licenses/ + http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION @@ -180,11 +178,24 @@ Copyright (C) 2015 Tendermint END OF TERMS AND CONDITIONS + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - https://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, diff --git a/vendor/github.com/tendermint/tendermint/tools/tm-monitor/LICENSE b/vendor/github.com/tendermint/tendermint/tools/tm-monitor/LICENSE new file mode 100644 index 000000000..20728d318 --- /dev/null +++ b/vendor/github.com/tendermint/tendermint/tools/tm-monitor/LICENSE @@ -0,0 +1,204 @@ +Tendermint Monitor +Copyright 2017 Tendermint + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/tendermint/tendermint/types/block.go b/vendor/github.com/tendermint/tendermint/types/block.go index 3004672c8..e23fd71d9 100644 --- a/vendor/github.com/tendermint/tendermint/types/block.go +++ b/vendor/github.com/tendermint/tendermint/types/block.go @@ -8,9 +8,9 @@ import ( "sync" "time" - cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/merkle" - "golang.org/x/crypto/ripemd160" + "github.com/tendermint/tendermint/crypto/merkle" + "github.com/tendermint/tendermint/crypto/tmhash" + cmn "github.com/tendermint/tendermint/libs/common" ) // Block defines the atomic unit of a Tendermint blockchain. @@ -107,6 +107,7 @@ func (b *Block) Hash() cmn.HexBytes { // MakePartSet returns a PartSet containing parts of a serialized block. // This is the form in which the block is gossipped to peers. +// CONTRACT: partSize is greater than zero. func (b *Block) MakePartSet(partSize int) *PartSet { if b == nil { return nil @@ -135,6 +136,15 @@ func (b *Block) HashesTo(hash []byte) bool { return bytes.Equal(b.Hash(), hash) } +// Size returns size of the block in bytes. +func (b *Block) Size() int { + bz, err := cdc.MarshalBinaryBare(b) + if err != nil { + return 0 + } + return len(bz) +} + // String returns a string representation of the block func (b *Block) String() string { return b.StringIndented("") @@ -199,7 +209,7 @@ type Header struct { // Hash returns the hash of the header. // Returns nil if ValidatorHash is missing, // since a Header is not valid unless there is -// a ValidaotrsHash (corresponding to the validator set). +// a ValidatorsHash (corresponding to the validator set). func (h *Header) Hash() cmn.HexBytes { if h == nil || len(h.ValidatorsHash) == 0 { return nil @@ -383,6 +393,9 @@ func (commit *Commit) ValidateBasic() error { // Hash returns the hash of the commit func (commit *Commit) Hash() cmn.HexBytes { + if commit == nil { + return nil + } if commit.hash == nil { bs := make([]merkle.Hasher, len(commit.Precommits)) for i, precommit := range commit.Precommits { @@ -455,7 +468,7 @@ func (data *Data) StringIndented(indent string) string { txStrings[i] = fmt.Sprintf("... (%v total)", len(data.Txs)) break } - txStrings[i] = fmt.Sprintf("Tx:%v", tx) + txStrings[i] = fmt.Sprintf("%X (%d bytes)", tx.Hash(), len(tx)) } return fmt.Sprintf(`Data{ %s %v @@ -495,7 +508,7 @@ func (data *EvidenceData) StringIndented(indent string) string { } evStrings[i] = fmt.Sprintf("Evidence:%v", ev) } - return fmt.Sprintf(`Data{ + return fmt.Sprintf(`EvidenceData{ %s %v %s}#%v`, indent, strings.Join(evStrings, "\n"+indent+" "), @@ -543,7 +556,7 @@ type hasher struct { } func (h hasher) Hash() []byte { - hasher := ripemd160.New() + hasher := tmhash.New() if h.item != nil && !cmn.IsTypedNil(h.item) && !cmn.IsEmpty(h.item) { bz, err := cdc.MarshalBinaryBare(h.item) if err != nil { diff --git a/vendor/github.com/tendermint/tendermint/types/canonical_json.go b/vendor/github.com/tendermint/tendermint/types/canonical_json.go index 95ade9c67..189a8a7a2 100644 --- a/vendor/github.com/tendermint/tendermint/types/canonical_json.go +++ b/vendor/github.com/tendermint/tendermint/types/canonical_json.go @@ -3,14 +3,13 @@ package types import ( "time" - "github.com/tendermint/go-amino" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) // Canonical json is amino's json for structs with fields in alphabetical order // TimeFormat is used for generating the sigs -const TimeFormat = amino.RFC3339Millis +const TimeFormat = "2006-01-02T15:04:05.000Z" type CanonicalJSONBlockID struct { Hash cmn.HexBytes `json:"hash,omitempty"` diff --git a/vendor/github.com/tendermint/tendermint/types/event_buffer.go b/vendor/github.com/tendermint/tendermint/types/event_buffer.go deleted file mode 100644 index 18b41014e..000000000 --- a/vendor/github.com/tendermint/tendermint/types/event_buffer.go +++ /dev/null @@ -1,50 +0,0 @@ -package types - -// Interface assertions -var _ TxEventPublisher = (*TxEventBuffer)(nil) - -// TxEventBuffer is a buffer of events, which uses a slice to temporarily store -// events. -type TxEventBuffer struct { - next TxEventPublisher - capacity int - events []EventDataTx -} - -// NewTxEventBuffer accepts a TxEventPublisher and returns a new buffer with the given -// capacity. -func NewTxEventBuffer(next TxEventPublisher, capacity int) *TxEventBuffer { - return &TxEventBuffer{ - next: next, - capacity: capacity, - events: make([]EventDataTx, 0, capacity), - } -} - -// Len returns the number of events cached. -func (b TxEventBuffer) Len() int { - return len(b.events) -} - -// PublishEventTx buffers an event to be fired upon finality. -func (b *TxEventBuffer) PublishEventTx(e EventDataTx) error { - b.events = append(b.events, e) - return nil -} - -// Flush publishes events by running next.PublishWithTags on all cached events. -// Blocks. Clears cached events. -func (b *TxEventBuffer) Flush() error { - for _, e := range b.events { - err := b.next.PublishEventTx(e) - if err != nil { - return err - } - } - - // Clear out the elements and set the length to 0 - // but maintain the underlying slice's capacity. - // See Issue https://github.com/tendermint/tendermint/issues/1189 - b.events = b.events[:0] - return nil -} diff --git a/vendor/github.com/tendermint/tendermint/types/event_bus.go b/vendor/github.com/tendermint/tendermint/types/event_bus.go index cb4b17d51..b4965feee 100644 --- a/vendor/github.com/tendermint/tendermint/types/event_bus.go +++ b/vendor/github.com/tendermint/tendermint/types/event_bus.go @@ -4,9 +4,9 @@ import ( "context" "fmt" + cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/log" tmpubsub "github.com/tendermint/tendermint/libs/pubsub" - cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/log" ) const defaultCapacity = 0 @@ -49,7 +49,7 @@ func (b *EventBus) OnStart() error { } func (b *EventBus) OnStop() { - b.pubsub.OnStop() + b.pubsub.Stop() } func (b *EventBus) Subscribe(ctx context.Context, subscriber string, query tmpubsub.Query, out chan<- interface{}) error { diff --git a/vendor/github.com/tendermint/tendermint/types/events.go b/vendor/github.com/tendermint/tendermint/types/events.go index 2b87297cd..891c6a902 100644 --- a/vendor/github.com/tendermint/tendermint/types/events.go +++ b/vendor/github.com/tendermint/tendermint/types/events.go @@ -10,22 +10,17 @@ import ( // Reserved event types const ( - EventBond = "Bond" EventCompleteProposal = "CompleteProposal" - EventDupeout = "Dupeout" - EventFork = "Fork" EventLock = "Lock" EventNewBlock = "NewBlock" EventNewBlockHeader = "NewBlockHeader" EventNewRound = "NewRound" EventNewRoundStep = "NewRoundStep" EventPolka = "Polka" - EventRebond = "Rebond" EventRelock = "Relock" EventTimeoutPropose = "TimeoutPropose" EventTimeoutWait = "TimeoutWait" EventTx = "Tx" - EventUnbond = "Unbond" EventUnlock = "Unlock" EventVote = "Vote" EventProposalHeartbeat = "ProposalHeartbeat" @@ -113,11 +108,6 @@ const ( ) var ( - EventQueryBond = QueryForEvent(EventBond) - EventQueryUnbond = QueryForEvent(EventUnbond) - EventQueryRebond = QueryForEvent(EventRebond) - EventQueryDupeout = QueryForEvent(EventDupeout) - EventQueryFork = QueryForEvent(EventFork) EventQueryNewBlock = QueryForEvent(EventNewBlock) EventQueryNewBlockHeader = QueryForEvent(EventNewBlockHeader) EventQueryNewRound = QueryForEvent(EventNewRound) diff --git a/vendor/github.com/tendermint/tendermint/types/evidence.go b/vendor/github.com/tendermint/tendermint/types/evidence.go index 10907869e..6313f43a5 100644 --- a/vendor/github.com/tendermint/tendermint/types/evidence.go +++ b/vendor/github.com/tendermint/tendermint/types/evidence.go @@ -4,9 +4,10 @@ import ( "bytes" "fmt" - "github.com/tendermint/go-amino" - "github.com/tendermint/go-crypto" - "github.com/tendermint/tmlibs/merkle" + amino "github.com/tendermint/go-amino" + + "github.com/tendermint/tendermint/crypto" + "github.com/tendermint/tendermint/crypto/merkle" ) // ErrEvidenceInvalid wraps a piece of evidence and the error denoting how or why it is invalid. @@ -180,7 +181,7 @@ type EvidenceList []Evidence // Hash returns the simple merkle root hash of the EvidenceList. func (evl EvidenceList) Hash() []byte { // Recursive impl. - // Copied from tmlibs/merkle to avoid allocations + // Copied from crypto/merkle to avoid allocations switch len(evl) { case 0: return nil diff --git a/vendor/github.com/tendermint/tendermint/types/genesis.go b/vendor/github.com/tendermint/tendermint/types/genesis.go index aee8e0767..220ee0e0e 100644 --- a/vendor/github.com/tendermint/tendermint/types/genesis.go +++ b/vendor/github.com/tendermint/tendermint/types/genesis.go @@ -5,8 +5,8 @@ import ( "io/ioutil" "time" - "github.com/tendermint/go-crypto" - cmn "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tendermint/crypto" + cmn "github.com/tendermint/tendermint/libs/common" ) //------------------------------------------------------------ @@ -26,17 +26,7 @@ type GenesisDoc struct { ConsensusParams *ConsensusParams `json:"consensus_params,omitempty"` Validators []GenesisValidator `json:"validators"` AppHash cmn.HexBytes `json:"app_hash"` - AppStateJSON json.RawMessage `json:"app_state,omitempty"` - AppOptions json.RawMessage `json:"app_options,omitempty"` // DEPRECATED -} - -// AppState returns raw application state. -// TODO: replace with AppState field during next breaking release (0.18) -func (genDoc *GenesisDoc) AppState() json.RawMessage { - if len(genDoc.AppOptions) > 0 { - return genDoc.AppOptions - } - return genDoc.AppStateJSON + AppState json.RawMessage `json:"app_state,omitempty"` } // SaveAs is a utility method for saving GenensisDoc as a JSON file. diff --git a/vendor/github.com/tendermint/tendermint/types/heartbeat.go b/vendor/github.com/tendermint/tendermint/types/heartbeat.go index 097dd22db..cebe2864c 100644 --- a/vendor/github.com/tendermint/tendermint/types/heartbeat.go +++ b/vendor/github.com/tendermint/tendermint/types/heartbeat.go @@ -3,8 +3,8 @@ package types import ( "fmt" - "github.com/tendermint/go-crypto" - cmn "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tendermint/crypto" + cmn "github.com/tendermint/tendermint/libs/common" ) // Heartbeat is a simple vote-like structure so validators can diff --git a/vendor/github.com/tendermint/tendermint/types/params.go b/vendor/github.com/tendermint/tendermint/types/params.go index 2df092d62..3056c82a0 100644 --- a/vendor/github.com/tendermint/tendermint/types/params.go +++ b/vendor/github.com/tendermint/tendermint/types/params.go @@ -1,12 +1,13 @@ package types import ( - abci "github.com/tendermint/abci/types" - cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/merkle" + abci "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/crypto/merkle" + cmn "github.com/tendermint/tendermint/libs/common" ) const ( + // MaxBlockSizeBytes is the maximum permitted size of the blocks. MaxBlockSizeBytes = 104857600 // 100MB ) @@ -56,7 +57,7 @@ func DefaultConsensusParams() *ConsensusParams { func DefaultBlockSize() BlockSize { return BlockSize{ MaxBytes: 22020096, // 21MB - MaxTxs: 100000, + MaxTxs: 10000, MaxGas: -1, } } diff --git a/vendor/github.com/tendermint/tendermint/types/part_set.go b/vendor/github.com/tendermint/tendermint/types/part_set.go index 18cfe802c..f6d7f6b6e 100644 --- a/vendor/github.com/tendermint/tendermint/types/part_set.go +++ b/vendor/github.com/tendermint/tendermint/types/part_set.go @@ -7,10 +7,9 @@ import ( "io" "sync" - "golang.org/x/crypto/ripemd160" - - cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/merkle" + "github.com/tendermint/tendermint/crypto/merkle" + "github.com/tendermint/tendermint/crypto/tmhash" + cmn "github.com/tendermint/tendermint/libs/common" ) var ( @@ -31,7 +30,7 @@ func (part *Part) Hash() []byte { if part.hash != nil { return part.hash } - hasher := ripemd160.New() + hasher := tmhash.New() hasher.Write(part.Bytes) // nolint: errcheck, gas part.hash = hasher.Sum(nil) return part.hash diff --git a/vendor/github.com/tendermint/tendermint/types/priv_validator.go b/vendor/github.com/tendermint/tendermint/types/priv_validator.go index 8759d3f99..85db65a41 100644 --- a/vendor/github.com/tendermint/tendermint/types/priv_validator.go +++ b/vendor/github.com/tendermint/tendermint/types/priv_validator.go @@ -4,7 +4,7 @@ import ( "bytes" "fmt" - "github.com/tendermint/go-crypto" + "github.com/tendermint/tendermint/crypto" ) // PrivValidator defines the functionality of a local Tendermint validator @@ -63,7 +63,10 @@ func (pv *MockPV) GetPubKey() crypto.PubKey { // Implements PrivValidator. func (pv *MockPV) SignVote(chainID string, vote *Vote) error { signBytes := vote.SignBytes(chainID) - sig := pv.privKey.Sign(signBytes) + sig, err := pv.privKey.Sign(signBytes) + if err != nil { + return err + } vote.Signature = sig return nil } @@ -71,14 +74,20 @@ func (pv *MockPV) SignVote(chainID string, vote *Vote) error { // Implements PrivValidator. func (pv *MockPV) SignProposal(chainID string, proposal *Proposal) error { signBytes := proposal.SignBytes(chainID) - sig := pv.privKey.Sign(signBytes) + sig, err := pv.privKey.Sign(signBytes) + if err != nil { + return err + } proposal.Signature = sig return nil } // signHeartbeat signs the heartbeat without any checking. func (pv *MockPV) SignHeartbeat(chainID string, heartbeat *Heartbeat) error { - sig := pv.privKey.Sign(heartbeat.SignBytes(chainID)) + sig, err := pv.privKey.Sign(heartbeat.SignBytes(chainID)) + if err != nil { + return err + } heartbeat.Signature = sig return nil } diff --git a/vendor/github.com/tendermint/tendermint/types/proposal.go b/vendor/github.com/tendermint/tendermint/types/proposal.go index 95008897b..52ce8756e 100644 --- a/vendor/github.com/tendermint/tendermint/types/proposal.go +++ b/vendor/github.com/tendermint/tendermint/types/proposal.go @@ -5,7 +5,7 @@ import ( "fmt" "time" - "github.com/tendermint/go-crypto" + "github.com/tendermint/tendermint/crypto" ) var ( diff --git a/vendor/github.com/tendermint/tendermint/types/protobuf.go b/vendor/github.com/tendermint/tendermint/types/protobuf.go index eb684ae7d..4fe448253 100644 --- a/vendor/github.com/tendermint/tendermint/types/protobuf.go +++ b/vendor/github.com/tendermint/tendermint/types/protobuf.go @@ -6,8 +6,8 @@ import ( "reflect" "time" - abci "github.com/tendermint/abci/types" - crypto "github.com/tendermint/go-crypto" + abci "github.com/tendermint/tendermint/abci/types" + crypto "github.com/tendermint/tendermint/crypto" ) //------------------------------------------------------- @@ -58,7 +58,7 @@ func (tm2pb) Validator(val *Validator) abci.Validator { } // XXX: panics on nil or unknown pubkey type -// TODO: add cases when new pubkey types are added to go-crypto +// TODO: add cases when new pubkey types are added to crypto func (tm2pb) PubKey(pubKey crypto.PubKey) abci.PubKey { switch pk := pubKey.(type) { case crypto.PubKeyEd25519: @@ -78,7 +78,7 @@ func (tm2pb) PubKey(pubKey crypto.PubKey) abci.PubKey { // XXX: panics on nil or unknown pubkey type func (tm2pb) Validators(vals *ValidatorSet) []abci.Validator { - validators := make([]abci.Validator, len(vals.Validators)) + validators := make([]abci.Validator, vals.Size()) for i, val := range vals.Validators { validators[i] = TM2PB.Validator(val) } @@ -153,7 +153,7 @@ var PB2TM = pb2tm{} type pb2tm struct{} func (pb2tm) PubKey(pubKey abci.PubKey) (crypto.PubKey, error) { - // TODO: define these in go-crypto and use them + // TODO: define these in crypto and use them sizeEd := 32 sizeSecp := 33 switch pubKey.Type { diff --git a/vendor/github.com/tendermint/tendermint/types/results.go b/vendor/github.com/tendermint/tendermint/types/results.go index 326cee48d..17d5891c3 100644 --- a/vendor/github.com/tendermint/tendermint/types/results.go +++ b/vendor/github.com/tendermint/tendermint/types/results.go @@ -1,9 +1,9 @@ package types import ( - abci "github.com/tendermint/abci/types" - cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/merkle" + abci "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/crypto/merkle" + cmn "github.com/tendermint/tendermint/libs/common" ) //----------------------------------------------------------------------------- @@ -24,15 +24,16 @@ func (a ABCIResult) Hash() []byte { // ABCIResults wraps the deliver tx results to return a proof type ABCIResults []ABCIResult -// NewResults creates ABCIResults from ResponseDeliverTx -func NewResults(del []*abci.ResponseDeliverTx) ABCIResults { - res := make(ABCIResults, len(del)) - for i, d := range del { +// NewResults creates ABCIResults from the list of ResponseDeliverTx. +func NewResults(responses []*abci.ResponseDeliverTx) ABCIResults { + res := make(ABCIResults, len(responses)) + for i, d := range responses { res[i] = NewResultFromResponse(d) } return res } +// NewResultFromResponse creates ABCIResult from ResponseDeliverTx. func NewResultFromResponse(response *abci.ResponseDeliverTx) ABCIResult { return ABCIResult{ Code: response.Code, @@ -51,6 +52,8 @@ func (a ABCIResults) Bytes() []byte { // Hash returns a merkle hash of all results func (a ABCIResults) Hash() []byte { + // NOTE: we copy the impl of the merkle tree for txs - + // we should be consistent and either do it for both or not. return merkle.SimpleHashFromHashers(a.toHashers()) } diff --git a/vendor/github.com/tendermint/tendermint/types/tx.go b/vendor/github.com/tendermint/tendermint/types/tx.go index e7247693a..489f0b232 100644 --- a/vendor/github.com/tendermint/tendermint/types/tx.go +++ b/vendor/github.com/tendermint/tendermint/types/tx.go @@ -5,20 +5,20 @@ import ( "errors" "fmt" - abci "github.com/tendermint/abci/types" - cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/merkle" + abci "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/crypto/merkle" + "github.com/tendermint/tendermint/crypto/tmhash" + cmn "github.com/tendermint/tendermint/libs/common" ) // Tx is an arbitrary byte array. // NOTE: Tx has no types at this level, so when wire encoded it's just length-prefixed. -// Alternatively, it may make sense to add types here and let -// []byte be type 0x1 so we can have versioned txs if need be in the future. +// Might we want types here ? type Tx []byte -// Hash computes the RIPEMD160 hash of the wire encoded transaction. +// Hash computes the TMHASH hash of the wire encoded transaction. func (tx Tx) Hash() []byte { - return aminoHasher(tx).Hash() + return tmhash.Sum(tx) } // String returns the hex-encoded transaction as a string. @@ -32,7 +32,7 @@ type Txs []Tx // Hash returns the simple Merkle root hash of the transactions. func (txs Txs) Hash() []byte { // Recursive impl. - // Copied from tmlibs/merkle to avoid allocations + // Copied from tendermint/crypto/merkle to avoid allocations switch len(txs) { case 0: return nil diff --git a/vendor/github.com/tendermint/tendermint/types/validator.go b/vendor/github.com/tendermint/tendermint/types/validator.go index 46dc61d07..e43acf09d 100644 --- a/vendor/github.com/tendermint/tendermint/types/validator.go +++ b/vendor/github.com/tendermint/tendermint/types/validator.go @@ -4,8 +4,8 @@ import ( "bytes" "fmt" - "github.com/tendermint/go-crypto" - cmn "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tendermint/crypto" + cmn "github.com/tendermint/tendermint/libs/common" ) // Volatile state for each Validator diff --git a/vendor/github.com/tendermint/tendermint/types/validator_set.go b/vendor/github.com/tendermint/tendermint/types/validator_set.go index f2fac2929..60fc2d83b 100644 --- a/vendor/github.com/tendermint/tendermint/types/validator_set.go +++ b/vendor/github.com/tendermint/tendermint/types/validator_set.go @@ -7,8 +7,8 @@ import ( "sort" "strings" - cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/merkle" + "github.com/tendermint/tendermint/crypto/merkle" + cmn "github.com/tendermint/tendermint/libs/common" ) // ValidatorSet represent a set of *Validator at a given height. @@ -39,14 +39,15 @@ func NewValidatorSet(vals []*Validator) *ValidatorSet { Validators: validators, } - if vals != nil { + if len(vals) > 0 { vs.IncrementAccum(1) } return vs } -// incrementAccum and update the proposer +// IncrementAccum increments accum of each validator and updates the +// proposer. Panics if validator set is empty. func (valSet *ValidatorSet) IncrementAccum(times int) { // Add VotingPower * times to each validator and order into heap. validatorsHeap := cmn.NewHeap() diff --git a/vendor/github.com/tendermint/tendermint/types/vote.go b/vendor/github.com/tendermint/tendermint/types/vote.go index e4ead612a..ed4ebd73e 100644 --- a/vendor/github.com/tendermint/tendermint/types/vote.go +++ b/vendor/github.com/tendermint/tendermint/types/vote.go @@ -6,8 +6,8 @@ import ( "fmt" "time" - crypto "github.com/tendermint/go-crypto" - cmn "github.com/tendermint/tmlibs/common" + crypto "github.com/tendermint/tendermint/crypto" + cmn "github.com/tendermint/tendermint/libs/common" ) var ( diff --git a/vendor/github.com/tendermint/tendermint/types/vote_set.go b/vendor/github.com/tendermint/tendermint/types/vote_set.go index a60d95daf..c51681053 100644 --- a/vendor/github.com/tendermint/tendermint/types/vote_set.go +++ b/vendor/github.com/tendermint/tendermint/types/vote_set.go @@ -8,7 +8,7 @@ import ( "github.com/pkg/errors" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) // UNSTABLE diff --git a/vendor/github.com/tendermint/tendermint/types/wire.go b/vendor/github.com/tendermint/tendermint/types/wire.go index bd5c4497d..6342d7eba 100644 --- a/vendor/github.com/tendermint/tendermint/types/wire.go +++ b/vendor/github.com/tendermint/tendermint/types/wire.go @@ -2,7 +2,7 @@ package types import ( "github.com/tendermint/go-amino" - "github.com/tendermint/go-crypto" + "github.com/tendermint/tendermint/crypto" ) var cdc = amino.NewCodec() diff --git a/vendor/github.com/tendermint/tendermint/version/version.go b/vendor/github.com/tendermint/tendermint/version/version.go index df553115a..165f25829 100644 --- a/vendor/github.com/tendermint/tendermint/version/version.go +++ b/vendor/github.com/tendermint/tendermint/version/version.go @@ -3,14 +3,14 @@ package version // Version components const ( Maj = "0" - Min = "21" - Fix = "0" + Min = "22" + Fix = "4" ) var ( // Version is the current version of Tendermint // Must be a string because scripts like dist.sh read this file. - Version = "0.21.0" + Version = "0.22.4" // GitCommit is the current HEAD set using ldflags. GitCommit string diff --git a/vendor/github.com/tendermint/tmlibs/common/array.go b/vendor/github.com/tendermint/tmlibs/common/array.go deleted file mode 100644 index adedc42be..000000000 --- a/vendor/github.com/tendermint/tmlibs/common/array.go +++ /dev/null @@ -1,5 +0,0 @@ -package common - -func Arr(items ...interface{}) []interface{} { - return items -} diff --git a/vendor/github.com/tendermint/tmlibs/merkle/simple_tree.go b/vendor/github.com/tendermint/tmlibs/merkle/simple_tree.go deleted file mode 100644 index 9bdf52cb2..000000000 --- a/vendor/github.com/tendermint/tmlibs/merkle/simple_tree.go +++ /dev/null @@ -1,91 +0,0 @@ -/* -Computes a deterministic minimal height merkle tree hash. -If the number of items is not a power of two, some leaves -will be at different levels. Tries to keep both sides of -the tree the same size, but the left may be one greater. - -Use this for short deterministic trees, such as the validator list. -For larger datasets, use IAVLTree. - - * - / \ - / \ - / \ - / \ - * * - / \ / \ - / \ / \ - / \ / \ - * * * h6 - / \ / \ / \ - h0 h1 h2 h3 h4 h5 - -*/ - -package merkle - -import ( - "golang.org/x/crypto/ripemd160" -) - -func SimpleHashFromTwoHashes(left []byte, right []byte) []byte { - var hasher = ripemd160.New() - err := encodeByteSlice(hasher, left) - if err != nil { - panic(err) - } - err = encodeByteSlice(hasher, right) - if err != nil { - panic(err) - } - return hasher.Sum(nil) -} - -func SimpleHashFromHashes(hashes [][]byte) []byte { - // Recursive impl. - switch len(hashes) { - case 0: - return nil - case 1: - return hashes[0] - default: - left := SimpleHashFromHashes(hashes[:(len(hashes)+1)/2]) - right := SimpleHashFromHashes(hashes[(len(hashes)+1)/2:]) - return SimpleHashFromTwoHashes(left, right) - } -} - -// NOTE: Do not implement this, use SimpleHashFromByteslices instead. -// type Byteser interface { Bytes() []byte } -// func SimpleHashFromBytesers(items []Byteser) []byte { ... } - -func SimpleHashFromByteslices(bzs [][]byte) []byte { - hashes := make([][]byte, len(bzs)) - for i, bz := range bzs { - hashes[i] = SimpleHashFromBytes(bz) - } - return SimpleHashFromHashes(hashes) -} - -func SimpleHashFromBytes(bz []byte) []byte { - hasher := ripemd160.New() - hasher.Write(bz) - return hasher.Sum(nil) -} - -func SimpleHashFromHashers(items []Hasher) []byte { - hashes := make([][]byte, len(items)) - for i, item := range items { - hash := item.Hash() - hashes[i] = hash - } - return SimpleHashFromHashes(hashes) -} - -func SimpleHashFromMap(m map[string]Hasher) []byte { - sm := NewSimpleMap() - for k, v := range m { - sm.Set(k, v) - } - return sm.Hash() -} diff --git a/vendor/golang.org/x/net/http2/client_conn_pool.go b/vendor/golang.org/x/net/http2/client_conn_pool.go index bdf5652b0..f4d9b5ece 100644 --- a/vendor/golang.org/x/net/http2/client_conn_pool.go +++ b/vendor/golang.org/x/net/http2/client_conn_pool.go @@ -52,9 +52,31 @@ const ( noDialOnMiss = false ) +// shouldTraceGetConn reports whether getClientConn should call any +// ClientTrace.GetConn hook associated with the http.Request. +// +// This complexity is needed to avoid double calls of the GetConn hook +// during the back-and-forth between net/http and x/net/http2 (when the +// net/http.Transport is upgraded to also speak http2), as well as support +// the case where x/net/http2 is being used directly. +func (p *clientConnPool) shouldTraceGetConn(st clientConnIdleState) bool { + // If our Transport wasn't made via ConfigureTransport, always + // trace the GetConn hook if provided, because that means the + // http2 package is being used directly and it's the one + // dialing, as opposed to net/http. + if _, ok := p.t.ConnPool.(noDialClientConnPool); !ok { + return true + } + // Otherwise, only use the GetConn hook if this connection has + // been used previously for other requests. For fresh + // connections, the net/http package does the dialing. + return !st.freshConn +} + func (p *clientConnPool) getClientConn(req *http.Request, addr string, dialOnMiss bool) (*ClientConn, error) { if isConnectionCloseRequest(req) && dialOnMiss { // It gets its own connection. + traceGetConn(req, addr) const singleUse = true cc, err := p.t.dialClientConn(addr, singleUse) if err != nil { @@ -64,7 +86,10 @@ func (p *clientConnPool) getClientConn(req *http.Request, addr string, dialOnMis } p.mu.Lock() for _, cc := range p.conns[addr] { - if cc.CanTakeNewRequest() { + if st := cc.idleState(); st.canTakeNewRequest { + if p.shouldTraceGetConn(st) { + traceGetConn(req, addr) + } p.mu.Unlock() return cc, nil } @@ -73,6 +98,7 @@ func (p *clientConnPool) getClientConn(req *http.Request, addr string, dialOnMis p.mu.Unlock() return nil, ErrNoCachedConn } + traceGetConn(req, addr) call := p.getStartDialLocked(addr) p.mu.Unlock() <-call.done diff --git a/vendor/golang.org/x/net/http2/go111.go b/vendor/golang.org/x/net/http2/go111.go new file mode 100644 index 000000000..e38ea2903 --- /dev/null +++ b/vendor/golang.org/x/net/http2/go111.go @@ -0,0 +1,17 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build go1.11 + +package http2 + +func traceHasWroteHeaderField(trace *clientTrace) bool { + return trace != nil && trace.WroteHeaderField != nil +} + +func traceWroteHeaderField(trace *clientTrace, k, v string) { + if trace != nil && trace.WroteHeaderField != nil { + trace.WroteHeaderField(k, []string{v}) + } +} diff --git a/vendor/golang.org/x/net/http2/go17.go b/vendor/golang.org/x/net/http2/go17.go index 47b7fae08..d957b7bc5 100644 --- a/vendor/golang.org/x/net/http2/go17.go +++ b/vendor/golang.org/x/net/http2/go17.go @@ -18,6 +18,8 @@ type contextContext interface { context.Context } +var errCanceled = context.Canceled + func serverConnBaseContext(c net.Conn, opts *ServeConnOpts) (ctx contextContext, cancel func()) { ctx, cancel = context.WithCancel(context.Background()) ctx = context.WithValue(ctx, http.LocalAddrContextKey, c.LocalAddr()) @@ -48,6 +50,14 @@ func (t *Transport) idleConnTimeout() time.Duration { func setResponseUncompressed(res *http.Response) { res.Uncompressed = true } +func traceGetConn(req *http.Request, hostPort string) { + trace := httptrace.ContextClientTrace(req.Context()) + if trace == nil || trace.GetConn == nil { + return + } + trace.GetConn(hostPort) +} + func traceGotConn(req *http.Request, cc *ClientConn) { trace := httptrace.ContextClientTrace(req.Context()) if trace == nil || trace.GotConn == nil { @@ -104,3 +114,8 @@ func requestTrace(req *http.Request) *clientTrace { func (cc *ClientConn) Ping(ctx context.Context) error { return cc.ping(ctx) } + +// Shutdown gracefully closes the client connection, waiting for running streams to complete. +func (cc *ClientConn) Shutdown(ctx context.Context) error { + return cc.shutdown(ctx) +} diff --git a/vendor/golang.org/x/net/http2/not_go111.go b/vendor/golang.org/x/net/http2/not_go111.go new file mode 100644 index 000000000..d036b013f --- /dev/null +++ b/vendor/golang.org/x/net/http2/not_go111.go @@ -0,0 +1,11 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !go1.11 + +package http2 + +func traceHasWroteHeaderField(trace *clientTrace) bool { return false } + +func traceWroteHeaderField(trace *clientTrace, k, v string) {} diff --git a/vendor/golang.org/x/net/http2/not_go17.go b/vendor/golang.org/x/net/http2/not_go17.go index 140434a79..7ffb25046 100644 --- a/vendor/golang.org/x/net/http2/not_go17.go +++ b/vendor/golang.org/x/net/http2/not_go17.go @@ -8,6 +8,7 @@ package http2 import ( "crypto/tls" + "errors" "net" "net/http" "time" @@ -18,6 +19,8 @@ type contextContext interface { Err() error } +var errCanceled = errors.New("canceled") + type fakeContext struct{} func (fakeContext) Done() <-chan struct{} { return nil } @@ -34,6 +37,7 @@ func setResponseUncompressed(res *http.Response) { type clientTrace struct{} func requestTrace(*http.Request) *clientTrace { return nil } +func traceGetConn(*http.Request, string) {} func traceGotConn(*http.Request, *ClientConn) {} func traceFirstResponseByte(*clientTrace) {} func traceWroteHeaders(*clientTrace) {} @@ -84,4 +88,8 @@ func (cc *ClientConn) Ping(ctx contextContext) error { return cc.ping(ctx) } +func (cc *ClientConn) Shutdown(ctx contextContext) error { + return cc.shutdown(ctx) +} + func (t *Transport) idleConnTimeout() time.Duration { return 0 } diff --git a/vendor/golang.org/x/net/http2/server.go b/vendor/golang.org/x/net/http2/server.go index 793899169..e111019d5 100644 --- a/vendor/golang.org/x/net/http2/server.go +++ b/vendor/golang.org/x/net/http2/server.go @@ -1721,6 +1721,13 @@ func (sc *serverConn) processHeaders(f *MetaHeadersFrame) error { // processing this frame. return nil } + // RFC 7540, sec 5.1: If an endpoint receives additional frames, other than + // WINDOW_UPDATE, PRIORITY, or RST_STREAM, for a stream that is in + // this state, it MUST respond with a stream error (Section 5.4.2) of + // type STREAM_CLOSED. + if st.state == stateHalfClosedRemote { + return streamError(id, ErrCodeStreamClosed) + } return st.processTrailerHeaders(f) } diff --git a/vendor/golang.org/x/net/http2/transport.go b/vendor/golang.org/x/net/http2/transport.go index d23a22625..300b02fe7 100644 --- a/vendor/golang.org/x/net/http2/transport.go +++ b/vendor/golang.org/x/net/http2/transport.go @@ -159,6 +159,7 @@ type ClientConn struct { cond *sync.Cond // hold mu; broadcast on flow/closed changes flow flow // our conn-level flow control quota (cs.flow is per stream) inflow flow // peer's conn-level flow control + closing bool closed bool wantSettingsAck bool // we sent a SETTINGS frame and haven't heard back goAway *GoAwayFrame // if non-nil, the GoAwayFrame we received @@ -630,12 +631,32 @@ func (cc *ClientConn) CanTakeNewRequest() bool { return cc.canTakeNewRequestLocked() } -func (cc *ClientConn) canTakeNewRequestLocked() bool { +// clientConnIdleState describes the suitability of a client +// connection to initiate a new RoundTrip request. +type clientConnIdleState struct { + canTakeNewRequest bool + freshConn bool // whether it's unused by any previous request +} + +func (cc *ClientConn) idleState() clientConnIdleState { + cc.mu.Lock() + defer cc.mu.Unlock() + return cc.idleStateLocked() +} + +func (cc *ClientConn) idleStateLocked() (st clientConnIdleState) { if cc.singleUse && cc.nextStreamID > 1 { - return false + return } - return cc.goAway == nil && !cc.closed && + st.canTakeNewRequest = cc.goAway == nil && !cc.closed && !cc.closing && int64(cc.nextStreamID)+int64(cc.pendingRequests) < math.MaxInt32 + st.freshConn = cc.nextStreamID == 1 && st.canTakeNewRequest + return +} + +func (cc *ClientConn) canTakeNewRequestLocked() bool { + st := cc.idleStateLocked() + return st.canTakeNewRequest } // onIdleTimeout is called from a time.AfterFunc goroutine. It will @@ -665,6 +686,88 @@ func (cc *ClientConn) closeIfIdle() { cc.tconn.Close() } +var shutdownEnterWaitStateHook = func() {} + +// Shutdown gracefully close the client connection, waiting for running streams to complete. +// Public implementation is in go17.go and not_go17.go +func (cc *ClientConn) shutdown(ctx contextContext) error { + if err := cc.sendGoAway(); err != nil { + return err + } + // Wait for all in-flight streams to complete or connection to close + done := make(chan error, 1) + cancelled := false // guarded by cc.mu + go func() { + cc.mu.Lock() + defer cc.mu.Unlock() + for { + if len(cc.streams) == 0 || cc.closed { + cc.closed = true + done <- cc.tconn.Close() + break + } + if cancelled { + break + } + cc.cond.Wait() + } + }() + shutdownEnterWaitStateHook() + select { + case err := <-done: + return err + case <-ctx.Done(): + cc.mu.Lock() + // Free the goroutine above + cancelled = true + cc.cond.Broadcast() + cc.mu.Unlock() + return ctx.Err() + } +} + +func (cc *ClientConn) sendGoAway() error { + cc.mu.Lock() + defer cc.mu.Unlock() + cc.wmu.Lock() + defer cc.wmu.Unlock() + if cc.closing { + // GOAWAY sent already + return nil + } + // Send a graceful shutdown frame to server + maxStreamID := cc.nextStreamID + if err := cc.fr.WriteGoAway(maxStreamID, ErrCodeNo, nil); err != nil { + return err + } + if err := cc.bw.Flush(); err != nil { + return err + } + // Prevent new requests + cc.closing = true + return nil +} + +// Close closes the client connection immediately. +// +// In-flight requests are interrupted. For a graceful shutdown, use Shutdown instead. +func (cc *ClientConn) Close() error { + cc.mu.Lock() + defer cc.cond.Broadcast() + defer cc.mu.Unlock() + err := errors.New("http2: client connection force closed via ClientConn.Close") + for id, cs := range cc.streams { + select { + case cs.resc <- resAndError{err: err}: + default: + } + cs.bufPipe.CloseWithError(err) + delete(cc.streams, id) + } + cc.closed = true + return cc.tconn.Close() +} + const maxAllocFrameSize = 512 << 10 // frameBuffer returns a scratch buffer suitable for writing DATA frames. @@ -747,7 +850,7 @@ func checkConnHeaders(req *http.Request) error { if vv := req.Header["Transfer-Encoding"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && vv[0] != "chunked") { return fmt.Errorf("http2: invalid Transfer-Encoding request header: %q", vv) } - if vv := req.Header["Connection"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && vv[0] != "close" && vv[0] != "keep-alive") { + if vv := req.Header["Connection"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && !strings.EqualFold(vv[0], "close") && !strings.EqualFold(vv[0], "keep-alive")) { return fmt.Errorf("http2: invalid Connection request header: %q", vv) } return nil @@ -1291,9 +1394,16 @@ func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trail return nil, errRequestHeaderListSize } + trace := requestTrace(req) + traceHeaders := traceHasWroteHeaderField(trace) + // Header list size is ok. Write the headers. enumerateHeaders(func(name, value string) { - cc.writeHeader(strings.ToLower(name), value) + name = strings.ToLower(name) + cc.writeHeader(name, value) + if traceHeaders { + traceWroteHeaderField(trace, name, value) + } }) return cc.hbuf.Bytes(), nil diff --git a/vendor/golang.org/x/net/netutil/listen.go b/vendor/golang.org/x/net/netutil/listen.go new file mode 100644 index 000000000..cee46e331 --- /dev/null +++ b/vendor/golang.org/x/net/netutil/listen.go @@ -0,0 +1,74 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package netutil provides network utility functions, complementing the more +// common ones in the net package. +package netutil // import "golang.org/x/net/netutil" + +import ( + "net" + "sync" +) + +// LimitListener returns a Listener that accepts at most n simultaneous +// connections from the provided Listener. +func LimitListener(l net.Listener, n int) net.Listener { + return &limitListener{ + Listener: l, + sem: make(chan struct{}, n), + done: make(chan struct{}), + } +} + +type limitListener struct { + net.Listener + sem chan struct{} + closeOnce sync.Once // ensures the done chan is only closed once + done chan struct{} // no values sent; closed when Close is called +} + +// acquire acquires the limiting semaphore. Returns true if successfully +// accquired, false if the listener is closed and the semaphore is not +// acquired. +func (l *limitListener) acquire() bool { + select { + case <-l.done: + return false + case l.sem <- struct{}{}: + return true + } +} +func (l *limitListener) release() { <-l.sem } + +func (l *limitListener) Accept() (net.Conn, error) { + acquired := l.acquire() + // If the semaphore isn't acquired because the listener was closed, expect + // that this call to accept won't block, but immediately return an error. + c, err := l.Listener.Accept() + if err != nil { + if acquired { + l.release() + } + return nil, err + } + return &limitListenerConn{Conn: c, release: l.release}, nil +} + +func (l *limitListener) Close() error { + err := l.Listener.Close() + l.closeOnce.Do(func() { close(l.done) }) + return err +} + +type limitListenerConn struct { + net.Conn + releaseOnce sync.Once + release func() +} + +func (l *limitListenerConn) Close() error { + err := l.Conn.Close() + l.releaseOnce.Do(l.release) + return err +} diff --git a/vendor/golang.org/x/sys/unix/syscall_bsd.go b/vendor/golang.org/x/sys/unix/syscall_bsd.go index 53fb85182..33c8b5f0d 100644 --- a/vendor/golang.org/x/sys/unix/syscall_bsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_bsd.go @@ -206,7 +206,7 @@ func (sa *SockaddrDatalink) sockaddr() (unsafe.Pointer, _Socklen, error) { return unsafe.Pointer(&sa.raw), SizeofSockaddrDatalink, nil } -func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) { +func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) { switch rsa.Addr.Family { case AF_LINK: pp := (*RawSockaddrDatalink)(unsafe.Pointer(rsa)) @@ -286,7 +286,7 @@ func Accept(fd int) (nfd int, sa Sockaddr, err error) { Close(nfd) return 0, nil, ECONNABORTED } - sa, err = anyToSockaddr(&rsa) + sa, err = anyToSockaddr(fd, &rsa) if err != nil { Close(nfd) nfd = 0 @@ -306,7 +306,7 @@ func Getsockname(fd int) (sa Sockaddr, err error) { rsa.Addr.Family = AF_UNIX rsa.Addr.Len = SizeofSockaddrUnix } - return anyToSockaddr(&rsa) + return anyToSockaddr(fd, &rsa) } //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) @@ -356,7 +356,7 @@ func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from recvflags = int(msg.Flags) // source address is only specified if the socket is unconnected if rsa.Addr.Family != AF_UNSPEC { - from, err = anyToSockaddr(&rsa) + from, err = anyToSockaddr(fd, &rsa) } return } diff --git a/vendor/golang.org/x/sys/unix/syscall_dragonfly.go b/vendor/golang.org/x/sys/unix/syscall_dragonfly.go index b5072de28..e34abe29d 100644 --- a/vendor/golang.org/x/sys/unix/syscall_dragonfly.go +++ b/vendor/golang.org/x/sys/unix/syscall_dragonfly.go @@ -87,7 +87,7 @@ func Accept4(fd, flags int) (nfd int, sa Sockaddr, err error) { if len > SizeofSockaddrAny { panic("RawSockaddrAny too small") } - sa, err = anyToSockaddr(&rsa) + sa, err = anyToSockaddr(fd, &rsa) if err != nil { Close(nfd) nfd = 0 diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd.go b/vendor/golang.org/x/sys/unix/syscall_freebsd.go index ba9df4ac1..5561a3eb7 100644 --- a/vendor/golang.org/x/sys/unix/syscall_freebsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_freebsd.go @@ -89,7 +89,7 @@ func Accept4(fd, flags int) (nfd int, sa Sockaddr, err error) { if len > SizeofSockaddrAny { panic("RawSockaddrAny too small") } - sa, err = anyToSockaddr(&rsa) + sa, err = anyToSockaddr(fd, &rsa) if err != nil { Close(nfd) nfd = 0 diff --git a/vendor/golang.org/x/sys/unix/syscall_linux.go b/vendor/golang.org/x/sys/unix/syscall_linux.go index 9908030cb..690c2c87f 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux.go @@ -489,6 +489,47 @@ func (sa *SockaddrL2) sockaddr() (unsafe.Pointer, _Socklen, error) { return unsafe.Pointer(&sa.raw), SizeofSockaddrL2, nil } +// SockaddrRFCOMM implements the Sockaddr interface for AF_BLUETOOTH type sockets +// using the RFCOMM protocol. +// +// Server example: +// +// fd, _ := Socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM) +// _ = unix.Bind(fd, &unix.SockaddrRFCOMM{ +// Channel: 1, +// Addr: [6]uint8{0, 0, 0, 0, 0, 0}, // BDADDR_ANY or 00:00:00:00:00:00 +// }) +// _ = Listen(fd, 1) +// nfd, sa, _ := Accept(fd) +// fmt.Printf("conn addr=%v fd=%d", sa.(*unix.SockaddrRFCOMM).Addr, nfd) +// Read(nfd, buf) +// +// Client example: +// +// fd, _ := Socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM) +// _ = Connect(fd, &SockaddrRFCOMM{ +// Channel: 1, +// Addr: [6]byte{0x11, 0x22, 0x33, 0xaa, 0xbb, 0xcc}, // CC:BB:AA:33:22:11 +// }) +// Write(fd, []byte(`hello`)) +type SockaddrRFCOMM struct { + // Addr represents a bluetooth address, byte ordering is little-endian. + Addr [6]uint8 + + // Channel is a designated bluetooth channel, only 1-30 are available for use. + // Since Linux 2.6.7 and further zero value is the first available channel. + Channel uint8 + + raw RawSockaddrRFCOMM +} + +func (sa *SockaddrRFCOMM) sockaddr() (unsafe.Pointer, _Socklen, error) { + sa.raw.Family = AF_BLUETOOTH + sa.raw.Channel = sa.Channel + sa.raw.Bdaddr = sa.Addr + return unsafe.Pointer(&sa.raw), SizeofSockaddrRFCOMM, nil +} + // SockaddrCAN implements the Sockaddr interface for AF_CAN type sockets. // The RxID and TxID fields are used for transport protocol addressing in // (CAN_TP16, CAN_TP20, CAN_MCNET, and CAN_ISOTP), they can be left with @@ -651,7 +692,7 @@ func (sa *SockaddrVM) sockaddr() (unsafe.Pointer, _Socklen, error) { return unsafe.Pointer(&sa.raw), SizeofSockaddrVM, nil } -func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) { +func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) { switch rsa.Addr.Family { case AF_NETLINK: pp := (*RawSockaddrNetlink)(unsafe.Pointer(rsa)) @@ -728,6 +769,30 @@ func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) { Port: pp.Port, } return sa, nil + case AF_BLUETOOTH: + proto, err := GetsockoptInt(fd, SOL_SOCKET, SO_PROTOCOL) + if err != nil { + return nil, err + } + // only BTPROTO_L2CAP and BTPROTO_RFCOMM can accept connections + switch proto { + case BTPROTO_L2CAP: + pp := (*RawSockaddrL2)(unsafe.Pointer(rsa)) + sa := &SockaddrL2{ + PSM: pp.Psm, + CID: pp.Cid, + Addr: pp.Bdaddr, + AddrType: pp.Bdaddr_type, + } + return sa, nil + case BTPROTO_RFCOMM: + pp := (*RawSockaddrRFCOMM)(unsafe.Pointer(rsa)) + sa := &SockaddrRFCOMM{ + Channel: pp.Channel, + Addr: pp.Bdaddr, + } + return sa, nil + } } return nil, EAFNOSUPPORT } @@ -739,7 +804,7 @@ func Accept(fd int) (nfd int, sa Sockaddr, err error) { if err != nil { return } - sa, err = anyToSockaddr(&rsa) + sa, err = anyToSockaddr(fd, &rsa) if err != nil { Close(nfd) nfd = 0 @@ -757,7 +822,7 @@ func Accept4(fd int, flags int) (nfd int, sa Sockaddr, err error) { if len > SizeofSockaddrAny { panic("RawSockaddrAny too small") } - sa, err = anyToSockaddr(&rsa) + sa, err = anyToSockaddr(fd, &rsa) if err != nil { Close(nfd) nfd = 0 @@ -771,7 +836,7 @@ func Getsockname(fd int) (sa Sockaddr, err error) { if err = getsockname(fd, &rsa, &len); err != nil { return } - return anyToSockaddr(&rsa) + return anyToSockaddr(fd, &rsa) } func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error) { @@ -960,7 +1025,7 @@ func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from recvflags = int(msg.Flags) // source address is only specified if the socket is unconnected if rsa.Addr.Family != AF_UNSPEC { - from, err = anyToSockaddr(&rsa) + from, err = anyToSockaddr(fd, &rsa) } return } diff --git a/vendor/golang.org/x/sys/unix/syscall_solaris.go b/vendor/golang.org/x/sys/unix/syscall_solaris.go index 820ef77af..a05337d54 100644 --- a/vendor/golang.org/x/sys/unix/syscall_solaris.go +++ b/vendor/golang.org/x/sys/unix/syscall_solaris.go @@ -112,7 +112,7 @@ func Getsockname(fd int) (sa Sockaddr, err error) { if err = getsockname(fd, &rsa, &len); err != nil { return } - return anyToSockaddr(&rsa) + return anyToSockaddr(fd, &rsa) } // GetsockoptString returns the string value of the socket option opt for the @@ -360,7 +360,7 @@ func Futimes(fd int, tv []Timeval) error { return futimesat(fd, nil, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) } -func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) { +func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) { switch rsa.Addr.Family { case AF_UNIX: pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa)) @@ -411,7 +411,7 @@ func Accept(fd int) (nfd int, sa Sockaddr, err error) { if nfd == -1 { return } - sa, err = anyToSockaddr(&rsa) + sa, err = anyToSockaddr(fd, &rsa) if err != nil { Close(nfd) nfd = 0 @@ -448,7 +448,7 @@ func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from oobn = int(msg.Accrightslen) // source address is only specified if the socket is unconnected if rsa.Addr.Family != AF_UNSPEC { - from, err = anyToSockaddr(&rsa) + from, err = anyToSockaddr(fd, &rsa) } return } diff --git a/vendor/golang.org/x/sys/unix/syscall_unix.go b/vendor/golang.org/x/sys/unix/syscall_unix.go index b835bad0f..95b2180ae 100644 --- a/vendor/golang.org/x/sys/unix/syscall_unix.go +++ b/vendor/golang.org/x/sys/unix/syscall_unix.go @@ -219,7 +219,7 @@ func Getpeername(fd int) (sa Sockaddr, err error) { if err = getpeername(fd, &rsa, &len); err != nil { return } - return anyToSockaddr(&rsa) + return anyToSockaddr(fd, &rsa) } func GetsockoptByte(fd, level, opt int) (value byte, err error) { @@ -291,7 +291,7 @@ func Recvfrom(fd int, p []byte, flags int) (n int, from Sockaddr, err error) { return } if rsa.Addr.Family != AF_UNSPEC { - from, err = anyToSockaddr(&rsa) + from, err = anyToSockaddr(fd, &rsa) } return } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go index 0ae2aa842..7cc1bfd12 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go @@ -1474,8 +1474,13 @@ func Munlockall() (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Dup2(oldfd int, newfd int) (err error) { - _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) +func faccessat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } @@ -1484,9 +1489,8 @@ func Dup2(oldfd int, newfd int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollCreate(size int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) - fd = int(r0) +func Dup2(oldfd int, newfd int) (err error) { + _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) } @@ -1495,13 +1499,9 @@ func EpollCreate(size int) (fd int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func faccessat(dirfd int, path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) +func EpollCreate(size int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) + fd = int(r0) if e1 != 0 { err = errnoErr(e1) } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go index fa16c165e..c3dcb3818 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go @@ -1474,8 +1474,13 @@ func Munlockall() (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Dup2(oldfd int, newfd int) (err error) { - _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) +func faccessat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } @@ -1484,9 +1489,8 @@ func Dup2(oldfd int, newfd int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollCreate(size int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) - fd = int(r0) +func Dup2(oldfd int, newfd int) (err error) { + _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) } @@ -1495,13 +1499,9 @@ func EpollCreate(size int) (fd int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func faccessat(dirfd int, path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) +func EpollCreate(size int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) + fd = int(r0) if e1 != 0 { err = errnoErr(e1) } diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_386.go b/vendor/golang.org/x/sys/unix/ztypes_linux_386.go index e89bc6b36..4c250033f 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_386.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_386.go @@ -248,6 +248,13 @@ type RawSockaddrL2 struct { _ [1]byte } +type RawSockaddrRFCOMM struct { + Family uint16 + Bdaddr [6]uint8 + Channel uint8 + _ [1]byte +} + type RawSockaddrCAN struct { Family uint16 _ [2]byte @@ -401,6 +408,7 @@ const ( SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrL2 = 0xe + SizeofSockaddrRFCOMM = 0xa SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go index d95372bae..2e4d709b4 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go @@ -250,6 +250,13 @@ type RawSockaddrL2 struct { _ [1]byte } +type RawSockaddrRFCOMM struct { + Family uint16 + Bdaddr [6]uint8 + Channel uint8 + _ [1]byte +} + type RawSockaddrCAN struct { Family uint16 _ [2]byte @@ -405,6 +412,7 @@ const ( SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrL2 = 0xe + SizeofSockaddrRFCOMM = 0xa SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go b/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go index 77875ba01..bf38e5e2c 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go @@ -251,6 +251,13 @@ type RawSockaddrL2 struct { _ [1]byte } +type RawSockaddrRFCOMM struct { + Family uint16 + Bdaddr [6]uint8 + Channel uint8 + _ [1]byte +} + type RawSockaddrCAN struct { Family uint16 _ [2]byte @@ -404,6 +411,7 @@ const ( SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrL2 = 0xe + SizeofSockaddrRFCOMM = 0xa SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go index 5a9df694a..972c1b872 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go @@ -251,6 +251,13 @@ type RawSockaddrL2 struct { _ [1]byte } +type RawSockaddrRFCOMM struct { + Family uint16 + Bdaddr [6]uint8 + Channel uint8 + _ [1]byte +} + type RawSockaddrCAN struct { Family uint16 _ [2]byte @@ -406,6 +413,7 @@ const ( SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrL2 = 0xe + SizeofSockaddrRFCOMM = 0xa SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go index dcb239de8..783e70e87 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go @@ -249,6 +249,13 @@ type RawSockaddrL2 struct { _ [1]byte } +type RawSockaddrRFCOMM struct { + Family uint16 + Bdaddr [6]uint8 + Channel uint8 + _ [1]byte +} + type RawSockaddrCAN struct { Family uint16 _ [2]byte @@ -402,6 +409,7 @@ const ( SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrL2 = 0xe + SizeofSockaddrRFCOMM = 0xa SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go index 9cf85f721..5c6ea719d 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go @@ -251,6 +251,13 @@ type RawSockaddrL2 struct { _ [1]byte } +type RawSockaddrRFCOMM struct { + Family uint16 + Bdaddr [6]uint8 + Channel uint8 + _ [1]byte +} + type RawSockaddrCAN struct { Family uint16 _ [2]byte @@ -406,6 +413,7 @@ const ( SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrL2 = 0xe + SizeofSockaddrRFCOMM = 0xa SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go index 6fd66e751..93effc8ec 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go @@ -251,6 +251,13 @@ type RawSockaddrL2 struct { _ [1]byte } +type RawSockaddrRFCOMM struct { + Family uint16 + Bdaddr [6]uint8 + Channel uint8 + _ [1]byte +} + type RawSockaddrCAN struct { Family uint16 _ [2]byte @@ -406,6 +413,7 @@ const ( SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrL2 = 0xe + SizeofSockaddrRFCOMM = 0xa SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go index faa5b3ef1..cc5ca242e 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go @@ -249,6 +249,13 @@ type RawSockaddrL2 struct { _ [1]byte } +type RawSockaddrRFCOMM struct { + Family uint16 + Bdaddr [6]uint8 + Channel uint8 + _ [1]byte +} + type RawSockaddrCAN struct { Family uint16 _ [2]byte @@ -402,6 +409,7 @@ const ( SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrL2 = 0xe + SizeofSockaddrRFCOMM = 0xa SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go index ad4c45246..712f64029 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go @@ -252,6 +252,13 @@ type RawSockaddrL2 struct { _ [1]byte } +type RawSockaddrRFCOMM struct { + Family uint16 + Bdaddr [6]uint8 + Channel uint8 + _ [1]byte +} + type RawSockaddrCAN struct { Family uint16 _ [2]byte @@ -407,6 +414,7 @@ const ( SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrL2 = 0xe + SizeofSockaddrRFCOMM = 0xa SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go index 1fdb2f216..1be45320a 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go @@ -252,6 +252,13 @@ type RawSockaddrL2 struct { _ [1]byte } +type RawSockaddrRFCOMM struct { + Family uint16 + Bdaddr [6]uint8 + Channel uint8 + _ [1]byte +} + type RawSockaddrCAN struct { Family uint16 _ [2]byte @@ -407,6 +414,7 @@ const ( SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrL2 = 0xe + SizeofSockaddrRFCOMM = 0xa SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go b/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go index d32079d1a..932b655fe 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go @@ -250,6 +250,13 @@ type RawSockaddrL2 struct { _ [1]byte } +type RawSockaddrRFCOMM struct { + Family uint16 + Bdaddr [6]uint8 + Channel uint8 + _ [1]byte +} + type RawSockaddrCAN struct { Family uint16 _ [2]byte @@ -405,6 +412,7 @@ const ( SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrL2 = 0xe + SizeofSockaddrRFCOMM = 0xa SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 diff --git a/vendor/golang.org/x/sys/windows/types_windows.go b/vendor/golang.org/x/sys/windows/types_windows.go index b4e424788..7d2a6794d 100644 --- a/vendor/golang.org/x/sys/windows/types_windows.go +++ b/vendor/golang.org/x/sys/windows/types_windows.go @@ -94,16 +94,29 @@ const ( FILE_APPEND_DATA = 0x00000004 FILE_WRITE_ATTRIBUTES = 0x00000100 - FILE_SHARE_READ = 0x00000001 - FILE_SHARE_WRITE = 0x00000002 - FILE_SHARE_DELETE = 0x00000004 - FILE_ATTRIBUTE_READONLY = 0x00000001 - FILE_ATTRIBUTE_HIDDEN = 0x00000002 - FILE_ATTRIBUTE_SYSTEM = 0x00000004 - FILE_ATTRIBUTE_DIRECTORY = 0x00000010 - FILE_ATTRIBUTE_ARCHIVE = 0x00000020 - FILE_ATTRIBUTE_NORMAL = 0x00000080 - FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400 + FILE_SHARE_READ = 0x00000001 + FILE_SHARE_WRITE = 0x00000002 + FILE_SHARE_DELETE = 0x00000004 + + FILE_ATTRIBUTE_READONLY = 0x00000001 + FILE_ATTRIBUTE_HIDDEN = 0x00000002 + FILE_ATTRIBUTE_SYSTEM = 0x00000004 + FILE_ATTRIBUTE_DIRECTORY = 0x00000010 + FILE_ATTRIBUTE_ARCHIVE = 0x00000020 + FILE_ATTRIBUTE_DEVICE = 0x00000040 + FILE_ATTRIBUTE_NORMAL = 0x00000080 + FILE_ATTRIBUTE_TEMPORARY = 0x00000100 + FILE_ATTRIBUTE_SPARSE_FILE = 0x00000200 + FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400 + FILE_ATTRIBUTE_COMPRESSED = 0x00000800 + FILE_ATTRIBUTE_OFFLINE = 0x00001000 + FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 0x00002000 + FILE_ATTRIBUTE_ENCRYPTED = 0x00004000 + FILE_ATTRIBUTE_INTEGRITY_STREAM = 0x00008000 + FILE_ATTRIBUTE_VIRTUAL = 0x00010000 + FILE_ATTRIBUTE_NO_SCRUB_DATA = 0x00020000 + FILE_ATTRIBUTE_RECALL_ON_OPEN = 0x00040000 + FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS = 0x00400000 INVALID_FILE_ATTRIBUTES = 0xffffffff From 467548dacdef7b280730d6c37ef4723b64c9e261 Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Fri, 20 Jul 2018 12:39:58 +0100 Subject: [PATCH 16/28] Fix up against Tendermint 0.24.4 Signed-off-by: Silas Davis --- blockchain/blockchain.go | 2 +- blockchain/blockchain_test.go | 2 +- cmd/burrow/commands/configure.go | 2 +- cmd/burrow/commands/dump.go | 2 +- consensus/tendermint/abci/app.go | 2 +- consensus/tendermint/codes/codes.go | 2 +- consensus/tendermint/config.go | 2 ++ consensus/tendermint/logger.go | 2 +- consensus/tendermint/query/node_view.go | 2 +- consensus/tendermint/tendermint.go | 10 +++--- .../validator/priv_validator_memory.go | 2 +- consensus/tendermint/validator/sign_info.go | 12 +++---- consensus/tendermint/validator/wire.go | 4 +-- core/kernel.go | 10 ++++-- crypto/address.go | 3 +- crypto/public_key.go | 32 ++----------------- crypto/public_key_test.go | 4 +-- event/emitter.go | 2 +- event/pubsub/pubsub.go | 2 +- execution/errors/errors_test.go | 2 ++ execution/exec/block_execution.go | 2 +- execution/exec/exec.pb.go | 2 +- execution/execution.go | 2 +- execution/execution_test.go | 2 +- execution/state.go | 2 +- execution/state_test.go | 2 +- execution/transactor.go | 2 +- execution/transactor_test.go | 2 +- forensics/block_explorer.go | 2 +- integration/core/kernel_test.go | 2 ++ integration/governance/main_test.go | 1 + integration/integration.go | 1 + .../rpctransact/transact_server_test.go | 2 +- keys/server_test.go | 2 +- protobuf/exec.proto | 2 +- rpc/lib/client/ws_client.go | 2 +- rpc/lib/rpc_test.go | 4 +-- rpc/lib/server/handlers.go | 2 +- rpc/lib/server/parse_test.go | 2 +- rpc/result_test.go | 4 +-- 40 files changed, 64 insertions(+), 79 deletions(-) diff --git a/blockchain/blockchain.go b/blockchain/blockchain.go index 4d8e2c942..43be5ca7b 100644 --- a/blockchain/blockchain.go +++ b/blockchain/blockchain.go @@ -25,7 +25,7 @@ import ( "github.com/hyperledger/burrow/genesis" "github.com/hyperledger/burrow/logging" "github.com/tendermint/go-amino" - dbm "github.com/tendermint/tmlibs/db" + dbm "github.com/tendermint/tendermint/libs/db" ) // Blocks to average validator power over diff --git a/blockchain/blockchain_test.go b/blockchain/blockchain_test.go index 53d74be30..aaa6f7ee3 100644 --- a/blockchain/blockchain_test.go +++ b/blockchain/blockchain_test.go @@ -10,7 +10,7 @@ import ( "github.com/hyperledger/burrow/logging/config" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tendermint/tmlibs/db" + "github.com/tendermint/tendermint/libs/db" ) func TestBlockchain_Encode(t *testing.T) { diff --git a/cmd/burrow/commands/configure.go b/cmd/burrow/commands/configure.go index d45ed4d3a..35788d6a6 100644 --- a/cmd/burrow/commands/configure.go +++ b/cmd/burrow/commands/configure.go @@ -19,7 +19,7 @@ import ( "github.com/hyperledger/burrow/logging/config/presets" cli "github.com/jawher/mow.cli" amino "github.com/tendermint/go-amino" - tm_crypto "github.com/tendermint/go-crypto" + tm_crypto "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/p2p" ) diff --git a/cmd/burrow/commands/dump.go b/cmd/burrow/commands/dump.go index 1e4ef0412..46a4aaf83 100644 --- a/cmd/burrow/commands/dump.go +++ b/cmd/burrow/commands/dump.go @@ -6,7 +6,7 @@ import ( "github.com/hyperledger/burrow/forensics" "github.com/hyperledger/burrow/txs" cli "github.com/jawher/mow.cli" - "github.com/tendermint/tmlibs/db" + "github.com/tendermint/tendermint/libs/db" ) func Dump(output Output) func(cmd *cli.Cmd) { diff --git a/consensus/tendermint/abci/app.go b/consensus/tendermint/abci/app.go index 41aed6b42..ce47eef2e 100644 --- a/consensus/tendermint/abci/app.go +++ b/consensus/tendermint/abci/app.go @@ -17,7 +17,7 @@ import ( "github.com/hyperledger/burrow/project" "github.com/hyperledger/burrow/txs" "github.com/pkg/errors" - abciTypes "github.com/tendermint/abci/types" + abciTypes "github.com/tendermint/tendermint/abci/types" ) const responseInfoName = "Burrow" diff --git a/consensus/tendermint/codes/codes.go b/consensus/tendermint/codes/codes.go index 9fe76ea60..3e882570e 100644 --- a/consensus/tendermint/codes/codes.go +++ b/consensus/tendermint/codes/codes.go @@ -1,7 +1,7 @@ package codes import ( - abci_types "github.com/tendermint/abci/types" + abci_types "github.com/tendermint/tendermint/abci/types" ) const ( diff --git a/consensus/tendermint/config.go b/consensus/tendermint/config.go index 4f9db3c7a..46e391d09 100644 --- a/consensus/tendermint/config.go +++ b/consensus/tendermint/config.go @@ -38,6 +38,8 @@ func (btc *BurrowTendermintConfig) TendermintConfig() *tm_config.Config { conf.P2P.PersistentPeers = btc.PersistentPeers conf.P2P.ListenAddress = btc.ListenAddress conf.Moniker = btc.Moniker + // Unfortunately this stops metrics from being used at all + conf.Instrumentation.Prometheus = false } // Disable Tendermint RPC conf.RPC.ListenAddress = "" diff --git a/consensus/tendermint/logger.go b/consensus/tendermint/logger.go index 2a73c22fb..1d174e90e 100644 --- a/consensus/tendermint/logger.go +++ b/consensus/tendermint/logger.go @@ -2,7 +2,7 @@ package tendermint import ( "github.com/hyperledger/burrow/logging" - "github.com/tendermint/tmlibs/log" + "github.com/tendermint/tendermint/libs/log" ) type tendermintLogger struct { diff --git a/consensus/tendermint/query/node_view.go b/consensus/tendermint/query/node_view.go index d99884675..4c547bc24 100644 --- a/consensus/tendermint/query/node_view.go +++ b/consensus/tendermint/query/node_view.go @@ -5,7 +5,7 @@ import ( "github.com/hyperledger/burrow/consensus/tendermint" "github.com/hyperledger/burrow/crypto" - tm_crypto "github.com/tendermint/go-crypto" + tm_crypto "github.com/tendermint/tendermint/crypto" "github.com/hyperledger/burrow/txs" "github.com/tendermint/tendermint/consensus" diff --git a/consensus/tendermint/tendermint.go b/consensus/tendermint/tendermint.go index 3ada43cf2..31f0c8cf0 100644 --- a/consensus/tendermint/tendermint.go +++ b/consensus/tendermint/tendermint.go @@ -6,18 +6,17 @@ import ( bcm "github.com/hyperledger/burrow/blockchain" "github.com/hyperledger/burrow/consensus/tendermint/abci" - "github.com/hyperledger/burrow/event" "github.com/hyperledger/burrow/execution" "github.com/hyperledger/burrow/genesis" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" "github.com/hyperledger/burrow/txs" - tmCrypto "github.com/tendermint/go-crypto" "github.com/tendermint/tendermint/config" + tmCrypto "github.com/tendermint/tendermint/crypto" + dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/node" "github.com/tendermint/tendermint/proxy" tmTypes "github.com/tendermint/tendermint/types" - dbm "github.com/tendermint/tmlibs/db" ) // Serves as a wrapper around the Tendermint node's closeable resources (database connections) @@ -28,8 +27,6 @@ type Node struct { } } -var NewBlockQuery = event.QueryForEventID(tmTypes.EventNewBlock) - func DBProvider(ID string, backendType dbm.DBBackendType, dbDir string) dbm.DB { return dbm.NewDB(ID, backendType, dbDir) } @@ -49,7 +46,7 @@ func (n *Node) Close() { func NewNode(conf *config.Config, privValidator tmTypes.PrivValidator, genesisDoc *tmTypes.GenesisDoc, blockchain *bcm.Blockchain, checker execution.BatchExecutor, committer execution.BatchCommitter, - txDecoder txs.Decoder, panicFunc func(error), logger *logging.Logger) (*Node, error) { + txDecoder txs.Decoder, metricsProvider node.MetricsProvider, panicFunc func(error), logger *logging.Logger) (*Node, error) { var err error // disable Tendermint's RPC @@ -69,6 +66,7 @@ func NewNode(conf *config.Config, privValidator tmTypes.PrivValidator, genesisDo return genesisDoc, nil }, nde.DBProvider, + metricsProvider, NewLogger(logger.WithPrefix(structure.ComponentKey, "Tendermint"). With(structure.ScopeKey, "tendermint.NewNode"))) if err != nil { diff --git a/consensus/tendermint/validator/priv_validator_memory.go b/consensus/tendermint/validator/priv_validator_memory.go index 3a5b6db35..5159e5036 100644 --- a/consensus/tendermint/validator/priv_validator_memory.go +++ b/consensus/tendermint/validator/priv_validator_memory.go @@ -2,7 +2,7 @@ package validator import ( "github.com/hyperledger/burrow/crypto" - tm_crypto "github.com/tendermint/go-crypto" + tm_crypto "github.com/tendermint/tendermint/crypto" tm_types "github.com/tendermint/tendermint/types" ) diff --git a/consensus/tendermint/validator/sign_info.go b/consensus/tendermint/validator/sign_info.go index 975538656..40230651c 100644 --- a/consensus/tendermint/validator/sign_info.go +++ b/consensus/tendermint/validator/sign_info.go @@ -7,9 +7,9 @@ import ( "sync" "time" - "github.com/tendermint/go-crypto" + "github.com/hyperledger/burrow/binary" + "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tmlibs/common" ) // TODO: type ? @@ -27,7 +27,7 @@ func voteToStep(vote *types.Vote) int8 { case types.VoteTypePrecommit: return stepPrecommit default: - cmn.PanicSanity("Unknown vote type") + panic("Unknown vote type") return 0 } } @@ -40,7 +40,7 @@ type LastSignedInfo struct { Round int `json:"round"` Step int8 `json:"step"` Signature crypto.Signature `json:"signature,omitempty"` // so we dont lose signatures - SignBytes cmn.HexBytes `json:"signbytes,omitempty"` // so we dont lose signatures + SignBytes binary.HexBytes `json:"signbytes,omitempty"` // so we dont lose signatures } func NewLastSignedInfo() *LastSignedInfo { @@ -57,7 +57,7 @@ func (lsi *LastSignedInfo) SignVote(sign goCryptoSigner, chainID string, vote *t lsi.Lock() defer lsi.Unlock() if err := lsi.signVote(sign, chainID, vote); err != nil { - return errors.New(cmn.Fmt("Error signing vote: %v", err)) + return fmt.Errorf("error signing vote: %v", err) } return nil } @@ -68,7 +68,7 @@ func (lsi *LastSignedInfo) SignProposal(sign goCryptoSigner, chainID string, pro lsi.Lock() defer lsi.Unlock() if err := lsi.signProposal(sign, chainID, proposal); err != nil { - return fmt.Errorf("Error signing proposal: %v", err) + return fmt.Errorf("error signing proposal: %v", err) } return nil } diff --git a/consensus/tendermint/validator/wire.go b/consensus/tendermint/validator/wire.go index 7f063ca38..3cdd4f0dc 100644 --- a/consensus/tendermint/validator/wire.go +++ b/consensus/tendermint/validator/wire.go @@ -1,8 +1,8 @@ package validator import ( - "github.com/tendermint/go-amino" - "github.com/tendermint/go-crypto" + amino "github.com/tendermint/go-amino" + "github.com/tendermint/tendermint/crypto" ) var cdc = amino.NewCodec() diff --git a/core/kernel.go b/core/kernel.go index ab44c0262..72329f2d7 100644 --- a/core/kernel.go +++ b/core/kernel.go @@ -45,8 +45,9 @@ import ( "github.com/hyperledger/burrow/rpc/tm" "github.com/hyperledger/burrow/txs" tmConfig "github.com/tendermint/tendermint/config" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/node" tmTypes "github.com/tendermint/tendermint/types" - dbm "github.com/tendermint/tmlibs/db" ) const ( @@ -106,8 +107,12 @@ func NewKernel(ctx context.Context, keyClient keys.KeyClient, privValidator tmTy emitter := event.NewEmitter(logger) committer := execution.NewBatchCommitter(state, blockchain, emitter, logger, exeOptions...) + + // We could use this to provide/register our own metrics (though this will register them with us). Unforunately + // Tendermint currently ignores the metrics passed unless its own server is turned on. + metricsProvider := node.DefaultMetricsProvider tmNode, err := tendermint.NewNode(tmConf, privValidator, tmGenesisDoc, blockchain, checker, committer, txCodec, - kern.Panic, tmLogger) + metricsProvider, kern.Panic, tmLogger) if err != nil { return nil, err } @@ -278,7 +283,6 @@ func (kern *Kernel) WaitForShutdown() { // Supervise kernel once booted func (kern *Kernel) supervise() { - // TODO: Consider capturing kernel panics from boot and sending them here via a channel where we could // perform disaster restarts of the kernel; rejoining the network as if we were a new node. signals := make(chan os.Signal, 1) signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL) diff --git a/crypto/address.go b/crypto/address.go index 69bd9af69..0a1a70579 100644 --- a/crypto/address.go +++ b/crypto/address.go @@ -59,7 +59,8 @@ func (as Addresses) Swap(i, j int) { as[i], as[j] = as[j], as[i] } -const AddressHexLength = 2 * binary.Word160Length +const AddressLength = binary.Word160Length +const AddressHexLength = 2 * AddressLength var ZeroAddress = Address{} diff --git a/crypto/public_key.go b/crypto/public_key.go index 2d3da8262..4d5764ad3 100644 --- a/crypto/public_key.go +++ b/crypto/public_key.go @@ -6,8 +6,8 @@ import ( "fmt" "github.com/btcsuite/btcd/btcec" - abci "github.com/tendermint/abci/types" - tmCrypto "github.com/tendermint/go-crypto" + abci "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/crypto/tmhash" "github.com/tmthrgd/go-hex" "golang.org/x/crypto/ed25519" "golang.org/x/crypto/ripemd160" @@ -98,10 +98,7 @@ func (p PublicKey) PublicKey() PublicKey { func (p PublicKey) Address() Address { switch p.CurveType { case CurveTypeEd25519: - // FIMXE: tendermint go-crypto-0.5.0 uses weird scheme, this is fixed in 0.6.0 - tmPubKey := new(tmCrypto.PubKeyEd25519) - copy(tmPubKey[:], p.Key) - addr, _ := AddressFromBytes(tmPubKey.Address()) + addr, _ := AddressFromBytes(tmhash.Sum(p.Key)) return addr case CurveTypeSecp256k1: sha := sha256.New() @@ -167,26 +164,3 @@ func (p PublicKey) Encode() []byte { copy(encoded[1:], p.Key) return encoded } - -// Decodes an encoded public key returning the number of bytes consumed -func DecodePublicKeyFixedWidth(buf []byte, publicKey *PublicKey) (int, error) { - if len(buf) < 1 { - return 0, fmt.Errorf("encoded bytes buffer must not be empty") - } - curveType := CurveType(buf[0]) - publicKeyEnd := PublicKeyLength(curveType) + 1 - if publicKeyEnd <= 0 { - return 0, fmt.Errorf("CurveType with identifier %v is unknown", curveType.Byte()) - } - if len(buf) < publicKeyEnd { - return 0, fmt.Errorf("encoded bytes buffer has length %v but public key encoding for %v needs %v bytes", - len(buf), curveType, publicKeyEnd) - } - - publicKey.CurveType = curveType - publicKey.Key = buf[1:publicKeyEnd] - if !publicKey.IsValid() { - return publicKeyEnd, fmt.Errorf("decoded public key %v is not valid", publicKey) - } - return publicKeyEnd, nil -} diff --git a/crypto/public_key_test.go b/crypto/public_key_test.go index f6c211a35..9d49e884b 100644 --- a/crypto/public_key_test.go +++ b/crypto/public_key_test.go @@ -13,8 +13,8 @@ func TestPublicKeySerialisation(t *testing.T) { priv := PrivateKeyFromSecret("foo", CurveTypeEd25519) pub := priv.GetPublicKey() expectedAddress := Address{ - 0x83, 0x20, 0x78, 0x17, 0xdc, 0x38, 0x14, 0xb9, 0x6f, 0x57, - 0xef, 0xf9, 0x25, 0xf4, 0x67, 0xe0, 0x7c, 0xaa, 0x91, 0x38, + 0x4, 0x5f, 0x56, 0x0, 0x65, 0x41, 0x82, 0xcf, 0xea, 0xcc, + 0xfe, 0x6c, 0xb1, 0x9f, 0x6, 0x42, 0xe8, 0xa5, 0x98, 0x98, } assert.Equal(t, expectedAddress, pub.Address()) bs, err := proto.Marshal(&pub) diff --git a/event/emitter.go b/event/emitter.go index c4d1fd413..8cc254af7 100644 --- a/event/emitter.go +++ b/event/emitter.go @@ -23,7 +23,7 @@ import ( "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" "github.com/hyperledger/burrow/process" - "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tendermint/libs/common" "github.com/tmthrgd/go-hex" ) diff --git a/event/pubsub/pubsub.go b/event/pubsub/pubsub.go index 8d7107730..41904fed7 100644 --- a/event/pubsub/pubsub.go +++ b/event/pubsub/pubsub.go @@ -19,7 +19,7 @@ import ( "sync" "github.com/hyperledger/burrow/event/query" - "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tendermint/libs/common" ) type operation int diff --git a/execution/errors/errors_test.go b/execution/errors/errors_test.go index c80c05722..33d487b4f 100644 --- a/execution/errors/errors_test.go +++ b/execution/errors/errors_test.go @@ -5,6 +5,8 @@ import ( "fmt" "testing" + "fmt" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/execution/exec/block_execution.go b/execution/exec/block_execution.go index 3fc8a905d..15b35d8b0 100644 --- a/execution/exec/block_execution.go +++ b/execution/exec/block_execution.go @@ -9,7 +9,7 @@ import ( "github.com/hyperledger/burrow/event" "github.com/hyperledger/burrow/event/query" "github.com/hyperledger/burrow/txs" - abciTypes "github.com/tendermint/abci/types" + abciTypes "github.com/tendermint/tendermint/abci/types" ) func EventStringBlockExecution(height uint64) string { return fmt.Sprintf("Execution/Block/%v", height) } diff --git a/execution/exec/exec.pb.go b/execution/exec/exec.pb.go index 5b4a82c98..26108e09f 100644 --- a/execution/exec/exec.pb.go +++ b/execution/exec/exec.pb.go @@ -28,7 +28,7 @@ import golang_proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import _ "github.com/gogo/protobuf/gogoproto" -import _ "github.com/tendermint/abci/types" +import _ "github.com/tendermint/tendermint/abci/types" import errors "github.com/hyperledger/burrow/execution/errors" import names "github.com/hyperledger/burrow/execution/names" import txs "github.com/hyperledger/burrow/txs" diff --git a/execution/execution.go b/execution/execution.go index d88d45bc2..32ee4cf80 100644 --- a/execution/execution.go +++ b/execution/execution.go @@ -37,7 +37,7 @@ import ( "github.com/hyperledger/burrow/txs" "github.com/hyperledger/burrow/txs/payload" "github.com/pkg/errors" - abciTypes "github.com/tendermint/abci/types" + abciTypes "github.com/tendermint/tendermint/abci/types" ) type Executor interface { diff --git a/execution/execution_test.go b/execution/execution_test.go index 033c55412..bfc4d96a2 100644 --- a/execution/execution_test.go +++ b/execution/execution_test.go @@ -42,7 +42,7 @@ import ( "github.com/hyperledger/burrow/txs" "github.com/hyperledger/burrow/txs/payload" "github.com/stretchr/testify/require" - dbm "github.com/tendermint/tmlibs/db" + dbm "github.com/tendermint/tendermint/libs/db" "github.com/tmthrgd/go-hex" ) diff --git a/execution/state.go b/execution/state.go index 12460d783..b9717ef11 100644 --- a/execution/state.go +++ b/execution/state.go @@ -29,7 +29,7 @@ import ( "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/permission" "github.com/tendermint/iavl" - dbm "github.com/tendermint/tmlibs/db" + dbm "github.com/tendermint/tendermint/libs/db" ) const ( diff --git a/execution/state_test.go b/execution/state_test.go index 7a821c340..4ed6a5c9c 100644 --- a/execution/state_test.go +++ b/execution/state_test.go @@ -27,7 +27,7 @@ import ( "github.com/hyperledger/burrow/permission" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tendermint/tmlibs/db" + "github.com/tendermint/tendermint/libs/db" ) func TestState_UpdateAccount(t *testing.T) { diff --git a/execution/transactor.go b/execution/transactor.go index 3a5cbd274..932e31297 100644 --- a/execution/transactor.go +++ b/execution/transactor.go @@ -28,7 +28,7 @@ import ( "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" "github.com/hyperledger/burrow/txs" - abciTypes "github.com/tendermint/abci/types" + abciTypes "github.com/tendermint/tendermint/abci/types" tmTypes "github.com/tendermint/tendermint/types" ) diff --git a/execution/transactor_test.go b/execution/transactor_test.go index 0d6df572d..5d19f06f7 100644 --- a/execution/transactor_test.go +++ b/execution/transactor_test.go @@ -32,7 +32,7 @@ import ( "github.com/hyperledger/burrow/txs/payload" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - abciTypes "github.com/tendermint/abci/types" + abciTypes "github.com/tendermint/tendermint/abci/types" tmTypes "github.com/tendermint/tendermint/types" ) diff --git a/forensics/block_explorer.go b/forensics/block_explorer.go index a8d2c84c1..ce2f492e2 100644 --- a/forensics/block_explorer.go +++ b/forensics/block_explorer.go @@ -6,7 +6,7 @@ import ( "github.com/hyperledger/burrow/consensus/tendermint" "github.com/hyperledger/burrow/txs" "github.com/tendermint/tendermint/blockchain" - "github.com/tendermint/tmlibs/db" + "github.com/tendermint/tendermint/libs/db" ) type BlockExplorer struct { diff --git a/integration/core/kernel_test.go b/integration/core/kernel_test.go index d4003e212..4459af6c6 100644 --- a/integration/core/kernel_test.go +++ b/integration/core/kernel_test.go @@ -30,6 +30,7 @@ func TestBootThenShutdown(t *testing.T) { os.RemoveAll(testDir) os.MkdirAll(testDir, 0777) os.Chdir(testDir) + defer os.RemoveAll(testDir) tmConf := tmConfig.DefaultConfig() //logger, _, _ := lifecycle.NewStdErrLogger() logger := logging.NewNoopLogger() @@ -42,6 +43,7 @@ func TestBootShutdownResume(t *testing.T) { os.RemoveAll(testDir) os.MkdirAll(testDir, 0777) os.Chdir(testDir) + defer os.RemoveAll(testDir) tmConf := tmConfig.DefaultConfig() //logger, _, _ := lifecycle.NewStdErrLogger() logger := logging.NewNoopLogger() diff --git a/integration/governance/main_test.go b/integration/governance/main_test.go index 684d6a13b..21b39516b 100644 --- a/integration/governance/main_test.go +++ b/integration/governance/main_test.go @@ -29,6 +29,7 @@ import ( var _ = integration.ClaimPorts() var inputAddress = rpctest.PrivateAccounts[0].Address() +var gene var testConfig = integration.NewTestConfig(rpctest.GenesisDoc) var kern *core.Kernel diff --git a/integration/integration.go b/integration/integration.go index cda7523b1..280f83207 100644 --- a/integration/integration.go +++ b/integration/integration.go @@ -65,6 +65,7 @@ func TestKernel(privateAccounts []*acm.PrivateAccount, testConfig *config.Burrow os.RemoveAll(testDir) os.MkdirAll(testDir, 0777) os.Chdir(testDir) + defer os.RemoveAll(testDir) os.MkdirAll("config", 0777) diff --git a/integration/rpctransact/transact_server_test.go b/integration/rpctransact/transact_server_test.go index 6ab30c545..096f80b25 100644 --- a/integration/rpctransact/transact_server_test.go +++ b/integration/rpctransact/transact_server_test.go @@ -102,7 +102,7 @@ func TestFormulateTx(t *testing.T) { require.NoError(t, err) // We should see the sign bytes embedded if !assert.Contains(t, string(bs), fmt.Sprintf("{\"ChainID\":\"%s\",\"Type\":\"CallTx\","+ - "\"Payload\":{\"Input\":{\"Address\":\"4A6DFB649EF0D50780998A686BD69AB175C08E26\",\"Amount\":230},"+ + "\"Payload\":{\"Input\":{\"Address\":\"E80BB91C2F0F4C3C39FC53E89BF8416B219BE6E4\",\"Amount\":230},"+ "\"Data\":\"0203060403\"}}", rpctest.GenesisDoc.ChainID())) { fmt.Println(string(bs)) } diff --git a/keys/server_test.go b/keys/server_test.go index 68ed229b2..68485dcd5 100644 --- a/keys/server_test.go +++ b/keys/server_test.go @@ -14,7 +14,7 @@ import ( "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/execution/evm/sha3" "github.com/hyperledger/burrow/logging" - tm_crypto "github.com/tendermint/go-crypto" + tm_crypto "github.com/tendermint/tendermint/crypto" "google.golang.org/grpc" ) diff --git a/protobuf/exec.proto b/protobuf/exec.proto index 58a8b2c98..172f540b8 100644 --- a/protobuf/exec.proto +++ b/protobuf/exec.proto @@ -5,7 +5,7 @@ package exec; option go_package = "github.com/hyperledger/burrow/execution/exec"; import "github.com/gogo/protobuf/gogoproto/gogo.proto"; -import "github.com/tendermint/abci/types/types.proto"; +import "github.com/tendermint/tendermint/abci/types/types.proto"; import "errors.proto"; import "names.proto"; diff --git a/rpc/lib/client/ws_client.go b/rpc/lib/client/ws_client.go index e93f06908..751de2708 100644 --- a/rpc/lib/client/ws_client.go +++ b/rpc/lib/client/ws_client.go @@ -13,7 +13,7 @@ import ( "github.com/hyperledger/burrow/rpc/lib/types" "github.com/pkg/errors" metrics "github.com/rcrowley/go-metrics" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) const ( diff --git a/rpc/lib/rpc_test.go b/rpc/lib/rpc_test.go index 1d21c21a1..db1f99a97 100644 --- a/rpc/lib/rpc_test.go +++ b/rpc/lib/rpc_test.go @@ -20,8 +20,8 @@ import ( "github.com/hyperledger/burrow/rpc/lib/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/log" + cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/log" ) // Client and Server should work over tcp or unix sockets diff --git a/rpc/lib/server/handlers.go b/rpc/lib/server/handlers.go index 506425b72..274ee30f2 100644 --- a/rpc/lib/server/handlers.go +++ b/rpc/lib/server/handlers.go @@ -20,7 +20,7 @@ import ( "github.com/hyperledger/burrow/logging/structure" "github.com/hyperledger/burrow/rpc/lib/types" "github.com/pkg/errors" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) // RegisterRPCFuncs adds a route for each function in the funcMap, as well as general jsonrpc and websocket handlers for all functions. diff --git a/rpc/lib/server/parse_test.go b/rpc/lib/server/parse_test.go index 0b5550c23..6f3f7dcbe 100644 --- a/rpc/lib/server/parse_test.go +++ b/rpc/lib/server/parse_test.go @@ -6,7 +6,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - cmn "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tendermint/libs/common" ) func TestParseJSONMap(t *testing.T) { diff --git a/rpc/result_test.go b/rpc/result_test.go index ca972de49..9c66f47ad 100644 --- a/rpc/result_test.go +++ b/rpc/result_test.go @@ -26,10 +26,10 @@ import ( "github.com/hyperledger/burrow/binary" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - goCrypto "github.com/tendermint/go-crypto" "github.com/tendermint/tendermint/consensus/types" + goCrypto "github.com/tendermint/tendermint/crypto" + "github.com/tendermint/tendermint/libs/common" tmTypes "github.com/tendermint/tendermint/types" - "github.com/tendermint/tmlibs/common" ) func TestResultListAccounts(t *testing.T) { From eb0c993d24867089a7cd6a682afb5f38f9e96d16 Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Sun, 22 Jul 2018 14:18:54 +0100 Subject: [PATCH 17/28] GovTx based validator set changes implemented and tested Signed-off-by: Silas Davis --- Gopkg.lock | 3 +- acm/balance/balance.go | 118 ++++ acm/balance/balance.pb.go | 337 ++++++++++ acm/balance/balance_test.go | 22 + acm/balance/type.go | 51 ++ acm/validator.go | 92 --- acm/validator/ring.go | 265 ++++++++ .../validator/ring_test.go | 26 +- .../validators.go => acm/validator/set.go | 126 ++-- .../validator/set_test.go | 8 +- acm/validator/validator.go | 27 + acm/validator/validator.pb.go | 405 ++++++++++++ acm/validator/validators.go | 111 ++++ acm/validator_test.go | 1 - {blockchain => bcm}/blockchain.go | 195 +++--- {blockchain => bcm}/blockchain_test.go | 23 +- blockchain/validators_ring.go | 198 ------ cmd/burrow/commands/configure.go | 4 +- cmd/burrow/commands/helpers.go | 2 +- cmd/burrow/commands/tx.go | 1 + config/config.go | 12 +- consensus/tendermint/abci/app.go | 90 +-- consensus/tendermint/config.go | 7 +- consensus/tendermint/{query => }/node_view.go | 12 +- .../{validator => }/priv_validator_memory.go | 2 +- .../tendermint/{validator => }/sign_info.go | 2 +- consensus/tendermint/tendermint.go | 8 +- consensus/tendermint/{validator => }/wire.go | 2 +- core/kernel.go | 98 +-- crypto/public_key.go | 12 + execution/contexts/call_context.go | 6 +- execution/contexts/governance_context.go | 36 +- execution/contexts/name_context.go | 4 +- execution/contexts/permissions_context.go | 16 +- execution/contexts/send_context.go | 9 +- execution/contexts/shared.go | 63 +- execution/errors/errors.go | 11 +- execution/errors/errors_test.go | 2 - execution/errors/vm.go | 5 +- execution/evm/vm.go | 20 +- execution/exec/exec.pb.go | 128 ++-- execution/execution.go | 55 +- execution/execution_test.go | 28 +- execution/simulated_call.go | 8 +- execution/transactor.go | 13 +- execution/transactor_test.go | 7 +- genesis/deterministic_genesis.go | 8 +- genesis/genesis.go | 30 +- genesis/genesis_test.go | 8 +- genesis/spec/genesis_spec.go | 8 +- genesis/spec/genesis_spec_test.go | 5 +- genesis/spec/presets.go | 20 +- genesis/spec/presets_test.go | 11 +- genesis/spec/spec.pb.go | 166 +++-- genesis/spec/template_account.go | 17 +- governance/governance.go | 38 ++ governance/governance_test.go | 23 + integration/core/kernel_test.go | 65 +- integration/governance/governance_test.go | 172 +++++ integration/governance/main_test.go | 55 +- integration/governance/validators_test.go | 7 - integration/integration.go | 71 +-- integration/integration_test.go | 28 + integration/rpcevents/main_test.go | 4 +- integration/rpcquery/main_test.go | 4 +- integration/rpctransact/main_test.go | 4 +- .../rpctransact/transact_server_test.go | 2 +- integration/tm/main_test.go | 4 +- logging/config/presets/instructions_test.go | 51 -- logging/config/sort.go | 1 - logging/lifecycle/lifecycle.go | 8 +- logging/{config => logconfig}/config.go | 16 +- logging/{config => logconfig}/config_test.go | 2 +- logging/{config => logconfig}/filter.go | 2 +- logging/{config => logconfig}/filter_test.go | 2 +- .../presets/instructions.go | 64 +- .../logconfig/presets/instructions_test.go | 51 ++ logging/{config => logconfig}/sinks.go | 13 +- logging/{config => logconfig}/sinks_test.go | 2 +- logging/logconfig/sort.go | 1 + logging/loggers/burrow_format_logger.go | 3 +- permission/account_permissions.go | 13 + permission/util.go | 23 +- permission/util_test.go | 10 +- protobuf/acm.proto | 7 +- protobuf/balance.proto | 20 + protobuf/exec.proto | 2 +- protobuf/payload.proto | 12 +- protobuf/rpcquery.proto | 15 + protobuf/rpctransact.proto | 10 +- protobuf/spec.proto | 25 +- protobuf/validator.proto | 22 + rpc/result.go | 8 +- rpc/rpcevents/execution_events_server.go | 6 +- rpc/rpcquery/query_server.go | 39 +- rpc/rpcquery/rpcquery.pb.go | 603 +++++++++++++++++- rpc/rpctransact/rpctransact.pb.go | 355 ++--------- rpc/rpctransact/transact_server.go | 60 +- rpc/service.go | 39 +- txs/amino_codec.go | 4 +- txs/payload/bond_tx.go | 6 + txs/payload/call_tx.go | 6 + txs/payload/gov_tx.go | 23 + txs/payload/governance_tx.go | 17 - txs/payload/name_tx.go | 6 + txs/payload/payload.go | 50 +- txs/payload/payload.pb.go | 391 ++++++++---- txs/payload/{permission_tx.go => perms_tx.go} | 22 +- txs/payload/send_tx.go | 6 + txs/payload/unbond_tx.go | 6 + txs/tx.go | 2 +- txs/tx_test.go | 4 +- util/logging/cmd/main.go | 2 +- 113 files changed, 3711 insertions(+), 1740 deletions(-) create mode 100644 acm/balance/balance.go create mode 100644 acm/balance/balance.pb.go create mode 100644 acm/balance/balance_test.go create mode 100644 acm/balance/type.go delete mode 100644 acm/validator.go create mode 100644 acm/validator/ring.go rename blockchain/validators_ring_test.go => acm/validator/ring_test.go (86%) rename blockchain/validators.go => acm/validator/set.go (51%) rename blockchain/validators_test.go => acm/validator/set_test.go (81%) create mode 100644 acm/validator/validator.go create mode 100644 acm/validator/validator.pb.go create mode 100644 acm/validator/validators.go delete mode 100644 acm/validator_test.go rename {blockchain => bcm}/blockchain.go (53%) rename {blockchain => bcm}/blockchain_test.go (60%) delete mode 100644 blockchain/validators_ring.go create mode 100644 cmd/burrow/commands/tx.go rename consensus/tendermint/{query => }/node_view.go (86%) rename consensus/tendermint/{validator => }/priv_validator_memory.go (98%) rename consensus/tendermint/{validator => }/sign_info.go (99%) rename consensus/tendermint/{validator => }/wire.go (89%) create mode 100644 governance/governance_test.go create mode 100644 integration/governance/governance_test.go delete mode 100644 integration/governance/validators_test.go create mode 100644 integration/integration_test.go delete mode 100644 logging/config/presets/instructions_test.go delete mode 100644 logging/config/sort.go rename logging/{config => logconfig}/config.go (84%) rename logging/{config => logconfig}/config_test.go (97%) rename logging/{config => logconfig}/filter.go (99%) rename logging/{config => logconfig}/filter_test.go (99%) rename logging/{config => logconfig}/presets/instructions.go (66%) create mode 100644 logging/logconfig/presets/instructions_test.go rename logging/{config => logconfig}/sinks.go (97%) rename logging/{config => logconfig}/sinks_test.go (99%) create mode 100644 logging/logconfig/sort.go create mode 100644 protobuf/balance.proto create mode 100644 protobuf/validator.proto create mode 100644 txs/payload/gov_tx.go delete mode 100644 txs/payload/governance_tx.go rename txs/payload/{permission_tx.go => perms_tx.go} (53%) diff --git a/Gopkg.lock b/Gopkg.lock index 6eb70eacc..ac4f2f285 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -572,14 +572,15 @@ "github.com/tendermint/tendermint/consensus", "github.com/tendermint/tendermint/consensus/types", "github.com/tendermint/tendermint/crypto", + "github.com/tendermint/tendermint/crypto/tmhash", "github.com/tendermint/tendermint/libs/common", "github.com/tendermint/tendermint/libs/db", "github.com/tendermint/tendermint/libs/log", "github.com/tendermint/tendermint/libs/pubsub", - "github.com/tendermint/tendermint/mempool", "github.com/tendermint/tendermint/node", "github.com/tendermint/tendermint/p2p", "github.com/tendermint/tendermint/proxy", + "github.com/tendermint/tendermint/rpc/core", "github.com/tendermint/tendermint/rpc/core/types", "github.com/tendermint/tendermint/state", "github.com/tendermint/tendermint/types", diff --git a/acm/balance/balance.go b/acm/balance/balance.go new file mode 100644 index 000000000..20b5cc85a --- /dev/null +++ b/acm/balance/balance.go @@ -0,0 +1,118 @@ +package balance + +import "fmt" + +type Balances []Balance + +func (b Balance) String() string { + return fmt.Sprintf("{%v: %d}", b.Type, b.Amount) +} + +func New() Balances { + return []Balance{} +} + +func (bs Balances) Len() int { + return len(bs) +} + +func (bs Balances) Less(i, j int) bool { + if bs[i].Type < bs[j].Type { + return true + } + return bs[i].Type == bs[j].Type && bs[i].Amount < bs[j].Amount +} + +func (bs Balances) Swap(i, j int) { + bs[i], bs[j] = bs[j], bs[i] +} + +func (bs Balances) Add(ty Type, amount uint64) Balances { + return append(bs, Balance{ + Type: ty, + Amount: amount, + }) +} + +func (bs Balances) Native(amount uint64) Balances { + return bs.Add(TypeNative, amount) +} + +func (bs Balances) Power(amount uint64) Balances { + return bs.Add(TypePower, amount) +} + +func (bs Balances) Sum(bss ...Balances) Balances { + return Sum(append(bss, bs)...) +} + +func Sum(bss ...Balances) Balances { + sum := New() + sumMap := make(map[Type]uint64) + for _, bs := range bss { + for _, b := range bs { + sumMap[b.Type] += b.Amount + } + } + for k, v := range sumMap { + sum = sum.Add(k, v) + } + return sum +} + +func Native(native uint64) Balance { + return Balance{ + Type: TypeNative, + Amount: native, + } +} + +func Power(power uint64) Balance { + return Balance{ + Type: TypePower, + Amount: power, + } +} + +func (bs Balances) Has(ty Type) bool { + for _, b := range bs { + if b.Type == ty { + return true + } + } + return false +} + +func (bs Balances) Get(ty Type) *uint64 { + for _, b := range bs { + if b.Type == ty { + return &b.Amount + } + } + return nil +} + +func (bs Balances) GetFallback(ty Type, fallback uint64) uint64 { + for _, b := range bs { + if b.Type == ty { + return b.Amount + } + } + return fallback +} + +func (bs Balances) GetNative(fallback uint64) uint64 { + return bs.GetFallback(TypeNative, fallback) +} + +func (bs Balances) GetPower(fallback uint64) uint64 { + return bs.GetFallback(TypePower, fallback) +} + +func (bs Balances) HasNative() bool { + return bs.Has(TypeNative) +} + +func (bs Balances) HasPower() bool { + return bs.Has(TypePower) +} diff --git a/acm/balance/balance.pb.go b/acm/balance/balance.pb.go new file mode 100644 index 000000000..c1e0bdbd2 --- /dev/null +++ b/acm/balance/balance.pb.go @@ -0,0 +1,337 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: balance.proto + +/* + Package balance is a generated protocol buffer package. + + It is generated from these files: + balance.proto + + It has these top-level messages: + Balance +*/ +package balance + +import proto "github.com/gogo/protobuf/proto" +import golang_proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" +import _ "github.com/gogo/protobuf/gogoproto" + +import io "io" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = golang_proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package + +type Balance struct { + Type Type `protobuf:"varint,1,opt,name=Type,proto3,casttype=Type" json:"Type,omitempty"` + Amount uint64 `protobuf:"varint,2,opt,name=Amount,proto3" json:"Amount,omitempty"` +} + +func (m *Balance) Reset() { *m = Balance{} } +func (*Balance) ProtoMessage() {} +func (*Balance) Descriptor() ([]byte, []int) { return fileDescriptorBalance, []int{0} } + +func (m *Balance) GetType() Type { + if m != nil { + return m.Type + } + return 0 +} + +func (m *Balance) GetAmount() uint64 { + if m != nil { + return m.Amount + } + return 0 +} + +func (*Balance) XXX_MessageName() string { + return "balance.Balance" +} +func init() { + proto.RegisterType((*Balance)(nil), "balance.Balance") + golang_proto.RegisterType((*Balance)(nil), "balance.Balance") +} +func (m *Balance) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Balance) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.Type != 0 { + dAtA[i] = 0x8 + i++ + i = encodeVarintBalance(dAtA, i, uint64(m.Type)) + } + if m.Amount != 0 { + dAtA[i] = 0x10 + i++ + i = encodeVarintBalance(dAtA, i, uint64(m.Amount)) + } + return i, nil +} + +func encodeVarintBalance(dAtA []byte, offset int, v uint64) int { + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return offset + 1 +} +func (m *Balance) Size() (n int) { + var l int + _ = l + if m.Type != 0 { + n += 1 + sovBalance(uint64(m.Type)) + } + if m.Amount != 0 { + n += 1 + sovBalance(uint64(m.Amount)) + } + return n +} + +func sovBalance(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n +} +func sozBalance(x uint64) (n int) { + return sovBalance(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Balance) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowBalance + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Balance: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Balance: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) + } + m.Type = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowBalance + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Type |= (Type(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) + } + m.Amount = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowBalance + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Amount |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipBalance(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthBalance + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipBalance(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowBalance + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowBalance + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowBalance + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + iNdEx += length + if length < 0 { + return 0, ErrInvalidLengthBalance + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowBalance + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipBalance(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} + +var ( + ErrInvalidLengthBalance = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowBalance = fmt.Errorf("proto: integer overflow") +) + +func init() { proto.RegisterFile("balance.proto", fileDescriptorBalance) } +func init() { golang_proto.RegisterFile("balance.proto", fileDescriptorBalance) } + +var fileDescriptorBalance = []byte{ + // 187 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x4d, 0x4a, 0xcc, 0x49, + 0xcc, 0x4b, 0x4e, 0xd5, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x87, 0x72, 0xa5, 0x74, 0xd3, + 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, 0xd3, 0xf3, 0xd3, 0xf3, 0xf5, 0xc1, + 0xf2, 0x49, 0xa5, 0x69, 0x60, 0x1e, 0x98, 0x03, 0x66, 0x41, 0xf4, 0x29, 0xb9, 0x72, 0xb1, 0x3b, + 0x41, 0x74, 0x0a, 0xc9, 0x70, 0xb1, 0x84, 0x54, 0x16, 0xa4, 0x4a, 0x30, 0x2a, 0x30, 0x6a, 0xf0, + 0x3a, 0x71, 0xfc, 0xba, 0x27, 0x0f, 0xe6, 0x07, 0x81, 0x49, 0x21, 0x31, 0x2e, 0x36, 0xc7, 0xdc, + 0xfc, 0xd2, 0xbc, 0x12, 0x09, 0x26, 0x05, 0x46, 0x0d, 0x96, 0x20, 0x28, 0xcf, 0x8a, 0x65, 0xc6, + 0x02, 0x79, 0x06, 0x27, 0xfb, 0x13, 0x8f, 0xe4, 0x18, 0x2f, 0x3c, 0x92, 0x63, 0x7c, 0xf0, 0x48, + 0x8e, 0xf1, 0xc0, 0x63, 0x39, 0xc6, 0x13, 0x8f, 0xe5, 0x18, 0xa3, 0x34, 0x91, 0xdc, 0x92, 0x51, + 0x59, 0x90, 0x5a, 0x94, 0x93, 0x9a, 0x92, 0x9e, 0x5a, 0xa4, 0x9f, 0x54, 0x5a, 0x54, 0x94, 0x5f, + 0xae, 0x9f, 0x98, 0x9c, 0xab, 0x0f, 0x75, 0x76, 0x12, 0x1b, 0xd8, 0x39, 0xc6, 0x80, 0x00, 0x00, + 0x00, 0xff, 0xff, 0x1d, 0x22, 0xfc, 0x8b, 0xd7, 0x00, 0x00, 0x00, +} diff --git a/acm/balance/balance_test.go b/acm/balance/balance_test.go new file mode 100644 index 000000000..d6710e09a --- /dev/null +++ b/acm/balance/balance_test.go @@ -0,0 +1,22 @@ +package balance + +import ( + "sort" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestSum(t *testing.T) { + one := New().Power(23223).Native(34).Native(1111) + two := New().Power(3).Native(22) + sum := one.Sum(two) + assert.Equal(t, New().Power(23226).Native(1167), sum) +} + +func TestSort(t *testing.T) { + balances := New().Power(232).Native(2523543).Native(232).Power(2).Power(4).Native(1) + sortedBalances := New().Native(1).Native(232).Native(2523543).Power(2).Power(4).Power(232) + sort.Sort(balances) + assert.Equal(t, sortedBalances, balances) +} diff --git a/acm/balance/type.go b/acm/balance/type.go new file mode 100644 index 000000000..8b8ece9a4 --- /dev/null +++ b/acm/balance/type.go @@ -0,0 +1,51 @@ +package balance + +type Type uint32 + +const ( + TypeNative Type = 1 + TypePower Type = 2 +) + +var nameFromType = map[Type]string{ + TypeNative: "Native", + TypePower: "Power", +} + +var typeFromName = make(map[string]Type) + +func init() { + for t, n := range nameFromType { + typeFromName[n] = t + } +} + +func TypeFromString(name string) Type { + return typeFromName[name] +} + +func (typ Type) String() string { + name, ok := nameFromType[typ] + if ok { + return name + } + return "UnknownBalanceType" +} + +func (typ Type) MarshalText() ([]byte, error) { + return []byte(typ.String()), nil +} + +func (typ *Type) UnmarshalText(data []byte) error { + *typ = TypeFromString(string(data)) + return nil +} + +// Protobuf support +func (typ Type) Marshal() ([]byte, error) { + return typ.MarshalText() +} + +func (typ *Type) Unmarshal(data []byte) error { + return typ.UnmarshalText(data) +} diff --git a/acm/validator.go b/acm/validator.go deleted file mode 100644 index ddf471ecd..000000000 --- a/acm/validator.go +++ /dev/null @@ -1,92 +0,0 @@ -package acm - -import ( - "encoding/json" - - "github.com/hyperledger/burrow/crypto" -) - -type Validator interface { - crypto.Addressable - // The validator's voting power - Power() uint64 -} - -// Neither abci_types or tm_types has quite the representation we want -type ConcreteValidator struct { - Address crypto.Address - PublicKey crypto.PublicKey - Power uint64 -} - -type concreteValidatorWrapper struct { - *ConcreteValidator `json:"unwrap"` -} - -var _ Validator = concreteValidatorWrapper{} - -func AsValidator(account Account) Validator { - return ConcreteValidator{ - Address: account.Address(), - PublicKey: account.PublicKey(), - Power: account.Balance(), - }.Validator() -} - -func AsConcreteValidator(validator Validator) *ConcreteValidator { - if validator == nil { - return nil - } - if ca, ok := validator.(concreteValidatorWrapper); ok { - return ca.ConcreteValidator - } - return &ConcreteValidator{ - Address: validator.Address(), - PublicKey: validator.PublicKey(), - Power: validator.Power(), - } -} - -func (cvw concreteValidatorWrapper) Address() crypto.Address { - return cvw.ConcreteValidator.Address -} - -func (cvw concreteValidatorWrapper) PublicKey() crypto.PublicKey { - return cvw.ConcreteValidator.PublicKey -} - -func (cvw concreteValidatorWrapper) Power() uint64 { - return cvw.ConcreteValidator.Power -} - -func (cvw concreteValidatorWrapper) WithNewPower(power uint64) Validator { - cv := cvw.Copy() - cv.Power = power - return concreteValidatorWrapper{ - ConcreteValidator: cv, - } -} - -func (cv ConcreteValidator) Validator() Validator { - return concreteValidatorWrapper{ - ConcreteValidator: &cv, - } -} - -func (cv *ConcreteValidator) Copy() *ConcreteValidator { - cvCopy := *cv - return &cvCopy -} - -func (cv *ConcreteValidator) String() string { - if cv == nil { - return "Nil Validator" - } - - bs, err := json.Marshal(cv) - if err != nil { - return "error serialising Validator" - } - - return string(bs) -} diff --git a/acm/validator/ring.go b/acm/validator/ring.go new file mode 100644 index 000000000..bbc6fa56e --- /dev/null +++ b/acm/validator/ring.go @@ -0,0 +1,265 @@ +package validator + +import ( + "fmt" + "math/big" + + "github.com/hyperledger/burrow/crypto" +) + +type Ring struct { + // The validator power history stored in buckets as a ring buffer + // The changes committed at rotation i + delta []*Set + // The cumulative changes at rotation i - 1 + cum []*Set + // Totals for each validator across all buckets + power *Set + // Current flow totals for each validator in the Head bucket + flow *Set + // Index of current head bucket + head int64 + // Number of buckets + size int64 +} + +var big1 = big.NewInt(1) +var big3 = big.NewInt(3) + +// Provides a sliding window over the last size buckets of validator power changes +func NewRing(initialSet Iterable, windowSize int) *Ring { + if windowSize < 1 { + windowSize = 1 + } + vw := &Ring{ + delta: make([]*Set, windowSize), + cum: make([]*Set, windowSize), + power: NewSet(), + flow: NewSet(), + size: int64(windowSize), + } + for i := 0; i < windowSize; i++ { + vw.delta[i] = NewSet() + // Important that this is trim set for accurate count + vw.cum[i] = NewTrimSet() + } + vw.cum[0] = Copy(initialSet) + + return vw +} + +// Implement Reader +// Get power at index from the delta bucket then falling through to the cumulative +func (vc *Ring) PowerAt(index int64, id crypto.Addressable) *big.Int { + power := vc.Head().MaybePower(id) + if power != nil { + return power + } + return vc.Cum().Power(id) +} + +func (vc *Ring) Power(id crypto.Addressable) *big.Int { + return vc.PowerAt(vc.head, id) +} + +// Return the resultant set at index of current cum plus delta +func (vc *Ring) Resultant(index int64) *Set { + i := vc.index(index) + cum := CopyTrim(vc.cum[i]) + vc.delta[i].Iterate(func(id crypto.Addressable, power *big.Int) (stop bool) { + cum.AlterPower(id, power) + return + }) + return cum +} + +func (vc *Ring) TotalPower() *big.Int { + return vc.Resultant(vc.head).totalPower +} + +// Updates the current head bucket (accumulator) with some safety checks +func (vc *Ring) AlterPower(id crypto.Addressable, power *big.Int) (*big.Int, error) { + if power.Sign() == -1 { + return nil, fmt.Errorf("cannot set negative validator power: %v", power) + } + if !power.IsInt64() { + return nil, fmt.Errorf("for tendermint compatibility validator power must fit within an Int64 bur %v "+ + "does not", power) + } + // if flow > maxflow then we cannot alter the power + flow := vc.Flow(id, power) + maxFlow := vc.MaxFlow() + // Set flow for this id to update flow.totalPower (total flow) for comparison below, keep track of flow for each id + // so that we only count flow once for each id + vc.flow.ChangePower(id, flow) + // The totalPower of the Flow Set is the absolute value of all power changes made so far + if vc.flow.totalPower.Cmp(maxFlow) == 1 { + // Reset flow to previous value to undo update above + prevFlow := vc.Flow(id, vc.Head().Power(id)) + vc.flow.ChangePower(id, prevFlow) + allowable := new(big.Int).Sub(maxFlow, vc.flow.totalPower) + return nil, fmt.Errorf("cannot change validator power of %v from %v to %v because that would result in a flow "+ + "greater than or equal to 1/3 of total power for the next commit: flow induced by change: %v, "+ + "current total flow: %v/%v (cumulative/max), remaining allowable flow: %v", + id.Address(), vc.Cum().Power(id), power, flow, vc.flow.totalPower, maxFlow, allowable) + } + // Add to total power + vc.Head().ChangePower(id, power) + return flow, nil +} + +// Returns the flow that would be induced by a validator change by comparing the head accumulater with the current set +func (vc *Ring) Flow(id crypto.Addressable, power *big.Int) *big.Int { + flow := new(big.Int) + return flow.Abs(flow.Sub(power, vc.Cum().Power(id))) +} + +// To ensure that in the maximum valildator shift at least one unit +// of validator power in the intersection of last block validators and this block validators must have at least one +// non-byzantine validator who can tell you if you've been lied to about the validator set +// So need at most ceiling((Total Power)/3) - 1, in integer division we have ceiling(X*p/q) = (p(X+1)-1)/q +// For p = 1 just X/q +// So we want (Total Power)/3 - 1 +func (vc *Ring) MaxFlow() *big.Int { + max := vc.Cum().TotalPower() + return max.Sub(max.Div(max, big3), big1) +} + +// Advance the current head bucket to the next bucket and returns the change in total power between the previous bucket +// and the current head, and the total flow which is the sum of absolute values of all changes each validator's power +// after rotation the next head is a copy of the current head +func (vc *Ring) Rotate() (totalPowerChange *big.Int, totalFlow *big.Int, err error) { + // Subtract the tail bucket (if any) from the total + err = Subtract(vc.power, vc.Next()) + if err != nil { + return + } + // Add head delta to total power + err = Add(vc.power, vc.Head()) + if err != nil { + return + } + // Copy current cumulative bucket + cum := CopyTrim(vc.Cum()) + // Copy delta into what will be the next cumulative bucket + err = Alter(cum, vc.Head()) + if err != nil { + return + } + // Advance the ring buffer + vc.head = vc.index(1) + // Overwrite new head bucket (previous tail) with a fresh delta accumulator + vc.delta[vc.head] = NewSet() + // Set the next cum + vc.cum[vc.head] = cum + // Capture flow before we wipe it + totalFlow = vc.flow.totalPower + // New flow accumulator + vc.flow = NewSet() + // Subtract the previous bucket total power so we can add on the current buckets power after this + totalPowerChange = new(big.Int).Sub(vc.Cum().TotalPower(), vc.cum[vc.index(-1)].TotalPower()) + return +} + +func (vc *Ring) CurrentSet() *Set { + return vc.cum[vc.head] +} + +func (vc *Ring) PreviousSet() *Set { + return vc.cum[vc.index(-1)] +} + +func (vc *Ring) Cum() *Set { + return vc.cum[vc.head] +} + +// Get the current accumulator bucket +func (vc *Ring) Head() *Set { + return vc.delta[vc.head] +} + +func (vc *Ring) Next() *Set { + return vc.delta[vc.index(1)] +} + +func (vc *Ring) index(i int64) int64 { + idx := (vc.size + vc.head + i) % vc.size + return idx +} + +// Get the number of buckets in the ring (use Current().Count() to get the current number of validators) +func (vc *Ring) Size() int64 { + return vc.size +} + +// Returns buckets in order head, previous, ... +func (vc *Ring) OrderedBuckets() (delta, cum []*Set) { + delta = make([]*Set, len(vc.delta)) + cum = make([]*Set, len(vc.cum)) + for i := int64(0); i < vc.size; i++ { + index := vc.index(-i) + delta[i] = vc.delta[index] + cum[i] = vc.cum[index] + } + return +} + +func (vc *Ring) String() string { + delta, _ := vc.OrderedBuckets() + return fmt.Sprintf("ValidatorsWindow{Total: %v; Delta: Head->%v<-Tail}", vc.power, delta) +} + +func (vc *Ring) Equal(vwOther *Ring) bool { + if vc.size != vwOther.size || vc.head != vwOther.head || len(vc.delta) != len(vwOther.delta) || + !vc.flow.Equal(vwOther.flow) || !vc.power.Equal(vwOther.power) { + return false + } + for i := 0; i < len(vc.delta); i++ { + if !vc.delta[i].Equal(vwOther.delta[i]) || !vc.cum[i].Equal(vwOther.cum[i]) { + return false + } + } + return true +} + +type PersistedRing struct { + Delta [][]*Validator + Cum [][]*Validator + Power []*Validator + Flow []*Validator + Head int64 +} + +func (vc *Ring) Persistable() PersistedRing { + delta := make([][]*Validator, len(vc.delta)) + cum := make([][]*Validator, len(vc.cum)) + for i := 0; i < len(delta); i++ { + delta[i] = vc.delta[i].Validators() + cum[i] = vc.cum[i].Validators() + + } + return PersistedRing{ + Delta: delta, + Cum: cum, + Power: vc.power.Validators(), + Flow: vc.flow.Validators(), + Head: vc.head, + } +} + +func UnpersistRing(pc PersistedRing) *Ring { + delta := make([]*Set, len(pc.Delta)) + cum := make([]*Set, len(pc.Cum)) + for i := 0; i < len(delta); i++ { + delta[i] = UnpersistSet(pc.Delta[i]) + cum[i] = UnpersistSet(pc.Cum[i]) + } + return &Ring{ + delta: delta, + cum: cum, + head: pc.Head, + power: UnpersistSet(pc.Power), + flow: UnpersistSet(pc.Flow), + size: int64(len(delta)), + } +} diff --git a/blockchain/validators_ring_test.go b/acm/validator/ring_test.go similarity index 86% rename from blockchain/validators_ring_test.go rename to acm/validator/ring_test.go index d0c816288..66d00db9d 100644 --- a/blockchain/validators_ring_test.go +++ b/acm/validator/ring_test.go @@ -1,4 +1,4 @@ -package blockchain +package validator import ( "fmt" @@ -14,10 +14,12 @@ var pubB = pubKey(2) var pubC = pubKey(3) func TestValidatorsWindow_AlterPower(t *testing.T) { - vs := NewValidators() + vsBase := NewSet() powAInitial := int64(10000) - vs.AlterPower(pubA, big.NewInt(powAInitial)) - vw := NewValidatorsRing(vs, 3) + vsBase.ChangePower(pubA, big.NewInt(powAInitial)) + + vs := Copy(vsBase) + vw := NewRing(vs, 3) // Just allowable validator tide var powA, powB, powC int64 = 7000, 23, 309 @@ -27,7 +29,8 @@ func TestValidatorsWindow_AlterPower(t *testing.T) { assert.Equal(t, big.NewInt(powAInitial/3-1), totalFlow) // This one is not - vw = NewValidatorsRing(vs, 5) + vs = Copy(vsBase) + vw = NewRing(vs, 5) powA, powB, powC = 7000, 23, 310 powerChange, totalFlow, err = alterPowers(t, vw, powA, powB, powC) require.Error(t, err) @@ -77,21 +80,21 @@ func TestValidatorsWindow_AlterPower(t *testing.T) { func TestValidatorsRing_Persistable(t *testing.T) { - vs := NewValidators() + vs := NewSet() powAInitial := int64(10000) - vs.AlterPower(pubA, big.NewInt(powAInitial)) - vw := NewValidatorsRing(vs, 30) + vs.ChangePower(pubA, big.NewInt(powAInitial)) + vw := NewRing(vs, 30) for i := int64(0); i < 61; i++ { _, _, err := alterPowers(t, vw, 10000, 200*i, 200*((i+1)%4)) require.NoError(t, err) } - vwOut := UnpersistValidatorsRing(vw.Persistable()) + vwOut := UnpersistRing(vw.Persistable()) assert.True(t, vw.Equal(vwOut), "should re equal across persistence") } -func alterPowers(t testing.TB, vw *ValidatorsRing, powA, powB, powC int64) (powerChange, totalFlow *big.Int, err error) { +func alterPowers(t testing.TB, vw *Ring, powA, powB, powC int64) (powerChange, totalFlow *big.Int, err error) { fmt.Println(vw) _, err = vw.AlterPower(pubA, big.NewInt(powA)) if err != nil { @@ -106,7 +109,8 @@ func alterPowers(t testing.TB, vw *ValidatorsRing, powA, powB, powC int64) (powe return nil, nil, err } maxFlow := vw.MaxFlow() - powerChange, totalFlow = vw.Rotate() + powerChange, totalFlow, err = vw.Rotate() + require.NoError(t, err) // totalFlow > maxFlow if totalFlow.Cmp(maxFlow) == 1 { return powerChange, totalFlow, fmt.Errorf("totalFlow (%v) exceeds maxFlow (%v)", totalFlow, maxFlow) diff --git a/blockchain/validators.go b/acm/validator/set.go similarity index 51% rename from blockchain/validators.go rename to acm/validator/set.go index ea2ddfd47..1ce7d0101 100644 --- a/blockchain/validators.go +++ b/acm/validator/set.go @@ -1,4 +1,4 @@ -package blockchain +package validator import ( "fmt" @@ -12,80 +12,76 @@ import ( var big0 = big.NewInt(0) // A Validator multiset - can be used to capture the global state of validators or as an accumulator each block -type Validators struct { +type Set struct { powers map[crypto.Address]*big.Int publicKeys map[crypto.Address]crypto.Addressable totalPower *big.Int + trim bool } -type ValidatorSet interface { - AlterPower(id crypto.Addressable, power *big.Int) (flow *big.Int, err error) -} - -// Create a new Validators which can act as an accumulator for validator power changes -func NewValidators() *Validators { - return &Validators{ +func newSet() *Set { + return &Set{ totalPower: new(big.Int), powers: make(map[crypto.Address]*big.Int), publicKeys: make(map[crypto.Address]crypto.Addressable), } } +// Create a new Validators which can act as an accumulator for validator power changes +func NewSet() *Set { + return newSet() +} + +// Like Set but removes entries when power is set to 0 this make Count() == CountNonZero() and prevents a set from leaking +// but does mean that a zero will not be iterated over when performing an update which is necessary in Ring +func NewTrimSet() *Set { + s := newSet() + s.trim = true + return s +} + +// Implements Writer, but will never error +func (vs *Set) AlterPower(id crypto.Addressable, power *big.Int) (flow *big.Int, err error) { + return vs.ChangePower(id, power), nil +} + // Add the power of a validator and returns the flow into that validator -func (vs *Validators) AlterPower(id crypto.Addressable, power *big.Int) *big.Int { - if power.Sign() == -1 { - panic("ASRRRH") - } +func (vs *Set) ChangePower(id crypto.Addressable, power *big.Int) *big.Int { address := id.Address() // Calculcate flow into this validator (postive means in, negative means out) flow := new(big.Int).Sub(power, vs.Power(id)) vs.totalPower.Add(vs.totalPower, flow) - if power.Cmp(big0) == 0 { - // Remove from set so that we return an accurate length + + if vs.trim && power.Sign() == 0 { delete(vs.publicKeys, address) delete(vs.powers, address) - return flow + } else { + vs.publicKeys[address] = crypto.MemoizeAddressable(id) + vs.powers[address] = new(big.Int).Set(power) } - vs.publicKeys[address] = crypto.MemoizeAddressable(id) - vs.powers[address] = new(big.Int).Set(power) return flow } -// Adds vsOther to vs -func (vs *Validators) Add(vsOther *Validators) { - vsOther.Iterate(func(id crypto.Addressable, power *big.Int) (stop bool) { - vs.AddPower(id, power) - return - }) -} - -func (vs *Validators) AddPower(id crypto.Addressable, power *big.Int) { - // Current power + power - vs.AlterPower(id, new(big.Int).Add(vs.Power(id), power)) -} - -// Subtracts vsOther from vs -func (vs *Validators) Subtract(vsOther *Validators) { - vsOther.Iterate(func(id crypto.Addressable, power *big.Int) (stop bool) { - vs.SubtractPower(id, power) - return - }) +func (vs *Set) TotalPower() *big.Int { + return new(big.Int).Set(vs.totalPower) } -func (vs *Validators) SubtractPower(id crypto.Addressable, power *big.Int) { - // Current power - power - thisPower := vs.Power(id) - vs.AlterPower(id, new(big.Int).Sub(thisPower, power)) +// Returns the power of id but only if it is set +func (vs *Set) MaybePower(id crypto.Addressable) *big.Int { + if vs.powers[id.Address()] == nil { + return nil + } + return new(big.Int).Set(vs.powers[id.Address()]) } -func (vs *Validators) Power(id crypto.Addressable) *big.Int { +func (vs *Set) Power(id crypto.Addressable) *big.Int { if vs.powers[id.Address()] == nil { return new(big.Int) } return new(big.Int).Set(vs.powers[id.Address()]) } -func (vs *Validators) Equal(vsOther *Validators) bool { +func (vs *Set) Equal(vsOther *Set) bool { if vs.Count() != vsOther.Count() { return false } @@ -100,7 +96,7 @@ func (vs *Validators) Equal(vsOther *Validators) bool { } // Iterates over validators sorted by address -func (vs *Validators) Iterate(iter func(id crypto.Addressable, power *big.Int) (stop bool)) (stopped bool) { +func (vs *Set) Iterate(iter func(id crypto.Addressable, power *big.Int) (stop bool)) (stopped bool) { if vs == nil { return } @@ -117,55 +113,47 @@ func (vs *Validators) Iterate(iter func(id crypto.Addressable, power *big.Int) ( return } -func (vs *Validators) Count() int { - return len(vs.publicKeys) -} - -func (vs *Validators) TotalPower() *big.Int { - return new(big.Int).Set(vs.totalPower) -} - -func (vs *Validators) Copy() *Validators { - vsCopy := NewValidators() +func (vs *Set) CountNonZero() int { + var count int vs.Iterate(func(id crypto.Addressable, power *big.Int) (stop bool) { - vsCopy.AlterPower(id, power) + if power.Sign() != 0 { + count++ + } return }) - return vsCopy + return count } -type PersistedValidator struct { - PublicKey crypto.PublicKey - PowerBytes []byte +func (vs *Set) Count() int { + return len(vs.publicKeys) } -func (vs *Validators) Persistable() []PersistedValidator { +func (vs *Set) Validators() []*Validator { if vs == nil { return nil } - pvs := make([]PersistedValidator, 0, vs.Count()) + pvs := make([]*Validator, 0, vs.Count()) vs.Iterate(func(id crypto.Addressable, power *big.Int) (stop bool) { - pvs = append(pvs, PersistedValidator{PublicKey: id.PublicKey(), PowerBytes: power.Bytes()}) + pvs = append(pvs, &Validator{PublicKey: id.PublicKey(), Power: power.Uint64()}) return }) return pvs } -func UnpersistValidators(pvs []PersistedValidator) *Validators { - vs := NewValidators() +func UnpersistSet(pvs []*Validator) *Set { + vs := NewSet() for _, pv := range pvs { - power := new(big.Int).SetBytes(pv.PowerBytes) - vs.AlterPower(pv.PublicKey, power) + vs.ChangePower(pv.PublicKey, new(big.Int).SetUint64(pv.Power)) } return vs } -func (vs *Validators) String() string { +func (vs *Set) String() string { return fmt.Sprintf("Validators{TotalPower: %v; Count: %v; %v}", vs.TotalPower(), vs.Count(), - vs.ValidatorStrings()) + vs.Strings()) } -func (vs *Validators) ValidatorStrings() string { +func (vs *Set) Strings() string { strs := make([]string, 0, vs.Count()) vs.Iterate(func(id crypto.Addressable, power *big.Int) (stop bool) { strs = append(strs, fmt.Sprintf("%v->%v", id.Address(), power)) diff --git a/blockchain/validators_test.go b/acm/validator/set_test.go similarity index 81% rename from blockchain/validators_test.go rename to acm/validator/set_test.go index 1bc7970e4..ea0eeb635 100644 --- a/blockchain/validators_test.go +++ b/acm/validator/set_test.go @@ -1,4 +1,4 @@ -package blockchain +package validator import ( "fmt" @@ -11,12 +11,12 @@ import ( ) func TestValidators_AlterPower(t *testing.T) { - vs := NewValidators() + vs := NewSet() pow1 := big.NewInt(2312312321) pubA := pubKey(1) - vs.AlterPower(pubA, pow1) + vs.ChangePower(pubA, pow1) assert.Equal(t, pow1, vs.TotalPower()) - vs.AlterPower(pubA, big.NewInt(0)) + vs.ChangePower(pubA, big.NewInt(0)) assertZero(t, vs.TotalPower()) } diff --git a/acm/validator/validator.go b/acm/validator/validator.go new file mode 100644 index 000000000..d2bdc174c --- /dev/null +++ b/acm/validator/validator.go @@ -0,0 +1,27 @@ +package validator + +import ( + "fmt" + + "github.com/hyperledger/burrow/acm" +) + +func (v Validator) String() string { + return fmt.Sprintf("Validator{Address: %v, PublicKey: %v, Power: %v}", v.Address, v.PublicKey, v.Power) +} + +func (v Validator) FillAddress() { + if v.Address == nil { + address := v.PublicKey.Address() + v.Address = &address + } +} + +func FromAccount(acc acm.Account, power uint64) Validator { + address := acc.Address() + return Validator{ + Address: &address, + PublicKey: acc.PublicKey(), + Power: power, + } +} diff --git a/acm/validator/validator.pb.go b/acm/validator/validator.pb.go new file mode 100644 index 000000000..93c8b77d7 --- /dev/null +++ b/acm/validator/validator.pb.go @@ -0,0 +1,405 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: validator.proto + +/* + Package validator is a generated protocol buffer package. + + It is generated from these files: + validator.proto + + It has these top-level messages: + Validator +*/ +package validator + +import proto "github.com/gogo/protobuf/proto" +import golang_proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" +import _ "github.com/gogo/protobuf/gogoproto" +import _ "github.com/hyperledger/burrow/permission" +import crypto "github.com/hyperledger/burrow/crypto" + +import github_com_hyperledger_burrow_crypto "github.com/hyperledger/burrow/crypto" + +import io "io" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = golang_proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package + +type Validator struct { + Address *github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,1,opt,name=Address,proto3,customtype=github.com/hyperledger/burrow/crypto.Address" json:"Address,omitempty"` + PublicKey crypto.PublicKey `protobuf:"bytes,2,opt,name=PublicKey" json:"PublicKey"` + Power uint64 `protobuf:"varint,3,opt,name=Power,proto3" json:"Power,omitempty"` +} + +func (m *Validator) Reset() { *m = Validator{} } +func (*Validator) ProtoMessage() {} +func (*Validator) Descriptor() ([]byte, []int) { return fileDescriptorValidator, []int{0} } + +func (m *Validator) GetPublicKey() crypto.PublicKey { + if m != nil { + return m.PublicKey + } + return crypto.PublicKey{} +} + +func (m *Validator) GetPower() uint64 { + if m != nil { + return m.Power + } + return 0 +} + +func (*Validator) XXX_MessageName() string { + return "validator.Validator" +} +func init() { + proto.RegisterType((*Validator)(nil), "validator.Validator") + golang_proto.RegisterType((*Validator)(nil), "validator.Validator") +} +func (m *Validator) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Validator) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.Address != nil { + dAtA[i] = 0xa + i++ + i = encodeVarintValidator(dAtA, i, uint64(m.Address.Size())) + n1, err := m.Address.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n1 + } + dAtA[i] = 0x12 + i++ + i = encodeVarintValidator(dAtA, i, uint64(m.PublicKey.Size())) + n2, err := m.PublicKey.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n2 + if m.Power != 0 { + dAtA[i] = 0x18 + i++ + i = encodeVarintValidator(dAtA, i, uint64(m.Power)) + } + return i, nil +} + +func encodeVarintValidator(dAtA []byte, offset int, v uint64) int { + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return offset + 1 +} +func (m *Validator) Size() (n int) { + var l int + _ = l + if m.Address != nil { + l = m.Address.Size() + n += 1 + l + sovValidator(uint64(l)) + } + l = m.PublicKey.Size() + n += 1 + l + sovValidator(uint64(l)) + if m.Power != 0 { + n += 1 + sovValidator(uint64(m.Power)) + } + return n +} + +func sovValidator(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n +} +func sozValidator(x uint64) (n int) { + return sovValidator(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Validator) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowValidator + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Validator: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Validator: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowValidator + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthValidator + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + var v github_com_hyperledger_burrow_crypto.Address + m.Address = &v + if err := m.Address.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PublicKey", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowValidator + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthValidator + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.PublicKey.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Power", wireType) + } + m.Power = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowValidator + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Power |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipValidator(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthValidator + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipValidator(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowValidator + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowValidator + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowValidator + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + iNdEx += length + if length < 0 { + return 0, ErrInvalidLengthValidator + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowValidator + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipValidator(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} + +var ( + ErrInvalidLengthValidator = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowValidator = fmt.Errorf("proto: integer overflow") +) + +func init() { proto.RegisterFile("validator.proto", fileDescriptorValidator) } +func init() { golang_proto.RegisterFile("validator.proto", fileDescriptorValidator) } + +var fileDescriptorValidator = []byte{ + // 255 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x2f, 0x4b, 0xcc, 0xc9, + 0x4c, 0x49, 0x2c, 0xc9, 0x2f, 0xd2, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x84, 0x0b, 0x48, + 0xe9, 0xa6, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0xa7, 0xe7, 0xa7, 0xe7, + 0xeb, 0x83, 0x55, 0x24, 0x95, 0xa6, 0x81, 0x79, 0x60, 0x0e, 0x98, 0x05, 0xd1, 0x29, 0x25, 0x50, + 0x90, 0x5a, 0x94, 0x9b, 0x59, 0x5c, 0x9c, 0x99, 0x9f, 0x07, 0x15, 0xe1, 0x49, 0x2e, 0xaa, 0x2c, + 0x28, 0x81, 0xca, 0x2b, 0xad, 0x62, 0xe4, 0xe2, 0x0c, 0x83, 0x19, 0x2e, 0xe4, 0xc5, 0xc5, 0xee, + 0x98, 0x92, 0x52, 0x94, 0x5a, 0x5c, 0x2c, 0xc1, 0xa8, 0xc0, 0xa8, 0xc1, 0xe3, 0x64, 0x70, 0xeb, + 0x9e, 0xbc, 0x0e, 0x92, 0x8d, 0x19, 0x95, 0x05, 0xa9, 0x45, 0x39, 0xa9, 0x29, 0xe9, 0xa9, 0x45, + 0xfa, 0x49, 0xa5, 0x45, 0x45, 0xf9, 0xe5, 0xfa, 0x50, 0xe3, 0xa0, 0xfa, 0x82, 0x60, 0x06, 0x08, + 0x99, 0x72, 0x71, 0x06, 0x94, 0x26, 0xe5, 0x64, 0x26, 0x7b, 0xa7, 0x56, 0x4a, 0x30, 0x29, 0x30, + 0x6a, 0x70, 0x1b, 0x09, 0xea, 0x41, 0x15, 0xc3, 0x25, 0x9c, 0x58, 0x4e, 0xdc, 0x93, 0x67, 0x08, + 0x42, 0xa8, 0x14, 0x12, 0xe1, 0x62, 0x0d, 0xc8, 0x2f, 0x4f, 0x2d, 0x92, 0x60, 0x56, 0x60, 0xd4, + 0x60, 0x09, 0x82, 0x70, 0xac, 0x58, 0x66, 0x2c, 0x90, 0x67, 0x70, 0x72, 0x3c, 0xf1, 0x48, 0x8e, + 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x0f, 0x3c, 0x96, 0x63, 0x3c, 0xf1, 0x58, + 0x8e, 0x31, 0x4a, 0x1b, 0xbf, 0xfb, 0x12, 0x93, 0x73, 0xf5, 0xe1, 0xc1, 0x97, 0xc4, 0x06, 0xf6, + 0xb6, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x1c, 0xca, 0xd9, 0x6f, 0x63, 0x01, 0x00, 0x00, +} diff --git a/acm/validator/validators.go b/acm/validator/validators.go new file mode 100644 index 000000000..21313b7a7 --- /dev/null +++ b/acm/validator/validators.go @@ -0,0 +1,111 @@ +package validator + +import ( + "math/big" + + "sync" + + "github.com/hyperledger/burrow/crypto" +) + +type Writer interface { + AlterPower(id crypto.Addressable, power *big.Int) (flow *big.Int, err error) +} + +type Reader interface { + Power(id crypto.Addressable) *big.Int +} + +type Iterable interface { + Iterate(func(id crypto.Addressable, power *big.Int) (stop bool)) (stopped bool) +} + +type IterableReader interface { + Reader + Iterable +} + +type ReaderWriter interface { + Reader + Writer +} + +type IterableReaderWriter interface { + ReaderWriter + Iterable +} + +type WriterFunc func(id crypto.Addressable, power *big.Int) (flow *big.Int, err error) + +func SyncWriter(locker sync.Locker, writerFunc WriterFunc) WriterFunc { + return WriterFunc(func(id crypto.Addressable, power *big.Int) (flow *big.Int, err error) { + locker.Lock() + defer locker.Unlock() + return writerFunc(id, power) + }) +} + +func (wf WriterFunc) AlterPower(id crypto.Addressable, power *big.Int) (flow *big.Int, err error) { + return wf(id, power) +} + +func AddPower(vs ReaderWriter, id crypto.Addressable, power *big.Int) error { + // Current power + power + _, err := vs.AlterPower(id, new(big.Int).Add(vs.Power(id), power)) + return err +} + +func SubtractPower(vs ReaderWriter, id crypto.Addressable, power *big.Int) error { + _, err := vs.AlterPower(id, new(big.Int).Sub(vs.Power(id), power)) + return err +} + +func Alter(vs Writer, vsOther Iterable) (err error) { + vsOther.Iterate(func(id crypto.Addressable, power *big.Int) (stop bool) { + _, err = vs.AlterPower(id, power) + if err != nil { + return true + } + return + }) + return +} + +// Adds vsOther to vs +func Add(vs ReaderWriter, vsOther Iterable) (err error) { + vsOther.Iterate(func(id crypto.Addressable, power *big.Int) (stop bool) { + err = AddPower(vs, id, power) + if err != nil { + return true + } + return + }) + return +} + +// Subtracts vsOther from vs +func Subtract(vs ReaderWriter, vsOther Iterable) (err error) { + vsOther.Iterate(func(id crypto.Addressable, power *big.Int) (stop bool) { + err = SubtractPower(vs, id, power) + if err != nil { + return true + } + return + }) + return +} + +func Copy(vs Iterable) *Set { + vsCopy := NewSet() + vs.Iterate(func(id crypto.Addressable, power *big.Int) (stop bool) { + vsCopy.ChangePower(id, power) + return + }) + return vsCopy +} + +func CopyTrim(vs Iterable) *Set { + s := Copy(vs) + s.trim = true + return s +} diff --git a/acm/validator_test.go b/acm/validator_test.go deleted file mode 100644 index 512990819..000000000 --- a/acm/validator_test.go +++ /dev/null @@ -1 +0,0 @@ -package acm diff --git a/blockchain/blockchain.go b/bcm/blockchain.go similarity index 53% rename from blockchain/blockchain.go rename to bcm/blockchain.go index 43be5ca7b..d12afd6fa 100644 --- a/blockchain/blockchain.go +++ b/bcm/blockchain.go @@ -12,16 +12,17 @@ // See the License for the specific language governing permissions and // limitations under the License. -package blockchain +package bcm import ( "bytes" "fmt" "math/big" - "sync" "time" - "github.com/hyperledger/burrow/crypto" + "sync" + + "github.com/hyperledger/burrow/acm/validator" "github.com/hyperledger/burrow/genesis" "github.com/hyperledger/burrow/logging" "github.com/tendermint/go-amino" @@ -33,55 +34,44 @@ const DefaultValidatorsWindowSize = 10 var stateKey = []byte("BlockchainState") -type TipInfo interface { +type BlockchainInfo interface { + GenesisHash() []byte + GenesisDoc() genesis.GenesisDoc ChainID() string LastBlockHeight() uint64 LastBlockTime() time.Time LastBlockHash() []byte AppHashAfterLastBlock() []byte - IterateValidators(iter func(id crypto.Addressable, power *big.Int) (stop bool)) (stopped bool) + Validators() validator.IterableReader + ValidatorsHistory() (currentSet *validator.Set, deltas []*validator.Set, height uint64) NumValidators() int } -type BlockchainInfo interface { - TipInfo - GenesisHash() []byte - GenesisDoc() genesis.GenesisDoc -} - -type Root struct { - genesisHash []byte - genesisDoc genesis.GenesisDoc -} - -type Tip struct { +type Blockchain struct { + sync.RWMutex + db dbm.DB + genesisHash []byte + genesisDoc genesis.GenesisDoc chainID string lastBlockHeight uint64 lastBlockTime time.Time lastBlockHash []byte appHashAfterLastBlock []byte - validators *ValidatorsRing + validatorCache *validator.Ring + validatorCheckCache *validator.Ring } -type Blockchain struct { - *Root - *Tip - sync.RWMutex - db dbm.DB -} - -var _ TipInfo = &Blockchain{} +var _ BlockchainInfo = &Blockchain{} type PersistedState struct { AppHashAfterLastBlock []byte LastBlockHeight uint64 GenesisDoc genesis.GenesisDoc - Validators PersistedValidatorsRing + ValidatorSet []validator.Validator + ValidatorCache validator.PersistedRing } -func LoadOrNewBlockchain(db dbm.DB, genesisDoc *genesis.GenesisDoc, - logger *logging.Logger) (*Blockchain, error) { - +func LoadOrNewBlockchain(db dbm.DB, genesisDoc *genesis.GenesisDoc, logger *logging.Logger) (*Blockchain, error) { logger = logger.WithScope("LoadOrNewBlockchain") logger.InfoMsg("Trying to load blockchain state from database", "database_key", stateKey) @@ -94,7 +84,8 @@ func LoadOrNewBlockchain(db dbm.DB, genesisDoc *genesis.GenesisDoc, argHash := genesisDoc.Hash() if !bytes.Equal(dbHash, argHash) { return nil, fmt.Errorf("GenesisDoc passed to LoadOrNewBlockchain has hash: 0x%X, which does not "+ - "match the one found in database: 0x%X", argHash, dbHash) + "match the one found in database: 0x%X, database genesis:\n%v\npassed genesis:\n%v\n", + argHash, dbHash, bc.genesisDoc.JSONString(), genesisDoc.JSONString()) } return bc, nil } @@ -105,15 +96,19 @@ func LoadOrNewBlockchain(db dbm.DB, genesisDoc *genesis.GenesisDoc, // Pointer to blockchain state initialised from genesis func newBlockchain(db dbm.DB, genesisDoc *genesis.GenesisDoc) *Blockchain { - vs := NewValidators() + vs := validator.NewTrimSet() for _, gv := range genesisDoc.Validators { - vs.AlterPower(gv.PublicKey, new(big.Int).SetUint64(gv.Amount)) + vs.ChangePower(gv.PublicKey, new(big.Int).SetUint64(gv.Amount)) } - root := NewRoot(genesisDoc) bc := &Blockchain{ - db: db, - Root: root, - Tip: NewTip(genesisDoc.ChainID(), root.genesisDoc.GenesisTime, root.genesisHash, vs), + db: db, + genesisHash: genesisDoc.Hash(), + genesisDoc: *genesisDoc, + chainID: genesisDoc.ChainID(), + lastBlockTime: genesisDoc.GenesisTime, + appHashAfterLastBlock: genesisDoc.Hash(), + validatorCache: validator.NewRing(vs, DefaultValidatorsWindowSize), + validatorCheckCache: validator.NewRing(vs, 1), } return bc } @@ -131,50 +126,38 @@ func loadBlockchain(db dbm.DB) (*Blockchain, error) { return bc, nil } -func NewRoot(genesisDoc *genesis.GenesisDoc) *Root { - return &Root{ - genesisHash: genesisDoc.Hash(), - genesisDoc: *genesisDoc, - } +func (bc *Blockchain) ValidatorChecker() validator.Writer { + return validator.SyncWriter(bc, bc.validatorCheckCache.AlterPower) } -// Create genesis Tip -func NewTip(chainID string, genesisTime time.Time, genesisHash []byte, initialValidators *Validators) *Tip { - return &Tip{ - chainID: chainID, - lastBlockTime: genesisTime, - appHashAfterLastBlock: genesisHash, - validators: NewValidatorsRing(initialValidators, DefaultValidatorsWindowSize), - } +func (bc *Blockchain) ValidatorWriter() validator.Writer { + return validator.SyncWriter(bc, bc.validatorCache.AlterPower) } -func (bc *Blockchain) AlterPower(id crypto.Addressable, power *big.Int) (*big.Int, error) { - return bc.validators.AlterPower(id, power) -} - -func (bc *Blockchain) CommitBlock(blockTime time.Time, blockHash, appHash []byte) error { +func (bc *Blockchain) CommitBlock(blockTime time.Time, + blockHash, appHash []byte) (totalPowerChange, totalFlow *big.Int, err error) { bc.Lock() defer bc.Unlock() // Checkpoint on the _previous_ block. If we die, this is where we will resume since we know it must have been // committed since we are committing the next block. If we fall over we can resume a safe committed state and // Tendermint will catch us up - err := bc.save() + err = bc.save() + if err != nil { + return + } + totalPowerChange, totalFlow, err = bc.validatorCache.Rotate() if err != nil { - return err + return } - maxFlow := bc.validators.MaxFlow() - // Update validator set - _, totalFlow := bc.validators.Rotate() - if totalFlow.Cmp(maxFlow) == 1 { - return fmt.Errorf("total flow during block was %v exceeding the maximum allowablw flow of %v - this "+ - "should have been prevented on a per transaction basis - we cannot continue", - totalFlow, maxFlow) + _, _, err = bc.validatorCheckCache.Rotate() + if err != nil { + return } bc.lastBlockHeight += 1 bc.lastBlockTime = blockTime bc.lastBlockHash = blockHash bc.appHashAfterLastBlock = appHash - return nil + return } func (bc *Blockchain) save() error { @@ -195,7 +178,7 @@ func (bc *Blockchain) Encode() ([]byte, error) { GenesisDoc: bc.genesisDoc, AppHashAfterLastBlock: bc.appHashAfterLastBlock, LastBlockHeight: bc.lastBlockHeight, - Validators: bc.validators.Persistable(), + ValidatorCache: bc.validatorCache.Persistable(), } encodedState, err := cdc.MarshalBinary(persistedState) if err != nil { @@ -213,46 +196,84 @@ func DecodeBlockchain(encodedState []byte) (*Blockchain, error) { bc := newBlockchain(nil, &persistedState.GenesisDoc) bc.lastBlockHeight = persistedState.LastBlockHeight bc.appHashAfterLastBlock = persistedState.AppHashAfterLastBlock - bc.validators = UnpersistValidatorsRing(persistedState.Validators) + bc.validatorCache = validator.UnpersistRing(persistedState.ValidatorCache) + bc.validatorCheckCache = validator.UnpersistRing(persistedState.ValidatorCache) return bc, nil } -func (r *Root) GenesisHash() []byte { - return r.genesisHash +func (bc *Blockchain) GenesisHash() []byte { + return bc.genesisHash +} + +func (bc *Blockchain) GenesisDoc() genesis.GenesisDoc { + return bc.genesisDoc +} + +func (bc *Blockchain) ChainID() string { + return bc.chainID +} + +func (bc *Blockchain) LastBlockHeight() uint64 { + bc.RLock() + defer bc.RUnlock() + return bc.lastBlockHeight } -func (r *Root) GenesisDoc() genesis.GenesisDoc { - return r.genesisDoc +func (bc *Blockchain) LastBlockTime() time.Time { + bc.RLock() + defer bc.RUnlock() + return bc.lastBlockTime } -func (t *Tip) ChainID() string { - return t.chainID +func (bc *Blockchain) LastBlockHash() []byte { + bc.RLock() + defer bc.RUnlock() + return bc.lastBlockHash } -func (t *Tip) LastBlockHeight() uint64 { - return t.lastBlockHeight +func (bc *Blockchain) AppHashAfterLastBlock() []byte { + bc.RLock() + defer bc.RUnlock() + return bc.appHashAfterLastBlock } -func (t *Tip) LastBlockTime() time.Time { - return t.lastBlockTime +func (bc *Blockchain) PendingValidators() validator.IterableReader { + bc.RLock() + defer bc.RUnlock() + return bc.validatorCache.Head() } -func (t *Tip) LastBlockHash() []byte { - return t.lastBlockHash +func (bc *Blockchain) Validators() validator.IterableReader { + bc.RLock() + defer bc.RUnlock() + return bc.validatorCache.CurrentSet() } -func (t *Tip) AppHashAfterLastBlock() []byte { - return t.appHashAfterLastBlock +func (bc *Blockchain) ValidatorsHistory() (*validator.Set, []*validator.Set, uint64) { + bc.RLock() + defer bc.RUnlock() + delta, _ := bc.validatorCache.OrderedBuckets() + deltas := make([]*validator.Set, len(delta)) + for i, d := range delta { + deltas[i] = validator.Copy(d) + } + return validator.CopyTrim(bc.validatorCache.CurrentSet()), deltas, bc.lastBlockHeight } -func (t *Tip) Validators() *Validators { - return t.validators.Prev().Copy() +func (bc *Blockchain) CurrentValidators() *validator.Set { + bc.RLock() + defer bc.RUnlock() + return bc.validatorCache.CurrentSet() } -func (t *Tip) IterateValidators(iter func(id crypto.Addressable, power *big.Int) (stop bool)) (stopped bool) { - return t.validators.Prev().Copy().Iterate(iter) +func (bc *Blockchain) PreviousValidators() *validator.Set { + bc.RLock() + defer bc.RUnlock() + return bc.validatorCache.PreviousSet() } -func (t *Tip) NumValidators() int { - return t.validators.Prev().Count() +func (bc *Blockchain) NumValidators() int { + bc.RLock() + defer bc.RUnlock() + return bc.validatorCache.CurrentSet().Count() } diff --git a/blockchain/blockchain_test.go b/bcm/blockchain_test.go similarity index 60% rename from blockchain/blockchain_test.go rename to bcm/blockchain_test.go index aaa6f7ee3..c5f5bc627 100644 --- a/blockchain/blockchain_test.go +++ b/bcm/blockchain_test.go @@ -1,4 +1,4 @@ -package blockchain +package bcm import ( "fmt" @@ -7,12 +7,14 @@ import ( "time" "github.com/hyperledger/burrow/genesis" - "github.com/hyperledger/burrow/logging/config" + "github.com/hyperledger/burrow/logging/logconfig" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/libs/db" ) +var big0 = big.NewInt(0) + func TestBlockchain_Encode(t *testing.T) { genesisDoc, _, validators := genesis.NewDeterministicGenesis(234). GenesisDoc(5, true, 232, 3, true, 34) @@ -20,27 +22,32 @@ func TestBlockchain_Encode(t *testing.T) { bs, err := bc.Encode() require.NoError(t, err) bcOut, err := DecodeBlockchain(bs) - require.True(t, bc.validators.Equal(bcOut.validators)) + require.True(t, bc.validatorCache.Equal(bcOut.validatorCache)) require.Equal(t, bc.genesisDoc.GenesisTime, bcOut.genesisDoc.GenesisTime) - assert.Equal(t, config.JSONString(bc.genesisDoc), config.JSONString(bcOut.genesisDoc)) + assert.Equal(t, logconfig.JSONString(bc.genesisDoc), logconfig.JSONString(bcOut.genesisDoc)) require.Equal(t, bc.genesisDoc.Hash(), bcOut.genesisDoc.Hash()) power := new(big.Int).SetUint64(genesisDoc.Validators[1].Amount) id1 := validators[1].PublicKey() var flow *big.Int for i := 0; i < 100; i++ { power := power.Div(power, big.NewInt(2)) - flow, err = bc.AlterPower(id1, power) + flow, err = bc.ValidatorWriter().AlterPower(id1, power) fmt.Println(flow) require.NoError(t, err) - err = bc.CommitBlock(time.Now(), []byte("blockhash"), []byte("apphash")) + _, _, err = bc.CommitBlock(time.Now(), []byte("blockhash"), []byte("apphash")) require.NoError(t, err) bs, err = bc.Encode() require.NoError(t, err) bcOut, err = DecodeBlockchain(bs) - require.True(t, bc.validators.Equal(bcOut.validators)) + require.True(t, bc.validatorCache.Equal(bcOut.validatorCache)) } // Should have exponentially decayed to 0 assertZero(t, flow) - assertZero(t, bc.validators.Prev().Power(id1)) + assertZero(t, bc.validatorCache.Power(id1)) +} + +// Since we have -0 and 0 with big.Int due to its representation with a neg flag +func assertZero(t testing.TB, i *big.Int) { + assert.True(t, big0.Cmp(i) == 0, "expected 0 but got %v", i) } diff --git a/blockchain/validators_ring.go b/blockchain/validators_ring.go deleted file mode 100644 index 2709b27c7..000000000 --- a/blockchain/validators_ring.go +++ /dev/null @@ -1,198 +0,0 @@ -package blockchain - -import ( - "fmt" - "math/big" - - "github.com/hyperledger/burrow/crypto" -) - -type ValidatorsRing struct { - buckets []*Validators - // Totals for each validator across all buckets - power *Validators - // Current flow totals for each validator in the Head bucket - flow *Validators - // Index of current head bucekt - head int64 - size int64 -} - -var big1 = big.NewInt(1) -var big3 = big.NewInt(3) - -// Provides a sliding window over the last size buckets of validator power changes -func NewValidatorsRing(initialValidators *Validators, size int) *ValidatorsRing { - if size < 2 { - size = 2 - } - vw := &ValidatorsRing{ - buckets: make([]*Validators, size), - power: NewValidators(), - flow: NewValidators(), - size: int64(size), - } - for i := 0; i < size; i++ { - vw.buckets[i] = NewValidators() - } - - initialValidators.Iterate(func(id crypto.Addressable, power *big.Int) (stop bool) { - // Existing set - vw.buckets[vw.index(-1)].AlterPower(id, power) - // Current accumulator - vw.buckets[vw.head].AlterPower(id, power) - - vw.power.AddPower(id, power.Add(power, power)) - return - }) - - return vw -} - -// Updates the current head bucket (accumulator) with some safety checks -func (vw *ValidatorsRing) AlterPower(id crypto.Addressable, power *big.Int) (*big.Int, error) { - if power.Sign() == -1 { - return nil, fmt.Errorf("cannot set negative validator power: %v", power) - } - // if flow > maxflow then we cannot alter the power - flow := vw.Flow(id, power) - maxFlow := vw.MaxFlow() - // Set flow to update total flow - vw.flow.AlterPower(id, flow) - if vw.flow.totalPower.Cmp(maxFlow) == 1 { - // Reset flow to previous value - vw.flow.AlterPower(id, vw.Flow(id, vw.Head().Power(id))) - allowable := new(big.Int).Sub(maxFlow, vw.flow.totalPower) - return nil, fmt.Errorf("cannot change validator power of %v from %v to %v because that would result in a flow "+ - "greater than or equal to 1/3 of total power for the next commit: flow induced by change: %v, "+ - "current total flow: %v/%v (cumulative/max), remaining allowable flow: %v", - id.Address(), vw.Prev().Power(id), power, flow, vw.flow.totalPower, maxFlow, allowable) - } - // Add to total power - vw.Head().AlterPower(id, power) - return flow, nil -} - -// Returns the flow that would be induced by a validator change by comparing the current accumulator with the previous -// bucket -func (vw *ValidatorsRing) Flow(id crypto.Addressable, power *big.Int) *big.Int { - flow := new(big.Int) - prevPower := vw.Prev().Power(id) - return flow.Abs(flow.Sub(power, prevPower)) -} - -// To ensure that in the maximum valildator shift at least one unit -// of validator power in the intersection of last block validators and this block validators must have at least one -// non-byzantine validator who can tell you if you've been lied to about the validator set -// So need at most ceiling((Total Power)/3) - 1, in integer division we have ceiling(X*p/q) = (p(X+1)-1)/q -// For p = 1 just X/q -// So we want (Total Power)/3 - 1 -func (vw *ValidatorsRing) MaxFlow() *big.Int { - max := vw.Prev().TotalPower() - return max.Sub(max.Div(max, big3), big1) -} - -// Advance the current head bucket to the next bucket and returns the change in total power between the previous bucket -// and the current head, and the total flow which is the sum of absolute values of all changes each validator's power -// after rotation the next head is a copy of the current head -func (vw *ValidatorsRing) Rotate() (totalPowerChange *big.Int, totalFlow *big.Int) { - // Subtract the previous bucket total power so we can add on the current buckets power after this - totalPowerChange = new(big.Int).Sub(vw.Head().totalPower, vw.Prev().totalPower) - // Capture flow before we wipe it - totalFlow = vw.flow.totalPower - // Subtract the tail bucket (if any) from the total - vw.power.Subtract(vw.Next()) - // Copy head bucket - headCopy := vw.Head().Copy() - // add it to total - vw.power.Add(headCopy) - // move the ring buffer on - vw.head = vw.index(1) - // Overwrite new head bucket (previous tail) with previous bucket copy updated with current head - vw.buckets[vw.head] = headCopy - // New flow accumulator1 - vw.flow = NewValidators() - // Advance the ring - return totalPowerChange, totalFlow -} - -func (vw *ValidatorsRing) Prev() *Validators { - return vw.buckets[vw.index(-1)] -} - -func (vw *ValidatorsRing) Head() *Validators { - return vw.buckets[vw.head] -} - -func (vw *ValidatorsRing) Next() *Validators { - return vw.buckets[vw.index(1)] -} - -func (vw *ValidatorsRing) index(i int64) int64 { - return (vw.size + vw.head + i) % vw.size -} - -func (vw *ValidatorsRing) Size() int64 { - return vw.size -} - -// Returns buckets in order head, previous, ... -func (vw *ValidatorsRing) OrderedBuckets() []*Validators { - buckets := make([]*Validators, len(vw.buckets)) - for i := int64(0); i < vw.size; i++ { - buckets[i] = vw.buckets[vw.index(-i)] - } - return buckets -} - -func (vw *ValidatorsRing) String() string { - return fmt.Sprintf("ValidatorsWindow{Total: %v; Buckets: Head->%v<-Tail}", vw.power, vw.OrderedBuckets()) -} - -func (vw *ValidatorsRing) Equal(vwOther *ValidatorsRing) bool { - if vw.size != vwOther.size || vw.head != vwOther.head || len(vw.buckets) != len(vwOther.buckets) || - !vw.flow.Equal(vwOther.flow) || !vw.power.Equal(vwOther.power) { - return false - } - for i, b := range vw.buckets { - if !b.Equal(vwOther.buckets[i]) { - return false - } - } - return true -} - -type PersistedValidatorsRing struct { - Buckets [][]PersistedValidator - Power []PersistedValidator - Flow []PersistedValidator - Head int64 -} - -func (vw *ValidatorsRing) Persistable() PersistedValidatorsRing { - buckets := make([][]PersistedValidator, len(vw.buckets)) - for i, vs := range vw.buckets { - buckets[i] = vs.Persistable() - } - return PersistedValidatorsRing{ - Buckets: buckets, - Power: vw.power.Persistable(), - Flow: vw.flow.Persistable(), - Head: vw.head, - } -} - -func UnpersistValidatorsRing(pvr PersistedValidatorsRing) *ValidatorsRing { - buckets := make([]*Validators, len(pvr.Buckets)) - for i, pv := range pvr.Buckets { - buckets[i] = UnpersistValidators(pv) - } - - return &ValidatorsRing{ - buckets: buckets, - head: pvr.Head, - power: UnpersistValidators(pvr.Power), - flow: UnpersistValidators(pvr.Flow), - size: int64(len(buckets)), - } -} diff --git a/cmd/burrow/commands/configure.go b/cmd/burrow/commands/configure.go index 35788d6a6..d0c149b26 100644 --- a/cmd/burrow/commands/configure.go +++ b/cmd/burrow/commands/configure.go @@ -15,8 +15,8 @@ import ( "github.com/hyperledger/burrow/genesis/spec" "github.com/hyperledger/burrow/keys" "github.com/hyperledger/burrow/logging" - logging_config "github.com/hyperledger/burrow/logging/config" - "github.com/hyperledger/burrow/logging/config/presets" + logging_config "github.com/hyperledger/burrow/logging/logconfig" + "github.com/hyperledger/burrow/logging/logconfig/presets" cli "github.com/jawher/mow.cli" amino "github.com/tendermint/go-amino" tm_crypto "github.com/tendermint/tendermint/crypto" diff --git a/cmd/burrow/commands/helpers.go b/cmd/burrow/commands/helpers.go index ee8807e08..2ac4c7415 100644 --- a/cmd/burrow/commands/helpers.go +++ b/cmd/burrow/commands/helpers.go @@ -9,7 +9,7 @@ import ( "github.com/hyperledger/burrow/config" "github.com/hyperledger/burrow/config/source" "github.com/hyperledger/burrow/genesis" - logging_config "github.com/hyperledger/burrow/logging/config" + logging_config "github.com/hyperledger/burrow/logging/logconfig" ) type Output interface { diff --git a/cmd/burrow/commands/tx.go b/cmd/burrow/commands/tx.go new file mode 100644 index 000000000..cdff10da7 --- /dev/null +++ b/cmd/burrow/commands/tx.go @@ -0,0 +1 @@ +package commands diff --git a/config/config.go b/config/config.go index c22ddbb11..8e3f7b8e7 100644 --- a/config/config.go +++ b/config/config.go @@ -1,20 +1,18 @@ package config import ( - "fmt" - "context" + "fmt" "github.com/hyperledger/burrow/config/source" "github.com/hyperledger/burrow/consensus/tendermint" - "github.com/hyperledger/burrow/consensus/tendermint/validator" "github.com/hyperledger/burrow/core" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/execution" "github.com/hyperledger/burrow/genesis" "github.com/hyperledger/burrow/keys" - logging_config "github.com/hyperledger/burrow/logging/config" "github.com/hyperledger/burrow/logging/lifecycle" + logging_config "github.com/hyperledger/burrow/logging/logconfig" "github.com/hyperledger/burrow/rpc" ) @@ -76,7 +74,7 @@ func (conf *BurrowConfig) Kernel(ctx context.Context) (*core.Kernel, error) { if err != nil { return nil, err } - privValidator := validator.NewPrivValidatorMemory(val, signer) + privValidator := tendermint.NewPrivValidatorMemory(val, signer) var exeOptions []execution.ExecutionOption if conf.Execution != nil { @@ -86,8 +84,8 @@ func (conf *BurrowConfig) Kernel(ctx context.Context) (*core.Kernel, error) { } } - return core.NewKernel(ctx, keyClient, privValidator, conf.GenesisDoc, conf.Tendermint.TendermintConfig(), conf.RPC, conf.Keys, - keyStore, exeOptions, logger) + return core.NewKernel(ctx, keyClient, privValidator, conf.GenesisDoc, conf.Tendermint.TendermintConfig(), conf.RPC, + conf.Keys, keyStore, exeOptions, logger) } func (conf *BurrowConfig) JSONString() string { diff --git a/consensus/tendermint/abci/app.go b/consensus/tendermint/abci/app.go index ce47eef2e..cbacbc94e 100644 --- a/consensus/tendermint/abci/app.go +++ b/consensus/tendermint/abci/app.go @@ -8,10 +8,12 @@ import ( "runtime/debug" - bcm "github.com/hyperledger/burrow/blockchain" + "github.com/hyperledger/burrow/acm/validator" + "github.com/hyperledger/burrow/bcm" "github.com/hyperledger/burrow/consensus/tendermint/codes" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/execution" + errors2 "github.com/hyperledger/burrow/execution/errors" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" "github.com/hyperledger/burrow/project" @@ -20,9 +22,9 @@ import ( abciTypes "github.com/tendermint/tendermint/abci/types" ) -const responseInfoName = "Burrow" - type App struct { + // Node information to return in Info + nodeInfo string // State blockchain *bcm.Blockchain checker execution.BatchExecutor @@ -40,16 +42,18 @@ type App struct { var _ abciTypes.Application = &App{} -func NewApp(blockchain *bcm.Blockchain, checker execution.BatchExecutor, committer execution.BatchCommitter, +func NewApp(nodeInfo string, blockchain *bcm.Blockchain, checker execution.BatchExecutor, committer execution.BatchCommitter, txDecoder txs.Decoder, panicFunc func(error), logger *logging.Logger) *App { return &App{ + nodeInfo: nodeInfo, blockchain: blockchain, checker: checker, committer: committer, checkTx: txExecutor(checker, txDecoder, logger.WithScope("CheckTx")), deliverTx: txExecutor(committer, txDecoder, logger.WithScope("DeliverTx")), panicFunc: panicFunc, - logger: logger.WithScope("abci.NewApp").With(structure.ComponentKey, "ABCI_App"), + logger: logger.WithScope("abci.NewApp").With(structure.ComponentKey, "ABCI_App", + "node_info", nodeInfo), } } @@ -61,12 +65,11 @@ func (app *App) SetMempoolLocker(mempoolLocker sync.Locker) { } func (app *App) Info(info abciTypes.RequestInfo) abciTypes.ResponseInfo { - tip := app.blockchain.Tip return abciTypes.ResponseInfo{ - Data: responseInfoName, + Data: app.nodeInfo, Version: project.History.CurrentVersion().String(), - LastBlockHeight: int64(tip.LastBlockHeight()), - LastBlockAppHash: tip.AppHashAfterLastBlock(), + LastBlockHeight: int64(app.blockchain.LastBlockHeight()), + LastBlockAppHash: app.blockchain.AppHashAfterLastBlock(), } } @@ -88,10 +91,15 @@ func (app *App) InitChain(chain abciTypes.RequestInitChain) (respInitChain abciT app.panicFunc(fmt.Errorf("panic occurred in abci.App/InitChain: %v\n%s", r, debug.Stack())) } }() - err := app.checkValidatorsMatch(chain.Validators) - if err != nil { - app.logger.InfoMsg("Initial validator set mistmatch", structure.ErrorKey, err) - panic(err) + if len(chain.Validators) != app.blockchain.NumValidators() { + panic(fmt.Errorf("Tendermint passes %d validators to InitChain but Burrow's Blockchain has %d", + len(chain.Validators), app.blockchain.NumValidators())) + } + for _, v := range chain.Validators { + err := app.checkValidatorMatches(app.blockchain.Validators(), v) + if err != nil { + panic(err) + } } app.logger.InfoMsg("Initial validator set matches") return @@ -105,31 +113,33 @@ func (app *App) BeginBlock(block abciTypes.RequestBeginBlock) (respBeginBlock ab } }() if block.Header.Height > 1 { - validators := make([]abciTypes.Validator, len(block.Validators)) - for i, v := range block.Validators { - validators[i] = v.Validator - } - err := app.checkValidatorsMatch(validators) - if err != nil { + var err error + // Tendermint runs a block behind with the validators passed in here + previousValidators := app.blockchain.PreviousValidators() + if len(block.Validators) != previousValidators.Count() { + err = fmt.Errorf("Tendermint passes %d validators to BeginBlock but Burrow's Blockchain has %d", + len(block.Validators), previousValidators.Count()) panic(err) } + for _, v := range block.Validators { + err = app.checkValidatorMatches(previousValidators, v.Validator) + if err != nil { + panic(err) + } + } } return } -func (app *App) checkValidatorsMatch(validators []abciTypes.Validator) error { - tendermintValidators := bcm.NewValidators() - for _, v := range validators { - publicKey, err := crypto.PublicKeyFromABCIPubKey(v.PubKey) - if err != nil { - panic(err) - } - tendermintValidators.AlterPower(publicKey, big.NewInt(v.Power)) +func (app *App) checkValidatorMatches(ours validator.Reader, v abciTypes.Validator) error { + publicKey, err := crypto.PublicKeyFromABCIPubKey(v.PubKey) + if err != nil { + return err } - burrowValidators := app.blockchain.Validators() - if !burrowValidators.Equal(tendermintValidators) { - return fmt.Errorf("validators provided by Tendermint at InitChain do not match those held by Burrow: "+ - "Tendermint gives: %v, Burrow gives: %v", tendermintValidators, burrowValidators) + power := ours.Power(publicKey) + if power.Cmp(big.NewInt(v.Power)) != 0 { + return fmt.Errorf("validator %v has power %d from Tendermint but power %d from Burrow", + publicKey.Address(), v.Power, power) } return nil } @@ -137,6 +147,7 @@ func (app *App) checkValidatorsMatch(validators []abciTypes.Validator) error { func (app *App) CheckTx(txBytes []byte) abciTypes.ResponseCheckTx { defer func() { if r := recover(); r != nil { + fmt.Println("BeginBlock") app.panicFunc(fmt.Errorf("panic occurred in abci.App/CheckTx: %v\n%s", r, debug.Stack())) } }() @@ -177,19 +188,20 @@ func txExecutor(executor execution.BatchExecutor, txDecoder txs.Decoder, logger txe, err := executor.Execute(txEnv) if err != nil { + ex := errors2.AsException(err) logger.TraceMsg("Execution error", structure.ErrorKey, err, "tx_hash", txEnv.Tx.Hash()) return abciTypes.ResponseCheckTx{ - Code: codes.EncodingErrorCode, - Log: fmt.Sprintf("Could not execute transaction: %s, error: %v", txEnv, err), + Code: codes.TxExecutionErrorCode, + Log: fmt.Sprintf("Could not execute transaction: %s, error: %v", txEnv, ex.Exception), } } bs, err := txe.Receipt.Encode() if err != nil { return abciTypes.ResponseCheckTx{ - Code: codes.TxExecutionErrorCode, + Code: codes.EncodingErrorCode, Log: fmt.Sprintf("Could not serialise receipt: %s", err), } } @@ -207,11 +219,13 @@ func txExecutor(executor execution.BatchExecutor, txDecoder txs.Decoder, logger func (app *App) EndBlock(reqEndBlock abciTypes.RequestEndBlock) abciTypes.ResponseEndBlock { var validatorUpdates abciTypes.Validators - app.blockchain.IterateValidators(func(id crypto.Addressable, power *big.Int) (stop bool) { + app.blockchain.PendingValidators().Iterate(func(id crypto.Addressable, power *big.Int) (stop bool) { + app.logger.InfoMsg("Updating validator power", "validator_address", id.Address(), + "new_power", power) validatorUpdates = append(validatorUpdates, abciTypes.Validator{ Address: id.Address().Bytes(), PubKey: id.PublicKey().ABCIPubKey(), - // Must be ensured during execution + // Must ensure power fits in an int64 during execution Power: power.Int64(), }) return @@ -235,8 +249,8 @@ func (app *App) Commit() abciTypes.ResponseCommit { "hash", app.block.Hash, "txs", app.block.Header.NumTxs, "block_time", blockTime, - "last_block_time", app.blockchain.Tip.LastBlockTime(), - "last_block_hash", app.blockchain.Tip.LastBlockHash()) + "last_block_time", app.blockchain.LastBlockTime(), + "last_block_hash", app.blockchain.LastBlockHash()) // Lock the checker while we reset it and possibly while recheckTxs replays transactions app.checker.Lock() diff --git a/consensus/tendermint/config.go b/consensus/tendermint/config.go index 46e391d09..d736e4baa 100644 --- a/consensus/tendermint/config.go +++ b/consensus/tendermint/config.go @@ -13,14 +13,16 @@ type BurrowTendermintConfig struct { // Peers to which we automatically connect PersistentPeers string ListenAddress string + // Optional external that nodes my provide with their NodeInfo + ExternalAddress string Moniker string TendermintRoot string } func DefaultBurrowTendermintConfig() *BurrowTendermintConfig { - tmDefaultConfig := tm_config.DefaultConfig() + //tmDefaultConfig := tm_config.DefaultConfig() return &BurrowTendermintConfig{ - ListenAddress: tmDefaultConfig.P2P.ListenAddress, + ListenAddress: "tcp://127.0.0.1:26656", //stmDefaultConfig.P2P.ListenAddress, TendermintRoot: ".burrow", } } @@ -37,6 +39,7 @@ func (btc *BurrowTendermintConfig) TendermintConfig() *tm_config.Config { conf.P2P.Seeds = btc.Seeds conf.P2P.PersistentPeers = btc.PersistentPeers conf.P2P.ListenAddress = btc.ListenAddress + conf.P2P.ExternalAddress = btc.ListenAddress conf.Moniker = btc.Moniker // Unfortunately this stops metrics from being used at all conf.Instrumentation.Prometheus = false diff --git a/consensus/tendermint/query/node_view.go b/consensus/tendermint/node_view.go similarity index 86% rename from consensus/tendermint/query/node_view.go rename to consensus/tendermint/node_view.go index 4c547bc24..62a50085d 100644 --- a/consensus/tendermint/query/node_view.go +++ b/consensus/tendermint/node_view.go @@ -1,26 +1,24 @@ -package query +package tendermint import ( "fmt" - "github.com/hyperledger/burrow/consensus/tendermint" "github.com/hyperledger/burrow/crypto" - tm_crypto "github.com/tendermint/tendermint/crypto" - "github.com/hyperledger/burrow/txs" "github.com/tendermint/tendermint/consensus" ctypes "github.com/tendermint/tendermint/consensus/types" + tmCrypto "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" ) type NodeView struct { - tmNode *tendermint.Node + tmNode *Node txDecoder txs.Decoder } -func NewNodeView(tmNode *tendermint.Node, txDecoder txs.Decoder) *NodeView { +func NewNodeView(tmNode *Node, txDecoder txs.Decoder) *NodeView { return &NodeView{ tmNode: tmNode, txDecoder: txDecoder, @@ -28,7 +26,7 @@ func NewNodeView(tmNode *tendermint.Node, txDecoder txs.Decoder) *NodeView { } func (nv *NodeView) PrivValidatorPublicKey() (crypto.PublicKey, error) { - pub := nv.tmNode.PrivValidator().GetPubKey().(tm_crypto.PubKeyEd25519) + pub := nv.tmNode.PrivValidator().GetPubKey().(tmCrypto.PubKeyEd25519) return crypto.PublicKeyFromBytes(pub[:], crypto.CurveTypeEd25519) } diff --git a/consensus/tendermint/validator/priv_validator_memory.go b/consensus/tendermint/priv_validator_memory.go similarity index 98% rename from consensus/tendermint/validator/priv_validator_memory.go rename to consensus/tendermint/priv_validator_memory.go index 5159e5036..fb63b76ae 100644 --- a/consensus/tendermint/validator/priv_validator_memory.go +++ b/consensus/tendermint/priv_validator_memory.go @@ -1,4 +1,4 @@ -package validator +package tendermint import ( "github.com/hyperledger/burrow/crypto" diff --git a/consensus/tendermint/validator/sign_info.go b/consensus/tendermint/sign_info.go similarity index 99% rename from consensus/tendermint/validator/sign_info.go rename to consensus/tendermint/sign_info.go index 40230651c..1a11cbf75 100644 --- a/consensus/tendermint/validator/sign_info.go +++ b/consensus/tendermint/sign_info.go @@ -1,4 +1,4 @@ -package validator +package tendermint import ( "bytes" diff --git a/consensus/tendermint/tendermint.go b/consensus/tendermint/tendermint.go index 31f0c8cf0..0122f580e 100644 --- a/consensus/tendermint/tendermint.go +++ b/consensus/tendermint/tendermint.go @@ -4,13 +4,10 @@ import ( "os" "path" - bcm "github.com/hyperledger/burrow/blockchain" "github.com/hyperledger/burrow/consensus/tendermint/abci" - "github.com/hyperledger/burrow/execution" "github.com/hyperledger/burrow/genesis" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" - "github.com/hyperledger/burrow/txs" "github.com/tendermint/tendermint/config" tmCrypto "github.com/tendermint/tendermint/crypto" dbm "github.com/tendermint/tendermint/libs/db" @@ -45,8 +42,7 @@ func (n *Node) Close() { } func NewNode(conf *config.Config, privValidator tmTypes.PrivValidator, genesisDoc *tmTypes.GenesisDoc, - blockchain *bcm.Blockchain, checker execution.BatchExecutor, committer execution.BatchCommitter, - txDecoder txs.Decoder, metricsProvider node.MetricsProvider, panicFunc func(error), logger *logging.Logger) (*Node, error) { + app *abci.App, metricsProvider node.MetricsProvider, logger *logging.Logger) (*Node, error) { var err error // disable Tendermint's RPC @@ -58,8 +54,6 @@ func NewNode(conf *config.Config, privValidator tmTypes.PrivValidator, genesisDo } nde := &Node{} - app := abci.NewApp(blockchain, checker, committer, txDecoder, panicFunc, logger) - conf.NodeKeyFile() nde.Node, err = node.NewNode(conf, privValidator, proxy.NewLocalClientCreator(app), func() (*tmTypes.GenesisDoc, error) { diff --git a/consensus/tendermint/validator/wire.go b/consensus/tendermint/wire.go similarity index 89% rename from consensus/tendermint/validator/wire.go rename to consensus/tendermint/wire.go index 3cdd4f0dc..24f0bc111 100644 --- a/consensus/tendermint/validator/wire.go +++ b/consensus/tendermint/wire.go @@ -1,4 +1,4 @@ -package validator +package tendermint import ( amino "github.com/tendermint/go-amino" diff --git a/core/kernel.go b/core/kernel.go index 72329f2d7..46854844a 100644 --- a/core/kernel.go +++ b/core/kernel.go @@ -27,9 +27,9 @@ import ( "time" kitlog "github.com/go-kit/kit/log" - bcm "github.com/hyperledger/burrow/blockchain" + "github.com/hyperledger/burrow/bcm" "github.com/hyperledger/burrow/consensus/tendermint" - "github.com/hyperledger/burrow/consensus/tendermint/query" + "github.com/hyperledger/burrow/consensus/tendermint/abci" "github.com/hyperledger/burrow/event" "github.com/hyperledger/burrow/execution" "github.com/hyperledger/burrow/genesis" @@ -51,10 +51,11 @@ import ( ) const ( - CooldownMilliseconds = 1000 - ServerShutdownTimeoutMilliseconds = 1000 - LoggingCallerDepth = 5 - AccountsRingMutexCount = 100 + FirstBlockTimeout = 3 * time.Second + CooldownTime = 1000 * time.Millisecond + ServerShutdownTimeout = 1000 * time.Millisecond + LoggingCallerDepth = 5 + AccountsRingMutexCount = 100 ) // Kernel is the root structure of Burrow @@ -64,8 +65,10 @@ type Kernel struct { Service *rpc.Service Launchers []process.Launcher State *execution.State - Blockchain bcm.BlockchainInfo + Blockchain *bcm.Blockchain + Node *tendermint.Node Logger *logging.Logger + nodeInfo string processes map[string]process.Process shutdownNotify chan struct{} shutdownOnce sync.Once @@ -75,57 +78,58 @@ func NewKernel(ctx context.Context, keyClient keys.KeyClient, privValidator tmTy genesisDoc *genesis.GenesisDoc, tmConf *tmConfig.Config, rpcConfig *rpc.RPCConfig, keyConfig *keys.KeysConfig, keyStore *keys.KeyStore, exeOptions []execution.ExecutionOption, logger *logging.Logger) (*Kernel, error) { + var err error kern := &Kernel{ processes: make(map[string]process.Process), shutdownNotify: make(chan struct{}), } logger = logger.WithScope("NewKernel()").With(structure.TimeKey, kitlog.DefaultTimestampUTC) tmLogger := logger.With(structure.CallerKey, kitlog.Caller(LoggingCallerDepth+1)) - logger = logger.WithInfo(structure.CallerKey, kitlog.Caller(LoggingCallerDepth)) + kern.Logger = logger.WithInfo(structure.CallerKey, kitlog.Caller(LoggingCallerDepth)) stateDB := dbm.NewDB("burrow_state", dbm.GoLevelDBBackend, tmConf.DBDir()) - blockchain, err := bcm.LoadOrNewBlockchain(stateDB, genesisDoc, logger) + kern.Blockchain, err = bcm.LoadOrNewBlockchain(stateDB, genesisDoc, kern.Logger) if err != nil { return nil, fmt.Errorf("error creating or loading blockchain state: %v", err) } - var state *execution.State // These should be in sync unless we are at the genesis block - if blockchain.LastBlockHeight() > 0 { - state, err = execution.LoadState(stateDB, blockchain.AppHashAfterLastBlock()) + if kern.Blockchain.LastBlockHeight() > 0 { + kern.State, err = execution.LoadState(stateDB, kern.Blockchain.AppHashAfterLastBlock()) if err != nil { return nil, fmt.Errorf("could not load persisted execution state at hash 0x%X: %v", - blockchain.AppHashAfterLastBlock(), err) + kern.Blockchain.AppHashAfterLastBlock(), err) } } else { - state, err = execution.MakeGenesisState(stateDB, genesisDoc) + kern.State, err = execution.MakeGenesisState(stateDB, genesisDoc) } txCodec := txs.NewAminoCodec() tmGenesisDoc := tendermint.DeriveGenesisDoc(genesisDoc) - checker := execution.NewBatchChecker(state, blockchain, logger) + checker := execution.NewBatchChecker(kern.State, kern.Blockchain, kern.Logger) - emitter := event.NewEmitter(logger) - committer := execution.NewBatchCommitter(state, blockchain, emitter, logger, exeOptions...) + kern.Emitter = event.NewEmitter(kern.Logger) + committer := execution.NewBatchCommitter(kern.State, kern.Blockchain, kern.Emitter, kern.Logger, exeOptions...) - // We could use this to provide/register our own metrics (though this will register them with us). Unforunately + kern.nodeInfo = fmt.Sprintf("Burrow_%s_%X", genesisDoc.ChainID(), privValidator.GetAddress()) + app := abci.NewApp(kern.nodeInfo, kern.Blockchain, checker, committer, txCodec, kern.Panic, logger) + // We could use this to provide/register our own metrics (though this will register them with us). Unfortunately // Tendermint currently ignores the metrics passed unless its own server is turned on. metricsProvider := node.DefaultMetricsProvider - tmNode, err := tendermint.NewNode(tmConf, privValidator, tmGenesisDoc, blockchain, checker, committer, txCodec, - metricsProvider, kern.Panic, tmLogger) + kern.Node, err = tendermint.NewNode(tmConf, privValidator, tmGenesisDoc, app, metricsProvider, tmLogger) if err != nil { return nil, err } - transactor := execution.NewTransactor(blockchain.Tip, emitter, execution.NewAccounts(checker, keyClient, AccountsRingMutexCount), - tmNode.MempoolReactor().BroadcastTx, txCodec, logger) + transactor := execution.NewTransactor(kern.Blockchain, kern.Emitter, execution.NewAccounts(checker, keyClient, AccountsRingMutexCount), + kern.Node.MempoolReactor().BroadcastTx, txCodec, kern.Logger) - nameRegState := state - accountState := state - service := rpc.NewService(accountState, nameRegState, blockchain, transactor, - query.NewNodeView(tmNode, txCodec), logger) + nameRegState := kern.State + accountState := kern.State + nodeView := tendermint.NewNodeView(kern.Node, txCodec) + kern.Service = rpc.NewService(accountState, nameRegState, kern.Blockchain, nodeView, kern.Logger) - launchers := []process.Launcher{ + kern.Launchers = []process.Launcher{ { Name: "Profiling Server", Enabled: rpcConfig.Profiler.Enabled, @@ -136,7 +140,7 @@ func NewKernel(ctx context.Context, keyClient keys.KeyClient, privValidator tmTy go func() { err := debugServer.ListenAndServe() if err != nil { - logger.InfoMsg("Error from pprof debug server", structure.ErrorKey, err) + kern.Logger.InfoMsg("Error from pprof debug server", structure.ErrorKey, err) } }() return debugServer, nil @@ -157,22 +161,22 @@ func NewKernel(ctx context.Context, keyClient keys.KeyClient, privValidator tmTy Name: "Tendermint", Enabled: true, Launch: func() (process.Process, error) { - err := tmNode.Start() + err := kern.Node.Start() if err != nil { return nil, fmt.Errorf("error starting Tendermint node: %v", err) } return process.ShutdownFunc(func(ctx context.Context) error { - err := tmNode.Stop() + err := kern.Node.Stop() // Close tendermint database connections using our wrapper - defer tmNode.Close() + defer kern.Node.Close() if err != nil { return err } select { case <-ctx.Done(): return ctx.Err() - case <-tmNode.Quit(): - logger.InfoMsg("Tendermint Node has quit, closing DB connections...") + case <-kern.Node.Quit(): + kern.Logger.InfoMsg("Tendermint Node has quit, closing DB connections...") return nil } return err @@ -183,7 +187,7 @@ func NewKernel(ctx context.Context, keyClient keys.KeyClient, privValidator tmTy Name: "RPC/tm", Enabled: rpcConfig.TM.Enabled, Launch: func() (process.Process, error) { - server, err := tm.StartServer(service, "/websocket", rpcConfig.TM.ListenAddress, logger) + server, err := tm.StartServer(kern.Service, "/websocket", rpcConfig.TM.ListenAddress, kern.Logger) if err != nil { return nil, err } @@ -194,7 +198,8 @@ func NewKernel(ctx context.Context, keyClient keys.KeyClient, privValidator tmTy Name: "RPC/metrics", Enabled: rpcConfig.Metrics.Enabled, Launch: func() (process.Process, error) { - server, err := metrics.StartServer(service, rpcConfig.Metrics.MetricsPath, rpcConfig.Metrics.ListenAddress, rpcConfig.Metrics.BlockSampleSize, logger) + server, err := metrics.StartServer(kern.Service, rpcConfig.Metrics.MetricsPath, + rpcConfig.Metrics.ListenAddress, rpcConfig.Metrics.BlockSampleSize, kern.Logger) if err != nil { return nil, err } @@ -210,7 +215,7 @@ func NewKernel(ctx context.Context, keyClient keys.KeyClient, privValidator tmTy return nil, err } - grpcServer := rpc.NewGRPCServer(logger) + grpcServer := rpc.NewGRPCServer(kern.Logger) var ks *keys.KeyStore if keyStore != nil { ks = keyStore @@ -218,17 +223,18 @@ func NewKernel(ctx context.Context, keyClient keys.KeyClient, privValidator tmTy if keyConfig.GRPCServiceEnabled { if keyStore == nil { - ks = keys.NewKeyStore(keyConfig.KeysDirectory, keyConfig.AllowBadFilePermissions, logger) + ks = keys.NewKeyStore(keyConfig.KeysDirectory, keyConfig.AllowBadFilePermissions, kern.Logger) } keys.RegisterKeysServer(grpcServer, ks) } - rpcquery.RegisterQueryServer(grpcServer, rpcquery.NewQueryServer(state, nameRegState)) + rpcquery.RegisterQueryServer(grpcServer, rpcquery.NewQueryServer(kern.State, nameRegState, + kern.Blockchain, nodeView, kern.Logger)) rpctransact.RegisterTransactServer(grpcServer, rpctransact.NewTransactServer(transactor, txCodec)) - rpcevents.RegisterExecutionEventsServer(grpcServer, rpcevents.NewExecutionEventsServer(state, emitter, - blockchain.Tip, logger)) + rpcevents.RegisterExecutionEventsServer(grpcServer, rpcevents.NewExecutionEventsServer(kern.State, + kern.Emitter, kern.Blockchain, kern.Logger)) // Provides metadata about services registered //reflection.Register(grpcServer) @@ -244,12 +250,6 @@ func NewKernel(ctx context.Context, keyClient keys.KeyClient, privValidator tmTy }, } - kern.Emitter = emitter - kern.Service = service - kern.Launchers = launchers - kern.State = state - kern.Blockchain = blockchain - kern.Logger = logger return kern, nil } @@ -270,7 +270,7 @@ func (kern *Kernel) Boot() error { } func (kern *Kernel) Panic(err error) { - fmt.Fprintf(os.Stderr, "Kernel shutting down due to panic: %v", err) + fmt.Fprintf(os.Stderr, "%s: Kernel shutting down due to panic: %v", kern.nodeInfo, err) kern.Shutdown(context.Background()) os.Exit(1) } @@ -298,7 +298,7 @@ func (kern *Kernel) Shutdown(ctx context.Context) (err error) { logger := kern.Logger.WithScope("Shutdown") logger.InfoMsg("Attempting graceful shutdown...") logger.InfoMsg("Shutting down servers") - ctx, cancel := context.WithTimeout(ctx, ServerShutdownTimeoutMilliseconds*time.Millisecond) + ctx, cancel := context.WithTimeout(ctx, ServerShutdownTimeout) defer cancel() // Shutdown servers in reverse order to boot for i := len(kern.Launchers) - 1; i >= 0; i-- { @@ -322,7 +322,7 @@ func (kern *Kernel) Shutdown(ctx context.Context) (err error) { structure.Sync(kern.Logger.Trace) // We don't want to wait for them, but yielding for a cooldown Let other goroutines flush // potentially interesting final output (e.g. log messages) - time.Sleep(time.Millisecond * CooldownMilliseconds) + time.Sleep(CooldownTime) close(kern.shutdownNotify) }) return diff --git a/crypto/public_key.go b/crypto/public_key.go index 4d5764ad3..27d592029 100644 --- a/crypto/public_key.go +++ b/crypto/public_key.go @@ -7,6 +7,7 @@ import ( "github.com/btcsuite/btcd/btcec" abci "github.com/tendermint/tendermint/abci/types" + tmCrypto "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/tmhash" "github.com/tmthrgd/go-hex" "golang.org/x/crypto/ed25519" @@ -136,6 +137,17 @@ func (p PublicKey) ABCIPubKey() abci.PubKey { } } +func PublicKeyFromTendermintPubKey(pubKey tmCrypto.PubKey) (PublicKey, error) { + switch pk := pubKey.(type) { + case tmCrypto.PubKeyEd25519: + return PublicKeyFromBytes(pk[:], CurveTypeEd25519) + case tmCrypto.PubKeySecp256k1: + return PublicKeyFromBytes(pk[:], CurveTypeSecp256k1) + default: + return PublicKey{}, fmt.Errorf("unrecognised tendermint public key type: %v", pk) + } + +} func PublicKeyFromABCIPubKey(pubKey abci.PubKey) (PublicKey, error) { switch pubKey.Type { case CurveTypeEd25519.ABCIType(): diff --git a/execution/contexts/call_context.go b/execution/contexts/call_context.go index 5278b21cc..fcf7e146c 100644 --- a/execution/contexts/call_context.go +++ b/execution/contexts/call_context.go @@ -5,8 +5,8 @@ import ( "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/acm/state" + "github.com/hyperledger/burrow/bcm" "github.com/hyperledger/burrow/binary" - "github.com/hyperledger/burrow/blockchain" "github.com/hyperledger/burrow/execution/errors" "github.com/hyperledger/burrow/execution/evm" "github.com/hyperledger/burrow/execution/exec" @@ -19,7 +19,7 @@ import ( const GasLimit = uint64(1000000) type CallContext struct { - Tip blockchain.TipInfo + Tip bcm.BlockchainInfo StateWriter state.ReaderWriter RunCall bool VMOptions []func(*evm.VM) @@ -101,7 +101,7 @@ func (ctx *CallContext) Precheck() (*acm.MutableAccount, acm.Account, error) { return nil, nil, fmt.Errorf("attempt to call a native contract at %s, "+ "but native contracts cannot be called using CallTx. Use a "+ "contract that calls the native contract or the appropriate tx "+ - "type (eg. PermissionsTx, NameTx)", ctx.tx.Address) + "type (eg. PermsTx, NameTx)", ctx.tx.Address) } // Output account may be nil if we are still in mempool and contract was created in same block as this tx diff --git a/execution/contexts/governance_context.go b/execution/contexts/governance_context.go index dd0a8afe9..39457b827 100644 --- a/execution/contexts/governance_context.go +++ b/execution/contexts/governance_context.go @@ -6,7 +6,7 @@ import ( "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/acm/state" - "github.com/hyperledger/burrow/blockchain" + "github.com/hyperledger/burrow/acm/validator" "github.com/hyperledger/burrow/execution/errors" "github.com/hyperledger/burrow/execution/exec" "github.com/hyperledger/burrow/genesis/spec" @@ -17,18 +17,18 @@ import ( type GovernanceContext struct { StateWriter state.ReaderWriter - ValidatorSet blockchain.ValidatorSet + ValidatorSet validator.Writer Logger *logging.Logger - tx *payload.GovernanceTx + tx *payload.GovTx txe *exec.TxExecution } -// GovernanceTx provides a set of TemplateAccounts and GovernanceContext tries to alter the chain state to match the +// GovTx provides a set of TemplateAccounts and GovernanceContext tries to alter the chain state to match the // specification given func (ctx *GovernanceContext) Execute(txe *exec.TxExecution) error { var ok bool ctx.txe = txe - ctx.tx, ok = txe.Envelope.Tx.Payload.(*payload.GovernanceTx) + ctx.tx, ok = txe.Envelope.Tx.Payload.(*payload.GovTx) if !ok { return fmt.Errorf("payload must be NameTx, but is: %v", txe.Envelope.Tx.Payload) } @@ -38,8 +38,9 @@ func (ctx *GovernanceContext) Execute(txe *exec.TxExecution) error { } // ensure all inputs have root permissions - if !allHavePermission(ctx.StateWriter, permission.Root, accounts, ctx.Logger) { - return fmt.Errorf("at least one input lacks Root permission needed for GovernanceTx") + err = allHavePermission(ctx.StateWriter, permission.Root, accounts, ctx.Logger) + if err != nil { + return errors.Wrap(err, "at least one input lacks permission for GovTx") } for _, i := range ctx.tx.Inputs { @@ -49,28 +50,25 @@ func (ctx *GovernanceContext) Execute(txe *exec.TxExecution) error { for _, update := range ctx.tx.AccountUpdates { if update.Address == nil && update.PublicKey == nil { // We do not want to generate a key - return fmt.Errorf("could not execution GovernanceTx since account template %v contains neither "+ + return fmt.Errorf("could not execution GovTx since account template %v contains neither "+ "address or public key", update) } if update.PublicKey != nil { address := update.PublicKey.Address() if update.Address != nil && address != *update.Address { return fmt.Errorf("supplied public key %v whose address %v does not match %v provided by"+ - "GovernanceTx", update.PublicKey, address, update.Address) + "GovTx", update.PublicKey, address, update.Address) } update.Address = &address } - if update.PublicKey == nil && update.Power != nil { + if update.PublicKey == nil && update.Balances().HasPower() { // If we are updating power we will need the key - return fmt.Errorf("GovernanceTx must be provided with public key when updating validator power") + return fmt.Errorf("GovTx must be provided with public key when updating validator power") } - account, err := state.GetMutableAccount(ctx.StateWriter, *update.Address) + account, err := getOrMakeOutput(ctx.StateWriter, accounts, *update.Address, ctx.Logger) if err != nil { return err } - if account == nil { - return fmt.Errorf("account %v not found so cannot update using template %v", update.Address, update) - } governAccountEvent, err := ctx.updateAccount(account, update) if err != nil { txe.GovernAccount(governAccountEvent, errors.AsException(err)) @@ -85,8 +83,8 @@ func (ctx *GovernanceContext) updateAccount(account *acm.MutableAccount, update ev = &exec.GovernAccountEvent{ AccountUpdate: update, } - if update.Amount != nil { - err = account.SetBalance(*update.Amount) + if update.Balances().HasNative() { + err = account.SetBalance(update.Balances().GetNative(0)) if err != nil { return } @@ -95,13 +93,13 @@ func (ctx *GovernanceContext) updateAccount(account *acm.MutableAccount, update // TODO: can we do something useful if provided with a NodeAddress for an account about to become a validator // like add it to persistent peers or pre gossip so it gets inbound connections? If so under which circumstances? } - if update.Power != nil { + if update.Balances().HasPower() { if update.PublicKey == nil { err = fmt.Errorf("updateAccount should have PublicKey by this point but appears not to for "+ "template account: %v", update) return } - power := new(big.Int).SetUint64(*update.Power) + power := new(big.Int).SetUint64(update.Balances().GetPower(0)) if !power.IsInt64() { err = fmt.Errorf("power supplied in update to validator power for %v does not fit into int64 and "+ "so is not supported by Tendermint", update.Address) diff --git a/execution/contexts/name_context.go b/execution/contexts/name_context.go index b5ba18a83..10c37a15b 100644 --- a/execution/contexts/name_context.go +++ b/execution/contexts/name_context.go @@ -6,7 +6,7 @@ import ( "regexp" "github.com/hyperledger/burrow/acm/state" - "github.com/hyperledger/burrow/blockchain" + "github.com/hyperledger/burrow/bcm" "github.com/hyperledger/burrow/execution/errors" "github.com/hyperledger/burrow/execution/exec" "github.com/hyperledger/burrow/execution/names" @@ -21,7 +21,7 @@ var regexpAlphaNum = regexp.MustCompile("^[a-zA-Z0-9._/-@]*$") var regexpJSON = regexp.MustCompile(`^[a-zA-Z0-9_/ \-+"':,\n\t.{}()\[\]]*$`) type NameContext struct { - Tip blockchain.TipInfo + Tip bcm.BlockchainInfo StateWriter state.ReaderWriter NameReg names.ReaderWriter Logger *logging.Logger diff --git a/execution/contexts/permissions_context.go b/execution/contexts/permissions_context.go index 4572e41cf..00cbd1a55 100644 --- a/execution/contexts/permissions_context.go +++ b/execution/contexts/permissions_context.go @@ -5,7 +5,7 @@ import ( "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/acm/state" - "github.com/hyperledger/burrow/blockchain" + "github.com/hyperledger/burrow/bcm" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/execution/errors" "github.com/hyperledger/burrow/execution/exec" @@ -16,17 +16,17 @@ import ( ) type PermissionsContext struct { - Tip blockchain.TipInfo + Tip bcm.BlockchainInfo StateWriter state.ReaderWriter Logger *logging.Logger - tx *payload.PermissionsTx + tx *payload.PermsTx } func (ctx *PermissionsContext) Execute(txe *exec.TxExecution) error { var ok bool - ctx.tx, ok = txe.Envelope.Tx.Payload.(*payload.PermissionsTx) + ctx.tx, ok = txe.Envelope.Tx.Payload.(*payload.PermsTx) if !ok { - return fmt.Errorf("payload must be PermissionsTx, but is: %v", txe.Envelope.Tx.Payload) + return fmt.Errorf("payload must be PermsTx, but is: %v", txe.Envelope.Tx.Payload) } // Validate input inAcc, err := state.GetMutableAccount(ctx.StateWriter, ctx.tx.Input.Address) @@ -41,7 +41,7 @@ func (ctx *PermissionsContext) Execute(txe *exec.TxExecution) error { err = ctx.tx.PermArgs.EnsureValid() if err != nil { - return fmt.Errorf("PermissionsTx received containing invalid PermArgs: %v", err) + return fmt.Errorf("PermsTx received containing invalid PermArgs: %v", err) } permFlag := ctx.tx.PermArgs.PermFlag @@ -61,7 +61,7 @@ func (ctx *PermissionsContext) Execute(txe *exec.TxExecution) error { value := ctx.tx.Input.Amount - ctx.Logger.TraceMsg("New PermissionsTx", + ctx.Logger.TraceMsg("New PermsTx", "perm_args", ctx.tx.PermArgs.String()) var permAcc acm.Account @@ -114,7 +114,7 @@ func (ctx *PermissionsContext) Execute(txe *exec.TxExecution) error { } // Good! - ctx.Logger.TraceMsg("Incrementing sequence number for PermissionsTx", + ctx.Logger.TraceMsg("Incrementing sequence number for PermsTx", "tag", "sequence", "account", inAcc.Address(), "old_sequence", inAcc.Sequence(), diff --git a/execution/contexts/send_context.go b/execution/contexts/send_context.go index 592cb6c40..a50c0b883 100644 --- a/execution/contexts/send_context.go +++ b/execution/contexts/send_context.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/hyperledger/burrow/acm/state" - "github.com/hyperledger/burrow/blockchain" + "github.com/hyperledger/burrow/bcm" "github.com/hyperledger/burrow/execution/errors" "github.com/hyperledger/burrow/execution/exec" "github.com/hyperledger/burrow/logging" @@ -13,7 +13,7 @@ import ( ) type SendContext struct { - Tip blockchain.TipInfo + Tip bcm.BlockchainInfo StateWriter state.ReaderWriter Logger *logging.Logger tx *payload.SendTx @@ -31,8 +31,9 @@ func (ctx *SendContext) Execute(txe *exec.TxExecution) error { } // ensure all inputs have send permissions - if !allHavePermission(ctx.StateWriter, permission.Send, accounts, ctx.Logger) { - return fmt.Errorf("at least one input lacks permission for SendTx") + err = allHavePermission(ctx.StateWriter, permission.Send, accounts, ctx.Logger) + if err != nil { + return errors.Wrap(err, "at least one input lacks permission for SendTx") } // add outputs to accounts map diff --git a/execution/contexts/shared.go b/execution/contexts/shared.go index ed97bbd15..23f645f6b 100644 --- a/execution/contexts/shared.go +++ b/execution/contexts/shared.go @@ -43,38 +43,45 @@ func getOrMakeOutputs(accountGetter state.AccountGetter, accs map[crypto.Address if accs == nil { accs = make(map[crypto.Address]*acm.MutableAccount) } - // we should err if an account is being created but the inputs don't have permission - var checkedCreatePerms bool + var err error for _, out := range outs { - // Account shouldn't be duplicated - if _, ok := accs[out.Address]; ok { - return nil, errors.ErrorCodeDuplicateAddress - } - acc, err := state.GetMutableAccount(accountGetter, out.Address) + accs[out.Address], err = getOrMakeOutput(accountGetter, accs, out.Address, logger) if err != nil { return nil, err } - // output account may be nil (new) - if acc == nil { - if !checkedCreatePerms { - if !hasCreateAccountPermission(accountGetter, accs, logger) { - return nil, fmt.Errorf("at least one input does not have permission to create accounts") - } - checkedCreatePerms = true - } - acc = acm.ConcreteAccount{ - Address: out.Address, - Sequence: 0, - Balance: 0, - Permissions: permission.ZeroAccountPermissions, - }.MutableAccount() - } - accs[out.Address] = acc } return accs, nil } +func getOrMakeOutput(accountGetter state.AccountGetter, accs map[crypto.Address]*acm.MutableAccount, + outputAddress crypto.Address, logger *logging.Logger) (*acm.MutableAccount, error) { + + // Account shouldn't be duplicated + if _, ok := accs[outputAddress]; ok { + return nil, errors.ErrorCodeDuplicateAddress + } + acc, err := state.GetMutableAccount(accountGetter, outputAddress) + if err != nil { + return nil, err + } + // output account may be nil (new) + if acc == nil { + if !hasCreateAccountPermission(accountGetter, accs, logger) { + return nil, fmt.Errorf("at least one input does not have permission to create accounts") + } + logger.InfoMsg("Account not found so attempting to create it", "address", outputAddress) + acc = acm.ConcreteAccount{ + Address: outputAddress, + Sequence: 0, + Balance: 0, + Permissions: permission.ZeroAccountPermissions, + }.MutableAccount() + } + + return acc, nil +} + func validateInputs(accs map[crypto.Address]*acm.MutableAccount, ins []*payload.TxInput) (uint64, error) { total := uint64(0) for _, in := range ins { @@ -188,15 +195,17 @@ func HasPermission(accountGetter state.AccountGetter, acc acm.Account, perm perm return v } -// TODO: for debug log the failed accounts func allHavePermission(accountGetter state.AccountGetter, perm permission.PermFlag, - accs map[crypto.Address]*acm.MutableAccount, logger *logging.Logger) bool { + accs map[crypto.Address]*acm.MutableAccount, logger *logging.Logger) error { for _, acc := range accs { if !HasPermission(accountGetter, acc, perm, logger) { - return false + return errors.PermissionDenied{ + Address: acc.Address(), + Perm: perm, + } } } - return true + return nil } func hasNamePermission(accountGetter state.AccountGetter, acc acm.Account, diff --git a/execution/errors/errors.go b/execution/errors/errors.go index b3bc55416..00e49c47b 100644 --- a/execution/errors/errors.go +++ b/execution/errors/errors.go @@ -44,6 +44,10 @@ func (c Code) ErrorCode() Code { return c } +func (c Code) Uint32() uint32 { + return uint32(c) +} + func (c Code) Error() string { return fmt.Sprintf("Error %d: %s", c, c.String()) } @@ -76,6 +80,8 @@ func (c Code) String() string { return "Data stack underflow" case ErrorCodeInvalidContract: return "Invalid contract" + case ErrorCodePermissionDenied: + return "Permission denied" case ErrorCodeNativeContractCodeCopy: return "Tried to copy native contract code" case ErrorCodeExecutionAborted: @@ -134,8 +140,9 @@ func AsException(err error) *Exception { } } -func Wrap(err CodedError, message string) *Exception { - return NewCodedError(err.ErrorCode(), message+": "+err.Error()) +func Wrap(err error, message string) *Exception { + ex := AsException(err) + return NewCodedError(ex.ErrorCode(), message+": "+ex.Error()) } func Errorf(format string, a ...interface{}) *Exception { diff --git a/execution/errors/errors_test.go b/execution/errors/errors_test.go index 33d487b4f..c80c05722 100644 --- a/execution/errors/errors_test.go +++ b/execution/errors/errors_test.go @@ -5,8 +5,6 @@ import ( "fmt" "testing" - "fmt" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/execution/errors/vm.go b/execution/errors/vm.go index 7e97d3750..95b36ccaa 100644 --- a/execution/errors/vm.go +++ b/execution/errors/vm.go @@ -9,7 +9,8 @@ import ( ) type PermissionDenied struct { - Perm permission.PermFlag + Address crypto.Address + Perm permission.PermFlag } func (err PermissionDenied) ErrorCode() Code { @@ -17,7 +18,7 @@ func (err PermissionDenied) ErrorCode() Code { } func (err PermissionDenied) Error() string { - return fmt.Sprintf("Contract does not have permission to %v", err.Perm) + return fmt.Sprintf("Account/contract %v does not have permission %v", err.Address, err.Perm) } type NestedCall struct { diff --git a/execution/evm/vm.go b/execution/evm/vm.go index 53d9b1ebc..0182a3f5e 100644 --- a/execution/evm/vm.go +++ b/execution/evm/vm.go @@ -855,7 +855,10 @@ func (vm *VM) call(callState *state.Cache, caller acm.Account, callee *acm.Mutab vm.returnData = nil if !HasPermission(callState, callee, permission.CreateContract) { - return nil, errors.PermissionDenied{Perm: permission.CreateContract} + return nil, errors.PermissionDenied{ + Address: callee.Address(), + Perm: permission.CreateContract, + } } contractValue, popErr := stack.PopU64() if popErr != nil { @@ -902,7 +905,10 @@ func (vm *VM) call(callState *state.Cache, caller acm.Account, callee *acm.Mutab vm.returnData = nil if !HasPermission(callState, callee, permission.Call) { - return nil, errors.PermissionDenied{Perm: permission.Call} + return nil, errors.PermissionDenied{ + Address: callee.Address(), + Perm: permission.Call, + } } gasLimit, popErr := stack.PopU64() if popErr != nil { @@ -982,7 +988,10 @@ func (vm *VM) call(callState *state.Cache, caller acm.Account, callee *acm.Mutab // nil account means we're sending funds to a new account if acc == nil { if !HasPermission(callState, caller, permission.CreateAccount) { - return nil, errors.PermissionDenied{Perm: permission.CreateAccount} + return nil, errors.PermissionDenied{ + Address: callee.Address(), + Perm: permission.CreateAccount, + } } acc = acm.ConcreteAccount{Address: crypto.AddressFromWord256(addr)}.MutableAccount() } @@ -1077,7 +1086,10 @@ func (vm *VM) call(callState *state.Cache, caller acm.Account, callee *acm.Mutab return nil, firstErr(err, gasErr) } if !HasPermission(callState, callee, permission.CreateContract) { - return nil, firstErr(err, errors.PermissionDenied{Perm: permission.CreateContract}) + return nil, firstErr(err, errors.PermissionDenied{ + Address: callee.Address(), + Perm: permission.CreateContract, + }) } var createErr errors.CodedError receiver, createErr = vm.createAccount(callState, callee, logger) diff --git a/execution/exec/exec.pb.go b/execution/exec/exec.pb.go index 26108e09f..df1d5e805 100644 --- a/execution/exec/exec.pb.go +++ b/execution/exec/exec.pb.go @@ -28,7 +28,6 @@ import golang_proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import _ "github.com/gogo/protobuf/gogoproto" -import _ "github.com/tendermint/tendermint/abci/types" import errors "github.com/hyperledger/burrow/execution/errors" import names "github.com/hyperledger/burrow/execution/names" import txs "github.com/hyperledger/burrow/txs" @@ -3351,68 +3350,67 @@ func init() { proto.RegisterFile("exec.proto", fileDescriptorExec) } func init() { golang_proto.RegisterFile("exec.proto", fileDescriptorExec) } var fileDescriptorExec = []byte{ - // 999 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x56, 0x4f, 0x6f, 0x1b, 0x45, - 0x14, 0xef, 0xda, 0xeb, 0x7f, 0xcf, 0x76, 0x09, 0xa3, 0x80, 0x56, 0x3d, 0xd8, 0xd6, 0x16, 0x55, - 0x21, 0xb4, 0x6b, 0xe4, 0x12, 0x24, 0x40, 0x42, 0x8a, 0x89, 0x95, 0xa4, 0x0a, 0x09, 0x4c, 0x5d, - 0x10, 0x08, 0x0e, 0xeb, 0xdd, 0xc1, 0x59, 0xd5, 0xde, 0x59, 0xcd, 0xce, 0x86, 0xf5, 0x87, 0xe0, - 0xc6, 0xa1, 0xdc, 0xf8, 0x28, 0x1c, 0x73, 0x83, 0x0b, 0x97, 0x1e, 0x2c, 0x94, 0x7e, 0x04, 0x38, - 0xf5, 0x84, 0xe6, 0xcf, 0xae, 0xd7, 0x02, 0x35, 0x55, 0x92, 0x8b, 0x35, 0xef, 0xbd, 0xdf, 0xfc, - 0xe6, 0xcd, 0x7b, 0xbf, 0x37, 0x5e, 0x00, 0x92, 0x12, 0xcf, 0x89, 0x18, 0xe5, 0x14, 0x99, 0x62, - 0x7d, 0xe7, 0xc1, 0x34, 0xe0, 0xa7, 0xc9, 0xc4, 0xf1, 0xe8, 0xbc, 0x3f, 0xa5, 0x53, 0xda, 0x97, - 0xc1, 0x49, 0xf2, 0x83, 0xb4, 0xa4, 0x21, 0x57, 0x6a, 0xd3, 0x9d, 0xfb, 0x05, 0x38, 0x27, 0xa1, - 0x4f, 0xd8, 0x3c, 0x08, 0x79, 0xdf, 0x9d, 0x78, 0x41, 0x9f, 0x2f, 0x22, 0x12, 0xab, 0x5f, 0x8d, - 0x6e, 0x11, 0xc6, 0x28, 0xcb, 0xac, 0x66, 0xe8, 0xce, 0xf3, 0x50, 0x83, 0xa7, 0xd9, 0x72, 0x23, - 0x12, 0x2c, 0x71, 0x1c, 0xd0, 0x50, 0x7b, 0x20, 0x8e, 0xb2, 0x34, 0xed, 0x9f, 0x0d, 0xb8, 0x3d, - 0x9c, 0x51, 0xef, 0xe9, 0x28, 0x25, 0x5e, 0xc2, 0x03, 0x1a, 0xa2, 0xb7, 0xa1, 0x7a, 0x40, 0x82, - 0xe9, 0x29, 0xb7, 0x8c, 0x9e, 0xb1, 0x65, 0x62, 0x6d, 0xa1, 0x87, 0xd0, 0x94, 0xc8, 0x03, 0xe2, - 0xfa, 0x84, 0x59, 0xa5, 0x9e, 0xb1, 0xd5, 0x1c, 0xbc, 0xe9, 0xc8, 0x3b, 0x17, 0x02, 0xb8, 0x88, - 0x42, 0x3b, 0xd0, 0x1a, 0xa7, 0x39, 0x77, 0x6c, 0x95, 0x7b, 0xe5, 0xd5, 0xae, 0x42, 0x04, 0xaf, - 0xc1, 0xec, 0x8f, 0xd6, 0xce, 0x42, 0x08, 0xcc, 0x47, 0x8f, 0x4f, 0x8e, 0x65, 0x42, 0x0d, 0x2c, - 0xd7, 0x22, 0xcd, 0xe3, 0x64, 0x3e, 0x4e, 0x63, 0x99, 0x49, 0x05, 0x6b, 0xcb, 0xfe, 0xb3, 0x0c, - 0xcd, 0x02, 0x17, 0x7a, 0x04, 0xd5, 0x71, 0x3a, 0x5e, 0x44, 0x44, 0xe2, 0xda, 0xc3, 0xc1, 0xcb, - 0x65, 0xd7, 0x29, 0xd4, 0xf9, 0x74, 0x11, 0x11, 0x36, 0x23, 0xfe, 0x94, 0xb0, 0xfe, 0x24, 0x61, - 0x8c, 0xfe, 0xd8, 0xe7, 0x69, 0xdc, 0x8f, 0xdc, 0xc5, 0x8c, 0xba, 0xbe, 0x23, 0x76, 0x62, 0xcd, - 0x80, 0x3e, 0x17, 0x5c, 0x07, 0x6e, 0x7c, 0x6a, 0x95, 0x7b, 0xc6, 0x56, 0x6b, 0xb8, 0x73, 0xbe, - 0xec, 0xde, 0x7a, 0xbe, 0xec, 0x3e, 0x78, 0x35, 0xdf, 0x24, 0x08, 0x5d, 0xb6, 0x70, 0x0e, 0x48, - 0x3a, 0x5c, 0x70, 0x12, 0x63, 0x4d, 0x52, 0xa8, 0xb4, 0xb9, 0x56, 0xe9, 0x4d, 0xa8, 0x1c, 0x86, - 0x3e, 0x49, 0xad, 0x8a, 0x74, 0x2b, 0x03, 0x7d, 0x03, 0xf5, 0x51, 0x78, 0x46, 0x66, 0x34, 0x22, - 0x56, 0x55, 0x16, 0xbf, 0xed, 0x88, 0x36, 0x67, 0xce, 0xa1, 0xf3, 0x7c, 0xd9, 0xdd, 0xbe, 0xf4, - 0x66, 0x39, 0x1e, 0xe7, 0x74, 0xe8, 0x2e, 0x54, 0x47, 0x67, 0x24, 0xe4, 0xb1, 0x55, 0x93, 0xfd, - 0x69, 0xaa, 0xfe, 0x48, 0x1f, 0xd6, 0x21, 0xf4, 0x0e, 0x54, 0x31, 0x89, 0x93, 0x19, 0xb7, 0xea, - 0xf2, 0xf4, 0x96, 0x02, 0x29, 0x1f, 0xd6, 0x31, 0x74, 0x0f, 0x6a, 0x98, 0x78, 0x24, 0x88, 0xb8, - 0xd5, 0xd0, 0x30, 0x71, 0xa8, 0xf6, 0xe1, 0x2c, 0x88, 0xfa, 0xd0, 0x18, 0xa5, 0x1e, 0x89, 0x44, - 0x8f, 0x2c, 0xc8, 0xb4, 0xa4, 0x04, 0x9d, 0x07, 0xf0, 0x0a, 0x63, 0xff, 0x5e, 0x12, 0xd5, 0x92, - 0x72, 0x58, 0xb5, 0xd4, 0xb8, 0xc1, 0x96, 0x96, 0x6e, 0xa2, 0xa5, 0xef, 0x41, 0x43, 0x96, 0x4b, - 0x66, 0x57, 0x96, 0xd9, 0xb5, 0x5f, 0x2e, 0xbb, 0x2b, 0x27, 0x5e, 0x2d, 0x91, 0x05, 0x35, 0x69, - 0x1c, 0xee, 0x49, 0x01, 0x34, 0x70, 0x66, 0x16, 0x94, 0x51, 0xf9, 0x7f, 0x65, 0x54, 0x8b, 0xca, - 0x58, 0xab, 0x65, 0xed, 0xf2, 0x5a, 0x7e, 0x6c, 0x3e, 0xfb, 0xb5, 0x7b, 0xcb, 0xfe, 0xa9, 0x04, - 0x15, 0x79, 0xa0, 0x68, 0xad, 0x9e, 0x6a, 0xa3, 0xd8, 0x5a, 0x3d, 0xd0, 0x59, 0xd9, 0xef, 0x89, - 0xc3, 0xa3, 0x84, 0xeb, 0xd1, 0xdf, 0x50, 0x20, 0xe9, 0x52, 0x4a, 0x51, 0x61, 0xf4, 0x2e, 0x54, - 0x4f, 0x12, 0x2e, 0x80, 0xe5, 0xe2, 0x1b, 0xa1, 0x7c, 0x5a, 0x53, 0xca, 0x40, 0x77, 0xc1, 0xfc, - 0xcc, 0x9d, 0xcd, 0xe4, 0xf5, 0x9b, 0x83, 0x37, 0x14, 0x50, 0x78, 0x14, 0x4c, 0x06, 0x51, 0x0f, - 0xca, 0x47, 0x74, 0x2a, 0x2b, 0xd1, 0x1c, 0xdc, 0x56, 0x98, 0x23, 0x3a, 0x55, 0x10, 0x11, 0x42, - 0x9f, 0x42, 0x7b, 0x9f, 0x9e, 0x11, 0x16, 0xee, 0x7a, 0x1e, 0x4d, 0x42, 0xae, 0xe7, 0xc3, 0x52, - 0xd8, 0xb5, 0x90, 0xda, 0xb5, 0x0e, 0xd7, 0xf5, 0x78, 0x66, 0x64, 0x0a, 0x17, 0xf5, 0xc7, 0x84, - 0x27, 0x2c, 0x94, 0x05, 0x69, 0x61, 0x6d, 0x89, 0x8e, 0xed, 0xbb, 0xf1, 0x93, 0x98, 0xf8, 0xb2, - 0x08, 0x26, 0xce, 0x4c, 0xb4, 0x0d, 0x8d, 0x63, 0x77, 0x4e, 0x46, 0x21, 0x67, 0x0b, 0x7d, 0xef, - 0x96, 0xa3, 0x9e, 0x64, 0xe9, 0xc3, 0xab, 0x30, 0x7a, 0x1f, 0xea, 0x5f, 0x10, 0x36, 0xdf, 0x65, - 0xd3, 0x58, 0xdf, 0x7c, 0xd3, 0x29, 0xbc, 0xd2, 0x59, 0x0c, 0xe7, 0x28, 0xfb, 0x6f, 0x03, 0xea, - 0xd9, 0x95, 0xd1, 0x31, 0xd4, 0x76, 0x7d, 0x9f, 0x91, 0x38, 0x56, 0xd9, 0x0d, 0x3f, 0xd0, 0x9a, - 0xbd, 0xff, 0x6a, 0xcd, 0x7a, 0x6c, 0x11, 0x71, 0xea, 0xe8, 0xbd, 0x38, 0x23, 0x41, 0x87, 0x60, - 0xee, 0xb9, 0xdc, 0xbd, 0xde, 0x00, 0x48, 0x0a, 0x74, 0x04, 0xd5, 0x31, 0x8d, 0x02, 0x4f, 0x3d, - 0xf4, 0xaf, 0x9d, 0x99, 0x26, 0xfb, 0x9a, 0x32, 0x7f, 0xb0, 0xf3, 0x21, 0xd6, 0x1c, 0xf6, 0x3f, - 0x06, 0x34, 0x72, 0x31, 0xa0, 0x6d, 0xa8, 0x0b, 0x43, 0xa6, 0x6a, 0x14, 0xb5, 0x90, 0x79, 0x71, - 0x1e, 0x17, 0x79, 0x9c, 0xb0, 0x60, 0x1a, 0x84, 0xfa, 0x52, 0x57, 0xab, 0x90, 0xe6, 0x40, 0x1d, - 0x80, 0xc7, 0xdc, 0xf5, 0x9e, 0xee, 0x91, 0x88, 0xab, 0xa7, 0xdf, 0xc4, 0x05, 0x8f, 0x78, 0x43, - 0xb4, 0x5a, 0xcc, 0x6b, 0xbd, 0x21, 0x8a, 0xc4, 0xfe, 0x12, 0xd0, 0x7f, 0x25, 0x8b, 0x3e, 0x81, - 0xb6, 0xb6, 0x9f, 0x44, 0xbe, 0xcb, 0x89, 0xae, 0xc1, 0x5b, 0x8e, 0xfc, 0x37, 0x1f, 0x93, 0x79, - 0x34, 0x73, 0x39, 0xd1, 0x10, 0xbc, 0x8e, 0xb5, 0xbf, 0x03, 0x58, 0xcd, 0xe9, 0x4d, 0x0b, 0xc8, - 0xfe, 0x1e, 0x9a, 0x85, 0xe1, 0xbe, 0x71, 0xfa, 0x5f, 0x4a, 0xb0, 0xd6, 0x59, 0xb1, 0xd6, 0x4f, - 0xd5, 0x95, 0x3b, 0xab, 0x38, 0x72, 0x36, 0x72, 0x3d, 0x9d, 0x28, 0x8e, 0x7c, 0x90, 0xca, 0xd7, - 0x1f, 0xa4, 0x4d, 0xa8, 0x7c, 0xe5, 0xce, 0x12, 0xa2, 0xbf, 0x0c, 0x94, 0x81, 0x36, 0xa0, 0xbc, - 0xef, 0xc6, 0xfa, 0x3f, 0x41, 0x2c, 0x87, 0xc3, 0xf3, 0x8b, 0x8e, 0xf1, 0xc7, 0x45, 0xc7, 0xf8, - 0xeb, 0xa2, 0x63, 0xfc, 0xf6, 0xa2, 0x63, 0x9c, 0xbf, 0xe8, 0x18, 0xdf, 0x5e, 0x92, 0x3e, 0xc9, - 0x3e, 0x8e, 0xe4, 0x6a, 0x52, 0x95, 0x9f, 0x82, 0x0f, 0xff, 0x0d, 0x00, 0x00, 0xff, 0xff, 0x47, - 0x90, 0xbb, 0xef, 0xbf, 0x0a, 0x00, 0x00, + // 979 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x56, 0x4f, 0x6f, 0xe3, 0x44, + 0x14, 0x5f, 0x37, 0xce, 0xbf, 0x97, 0x64, 0x29, 0xa3, 0x82, 0xac, 0x3d, 0x24, 0x91, 0x17, 0xad, + 0x4a, 0x61, 0x1d, 0x94, 0xa5, 0x48, 0x80, 0x84, 0xd4, 0xd0, 0xa8, 0xed, 0xaa, 0xb4, 0x30, 0x9b, + 0x05, 0x81, 0xe0, 0xe0, 0x38, 0x83, 0x6b, 0xad, 0xe3, 0xb1, 0xc6, 0xe3, 0xe2, 0x7c, 0x08, 0x6e, + 0x1c, 0x96, 0x1b, 0x1f, 0x85, 0x63, 0x6f, 0x70, 0xe1, 0xb2, 0x87, 0x08, 0x75, 0x3f, 0x02, 0x9c, + 0xf6, 0x84, 0xe6, 0x8f, 0x1d, 0x47, 0xa0, 0x2d, 0xda, 0xf6, 0x36, 0xef, 0xbd, 0xdf, 0xfc, 0xe6, + 0xcd, 0x7b, 0xbf, 0x37, 0x36, 0x00, 0xc9, 0x88, 0xe7, 0xc4, 0x8c, 0x72, 0x8a, 0x4c, 0xb1, 0xbe, + 0x73, 0xdf, 0x0f, 0xf8, 0x59, 0x3a, 0x75, 0x3c, 0x3a, 0x1f, 0xf8, 0xd4, 0xa7, 0x03, 0x19, 0x9c, + 0xa6, 0xdf, 0x4b, 0x4b, 0x1a, 0x72, 0xa5, 0x36, 0xdd, 0x69, 0x13, 0xc6, 0x28, 0x4b, 0xb4, 0xd5, + 0x8a, 0xdc, 0x39, 0xc9, 0x8d, 0x26, 0xcf, 0xf2, 0xe5, 0x66, 0x4c, 0xd8, 0x3c, 0x48, 0x92, 0x80, + 0x46, 0xda, 0x03, 0x49, 0x9c, 0x1f, 0x6c, 0xff, 0x64, 0xc0, 0xed, 0x51, 0x48, 0xbd, 0x27, 0xe3, + 0x8c, 0x78, 0x29, 0x0f, 0x68, 0x84, 0xde, 0x84, 0xda, 0x21, 0x09, 0xfc, 0x33, 0x6e, 0x19, 0x7d, + 0x63, 0xdb, 0xc4, 0xda, 0x42, 0x0f, 0xa0, 0x25, 0x91, 0x87, 0xc4, 0x9d, 0x11, 0x66, 0x6d, 0xf4, + 0x8d, 0xed, 0xd6, 0xf0, 0x75, 0x47, 0xde, 0xa2, 0x14, 0xc0, 0x65, 0x14, 0xda, 0x85, 0xf6, 0x24, + 0x2b, 0xb8, 0x13, 0xab, 0xd2, 0xaf, 0xac, 0x76, 0x95, 0x22, 0x78, 0x0d, 0x66, 0x7f, 0xb8, 0x76, + 0x16, 0x42, 0x60, 0x3e, 0x7c, 0x74, 0x7a, 0x22, 0x13, 0x6a, 0x62, 0xb9, 0x16, 0x69, 0x9e, 0xa4, + 0xf3, 0x49, 0x96, 0xc8, 0x4c, 0xaa, 0x58, 0x5b, 0xf6, 0x1f, 0x15, 0x68, 0x95, 0xb8, 0xd0, 0x43, + 0xa8, 0x4d, 0xb2, 0xc9, 0x22, 0x26, 0x12, 0xd7, 0x19, 0x0d, 0x5f, 0x2c, 0x7b, 0x4e, 0xa9, 0xd0, + 0x67, 0x8b, 0x98, 0xb0, 0x90, 0xcc, 0x7c, 0xc2, 0x06, 0xd3, 0x94, 0x31, 0xfa, 0xc3, 0x80, 0x67, + 0xc9, 0x20, 0x76, 0x17, 0x21, 0x75, 0x67, 0x8e, 0xd8, 0x89, 0x35, 0x03, 0xfa, 0x4c, 0x70, 0x1d, + 0xba, 0xc9, 0x99, 0x55, 0xe9, 0x1b, 0xdb, 0xed, 0xd1, 0xee, 0xc5, 0xb2, 0x77, 0xeb, 0xd9, 0xb2, + 0x77, 0xff, 0xe5, 0x7c, 0xd3, 0x20, 0x72, 0xd9, 0xc2, 0x39, 0x24, 0xd9, 0x68, 0xc1, 0x49, 0x82, + 0x35, 0x49, 0xa9, 0xd2, 0xe6, 0x5a, 0xa5, 0xb7, 0xa0, 0x7a, 0x14, 0xcd, 0x48, 0x66, 0x55, 0xa5, + 0x5b, 0x19, 0xe8, 0x6b, 0x68, 0x8c, 0xa3, 0x73, 0x12, 0xd2, 0x98, 0x58, 0x35, 0x59, 0xfc, 0x8e, + 0x23, 0xda, 0x9c, 0x3b, 0x47, 0xce, 0xb3, 0x65, 0x6f, 0xe7, 0xca, 0x9b, 0x15, 0x78, 0x5c, 0xd0, + 0xa1, 0xbb, 0x50, 0x1b, 0x9f, 0x93, 0x88, 0x27, 0x56, 0x5d, 0xf6, 0xa7, 0xa5, 0xfa, 0x23, 0x7d, + 0x58, 0x87, 0xd0, 0x5b, 0x50, 0xc3, 0x24, 0x49, 0x43, 0x6e, 0x35, 0xe4, 0xe9, 0x6d, 0x05, 0x52, + 0x3e, 0xac, 0x63, 0xe8, 0x1e, 0xd4, 0x31, 0xf1, 0x48, 0x10, 0x73, 0xab, 0xa9, 0x61, 0xe2, 0x50, + 0xed, 0xc3, 0x79, 0x10, 0x0d, 0xa0, 0x39, 0xce, 0x3c, 0x12, 0x8b, 0x1e, 0x59, 0x90, 0x6b, 0x49, + 0x09, 0xba, 0x08, 0xe0, 0x15, 0xc6, 0xfe, 0x6d, 0x43, 0x54, 0x4b, 0xca, 0x61, 0xd5, 0x52, 0xe3, + 0x06, 0x5b, 0xba, 0x71, 0x13, 0x2d, 0x7d, 0x07, 0x9a, 0xb2, 0x5c, 0x32, 0xbb, 0x8a, 0xcc, 0xae, + 0xf3, 0x62, 0xd9, 0x5b, 0x39, 0xf1, 0x6a, 0x89, 0x2c, 0xa8, 0x4b, 0xe3, 0x68, 0x5f, 0x0a, 0xa0, + 0x89, 0x73, 0xb3, 0xa4, 0x8c, 0xea, 0x7f, 0x2b, 0xa3, 0x56, 0x56, 0xc6, 0x5a, 0x2d, 0xeb, 0x57, + 0xd7, 0xf2, 0x23, 0xf3, 0xe9, 0x2f, 0xbd, 0x5b, 0xf6, 0x8f, 0x1b, 0x50, 0x95, 0x07, 0x8a, 0xd6, + 0xea, 0xa9, 0x36, 0xca, 0xad, 0xd5, 0x03, 0x9d, 0x97, 0xfd, 0x9e, 0x38, 0x3c, 0x4e, 0xb9, 0x1e, + 0xfd, 0x4d, 0x05, 0x92, 0x2e, 0xa5, 0x14, 0x15, 0x46, 0x6f, 0x43, 0xed, 0x34, 0xe5, 0x02, 0x58, + 0x29, 0xbf, 0x11, 0xca, 0xa7, 0x35, 0xa5, 0x0c, 0x74, 0x17, 0xcc, 0x4f, 0xdd, 0x30, 0x94, 0xd7, + 0x6f, 0x0d, 0x5f, 0x53, 0x40, 0xe1, 0x51, 0x30, 0x19, 0x44, 0x7d, 0xa8, 0x1c, 0x53, 0x5f, 0x56, + 0xa2, 0x35, 0xbc, 0xad, 0x30, 0xc7, 0xd4, 0x57, 0x10, 0x11, 0x42, 0x9f, 0x40, 0xe7, 0x80, 0x9e, + 0x13, 0x16, 0xed, 0x79, 0x1e, 0x4d, 0x23, 0xae, 0xe7, 0xc3, 0x52, 0xd8, 0xb5, 0x90, 0xda, 0xb5, + 0x0e, 0xd7, 0xf5, 0x78, 0x6a, 0xe4, 0x0a, 0x17, 0xf5, 0xc7, 0x84, 0xa7, 0x2c, 0x92, 0x05, 0x69, + 0x63, 0x6d, 0x89, 0x8e, 0x1d, 0xb8, 0xc9, 0xe3, 0x84, 0xcc, 0x64, 0x11, 0x4c, 0x9c, 0x9b, 0x68, + 0x07, 0x9a, 0x27, 0xee, 0x9c, 0x8c, 0x23, 0xce, 0x16, 0xfa, 0xde, 0x6d, 0x47, 0x3d, 0xc9, 0xd2, + 0x87, 0x57, 0x61, 0xf4, 0x1e, 0x34, 0x3e, 0x27, 0x6c, 0xbe, 0xc7, 0xfc, 0x44, 0xdf, 0x7c, 0xcb, + 0x29, 0xbd, 0xd2, 0x79, 0x0c, 0x17, 0x28, 0xfb, 0x2f, 0x03, 0x1a, 0xf9, 0x95, 0xd1, 0x09, 0xd4, + 0xf7, 0x66, 0x33, 0x46, 0x92, 0x44, 0x65, 0x37, 0x7a, 0x5f, 0x6b, 0xf6, 0xdd, 0x97, 0x6b, 0xd6, + 0x63, 0x8b, 0x98, 0x53, 0x47, 0xef, 0xc5, 0x39, 0x09, 0x3a, 0x02, 0x73, 0xdf, 0xe5, 0xee, 0xf5, + 0x06, 0x40, 0x52, 0xa0, 0x63, 0xa8, 0x4d, 0x68, 0x1c, 0x78, 0xea, 0xa1, 0xff, 0xdf, 0x99, 0x69, + 0xb2, 0xaf, 0x28, 0x9b, 0x0d, 0x77, 0x3f, 0xc0, 0x9a, 0xc3, 0xfe, 0xdb, 0x80, 0x66, 0x21, 0x06, + 0xb4, 0x03, 0x0d, 0x61, 0xc8, 0x54, 0x8d, 0xb2, 0x16, 0x72, 0x2f, 0x2e, 0xe2, 0x22, 0x8f, 0x53, + 0x16, 0xf8, 0x41, 0xa4, 0x2f, 0xf5, 0x6a, 0x15, 0xd2, 0x1c, 0xa8, 0x0b, 0xf0, 0x88, 0xbb, 0xde, + 0x93, 0x7d, 0x12, 0x73, 0xf5, 0xf4, 0x9b, 0xb8, 0xe4, 0x11, 0x6f, 0x88, 0x56, 0x8b, 0x79, 0xad, + 0x37, 0x44, 0x91, 0xd8, 0x5f, 0x00, 0xfa, 0xb7, 0x64, 0xd1, 0xc7, 0xd0, 0xd1, 0xf6, 0xe3, 0x78, + 0xe6, 0x72, 0xa2, 0x6b, 0xf0, 0x86, 0x23, 0xbf, 0xe6, 0x13, 0x32, 0x8f, 0x43, 0x97, 0x13, 0x0d, + 0xc1, 0xeb, 0x58, 0xfb, 0x5b, 0x80, 0xd5, 0x9c, 0xde, 0xb4, 0x80, 0xec, 0xef, 0xa0, 0x55, 0x1a, + 0xee, 0x1b, 0xa7, 0xff, 0x79, 0x03, 0xd6, 0x3a, 0x2b, 0xd6, 0xfa, 0xa9, 0x7a, 0xe5, 0xce, 0x2a, + 0x8e, 0x82, 0x8d, 0x5c, 0x4f, 0x27, 0x8a, 0xa3, 0x18, 0xa4, 0xca, 0xf5, 0x07, 0x69, 0x0b, 0xaa, + 0x5f, 0xba, 0x61, 0x4a, 0xf4, 0x9f, 0x81, 0x32, 0xd0, 0x26, 0x54, 0x0e, 0xdc, 0x44, 0x7f, 0x13, + 0xc4, 0x72, 0x34, 0xba, 0xb8, 0xec, 0x1a, 0xbf, 0x5f, 0x76, 0x8d, 0x3f, 0x2f, 0xbb, 0xc6, 0xaf, + 0xcf, 0xbb, 0xc6, 0xc5, 0xf3, 0xae, 0xf1, 0xcd, 0x15, 0xe9, 0x93, 0xfc, 0xe7, 0x48, 0xae, 0xa6, + 0x35, 0xf9, 0x2b, 0xf8, 0xe0, 0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xa8, 0xaa, 0x48, 0xa0, 0x91, + 0x0a, 0x00, 0x00, } diff --git a/execution/execution.go b/execution/execution.go index 32ee4cf80..2fe05f133 100644 --- a/execution/execution.go +++ b/execution/execution.go @@ -15,17 +15,16 @@ package execution import ( + "context" "fmt" "runtime/debug" "sync" "time" - "context" - "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/acm/state" + "github.com/hyperledger/burrow/bcm" "github.com/hyperledger/burrow/binary" - bcm "github.com/hyperledger/burrow/blockchain" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/event" "github.com/hyperledger/burrow/execution/contexts" @@ -36,7 +35,6 @@ import ( "github.com/hyperledger/burrow/logging/structure" "github.com/hyperledger/burrow/txs" "github.com/hyperledger/burrow/txs/payload" - "github.com/pkg/errors" abciTypes "github.com/tendermint/tendermint/abci/types" ) @@ -83,7 +81,7 @@ type executor struct { blockExecution *exec.BlockExecution logger *logging.Logger vmOptions []func(*evm.VM) - txExecutors map[payload.Type]Context + contexts map[payload.Type]Context } var _ BatchExecutor = (*executor)(nil) @@ -92,20 +90,35 @@ var _ BatchExecutor = (*executor)(nil) func NewBatchChecker(backend ExecutorState, blockchain *bcm.Blockchain, logger *logging.Logger, options ...ExecutionOption) BatchExecutor { - return newExecutor("CheckCache", false, backend, blockchain, event.NewNoOpPublisher(), + exe := newExecutor("CheckCache", false, backend, blockchain, event.NewNoOpPublisher(), logger.WithScope("NewBatchExecutor"), options...) + + return exe.AddContext(payload.TypeGovernance, + &contexts.GovernanceContext{ + ValidatorSet: exe.blockchain.ValidatorChecker(), + StateWriter: exe.stateCache, + Logger: exe.logger, + }, + ) } func NewBatchCommitter(backend ExecutorState, blockchain *bcm.Blockchain, emitter event.Publisher, logger *logging.Logger, options ...ExecutionOption) BatchCommitter { - return newExecutor("CommitCache", true, backend, blockchain, emitter, + exe := newExecutor("CommitCache", true, backend, blockchain, emitter, logger.WithScope("NewBatchCommitter"), options...) + + return exe.AddContext(payload.TypeGovernance, + &contexts.GovernanceContext{ + ValidatorSet: exe.blockchain.ValidatorWriter(), + StateWriter: exe.stateCache, + Logger: exe.logger, + }, + ) } func newExecutor(name string, runCall bool, backend ExecutorState, blockchain *bcm.Blockchain, publisher event.Publisher, logger *logging.Logger, options ...ExecutionOption) *executor { - exe := &executor{ runCall: runCall, state: backend, @@ -121,7 +134,7 @@ func newExecutor(name string, runCall bool, backend ExecutorState, blockchain *b for _, option := range options { option(exe) } - exe.txExecutors = map[payload.Type]Context{ + exe.contexts = map[payload.Type]Context{ payload.TypeSend: &contexts.SendContext{ Tip: blockchain, StateWriter: exe.stateCache, @@ -145,15 +158,15 @@ func newExecutor(name string, runCall bool, backend ExecutorState, blockchain *b StateWriter: exe.stateCache, Logger: exe.logger, }, - payload.TypeGovernance: &contexts.GovernanceContext{ - ValidatorSet: blockchain, - StateWriter: exe.stateCache, - Logger: exe.logger, - }, } return exe } +func (exe *executor) AddContext(ty payload.Type, ctx Context) *executor { + exe.contexts[ty] = ctx + return exe +} + // If the tx is invalid, an error will be returned. // Unlike ExecBlock(), state will not be altered. func (exe *executor) Execute(txEnv *txs.Envelope) (txe *exec.TxExecution, err error) { @@ -176,7 +189,7 @@ func (exe *executor) Execute(txEnv *txs.Envelope) (txe *exec.TxExecution, err er return nil, err } - if txExecutor, ok := exe.txExecutors[txEnv.Tx.Type()]; ok { + if txExecutor, ok := exe.contexts[txEnv.Tx.Type()]; ok { // Establish new TxExecution txe := exe.blockExecution.Tx(txEnv) err = txExecutor.Execute(txe) @@ -251,15 +264,17 @@ func (exe *executor) Commit(blockHash []byte, blockTime time.Time, header *abciT } publishErr := exe.publisher.Publish(context.Background(), blockExecution, blockExecution.Tagged()) exe.logger.InfoMsg("Error publishing TxExecution", - "height", blockExecution.Height, - structure.ErrorKey, publishErr) - + "height", blockExecution.Height, structure.ErrorKey, publishErr) // Commit to our blockchain state which will checkpoint the previous app hash by saving it to the database // (we know the previous app hash is safely committed because we are about to commit the next) - err = exe.blockchain.CommitBlock(blockTime, blockHash, hash) + totalPowerChange, totalFlow, err := exe.blockchain.CommitBlock(blockTime, blockHash, hash) if err != nil { - panic(errors.Wrap(err, "could not commit block to blockchain state")) + panic(fmt.Errorf("could not commit block to blockchain state: %v", err)) } + exe.logger.InfoMsg("Committed block", + "total_validator_power", exe.blockchain.CurrentValidators().TotalPower(), + "total_validator_power_change", totalPowerChange, + "total_validator_flow", totalFlow) return hash, nil } diff --git a/execution/execution_test.go b/execution/execution_test.go index bfc4d96a2..58b28ab4b 100644 --- a/execution/execution_test.go +++ b/execution/execution_test.go @@ -17,16 +17,15 @@ package execution import ( "bytes" "fmt" + "runtime/debug" "strconv" "testing" "time" - "runtime/debug" - "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/acm/state" + "github.com/hyperledger/burrow/bcm" . "github.com/hyperledger/burrow/binary" - bcm "github.com/hyperledger/burrow/blockchain" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/event" "github.com/hyperledger/burrow/execution/errors" @@ -898,10 +897,10 @@ func TestSNativeTx(t *testing.T) { } func TestTxSequence(t *testing.T) { - state, privAccounts := makeGenesisState(3, true, 1000, 1, true, 1000) - acc0 := getAccount(state, privAccounts[0].Address()) + st, privAccounts := makeGenesisState(3, true, 1000, 1, true, 1000) + acc0 := getAccount(st, privAccounts[0].Address()) acc0PubKey := privAccounts[0].PublicKey() - acc1 := getAccount(state, privAccounts[1].Address()) + acc1 := getAccount(st, privAccounts[1].Address()) // Test a variety of sequence numbers for the tx. // The tx should only pass when i == 1. @@ -912,7 +911,7 @@ func TestTxSequence(t *testing.T) { tx.AddOutput(acc1.Address(), 1) txEnv := txs.Enclose(testChainID, tx) require.NoError(t, txEnv.Sign(privAccounts[0])) - stateCopy, err := state.Copy(dbm.NewMemDB()) + stateCopy, err := st.Copy(dbm.NewMemDB()) require.NoError(t, err) err = execTxWithState(stateCopy, txEnv) if i == 1 { @@ -1033,7 +1032,7 @@ func TestNameTxs(t *testing.T) { // fail to update it as non-owner // Fast forward - for exe.blockchain.Tip.LastBlockHeight() < entry.Expires-1 { + for exe.blockchain.LastBlockHeight() < entry.Expires-1 { commitNewBlock(st, exe.blockchain) } tx, _ = payload.NewNameTx(st, testPrivAccounts[1].PublicKey(), name, data, amt, fee) @@ -1086,7 +1085,7 @@ func TestNameTxs(t *testing.T) { require.NoError(t, err) validateEntry(t, entry, name, data, testPrivAccounts[0].Address(), startingBlock+numDesiredBlocks) // Fast forward - for exe.blockchain.Tip.LastBlockHeight() < entry.Expires { + for exe.blockchain.LastBlockHeight() < entry.Expires { commitNewBlock(st, exe.blockchain) } @@ -1613,7 +1612,7 @@ func execTxWithStateNewBlock(state *State, blockchain *bcm.Blockchain, txEnv *tx } func makeGenesisState(numAccounts int, randBalance bool, minBalance uint64, numValidators int, randBonded bool, - minBonded int64) (*State, []acm.AddressableSigner) { + minBonded int64) (*State, []*acm.PrivateAccount) { testGenesisDoc, privAccounts, _ := deterministicGenesis.GenesisDoc(numAccounts, randBalance, minBalance, numValidators, randBonded, minBonded) s0, err := MakeGenesisState(dbm.NewMemDB(), testGenesisDoc) @@ -1625,7 +1624,10 @@ func makeGenesisState(numAccounts int, randBalance bool, minBalance uint64, numV } func getAccount(accountGetter state.AccountGetter, address crypto.Address) *acm.MutableAccount { - acc, _ := state.GetMutableAccount(accountGetter, address) + acc, err := state.GetMutableAccount(accountGetter, address) + if err != nil { + panic(err) + } return acc } @@ -1658,7 +1660,7 @@ func execTxWaitAccountCall(t *testing.T, exe *testExecutor, txEnv *txs.Envelope, } _, err = exe.Commit([]byte("Blocky McHash"), time.Now(), nil) require.NoError(t, err) - err = exe.blockchain.CommitBlock(time.Time{}, nil, nil) + _, _, err = exe.blockchain.CommitBlock(time.Time{}, nil, nil) require.NoError(t, err) for _, ev := range evs.TaggedEvents().Filter(qry) { @@ -1725,7 +1727,7 @@ func testSNativeTx(t *testing.T, expectPass bool, batchCommitter *testExecutor, acc.MutablePermissions().Base.Set(perm, true) batchCommitter.stateCache.UpdateAccount(acc) } - tx, _ := payload.NewPermissionsTx(batchCommitter.stateCache, users[0].PublicKey(), snativeArgs) + tx, _ := payload.NewPermsTx(batchCommitter.stateCache, users[0].PublicKey(), snativeArgs) txEnv := txs.Enclose(testChainID, tx) require.NoError(t, txEnv.Sign(users[0])) _, err := batchCommitter.Execute(txEnv) diff --git a/execution/simulated_call.go b/execution/simulated_call.go index d921b5e45..0274a7393 100644 --- a/execution/simulated_call.go +++ b/execution/simulated_call.go @@ -6,8 +6,8 @@ import ( "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/acm/state" + "github.com/hyperledger/burrow/bcm" "github.com/hyperledger/burrow/binary" - "github.com/hyperledger/burrow/blockchain" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/execution/contexts" "github.com/hyperledger/burrow/execution/evm" @@ -17,7 +17,7 @@ import ( // Run a contract's code on an isolated and unpersisted state // Cannot be used to create new contracts -func CallSim(reader state.Reader, tip blockchain.TipInfo, fromAddress, address crypto.Address, data []byte, +func CallSim(reader state.Reader, tip bcm.BlockchainInfo, fromAddress, address crypto.Address, data []byte, logger *logging.Logger) (*exec.TxExecution, error) { if evm.IsRegisteredNativeContract(address.Word256()) { @@ -38,7 +38,7 @@ func CallSim(reader state.Reader, tip blockchain.TipInfo, fromAddress, address c // Run the given code on an isolated and unpersisted state // Cannot be used to create new contracts. -func CallCodeSim(reader state.Reader, tip blockchain.TipInfo, fromAddress, address crypto.Address, code, data []byte, +func CallCodeSim(reader state.Reader, tip bcm.BlockchainInfo, fromAddress, address crypto.Address, code, data []byte, logger *logging.Logger) (_ *exec.TxExecution, err error) { // This was being run against CheckTx cache, need to understand the reasoning caller := acm.ConcreteAccount{Address: fromAddress}.MutableAccount() @@ -65,7 +65,7 @@ func CallCodeSim(reader state.Reader, tip blockchain.TipInfo, fromAddress, addre return txe, nil } -func vmParams(tip blockchain.TipInfo) evm.Params { +func vmParams(tip bcm.BlockchainInfo) evm.Params { return evm.Params{ BlockHeight: tip.LastBlockHeight(), BlockHash: binary.LeftPadWord256(tip.LastBlockHash()), diff --git a/execution/transactor.go b/execution/transactor.go index 932e31297..c1a12edc3 100644 --- a/execution/transactor.go +++ b/execution/transactor.go @@ -20,10 +20,11 @@ import ( "time" "github.com/hyperledger/burrow/acm" - "github.com/hyperledger/burrow/blockchain" + "github.com/hyperledger/burrow/bcm" "github.com/hyperledger/burrow/consensus/tendermint/codes" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/event" + "github.com/hyperledger/burrow/execution/errors" "github.com/hyperledger/burrow/execution/exec" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" @@ -46,7 +47,7 @@ const ( // for a key it holds or is provided - it is down to the key-holder to manage the mutual information between transactions // concurrent within a new block window. type Transactor struct { - Tip blockchain.TipInfo + Tip bcm.BlockchainInfo Subscribable event.Subscribable MempoolAccounts *Accounts checkTxAsync func(tx tmTypes.Tx, cb func(*abciTypes.Response)) error @@ -54,7 +55,7 @@ type Transactor struct { logger *logging.Logger } -func NewTransactor(tip blockchain.TipInfo, subscribable event.Subscribable, mempoolAccounts *Accounts, +func NewTransactor(tip bcm.BlockchainInfo, subscribable event.Subscribable, mempoolAccounts *Accounts, checkTxAsync func(tx tmTypes.Tx, cb func(*abciTypes.Response)) error, txEncoder txs.Encoder, logger *logging.Logger) *Transactor { @@ -76,7 +77,7 @@ func (trans *Transactor) BroadcastTxSync(ctx context.Context, txEnv *txs.Envelop var unlock UnlockFunc txEnv, unlock, err = trans.SignTxMempool(txEnv) if err != nil { - return nil, fmt.Errorf("error signing trnasction: %v", err) + return nil, fmt.Errorf("error signing transaction: %v", err) } defer unlock() } @@ -215,8 +216,8 @@ func (trans *Transactor) CheckTxSyncRaw(txBytes []byte) (*txs.Receipt, error) { } return receipt, nil default: - return nil, fmt.Errorf("error returned by Tendermint in BroadcastTxSync "+ - "ABCI code: %v, ABCI log: %v", checkTxResponse.Code, checkTxResponse.Log) + return nil, errors.ErrorCodef(errors.Code(checkTxResponse.Code), + "error returned by Tendermint in BroadcastTxSync ABCI log: %v", checkTxResponse.Log) } } } diff --git a/execution/transactor_test.go b/execution/transactor_test.go index 5d19f06f7..3e9f82e64 100644 --- a/execution/transactor_test.go +++ b/execution/transactor_test.go @@ -17,11 +17,10 @@ package execution import ( "context" "testing" - "time" "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/acm/state" - "github.com/hyperledger/burrow/blockchain" + "github.com/hyperledger/burrow/bcm" "github.com/hyperledger/burrow/consensus/tendermint/codes" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/event" @@ -38,7 +37,7 @@ import ( func TestTransactor_BroadcastTxSync(t *testing.T) { chainID := "TestChain" - tip := blockchain.NewTip(chainID, time.Time{}, []byte("genesis"), blockchain.NewValidators()) + bc := &bcm.Blockchain{} logger := logging.NewNoopLogger() evc := event.NewEmitter(logger) txCodec := txs.NewAminoCodec() @@ -53,7 +52,7 @@ func TestTransactor_BroadcastTxSync(t *testing.T) { err := txEnv.Sign(privAccount) require.NoError(t, err) height := uint64(35) - trans := NewTransactor(tip, evc, NewAccounts(state.NewMemoryState(), mock.NewKeyClient(privAccount), 100), + trans := NewTransactor(bc, evc, NewAccounts(state.NewMemoryState(), mock.NewKeyClient(privAccount), 100), func(tx tmTypes.Tx, cb func(*abciTypes.Response)) error { txe := exec.NewTxExecution(txEnv) txe.Height = height diff --git a/genesis/deterministic_genesis.go b/genesis/deterministic_genesis.go index 15708c9e6..d7da9d22b 100644 --- a/genesis/deterministic_genesis.go +++ b/genesis/deterministic_genesis.go @@ -22,10 +22,10 @@ func NewDeterministicGenesis(seed int64) *deterministicGenesis { } func (dg *deterministicGenesis) GenesisDoc(numAccounts int, randBalance bool, minBalance uint64, numValidators int, - randBonded bool, minBonded int64) (*GenesisDoc, []acm.AddressableSigner, []acm.AddressableSigner) { + randBonded bool, minBonded int64) (*GenesisDoc, []*acm.PrivateAccount, []*acm.PrivateAccount) { accounts := make([]Account, numAccounts) - privAccounts := make([]acm.AddressableSigner, numAccounts) + privAccounts := make([]*acm.PrivateAccount, numAccounts) defaultPerms := permission.DefaultAccountPermissions for i := 0; i < numAccounts; i++ { account, privAccount := dg.Account(randBalance, minBalance) @@ -39,7 +39,7 @@ func (dg *deterministicGenesis) GenesisDoc(numAccounts int, randBalance bool, mi privAccounts[i] = privAccount } validators := make([]Validator, numValidators) - privValidators := make([]acm.AddressableSigner, numValidators) + privValidators := make([]*acm.PrivateAccount, numValidators) for i := 0; i < numValidators; i++ { validator := acm.GeneratePrivateAccountFromSecret(fmt.Sprintf("val_%v", i)) privValidators[i] = validator @@ -66,7 +66,7 @@ func (dg *deterministicGenesis) GenesisDoc(numAccounts int, randBalance bool, mi } -func (dg *deterministicGenesis) Account(randBalance bool, minBalance uint64) (acm.Account, acm.AddressableSigner) { +func (dg *deterministicGenesis) Account(randBalance bool, minBalance uint64) (acm.Account, *acm.PrivateAccount) { privateKey, err := crypto.GeneratePrivateKey(dg.random, crypto.CurveTypeEd25519) if err != nil { panic(fmt.Errorf("could not generate private key deterministically")) diff --git a/genesis/genesis.go b/genesis/genesis.go index c98607e1b..bfc30c2f9 100644 --- a/genesis/genesis.go +++ b/genesis/genesis.go @@ -22,6 +22,7 @@ import ( "time" "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/validator" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/permission" ) @@ -66,6 +67,14 @@ type GenesisDoc struct { Validators []Validator } +func (genesisDoc *GenesisDoc) JSONString() string { + bs, err := genesisDoc.JSONBytes() + if err != nil { + return fmt.Sprintf("error marshalling GenesisDoc: %v", err) + } + return string(bs) +} + // JSONBytes returns the JSON canonical bytes for a given GenesisDoc or an error. func (genesisDoc *GenesisDoc) JSONBytes() ([]byte, error) { // Just in case @@ -133,12 +142,13 @@ func (genesisAccount *Account) Clone() Account { //------------------------------------------------------------ // Validator methods -func (gv *Validator) Validator() acm.Validator { - return acm.ConcreteValidator{ - Address: gv.PublicKey.Address(), +func (gv *Validator) Validator() validator.Validator { + address := gv.PublicKey.Address() + return validator.Validator{ + Address: &address, PublicKey: gv.PublicKey, Power: uint64(gv.Amount), - }.Validator() + } } // Clone clones the genesis validator @@ -175,7 +185,7 @@ func (basicAccount *BasicAccount) Clone() BasicAccount { // failure. In particular MakeGenesisDocFromAccount uses the local time as a // timestamp for the GenesisDoc. func MakeGenesisDocFromAccounts(chainName string, salt []byte, genesisTime time.Time, accounts map[string]acm.Account, - validators map[string]acm.Validator) *GenesisDoc { + validators map[string]validator.Validator) *GenesisDoc { // Establish deterministic order of accounts by name so we obtain identical GenesisDoc // from identical input @@ -202,15 +212,15 @@ func MakeGenesisDocFromAccounts(chainName string, salt []byte, genesisTime time. genesisValidators = append(genesisValidators, Validator{ Name: name, BasicAccount: BasicAccount{ - Address: val.Address(), - PublicKey: val.PublicKey(), - Amount: val.Power(), + Address: *val.Address, + PublicKey: val.PublicKey, + Amount: val.Power, }, // Simpler to just do this by convention UnbondTo: []BasicAccount{ { - Amount: val.Power(), - Address: val.Address(), + Amount: val.Power, + Address: *val.Address, }, }, }) diff --git a/genesis/genesis_test.go b/genesis/genesis_test.go index 640bf18d9..cfeb6f41e 100644 --- a/genesis/genesis_test.go +++ b/genesis/genesis_test.go @@ -6,6 +6,7 @@ import ( "time" "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/validator" "github.com/hyperledger/burrow/permission" "github.com/stretchr/testify/assert" ) @@ -41,10 +42,11 @@ func accountMap(names ...string) map[string]acm.Account { return accounts } -func validatorMap(names ...string) map[string]acm.Validator { - validators := make(map[string]acm.Validator, len(names)) +func validatorMap(names ...string) map[string]validator.Validator { + validators := make(map[string]validator.Validator, len(names)) for _, name := range names { - validators[name] = acm.AsValidator(accountFromName(name)) + acc := accountFromName(name) + validators[name] = validator.FromAccount(acc, acc.Balance()) } return validators } diff --git a/genesis/spec/genesis_spec.go b/genesis/spec/genesis_spec.go index de96d9a74..6990afa12 100644 --- a/genesis/spec/genesis_spec.go +++ b/genesis/spec/genesis_spec.go @@ -7,6 +7,7 @@ import ( "fmt" "time" + "github.com/hyperledger/burrow/acm/balance" "github.com/hyperledger/burrow/genesis" "github.com/hyperledger/burrow/keys" "github.com/hyperledger/burrow/permission" @@ -68,9 +69,8 @@ func (gs *GenesisSpec) GenesisDoc(keyClient keys.KeyClient, generateNodeKeys boo templateAccounts := gs.Accounts if len(gs.Accounts) == 0 { - Power := DefaultPower templateAccounts = append(templateAccounts, TemplateAccount{ - Power: &Power, + Amounts: balance.New().Power(DefaultPower), }) } @@ -80,8 +80,8 @@ func (gs *GenesisSpec) GenesisDoc(keyClient keys.KeyClient, generateNodeKeys boo return nil, fmt.Errorf("could not create Account from template: %v", err) } genesisDoc.Accounts = append(genesisDoc.Accounts, *account) - // Create a corresponding validator - if templateAccount.Power != nil { + + if templateAccount.Balances().HasPower() { // Note this does not modify the input template templateAccount.Address = &account.Address validator, err := templateAccount.Validator(keyClient, i, generateNodeKeys) diff --git a/genesis/spec/genesis_spec_test.go b/genesis/spec/genesis_spec_test.go index 98665055d..1d52df39a 100644 --- a/genesis/spec/genesis_spec_test.go +++ b/genesis/spec/genesis_spec_test.go @@ -3,6 +3,7 @@ package spec import ( "testing" + "github.com/hyperledger/burrow/acm/balance" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/keys/mock" "github.com/hyperledger/burrow/permission" @@ -17,7 +18,7 @@ func TestGenesisSpec_GenesisDoc(t *testing.T) { amtBonded := uint64(100) genesisSpec := GenesisSpec{ Accounts: []TemplateAccount{{ - Power: &amtBonded, + Amounts: balance.New().Power(amtBonded), }}, } @@ -46,7 +47,7 @@ func TestGenesisSpec_GenesisDoc(t *testing.T) { Address: &address, }, { - Amount: &amt, + Amounts: balance.New().Native(amt), Permissions: []string{permission.CreateAccountString, permission.CallString}, }}, } diff --git a/genesis/spec/presets.go b/genesis/spec/presets.go index 3025d98c0..223ae0f4f 100644 --- a/genesis/spec/presets.go +++ b/genesis/spec/presets.go @@ -3,6 +3,7 @@ package spec import ( "sort" + "github.com/hyperledger/burrow/acm/balance" "github.com/hyperledger/burrow/permission" ) @@ -16,8 +17,7 @@ func FullAccount(name string) GenesisSpec { return GenesisSpec{ Accounts: []TemplateAccount{{ Name: name, - Amount: &amount, - Power: &Power, + Amounts: balance.New().Native(amount).Power(Power), Permissions: []string{permission.AllString}, }, }, @@ -30,7 +30,7 @@ func RootAccount(name string) GenesisSpec { return GenesisSpec{ Accounts: []TemplateAccount{{ Name: name, - Amount: &amount, + Amounts: balance.New().Native(amount), Permissions: []string{permission.AllString}, }, }, @@ -42,8 +42,8 @@ func ParticipantAccount(name string) GenesisSpec { amount := uint64(9999999999) return GenesisSpec{ Accounts: []TemplateAccount{{ - Name: name, - Amount: &amount, + Name: name, + Amounts: balance.New().Native(amount), Permissions: []string{permission.SendString, permission.CallString, permission.NameString, permission.HasRoleString}, }}, @@ -55,8 +55,8 @@ func DeveloperAccount(name string) GenesisSpec { amount := uint64(9999999999) return GenesisSpec{ Accounts: []TemplateAccount{{ - Name: name, - Amount: &amount, + Name: name, + Amounts: balance.New().Native(amount), Permissions: []string{permission.SendString, permission.CallString, permission.CreateContractString, permission.CreateAccountString, permission.NameString, permission.HasRoleString, permission.RemoveRoleString}, @@ -71,8 +71,7 @@ func ValidatorAccount(name string) GenesisSpec { return GenesisSpec{ Accounts: []TemplateAccount{{ Name: name, - Amount: &amount, - Power: &Power, + Amounts: balance.New().Native(amount).Power(Power), Permissions: []string{permission.BondString}, }}, } @@ -146,8 +145,7 @@ func mergeAccount(base, override TemplateAccount) TemplateAccount { base.Name = override.Name } - base.Amount = addUint64Pointers(base.Amount, override.Amount) - base.Power = addUint64Pointers(base.Power, override.Power) + base.Amounts = base.Balances().Sum(override.Balances()) base.Permissions = mergeStrings(base.Permissions, override.Permissions) base.Roles = mergeStrings(base.Roles, override.Roles) diff --git a/genesis/spec/presets_test.go b/genesis/spec/presets_test.go index 762e397bd..1c11015f9 100644 --- a/genesis/spec/presets_test.go +++ b/genesis/spec/presets_test.go @@ -3,6 +3,7 @@ package spec import ( "testing" + "github.com/hyperledger/burrow/acm/balance" "github.com/hyperledger/burrow/keys/mock" "github.com/hyperledger/burrow/permission" "github.com/stretchr/testify/assert" @@ -43,7 +44,7 @@ func TestMergeGenesisSpecsRepeatedAccounts(t *testing.T) { Accounts: []TemplateAccount{ { Name: name1, - Amount: &amt1, + Amounts: balance.New().Native(amt1), Permissions: []string{permission.SendString, permission.CreateAccountString, permission.HasRoleString}, Roles: []string{"fooer"}, }, @@ -53,7 +54,7 @@ func TestMergeGenesisSpecsRepeatedAccounts(t *testing.T) { Accounts: []TemplateAccount{ { Name: name1, - Amount: &amt2, + Amounts: balance.New().Native(amt2), Permissions: []string{permission.SendString, permission.CreateAccountString}, Roles: []string{"barer"}, }, @@ -62,8 +63,8 @@ func TestMergeGenesisSpecsRepeatedAccounts(t *testing.T) { gs3 := GenesisSpec{ Accounts: []TemplateAccount{ { - Name: name3, - Amount: &amt3, + Name: name3, + Amounts: balance.New().Native(amt3), }, }, } @@ -77,7 +78,7 @@ func TestMergeGenesisSpecsRepeatedAccounts(t *testing.T) { Accounts: []TemplateAccount{ { Name: name1, - Amount: &amtExpected, + Amounts: balance.New().Native(amtExpected), Permissions: []string{permission.CreateAccountString, permission.HasRoleString, permission.SendString}, Roles: []string{"barer", "fooer"}, }, diff --git a/genesis/spec/spec.pb.go b/genesis/spec/spec.pb.go index 9d568bfd4..ffaaef3af 100644 --- a/genesis/spec/spec.pb.go +++ b/genesis/spec/spec.pb.go @@ -18,6 +18,7 @@ import fmt "fmt" import math "math" import _ "github.com/gogo/protobuf/gogoproto" import crypto "github.com/hyperledger/burrow/crypto" +import balance "github.com/hyperledger/burrow/acm/balance" import github_com_hyperledger_burrow_crypto "github.com/hyperledger/burrow/crypto" @@ -36,14 +37,13 @@ var _ = math.Inf const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package type TemplateAccount struct { - Name string `protobuf:"bytes,1,opt,name=Name" json:"Name"` - Address *github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,2,opt,name=Address,customtype=github.com/hyperledger/burrow/crypto.Address" json:",omitempty" toml:",omitempty"` - NodeAddress *github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,3,opt,name=NodeAddress,customtype=github.com/hyperledger/burrow/crypto.Address" json:",omitempty" toml:",omitempty"` + Name string `protobuf:"bytes,1,opt,name=Name,proto3" json:"Name,omitempty"` + Address *github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,2,opt,name=Address,proto3,customtype=github.com/hyperledger/burrow/crypto.Address" json:",omitempty" toml:",omitempty"` + NodeAddress *github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,3,opt,name=NodeAddress,proto3,customtype=github.com/hyperledger/burrow/crypto.Address" json:",omitempty" toml:",omitempty"` PublicKey *crypto.PublicKey `protobuf:"bytes,4,opt,name=PublicKey" json:",omitempty" toml:",omitempty"` - Amount *uint64 `protobuf:"varint,5,opt,name=Amount" json:",omitempty" toml:",omitempty"` - Power *uint64 `protobuf:"varint,6,opt,name=Power" json:",omitempty" toml:",omitempty"` - Permissions []string `protobuf:"bytes,7,rep,name=Permissions" json:",omitempty" toml:",omitempty"` - Roles []string `protobuf:"bytes,8,rep,name=Roles" json:",omitempty" toml:",omitempty"` + Amounts []balance.Balance `protobuf:"bytes,5,rep,name=Amounts" json:",omitempty" toml:",omitempty"` + Permissions []string `protobuf:"bytes,6,rep,name=Permissions" json:",omitempty" toml:",omitempty"` + Roles []string `protobuf:"bytes,7,rep,name=Roles" json:",omitempty" toml:",omitempty"` } func (m *TemplateAccount) Reset() { *m = TemplateAccount{} } @@ -65,18 +65,11 @@ func (m *TemplateAccount) GetPublicKey() *crypto.PublicKey { return nil } -func (m *TemplateAccount) GetAmount() uint64 { - if m != nil && m.Amount != nil { - return *m.Amount - } - return 0 -} - -func (m *TemplateAccount) GetPower() uint64 { - if m != nil && m.Power != nil { - return *m.Power +func (m *TemplateAccount) GetAmounts() []balance.Balance { + if m != nil { + return m.Amounts } - return 0 + return nil } func (m *TemplateAccount) GetPermissions() []string { @@ -115,10 +108,12 @@ func (m *TemplateAccount) MarshalTo(dAtA []byte) (int, error) { _ = i var l int _ = l - dAtA[i] = 0xa - i++ - i = encodeVarintSpec(dAtA, i, uint64(len(m.Name))) - i += copy(dAtA[i:], m.Name) + if len(m.Name) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintSpec(dAtA, i, uint64(len(m.Name))) + i += copy(dAtA[i:], m.Name) + } if m.Address != nil { dAtA[i] = 0x12 i++ @@ -149,19 +144,21 @@ func (m *TemplateAccount) MarshalTo(dAtA []byte) (int, error) { } i += n3 } - if m.Amount != nil { - dAtA[i] = 0x28 - i++ - i = encodeVarintSpec(dAtA, i, uint64(*m.Amount)) - } - if m.Power != nil { - dAtA[i] = 0x30 - i++ - i = encodeVarintSpec(dAtA, i, uint64(*m.Power)) + if len(m.Amounts) > 0 { + for _, msg := range m.Amounts { + dAtA[i] = 0x2a + i++ + i = encodeVarintSpec(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } } if len(m.Permissions) > 0 { for _, s := range m.Permissions { - dAtA[i] = 0x3a + dAtA[i] = 0x32 i++ l = len(s) for l >= 1<<7 { @@ -176,7 +173,7 @@ func (m *TemplateAccount) MarshalTo(dAtA []byte) (int, error) { } if len(m.Roles) > 0 { for _, s := range m.Roles { - dAtA[i] = 0x42 + dAtA[i] = 0x3a i++ l = len(s) for l >= 1<<7 { @@ -205,7 +202,9 @@ func (m *TemplateAccount) Size() (n int) { var l int _ = l l = len(m.Name) - n += 1 + l + sovSpec(uint64(l)) + if l > 0 { + n += 1 + l + sovSpec(uint64(l)) + } if m.Address != nil { l = m.Address.Size() n += 1 + l + sovSpec(uint64(l)) @@ -218,11 +217,11 @@ func (m *TemplateAccount) Size() (n int) { l = m.PublicKey.Size() n += 1 + l + sovSpec(uint64(l)) } - if m.Amount != nil { - n += 1 + sovSpec(uint64(*m.Amount)) - } - if m.Power != nil { - n += 1 + sovSpec(uint64(*m.Power)) + if len(m.Amounts) > 0 { + for _, e := range m.Amounts { + l = e.Size() + n += 1 + l + sovSpec(uint64(l)) + } } if len(m.Permissions) > 0 { for _, s := range m.Permissions { @@ -408,10 +407,10 @@ func (m *TemplateAccount) Unmarshal(dAtA []byte) error { } iNdEx = postIndex case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Amounts", wireType) } - var v uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowSpec @@ -421,33 +420,24 @@ func (m *TemplateAccount) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - v |= (uint64(b) & 0x7F) << shift + msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } - m.Amount = &v - case 6: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Power", wireType) + if msglen < 0 { + return ErrInvalidLengthSpec } - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSpec - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF } - m.Power = &v - case 7: + m.Amounts = append(m.Amounts, balance.Balance{}) + if err := m.Amounts[len(m.Amounts)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Permissions", wireType) } @@ -476,7 +466,7 @@ func (m *TemplateAccount) Unmarshal(dAtA []byte) error { } m.Permissions = append(m.Permissions, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex - case 8: + case 7: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Roles", wireType) } @@ -635,28 +625,28 @@ func init() { proto.RegisterFile("spec.proto", fileDescriptorSpec) } func init() { golang_proto.RegisterFile("spec.proto", fileDescriptorSpec) } var fileDescriptorSpec = []byte{ - // 359 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x92, 0x3f, 0x6f, 0xe2, 0x30, - 0x18, 0x87, 0xf1, 0x11, 0xe0, 0x30, 0x48, 0x27, 0x3c, 0x59, 0x0c, 0x49, 0xc4, 0x2d, 0xd1, 0x89, - 0x23, 0xd2, 0x6d, 0x47, 0x97, 0x12, 0xa9, 0x53, 0x25, 0x84, 0x28, 0x53, 0x37, 0x92, 0xbc, 0x0d, - 0x91, 0x62, 0x1c, 0xd9, 0x8e, 0x50, 0x3e, 0x4e, 0xbf, 0x49, 0x47, 0x46, 0xe6, 0x0e, 0x51, 0x05, - 0x43, 0xa5, 0x8e, 0xfd, 0x04, 0x55, 0x42, 0x28, 0x4c, 0x55, 0x96, 0x6e, 0xef, 0x1f, 0x3d, 0xbf, - 0xc7, 0xb2, 0x8d, 0xb1, 0x8c, 0xc1, 0x1b, 0xc5, 0x82, 0x2b, 0x4e, 0xb4, 0xbc, 0xee, 0xff, 0x0d, - 0x42, 0xb5, 0x4a, 0xdc, 0x91, 0xc7, 0x99, 0x1d, 0xf0, 0x80, 0xdb, 0xc5, 0xd2, 0x4d, 0x1e, 0x8a, - 0xae, 0x68, 0x8a, 0xea, 0x08, 0xf5, 0xbb, 0x9e, 0x48, 0x63, 0x55, 0x76, 0x83, 0x57, 0x0d, 0xff, - 0x5a, 0x00, 0x8b, 0xa3, 0xa5, 0x82, 0x89, 0xe7, 0xf1, 0x64, 0xad, 0x08, 0xc5, 0xda, 0x74, 0xc9, - 0x80, 0x22, 0x13, 0x59, 0x6d, 0x47, 0xdb, 0x66, 0x46, 0x6d, 0x5e, 0x4c, 0x08, 0xc3, 0xad, 0x89, - 0xef, 0x0b, 0x90, 0x92, 0xfe, 0x30, 0x91, 0xd5, 0x75, 0xee, 0x9e, 0x33, 0x63, 0x78, 0xe1, 0x5f, - 0xa5, 0x31, 0x88, 0x08, 0xfc, 0x00, 0x84, 0xed, 0x26, 0x42, 0xf0, 0x8d, 0x5d, 0xea, 0x4a, 0xee, - 0x2d, 0x33, 0xf0, 0x90, 0xb3, 0x50, 0x01, 0x8b, 0x55, 0xfa, 0x9e, 0x19, 0x3d, 0xc5, 0x59, 0x34, - 0x1e, 0x9c, 0x67, 0x83, 0xf9, 0xc9, 0x41, 0x12, 0xdc, 0x99, 0x72, 0x1f, 0x4e, 0xca, 0xfa, 0xf7, - 0x29, 0x2f, 0x3d, 0x64, 0x81, 0xdb, 0xb3, 0xc4, 0x8d, 0x42, 0xef, 0x16, 0x52, 0xaa, 0x99, 0xc8, - 0xea, 0xfc, 0xeb, 0x8d, 0xca, 0xcc, 0xcf, 0x85, 0xf3, 0xbb, 0x4a, 0xee, 0x39, 0x88, 0x5c, 0xe1, - 0xe6, 0x84, 0xe5, 0xf7, 0x4b, 0x1b, 0x26, 0xb2, 0xb4, 0x6a, 0x7c, 0x89, 0x90, 0xff, 0xb8, 0x31, - 0xe3, 0x1b, 0x10, 0xb4, 0x59, 0x9d, 0x3d, 0x12, 0xe4, 0x06, 0x77, 0x66, 0x20, 0x58, 0x28, 0x65, - 0xc8, 0xd7, 0x92, 0xb6, 0xcc, 0xba, 0xd5, 0xae, 0x16, 0x70, 0xc9, 0xe5, 0x27, 0x98, 0xf3, 0x08, - 0x24, 0xfd, 0x59, 0x3d, 0xe0, 0x48, 0x8c, 0xb5, 0xdd, 0xa3, 0x51, 0x73, 0xae, 0xb7, 0x7b, 0x1d, - 0xed, 0xf6, 0x3a, 0x7a, 0xd9, 0xeb, 0xe8, 0xe9, 0xa0, 0xa3, 0xed, 0x41, 0x47, 0xf7, 0x7f, 0xbe, - 0x7e, 0xc9, 0x00, 0xd6, 0x20, 0x43, 0x69, 0xe7, 0x1f, 0xfd, 0x23, 0x00, 0x00, 0xff, 0xff, 0x4b, - 0xcc, 0xe3, 0x66, 0xfb, 0x02, 0x00, 0x00, + // 367 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x52, 0xbf, 0x6f, 0xda, 0x40, + 0x14, 0xee, 0x15, 0x03, 0xe2, 0x4c, 0xd5, 0x72, 0x93, 0xc5, 0x60, 0x5b, 0x74, 0xa8, 0x55, 0x51, + 0x5b, 0xa2, 0x53, 0x3b, 0x15, 0x4b, 0x9d, 0x22, 0x21, 0x04, 0x4c, 0xd9, 0xfc, 0xe3, 0xc5, 0x58, + 0xf2, 0xf9, 0xac, 0xbb, 0xb3, 0x22, 0xff, 0x67, 0x19, 0x33, 0x32, 0x66, 0xce, 0x60, 0x45, 0xb0, + 0x65, 0xcc, 0x5f, 0x10, 0x61, 0xe3, 0xc0, 0x14, 0x79, 0xc9, 0x74, 0xdf, 0x77, 0x4f, 0xdf, 0xf7, + 0x3d, 0xbd, 0xf7, 0x30, 0x16, 0x19, 0x04, 0x76, 0xc6, 0x99, 0x64, 0x44, 0x39, 0xe2, 0xf1, 0xaf, + 0x28, 0x96, 0xdb, 0xdc, 0xb7, 0x03, 0x46, 0x9d, 0x88, 0x45, 0xcc, 0xa9, 0x8a, 0x7e, 0x7e, 0x53, + 0xb1, 0x8a, 0x54, 0xa8, 0x16, 0x8d, 0x87, 0x01, 0x2f, 0x32, 0xd9, 0xb0, 0x2f, 0xbe, 0x97, 0x78, + 0x69, 0x00, 0x35, 0x9d, 0xdc, 0x29, 0xf8, 0xeb, 0x06, 0x68, 0x96, 0x78, 0x12, 0xe6, 0x41, 0xc0, + 0xf2, 0x54, 0x12, 0x82, 0x95, 0x85, 0x47, 0x41, 0x43, 0x26, 0xb2, 0x06, 0xab, 0x0a, 0x13, 0x8a, + 0xfb, 0xf3, 0x30, 0xe4, 0x20, 0x84, 0xf6, 0xd9, 0x44, 0xd6, 0xd0, 0x5d, 0x3f, 0x96, 0xc6, 0xf4, + 0xa2, 0x91, 0x6d, 0x91, 0x01, 0x4f, 0x20, 0x8c, 0x80, 0x3b, 0x7e, 0xce, 0x39, 0xbb, 0x75, 0x4e, + 0xb9, 0x27, 0xdd, 0x73, 0x69, 0xe0, 0x29, 0xa3, 0xb1, 0x04, 0x9a, 0xc9, 0xe2, 0xa5, 0x34, 0x46, + 0x92, 0xd1, 0xe4, 0xef, 0xe4, 0xfc, 0x37, 0x59, 0x35, 0x19, 0x24, 0xc7, 0xea, 0x82, 0x85, 0xd0, + 0x44, 0x76, 0x3e, 0x2e, 0xf2, 0x32, 0x87, 0x6c, 0xf0, 0x60, 0x99, 0xfb, 0x49, 0x1c, 0x5c, 0x41, + 0xa1, 0x29, 0x26, 0xb2, 0xd4, 0xd9, 0xc8, 0x3e, 0x79, 0xbe, 0x15, 0xdc, 0xef, 0x6d, 0x7c, 0xcf, + 0x46, 0x64, 0x8d, 0xfb, 0x73, 0x7a, 0x9c, 0xac, 0xd0, 0xba, 0x66, 0xc7, 0x52, 0x67, 0xdf, 0xec, + 0x66, 0x09, 0x6e, 0xfd, 0xba, 0x3f, 0x76, 0xa5, 0xf1, 0xa9, 0xdd, 0x84, 0x6a, 0x27, 0xf2, 0x1f, + 0xab, 0x4b, 0xe0, 0x34, 0x16, 0x22, 0x66, 0xa9, 0xd0, 0x7a, 0x66, 0xc7, 0x1a, 0xb4, 0xeb, 0xec, + 0x52, 0x47, 0xfe, 0xe0, 0xee, 0x8a, 0x25, 0x20, 0xb4, 0x7e, 0x7b, 0x83, 0x5a, 0xe1, 0xfe, 0xdb, + 0xed, 0x75, 0xf4, 0xb0, 0xd7, 0xd1, 0xd3, 0x5e, 0x47, 0xf7, 0x07, 0x1d, 0xed, 0x0e, 0x3a, 0xba, + 0xfe, 0xf9, 0xfe, 0x82, 0x22, 0x48, 0x41, 0xc4, 0xc2, 0x39, 0x1e, 0xb2, 0xdf, 0xab, 0x6e, 0xf0, + 0xf7, 0x6b, 0x00, 0x00, 0x00, 0xff, 0xff, 0x8b, 0xc3, 0x66, 0xb6, 0xe3, 0x02, 0x00, 0x00, } diff --git a/genesis/spec/template_account.go b/genesis/spec/template_account.go index b4ce1fa46..152a8097f 100644 --- a/genesis/spec/template_account.go +++ b/genesis/spec/template_account.go @@ -3,6 +3,7 @@ package spec import ( "fmt" + "github.com/hyperledger/burrow/acm/balance" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/genesis" "github.com/hyperledger/burrow/keys" @@ -24,11 +25,7 @@ func (ta TemplateAccount) Validator(keyClient keys.KeyClient, index int, generat } ta.NodeAddress = &address } - if ta.Power == nil { - gv.Amount = DefaultPower - } else { - gv.Amount = *ta.Power - } + gv.Amount = ta.Balances().GetPower(DefaultPower) if ta.Name == "" { gv.Name = accountNameFromIndex(index) } else { @@ -62,11 +59,7 @@ func (ta TemplateAccount) GenesisAccount(keyClient keys.KeyClient, index int) (* if err != nil { return nil, err } - if ta.Amount == nil { - ga.Amount = DefaultAmount - } else { - ga.Amount = *ta.Amount - } + ga.Amount = ta.Balances().GetNative(DefaultAmount) if ta.Name == "" { ga.Name = accountNameFromIndex(index) } else { @@ -111,3 +104,7 @@ func (ta TemplateAccount) RealisePubKeyAndAddress(keyClient keys.KeyClient) (pub } return } + +func (ta TemplateAccount) Balances() balance.Balances { + return ta.Amounts +} diff --git a/governance/governance.go b/governance/governance.go index b3e56f5b8..5ea2e1250 100644 --- a/governance/governance.go +++ b/governance/governance.go @@ -2,6 +2,14 @@ // validators, and network forks. package governance +import ( + "github.com/hyperledger/burrow/acm/balance" + "github.com/hyperledger/burrow/crypto" + "github.com/hyperledger/burrow/genesis/spec" + "github.com/hyperledger/burrow/permission" + "github.com/hyperledger/burrow/txs/payload" +) + // TODO: // - Set validator power // - Set account amount(s) @@ -15,3 +23,33 @@ package governance // - Network administered proxies (i.e. instead of keys have password authentication for identities - allow calls to originate as if from address without key?) // Subject to: // - Less than 1/3 validator power change per block + +// Creates a GovTx that alters the validator power of id to the power passed +func AlterPowerTx(inputAddress crypto.Address, id crypto.Addressable, power uint64) *payload.GovTx { + return AlterBalanceTx(inputAddress, id, balance.New().Power(power)) +} + +func AlterBalanceTx(inputAddress crypto.Address, id crypto.Addressable, bal balance.Balances) *payload.GovTx { + publicKey := id.PublicKey() + return UpdateAccountTx(inputAddress, &spec.TemplateAccount{ + PublicKey: &publicKey, + Amounts: bal, + }) +} + +func AlterPermissionsTx(inputAddress crypto.Address, id crypto.Addressable, perms permission.PermFlag) *payload.GovTx { + address := id.Address() + return UpdateAccountTx(inputAddress, &spec.TemplateAccount{ + Address: &address, + Permissions: permission.PermFlagToStringList(perms), + }) +} + +func UpdateAccountTx(inputAddress crypto.Address, updates ...*spec.TemplateAccount) *payload.GovTx { + return &payload.GovTx{ + Inputs: []*payload.TxInput{{ + Address: inputAddress, + }}, + AccountUpdates: updates, + } +} diff --git a/governance/governance_test.go b/governance/governance_test.go new file mode 100644 index 000000000..42d4d396f --- /dev/null +++ b/governance/governance_test.go @@ -0,0 +1,23 @@ +package governance + +import ( + "testing" + + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/execution/exec" + "github.com/hyperledger/burrow/txs" + "github.com/stretchr/testify/require" +) + +func TestSerialise(t *testing.T) { + priv := acm.GeneratePrivateAccountFromSecret("hhelo") + tx := AlterPowerTx(priv.Address(), priv, 3242323) + txEnv := txs.Enclose("OOh", tx) + + txe := exec.NewTxExecution(txEnv) + bs, err := txe.Marshal() + require.NoError(t, err) + txeOut := new(exec.TxExecution) + err = txeOut.Unmarshal(bs) + require.NoError(t, err) +} diff --git a/integration/core/kernel_test.go b/integration/core/kernel_test.go index 4459af6c6..3850fbc92 100644 --- a/integration/core/kernel_test.go +++ b/integration/core/kernel_test.go @@ -5,75 +5,75 @@ package core import ( "context" "fmt" - "os" "testing" "time" "github.com/hyperledger/burrow/config" - "github.com/hyperledger/burrow/consensus/tendermint/validator" + "github.com/hyperledger/burrow/consensus/tendermint" "github.com/hyperledger/burrow/core" "github.com/hyperledger/burrow/event" "github.com/hyperledger/burrow/execution/exec" "github.com/hyperledger/burrow/genesis" "github.com/hyperledger/burrow/integration" + "github.com/hyperledger/burrow/integration/rpctest" "github.com/hyperledger/burrow/keys" + "github.com/hyperledger/burrow/keys/mock" "github.com/hyperledger/burrow/logging" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - tmConfig "github.com/tendermint/tendermint/config" tmTypes "github.com/tendermint/tendermint/types" ) -const testDir = "./test_scratch/kernel_test" +var genesisDoc, privateAccounts, privateValidators = genesis.NewDeterministicGenesis(123).GenesisDoc(1, true, 1000, 1, true, 1000) func TestBootThenShutdown(t *testing.T) { - os.RemoveAll(testDir) - os.MkdirAll(testDir, 0777) - os.Chdir(testDir) - defer os.RemoveAll(testDir) - tmConf := tmConfig.DefaultConfig() + cleanup := integration.EnterTestDirectory() + defer cleanup() //logger, _, _ := lifecycle.NewStdErrLogger() logger := logging.NewNoopLogger() - genesisDoc, _, privateValidators := genesis.NewDeterministicGenesis(123).GenesisDoc(1, true, 1000, 1, true, 1000) - privValidator := validator.NewPrivValidatorMemory(privateValidators[0], privateValidators[0]) - assert.NoError(t, bootWaitBlocksShutdown(privValidator, integration.NewTestConfig(genesisDoc), tmConf, logger, nil)) + privValidator := tendermint.NewPrivValidatorMemory(privateValidators[0], privateValidators[0]) + assert.NoError(t, bootWaitBlocksShutdown(t, privValidator, integration.NewTestConfig(genesisDoc), logger, nil)) } func TestBootShutdownResume(t *testing.T) { - os.RemoveAll(testDir) - os.MkdirAll(testDir, 0777) - os.Chdir(testDir) - defer os.RemoveAll(testDir) - tmConf := tmConfig.DefaultConfig() - //logger, _, _ := lifecycle.NewStdErrLogger() + cleanup := integration.EnterTestDirectory() + defer cleanup() + //logger, _ := lifecycle.NewStdErrLogger() logger := logging.NewNoopLogger() - genesisDoc, _, privateValidators := genesis.NewDeterministicGenesis(123).GenesisDoc(1, true, 1000, 1, true, 1000) - privValidator := validator.NewPrivValidatorMemory(privateValidators[0], privateValidators[0]) + privValidator := tendermint.NewPrivValidatorMemory(privateValidators[0], privateValidators[0]) + testConfig := integration.NewTestConfig(genesisDoc) i := uint64(0) // asserts we get a consecutive run of blocks blockChecker := func(block *exec.BlockExecution) bool { - assert.Equal(t, i+1, block.Height) + if i == 0 { + // We send some synchronous transactions so catch up to latest block + i = block.Height - 1 + } + require.Equal(t, i+1, block.Height) i++ // stop every third block - return i%3 != 0 + if i%3 == 0 { + i = 0 + return false + } + return true } - testConfig := integration.NewTestConfig(genesisDoc) // First run - require.NoError(t, bootWaitBlocksShutdown(privValidator, testConfig, tmConf, logger, blockChecker)) + require.NoError(t, bootWaitBlocksShutdown(t, privValidator, testConfig, logger, blockChecker)) // Resume and check we pick up where we left off - require.NoError(t, bootWaitBlocksShutdown(privValidator, testConfig, tmConf, logger, blockChecker)) + require.NoError(t, bootWaitBlocksShutdown(t, privValidator, testConfig, logger, blockChecker)) // Resuming with mismatched genesis should fail genesisDoc.Salt = []byte("foo") - assert.Error(t, bootWaitBlocksShutdown(privValidator, testConfig, tmConf, logger, blockChecker)) + assert.Error(t, bootWaitBlocksShutdown(t, privValidator, testConfig, logger, blockChecker)) } -func bootWaitBlocksShutdown(privValidator tmTypes.PrivValidator, testConfig *config.BurrowConfig, - tmConf *tmConfig.Config, logger *logging.Logger, +func bootWaitBlocksShutdown(t testing.TB, privValidator tmTypes.PrivValidator, testConfig *config.BurrowConfig, + logger *logging.Logger, blockChecker func(block *exec.BlockExecution) (cont bool)) error { keyStore := keys.NewKeyStore(keys.DefaultKeysDir, false, logger) - keyClient := keys.NewLocalKeyClient(keyStore, logging.NewNoopLogger()) + keyClient := mock.NewKeyClient(privateAccounts...) kern, err := core.NewKernel(context.Background(), keyClient, privValidator, testConfig.GenesisDoc, testConfig.Tendermint.TendermintConfig(), @@ -89,6 +89,13 @@ func bootWaitBlocksShutdown(privValidator tmTypes.PrivValidator, testConfig *con return err } + inputAddress := privateAccounts[0].Address() + tcli := rpctest.NewTransactClient(t, testConfig.RPC.GRPC.ListenAddress) + // Generate a few transactions + for i := 0; i < 3; i++ { + rpctest.CreateContract(t, tcli, inputAddress) + } + subID := event.GenSubID() ch, err := kern.Emitter.Subscribe(context.Background(), subID, exec.QueryForBlockExecution(), 10) if err != nil { diff --git a/integration/governance/governance_test.go b/integration/governance/governance_test.go new file mode 100644 index 000000000..b188331c5 --- /dev/null +++ b/integration/governance/governance_test.go @@ -0,0 +1,172 @@ +// +build integration + +package governance + +import ( + "context" + "fmt" + "math/big" + "testing" + + "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/balance" + "github.com/hyperledger/burrow/acm/validator" + "github.com/hyperledger/burrow/crypto" + "github.com/hyperledger/burrow/execution/errors" + "github.com/hyperledger/burrow/execution/exec" + "github.com/hyperledger/burrow/governance" + "github.com/hyperledger/burrow/integration/rpctest" + "github.com/hyperledger/burrow/permission" + "github.com/hyperledger/burrow/rpc/rpcevents" + "github.com/hyperledger/burrow/rpc/rpcquery" + "github.com/hyperledger/burrow/rpc/rpctransact" + "github.com/hyperledger/burrow/txs/payload" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/tendermint/tendermint/rpc/core" +) + +func TestAlterValidators(t *testing.T) { + inputAddress := privateAccounts[0].Address() + grpcAddress := testConfigs[0].RPC.GRPC.ListenAddress + tcli := rpctest.NewTransactClient(t, grpcAddress) + qcli := rpctest.NewQueryClient(t, grpcAddress) + ecli := rpctest.NewExecutionEventsClient(t, grpcAddress) + + // Build a batch of validator alterations to make + vs := validator.NewTrimSet() + alterPower(vs, 3, 2131) + alterPower(vs, 2, 4561) + alterPower(vs, 5, 7831) + alterPower(vs, 8, 9931) + + vs.Iterate(func(id crypto.Addressable, power *big.Int) (stop bool) { + _, err := govSync(t, tcli, governance.AlterPowerTx(inputAddress, id, power.Uint64())) + require.NoError(t, err) + return + }) + + vsOut := getValidatorHistory(t, qcli) + // Include the genesis validator and compare the sets + alterPower(vs, 0, genesisDoc.Validators[0].Amount) + assertValidatorsEqual(t, vs, vsOut) + + // Remove validator from chain + txe, err := govSync(t, tcli, governance.AlterPowerTx(inputAddress, account(3), 0)) + // Mirror in our check set + alterPower(vs, 3, 0) + fmt.Println(txe.Events) + vsOut = getValidatorHistory(t, qcli) + assertValidatorsEqual(t, vs, vsOut) + + waitNBlocks(t, ecli, 3) + height := int64(kernels[4].Blockchain.LastBlockHeight()) + kernels[4].Node.ConfigureRPC() + tmVals, err := core.Validators(&height) + require.NoError(t, err) + vsOut = validator.NewTrimSet() + + for _, v := range tmVals.Validators { + publicKey, err := crypto.PublicKeyFromTendermintPubKey(v.PubKey) + require.NoError(t, err) + vsOut.AlterPower(publicKey, big.NewInt(v.VotingPower)) + } + assertValidatorsEqual(t, vs, vsOut) +} + +func TestNoRootPermission(t *testing.T) { + grpcAddress := testConfigs[0].RPC.GRPC.ListenAddress + tcli := rpctest.NewTransactClient(t, grpcAddress) + // Account does not have Root permission + inputAddress := privateAccounts[4].Address() + _, err := govSync(t, tcli, governance.AlterPowerTx(inputAddress, account(5), 3433)) + require.Error(t, err) + assert.Contains(t, err.Error(), errors.ErrorCodePermissionDenied.Error()) +} + +func TestAlterAmount(t *testing.T) { + inputAddress := privateAccounts[0].Address() + grpcAddress := testConfigs[0].RPC.GRPC.ListenAddress + tcli := rpctest.NewTransactClient(t, grpcAddress) + qcli := rpctest.NewQueryClient(t, grpcAddress) + var amount uint64 = 18889 + acc := account(5) + _, err := govSync(t, tcli, governance.AlterBalanceTx(inputAddress, acc, balance.New().Native(amount))) + require.NoError(t, err) + ca, err := qcli.GetAccount(context.Background(), &rpcquery.GetAccountParam{Address: acc.Address()}) + require.NoError(t, err) + assert.Equal(t, amount, ca.Balance) +} + +func TestAlterPermissions(t *testing.T) { + inputAddress := privateAccounts[0].Address() + grpcAddress := testConfigs[0].RPC.GRPC.ListenAddress + tcli := rpctest.NewTransactClient(t, grpcAddress) + qcli := rpctest.NewQueryClient(t, grpcAddress) + acc := account(5) + _, err := govSync(t, tcli, governance.AlterPermissionsTx(inputAddress, acc, permission.Send)) + require.NoError(t, err) + ca, err := qcli.GetAccount(context.Background(), &rpcquery.GetAccountParam{Address: acc.Address()}) + require.NoError(t, err) + assert.Equal(t, permission.AccountPermissions{ + Base: permission.BasePermissions{ + Perms: permission.Send, + SetBit: permission.Send, + }, + }, ca.Permissions) +} + +func TestCreateAccount(t *testing.T) { + inputAddress := privateAccounts[0].Address() + grpcAddress := testConfigs[0].RPC.GRPC.ListenAddress + tcli := rpctest.NewTransactClient(t, grpcAddress) + qcli := rpctest.NewQueryClient(t, grpcAddress) + var amount uint64 = 18889 + acc := acm.GeneratePrivateAccountFromSecret("we almost certainly don't exist") + _, err := govSync(t, tcli, governance.AlterBalanceTx(inputAddress, acc, balance.New().Native(amount))) + require.NoError(t, err) + ca, err := qcli.GetAccount(context.Background(), &rpcquery.GetAccountParam{Address: acc.Address()}) + require.NoError(t, err) + assert.Equal(t, amount, ca.Balance) +} + +func getValidatorHistory(t testing.TB, qcli rpcquery.QueryClient) *validator.Set { + history, err := qcli.GetValidatorSet(context.Background(), &rpcquery.GetValidatorSetParam{ + IncludeHistory: true, + }) + require.NoError(t, err) + + // Include the genesis validator and compare the sets + return validator.UnpersistSet(history.Set) +} + +func account(i int) *acm.PrivateAccount { + return rpctest.PrivateAccounts[i] +} + +func govSync(t testing.TB, cli rpctransact.TransactClient, tx *payload.GovTx) (*exec.TxExecution, error) { + return cli.BroadcastTxSync(context.Background(), &rpctransact.TxEnvelopeParam{ + Payload: tx.Any(), + }) +} + +func assertValidatorsEqual(t testing.TB, expected, actual *validator.Set) { + if !assert.True(t, expected.Equal(actual), "sets should be equal") { + fmt.Printf("Expected:\n%v\nActual:\n%v\n", expected, actual) + } +} + +func alterPower(vs *validator.Set, i int, power uint64) { + vs.AlterPower(account(i), new(big.Int).SetUint64(power)) +} + +func waitNBlocks(t testing.TB, ecli rpcevents.ExecutionEventsClient, n int) { + stream, err := ecli.GetBlocks(context.Background(), &rpcevents.BlocksRequest{ + BlockRange: rpcevents.NewBlockRange(rpcevents.LatestBound(), rpcevents.StreamBound()), + }) + defer stream.CloseSend() + for i := 0; i < n; i++ { + require.NoError(t, err) + _, err = stream.Recv() + } +} diff --git a/integration/governance/main_test.go b/integration/governance/main_test.go index 21b39516b..65e338e35 100644 --- a/integration/governance/main_test.go +++ b/integration/governance/main_test.go @@ -21,28 +21,59 @@ import ( "context" "os" "testing" + "time" + "github.com/hyperledger/burrow/config" "github.com/hyperledger/burrow/core" "github.com/hyperledger/burrow/integration" - "github.com/hyperledger/burrow/integration/rpctest" + "github.com/hyperledger/burrow/logging/logconfig" + "github.com/hyperledger/burrow/permission" ) +var privateAccounts = integration.MakePrivateAccounts(10) // make keys +var genesisDoc = integration.TestGenesisDoc(privateAccounts) var _ = integration.ClaimPorts() -var inputAddress = rpctest.PrivateAccounts[0].Address() -var gene -var testConfig = integration.NewTestConfig(rpctest.GenesisDoc) -var kern *core.Kernel +var testConfigs []*config.BurrowConfig +var kernels []*core.Kernel // Needs to be in a _test.go file to be picked up func TestMain(m *testing.M) { - kern = integration.TestKernel(rpctest.PrivateAccounts, testConfig) - err := kern.Boot() + cleanup := integration.EnterTestDirectory() + defer cleanup() + testConfigs = make([]*config.BurrowConfig, len(privateAccounts)) + kernels = make([]*core.Kernel, len(privateAccounts)) + genesisDoc.Accounts[4].Permissions = permission.NewAccountPermissions(permission.Send | permission.Call) + for i, acc := range privateAccounts { + testConfig := integration.NewTestConfig(genesisDoc) + testConfigs[i] = testConfig + kernels[i] = integration.TestKernel(acc, privateAccounts, testConfigs[i], + logconfig.New().Root(func(sink *logconfig.SinkConfig) *logconfig.SinkConfig { + return sink.SetTransform(logconfig.FilterTransform(logconfig.IncludeWhenAllMatch, + "total_validator")).SetOutput(logconfig.StdoutOutput()) + })) + err := kernels[i].Boot() + if err != nil { + panic(err) + } + // Sometimes better to not shutdown as logging errors on shutdown may obscure real issue + defer func() { + kernels[i].Shutdown(context.Background()) + }() + } + time.Sleep(1 * time.Second) + for i := 0; i < len(kernels); i++ { + for j := i; j < len(kernels); j++ { + if i != j { + connectKernels(kernels[i], kernels[j]) + } + } + } + os.Exit(m.Run()) +} + +func connectKernels(k1, k2 *core.Kernel) { + err := k1.Node.Switch().DialPeerWithAddress(k2.Node.NodeInfo().NetAddress(), false) if err != nil { panic(err) } - // Sometimes better to not shutdown as logging errors on shutdown may obscure real issue - defer func() { - kern.Shutdown(context.Background()) - }() - os.Exit(m.Run()) } diff --git a/integration/governance/validators_test.go b/integration/governance/validators_test.go deleted file mode 100644 index 07b8008d0..000000000 --- a/integration/governance/validators_test.go +++ /dev/null @@ -1,7 +0,0 @@ -package governance - -import "testing" - -func TestName(t *testing.T) { - -} diff --git a/integration/integration.go b/integration/integration.go index 280f83207..ae3cf0ba6 100644 --- a/integration/integration.go +++ b/integration/integration.go @@ -25,27 +25,25 @@ import ( "time" "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/validator" "github.com/hyperledger/burrow/config" - "github.com/hyperledger/burrow/consensus/tendermint/validator" + "github.com/hyperledger/burrow/consensus/tendermint" "github.com/hyperledger/burrow/core" "github.com/hyperledger/burrow/execution/evm/sha3" "github.com/hyperledger/burrow/genesis" "github.com/hyperledger/burrow/keys/mock" "github.com/hyperledger/burrow/logging" - lConfig "github.com/hyperledger/burrow/logging/config" "github.com/hyperledger/burrow/logging/lifecycle" - "github.com/hyperledger/burrow/logging/structure" + lConfig "github.com/hyperledger/burrow/logging/logconfig" "github.com/hyperledger/burrow/permission" ) const ( - chainName = "Integration_Test_Chain" + ChainName = "Integration_Test_Chain" testDir = "./test_scratch/tm_test" ) // Enable logger output during tests -//var debugLogging = true -var debugLogging = false // Starting point for assigning range of ports for tests // Start at unprivileged port (hoping for the best) @@ -58,41 +56,25 @@ const startingPortBuckets = 1000 // Mutable port to assign to next claimant var port = uint32(startingPort) -// We use this to wrap tests -func TestKernel(privateAccounts []*acm.PrivateAccount, testConfig *config.BurrowConfig) *core.Kernel { - fmt.Println("Running with integration TestWrapper (core/integration/integration.go)...") - - os.RemoveAll(testDir) - os.MkdirAll(testDir, 0777) - os.Chdir(testDir) - defer os.RemoveAll(testDir) +var node uint64 = 0 - os.MkdirAll("config", 0777) +// We use this to wrap tests +func TestKernel(validatorAccount *acm.PrivateAccount, keysAccounts []*acm.PrivateAccount, + testConfig *config.BurrowConfig, loggingConfig *lConfig.LoggingConfig) *core.Kernel { + fmt.Println("Creating integration test Kernel...") logger := logging.NewNoopLogger() - if debugLogging { + if loggingConfig != nil { var err error // Change config as needed - logger, err = lifecycle.NewLoggerFromLoggingConfig(&lConfig.LoggingConfig{ - ExcludeTrace: false, - RootSink: lConfig.Sink(). - SetTransform(lConfig.FilterTransform(lConfig.IncludeWhenAnyMatches, - structure.ComponentKey, "Tendermint", - structure.ScopeKey, "executor.Execute\\(tx txs.Tx\\)", - )). - //AddSinks(config.Sink().SetTransform(config.FilterTransform(config.ExcludeWhenAnyMatches, "run_call", "false")). - AddSinks(lConfig.Sink().SetTransform(lConfig.PruneTransform("log_channel", "trace", "scope", "returns", "run_id", "args")). - AddSinks(lConfig.Sink().SetTransform(lConfig.SortTransform("tx_hash", "time", "message", "method")). - SetOutput(lConfig.StdoutOutput()))), - }) + logger, err = lifecycle.NewLoggerFromLoggingConfig(loggingConfig) if err != nil { panic(err) } } - validatorAccount := privateAccounts[0] - privValidator := validator.NewPrivValidatorMemory(validatorAccount, validatorAccount) - keyClient := mock.NewKeyClient(privateAccounts...) + privValidator := tendermint.NewPrivValidatorMemory(validatorAccount, validatorAccount) + keyClient := mock.NewKeyClient(keysAccounts...) kernel, err := core.NewKernel(context.Background(), keyClient, privValidator, testConfig.GenesisDoc, testConfig.Tendermint.TendermintConfig(), @@ -106,6 +88,14 @@ func TestKernel(privateAccounts []*acm.PrivateAccount, testConfig *config.Burrow return kernel } +func EnterTestDirectory() (cleanup func()) { + os.RemoveAll(testDir) + os.MkdirAll(testDir, 0777) + os.Chdir(testDir) + os.MkdirAll("config", 0777) + return func() { os.RemoveAll(testDir) } +} + func TestGenesisDoc(addressables []*acm.PrivateAccount) *genesis.GenesisDoc { accounts := make(map[string]acm.Account, len(addressables)) for i, pa := range addressables { @@ -118,9 +108,9 @@ func TestGenesisDoc(addressables []*acm.PrivateAccount) *genesis.GenesisDoc { if err != nil { panic("could not parse test genesis time") } - return genesis.MakeGenesisDocFromAccounts(chainName, nil, genesisTime, accounts, - map[string]acm.Validator{ - "genesis_validator": acm.AsValidator(accounts["user_0"]), + return genesis.MakeGenesisDocFromAccounts(ChainName, nil, genesisTime, accounts, + map[string]validator.Validator{ + "genesis_validator": validator.FromAccount(accounts["user_0"], 1<<16), }) } @@ -152,17 +142,26 @@ func GetPort() uint16 { return uint16(atomic.AddUint32(&port, 1)) } +// Gets an name based on an incrementing counter for running multiple nodes +func GetName() string { + nodeNumber := atomic.AddUint64(&node, 1) + return fmt.Sprintf("node_%03d", nodeNumber) +} + func GetLocalAddress() string { - return fmt.Sprintf("localhost:%v", GetPort()) + return fmt.Sprintf("127.0.0.1:%v", GetPort()) } func GetTCPLocalAddress() string { - return fmt.Sprintf("tcp://localhost:%v", GetPort()) + return fmt.Sprintf("tcp://127.0.0.1:%v", GetPort()) } func NewTestConfig(genesisDoc *genesis.GenesisDoc) *config.BurrowConfig { + name := GetName() cnf := config.DefaultBurrowConfig() cnf.GenesisDoc = genesisDoc + cnf.Tendermint.Moniker = name + cnf.Tendermint.TendermintRoot = fmt.Sprintf(".burrow_%s", name) cnf.Tendermint.ListenAddress = GetTCPLocalAddress() cnf.RPC.GRPC.ListenAddress = GetLocalAddress() cnf.RPC.Metrics.ListenAddress = GetTCPLocalAddress() diff --git a/integration/integration_test.go b/integration/integration_test.go new file mode 100644 index 000000000..485a5bd91 --- /dev/null +++ b/integration/integration_test.go @@ -0,0 +1,28 @@ +// Copyright 2017 Monax Industries Limited +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package integration + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestNamesAndPorts(t *testing.T) { + assert.Equal(t, "node_001", GetName()) + assert.Equal(t, "node_002", GetName()) + assert.Equal(t, startingPort+1, GetPort()) + assert.Equal(t, startingPort+2, GetPort()) +} diff --git a/integration/rpcevents/main_test.go b/integration/rpcevents/main_test.go index 1a842bd95..1acbd46f3 100644 --- a/integration/rpcevents/main_test.go +++ b/integration/rpcevents/main_test.go @@ -34,7 +34,9 @@ var kern *core.Kernel // Needs to be in a _test.go file to be picked up func TestMain(m *testing.M) { - kern = integration.TestKernel(rpctest.PrivateAccounts, testConfig) + cleanup := integration.EnterTestDirectory() + defer cleanup() + kern = integration.TestKernel(rpctest.PrivateAccounts[0], rpctest.PrivateAccounts, testConfig, nil) err := kern.Boot() if err != nil { panic(err) diff --git a/integration/rpcquery/main_test.go b/integration/rpcquery/main_test.go index 9f13b06be..d6e9694ea 100644 --- a/integration/rpcquery/main_test.go +++ b/integration/rpcquery/main_test.go @@ -33,7 +33,9 @@ var kern *core.Kernel // Needs to be in a _test.go file to be picked up func TestMain(m *testing.M) { - kern = integration.TestKernel(rpctest.PrivateAccounts, testConfig) + cleanup := integration.EnterTestDirectory() + defer cleanup() + kern = integration.TestKernel(rpctest.PrivateAccounts[0], rpctest.PrivateAccounts, testConfig, nil) err := kern.Boot() if err != nil { panic(err) diff --git a/integration/rpctransact/main_test.go b/integration/rpctransact/main_test.go index 1f773a001..5b0d3d05a 100644 --- a/integration/rpctransact/main_test.go +++ b/integration/rpctransact/main_test.go @@ -33,7 +33,9 @@ var kern *core.Kernel // Needs to be in a _test.go file to be picked up func TestMain(m *testing.M) { - kern = integration.TestKernel(rpctest.PrivateAccounts, testConfig) + cleanup := integration.EnterTestDirectory() + defer cleanup() + kern = integration.TestKernel(rpctest.PrivateAccounts[0], rpctest.PrivateAccounts, testConfig, nil) err := kern.Boot() if err != nil { panic(err) diff --git a/integration/rpctransact/transact_server_test.go b/integration/rpctransact/transact_server_test.go index 096f80b25..1132faf6a 100644 --- a/integration/rpctransact/transact_server_test.go +++ b/integration/rpctransact/transact_server_test.go @@ -88,7 +88,7 @@ func TestBroadcastTxLocallySigned(t *testing.T) { func TestFormulateTx(t *testing.T) { cli := rpctest.NewTransactClient(t, testConfig.RPC.GRPC.ListenAddress) - txEnv, err := cli.FormulateTx(context.Background(), &rpctransact.PayloadParam{ + txEnv, err := cli.FormulateTx(context.Background(), &payload.Any{ CallTx: &payload.CallTx{ Input: &payload.TxInput{ Address: inputAddress, diff --git a/integration/tm/main_test.go b/integration/tm/main_test.go index 627fa6d28..44e733ab8 100644 --- a/integration/tm/main_test.go +++ b/integration/tm/main_test.go @@ -41,7 +41,9 @@ var clients = map[string]tmClient.RPCClient{ // Needs to be in a _test.go file to be picked up func TestMain(m *testing.M) { - kern = integration.TestKernel(rpctest.PrivateAccounts, testConfig) + cleanup := integration.EnterTestDirectory() + defer cleanup() + kern = integration.TestKernel(rpctest.PrivateAccounts[0], rpctest.PrivateAccounts, testConfig, nil) err := kern.Boot() if err != nil { panic(err) diff --git a/logging/config/presets/instructions_test.go b/logging/config/presets/instructions_test.go deleted file mode 100644 index c8398cc5c..000000000 --- a/logging/config/presets/instructions_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package presets - -import ( - "testing" - - "github.com/hyperledger/burrow/logging/config" - "github.com/hyperledger/burrow/logging/loggers" - "github.com/hyperledger/burrow/logging/structure" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestBuildSinkConfig(t *testing.T) { - builtSink, err := BuildSinkConfig(IncludeAny, Info, Stdout, Terminal, Down, Down, Info, Stdout, Up, Info, Stderr) - require.NoError(t, err) - expectedSink := config.Sink(). - SetTransform(config.FilterTransform(config.IncludeWhenAnyMatches, - structure.ChannelKey, structure.InfoChannelName)).SetOutput(config.StdoutOutput().SetFormat(loggers.TerminalFormat)).AddSinks( - config.Sink().SetTransform(config.FilterTransform(config.NoFilterMode, - structure.ChannelKey, structure.InfoChannelName)).SetOutput(config.StderrOutput()).AddSinks( - config.Sink().SetTransform(config.FilterTransform(config.NoFilterMode, - structure.ChannelKey, structure.InfoChannelName)).SetOutput(config.StdoutOutput()))) - - //fmt.Println(config.JSONString(expectedSink), "\n", config.JSONString(builtSink)) - assert.Equal(t, config.JSONString(expectedSink), config.JSONString(builtSink)) -} - -func TestMinimalPreset(t *testing.T) { - builtSink, err := BuildSinkConfig(Minimal, Stderr) - require.NoError(t, err) - expectedSink := config.Sink(). - AddSinks(config.Sink().SetTransform(config.PruneTransform(structure.TraceKey, structure.RunId)). - AddSinks(config.Sink().SetTransform(config.FilterTransform(config.IncludeWhenAllMatch, - structure.ChannelKey, structure.InfoChannelName)). - AddSinks(config.Sink().SetTransform(config.FilterTransform(config.ExcludeWhenAnyMatches, - structure.ComponentKey, "Tendermint", - "module", "p2p", - "module", "mempool")).SetOutput(config.StderrOutput())))) - //fmt.Println(config.TOMLString(expectedSink), "\n", config.TOMLString(builtSink)) - assert.Equal(t, config.TOMLString(expectedSink), config.TOMLString(builtSink)) -} - -func TestFileOutput(t *testing.T) { - path := "foo.log" - builtSink, err := BuildSinkConfig(Down, File, path, JSON) - require.NoError(t, err) - expectedSink := config.Sink(). - AddSinks(config.Sink().SetOutput(config.FileOutput(path).SetFormat(loggers.JSONFormat))) - //fmt.Println(config.TOMLString(expectedSink), "\n", config.TOMLString(builtSink)) - assert.Equal(t, config.TOMLString(expectedSink), config.TOMLString(builtSink)) -} diff --git a/logging/config/sort.go b/logging/config/sort.go deleted file mode 100644 index d912156be..000000000 --- a/logging/config/sort.go +++ /dev/null @@ -1 +0,0 @@ -package config diff --git a/logging/lifecycle/lifecycle.go b/logging/lifecycle/lifecycle.go index f17622e69..911525bfe 100644 --- a/logging/lifecycle/lifecycle.go +++ b/logging/lifecycle/lifecycle.go @@ -21,7 +21,7 @@ import ( "time" "github.com/hyperledger/burrow/logging/adapters/stdlib" - "github.com/hyperledger/burrow/logging/config" + "github.com/hyperledger/burrow/logging/logconfig" "github.com/hyperledger/burrow/logging/loggers" "github.com/hyperledger/burrow/logging/structure" @@ -37,7 +37,7 @@ import ( // to set up their root logger and capture any other logging output. // Obtain a logger from a LoggingConfig -func NewLoggerFromLoggingConfig(loggingConfig *config.LoggingConfig) (*logging.Logger, error) { +func NewLoggerFromLoggingConfig(loggingConfig *logconfig.LoggingConfig) (*logging.Logger, error) { if loggingConfig == nil { return NewStdErrLogger() } else { @@ -61,7 +61,7 @@ func NewLoggerFromLoggingConfig(loggingConfig *config.LoggingConfig) (*logging.L // Hot swap logging config by replacing output loggers of passed InfoTraceLogger // with those built from loggingConfig -func SwapOutputLoggersFromLoggingConfig(logger *logging.Logger, loggingConfig *config.LoggingConfig) (error, channels.Channel) { +func SwapOutputLoggersFromLoggingConfig(logger *logging.Logger, loggingConfig *logconfig.LoggingConfig) (error, channels.Channel) { outputLogger, errCh, err := loggerFromLoggingConfig(loggingConfig) if err != nil { return err, channels.NewDeadChannel() @@ -99,7 +99,7 @@ func CaptureStdlibLogOutput(infoTraceLogger *logging.Logger) { } // Helpers -func loggerFromLoggingConfig(loggingConfig *config.LoggingConfig) (kitlog.Logger, channels.Channel, error) { +func loggerFromLoggingConfig(loggingConfig *logconfig.LoggingConfig) (kitlog.Logger, channels.Channel, error) { outputLogger, _, err := loggingConfig.RootSink.BuildLogger() if err != nil { return nil, nil, err diff --git a/logging/config/config.go b/logging/logconfig/config.go similarity index 84% rename from logging/config/config.go rename to logging/logconfig/config.go index 8616aeb7a..d5ffd0e89 100644 --- a/logging/config/config.go +++ b/logging/logconfig/config.go @@ -1,4 +1,4 @@ -package config +package logconfig import ( "bytes" @@ -39,6 +39,20 @@ func DefaultClientLoggingConfig() *LoggingConfig { } } +func New() *LoggingConfig { + return &LoggingConfig{} +} + +func (lc *LoggingConfig) NoTrace() *LoggingConfig { + lc.ExcludeTrace = true + return lc +} + +func (lc *LoggingConfig) Root(configure func(sink *SinkConfig) *SinkConfig) *LoggingConfig { + lc.RootSink = configure(Sink()) + return lc +} + // Returns the TOML for a top-level logging config wrapped with [logging] func (lc *LoggingConfig) RootTOMLString() string { return TOMLString(LoggingConfigWrapper{lc}) diff --git a/logging/config/config_test.go b/logging/logconfig/config_test.go similarity index 97% rename from logging/config/config_test.go rename to logging/logconfig/config_test.go index 089710aa7..af0c3a5e7 100644 --- a/logging/config/config_test.go +++ b/logging/logconfig/config_test.go @@ -1,4 +1,4 @@ -package config +package logconfig import ( "testing" diff --git a/logging/config/filter.go b/logging/logconfig/filter.go similarity index 99% rename from logging/config/filter.go rename to logging/logconfig/filter.go index d4d4aede8..a048ebc8c 100644 --- a/logging/config/filter.go +++ b/logging/logconfig/filter.go @@ -1,4 +1,4 @@ -package config +package logconfig import ( "fmt" diff --git a/logging/config/filter_test.go b/logging/logconfig/filter_test.go similarity index 99% rename from logging/config/filter_test.go rename to logging/logconfig/filter_test.go index 9602fa71e..967d0c0d7 100644 --- a/logging/config/filter_test.go +++ b/logging/logconfig/filter_test.go @@ -1,4 +1,4 @@ -package config +package logconfig import ( "testing" diff --git a/logging/config/presets/instructions.go b/logging/logconfig/presets/instructions.go similarity index 66% rename from logging/config/presets/instructions.go rename to logging/logconfig/presets/instructions.go index 91065d2fa..6bc4c4f7b 100644 --- a/logging/config/presets/instructions.go +++ b/logging/logconfig/presets/instructions.go @@ -3,7 +3,7 @@ package presets import ( "fmt" - "github.com/hyperledger/burrow/logging/config" + "github.com/hyperledger/burrow/logging/logconfig" "github.com/hyperledger/burrow/logging/loggers" "github.com/hyperledger/burrow/logging/structure" ) @@ -20,7 +20,7 @@ type Instruction struct { // by mutating the sink at the top of the stack and may move the cursor or by pushing child sinks // to the stack. The builder may also return a modified ops slice whereby it may insert Instruction calls // acting as a macro or consume ops as arguments. - builder func(stack []*config.SinkConfig, args []string) ([]*config.SinkConfig, error) + builder func(stack []*logconfig.SinkConfig, args []string) ([]*logconfig.SinkConfig, error) } func (i Instruction) Name() string { @@ -48,26 +48,26 @@ var instructions = []Instruction{ { name: Up, desc: "Ascend the sink tree by travelling up the stack to the previous sink recorded on the stack", - builder: func(stack []*config.SinkConfig, args []string) ([]*config.SinkConfig, error) { + builder: func(stack []*logconfig.SinkConfig, args []string) ([]*logconfig.SinkConfig, error) { return pop(stack), nil }, }, { name: Down, desc: "Descend the sink tree by inserting a sink as a child to the current sink and adding it to the stack", - builder: func(stack []*config.SinkConfig, args []string) ([]*config.SinkConfig, error) { - return push(stack, config.Sink()), nil + builder: func(stack []*logconfig.SinkConfig, args []string) ([]*logconfig.SinkConfig, error) { + return push(stack, logconfig.Sink()), nil }, }, { name: Minimal, desc: "A generally less chatty log output, follow with output options", - builder: func(stack []*config.SinkConfig, args []string) ([]*config.SinkConfig, error) { + builder: func(stack []*logconfig.SinkConfig, args []string) ([]*logconfig.SinkConfig, error) { return push(stack, - config.Sink().SetTransform(config.PruneTransform(structure.TraceKey, structure.RunId)), - config.Sink().SetTransform(config.FilterTransform(config.IncludeWhenAllMatch, + logconfig.Sink().SetTransform(logconfig.PruneTransform(structure.TraceKey, structure.RunId)), + logconfig.Sink().SetTransform(logconfig.FilterTransform(logconfig.IncludeWhenAllMatch, structure.ChannelKey, structure.InfoChannelName)), - config.Sink().SetTransform(config.FilterTransform(config.ExcludeWhenAnyMatches, + logconfig.Sink().SetTransform(logconfig.FilterTransform(logconfig.ExcludeWhenAnyMatches, structure.ComponentKey, "Tendermint", "module", "p2p", "module", "mempool"))), nil @@ -76,17 +76,17 @@ var instructions = []Instruction{ { name: IncludeAny, desc: "Establish an 'include when any predicate matches' filter transform at this this sink", - builder: func(stack []*config.SinkConfig, args []string) ([]*config.SinkConfig, error) { + builder: func(stack []*logconfig.SinkConfig, args []string) ([]*logconfig.SinkConfig, error) { sink := peek(stack) ensureFilter(sink) - sink.Transform.FilterConfig.FilterMode = config.IncludeWhenAnyMatches + sink.Transform.FilterConfig.FilterMode = logconfig.IncludeWhenAnyMatches return stack, nil }, }, { name: Info, desc: "Add a filter predicate to match the Info logging channel", - builder: func(stack []*config.SinkConfig, args []string) ([]*config.SinkConfig, error) { + builder: func(stack []*logconfig.SinkConfig, args []string) ([]*logconfig.SinkConfig, error) { sink := peek(stack) ensureFilter(sink) sink.Transform.FilterConfig.AddPredicate(structure.ChannelKey, structure.InfoChannelName) @@ -96,27 +96,27 @@ var instructions = []Instruction{ { name: Stdout, desc: "Use Stdout output for this sink", - builder: func(stack []*config.SinkConfig, args []string) ([]*config.SinkConfig, error) { + builder: func(stack []*logconfig.SinkConfig, args []string) ([]*logconfig.SinkConfig, error) { sink := peek(stack) ensureOutput(sink) - sink.Output.OutputType = config.Stdout + sink.Output.OutputType = logconfig.Stdout return stack, nil }, }, { name: Stderr, desc: "Use Stderr output for this sink", - builder: func(stack []*config.SinkConfig, args []string) ([]*config.SinkConfig, error) { + builder: func(stack []*logconfig.SinkConfig, args []string) ([]*logconfig.SinkConfig, error) { sink := peek(stack) ensureOutput(sink) - sink.Output.OutputType = config.Stderr + sink.Output.OutputType = logconfig.Stderr return stack, nil }, }, { name: Terminal, desc: "Use the the terminal output format for this sink", - builder: func(stack []*config.SinkConfig, args []string) ([]*config.SinkConfig, error) { + builder: func(stack []*logconfig.SinkConfig, args []string) ([]*logconfig.SinkConfig, error) { sink := peek(stack) ensureOutput(sink) sink.Output.Format = loggers.TerminalFormat @@ -126,7 +126,7 @@ var instructions = []Instruction{ { name: JSON, desc: "Use the the terminal output format for this sink", - builder: func(stack []*config.SinkConfig, args []string) ([]*config.SinkConfig, error) { + builder: func(stack []*logconfig.SinkConfig, args []string) ([]*logconfig.SinkConfig, error) { sink := peek(stack) ensureOutput(sink) sink.Output.Format = loggers.JSONFormat @@ -137,11 +137,11 @@ var instructions = []Instruction{ name: File, desc: "Use the the terminal output format for this sink", nargs: 1, - builder: func(stack []*config.SinkConfig, args []string) ([]*config.SinkConfig, error) { + builder: func(stack []*logconfig.SinkConfig, args []string) ([]*logconfig.SinkConfig, error) { sink := peek(stack) ensureOutput(sink) - sink.Output.OutputType = config.File - sink.Output.FileConfig = &config.FileConfig{ + sink.Output.OutputType = logconfig.File + sink.Output.FileConfig = &logconfig.FileConfig{ Path: args[0], } return stack, nil @@ -172,8 +172,8 @@ func Describe(name string) string { return preset.desc } -func BuildSinkConfig(ops ...string) (*config.SinkConfig, error) { - stack := []*config.SinkConfig{config.Sink()} +func BuildSinkConfig(ops ...string) (*logconfig.SinkConfig, error) { + stack := []*logconfig.SinkConfig{logconfig.Sink()} var err error pos := 0 for len(ops) > 0 { @@ -199,24 +199,24 @@ func BuildSinkConfig(ops ...string) (*config.SinkConfig, error) { return stack[0], nil } -func ensureFilter(sinkConfig *config.SinkConfig) { +func ensureFilter(sinkConfig *logconfig.SinkConfig) { if sinkConfig.Transform == nil { - sinkConfig.Transform = &config.TransformConfig{} + sinkConfig.Transform = &logconfig.TransformConfig{} } if sinkConfig.Transform.FilterConfig == nil { - sinkConfig.Transform.FilterConfig = &config.FilterConfig{} + sinkConfig.Transform.FilterConfig = &logconfig.FilterConfig{} } - sinkConfig.Transform.TransformType = config.Filter + sinkConfig.Transform.TransformType = logconfig.Filter } -func ensureOutput(sinkConfig *config.SinkConfig) { +func ensureOutput(sinkConfig *logconfig.SinkConfig) { if sinkConfig.Output == nil { - sinkConfig.Output = &config.OutputConfig{} + sinkConfig.Output = &logconfig.OutputConfig{} } } // Push a path sequence of sinks onto the stack -func push(stack []*config.SinkConfig, sinkConfigs ...*config.SinkConfig) []*config.SinkConfig { +func push(stack []*logconfig.SinkConfig, sinkConfigs ...*logconfig.SinkConfig) []*logconfig.SinkConfig { for _, sinkConfig := range sinkConfigs { peek(stack).AddSinks(sinkConfig) stack = append(stack, sinkConfig) @@ -224,10 +224,10 @@ func push(stack []*config.SinkConfig, sinkConfigs ...*config.SinkConfig) []*conf return stack } -func pop(stack []*config.SinkConfig) []*config.SinkConfig { +func pop(stack []*logconfig.SinkConfig) []*logconfig.SinkConfig { return stack[:len(stack)-1] } -func peek(stack []*config.SinkConfig) *config.SinkConfig { +func peek(stack []*logconfig.SinkConfig) *logconfig.SinkConfig { return stack[len(stack)-1] } diff --git a/logging/logconfig/presets/instructions_test.go b/logging/logconfig/presets/instructions_test.go new file mode 100644 index 000000000..7cd1adb12 --- /dev/null +++ b/logging/logconfig/presets/instructions_test.go @@ -0,0 +1,51 @@ +package presets + +import ( + "testing" + + "github.com/hyperledger/burrow/logging/logconfig" + "github.com/hyperledger/burrow/logging/loggers" + "github.com/hyperledger/burrow/logging/structure" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestBuildSinkConfig(t *testing.T) { + builtSink, err := BuildSinkConfig(IncludeAny, Info, Stdout, Terminal, Down, Down, Info, Stdout, Up, Info, Stderr) + require.NoError(t, err) + expectedSink := logconfig.Sink(). + SetTransform(logconfig.FilterTransform(logconfig.IncludeWhenAnyMatches, + structure.ChannelKey, structure.InfoChannelName)).SetOutput(logconfig.StdoutOutput().SetFormat(loggers.TerminalFormat)).AddSinks( + logconfig.Sink().SetTransform(logconfig.FilterTransform(logconfig.NoFilterMode, + structure.ChannelKey, structure.InfoChannelName)).SetOutput(logconfig.StderrOutput()).AddSinks( + logconfig.Sink().SetTransform(logconfig.FilterTransform(logconfig.NoFilterMode, + structure.ChannelKey, structure.InfoChannelName)).SetOutput(logconfig.StdoutOutput()))) + + //fmt.Println(config.JSONString(expectedSink), "\n", config.JSONString(builtSink)) + assert.Equal(t, logconfig.JSONString(expectedSink), logconfig.JSONString(builtSink)) +} + +func TestMinimalPreset(t *testing.T) { + builtSink, err := BuildSinkConfig(Minimal, Stderr) + require.NoError(t, err) + expectedSink := logconfig.Sink(). + AddSinks(logconfig.Sink().SetTransform(logconfig.PruneTransform(structure.TraceKey, structure.RunId)). + AddSinks(logconfig.Sink().SetTransform(logconfig.FilterTransform(logconfig.IncludeWhenAllMatch, + structure.ChannelKey, structure.InfoChannelName)). + AddSinks(logconfig.Sink().SetTransform(logconfig.FilterTransform(logconfig.ExcludeWhenAnyMatches, + structure.ComponentKey, "Tendermint", + "module", "p2p", + "module", "mempool")).SetOutput(logconfig.StderrOutput())))) + //fmt.Println(config.TOMLString(expectedSink), "\n", config.TOMLString(builtSink)) + assert.Equal(t, logconfig.TOMLString(expectedSink), logconfig.TOMLString(builtSink)) +} + +func TestFileOutput(t *testing.T) { + path := "foo.log" + builtSink, err := BuildSinkConfig(Down, File, path, JSON) + require.NoError(t, err) + expectedSink := logconfig.Sink(). + AddSinks(logconfig.Sink().SetOutput(logconfig.FileOutput(path).SetFormat(loggers.JSONFormat))) + //fmt.Println(config.TOMLString(expectedSink), "\n", config.TOMLString(builtSink)) + assert.Equal(t, logconfig.TOMLString(expectedSink), logconfig.TOMLString(builtSink)) +} diff --git a/logging/config/sinks.go b/logging/logconfig/sinks.go similarity index 97% rename from logging/config/sinks.go rename to logging/logconfig/sinks.go index aa30a69e1..e323fdabd 100644 --- a/logging/config/sinks.go +++ b/logging/logconfig/sinks.go @@ -1,4 +1,4 @@ -package config +package logconfig import ( "fmt" @@ -236,14 +236,17 @@ func PruneTransform(keys ...string) *TransformConfig { } } -func FilterTransform(fmode filterMode, keyvalueRegexes ...string) *TransformConfig { - length := len(keyvalueRegexes) / 2 +func FilterTransform(fmode filterMode, keyValueRegexes ...string) *TransformConfig { + if len(keyValueRegexes)%2 == 1 { + keyValueRegexes = append(keyValueRegexes, "") + } + length := len(keyValueRegexes) / 2 predicates := make([]*KeyValuePredicateConfig, length) for i := 0; i < length; i++ { kv := i * 2 predicates[i] = &KeyValuePredicateConfig{ - KeyRegex: keyvalueRegexes[kv], - ValueRegex: keyvalueRegexes[kv+1], + KeyRegex: keyValueRegexes[kv], + ValueRegex: keyValueRegexes[kv+1], } } return &TransformConfig{ diff --git a/logging/config/sinks_test.go b/logging/logconfig/sinks_test.go similarity index 99% rename from logging/config/sinks_test.go rename to logging/logconfig/sinks_test.go index ba722a9d0..8eba26284 100644 --- a/logging/config/sinks_test.go +++ b/logging/logconfig/sinks_test.go @@ -1,4 +1,4 @@ -package config +package logconfig import ( "encoding/json" diff --git a/logging/logconfig/sort.go b/logging/logconfig/sort.go new file mode 100644 index 000000000..6b6aa6741 --- /dev/null +++ b/logging/logconfig/sort.go @@ -0,0 +1 @@ +package logconfig diff --git a/logging/loggers/burrow_format_logger.go b/logging/loggers/burrow_format_logger.go index f32d0933d..1a8070bf3 100644 --- a/logging/loggers/burrow_format_logger.go +++ b/logging/loggers/burrow_format_logger.go @@ -20,6 +20,7 @@ import ( kitlog "github.com/go-kit/kit/log" "github.com/hyperledger/burrow/logging/structure" + "github.com/tmthrgd/go-hex" ) // Logger that implements some formatting conventions for burrow and burrow-client @@ -48,7 +49,7 @@ func (bfl *burrowFormatLogger) Log(keyvals ...interface{}) error { case fmt.Stringer: value = v.String() case []byte: - value = fmt.Sprintf("%X", v) + value = hex.EncodeUpperToString(v) case time.Time: value = v.Format(time.RFC3339Nano) } diff --git a/permission/account_permissions.go b/permission/account_permissions.go index 6de0a4431..fdc304273 100644 --- a/permission/account_permissions.go +++ b/permission/account_permissions.go @@ -2,6 +2,19 @@ package permission import "github.com/hyperledger/burrow/binary" +func NewAccountPermissions(pss ...PermFlag) AccountPermissions { + var perms PermFlag + for _, ps := range pss { + perms |= ps + } + return AccountPermissions{ + Base: BasePermissions{ + Perms: perms, + SetBit: perms, + }, + } +} + // Returns true if the role is found func (ap AccountPermissions) HasRole(role string) bool { role = string(binary.RightPadBytes([]byte(role), 32)) diff --git a/permission/util.go b/permission/util.go index 6f4ba1ebe..0436f9390 100644 --- a/permission/util.go +++ b/permission/util.go @@ -15,7 +15,6 @@ package permission import ( - "fmt" "strings" ) @@ -83,40 +82,28 @@ func PermFlagFromStringList(permissions []string) (PermFlag, error) { // Builds a list of set permissions from a BasePermission by creating a list of permissions strings // from the resultant permissions of basePermissions -func BasePermissionsToStringList(basePermissions BasePermissions) ([]string, error) { +func BasePermissionsToStringList(basePermissions BasePermissions) []string { return PermFlagToStringList(basePermissions.ResultantPerms()) } // Creates a list of individual permission flag strings from a possibly composite PermFlag // by projecting out each bit and adding its permission string if it is set -func PermFlagToStringList(permFlag PermFlag) ([]string, error) { +func PermFlagToStringList(permFlag PermFlag) []string { permStrings := make([]string, 0, NumPermissions) - if permFlag > AllPermFlags { - return nil, fmt.Errorf("resultant permission 0b%b is invalid: has permission flag set above top flag 0b%b", - permFlag, TopPermFlag) - } for i := uint(0); i < NumPermissions; i++ { permFlag := permFlag & (1 << i) if permFlag > 0 { permStrings = append(permStrings, permFlag.String()) } } - return permStrings, nil + return permStrings } // Generates a human readable string from the resultant permissions of basePermission func BasePermissionsString(basePermissions BasePermissions) string { - permStrings, err := BasePermissionsToStringList(basePermissions) - if err != nil { - return UnknownString - } - return strings.Join(permStrings, " | ") + return strings.Join(BasePermissionsToStringList(basePermissions), " | ") } func String(permFlag PermFlag) string { - permStrings, err := PermFlagToStringList(permFlag) - if err != nil { - return UnknownString - } - return strings.Join(permStrings, " | ") + return strings.Join(PermFlagToStringList(permFlag), " | ") } diff --git a/permission/util_test.go b/permission/util_test.go index 105536120..86f0ed625 100644 --- a/permission/util_test.go +++ b/permission/util_test.go @@ -25,17 +25,15 @@ func TestBasePermissionsFromStringList(t *testing.T) { } func TestBasePermissionsToStringList(t *testing.T) { - permStrings, err := BasePermissionsToStringList(allSetBasePermission(Root | HasRole | SetBase | Call)) - require.NoError(t, err) + permStrings := BasePermissionsToStringList(allSetBasePermission(Root | HasRole | SetBase | Call)) assert.Equal(t, []string{"root", "call", "setBase", "hasRole"}, permStrings) - permStrings, err = BasePermissionsToStringList(allSetBasePermission(AllPermFlags)) - require.NoError(t, err) + permStrings = BasePermissionsToStringList(allSetBasePermission(AllPermFlags)) assert.Equal(t, []string{"root", "send", "call", "createContract", "createAccount", "bond", "name", "hasBase", "setBase", "unsetBase", "setGlobal", "hasRole", "addRole", "removeRole"}, permStrings) - permStrings, err = BasePermissionsToStringList(allSetBasePermission(AllPermFlags + 1)) - assert.Error(t, err) + permStrings = BasePermissionsToStringList(allSetBasePermission(AllPermFlags + 1)) + assert.Equal(t, []string{}, permStrings) } func TestBasePermissionsString(t *testing.T) { diff --git a/protobuf/acm.proto b/protobuf/acm.proto index 8a52a277d..1fef3bd9a 100644 --- a/protobuf/acm.proto +++ b/protobuf/acm.proto @@ -9,15 +9,10 @@ import "github.com/gogo/protobuf/gogoproto/gogo.proto"; import "permission.proto"; import "crypto.proto"; -// Enable custom Marshal method. option (gogoproto.marshaler_all) = true; -// Enable custom Unmarshal method. option (gogoproto.unmarshaler_all) = true; -// Enable custom Size method (Required by Marshal and Unmarshal). option (gogoproto.sizer_all) = true; -// Enable registration with golang/protobuf for the grpc-gateway. option (gogoproto.goproto_registration) = true; -// Enable generation of XXX_MessageName methods for grpc-go/status. option (gogoproto.messagename_all) = true; message ConcreteAccount { @@ -28,4 +23,4 @@ message ConcreteAccount { uint64 Balance = 4; bytes Code = 5 [(gogoproto.customtype) = "Bytecode", (gogoproto.nullable) = false]; permission.AccountPermissions Permissions = 6 [(gogoproto.nullable) = false]; -} \ No newline at end of file +} diff --git a/protobuf/balance.proto b/protobuf/balance.proto new file mode 100644 index 000000000..ea71f6c4a --- /dev/null +++ b/protobuf/balance.proto @@ -0,0 +1,20 @@ +// Needed to proto2 rather than proto3 to get pointer field for PermArg +syntax = 'proto3'; + +option go_package = "github.com/hyperledger/burrow/acm/balance"; + +import "github.com/gogo/protobuf/gogoproto/gogo.proto"; + +package balance; + +option (gogoproto.marshaler_all) = true; +option (gogoproto.unmarshaler_all) = true; +option (gogoproto.sizer_all) = true; +option (gogoproto.goproto_registration) = true; +option (gogoproto.messagename_all) = true; + +message Balance { + option (gogoproto.goproto_stringer) = false; + uint32 Type = 1 [(gogoproto.casttype) = "Type"]; + uint64 Amount = 2; +} \ No newline at end of file diff --git a/protobuf/exec.proto b/protobuf/exec.proto index 172f540b8..fde241498 100644 --- a/protobuf/exec.proto +++ b/protobuf/exec.proto @@ -5,7 +5,7 @@ package exec; option go_package = "github.com/hyperledger/burrow/execution/exec"; import "github.com/gogo/protobuf/gogoproto/gogo.proto"; -import "github.com/tendermint/tendermint/abci/types/types.proto"; +//import "github.com/tendermint/tendermint/abci/types/types.proto"; import "errors.proto"; import "names.proto"; diff --git a/protobuf/payload.proto b/protobuf/payload.proto index 1e75fdf40..55938021e 100644 --- a/protobuf/payload.proto +++ b/protobuf/payload.proto @@ -20,12 +20,14 @@ option (gogoproto.goproto_registration) = true; // Enable generation of XXX_MessageName methods for grpc-go/status. option (gogoproto.messagename_all) = true; -message AnyPayload { +message Any { CallTx CallTx = 1; SendTx SendTx = 2; NameTx NameTx = 3; - PermissionsTx PermissionsTx = 4; - GovernanceTx GovernanceTx = 5; + PermsTx PermsTx = 4; + GovTx GovTx = 5; + BondTx BondTx = 6; + UnbondTx UnbondTx = 7; } // An input to a transaction that may carry an Amount as a charge and whose sequence number must be one greater than @@ -76,7 +78,7 @@ message SendTx { } // An update to the on-chain permissions -message PermissionsTx { +message PermsTx { option (gogoproto.goproto_stringer) = false; // The permission moderator TxInput Input = 1; @@ -114,7 +116,7 @@ message UnbondTx { uint64 Height = 3; } -message GovernanceTx { +message GovTx { option (gogoproto.goproto_stringer) = false; option (gogoproto.goproto_getters) = false; diff --git a/protobuf/rpcquery.proto b/protobuf/rpcquery.proto index bbb512255..fc8b66262 100644 --- a/protobuf/rpcquery.proto +++ b/protobuf/rpcquery.proto @@ -8,6 +8,7 @@ import "github.com/gogo/protobuf/gogoproto/gogo.proto"; import "names.proto"; import "acm.proto"; +import "validator.proto"; option (gogoproto.marshaler_all) = true; option (gogoproto.unmarshaler_all) = true; @@ -20,6 +21,7 @@ service Query { rpc ListAccounts (ListAccountsParam) returns (stream acm.ConcreteAccount); rpc GetName (GetNameParam) returns (names.Entry); rpc ListNames (ListNamesParam) returns (stream names.Entry); + rpc GetValidatorSet (GetValidatorSetParam) returns (ValidatorSet); } message GetAccountParam { @@ -38,3 +40,16 @@ message ListNamesParam { string Query = 1; } +message GetValidatorSetParam { + bool IncludeHistory = 1; +} + +message ValidatorSet { + uint64 height = 1; + repeated validator.Validator Set = 2; + repeated ValidatorSetDeltas History = 3; +} + +message ValidatorSetDeltas { + repeated validator.Validator Validators = 2; +} \ No newline at end of file diff --git a/protobuf/rpctransact.proto b/protobuf/rpctransact.proto index b2753a171..64b778213 100644 --- a/protobuf/rpctransact.proto +++ b/protobuf/rpctransact.proto @@ -32,7 +32,7 @@ service Transact { // Sign transaction server-side rpc SignTx (TxEnvelopeParam) returns (TxEnvelope); // Formulate a transaction from a Payload and retrun the envelop with the Tx bytes ready to sign - rpc FormulateTx (PayloadParam) returns (TxEnvelope); + rpc FormulateTx (payload.Any) returns (TxEnvelope); // Formulate and sign a CallTx transaction signed server-side and wait for it to be included in a block, retrieving response rpc CallTxSync (payload.CallTx) returns (exec.TxExecution); @@ -61,12 +61,6 @@ message CallCodeParam { bytes Data = 3; } -message PayloadParam { - payload.CallTx CallTx = 1; - payload.SendTx SendTx = 2; - payload.NameTx NameTx = 3; -} - message TxEnvelope { txs.Envelope Envelope = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/txs.Envelope"]; } @@ -75,6 +69,6 @@ message TxEnvelopeParam { // An existing Envelope - either signed or unsigned - if the latter will be signed server-side txs.Envelope Envelope = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/txs.Envelope"]; // If no Envelope provided then one will be generated from the provided payload and signed server-side - PayloadParam Payload = 2; + payload.Any Payload = 2; } diff --git a/protobuf/spec.proto b/protobuf/spec.proto index 7f0c6abec..03a2090b9 100644 --- a/protobuf/spec.proto +++ b/protobuf/spec.proto @@ -1,35 +1,28 @@ // Needed to proto2 rather than proto3 to get pointer field for PermArg -syntax = 'proto2'; +syntax = 'proto3'; option go_package = "github.com/hyperledger/burrow/genesis/spec"; import "github.com/gogo/protobuf/gogoproto/gogo.proto"; import "crypto.proto"; +import "balance.proto"; package spec; -// Enable custom Marshal method. option (gogoproto.marshaler_all) = true; -// Enable custom Unmarshal method. option (gogoproto.unmarshaler_all) = true; -// Enable custom Size method (Required by Marshal and Unmarshal). option (gogoproto.sizer_all) = true; -// Enable registration with golang/protobuf for the grpc-gateway. option (gogoproto.goproto_registration) = true; -// Enable generation of XXX_MessageName methods for grpc-go/status. option (gogoproto.messagename_all) = true; message TemplateAccount { - option (gogoproto.goproto_unrecognized) = false; - - optional string Name = 1 [(gogoproto.nullable) = false]; - optional bytes Address = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""]; - optional bytes NodeAddress = 3 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""]; - optional crypto.PublicKey PublicKey = 4 [(gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""]; - optional uint64 Amount = 5 [(gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""]; - optional uint64 Power = 6 [(gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""]; - repeated string Permissions = 7 [(gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""]; - repeated string Roles = 8 [(gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""]; + string Name = 1; + bytes Address = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""]; + bytes NodeAddress = 3 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""]; + crypto.PublicKey PublicKey = 4 [(gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""]; + repeated balance.Balance Amounts = 5 [(gogoproto.nullable) = false, (gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""]; + repeated string Permissions = 6 [(gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""]; + repeated string Roles = 7 [(gogoproto.jsontag) = ",omitempty", (gogoproto.moretags) = "toml:\",omitempty\""]; } diff --git a/protobuf/validator.proto b/protobuf/validator.proto new file mode 100644 index 000000000..dc621ab7a --- /dev/null +++ b/protobuf/validator.proto @@ -0,0 +1,22 @@ +syntax = 'proto3'; + +package validator; + +option go_package = "github.com/hyperledger/burrow/acm/validator"; + +import "github.com/gogo/protobuf/gogoproto/gogo.proto"; + +import "crypto.proto"; + +option (gogoproto.marshaler_all) = true; +option (gogoproto.unmarshaler_all) = true; +option (gogoproto.sizer_all) = true; +option (gogoproto.goproto_registration) = true; +option (gogoproto.messagename_all) = true; + +message Validator { + option (gogoproto.goproto_stringer) = false; + bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address"]; + crypto.PublicKey PublicKey = 2 [(gogoproto.nullable) = false]; + uint64 Power = 3; +} diff --git a/rpc/result.go b/rpc/result.go index af777d940..35d21892f 100644 --- a/rpc/result.go +++ b/rpc/result.go @@ -18,6 +18,7 @@ import ( "time" "github.com/hyperledger/burrow/acm" + "github.com/hyperledger/burrow/acm/validator" "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/execution/names" @@ -96,7 +97,7 @@ func (b *Block) UnmarshalJSON(data []byte) (err error) { type ResultStatus struct { NodeInfo p2p.NodeInfo GenesisHash binary.HexBytes - PubKey crypto.PublicKey + PublicKey crypto.PublicKey LatestBlockHash binary.HexBytes LatestBlockHeight uint64 LatestBlockTime int64 @@ -130,6 +131,7 @@ type Peer struct { } type ResultNetInfo struct { + ThisNode p2p.NodeInfo Listening bool Listeners []string Peers []*Peer @@ -137,8 +139,8 @@ type ResultNetInfo struct { type ResultListValidators struct { BlockHeight uint64 - BondedValidators []*acm.ConcreteValidator - UnbondingValidators []*acm.ConcreteValidator + BondedValidators []*validator.Validator + UnbondingValidators []*validator.Validator } type ResultDumpConsensusState struct { diff --git a/rpc/rpcevents/execution_events_server.go b/rpc/rpcevents/execution_events_server.go index 2b042c77f..d8f48e147 100644 --- a/rpc/rpcevents/execution_events_server.go +++ b/rpc/rpcevents/execution_events_server.go @@ -7,7 +7,7 @@ import ( "io" "github.com/gogo/protobuf/proto" - bcm "github.com/hyperledger/burrow/blockchain" + bcm "github.com/hyperledger/burrow/bcm" "github.com/hyperledger/burrow/event" "github.com/hyperledger/burrow/event/query" "github.com/hyperledger/burrow/execution/exec" @@ -29,12 +29,12 @@ type Provider interface { type executionEventsServer struct { eventsProvider Provider subscribable event.Subscribable - tip bcm.TipInfo + tip bcm.BlockchainInfo logger *logging.Logger } func NewExecutionEventsServer(eventsProvider Provider, subscribable event.Subscribable, - tip bcm.TipInfo, logger *logging.Logger) ExecutionEventsServer { + tip bcm.BlockchainInfo, logger *logging.Logger) ExecutionEventsServer { return &executionEventsServer{ eventsProvider: eventsProvider, diff --git a/rpc/rpcquery/query_server.go b/rpc/rpcquery/query_server.go index edcb968b6..debdc05b5 100644 --- a/rpc/rpcquery/query_server.go +++ b/rpc/rpcquery/query_server.go @@ -5,24 +5,36 @@ import ( "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/acm/state" + "github.com/hyperledger/burrow/bcm" + "github.com/hyperledger/burrow/consensus/tendermint" "github.com/hyperledger/burrow/event/query" "github.com/hyperledger/burrow/execution/names" + "github.com/hyperledger/burrow/logging" ) type queryServer struct { - accounts state.IterableReader - nameReg names.IterableReader + accounts state.IterableReader + nameReg names.IterableReader + blockchain bcm.BlockchainInfo + nodeView *tendermint.NodeView + logger *logging.Logger } var _ QueryServer = &queryServer{} -func NewQueryServer(state state.IterableReader, nameReg names.IterableReader) *queryServer { +func NewQueryServer(state state.IterableReader, nameReg names.IterableReader, blockchain bcm.BlockchainInfo, + nodeView *tendermint.NodeView, logger *logging.Logger) *queryServer { return &queryServer{ - accounts: state, - nameReg: nameReg, + accounts: state, + nameReg: nameReg, + blockchain: blockchain, + nodeView: nodeView, + logger: logger, } } +// Account state + func (qs *queryServer) GetAccount(ctx context.Context, param *GetAccountParam) (*acm.ConcreteAccount, error) { acc, err := qs.accounts.GetAccount(param.Address) if err != nil { @@ -74,3 +86,20 @@ func (qs *queryServer) ListNames(param *ListNamesParam, stream Query_ListNamesSe } return streamErr } + +func (qs *queryServer) GetValidatorSet(ctx context.Context, param *GetValidatorSetParam) (*ValidatorSet, error) { + set, deltas, height := qs.blockchain.ValidatorsHistory() + vs := &ValidatorSet{ + Height: height, + Set: set.Validators(), + } + if param.IncludeHistory { + vs.History = make([]*ValidatorSetDeltas, len(deltas)) + for i, d := range deltas { + vs.History[i] = &ValidatorSetDeltas{ + Validators: d.Validators(), + } + } + } + return vs, nil +} diff --git a/rpc/rpcquery/rpcquery.pb.go b/rpc/rpcquery/rpcquery.pb.go index ce9b9f17d..ec9b81710 100644 --- a/rpc/rpcquery/rpcquery.pb.go +++ b/rpc/rpcquery/rpcquery.pb.go @@ -12,6 +12,9 @@ ListAccountsParam GetNameParam ListNamesParam + GetValidatorSetParam + ValidatorSet + ValidatorSetDeltas */ package rpcquery @@ -22,6 +25,7 @@ import math "math" import _ "github.com/gogo/protobuf/gogoproto" import names "github.com/hyperledger/burrow/execution/names" import acm "github.com/hyperledger/burrow/acm" +import validator "github.com/hyperledger/burrow/acm/validator" import github_com_hyperledger_burrow_crypto "github.com/hyperledger/burrow/crypto" @@ -114,6 +118,82 @@ func (m *ListNamesParam) GetQuery() string { func (*ListNamesParam) XXX_MessageName() string { return "rpcquery.ListNamesParam" } + +type GetValidatorSetParam struct { + IncludeHistory bool `protobuf:"varint,1,opt,name=IncludeHistory,proto3" json:"IncludeHistory,omitempty"` +} + +func (m *GetValidatorSetParam) Reset() { *m = GetValidatorSetParam{} } +func (m *GetValidatorSetParam) String() string { return proto.CompactTextString(m) } +func (*GetValidatorSetParam) ProtoMessage() {} +func (*GetValidatorSetParam) Descriptor() ([]byte, []int) { return fileDescriptorRpcquery, []int{4} } + +func (m *GetValidatorSetParam) GetIncludeHistory() bool { + if m != nil { + return m.IncludeHistory + } + return false +} + +func (*GetValidatorSetParam) XXX_MessageName() string { + return "rpcquery.GetValidatorSetParam" +} + +type ValidatorSet struct { + Height uint64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` + Set []*validator.Validator `protobuf:"bytes,2,rep,name=Set" json:"Set,omitempty"` + History []*ValidatorSetDeltas `protobuf:"bytes,3,rep,name=History" json:"History,omitempty"` +} + +func (m *ValidatorSet) Reset() { *m = ValidatorSet{} } +func (m *ValidatorSet) String() string { return proto.CompactTextString(m) } +func (*ValidatorSet) ProtoMessage() {} +func (*ValidatorSet) Descriptor() ([]byte, []int) { return fileDescriptorRpcquery, []int{5} } + +func (m *ValidatorSet) GetHeight() uint64 { + if m != nil { + return m.Height + } + return 0 +} + +func (m *ValidatorSet) GetSet() []*validator.Validator { + if m != nil { + return m.Set + } + return nil +} + +func (m *ValidatorSet) GetHistory() []*ValidatorSetDeltas { + if m != nil { + return m.History + } + return nil +} + +func (*ValidatorSet) XXX_MessageName() string { + return "rpcquery.ValidatorSet" +} + +type ValidatorSetDeltas struct { + Validators []*validator.Validator `protobuf:"bytes,2,rep,name=Validators" json:"Validators,omitempty"` +} + +func (m *ValidatorSetDeltas) Reset() { *m = ValidatorSetDeltas{} } +func (m *ValidatorSetDeltas) String() string { return proto.CompactTextString(m) } +func (*ValidatorSetDeltas) ProtoMessage() {} +func (*ValidatorSetDeltas) Descriptor() ([]byte, []int) { return fileDescriptorRpcquery, []int{6} } + +func (m *ValidatorSetDeltas) GetValidators() []*validator.Validator { + if m != nil { + return m.Validators + } + return nil +} + +func (*ValidatorSetDeltas) XXX_MessageName() string { + return "rpcquery.ValidatorSetDeltas" +} func init() { proto.RegisterType((*GetAccountParam)(nil), "rpcquery.GetAccountParam") golang_proto.RegisterType((*GetAccountParam)(nil), "rpcquery.GetAccountParam") @@ -123,6 +203,12 @@ func init() { golang_proto.RegisterType((*GetNameParam)(nil), "rpcquery.GetNameParam") proto.RegisterType((*ListNamesParam)(nil), "rpcquery.ListNamesParam") golang_proto.RegisterType((*ListNamesParam)(nil), "rpcquery.ListNamesParam") + proto.RegisterType((*GetValidatorSetParam)(nil), "rpcquery.GetValidatorSetParam") + golang_proto.RegisterType((*GetValidatorSetParam)(nil), "rpcquery.GetValidatorSetParam") + proto.RegisterType((*ValidatorSet)(nil), "rpcquery.ValidatorSet") + golang_proto.RegisterType((*ValidatorSet)(nil), "rpcquery.ValidatorSet") + proto.RegisterType((*ValidatorSetDeltas)(nil), "rpcquery.ValidatorSetDeltas") + golang_proto.RegisterType((*ValidatorSetDeltas)(nil), "rpcquery.ValidatorSetDeltas") } // Reference imports to suppress errors if they are not otherwise used. @@ -140,6 +226,7 @@ type QueryClient interface { ListAccounts(ctx context.Context, in *ListAccountsParam, opts ...grpc.CallOption) (Query_ListAccountsClient, error) GetName(ctx context.Context, in *GetNameParam, opts ...grpc.CallOption) (*names.Entry, error) ListNames(ctx context.Context, in *ListNamesParam, opts ...grpc.CallOption) (Query_ListNamesClient, error) + GetValidatorSet(ctx context.Context, in *GetValidatorSetParam, opts ...grpc.CallOption) (*ValidatorSet, error) } type queryClient struct { @@ -232,6 +319,15 @@ func (x *queryListNamesClient) Recv() (*names.Entry, error) { return m, nil } +func (c *queryClient) GetValidatorSet(ctx context.Context, in *GetValidatorSetParam, opts ...grpc.CallOption) (*ValidatorSet, error) { + out := new(ValidatorSet) + err := grpc.Invoke(ctx, "/rpcquery.Query/GetValidatorSet", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + // Server API for Query service type QueryServer interface { @@ -239,6 +335,7 @@ type QueryServer interface { ListAccounts(*ListAccountsParam, Query_ListAccountsServer) error GetName(context.Context, *GetNameParam) (*names.Entry, error) ListNames(*ListNamesParam, Query_ListNamesServer) error + GetValidatorSet(context.Context, *GetValidatorSetParam) (*ValidatorSet, error) } func RegisterQueryServer(s *grpc.Server, srv QueryServer) { @@ -323,6 +420,24 @@ func (x *queryListNamesServer) Send(m *names.Entry) error { return x.ServerStream.SendMsg(m) } +func _Query_GetValidatorSet_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetValidatorSetParam) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).GetValidatorSet(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/rpcquery.Query/GetValidatorSet", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).GetValidatorSet(ctx, req.(*GetValidatorSetParam)) + } + return interceptor(ctx, in, info, handler) +} + var _Query_serviceDesc = grpc.ServiceDesc{ ServiceName: "rpcquery.Query", HandlerType: (*QueryServer)(nil), @@ -335,6 +450,10 @@ var _Query_serviceDesc = grpc.ServiceDesc{ MethodName: "GetName", Handler: _Query_GetName_Handler, }, + { + MethodName: "GetValidatorSet", + Handler: _Query_GetValidatorSet_Handler, + }, }, Streams: []grpc.StreamDesc{ { @@ -449,6 +568,111 @@ func (m *ListNamesParam) MarshalTo(dAtA []byte) (int, error) { return i, nil } +func (m *GetValidatorSetParam) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GetValidatorSetParam) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.IncludeHistory { + dAtA[i] = 0x8 + i++ + if m.IncludeHistory { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i++ + } + return i, nil +} + +func (m *ValidatorSet) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ValidatorSet) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.Height != 0 { + dAtA[i] = 0x8 + i++ + i = encodeVarintRpcquery(dAtA, i, uint64(m.Height)) + } + if len(m.Set) > 0 { + for _, msg := range m.Set { + dAtA[i] = 0x12 + i++ + i = encodeVarintRpcquery(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + if len(m.History) > 0 { + for _, msg := range m.History { + dAtA[i] = 0x1a + i++ + i = encodeVarintRpcquery(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + return i, nil +} + +func (m *ValidatorSetDeltas) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ValidatorSetDeltas) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Validators) > 0 { + for _, msg := range m.Validators { + dAtA[i] = 0x12 + i++ + i = encodeVarintRpcquery(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n + } + } + return i, nil +} + func encodeVarintRpcquery(dAtA []byte, offset int, v uint64) int { for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) @@ -496,6 +720,48 @@ func (m *ListNamesParam) Size() (n int) { return n } +func (m *GetValidatorSetParam) Size() (n int) { + var l int + _ = l + if m.IncludeHistory { + n += 2 + } + return n +} + +func (m *ValidatorSet) Size() (n int) { + var l int + _ = l + if m.Height != 0 { + n += 1 + sovRpcquery(uint64(m.Height)) + } + if len(m.Set) > 0 { + for _, e := range m.Set { + l = e.Size() + n += 1 + l + sovRpcquery(uint64(l)) + } + } + if len(m.History) > 0 { + for _, e := range m.History { + l = e.Size() + n += 1 + l + sovRpcquery(uint64(l)) + } + } + return n +} + +func (m *ValidatorSetDeltas) Size() (n int) { + var l int + _ = l + if len(m.Validators) > 0 { + for _, e := range m.Validators { + l = e.Size() + n += 1 + l + sovRpcquery(uint64(l)) + } + } + return n +} + func sovRpcquery(x uint64) (n int) { for { n++ @@ -826,6 +1092,288 @@ func (m *ListNamesParam) Unmarshal(dAtA []byte) error { } return nil } +func (m *GetValidatorSetParam) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcquery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GetValidatorSetParam: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GetValidatorSetParam: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field IncludeHistory", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcquery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + m.IncludeHistory = bool(v != 0) + default: + iNdEx = preIndex + skippy, err := skipRpcquery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthRpcquery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ValidatorSet) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcquery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ValidatorSet: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ValidatorSet: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcquery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Set", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcquery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthRpcquery + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Set = append(m.Set, &validator.Validator{}) + if err := m.Set[len(m.Set)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field History", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcquery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthRpcquery + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.History = append(m.History, &ValidatorSetDeltas{}) + if err := m.History[len(m.History)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipRpcquery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthRpcquery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ValidatorSetDeltas) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcquery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ValidatorSetDeltas: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ValidatorSetDeltas: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Validators", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcquery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthRpcquery + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Validators = append(m.Validators, &validator.Validator{}) + if err := m.Validators[len(m.Validators)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipRpcquery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthRpcquery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func skipRpcquery(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 @@ -935,27 +1483,36 @@ func init() { proto.RegisterFile("rpcquery.proto", fileDescriptorRpcquery) } func init() { golang_proto.RegisterFile("rpcquery.proto", fileDescriptorRpcquery) } var fileDescriptorRpcquery = []byte{ - // 349 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x92, 0xcd, 0x4a, 0xc3, 0x40, - 0x14, 0x85, 0x1d, 0x50, 0x6b, 0xaf, 0xa1, 0xe2, 0x50, 0xa4, 0x46, 0x48, 0x25, 0x0b, 0x51, 0xd1, - 0xa4, 0xf8, 0xb3, 0x14, 0x6c, 0x8b, 0x74, 0x23, 0x45, 0xbb, 0x74, 0x97, 0x4c, 0xc7, 0xb4, 0x60, - 0x32, 0xf1, 0x66, 0x82, 0xe4, 0xed, 0x5c, 0x76, 0xe9, 0xda, 0x45, 0x91, 0xf6, 0x11, 0x7c, 0x01, - 0xc9, 0x24, 0xe9, 0x8f, 0x4a, 0x77, 0xf7, 0x84, 0x7b, 0xce, 0x99, 0x6f, 0x26, 0x50, 0xc1, 0x90, - 0xbd, 0xc6, 0x1c, 0x13, 0x2b, 0x44, 0x21, 0x05, 0xdd, 0x2a, 0xb4, 0x7e, 0xee, 0x0d, 0xe5, 0x20, - 0x76, 0x2d, 0x26, 0x7c, 0xdb, 0x13, 0x9e, 0xb0, 0xd5, 0x82, 0x1b, 0x3f, 0x2b, 0xa5, 0x84, 0x9a, - 0x32, 0xa3, 0xbe, 0x1d, 0x38, 0x3e, 0x8f, 0x72, 0x51, 0x76, 0x98, 0x9f, 0x8d, 0xa6, 0x03, 0x3b, - 0x1d, 0x2e, 0x9b, 0x8c, 0x89, 0x38, 0x90, 0x0f, 0x0e, 0x3a, 0x3e, 0xed, 0x42, 0xa9, 0xd9, 0xef, - 0x23, 0x8f, 0xa2, 0x1a, 0x39, 0x24, 0xc7, 0x5a, 0xeb, 0x6a, 0x34, 0xae, 0xaf, 0x7d, 0x8e, 0xeb, - 0x67, 0x0b, 0x95, 0x83, 0x24, 0xe4, 0xf8, 0xc2, 0xfb, 0x1e, 0x47, 0xdb, 0x8d, 0x11, 0xc5, 0x9b, - 0xcd, 0x30, 0x09, 0xa5, 0xb0, 0x72, 0x6f, 0xaf, 0x08, 0x31, 0x4f, 0x60, 0xf7, 0x7e, 0x18, 0x15, - 0x1d, 0x51, 0x56, 0x52, 0x85, 0x8d, 0xc7, 0x94, 0x43, 0x55, 0x94, 0x7b, 0x99, 0x30, 0x4d, 0xd0, - 0x3a, 0x5c, 0x76, 0x1d, 0x9f, 0x67, 0x5b, 0x14, 0xd6, 0x53, 0x91, 0x2f, 0xa9, 0xd9, 0x3c, 0x82, - 0x4a, 0x1a, 0x97, 0xce, 0xab, 0xb2, 0x2e, 0xbe, 0x49, 0xfe, 0x99, 0xde, 0x00, 0xcc, 0x19, 0xe9, - 0xbe, 0x35, 0xbb, 0xd3, 0x5f, 0xe4, 0x7a, 0xd5, 0x4a, 0x2f, 0xa6, 0x2d, 0x02, 0x86, 0x5c, 0xf2, - 0xc2, 0xd0, 0x06, 0x6d, 0xf1, 0xfc, 0xf4, 0x60, 0x1e, 0xf0, 0x87, 0xeb, 0xff, 0x88, 0x06, 0xa1, - 0x36, 0x94, 0x72, 0x32, 0xba, 0xb7, 0x74, 0x80, 0x19, 0xac, 0xae, 0x59, 0xd9, 0x1b, 0xdd, 0x05, - 0x12, 0x13, 0x7a, 0x0d, 0xe5, 0x19, 0x26, 0xad, 0x2d, 0x57, 0xce, 0xd9, 0x97, 0x4d, 0x0d, 0xd2, - 0xba, 0x1d, 0x4d, 0x0c, 0xf2, 0x31, 0x31, 0xc8, 0xd7, 0xc4, 0x20, 0xef, 0x53, 0x83, 0x8c, 0xa6, - 0x06, 0x79, 0x3a, 0x5d, 0xfd, 0x72, 0x18, 0x32, 0xbb, 0x28, 0x70, 0x37, 0xd5, 0x8f, 0x71, 0xf9, - 0x13, 0x00, 0x00, 0xff, 0xff, 0xfa, 0xef, 0x21, 0x21, 0x7b, 0x02, 0x00, 0x00, + // 487 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x53, 0x4f, 0x6f, 0xd3, 0x30, + 0x1c, 0xc5, 0xeb, 0x58, 0xd7, 0xdf, 0xaa, 0x4e, 0x58, 0x55, 0x55, 0x02, 0xca, 0xa6, 0x1c, 0xaa, + 0x81, 0x20, 0x99, 0xc6, 0xe0, 0x06, 0x62, 0x1b, 0xa8, 0x0c, 0xa1, 0x09, 0x32, 0x89, 0x03, 0x37, + 0xd7, 0x31, 0x69, 0xa4, 0x26, 0x0e, 0x8e, 0x03, 0xea, 0x17, 0xe0, 0x63, 0x21, 0x8e, 0x3d, 0x72, + 0xe6, 0x30, 0xa1, 0xee, 0x8b, 0xa0, 0x38, 0xce, 0xbf, 0x75, 0xea, 0xcd, 0xcf, 0x79, 0xef, 0xf7, + 0xec, 0xbc, 0x67, 0xe8, 0x89, 0x98, 0x7e, 0x4b, 0x99, 0x98, 0xdb, 0xb1, 0xe0, 0x92, 0xe3, 0xed, + 0x02, 0x1b, 0x4f, 0xfd, 0x40, 0x4e, 0xd3, 0x89, 0x4d, 0x79, 0xe8, 0xf8, 0xdc, 0xe7, 0x8e, 0x22, + 0x4c, 0xd2, 0xaf, 0x0a, 0x29, 0xa0, 0x56, 0xb9, 0xd0, 0xd8, 0x89, 0x48, 0xc8, 0x12, 0x0d, 0x3a, + 0x84, 0x86, 0x7a, 0xb9, 0xfb, 0x9d, 0xcc, 0x02, 0x8f, 0x48, 0x2e, 0xf2, 0x0d, 0x8b, 0xc0, 0xee, + 0x98, 0xc9, 0x13, 0x4a, 0x79, 0x1a, 0xc9, 0x8f, 0x44, 0x90, 0x10, 0x5f, 0x40, 0xfb, 0xc4, 0xf3, + 0x04, 0x4b, 0x92, 0x21, 0xda, 0x47, 0x07, 0xdd, 0xd3, 0xe3, 0xc5, 0xd5, 0xde, 0x9d, 0xbf, 0x57, + 0x7b, 0x4f, 0x6a, 0x67, 0x98, 0xce, 0x63, 0x26, 0x66, 0xcc, 0xf3, 0x99, 0x70, 0x26, 0xa9, 0x10, + 0xfc, 0x87, 0x43, 0xc5, 0x3c, 0x96, 0xdc, 0xd6, 0x5a, 0xb7, 0x18, 0x62, 0x3d, 0x82, 0x7b, 0x1f, + 0x82, 0xa4, 0xf0, 0x48, 0x72, 0x93, 0x3e, 0xdc, 0xfd, 0x94, 0x5d, 0x4c, 0x59, 0x74, 0xdc, 0x1c, + 0x58, 0x16, 0x74, 0xc7, 0x4c, 0x5e, 0x90, 0x90, 0xe5, 0x2c, 0x0c, 0x9b, 0x19, 0xd0, 0x24, 0xb5, + 0xb6, 0x46, 0xd0, 0xcb, 0xc6, 0x65, 0xeb, 0xb5, 0xb3, 0x5e, 0x41, 0x7f, 0xcc, 0xe4, 0xe7, 0xe2, + 0xbe, 0x97, 0x4c, 0x5f, 0x6f, 0x04, 0xbd, 0xf3, 0x88, 0xce, 0x52, 0x8f, 0xbd, 0x0b, 0x12, 0xc9, + 0xb5, 0x6c, 0xdb, 0xbd, 0xb1, 0x6b, 0xfd, 0x44, 0xd0, 0xad, 0xab, 0xf1, 0x00, 0xb6, 0xa6, 0x2c, + 0xf0, 0xa7, 0x52, 0x09, 0x36, 0x5d, 0x8d, 0xf0, 0x08, 0x5a, 0x97, 0x4c, 0x0e, 0x37, 0xf6, 0x5b, + 0x07, 0x3b, 0x47, 0x7d, 0xbb, 0xfa, 0xc3, 0xa5, 0xda, 0xcd, 0x08, 0xf8, 0x05, 0xb4, 0x0b, 0xc7, + 0x96, 0xe2, 0x3e, 0xb4, 0xcb, 0xb8, 0xeb, 0x46, 0x6f, 0xd8, 0x4c, 0x92, 0xc4, 0x2d, 0xc8, 0xd6, + 0x7b, 0xc0, 0xab, 0x9f, 0xf1, 0x31, 0x40, 0xb9, 0x9b, 0xac, 0x35, 0xaf, 0xf1, 0x8e, 0x7e, 0x6d, + 0xe8, 0x7f, 0x85, 0x5f, 0x02, 0x54, 0xc1, 0xe3, 0xfb, 0xd5, 0x51, 0x6e, 0xd4, 0xc1, 0xe8, 0xdb, + 0x59, 0x7d, 0xce, 0x78, 0x44, 0x05, 0x93, 0xac, 0x10, 0x9c, 0x41, 0xb7, 0x1e, 0x2a, 0x7e, 0x50, + 0x0d, 0x58, 0x09, 0xfb, 0xf6, 0x11, 0x87, 0x08, 0x3b, 0xd0, 0xd6, 0x71, 0xe3, 0x41, 0xe3, 0x00, + 0x65, 0x03, 0x8c, 0xae, 0x9d, 0x37, 0xf9, 0x6d, 0x24, 0xc5, 0x1c, 0x3f, 0x87, 0x4e, 0x99, 0x3d, + 0x1e, 0x36, 0x2d, 0xab, 0x42, 0x34, 0x45, 0x87, 0x08, 0x9f, 0xab, 0x92, 0x37, 0xc2, 0x34, 0x1b, + 0x7e, 0x2b, 0x2d, 0x31, 0x06, 0xb7, 0x67, 0x73, 0xfa, 0x7a, 0xb1, 0x34, 0xd1, 0x9f, 0xa5, 0x89, + 0xfe, 0x2d, 0x4d, 0xf4, 0xfb, 0xda, 0x44, 0x8b, 0x6b, 0x13, 0x7d, 0x79, 0xbc, 0xfe, 0x65, 0x88, + 0x98, 0x3a, 0xc5, 0xb8, 0xc9, 0x96, 0x7a, 0x78, 0xcf, 0xfe, 0x07, 0x00, 0x00, 0xff, 0xff, 0xfd, + 0xa4, 0xb6, 0xf9, 0xec, 0x03, 0x00, 0x00, } diff --git a/rpc/rpctransact/rpctransact.pb.go b/rpc/rpctransact/rpctransact.pb.go index 903e977b4..988615476 100644 --- a/rpc/rpctransact/rpctransact.pb.go +++ b/rpc/rpctransact/rpctransact.pb.go @@ -9,7 +9,6 @@ It has these top-level messages: CallCodeParam - PayloadParam TxEnvelope TxEnvelopeParam */ @@ -73,42 +72,6 @@ func (*CallCodeParam) XXX_MessageName() string { return "rpctransact.CallCodeParam" } -type PayloadParam struct { - CallTx *payload.CallTx `protobuf:"bytes,1,opt,name=CallTx" json:"CallTx,omitempty"` - SendTx *payload.SendTx `protobuf:"bytes,2,opt,name=SendTx" json:"SendTx,omitempty"` - NameTx *payload.NameTx `protobuf:"bytes,3,opt,name=NameTx" json:"NameTx,omitempty"` -} - -func (m *PayloadParam) Reset() { *m = PayloadParam{} } -func (m *PayloadParam) String() string { return proto.CompactTextString(m) } -func (*PayloadParam) ProtoMessage() {} -func (*PayloadParam) Descriptor() ([]byte, []int) { return fileDescriptorRpctransact, []int{1} } - -func (m *PayloadParam) GetCallTx() *payload.CallTx { - if m != nil { - return m.CallTx - } - return nil -} - -func (m *PayloadParam) GetSendTx() *payload.SendTx { - if m != nil { - return m.SendTx - } - return nil -} - -func (m *PayloadParam) GetNameTx() *payload.NameTx { - if m != nil { - return m.NameTx - } - return nil -} - -func (*PayloadParam) XXX_MessageName() string { - return "rpctransact.PayloadParam" -} - type TxEnvelope struct { Envelope *github_com_hyperledger_burrow_txs.Envelope `protobuf:"bytes,1,opt,name=Envelope,customtype=github.com/hyperledger/burrow/txs.Envelope" json:"Envelope,omitempty"` } @@ -116,7 +79,7 @@ type TxEnvelope struct { func (m *TxEnvelope) Reset() { *m = TxEnvelope{} } func (m *TxEnvelope) String() string { return proto.CompactTextString(m) } func (*TxEnvelope) ProtoMessage() {} -func (*TxEnvelope) Descriptor() ([]byte, []int) { return fileDescriptorRpctransact, []int{2} } +func (*TxEnvelope) Descriptor() ([]byte, []int) { return fileDescriptorRpctransact, []int{1} } func (*TxEnvelope) XXX_MessageName() string { return "rpctransact.TxEnvelope" @@ -126,15 +89,15 @@ type TxEnvelopeParam struct { // An existing Envelope - either signed or unsigned - if the latter will be signed server-side Envelope *github_com_hyperledger_burrow_txs.Envelope `protobuf:"bytes,1,opt,name=Envelope,customtype=github.com/hyperledger/burrow/txs.Envelope" json:"Envelope,omitempty"` // If no Envelope provided then one will be generated from the provided payload and signed server-side - Payload *PayloadParam `protobuf:"bytes,2,opt,name=Payload" json:"Payload,omitempty"` + Payload *payload.Any `protobuf:"bytes,2,opt,name=Payload" json:"Payload,omitempty"` } func (m *TxEnvelopeParam) Reset() { *m = TxEnvelopeParam{} } func (m *TxEnvelopeParam) String() string { return proto.CompactTextString(m) } func (*TxEnvelopeParam) ProtoMessage() {} -func (*TxEnvelopeParam) Descriptor() ([]byte, []int) { return fileDescriptorRpctransact, []int{3} } +func (*TxEnvelopeParam) Descriptor() ([]byte, []int) { return fileDescriptorRpctransact, []int{2} } -func (m *TxEnvelopeParam) GetPayload() *PayloadParam { +func (m *TxEnvelopeParam) GetPayload() *payload.Any { if m != nil { return m.Payload } @@ -147,8 +110,6 @@ func (*TxEnvelopeParam) XXX_MessageName() string { func init() { proto.RegisterType((*CallCodeParam)(nil), "rpctransact.CallCodeParam") golang_proto.RegisterType((*CallCodeParam)(nil), "rpctransact.CallCodeParam") - proto.RegisterType((*PayloadParam)(nil), "rpctransact.PayloadParam") - golang_proto.RegisterType((*PayloadParam)(nil), "rpctransact.PayloadParam") proto.RegisterType((*TxEnvelope)(nil), "rpctransact.TxEnvelope") golang_proto.RegisterType((*TxEnvelope)(nil), "rpctransact.TxEnvelope") proto.RegisterType((*TxEnvelopeParam)(nil), "rpctransact.TxEnvelopeParam") @@ -174,7 +135,7 @@ type TransactClient interface { // Sign transaction server-side SignTx(ctx context.Context, in *TxEnvelopeParam, opts ...grpc.CallOption) (*TxEnvelope, error) // Formulate a transaction from a Payload and retrun the envelop with the Tx bytes ready to sign - FormulateTx(ctx context.Context, in *PayloadParam, opts ...grpc.CallOption) (*TxEnvelope, error) + FormulateTx(ctx context.Context, in *payload.Any, opts ...grpc.CallOption) (*TxEnvelope, error) // Formulate and sign a CallTx transaction signed server-side and wait for it to be included in a block, retrieving response CallTxSync(ctx context.Context, in *payload.CallTx, opts ...grpc.CallOption) (*exec.TxExecution, error) // Formulate and sign a CallTx transaction signed server-side @@ -229,7 +190,7 @@ func (c *transactClient) SignTx(ctx context.Context, in *TxEnvelopeParam, opts . return out, nil } -func (c *transactClient) FormulateTx(ctx context.Context, in *PayloadParam, opts ...grpc.CallOption) (*TxEnvelope, error) { +func (c *transactClient) FormulateTx(ctx context.Context, in *payload.Any, opts ...grpc.CallOption) (*TxEnvelope, error) { out := new(TxEnvelope) err := grpc.Invoke(ctx, "/rpctransact.Transact/FormulateTx", in, out, c.cc, opts...) if err != nil { @@ -321,7 +282,7 @@ type TransactServer interface { // Sign transaction server-side SignTx(context.Context, *TxEnvelopeParam) (*TxEnvelope, error) // Formulate a transaction from a Payload and retrun the envelop with the Tx bytes ready to sign - FormulateTx(context.Context, *PayloadParam) (*TxEnvelope, error) + FormulateTx(context.Context, *payload.Any) (*TxEnvelope, error) // Formulate and sign a CallTx transaction signed server-side and wait for it to be included in a block, retrieving response CallTxSync(context.Context, *payload.CallTx) (*exec.TxExecution, error) // Formulate and sign a CallTx transaction signed server-side @@ -400,7 +361,7 @@ func _Transact_SignTx_Handler(srv interface{}, ctx context.Context, dec func(int } func _Transact_FormulateTx_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(PayloadParam) + in := new(payload.Any) if err := dec(in); err != nil { return nil, err } @@ -412,7 +373,7 @@ func _Transact_FormulateTx_Handler(srv interface{}, ctx context.Context, dec fun FullMethod: "/rpctransact.Transact/FormulateTx", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TransactServer).FormulateTx(ctx, req.(*PayloadParam)) + return srv.(TransactServer).FormulateTx(ctx, req.(*payload.Any)) } return interceptor(ctx, in, info, handler) } @@ -656,54 +617,6 @@ func (m *CallCodeParam) MarshalTo(dAtA []byte) (int, error) { return i, nil } -func (m *PayloadParam) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *PayloadParam) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if m.CallTx != nil { - dAtA[i] = 0xa - i++ - i = encodeVarintRpctransact(dAtA, i, uint64(m.CallTx.Size())) - n2, err := m.CallTx.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n2 - } - if m.SendTx != nil { - dAtA[i] = 0x12 - i++ - i = encodeVarintRpctransact(dAtA, i, uint64(m.SendTx.Size())) - n3, err := m.SendTx.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n3 - } - if m.NameTx != nil { - dAtA[i] = 0x1a - i++ - i = encodeVarintRpctransact(dAtA, i, uint64(m.NameTx.Size())) - n4, err := m.NameTx.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n4 - } - return i, nil -} - func (m *TxEnvelope) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -723,11 +636,11 @@ func (m *TxEnvelope) MarshalTo(dAtA []byte) (int, error) { dAtA[i] = 0xa i++ i = encodeVarintRpctransact(dAtA, i, uint64(m.Envelope.Size())) - n5, err := m.Envelope.MarshalTo(dAtA[i:]) + n2, err := m.Envelope.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n5 + i += n2 } return i, nil } @@ -751,21 +664,21 @@ func (m *TxEnvelopeParam) MarshalTo(dAtA []byte) (int, error) { dAtA[i] = 0xa i++ i = encodeVarintRpctransact(dAtA, i, uint64(m.Envelope.Size())) - n6, err := m.Envelope.MarshalTo(dAtA[i:]) + n3, err := m.Envelope.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n6 + i += n3 } if m.Payload != nil { dAtA[i] = 0x12 i++ i = encodeVarintRpctransact(dAtA, i, uint64(m.Payload.Size())) - n7, err := m.Payload.MarshalTo(dAtA[i:]) + n4, err := m.Payload.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n7 + i += n4 } return i, nil } @@ -795,24 +708,6 @@ func (m *CallCodeParam) Size() (n int) { return n } -func (m *PayloadParam) Size() (n int) { - var l int - _ = l - if m.CallTx != nil { - l = m.CallTx.Size() - n += 1 + l + sovRpctransact(uint64(l)) - } - if m.SendTx != nil { - l = m.SendTx.Size() - n += 1 + l + sovRpctransact(uint64(l)) - } - if m.NameTx != nil { - l = m.NameTx.Size() - n += 1 + l + sovRpctransact(uint64(l)) - } - return n -} - func (m *TxEnvelope) Size() (n int) { var l int _ = l @@ -992,155 +887,6 @@ func (m *CallCodeParam) Unmarshal(dAtA []byte) error { } return nil } -func (m *PayloadParam) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowRpctransact - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PayloadParam: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PayloadParam: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CallTx", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowRpctransact - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthRpctransact - } - postIndex := iNdEx + msglen - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.CallTx == nil { - m.CallTx = &payload.CallTx{} - } - if err := m.CallTx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SendTx", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowRpctransact - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthRpctransact - } - postIndex := iNdEx + msglen - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.SendTx == nil { - m.SendTx = &payload.SendTx{} - } - if err := m.SendTx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NameTx", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowRpctransact - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthRpctransact - } - postIndex := iNdEx + msglen - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.NameTx == nil { - m.NameTx = &payload.NameTx{} - } - if err := m.NameTx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipRpctransact(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthRpctransact - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} func (m *TxEnvelope) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1313,7 +1059,7 @@ func (m *TxEnvelopeParam) Unmarshal(dAtA []byte) error { return io.ErrUnexpectedEOF } if m.Payload == nil { - m.Payload = &PayloadParam{} + m.Payload = &payload.Any{} } if err := m.Payload.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err @@ -1449,40 +1195,37 @@ func init() { proto.RegisterFile("rpctransact.proto", fileDescriptorRpctransact) func init() { golang_proto.RegisterFile("rpctransact.proto", fileDescriptorRpctransact) } var fileDescriptorRpctransact = []byte{ - // 552 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x54, 0xcd, 0x6e, 0xd3, 0x40, - 0x10, 0xc6, 0xfc, 0x84, 0x76, 0x92, 0x28, 0x74, 0x2f, 0x84, 0x08, 0x25, 0x28, 0x17, 0x10, 0x6a, - 0xed, 0xa8, 0xe5, 0x88, 0x40, 0x49, 0x68, 0x8f, 0xa8, 0x72, 0x2c, 0x24, 0xb8, 0x6d, 0xec, 0xc5, - 0x8d, 0x64, 0x7b, 0xad, 0xf5, 0x06, 0x36, 0x8f, 0xc0, 0x89, 0x67, 0xe8, 0x9b, 0x70, 0xcc, 0x91, - 0x73, 0x0f, 0x11, 0x4a, 0x5f, 0x04, 0xed, 0x4f, 0x60, 0x6d, 0x9a, 0x96, 0x4b, 0x6f, 0xe3, 0x6f, - 0x66, 0xbe, 0x99, 0xef, 0xd3, 0x8e, 0x61, 0x8f, 0xe5, 0x21, 0x67, 0x38, 0x2b, 0x70, 0xc8, 0xdd, - 0x9c, 0x51, 0x4e, 0x51, 0xdd, 0x82, 0x3a, 0x07, 0xf1, 0x8c, 0x9f, 0xcd, 0xa7, 0x6e, 0x48, 0x53, - 0x2f, 0xa6, 0x31, 0xf5, 0x54, 0xcd, 0x74, 0xfe, 0x59, 0x7d, 0xa9, 0x0f, 0x15, 0xe9, 0xde, 0x0e, - 0x10, 0x41, 0x42, 0x13, 0x37, 0x73, 0xbc, 0x48, 0x28, 0x8e, 0xcc, 0xe7, 0x2e, 0x17, 0x85, 0x0e, - 0xfb, 0xdf, 0x1d, 0x68, 0x8e, 0x71, 0x92, 0x8c, 0x69, 0x44, 0x4e, 0x31, 0xc3, 0x29, 0xfa, 0x00, - 0xf5, 0x13, 0x46, 0xd3, 0x61, 0x14, 0x31, 0x52, 0x14, 0x6d, 0xe7, 0x99, 0xf3, 0xa2, 0x31, 0x7a, - 0xb5, 0x5c, 0xf5, 0xee, 0x5c, 0xac, 0x7a, 0xfb, 0xd6, 0x0e, 0x67, 0x8b, 0x9c, 0xb0, 0x84, 0x44, - 0x31, 0x61, 0xde, 0x74, 0xce, 0x18, 0xfd, 0xea, 0x85, 0x6c, 0x91, 0x73, 0xea, 0x9a, 0x5e, 0xdf, - 0x26, 0x42, 0x08, 0xee, 0xcb, 0x21, 0xed, 0xbb, 0x92, 0xd0, 0x57, 0xb1, 0xc4, 0xde, 0x61, 0x8e, - 0xdb, 0xf7, 0x34, 0x26, 0xe3, 0xfe, 0x37, 0x07, 0x1a, 0xa7, 0x7a, 0x5d, 0xbd, 0xd0, 0x73, 0xa8, - 0xc9, 0x0d, 0x03, 0xa1, 0x76, 0xa9, 0x1f, 0xb6, 0xdc, 0x8d, 0x1a, 0x0d, 0xfb, 0x26, 0x2d, 0x0b, - 0x27, 0x24, 0x8b, 0x02, 0xa1, 0x66, 0xd8, 0x85, 0x1a, 0xf6, 0x4d, 0x5a, 0x16, 0xbe, 0xc7, 0x29, - 0x09, 0x84, 0x1a, 0x6c, 0x17, 0x6a, 0xd8, 0x37, 0xe9, 0x7e, 0x0c, 0x10, 0x88, 0xe3, 0xec, 0x0b, - 0x49, 0x68, 0x4e, 0xd0, 0x47, 0xd8, 0xd9, 0xc4, 0x66, 0x95, 0xa6, 0x2b, 0x9d, 0xdc, 0x80, 0x23, - 0xf7, 0x62, 0xd5, 0x7b, 0x79, 0xbd, 0x43, 0x76, 0xbd, 0xff, 0x87, 0xae, 0x7f, 0xee, 0x40, 0xeb, - 0xef, 0x24, 0xad, 0xfb, 0xf6, 0xc6, 0xa1, 0x23, 0x78, 0x68, 0x2c, 0x36, 0x56, 0x3d, 0x71, 0xed, - 0xc7, 0x67, 0xdb, 0xef, 0x6f, 0x2a, 0x0f, 0xcf, 0x1f, 0xc0, 0x4e, 0x60, 0x4a, 0xd0, 0x08, 0x5a, - 0x23, 0x46, 0x71, 0x14, 0xe2, 0x82, 0x07, 0x62, 0xb2, 0xc8, 0x42, 0xf4, 0xb4, 0xc4, 0x51, 0x51, - 0xd3, 0xd9, 0x73, 0xd5, 0x7b, 0x0c, 0xc4, 0xb1, 0x20, 0xe1, 0x9c, 0xcf, 0x68, 0x86, 0xde, 0xc0, - 0x23, 0x8b, 0x63, 0x58, 0xdc, 0x4c, 0xd2, 0x50, 0x06, 0xf8, 0x24, 0x24, 0xb3, 0x9c, 0xa3, 0xb7, - 0x50, 0x9b, 0xcc, 0xe2, 0x2c, 0x10, 0x37, 0x74, 0x3d, 0xde, 0x92, 0x45, 0x43, 0xa8, 0x9f, 0x50, - 0x96, 0xce, 0x13, 0xcc, 0x49, 0x20, 0xd0, 0x76, 0x13, 0xb6, 0x53, 0x0c, 0x00, 0xf4, 0xeb, 0x53, - 0x16, 0x54, 0x9f, 0xe6, 0x55, 0xaa, 0xf7, 0xa1, 0xae, 0x93, 0x5a, 0xf0, 0x3f, 0x2d, 0x65, 0x8d, - 0x1e, 0xec, 0x1a, 0xfe, 0x59, 0xfa, 0x5f, 0xf4, 0xaf, 0x35, 0xbd, 0x3c, 0x2f, 0xd9, 0xd2, 0x29, - 0x2d, 0x5e, 0xba, 0xf4, 0xab, 0xba, 0x07, 0x00, 0xfa, 0x46, 0x2a, 0x72, 0x34, 0xb8, 0x45, 0x8e, - 0x4e, 0x56, 0xe5, 0x98, 0x96, 0xb2, 0x9c, 0x01, 0x80, 0x3e, 0xad, 0x0a, 0xbf, 0x06, 0xb7, 0xf0, - 0xeb, 0x64, 0x95, 0xdf, 0xb4, 0x94, 0xf8, 0x47, 0xe3, 0xe5, 0xba, 0xeb, 0xfc, 0x5c, 0x77, 0x9d, - 0x5f, 0xeb, 0xae, 0xf3, 0xe3, 0xb2, 0xeb, 0x2c, 0x2f, 0xbb, 0xce, 0xa7, 0x83, 0xeb, 0x8f, 0x84, - 0xe5, 0xa1, 0x67, 0xb9, 0x34, 0xad, 0xa9, 0x5f, 0xe3, 0xd1, 0xef, 0x00, 0x00, 0x00, 0xff, 0xff, - 0x0f, 0x15, 0x24, 0xfe, 0x91, 0x05, 0x00, 0x00, + // 506 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x54, 0xcf, 0x6f, 0xd3, 0x30, + 0x18, 0x25, 0xfc, 0x18, 0xdb, 0x97, 0x56, 0x65, 0xbe, 0x50, 0x55, 0x28, 0x45, 0x3d, 0x20, 0x84, + 0xb6, 0xa4, 0x2a, 0x3b, 0x22, 0x50, 0x53, 0xb6, 0x23, 0x9a, 0xd2, 0x08, 0x09, 0x6e, 0xae, 0x63, + 0xb2, 0x48, 0x49, 0x1c, 0x39, 0x0e, 0x24, 0x7f, 0x05, 0x97, 0xfd, 0x41, 0x1c, 0x7b, 0xe4, 0xbc, + 0x43, 0x85, 0xba, 0x7f, 0x04, 0xc5, 0x4e, 0x47, 0xd2, 0xae, 0x2b, 0x97, 0xdd, 0x9e, 0xdf, 0x97, + 0xf7, 0xfc, 0x3d, 0x7f, 0x76, 0xe0, 0x90, 0x27, 0x44, 0x70, 0x1c, 0xa7, 0x98, 0x08, 0x33, 0xe1, + 0x4c, 0x30, 0xa4, 0xd7, 0xa8, 0xde, 0xb1, 0x1f, 0x88, 0x8b, 0x6c, 0x66, 0x12, 0x16, 0x59, 0x3e, + 0xf3, 0x99, 0x25, 0xbf, 0x99, 0x65, 0xdf, 0xe4, 0x4a, 0x2e, 0x24, 0x52, 0xda, 0x1e, 0xd0, 0x9c, + 0x92, 0x0a, 0xb7, 0x13, 0x5c, 0x84, 0x0c, 0x7b, 0xd5, 0xf2, 0x40, 0xe4, 0xa9, 0x82, 0x83, 0x9f, + 0x1a, 0xb4, 0x27, 0x38, 0x0c, 0x27, 0xcc, 0xa3, 0xe7, 0x98, 0xe3, 0x08, 0x7d, 0x06, 0xfd, 0x8c, + 0xb3, 0x68, 0xec, 0x79, 0x9c, 0xa6, 0x69, 0x57, 0x7b, 0xa9, 0xbd, 0x6e, 0xd9, 0x27, 0xf3, 0x45, + 0xff, 0xc1, 0xd5, 0xa2, 0x7f, 0x54, 0xeb, 0xe1, 0xa2, 0x48, 0x28, 0x0f, 0xa9, 0xe7, 0x53, 0x6e, + 0xcd, 0x32, 0xce, 0xd9, 0x0f, 0x8b, 0xf0, 0x22, 0x11, 0xcc, 0xac, 0xb4, 0x4e, 0xdd, 0x08, 0x21, + 0x78, 0x5c, 0x6e, 0xd2, 0x7d, 0x58, 0x1a, 0x3a, 0x12, 0x97, 0xdc, 0x47, 0x2c, 0x70, 0xf7, 0x91, + 0xe2, 0x4a, 0x3c, 0xf0, 0x01, 0xdc, 0xfc, 0x34, 0xfe, 0x4e, 0x43, 0x96, 0x50, 0xf4, 0x05, 0xf6, + 0x57, 0x58, 0xb6, 0xa2, 0x8f, 0xda, 0x66, 0xd9, 0xfd, 0x8a, 0xb4, 0xcd, 0xab, 0x45, 0xff, 0xcd, + 0xdd, 0x5d, 0xd5, 0xbf, 0x77, 0x6e, 0xec, 0x06, 0x97, 0x1a, 0x74, 0xfe, 0xed, 0xa4, 0xc2, 0xdf, + 0xdf, 0x76, 0xe8, 0x15, 0x3c, 0x3d, 0x57, 0x53, 0x90, 0x47, 0xa0, 0x8f, 0x5a, 0xe6, 0x6a, 0x2a, + 0xe3, 0xb8, 0x70, 0x56, 0xc5, 0xd1, 0xe5, 0x13, 0xd8, 0x77, 0xab, 0x99, 0x23, 0x1b, 0x3a, 0x36, + 0x67, 0xd8, 0x23, 0x38, 0x15, 0x6e, 0x3e, 0x2d, 0x62, 0x82, 0x5e, 0x98, 0xf5, 0x7b, 0xb2, 0x16, + 0xa0, 0x77, 0x68, 0xca, 0xb1, 0xbb, 0xf9, 0x69, 0x4e, 0x49, 0x26, 0x02, 0x16, 0xa3, 0xf7, 0xf0, + 0xac, 0xe6, 0x31, 0x4e, 0x77, 0x9b, 0xb4, 0x64, 0x66, 0x87, 0x12, 0x1a, 0x24, 0x02, 0x7d, 0x80, + 0xbd, 0x69, 0xe0, 0xc7, 0x6e, 0xbe, 0x43, 0xf5, 0x7c, 0x4b, 0x15, 0x9d, 0x80, 0x7e, 0xc6, 0x78, + 0x94, 0x85, 0x58, 0x50, 0x37, 0x47, 0x8d, 0xdc, 0xdb, 0x55, 0x43, 0x80, 0xf2, 0x62, 0x56, 0xa9, + 0x3b, 0x37, 0x22, 0x45, 0xde, 0x16, 0xf4, 0x08, 0x74, 0x55, 0x54, 0x19, 0x37, 0x24, 0xcd, 0x58, + 0x16, 0x1c, 0x54, 0xfe, 0x41, 0xf4, 0x5f, 0xf6, 0xef, 0x94, 0x7d, 0x79, 0x71, 0x4b, 0x49, 0xaf, + 0xd1, 0x78, 0xe3, 0x0d, 0xdd, 0xa6, 0x1e, 0x02, 0x4c, 0x69, 0xec, 0x6d, 0xc4, 0x51, 0xe4, 0x96, + 0x38, 0xaa, 0xb8, 0x1e, 0xa7, 0x92, 0x34, 0xe3, 0x0c, 0x01, 0x3e, 0xe1, 0x88, 0x6e, 0xf8, 0x2b, + 0x72, 0x8b, 0xbf, 0x2a, 0xae, 0xfb, 0x57, 0x92, 0x86, 0xbf, 0x3d, 0x99, 0x2f, 0x0d, 0xed, 0xf7, + 0xd2, 0xd0, 0xfe, 0x2c, 0x0d, 0xed, 0xd7, 0xb5, 0xa1, 0xcd, 0xaf, 0x0d, 0xed, 0xeb, 0xf1, 0xdd, + 0x4f, 0x81, 0x27, 0xc4, 0xaa, 0x9d, 0xd2, 0x6c, 0x4f, 0xfe, 0x74, 0xde, 0xfe, 0x0d, 0x00, 0x00, + 0xff, 0xff, 0xd4, 0x01, 0x16, 0xdf, 0xeb, 0x04, 0x00, 0x00, } diff --git a/rpc/rpctransact/transact_server.go b/rpc/rpctransact/transact_server.go index ab3a8c6ea..d2e0a9b45 100644 --- a/rpc/rpctransact/transact_server.go +++ b/rpc/rpctransact/transact_server.go @@ -52,8 +52,8 @@ func (ts *transactServer) SignTx(ctx context.Context, param *TxEnvelopeParam) (* }, nil } -func (ts *transactServer) FormulateTx(ctx context.Context, param *PayloadParam) (*TxEnvelope, error) { - txEnv := param.Envelope(ts.transactor.Tip.ChainID()) +func (ts *transactServer) FormulateTx(ctx context.Context, param *payload.Any) (*TxEnvelope, error) { + txEnv := EnvelopeFromAny(ts.transactor.Tip.ChainID(), param) if txEnv == nil { return nil, fmt.Errorf("no payload provided to FormulateTx") } @@ -63,11 +63,11 @@ func (ts *transactServer) FormulateTx(ctx context.Context, param *PayloadParam) } func (ts *transactServer) CallTxSync(ctx context.Context, param *payload.CallTx) (*exec.TxExecution, error) { - return ts.BroadcastTxSync(ctx, txEnvelopeParam(param)) + return ts.BroadcastTxSync(ctx, &TxEnvelopeParam{Payload: param.Any()}) } func (ts *transactServer) CallTxAsync(ctx context.Context, param *payload.CallTx) (*txs.Receipt, error) { - return ts.BroadcastTxAsync(ctx, txEnvelopeParam(param)) + return ts.BroadcastTxAsync(ctx, &TxEnvelopeParam{Payload: param.Any()}) } func (ts *transactServer) CallTxSim(ctx context.Context, param *payload.CallTx) (*exec.TxExecution, error) { @@ -82,19 +82,19 @@ func (ts *transactServer) CallCodeSim(ctx context.Context, param *CallCodeParam) } func (ts *transactServer) SendTxSync(ctx context.Context, param *payload.SendTx) (*exec.TxExecution, error) { - return ts.BroadcastTxSync(ctx, txEnvelopeParam(param)) + return ts.BroadcastTxSync(ctx, &TxEnvelopeParam{Payload: param.Any()}) } func (ts *transactServer) SendTxAsync(ctx context.Context, param *payload.SendTx) (*txs.Receipt, error) { - return ts.BroadcastTxAsync(ctx, txEnvelopeParam(param)) + return ts.BroadcastTxAsync(ctx, &TxEnvelopeParam{Payload: param.Any()}) } func (ts *transactServer) NameTxSync(ctx context.Context, param *payload.NameTx) (*exec.TxExecution, error) { - return ts.BroadcastTxSync(ctx, txEnvelopeParam(param)) + return ts.BroadcastTxSync(ctx, &TxEnvelopeParam{Payload: param.Any()}) } func (ts *transactServer) NameTxAsync(ctx context.Context, param *payload.NameTx) (*txs.Receipt, error) { - return ts.BroadcastTxAsync(ctx, txEnvelopeParam(param)) + return ts.BroadcastTxAsync(ctx, &TxEnvelopeParam{Payload: param.Any()}) } func (te *TxEnvelopeParam) GetEnvelope(chainID string) *txs.Envelope { @@ -105,44 +105,26 @@ func (te *TxEnvelopeParam) GetEnvelope(chainID string) *txs.Envelope { return te.Envelope } if te.Payload != nil { - return te.Payload.Envelope(chainID) + return EnvelopeFromAny(chainID, te.Payload) } return nil } -func (pp *PayloadParam) Envelope(chainID string) *txs.Envelope { - if pp.CallTx != nil { - return txs.Enclose(chainID, pp.CallTx) +func EnvelopeFromAny(chainID string, p *payload.Any) *txs.Envelope { + if p.CallTx != nil { + return txs.Enclose(chainID, p.CallTx) } - if pp.SendTx != nil { - return txs.Enclose(chainID, pp.SendTx) + if p.SendTx != nil { + return txs.Enclose(chainID, p.SendTx) } - if pp.NameTx != nil { - return txs.Enclose(chainID, pp.NameTx) + if p.NameTx != nil { + return txs.Enclose(chainID, p.NameTx) } - return nil -} - -func txEnvelopeParam(pl payload.Payload) *TxEnvelopeParam { - switch tx := pl.(type) { - case *payload.CallTx: - return &TxEnvelopeParam{ - Payload: &PayloadParam{ - CallTx: tx, - }, - } - case *payload.SendTx: - return &TxEnvelopeParam{ - Payload: &PayloadParam{ - SendTx: tx, - }, - } - case *payload.NameTx: - return &TxEnvelopeParam{ - Payload: &PayloadParam{ - NameTx: tx, - }, - } + if p.PermsTx != nil { + return txs.Enclose(chainID, p.PermsTx) + } + if p.GovTx != nil { + return txs.Enclose(chainID, p.GovTx) } return nil } diff --git a/rpc/service.go b/rpc/service.go index 42ebc1cf3..3c266ad25 100644 --- a/rpc/service.go +++ b/rpc/service.go @@ -22,11 +22,11 @@ import ( "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/acm/state" + "github.com/hyperledger/burrow/acm/validator" + "github.com/hyperledger/burrow/bcm" "github.com/hyperledger/burrow/binary" - bcm "github.com/hyperledger/burrow/blockchain" - "github.com/hyperledger/burrow/consensus/tendermint/query" + "github.com/hyperledger/burrow/consensus/tendermint" "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/execution" "github.com/hyperledger/burrow/execution/names" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" @@ -45,31 +45,24 @@ type Service struct { state state.IterableReader nameReg names.IterableReader blockchain bcm.BlockchainInfo - transactor *execution.Transactor - nodeView *query.NodeView + nodeView *tendermint.NodeView logger *logging.Logger } -func NewService(state state.IterableReader, nameReg names.IterableReader, - blockchain bcm.BlockchainInfo, transactor *execution.Transactor, nodeView *query.NodeView, - logger *logging.Logger) *Service { +// Service provides an internal query and information service with serialisable return types on which can accomodate +// a number of transport front ends +func NewService(state state.IterableReader, nameReg names.IterableReader, blockchain bcm.BlockchainInfo, + nodeView *tendermint.NodeView, logger *logging.Logger) *Service { return &Service{ state: state, nameReg: nameReg, blockchain: blockchain, - transactor: transactor, nodeView: nodeView, logger: logger.With(structure.ComponentKey, "Service"), } } -// Get a Transactor providing methods for delegating signing and the core BroadcastTx function for publishing -// transactions to the network -func (s *Service) Transactor() *execution.Transactor { - return s.transactor -} - func (s *Service) State() state.Reader { return s.state } @@ -117,7 +110,7 @@ func (s *Service) Status() (*ResultStatus, error) { return &ResultStatus{ NodeInfo: s.nodeView.NodeInfo(), GenesisHash: s.blockchain.GenesisHash(), - PubKey: publicKey, + PublicKey: publicKey, LatestBlockHash: latestBlockHash, LatestBlockHeight: latestHeight, LatestBlockTime: latestBlockTime, @@ -157,6 +150,7 @@ func (s *Service) NetInfo() (*ResultNetInfo, error) { return nil, err } return &ResultNetInfo{ + ThisNode: s.nodeView.NodeInfo(), Listening: listening, Listeners: listeners, Peers: peers.Peers, @@ -242,7 +236,7 @@ func (s *Service) GetAccountHumanReadable(address crypto.Address) (*ResultGetAcc if acc == nil { return &ResultGetAccountHumanReadable{}, nil } - perms, err := permission.BasePermissionsToStringList(acc.Permissions().Base) + perms := permission.BasePermissionsToStringList(acc.Permissions().Base) if acc == nil { return &ResultGetAccountHumanReadable{}, nil } @@ -323,10 +317,11 @@ func (s *Service) ListBlocks(minHeight, maxHeight uint64) (*ResultListBlocks, er } func (s *Service) ListValidators() (*ResultListValidators, error) { - concreteValidators := make([]*acm.ConcreteValidator, 0, s.blockchain.NumValidators()) - s.blockchain.IterateValidators(func(id crypto.Addressable, power *big.Int) (stop bool) { - concreteValidators = append(concreteValidators, &acm.ConcreteValidator{ - Address: id.Address(), + validators := make([]*validator.Validator, 0, s.blockchain.NumValidators()) + s.blockchain.Validators().Iterate(func(id crypto.Addressable, power *big.Int) (stop bool) { + address := id.Address() + validators = append(validators, &validator.Validator{ + Address: &address, PublicKey: id.PublicKey(), Power: power.Uint64(), }) @@ -334,7 +329,7 @@ func (s *Service) ListValidators() (*ResultListValidators, error) { }) return &ResultListValidators{ BlockHeight: s.blockchain.LastBlockHeight(), - BondedValidators: concreteValidators, + BondedValidators: validators, UnbondingValidators: nil, }, nil } diff --git a/txs/amino_codec.go b/txs/amino_codec.go index 9d85480b2..2ff423317 100644 --- a/txs/amino_codec.go +++ b/txs/amino_codec.go @@ -18,9 +18,9 @@ func NewAminoCodec() *aminoCodec { registerTx(cdc, &payload.CallTx{}) registerTx(cdc, &payload.BondTx{}) registerTx(cdc, &payload.UnbondTx{}) - registerTx(cdc, &payload.PermissionsTx{}) + registerTx(cdc, &payload.PermsTx{}) registerTx(cdc, &payload.NameTx{}) - registerTx(cdc, &payload.GovernanceTx{}) + registerTx(cdc, &payload.GovTx{}) return &aminoCodec{cdc} } diff --git a/txs/payload/bond_tx.go b/txs/payload/bond_tx.go index 59585b6e0..f81b21336 100644 --- a/txs/payload/bond_tx.go +++ b/txs/payload/bond_tx.go @@ -54,3 +54,9 @@ func (tx *BondTx) AddOutput(addr crypto.Address, amt uint64) error { }) return nil } + +func (tx *BondTx) Any() *Any { + return &Any{ + BondTx: tx, + } +} diff --git a/txs/payload/call_tx.go b/txs/payload/call_tx.go index 68638de3e..9855e296d 100644 --- a/txs/payload/call_tx.go +++ b/txs/payload/call_tx.go @@ -59,3 +59,9 @@ func (tx *CallTx) CreatesContractAddress() *crypto.Address { address := crypto.NewContractAddress(tx.Input.Address, tx.Input.Sequence) return &address } + +func (tx *CallTx) Any() *Any { + return &Any{ + CallTx: tx, + } +} diff --git a/txs/payload/gov_tx.go b/txs/payload/gov_tx.go new file mode 100644 index 000000000..eb4e5a1d4 --- /dev/null +++ b/txs/payload/gov_tx.go @@ -0,0 +1,23 @@ +package payload + +import ( + "fmt" +) + +func (tx *GovTx) Type() Type { + return TypeGovernance +} + +func (tx *GovTx) GetInputs() []*TxInput { + return tx.Inputs +} + +func (tx *GovTx) String() string { + return fmt.Sprintf("GovTx{%v -> %v}", tx.Inputs, tx.AccountUpdates) +} + +func (tx *GovTx) Any() *Any { + return &Any{ + GovTx: tx, + } +} diff --git a/txs/payload/governance_tx.go b/txs/payload/governance_tx.go deleted file mode 100644 index 5f8bfdeb4..000000000 --- a/txs/payload/governance_tx.go +++ /dev/null @@ -1,17 +0,0 @@ -package payload - -import ( - "fmt" -) - -func (tx *GovernanceTx) Type() Type { - return TypeGovernance -} - -func (tx *GovernanceTx) GetInputs() []*TxInput { - return tx.Inputs -} - -func (tx *GovernanceTx) String() string { - return fmt.Sprintf("GovernanceTx{%v -> %v}", tx.Inputs, tx.AccountUpdates) -} diff --git a/txs/payload/name_tx.go b/txs/payload/name_tx.go index 334fa6df3..13f85318f 100644 --- a/txs/payload/name_tx.go +++ b/txs/payload/name_tx.go @@ -47,3 +47,9 @@ func (tx *NameTx) GetInputs() []*TxInput { func (tx *NameTx) String() string { return fmt.Sprintf("NameTx{%v -> %s: %s}", tx.Input, tx.Name, tx.Data) } + +func (tx *NameTx) Any() *Any { + return &Any{ + NameTx: tx, + } +} diff --git a/txs/payload/payload.go b/txs/payload/payload.go index f415d8f83..d55a8cadd 100644 --- a/txs/payload/payload.go +++ b/txs/payload/payload.go @@ -1,5 +1,7 @@ package payload +import "fmt" + /* Payload (Transaction) is an atomic operation on the ledger state. @@ -13,7 +15,7 @@ Validation Txs: - UnbondTx Validator leaves Admin Txs: - - PermissionsTx + - PermsTx */ type Type uint32 @@ -42,8 +44,8 @@ var nameFromType = map[Type]string{ TypeName: "NameTx", TypeBond: "BondTx", TypeUnbond: "UnbondTx", - TypePermissions: "PermissionsTx", - TypeGovernance: "GovernanceTx", + TypePermissions: "PermsTx", + TypeGovernance: "GovTx", } var typeFromName = make(map[string]Type) @@ -88,24 +90,50 @@ type Payload interface { String() string GetInputs() []*TxInput Type() Type + Any() *Any // The serialised size in bytes Size() int } -func New(txType Type) Payload { +type UnknownTx struct { +} + +func (UnknownTx) String() string { + panic("implement me") +} + +func (UnknownTx) GetInputs() []*TxInput { + panic("implement me") +} + +func (UnknownTx) Type() Type { + panic("implement me") +} + +func (UnknownTx) Any() *Any { + panic("implement me") +} + +func (UnknownTx) Size() int { + panic("implement me") +} + +func New(txType Type) (Payload, error) { switch txType { case TypeSend: - return &SendTx{} + return &SendTx{}, nil case TypeCall: - return &CallTx{} + return &CallTx{}, nil case TypeName: - return &NameTx{} + return &NameTx{}, nil case TypeBond: - return &BondTx{} + return &BondTx{}, nil case TypeUnbond: - return &UnbondTx{} + return &UnbondTx{}, nil case TypePermissions: - return &PermissionsTx{} + return &PermsTx{}, nil + case TypeGovernance: + return &GovTx{}, nil } - return nil + return nil, fmt.Errorf("unknown payload type: %d", txType) } diff --git a/txs/payload/payload.pb.go b/txs/payload/payload.pb.go index a5e27c742..f1e5755ef 100644 --- a/txs/payload/payload.pb.go +++ b/txs/payload/payload.pb.go @@ -8,16 +8,16 @@ payload.proto It has these top-level messages: - AnyPayload + Any TxInput TxOutput CallTx SendTx - PermissionsTx + PermsTx NameTx BondTx UnbondTx - GovernanceTx + GovTx */ package payload @@ -46,56 +46,72 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package -type AnyPayload struct { - CallTx *CallTx `protobuf:"bytes,1,opt,name=CallTx" json:"CallTx,omitempty"` - SendTx *SendTx `protobuf:"bytes,2,opt,name=SendTx" json:"SendTx,omitempty"` - NameTx *NameTx `protobuf:"bytes,3,opt,name=NameTx" json:"NameTx,omitempty"` - PermissionsTx *PermissionsTx `protobuf:"bytes,4,opt,name=PermissionsTx" json:"PermissionsTx,omitempty"` - GovernanceTx *GovernanceTx `protobuf:"bytes,5,opt,name=GovernanceTx" json:"GovernanceTx,omitempty"` +type Any struct { + CallTx *CallTx `protobuf:"bytes,1,opt,name=CallTx" json:"CallTx,omitempty"` + SendTx *SendTx `protobuf:"bytes,2,opt,name=SendTx" json:"SendTx,omitempty"` + NameTx *NameTx `protobuf:"bytes,3,opt,name=NameTx" json:"NameTx,omitempty"` + PermsTx *PermsTx `protobuf:"bytes,4,opt,name=PermsTx" json:"PermsTx,omitempty"` + GovTx *GovTx `protobuf:"bytes,5,opt,name=GovTx" json:"GovTx,omitempty"` + BondTx *BondTx `protobuf:"bytes,6,opt,name=BondTx" json:"BondTx,omitempty"` + UnbondTx *UnbondTx `protobuf:"bytes,7,opt,name=UnbondTx" json:"UnbondTx,omitempty"` } -func (m *AnyPayload) Reset() { *m = AnyPayload{} } -func (m *AnyPayload) String() string { return proto.CompactTextString(m) } -func (*AnyPayload) ProtoMessage() {} -func (*AnyPayload) Descriptor() ([]byte, []int) { return fileDescriptorPayload, []int{0} } +func (m *Any) Reset() { *m = Any{} } +func (m *Any) String() string { return proto.CompactTextString(m) } +func (*Any) ProtoMessage() {} +func (*Any) Descriptor() ([]byte, []int) { return fileDescriptorPayload, []int{0} } -func (m *AnyPayload) GetCallTx() *CallTx { +func (m *Any) GetCallTx() *CallTx { if m != nil { return m.CallTx } return nil } -func (m *AnyPayload) GetSendTx() *SendTx { +func (m *Any) GetSendTx() *SendTx { if m != nil { return m.SendTx } return nil } -func (m *AnyPayload) GetNameTx() *NameTx { +func (m *Any) GetNameTx() *NameTx { if m != nil { return m.NameTx } return nil } -func (m *AnyPayload) GetPermissionsTx() *PermissionsTx { +func (m *Any) GetPermsTx() *PermsTx { if m != nil { - return m.PermissionsTx + return m.PermsTx } return nil } -func (m *AnyPayload) GetGovernanceTx() *GovernanceTx { +func (m *Any) GetGovTx() *GovTx { if m != nil { - return m.GovernanceTx + return m.GovTx } return nil } -func (*AnyPayload) XXX_MessageName() string { - return "payload.AnyPayload" +func (m *Any) GetBondTx() *BondTx { + if m != nil { + return m.BondTx + } + return nil +} + +func (m *Any) GetUnbondTx() *UnbondTx { + if m != nil { + return m.UnbondTx + } + return nil +} + +func (*Any) XXX_MessageName() string { + return "payload.Any" } // An input to a transaction that may carry an Amount as a charge and whose sequence number must be one greater than @@ -214,33 +230,33 @@ func (*SendTx) XXX_MessageName() string { } // An update to the on-chain permissions -type PermissionsTx struct { +type PermsTx struct { // The permission moderator Input *TxInput `protobuf:"bytes,1,opt,name=Input" json:"Input,omitempty"` // The modified permissions PermArgs permission.PermArgs `protobuf:"bytes,2,opt,name=PermArgs" json:"PermArgs"` } -func (m *PermissionsTx) Reset() { *m = PermissionsTx{} } -func (*PermissionsTx) ProtoMessage() {} -func (*PermissionsTx) Descriptor() ([]byte, []int) { return fileDescriptorPayload, []int{5} } +func (m *PermsTx) Reset() { *m = PermsTx{} } +func (*PermsTx) ProtoMessage() {} +func (*PermsTx) Descriptor() ([]byte, []int) { return fileDescriptorPayload, []int{5} } -func (m *PermissionsTx) GetInput() *TxInput { +func (m *PermsTx) GetInput() *TxInput { if m != nil { return m.Input } return nil } -func (m *PermissionsTx) GetPermArgs() permission.PermArgs { +func (m *PermsTx) GetPermArgs() permission.PermArgs { if m != nil { return m.PermArgs } return permission.PermArgs{} } -func (*PermissionsTx) XXX_MessageName() string { - return "payload.PermissionsTx" +func (*PermsTx) XXX_MessageName() string { + return "payload.PermsTx" } // A request to claim a globally unique name across the entire chain with some optional data storage leased for a fee @@ -318,21 +334,21 @@ func (*UnbondTx) XXX_MessageName() string { return "payload.UnbondTx" } -type GovernanceTx struct { +type GovTx struct { Inputs []*TxInput `protobuf:"bytes,1,rep,name=Inputs" json:"Inputs,omitempty"` AccountUpdates []*spec.TemplateAccount `protobuf:"bytes,2,rep,name=AccountUpdates" json:"AccountUpdates,omitempty"` } -func (m *GovernanceTx) Reset() { *m = GovernanceTx{} } -func (*GovernanceTx) ProtoMessage() {} -func (*GovernanceTx) Descriptor() ([]byte, []int) { return fileDescriptorPayload, []int{9} } +func (m *GovTx) Reset() { *m = GovTx{} } +func (*GovTx) ProtoMessage() {} +func (*GovTx) Descriptor() ([]byte, []int) { return fileDescriptorPayload, []int{9} } -func (*GovernanceTx) XXX_MessageName() string { - return "payload.GovernanceTx" +func (*GovTx) XXX_MessageName() string { + return "payload.GovTx" } func init() { - proto.RegisterType((*AnyPayload)(nil), "payload.AnyPayload") - golang_proto.RegisterType((*AnyPayload)(nil), "payload.AnyPayload") + proto.RegisterType((*Any)(nil), "payload.Any") + golang_proto.RegisterType((*Any)(nil), "payload.Any") proto.RegisterType((*TxInput)(nil), "payload.TxInput") golang_proto.RegisterType((*TxInput)(nil), "payload.TxInput") proto.RegisterType((*TxOutput)(nil), "payload.TxOutput") @@ -341,18 +357,18 @@ func init() { golang_proto.RegisterType((*CallTx)(nil), "payload.CallTx") proto.RegisterType((*SendTx)(nil), "payload.SendTx") golang_proto.RegisterType((*SendTx)(nil), "payload.SendTx") - proto.RegisterType((*PermissionsTx)(nil), "payload.PermissionsTx") - golang_proto.RegisterType((*PermissionsTx)(nil), "payload.PermissionsTx") + proto.RegisterType((*PermsTx)(nil), "payload.PermsTx") + golang_proto.RegisterType((*PermsTx)(nil), "payload.PermsTx") proto.RegisterType((*NameTx)(nil), "payload.NameTx") golang_proto.RegisterType((*NameTx)(nil), "payload.NameTx") proto.RegisterType((*BondTx)(nil), "payload.BondTx") golang_proto.RegisterType((*BondTx)(nil), "payload.BondTx") proto.RegisterType((*UnbondTx)(nil), "payload.UnbondTx") golang_proto.RegisterType((*UnbondTx)(nil), "payload.UnbondTx") - proto.RegisterType((*GovernanceTx)(nil), "payload.GovernanceTx") - golang_proto.RegisterType((*GovernanceTx)(nil), "payload.GovernanceTx") + proto.RegisterType((*GovTx)(nil), "payload.GovTx") + golang_proto.RegisterType((*GovTx)(nil), "payload.GovTx") } -func (m *AnyPayload) Marshal() (dAtA []byte, err error) { +func (m *Any) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) @@ -362,7 +378,7 @@ func (m *AnyPayload) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *AnyPayload) MarshalTo(dAtA []byte) (int, error) { +func (m *Any) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int @@ -397,26 +413,46 @@ func (m *AnyPayload) MarshalTo(dAtA []byte) (int, error) { } i += n3 } - if m.PermissionsTx != nil { + if m.PermsTx != nil { dAtA[i] = 0x22 i++ - i = encodeVarintPayload(dAtA, i, uint64(m.PermissionsTx.Size())) - n4, err := m.PermissionsTx.MarshalTo(dAtA[i:]) + i = encodeVarintPayload(dAtA, i, uint64(m.PermsTx.Size())) + n4, err := m.PermsTx.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n4 } - if m.GovernanceTx != nil { + if m.GovTx != nil { dAtA[i] = 0x2a i++ - i = encodeVarintPayload(dAtA, i, uint64(m.GovernanceTx.Size())) - n5, err := m.GovernanceTx.MarshalTo(dAtA[i:]) + i = encodeVarintPayload(dAtA, i, uint64(m.GovTx.Size())) + n5, err := m.GovTx.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n5 } + if m.BondTx != nil { + dAtA[i] = 0x32 + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.BondTx.Size())) + n6, err := m.BondTx.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n6 + } + if m.UnbondTx != nil { + dAtA[i] = 0x3a + i++ + i = encodeVarintPayload(dAtA, i, uint64(m.UnbondTx.Size())) + n7, err := m.UnbondTx.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n7 + } return i, nil } @@ -438,11 +474,11 @@ func (m *TxInput) MarshalTo(dAtA []byte) (int, error) { dAtA[i] = 0xa i++ i = encodeVarintPayload(dAtA, i, uint64(m.Address.Size())) - n6, err := m.Address.MarshalTo(dAtA[i:]) + n8, err := m.Address.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n6 + i += n8 if m.Amount != 0 { dAtA[i] = 0x10 i++ @@ -474,11 +510,11 @@ func (m *TxOutput) MarshalTo(dAtA []byte) (int, error) { dAtA[i] = 0xa i++ i = encodeVarintPayload(dAtA, i, uint64(m.Address.Size())) - n7, err := m.Address.MarshalTo(dAtA[i:]) + n9, err := m.Address.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n7 + i += n9 if m.Amount != 0 { dAtA[i] = 0x10 i++ @@ -506,21 +542,21 @@ func (m *CallTx) MarshalTo(dAtA []byte) (int, error) { dAtA[i] = 0xa i++ i = encodeVarintPayload(dAtA, i, uint64(m.Input.Size())) - n8, err := m.Input.MarshalTo(dAtA[i:]) + n10, err := m.Input.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n8 + i += n10 } if m.Address != nil { dAtA[i] = 0x12 i++ i = encodeVarintPayload(dAtA, i, uint64(m.Address.Size())) - n9, err := m.Address.MarshalTo(dAtA[i:]) + n11, err := m.Address.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n9 + i += n11 } if m.GasLimit != 0 { dAtA[i] = 0x18 @@ -535,11 +571,11 @@ func (m *CallTx) MarshalTo(dAtA []byte) (int, error) { dAtA[i] = 0x2a i++ i = encodeVarintPayload(dAtA, i, uint64(m.Data.Size())) - n10, err := m.Data.MarshalTo(dAtA[i:]) + n12, err := m.Data.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n10 + i += n12 return i, nil } @@ -585,7 +621,7 @@ func (m *SendTx) MarshalTo(dAtA []byte) (int, error) { return i, nil } -func (m *PermissionsTx) Marshal() (dAtA []byte, err error) { +func (m *PermsTx) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) @@ -595,7 +631,7 @@ func (m *PermissionsTx) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *PermissionsTx) MarshalTo(dAtA []byte) (int, error) { +func (m *PermsTx) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int @@ -604,20 +640,20 @@ func (m *PermissionsTx) MarshalTo(dAtA []byte) (int, error) { dAtA[i] = 0xa i++ i = encodeVarintPayload(dAtA, i, uint64(m.Input.Size())) - n11, err := m.Input.MarshalTo(dAtA[i:]) + n13, err := m.Input.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n11 + i += n13 } dAtA[i] = 0x12 i++ i = encodeVarintPayload(dAtA, i, uint64(m.PermArgs.Size())) - n12, err := m.PermArgs.MarshalTo(dAtA[i:]) + n14, err := m.PermArgs.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n12 + i += n14 return i, nil } @@ -640,11 +676,11 @@ func (m *NameTx) MarshalTo(dAtA []byte) (int, error) { dAtA[i] = 0xa i++ i = encodeVarintPayload(dAtA, i, uint64(m.Input.Size())) - n13, err := m.Input.MarshalTo(dAtA[i:]) + n15, err := m.Input.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n13 + i += n15 } if len(m.Name) > 0 { dAtA[i] = 0x12 @@ -727,20 +763,20 @@ func (m *UnbondTx) MarshalTo(dAtA []byte) (int, error) { dAtA[i] = 0xa i++ i = encodeVarintPayload(dAtA, i, uint64(m.Input.Size())) - n14, err := m.Input.MarshalTo(dAtA[i:]) + n16, err := m.Input.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n14 + i += n16 } dAtA[i] = 0x12 i++ i = encodeVarintPayload(dAtA, i, uint64(m.Address.Size())) - n15, err := m.Address.MarshalTo(dAtA[i:]) + n17, err := m.Address.MarshalTo(dAtA[i:]) if err != nil { return 0, err } - i += n15 + i += n17 if m.Height != 0 { dAtA[i] = 0x18 i++ @@ -749,7 +785,7 @@ func (m *UnbondTx) MarshalTo(dAtA []byte) (int, error) { return i, nil } -func (m *GovernanceTx) Marshal() (dAtA []byte, err error) { +func (m *GovTx) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) @@ -759,7 +795,7 @@ func (m *GovernanceTx) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *GovernanceTx) MarshalTo(dAtA []byte) (int, error) { +func (m *GovTx) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int @@ -800,7 +836,7 @@ func encodeVarintPayload(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return offset + 1 } -func (m *AnyPayload) Size() (n int) { +func (m *Any) Size() (n int) { var l int _ = l if m.CallTx != nil { @@ -815,12 +851,20 @@ func (m *AnyPayload) Size() (n int) { l = m.NameTx.Size() n += 1 + l + sovPayload(uint64(l)) } - if m.PermissionsTx != nil { - l = m.PermissionsTx.Size() + if m.PermsTx != nil { + l = m.PermsTx.Size() n += 1 + l + sovPayload(uint64(l)) } - if m.GovernanceTx != nil { - l = m.GovernanceTx.Size() + if m.GovTx != nil { + l = m.GovTx.Size() + n += 1 + l + sovPayload(uint64(l)) + } + if m.BondTx != nil { + l = m.BondTx.Size() + n += 1 + l + sovPayload(uint64(l)) + } + if m.UnbondTx != nil { + l = m.UnbondTx.Size() n += 1 + l + sovPayload(uint64(l)) } return n @@ -891,7 +935,7 @@ func (m *SendTx) Size() (n int) { return n } -func (m *PermissionsTx) Size() (n int) { +func (m *PermsTx) Size() (n int) { var l int _ = l if m.Input != nil { @@ -957,7 +1001,7 @@ func (m *UnbondTx) Size() (n int) { return n } -func (m *GovernanceTx) Size() (n int) { +func (m *GovTx) Size() (n int) { var l int _ = l if len(m.Inputs) > 0 { @@ -988,7 +1032,7 @@ func sovPayload(x uint64) (n int) { func sozPayload(x uint64) (n int) { return sovPayload(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } -func (m *AnyPayload) Unmarshal(dAtA []byte) error { +func (m *Any) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -1011,10 +1055,10 @@ func (m *AnyPayload) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: AnyPayload: wiretype end group for non-group") + return fmt.Errorf("proto: Any: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: AnyPayload: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: Any: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -1118,7 +1162,7 @@ func (m *AnyPayload) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 4: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PermissionsTx", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field PermsTx", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -1142,16 +1186,82 @@ func (m *AnyPayload) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.PermissionsTx == nil { - m.PermissionsTx = &PermissionsTx{} + if m.PermsTx == nil { + m.PermsTx = &PermsTx{} } - if err := m.PermissionsTx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.PermsTx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 5: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field GovernanceTx", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field GovTx", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.GovTx == nil { + m.GovTx = &GovTx{} + } + if err := m.GovTx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BondTx", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPayload + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPayload + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.BondTx == nil { + m.BondTx = &BondTx{} + } + if err := m.BondTx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field UnbondTx", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -1175,10 +1285,10 @@ func (m *AnyPayload) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.GovernanceTx == nil { - m.GovernanceTx = &GovernanceTx{} + if m.UnbondTx == nil { + m.UnbondTx = &UnbondTx{} } - if err := m.GovernanceTx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.UnbondTx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -1715,7 +1825,7 @@ func (m *SendTx) Unmarshal(dAtA []byte) error { } return nil } -func (m *PermissionsTx) Unmarshal(dAtA []byte) error { +func (m *PermsTx) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -1738,10 +1848,10 @@ func (m *PermissionsTx) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: PermissionsTx: wiretype end group for non-group") + return fmt.Errorf("proto: PermsTx: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: PermissionsTx: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: PermsTx: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -2232,7 +2342,7 @@ func (m *UnbondTx) Unmarshal(dAtA []byte) error { } return nil } -func (m *GovernanceTx) Unmarshal(dAtA []byte) error { +func (m *GovTx) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -2255,10 +2365,10 @@ func (m *GovernanceTx) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: GovernanceTx: wiretype end group for non-group") + return fmt.Errorf("proto: GovTx: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: GovernanceTx: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: GovTx: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -2453,46 +2563,47 @@ func init() { proto.RegisterFile("payload.proto", fileDescriptorPayload) } func init() { golang_proto.RegisterFile("payload.proto", fileDescriptorPayload) } var fileDescriptorPayload = []byte{ - // 652 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x55, 0xbf, 0x6f, 0xd3, 0x40, - 0x14, 0xee, 0x35, 0x6e, 0x62, 0x8e, 0x16, 0xca, 0x89, 0x56, 0x51, 0x86, 0x04, 0x75, 0x80, 0x22, - 0xa8, 0x83, 0xf8, 0x25, 0x51, 0x21, 0xa1, 0xb8, 0x88, 0xb6, 0x08, 0x85, 0xea, 0xea, 0x2e, 0x6c, - 0xfe, 0x71, 0x38, 0x16, 0xb1, 0xcf, 0xd8, 0x67, 0xb0, 0x37, 0x36, 0xd8, 0x59, 0x18, 0x3b, 0xf0, - 0x87, 0x30, 0x66, 0x64, 0x66, 0xa8, 0x50, 0xfa, 0x67, 0xb0, 0xa0, 0x3b, 0x9f, 0x5d, 0x27, 0x40, - 0x95, 0x82, 0xc4, 0x76, 0xef, 0x7d, 0xdf, 0xbb, 0xf7, 0xde, 0x77, 0xef, 0xd9, 0x70, 0x29, 0x34, - 0xb3, 0x21, 0x35, 0x1d, 0x2d, 0x8c, 0x28, 0xa3, 0xa8, 0x21, 0xcd, 0xd6, 0x86, 0xeb, 0xb1, 0x41, - 0x62, 0x69, 0x36, 0xf5, 0xbb, 0x2e, 0x75, 0x69, 0x57, 0xe0, 0x56, 0xf2, 0x52, 0x58, 0xc2, 0x10, - 0xa7, 0x3c, 0xae, 0xb5, 0x1c, 0x92, 0xc8, 0xf7, 0xe2, 0xd8, 0xa3, 0x81, 0xf4, 0xc0, 0x38, 0x24, - 0x76, 0x7e, 0x5e, 0x7b, 0x37, 0x0f, 0x61, 0x2f, 0xc8, 0xf6, 0xf2, 0xbb, 0xd1, 0x35, 0x58, 0xdf, - 0x32, 0x87, 0x43, 0x23, 0x6d, 0x82, 0x2b, 0x60, 0xfd, 0xfc, 0xed, 0x8b, 0x5a, 0x51, 0x44, 0xee, - 0xc6, 0x12, 0xe6, 0xc4, 0x7d, 0x12, 0x38, 0x46, 0xda, 0x9c, 0x9f, 0x22, 0xe6, 0x6e, 0x2c, 0x61, - 0x4e, 0xec, 0x9b, 0x3e, 0x31, 0xd2, 0x66, 0x6d, 0x8a, 0x98, 0xbb, 0xb1, 0x84, 0xd1, 0x43, 0xb8, - 0xb4, 0x57, 0x56, 0x1a, 0x1b, 0x69, 0x53, 0x11, 0xfc, 0xd5, 0x92, 0x3f, 0x81, 0xe2, 0x49, 0x32, - 0x7a, 0x00, 0x17, 0xb7, 0xe9, 0x1b, 0x12, 0x05, 0x66, 0x60, 0xf3, 0x64, 0x0b, 0x22, 0x78, 0xa5, - 0x0c, 0xae, 0x82, 0x78, 0x82, 0xba, 0xf6, 0x11, 0xc0, 0x86, 0x91, 0xee, 0x06, 0x61, 0xc2, 0x50, - 0x1f, 0x36, 0x7a, 0x8e, 0x13, 0x91, 0x38, 0x16, 0x02, 0x2c, 0xea, 0x77, 0x47, 0x47, 0x9d, 0xb9, - 0x6f, 0x47, 0x9d, 0x9b, 0x15, 0xd1, 0x07, 0x59, 0x48, 0xa2, 0x21, 0x71, 0x5c, 0x12, 0x75, 0xad, - 0x24, 0x8a, 0xe8, 0xdb, 0xae, 0x1d, 0x65, 0x21, 0xa3, 0x9a, 0x8c, 0xc5, 0xc5, 0x25, 0x68, 0x15, - 0xd6, 0x7b, 0x3e, 0x4d, 0x02, 0x26, 0x64, 0x52, 0xb0, 0xb4, 0x50, 0x0b, 0xaa, 0xfb, 0xe4, 0x75, - 0x42, 0x02, 0x9b, 0x08, 0x5d, 0x14, 0x5c, 0xda, 0x9b, 0xca, 0xa7, 0xc3, 0xce, 0xdc, 0x5a, 0x0a, - 0x55, 0x23, 0x7d, 0x9e, 0xb0, 0xff, 0x58, 0x95, 0xcc, 0xfc, 0x03, 0x14, 0x43, 0x80, 0xae, 0xc2, - 0x05, 0xa1, 0x8b, 0x9c, 0x86, 0xe5, 0x52, 0x4e, 0xa9, 0x17, 0xce, 0x61, 0xf4, 0xf4, 0xa4, 0xc0, - 0x79, 0x51, 0xe0, 0xad, 0xbf, 0x2f, 0xae, 0x05, 0xd5, 0x6d, 0x33, 0x7e, 0xe6, 0xf9, 0x1e, 0x2b, - 0xa4, 0x29, 0x6c, 0xb4, 0x0c, 0x6b, 0x4f, 0x08, 0x11, 0x93, 0xa1, 0x60, 0x7e, 0x44, 0xbb, 0x50, - 0x79, 0x6c, 0x32, 0x53, 0xbc, 0xf7, 0xa2, 0x7e, 0x4f, 0xea, 0xb2, 0x71, 0x7a, 0x6a, 0xcb, 0x0b, - 0xcc, 0x28, 0xd3, 0x76, 0x48, 0xaa, 0x67, 0x8c, 0xc4, 0x58, 0x5c, 0x21, 0xbb, 0xf7, 0x8a, 0xc1, - 0x46, 0xeb, 0xb0, 0x2e, 0xba, 0xe3, 0xa2, 0xd7, 0x7e, 0xdb, 0xbd, 0xc4, 0xd1, 0x0d, 0xd8, 0xc8, - 0x5f, 0x8a, 0xb7, 0xcf, 0xa9, 0x97, 0x2a, 0xd4, 0x1c, 0xc1, 0x05, 0x63, 0x53, 0xfd, 0x70, 0xd8, - 0x99, 0x13, 0xa9, 0x92, 0xa9, 0x89, 0x9f, 0x59, 0xee, 0xfb, 0x50, 0xe5, 0x81, 0xbd, 0xc8, 0x8d, - 0xe5, 0xfa, 0x5d, 0xd6, 0x2a, 0x5b, 0x5e, 0x60, 0xba, 0xc2, 0xe5, 0xc0, 0x25, 0x57, 0x76, 0x18, - 0x16, 0x1b, 0x39, 0x73, 0x3e, 0x04, 0x15, 0x1e, 0x21, 0x72, 0x9d, 0xc3, 0xe2, 0xcc, 0x7d, 0x42, - 0xf8, 0x5a, 0xee, 0xe3, 0xe7, 0x5f, 0x9f, 0x47, 0x66, 0x7c, 0x05, 0xeb, 0x3a, 0x3d, 0xa3, 0xa6, - 0x1b, 0x50, 0x3d, 0x08, 0x2c, 0x1e, 0x45, 0xff, 0x2c, 0x6a, 0x49, 0xa9, 0xa8, 0xfa, 0x19, 0x94, - 0x91, 0xb3, 0x77, 0xd8, 0x9f, 0x1e, 0xe0, 0x7f, 0xdf, 0xb0, 0x1d, 0xe2, 0xb9, 0x83, 0x62, 0x84, - 0xa5, 0x55, 0x29, 0xf3, 0x3d, 0x98, 0xfc, 0x62, 0x9d, 0x41, 0x9a, 0x2d, 0x78, 0xa1, 0x67, 0xdb, - 0x7c, 0x63, 0x0f, 0x42, 0xc7, 0x64, 0xa4, 0x98, 0xba, 0x15, 0x4d, 0x7c, 0xd8, 0x0d, 0xe2, 0x87, - 0x43, 0x93, 0x11, 0xc9, 0x11, 0x53, 0x00, 0xf0, 0x54, 0xc8, 0x49, 0x25, 0xfa, 0xa3, 0xd1, 0xb8, - 0x0d, 0xbe, 0x8e, 0xdb, 0xe0, 0xfb, 0xb8, 0x0d, 0xbe, 0x1c, 0xb7, 0xc1, 0xe8, 0xb8, 0x0d, 0x5e, - 0x5c, 0x3f, 0xbd, 0x71, 0x96, 0xc6, 0x5d, 0x59, 0x9f, 0x55, 0x17, 0xbf, 0x92, 0x3b, 0x3f, 0x03, - 0x00, 0x00, 0xff, 0xff, 0xac, 0xa5, 0xe3, 0x1c, 0xb1, 0x06, 0x00, 0x00, + // 665 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x55, 0x3b, 0x6f, 0xd4, 0x40, + 0x10, 0xce, 0xe6, 0x9c, 0xbb, 0x63, 0x09, 0x21, 0xac, 0x00, 0x9d, 0xae, 0xb8, 0x43, 0x11, 0x82, + 0xf0, 0x88, 0x0f, 0xf1, 0x2a, 0xd2, 0xa0, 0xbb, 0x20, 0x92, 0x20, 0x14, 0xd0, 0xc6, 0x69, 0xe8, + 0xfc, 0x58, 0x1c, 0x8b, 0xb3, 0xd7, 0xd8, 0x6b, 0xb0, 0x3b, 0x4a, 0x7a, 0x1a, 0xca, 0x14, 0x54, + 0xfc, 0x0a, 0xca, 0x94, 0xd4, 0x14, 0x11, 0x4a, 0x7e, 0x06, 0x0d, 0xda, 0xf1, 0xae, 0xef, 0x38, + 0x20, 0xba, 0x80, 0x44, 0xb7, 0x33, 0xdf, 0xb7, 0x9e, 0x99, 0x6f, 0x66, 0xd6, 0xf8, 0x4c, 0x6c, + 0x17, 0x43, 0x6e, 0x7b, 0x66, 0x9c, 0x70, 0xc1, 0x49, 0x43, 0x99, 0xed, 0x15, 0x3f, 0x10, 0xbb, + 0x99, 0x63, 0xba, 0x3c, 0xec, 0xf9, 0xdc, 0xe7, 0x3d, 0xc0, 0x9d, 0xec, 0x05, 0x58, 0x60, 0xc0, + 0xa9, 0xbc, 0xd7, 0x5e, 0x8c, 0x59, 0x12, 0x06, 0x69, 0x1a, 0xf0, 0x48, 0x79, 0x70, 0x1a, 0x33, + 0xb7, 0x3c, 0x2f, 0x7d, 0x9a, 0xc5, 0xb5, 0x7e, 0x54, 0x90, 0xab, 0xb8, 0xbe, 0x66, 0x0f, 0x87, + 0x56, 0xde, 0x42, 0x97, 0xd0, 0xf2, 0xe9, 0xdb, 0x67, 0x4d, 0x1d, 0xbd, 0x74, 0x53, 0x05, 0x4b, + 0xe2, 0x36, 0x8b, 0x3c, 0x2b, 0x6f, 0xcd, 0x4e, 0x10, 0x4b, 0x37, 0x55, 0xb0, 0x24, 0x6e, 0xd9, + 0x21, 0xb3, 0xf2, 0x56, 0x6d, 0x82, 0x58, 0xba, 0xa9, 0x82, 0xc9, 0x75, 0xdc, 0x78, 0xc6, 0x92, + 0x30, 0xb5, 0xf2, 0x96, 0x01, 0xcc, 0xc5, 0x8a, 0xa9, 0xfc, 0x54, 0x13, 0xc8, 0x65, 0x3c, 0xb7, + 0xce, 0x5f, 0x5b, 0x79, 0x6b, 0x0e, 0x98, 0x0b, 0x15, 0x13, 0xbc, 0xb4, 0x04, 0x65, 0xe8, 0x01, + 0x87, 0x1c, 0xeb, 0x13, 0xa1, 0x4b, 0x37, 0x55, 0x30, 0x59, 0xc1, 0xcd, 0x9d, 0xc8, 0x29, 0xa9, + 0x0d, 0xa0, 0x9e, 0xab, 0xa8, 0x1a, 0xa0, 0x15, 0x65, 0xe9, 0x3d, 0xc2, 0x0d, 0x2b, 0xdf, 0x8c, + 0xe2, 0x4c, 0x90, 0x2d, 0xdc, 0xe8, 0x7b, 0x5e, 0xc2, 0xd2, 0x14, 0x14, 0x9b, 0x1f, 0xdc, 0xdd, + 0x3f, 0xe8, 0xce, 0x7c, 0x3d, 0xe8, 0xde, 0x1c, 0x6b, 0xcf, 0x6e, 0x11, 0xb3, 0x64, 0xc8, 0x3c, + 0x9f, 0x25, 0x3d, 0x27, 0x4b, 0x12, 0xfe, 0xa6, 0xe7, 0x26, 0x45, 0x2c, 0xb8, 0xa9, 0xee, 0x52, + 0xfd, 0x11, 0x72, 0x11, 0xd7, 0xfb, 0x21, 0xcf, 0x22, 0x01, 0xba, 0x1a, 0x54, 0x59, 0xa4, 0x8d, + 0x9b, 0xdb, 0xec, 0x55, 0xc6, 0x22, 0x97, 0x81, 0x90, 0x06, 0xad, 0xec, 0x55, 0xe3, 0xc3, 0x5e, + 0x77, 0x66, 0x29, 0xc7, 0x4d, 0x2b, 0x7f, 0x9a, 0x89, 0xff, 0x98, 0x95, 0x8a, 0xfc, 0x1d, 0xe9, + 0xa9, 0x21, 0x57, 0xf0, 0x1c, 0xe8, 0xa2, 0xc6, 0x67, 0xd4, 0x42, 0xa5, 0x17, 0x2d, 0x61, 0xf2, + 0x78, 0x94, 0xe0, 0x2c, 0x24, 0x78, 0xeb, 0xef, 0x93, 0x6b, 0xe3, 0xe6, 0xba, 0x9d, 0x3e, 0x09, + 0xc2, 0x40, 0x68, 0x69, 0xb4, 0x4d, 0x16, 0x71, 0xed, 0x11, 0x63, 0x30, 0x50, 0x06, 0x95, 0x47, + 0xb2, 0x89, 0x8d, 0x87, 0xb6, 0xb0, 0x61, 0x72, 0xe6, 0x07, 0xf7, 0x94, 0x2e, 0x2b, 0xc7, 0x87, + 0x76, 0x82, 0xc8, 0x4e, 0x0a, 0x73, 0x83, 0xe5, 0x83, 0x42, 0xb0, 0x94, 0xc2, 0x27, 0x54, 0xf5, + 0x81, 0xde, 0x04, 0xb2, 0x8c, 0xeb, 0x50, 0x9d, 0x14, 0xbd, 0xf6, 0xdb, 0xea, 0x15, 0x4e, 0x6e, + 0xe0, 0x46, 0xd9, 0x29, 0x59, 0x7e, 0xed, 0xa7, 0x79, 0xd3, 0x3d, 0xa4, 0x9a, 0xb1, 0xda, 0x7c, + 0xb7, 0xd7, 0x9d, 0x81, 0x50, 0xbc, 0x5a, 0x91, 0xa9, 0x85, 0xbe, 0x8f, 0x9b, 0xf2, 0x4a, 0x3f, + 0xf1, 0x53, 0xb5, 0xa9, 0xe7, 0xcd, 0xb1, 0x97, 0x40, 0x63, 0x03, 0x43, 0x0a, 0x41, 0x2b, 0xae, + 0xaa, 0x2d, 0xd6, 0xcb, 0x3b, 0x75, 0x3c, 0x82, 0x0d, 0x79, 0x03, 0x62, 0x9d, 0xa2, 0x70, 0x96, + 0x3e, 0x90, 0xbc, 0x56, 0xfa, 0xe4, 0xf9, 0xd7, 0xc6, 0xa8, 0x88, 0x2f, 0xf5, 0xce, 0x9e, 0x40, + 0xcd, 0xd1, 0xfa, 0xf2, 0x3f, 0xcb, 0x59, 0x51, 0xc6, 0xf4, 0xfc, 0x88, 0x46, 0x8b, 0x3f, 0x75, + 0x85, 0x5b, 0x93, 0xa3, 0xfb, 0xef, 0xbb, 0xb5, 0xc1, 0x02, 0x7f, 0x57, 0x0f, 0xaf, 0xb2, 0xc6, + 0xd2, 0x7c, 0x8b, 0xd4, 0x73, 0x77, 0x02, 0x4d, 0xd6, 0xf0, 0x42, 0xdf, 0x75, 0xe5, 0x92, 0xee, + 0xc4, 0x9e, 0x2d, 0x98, 0x1e, 0xb4, 0x0b, 0x26, 0xbc, 0xfa, 0x16, 0x0b, 0xe3, 0xa1, 0x2d, 0x98, + 0xe2, 0x40, 0xfb, 0x11, 0x9d, 0xb8, 0x32, 0x4a, 0x61, 0xf0, 0x60, 0xff, 0xb0, 0x83, 0xbe, 0x1c, + 0x76, 0xd0, 0xb7, 0xc3, 0x0e, 0xfa, 0x7c, 0xd4, 0x41, 0xfb, 0x47, 0x1d, 0xf4, 0xfc, 0xda, 0xf1, + 0x15, 0x8b, 0x3c, 0xed, 0xa9, 0xfc, 0x9c, 0x3a, 0xfc, 0x67, 0xee, 0xfc, 0x08, 0x00, 0x00, 0xff, + 0xff, 0xf8, 0x92, 0x62, 0xb5, 0xce, 0x06, 0x00, 0x00, } diff --git a/txs/payload/permission_tx.go b/txs/payload/perms_tx.go similarity index 53% rename from txs/payload/permission_tx.go rename to txs/payload/perms_tx.go index d22984f93..5dbff87e7 100644 --- a/txs/payload/permission_tx.go +++ b/txs/payload/perms_tx.go @@ -8,7 +8,7 @@ import ( "github.com/hyperledger/burrow/permission" ) -func NewPermissionsTx(st state.AccountGetter, from crypto.PublicKey, args permission.PermArgs) (*PermissionsTx, error) { +func NewPermsTx(st state.AccountGetter, from crypto.PublicKey, args permission.PermArgs) (*PermsTx, error) { addr := from.Address() acc, err := st.GetAccount(addr) if err != nil { @@ -19,30 +19,36 @@ func NewPermissionsTx(st state.AccountGetter, from crypto.PublicKey, args permis } sequence := acc.Sequence() + 1 - return NewPermissionsTxWithSequence(from, args, sequence), nil + return NewPermsTxWithSequence(from, args, sequence), nil } -func NewPermissionsTxWithSequence(from crypto.PublicKey, args permission.PermArgs, sequence uint64) *PermissionsTx { +func NewPermsTxWithSequence(from crypto.PublicKey, args permission.PermArgs, sequence uint64) *PermsTx { input := &TxInput{ Address: from.Address(), Amount: 1, // NOTE: amounts can't be 0 ... Sequence: sequence, } - return &PermissionsTx{ + return &PermsTx{ Input: input, PermArgs: args, } } -func (tx *PermissionsTx) Type() Type { +func (tx *PermsTx) Type() Type { return TypePermissions } -func (tx *PermissionsTx) GetInputs() []*TxInput { +func (tx *PermsTx) GetInputs() []*TxInput { return []*TxInput{tx.Input} } -func (tx *PermissionsTx) String() string { - return fmt.Sprintf("PermissionsTx{%v -> %v}", tx.Input, tx.PermArgs) +func (tx *PermsTx) String() string { + return fmt.Sprintf("PermsTx{%v -> %v}", tx.Input, tx.PermArgs) +} + +func (tx *PermsTx) Any() *Any { + return &Any{ + PermsTx: tx, + } } diff --git a/txs/payload/send_tx.go b/txs/payload/send_tx.go index f83fcf953..c67babef8 100644 --- a/txs/payload/send_tx.go +++ b/txs/payload/send_tx.go @@ -55,3 +55,9 @@ func (tx *SendTx) AddOutput(addr crypto.Address, amt uint64) error { }) return nil } + +func (tx *SendTx) Any() *Any { + return &Any{ + SendTx: tx, + } +} diff --git a/txs/payload/unbond_tx.go b/txs/payload/unbond_tx.go index c6fe036fa..c295cfad4 100644 --- a/txs/payload/unbond_tx.go +++ b/txs/payload/unbond_tx.go @@ -24,3 +24,9 @@ func (tx *UnbondTx) GetInputs() []*TxInput { func (tx *UnbondTx) String() string { return fmt.Sprintf("UnbondTx{%v -> %s,%v}", tx.Input, tx.Address, tx.Height) } + +func (tx *UnbondTx) Any() *Any { + return &Any{ + UnbondTx: tx, + } +} diff --git a/txs/tx.go b/txs/tx.go index ee773c3cc..45b15ca85 100644 --- a/txs/tx.go +++ b/txs/tx.go @@ -103,7 +103,7 @@ func (tx *Tx) UnmarshalJSON(data []byte) error { } tx.ChainID = w.ChainID // Now we know the Type we can deserialise the Payload - tx.Payload = payload.New(w.Type) + tx.Payload, err = payload.New(w.Type) return json.Unmarshal(w.Payload, tx.Payload) } diff --git a/txs/tx_test.go b/txs/tx_test.go index 4716bc28d..b3d0d4a41 100644 --- a/txs/tx_test.go +++ b/txs/tx_test.go @@ -153,7 +153,7 @@ func TestUnbondTxSignable(t *testing.T) { } func TestPermissionsTxSignable(t *testing.T) { - permsTx := &payload.PermissionsTx{ + permsTx := &payload.PermsTx{ Input: &payload.TxInput{ Address: makePrivateAccount("input1").Address(), Amount: 12345, @@ -191,7 +191,7 @@ func TestTxWrapper_MarshalJSON(t *testing.T) { func TestNewPermissionsTxWithSequence(t *testing.T) { privateAccount := makePrivateAccount("shhhhh") args := permission.SetBaseArgs(privateAccount.PublicKey().Address(), permission.HasRole, true) - permTx := payload.NewPermissionsTxWithSequence(privateAccount.PublicKey(), args, 1) + permTx := payload.NewPermsTxWithSequence(privateAccount.PublicKey(), args, 1) testTxMarshalJSON(t, permTx) testTxSignVerify(t, permTx) } diff --git a/util/logging/cmd/main.go b/util/logging/cmd/main.go index cc6960b6b..d0b8acda2 100644 --- a/util/logging/cmd/main.go +++ b/util/logging/cmd/main.go @@ -17,7 +17,7 @@ package main import ( "fmt" - . "github.com/hyperledger/burrow/logging/config" + . "github.com/hyperledger/burrow/logging/logconfig" ) // Dump an example logging configuration From 3ad3c1271ee8a7cc7058cac3882e7049c9bd7ca5 Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Mon, 23 Jul 2018 13:08:32 +0100 Subject: [PATCH 18/28] Use Tendermint default address and fix up integration test helper to use routable local address Signed-off-by: Silas Davis --- consensus/tendermint/config.go | 9 +++++---- integration/integration.go | 1 + rpc/config.go | 14 ++++++++++---- 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/consensus/tendermint/config.go b/consensus/tendermint/config.go index d736e4baa..92acbf9c8 100644 --- a/consensus/tendermint/config.go +++ b/consensus/tendermint/config.go @@ -20,10 +20,11 @@ type BurrowTendermintConfig struct { } func DefaultBurrowTendermintConfig() *BurrowTendermintConfig { - //tmDefaultConfig := tm_config.DefaultConfig() + tmDefaultConfig := tm_config.DefaultConfig() return &BurrowTendermintConfig{ - ListenAddress: "tcp://127.0.0.1:26656", //stmDefaultConfig.P2P.ListenAddress, - TendermintRoot: ".burrow", + ListenAddress: tmDefaultConfig.P2P.ListenAddress, + ExternalAddress: tmDefaultConfig.P2P.ExternalAddress, + TendermintRoot: ".burrow", } } @@ -39,7 +40,7 @@ func (btc *BurrowTendermintConfig) TendermintConfig() *tm_config.Config { conf.P2P.Seeds = btc.Seeds conf.P2P.PersistentPeers = btc.PersistentPeers conf.P2P.ListenAddress = btc.ListenAddress - conf.P2P.ExternalAddress = btc.ListenAddress + conf.P2P.ExternalAddress = btc.ExternalAddress conf.Moniker = btc.Moniker // Unfortunately this stops metrics from being used at all conf.Instrumentation.Prometheus = false diff --git a/integration/integration.go b/integration/integration.go index ae3cf0ba6..692675215 100644 --- a/integration/integration.go +++ b/integration/integration.go @@ -163,6 +163,7 @@ func NewTestConfig(genesisDoc *genesis.GenesisDoc) *config.BurrowConfig { cnf.Tendermint.Moniker = name cnf.Tendermint.TendermintRoot = fmt.Sprintf(".burrow_%s", name) cnf.Tendermint.ListenAddress = GetTCPLocalAddress() + cnf.Tendermint.ExternalAddress = cnf.Tendermint.ListenAddress cnf.RPC.GRPC.ListenAddress = GetLocalAddress() cnf.RPC.Metrics.ListenAddress = GetTCPLocalAddress() cnf.RPC.TM.ListenAddress = GetTCPLocalAddress() diff --git a/rpc/config.go b/rpc/config.go index 44acb5555..23bfbdbb7 100644 --- a/rpc/config.go +++ b/rpc/config.go @@ -1,5 +1,11 @@ package rpc +import "fmt" + +// 'localhost' gets interpreted as ipv6 +// TODO: revisit this +const localhost = "127.0.0.1" + type RPCConfig struct { TM *ServerConfig `json:",omitempty" toml:",omitempty"` Profiler *ServerConfig `json:",omitempty" toml:",omitempty"` @@ -41,28 +47,28 @@ func DefaultRPCConfig() *RPCConfig { func DefaultTMConfig() *ServerConfig { return &ServerConfig{ Enabled: true, - ListenAddress: "tcp://localhost:26658", + ListenAddress: fmt.Sprintf("tcp://%s:26658", localhost), } } func DefaultGRPCConfig() *ServerConfig { return &ServerConfig{ Enabled: true, - ListenAddress: "localhost:10997", + ListenAddress: fmt.Sprintf("%s:10997", localhost), } } func DefaultProfilerConfig() *ServerConfig { return &ServerConfig{ Enabled: false, - ListenAddress: "tcp://localhost:6060", + ListenAddress: fmt.Sprintf("tcp://%s:6060", localhost), } } func DefaultMetricsConfig() *MetricsConfig { return &MetricsConfig{ Enabled: false, - ListenAddress: "tcp://localhost:9102", + ListenAddress: fmt.Sprintf("tcp://%s:9102", localhost), MetricsPath: "/metrics", BlockSampleSize: 100, } From 80eba03ff375b8a5001530593e45f1be4171e33b Mon Sep 17 00:00:00 2001 From: Sean Young Date: Mon, 23 Jul 2018 13:23:14 +0100 Subject: [PATCH 19/28] Add 0.20.0 changelog Signed-off-by: Sean Young --- CHANGELOG.md | 22 ++++++++++++++++++++++ NOTES.md | 43 +++++++++++-------------------------------- project/history.go | 23 +++++++++++++++++++++++ 3 files changed, 56 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 991e0ed13..b5b1250ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,26 @@ # Hyperledger Burrow Changelog +## Version 0.20.0 +This is a major (pre-1.0.0) release that brings upgrades, and new grpc services. + +#### Breaking changes +- Address format has been changed (by Tendermint and we have followed suite) - conversion is possible but simpler to regenerated keys +- JSON-RPC interface has been removed +- burrow-client has been removed +- rpc/TM methods for events and broadcast have been removed + +#### Features +- Tendermint 0.24.4 +- GovTx GRPC service. The validator set can be now be changed. +- Enhanced GRPC services: NameReg, Transaction index, blocks service +- Events GRPC service +- Transaction Service can set value transferred + +#### Improvements +- The output of "burrow keys export" can be templated + +#### Bug fixes +- Fixed panic on nil bounds for blocks service + ## Version 0.19.0 This is a major (pre-1.0.0) release that brings upgrades, safety improvements, cloud configuration, and GRPC endpoints to Burrow. diff --git a/NOTES.md b/NOTES.md index 1b1f11821..ee42b8ae3 100644 --- a/NOTES.md +++ b/NOTES.md @@ -1,39 +1,18 @@ -This is a major (pre-1.0.0) release that brings upgrades, safety improvements, cloud configuration, and GRPC endpoints to Burrow. - #### Breaking changes -In addition to breaking changes associated with Tendermint (see their changelog): -- State checkpointing logic has changed which has we load based on blockchain -- Event format has changed over rpc/V0 see execution/events/ package -- On-disk keys format has change from monax-keys to be more standard burrow keys - Address format has been changed (by Tendermint and we have followed suite) - conversion is possible but simpler to regenerated keys +- JSON-RPC interface has been removed +- burrow-client has been removed +- rpc/TM methods for events and broadcast have been removed #### Features -- Tendermint 0.21.0 -- Implemented EVM opcodes: REVERT, INVALID, SHL, SAR, SHR, RETURNDATACOPY, RETURNDATASIZE -- Add config templating with burrow configure --config-template-in --config-out -- Add config templates for kubernetes -- Integrate monax-keys as internal (default) or standalone keys service, key gen exposed over CLI -- Use GRPC for keys -- Add GRPC service for Transactor and Events -- Store ExecutionEvent by height and index in merkle tree state -- Add historical query for all time with GetEvents -- Add streaming GRPC service for ExecutionEvents with query language over tags -- Add metadata to ExecutionEvents -- Add BlockExplorer CLI for forensics -- Expose reason for REVERT -- Add last_block_info healthcheck endpoint to rpc/TM -- +- Tendermint 0.24.4 +- GovTx GRPC service. The validator set can be now be changed. +- Enhanced GRPC services: NameReg, Transaction index, blocks service +- Events GRPC service +- Transaction Service can set value transferred + #### Improvements -- Implement checkpointing when saving application and blockchain state in commit - interrupted commit rolls burrow back to last block whereon it can catch up using Tendermint -- Maintain separate read-only tree in state so that long-running RPC request cannot block writes -- Improve state safety -- Improved input account server-side-signing -- Increase subscription reap time on rpc/V0 to 20 seconds -- Reorganise CLI -- Improve internal serialisation -- Refactor and modularise execution logic +- The output of "burrow keys export" can be templated #### Bug fixes -- Fix address generation from bytes mismatch - - +- Fixed panic on nil bounds for blocks service diff --git a/project/history.go b/project/history.go index 36432076c..d461c6edf 100644 --- a/project/history.go +++ b/project/history.go @@ -28,6 +28,29 @@ func FullVersion() string { // To cut a new release add a release to the front of this slice then run the // release tagging script: ./scripts/tag_release.sh var History relic.ImmutableHistory = relic.NewHistory("Hyperledger Burrow").MustDeclareReleases( + "0.20.0", + `This is a major (pre-1.0.0) release that brings upgrades, safety improvements, cloud configuration, and GRPC endpoints to Burrow. + +#### Breaking changes +- Address format has been changed (by Tendermint and we have followed suite) - conversion is possible but simpler to regenerated keys +- JSON-RPC interface has been removed +- burrow-client has been removed +- rpc/TM methods for events and broadcast have been removed + +#### Features +- Tendermint 0.24.4 +- GovTx GRPC service. The validator set can be now be changed. +- Enhanced GRPC services: NameReg, Transaction index, blocks service +- Events GRPC service +- Transaction Service can set value transferred + +#### Improvements +- The output of "burrow keys export" can be templated + +#### Bug fixes +- Fixed panic on nil bounds for blocks service + +`, "0.19.0", `This is a major (pre-1.0.0) release that brings upgrades, safety improvements, cloud configuration, and GRPC endpoints to Burrow. From face4ace4fca4a74d9f2a88672e2ce2fb6b85b82 Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Mon, 23 Jul 2018 13:31:56 +0100 Subject: [PATCH 20/28] Check ChainID in Verify! Signed-off-by: Silas Davis --- execution/execution.go | 2 +- txs/envelope.go | 6 +++++- txs/tx_test.go | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/execution/execution.go b/execution/execution.go index 2fe05f133..63328d291 100644 --- a/execution/execution.go +++ b/execution/execution.go @@ -184,7 +184,7 @@ func (exe *executor) Execute(txEnv *txs.Envelope) (txe *exec.TxExecution, err er logger.TraceMsg("Executing transaction", "tx", txEnv.String()) // Verify transaction signature against inputs - err = txEnv.Verify(exe.stateCache) + err = txEnv.Verify(exe.stateCache, exe.blockchain.ChainID()) if err != nil { return nil, err } diff --git a/txs/envelope.go b/txs/envelope.go index 06ed3832a..817f26e58 100644 --- a/txs/envelope.go +++ b/txs/envelope.go @@ -77,12 +77,16 @@ func (txEnv *Envelope) Validate() error { // Verifies the validity of the Signatories' Signatures in the Envelope. The Signatories must // appear in the same order as the inputs as returned by Tx.GetInputs(). -func (txEnv *Envelope) Verify(getter state.AccountGetter) error { +func (txEnv *Envelope) Verify(getter state.AccountGetter, chainID string) error { err := txEnv.Validate() if err != nil { return err } errPrefix := fmt.Sprintf("could not verify transaction %X", txEnv.Tx.Hash()) + if txEnv.Tx.ChainID != chainID { + return fmt.Errorf("%s: ChainID in envelope is %s but receiving chain has ID %s", + errPrefix, txEnv.Tx.ChainID, chainID) + } inputs := txEnv.Tx.GetInputs() if len(inputs) != len(txEnv.Signatories) { return fmt.Errorf("%s: number of inputs (= %v) should equal number of signatories (= %v)", diff --git a/txs/tx_test.go b/txs/tx_test.go index b3d0d4a41..9fbc93cb4 100644 --- a/txs/tx_test.go +++ b/txs/tx_test.go @@ -216,5 +216,5 @@ func testTxSignVerify(t *testing.T, tx payload.Payload) { } txEnv := Enclose(chainID, tx) require.NoError(t, txEnv.Sign(signers...), "Error signing tx: %s", debug.Stack()) - require.NoError(t, txEnv.Verify(nil), "Error verifying tx: %s", debug.Stack()) + require.NoError(t, txEnv.Verify(nil, chainID), "Error verifying tx: %s", debug.Stack()) } From 1ebdd15f3febc20639003f62f53b154879dfa68b Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Mon, 23 Jul 2018 15:38:37 +0100 Subject: [PATCH 21/28] Unify Status with LastBlockInfo, removing the later and add Status call to QueryServer for use by both and others. Status now serves as healthcheck with blockWithin parameter Signed-off-by: Silas Davis --- acm/validator/validator.pb.go | 29 +- consensus/tendermint/node_view.go | 29 +- consensus/tendermint/tendermint.go | 21 +- consensus/tendermint/tendermint.pb.go | 609 ++++++++++++++++++++ core/kernel.go | 5 +- integration/rpcquery/query_server_test.go | 19 + protobuf/rpc.proto | 31 + protobuf/rpcquery.proto | 8 + protobuf/tendermint.proto | 25 + rpc/metrics/export.go | 2 +- rpc/metrics/server.go | 2 +- rpc/result.go | 24 +- rpc/result_test.go | 17 - rpc/rpc.pb.go | 652 ++++++++++++++++++++++ rpc/rpcquery/query_server.go | 5 + rpc/rpcquery/rpcquery.pb.go | 251 +++++++-- rpc/service.go | 50 +- rpc/tm/methods.go | 8 +- 18 files changed, 1631 insertions(+), 156 deletions(-) create mode 100644 consensus/tendermint/tendermint.pb.go create mode 100644 protobuf/rpc.proto create mode 100644 protobuf/tendermint.proto create mode 100644 rpc/rpc.pb.go diff --git a/acm/validator/validator.pb.go b/acm/validator/validator.pb.go index 93c8b77d7..b15639c0e 100644 --- a/acm/validator/validator.pb.go +++ b/acm/validator/validator.pb.go @@ -17,7 +17,6 @@ import golang_proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import _ "github.com/gogo/protobuf/gogoproto" -import _ "github.com/hyperledger/burrow/permission" import crypto "github.com/hyperledger/burrow/crypto" import github_com_hyperledger_burrow_crypto "github.com/hyperledger/burrow/crypto" @@ -385,21 +384,21 @@ func init() { proto.RegisterFile("validator.proto", fileDescriptorValidator) } func init() { golang_proto.RegisterFile("validator.proto", fileDescriptorValidator) } var fileDescriptorValidator = []byte{ - // 255 bytes of a gzipped FileDescriptorProto + // 242 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x2f, 0x4b, 0xcc, 0xc9, 0x4c, 0x49, 0x2c, 0xc9, 0x2f, 0xd2, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x84, 0x0b, 0x48, 0xe9, 0xa6, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0xa7, 0xe7, 0xa7, 0xe7, - 0xeb, 0x83, 0x55, 0x24, 0x95, 0xa6, 0x81, 0x79, 0x60, 0x0e, 0x98, 0x05, 0xd1, 0x29, 0x25, 0x50, - 0x90, 0x5a, 0x94, 0x9b, 0x59, 0x5c, 0x9c, 0x99, 0x9f, 0x07, 0x15, 0xe1, 0x49, 0x2e, 0xaa, 0x2c, - 0x28, 0x81, 0xca, 0x2b, 0xad, 0x62, 0xe4, 0xe2, 0x0c, 0x83, 0x19, 0x2e, 0xe4, 0xc5, 0xc5, 0xee, - 0x98, 0x92, 0x52, 0x94, 0x5a, 0x5c, 0x2c, 0xc1, 0xa8, 0xc0, 0xa8, 0xc1, 0xe3, 0x64, 0x70, 0xeb, - 0x9e, 0xbc, 0x0e, 0x92, 0x8d, 0x19, 0x95, 0x05, 0xa9, 0x45, 0x39, 0xa9, 0x29, 0xe9, 0xa9, 0x45, - 0xfa, 0x49, 0xa5, 0x45, 0x45, 0xf9, 0xe5, 0xfa, 0x50, 0xe3, 0xa0, 0xfa, 0x82, 0x60, 0x06, 0x08, - 0x99, 0x72, 0x71, 0x06, 0x94, 0x26, 0xe5, 0x64, 0x26, 0x7b, 0xa7, 0x56, 0x4a, 0x30, 0x29, 0x30, - 0x6a, 0x70, 0x1b, 0x09, 0xea, 0x41, 0x15, 0xc3, 0x25, 0x9c, 0x58, 0x4e, 0xdc, 0x93, 0x67, 0x08, - 0x42, 0xa8, 0x14, 0x12, 0xe1, 0x62, 0x0d, 0xc8, 0x2f, 0x4f, 0x2d, 0x92, 0x60, 0x56, 0x60, 0xd4, - 0x60, 0x09, 0x82, 0x70, 0xac, 0x58, 0x66, 0x2c, 0x90, 0x67, 0x70, 0x72, 0x3c, 0xf1, 0x48, 0x8e, - 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x0f, 0x3c, 0x96, 0x63, 0x3c, 0xf1, 0x58, - 0x8e, 0x31, 0x4a, 0x1b, 0xbf, 0xfb, 0x12, 0x93, 0x73, 0xf5, 0xe1, 0xc1, 0x97, 0xc4, 0x06, 0xf6, - 0xb6, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x1c, 0xca, 0xd9, 0x6f, 0x63, 0x01, 0x00, 0x00, + 0xeb, 0x83, 0x55, 0x24, 0x95, 0xa6, 0x81, 0x79, 0x60, 0x0e, 0x98, 0x05, 0xd1, 0x29, 0xc5, 0x93, + 0x5c, 0x54, 0x59, 0x50, 0x02, 0xe5, 0x29, 0xad, 0x62, 0xe4, 0xe2, 0x0c, 0x83, 0x19, 0x25, 0xe4, + 0xc5, 0xc5, 0xee, 0x98, 0x92, 0x52, 0x94, 0x5a, 0x5c, 0x2c, 0xc1, 0xa8, 0xc0, 0xa8, 0xc1, 0xe3, + 0x64, 0x70, 0xeb, 0x9e, 0xbc, 0x0e, 0x92, 0xf9, 0x19, 0x95, 0x05, 0xa9, 0x45, 0x39, 0xa9, 0x29, + 0xe9, 0xa9, 0x45, 0xfa, 0x49, 0xa5, 0x45, 0x45, 0xf9, 0xe5, 0xfa, 0x50, 0xe3, 0xa0, 0xfa, 0x82, + 0x60, 0x06, 0x08, 0x99, 0x72, 0x71, 0x06, 0x94, 0x26, 0xe5, 0x64, 0x26, 0x7b, 0xa7, 0x56, 0x4a, + 0x30, 0x29, 0x30, 0x6a, 0x70, 0x1b, 0x09, 0xea, 0x41, 0x15, 0xc3, 0x25, 0x9c, 0x58, 0x4e, 0xdc, + 0x93, 0x67, 0x08, 0x42, 0xa8, 0x14, 0x12, 0xe1, 0x62, 0x0d, 0xc8, 0x2f, 0x4f, 0x2d, 0x92, 0x60, + 0x56, 0x60, 0xd4, 0x60, 0x09, 0x82, 0x70, 0xac, 0x58, 0x66, 0x2c, 0x90, 0x67, 0x70, 0x72, 0x3c, + 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x0f, 0x3c, 0x96, 0x63, + 0x3c, 0xf1, 0x58, 0x8e, 0x31, 0x4a, 0x1b, 0xbf, 0xfb, 0x12, 0x93, 0x73, 0xf5, 0xe1, 0x81, 0x95, + 0xc4, 0x06, 0xf6, 0xb6, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x5d, 0xe5, 0x4a, 0x65, 0x51, 0x01, + 0x00, 0x00, } diff --git a/consensus/tendermint/node_view.go b/consensus/tendermint/node_view.go index 62a50085d..023533e14 100644 --- a/consensus/tendermint/node_view.go +++ b/consensus/tendermint/node_view.go @@ -7,32 +7,35 @@ import ( "github.com/hyperledger/burrow/txs" "github.com/tendermint/tendermint/consensus" ctypes "github.com/tendermint/tendermint/consensus/types" - tmCrypto "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" ) type NodeView struct { - tmNode *Node - txDecoder txs.Decoder + tmNode *Node + validatorPublicKey crypto.PublicKey + txDecoder txs.Decoder } -func NewNodeView(tmNode *Node, txDecoder txs.Decoder) *NodeView { - return &NodeView{ - tmNode: tmNode, - txDecoder: txDecoder, +func NewNodeView(tmNode *Node, txDecoder txs.Decoder) (*NodeView, error) { + publicKey, err := crypto.PublicKeyFromTendermintPubKey(tmNode.PrivValidator().GetPubKey()) + if err != nil { + return nil, err } + return &NodeView{ + validatorPublicKey: publicKey, + tmNode: tmNode, + txDecoder: txDecoder, + }, nil } -func (nv *NodeView) PrivValidatorPublicKey() (crypto.PublicKey, error) { - pub := nv.tmNode.PrivValidator().GetPubKey().(tmCrypto.PubKeyEd25519) - - return crypto.PublicKeyFromBytes(pub[:], crypto.CurveTypeEd25519) +func (nv *NodeView) ValidatorPublicKey() crypto.PublicKey { + return nv.validatorPublicKey } -func (nv *NodeView) NodeInfo() p2p.NodeInfo { - return nv.tmNode.NodeInfo() +func (nv *NodeView) NodeInfo() *NodeInfo { + return NewNodeInfo(nv.tmNode.NodeInfo()) } func (nv *NodeView) IsListening() bool { diff --git a/consensus/tendermint/tendermint.go b/consensus/tendermint/tendermint.go index 0122f580e..573265ee6 100644 --- a/consensus/tendermint/tendermint.go +++ b/consensus/tendermint/tendermint.go @@ -4,7 +4,9 @@ import ( "os" "path" + "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/consensus/tendermint/abci" + "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/genesis" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" @@ -12,6 +14,7 @@ import ( tmCrypto "github.com/tendermint/tendermint/crypto" dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/node" + "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/proxy" tmTypes "github.com/tendermint/tendermint/types" ) @@ -90,13 +93,15 @@ func DeriveGenesisDoc(burrowGenesisDoc *genesis.GenesisDoc) *tmTypes.GenesisDoc } } -func NewBlockEvent(message interface{}) *tmTypes.EventDataNewBlock { - tmEventData, ok := message.(tmTypes.TMEventData) - if ok { - eventDataNewBlock, ok := tmEventData.(tmTypes.EventDataNewBlock) - if ok { - return &eventDataNewBlock - } +func NewNodeInfo(ni p2p.NodeInfo) *NodeInfo { + address, _ := crypto.AddressFromHexString(string(ni.ID)) + return &NodeInfo{ + ID: address, + Moniker: ni.Moniker, + ListenAddress: ni.ListenAddr, + Version: ni.Version, + Channels: binary.HexBytes(ni.Channels), + Network: ni.Network, + Other: ni.Other, } - return nil } diff --git a/consensus/tendermint/tendermint.pb.go b/consensus/tendermint/tendermint.pb.go new file mode 100644 index 000000000..6dd3e449a --- /dev/null +++ b/consensus/tendermint/tendermint.pb.go @@ -0,0 +1,609 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: tendermint.proto + +/* + Package tendermint is a generated protocol buffer package. + + It is generated from these files: + tendermint.proto + + It has these top-level messages: + NodeInfo +*/ +package tendermint + +import proto "github.com/gogo/protobuf/proto" +import golang_proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" +import _ "github.com/gogo/protobuf/gogoproto" +import _ "github.com/hyperledger/burrow/crypto" + +import github_com_hyperledger_burrow_crypto "github.com/hyperledger/burrow/crypto" +import github_com_hyperledger_burrow_binary "github.com/hyperledger/burrow/binary" + +import io "io" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = golang_proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package + +type NodeInfo struct { + ID github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,1,opt,name=ID,proto3,customtype=github.com/hyperledger/burrow/crypto.Address" json:"ID"` + ListenAddress string `protobuf:"bytes,2,opt,name=ListenAddress,proto3" json:"ListenAddress,omitempty"` + Network string `protobuf:"bytes,3,opt,name=Network,proto3" json:"Network,omitempty"` + Version string `protobuf:"bytes,4,opt,name=Version,proto3" json:"Version,omitempty"` + Channels github_com_hyperledger_burrow_binary.HexBytes `protobuf:"bytes,5,opt,name=Channels,proto3,customtype=github.com/hyperledger/burrow/binary.HexBytes" json:"Channels"` + Moniker string `protobuf:"bytes,6,opt,name=Moniker,proto3" json:"Moniker,omitempty"` + Other []string `protobuf:"bytes,7,rep,name=Other" json:"Other,omitempty"` +} + +func (m *NodeInfo) Reset() { *m = NodeInfo{} } +func (m *NodeInfo) String() string { return proto.CompactTextString(m) } +func (*NodeInfo) ProtoMessage() {} +func (*NodeInfo) Descriptor() ([]byte, []int) { return fileDescriptorTendermint, []int{0} } + +func (m *NodeInfo) GetListenAddress() string { + if m != nil { + return m.ListenAddress + } + return "" +} + +func (m *NodeInfo) GetNetwork() string { + if m != nil { + return m.Network + } + return "" +} + +func (m *NodeInfo) GetVersion() string { + if m != nil { + return m.Version + } + return "" +} + +func (m *NodeInfo) GetMoniker() string { + if m != nil { + return m.Moniker + } + return "" +} + +func (m *NodeInfo) GetOther() []string { + if m != nil { + return m.Other + } + return nil +} + +func (*NodeInfo) XXX_MessageName() string { + return "tendermint.NodeInfo" +} +func init() { + proto.RegisterType((*NodeInfo)(nil), "tendermint.NodeInfo") + golang_proto.RegisterType((*NodeInfo)(nil), "tendermint.NodeInfo") +} +func (m *NodeInfo) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *NodeInfo) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + dAtA[i] = 0xa + i++ + i = encodeVarintTendermint(dAtA, i, uint64(m.ID.Size())) + n1, err := m.ID.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n1 + if len(m.ListenAddress) > 0 { + dAtA[i] = 0x12 + i++ + i = encodeVarintTendermint(dAtA, i, uint64(len(m.ListenAddress))) + i += copy(dAtA[i:], m.ListenAddress) + } + if len(m.Network) > 0 { + dAtA[i] = 0x1a + i++ + i = encodeVarintTendermint(dAtA, i, uint64(len(m.Network))) + i += copy(dAtA[i:], m.Network) + } + if len(m.Version) > 0 { + dAtA[i] = 0x22 + i++ + i = encodeVarintTendermint(dAtA, i, uint64(len(m.Version))) + i += copy(dAtA[i:], m.Version) + } + dAtA[i] = 0x2a + i++ + i = encodeVarintTendermint(dAtA, i, uint64(m.Channels.Size())) + n2, err := m.Channels.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n2 + if len(m.Moniker) > 0 { + dAtA[i] = 0x32 + i++ + i = encodeVarintTendermint(dAtA, i, uint64(len(m.Moniker))) + i += copy(dAtA[i:], m.Moniker) + } + if len(m.Other) > 0 { + for _, s := range m.Other { + dAtA[i] = 0x3a + i++ + l = len(s) + for l >= 1<<7 { + dAtA[i] = uint8(uint64(l)&0x7f | 0x80) + l >>= 7 + i++ + } + dAtA[i] = uint8(l) + i++ + i += copy(dAtA[i:], s) + } + } + return i, nil +} + +func encodeVarintTendermint(dAtA []byte, offset int, v uint64) int { + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return offset + 1 +} +func (m *NodeInfo) Size() (n int) { + var l int + _ = l + l = m.ID.Size() + n += 1 + l + sovTendermint(uint64(l)) + l = len(m.ListenAddress) + if l > 0 { + n += 1 + l + sovTendermint(uint64(l)) + } + l = len(m.Network) + if l > 0 { + n += 1 + l + sovTendermint(uint64(l)) + } + l = len(m.Version) + if l > 0 { + n += 1 + l + sovTendermint(uint64(l)) + } + l = m.Channels.Size() + n += 1 + l + sovTendermint(uint64(l)) + l = len(m.Moniker) + if l > 0 { + n += 1 + l + sovTendermint(uint64(l)) + } + if len(m.Other) > 0 { + for _, s := range m.Other { + l = len(s) + n += 1 + l + sovTendermint(uint64(l)) + } + } + return n +} + +func sovTendermint(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n +} +func sozTendermint(x uint64) (n int) { + return sovTendermint(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *NodeInfo) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTendermint + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: NodeInfo: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: NodeInfo: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTendermint + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTendermint + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ListenAddress", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTendermint + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTendermint + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ListenAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Network", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTendermint + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTendermint + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Network = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTendermint + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTendermint + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Version = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Channels", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTendermint + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTendermint + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Channels.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Moniker", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTendermint + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTendermint + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Moniker = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Other", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTendermint + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTendermint + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Other = append(m.Other, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTendermint(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTendermint + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTendermint(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTendermint + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTendermint + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTendermint + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + iNdEx += length + if length < 0 { + return 0, ErrInvalidLengthTendermint + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTendermint + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipTendermint(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} + +var ( + ErrInvalidLengthTendermint = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTendermint = fmt.Errorf("proto: integer overflow") +) + +func init() { proto.RegisterFile("tendermint.proto", fileDescriptorTendermint) } +func init() { golang_proto.RegisterFile("tendermint.proto", fileDescriptorTendermint) } + +var fileDescriptorTendermint = []byte{ + // 321 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x91, 0xbd, 0x4e, 0x3a, 0x41, + 0x14, 0xc5, 0xff, 0xb3, 0xfc, 0xf9, 0x9a, 0x60, 0x62, 0x36, 0x16, 0x13, 0x8a, 0x85, 0x18, 0x0b, + 0x0a, 0x61, 0x13, 0x3f, 0x1e, 0x40, 0xa4, 0x80, 0x44, 0x31, 0x6e, 0x61, 0x61, 0xc7, 0xb2, 0x97, + 0xdd, 0x0d, 0x30, 0x97, 0xdc, 0x99, 0x0d, 0xee, 0x43, 0xf9, 0x0e, 0x96, 0x94, 0xd6, 0x16, 0xc4, + 0xc0, 0x8b, 0x18, 0x66, 0x57, 0xd1, 0x46, 0xbb, 0xf9, 0x9d, 0x33, 0x73, 0xee, 0xc9, 0x5c, 0x7e, + 0xa8, 0x41, 0x06, 0x40, 0xf3, 0x58, 0xea, 0xce, 0x82, 0x50, 0xa3, 0xcd, 0xf7, 0x4a, 0xbd, 0x1d, + 0xc6, 0x3a, 0x4a, 0xfc, 0xce, 0x18, 0xe7, 0x6e, 0x88, 0x21, 0xba, 0xe6, 0x8a, 0x9f, 0x4c, 0x0c, + 0x19, 0x30, 0xa7, 0xec, 0x69, 0xbd, 0x36, 0xa6, 0x74, 0xa1, 0x73, 0x3a, 0x7e, 0xb6, 0x78, 0x65, + 0x88, 0x01, 0x0c, 0xe4, 0x04, 0xed, 0x1e, 0xb7, 0x06, 0x3d, 0xc1, 0x9a, 0xac, 0x55, 0xeb, 0x5e, + 0xac, 0xd6, 0x8d, 0x7f, 0x6f, 0xeb, 0xc6, 0xe9, 0xb7, 0xf4, 0x28, 0x5d, 0x00, 0xcd, 0x20, 0x08, + 0x81, 0x5c, 0x3f, 0x21, 0xc2, 0xa5, 0x9b, 0x87, 0x5d, 0x05, 0x01, 0x81, 0x52, 0x9e, 0x35, 0xe8, + 0xd9, 0x27, 0xfc, 0xe0, 0x26, 0x56, 0x1a, 0x64, 0x2e, 0x0a, 0xab, 0xc9, 0x5a, 0x55, 0xef, 0xa7, + 0x68, 0x0b, 0x5e, 0x1e, 0x82, 0x5e, 0x22, 0x4d, 0x45, 0xc1, 0xf8, 0x9f, 0xb8, 0x73, 0x1e, 0x80, + 0x54, 0x8c, 0x52, 0xfc, 0xcf, 0x9c, 0x1c, 0xed, 0x7b, 0x5e, 0xb9, 0x8e, 0x46, 0x52, 0xc2, 0x4c, + 0x89, 0xa2, 0x69, 0x79, 0x99, 0xb7, 0x6c, 0xff, 0xde, 0xd2, 0x8f, 0xe5, 0x88, 0xd2, 0x4e, 0x1f, + 0x9e, 0xba, 0xa9, 0x06, 0xe5, 0x7d, 0xc5, 0xec, 0x86, 0xdd, 0xa2, 0x8c, 0xa7, 0x40, 0xa2, 0x94, + 0x0d, 0xcb, 0xd1, 0x3e, 0xe2, 0xc5, 0x3b, 0x1d, 0x01, 0x89, 0x72, 0xb3, 0xd0, 0xaa, 0x7a, 0x19, + 0x74, 0xfb, 0xab, 0x8d, 0xc3, 0x5e, 0x37, 0x0e, 0x7b, 0xdf, 0x38, 0xec, 0x65, 0xeb, 0xb0, 0xd5, + 0xd6, 0x61, 0x8f, 0x67, 0x7f, 0x7c, 0x12, 0x4a, 0x05, 0x52, 0x25, 0xca, 0xdd, 0xaf, 0xcd, 0x2f, + 0x99, 0x05, 0x9c, 0x7f, 0x04, 0x00, 0x00, 0xff, 0xff, 0x29, 0x50, 0xa8, 0x1b, 0xdd, 0x01, 0x00, + 0x00, +} diff --git a/core/kernel.go b/core/kernel.go index 46854844a..28ff55a72 100644 --- a/core/kernel.go +++ b/core/kernel.go @@ -126,7 +126,10 @@ func NewKernel(ctx context.Context, keyClient keys.KeyClient, privValidator tmTy nameRegState := kern.State accountState := kern.State - nodeView := tendermint.NewNodeView(kern.Node, txCodec) + nodeView, err := tendermint.NewNodeView(kern.Node, txCodec) + if err != nil { + return nil, err + } kern.Service = rpc.NewService(accountState, nameRegState, kern.Blockchain, nodeView, kern.Logger) kern.Launchers = []process.Launcher{ diff --git a/integration/rpcquery/query_server_test.go b/integration/rpcquery/query_server_test.go index 05bb7e858..adef77c72 100644 --- a/integration/rpcquery/query_server_test.go +++ b/integration/rpcquery/query_server_test.go @@ -18,6 +18,25 @@ import ( "github.com/stretchr/testify/require" ) +func TestStatus(t *testing.T) { + cli := rpctest.NewQueryClient(t, testConfig.RPC.GRPC.ListenAddress) + stat, err := cli.Status(context.Background(), &rpcquery.StatusParam{}) + require.NoError(t, err) + assert.Equal(t, rpctest.PrivateAccounts[0].PublicKey(), stat.PublicKey) + assert.Equal(t, rpctest.GenesisDoc.ChainID(), stat.ChainID) + for i := 0; i < 3; i++ { + // Unless we get lucky this is an error + _, err = cli.Status(context.Background(), &rpcquery.StatusParam{ + BlockWithin: "1ns", + }) + if err != nil { + break + } + } + require.Error(t, err) + assert.Contains(t, err.Error(), "no block committed within") +} + func TestGetAccount(t *testing.T) { cli := rpctest.NewQueryClient(t, testConfig.RPC.GRPC.ListenAddress) ca, err := cli.GetAccount(context.Background(), &rpcquery.GetAccountParam{ diff --git a/protobuf/rpc.proto b/protobuf/rpc.proto new file mode 100644 index 000000000..88f78933e --- /dev/null +++ b/protobuf/rpc.proto @@ -0,0 +1,31 @@ +// Needed to proto2 rather than proto3 to get pointer field for PermArg +syntax = 'proto3'; + +option go_package = "github.com/hyperledger/burrow/rpc"; + +import "github.com/gogo/protobuf/gogoproto/gogo.proto"; +import "crypto.proto"; +import "tendermint.proto"; +import "google/protobuf/timestamp.proto"; + +package rpc; + +option (gogoproto.marshaler_all) = true; +option (gogoproto.unmarshaler_all) = true; +option (gogoproto.sizer_all) = true; +option (gogoproto.goproto_registration) = true; +option (gogoproto.messagename_all) = true; + +message ResultStatus { + string ChainID = 1; + bytes GenesisHash = 4 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false]; + tendermint.NodeInfo NodeInfo = 2; + string NodeVersion = 3; + crypto.PublicKey PublicKey = 5 [(gogoproto.nullable) = false]; + bytes LatestBlockHash = 6 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false]; + uint64 LatestBlockHeight = 7; + // Unix + + google.protobuf.Timestamp LatestBlockTime = 8 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; +} + diff --git a/protobuf/rpcquery.proto b/protobuf/rpcquery.proto index fc8b66262..8981b7b7f 100644 --- a/protobuf/rpcquery.proto +++ b/protobuf/rpcquery.proto @@ -9,6 +9,7 @@ import "github.com/gogo/protobuf/gogoproto/gogo.proto"; import "names.proto"; import "acm.proto"; import "validator.proto"; +import "rpc.proto"; option (gogoproto.marshaler_all) = true; option (gogoproto.unmarshaler_all) = true; @@ -17,13 +18,20 @@ option (gogoproto.goproto_registration) = true; option (gogoproto.messagename_all) = true; service Query { + rpc Status (StatusParam) returns (rpc.ResultStatus); rpc GetAccount (GetAccountParam) returns (acm.ConcreteAccount); rpc ListAccounts (ListAccountsParam) returns (stream acm.ConcreteAccount); + rpc GetName (GetNameParam) returns (names.Entry); rpc ListNames (ListNamesParam) returns (stream names.Entry); + rpc GetValidatorSet (GetValidatorSetParam) returns (ValidatorSet); } +message StatusParam { + string BlockWithin = 1; +} + message GetAccountParam { bytes Address = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false]; } diff --git a/protobuf/tendermint.proto b/protobuf/tendermint.proto new file mode 100644 index 000000000..cef3f0c38 --- /dev/null +++ b/protobuf/tendermint.proto @@ -0,0 +1,25 @@ +// Needed to proto2 rather than proto3 to get pointer field for PermArg +syntax = 'proto3'; + +option go_package = "github.com/hyperledger/burrow/consensus/tendermint"; + +import "github.com/gogo/protobuf/gogoproto/gogo.proto"; +import "crypto.proto"; + +package tendermint; + +option (gogoproto.marshaler_all) = true; +option (gogoproto.unmarshaler_all) = true; +option (gogoproto.sizer_all) = true; +option (gogoproto.goproto_registration) = true; +option (gogoproto.messagename_all) = true; + +message NodeInfo { + bytes ID = 1 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address", (gogoproto.nullable) = false]; + string ListenAddress = 2; + string Network = 3; + string Version = 4; + bytes Channels = 5 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false]; + string Moniker = 6; + repeated string Other = 7; +} diff --git a/rpc/metrics/export.go b/rpc/metrics/export.go index 51e105c96..d64a8577e 100644 --- a/rpc/metrics/export.go +++ b/rpc/metrics/export.go @@ -53,7 +53,7 @@ func (e *Exporter) gatherData() error { // Get status func (e *Exporter) getStatus() error { - res, err := e.service.Status() + res, err := e.service.Status("") if err != nil { return err } diff --git a/rpc/metrics/server.go b/rpc/metrics/server.go index 5eab0754c..273996ddd 100644 --- a/rpc/metrics/server.go +++ b/rpc/metrics/server.go @@ -55,7 +55,7 @@ func StartServer(service *rpc.Service, pattern, listenAddress string, blockSampl logger *logging.Logger) (*http.Server, error) { // instantiate metrics and variables we do not expect to change during runtime - chainStatus, _ := service.Status() + chainStatus, _ := service.Status("") exporter := Exporter{ burrowMetrics: AddMetrics(), datum: &Datum{}, diff --git a/rpc/result.go b/rpc/result.go index 35d21892f..a7ca72edb 100644 --- a/rpc/result.go +++ b/rpc/result.go @@ -15,18 +15,16 @@ package rpc import ( - "time" - "github.com/hyperledger/burrow/acm" "github.com/hyperledger/burrow/acm/validator" "github.com/hyperledger/burrow/binary" + "github.com/hyperledger/burrow/consensus/tendermint" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/execution/names" "github.com/hyperledger/burrow/genesis" "github.com/hyperledger/burrow/txs" "github.com/tendermint/go-amino" consensusTypes "github.com/tendermint/tendermint/consensus/types" - "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/rpc/core/types" tmTypes "github.com/tendermint/tendermint/types" ) @@ -94,22 +92,6 @@ func (b *Block) UnmarshalJSON(data []byte) (err error) { return aminoCodec.UnmarshalJSON(data, &b.Block) } -type ResultStatus struct { - NodeInfo p2p.NodeInfo - GenesisHash binary.HexBytes - PublicKey crypto.PublicKey - LatestBlockHash binary.HexBytes - LatestBlockHeight uint64 - LatestBlockTime int64 - NodeVersion string -} - -type ResultLastBlockInfo struct { - LastBlockHeight uint64 - LastBlockTime time.Time - LastBlockHash binary.HexBytes -} - type ResultChainId struct { ChainName string ChainId string @@ -126,12 +108,12 @@ type ResultUnsubscribe struct { } type Peer struct { - NodeInfo p2p.NodeInfo + NodeInfo *tendermint.NodeInfo IsOutbound bool } type ResultNetInfo struct { - ThisNode p2p.NodeInfo + ThisNode *tendermint.NodeInfo Listening bool Listeners []string Peers []*Peer diff --git a/rpc/result_test.go b/rpc/result_test.go index 9c66f47ad..78af66633 100644 --- a/rpc/result_test.go +++ b/rpc/result_test.go @@ -18,12 +18,7 @@ import ( "encoding/json" "testing" - "time" - - "fmt" - "github.com/hyperledger/burrow/acm" - "github.com/hyperledger/burrow/binary" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/consensus/types" @@ -87,15 +82,3 @@ func TestResultDumpConsensusState(t *testing.T) { require.NoError(t, err) assert.Equal(t, string(bs), string(bsOut)) } - -func TestResultLastBlockInfo(t *testing.T) { - res := &ResultLastBlockInfo{ - LastBlockTime: time.Now(), - LastBlockHash: binary.HexBytes{3, 4, 5, 6}, - LastBlockHeight: 2343, - } - bs, err := json.Marshal(res) - require.NoError(t, err) - fmt.Println(string(bs)) - -} diff --git a/rpc/rpc.pb.go b/rpc/rpc.pb.go new file mode 100644 index 000000000..8836266a7 --- /dev/null +++ b/rpc/rpc.pb.go @@ -0,0 +1,652 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: rpc.proto + +/* + Package rpc is a generated protocol buffer package. + + It is generated from these files: + rpc.proto + + It has these top-level messages: + ResultStatus +*/ +package rpc + +import proto "github.com/gogo/protobuf/proto" +import golang_proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" +import _ "github.com/gogo/protobuf/gogoproto" +import crypto "github.com/hyperledger/burrow/crypto" +import tendermint "github.com/hyperledger/burrow/consensus/tendermint" +import _ "github.com/golang/protobuf/ptypes/timestamp" + +import github_com_hyperledger_burrow_binary "github.com/hyperledger/burrow/binary" +import time "time" + +import types "github.com/gogo/protobuf/types" + +import io "io" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = golang_proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf +var _ = time.Kitchen + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package + +type ResultStatus struct { + ChainID string `protobuf:"bytes,1,opt,name=ChainID,proto3" json:"ChainID,omitempty"` + GenesisHash github_com_hyperledger_burrow_binary.HexBytes `protobuf:"bytes,4,opt,name=GenesisHash,proto3,customtype=github.com/hyperledger/burrow/binary.HexBytes" json:"GenesisHash"` + NodeInfo *tendermint.NodeInfo `protobuf:"bytes,2,opt,name=NodeInfo" json:"NodeInfo,omitempty"` + NodeVersion string `protobuf:"bytes,3,opt,name=NodeVersion,proto3" json:"NodeVersion,omitempty"` + PublicKey crypto.PublicKey `protobuf:"bytes,5,opt,name=PublicKey" json:"PublicKey"` + LatestBlockHash github_com_hyperledger_burrow_binary.HexBytes `protobuf:"bytes,6,opt,name=LatestBlockHash,proto3,customtype=github.com/hyperledger/burrow/binary.HexBytes" json:"LatestBlockHash"` + LatestBlockHeight uint64 `protobuf:"varint,7,opt,name=LatestBlockHeight,proto3" json:"LatestBlockHeight,omitempty"` + LatestBlockTime time.Time `protobuf:"bytes,8,opt,name=LatestBlockTime,stdtime" json:"LatestBlockTime"` +} + +func (m *ResultStatus) Reset() { *m = ResultStatus{} } +func (m *ResultStatus) String() string { return proto.CompactTextString(m) } +func (*ResultStatus) ProtoMessage() {} +func (*ResultStatus) Descriptor() ([]byte, []int) { return fileDescriptorRpc, []int{0} } + +func (m *ResultStatus) GetChainID() string { + if m != nil { + return m.ChainID + } + return "" +} + +func (m *ResultStatus) GetNodeInfo() *tendermint.NodeInfo { + if m != nil { + return m.NodeInfo + } + return nil +} + +func (m *ResultStatus) GetNodeVersion() string { + if m != nil { + return m.NodeVersion + } + return "" +} + +func (m *ResultStatus) GetPublicKey() crypto.PublicKey { + if m != nil { + return m.PublicKey + } + return crypto.PublicKey{} +} + +func (m *ResultStatus) GetLatestBlockHeight() uint64 { + if m != nil { + return m.LatestBlockHeight + } + return 0 +} + +func (m *ResultStatus) GetLatestBlockTime() time.Time { + if m != nil { + return m.LatestBlockTime + } + return time.Time{} +} + +func (*ResultStatus) XXX_MessageName() string { + return "rpc.ResultStatus" +} +func init() { + proto.RegisterType((*ResultStatus)(nil), "rpc.ResultStatus") + golang_proto.RegisterType((*ResultStatus)(nil), "rpc.ResultStatus") +} +func (m *ResultStatus) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResultStatus) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.ChainID) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintRpc(dAtA, i, uint64(len(m.ChainID))) + i += copy(dAtA[i:], m.ChainID) + } + if m.NodeInfo != nil { + dAtA[i] = 0x12 + i++ + i = encodeVarintRpc(dAtA, i, uint64(m.NodeInfo.Size())) + n1, err := m.NodeInfo.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n1 + } + if len(m.NodeVersion) > 0 { + dAtA[i] = 0x1a + i++ + i = encodeVarintRpc(dAtA, i, uint64(len(m.NodeVersion))) + i += copy(dAtA[i:], m.NodeVersion) + } + dAtA[i] = 0x22 + i++ + i = encodeVarintRpc(dAtA, i, uint64(m.GenesisHash.Size())) + n2, err := m.GenesisHash.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n2 + dAtA[i] = 0x2a + i++ + i = encodeVarintRpc(dAtA, i, uint64(m.PublicKey.Size())) + n3, err := m.PublicKey.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n3 + dAtA[i] = 0x32 + i++ + i = encodeVarintRpc(dAtA, i, uint64(m.LatestBlockHash.Size())) + n4, err := m.LatestBlockHash.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n4 + if m.LatestBlockHeight != 0 { + dAtA[i] = 0x38 + i++ + i = encodeVarintRpc(dAtA, i, uint64(m.LatestBlockHeight)) + } + dAtA[i] = 0x42 + i++ + i = encodeVarintRpc(dAtA, i, uint64(types.SizeOfStdTime(m.LatestBlockTime))) + n5, err := types.StdTimeMarshalTo(m.LatestBlockTime, dAtA[i:]) + if err != nil { + return 0, err + } + i += n5 + return i, nil +} + +func encodeVarintRpc(dAtA []byte, offset int, v uint64) int { + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return offset + 1 +} +func (m *ResultStatus) Size() (n int) { + var l int + _ = l + l = len(m.ChainID) + if l > 0 { + n += 1 + l + sovRpc(uint64(l)) + } + if m.NodeInfo != nil { + l = m.NodeInfo.Size() + n += 1 + l + sovRpc(uint64(l)) + } + l = len(m.NodeVersion) + if l > 0 { + n += 1 + l + sovRpc(uint64(l)) + } + l = m.GenesisHash.Size() + n += 1 + l + sovRpc(uint64(l)) + l = m.PublicKey.Size() + n += 1 + l + sovRpc(uint64(l)) + l = m.LatestBlockHash.Size() + n += 1 + l + sovRpc(uint64(l)) + if m.LatestBlockHeight != 0 { + n += 1 + sovRpc(uint64(m.LatestBlockHeight)) + } + l = types.SizeOfStdTime(m.LatestBlockTime) + n += 1 + l + sovRpc(uint64(l)) + return n +} + +func sovRpc(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n +} +func sozRpc(x uint64) (n int) { + return sovRpc(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *ResultStatus) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpc + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ResultStatus: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ResultStatus: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ChainID", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpc + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthRpc + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ChainID = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NodeInfo", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpc + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthRpc + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.NodeInfo == nil { + m.NodeInfo = &tendermint.NodeInfo{} + } + if err := m.NodeInfo.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NodeVersion", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpc + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthRpc + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.NodeVersion = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field GenesisHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpc + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthRpc + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.GenesisHash.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PublicKey", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpc + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthRpc + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.PublicKey.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LatestBlockHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpc + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthRpc + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.LatestBlockHash.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 7: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field LatestBlockHeight", wireType) + } + m.LatestBlockHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpc + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.LatestBlockHeight |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LatestBlockTime", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpc + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthRpc + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := types.StdTimeUnmarshal(&m.LatestBlockTime, dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipRpc(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthRpc + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipRpc(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowRpc + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowRpc + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowRpc + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + iNdEx += length + if length < 0 { + return 0, ErrInvalidLengthRpc + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowRpc + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipRpc(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} + +var ( + ErrInvalidLengthRpc = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowRpc = fmt.Errorf("proto: integer overflow") +) + +func init() { proto.RegisterFile("rpc.proto", fileDescriptorRpc) } +func init() { golang_proto.RegisterFile("rpc.proto", fileDescriptorRpc) } + +var fileDescriptorRpc = []byte{ + // 397 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x51, 0x41, 0xcf, 0xd2, 0x40, + 0x10, 0x75, 0x05, 0xbf, 0x0f, 0x16, 0x12, 0x65, 0xe3, 0x61, 0xc3, 0xa1, 0xad, 0x9e, 0x7a, 0xd0, + 0xad, 0xd1, 0x10, 0xef, 0xd5, 0x44, 0x88, 0x86, 0x98, 0x4a, 0x34, 0xf1, 0x62, 0xda, 0x32, 0xb4, + 0x1b, 0xdb, 0x6e, 0xb3, 0xbb, 0x8d, 0xf6, 0x5f, 0xf8, 0x93, 0x3c, 0x72, 0xf4, 0xec, 0x01, 0x0d, + 0x1c, 0xfd, 0x13, 0x86, 0x85, 0x42, 0xc5, 0xc4, 0x8b, 0xb7, 0x79, 0xf3, 0x66, 0xde, 0xbc, 0x99, + 0xc1, 0x7d, 0x59, 0xc6, 0xac, 0x94, 0x42, 0x0b, 0xd2, 0x91, 0x65, 0x3c, 0x7e, 0x98, 0x70, 0x9d, + 0x56, 0x11, 0x8b, 0x45, 0xee, 0x25, 0x22, 0x11, 0x9e, 0xe1, 0xa2, 0x6a, 0x65, 0x90, 0x01, 0x26, + 0x3a, 0xf4, 0x8c, 0x87, 0xb1, 0xac, 0x4b, 0xdd, 0xa0, 0x3b, 0x1a, 0x8a, 0x25, 0xc8, 0x9c, 0x17, + 0xfa, 0x98, 0xb1, 0x13, 0x21, 0x92, 0x0c, 0xce, 0x2a, 0x9a, 0xe7, 0xa0, 0x74, 0x98, 0x97, 0x87, + 0x82, 0xfb, 0xbf, 0x3a, 0x78, 0x18, 0x80, 0xaa, 0x32, 0xfd, 0x46, 0x87, 0xba, 0x52, 0x84, 0xe2, + 0xeb, 0x67, 0x69, 0xc8, 0x8b, 0xd9, 0x73, 0x8a, 0x1c, 0xe4, 0xf6, 0x83, 0x06, 0x92, 0x47, 0xb8, + 0x37, 0x17, 0x4b, 0x98, 0x15, 0x2b, 0x41, 0x6f, 0x3a, 0xc8, 0x1d, 0x3c, 0xbe, 0xcb, 0x5a, 0x03, + 0x1b, 0x2e, 0x38, 0x55, 0x11, 0x07, 0x0f, 0xf6, 0xf1, 0x5b, 0x90, 0x8a, 0x8b, 0x82, 0x76, 0x8c, + 0x5e, 0x3b, 0x45, 0xde, 0xe1, 0xc1, 0x0b, 0x28, 0x40, 0x71, 0x35, 0x0d, 0x55, 0x4a, 0xbb, 0x0e, + 0x72, 0x87, 0xfe, 0x64, 0xbd, 0xb1, 0x6f, 0x7c, 0xdf, 0xd8, 0xed, 0x5b, 0xa4, 0x75, 0x09, 0x32, + 0x83, 0x65, 0x02, 0xd2, 0x8b, 0x2a, 0x29, 0xc5, 0x27, 0x2f, 0xe2, 0x45, 0x28, 0x6b, 0x36, 0x85, + 0xcf, 0x7e, 0xad, 0x41, 0x05, 0x6d, 0x25, 0x32, 0xc1, 0xfd, 0xd7, 0x55, 0x94, 0xf1, 0xf8, 0x25, + 0xd4, 0xf4, 0x96, 0x71, 0x3b, 0x62, 0xc7, 0x63, 0x9d, 0x08, 0xbf, 0xbb, 0x9f, 0x14, 0x9c, 0x2b, + 0xc9, 0x07, 0x7c, 0xfb, 0x55, 0xa8, 0x41, 0x69, 0x3f, 0x13, 0xf1, 0x47, 0xe3, 0xe9, 0xea, 0x7f, + 0x3c, 0x5d, 0xaa, 0x91, 0x07, 0x78, 0xd4, 0x4e, 0x01, 0x4f, 0x52, 0x4d, 0xaf, 0x1d, 0xe4, 0x76, + 0x83, 0xbf, 0x09, 0x32, 0xff, 0xc3, 0xce, 0x82, 0xe7, 0x40, 0x7b, 0x66, 0x97, 0x31, 0x3b, 0x3c, + 0x96, 0x35, 0x8f, 0x65, 0x8b, 0xe6, 0xb1, 0x7e, 0x6f, 0x6f, 0xf5, 0xcb, 0x0f, 0x1b, 0x05, 0x97, + 0xcd, 0xfe, 0xd3, 0xf5, 0xd6, 0x42, 0xdf, 0xb6, 0x16, 0xfa, 0xb9, 0xb5, 0xd0, 0xd7, 0x9d, 0x85, + 0xd6, 0x3b, 0x0b, 0xbd, 0xbf, 0xf7, 0xef, 0x9d, 0x64, 0x19, 0x47, 0x57, 0x66, 0xce, 0x93, 0xdf, + 0x01, 0x00, 0x00, 0xff, 0xff, 0x84, 0x6f, 0xc9, 0xec, 0xaf, 0x02, 0x00, 0x00, +} diff --git a/rpc/rpcquery/query_server.go b/rpc/rpcquery/query_server.go index debdc05b5..45f2a54e2 100644 --- a/rpc/rpcquery/query_server.go +++ b/rpc/rpcquery/query_server.go @@ -10,6 +10,7 @@ import ( "github.com/hyperledger/burrow/event/query" "github.com/hyperledger/burrow/execution/names" "github.com/hyperledger/burrow/logging" + "github.com/hyperledger/burrow/rpc" ) type queryServer struct { @@ -33,6 +34,10 @@ func NewQueryServer(state state.IterableReader, nameReg names.IterableReader, bl } } +func (qs *queryServer) Status(ctx context.Context, param *StatusParam) (*rpc.ResultStatus, error) { + return rpc.Status(qs.blockchain, qs.nodeView, param.BlockWithin) +} + // Account state func (qs *queryServer) GetAccount(ctx context.Context, param *GetAccountParam) (*acm.ConcreteAccount, error) { diff --git a/rpc/rpcquery/rpcquery.pb.go b/rpc/rpcquery/rpcquery.pb.go index ec9b81710..120b2df0b 100644 --- a/rpc/rpcquery/rpcquery.pb.go +++ b/rpc/rpcquery/rpcquery.pb.go @@ -8,6 +8,7 @@ rpcquery.proto It has these top-level messages: + StatusParam GetAccountParam ListAccountsParam GetNameParam @@ -26,6 +27,7 @@ import _ "github.com/gogo/protobuf/gogoproto" import names "github.com/hyperledger/burrow/execution/names" import acm "github.com/hyperledger/burrow/acm" import validator "github.com/hyperledger/burrow/acm/validator" +import rpc "github.com/hyperledger/burrow/rpc" import github_com_hyperledger_burrow_crypto "github.com/hyperledger/burrow/crypto" @@ -46,6 +48,26 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package +type StatusParam struct { + BlockWithin string `protobuf:"bytes,1,opt,name=BlockWithin,proto3" json:"BlockWithin,omitempty"` +} + +func (m *StatusParam) Reset() { *m = StatusParam{} } +func (m *StatusParam) String() string { return proto.CompactTextString(m) } +func (*StatusParam) ProtoMessage() {} +func (*StatusParam) Descriptor() ([]byte, []int) { return fileDescriptorRpcquery, []int{0} } + +func (m *StatusParam) GetBlockWithin() string { + if m != nil { + return m.BlockWithin + } + return "" +} + +func (*StatusParam) XXX_MessageName() string { + return "rpcquery.StatusParam" +} + type GetAccountParam struct { Address github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,1,opt,name=Address,proto3,customtype=github.com/hyperledger/burrow/crypto.Address" json:"Address"` } @@ -53,7 +75,7 @@ type GetAccountParam struct { func (m *GetAccountParam) Reset() { *m = GetAccountParam{} } func (m *GetAccountParam) String() string { return proto.CompactTextString(m) } func (*GetAccountParam) ProtoMessage() {} -func (*GetAccountParam) Descriptor() ([]byte, []int) { return fileDescriptorRpcquery, []int{0} } +func (*GetAccountParam) Descriptor() ([]byte, []int) { return fileDescriptorRpcquery, []int{1} } func (*GetAccountParam) XXX_MessageName() string { return "rpcquery.GetAccountParam" @@ -66,7 +88,7 @@ type ListAccountsParam struct { func (m *ListAccountsParam) Reset() { *m = ListAccountsParam{} } func (m *ListAccountsParam) String() string { return proto.CompactTextString(m) } func (*ListAccountsParam) ProtoMessage() {} -func (*ListAccountsParam) Descriptor() ([]byte, []int) { return fileDescriptorRpcquery, []int{1} } +func (*ListAccountsParam) Descriptor() ([]byte, []int) { return fileDescriptorRpcquery, []int{2} } func (m *ListAccountsParam) GetQuery() string { if m != nil { @@ -86,7 +108,7 @@ type GetNameParam struct { func (m *GetNameParam) Reset() { *m = GetNameParam{} } func (m *GetNameParam) String() string { return proto.CompactTextString(m) } func (*GetNameParam) ProtoMessage() {} -func (*GetNameParam) Descriptor() ([]byte, []int) { return fileDescriptorRpcquery, []int{2} } +func (*GetNameParam) Descriptor() ([]byte, []int) { return fileDescriptorRpcquery, []int{3} } func (m *GetNameParam) GetName() string { if m != nil { @@ -106,7 +128,7 @@ type ListNamesParam struct { func (m *ListNamesParam) Reset() { *m = ListNamesParam{} } func (m *ListNamesParam) String() string { return proto.CompactTextString(m) } func (*ListNamesParam) ProtoMessage() {} -func (*ListNamesParam) Descriptor() ([]byte, []int) { return fileDescriptorRpcquery, []int{3} } +func (*ListNamesParam) Descriptor() ([]byte, []int) { return fileDescriptorRpcquery, []int{4} } func (m *ListNamesParam) GetQuery() string { if m != nil { @@ -126,7 +148,7 @@ type GetValidatorSetParam struct { func (m *GetValidatorSetParam) Reset() { *m = GetValidatorSetParam{} } func (m *GetValidatorSetParam) String() string { return proto.CompactTextString(m) } func (*GetValidatorSetParam) ProtoMessage() {} -func (*GetValidatorSetParam) Descriptor() ([]byte, []int) { return fileDescriptorRpcquery, []int{4} } +func (*GetValidatorSetParam) Descriptor() ([]byte, []int) { return fileDescriptorRpcquery, []int{5} } func (m *GetValidatorSetParam) GetIncludeHistory() bool { if m != nil { @@ -148,7 +170,7 @@ type ValidatorSet struct { func (m *ValidatorSet) Reset() { *m = ValidatorSet{} } func (m *ValidatorSet) String() string { return proto.CompactTextString(m) } func (*ValidatorSet) ProtoMessage() {} -func (*ValidatorSet) Descriptor() ([]byte, []int) { return fileDescriptorRpcquery, []int{5} } +func (*ValidatorSet) Descriptor() ([]byte, []int) { return fileDescriptorRpcquery, []int{6} } func (m *ValidatorSet) GetHeight() uint64 { if m != nil { @@ -182,7 +204,7 @@ type ValidatorSetDeltas struct { func (m *ValidatorSetDeltas) Reset() { *m = ValidatorSetDeltas{} } func (m *ValidatorSetDeltas) String() string { return proto.CompactTextString(m) } func (*ValidatorSetDeltas) ProtoMessage() {} -func (*ValidatorSetDeltas) Descriptor() ([]byte, []int) { return fileDescriptorRpcquery, []int{6} } +func (*ValidatorSetDeltas) Descriptor() ([]byte, []int) { return fileDescriptorRpcquery, []int{7} } func (m *ValidatorSetDeltas) GetValidators() []*validator.Validator { if m != nil { @@ -195,6 +217,8 @@ func (*ValidatorSetDeltas) XXX_MessageName() string { return "rpcquery.ValidatorSetDeltas" } func init() { + proto.RegisterType((*StatusParam)(nil), "rpcquery.StatusParam") + golang_proto.RegisterType((*StatusParam)(nil), "rpcquery.StatusParam") proto.RegisterType((*GetAccountParam)(nil), "rpcquery.GetAccountParam") golang_proto.RegisterType((*GetAccountParam)(nil), "rpcquery.GetAccountParam") proto.RegisterType((*ListAccountsParam)(nil), "rpcquery.ListAccountsParam") @@ -222,6 +246,7 @@ const _ = grpc.SupportPackageIsVersion4 // Client API for Query service type QueryClient interface { + Status(ctx context.Context, in *StatusParam, opts ...grpc.CallOption) (*rpc.ResultStatus, error) GetAccount(ctx context.Context, in *GetAccountParam, opts ...grpc.CallOption) (*acm.ConcreteAccount, error) ListAccounts(ctx context.Context, in *ListAccountsParam, opts ...grpc.CallOption) (Query_ListAccountsClient, error) GetName(ctx context.Context, in *GetNameParam, opts ...grpc.CallOption) (*names.Entry, error) @@ -237,6 +262,15 @@ func NewQueryClient(cc *grpc.ClientConn) QueryClient { return &queryClient{cc} } +func (c *queryClient) Status(ctx context.Context, in *StatusParam, opts ...grpc.CallOption) (*rpc.ResultStatus, error) { + out := new(rpc.ResultStatus) + err := grpc.Invoke(ctx, "/rpcquery.Query/Status", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *queryClient) GetAccount(ctx context.Context, in *GetAccountParam, opts ...grpc.CallOption) (*acm.ConcreteAccount, error) { out := new(acm.ConcreteAccount) err := grpc.Invoke(ctx, "/rpcquery.Query/GetAccount", in, out, c.cc, opts...) @@ -331,6 +365,7 @@ func (c *queryClient) GetValidatorSet(ctx context.Context, in *GetValidatorSetPa // Server API for Query service type QueryServer interface { + Status(context.Context, *StatusParam) (*rpc.ResultStatus, error) GetAccount(context.Context, *GetAccountParam) (*acm.ConcreteAccount, error) ListAccounts(*ListAccountsParam, Query_ListAccountsServer) error GetName(context.Context, *GetNameParam) (*names.Entry, error) @@ -342,6 +377,24 @@ func RegisterQueryServer(s *grpc.Server, srv QueryServer) { s.RegisterService(&_Query_serviceDesc, srv) } +func _Query_Status_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(StatusParam) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).Status(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/rpcquery.Query/Status", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).Status(ctx, req.(*StatusParam)) + } + return interceptor(ctx, in, info, handler) +} + func _Query_GetAccount_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetAccountParam) if err := dec(in); err != nil { @@ -442,6 +495,10 @@ var _Query_serviceDesc = grpc.ServiceDesc{ ServiceName: "rpcquery.Query", HandlerType: (*QueryServer)(nil), Methods: []grpc.MethodDesc{ + { + MethodName: "Status", + Handler: _Query_Status_Handler, + }, { MethodName: "GetAccount", Handler: _Query_GetAccount_Handler, @@ -470,6 +527,30 @@ var _Query_serviceDesc = grpc.ServiceDesc{ Metadata: "rpcquery.proto", } +func (m *StatusParam) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *StatusParam) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.BlockWithin) > 0 { + dAtA[i] = 0xa + i++ + i = encodeVarintRpcquery(dAtA, i, uint64(len(m.BlockWithin))) + i += copy(dAtA[i:], m.BlockWithin) + } + return i, nil +} + func (m *GetAccountParam) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -682,6 +763,16 @@ func encodeVarintRpcquery(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return offset + 1 } +func (m *StatusParam) Size() (n int) { + var l int + _ = l + l = len(m.BlockWithin) + if l > 0 { + n += 1 + l + sovRpcquery(uint64(l)) + } + return n +} + func (m *GetAccountParam) Size() (n int) { var l int _ = l @@ -775,6 +866,85 @@ func sovRpcquery(x uint64) (n int) { func sozRpcquery(x uint64) (n int) { return sovRpcquery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } +func (m *StatusParam) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcquery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: StatusParam: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: StatusParam: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockWithin", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRpcquery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthRpcquery + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.BlockWithin = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipRpcquery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthRpcquery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func (m *GetAccountParam) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1483,36 +1653,39 @@ func init() { proto.RegisterFile("rpcquery.proto", fileDescriptorRpcquery) } func init() { golang_proto.RegisterFile("rpcquery.proto", fileDescriptorRpcquery) } var fileDescriptorRpcquery = []byte{ - // 487 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x53, 0x4f, 0x6f, 0xd3, 0x30, - 0x1c, 0xc5, 0xeb, 0x58, 0xd7, 0xdf, 0xaa, 0x4e, 0x58, 0x55, 0x55, 0x02, 0xca, 0xa6, 0x1c, 0xaa, - 0x81, 0x20, 0x99, 0xc6, 0xe0, 0x06, 0x62, 0x1b, 0xa8, 0x0c, 0xa1, 0x09, 0x32, 0x89, 0x03, 0x37, - 0xd7, 0x31, 0x69, 0xa4, 0x26, 0x0e, 0x8e, 0x03, 0xea, 0x17, 0xe0, 0x63, 0x21, 0x8e, 0x3d, 0x72, - 0xe6, 0x30, 0xa1, 0xee, 0x8b, 0xa0, 0x38, 0xce, 0xbf, 0x75, 0xea, 0xcd, 0xcf, 0x79, 0xef, 0xf7, - 0xec, 0xbc, 0x67, 0xe8, 0x89, 0x98, 0x7e, 0x4b, 0x99, 0x98, 0xdb, 0xb1, 0xe0, 0x92, 0xe3, 0xed, - 0x02, 0x1b, 0x4f, 0xfd, 0x40, 0x4e, 0xd3, 0x89, 0x4d, 0x79, 0xe8, 0xf8, 0xdc, 0xe7, 0x8e, 0x22, - 0x4c, 0xd2, 0xaf, 0x0a, 0x29, 0xa0, 0x56, 0xb9, 0xd0, 0xd8, 0x89, 0x48, 0xc8, 0x12, 0x0d, 0x3a, - 0x84, 0x86, 0x7a, 0xb9, 0xfb, 0x9d, 0xcc, 0x02, 0x8f, 0x48, 0x2e, 0xf2, 0x0d, 0x8b, 0xc0, 0xee, - 0x98, 0xc9, 0x13, 0x4a, 0x79, 0x1a, 0xc9, 0x8f, 0x44, 0x90, 0x10, 0x5f, 0x40, 0xfb, 0xc4, 0xf3, - 0x04, 0x4b, 0x92, 0x21, 0xda, 0x47, 0x07, 0xdd, 0xd3, 0xe3, 0xc5, 0xd5, 0xde, 0x9d, 0xbf, 0x57, - 0x7b, 0x4f, 0x6a, 0x67, 0x98, 0xce, 0x63, 0x26, 0x66, 0xcc, 0xf3, 0x99, 0x70, 0x26, 0xa9, 0x10, - 0xfc, 0x87, 0x43, 0xc5, 0x3c, 0x96, 0xdc, 0xd6, 0x5a, 0xb7, 0x18, 0x62, 0x3d, 0x82, 0x7b, 0x1f, - 0x82, 0xa4, 0xf0, 0x48, 0x72, 0x93, 0x3e, 0xdc, 0xfd, 0x94, 0x5d, 0x4c, 0x59, 0x74, 0xdc, 0x1c, - 0x58, 0x16, 0x74, 0xc7, 0x4c, 0x5e, 0x90, 0x90, 0xe5, 0x2c, 0x0c, 0x9b, 0x19, 0xd0, 0x24, 0xb5, - 0xb6, 0x46, 0xd0, 0xcb, 0xc6, 0x65, 0xeb, 0xb5, 0xb3, 0x5e, 0x41, 0x7f, 0xcc, 0xe4, 0xe7, 0xe2, - 0xbe, 0x97, 0x4c, 0x5f, 0x6f, 0x04, 0xbd, 0xf3, 0x88, 0xce, 0x52, 0x8f, 0xbd, 0x0b, 0x12, 0xc9, - 0xb5, 0x6c, 0xdb, 0xbd, 0xb1, 0x6b, 0xfd, 0x44, 0xd0, 0xad, 0xab, 0xf1, 0x00, 0xb6, 0xa6, 0x2c, - 0xf0, 0xa7, 0x52, 0x09, 0x36, 0x5d, 0x8d, 0xf0, 0x08, 0x5a, 0x97, 0x4c, 0x0e, 0x37, 0xf6, 0x5b, - 0x07, 0x3b, 0x47, 0x7d, 0xbb, 0xfa, 0xc3, 0xa5, 0xda, 0xcd, 0x08, 0xf8, 0x05, 0xb4, 0x0b, 0xc7, - 0x96, 0xe2, 0x3e, 0xb4, 0xcb, 0xb8, 0xeb, 0x46, 0x6f, 0xd8, 0x4c, 0x92, 0xc4, 0x2d, 0xc8, 0xd6, - 0x7b, 0xc0, 0xab, 0x9f, 0xf1, 0x31, 0x40, 0xb9, 0x9b, 0xac, 0x35, 0xaf, 0xf1, 0x8e, 0x7e, 0x6d, - 0xe8, 0x7f, 0x85, 0x5f, 0x02, 0x54, 0xc1, 0xe3, 0xfb, 0xd5, 0x51, 0x6e, 0xd4, 0xc1, 0xe8, 0xdb, - 0x59, 0x7d, 0xce, 0x78, 0x44, 0x05, 0x93, 0xac, 0x10, 0x9c, 0x41, 0xb7, 0x1e, 0x2a, 0x7e, 0x50, - 0x0d, 0x58, 0x09, 0xfb, 0xf6, 0x11, 0x87, 0x08, 0x3b, 0xd0, 0xd6, 0x71, 0xe3, 0x41, 0xe3, 0x00, - 0x65, 0x03, 0x8c, 0xae, 0x9d, 0x37, 0xf9, 0x6d, 0x24, 0xc5, 0x1c, 0x3f, 0x87, 0x4e, 0x99, 0x3d, - 0x1e, 0x36, 0x2d, 0xab, 0x42, 0x34, 0x45, 0x87, 0x08, 0x9f, 0xab, 0x92, 0x37, 0xc2, 0x34, 0x1b, - 0x7e, 0x2b, 0x2d, 0x31, 0x06, 0xb7, 0x67, 0x73, 0xfa, 0x7a, 0xb1, 0x34, 0xd1, 0x9f, 0xa5, 0x89, - 0xfe, 0x2d, 0x4d, 0xf4, 0xfb, 0xda, 0x44, 0x8b, 0x6b, 0x13, 0x7d, 0x79, 0xbc, 0xfe, 0x65, 0x88, - 0x98, 0x3a, 0xc5, 0xb8, 0xc9, 0x96, 0x7a, 0x78, 0xcf, 0xfe, 0x07, 0x00, 0x00, 0xff, 0xff, 0xfd, - 0xa4, 0xb6, 0xf9, 0xec, 0x03, 0x00, 0x00, + // 538 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x93, 0xc1, 0x6e, 0xd3, 0x40, + 0x10, 0x86, 0xd9, 0xa6, 0x24, 0xcd, 0x24, 0x4a, 0xd5, 0x55, 0x88, 0x82, 0x41, 0x6e, 0xe4, 0x43, + 0x54, 0x10, 0xd8, 0x55, 0x28, 0xdc, 0x40, 0x34, 0x05, 0x85, 0x22, 0x54, 0x81, 0x23, 0x81, 0xc4, + 0x6d, 0xb3, 0x59, 0x12, 0x0b, 0xc7, 0x6b, 0xd6, 0x6b, 0x50, 0x5e, 0x80, 0xe7, 0xe2, 0x98, 0x23, + 0x67, 0x0e, 0x15, 0x4a, 0xdf, 0x80, 0x27, 0x40, 0x5e, 0xaf, 0x63, 0xa7, 0xa9, 0x72, 0x9b, 0x59, + 0xff, 0xff, 0xcc, 0x78, 0xf7, 0x1b, 0x68, 0x88, 0x90, 0x7e, 0x8b, 0x99, 0x98, 0xdb, 0xa1, 0xe0, + 0x92, 0xe3, 0xbd, 0x2c, 0x37, 0x1e, 0x4f, 0x3c, 0x39, 0x8d, 0x47, 0x36, 0xe5, 0x33, 0x67, 0xc2, + 0x27, 0xdc, 0x51, 0x82, 0x51, 0xfc, 0x45, 0x65, 0x2a, 0x51, 0x51, 0x6a, 0x34, 0x6a, 0x01, 0x99, + 0xb1, 0x48, 0x27, 0x55, 0x42, 0x67, 0x3a, 0xdc, 0xff, 0x4e, 0x7c, 0x6f, 0x4c, 0x24, 0x17, 0xd9, + 0x37, 0x11, 0xd2, 0x34, 0xb4, 0x1c, 0xa8, 0x0d, 0x25, 0x91, 0x71, 0xf4, 0x9e, 0x08, 0x32, 0xc3, + 0x1d, 0xa8, 0xf5, 0x7d, 0x4e, 0xbf, 0x7e, 0xf2, 0xe4, 0xd4, 0x0b, 0xda, 0xa8, 0x83, 0x8e, 0xaa, + 0x6e, 0xf1, 0xc8, 0x22, 0xb0, 0x3f, 0x60, 0xf2, 0x94, 0x52, 0x1e, 0x07, 0x32, 0x35, 0x5d, 0x40, + 0xe5, 0x74, 0x3c, 0x16, 0x2c, 0x8a, 0x94, 0xa1, 0xde, 0x3f, 0x59, 0x5c, 0x1e, 0xde, 0xfa, 0x73, + 0x79, 0xf8, 0xa8, 0x30, 0xff, 0x74, 0x1e, 0x32, 0xe1, 0xb3, 0xf1, 0x84, 0x09, 0x67, 0x14, 0x0b, + 0xc1, 0x7f, 0x38, 0x54, 0xcc, 0x43, 0xc9, 0x6d, 0xed, 0x75, 0xb3, 0x22, 0xd6, 0x03, 0x38, 0x78, + 0xe7, 0x45, 0x59, 0x0f, 0x3d, 0x59, 0x13, 0x6e, 0x7f, 0x48, 0x2e, 0x45, 0xcf, 0x94, 0x26, 0x96, + 0x05, 0xf5, 0x01, 0x93, 0x17, 0x64, 0xc6, 0x52, 0x15, 0x86, 0xdd, 0x24, 0xd1, 0x22, 0x15, 0x5b, + 0x5d, 0x68, 0x24, 0xe5, 0x92, 0x78, 0x6b, 0xad, 0x17, 0xd0, 0x1c, 0x30, 0xf9, 0x31, 0xbb, 0xab, + 0x21, 0xd3, 0xbf, 0xd7, 0x85, 0xc6, 0x79, 0x40, 0xfd, 0x78, 0xcc, 0xde, 0x78, 0x91, 0xe4, 0xda, + 0xb6, 0xe7, 0x5e, 0x3b, 0xb5, 0x7e, 0x22, 0xa8, 0x17, 0xdd, 0xb8, 0x05, 0xe5, 0x29, 0xf3, 0x26, + 0x53, 0xa9, 0x0c, 0xbb, 0xae, 0xce, 0x70, 0x17, 0x4a, 0x43, 0x26, 0xdb, 0x3b, 0x9d, 0xd2, 0x51, + 0xad, 0xd7, 0xb4, 0xf3, 0xd7, 0x59, 0xb9, 0xdd, 0x44, 0x80, 0x9f, 0x41, 0x25, 0xeb, 0x58, 0x52, + 0xda, 0xfb, 0xf6, 0x0a, 0x95, 0x62, 0xa3, 0x57, 0xcc, 0x97, 0x24, 0x72, 0x33, 0xb1, 0xf5, 0x16, + 0xf0, 0xe6, 0x67, 0x7c, 0x02, 0xb0, 0x3a, 0x8d, 0xb6, 0x36, 0x2f, 0xe8, 0x7a, 0xff, 0x76, 0xf4, + 0x5d, 0xe1, 0x1e, 0x94, 0x53, 0x52, 0xf0, 0x9d, 0x7c, 0x8c, 0x02, 0x3b, 0xc6, 0x41, 0x72, 0x6c, + 0xbb, 0x2c, 0x8a, 0x7d, 0xa9, 0x95, 0xcf, 0x01, 0x72, 0x58, 0xf0, 0xdd, 0xdc, 0x77, 0x0d, 0x21, + 0xa3, 0x69, 0x27, 0xb8, 0x9e, 0xf1, 0x80, 0x0a, 0x26, 0x59, 0x66, 0x38, 0x83, 0x7a, 0x11, 0x04, + 0x7c, 0x2f, 0x2f, 0xb0, 0x01, 0xc8, 0xcd, 0x25, 0x8e, 0x11, 0x76, 0xa0, 0xa2, 0x11, 0xc1, 0xad, + 0xb5, 0x01, 0x56, 0xd4, 0x18, 0x75, 0x3b, 0xdd, 0x9c, 0xd7, 0x81, 0x14, 0x73, 0xfc, 0x14, 0xaa, + 0x2b, 0x5e, 0x70, 0x7b, 0xbd, 0x65, 0x0e, 0xd1, 0xba, 0xe9, 0x18, 0xe1, 0x73, 0xb5, 0x18, 0x6b, + 0x00, 0x98, 0x6b, 0xfd, 0x36, 0xc8, 0x32, 0x5a, 0x37, 0xbf, 0x67, 0xff, 0xe5, 0x62, 0x69, 0xa2, + 0xdf, 0x4b, 0x13, 0xfd, 0x5d, 0x9a, 0xe8, 0xd7, 0x95, 0x89, 0x16, 0x57, 0x26, 0xfa, 0xfc, 0x70, + 0xfb, 0x36, 0x89, 0x90, 0x3a, 0x59, 0xb9, 0x51, 0x59, 0x6d, 0xf7, 0x93, 0xff, 0x01, 0x00, 0x00, + 0xff, 0xff, 0xb5, 0xb5, 0x70, 0xe2, 0x5c, 0x04, 0x00, 0x00, } diff --git a/rpc/service.go b/rpc/service.go index 3c266ad25..031a5f33a 100644 --- a/rpc/service.go +++ b/rpc/service.go @@ -91,31 +91,8 @@ func (s *Service) ListUnconfirmedTxs(maxTxs int) (*ResultListUnconfirmedTxs, err }, nil } -func (s *Service) Status() (*ResultStatus, error) { - latestHeight := s.blockchain.LastBlockHeight() - var ( - latestBlockMeta *tmTypes.BlockMeta - latestBlockHash []byte - latestBlockTime int64 - ) - if latestHeight != 0 { - latestBlockMeta = s.nodeView.BlockStore().LoadBlockMeta(int64(latestHeight)) - latestBlockHash = latestBlockMeta.Header.Hash() - latestBlockTime = latestBlockMeta.Header.Time.UnixNano() - } - publicKey, err := s.nodeView.PrivValidatorPublicKey() - if err != nil { - return nil, err - } - return &ResultStatus{ - NodeInfo: s.nodeView.NodeInfo(), - GenesisHash: s.blockchain.GenesisHash(), - PublicKey: publicKey, - LatestBlockHash: latestBlockHash, - LatestBlockHeight: latestHeight, - LatestBlockTime: latestBlockTime, - NodeVersion: project.History.CurrentVersion().String(), - }, nil +func (s *Service) Status(blockWithin string) (*ResultStatus, error) { + return Status(s.BlockchainInfo(), s.nodeView, blockWithin) } func (s *Service) ChainIdentifiers() (*ResultChainId, error) { @@ -130,7 +107,7 @@ func (s *Service) Peers() (*ResultPeers, error) { peers := make([]*Peer, s.nodeView.Peers().Size()) for i, peer := range s.nodeView.Peers().List() { peers[i] = &Peer{ - NodeInfo: peer.NodeInfo(), + NodeInfo: tendermint.NewNodeInfo(peer.NodeInfo()), IsOutbound: peer.IsOutbound(), } } @@ -355,11 +332,16 @@ func (s *Service) GeneratePrivateAccount() (*ResultGeneratePrivateAccount, error }, nil } -func (s *Service) LastBlockInfo(blockWithin string) (*ResultLastBlockInfo, error) { - res := &ResultLastBlockInfo{ - LastBlockHeight: s.blockchain.LastBlockHeight(), - LastBlockHash: s.blockchain.LastBlockHash(), - LastBlockTime: s.blockchain.LastBlockTime(), +func Status(blockchain bcm.BlockchainInfo, nodeView *tendermint.NodeView, blockWithin string) (*ResultStatus, error) { + res := &ResultStatus{ + ChainID: blockchain.ChainID(), + NodeInfo: nodeView.NodeInfo(), + NodeVersion: project.History.CurrentVersion().String(), + GenesisHash: blockchain.GenesisHash(), + PublicKey: nodeView.ValidatorPublicKey(), + LatestBlockHash: blockchain.LastBlockHash(), + LatestBlockHeight: blockchain.LastBlockHeight(), + LatestBlockTime: blockchain.LastBlockTime(), } if blockWithin == "" { return res, nil @@ -368,12 +350,12 @@ func (s *Service) LastBlockInfo(blockWithin string) (*ResultLastBlockInfo, error if err != nil { return nil, fmt.Errorf("could not parse blockWithin duration to determine whether to throw error: %v", err) } - // Take neg abs in case caller is counting backwards (not we add later) + // Take neg abs in case caller is counting backwards (note we later add the time since we normalise the duration to negative) if duration > 0 { duration = -duration } blockTimeThreshold := time.Now().Add(duration) - if res.LastBlockTime.After(blockTimeThreshold) { + if res.LatestBlockTime.After(blockTimeThreshold) { // We've created blocks recently enough return res, nil } @@ -381,6 +363,6 @@ func (s *Service) LastBlockInfo(blockWithin string) (*ResultLastBlockInfo, error if err != nil { resJSON = []byte("") } - return nil, fmt.Errorf("no block committed within the last %s (cutoff: %s), last block info: %s", + return nil, fmt.Errorf("no block committed within the last %s (cutoff: %s), current status: %s", blockWithin, blockTimeThreshold.Format(time.RFC3339), string(resJSON)) } diff --git a/rpc/tm/methods.go b/rpc/tm/methods.go index e28e7d862..6732aa66b 100644 --- a/rpc/tm/methods.go +++ b/rpc/tm/methods.go @@ -11,7 +11,7 @@ import ( // Method names const ( - // Status + // Status and healthcheck Status = "status" NetInfo = "net_info" @@ -44,16 +44,13 @@ const ( // Private keys and signing GeneratePrivateAccount = "unsafe/gen_priv_account" SignTx = "unsafe/sign_tx" - - // Health check - LastBlockInfo = "last_block_info" ) func GetRoutes(service *rpc.Service, logger *logging.Logger) map[string]*server.RPCFunc { logger = logger.WithScope("GetRoutes") return map[string]*server.RPCFunc{ // Status - Status: server.NewRPCFunc(service.Status, ""), + Status: server.NewRPCFunc(service.Status, "block_within"), NetInfo: server.NewRPCFunc(service.NetInfo, ""), // Accounts @@ -85,7 +82,6 @@ func GetRoutes(service *rpc.Service, logger *logging.Logger) map[string]*server. // Private account GeneratePrivateAccount: server.NewRPCFunc(service.GeneratePrivateAccount, ""), - LastBlockInfo: server.NewRPCFunc(service.LastBlockInfo, "block_within"), } } From 47e3d96559817356636c9db3bece99ddb9b9725c Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Mon, 23 Jul 2018 17:16:27 +0100 Subject: [PATCH 22/28] Add gogo.proto to our protobuf at a depth that makes it importable with protobuf/ as an include root (for js) Signed-off-by: Silas Davis --- .../gogo/protobuf/gogoproto/gogo.proto | 136 ++++++++++++++++++ 1 file changed, 136 insertions(+) create mode 100644 protobuf/github.com/gogo/protobuf/gogoproto/gogo.proto diff --git a/protobuf/github.com/gogo/protobuf/gogoproto/gogo.proto b/protobuf/github.com/gogo/protobuf/gogoproto/gogo.proto new file mode 100644 index 000000000..bc8d889f1 --- /dev/null +++ b/protobuf/github.com/gogo/protobuf/gogoproto/gogo.proto @@ -0,0 +1,136 @@ +// Protocol Buffers for Go with Gadgets +// +// Copyright (c) 2013, The GoGo Authors. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto2"; +package gogoproto; + +import "google/protobuf/descriptor.proto"; + +option java_package = "com.google.protobuf"; +option java_outer_classname = "GoGoProtos"; +option go_package = "github.com/gogo/protobuf/gogoproto"; + +extend google.protobuf.EnumOptions { + optional bool goproto_enum_prefix = 62001; + optional bool goproto_enum_stringer = 62021; + optional bool enum_stringer = 62022; + optional string enum_customname = 62023; + optional bool enumdecl = 62024; +} + +extend google.protobuf.EnumValueOptions { + optional string enumvalue_customname = 66001; +} + +extend google.protobuf.FileOptions { + optional bool goproto_getters_all = 63001; + optional bool goproto_enum_prefix_all = 63002; + optional bool goproto_stringer_all = 63003; + optional bool verbose_equal_all = 63004; + optional bool face_all = 63005; + optional bool gostring_all = 63006; + optional bool populate_all = 63007; + optional bool stringer_all = 63008; + optional bool onlyone_all = 63009; + + optional bool equal_all = 63013; + optional bool description_all = 63014; + optional bool testgen_all = 63015; + optional bool benchgen_all = 63016; + optional bool marshaler_all = 63017; + optional bool unmarshaler_all = 63018; + optional bool stable_marshaler_all = 63019; + + optional bool sizer_all = 63020; + + optional bool goproto_enum_stringer_all = 63021; + optional bool enum_stringer_all = 63022; + + optional bool unsafe_marshaler_all = 63023; + optional bool unsafe_unmarshaler_all = 63024; + + optional bool goproto_extensions_map_all = 63025; + optional bool goproto_unrecognized_all = 63026; + optional bool gogoproto_import = 63027; + optional bool protosizer_all = 63028; + optional bool compare_all = 63029; + optional bool typedecl_all = 63030; + optional bool enumdecl_all = 63031; + + optional bool goproto_registration = 63032; + optional bool messagename_all = 63033; +} + +extend google.protobuf.MessageOptions { + optional bool goproto_getters = 64001; + optional bool goproto_stringer = 64003; + optional bool verbose_equal = 64004; + optional bool face = 64005; + optional bool gostring = 64006; + optional bool populate = 64007; + optional bool stringer = 67008; + optional bool onlyone = 64009; + + optional bool equal = 64013; + optional bool description = 64014; + optional bool testgen = 64015; + optional bool benchgen = 64016; + optional bool marshaler = 64017; + optional bool unmarshaler = 64018; + optional bool stable_marshaler = 64019; + + optional bool sizer = 64020; + + optional bool unsafe_marshaler = 64023; + optional bool unsafe_unmarshaler = 64024; + + optional bool goproto_extensions_map = 64025; + optional bool goproto_unrecognized = 64026; + + optional bool protosizer = 64028; + optional bool compare = 64029; + + optional bool typedecl = 64030; + + optional bool messagename = 64033; +} + +extend google.protobuf.FieldOptions { + optional bool nullable = 65001; + optional bool embed = 65002; + optional string customtype = 65003; + optional string customname = 65004; + optional string jsontag = 65005; + optional string moretags = 65006; + optional string casttype = 65007; + optional string castkey = 65008; + optional string castvalue = 65009; + + optional bool stdtime = 65010; + optional bool stdduration = 65011; +} From 193df33ed9dc557ce824d40689baabb5206dbe0e Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Mon, 23 Jul 2018 19:25:32 +0100 Subject: [PATCH 23/28] Make PermArgs field naming less inpenetrable Signed-off-by: Silas Davis --- Gopkg.lock | 8 +- Makefile | 2 +- execution/contexts/permissions_context.go | 16 ++-- permission/permission.pb.go | 90 ++++++++++++----------- permission/snatives.go | 42 +++++------ protobuf/permission.proto | 7 +- 6 files changed, 87 insertions(+), 78 deletions(-) diff --git a/Gopkg.lock b/Gopkg.lock index ac4f2f285..fb5c586a4 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -31,7 +31,7 @@ name = "github.com/btcsuite/btcd" packages = ["btcec"] pruneopts = "NUT" - revision = "f673a4b563b57b9a95832545c878669a7fa801d9" + revision = "9a2f9524024889e129a5422aca2cff73cb3eabf6" [[projects]] branch = "master" @@ -436,7 +436,7 @@ "ssh/terminal", ] pruneopts = "NUT" - revision = "a2144134853fc9a27a7b1e3eb4f19f1a76df13c9" + revision = "c126467f60eb25f8f27e5a981f32a87e3965053f" [[projects]] digest = "1:15dbe437d38eb2103f6b55348758958a6f85a400ecc16fcb53b3f271d38cd8ea" @@ -495,7 +495,7 @@ name = "google.golang.org/genproto" packages = ["googleapis/rpc/status"] pruneopts = "NUT" - revision = "fedd2861243fd1a8152376292b921b394c7bef7e" + revision = "02b4e95473316948020af0b7a4f0f22c73929b0e" [[projects]] digest = "1:f778941d5c2e46da5e0f5d553d3e80bf70eb40d2e80bb4c649b625b9133f3d5f" @@ -552,7 +552,9 @@ "github.com/go-kit/kit/log/term", "github.com/gogo/protobuf/gogoproto", "github.com/gogo/protobuf/proto", + "github.com/gogo/protobuf/types", "github.com/golang/protobuf/proto", + "github.com/golang/protobuf/ptypes/timestamp", "github.com/gorilla/websocket", "github.com/howeyc/gopass", "github.com/imdario/mergo", diff --git a/Makefile b/Makefile index fcc9956dd..3db456789 100644 --- a/Makefile +++ b/Makefile @@ -78,7 +78,7 @@ protobuf_deps: # Implicit compile rule for GRPC/proto files (note since pb.go files no longer generated # in same directory as proto file this just regenerates everything %.pb.go: %.proto - protoc -I vendor -I protobuf $< --gogo_out=plugins=grpc:${GOPATH}/src + protoc -I protobuf -I vendor $< --gogo_out=plugins=grpc:${GOPATH}/src .PHONY: protobuf protobuf: $(PROTO_GO_FILES) diff --git a/execution/contexts/permissions_context.go b/execution/contexts/permissions_context.go index 00cbd1a55..ac4c450b3 100644 --- a/execution/contexts/permissions_context.go +++ b/execution/contexts/permissions_context.go @@ -44,7 +44,7 @@ func (ctx *PermissionsContext) Execute(txe *exec.TxExecution) error { return fmt.Errorf("PermsTx received containing invalid PermArgs: %v", err) } - permFlag := ctx.tx.PermArgs.PermFlag + permFlag := ctx.tx.PermArgs.Action // check permission if !HasPermission(ctx.StateWriter, inAcc, permFlag, ctx.Logger) { return fmt.Errorf("account %s does not have moderator permission %s (%b)", ctx.tx.Input.Address, @@ -65,17 +65,17 @@ func (ctx *PermissionsContext) Execute(txe *exec.TxExecution) error { "perm_args", ctx.tx.PermArgs.String()) var permAcc acm.Account - switch ctx.tx.PermArgs.PermFlag { + switch ctx.tx.PermArgs.Action { case permission.HasBase: // this one doesn't make sense from txs return fmt.Errorf("HasBase is for contracts, not humans. Just look at the blockchain") case permission.SetBase: - permAcc, err = mutatePermissions(ctx.StateWriter, *ctx.tx.PermArgs.Address, + permAcc, err = mutatePermissions(ctx.StateWriter, *ctx.tx.PermArgs.Target, func(perms *permission.AccountPermissions) error { return perms.Base.Set(*ctx.tx.PermArgs.Permission, *ctx.tx.PermArgs.Value) }) case permission.UnsetBase: - permAcc, err = mutatePermissions(ctx.StateWriter, *ctx.tx.PermArgs.Address, + permAcc, err = mutatePermissions(ctx.StateWriter, *ctx.tx.PermArgs.Target, func(perms *permission.AccountPermissions) error { return perms.Base.Unset(*ctx.tx.PermArgs.Permission) }) @@ -87,20 +87,20 @@ func (ctx *PermissionsContext) Execute(txe *exec.TxExecution) error { case permission.HasRole: return fmt.Errorf("HasRole is for contracts, not humans. Just look at the blockchain") case permission.AddRole: - permAcc, err = mutatePermissions(ctx.StateWriter, *ctx.tx.PermArgs.Address, + permAcc, err = mutatePermissions(ctx.StateWriter, *ctx.tx.PermArgs.Target, func(perms *permission.AccountPermissions) error { if !perms.AddRole(*ctx.tx.PermArgs.Role) { return fmt.Errorf("role (%s) already exists for account %s", - *ctx.tx.PermArgs.Role, *ctx.tx.PermArgs.Address) + *ctx.tx.PermArgs.Role, *ctx.tx.PermArgs.Target) } return nil }) case permission.RemoveRole: - permAcc, err = mutatePermissions(ctx.StateWriter, *ctx.tx.PermArgs.Address, + permAcc, err = mutatePermissions(ctx.StateWriter, *ctx.tx.PermArgs.Target, func(perms *permission.AccountPermissions) error { if !perms.RmRole(*ctx.tx.PermArgs.Role) { return fmt.Errorf("role (%s) does not exist for account %s", - *ctx.tx.PermArgs.Role, *ctx.tx.PermArgs.Address) + *ctx.tx.PermArgs.Role, *ctx.tx.PermArgs.Target) } return nil }) diff --git a/permission/permission.pb.go b/permission/permission.pb.go index b72986011..da42a596c 100644 --- a/permission/permission.pb.go +++ b/permission/permission.pb.go @@ -94,20 +94,23 @@ func (*BasePermissions) XXX_MessageName() string { } type PermArgs struct { - PermFlag PermFlag `protobuf:"varint,1,opt,name=PermFlag,casttype=PermFlag" json:"PermFlag"` - Address *github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,2,opt,name=Address,customtype=github.com/hyperledger/burrow/crypto.Address" json:"Address,omitempty"` - Permission *PermFlag `protobuf:"varint,3,opt,name=Permission,casttype=PermFlag" json:"Permission,omitempty"` - Role *string `protobuf:"bytes,4,opt,name=Role" json:"Role,omitempty"` - Value *bool `protobuf:"varint,5,opt,name=Value" json:"Value,omitempty"` + // The permission function + Action PermFlag `protobuf:"varint,1,opt,name=Action,casttype=PermFlag" json:"Action"` + // The target of the action + Target *github_com_hyperledger_burrow_crypto.Address `protobuf:"bytes,2,opt,name=Target,customtype=github.com/hyperledger/burrow/crypto.Address" json:"Target,omitempty"` + // Possible arguments + Permission *PermFlag `protobuf:"varint,3,opt,name=Permission,casttype=PermFlag" json:"Permission,omitempty"` + Role *string `protobuf:"bytes,4,opt,name=Role" json:"Role,omitempty"` + Value *bool `protobuf:"varint,5,opt,name=Value" json:"Value,omitempty"` } func (m *PermArgs) Reset() { *m = PermArgs{} } func (*PermArgs) ProtoMessage() {} func (*PermArgs) Descriptor() ([]byte, []int) { return fileDescriptorPermission, []int{2} } -func (m *PermArgs) GetPermFlag() PermFlag { +func (m *PermArgs) GetAction() PermFlag { if m != nil { - return m.PermFlag + return m.Action } return 0 } @@ -232,12 +235,12 @@ func (m *PermArgs) MarshalTo(dAtA []byte) (int, error) { _ = l dAtA[i] = 0x8 i++ - i = encodeVarintPermission(dAtA, i, uint64(m.PermFlag)) - if m.Address != nil { + i = encodeVarintPermission(dAtA, i, uint64(m.Action)) + if m.Target != nil { dAtA[i] = 0x12 i++ - i = encodeVarintPermission(dAtA, i, uint64(m.Address.Size())) - n2, err := m.Address.MarshalTo(dAtA[i:]) + i = encodeVarintPermission(dAtA, i, uint64(m.Target.Size())) + n2, err := m.Target.MarshalTo(dAtA[i:]) if err != nil { return 0, err } @@ -307,9 +310,9 @@ func (m *BasePermissions) Size() (n int) { func (m *PermArgs) Size() (n int) { var l int _ = l - n += 1 + sovPermission(uint64(m.PermFlag)) - if m.Address != nil { - l = m.Address.Size() + n += 1 + sovPermission(uint64(m.Action)) + if m.Target != nil { + l = m.Target.Size() n += 1 + l + sovPermission(uint64(l)) } if m.Permission != nil { @@ -568,9 +571,9 @@ func (m *PermArgs) Unmarshal(dAtA []byte) error { switch fieldNum { case 1: if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field PermFlag", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Action", wireType) } - m.PermFlag = 0 + m.Action = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowPermission @@ -580,14 +583,14 @@ func (m *PermArgs) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.PermFlag |= (PermFlag(b) & 0x7F) << shift + m.Action |= (PermFlag(b) & 0x7F) << shift if b < 0x80 { break } } case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Target", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { @@ -612,8 +615,8 @@ func (m *PermArgs) Unmarshal(dAtA []byte) error { return io.ErrUnexpectedEOF } var v github_com_hyperledger_burrow_crypto.Address - m.Address = &v - if err := m.Address.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.Target = &v + if err := m.Target.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -818,27 +821,28 @@ func init() { proto.RegisterFile("permission.proto", fileDescriptorPermission) } func init() { golang_proto.RegisterFile("permission.proto", fileDescriptorPermission) } var fileDescriptorPermission = []byte{ - // 351 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x51, 0x31, 0x4b, 0xc3, 0x40, - 0x14, 0xee, 0xb5, 0xa9, 0xb6, 0xcf, 0x82, 0xe5, 0x70, 0x08, 0x0a, 0x49, 0xe8, 0x20, 0x19, 0x6a, - 0x22, 0x82, 0x4b, 0x07, 0xa1, 0x19, 0x1c, 0x9c, 0xe4, 0x04, 0x07, 0xb7, 0x34, 0x3d, 0xd3, 0x40, - 0xda, 0x0b, 0x77, 0x17, 0xa4, 0xff, 0xc4, 0x51, 0xff, 0x89, 0x63, 0xc7, 0xce, 0x0e, 0x45, 0x5a, - 0xf0, 0x47, 0x38, 0xc9, 0x5d, 0x6a, 0x1b, 0x85, 0xba, 0xbd, 0xef, 0x7d, 0xdf, 0x7b, 0xdf, 0xbd, - 0xef, 0xa0, 0x9d, 0x51, 0x3e, 0x4e, 0x84, 0x48, 0xd8, 0xc4, 0xcb, 0x38, 0x93, 0x0c, 0xc3, 0xb6, - 0x73, 0x7c, 0x16, 0x27, 0x72, 0x94, 0x0f, 0xbc, 0x88, 0x8d, 0xfd, 0x98, 0xc5, 0xcc, 0xd7, 0x92, - 0x41, 0xfe, 0xa8, 0x91, 0x06, 0xba, 0x2a, 0x46, 0x3b, 0x21, 0xe0, 0x7e, 0x14, 0xb1, 0x7c, 0x22, - 0x6f, 0x37, 0x3b, 0x04, 0xbe, 0x04, 0x23, 0x08, 0x05, 0x35, 0x91, 0x83, 0xdc, 0x83, 0x8b, 0x13, - 0xaf, 0xe4, 0xa8, 0xfa, 0x25, 0x69, 0x60, 0xcc, 0x16, 0x76, 0x85, 0x68, 0x39, 0x3e, 0x82, 0x3a, - 0x61, 0x29, 0x15, 0x66, 0xd5, 0xa9, 0xb9, 0x4d, 0x52, 0x80, 0x4e, 0x02, 0x87, 0x7f, 0x86, 0xf0, - 0x29, 0xd4, 0x15, 0x14, 0xda, 0xc0, 0x08, 0xda, 0x6a, 0xc7, 0xd7, 0xc2, 0x6e, 0xa8, 0xe6, 0x75, - 0x1a, 0xc6, 0xa4, 0xa0, 0xb1, 0x0b, 0x7b, 0x77, 0x54, 0x06, 0x89, 0x34, 0xab, 0x3b, 0x84, 0x6b, - 0xbe, 0x67, 0x3c, 0xbf, 0xd8, 0x95, 0xce, 0x27, 0x02, 0x4d, 0xf5, 0x79, 0x2c, 0x70, 0x17, 0x36, - 0xb2, 0x9d, 0x3e, 0x9b, 0x0a, 0xdf, 0xc0, 0x7e, 0x7f, 0x38, 0xe4, 0x54, 0x08, 0xed, 0xd5, 0x0a, - 0xce, 0xdf, 0x17, 0x76, 0xb7, 0x14, 0xe6, 0x68, 0x9a, 0x51, 0x9e, 0xd2, 0x61, 0x4c, 0xb9, 0x3f, - 0xc8, 0x39, 0x67, 0x4f, 0x7e, 0xc4, 0xa7, 0x99, 0x64, 0xde, 0x7a, 0x8e, 0xfc, 0x2c, 0xc0, 0x5d, - 0x80, 0xed, 0xb5, 0x66, 0x4d, 0x7b, 0xb7, 0x7e, 0xf9, 0x96, 0x78, 0x8c, 0xc1, 0x50, 0x41, 0x99, - 0x86, 0x83, 0xdc, 0x26, 0xd1, 0xb5, 0x4a, 0xf2, 0x3e, 0x4c, 0x73, 0x6a, 0xd6, 0x1d, 0xe4, 0x36, - 0x48, 0x01, 0x7a, 0x0d, 0x75, 0xe4, 0xfc, 0xd5, 0xae, 0x04, 0x57, 0xb3, 0xa5, 0x85, 0xe6, 0x4b, - 0x0b, 0x7d, 0x2c, 0x2d, 0xf4, 0xb6, 0xb2, 0xd0, 0x6c, 0x65, 0xa1, 0x07, 0xf7, 0xff, 0xe7, 0x6e, - 0x7f, 0xf1, 0x3b, 0x00, 0x00, 0xff, 0xff, 0x75, 0xf4, 0x5f, 0xe9, 0x44, 0x02, 0x00, 0x00, + // 355 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x51, 0xb1, 0x4b, 0xfb, 0x40, + 0x14, 0xee, 0xb5, 0x69, 0x69, 0xdf, 0xaf, 0xf0, 0x2b, 0x87, 0x43, 0x50, 0x48, 0x42, 0x07, 0xc9, + 0x50, 0x13, 0x11, 0x5c, 0x3a, 0x08, 0xc9, 0x20, 0x8e, 0x12, 0xc5, 0xc1, 0x2d, 0x4d, 0xcf, 0x6b, + 0x20, 0xed, 0x85, 0xbb, 0x0b, 0xd2, 0xff, 0xc4, 0x51, 0xff, 0x13, 0xc7, 0x8e, 0x9d, 0x1d, 0x4a, + 0x69, 0xff, 0x0b, 0x27, 0xb9, 0x4b, 0xb1, 0x51, 0xa8, 0xdb, 0xfb, 0xde, 0xf7, 0x7d, 0xef, 0xbb, + 0xf7, 0x0e, 0x7a, 0x39, 0xe1, 0xd3, 0x54, 0x88, 0x94, 0xcd, 0xbc, 0x9c, 0x33, 0xc9, 0x30, 0xec, + 0x3b, 0xc7, 0x67, 0x34, 0x95, 0x93, 0x62, 0xe4, 0x25, 0x6c, 0xea, 0x53, 0x46, 0x99, 0xaf, 0x25, + 0xa3, 0xe2, 0x49, 0x23, 0x0d, 0x74, 0x55, 0x5a, 0xfb, 0x31, 0xe0, 0x20, 0x49, 0x58, 0x31, 0x93, + 0xb7, 0xdf, 0x33, 0x04, 0xbe, 0x04, 0x23, 0x8c, 0x05, 0x31, 0x91, 0x83, 0xdc, 0x7f, 0x17, 0x27, + 0x5e, 0x25, 0x51, 0xf5, 0x2b, 0xd2, 0xd0, 0x58, 0xac, 0xec, 0x5a, 0xa4, 0xe5, 0xf8, 0x08, 0x9a, + 0x11, 0xcb, 0x88, 0x30, 0xeb, 0x4e, 0xc3, 0xed, 0x44, 0x25, 0xe8, 0xa7, 0xf0, 0xff, 0x97, 0x09, + 0x9f, 0x42, 0x53, 0x41, 0xa1, 0x03, 0x8c, 0xb0, 0xa7, 0x66, 0x7c, 0xae, 0xec, 0xb6, 0x6a, 0x5e, + 0x67, 0x31, 0x8d, 0x4a, 0x1a, 0xbb, 0xd0, 0xba, 0x23, 0x32, 0x4c, 0xa5, 0x59, 0x3f, 0x20, 0xdc, + 0xf1, 0x43, 0xe3, 0xe5, 0xd5, 0xae, 0xf5, 0xd7, 0x08, 0x34, 0x15, 0x70, 0xaa, 0xcd, 0x41, 0x22, + 0x53, 0x36, 0x3b, 0x98, 0xb2, 0xe3, 0xf1, 0x0d, 0xb4, 0xee, 0x63, 0x4e, 0x49, 0x19, 0xd3, 0x0d, + 0xcf, 0x3f, 0x56, 0xf6, 0xa0, 0x72, 0xc7, 0xc9, 0x3c, 0x27, 0x3c, 0x23, 0x63, 0x4a, 0xb8, 0x3f, + 0x2a, 0x38, 0x67, 0xcf, 0x7e, 0xc2, 0xe7, 0xb9, 0x64, 0x5e, 0x30, 0x1e, 0x73, 0x22, 0x44, 0xb4, + 0xf3, 0xe3, 0x01, 0xc0, 0x7e, 0x4f, 0xb3, 0xa1, 0x73, 0xbb, 0x3f, 0x32, 0x2b, 0x3c, 0xc6, 0x60, + 0xa8, 0x13, 0x99, 0x86, 0x83, 0xdc, 0x4e, 0xa4, 0x6b, 0x75, 0xc3, 0x87, 0x38, 0x2b, 0x88, 0xd9, + 0x74, 0x90, 0xdb, 0x8e, 0x4a, 0x30, 0x6c, 0xab, 0xf5, 0x96, 0x6f, 0x76, 0x2d, 0xbc, 0x5a, 0x6c, + 0x2c, 0xb4, 0xdc, 0x58, 0x68, 0xbd, 0xb1, 0xd0, 0xfb, 0xd6, 0x42, 0x8b, 0xad, 0x85, 0x1e, 0xdd, + 0xbf, 0x5f, 0xbb, 0xff, 0xbf, 0xaf, 0x00, 0x00, 0x00, 0xff, 0xff, 0xaa, 0x70, 0x53, 0xf2, 0x3e, + 0x02, 0x00, 0x00, } diff --git a/permission/snatives.go b/permission/snatives.go index 6f3df0a1e..649fcc111 100644 --- a/permission/snatives.go +++ b/permission/snatives.go @@ -26,9 +26,9 @@ import ( func (pa PermArgs) String() string { body := make([]string, 0, 5) - body = append(body, fmt.Sprintf("PermFlag: %v", String(pa.PermFlag))) - if pa.Address != nil { - body = append(body, fmt.Sprintf("Address: %s", *pa.Address)) + body = append(body, fmt.Sprintf("PermFlag: %v", String(pa.Action))) + if pa.Target != nil { + body = append(body, fmt.Sprintf("Address: %s", *pa.Target)) } if pa.Permission != nil { body = append(body, fmt.Sprintf("Permission: %v", String(*pa.Permission))) @@ -43,9 +43,9 @@ func (pa PermArgs) String() string { } func (pa PermArgs) EnsureValid() error { - pf := pa.PermFlag + pf := pa.Action // Address - if pa.Address == nil && pf != SetGlobal { + if pa.Target == nil && pf != SetGlobal { return fmt.Errorf("PermArgs for PermFlag %v requires Address to be provided but was nil", pf) } if pf == HasRole || pf == AddRole || pf == RemoveRole { @@ -65,16 +65,16 @@ func (pa PermArgs) EnsureValid() error { func HasBaseArgs(address crypto.Address, permFlag PermFlag) PermArgs { return PermArgs{ - PermFlag: HasBase, - Address: &address, + Action: HasBase, + Target: &address, Permission: &permFlag, } } func SetBaseArgs(address crypto.Address, permFlag PermFlag, value bool) PermArgs { return PermArgs{ - PermFlag: SetBase, - Address: &address, + Action: SetBase, + Target: &address, Permission: &permFlag, Value: &value, } @@ -82,15 +82,15 @@ func SetBaseArgs(address crypto.Address, permFlag PermFlag, value bool) PermArgs func UnsetBaseArgs(address crypto.Address, permFlag PermFlag) PermArgs { return PermArgs{ - PermFlag: UnsetBase, - Address: &address, + Action: UnsetBase, + Target: &address, Permission: &permFlag, } } func SetGlobalArgs(permFlag PermFlag, value bool) PermArgs { return PermArgs{ - PermFlag: SetGlobal, + Action: SetGlobal, Permission: &permFlag, Value: &value, } @@ -98,24 +98,24 @@ func SetGlobalArgs(permFlag PermFlag, value bool) PermArgs { func HasRoleArgs(address crypto.Address, role string) PermArgs { return PermArgs{ - PermFlag: HasRole, - Address: &address, - Role: &role, + Action: HasRole, + Target: &address, + Role: &role, } } func AddRoleArgs(address crypto.Address, role string) PermArgs { return PermArgs{ - PermFlag: AddRole, - Address: &address, - Role: &role, + Action: AddRole, + Target: &address, + Role: &role, } } func RemoveRoleArgs(address crypto.Address, role string) PermArgs { return PermArgs{ - PermFlag: RemoveRole, - Address: &address, - Role: &role, + Action: RemoveRole, + Target: &address, + Role: &role, } } diff --git a/protobuf/permission.proto b/protobuf/permission.proto index d7ba52af5..b1709bffe 100644 --- a/protobuf/permission.proto +++ b/protobuf/permission.proto @@ -31,8 +31,11 @@ message BasePermissions { message PermArgs { option (gogoproto.goproto_unrecognized) = false; option (gogoproto.goproto_stringer) = false; - optional uint64 PermFlag = 1 [(gogoproto.casttype) = "PermFlag", (gogoproto.nullable) = false]; - optional bytes Address = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address"]; + // The permission function + optional uint64 Action = 1 [(gogoproto.casttype) = "PermFlag", (gogoproto.nullable) = false]; + // The target of the action + optional bytes Target = 2 [(gogoproto.customtype) = "github.com/hyperledger/burrow/crypto.Address"]; + // Possible arguments optional uint64 Permission = 3 [(gogoproto.casttype) = "PermFlag"]; optional string Role = 4; optional bool Value = 5; From b7d1f3b56c212eafff4d1c641599b55008b838c9 Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Tue, 24 Jul 2018 00:05:28 +0100 Subject: [PATCH 24/28] Fix exception surfacing Signed-off-by: Silas Davis --- consensus/tendermint/tendermint.pb.go | 44 ++++++++++----------- execution/contexts/call_context.go | 1 + execution/errors/errors.go | 2 +- execution/exec/tx_execution.go | 4 ++ execution/execution.go | 2 +- execution/simulated_call.go | 1 + execution/transactor.go | 6 ++- protobuf/rpc.proto | 2 +- protobuf/tendermint.proto | 1 - rpc/rpc.pb.go | 55 ++++++++++++++------------- 10 files changed, 63 insertions(+), 55 deletions(-) diff --git a/consensus/tendermint/tendermint.pb.go b/consensus/tendermint/tendermint.pb.go index 6dd3e449a..47f2bd55b 100644 --- a/consensus/tendermint/tendermint.pb.go +++ b/consensus/tendermint/tendermint.pb.go @@ -17,7 +17,6 @@ import golang_proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import _ "github.com/gogo/protobuf/gogoproto" -import _ "github.com/hyperledger/burrow/crypto" import github_com_hyperledger_burrow_crypto "github.com/hyperledger/burrow/crypto" import github_com_hyperledger_burrow_binary "github.com/hyperledger/burrow/binary" @@ -584,26 +583,25 @@ func init() { proto.RegisterFile("tendermint.proto", fileDescriptorTendermint) } func init() { golang_proto.RegisterFile("tendermint.proto", fileDescriptorTendermint) } var fileDescriptorTendermint = []byte{ - // 321 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x91, 0xbd, 0x4e, 0x3a, 0x41, - 0x14, 0xc5, 0xff, 0xb3, 0xfc, 0xf9, 0x9a, 0x60, 0x62, 0x36, 0x16, 0x13, 0x8a, 0x85, 0x18, 0x0b, - 0x0a, 0x61, 0x13, 0x3f, 0x1e, 0x40, 0xa4, 0x80, 0x44, 0x31, 0x6e, 0x61, 0x61, 0xc7, 0xb2, 0x97, - 0xdd, 0x0d, 0x30, 0x97, 0xdc, 0x99, 0x0d, 0xee, 0x43, 0xf9, 0x0e, 0x96, 0x94, 0xd6, 0x16, 0xc4, - 0xc0, 0x8b, 0x18, 0x66, 0x57, 0xd1, 0x46, 0xbb, 0xf9, 0x9d, 0x33, 0x73, 0xee, 0xc9, 0x5c, 0x7e, - 0xa8, 0x41, 0x06, 0x40, 0xf3, 0x58, 0xea, 0xce, 0x82, 0x50, 0xa3, 0xcd, 0xf7, 0x4a, 0xbd, 0x1d, - 0xc6, 0x3a, 0x4a, 0xfc, 0xce, 0x18, 0xe7, 0x6e, 0x88, 0x21, 0xba, 0xe6, 0x8a, 0x9f, 0x4c, 0x0c, - 0x19, 0x30, 0xa7, 0xec, 0x69, 0xbd, 0x36, 0xa6, 0x74, 0xa1, 0x73, 0x3a, 0x7e, 0xb6, 0x78, 0x65, - 0x88, 0x01, 0x0c, 0xe4, 0x04, 0xed, 0x1e, 0xb7, 0x06, 0x3d, 0xc1, 0x9a, 0xac, 0x55, 0xeb, 0x5e, - 0xac, 0xd6, 0x8d, 0x7f, 0x6f, 0xeb, 0xc6, 0xe9, 0xb7, 0xf4, 0x28, 0x5d, 0x00, 0xcd, 0x20, 0x08, - 0x81, 0x5c, 0x3f, 0x21, 0xc2, 0xa5, 0x9b, 0x87, 0x5d, 0x05, 0x01, 0x81, 0x52, 0x9e, 0x35, 0xe8, - 0xd9, 0x27, 0xfc, 0xe0, 0x26, 0x56, 0x1a, 0x64, 0x2e, 0x0a, 0xab, 0xc9, 0x5a, 0x55, 0xef, 0xa7, - 0x68, 0x0b, 0x5e, 0x1e, 0x82, 0x5e, 0x22, 0x4d, 0x45, 0xc1, 0xf8, 0x9f, 0xb8, 0x73, 0x1e, 0x80, - 0x54, 0x8c, 0x52, 0xfc, 0xcf, 0x9c, 0x1c, 0xed, 0x7b, 0x5e, 0xb9, 0x8e, 0x46, 0x52, 0xc2, 0x4c, - 0x89, 0xa2, 0x69, 0x79, 0x99, 0xb7, 0x6c, 0xff, 0xde, 0xd2, 0x8f, 0xe5, 0x88, 0xd2, 0x4e, 0x1f, - 0x9e, 0xba, 0xa9, 0x06, 0xe5, 0x7d, 0xc5, 0xec, 0x86, 0xdd, 0xa2, 0x8c, 0xa7, 0x40, 0xa2, 0x94, - 0x0d, 0xcb, 0xd1, 0x3e, 0xe2, 0xc5, 0x3b, 0x1d, 0x01, 0x89, 0x72, 0xb3, 0xd0, 0xaa, 0x7a, 0x19, - 0x74, 0xfb, 0xab, 0x8d, 0xc3, 0x5e, 0x37, 0x0e, 0x7b, 0xdf, 0x38, 0xec, 0x65, 0xeb, 0xb0, 0xd5, - 0xd6, 0x61, 0x8f, 0x67, 0x7f, 0x7c, 0x12, 0x4a, 0x05, 0x52, 0x25, 0xca, 0xdd, 0xaf, 0xcd, 0x2f, - 0x99, 0x05, 0x9c, 0x7f, 0x04, 0x00, 0x00, 0xff, 0xff, 0x29, 0x50, 0xa8, 0x1b, 0xdd, 0x01, 0x00, - 0x00, + // 318 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x91, 0xcd, 0x4e, 0xfa, 0x40, + 0x14, 0xc5, 0xff, 0x53, 0xfe, 0x7c, 0x4d, 0x34, 0x31, 0x8d, 0x8b, 0x89, 0x8b, 0x42, 0x8c, 0x0b, + 0x16, 0xd2, 0x26, 0x7e, 0x3c, 0x80, 0xc8, 0x02, 0x12, 0xc5, 0xd8, 0x85, 0x0b, 0x77, 0x94, 0x5e, + 0xda, 0x06, 0x98, 0x4b, 0xee, 0x4c, 0x83, 0x7d, 0x28, 0xdf, 0xc1, 0x25, 0x4b, 0xd7, 0x2e, 0x88, + 0x81, 0x17, 0x31, 0x4c, 0xab, 0xe8, 0x46, 0x77, 0xf3, 0x3b, 0x67, 0xe6, 0xde, 0x93, 0x39, 0xfc, + 0x40, 0x83, 0x0c, 0x81, 0x66, 0x89, 0xd4, 0xee, 0x9c, 0x50, 0xa3, 0xcd, 0x77, 0xca, 0x51, 0x3b, + 0x4a, 0x74, 0x9c, 0x06, 0xee, 0x08, 0x67, 0x5e, 0x84, 0x11, 0x7a, 0xe6, 0x4a, 0x90, 0x8e, 0x0d, + 0x19, 0x30, 0xa7, 0xfc, 0xe9, 0xf1, 0xb3, 0xc5, 0x6b, 0x03, 0x0c, 0xa1, 0x2f, 0xc7, 0x68, 0x77, + 0xb9, 0xd5, 0xef, 0x0a, 0xd6, 0x64, 0xad, 0xbd, 0xce, 0xc5, 0x72, 0xd5, 0xf8, 0xf7, 0xb6, 0x6a, + 0x9c, 0x7e, 0x9b, 0x17, 0x67, 0x73, 0xa0, 0x29, 0x84, 0x11, 0x90, 0x17, 0xa4, 0x44, 0xb8, 0xf0, + 0x46, 0x94, 0xcd, 0x35, 0xba, 0x57, 0x61, 0x48, 0xa0, 0x94, 0x6f, 0xf5, 0xbb, 0xf6, 0x09, 0xdf, + 0xbf, 0x49, 0x94, 0x06, 0x59, 0x88, 0xc2, 0x6a, 0xb2, 0x56, 0xdd, 0xff, 0x29, 0xda, 0x82, 0x57, + 0x07, 0xa0, 0x17, 0x48, 0x13, 0x51, 0x32, 0xfe, 0x27, 0x6e, 0x9d, 0x07, 0x20, 0x95, 0xa0, 0x14, + 0xff, 0x73, 0xa7, 0x40, 0xfb, 0x9e, 0xd7, 0xae, 0xe3, 0xa1, 0x94, 0x30, 0x55, 0xa2, 0x6c, 0x52, + 0x5e, 0x16, 0x29, 0xdb, 0xbf, 0xa7, 0x0c, 0x12, 0x39, 0xa4, 0xcc, 0xed, 0xc1, 0x53, 0x27, 0xd3, + 0xa0, 0xfc, 0xaf, 0x31, 0xdb, 0x65, 0xb7, 0x28, 0x93, 0x09, 0x90, 0xa8, 0xe4, 0xcb, 0x0a, 0xb4, + 0x0f, 0x79, 0xf9, 0x4e, 0xc7, 0x40, 0xa2, 0xda, 0x2c, 0xb5, 0xea, 0x7e, 0x0e, 0x9d, 0xde, 0x72, + 0xed, 0xb0, 0xd7, 0xb5, 0xc3, 0xde, 0xd7, 0x0e, 0x7b, 0xd9, 0x38, 0x6c, 0xb9, 0x71, 0xd8, 0xe3, + 0xd9, 0x1f, 0x9f, 0x84, 0x52, 0x81, 0x54, 0xa9, 0xf2, 0x76, 0x45, 0x05, 0x15, 0x53, 0xc0, 0xf9, + 0x47, 0x00, 0x00, 0x00, 0xff, 0xff, 0xd1, 0x1c, 0x4c, 0x76, 0xcf, 0x01, 0x00, 0x00, } diff --git a/execution/contexts/call_context.go b/execution/contexts/call_context.go index fcf7e146c..385d05e18 100644 --- a/execution/contexts/call_context.go +++ b/execution/contexts/call_context.go @@ -213,6 +213,7 @@ func (ctx *CallContext) Deliver(inAcc, outAcc acm.Account, value uint64) error { // Failure. Charge the gas fee. The 'value' was otherwise not transferred. ctx.Logger.InfoMsg("Error on execution", structure.ErrorKey, exception) + ctx.txe.SetException(exception) } else { ctx.Logger.TraceMsg("Successful execution") if createContract { diff --git a/execution/errors/errors.go b/execution/errors/errors.go index 00e49c47b..69f9f89c1 100644 --- a/execution/errors/errors.go +++ b/execution/errors/errors.go @@ -173,5 +173,5 @@ func (e *Exception) Error() string { if e == nil { return "" } - return fmt.Sprintf("Error %v: %s", e.Code, e.Exception) + return fmt.Sprintf("Error %d: %s", e.Code, e.Exception) } diff --git a/execution/exec/tx_execution.go b/execution/exec/tx_execution.go index 9de377ffe..98886d049 100644 --- a/execution/exec/tx_execution.go +++ b/execution/exec/tx_execution.go @@ -97,6 +97,10 @@ func (txe *TxExecution) GovernAccount(governAccount *GovernAccountEvent, excepti }) } +func (txe *TxExecution) SetException(err error) { + txe.Exception = errors.AsException(err) +} + // Set result func (txe *TxExecution) Return(returnValue []byte, gasUsed uint64) { if txe.Result == nil { diff --git a/execution/execution.go b/execution/execution.go index 63328d291..d14b40a88 100644 --- a/execution/execution.go +++ b/execution/execution.go @@ -197,7 +197,7 @@ func (exe *executor) Execute(txEnv *txs.Envelope) (txe *exec.TxExecution, err er return nil, err } // Return execution for this tx - return txe, err + return txe, nil } return nil, fmt.Errorf("unknown transaction type: %v", txEnv.Tx.Type()) } diff --git a/execution/simulated_call.go b/execution/simulated_call.go index 0274a7393..813937d40 100644 --- a/execution/simulated_call.go +++ b/execution/simulated_call.go @@ -57,6 +57,7 @@ func CallCodeSim(reader state.Reader, tip bcm.BlockchainInfo, fromAddress, addre err = fmt.Errorf("panic from VM in simulated call: %v\n%s", r, debug.Stack()) } }() + ret, err := vmach.Call(txCache, caller, callee, code, data, 0, &gas) if err != nil { return nil, err diff --git a/execution/transactor.go b/execution/transactor.go index c1a12edc3..8cf042111 100644 --- a/execution/transactor.go +++ b/execution/transactor.go @@ -106,7 +106,11 @@ func (trans *Transactor) BroadcastTxSync(ctx context.Context, txEnv *txs.Envelop return nil, fmt.Errorf("timed out waiting for transaction with hash %v timed out after %v", checkTxReceipt.TxHash, BlockingTimeout) case msg := <-out: - return msg.(*exec.TxExecution), nil + txe := msg.(*exec.TxExecution) + if txe.Exception != nil && txe.Exception.ErrorCode() != errors.ErrorCodeExecutionReverted { + return nil, errors.Wrap(txe.Exception, "exception during transaction execution") + } + return txe, nil } } diff --git a/protobuf/rpc.proto b/protobuf/rpc.proto index 88f78933e..4270702ee 100644 --- a/protobuf/rpc.proto +++ b/protobuf/rpc.proto @@ -23,7 +23,7 @@ message ResultStatus { string NodeVersion = 3; crypto.PublicKey PublicKey = 5 [(gogoproto.nullable) = false]; bytes LatestBlockHash = 6 [(gogoproto.customtype) = "github.com/hyperledger/burrow/binary.HexBytes", (gogoproto.nullable) = false]; - uint64 LatestBlockHeight = 7; + uint64 LatestBlockHeight = 7 [(gogoproto.jsontag) = ""]; // Unix google.protobuf.Timestamp LatestBlockTime = 8 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; diff --git a/protobuf/tendermint.proto b/protobuf/tendermint.proto index cef3f0c38..a4a06319f 100644 --- a/protobuf/tendermint.proto +++ b/protobuf/tendermint.proto @@ -4,7 +4,6 @@ syntax = 'proto3'; option go_package = "github.com/hyperledger/burrow/consensus/tendermint"; import "github.com/gogo/protobuf/gogoproto/gogo.proto"; -import "crypto.proto"; package tendermint; diff --git a/rpc/rpc.pb.go b/rpc/rpc.pb.go index 8836266a7..1815a6200 100644 --- a/rpc/rpc.pb.go +++ b/rpc/rpc.pb.go @@ -48,7 +48,7 @@ type ResultStatus struct { NodeVersion string `protobuf:"bytes,3,opt,name=NodeVersion,proto3" json:"NodeVersion,omitempty"` PublicKey crypto.PublicKey `protobuf:"bytes,5,opt,name=PublicKey" json:"PublicKey"` LatestBlockHash github_com_hyperledger_burrow_binary.HexBytes `protobuf:"bytes,6,opt,name=LatestBlockHash,proto3,customtype=github.com/hyperledger/burrow/binary.HexBytes" json:"LatestBlockHash"` - LatestBlockHeight uint64 `protobuf:"varint,7,opt,name=LatestBlockHeight,proto3" json:"LatestBlockHeight,omitempty"` + LatestBlockHeight uint64 `protobuf:"varint,7,opt,name=LatestBlockHeight,proto3" json:""` LatestBlockTime time.Time `protobuf:"bytes,8,opt,name=LatestBlockTime,stdtime" json:"LatestBlockTime"` } @@ -623,30 +623,31 @@ func init() { proto.RegisterFile("rpc.proto", fileDescriptorRpc) } func init() { golang_proto.RegisterFile("rpc.proto", fileDescriptorRpc) } var fileDescriptorRpc = []byte{ - // 397 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x51, 0x41, 0xcf, 0xd2, 0x40, - 0x10, 0x75, 0x05, 0xbf, 0x0f, 0x16, 0x12, 0x65, 0xe3, 0x61, 0xc3, 0xa1, 0xad, 0x9e, 0x7a, 0xd0, - 0xad, 0xd1, 0x10, 0xef, 0xd5, 0x44, 0x88, 0x86, 0x98, 0x4a, 0x34, 0xf1, 0x62, 0xda, 0x32, 0xb4, - 0x1b, 0xdb, 0x6e, 0xb3, 0xbb, 0x8d, 0xf6, 0x5f, 0xf8, 0x93, 0x3c, 0x72, 0xf4, 0xec, 0x01, 0x0d, - 0x1c, 0xfd, 0x13, 0x86, 0x85, 0x42, 0xc5, 0xc4, 0x8b, 0xb7, 0x79, 0xf3, 0x66, 0xde, 0xbc, 0x99, - 0xc1, 0x7d, 0x59, 0xc6, 0xac, 0x94, 0x42, 0x0b, 0xd2, 0x91, 0x65, 0x3c, 0x7e, 0x98, 0x70, 0x9d, - 0x56, 0x11, 0x8b, 0x45, 0xee, 0x25, 0x22, 0x11, 0x9e, 0xe1, 0xa2, 0x6a, 0x65, 0x90, 0x01, 0x26, - 0x3a, 0xf4, 0x8c, 0x87, 0xb1, 0xac, 0x4b, 0xdd, 0xa0, 0x3b, 0x1a, 0x8a, 0x25, 0xc8, 0x9c, 0x17, - 0xfa, 0x98, 0xb1, 0x13, 0x21, 0x92, 0x0c, 0xce, 0x2a, 0x9a, 0xe7, 0xa0, 0x74, 0x98, 0x97, 0x87, - 0x82, 0xfb, 0xbf, 0x3a, 0x78, 0x18, 0x80, 0xaa, 0x32, 0xfd, 0x46, 0x87, 0xba, 0x52, 0x84, 0xe2, - 0xeb, 0x67, 0x69, 0xc8, 0x8b, 0xd9, 0x73, 0x8a, 0x1c, 0xe4, 0xf6, 0x83, 0x06, 0x92, 0x47, 0xb8, - 0x37, 0x17, 0x4b, 0x98, 0x15, 0x2b, 0x41, 0x6f, 0x3a, 0xc8, 0x1d, 0x3c, 0xbe, 0xcb, 0x5a, 0x03, - 0x1b, 0x2e, 0x38, 0x55, 0x11, 0x07, 0x0f, 0xf6, 0xf1, 0x5b, 0x90, 0x8a, 0x8b, 0x82, 0x76, 0x8c, - 0x5e, 0x3b, 0x45, 0xde, 0xe1, 0xc1, 0x0b, 0x28, 0x40, 0x71, 0x35, 0x0d, 0x55, 0x4a, 0xbb, 0x0e, - 0x72, 0x87, 0xfe, 0x64, 0xbd, 0xb1, 0x6f, 0x7c, 0xdf, 0xd8, 0xed, 0x5b, 0xa4, 0x75, 0x09, 0x32, - 0x83, 0x65, 0x02, 0xd2, 0x8b, 0x2a, 0x29, 0xc5, 0x27, 0x2f, 0xe2, 0x45, 0x28, 0x6b, 0x36, 0x85, - 0xcf, 0x7e, 0xad, 0x41, 0x05, 0x6d, 0x25, 0x32, 0xc1, 0xfd, 0xd7, 0x55, 0x94, 0xf1, 0xf8, 0x25, - 0xd4, 0xf4, 0x96, 0x71, 0x3b, 0x62, 0xc7, 0x63, 0x9d, 0x08, 0xbf, 0xbb, 0x9f, 0x14, 0x9c, 0x2b, - 0xc9, 0x07, 0x7c, 0xfb, 0x55, 0xa8, 0x41, 0x69, 0x3f, 0x13, 0xf1, 0x47, 0xe3, 0xe9, 0xea, 0x7f, - 0x3c, 0x5d, 0xaa, 0x91, 0x07, 0x78, 0xd4, 0x4e, 0x01, 0x4f, 0x52, 0x4d, 0xaf, 0x1d, 0xe4, 0x76, - 0x83, 0xbf, 0x09, 0x32, 0xff, 0xc3, 0xce, 0x82, 0xe7, 0x40, 0x7b, 0x66, 0x97, 0x31, 0x3b, 0x3c, - 0x96, 0x35, 0x8f, 0x65, 0x8b, 0xe6, 0xb1, 0x7e, 0x6f, 0x6f, 0xf5, 0xcb, 0x0f, 0x1b, 0x05, 0x97, - 0xcd, 0xfe, 0xd3, 0xf5, 0xd6, 0x42, 0xdf, 0xb6, 0x16, 0xfa, 0xb9, 0xb5, 0xd0, 0xd7, 0x9d, 0x85, - 0xd6, 0x3b, 0x0b, 0xbd, 0xbf, 0xf7, 0xef, 0x9d, 0x64, 0x19, 0x47, 0x57, 0x66, 0xce, 0x93, 0xdf, - 0x01, 0x00, 0x00, 0xff, 0xff, 0x84, 0x6f, 0xc9, 0xec, 0xaf, 0x02, 0x00, 0x00, + // 403 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x51, 0xb1, 0x8e, 0xd3, 0x40, + 0x10, 0x65, 0x89, 0xb9, 0x4b, 0x36, 0x91, 0xe0, 0x56, 0x14, 0xab, 0x14, 0xb6, 0xa1, 0x72, 0xc3, + 0x1a, 0x1d, 0x3a, 0xd1, 0x1b, 0x24, 0xee, 0x04, 0x3a, 0x21, 0x13, 0x81, 0x44, 0x83, 0x6c, 0x67, + 0x62, 0xaf, 0xb0, 0xbd, 0xd6, 0xee, 0x5a, 0xe0, 0xbf, 0xe0, 0x93, 0x28, 0x53, 0x52, 0x53, 0x04, + 0x94, 0x74, 0x74, 0xfc, 0x01, 0xf2, 0x26, 0x4e, 0x4c, 0x90, 0x68, 0xae, 0x9b, 0x37, 0x6f, 0xe6, + 0xcd, 0x9b, 0x19, 0x3c, 0x92, 0x55, 0xc2, 0x2a, 0x29, 0xb4, 0x20, 0x03, 0x59, 0x25, 0xd3, 0x47, + 0x29, 0xd7, 0x59, 0x1d, 0xb3, 0x44, 0x14, 0x7e, 0x2a, 0x52, 0xe1, 0x1b, 0x2e, 0xae, 0x17, 0x06, + 0x19, 0x60, 0xa2, 0x6d, 0xcf, 0x74, 0x92, 0xc8, 0xa6, 0xd2, 0x1d, 0xba, 0xa7, 0xa1, 0x9c, 0x83, + 0x2c, 0x78, 0xa9, 0x77, 0x19, 0x27, 0x15, 0x22, 0xcd, 0xe1, 0xa0, 0xa2, 0x79, 0x01, 0x4a, 0x47, + 0x45, 0xb5, 0x2d, 0x78, 0xf8, 0x7b, 0x80, 0x27, 0x21, 0xa8, 0x3a, 0xd7, 0x6f, 0x74, 0xa4, 0x6b, + 0x45, 0x28, 0x3e, 0x7d, 0x96, 0x45, 0xbc, 0xbc, 0x7a, 0x4e, 0x91, 0x8b, 0xbc, 0x51, 0xd8, 0x41, + 0xf2, 0x18, 0x0f, 0xaf, 0xc5, 0x1c, 0xae, 0xca, 0x85, 0xa0, 0xb7, 0x5d, 0xe4, 0x8d, 0xcf, 0xef, + 0xb3, 0xde, 0xc0, 0x8e, 0x0b, 0xf7, 0x55, 0xc4, 0xc5, 0xe3, 0x36, 0x7e, 0x0b, 0x52, 0x71, 0x51, + 0xd2, 0x81, 0xd1, 0xeb, 0xa7, 0xc8, 0x3b, 0x3c, 0x7e, 0x01, 0x25, 0x28, 0xae, 0x2e, 0x23, 0x95, + 0x51, 0xcb, 0x45, 0xde, 0x24, 0xb8, 0x58, 0xae, 0x9c, 0x5b, 0xdf, 0x57, 0x4e, 0xff, 0x16, 0x59, + 0x53, 0x81, 0xcc, 0x61, 0x9e, 0x82, 0xf4, 0xe3, 0x5a, 0x4a, 0xf1, 0xc9, 0x8f, 0x79, 0x19, 0xc9, + 0x86, 0x5d, 0xc2, 0xe7, 0xa0, 0xd1, 0xa0, 0xc2, 0xbe, 0x12, 0xb9, 0xc0, 0xa3, 0xd7, 0x75, 0x9c, + 0xf3, 0xe4, 0x25, 0x34, 0xf4, 0x8e, 0x71, 0x7b, 0xc6, 0x76, 0xc7, 0xda, 0x13, 0x81, 0xd5, 0x4e, + 0x0a, 0x0f, 0x95, 0xe4, 0x03, 0xbe, 0xfb, 0x2a, 0xd2, 0xa0, 0x74, 0x90, 0x8b, 0xe4, 0xa3, 0xf1, + 0x74, 0x72, 0x13, 0x4f, 0xc7, 0x6a, 0xe4, 0x1c, 0x9f, 0xf5, 0x53, 0xc0, 0xd3, 0x4c, 0xd3, 0x53, + 0x17, 0x79, 0x56, 0x60, 0xfd, 0x6a, 0xcd, 0xfc, 0x4b, 0x93, 0xeb, 0xbf, 0x4c, 0xcd, 0x78, 0x01, + 0x74, 0x68, 0x36, 0x9a, 0xb2, 0xed, 0x7b, 0x59, 0xf7, 0x5e, 0x36, 0xeb, 0xde, 0x1b, 0x0c, 0x5b, + 0xc3, 0x5f, 0x7e, 0x38, 0x28, 0x3c, 0x6e, 0x0e, 0x9e, 0x2e, 0xd7, 0x36, 0xfa, 0xb6, 0xb6, 0xd1, + 0xcf, 0xb5, 0x8d, 0xbe, 0x6e, 0x6c, 0xb4, 0xdc, 0xd8, 0xe8, 0xfd, 0x83, 0xff, 0x6f, 0x26, 0xab, + 0x24, 0x3e, 0x31, 0x73, 0x9e, 0xfc, 0x09, 0x00, 0x00, 0xff, 0xff, 0xee, 0x3a, 0x76, 0xc2, 0xb5, + 0x02, 0x00, 0x00, } From e4bb6b2e7c2e5f9a88faf6c0b7c6771b6376376f Mon Sep 17 00:00:00 2001 From: Casey Kuhlman Date: Tue, 24 Jul 2018 10:11:49 +0100 Subject: [PATCH 25/28] upgrade bos version used for integration tests Signed-off-by: Casey Kuhlman --- scripts/deps/bos.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/deps/bos.sh b/scripts/deps/bos.sh index 778e5fa97..012ca71cd 100755 --- a/scripts/deps/bos.sh +++ b/scripts/deps/bos.sh @@ -2,4 +2,4 @@ # The git revision of Bosmarmot/bos we will build and install into ./bin/ for integration tests -echo "a8162471f2dfd1cae183f2aa2614fdd3dc1d5155" \ No newline at end of file +echo "681dc6d1420aa2db346323ad2e8aca28f21ee4b8" \ No newline at end of file From e711a217f70f4e1f41f16927940a588dd2d8e571 Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Tue, 24 Jul 2018 09:57:04 +0100 Subject: [PATCH 26/28] Fix various test flakes Signed-off-by: Silas Davis --- acm/balance/balance.go | 11 ++++- acm/balance/balance_test.go | 2 +- integration/governance/governance_test.go | 53 ++++++++++++++++++----- integration/tm/tm_server_test.go | 18 +++++--- 4 files changed, 67 insertions(+), 17 deletions(-) diff --git a/acm/balance/balance.go b/acm/balance/balance.go index 20b5cc85a..e8a927c73 100644 --- a/acm/balance/balance.go +++ b/acm/balance/balance.go @@ -1,6 +1,9 @@ package balance -import "fmt" +import ( + "fmt" + "sort" +) type Balances []Balance @@ -12,6 +15,11 @@ func New() Balances { return []Balance{} } +func (bs Balances) Sort() Balances { + sort.Stable(bs) + return bs +} + func (bs Balances) Len() int { return len(bs) } @@ -57,6 +65,7 @@ func Sum(bss ...Balances) Balances { for k, v := range sumMap { sum = sum.Add(k, v) } + sort.Stable(sum) return sum } diff --git a/acm/balance/balance_test.go b/acm/balance/balance_test.go index d6710e09a..d69157d46 100644 --- a/acm/balance/balance_test.go +++ b/acm/balance/balance_test.go @@ -11,7 +11,7 @@ func TestSum(t *testing.T) { one := New().Power(23223).Native(34).Native(1111) two := New().Power(3).Native(22) sum := one.Sum(two) - assert.Equal(t, New().Power(23226).Native(1167), sum) + assert.Equal(t, New().Power(23226).Native(1167).Sort(), sum) } func TestSort(t *testing.T) { diff --git a/integration/governance/governance_test.go b/integration/governance/governance_test.go index b188331c5..af9d045b7 100644 --- a/integration/governance/governance_test.go +++ b/integration/governance/governance_test.go @@ -41,7 +41,7 @@ func TestAlterValidators(t *testing.T) { alterPower(vs, 8, 9931) vs.Iterate(func(id crypto.Addressable, power *big.Int) (stop bool) { - _, err := govSync(t, tcli, governance.AlterPowerTx(inputAddress, id, power.Uint64())) + _, err := govSync(tcli, governance.AlterPowerTx(inputAddress, id, power.Uint64())) require.NoError(t, err) return }) @@ -52,16 +52,17 @@ func TestAlterValidators(t *testing.T) { assertValidatorsEqual(t, vs, vsOut) // Remove validator from chain - txe, err := govSync(t, tcli, governance.AlterPowerTx(inputAddress, account(3), 0)) + txe, err := govSync(tcli, governance.AlterPowerTx(inputAddress, account(3), 0)) // Mirror in our check set alterPower(vs, 3, 0) fmt.Println(txe.Events) vsOut = getValidatorHistory(t, qcli) assertValidatorsEqual(t, vs, vsOut) + // Now check Tendermint waitNBlocks(t, ecli, 3) - height := int64(kernels[4].Blockchain.LastBlockHeight()) - kernels[4].Node.ConfigureRPC() + height := int64(kernels[0].Blockchain.LastBlockHeight()) + kernels[0].Node.ConfigureRPC() tmVals, err := core.Validators(&height) require.NoError(t, err) vsOut = validator.NewTrimSet() @@ -74,14 +75,36 @@ func TestAlterValidators(t *testing.T) { assertValidatorsEqual(t, vs, vsOut) } +func TestAlterValidatorsTooQuickly(t *testing.T) { + grpcAddress := testConfigs[0].RPC.GRPC.ListenAddress + inputAddress := privateAccounts[0].Address() + tcli := rpctest.NewTransactClient(t, grpcAddress) + qcli := rpctest.NewQueryClient(t, grpcAddress) + + maxFlow := getMaxFlow(t, qcli) + acc1 := acm.GeneratePrivateAccountFromSecret("Foo1") + t.Logf("Changing power of new account %v to MaxFlow = %d that should succeed", acc1.Address(), maxFlow) + + _, err := govSync(tcli, governance.AlterPowerTx(inputAddress, acc1, maxFlow)) + require.NoError(t, err) + + maxFlow = getMaxFlow(t, qcli) + power := maxFlow + 1 + acc2 := acm.GeneratePrivateAccountFromSecret("Foo2") + t.Logf("Changing power of new account %v to MaxFlow + 1 = %d that should fail", acc2.Address(), power) + + _, err = govSync(tcli, governance.AlterPowerTx(inputAddress, acc2, power)) + require.Error(t, err) +} + func TestNoRootPermission(t *testing.T) { grpcAddress := testConfigs[0].RPC.GRPC.ListenAddress tcli := rpctest.NewTransactClient(t, grpcAddress) // Account does not have Root permission inputAddress := privateAccounts[4].Address() - _, err := govSync(t, tcli, governance.AlterPowerTx(inputAddress, account(5), 3433)) + _, err := govSync(tcli, governance.AlterPowerTx(inputAddress, account(5), 3433)) require.Error(t, err) - assert.Contains(t, err.Error(), errors.ErrorCodePermissionDenied.Error()) + assert.Contains(t, err.Error(), errors.PermissionDenied{Address: inputAddress, Perm: permission.Root}.Error()) } func TestAlterAmount(t *testing.T) { @@ -91,7 +114,7 @@ func TestAlterAmount(t *testing.T) { qcli := rpctest.NewQueryClient(t, grpcAddress) var amount uint64 = 18889 acc := account(5) - _, err := govSync(t, tcli, governance.AlterBalanceTx(inputAddress, acc, balance.New().Native(amount))) + _, err := govSync(tcli, governance.AlterBalanceTx(inputAddress, acc, balance.New().Native(amount))) require.NoError(t, err) ca, err := qcli.GetAccount(context.Background(), &rpcquery.GetAccountParam{Address: acc.Address()}) require.NoError(t, err) @@ -104,7 +127,7 @@ func TestAlterPermissions(t *testing.T) { tcli := rpctest.NewTransactClient(t, grpcAddress) qcli := rpctest.NewQueryClient(t, grpcAddress) acc := account(5) - _, err := govSync(t, tcli, governance.AlterPermissionsTx(inputAddress, acc, permission.Send)) + _, err := govSync(tcli, governance.AlterPermissionsTx(inputAddress, acc, permission.Send)) require.NoError(t, err) ca, err := qcli.GetAccount(context.Background(), &rpcquery.GetAccountParam{Address: acc.Address()}) require.NoError(t, err) @@ -123,13 +146,22 @@ func TestCreateAccount(t *testing.T) { qcli := rpctest.NewQueryClient(t, grpcAddress) var amount uint64 = 18889 acc := acm.GeneratePrivateAccountFromSecret("we almost certainly don't exist") - _, err := govSync(t, tcli, governance.AlterBalanceTx(inputAddress, acc, balance.New().Native(amount))) + _, err := govSync(tcli, governance.AlterBalanceTx(inputAddress, acc, balance.New().Native(amount))) require.NoError(t, err) ca, err := qcli.GetAccount(context.Background(), &rpcquery.GetAccountParam{Address: acc.Address()}) require.NoError(t, err) assert.Equal(t, amount, ca.Balance) } +func getMaxFlow(t testing.TB, qcli rpcquery.QueryClient) uint64 { + vs, err := qcli.GetValidatorSet(context.Background(), &rpcquery.GetValidatorSetParam{}) + require.NoError(t, err) + set := validator.UnpersistSet(vs.Set) + totalPower := set.TotalPower() + maxFlow := new(big.Int) + return maxFlow.Sub(maxFlow.Div(totalPower, big.NewInt(3)), big.NewInt(1)).Uint64() +} + func getValidatorHistory(t testing.TB, qcli rpcquery.QueryClient) *validator.Set { history, err := qcli.GetValidatorSet(context.Background(), &rpcquery.GetValidatorSetParam{ IncludeHistory: true, @@ -144,7 +176,7 @@ func account(i int) *acm.PrivateAccount { return rpctest.PrivateAccounts[i] } -func govSync(t testing.TB, cli rpctransact.TransactClient, tx *payload.GovTx) (*exec.TxExecution, error) { +func govSync(cli rpctransact.TransactClient, tx *payload.GovTx) (*exec.TxExecution, error) { return cli.BroadcastTxSync(context.Background(), &rpctransact.TxEnvelopeParam{ Payload: tx.Any(), }) @@ -166,6 +198,7 @@ func waitNBlocks(t testing.TB, ecli rpcevents.ExecutionEventsClient, n int) { }) defer stream.CloseSend() for i := 0; i < n; i++ { + fmt.Println("block") require.NoError(t, err) _, err = stream.Recv() } diff --git a/integration/tm/tm_server_test.go b/integration/tm/tm_server_test.go index 09ce3b581..c095365e0 100644 --- a/integration/tm/tm_server_test.go +++ b/integration/tm/tm_server_test.go @@ -19,7 +19,7 @@ package tm import ( "context" - "fmt" + "strconv" "strings" "testing" "time" @@ -194,13 +194,21 @@ func TestListValidators(t *testing.T) { } func TestDumpConsensusState(t *testing.T) { - startTime := time.Now() testWithAllClients(t, func(t *testing.T, clientName string, client tmclient.RPCClient) { resp, err := tmclient.DumpConsensusState(client) assert.NoError(t, err) - assert.NotZero(t, startTime) - assert.Equal(t, fmt.Sprintf("/0/%d", types.RoundStepNewHeight), - strings.TrimLeft(resp.RoundState.HeightRoundStep, "0123456789")) + hrs := strings.Split(resp.RoundState.HeightRoundStep, "/") + require.Len(t, hrs, 3) + // height + _, err = strconv.ParseUint(hrs[0], 10, 64) + require.NoError(t, err) + // round + _, err = strconv.ParseUint(hrs[1], 10, 64) + require.NoError(t, err) + step, err := strconv.ParseUint(hrs[2], 10, 8) + require.NoError(t, err) + + assert.True(t, step <= uint64(types.RoundStepCommit), "round step should be of proper enum type") }) } From 9de474a9affa0243f300138f1c4757c3d592e4e9 Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Tue, 24 Jul 2018 12:46:31 +0100 Subject: [PATCH 27/28] Prepare for 0.20.0 release Signed-off-by: Silas Davis --- scripts/deps/bos.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/deps/bos.sh b/scripts/deps/bos.sh index 012ca71cd..1f0aff807 100755 --- a/scripts/deps/bos.sh +++ b/scripts/deps/bos.sh @@ -2,4 +2,4 @@ # The git revision of Bosmarmot/bos we will build and install into ./bin/ for integration tests -echo "681dc6d1420aa2db346323ad2e8aca28f21ee4b8" \ No newline at end of file +echo "5b43575ee375e76804d1a0654b8f4edf350876d0" \ No newline at end of file From 126f8547a265cc05347541e89ef3d509c7abe1ba Mon Sep 17 00:00:00 2001 From: Silas Davis Date: Tue, 24 Jul 2018 13:40:43 +0100 Subject: [PATCH 28/28] Fix duplicated docs Signed-off-by: Silas Davis --- CHANGELOG.md | 4 +++- NOTES.md | 4 ++++ project/history.go | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b5b1250ab..38c65b5eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Hyperledger Burrow Changelog ## Version 0.20.0 -This is a major (pre-1.0.0) release that brings upgrades, and new grpc services. +This is a major (pre-1.0.0) release that introduces the ability to change the validator set through GovTx, transaction execution history, and fuller GRPC endpoint. #### Breaking changes - Address format has been changed (by Tendermint and we have followed suite) - conversion is possible but simpler to regenerated keys @@ -21,6 +21,8 @@ This is a major (pre-1.0.0) release that brings upgrades, and new grpc services. #### Bug fixes - Fixed panic on nil bounds for blocks service + + ## Version 0.19.0 This is a major (pre-1.0.0) release that brings upgrades, safety improvements, cloud configuration, and GRPC endpoints to Burrow. diff --git a/NOTES.md b/NOTES.md index ee42b8ae3..926edb3f7 100644 --- a/NOTES.md +++ b/NOTES.md @@ -1,3 +1,5 @@ +This is a major (pre-1.0.0) release that introduces the ability to change the validator set through GovTx, transaction execution history, and fuller GRPC endpoint. + #### Breaking changes - Address format has been changed (by Tendermint and we have followed suite) - conversion is possible but simpler to regenerated keys - JSON-RPC interface has been removed @@ -16,3 +18,5 @@ #### Bug fixes - Fixed panic on nil bounds for blocks service + + diff --git a/project/history.go b/project/history.go index d461c6edf..6be33f36a 100644 --- a/project/history.go +++ b/project/history.go @@ -29,7 +29,7 @@ func FullVersion() string { // release tagging script: ./scripts/tag_release.sh var History relic.ImmutableHistory = relic.NewHistory("Hyperledger Burrow").MustDeclareReleases( "0.20.0", - `This is a major (pre-1.0.0) release that brings upgrades, safety improvements, cloud configuration, and GRPC endpoints to Burrow. + `This is a major (pre-1.0.0) release that introduces the ability to change the validator set through GovTx, transaction execution history, and fuller GRPC endpoint. #### Breaking changes - Address format has been changed (by Tendermint and we have followed suite) - conversion is possible but simpler to regenerated keys