diff --git a/Makefile b/Makefile index 9219904..6911d52 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,5 @@ PROJECT_NAME := "tzpay" -VERSION := "v2.0.0" +VERSION := "v2.5.0-alpha" PKG := "github.com/goat-systems/$(PROJECT_NAME)" PKG_LIST := $(shell go list ${PKG}/... | grep -v /vendor/) GO_FILES := $(shell find . -name '*.go' | grep -v /vendor/ | grep -v _test.go) diff --git a/README.md b/README.md index 82a0cb1..4279541 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ go get -u github.com/goat-systems/tzpay/v2 ### Linux ``` -wget https://github.com/goat-systems/tzpay/releases/download/v2.3.0-alpha/tzpay_linux_amd64 +wget https://github.com/goat-systems/tzpay/releases/download/v2.5.0-alpha/tzpay_linux_amd64 sudo mv tzpay_linux_amd64 /usr/local/bin/tzpay sudo chmod a+x /usr/local/bin/tzpay ``` @@ -30,14 +30,7 @@ docker run --rm -ti goatsystems/tzpay:latest tzpay [command] \ ## Usage -### Initializing - -tzpay uses boltdb to safely store your edesk. You're edesk will be aes encrypted with you're wallet password as the key. -In order for tzpay to intialize this database you must first run tzpay with the `TZPAY_WALLET_SECRET` enviroment variable. - -`TZPAY_WALLET_SECRET` should be set to the edesk of your wallet. On the first run, tzpay will store the secret with aes encryption, and then remove the enviroment variable from the enviroment. It is recommend that you export this in your shell on your first run, so that it doesn't persist in a file somewhere. - -On you're first run you should have the following enviroment variables: +### Required Enviroment Variables ``` TZPAY_HOST_NODE= TZPAY_BAKERS_FEE= @@ -46,22 +39,12 @@ TZPAY_WALLET_SECRET= TZPAY_WALLET_PASSWORD= ``` - -### Required Enviroment Variables After Initialization -``` -TZPAY_HOST_NODE= -TZPAY_BAKERS_FEE= -TZPAY_DELEGATE= -TZPAY_WALLET_PASSWORD= -``` - ### Optional Enviroment Variables ``` -TZPAY_BLACKLIST= +TZPAY_BLACKLIST= TZPAY_NETWORK_GAS_LIMIT= TZPAY_NETWORK_FEE= TZPAY_MINIMUM_PAYMENT= -TZPAY_BOLT_DB= ``` ### Help diff --git a/cli/internal/baker/baker.go b/cli/internal/baker/baker.go deleted file mode 100644 index 25cc6ba..0000000 --- a/cli/internal/baker/baker.go +++ /dev/null @@ -1,250 +0,0 @@ -package baker - -import ( - "context" - "math/big" - - gotezos "github.com/goat-systems/go-tezos/v2" - "github.com/goat-systems/tzpay/v2/cli/internal/db/model" - "github.com/goat-systems/tzpay/v2/cli/internal/enviroment" - "github.com/pkg/errors" -) - -// Baker is a tezos baker that can get payouts and execute them. -type Baker struct { - gt gotezos.IFace -} - -type processDelegationsInput struct { - delegations *[]string - stakingBalance *big.Int - frozenBalanceRewards *gotezos.FrozenBalance - blockHash string -} - -type processDelegateInput struct { - delegate string - delegations []model.DelegationEarning - stakingBalance *big.Int - frozenBalanceRewards *gotezos.FrozenBalance - blockHash string -} - -type processDelegationsOutput struct { - delegationEarning model.DelegationEarning - err error -} - -type processDelegationInput struct { - delegation string - stakingBalance *big.Int - frozenBalanceRewards *gotezos.FrozenBalance - blockHash string -} - -// NewBaker returns a pointer to a new Baker -func NewBaker(gt gotezos.IFace) *Baker { - return &Baker{gt: gt} -} - -// Payouts returns all payouts for a cycle -func (b *Baker) Payouts(ctx context.Context, cycle int) (*model.Payout, error) { - params := enviroment.GetEnviromentFromContext(ctx) - frozenBalanceRewards, err := b.gt.FrozenBalance(cycle, params.Delegate) - if err != nil { - return nil, errors.Wrapf(err, "failed to get delegation earnings for cycle %d", cycle) - } - - delegations, err := b.gt.DelegatedContractsAtCycle(cycle, params.Delegate) - if err != nil { - return nil, errors.Wrapf(err, "failed to get delegation earnings for cycle %d", cycle) - } - - networkCycle, err := b.gt.Cycle(cycle) - if err != nil { - return nil, errors.Wrapf(err, "failed to get delegation earnings for cycle %d", cycle) - } - - stakingBalance, err := b.gt.StakingBalance(networkCycle.BlockHash, params.Delegate) - if err != nil { - return nil, errors.Wrapf(err, "failed to get delegation earnings for cycle %d", cycle) - } - - out := b.proccessDelegations(ctx, &processDelegationsInput{ - delegations: delegations, - stakingBalance: stakingBalance, - frozenBalanceRewards: frozenBalanceRewards, - blockHash: networkCycle.BlockHash, - }) - - payouts := model.Payout{ - StakingBalance: stakingBalance, - CycleHash: networkCycle.BlockHash, - Cycle: cycle, - FrozenBalance: frozenBalanceRewards.Rewards.Big, - } - - for _, delegation := range out { - if delegation.err != nil { - err = errors.Wrapf(delegation.err, "failed to get payout for delegation %s", delegation.delegationEarning.Address) - } else { - payouts.DelegationEarnings = append(payouts.DelegationEarnings, delegation.delegationEarning) - } - } - - payouts.DelegateEarnings, err = b.processDelegate(ctx, &processDelegateInput{ - delegate: params.Delegate, - delegations: payouts.DelegationEarnings, - stakingBalance: stakingBalance, - frozenBalanceRewards: frozenBalanceRewards, - blockHash: networkCycle.BlockHash, - }) - if err != nil { - err = errors.Wrap(err, "failed to get contruct payout info for delegate") - } - - payouts.DelegationEarnings = FilterEarnings(params.BlackList, payouts.DelegationEarnings) - - return &payouts, err -} - -func (b *Baker) processDelegate(ctx context.Context, input *processDelegateInput) (model.DelegateEarnings, error) { - delegateEarning := model.DelegateEarnings{ - Address: input.delegate, - Net: big.NewInt(0), - } - balance, err := b.gt.Balance(input.blockHash, input.delegate) - if err != nil { - return delegateEarning, errors.Wrapf(err, "failed to process delegate earnings for %s", input.delegate) - } - - delegateEarning.Share = float64(balance.Int64()) / float64(input.stakingBalance.Int64()) - rewardsFloat := delegateEarning.Share * float64(input.frozenBalanceRewards.Rewards.Big.Int64()) - delegateEarning.Rewards = big.NewInt(int64(rewardsFloat)) - - fees := big.NewInt(0) - for _, delegation := range input.delegations { - fees.Add(fees, delegation.Fee) - } - - delegateEarning.Fees = fees - delegateEarning.Net.Add(delegateEarning.Fees, delegateEarning.Rewards) - - return delegateEarning, nil -} - -func (b *Baker) proccessDelegations(ctx context.Context, input *processDelegationsInput) []processDelegationsOutput { - numJobs := len(*input.delegations) - jobs := make(chan processDelegationInput, numJobs) - results := make(chan processDelegationsOutput, numJobs) - - for i := 0; i < 50; i++ { - go b.proccessDelegationWorker(ctx, jobs, results) - } - - for _, pd := range *input.delegations { - jobs <- processDelegationInput{ - delegation: pd, - stakingBalance: input.stakingBalance, - frozenBalanceRewards: input.frozenBalanceRewards, - blockHash: input.blockHash, - } - } - close(jobs) - - var out []processDelegationsOutput - for i := 1; i <= numJobs; i++ { - out = append(out, <-results) - } - close(results) - - return out -} - -func (b *Baker) proccessDelegationWorker(ctx context.Context, jobs <-chan processDelegationInput, results chan<- processDelegationsOutput) { - for j := range jobs { - d, err := b.processDelegation(ctx, &j) - if err != nil { - results <- processDelegationsOutput{ - err: err, - } - } else { - results <- processDelegationsOutput{ - delegationEarning: *d, - } - } - } -} - -func (b *Baker) processDelegation(ctx context.Context, input *processDelegationInput) (*model.DelegationEarning, error) { - params := enviroment.GetEnviromentFromContext(ctx) - delegationEarning := &model.DelegationEarning{Address: input.delegation} - balance, err := b.gt.Balance(input.blockHash, input.delegation) - if err != nil { - return nil, errors.Wrapf(err, "failed to process delegation earnings for delegation %s", input.delegation) - } - - delegationEarning.Share = float64(balance.Int64()) / float64(input.stakingBalance.Int64()) - grossRewardsFloat := delegationEarning.Share * float64(input.frozenBalanceRewards.Rewards.Big.Int64()) - feeFloat := grossRewardsFloat * params.BakersFee - - delegationEarning.GrossRewards = big.NewInt(int64(grossRewardsFloat)) - delegationEarning.Fee = big.NewInt(int64(feeFloat)) - delegationEarning.NetRewards = big.NewInt(0).Sub(delegationEarning.GrossRewards, delegationEarning.Fee) - - return delegationEarning, nil -} - -// ForgePayout converts Payout into operation contents and forges them locally -func (b *Baker) ForgePayout(ctx context.Context, payout model.Payout) (string, int, error) { - base := enviroment.GetEnviromentFromContext(ctx) - head, err := b.gt.Head() - if err != nil { - return "", 0, errors.Wrap(err, "failed to forge payout") - } - - counter, err := b.gt.Counter(head.Hash, base.Wallet.Address) - if err != nil { - return "", 0, errors.Wrap(err, "failed to forge payout") - } - - transactions, lastCounter := b.constructPayoutContents(ctx, *counter, payout) - - forge, err := gotezos.ForgeTransactionOperation(head.Hash, transactions...) - if err != nil { - return "", lastCounter, errors.Wrap(err, "failed to forge payout") - } - - return *forge, lastCounter, nil -} - -func (b *Baker) constructPayoutContents(ctx context.Context, counter int, payout model.Payout) ([]gotezos.ForgeTransactionOperationInput, int) { - base := enviroment.GetEnviromentFromContext(ctx) - var contents []gotezos.ForgeTransactionOperationInput - for _, delegation := range payout.DelegationEarnings { - if delegation.NetRewards.Int64() >= int64(base.MinimumPayment) { - counter++ - contents = append(contents, gotezos.ForgeTransactionOperationInput{ - Source: base.Wallet.Address, - Destination: delegation.Address, - Amount: gotezos.Int{Big: delegation.NetRewards}, - Fee: gotezos.Int{Big: big.NewInt(int64(base.NetworkFee))}, //TODO: expose NewInt function in GoTezos - GasLimit: gotezos.Int{Big: big.NewInt(int64(base.GasLimit))}, - Counter: counter, - StorageLimit: gotezos.Int{Big: big.NewInt(int64(0))}, - }) - } - } - return contents, counter -} - -func FilterEarnings(blacklist enviroment.BlackList, delegationEarnings model.DelegationEarnings) model.DelegationEarnings { - var de model.DelegationEarnings - for _, delegation := range delegationEarnings { - if !blacklist.Contains(delegation.Address) { - de = append(de, delegation) - } - } - - return de -} diff --git a/cli/internal/baker/baker_test.go b/cli/internal/baker/baker_test.go deleted file mode 100644 index 4cd2546..0000000 --- a/cli/internal/baker/baker_test.go +++ /dev/null @@ -1,500 +0,0 @@ -package baker - -import ( - "context" - "math/big" - "sort" - "testing" - - gotezos "github.com/goat-systems/go-tezos/v2" - "github.com/goat-systems/tzpay/v2/cli/internal/db/model" - "github.com/goat-systems/tzpay/v2/cli/internal/enviroment" - "github.com/goat-systems/tzpay/v2/cli/internal/test" - "github.com/stretchr/testify/assert" -) - -func Test_processDelegation(t *testing.T) { - type want struct { - err bool - errContains string - delegationEarnings *model.DelegationEarning - } - - cases := []struct { - name string - input *processDelegationInput - want want - }{ - { - "is successful", - &processDelegationInput{ - stakingBalance: big.NewInt(100000000000), - frozenBalanceRewards: &gotezos.FrozenBalance{ - Rewards: gotezos.Int{Big: big.NewInt(800000000)}, - }, - }, - want{ - false, - "", - &model.DelegationEarning{Fee: big.NewInt(4000000), GrossRewards: big.NewInt(80000000), NetRewards: big.NewInt(76000000), Share: 0.1}, - }, - }, - { - "handles failure", - &processDelegationInput{ - stakingBalance: big.NewInt(100000000000), - frozenBalanceRewards: &gotezos.FrozenBalance{ - Rewards: gotezos.Int{Big: big.NewInt(800000000)}, - }, - }, - want{ - true, - "failed to get balance", - nil, - }, - }, - } - - for _, tt := range cases { - t.Run(tt.name, func(t *testing.T) { - baker := &Baker{ - gt: &test.GoTezosMock{ - BalanceErr: tt.want.err, - }, - } - out, err := baker.processDelegation(goldenContext, tt.input) - checkErr(t, tt.want.err, tt.want.errContains, err) - assert.Equal(t, tt.want.delegationEarnings, out) - }) - } -} - -func Test_processDelegations(t *testing.T) { - type want struct { - err bool - errcount int - successful int - } - - cases := []struct { - name string - input *processDelegationsInput - want want - }{ - { - "is successful", - &processDelegationsInput{ - delegations: &[]string{ - "some_delegation", - "some_delegation1", - "some_delegation2", - }, - stakingBalance: big.NewInt(100000000000), - frozenBalanceRewards: &gotezos.FrozenBalance{ - Rewards: gotezos.Int{Big: big.NewInt(800000000)}, - }, - }, - want{ - false, - 0, - 3, - }, - }, - { - "handles failure", - &processDelegationsInput{ - delegations: &[]string{ - "some_delegation", - "some_delegation1", - "some_delegation2", - }, - stakingBalance: big.NewInt(100000000000), - frozenBalanceRewards: &gotezos.FrozenBalance{ - Rewards: gotezos.Int{Big: big.NewInt(800000000)}, - }, - }, - want{ - true, - 3, - 0, - }, - }, - } - - for _, tt := range cases { - t.Run(tt.name, func(t *testing.T) { - baker := &Baker{ - gt: &test.GoTezosMock{ - BalanceErr: tt.want.err, - }, - } - - out := baker.proccessDelegations(goldenContext, tt.input) - successful := 0 - errcount := 0 - - for _, o := range out { - if o.err != nil { - errcount++ - } else { - successful++ - } - } - - assert.Equal(t, tt.want.successful, successful) - assert.Equal(t, tt.want.errcount, errcount) - }) - } -} - -func Test_Payouts(t *testing.T) { - type want struct { - err bool - errContains string - payouts *model.Payout - } - - cases := []struct { - name string - input gotezos.IFace - want want - }{ - { - "handles FrozenBalance failue", - &test.GoTezosMock{ - FrozenBalanceErr: true, - }, - want{ - true, - "failed to get delegation earnings for cycle 100: failed to get frozen balance", - nil, - }, - }, - { - "handles DelegatedContractsAtCycle failue", - &test.GoTezosMock{ - DelegatedContractsErr: true, - }, - want{ - true, - "failed to get delegation earnings for cycle 100: failed to get delegated contracts at cycle", - nil, - }, - }, - { - "handles Cycle failue", - &test.GoTezosMock{ - CycleErr: true, - }, - want{ - true, - "failed to get delegation earnings for cycle 100: failed to get cycle", - nil, - }, - }, - { - "handles StakingBalance failue", - &test.GoTezosMock{ - StakingBalanceErr: true, - }, - want{ - true, - "failed to get delegation earnings for cycle 100: failed to get staking balance", - nil, - }, - }, - { - "is successful", - &test.GoTezosMock{}, - want{ - false, - "", - &model.Payout{ - DelegationEarnings: model.DelegationEarnings{ - model.DelegationEarning{ - Address: "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", - Fee: big.NewInt(3500000), - GrossRewards: big.NewInt(70000000), - NetRewards: big.NewInt(66500000), - Share: 1, - }, - model.DelegationEarning{ - Address: "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", - Fee: big.NewInt(3500000), - GrossRewards: big.NewInt(70000000), - NetRewards: big.NewInt(66500000), - Share: 1, - }, - model.DelegationEarning{ - Address: "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", - Fee: big.NewInt(3500000), - GrossRewards: big.NewInt(70000000), - NetRewards: big.NewInt(66500000), - Share: 1, - }, - }, - DelegateEarnings: model.DelegateEarnings{ - Address: "somedelegate", - Fees: big.NewInt(10500000), - Share: 1, - Rewards: big.NewInt(70000000), - Net: big.NewInt(80500000), - }, - CycleHash: "some_hash", - Cycle: 100, - FrozenBalance: big.NewInt(70000000), - StakingBalance: big.NewInt(10000000000), - Operations: nil, - OperationsLink: nil, - }, - }, - }, - } - - for _, tt := range cases { - t.Run(tt.name, func(t *testing.T) { - baker := &Baker{gt: tt.input} - payout, err := baker.Payouts(goldenContext, 100) - checkErr(t, tt.want.err, tt.want.errContains, err) - - if tt.want.payouts != nil { - sort.Sort(tt.want.payouts.DelegationEarnings) - } - - if payout != nil { - sort.Sort(payout.DelegationEarnings) - } - - assert.Equal(t, tt.want.payouts, payout) - }) - } -} - -func Test_PayoutsSort(t *testing.T) { - delegationEarnings := model.DelegationEarnings{} - delegationEarnings = append(delegationEarnings, - []model.DelegationEarning{ - model.DelegationEarning{ - Address: "tz1c", - }, - model.DelegationEarning{ - Address: "tz1a", - }, - model.DelegationEarning{ - Address: "tz1b", - }, - }..., - ) - sort.Sort(&delegationEarnings) - - want := model.DelegationEarnings{} - want = append(want, - []model.DelegationEarning{ - model.DelegationEarning{ - Address: "tz1a", - }, - model.DelegationEarning{ - Address: "tz1b", - }, - model.DelegationEarning{ - Address: "tz1c", - }, - }..., - ) - - assert.Equal(t, want, delegationEarnings) -} - -func Test_ForgePayout(t *testing.T) { - type input struct { - payout model.Payout - gt gotezos.IFace - } - - type want struct { - err bool - errContains string - forge string - } - - cases := []struct { - name string - input input - want want - }{ - { - "is successful", - input{ - model.Payout{ - DelegationEarnings: model.DelegationEarnings{ - model.DelegationEarning{ - Address: "tz1SUgyRB8T5jXgXAwS33pgRHAKrafyg87Yc", - GrossRewards: big.NewInt(1000000), - NetRewards: big.NewInt(900000), - }, - model.DelegationEarning{ - Address: "tz1SUgyRB8T5jXgXAwS33pgRHAKrafyg87Yc", - GrossRewards: big.NewInt(1000000), - NetRewards: big.NewInt(950000), - }, - }, - }, - &test.GoTezosMock{}, - }, - want{ - false, - "", - "7cc601d2729c90b267e6a79d902f8b048d37fd990f2f7447efefb0cfb2f8e8a46c004b04ad1e57c2f13b61b3d2c95b3073d961a4132ba08d0665a08d0600a0f73600004b04ad1e57c2f13b61b3d2c95b3073d961a4132b006c004b04ad1e57c2f13b61b3d2c95b3073d961a4132ba08d0666a08d0600f0fd3900004b04ad1e57c2f13b61b3d2c95b3073d961a4132b00", - }, - }, - } - - for _, tt := range cases { - t.Run(tt.name, func(t *testing.T) { - baker := &Baker{gt: &test.GoTezosMock{}} - forge, _, err := baker.ForgePayout(goldenContext, tt.input.payout) - checkErr(t, tt.want.err, tt.want.errContains, err) - assert.Equal(t, tt.want.forge, forge) - }) - } -} - -func Test_constructPayoutContents(t *testing.T) { - type input struct { - counter int - payout model.Payout - } - - cases := []struct { - name string - input input - want []gotezos.ForgeTransactionOperationInput - }{ - { - "is successful", - input{ - 100, - model.Payout{ - DelegationEarnings: model.DelegationEarnings{ - model.DelegationEarning{ - Address: "somedelegation", - GrossRewards: big.NewInt(1000000), - NetRewards: big.NewInt(900000), - }, - model.DelegationEarning{ - Address: "someotherdelegation", - GrossRewards: big.NewInt(1000000), - NetRewards: big.NewInt(950000), - }, - }, - }, - }, - []gotezos.ForgeTransactionOperationInput{ - gotezos.ForgeTransactionOperationInput{ - Source: "tz1SUgyRB8T5jXgXAwS33pgRHAKrafyg87Yc", - Fee: gotezos.Int{Big: big.NewInt(100000)}, - Counter: 101, - GasLimit: gotezos.Int{Big: big.NewInt(100000)}, - StorageLimit: gotezos.Int{Big: big.NewInt(0)}, - Amount: gotezos.Int{Big: big.NewInt(900000)}, - Destination: "somedelegation", - }, - gotezos.ForgeTransactionOperationInput{ - Source: "tz1SUgyRB8T5jXgXAwS33pgRHAKrafyg87Yc", - Fee: gotezos.Int{Big: big.NewInt(100000)}, - Counter: 102, - GasLimit: gotezos.Int{Big: big.NewInt(100000)}, - StorageLimit: gotezos.Int{Big: big.NewInt(0)}, - Amount: gotezos.Int{Big: big.NewInt(950000)}, - Destination: "someotherdelegation", - }, - }, - }, - } - - for _, tt := range cases { - t.Run(tt.name, func(t *testing.T) { - baker := &Baker{gt: &test.GoTezosMock{}} - contents, _ := baker.constructPayoutContents(goldenContext, tt.input.counter, tt.input.payout) - assert.Equal(t, tt.want, contents) - }) - } -} - -func checkErr(t *testing.T, wantErr bool, errContains string, err error) { - if wantErr { - assert.Error(t, err) - assert.Contains(t, err.Error(), errContains) - } else { - assert.Nil(t, err) - } -} - -var goldenContext = context.WithValue( - context.TODO(), - enviroment.ENVIROMENTKEY, - &enviroment.ContextEnviroment{ - BakersFee: 0.05, - BlackList: []string{"somehash, somehash1"}, - Delegate: "somedelegate", - GasLimit: 100000, - HostNode: "http://somenode.com:8732", - MinimumPayment: 1000, - NetworkFee: 100000, - Wallet: gotezos.Wallet{ - Address: "tz1SUgyRB8T5jXgXAwS33pgRHAKrafyg87Yc", - }, - }, -) - -func Test_Filter(t *testing.T) { - type input struct { - blacklist enviroment.BlackList - delegationEarnings model.DelegationEarnings - } - - cases := []struct { - name string - input input - want model.DelegationEarnings - }{ - { - "is successfull", - input{ - enviroment.BlackList{ - "some_public_key_hash_10", - "some_public_key_hash_11", - }, - model.DelegationEarnings{ - { - Address: "some_public_key_hash_10", - }, - { - Address: "some_public_key_hash_11", - }, - { - Address: "some_public_key_hash_12", - }, - { - Address: "some_public_key_hash_13", - }, - }, - }, - model.DelegationEarnings{ - { - Address: "some_public_key_hash_12", - }, - { - Address: "some_public_key_hash_13", - }, - }, - }, - } - - for _, tt := range cases { - t.Run(tt.name, func(t *testing.T) { - delegationEarnings := FilterEarnings(tt.input.blacklist, tt.input.delegationEarnings) - assert.Equal(t, tt.want, delegationEarnings) - }) - } -} diff --git a/cli/internal/cmd/dryrun.go b/cli/internal/cmd/dryrun.go deleted file mode 100644 index fd018c0..0000000 --- a/cli/internal/cmd/dryrun.go +++ /dev/null @@ -1,80 +0,0 @@ -package cmd - -import ( - "strconv" - - gotezos "github.com/goat-systems/go-tezos/v2" - "github.com/goat-systems/tzpay/v2/cli/internal/baker" - "github.com/goat-systems/tzpay/v2/cli/internal/enviroment" - "github.com/goat-systems/tzpay/v2/cli/internal/print" - log "github.com/sirupsen/logrus" - "github.com/spf13/cobra" -) - -// NewDryRunCommand returns a new dryrun cobra command -func NewDryRunCommand() *cobra.Command { - var table bool - - var report = &cobra.Command{ - Use: "dryrun", - Short: "dryrun simulates a payout", - Long: "dryrun simulates a payout and prints the result in json or a table", - Example: `tzpay dryrun `, - Run: func(cmd *cobra.Command, args []string) { - if len(args) == 0 { - log.WithFields(nil).Fatal("Missing cycle as argument.") - } - dryrun(args[0], table) - }, - } - - report.PersistentFlags().BoolVarP(&table, "table", "t", false, "formats result into a table (Default: json)") - - return report -} - -func dryrun(arg string, table bool) { - cycle, err := strconv.Atoi(arg) - if err != nil { - log.WithFields(log.Fields{ - "error": err.Error(), - }).Fatal("Failed to read cycle argument.") - } - - ctx, err := enviroment.InitContext(nil) - if err != nil { - log.WithFields(log.Fields{ - "error": err.Error(), - }).Fatal("Failed to get enviroment and initialize context.") - } - - base := enviroment.GetEnviromentFromContext(ctx) - - gt, err := gotezos.New(base.HostNode) - if err != nil { - log.WithFields(log.Fields{ - "error": err.Error(), - }).Fatal("Failed to connect to node.") - } - baker := baker.NewBaker(gt) - - payouts, err := baker.Payouts(ctx, cycle) - if err != nil { - log.WithFields(log.Fields{ - "error": err.Error(), - }).Fatal("Failed to get payouts.") - } - - _, _, err = baker.ForgePayout(ctx, *payouts) - if err != nil { - log.WithFields(log.Fields{ - "error": err.Error(), - }).Fatal("Failed to forge operation.") - } - - if table { - print.Table(ctx, payouts) - } else { - print.JSON(payouts) - } -} diff --git a/cli/internal/cmd/history.go b/cli/internal/cmd/history.go deleted file mode 100644 index 1d619dd..0000000 --- a/cli/internal/cmd/history.go +++ /dev/null @@ -1 +0,0 @@ -package cmd diff --git a/cli/internal/cmd/run.go b/cli/internal/cmd/run.go deleted file mode 100644 index 836309e..0000000 --- a/cli/internal/cmd/run.go +++ /dev/null @@ -1,204 +0,0 @@ -package cmd - -import ( - "context" - "fmt" - "strconv" - "time" - - "github.com/pkg/errors" - - gotezos "github.com/goat-systems/go-tezos/v2" - "github.com/goat-systems/tzpay/v2/cli/internal/baker" - "github.com/goat-systems/tzpay/v2/cli/internal/db/model" - "github.com/goat-systems/tzpay/v2/cli/internal/enviroment" - "github.com/goat-systems/tzpay/v2/cli/internal/print" - log "github.com/sirupsen/logrus" - "github.com/spf13/cobra" -) - -var ( - confirmationDurationInterval = time.Second * 1 - confirmationTimoutInterval = time.Minute * 2 - confirm = true -) - -// NewRunCommand returns a new run cobra command -func NewRunCommand() *cobra.Command { - var table bool - var batchSize int - - var report = &cobra.Command{ - Use: "run", - Short: "run executes a batch payout", - Long: "run executes a batch payout and prints the result in json or a table", - Example: `tzpay run `, - Run: func(cmd *cobra.Command, args []string) { - if len(args) == 0 { - log.WithFields(nil).Fatal("Missing cycle as argument.") - } - runner, err := newRunner(newRunnerInput{ - cycle: args[0], - table: table, - batchSize: batchSize, - }) - if err != nil { - log.WithFields(log.Fields{ - "error": err.Error(), - }).Fatal("Failed to run payout.") - } - payout, err := runner.run() - if err != nil { - log.WithFields(log.Fields{ - "error": err.Error(), - }).Fatal("Failed to run payout.") - } - - runner.print(payout) - }, - } - - report.PersistentFlags().BoolVarP(&table, "table", "t", false, "formats result into a table (Default: json)") - report.PersistentFlags().IntVarP(&batchSize, "batch-size", "b", 125, "changes the size of the payout batches (too large may result in failure).") - - return report -} - -type runner struct { - ctx context.Context - base *enviroment.ContextEnviroment - cycle int - table bool - batchSize int -} - -type newRunnerInput struct { - cycle string - table bool - batchSize int - gt gotezos.IFace // only pass for testing -} - -func newRunner(input newRunnerInput) (*runner, error) { - cycle, err := strconv.Atoi(input.cycle) - if err != nil { - return nil, errors.New("failed to read cycle argument") - } - - ctx, err := enviroment.InitContext(input.gt) - if err != nil { - return nil, errors.Wrap(err, "failed to initialize enviroment") - } - - return &runner{ - ctx: ctx, - cycle: cycle, - table: input.table, - base: enviroment.GetEnviromentFromContext(ctx), - batchSize: input.batchSize, - }, nil -} - -func (r *runner) run() (*model.Payout, error) { - baker := baker.NewBaker(r.base.GoTezos) - - payout, err := baker.Payouts(r.ctx, r.cycle) - if err != nil { - return nil, err - } - - payouts := splitPayouts(*payout, r.batchSize) - - var operations []string - for i, p := range payouts { - forge, lastCounter, err := baker.ForgePayout(r.ctx, *p) - if err != nil { - return nil, err - } - - signedop, err := r.base.Wallet.SignOperation(forge) - if err != nil { - return nil, err - } - - op, err := r.base.GoTezos.InjectionOperation(&gotezos.InjectionOperationInput{ - Operation: &signedop, - }) - if err != nil { - return nil, err - } - - if confirm { - log.WithFields(log.Fields{ - "Injection": fmt.Sprintf("%d/%d", (i + 1), len(payouts)), - }).Info("Confirming Injection.") - - ok := r.ConfirmInjection(lastCounter) - if !ok { - return p, errors.New("failed to confirm injection") - } - } - - operations = append(operations, string(*op)) - } - - payout.SetOperations(operations...) - - return payout, nil -} - -func (r *runner) ConfirmInjection(lastCounter int) bool { - timer := time.After(confirmationTimoutInterval) - ticker := time.Tick(confirmationDurationInterval) - for { - select { - case <-ticker: - if head, err := r.base.GoTezos.Head(); err == nil { - if counter, err := r.base.GoTezos.Counter(head.Hash, r.base.Wallet.Address); err == nil { - if *counter == lastCounter { - return true - } - } - } - case <-timer: - return false - } - } -} - -// func (r *runner) save(payout *model.Payout) error { -// err := r.base.BoltDB.SavePayout(*payout) -// if err != nil { -// return errors.Wrap(err, "failed to save payout in tzpay.db") -// } -// return nil -// } - -func (r *runner) print(payout *model.Payout) { - if r.table { - print.Table(r.ctx, payout) - } else { - print.JSON(payout) - } -} - -func splitPayouts(payout model.Payout, split int) []*model.Payout { - var payouts []*model.Payout - if len(payout.DelegationEarnings) <= split { - payouts = append(payouts, &payout) - return payouts - } - for len(payout.DelegationEarnings) >= split { - p := &model.Payout{ - CycleHash: payout.CycleHash, - FrozenBalance: payout.FrozenBalance, - StakingBalance: payout.StakingBalance, - DelegateEarnings: payout.DelegateEarnings, - DelegationEarnings: payout.DelegationEarnings[:split], - } - payouts = append(payouts, p) - payout.DelegationEarnings = payout.DelegationEarnings[split:] - } - - return payouts -} diff --git a/cli/internal/cmd/run_test.go b/cli/internal/cmd/run_test.go deleted file mode 100644 index 81210b7..0000000 --- a/cli/internal/cmd/run_test.go +++ /dev/null @@ -1,401 +0,0 @@ -package cmd - -import ( - "math/big" - "os" - "testing" - "time" - - gotezos "github.com/goat-systems/go-tezos/v2" - "github.com/goat-systems/tzpay/v2/cli/internal/db/model" - "github.com/goat-systems/tzpay/v2/cli/internal/enviroment" - "github.com/goat-systems/tzpay/v2/cli/internal/test" - "github.com/stretchr/testify/assert" -) - -func Test_splitPayouts(t *testing.T) { - type input struct { - split int - payout *model.Payout - } - - type want struct { - payouts []model.Payout - } - - cases := []struct { - name string - input input - want want - }{ - { - "is successful", - input{ - split: 3, - payout: &model.Payout{ - DelegationEarnings: []model.DelegationEarning{ - model.DelegationEarning{ - Address: "tz1a", - }, - model.DelegationEarning{ - Address: "tz1b", - }, - model.DelegationEarning{ - Address: "tz1c", - }, - model.DelegationEarning{ - Address: "tz1d", - }, - model.DelegationEarning{ - Address: "tz1e", - }, - model.DelegationEarning{ - Address: "tz1f", - }, - model.DelegationEarning{ - Address: "tz1g", - }, - model.DelegationEarning{ - Address: "tz1h", - }, - model.DelegationEarning{ - Address: "tz1i", - }, - model.DelegationEarning{ - Address: "tz1j", - }, - model.DelegationEarning{ - Address: "tz1k", - }, - model.DelegationEarning{ - Address: "tz1l", - }, - model.DelegationEarning{ - Address: "tz1m", - }, - model.DelegationEarning{ - Address: "tz1n", - }, - model.DelegationEarning{ - Address: "tz1o", - }, - model.DelegationEarning{ - Address: "tz1p", - }, - model.DelegationEarning{ - Address: "tz1q", - }, - model.DelegationEarning{ - Address: "tz1r", - }, - model.DelegationEarning{ - Address: "tz1s", - }, - }, - }, - }, - want{ - payouts: []model.Payout{ - model.Payout{ - DelegationEarnings: []model.DelegationEarning{ - model.DelegationEarning{ - Address: "tz1a", - }, - model.DelegationEarning{ - Address: "tz1b", - }, - model.DelegationEarning{ - Address: "tz1c", - }, - }, - }, - model.Payout{ - DelegationEarnings: []model.DelegationEarning{ - model.DelegationEarning{ - Address: "tz1d", - }, - model.DelegationEarning{ - Address: "tz1e", - }, - model.DelegationEarning{ - Address: "tz1f", - }, - }, - }, - model.Payout{ - DelegationEarnings: []model.DelegationEarning{ - model.DelegationEarning{ - Address: "tz1g", - }, - model.DelegationEarning{ - Address: "tz1h", - }, - model.DelegationEarning{ - Address: "tz1i", - }, - }, - }, - model.Payout{ - DelegationEarnings: []model.DelegationEarning{ - model.DelegationEarning{ - Address: "tz1j", - }, - model.DelegationEarning{ - Address: "tz1k", - }, - model.DelegationEarning{ - Address: "tz1l", - }, - }, - }, - model.Payout{ - DelegationEarnings: []model.DelegationEarning{ - model.DelegationEarning{ - Address: "tz1m", - }, - model.DelegationEarning{ - Address: "tz1n", - }, - model.DelegationEarning{ - Address: "tz1o", - }, - }, - }, - model.Payout{ - DelegationEarnings: []model.DelegationEarning{ - model.DelegationEarning{ - Address: "tz1p", - }, - model.DelegationEarning{ - Address: "tz1q", - }, - model.DelegationEarning{ - Address: "tz1r", - }, - }, - }, - model.Payout{ - DelegationEarnings: []model.DelegationEarning{ - model.DelegationEarning{ - Address: "tz1s", - }, - }, - }, - }, - }, - }, - { - "is successful with 1 split", - input{ - split: 1, - payout: &model.Payout{ - DelegationEarnings: []model.DelegationEarning{ - model.DelegationEarning{ - Address: "tz1a", - }, - model.DelegationEarning{ - Address: "tz1b", - }, - model.DelegationEarning{ - Address: "tz1c", - }, - }, - }, - }, - want{ - []model.Payout{ - model.Payout{ - DelegationEarnings: []model.DelegationEarning{ - model.DelegationEarning{ - Address: "tz1a", - }, - }, - }, - model.Payout{ - DelegationEarnings: []model.DelegationEarning{ - model.DelegationEarning{ - Address: "tz1b", - }, - }, - }, - model.Payout{ - DelegationEarnings: []model.DelegationEarning{ - model.DelegationEarning{ - Address: "tz1c", - }, - }, - }, - }, - }, - }, - } - - for _, tt := range cases { - t.Run(tt.name, func(t *testing.T) { - payouts := splitPayouts(*tt.input.payout, tt.input.split) - for i := range payouts { - assert.Equal(t, tt.want.payouts[i], *payouts[i]) - } - }) - } -} - -func Test_run(t *testing.T) { - type input struct { - runnerInput newRunnerInput - } - - type want struct { - err bool - errContains string - payout *model.Payout - } - - cases := []struct { - name string - input input - want want - }{ - { - "is successful", - input{ - newRunnerInput{ - "130", - false, - 1, - &test.GoTezosMock{}, - }, - }, - want{ - false, - "", - &model.Payout{ - DelegationEarnings: model.DelegationEarnings{ - model.DelegationEarning{ - Address: "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", - Fee: big.NewInt(3500000), - GrossRewards: big.NewInt(70000000), - NetRewards: big.NewInt(66500000), - Share: 1, - }, - model.DelegationEarning{ - Address: "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", - Fee: big.NewInt(3500000), - GrossRewards: big.NewInt(70000000), - NetRewards: big.NewInt(66500000), - Share: 1, - }, - model.DelegationEarning{ - Address: "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", - Fee: big.NewInt(3500000), - GrossRewards: big.NewInt(70000000), - NetRewards: big.NewInt(66500000), - Share: 1, - }, - }, - DelegateEarnings: model.DelegateEarnings{ - Address: "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", - Fees: big.NewInt(10500000), - Share: 1, - Rewards: big.NewInt(70000000), - Net: big.NewInt(80500000), - }, - CycleHash: "some_hash", - Cycle: 130, - FrozenBalance: big.NewInt(70000000), - StakingBalance: big.NewInt(10000000000), - Operations: []string{"ooYympR9wfV98X4MUHtE78NjXYRDeMTAD4ei7zEZDqoHv2rfb1M", "ooYympR9wfV98X4MUHtE78NjXYRDeMTAD4ei7zEZDqoHv2rfb1M", "ooYympR9wfV98X4MUHtE78NjXYRDeMTAD4ei7zEZDqoHv2rfb1M"}, - OperationsLink: []string{"http://tzstats.com/ooYympR9wfV98X4MUHtE78NjXYRDeMTAD4ei7zEZDqoHv2rfb1M", "http://tzstats.com/ooYympR9wfV98X4MUHtE78NjXYRDeMTAD4ei7zEZDqoHv2rfb1M", "http://tzstats.com/ooYympR9wfV98X4MUHtE78NjXYRDeMTAD4ei7zEZDqoHv2rfb1M"}, - }, - }, - }, - } - - for _, tt := range cases { - t.Run(tt.name, func(t *testing.T) { - initTestEnv() - r, err := newRunner(tt.input.runnerInput) - assert.NoError(t, err) - - confirm = false - payout, err := r.run() - if tt.want.err { - assert.Error(t, err) - assert.Contains(t, err.Error(), tt.want.errContains) - } else { - assert.NoError(t, err) - } - - assert.Equal(t, tt.want.payout, payout) - uninitTestEnv() - }) - } -} - -func Test_ConfirmInjection(t *testing.T) { - type input struct { - counter int - gt gotezos.IFace - } - cases := []struct { - name string - input input - want bool - }{ - { - "is successful", - input{ - 100, - &test.GoTezosMock{}, - }, - true, - }, - { - "handles timeout", - input{ - 100, - &test.GoTezosMock{CounterErr: true}, - }, - false, - }, - } - - for _, tt := range cases { - t.Run(tt.name, func(t *testing.T) { - confirmationDurationInterval = time.Millisecond * 500 - confirmationTimoutInterval = time.Second * 1 - - r := runner{ - base: &enviroment.ContextEnviroment{ - GoTezos: tt.input.gt, - }, - } - - ok := r.ConfirmInjection(tt.input.counter) - assert.Equal(t, tt.want, ok) - }) - } -} - -var env = map[string]string{ - "TZPAY_BAKERS_FEE": "0.05", - "TZPAY_DELEGATE": "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", - "TZPAY_NETWORK_GAS_LIMIT": "100000", - "TZPAY_HOST_NODE": "http://somenode.com:8732", - "TZPAY_MINIMUM_PAYMENT": "1000", - "TZPAY_NETWORK_FEE": "100000", - "TZPAY_WALLET_SECRET": "edesk1fddn27MaLcQVEdZpAYiyGQNm6UjtWiBfNP2ZenTy3CFsoSVJgeHM9pP9cvLJ2r5Xp2quQ5mYexW1LRKee2", - "TZPAY_WALLET_PASSWORD": "password12345##", -} - -func initTestEnv() { - for key, elem := range env { - os.Setenv(key, string(elem)) - } -} - -func uninitTestEnv() { - for key := range env { - os.Unsetenv(key) - } -} diff --git a/cli/internal/db/db.go b/cli/internal/db/db.go deleted file mode 100644 index d657be5..0000000 --- a/cli/internal/db/db.go +++ /dev/null @@ -1,69 +0,0 @@ -package db - -import ( - "fmt" - "os" - "os/user" - - "github.com/boltdb/bolt" - gotezos "github.com/goat-systems/go-tezos/v2" - "github.com/pkg/errors" -) - -type bucketKey string - -const ( - walletBucket bucketKey = "WALLETBUCKET" - historyBucket bucketKey = "HISTORYBUCKET" - walletBucketSecret bucketKey = "edesk" -) - -// DB wraps bolt db functions -type DB struct { - bolt *bolt.DB - gt gotezos.IFace -} - -// New will open or create the tzpay boltdb profile -func New(gt gotezos.IFace, path string) (*DB, error) { - - if path == "" { - usr, err := user.Current() - if err != nil { - return &DB{}, errors.Wrap(err, "failed to open boltdb") - } - - if _, err := os.Stat(fmt.Sprintf("%s/.tzpay", usr.HomeDir)); os.IsNotExist(err) { - err = os.Mkdir(fmt.Sprintf("%s/.tzpay", usr.HomeDir), 0755) - if err != nil { - return &DB{}, errors.Wrap(err, "failed to open boltdb") - } - } - - path = fmt.Sprintf("%s/.tzpay/tzpay.db", usr.HomeDir) - } - db, err := bolt.Open(path, 0600, nil) - if err != nil { - return &DB{}, errors.Wrap(err, "failed to open boltdb") - } - err = db.Update(func(tx *bolt.Tx) error { - _, err = tx.CreateBucketIfNotExists([]byte(walletBucket)) - if err != nil { - return fmt.Errorf("create bucket: %s", err) - } - return nil - }) - - err = db.Update(func(tx *bolt.Tx) error { - _, err = tx.CreateBucketIfNotExists([]byte(historyBucket)) - if err != nil { - return fmt.Errorf("create bucket: %s", err) - } - return nil - }) - - return &DB{ - bolt: db, - gt: gt, - }, nil -} diff --git a/cli/internal/db/db_test.go b/cli/internal/db/db_test.go deleted file mode 100644 index d54895c..0000000 --- a/cli/internal/db/db_test.go +++ /dev/null @@ -1,16 +0,0 @@ -package db - -import ( - "os" - "testing" - - "github.com/stretchr/testify/assert" -) - -func Test_Open(t *testing.T) { - db, err := New(nil, "./tzpay.db") - assert.Nil(t, err) - assert.NotNil(t, db) - err = os.Remove("./tzpay.db") - assert.Nil(t, err) -} diff --git a/cli/internal/db/historybucket.go b/cli/internal/db/historybucket.go deleted file mode 100644 index 5f89e1d..0000000 --- a/cli/internal/db/historybucket.go +++ /dev/null @@ -1,83 +0,0 @@ -package db - -import ( - "encoding/json" - "fmt" - - "github.com/boltdb/bolt" - "github.com/goat-systems/tzpay/v2/cli/internal/db/model" - "github.com/pkg/errors" -) - -// SavePayout stores an executed run into the tzpay db for further reference -func (db *DB) SavePayout(payout model.Payout) error { - if err := db.bolt.Update(func(tx *bolt.Tx) error { - return db.storePayout(tx, payout) - }); err != nil { - return errors.Wrap(err, "failed to save payout in tzpay's history bucket") - } - - return nil -} - -func (db *DB) storePayout(tx *bolt.Tx, payout model.Payout) error { - b := tx.Bucket([]byte(string(historyBucket))) - if b == nil { - return errors.New("failed to open history bucket") - } - - payoutBytes, err := json.Marshal(&payout) - if err != nil { - errors.New("failed to open history bucket") - } - - fmt.Println(string(payoutBytes)) - err = b.Put([]byte(payout.CycleHash), payoutBytes) - if err != nil { - return errors.Wrap(err, "failed to put payout into history bucket") - } - - return nil -} - -// GetPayout retrieves a payout by cycle -func (db *DB) GetPayout(cycle int) (*model.Payout, error) { - networkCycle, err := db.gt.Cycle(cycle) - if err != nil { - return nil, errors.Wrap(err, "failed to get payout from history bucket") - } - - var payoutBytes []byte - if err := db.bolt.View(func(tx *bolt.Tx) error { - var err error - if payoutBytes, err = db.getPayout(tx, networkCycle.BlockHash); err != nil { - return err - } - - return nil - }); err != nil { - return nil, errors.Wrap(err, "failed to get payout from history bucket") - } - - var payout model.Payout - err = json.Unmarshal(payoutBytes, &payout) - if err != nil { - return nil, errors.Wrap(err, "failed to get payout from history bucket") - } - - return &payout, nil -} - -func (db *DB) getPayout(tx *bolt.Tx, blockhash string) ([]byte, error) { - b := tx.Bucket([]byte(string(historyBucket))) - if b == nil { - return nil, errors.New("failed to open history bucket") - } - - payout := b.Get([]byte(blockhash)) - if payout == nil { - return nil, fmt.Errorf("failed to get %s from history bucket", blockhash) - } - - return payout, nil -} diff --git a/cli/internal/db/historybucket_test.go b/cli/internal/db/historybucket_test.go deleted file mode 100644 index d9d978d..0000000 --- a/cli/internal/db/historybucket_test.go +++ /dev/null @@ -1,138 +0,0 @@ -package db - -import ( - "math/big" - "os" - "testing" - - gotezos "github.com/goat-systems/go-tezos/v2" - "github.com/goat-systems/tzpay/v2/cli/internal/db/model" - "github.com/pkg/errors" - "github.com/stretchr/testify/assert" -) - -func Test_SavePayout(t *testing.T) { - type want struct { - err bool - } - - cases := []struct { - name string - input model.Payout - want want - }{ - { - "is successful", - model.Payout{ - StakingBalance: big.NewInt(0), - CycleHash: "BLfEWKVudXH15N8nwHZehyLNjRuNLoJavJDjSZ7nq8ggfzbZ18p", - }, - want{ - false, - }, - }, - } - - for _, tt := range cases { - t.Run(tt.name, func(t *testing.T) { - db, err := New(nil, "./tzpay.db") - assert.Nil(t, err) - assert.NotNil(t, db) - - err = db.SavePayout(tt.input) - checkErr(t, tt.want.err, "", err) - - err = os.Remove("./tzpay.db") - assert.Nil(t, err) - }) - } -} - -func Test_GetPayout(t *testing.T) { - type input struct { - cycle int - payout model.Payout - } - - type want struct { - err bool - errContains string - payout *model.Payout - } - - cases := []struct { - name string - input input - want want - }{ - { - "is successful", - input{ - 10, - model.Payout{ - StakingBalance: big.NewInt(0), - CycleHash: "BLfEWKVudXH15N8nwHZehyLNjRuNLoJavJDjSZ7nq8ggfzbZ18p", - }, - }, - want{ - false, - "", - &model.Payout{ - StakingBalance: big.NewInt(0), - CycleHash: "BLfEWKVudXH15N8nwHZehyLNjRuNLoJavJDjSZ7nq8ggfzbZ18p", - }, - }, - }, - { - "handles cycle error", - input{ - 10, - model.Payout{ - StakingBalance: big.NewInt(0), - CycleHash: "BLfEWKVudXH15N8nwHZehyLNjRuNLoJavJDjSZ7nq8ggfzbZ18p", - }, - }, - want{ - true, - "failed to get payout from history bucket: failed to get cycle", - nil, - }, - }, - } - - for _, tt := range cases { - t.Run(tt.name, func(t *testing.T) { - db, err := New(nil, "./tzpay.db") - db.gt = &gotezosMock{cycleErr: tt.want.err} - assert.Nil(t, err) - assert.NotNil(t, db) - - err = db.SavePayout(tt.input.payout) - checkErr(t, false, "", err) - - payout, err := db.GetPayout(tt.input.cycle) - checkErr(t, tt.want.err, tt.want.errContains, err) - - assert.Equal(t, tt.want.payout, payout) - - err = os.Remove("./tzpay.db") - assert.Nil(t, err) - }) - } -} - -type gotezosMock struct { - gotezos.IFace - cycleErr bool -} - -func (g *gotezosMock) Cycle(cycle int) (*gotezos.Cycle, error) { - if g.cycleErr { - return &gotezos.Cycle{}, errors.New("failed to get cycle") - } - return &gotezos.Cycle{ - RandomSeed: "some_seed", - RollSnapshot: 10, - BlockHash: "BLfEWKVudXH15N8nwHZehyLNjRuNLoJavJDjSZ7nq8ggfzbZ18p", - }, nil -} diff --git a/cli/internal/db/model/model.go b/cli/internal/db/model/model.go deleted file mode 100644 index 79915c8..0000000 --- a/cli/internal/db/model/model.go +++ /dev/null @@ -1,81 +0,0 @@ -package model - -import ( - "fmt" - "math/big" - "unicode" -) - -// DelegationEarning - -type DelegationEarning struct { - Address string - Fee *big.Int - GrossRewards *big.Int - NetRewards *big.Int - Share float64 -} - -// DelegateEarnings - -type DelegateEarnings struct { - Address string - Fees *big.Int - Share float64 - Rewards *big.Int - Net *big.Int -} - -// Payout contains all needed information for a payout -type Payout struct { - DelegationEarnings DelegationEarnings `json:"delegaions"` - DelegateEarnings DelegateEarnings `json:"delegate"` - CycleHash string `json:"cycle_hash"` - Cycle int `json:"cycle"` - FrozenBalance *big.Int `json:"rewards"` - StakingBalance *big.Int `json:"staking_balance"` - Operations []string `json:"operation"` - OperationsLink []string `json:"operation_link"` -} - -// SetOperations will set Payout's operation string and link -func (p *Payout) SetOperations(operations ...string) { - p.Operations = append(p.Operations, operations...) - for _, operation := range operations { - p.OperationsLink = append(p.OperationsLink, fmt.Sprintf("http://tzstats.com/%s", operation)) - } -} - -// DelegationEarnings contains list of DelegationEarning and implements sort. -type DelegationEarnings []DelegationEarning - -func (d DelegationEarnings) Len() int { return len(d) } -func (d DelegationEarnings) Swap(i, j int) { - d[i], d[j] = d[j], d[i] -} - -func (d DelegationEarnings) Less(i, j int) bool { - iRunes := []rune(d[i].Address) - jRunes := []rune(d[j].Address) - - max := len(iRunes) - if max > len(jRunes) { - max = len(jRunes) - } - - for idx := 0; idx < max; idx++ { - ir := iRunes[idx] - jr := jRunes[idx] - - lir := unicode.ToLower(ir) - ljr := unicode.ToLower(jr) - - if lir != ljr { - return lir < ljr - } - - if ir != jr { - return ir < jr - } - } - - return false -} diff --git a/cli/internal/db/walletbucket.go b/cli/internal/db/walletbucket.go deleted file mode 100644 index ec36249..0000000 --- a/cli/internal/db/walletbucket.go +++ /dev/null @@ -1,141 +0,0 @@ -package db - -import ( - "crypto/aes" - "crypto/cipher" - "crypto/md5" - "crypto/rand" - "encoding/hex" - "io" - - "github.com/boltdb/bolt" - "github.com/pkg/errors" -) - -// InitWallet will initialize the storage of the edesk, and password. -// It will store the edesk, and password of the tezos wallet with a salted hash. -// This function call will unset TZPAY_WALLET_SECRET from the enviroment for safety -func (db *DB) InitWallet(password string, secret string) error { - if err := db.bolt.Update(func(tx *bolt.Tx) error { - return db.storeSecret(tx, password, secret) - }); err != nil { - return errors.Wrap(err, "failed to initialize wallet in tzpay bucket") - } - - return nil -} - -func (db *DB) storeSecret(tx *bolt.Tx, password, secret string) error { - b := tx.Bucket([]byte(string(walletBucket))) - if b == nil { - return errors.New("failed to open wallet bucket") - } - - encryptedSecret, err := encrypt([]byte(secret), password) - if err != nil { - return errors.Wrap(err, "failed to encrypt edesk") - } - - err = b.Put([]byte(string(walletBucketSecret)), encryptedSecret) - if err != nil { - return errors.Wrap(err, "failed to put edesk in wallet bucket") - } - - return nil -} - -// IsWalletInitialized will return an error if no wallet bucket exists, or -// the aes encrypted edesk is missing. -func (db *DB) IsWalletInitialized() bool { - if err := db.bolt.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte(string(walletBucket))) - if b == nil { - return errors.New("") - } - secretAES := b.Get([]byte(string(walletBucketSecret))) - if secretAES == nil { - return errors.New("") - } - - return nil - }); err != nil { - return false - } - - return true -} - -// GetSecret returns the decrpted string of the aes encrypted edesk -func (db *DB) GetSecret(password string) (string, error) { - var secret []byte - if err := db.bolt.View(func(tx *bolt.Tx) error { - var err error - if secret, err = db.getSecret(tx, password); err != nil { - return err - } - - return nil - }); err != nil { - return "", errors.Wrap(err, "failed to authorize") - } - - return string(secret), nil -} - -func (db *DB) getSecret(tx *bolt.Tx, password string) ([]byte, error) { - b := tx.Bucket([]byte(string(walletBucket))) - if b == nil { - return nil, errors.New("failed to open wallet bucket") - } - - secretAES := b.Get([]byte(string(walletBucketSecret))) - if secretAES == nil { - return nil, errors.New("failed to get aes encrypted secret") - } - - secret, err := decrypt(secretAES, password) - if err != nil { - return nil, errors.Wrap(err, "failed to decrypt secret") - } - - return secret, nil -} - -func encrypt(data []byte, passphrase string) ([]byte, error) { - block, _ := aes.NewCipher([]byte(createHash(passphrase))) - gcm, err := cipher.NewGCM(block) - if err != nil { - return nil, errors.Wrap(err, "failed to encrypt data with aes") - } - nonce := make([]byte, gcm.NonceSize()) - if _, err = io.ReadFull(rand.Reader, nonce); err != nil { - return nil, errors.Wrap(err, "failed to encrypt data with aes") - } - ciphertext := gcm.Seal(nonce, nonce, data, nil) - return ciphertext, nil -} - -func decrypt(data []byte, passphrase string) ([]byte, error) { - key := []byte(createHash(passphrase)) - block, err := aes.NewCipher(key) - if err != nil { - return nil, errors.Wrap(err, "failed to decrypt aes data") - } - gcm, err := cipher.NewGCM(block) - if err != nil { - return nil, errors.Wrap(err, "failed to decrypt aes data") - } - nonceSize := gcm.NonceSize() - nonce, ciphertext := data[:nonceSize], data[nonceSize:] - plaintext, err := gcm.Open(nil, nonce, ciphertext, nil) - if err != nil { - return nil, errors.Wrap(err, "failed to decrypt aes data") - } - return plaintext, nil -} - -func createHash(key string) string { - hasher := md5.New() - hasher.Write([]byte(key)) - return hex.EncodeToString(hasher.Sum(nil)) -} diff --git a/cli/internal/db/walletbucket_test.go b/cli/internal/db/walletbucket_test.go deleted file mode 100644 index 792fbe6..0000000 --- a/cli/internal/db/walletbucket_test.go +++ /dev/null @@ -1,204 +0,0 @@ -package db - -import ( - "os" - "testing" - - "github.com/stretchr/testify/assert" -) - -func Test_InitWallet(t *testing.T) { - type input struct { - secret string - password string - } - - type want struct { - err bool - } - - cases := []struct { - name string - input input - want want - }{ - { - "is successful", - input{ - "edesk1fddn27MaLcQVEdZpAYiyGQNm6UjtWiBfNP2ZenTy3CFsoSVJgeHM9pP9cvLJ2r5Xp2quQ5mYexW1LRKee2", - "password12345", - }, - want{ - false, - }, - }, - } - - for _, tt := range cases { - t.Run(tt.name, func(t *testing.T) { - db, err := New(nil, "./tzpay.db") - assert.Nil(t, err) - assert.NotNil(t, db) - - err = db.InitWallet(tt.input.password, tt.input.secret) - checkErr(t, tt.want.err, "", err) - - err = os.Remove("./tzpay.db") - assert.Nil(t, err) - }) - } -} - -func Test_GetSecret(t *testing.T) { - type store struct { - secret string - password string - } - - type input struct { - store store - password string - } - - type want struct { - err bool - errContains string - esesk string - } - - cases := []struct { - name string - input input - want want - }{ - { - "is successful", - input{ - store{ - "edesk1fddn27MaLcQVEdZpAYiyGQNm6UjtWiBfNP2ZenTy3CFsoSVJgeHM9pP9cvLJ2r5Xp2quQ5mYexW1LRKee2", - "password12345", - }, - "password12345", - }, - want{ - false, - "", - "edesk1fddn27MaLcQVEdZpAYiyGQNm6UjtWiBfNP2ZenTy3CFsoSVJgeHM9pP9cvLJ2r5Xp2quQ5mYexW1LRKee2", - }, - }, - { - "handles unauthorized", - input{ - store{ - "edesk1fddn27MaLcQVEdZpAYiyGQNm6UjtWiBfNP2ZenTy3CFsoSVJgeHM9pP9cvLJ2r5Xp2quQ5mYexW1LRKee2", - "password12345", - }, - "wrong password", - }, - want{ - true, - "failed to authorize", - "", - }, - }, - } - - for _, tt := range cases { - t.Run(tt.name, func(t *testing.T) { - db, err := New(nil, "./tzpay.db") - assert.Nil(t, err) - assert.NotNil(t, db) - - err = db.InitWallet(tt.input.store.password, tt.input.store.secret) - checkErr(t, false, "", err) - - edesk, err := db.GetSecret(tt.input.password) - checkErr(t, tt.want.err, tt.want.errContains, err) - - assert.Equal(t, tt.want.esesk, edesk) - - err = os.Remove("./tzpay.db") - assert.Nil(t, err) - }) - } -} - -func Test_IsWalletInitialized(t *testing.T) { - type store struct { - init bool - secret string - password string - } - - type input struct { - store store - password string - } - - type want struct { - ok bool - } - - cases := []struct { - name string - input input - want want - }{ - { - "is initialized", - input{ - store{ - true, - "edesk1fddn27MaLcQVEdZpAYiyGQNm6UjtWiBfNP2ZenTy3CFsoSVJgeHM9pP9cvLJ2r5Xp2quQ5mYexW1LRKee2", - "password12345", - }, - "password12345", - }, - want{ - true, - }, - }, - { - "is not initialized", - input{ - store{ - false, - "", - "", - }, - "wrong password", - }, - want{ - false, - }, - }, - } - - for _, tt := range cases { - t.Run(tt.name, func(t *testing.T) { - db, err := New(nil, "./tzpay.db") - assert.Nil(t, err) - assert.NotNil(t, db) - - if tt.input.store.init { - err = db.InitWallet(tt.input.store.password, tt.input.store.secret) - checkErr(t, false, "", err) - } - - ok := db.IsWalletInitialized() - assert.Equal(t, tt.want.ok, ok) - - err = os.Remove("./tzpay.db") - assert.Nil(t, err) - }) - } -} - -func checkErr(t *testing.T, wantErr bool, errContains string, err error) { - if wantErr { - assert.Error(t, err) - assert.Contains(t, err.Error(), errContains) - } else { - assert.Nil(t, err) - } -} diff --git a/cli/internal/enviroment/enviroment.go b/cli/internal/enviroment/enviroment.go deleted file mode 100644 index 7987b95..0000000 --- a/cli/internal/enviroment/enviroment.go +++ /dev/null @@ -1,196 +0,0 @@ -package enviroment - -import ( - "context" - "os" - "strings" - - cenv "github.com/caarlos0/env/v6" - "github.com/go-playground/validator" - gotezos "github.com/goat-systems/go-tezos/v2" - "github.com/goat-systems/tzpay/v2/cli/internal/db" - "github.com/pkg/errors" -) - -// ContextKey is a key to context for enviroment or wallet -type ContextKey string - -// BlackList contains a string of addresses not to be paid out -type BlackList []string - -var newgt = gotezos.New - -const ( - // ENVIROMENTKEY is a key to get the tzpay enviroment off of context - ENVIROMENTKEY ContextKey = "ffe0524c-a49c-401c-8b38-556b013fbdd4" - // WALLETKEY is a key to get the tzpay wallet off of context - WALLETKEY ContextKey = "43600f87-e1f7-4206-b1cc-7579a1532cc9" -) - -// Enviroment is the enviroment for a tzpay baker -type Enviroment struct { - BakersFee float64 `validate:"required" env:"TZPAY_BAKERS_FEE"` - BlackList string `env:"TZPAY_BLACKLIST"` - Delegate string `validate:"required" env:"TZPAY_DELEGATE"` - GasLimit int `env:"TZPAY_NETWORK_GAS_LIMIT" envDefault:"26283"` - HostNode string `validate:"required" env:"TZPAY_HOST_NODE"` - MinimumPayment int `env:"TZPAY_MINIMUM_PAYMENT" envDefault:"0"` - EarningsOnly bool `env:"TZPAY_EARNINGS_ONLY"` // If this is turned on, tzpay won't pay for missed blocks or endorsements - NetworkFee int `env:"TZPAY_NETWORK_FEE" envDefault:"2941"` - WalletSecret string `env:"TZPAY_WALLET_SECRET"` - WalletPassword string `validate:"required" env:"TZPAY_WALLET_PASSWORD"` - BoltDB string `env:"TZPAY_BOLT_DB"` -} - -// ContextEnviroment is the enviroment to be attatched to context -type ContextEnviroment struct { - BakersFee float64 - BlackList BlackList - Delegate string - GasLimit int - HostNode string - MinimumPayment int - EarningsOnly bool - NetworkFee int - BoltDB *db.DB - Password string - GoTezos gotezos.IFace - Wallet gotezos.Wallet -} - -// Contains returns true if the pkh is apart of BlackList -func (b *BlackList) Contains(pkh string) bool { - for _, addr := range *b { - if addr == pkh { - return true - } - } - - return false -} - -// GetEnviromentFromContext gets the Enviroment off context -func GetEnviromentFromContext(ctx context.Context) *ContextEnviroment { - val := ctx.Value(ENVIROMENTKEY) - env, _ := val.(*ContextEnviroment) - return env -} - -// setEnviromentToContext sets tzpays enviroment to context -func setEnviromentToContext(ctx context.Context, env *Enviroment, gt gotezos.IFace) (context.Context, error) { - cenv, err := enviromentToContextEnviroment(*env, gt) - if err != nil { - return ctx, errors.Wrap(err, "failed to set context enviroment") - } - - return context.WithValue(ctx, ENVIROMENTKEY, &cenv), nil -} - -// InitContext returns and validates the enviroment for tzpay in context -func InitContext(gt gotezos.IFace) (context.Context, error) { - env, err := loadEnviroment() - if err != nil { - return context.Background(), err - } - err = validate(env) - if err != nil { - return context.Background(), err - } - - ctx, err := setEnviromentToContext(context.Background(), env, gt) - if err != nil { - return ctx, err - } - - return ctx, nil -} - -func loadEnviroment() (*Enviroment, error) { - env := &Enviroment{} - if err := cenv.Parse(env); err != nil { - return env, errors.Wrap(err, "failed to load enviroment") - } - - return env, nil -} - -func validate(i interface{}) error { - validate := validator.New() - if err := validate.Struct(i); err != nil { - return errors.Wrap(err, "failed to load required parameters") - } - - return nil -} - -// ParseBlackList - -func ParseBlackList(list string) []string { - blacklist := strings.Split(list, ",") - for i := range blacklist { - blacklist[i] = strings.Trim(blacklist[i], " ") - } - - return blacklist -} - -func enviromentToContextEnviroment(env Enviroment, gt gotezos.IFace) (ContextEnviroment, error) { - if gt == nil { - var err error - gt, err = newgt(env.HostNode) - if err != nil { - return ContextEnviroment{}, errors.Wrap(err, "failed to connect to host node") - } - } - - // open tzpay db - db, err := db.New(gt, env.BoltDB) - if err != nil { - return ContextEnviroment{}, errors.Wrap(err, "failed to open tzpay db") - } - - // check if tzpay is initialized with a wallet by seeing if there is an edesk in the store - if env.WalletSecret == "" { - init := db.IsWalletInitialized() - if !init { - return ContextEnviroment{}, errors.New("failed to find existing wallet: initialize tzpay by passing TZPAY_WALLET_SECRET and TZPAY_WALLET_PASSWORD: please refer to the README") - } - } - - if env.WalletSecret != "" { - err := db.InitWallet(env.WalletPassword, env.WalletSecret) - if err != nil { - return ContextEnviroment{}, errors.Wrap(err, "failed to initialize wallet") - } - - err = os.Unsetenv("TZPAY_WALLET_SECRET") - if err != nil { - return ContextEnviroment{}, errors.Wrap(err, "failed to unset TZPAY_WALLET_SECRET from enviroment") - } - } - - secret, err := db.GetSecret(env.WalletPassword) - if err != nil { - return ContextEnviroment{}, errors.Wrap(err, "failed to get secret") - } - - wallet, err := gotezos.ImportEncryptedWallet(env.WalletPassword, secret) // TODO ImportEncryptedWallet second parameter name should be edesk - if err != nil { - return ContextEnviroment{}, errors.Wrap(err, "failed to set enviroment to context") - } - - blacklist := strings.Split(env.BlackList, " ,") - - return ContextEnviroment{ - BakersFee: env.BakersFee, - BlackList: blacklist, - Delegate: env.Delegate, - GasLimit: env.GasLimit, - HostNode: env.HostNode, - MinimumPayment: env.MinimumPayment, - EarningsOnly: env.EarningsOnly, - NetworkFee: env.NetworkFee, - GoTezos: gt, - BoltDB: db, - Wallet: *wallet, - }, nil -} diff --git a/cli/internal/enviroment/enviroment_test.go b/cli/internal/enviroment/enviroment_test.go deleted file mode 100644 index e6af343..0000000 --- a/cli/internal/enviroment/enviroment_test.go +++ /dev/null @@ -1,191 +0,0 @@ -package enviroment - -import ( - "context" - "os" - "testing" - - "github.com/stretchr/testify/assert" -) - -func Test_GetEnviromentFromContext(t *testing.T) { - env := &ContextEnviroment{} - ctx := context.WithValue(context.Background(), ENVIROMENTKEY, env) - outenv := GetEnviromentFromContext(ctx) - assert.Equal(t, env, outenv) -} -func Test_validate(t *testing.T) { - type Test struct { - Someval int `validate:"required"` - } - - cases := []struct { - name string - input Test - wantErr bool - }{ - { - "it is successful", - Test{10}, - false, - }, - { - "it handles error", - Test{}, - true, - }, - } - - for _, tt := range cases { - t.Run(tt.name, func(t *testing.T) { - err := validate(tt.input) - if tt.wantErr { - assert.NotNil(t, err) - } else { - assert.Nil(t, err) - } - }) - } -} - -func Test_loadEnviroment(t *testing.T) { - - type want struct { - err bool - env *Enviroment - } - - cases := []struct { - name string - env map[string]string - want want - }{ - { - "it is successful", - map[string]string{ - "TZPAY_BAKERS_FEE": "0.05", - "TZPAY_BLACKLIST": "somehash, somehash1", - "TZPAY_DELEGATE": "somedelegate", - "TZPAY_NETWORK_GAS_LIMIT": "100000", - "TZPAY_HOST_NODE": "http://somenode.com:8732", - "TZPAY_MINIMUM_PAYMENT": "1000", - "TZPAY_NETWORK_FEE": "100000", - "TZPAY_WALLET_SECRET": "edesk1fddn27MaLcQVEdZpAYiyGQNm6UjtWiBfNP2ZenTy3CFsoSVJgeHM9pP9cvLJ2r5Xp2quQ5mYexW1LRKee2", - "TZPAY_WALLET_PASSWORD": "password12345", - }, - want{ - false, - &Enviroment{ - BakersFee: 0.05, - BlackList: "somehash, somehash1", - Delegate: "somedelegate", - GasLimit: 100000, - HostNode: "http://somenode.com:8732", - MinimumPayment: 1000, - EarningsOnly: false, - NetworkFee: 100000, - WalletSecret: "edesk1fddn27MaLcQVEdZpAYiyGQNm6UjtWiBfNP2ZenTy3CFsoSVJgeHM9pP9cvLJ2r5Xp2quQ5mYexW1LRKee2", - WalletPassword: "password12345", - BoltDB: "", - }, - }, - }, - { - "is sucessful with missing fields", - map[string]string{ - "TZPAY_BAKERS_FEE": "0.05", - }, - want{ - false, - &Enviroment{ - BakersFee: 0.05, - GasLimit: 26283, - NetworkFee: 2941, - }, - }, - }, - } - - for _, tt := range cases { - t.Run(tt.name, func(t *testing.T) { - for key, elem := range tt.env { - os.Setenv(key, string(elem)) - } - - env, err := loadEnviroment() - if tt.want.err { - assert.NotNil(t, err) - } else { - assert.Nil(t, err) - } - - assert.Equal(t, tt.want.env, env) - - for key := range tt.env { - os.Unsetenv(key) - } - }) - } -} - -func Test_ParseBlackList(t *testing.T) { - cases := []struct { - name string - input string - want []string - }{ - { - "is successful", - "some_address, some_other_address, yet_another_address", - []string{ - "some_address", - "some_other_address", - "yet_another_address", - }, - }, - } - - for _, tt := range cases { - t.Run(tt.name, func(t *testing.T) { - out := ParseBlackList(tt.input) - assert.Equal(t, tt.want, out) - }) - } -} - -func Test_Contains(t *testing.T) { - cases := []struct { - name string - pkh string - want bool - }{ - { - "handles true", - "tz1a", - true, - }, - - { - "handles false", - "tz1z", - false, - }, - } - - for _, tt := range cases { - t.Run(tt.name, func(t *testing.T) { - var blacklist BlackList = []string{ - "tz1a", - "tz1b", - "tz1c", - "tz1d", - "tz1e", - "tz1f", - "tz1g", - } - ok := blacklist.Contains(tt.pkh) - assert.Equal(t, tt.want, ok) - }) - - } -} diff --git a/cli/internal/prompt/prompt.go b/cli/internal/prompt/prompt.go deleted file mode 100644 index ee10351..0000000 --- a/cli/internal/prompt/prompt.go +++ /dev/null @@ -1,4 +0,0 @@ -package prompt - -// type Prompt struct { -// } diff --git a/cli/root.go b/cli/root.go deleted file mode 100644 index 6796e3a..0000000 --- a/cli/root.go +++ /dev/null @@ -1,27 +0,0 @@ -package cli - -import ( - "github.com/goat-systems/tzpay/v2/cli/internal/cmd" - "github.com/spf13/cobra" -) - -func newRootCommand() *cobra.Command { - rootCommand := &cobra.Command{ - Use: "tzpay", - Short: "A bulk payout tool for bakers in the Tezos Ecosystem", - } - - rootCommand.AddCommand( - cmd.NewDryRunCommand(), - cmd.NewRunCommand(), - cmd.NewVersionCommand(), - cmd.NewSetupCommand(), - ) - - return rootCommand -} - -// Execute executes the user command. -func Execute() error { - return newRootCommand().Execute() -} diff --git a/go.mod b/go.mod index 41f92ec..f7da9e4 100644 --- a/go.mod +++ b/go.mod @@ -3,12 +3,10 @@ module github.com/goat-systems/tzpay/v2 go 1.13 require ( - github.com/DefinitelyNotAGoat/go-tezos v1.0.9 - github.com/boltdb/bolt v1.3.1 + github.com/btcsuite/btcutil v1.0.2 // indirect github.com/caarlos0/env/v6 v6.2.1 - github.com/go-playground/validator v9.31.0+incompatible - github.com/go-playground/validator/v10 v10.2.0 // indirect - github.com/goat-systems/go-tezos/v2 v2.6.0-alpha + github.com/go-playground/validator/v10 v10.2.0 + github.com/goat-systems/go-tezos/v2 v2.7.0-alpha github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect github.com/mattn/go-runewidth v0.0.8 // indirect github.com/olekukonko/tablewriter v0.0.4 @@ -17,7 +15,6 @@ require ( github.com/spf13/cobra v0.0.6 github.com/spf13/pflag v1.0.5 // indirect github.com/stretchr/testify v1.5.1 - golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073 // indirect - golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527 // indirect - gopkg.in/go-playground/assert.v1 v1.2.1 // indirect + golang.org/x/crypto v0.0.0-20200427165652-729f1e841bcc // indirect + golang.org/x/sys v0.0.0-20200427175716-29b57079015a // indirect ) diff --git a/go.sum b/go.sum index 5a87045..84e9b2b 100644 --- a/go.sum +++ b/go.sum @@ -12,13 +12,13 @@ github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRF github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= -github.com/boltdb/bolt v1.3.1 h1:JQmyP4ZBrce+ZQu0dY660FMfatumYDLun9hBCUVIkF4= -github.com/boltdb/bolt v1.3.1/go.mod h1:clJnj/oiGkjum5o1McbSZDSLxVThjynRyGBgiAx27Ps= github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ= github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA= github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= github.com/btcsuite/btcutil v1.0.1 h1:GKOz8BnRjYrb/JTKgaOk+zh26NWNdSNvdvv0xoAZMSA= github.com/btcsuite/btcutil v1.0.1/go.mod h1:j9HUFwoQRsZL3V4n+qG+CUnEGHOarIxfC3Le2Yhbcts= +github.com/btcsuite/btcutil v1.0.2 h1:9iZ1Terx9fMIOtq1VrwdqfsATL9MC2l8ZrUY6YZ2uts= +github.com/btcsuite/btcutil v1.0.2/go.mod h1:j9HUFwoQRsZL3V4n+qG+CUnEGHOarIxfC3Le2Yhbcts= github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg= github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVaaLLH7j4eDXPRvw78tMflu7Ie2bzYOH4Y8rRKBY= github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc= @@ -53,14 +53,12 @@ github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8c github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= -github.com/go-playground/validator v9.31.0+incompatible h1:UA72EPEogEnq76ehGdEDp4Mit+3FDh548oRqwVgNsHA= -github.com/go-playground/validator v9.31.0+incompatible/go.mod h1:yrEkQXlcI+PugkyDjY2bRrL/UBU4f3rvrgkN3V8JEig= github.com/go-playground/validator/v10 v10.1.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI= github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1Vv0sFl1UcHBOY= github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/goat-systems/go-tezos/v2 v2.6.0-alpha h1:OvRtgTaEcdZtkdZcq7bQJhN1851CYheyb7r3SZrXlSk= -github.com/goat-systems/go-tezos/v2 v2.6.0-alpha/go.mod h1:cOs4TyAFZWnwg4syEAAOJGZNduIjGD2e4oov8K67NCw= +github.com/goat-systems/go-tezos/v2 v2.7.0-alpha h1:M/IfNccEd1zC4zkAeS9GqdUnVvwwY+dd93uY0KLIZZU= +github.com/goat-systems/go-tezos/v2 v2.7.0-alpha/go.mod h1:1FrQJqxudeduGbDc1XEww+X3EYzVvEzyyaN6LdVYAwc= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= @@ -182,8 +180,8 @@ golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200115085410-6d4e4cb37c7d h1:2+ZP7EfsZV7Vvmx3TIqSlSzATMkTAKqM14YGFPoSKjI= golang.org/x/crypto v0.0.0-20200115085410-6d4e4cb37c7d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073 h1:xMPOj6Pz6UipU1wXLkrtqpHbR0AVFnyPEQq/wRWz9lM= -golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200427165652-729f1e841bcc h1:ZGI/fILM2+ueot/UixBSoj9188jCAxVHEZEGhqq67I4= +golang.org/x/crypto v0.0.0-20200427165652-729f1e841bcc/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20200130185559-910be7a94367 h1:0IiAsCRByjO2QjX7ZPkw5oU9x+n1YqRL802rjC0c3Aw= @@ -216,8 +214,8 @@ golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc= golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527 h1:uYVVQ9WP/Ds2ROhcaGPeIdVq0RIXVLwsHlnvJ+cT1So= -golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200427175716-29b57079015a h1:08u6b1caTT9MQY4wSbmsd4Ulm6DmgNYnbImBuZjGJow= +golang.org/x/sys v0.0.0-20200427175716-29b57079015a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= @@ -246,8 +244,6 @@ gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33 gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/go-playground/assert.v1 v1.2.1 h1:xoYuJVE7KT85PYWrN730RguIQO0ePzVRfFMXadIrXTM= -gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= diff --git a/internal/cmd/dryrun.go b/internal/cmd/dryrun.go new file mode 100644 index 0000000..5fa5139 --- /dev/null +++ b/internal/cmd/dryrun.go @@ -0,0 +1,108 @@ +package cmd + +import ( + "strconv" + + gotezos "github.com/goat-systems/go-tezos/v2" + "github.com/goat-systems/tzpay/v2/internal/enviroment" + "github.com/goat-systems/tzpay/v2/internal/payout" + "github.com/goat-systems/tzpay/v2/internal/print" + log "github.com/sirupsen/logrus" + "github.com/spf13/cobra" +) + +// DryRun configures and exposes functions to allow tzpay to simulate a payout without injecting it into the network. +type DryRun struct { + gt gotezos.IFace + bakersFee float64 + delegate string + gasLimit int + minimumPayment int + networkFee int + blackList []string +} + +// DryRunInput is the input for NewDryRun +type DryRunInput struct { + GoTezos gotezos.IFace + BakersFee float64 + Delegate string + GasLimit int + MinimumPayment int + NetworkFee int + BlackList []string +} + +// NewDryRun returns a pointer to a DryRun +func NewDryRun(input DryRunInput) *DryRun { + return &DryRun{ + gt: input.GoTezos, + bakersFee: input.BakersFee, + delegate: input.Delegate, + gasLimit: input.GasLimit, + minimumPayment: input.MinimumPayment, + networkFee: input.NetworkFee, + blackList: input.BlackList, + } +} + +// DryRunCommand returns the cobra command for dryrun +func DryRunCommand() *cobra.Command { + var table bool + + var dryrun = &cobra.Command{ + Use: "dryrun", + Short: "dryrun simulates a payout", + Long: "dryrun simulates a payout and prints the result in json or a table", + Example: `tzpay dryrun `, + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 0 { + log.Fatal("Missing cycle as argument.") + } + + env, err := enviroment.NewDryRunEnviroment() + if err != nil { + log.WithField("error", err.Error()).Fatal("Failed to load enviroment.") + } + + NewDryRun(DryRunInput{ + GoTezos: env.GoTezos, + BakersFee: env.BakersFee, + Delegate: env.Delegate, + GasLimit: env.GasLimit, + MinimumPayment: env.MinimumPayment, + NetworkFee: env.NetworkFee, + BlackList: env.BlackList, + }).execute(args[0], table) + }, + } + + dryrun.PersistentFlags().BoolVarP(&table, "table", "t", false, "formats result into a table (Default: json)") + + return dryrun +} + +func (d *DryRun) execute(arg string, table bool) { + cycle, err := strconv.Atoi(arg) + if err != nil { + log.Fatal("Failed to parse cycle argument into integer.") + } + + report, err := payout.NewPayout(payout.NewPayoutInput{ + GoTezos: d.gt, + Cycle: cycle, + Delegate: d.delegate, + BakerFee: d.bakersFee, + MinPayment: d.minimumPayment, + BlackList: d.blackList, + BatchSize: 125, + NetworkFee: d.networkFee, + GasLimit: d.gasLimit, + }).Execute() + + if table { + print.Table(d.delegate, "", report) + } else { + print.JSON(report) + } +} diff --git a/internal/cmd/run.go b/internal/cmd/run.go new file mode 100644 index 0000000..e4e2ce1 --- /dev/null +++ b/internal/cmd/run.go @@ -0,0 +1,119 @@ +package cmd + +import ( + "strconv" + + gotezos "github.com/goat-systems/go-tezos/v2" + "github.com/goat-systems/tzpay/v2/internal/enviroment" + "github.com/goat-systems/tzpay/v2/internal/payout" + "github.com/goat-systems/tzpay/v2/internal/print" + log "github.com/sirupsen/logrus" + "github.com/spf13/cobra" +) + +// Run configures and exposes functions to allow tzpay inject a payout into the tezos network. +type Run struct { + gt gotezos.IFace + bakersFee float64 + delegate string + gasLimit int + minimumPayment int + networkFee int + blackList []string + wallet gotezos.Wallet +} + +// RunInput is the input for NewDryRun +type RunInput struct { + GoTezos gotezos.IFace + BakersFee float64 + Delegate string + GasLimit int + MinimumPayment int + NetworkFee int + BlackList []string + Wallet gotezos.Wallet +} + +// NewRun returns a pointer to a Run +func NewRun(input RunInput) *Run { + return &Run{ + gt: input.GoTezos, + bakersFee: input.BakersFee, + delegate: input.Delegate, + gasLimit: input.GasLimit, + minimumPayment: input.MinimumPayment, + networkFee: input.NetworkFee, + blackList: input.BlackList, + wallet: input.Wallet, + } +} + +// RunCommand returns a new run cobra command +func RunCommand() *cobra.Command { + var table bool + var batchSize int + var verbose bool + + var run = &cobra.Command{ + Use: "run", + Short: "run executes a batch payout", + Long: "run executes a batch payout and prints the result in json or a table", + Example: `tzpay run `, + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 0 { + log.Fatal("Missing cycle as argument.") + } + + env, err := enviroment.NewRunEnviroment() + if err != nil { + log.WithField("error", err.Error()).Fatal("Failed to load enviroment.") + } + + NewRun(RunInput{ + GoTezos: env.GoTezos, + BakersFee: env.BakersFee, + Delegate: env.Delegate, + GasLimit: env.GasLimit, + MinimumPayment: env.MinimumPayment, + NetworkFee: env.NetworkFee, + BlackList: env.BlackList, + Wallet: env.Wallet, + }).execute(args[0], batchSize, verbose, table) + }, + } + + run.PersistentFlags().BoolVarP(&table, "table", "t", false, "formats result into a table (Default: json)") + run.PersistentFlags().IntVarP(&batchSize, "batch-size", "b", 125, "changes the size of the payout batches (too large may result in failure).") + run.PersistentFlags().BoolVarP(&verbose, "verbose", "v", true, "will print confirmations in between injections.") + + return run +} + +func (r *Run) execute(arg string, batchSize int, verbose, table bool) { + cycle, err := strconv.Atoi(arg) + if err != nil { + log.WithField("error", err.Error()).Fatal("Failed to parse cycle argument into integer.") + } + + report, err := payout.NewPayout(payout.NewPayoutInput{ + GoTezos: r.gt, + Cycle: cycle, + Delegate: r.delegate, + BakerFee: r.bakersFee, + MinPayment: r.minimumPayment, + BlackList: r.blackList, + BatchSize: batchSize, + NetworkFee: r.networkFee, + GasLimit: r.gasLimit, + Inject: true, + Verbose: verbose, + Wallet: r.wallet, + }).Execute() + + if table { + print.Table(r.delegate, r.wallet.Address, report) + } else { + print.JSON(report) + } +} diff --git a/cli/internal/cmd/setup.go b/internal/cmd/setup.go similarity index 86% rename from cli/internal/cmd/setup.go rename to internal/cmd/setup.go index 03d36de..6a5e872 100644 --- a/cli/internal/cmd/setup.go +++ b/internal/cmd/setup.go @@ -9,7 +9,7 @@ import ( // NewSetupCommand returns a new setup cobra command func NewSetupCommand() *cobra.Command { - var version = &cobra.Command{ + var setup = &cobra.Command{ Use: "setup", Short: "setup prints a list of enviroment variables needed to get started.", Example: `tzpay setup`, @@ -22,7 +22,7 @@ func NewSetupCommand() *cobra.Command { sb.WriteString("TZPAY_WALLET_SECRET=\n") sb.WriteString("TZPAY_WALLET_PASSWORD=\n\n") sb.WriteString("###### OPTIONAL ENVIROMENT VARIABLES ######\n") - sb.WriteString("TZPAY_BLACKLIST=\n") + sb.WriteString("TZPAY_BLACKLIST=\n") sb.WriteString("TZPAY_NETWORK_GAS_LIMIT=\n") sb.WriteString("TZPAY_NETWORK_FEE=\n") sb.WriteString("TZPAY_MINIMUM_PAYMENT=\n") @@ -30,5 +30,5 @@ func NewSetupCommand() *cobra.Command { fmt.Println(sb.String()) }, } - return version + return setup } diff --git a/cli/internal/cmd/version.go b/internal/cmd/version.go similarity index 71% rename from cli/internal/cmd/version.go rename to internal/cmd/version.go index 05ef8af..61b8eef 100644 --- a/cli/internal/cmd/version.go +++ b/internal/cmd/version.go @@ -7,8 +7,8 @@ import ( ) const ( - version = "v2.4.0-alpha" - changed = "Fixed:\n Fixed logic around blacklist." + version = "v2.5.0-alpha" + changed = "Increased test coverage by refactoring to a fluid design. Removed boltdb requirement." ) // NewVersionCommand returns a version cobra command @@ -19,8 +19,7 @@ func NewVersionCommand() *cobra.Command { Long: "version prints tzpay's version to stdout", Example: `tzpay version`, Run: func(cmd *cobra.Command, args []string) { - fmt.Println(version) - fmt.Println(changed) + fmt.Printf("%s - %s\n", version, changed) }, } return version diff --git a/internal/enviroment/enviroment.go b/internal/enviroment/enviroment.go new file mode 100644 index 0000000..ce90500 --- /dev/null +++ b/internal/enviroment/enviroment.go @@ -0,0 +1,128 @@ +package enviroment + +import ( + "encoding/json" + "io/ioutil" + + "github.com/caarlos0/env/v6" + validate "github.com/go-playground/validator/v10" + gotezos "github.com/goat-systems/go-tezos/v2" + "github.com/pkg/errors" +) + +var ( + newGoTezos = gotezos.New + readFile = ioutil.ReadFile + importWallet = gotezos.ImportEncryptedWallet +) + +// DryRunEnviroment is a list of dry run enviroment variables used to configure the tzpay application +type DryRunEnviroment struct { + BakersFee float64 `env:"TZPAY_BAKERS_FEE" validate:"required" ` + Delegate string `env:"TZPAY_DELEGATE" validate:"required"` + GasLimit int `env:"TZPAY_NETWORK_GAS_LIMIT" envDefault:"26283" validate:"required"` + HostNode string `env:"TZPAY_HOST_NODE" validate:"required"` + MinimumPayment int `env:"TZPAY_MINIMUM_PAYMENT" envDefault:"100" validate:"required"` + NetworkFee int `env:"TZPAY_NETWORK_FEE" envDefault:"2941" validate:"required"` + + BlackListFile string `env:"TZPAY_BLACKLIST"` + // TODO :: EarningsOnly bool `env:"TZPAY_EARNINGS_ONLY"` + + GoTezos gotezos.IFace `env:"-"` + BlackList []string `env:"-"` +} + +// RunEnviroment is a list of dry run enviroment variables used to configure the tzpay application +type RunEnviroment struct { + BakersFee float64 `env:"TZPAY_BAKERS_FEE" validate:"required" ` + Delegate string `env:"TZPAY_DELEGATE" validate:"required"` + GasLimit int `env:"TZPAY_NETWORK_GAS_LIMIT" envDefault:"26283" validate:"required"` + HostNode string `env:"TZPAY_HOST_NODE" validate:"required"` + WalletPassword string `env:"TZPAY_WALLET_PASSWORD" validate:"required"` + MinimumPayment int `env:"TZPAY_MINIMUM_PAYMENT" envDefault:"100" validate:"required"` + NetworkFee int `env:"TZPAY_NETWORK_FEE" envDefault:"2941" validate:"required"` + WalletSecret string `env:"TZPAY_WALLET_SECRET" validate:"required"` + + BlackListFile string `env:"TZPAY_BLACKLIST"` + // TODO :: EarningsOnly bool `env:"TZPAY_EARNINGS_ONLY"` + + GoTezos gotezos.IFace `env:"-"` + BlackList []string `env:"-"` + Wallet gotezos.Wallet `env:"-"` +} + +// NewDryRunEnviroment returns a new DryRunEnviroment +func NewDryRunEnviroment() (*DryRunEnviroment, error) { + enviroment := &DryRunEnviroment{} + if err := env.Parse(enviroment); err != nil { + return nil, errors.Wrap(err, "failed to load paramters from enviroment") + } + + err := validate.New().Struct(enviroment) + if err != nil { + return nil, errors.Wrap(err, "failed to validate required enviroment variables") + } + + gt, err := newGoTezos(enviroment.HostNode) + if err != nil { + return nil, errors.Wrap(err, "failed to make connection to host node") + } + enviroment.GoTezos = gt + + var blacklist []string + if enviroment.BlackListFile != "" { + byts, err := readFile(enviroment.BlackListFile) + if err != nil { + return nil, errors.Wrap(err, "failed to open blacklist file") + } + + err = json.Unmarshal(byts, &blacklist) + if err != nil { + return nil, errors.Wrap(err, "failed to parse blacklist file: expected json string array") + } + } + enviroment.BlackList = blacklist + + return enviroment, nil +} + +// NewRunEnviroment returns a new RunEnviroment +func NewRunEnviroment() (*RunEnviroment, error) { + enviroment := &RunEnviroment{} + if err := env.Parse(enviroment); err != nil { + return nil, errors.Wrap(err, "failed to load paramters from enviroment") + } + + err := validate.New().Struct(enviroment) + if err != nil { + return nil, errors.Wrap(err, "failed to validate required enviroment variables") + } + + gt, err := newGoTezos(enviroment.HostNode) + if err != nil { + return nil, errors.Wrap(err, "failed to make connection to host node") + } + enviroment.GoTezos = gt + + var blacklist []string + if enviroment.BlackListFile != "" { + byts, err := readFile(enviroment.BlackListFile) + if err != nil { + return nil, errors.Wrap(err, "failed to open blacklist file") + } + + err = json.Unmarshal(byts, &blacklist) + if err != nil { + return nil, errors.Wrap(err, "failed to parse blacklist file: expected json string array") + } + } + enviroment.BlackList = blacklist + + wallet, err := importWallet(enviroment.WalletPassword, enviroment.WalletSecret) + if err != nil { + return nil, errors.Wrap(err, "failed to import encrypted wallet") + } + enviroment.Wallet = *wallet + + return enviroment, nil +} diff --git a/internal/enviroment/enviroment_test.go b/internal/enviroment/enviroment_test.go new file mode 100644 index 0000000..b7d4ffc --- /dev/null +++ b/internal/enviroment/enviroment_test.go @@ -0,0 +1,396 @@ +package enviroment + +import ( + "errors" + "os" + "testing" + + gotezos "github.com/goat-systems/go-tezos/v2" + "github.com/goat-systems/tzpay/v2/internal/test" + "github.com/stretchr/testify/assert" +) + +func Test_NewDryRunEnviroment(t *testing.T) { + type input struct { + newGoTezos func(host string) (*gotezos.GoTezos, error) + readFile func(filename string) ([]byte, error) + enviroment map[string]string + } + + type want struct { + err bool + errContains string + dryrun *DryRunEnviroment + } + + cases := []struct { + name string + input input + want want + }{ + { + "is successful", + input{ + newGoTezos: func(host string) (*gotezos.GoTezos, error) { + return &gotezos.GoTezos{}, nil + }, + readFile: func(filename string) ([]byte, error) { + return []byte(`["a","b"]`), nil + }, + enviroment: map[string]string{ + "TZPAY_BAKERS_FEE": "0.05", + "TZPAY_DELEGATE": "some_delegate", + "TZPAY_HOST_NODE": "http://127.0.0.1:8732", + "TZPAY_BLACKLIST": "some_blacklist_file.json", + }, + }, + want{ + false, + "", + &DryRunEnviroment{ + BakersFee: 0.05, + Delegate: "some_delegate", + GasLimit: 26283, + HostNode: "http://127.0.0.1:8732", + MinimumPayment: 100, + NetworkFee: 2941, + BlackListFile: "some_blacklist_file.json", + BlackList: []string{ + "a", + "b", + }, + GoTezos: &gotezos.GoTezos{}, + }, + }, + }, + { + "handles missing field", + input{ + newGoTezos: func(host string) (*gotezos.GoTezos, error) { + return &gotezos.GoTezos{}, nil + }, + readFile: func(filename string) ([]byte, error) { + return []byte(`["a","b"]`), nil + }, + enviroment: map[string]string{ + "TZPAY_DELEGATE": "some_delegate", + "TZPAY_HOST_NODE": "http://127.0.0.1:8732", + "TZPAY_BLACKLIST": "some_blacklist_file.json", + }, + }, + want{ + true, + "failed to validate required enviroment variables", + nil, + }, + }, + { + "handles failure to initialize go tezos", + input{ + newGoTezos: func(host string) (*gotezos.GoTezos, error) { + return &gotezos.GoTezos{}, errors.New("some err") + }, + readFile: func(filename string) ([]byte, error) { + return []byte(`["a","b"]`), nil + }, + enviroment: map[string]string{ + "TZPAY_BAKERS_FEE": "0.05", + "TZPAY_DELEGATE": "some_delegate", + "TZPAY_HOST_NODE": "http://127.0.0.1:8732", + "TZPAY_BLACKLIST": "some_blacklist_file.json", + }, + }, + want{ + true, + "failed to make connection to host node", + nil, + }, + }, + { + "handles failure to read black list file", + input{ + newGoTezos: func(host string) (*gotezos.GoTezos, error) { + return &gotezos.GoTezos{}, nil + }, + readFile: func(filename string) ([]byte, error) { + return []byte(`["a","b"]`), errors.New("some_err") + }, + enviroment: map[string]string{ + "TZPAY_BAKERS_FEE": "0.05", + "TZPAY_DELEGATE": "some_delegate", + "TZPAY_HOST_NODE": "http://127.0.0.1:8732", + "TZPAY_BLACKLIST": "some_blacklist_file.json", + }, + }, + want{ + true, + "failed to open blacklist file", + nil, + }, + }, + { + "handles failure unmarshal blacklist file", + input{ + newGoTezos: func(host string) (*gotezos.GoTezos, error) { + return &gotezos.GoTezos{}, nil + }, + readFile: func(filename string) ([]byte, error) { + return []byte(`junk`), nil + }, + enviroment: map[string]string{ + "TZPAY_BAKERS_FEE": "0.05", + "TZPAY_DELEGATE": "some_delegate", + "TZPAY_HOST_NODE": "http://127.0.0.1:8732", + "TZPAY_BLACKLIST": "some_blacklist_file.json", + }, + }, + want{ + true, + "failed to parse blacklist file", + nil, + }, + }, + } + + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + setEnv(tt.input.enviroment) + + newGoTezos = tt.input.newGoTezos + readFile = tt.input.readFile + + env, err := NewDryRunEnviroment() + test.CheckErr(t, tt.want.err, tt.want.errContains, err) + assert.Equal(t, tt.want.dryrun, env) + + unsetEnv(tt.input.enviroment) + }) + } +} + +func Test_NewRunEnviroment(t *testing.T) { + type input struct { + newGoTezos func(host string) (*gotezos.GoTezos, error) + readFile func(filename string) ([]byte, error) + importWallet func(password string, esk string) (*gotezos.Wallet, error) + enviroment map[string]string + } + + type want struct { + err bool + errContains string + dryrun *RunEnviroment + } + + cases := []struct { + name string + input input + want want + }{ + { + "is successful", + input{ + newGoTezos: func(host string) (*gotezos.GoTezos, error) { + return &gotezos.GoTezos{}, nil + }, + readFile: func(filename string) ([]byte, error) { + return []byte(`["a","b"]`), nil + }, + importWallet: func(password string, esk string) (*gotezos.Wallet, error) { + return &gotezos.Wallet{}, nil + }, + enviroment: map[string]string{ + "TZPAY_BAKERS_FEE": "0.05", + "TZPAY_DELEGATE": "some_delegate", + "TZPAY_HOST_NODE": "http://127.0.0.1:8732", + "TZPAY_BLACKLIST": "some_blacklist_file.json", + "TZPAY_WALLET_SECRET": "secret", + "TZPAY_WALLET_PASSWORD": "password", + }, + }, + want{ + false, + "", + &RunEnviroment{ + BakersFee: 0.05, + Delegate: "some_delegate", + GasLimit: 26283, + HostNode: "http://127.0.0.1:8732", + MinimumPayment: 100, + NetworkFee: 2941, + BlackListFile: "some_blacklist_file.json", + BlackList: []string{ + "a", + "b", + }, + GoTezos: &gotezos.GoTezos{}, + Wallet: gotezos.Wallet{}, + WalletPassword: "password", + WalletSecret: "secret", + }, + }, + }, + { + "handles missing field", + input{ + newGoTezos: func(host string) (*gotezos.GoTezos, error) { + return &gotezos.GoTezos{}, nil + }, + readFile: func(filename string) ([]byte, error) { + return []byte(`["a","b"]`), nil + }, + importWallet: func(password string, esk string) (*gotezos.Wallet, error) { + return &gotezos.Wallet{}, nil + }, + enviroment: map[string]string{ + "TZPAY_DELEGATE": "some_delegate", + "TZPAY_HOST_NODE": "http://127.0.0.1:8732", + "TZPAY_BLACKLIST": "some_blacklist_file.json", + "TZPAY_WALLET_SECRET": "secret", + "TZPAY_WALLET_PASSWORD": "password", + }, + }, + want{ + true, + "failed to validate required enviroment variables", + nil, + }, + }, + { + "handles failure to initialize go tezos", + input{ + newGoTezos: func(host string) (*gotezos.GoTezos, error) { + return &gotezos.GoTezos{}, errors.New("some err") + }, + readFile: func(filename string) ([]byte, error) { + return []byte(`["a","b"]`), nil + }, + importWallet: func(password string, esk string) (*gotezos.Wallet, error) { + return &gotezos.Wallet{}, nil + }, + enviroment: map[string]string{ + "TZPAY_BAKERS_FEE": "0.05", + "TZPAY_DELEGATE": "some_delegate", + "TZPAY_HOST_NODE": "http://127.0.0.1:8732", + "TZPAY_BLACKLIST": "some_blacklist_file.json", + "TZPAY_WALLET_SECRET": "secret", + "TZPAY_WALLET_PASSWORD": "password", + }, + }, + want{ + true, + "failed to make connection to host node", + nil, + }, + }, + { + "handles failure to read black list file", + input{ + newGoTezos: func(host string) (*gotezos.GoTezos, error) { + return &gotezos.GoTezos{}, nil + }, + readFile: func(filename string) ([]byte, error) { + return []byte(`["a","b"]`), errors.New("some_err") + }, + importWallet: func(password string, esk string) (*gotezos.Wallet, error) { + return &gotezos.Wallet{}, nil + }, + enviroment: map[string]string{ + "TZPAY_BAKERS_FEE": "0.05", + "TZPAY_DELEGATE": "some_delegate", + "TZPAY_HOST_NODE": "http://127.0.0.1:8732", + "TZPAY_BLACKLIST": "some_blacklist_file.json", + "TZPAY_WALLET_SECRET": "secret", + "TZPAY_WALLET_PASSWORD": "password", + }, + }, + want{ + true, + "failed to open blacklist file", + nil, + }, + }, + { + "handles failure unmarshal blacklist file", + input{ + newGoTezos: func(host string) (*gotezos.GoTezos, error) { + return &gotezos.GoTezos{}, nil + }, + readFile: func(filename string) ([]byte, error) { + return []byte(`junk`), nil + }, + importWallet: func(password string, esk string) (*gotezos.Wallet, error) { + return &gotezos.Wallet{}, nil + }, + enviroment: map[string]string{ + "TZPAY_BAKERS_FEE": "0.05", + "TZPAY_DELEGATE": "some_delegate", + "TZPAY_HOST_NODE": "http://127.0.0.1:8732", + "TZPAY_BLACKLIST": "some_blacklist_file.json", + "TZPAY_WALLET_SECRET": "secret", + "TZPAY_WALLET_PASSWORD": "password", + }, + }, + want{ + true, + "failed to parse blacklist file", + nil, + }, + }, + { + "handles failure import wallet", + input{ + newGoTezos: func(host string) (*gotezos.GoTezos, error) { + return &gotezos.GoTezos{}, nil + }, + readFile: func(filename string) ([]byte, error) { + return []byte(`["a","b"]`), nil + }, + importWallet: func(password string, esk string) (*gotezos.Wallet, error) { + return &gotezos.Wallet{}, errors.New("some_err") + }, + enviroment: map[string]string{ + "TZPAY_BAKERS_FEE": "0.05", + "TZPAY_DELEGATE": "some_delegate", + "TZPAY_HOST_NODE": "http://127.0.0.1:8732", + "TZPAY_BLACKLIST": "some_blacklist_file.json", + "TZPAY_WALLET_SECRET": "secret", + "TZPAY_WALLET_PASSWORD": "password", + }, + }, + want{ + true, + "failed to import encrypted wallet", + nil, + }, + }, + } + + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + setEnv(tt.input.enviroment) + + newGoTezos = tt.input.newGoTezos + readFile = tt.input.readFile + importWallet = tt.input.importWallet + + env, err := NewRunEnviroment() + test.CheckErr(t, tt.want.err, tt.want.errContains, err) + assert.Equal(t, tt.want.dryrun, env) + + unsetEnv(tt.input.enviroment) + }) + } +} + +func setEnv(env map[string]string) { + for key, element := range env { + os.Setenv(key, element) + } +} + +func unsetEnv(env map[string]string) { + for key := range env { + os.Unsetenv(key) + } +} diff --git a/internal/payout/payouts.go b/internal/payout/payouts.go new file mode 100644 index 0000000..e73e83d --- /dev/null +++ b/internal/payout/payouts.go @@ -0,0 +1,483 @@ +package payout + +import ( + "encoding/json" + "fmt" + "math/big" + "sort" + "time" + "unicode" + + gotezos "github.com/goat-systems/go-tezos/v2" + "github.com/pkg/errors" + "github.com/sirupsen/logrus" +) + +var ( + confirmationDurationInterval = time.Second * 1 + confirmationTimoutInterval = time.Minute * 2 +) + +// Payout represents a payout and payout operations. +type Payout struct { + gt gotezos.IFace + cycle int + delegate string + bakerFee float64 + wallet gotezos.Wallet + minPayment int + blacklist []string + inject bool + networkFee int + gasLimit int + batchSize int + verbose bool +} + +// NewPayoutInput is the input for NewPayout +type NewPayoutInput struct { + GoTezos gotezos.IFace + Cycle int + Delegate string + BakerFee float64 + Wallet gotezos.Wallet + MinPayment int + BlackList []string + Inject bool // If false, nothing will be injected. + NetworkFee int + GasLimit int + BatchSize int + Verbose bool +} + +// Report contains all needed information for a payout +type Report struct { + DelegationEarnings DelegationEarnings `json:"delegaions"` + DelegateEarnings DelegateEarnings `json:"delegate"` + CycleHash string `json:"cycle_hash"` + Cycle int `json:"cycle"` + FrozenBalance *big.Int `json:"rewards"` + StakingBalance *big.Int `json:"staking_balance"` + Operations []string `json:"operation"` + OperationsLink []string `json:"operation_link"` +} + +// DelegationEarning - +type DelegationEarning struct { + Address string + Fee *big.Int + GrossRewards *big.Int + NetRewards *big.Int + Share float64 +} + +// DelegateEarnings - +type DelegateEarnings struct { + Address string + Fees *big.Int + Share float64 + Rewards *big.Int + Net *big.Int +} + +// DelegationEarnings contains list of DelegationEarning and implements sort. +type DelegationEarnings []DelegationEarning + +func (d DelegationEarnings) Len() int { return len(d) } +func (d DelegationEarnings) Swap(i, j int) { + d[i], d[j] = d[j], d[i] +} + +func (d DelegationEarnings) Less(i, j int) bool { + iRunes := []rune(d[i].Address) + jRunes := []rune(d[j].Address) + + max := len(iRunes) + if max > len(jRunes) { + max = len(jRunes) + } + + for idx := 0; idx < max; idx++ { + ir := iRunes[idx] + jr := jRunes[idx] + + lir := unicode.ToLower(ir) + ljr := unicode.ToLower(jr) + + if lir != ljr { + return lir < ljr + } + + if ir != jr { + return ir < jr + } + } + + return false +} + +type processDelegationsInput struct { + delegations []*string + stakingBalance *big.Int + frozenBalanceRewards gotezos.FrozenBalance + blockHash string +} + +type processDelegateInput struct { + delegate string + delegations []DelegationEarning + stakingBalance *big.Int + frozenBalanceRewards gotezos.FrozenBalance + blockHash string +} + +type processDelegationsOutput struct { + delegationEarning DelegationEarning + err error +} + +type processDelegationInput struct { + delegation string + stakingBalance *big.Int + frozenBalanceRewards gotezos.FrozenBalance + blockHash string +} + +// NewPayout returns a pointer to a new Baker +func NewPayout(input NewPayoutInput) *Payout { + return &Payout{ + gt: input.GoTezos, + cycle: input.Cycle, + delegate: input.Delegate, + bakerFee: input.BakerFee, + wallet: input.Wallet, + minPayment: input.MinPayment, + inject: input.Inject, + networkFee: input.NetworkFee, + gasLimit: input.GasLimit, + verbose: input.Verbose, + batchSize: input.BatchSize, + } +} + +// Execute will execute a payout based off the Payout configuration +func (p *Payout) Execute() (Report, error) { + frozenBalanceRewards, err := p.gt.FrozenBalance(p.cycle, p.delegate) + if err != nil { + return Report{}, errors.Wrapf(err, "failed to get delegation earnings for cycle %d", p.cycle) + } + + delegations, err := p.gt.DelegatedContractsAtCycle(p.cycle, p.delegate) + if err != nil { + return Report{}, errors.Wrapf(err, "failed to get delegation earnings for cycle %d", p.cycle) + } + + networkCycle, err := p.gt.Cycle(p.cycle) + if err != nil { + return Report{}, errors.Wrapf(err, "failed to get delegation earnings for cycle %d", p.cycle) + } + + stakingBalance, err := p.gt.StakingBalance(networkCycle.BlockHash, p.delegate) + if err != nil { + return Report{}, errors.Wrapf(err, "failed to get delegation earnings for cycle %d", p.cycle) + } + + delegationsOutput := p.proccessDelegations(processDelegationsInput{ + delegations: delegations, + stakingBalance: stakingBalance, + frozenBalanceRewards: frozenBalanceRewards, + blockHash: networkCycle.BlockHash, + }) + + report := Report{ + StakingBalance: stakingBalance, + CycleHash: networkCycle.BlockHash, + Cycle: p.cycle, + FrozenBalance: frozenBalanceRewards.Rewards.Big, + } + + for _, delegation := range delegationsOutput { + if delegation.err != nil { + err = errors.Wrapf(delegation.err, "failed to get payout for delegation %s", delegation.delegationEarning.Address) + } else { + report.DelegationEarnings = append(report.DelegationEarnings, delegation.delegationEarning) + } + } + sort.Sort(report.DelegationEarnings) + + if report.DelegateEarnings, err = p.processDelegate(processDelegateInput{ + delegate: p.delegate, + delegations: report.DelegationEarnings, + stakingBalance: stakingBalance, + frozenBalanceRewards: frozenBalanceRewards, + blockHash: networkCycle.BlockHash, + }); err != nil { + err = errors.Wrap(err, "failed to get contruct payout info for delegate") + } + + operations, err := p.getOperationHexStrings(report.DelegationEarnings) + if err != nil { + err = errors.Wrap(err, "failed to get contruct payout for delegate") + } + + if p.inject { + operationHashes, err := p.injectOperations(operations) + if err != nil { + err = errors.Wrap(err, "failed to get inject payout for delegate") + } + report.Operations = operationHashes + for _, op := range operationHashes { + report.OperationsLink = append(report.OperationsLink, fmt.Sprintf("https://tzstats.com/%s", op)) + } + } + + return report, err +} + +func (p *Payout) processDelegate(input processDelegateInput) (DelegateEarnings, error) { + delegateEarning := DelegateEarnings{ + Address: input.delegate, + Net: big.NewInt(0), + } + + balance, err := p.gt.Balance(input.blockHash, input.delegate) + if err != nil { + return delegateEarning, errors.Wrapf(err, "failed to process delegate earnings for %s", input.delegate) + } + + delegateEarning.Share = float64(balance.Int64()) / float64(input.stakingBalance.Int64()) + rewardsFloat := delegateEarning.Share * float64(input.frozenBalanceRewards.Rewards.Big.Int64()) + delegateEarning.Rewards = big.NewInt(int64(rewardsFloat)) + + fees := big.NewInt(0) + for _, delegation := range input.delegations { + fees.Add(fees, delegation.Fee) + } + + delegateEarning.Fees = fees + delegateEarning.Net.Add(delegateEarning.Fees, delegateEarning.Rewards) + + return delegateEarning, nil +} + +func (p *Payout) proccessDelegations(input processDelegationsInput) []processDelegationsOutput { + numJobs := len(input.delegations) + jobs := make(chan processDelegationInput, numJobs) + results := make(chan processDelegationsOutput, numJobs) + + for i := 0; i < 50; i++ { + go p.proccessDelegationWorker(jobs, results) + } + + for _, delegation := range input.delegations { + jobs <- processDelegationInput{ + delegation: *delegation, + stakingBalance: input.stakingBalance, + frozenBalanceRewards: input.frozenBalanceRewards, + blockHash: input.blockHash, + } + } + close(jobs) + + var out []processDelegationsOutput + for i := 1; i <= numJobs; i++ { + out = append(out, <-results) + } + + close(results) + return out +} + +func (p *Payout) proccessDelegationWorker(jobs <-chan processDelegationInput, results chan<- processDelegationsOutput) { + for j := range jobs { + d, err := p.processDelegation(j) + if err != nil { + results <- processDelegationsOutput{ + err: err, + } + } else { + results <- processDelegationsOutput{ + delegationEarning: *d, + } + } + } +} + +func (p *Payout) processDelegation(input processDelegationInput) (*DelegationEarning, error) { + delegationEarning := &DelegationEarning{Address: input.delegation} + balance, err := p.gt.Balance(input.blockHash, input.delegation) + if err != nil { + return nil, errors.Wrapf(err, "failed to process delegation earnings for delegation %s", input.delegation) + } + + delegationEarning.Share = float64(balance.Int64()) / float64(input.stakingBalance.Int64()) + grossRewardsFloat := delegationEarning.Share * float64(input.frozenBalanceRewards.Rewards.Big.Int64()) + feeFloat := grossRewardsFloat * p.bakerFee + + delegationEarning.GrossRewards = big.NewInt(int64(grossRewardsFloat)) + delegationEarning.Fee = big.NewInt(int64(feeFloat)) + delegationEarning.NetRewards = big.NewInt(0).Sub(delegationEarning.GrossRewards, delegationEarning.Fee) + + return delegationEarning, nil +} + +func (p *Payout) getOperationHexStrings(delegationEarnings DelegationEarnings) ([]string, error) { + head, err := p.gt.Head() + if err != nil { + return nil, errors.Wrap(err, "failed to get operation hex string") + } + + counter, err := p.gt.Counter(head.Hash, p.wallet.Address) + if err != nil { + return nil, errors.Wrap(err, "failed to get operation hex string") + } + + operations := []string{} + for _, batch := range p.batch(delegationEarnings) { + var op string + var err error + op, counter, err = p.forgeOperation(counter, batch) + if err != nil { + return nil, errors.Wrap(err, "failed to get operation hex string") + } + + operations = append(operations, op) + } + + return operations, nil +} + +func (p *Payout) forgeOperation(counter int, delegationEarnings DelegationEarnings) (string, int, error) { + head, err := p.gt.Head() + if err != nil { + return "", counter, errors.Wrap(err, "failed to forge payout") + } + + transactions, lastCounter := p.constructPayoutContents(counter, delegationEarnings) + + forge, err := gotezos.ForgeTransactionOperation(head.Hash, transactions...) + if err != nil { + return "", lastCounter, errors.Wrap(err, "failed to forge payout") + } + + return *forge, lastCounter, nil +} + +func (p *Payout) constructPayoutContents(counter int, delegationEarnings DelegationEarnings) ([]gotezos.ForgeTransactionOperationInput, int) { + var contents []gotezos.ForgeTransactionOperationInput + for _, delegation := range delegationEarnings { + if !p.isInBlacklist(delegation.Address) { + if delegation.NetRewards.Int64() >= int64(p.minPayment) { + counter++ + contents = append(contents, gotezos.ForgeTransactionOperationInput{ + Source: p.wallet.Address, + Destination: delegation.Address, + Amount: &gotezos.Int{Big: delegation.NetRewards}, + Fee: gotezos.NewInt(p.networkFee), + GasLimit: gotezos.NewInt(p.gasLimit), + Counter: counter, + StorageLimit: gotezos.NewInt(0), + }) + } + } + } + return contents, counter +} + +func (p *Payout) batch(delegationEarnings DelegationEarnings) []DelegationEarnings { + var delegationEarningsBatch []DelegationEarnings + if len(delegationEarnings) <= p.batchSize { + delegationEarningsBatch = append(delegationEarningsBatch, delegationEarnings) + return delegationEarningsBatch + } + + for len(delegationEarnings) >= p.batchSize { + delegationEarningsBatch = append(delegationEarningsBatch, delegationEarnings[:p.batchSize]) + delegationEarnings = delegationEarnings[p.batchSize:] + } + + if len(delegationEarnings) != 0 { + delegationEarningsBatch = append(delegationEarningsBatch, delegationEarnings) + } + + return delegationEarningsBatch +} + +func (p *Payout) injectOperations(operations []string) ([]string, error) { + ophashes := []string{} + for i, op := range operations { + signedop, err := p.wallet.SignOperation(op) + if err != nil { + return ophashes, errors.Wrap(err, "failed to inject operation") + } + + resp, err := p.gt.InjectionOperation(gotezos.InjectionOperationInput{ + Operation: &signedop, + }) + if err != nil { + return ophashes, errors.Wrap(err, "failed to inject operation") + } + + // TODO this unmarshaling should be done in the go lib + var ophash string + err = json.Unmarshal(resp, &ophash) + if err != nil { + return ophashes, errors.Wrap(err, "failed to inject operation: failed to unmarshal operation hash") + } + + ophashes = append(ophashes, ophash) + + if p.verbose { + logrus.WithFields(logrus.Fields{ + "hash": ophash, + "operation": fmt.Sprintf("%d/%d", (i + 1), len(operations)), + }).Info("Confirming injection.") + } + + if !p.confirmOperation(ophash) { + return ophashes, errors.Wrap(err, "failed to inject operation: failed to confirm operation") + } + + if p.verbose { + logrus.WithFields(logrus.Fields{ + "hash": ophash, + "operation": fmt.Sprintf("%d/%d", (i + 1), len(operations)), + }).Info("Injection confirmed.") + } + } + + return ophashes, nil +} + +func (p *Payout) confirmOperation(operation string) bool { + timer := time.After(confirmationTimoutInterval) + ticker := time.Tick(confirmationDurationInterval) + for { + select { + case <-ticker: + if head, err := p.gt.Head(); err == nil { + if ophashes, err := p.gt.OperationHashes(head.Hash); err == nil { + for _, out := range ophashes { + for _, in := range out { + if in == operation { + return true + } + } + } + } + } + case <-timer: + return false + } + } +} + +func (p *Payout) isInBlacklist(delegation string) bool { + for _, b := range p.blacklist { + if b == delegation { + return true + } + } + + return false +} diff --git a/internal/payout/payouts_test.go b/internal/payout/payouts_test.go new file mode 100644 index 0000000..0b18f42 --- /dev/null +++ b/internal/payout/payouts_test.go @@ -0,0 +1,864 @@ +package payout + +import ( + "math/big" + "sort" + "testing" + "time" + + gotezos "github.com/goat-systems/go-tezos/v2" + "github.com/goat-systems/tzpay/v2/internal/test" + "github.com/stretchr/testify/assert" +) + +func Test_PayoutsSort(t *testing.T) { + delegationEarnings := DelegationEarnings{} + delegationEarnings = append(delegationEarnings, + []DelegationEarning{ + { + Address: "tz1c", + }, + { + Address: "tz1a", + }, + { + Address: "tz1b", + }, + }..., + ) + sort.Sort(&delegationEarnings) + + want := DelegationEarnings{} + want = append(want, + []DelegationEarning{ + { + Address: "tz1a", + }, + { + Address: "tz1b", + }, + { + Address: "tz1c", + }, + }..., + ) + + assert.Equal(t, want, delegationEarnings) +} + +func Test_Execute(t *testing.T) { + type want struct { + err bool + errContains string + report Report + } + + cases := []struct { + name string + input gotezos.IFace + want want + }{ + { + "handles FrozenBalance failue", + &test.GoTezosMock{ + FrozenBalanceErr: true, + }, + want{ + true, + "failed to get delegation earnings for cycle 0: failed to get frozen balance", + Report{}, + }, + }, + { + "handles DelegatedContractsAtCycle failue", + &test.GoTezosMock{ + DelegatedContractsErr: true, + }, + want{ + true, + "failed to get delegation earnings for cycle 0: failed to get delegated contracts at cycle", + Report{}, + }, + }, + { + "handles Cycle failue", + &test.GoTezosMock{ + CycleErr: true, + }, + want{ + true, + "failed to get delegation earnings for cycle 0: failed to get cycle", + Report{}, + }, + }, + { + "handles StakingBalance failue", + &test.GoTezosMock{ + StakingBalanceErr: true, + }, + want{ + true, + "failed to get delegation earnings for cycle 0: failed to get staking balance", + Report{}, + }, + }, + { + "is successful", + &test.GoTezosMock{}, + want{ + false, + "", + Report{ + DelegationEarnings: DelegationEarnings{ + DelegationEarning{ + Address: "KT1GcSsQaTtMB2HvUKU9b6WRFUnGpGx9JwGk", + Fee: big.NewInt(1750), + GrossRewards: big.NewInt(35000), + NetRewards: big.NewInt(33250), + Share: 0.0005, + }, + DelegationEarning{ + Address: "KT1K4xei3yozp7UP5rHV5wuoDzWwBXqCGRBt", + Fee: big.NewInt(1750), + GrossRewards: big.NewInt(35000), + NetRewards: big.NewInt(33250), + Share: 0.0005, + }, + DelegationEarning{ + Address: "KT1LinsZAnyxajEv4eNFWtwHMdyhbJsGfvp3", + Fee: big.NewInt(1750), + GrossRewards: big.NewInt(35000), + NetRewards: big.NewInt(33250), + Share: 0.0005, + }, + }, + DelegateEarnings: DelegateEarnings{ + Address: "tz1SUgyRB8T5jXgXAwS33pgRHAKrafyg87Yc", + Fees: big.NewInt(5250), + Share: 0.0005, + Rewards: big.NewInt(35000), + Net: big.NewInt(40250), + }, + CycleHash: "some_hash", + Cycle: 0, + FrozenBalance: big.NewInt(70000000), + StakingBalance: big.NewInt(10000000000), + Operations: nil, + OperationsLink: nil, + }, + }, + }, + } + + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + payout := &Payout{ + gt: tt.input, + wallet: gotezos.Wallet{ + Address: "tz1SUgyRB8T5jXgXAwS33pgRHAKrafyg87Yc", + }, + batchSize: 2, + delegate: "tz1SUgyRB8T5jXgXAwS33pgRHAKrafyg87Yc", + bakerFee: 0.05, + } + report, err := payout.Execute() + test.CheckErr(t, tt.want.err, tt.want.errContains, err) + assert.Equal(t, tt.want.report, report) + }) + } +} +func Test_processDelegate(t *testing.T) { + type input struct { + gt gotezos.IFace + delegateInput processDelegateInput + } + + type want struct { + err bool + errContains string + delegateEarnings DelegateEarnings + } + + cases := []struct { + name string + input input + want want + }{ + { + "is successful", + input{ + gt: &test.GoTezosMock{}, + delegateInput: processDelegateInput{ + delegate: "some_delegate", + delegations: []DelegationEarning{ + { + Fee: big.NewInt(1000), + }, + { + Fee: big.NewInt(1000), + }, + { + Fee: big.NewInt(1000), + }, + }, + stakingBalance: big.NewInt(10000000), + frozenBalanceRewards: gotezos.FrozenBalance{ + Rewards: gotezos.NewInt(700), + }, + blockHash: "block_hash", + }, + }, + want{ + false, + "", + DelegateEarnings{Address: "some_delegate", Fees: big.NewInt(3000), Share: 0.5, Rewards: big.NewInt(350), Net: big.NewInt(3350)}, + }, + }, + { + "handles failure to get balance", + input{ + gt: &test.GoTezosMock{BalanceErr: true}, + delegateInput: processDelegateInput{ + delegate: "some_delegate", + delegations: []DelegationEarning{ + { + Fee: big.NewInt(1000), + }, + { + Fee: big.NewInt(1000), + }, + { + Fee: big.NewInt(1000), + }, + }, + stakingBalance: big.NewInt(10000000), + frozenBalanceRewards: gotezos.FrozenBalance{ + Rewards: gotezos.NewInt(700), + }, + blockHash: "block_hash", + }, + }, + want{ + true, + "failed to process delegate earnings", + DelegateEarnings{Address: "some_delegate", Fees: nil, Share: 0, Rewards: nil, Net: big.NewInt(0)}, + }, + }, + } + + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + payout := Payout{ + gt: tt.input.gt, + } + delegateEarnings, err := payout.processDelegate(tt.input.delegateInput) + test.CheckErr(t, tt.want.err, tt.want.errContains, err) + assert.Equal(t, tt.want.delegateEarnings, delegateEarnings) + }) + } +} + +func Test_processDelegations(t *testing.T) { + type want struct { + err bool + errcount int + successful int + } + + cases := []struct { + name string + input processDelegationsInput + want want + }{ + { + "is successful", + processDelegationsInput{ + delegations: []*string{ + strToPointer("some_delegation"), + strToPointer("some_delegation1"), + strToPointer("some_delegation2"), + }, + stakingBalance: big.NewInt(100000000000), + frozenBalanceRewards: gotezos.FrozenBalance{ + Rewards: gotezos.NewInt(800000000), + }, + }, + want{ + false, + 0, + 3, + }, + }, + { + "handles failure", + processDelegationsInput{ + delegations: []*string{ + strToPointer("some_delegation"), + strToPointer("some_delegation1"), + strToPointer("some_delegation2"), + }, + stakingBalance: big.NewInt(100000000000), + frozenBalanceRewards: gotezos.FrozenBalance{ + Rewards: gotezos.NewInt(800000000), + }, + }, + want{ + true, + 3, + 0, + }, + }, + } + + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + payout := &Payout{ + gt: &test.GoTezosMock{ + BalanceErr: tt.want.err, + }, + } + + out := payout.proccessDelegations(tt.input) + successful := 0 + errcount := 0 + + for _, o := range out { + if o.err != nil { + errcount++ + } else { + successful++ + } + } + + assert.Equal(t, tt.want.successful, successful) + assert.Equal(t, tt.want.errcount, errcount) + }) + } +} + +func Test_processDelegation(t *testing.T) { + type want struct { + err bool + errContains string + delegationEarnings *DelegationEarning + } + + cases := []struct { + name string + input processDelegationInput + want want + }{ + { + "is successful", + processDelegationInput{ + stakingBalance: big.NewInt(100000000000), + frozenBalanceRewards: gotezos.FrozenBalance{ + Rewards: gotezos.NewInt(800000000), + }, + }, + want{ + false, + "", + &DelegationEarning{Fee: big.NewInt(2000), GrossRewards: big.NewInt(40000), NetRewards: big.NewInt(38000), Share: 5e-05}, + }, + }, + { + "handles failure", + processDelegationInput{ + stakingBalance: big.NewInt(100000000000), + frozenBalanceRewards: gotezos.FrozenBalance{ + Rewards: gotezos.NewInt(800000000), + }, + }, + want{ + true, + "failed to get balance", + nil, + }, + }, + } + + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + payout := &Payout{ + gt: &test.GoTezosMock{ + BalanceErr: tt.want.err, + }, + bakerFee: 0.05, + } + out, err := payout.processDelegation(tt.input) + test.CheckErr(t, tt.want.err, tt.want.errContains, err) + assert.Equal(t, tt.want.delegationEarnings, out) + }) + } +} + +func Test_getOperationHexStrings(t *testing.T) { + type input struct { + gt gotezos.IFace + delegationEarnings DelegationEarnings + } + + type want struct { + err bool + errContains string + ophexes []string + } + cases := []struct { + name string + input input + want want + }{ + { + "is successful", + input{ + &test.GoTezosMock{}, + DelegationEarnings{ + DelegationEarning{ + Address: "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", + GrossRewards: big.NewInt(1000000), + NetRewards: big.NewInt(900000), + }, + DelegationEarning{ + Address: "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", + GrossRewards: big.NewInt(1000000), + NetRewards: big.NewInt(950000), + }, + }, + }, + want{ + false, + "", + []string{ + "7cc601d2729c90b267e6a79d902f8b048d37fd990f2f7447efefb0cfb2f8e8a46c004b04ad1e57c2f13b61b3d2c95b3073d961a4132b00650000a0f7360000056a59972593bdc74a5295671c8f5d43c21348da006c004b04ad1e57c2f13b61b3d2c95b3073d961a4132b00660000f0fd390000056a59972593bdc74a5295671c8f5d43c21348da00", + }, + }, + }, + { + "handles failure to get head", + input{ + &test.GoTezosMock{HeadErr: true}, + DelegationEarnings{ + DelegationEarning{ + Address: "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", + GrossRewards: big.NewInt(1000000), + NetRewards: big.NewInt(900000), + }, + DelegationEarning{ + Address: "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", + GrossRewards: big.NewInt(1000000), + NetRewards: big.NewInt(950000), + }, + }, + }, + want{ + true, + "failed to get operation hex string: failed to get block", + nil, + }, + }, + { + "handles failure to get counter", + input{ + &test.GoTezosMock{CounterErr: true}, + DelegationEarnings{ + DelegationEarning{ + Address: "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", + GrossRewards: big.NewInt(1000000), + NetRewards: big.NewInt(900000), + }, + DelegationEarning{ + Address: "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", + GrossRewards: big.NewInt(1000000), + NetRewards: big.NewInt(950000), + }, + }, + }, + want{ + true, + "failed to get operation hex string: failed to get counter", + nil, + }, + }, + { + "handles failure to forge", + input{ + &test.GoTezosMock{}, + DelegationEarnings{ + DelegationEarning{ + Address: "invalid_addr", + GrossRewards: big.NewInt(1000000), + NetRewards: big.NewInt(900000), + }, + DelegationEarning{ + Address: "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", + GrossRewards: big.NewInt(1000000), + NetRewards: big.NewInt(950000), + }, + }, + }, + want{ + true, + "failed to get operation hex string: failed to forge payout", + nil, + }, + }, + } + + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + payout := Payout{ + gt: tt.input.gt, + batchSize: 10, + wallet: gotezos.Wallet{ + Address: "tz1SUgyRB8T5jXgXAwS33pgRHAKrafyg87Yc", + }, + } + ophexes, err := payout.getOperationHexStrings(tt.input.delegationEarnings) + test.CheckErr(t, tt.want.err, tt.want.errContains, err) + assert.Equal(t, tt.want.ophexes, ophexes) + }) + } +} + +func Test_forgeOperation(t *testing.T) { + type input struct { + counter int + delegationEarnings DelegationEarnings + gt gotezos.IFace + } + + type want struct { + err bool + errContains string + ophash string + counter int + } + + cases := []struct { + name string + input input + want want + }{ + { + "is successful", + input{ + 5, + DelegationEarnings{ + DelegationEarning{ + Address: "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", + GrossRewards: big.NewInt(1000000), + NetRewards: big.NewInt(900000), + }, + DelegationEarning{ + Address: "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", + GrossRewards: big.NewInt(1000000), + NetRewards: big.NewInt(950000), + }, + }, + &test.GoTezosMock{}, + }, + want{ + err: false, + errContains: "", + ophash: "7cc601d2729c90b267e6a79d902f8b048d37fd990f2f7447efefb0cfb2f8e8a46c004b04ad1e57c2f13b61b3d2c95b3073d961a4132b00060000a0f7360000056a59972593bdc74a5295671c8f5d43c21348da006c004b04ad1e57c2f13b61b3d2c95b3073d961a4132b00070000f0fd390000056a59972593bdc74a5295671c8f5d43c21348da00", + counter: 7, + }, + }, + { + "handles failure to get head", + input{ + 5, + DelegationEarnings{ + DelegationEarning{ + Address: "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", + GrossRewards: big.NewInt(1000000), + NetRewards: big.NewInt(900000), + }, + DelegationEarning{ + Address: "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", + GrossRewards: big.NewInt(1000000), + NetRewards: big.NewInt(950000), + }, + }, + &test.GoTezosMock{HeadErr: true}, + }, + want{ + err: true, + errContains: "failed to forge payout: failed to get block", + ophash: "", + counter: 5, + }, + }, + { + "handles failure to forge", + input{ + 5, + DelegationEarnings{ + DelegationEarning{ + Address: "invalid_addr", + GrossRewards: big.NewInt(1000000), + NetRewards: big.NewInt(900000), + }, + DelegationEarning{ + Address: "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", + GrossRewards: big.NewInt(1000000), + NetRewards: big.NewInt(950000), + }, + }, + &test.GoTezosMock{}, + }, + want{ + err: true, + errContains: "failed to forge payout: failed to forge operation", + ophash: "", + counter: 7, + }, + }, + } + + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + payout := &Payout{ + gt: tt.input.gt, + wallet: gotezos.Wallet{ + Address: "tz1SUgyRB8T5jXgXAwS33pgRHAKrafyg87Yc", + }, + } + ophash, counter, err := payout.forgeOperation(tt.input.counter, tt.input.delegationEarnings) + test.CheckErr(t, tt.want.err, tt.want.errContains, err) + assert.Equal(t, tt.want.counter, counter) + assert.Equal(t, tt.want.ophash, ophash) + }) + } + +} + +func Test_constructPayoutContents(t *testing.T) { + type input struct { + counter int + blacklist []string + delegationEarnings DelegationEarnings + } + + cases := []struct { + name string + input input + want []gotezos.ForgeTransactionOperationInput + }{ + { + "is successful", + input{ + 100, + []string{}, + DelegationEarnings{ + DelegationEarning{ + Address: "somedelegation", + GrossRewards: big.NewInt(1000000), + NetRewards: big.NewInt(900000), + }, + DelegationEarning{ + Address: "someotherdelegation", + GrossRewards: big.NewInt(1000000), + NetRewards: big.NewInt(950000), + }, + }, + }, + []gotezos.ForgeTransactionOperationInput{ + { + Source: "tz1SUgyRB8T5jXgXAwS33pgRHAKrafyg87Yc", + Fee: gotezos.NewInt(0), + Counter: 101, + GasLimit: gotezos.NewInt(0), + StorageLimit: gotezos.NewInt(0), + Amount: gotezos.NewInt(900000), + Destination: "somedelegation", + }, + { + Source: "tz1SUgyRB8T5jXgXAwS33pgRHAKrafyg87Yc", + Fee: gotezos.NewInt(0), + Counter: 102, + GasLimit: gotezos.NewInt(0), + StorageLimit: gotezos.NewInt(0), + Amount: gotezos.NewInt(950000), + Destination: "someotherdelegation", + }, + }, + }, + { + "is successful in respecting blacklist", + input{ + 100, + []string{ + "someotherdelegation", + }, + DelegationEarnings{ + DelegationEarning{ + Address: "somedelegation", + GrossRewards: big.NewInt(1000000), + NetRewards: big.NewInt(900000), + }, + DelegationEarning{ + Address: "someotherdelegation", + GrossRewards: big.NewInt(1000000), + NetRewards: big.NewInt(950000), + }, + }, + }, + []gotezos.ForgeTransactionOperationInput{ + { + Source: "tz1SUgyRB8T5jXgXAwS33pgRHAKrafyg87Yc", + Fee: gotezos.NewInt(0), + Counter: 101, + GasLimit: gotezos.NewInt(0), + StorageLimit: gotezos.NewInt(0), + Amount: gotezos.NewInt(900000), + Destination: "somedelegation", + }, + }, + }, + } + + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + payout := &Payout{ + wallet: gotezos.Wallet{ + Address: "tz1SUgyRB8T5jXgXAwS33pgRHAKrafyg87Yc", + }, + blacklist: tt.input.blacklist, + } + contents, _ := payout.constructPayoutContents(tt.input.counter, tt.input.delegationEarnings) + assert.Equal(t, tt.want, contents) + }) + } +} + +func Test_batch(t *testing.T) { + cases := []struct { + name string + input DelegationEarnings + want []DelegationEarnings + }{ + { + "is successful with multiple batches", + DelegationEarnings{ + DelegationEarning{Address: "some_addr"}, + DelegationEarning{Address: "some_addr1"}, + DelegationEarning{Address: "some_addr2"}, + DelegationEarning{Address: "some_addr3"}, + DelegationEarning{Address: "some_addr4"}, + }, + []DelegationEarnings{ + { + DelegationEarning{Address: "some_addr"}, + DelegationEarning{Address: "some_addr1"}, + }, + { + DelegationEarning{Address: "some_addr2"}, + DelegationEarning{Address: "some_addr3"}}, + { + DelegationEarning{Address: "some_addr4"}, + }, + }, + }, + { + "is successful with one batch", + DelegationEarnings{ + DelegationEarning{Address: "some_addr"}, + DelegationEarning{Address: "some_addr1"}, + }, + []DelegationEarnings{ + { + DelegationEarning{Address: "some_addr"}, + DelegationEarning{Address: "some_addr1"}, + }, + }, + }, + } + + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + payout := Payout{batchSize: 2} + batch := payout.batch(tt.input) + assert.Equal(t, tt.want, batch) + }) + } +} + +func Test_confirmOperation(t *testing.T) { + type input struct { + operation string + gt gotezos.IFace + } + cases := []struct { + name string + input input + want bool + }{ + { + "is successful", + input{ + "ooYympR9wfV98X4MUHtE78NjXYRDeMTAD4ei7zEZDqoHv2rfb1M", + &test.GoTezosMock{}, + }, + true, + }, + { + "handles timeout", + input{ + "ooYympR9wfV98X4MUHtE78NjXYRDeMTAD4ei7zEZDqoHv2safdj", + &test.GoTezosMock{OperationHashesErr: true}, + }, + false, + }, + } + + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + confirmationDurationInterval = time.Millisecond * 500 + confirmationTimoutInterval = time.Second * 1 + + payout := Payout{ + gt: tt.input.gt, + } + + ok := payout.confirmOperation(tt.input.operation) + assert.Equal(t, tt.want, ok) + }) + } +} + +func Test_isInBlacklist(t *testing.T) { + cases := []struct { + name string + input string + want bool + }{ + { + "finds address in blacklist", + "some_addr", + true, + }, + { + "does not find address in blacklist", + "some_other_addr", + false, + }, + } + + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + payout := Payout{blacklist: []string{ + "some_addr", + "some_addr_1", + }} + + actual := payout.isInBlacklist(tt.input) + assert.Equal(t, tt.want, actual) + }) + } +} + +func strToPointer(str string) *string { + return &str +} diff --git a/cli/internal/print/print.go b/internal/print/print.go similarity index 72% rename from cli/internal/print/print.go rename to internal/print/print.go index b3c201b..35187d7 100644 --- a/cli/internal/print/print.go +++ b/internal/print/print.go @@ -1,7 +1,6 @@ package print import ( - "context" "encoding/json" "fmt" "os" @@ -10,23 +9,25 @@ import ( "strings" gotezos "github.com/goat-systems/go-tezos/v2" - "github.com/goat-systems/tzpay/v2/cli/internal/db/model" - "github.com/goat-systems/tzpay/v2/cli/internal/enviroment" + "github.com/goat-systems/tzpay/v2/internal/payout" "github.com/olekukonko/tablewriter" "github.com/pkg/errors" ) // Table prints a payout in table format -func Table(ctx context.Context, payouts *model.Payout) { - base := enviroment.GetEnviromentFromContext(ctx) +func Table(delegate, walletAddress string, report payout.Report) { + if walletAddress == "" { + walletAddress = "N/A" + } + table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Cylce", "Baker", "Wallet", "Rewards", "Operation"}) table.Append([]string{ - strconv.Itoa(payouts.Cycle), - base.Delegate, - base.Wallet.Address, - fmt.Sprintf("%.6f", float64(payouts.FrozenBalance.Int64())/float64(gotezos.MUTEZ)), - groomOperations(payouts.OperationsLink...), + strconv.Itoa(report.Cycle), + delegate, + walletAddress, + fmt.Sprintf("%.6f", float64(report.FrozenBalance.Int64())/float64(gotezos.MUTEZ)), + groomOperations(report.OperationsLink...), }) table.Render() @@ -35,8 +36,8 @@ func Table(ctx context.Context, payouts *model.Payout) { table.SetHeader([]string{"Delegation", "Share", "Gross", "Net", "Fee"}) var net, fee float64 - sort.Sort(payouts.DelegationEarnings) - for _, delegation := range payouts.DelegationEarnings { + sort.Sort(report.DelegationEarnings) + for _, delegation := range report.DelegationEarnings { table.Append([]string{ delegation.Address, fmt.Sprintf("%.6f", delegation.Share), @@ -54,8 +55,8 @@ func Table(ctx context.Context, payouts *model.Payout) { } // JSON prints a payout to json -func JSON(payouts *model.Payout) error { - prettyJSON, err := json.MarshalIndent(payouts, "", " ") +func JSON(report payout.Report) error { + prettyJSON, err := json.MarshalIndent(report, "", " ") if err != nil { return errors.Wrap(err, "failed to print json") } diff --git a/cli/internal/test/mock.go b/internal/test/mock.go similarity index 50% rename from cli/internal/test/mock.go rename to internal/test/mock.go index 6fd7dc9..045e18f 100644 --- a/cli/internal/test/mock.go +++ b/internal/test/mock.go @@ -3,8 +3,10 @@ package test import ( "errors" "math/big" + "testing" gotezos "github.com/goat-systems/go-tezos/v2" + "github.com/stretchr/testify/assert" ) // GoTezosMock is a test helper mocking the GoTezos lib @@ -18,6 +20,8 @@ type GoTezosMock struct { CycleErr bool StakingBalanceErr bool InjectionOperationErr bool + OperationHashesErr bool + ForgeOperationErr bool } // Head - @@ -31,13 +35,13 @@ func (g *GoTezosMock) Head() (*gotezos.Block, error) { } // Counter - -func (g *GoTezosMock) Counter(blockhash, pkh string) (*int, error) { +func (g *GoTezosMock) Counter(blockhash, pkh string) (int, error) { counter := 0 if g.CounterErr { - return &counter, errors.New("failed to get block") + return counter, errors.New("failed to get counter") } counter = 100 - return &counter, nil + return counter, nil } // Balance - @@ -45,39 +49,46 @@ func (g *GoTezosMock) Balance(blockhash, address string) (*big.Int, error) { if g.BalanceErr { return big.NewInt(0), errors.New("failed to get balance") } - return big.NewInt(10000000000), nil + return big.NewInt(5000000), nil } // FrozenBalance - -func (g *GoTezosMock) FrozenBalance(cycle int, delegate string) (*gotezos.FrozenBalance, error) { +func (g *GoTezosMock) FrozenBalance(cycle int, delegate string) (gotezos.FrozenBalance, error) { if g.FrozenBalanceErr { - return &gotezos.FrozenBalance{}, errors.New("failed to get frozen balance") + return gotezos.FrozenBalance{}, errors.New("failed to get frozen balance") } - return &gotezos.FrozenBalance{ - Deposits: gotezos.Int{Big: big.NewInt(10000000000)}, - Fees: gotezos.Int{Big: big.NewInt(3000)}, - Rewards: gotezos.Int{Big: big.NewInt(70000000)}, + return gotezos.FrozenBalance{ + Deposits: gotezos.NewInt(10000000000), + Fees: gotezos.NewInt(3000), + Rewards: gotezos.NewInt(70000000), }, nil } // DelegatedContractsAtCycle - -func (g *GoTezosMock) DelegatedContractsAtCycle(cycle int, delegate string) (*[]string, error) { +func (g *GoTezosMock) DelegatedContractsAtCycle(cycle int, delegate string) ([]*string, error) { if g.DelegatedContractsErr { - return &[]string{}, errors.New("failed to get delegated contracts at cycle") + return []*string{}, errors.New("failed to get delegated contracts at cycle") } - return &[]string{ - "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", - "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", - "tz1L8fUQLuwRuywTZUP5JUw9LL3kJa8LMfoo", - }, nil + strs := []string{ + "KT1LinsZAnyxajEv4eNFWtwHMdyhbJsGfvp3", + "KT1K4xei3yozp7UP5rHV5wuoDzWwBXqCGRBt", + "KT1GcSsQaTtMB2HvUKU9b6WRFUnGpGx9JwGk", + } + + var rtnstrs []*string + for i := range strs { + rtnstrs = append(rtnstrs, &strs[i]) + } + + return rtnstrs, nil } // Cycle - -func (g *GoTezosMock) Cycle(cycle int) (*gotezos.Cycle, error) { +func (g *GoTezosMock) Cycle(cycle int) (gotezos.Cycle, error) { if g.CycleErr { - return &gotezos.Cycle{}, errors.New("failed to get cycle") + return gotezos.Cycle{}, errors.New("failed to get cycle") } - return &gotezos.Cycle{ + return gotezos.Cycle{ RandomSeed: "some_seed", RollSnapshot: 10, BlockHash: "some_hash", @@ -93,10 +104,34 @@ func (g *GoTezosMock) StakingBalance(blockhash, delegate string) (*big.Int, erro } // InjectionOperation - -func (g *GoTezosMock) InjectionOperation(input *gotezos.InjectionOperationInput) (*[]byte, error) { +func (g *GoTezosMock) InjectionOperation(input gotezos.InjectionOperationInput) ([]byte, error) { if g.StakingBalanceErr { return nil, errors.New("failed to inject operation") } resp := []byte("ooYympR9wfV98X4MUHtE78NjXYRDeMTAD4ei7zEZDqoHv2rfb1M") - return &resp, nil + return resp, nil +} + +// OperationHashes - +func (g *GoTezosMock) OperationHashes(blockhash string) ([][]string, error) { + if g.OperationHashesErr { + return nil, errors.New("failed to get operation hashes") + } + + return [][]string{ + { + "ooYympR9wfV98X4MUHtE78NjXYRDeMTAD4ei7zEZDqoHv2rfb1M", + "ooYympR9wfV98X4MUHtE78NjXYRDeMTAD4ei7zEZDqoHv2rfFGD", + }, + }, nil +} + +// CheckErr - +func CheckErr(t *testing.T, wantErr bool, errContains string, err error) { + if wantErr { + assert.Error(t, err) + assert.Contains(t, err.Error(), errContains) + } else { + assert.Nil(t, err) + } } diff --git a/main.go b/main.go index 208f846..6cfa1b0 100644 --- a/main.go +++ b/main.go @@ -1,8 +1,21 @@ package main -import "github.com/goat-systems/tzpay/v2/cli" +import ( + "github.com/goat-systems/tzpay/v2/internal/cmd" + "github.com/spf13/cobra" +) -//Used to show how to use added features to Create Batch Payments. The signed operations are not injeced but rather returned as an array. func main() { - cli.Execute() + rootCommand := &cobra.Command{ + Use: "tzpay", + Short: "A bulk payout tool for bakers in the Tezos Ecosystem", + } + rootCommand.AddCommand( + cmd.DryRunCommand(), + cmd.RunCommand(), + cmd.NewVersionCommand(), + cmd.NewSetupCommand(), + ) + + rootCommand.Execute() } diff --git a/vendor/github.com/boltdb/bolt/.gitignore b/vendor/github.com/boltdb/bolt/.gitignore deleted file mode 100644 index c7bd2b7..0000000 --- a/vendor/github.com/boltdb/bolt/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -*.prof -*.test -*.swp -/bin/ diff --git a/vendor/github.com/boltdb/bolt/LICENSE b/vendor/github.com/boltdb/bolt/LICENSE deleted file mode 100644 index 004e77f..0000000 --- a/vendor/github.com/boltdb/bolt/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 Ben Johnson - -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/boltdb/bolt/Makefile b/vendor/github.com/boltdb/bolt/Makefile deleted file mode 100644 index e035e63..0000000 --- a/vendor/github.com/boltdb/bolt/Makefile +++ /dev/null @@ -1,18 +0,0 @@ -BRANCH=`git rev-parse --abbrev-ref HEAD` -COMMIT=`git rev-parse --short HEAD` -GOLDFLAGS="-X main.branch $(BRANCH) -X main.commit $(COMMIT)" - -default: build - -race: - @go test -v -race -test.run="TestSimulate_(100op|1000op)" - -# go get github.com/kisielk/errcheck -errcheck: - @errcheck -ignorepkg=bytes -ignore=os:Remove github.com/boltdb/bolt - -test: - @go test -v -cover . - @go test -v ./cmd/bolt - -.PHONY: fmt test diff --git a/vendor/github.com/boltdb/bolt/README.md b/vendor/github.com/boltdb/bolt/README.md deleted file mode 100644 index 7d43a15..0000000 --- a/vendor/github.com/boltdb/bolt/README.md +++ /dev/null @@ -1,916 +0,0 @@ -Bolt [![Coverage Status](https://coveralls.io/repos/boltdb/bolt/badge.svg?branch=master)](https://coveralls.io/r/boltdb/bolt?branch=master) [![GoDoc](https://godoc.org/github.com/boltdb/bolt?status.svg)](https://godoc.org/github.com/boltdb/bolt) ![Version](https://img.shields.io/badge/version-1.2.1-green.svg) -==== - -Bolt is a pure Go key/value store inspired by [Howard Chu's][hyc_symas] -[LMDB project][lmdb]. The goal of the project is to provide a simple, -fast, and reliable database for projects that don't require a full database -server such as Postgres or MySQL. - -Since Bolt is meant to be used as such a low-level piece of functionality, -simplicity is key. The API will be small and only focus on getting values -and setting values. That's it. - -[hyc_symas]: https://twitter.com/hyc_symas -[lmdb]: http://symas.com/mdb/ - -## Project Status - -Bolt is stable, the API is fixed, and the file format is fixed. Full unit -test coverage and randomized black box testing are used to ensure database -consistency and thread safety. Bolt is currently used in high-load production -environments serving databases as large as 1TB. Many companies such as -Shopify and Heroku use Bolt-backed services every day. - -## Table of Contents - -- [Getting Started](#getting-started) - - [Installing](#installing) - - [Opening a database](#opening-a-database) - - [Transactions](#transactions) - - [Read-write transactions](#read-write-transactions) - - [Read-only transactions](#read-only-transactions) - - [Batch read-write transactions](#batch-read-write-transactions) - - [Managing transactions manually](#managing-transactions-manually) - - [Using buckets](#using-buckets) - - [Using key/value pairs](#using-keyvalue-pairs) - - [Autoincrementing integer for the bucket](#autoincrementing-integer-for-the-bucket) - - [Iterating over keys](#iterating-over-keys) - - [Prefix scans](#prefix-scans) - - [Range scans](#range-scans) - - [ForEach()](#foreach) - - [Nested buckets](#nested-buckets) - - [Database backups](#database-backups) - - [Statistics](#statistics) - - [Read-Only Mode](#read-only-mode) - - [Mobile Use (iOS/Android)](#mobile-use-iosandroid) -- [Resources](#resources) -- [Comparison with other databases](#comparison-with-other-databases) - - [Postgres, MySQL, & other relational databases](#postgres-mysql--other-relational-databases) - - [LevelDB, RocksDB](#leveldb-rocksdb) - - [LMDB](#lmdb) -- [Caveats & Limitations](#caveats--limitations) -- [Reading the Source](#reading-the-source) -- [Other Projects Using Bolt](#other-projects-using-bolt) - -## Getting Started - -### Installing - -To start using Bolt, install Go and run `go get`: - -```sh -$ go get github.com/boltdb/bolt/... -``` - -This will retrieve the library and install the `bolt` command line utility into -your `$GOBIN` path. - - -### Opening a database - -The top-level object in Bolt is a `DB`. It is represented as a single file on -your disk and represents a consistent snapshot of your data. - -To open your database, simply use the `bolt.Open()` function: - -```go -package main - -import ( - "log" - - "github.com/boltdb/bolt" -) - -func main() { - // Open the my.db data file in your current directory. - // It will be created if it doesn't exist. - db, err := bolt.Open("my.db", 0600, nil) - if err != nil { - log.Fatal(err) - } - defer db.Close() - - ... -} -``` - -Please note that Bolt obtains a file lock on the data file so multiple processes -cannot open the same database at the same time. Opening an already open Bolt -database will cause it to hang until the other process closes it. To prevent -an indefinite wait you can pass a timeout option to the `Open()` function: - -```go -db, err := bolt.Open("my.db", 0600, &bolt.Options{Timeout: 1 * time.Second}) -``` - - -### Transactions - -Bolt allows only one read-write transaction at a time but allows as many -read-only transactions as you want at a time. Each transaction has a consistent -view of the data as it existed when the transaction started. - -Individual transactions and all objects created from them (e.g. buckets, keys) -are not thread safe. To work with data in multiple goroutines you must start -a transaction for each one or use locking to ensure only one goroutine accesses -a transaction at a time. Creating transaction from the `DB` is thread safe. - -Read-only transactions and read-write transactions should not depend on one -another and generally shouldn't be opened simultaneously in the same goroutine. -This can cause a deadlock as the read-write transaction needs to periodically -re-map the data file but it cannot do so while a read-only transaction is open. - - -#### Read-write transactions - -To start a read-write transaction, you can use the `DB.Update()` function: - -```go -err := db.Update(func(tx *bolt.Tx) error { - ... - return nil -}) -``` - -Inside the closure, you have a consistent view of the database. You commit the -transaction by returning `nil` at the end. You can also rollback the transaction -at any point by returning an error. All database operations are allowed inside -a read-write transaction. - -Always check the return error as it will report any disk failures that can cause -your transaction to not complete. If you return an error within your closure -it will be passed through. - - -#### Read-only transactions - -To start a read-only transaction, you can use the `DB.View()` function: - -```go -err := db.View(func(tx *bolt.Tx) error { - ... - return nil -}) -``` - -You also get a consistent view of the database within this closure, however, -no mutating operations are allowed within a read-only transaction. You can only -retrieve buckets, retrieve values, and copy the database within a read-only -transaction. - - -#### Batch read-write transactions - -Each `DB.Update()` waits for disk to commit the writes. This overhead -can be minimized by combining multiple updates with the `DB.Batch()` -function: - -```go -err := db.Batch(func(tx *bolt.Tx) error { - ... - return nil -}) -``` - -Concurrent Batch calls are opportunistically combined into larger -transactions. Batch is only useful when there are multiple goroutines -calling it. - -The trade-off is that `Batch` can call the given -function multiple times, if parts of the transaction fail. The -function must be idempotent and side effects must take effect only -after a successful return from `DB.Batch()`. - -For example: don't display messages from inside the function, instead -set variables in the enclosing scope: - -```go -var id uint64 -err := db.Batch(func(tx *bolt.Tx) error { - // Find last key in bucket, decode as bigendian uint64, increment - // by one, encode back to []byte, and add new key. - ... - id = newValue - return nil -}) -if err != nil { - return ... -} -fmt.Println("Allocated ID %d", id) -``` - - -#### Managing transactions manually - -The `DB.View()` and `DB.Update()` functions are wrappers around the `DB.Begin()` -function. These helper functions will start the transaction, execute a function, -and then safely close your transaction if an error is returned. This is the -recommended way to use Bolt transactions. - -However, sometimes you may want to manually start and end your transactions. -You can use the `DB.Begin()` function directly but **please** be sure to close -the transaction. - -```go -// Start a writable transaction. -tx, err := db.Begin(true) -if err != nil { - return err -} -defer tx.Rollback() - -// Use the transaction... -_, err := tx.CreateBucket([]byte("MyBucket")) -if err != nil { - return err -} - -// Commit the transaction and check for error. -if err := tx.Commit(); err != nil { - return err -} -``` - -The first argument to `DB.Begin()` is a boolean stating if the transaction -should be writable. - - -### Using buckets - -Buckets are collections of key/value pairs within the database. All keys in a -bucket must be unique. You can create a bucket using the `DB.CreateBucket()` -function: - -```go -db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("MyBucket")) - if err != nil { - return fmt.Errorf("create bucket: %s", err) - } - return nil -}) -``` - -You can also create a bucket only if it doesn't exist by using the -`Tx.CreateBucketIfNotExists()` function. It's a common pattern to call this -function for all your top-level buckets after you open your database so you can -guarantee that they exist for future transactions. - -To delete a bucket, simply call the `Tx.DeleteBucket()` function. - - -### Using key/value pairs - -To save a key/value pair to a bucket, use the `Bucket.Put()` function: - -```go -db.Update(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("MyBucket")) - err := b.Put([]byte("answer"), []byte("42")) - return err -}) -``` - -This will set the value of the `"answer"` key to `"42"` in the `MyBucket` -bucket. To retrieve this value, we can use the `Bucket.Get()` function: - -```go -db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("MyBucket")) - v := b.Get([]byte("answer")) - fmt.Printf("The answer is: %s\n", v) - return nil -}) -``` - -The `Get()` function does not return an error because its operation is -guaranteed to work (unless there is some kind of system failure). If the key -exists then it will return its byte slice value. If it doesn't exist then it -will return `nil`. It's important to note that you can have a zero-length value -set to a key which is different than the key not existing. - -Use the `Bucket.Delete()` function to delete a key from the bucket. - -Please note that values returned from `Get()` are only valid while the -transaction is open. If you need to use a value outside of the transaction -then you must use `copy()` to copy it to another byte slice. - - -### Autoincrementing integer for the bucket -By using the `NextSequence()` function, you can let Bolt determine a sequence -which can be used as the unique identifier for your key/value pairs. See the -example below. - -```go -// CreateUser saves u to the store. The new user ID is set on u once the data is persisted. -func (s *Store) CreateUser(u *User) error { - return s.db.Update(func(tx *bolt.Tx) error { - // Retrieve the users bucket. - // This should be created when the DB is first opened. - b := tx.Bucket([]byte("users")) - - // Generate ID for the user. - // This returns an error only if the Tx is closed or not writeable. - // That can't happen in an Update() call so I ignore the error check. - id, _ := b.NextSequence() - u.ID = int(id) - - // Marshal user data into bytes. - buf, err := json.Marshal(u) - if err != nil { - return err - } - - // Persist bytes to users bucket. - return b.Put(itob(u.ID), buf) - }) -} - -// itob returns an 8-byte big endian representation of v. -func itob(v int) []byte { - b := make([]byte, 8) - binary.BigEndian.PutUint64(b, uint64(v)) - return b -} - -type User struct { - ID int - ... -} -``` - -### Iterating over keys - -Bolt stores its keys in byte-sorted order within a bucket. This makes sequential -iteration over these keys extremely fast. To iterate over keys we'll use a -`Cursor`: - -```go -db.View(func(tx *bolt.Tx) error { - // Assume bucket exists and has keys - b := tx.Bucket([]byte("MyBucket")) - - c := b.Cursor() - - for k, v := c.First(); k != nil; k, v = c.Next() { - fmt.Printf("key=%s, value=%s\n", k, v) - } - - return nil -}) -``` - -The cursor allows you to move to a specific point in the list of keys and move -forward or backward through the keys one at a time. - -The following functions are available on the cursor: - -``` -First() Move to the first key. -Last() Move to the last key. -Seek() Move to a specific key. -Next() Move to the next key. -Prev() Move to the previous key. -``` - -Each of those functions has a return signature of `(key []byte, value []byte)`. -When you have iterated to the end of the cursor then `Next()` will return a -`nil` key. You must seek to a position using `First()`, `Last()`, or `Seek()` -before calling `Next()` or `Prev()`. If you do not seek to a position then -these functions will return a `nil` key. - -During iteration, if the key is non-`nil` but the value is `nil`, that means -the key refers to a bucket rather than a value. Use `Bucket.Bucket()` to -access the sub-bucket. - - -#### Prefix scans - -To iterate over a key prefix, you can combine `Seek()` and `bytes.HasPrefix()`: - -```go -db.View(func(tx *bolt.Tx) error { - // Assume bucket exists and has keys - c := tx.Bucket([]byte("MyBucket")).Cursor() - - prefix := []byte("1234") - for k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() { - fmt.Printf("key=%s, value=%s\n", k, v) - } - - return nil -}) -``` - -#### Range scans - -Another common use case is scanning over a range such as a time range. If you -use a sortable time encoding such as RFC3339 then you can query a specific -date range like this: - -```go -db.View(func(tx *bolt.Tx) error { - // Assume our events bucket exists and has RFC3339 encoded time keys. - c := tx.Bucket([]byte("Events")).Cursor() - - // Our time range spans the 90's decade. - min := []byte("1990-01-01T00:00:00Z") - max := []byte("2000-01-01T00:00:00Z") - - // Iterate over the 90's. - for k, v := c.Seek(min); k != nil && bytes.Compare(k, max) <= 0; k, v = c.Next() { - fmt.Printf("%s: %s\n", k, v) - } - - return nil -}) -``` - -Note that, while RFC3339 is sortable, the Golang implementation of RFC3339Nano does not use a fixed number of digits after the decimal point and is therefore not sortable. - - -#### ForEach() - -You can also use the function `ForEach()` if you know you'll be iterating over -all the keys in a bucket: - -```go -db.View(func(tx *bolt.Tx) error { - // Assume bucket exists and has keys - b := tx.Bucket([]byte("MyBucket")) - - b.ForEach(func(k, v []byte) error { - fmt.Printf("key=%s, value=%s\n", k, v) - return nil - }) - return nil -}) -``` - -Please note that keys and values in `ForEach()` are only valid while -the transaction is open. If you need to use a key or value outside of -the transaction, you must use `copy()` to copy it to another byte -slice. - -### Nested buckets - -You can also store a bucket in a key to create nested buckets. The API is the -same as the bucket management API on the `DB` object: - -```go -func (*Bucket) CreateBucket(key []byte) (*Bucket, error) -func (*Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) -func (*Bucket) DeleteBucket(key []byte) error -``` - -Say you had a multi-tenant application where the root level bucket was the account bucket. Inside of this bucket was a sequence of accounts which themselves are buckets. And inside the sequence bucket you could have many buckets pertaining to the Account itself (Users, Notes, etc) isolating the information into logical groupings. - -```go - -// createUser creates a new user in the given account. -func createUser(accountID int, u *User) error { - // Start the transaction. - tx, err := db.Begin(true) - if err != nil { - return err - } - defer tx.Rollback() - - // Retrieve the root bucket for the account. - // Assume this has already been created when the account was set up. - root := tx.Bucket([]byte(strconv.FormatUint(accountID, 10))) - - // Setup the users bucket. - bkt, err := root.CreateBucketIfNotExists([]byte("USERS")) - if err != nil { - return err - } - - // Generate an ID for the new user. - userID, err := bkt.NextSequence() - if err != nil { - return err - } - u.ID = userID - - // Marshal and save the encoded user. - if buf, err := json.Marshal(u); err != nil { - return err - } else if err := bkt.Put([]byte(strconv.FormatUint(u.ID, 10)), buf); err != nil { - return err - } - - // Commit the transaction. - if err := tx.Commit(); err != nil { - return err - } - - return nil -} - -``` - - - - -### Database backups - -Bolt is a single file so it's easy to backup. You can use the `Tx.WriteTo()` -function to write a consistent view of the database to a writer. If you call -this from a read-only transaction, it will perform a hot backup and not block -your other database reads and writes. - -By default, it will use a regular file handle which will utilize the operating -system's page cache. See the [`Tx`](https://godoc.org/github.com/boltdb/bolt#Tx) -documentation for information about optimizing for larger-than-RAM datasets. - -One common use case is to backup over HTTP so you can use tools like `cURL` to -do database backups: - -```go -func BackupHandleFunc(w http.ResponseWriter, req *http.Request) { - err := db.View(func(tx *bolt.Tx) error { - w.Header().Set("Content-Type", "application/octet-stream") - w.Header().Set("Content-Disposition", `attachment; filename="my.db"`) - w.Header().Set("Content-Length", strconv.Itoa(int(tx.Size()))) - _, err := tx.WriteTo(w) - return err - }) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } -} -``` - -Then you can backup using this command: - -```sh -$ curl http://localhost/backup > my.db -``` - -Or you can open your browser to `http://localhost/backup` and it will download -automatically. - -If you want to backup to another file you can use the `Tx.CopyFile()` helper -function. - - -### Statistics - -The database keeps a running count of many of the internal operations it -performs so you can better understand what's going on. By grabbing a snapshot -of these stats at two points in time we can see what operations were performed -in that time range. - -For example, we could start a goroutine to log stats every 10 seconds: - -```go -go func() { - // Grab the initial stats. - prev := db.Stats() - - for { - // Wait for 10s. - time.Sleep(10 * time.Second) - - // Grab the current stats and diff them. - stats := db.Stats() - diff := stats.Sub(&prev) - - // Encode stats to JSON and print to STDERR. - json.NewEncoder(os.Stderr).Encode(diff) - - // Save stats for the next loop. - prev = stats - } -}() -``` - -It's also useful to pipe these stats to a service such as statsd for monitoring -or to provide an HTTP endpoint that will perform a fixed-length sample. - - -### Read-Only Mode - -Sometimes it is useful to create a shared, read-only Bolt database. To this, -set the `Options.ReadOnly` flag when opening your database. Read-only mode -uses a shared lock to allow multiple processes to read from the database but -it will block any processes from opening the database in read-write mode. - -```go -db, err := bolt.Open("my.db", 0666, &bolt.Options{ReadOnly: true}) -if err != nil { - log.Fatal(err) -} -``` - -### Mobile Use (iOS/Android) - -Bolt is able to run on mobile devices by leveraging the binding feature of the -[gomobile](https://github.com/golang/mobile) tool. Create a struct that will -contain your database logic and a reference to a `*bolt.DB` with a initializing -constructor that takes in a filepath where the database file will be stored. -Neither Android nor iOS require extra permissions or cleanup from using this method. - -```go -func NewBoltDB(filepath string) *BoltDB { - db, err := bolt.Open(filepath+"/demo.db", 0600, nil) - if err != nil { - log.Fatal(err) - } - - return &BoltDB{db} -} - -type BoltDB struct { - db *bolt.DB - ... -} - -func (b *BoltDB) Path() string { - return b.db.Path() -} - -func (b *BoltDB) Close() { - b.db.Close() -} -``` - -Database logic should be defined as methods on this wrapper struct. - -To initialize this struct from the native language (both platforms now sync -their local storage to the cloud. These snippets disable that functionality for the -database file): - -#### Android - -```java -String path; -if (android.os.Build.VERSION.SDK_INT >=android.os.Build.VERSION_CODES.LOLLIPOP){ - path = getNoBackupFilesDir().getAbsolutePath(); -} else{ - path = getFilesDir().getAbsolutePath(); -} -Boltmobiledemo.BoltDB boltDB = Boltmobiledemo.NewBoltDB(path) -``` - -#### iOS - -```objc -- (void)demo { - NSString* path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, - NSUserDomainMask, - YES) objectAtIndex:0]; - GoBoltmobiledemoBoltDB * demo = GoBoltmobiledemoNewBoltDB(path); - [self addSkipBackupAttributeToItemAtPath:demo.path]; - //Some DB Logic would go here - [demo close]; -} - -- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString -{ - NSURL* URL= [NSURL fileURLWithPath: filePathString]; - assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]); - - NSError *error = nil; - BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES] - forKey: NSURLIsExcludedFromBackupKey error: &error]; - if(!success){ - NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error); - } - return success; -} - -``` - -## Resources - -For more information on getting started with Bolt, check out the following articles: - -* [Intro to BoltDB: Painless Performant Persistence](http://npf.io/2014/07/intro-to-boltdb-painless-performant-persistence/) by [Nate Finch](https://github.com/natefinch). -* [Bolt -- an embedded key/value database for Go](https://www.progville.com/go/bolt-embedded-db-golang/) by Progville - - -## Comparison with other databases - -### Postgres, MySQL, & other relational databases - -Relational databases structure data into rows and are only accessible through -the use of SQL. This approach provides flexibility in how you store and query -your data but also incurs overhead in parsing and planning SQL statements. Bolt -accesses all data by a byte slice key. This makes Bolt fast to read and write -data by key but provides no built-in support for joining values together. - -Most relational databases (with the exception of SQLite) are standalone servers -that run separately from your application. This gives your systems -flexibility to connect multiple application servers to a single database -server but also adds overhead in serializing and transporting data over the -network. Bolt runs as a library included in your application so all data access -has to go through your application's process. This brings data closer to your -application but limits multi-process access to the data. - - -### LevelDB, RocksDB - -LevelDB and its derivatives (RocksDB, HyperLevelDB) are similar to Bolt in that -they are libraries bundled into the application, however, their underlying -structure is a log-structured merge-tree (LSM tree). An LSM tree optimizes -random writes by using a write ahead log and multi-tiered, sorted files called -SSTables. Bolt uses a B+tree internally and only a single file. Both approaches -have trade-offs. - -If you require a high random write throughput (>10,000 w/sec) or you need to use -spinning disks then LevelDB could be a good choice. If your application is -read-heavy or does a lot of range scans then Bolt could be a good choice. - -One other important consideration is that LevelDB does not have transactions. -It supports batch writing of key/values pairs and it supports read snapshots -but it will not give you the ability to do a compare-and-swap operation safely. -Bolt supports fully serializable ACID transactions. - - -### LMDB - -Bolt was originally a port of LMDB so it is architecturally similar. Both use -a B+tree, have ACID semantics with fully serializable transactions, and support -lock-free MVCC using a single writer and multiple readers. - -The two projects have somewhat diverged. LMDB heavily focuses on raw performance -while Bolt has focused on simplicity and ease of use. For example, LMDB allows -several unsafe actions such as direct writes for the sake of performance. Bolt -opts to disallow actions which can leave the database in a corrupted state. The -only exception to this in Bolt is `DB.NoSync`. - -There are also a few differences in API. LMDB requires a maximum mmap size when -opening an `mdb_env` whereas Bolt will handle incremental mmap resizing -automatically. LMDB overloads the getter and setter functions with multiple -flags whereas Bolt splits these specialized cases into their own functions. - - -## Caveats & Limitations - -It's important to pick the right tool for the job and Bolt is no exception. -Here are a few things to note when evaluating and using Bolt: - -* Bolt is good for read intensive workloads. Sequential write performance is - also fast but random writes can be slow. You can use `DB.Batch()` or add a - write-ahead log to help mitigate this issue. - -* Bolt uses a B+tree internally so there can be a lot of random page access. - SSDs provide a significant performance boost over spinning disks. - -* Try to avoid long running read transactions. Bolt uses copy-on-write so - old pages cannot be reclaimed while an old transaction is using them. - -* Byte slices returned from Bolt are only valid during a transaction. Once the - transaction has been committed or rolled back then the memory they point to - can be reused by a new page or can be unmapped from virtual memory and you'll - see an `unexpected fault address` panic when accessing it. - -* Bolt uses an exclusive write lock on the database file so it cannot be - shared by multiple processes. - -* Be careful when using `Bucket.FillPercent`. Setting a high fill percent for - buckets that have random inserts will cause your database to have very poor - page utilization. - -* Use larger buckets in general. Smaller buckets causes poor page utilization - once they become larger than the page size (typically 4KB). - -* Bulk loading a lot of random writes into a new bucket can be slow as the - page will not split until the transaction is committed. Randomly inserting - more than 100,000 key/value pairs into a single new bucket in a single - transaction is not advised. - -* Bolt uses a memory-mapped file so the underlying operating system handles the - caching of the data. Typically, the OS will cache as much of the file as it - can in memory and will release memory as needed to other processes. This means - that Bolt can show very high memory usage when working with large databases. - However, this is expected and the OS will release memory as needed. Bolt can - handle databases much larger than the available physical RAM, provided its - memory-map fits in the process virtual address space. It may be problematic - on 32-bits systems. - -* The data structures in the Bolt database are memory mapped so the data file - will be endian specific. This means that you cannot copy a Bolt file from a - little endian machine to a big endian machine and have it work. For most - users this is not a concern since most modern CPUs are little endian. - -* Because of the way pages are laid out on disk, Bolt cannot truncate data files - and return free pages back to the disk. Instead, Bolt maintains a free list - of unused pages within its data file. These free pages can be reused by later - transactions. This works well for many use cases as databases generally tend - to grow. However, it's important to note that deleting large chunks of data - will not allow you to reclaim that space on disk. - - For more information on page allocation, [see this comment][page-allocation]. - -[page-allocation]: https://github.com/boltdb/bolt/issues/308#issuecomment-74811638 - - -## Reading the Source - -Bolt is a relatively small code base (<3KLOC) for an embedded, serializable, -transactional key/value database so it can be a good starting point for people -interested in how databases work. - -The best places to start are the main entry points into Bolt: - -- `Open()` - Initializes the reference to the database. It's responsible for - creating the database if it doesn't exist, obtaining an exclusive lock on the - file, reading the meta pages, & memory-mapping the file. - -- `DB.Begin()` - Starts a read-only or read-write transaction depending on the - value of the `writable` argument. This requires briefly obtaining the "meta" - lock to keep track of open transactions. Only one read-write transaction can - exist at a time so the "rwlock" is acquired during the life of a read-write - transaction. - -- `Bucket.Put()` - Writes a key/value pair into a bucket. After validating the - arguments, a cursor is used to traverse the B+tree to the page and position - where they key & value will be written. Once the position is found, the bucket - materializes the underlying page and the page's parent pages into memory as - "nodes". These nodes are where mutations occur during read-write transactions. - These changes get flushed to disk during commit. - -- `Bucket.Get()` - Retrieves a key/value pair from a bucket. This uses a cursor - to move to the page & position of a key/value pair. During a read-only - transaction, the key and value data is returned as a direct reference to the - underlying mmap file so there's no allocation overhead. For read-write - transactions, this data may reference the mmap file or one of the in-memory - node values. - -- `Cursor` - This object is simply for traversing the B+tree of on-disk pages - or in-memory nodes. It can seek to a specific key, move to the first or last - value, or it can move forward or backward. The cursor handles the movement up - and down the B+tree transparently to the end user. - -- `Tx.Commit()` - Converts the in-memory dirty nodes and the list of free pages - into pages to be written to disk. Writing to disk then occurs in two phases. - First, the dirty pages are written to disk and an `fsync()` occurs. Second, a - new meta page with an incremented transaction ID is written and another - `fsync()` occurs. This two phase write ensures that partially written data - pages are ignored in the event of a crash since the meta page pointing to them - is never written. Partially written meta pages are invalidated because they - are written with a checksum. - -If you have additional notes that could be helpful for others, please submit -them via pull request. - - -## Other Projects Using Bolt - -Below is a list of public, open source projects that use Bolt: - -* [BoltDbWeb](https://github.com/evnix/boltdbweb) - A web based GUI for BoltDB files. -* [Operation Go: A Routine Mission](http://gocode.io) - An online programming game for Golang using Bolt for user accounts and a leaderboard. -* [Bazil](https://bazil.org/) - A file system that lets your data reside where it is most convenient for it to reside. -* [DVID](https://github.com/janelia-flyem/dvid) - Added Bolt as optional storage engine and testing it against Basho-tuned leveldb. -* [Skybox Analytics](https://github.com/skybox/skybox) - A standalone funnel analysis tool for web analytics. -* [Scuttlebutt](https://github.com/benbjohnson/scuttlebutt) - Uses Bolt to store and process all Twitter mentions of GitHub projects. -* [Wiki](https://github.com/peterhellberg/wiki) - A tiny wiki using Goji, BoltDB and Blackfriday. -* [ChainStore](https://github.com/pressly/chainstore) - Simple key-value interface to a variety of storage engines organized as a chain of operations. -* [MetricBase](https://github.com/msiebuhr/MetricBase) - Single-binary version of Graphite. -* [Gitchain](https://github.com/gitchain/gitchain) - Decentralized, peer-to-peer Git repositories aka "Git meets Bitcoin". -* [event-shuttle](https://github.com/sclasen/event-shuttle) - A Unix system service to collect and reliably deliver messages to Kafka. -* [ipxed](https://github.com/kelseyhightower/ipxed) - Web interface and api for ipxed. -* [BoltStore](https://github.com/yosssi/boltstore) - Session store using Bolt. -* [photosite/session](https://godoc.org/bitbucket.org/kardianos/photosite/session) - Sessions for a photo viewing site. -* [LedisDB](https://github.com/siddontang/ledisdb) - A high performance NoSQL, using Bolt as optional storage. -* [ipLocator](https://github.com/AndreasBriese/ipLocator) - A fast ip-geo-location-server using bolt with bloom filters. -* [cayley](https://github.com/google/cayley) - Cayley is an open-source graph database using Bolt as optional backend. -* [bleve](http://www.blevesearch.com/) - A pure Go search engine similar to ElasticSearch that uses Bolt as the default storage backend. -* [tentacool](https://github.com/optiflows/tentacool) - REST api server to manage system stuff (IP, DNS, Gateway...) on a linux server. -* [Seaweed File System](https://github.com/chrislusf/seaweedfs) - Highly scalable distributed key~file system with O(1) disk read. -* [InfluxDB](https://influxdata.com) - Scalable datastore for metrics, events, and real-time analytics. -* [Freehold](http://tshannon.bitbucket.org/freehold/) - An open, secure, and lightweight platform for your files and data. -* [Prometheus Annotation Server](https://github.com/oliver006/prom_annotation_server) - Annotation server for PromDash & Prometheus service monitoring system. -* [Consul](https://github.com/hashicorp/consul) - Consul is service discovery and configuration made easy. Distributed, highly available, and datacenter-aware. -* [Kala](https://github.com/ajvb/kala) - Kala is a modern job scheduler optimized to run on a single node. It is persistent, JSON over HTTP API, ISO 8601 duration notation, and dependent jobs. -* [drive](https://github.com/odeke-em/drive) - drive is an unofficial Google Drive command line client for \*NIX operating systems. -* [stow](https://github.com/djherbis/stow) - a persistence manager for objects - backed by boltdb. -* [buckets](https://github.com/joyrexus/buckets) - a bolt wrapper streamlining - simple tx and key scans. -* [mbuckets](https://github.com/abhigupta912/mbuckets) - A Bolt wrapper that allows easy operations on multi level (nested) buckets. -* [Request Baskets](https://github.com/darklynx/request-baskets) - A web service to collect arbitrary HTTP requests and inspect them via REST API or simple web UI, similar to [RequestBin](http://requestb.in/) service -* [Go Report Card](https://goreportcard.com/) - Go code quality report cards as a (free and open source) service. -* [Boltdb Boilerplate](https://github.com/bobintornado/boltdb-boilerplate) - Boilerplate wrapper around bolt aiming to make simple calls one-liners. -* [lru](https://github.com/crowdriff/lru) - Easy to use Bolt-backed Least-Recently-Used (LRU) read-through cache with chainable remote stores. -* [Storm](https://github.com/asdine/storm) - Simple and powerful ORM for BoltDB. -* [GoWebApp](https://github.com/josephspurrier/gowebapp) - A basic MVC web application in Go using BoltDB. -* [SimpleBolt](https://github.com/xyproto/simplebolt) - A simple way to use BoltDB. Deals mainly with strings. -* [Algernon](https://github.com/xyproto/algernon) - A HTTP/2 web server with built-in support for Lua. Uses BoltDB as the default database backend. -* [MuLiFS](https://github.com/dankomiocevic/mulifs) - Music Library Filesystem creates a filesystem to organise your music files. -* [GoShort](https://github.com/pankajkhairnar/goShort) - GoShort is a URL shortener written in Golang and BoltDB for persistent key/value storage and for routing it's using high performent HTTPRouter. -* [torrent](https://github.com/anacrolix/torrent) - Full-featured BitTorrent client package and utilities in Go. BoltDB is a storage backend in development. -* [gopherpit](https://github.com/gopherpit/gopherpit) - A web service to manage Go remote import paths with custom domains -* [bolter](https://github.com/hasit/bolter) - Command-line app for viewing BoltDB file in your terminal. -* [btcwallet](https://github.com/btcsuite/btcwallet) - A bitcoin wallet. -* [dcrwallet](https://github.com/decred/dcrwallet) - A wallet for the Decred cryptocurrency. -* [Ironsmith](https://github.com/timshannon/ironsmith) - A simple, script-driven continuous integration (build - > test -> release) tool, with no external dependencies -* [BoltHold](https://github.com/timshannon/bolthold) - An embeddable NoSQL store for Go types built on BoltDB -* [Ponzu CMS](https://ponzu-cms.org) - Headless CMS + automatic JSON API with auto-HTTPS, HTTP/2 Server Push, and flexible server framework. - -If you are using Bolt in a project please send a pull request to add it to the list. diff --git a/vendor/github.com/boltdb/bolt/appveyor.yml b/vendor/github.com/boltdb/bolt/appveyor.yml deleted file mode 100644 index 6e26e94..0000000 --- a/vendor/github.com/boltdb/bolt/appveyor.yml +++ /dev/null @@ -1,18 +0,0 @@ -version: "{build}" - -os: Windows Server 2012 R2 - -clone_folder: c:\gopath\src\github.com\boltdb\bolt - -environment: - GOPATH: c:\gopath - -install: - - echo %PATH% - - echo %GOPATH% - - go version - - go env - - go get -v -t ./... - -build_script: - - go test -v ./... diff --git a/vendor/github.com/boltdb/bolt/bolt_386.go b/vendor/github.com/boltdb/bolt/bolt_386.go deleted file mode 100644 index 820d533..0000000 --- a/vendor/github.com/boltdb/bolt/bolt_386.go +++ /dev/null @@ -1,10 +0,0 @@ -package bolt - -// maxMapSize represents the largest mmap size supported by Bolt. -const maxMapSize = 0x7FFFFFFF // 2GB - -// maxAllocSize is the size used when creating array pointers. -const maxAllocSize = 0xFFFFFFF - -// Are unaligned load/stores broken on this arch? -var brokenUnaligned = false diff --git a/vendor/github.com/boltdb/bolt/bolt_amd64.go b/vendor/github.com/boltdb/bolt/bolt_amd64.go deleted file mode 100644 index 98fafdb..0000000 --- a/vendor/github.com/boltdb/bolt/bolt_amd64.go +++ /dev/null @@ -1,10 +0,0 @@ -package bolt - -// maxMapSize represents the largest mmap size supported by Bolt. -const maxMapSize = 0xFFFFFFFFFFFF // 256TB - -// maxAllocSize is the size used when creating array pointers. -const maxAllocSize = 0x7FFFFFFF - -// Are unaligned load/stores broken on this arch? -var brokenUnaligned = false diff --git a/vendor/github.com/boltdb/bolt/bolt_arm.go b/vendor/github.com/boltdb/bolt/bolt_arm.go deleted file mode 100644 index 7e5cb4b..0000000 --- a/vendor/github.com/boltdb/bolt/bolt_arm.go +++ /dev/null @@ -1,28 +0,0 @@ -package bolt - -import "unsafe" - -// maxMapSize represents the largest mmap size supported by Bolt. -const maxMapSize = 0x7FFFFFFF // 2GB - -// maxAllocSize is the size used when creating array pointers. -const maxAllocSize = 0xFFFFFFF - -// Are unaligned load/stores broken on this arch? -var brokenUnaligned bool - -func init() { - // Simple check to see whether this arch handles unaligned load/stores - // correctly. - - // ARM9 and older devices require load/stores to be from/to aligned - // addresses. If not, the lower 2 bits are cleared and that address is - // read in a jumbled up order. - - // See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/ka15414.html - - raw := [6]byte{0xfe, 0xef, 0x11, 0x22, 0x22, 0x11} - val := *(*uint32)(unsafe.Pointer(uintptr(unsafe.Pointer(&raw)) + 2)) - - brokenUnaligned = val != 0x11222211 -} diff --git a/vendor/github.com/boltdb/bolt/bolt_arm64.go b/vendor/github.com/boltdb/bolt/bolt_arm64.go deleted file mode 100644 index b26d84f..0000000 --- a/vendor/github.com/boltdb/bolt/bolt_arm64.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build arm64 - -package bolt - -// maxMapSize represents the largest mmap size supported by Bolt. -const maxMapSize = 0xFFFFFFFFFFFF // 256TB - -// maxAllocSize is the size used when creating array pointers. -const maxAllocSize = 0x7FFFFFFF - -// Are unaligned load/stores broken on this arch? -var brokenUnaligned = false diff --git a/vendor/github.com/boltdb/bolt/bolt_linux.go b/vendor/github.com/boltdb/bolt/bolt_linux.go deleted file mode 100644 index 2b67666..0000000 --- a/vendor/github.com/boltdb/bolt/bolt_linux.go +++ /dev/null @@ -1,10 +0,0 @@ -package bolt - -import ( - "syscall" -) - -// fdatasync flushes written data to a file descriptor. -func fdatasync(db *DB) error { - return syscall.Fdatasync(int(db.file.Fd())) -} diff --git a/vendor/github.com/boltdb/bolt/bolt_openbsd.go b/vendor/github.com/boltdb/bolt/bolt_openbsd.go deleted file mode 100644 index 7058c3d..0000000 --- a/vendor/github.com/boltdb/bolt/bolt_openbsd.go +++ /dev/null @@ -1,27 +0,0 @@ -package bolt - -import ( - "syscall" - "unsafe" -) - -const ( - msAsync = 1 << iota // perform asynchronous writes - msSync // perform synchronous writes - msInvalidate // invalidate cached data -) - -func msync(db *DB) error { - _, _, errno := syscall.Syscall(syscall.SYS_MSYNC, uintptr(unsafe.Pointer(db.data)), uintptr(db.datasz), msInvalidate) - if errno != 0 { - return errno - } - return nil -} - -func fdatasync(db *DB) error { - if db.data != nil { - return msync(db) - } - return db.file.Sync() -} diff --git a/vendor/github.com/boltdb/bolt/bolt_ppc.go b/vendor/github.com/boltdb/bolt/bolt_ppc.go deleted file mode 100644 index 645ddc3..0000000 --- a/vendor/github.com/boltdb/bolt/bolt_ppc.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build ppc - -package bolt - -// maxMapSize represents the largest mmap size supported by Bolt. -const maxMapSize = 0x7FFFFFFF // 2GB - -// maxAllocSize is the size used when creating array pointers. -const maxAllocSize = 0xFFFFFFF diff --git a/vendor/github.com/boltdb/bolt/bolt_ppc64.go b/vendor/github.com/boltdb/bolt/bolt_ppc64.go deleted file mode 100644 index 9331d97..0000000 --- a/vendor/github.com/boltdb/bolt/bolt_ppc64.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build ppc64 - -package bolt - -// maxMapSize represents the largest mmap size supported by Bolt. -const maxMapSize = 0xFFFFFFFFFFFF // 256TB - -// maxAllocSize is the size used when creating array pointers. -const maxAllocSize = 0x7FFFFFFF - -// Are unaligned load/stores broken on this arch? -var brokenUnaligned = false diff --git a/vendor/github.com/boltdb/bolt/bolt_ppc64le.go b/vendor/github.com/boltdb/bolt/bolt_ppc64le.go deleted file mode 100644 index 8c143bc..0000000 --- a/vendor/github.com/boltdb/bolt/bolt_ppc64le.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build ppc64le - -package bolt - -// maxMapSize represents the largest mmap size supported by Bolt. -const maxMapSize = 0xFFFFFFFFFFFF // 256TB - -// maxAllocSize is the size used when creating array pointers. -const maxAllocSize = 0x7FFFFFFF - -// Are unaligned load/stores broken on this arch? -var brokenUnaligned = false diff --git a/vendor/github.com/boltdb/bolt/bolt_s390x.go b/vendor/github.com/boltdb/bolt/bolt_s390x.go deleted file mode 100644 index d7c39af..0000000 --- a/vendor/github.com/boltdb/bolt/bolt_s390x.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build s390x - -package bolt - -// maxMapSize represents the largest mmap size supported by Bolt. -const maxMapSize = 0xFFFFFFFFFFFF // 256TB - -// maxAllocSize is the size used when creating array pointers. -const maxAllocSize = 0x7FFFFFFF - -// Are unaligned load/stores broken on this arch? -var brokenUnaligned = false diff --git a/vendor/github.com/boltdb/bolt/bolt_unix.go b/vendor/github.com/boltdb/bolt/bolt_unix.go deleted file mode 100644 index cad62dd..0000000 --- a/vendor/github.com/boltdb/bolt/bolt_unix.go +++ /dev/null @@ -1,89 +0,0 @@ -// +build !windows,!plan9,!solaris - -package bolt - -import ( - "fmt" - "os" - "syscall" - "time" - "unsafe" -) - -// flock acquires an advisory lock on a file descriptor. -func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error { - var t time.Time - for { - // If we're beyond our timeout then return an error. - // This can only occur after we've attempted a flock once. - if t.IsZero() { - t = time.Now() - } else if timeout > 0 && time.Since(t) > timeout { - return ErrTimeout - } - flag := syscall.LOCK_SH - if exclusive { - flag = syscall.LOCK_EX - } - - // Otherwise attempt to obtain an exclusive lock. - err := syscall.Flock(int(db.file.Fd()), flag|syscall.LOCK_NB) - if err == nil { - return nil - } else if err != syscall.EWOULDBLOCK { - return err - } - - // Wait for a bit and try again. - time.Sleep(50 * time.Millisecond) - } -} - -// funlock releases an advisory lock on a file descriptor. -func funlock(db *DB) error { - return syscall.Flock(int(db.file.Fd()), syscall.LOCK_UN) -} - -// mmap memory maps a DB's data file. -func mmap(db *DB, sz int) error { - // Map the data file to memory. - b, err := syscall.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags) - if err != nil { - return err - } - - // Advise the kernel that the mmap is accessed randomly. - if err := madvise(b, syscall.MADV_RANDOM); err != nil { - return fmt.Errorf("madvise: %s", err) - } - - // Save the original byte slice and convert to a byte array pointer. - db.dataref = b - db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0])) - db.datasz = sz - return nil -} - -// munmap unmaps a DB's data file from memory. -func munmap(db *DB) error { - // Ignore the unmap if we have no mapped data. - if db.dataref == nil { - return nil - } - - // Unmap using the original byte slice. - err := syscall.Munmap(db.dataref) - db.dataref = nil - db.data = nil - db.datasz = 0 - return err -} - -// NOTE: This function is copied from stdlib because it is not available on darwin. -func madvise(b []byte, advice int) (err error) { - _, _, e1 := syscall.Syscall(syscall.SYS_MADVISE, uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), uintptr(advice)) - if e1 != 0 { - err = e1 - } - return -} diff --git a/vendor/github.com/boltdb/bolt/bolt_unix_solaris.go b/vendor/github.com/boltdb/bolt/bolt_unix_solaris.go deleted file mode 100644 index 307bf2b..0000000 --- a/vendor/github.com/boltdb/bolt/bolt_unix_solaris.go +++ /dev/null @@ -1,90 +0,0 @@ -package bolt - -import ( - "fmt" - "os" - "syscall" - "time" - "unsafe" - - "golang.org/x/sys/unix" -) - -// flock acquires an advisory lock on a file descriptor. -func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error { - var t time.Time - for { - // If we're beyond our timeout then return an error. - // This can only occur after we've attempted a flock once. - if t.IsZero() { - t = time.Now() - } else if timeout > 0 && time.Since(t) > timeout { - return ErrTimeout - } - var lock syscall.Flock_t - lock.Start = 0 - lock.Len = 0 - lock.Pid = 0 - lock.Whence = 0 - lock.Pid = 0 - if exclusive { - lock.Type = syscall.F_WRLCK - } else { - lock.Type = syscall.F_RDLCK - } - err := syscall.FcntlFlock(db.file.Fd(), syscall.F_SETLK, &lock) - if err == nil { - return nil - } else if err != syscall.EAGAIN { - return err - } - - // Wait for a bit and try again. - time.Sleep(50 * time.Millisecond) - } -} - -// funlock releases an advisory lock on a file descriptor. -func funlock(db *DB) error { - var lock syscall.Flock_t - lock.Start = 0 - lock.Len = 0 - lock.Type = syscall.F_UNLCK - lock.Whence = 0 - return syscall.FcntlFlock(uintptr(db.file.Fd()), syscall.F_SETLK, &lock) -} - -// mmap memory maps a DB's data file. -func mmap(db *DB, sz int) error { - // Map the data file to memory. - b, err := unix.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags) - if err != nil { - return err - } - - // Advise the kernel that the mmap is accessed randomly. - if err := unix.Madvise(b, syscall.MADV_RANDOM); err != nil { - return fmt.Errorf("madvise: %s", err) - } - - // Save the original byte slice and convert to a byte array pointer. - db.dataref = b - db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0])) - db.datasz = sz - return nil -} - -// munmap unmaps a DB's data file from memory. -func munmap(db *DB) error { - // Ignore the unmap if we have no mapped data. - if db.dataref == nil { - return nil - } - - // Unmap using the original byte slice. - err := unix.Munmap(db.dataref) - db.dataref = nil - db.data = nil - db.datasz = 0 - return err -} diff --git a/vendor/github.com/boltdb/bolt/bolt_windows.go b/vendor/github.com/boltdb/bolt/bolt_windows.go deleted file mode 100644 index b00fb07..0000000 --- a/vendor/github.com/boltdb/bolt/bolt_windows.go +++ /dev/null @@ -1,144 +0,0 @@ -package bolt - -import ( - "fmt" - "os" - "syscall" - "time" - "unsafe" -) - -// LockFileEx code derived from golang build filemutex_windows.go @ v1.5.1 -var ( - modkernel32 = syscall.NewLazyDLL("kernel32.dll") - procLockFileEx = modkernel32.NewProc("LockFileEx") - procUnlockFileEx = modkernel32.NewProc("UnlockFileEx") -) - -const ( - lockExt = ".lock" - - // see https://msdn.microsoft.com/en-us/library/windows/desktop/aa365203(v=vs.85).aspx - flagLockExclusive = 2 - flagLockFailImmediately = 1 - - // see https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx - errLockViolation syscall.Errno = 0x21 -) - -func lockFileEx(h syscall.Handle, flags, reserved, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) { - r, _, err := procLockFileEx.Call(uintptr(h), uintptr(flags), uintptr(reserved), uintptr(locklow), uintptr(lockhigh), uintptr(unsafe.Pointer(ol))) - if r == 0 { - return err - } - return nil -} - -func unlockFileEx(h syscall.Handle, reserved, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) { - r, _, err := procUnlockFileEx.Call(uintptr(h), uintptr(reserved), uintptr(locklow), uintptr(lockhigh), uintptr(unsafe.Pointer(ol)), 0) - if r == 0 { - return err - } - return nil -} - -// fdatasync flushes written data to a file descriptor. -func fdatasync(db *DB) error { - return db.file.Sync() -} - -// flock acquires an advisory lock on a file descriptor. -func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error { - // Create a separate lock file on windows because a process - // cannot share an exclusive lock on the same file. This is - // needed during Tx.WriteTo(). - f, err := os.OpenFile(db.path+lockExt, os.O_CREATE, mode) - if err != nil { - return err - } - db.lockfile = f - - var t time.Time - for { - // If we're beyond our timeout then return an error. - // This can only occur after we've attempted a flock once. - if t.IsZero() { - t = time.Now() - } else if timeout > 0 && time.Since(t) > timeout { - return ErrTimeout - } - - var flag uint32 = flagLockFailImmediately - if exclusive { - flag |= flagLockExclusive - } - - err := lockFileEx(syscall.Handle(db.lockfile.Fd()), flag, 0, 1, 0, &syscall.Overlapped{}) - if err == nil { - return nil - } else if err != errLockViolation { - return err - } - - // Wait for a bit and try again. - time.Sleep(50 * time.Millisecond) - } -} - -// funlock releases an advisory lock on a file descriptor. -func funlock(db *DB) error { - err := unlockFileEx(syscall.Handle(db.lockfile.Fd()), 0, 1, 0, &syscall.Overlapped{}) - db.lockfile.Close() - os.Remove(db.path + lockExt) - return err -} - -// mmap memory maps a DB's data file. -// Based on: https://github.com/edsrzf/mmap-go -func mmap(db *DB, sz int) error { - if !db.readOnly { - // Truncate the database to the size of the mmap. - if err := db.file.Truncate(int64(sz)); err != nil { - return fmt.Errorf("truncate: %s", err) - } - } - - // Open a file mapping handle. - sizelo := uint32(sz >> 32) - sizehi := uint32(sz) & 0xffffffff - h, errno := syscall.CreateFileMapping(syscall.Handle(db.file.Fd()), nil, syscall.PAGE_READONLY, sizelo, sizehi, nil) - if h == 0 { - return os.NewSyscallError("CreateFileMapping", errno) - } - - // Create the memory map. - addr, errno := syscall.MapViewOfFile(h, syscall.FILE_MAP_READ, 0, 0, uintptr(sz)) - if addr == 0 { - return os.NewSyscallError("MapViewOfFile", errno) - } - - // Close mapping handle. - if err := syscall.CloseHandle(syscall.Handle(h)); err != nil { - return os.NewSyscallError("CloseHandle", err) - } - - // Convert to a byte array. - db.data = ((*[maxMapSize]byte)(unsafe.Pointer(addr))) - db.datasz = sz - - return nil -} - -// munmap unmaps a pointer from a file. -// Based on: https://github.com/edsrzf/mmap-go -func munmap(db *DB) error { - if db.data == nil { - return nil - } - - addr := (uintptr)(unsafe.Pointer(&db.data[0])) - if err := syscall.UnmapViewOfFile(addr); err != nil { - return os.NewSyscallError("UnmapViewOfFile", err) - } - return nil -} diff --git a/vendor/github.com/boltdb/bolt/boltsync_unix.go b/vendor/github.com/boltdb/bolt/boltsync_unix.go deleted file mode 100644 index f504425..0000000 --- a/vendor/github.com/boltdb/bolt/boltsync_unix.go +++ /dev/null @@ -1,8 +0,0 @@ -// +build !windows,!plan9,!linux,!openbsd - -package bolt - -// fdatasync flushes written data to a file descriptor. -func fdatasync(db *DB) error { - return db.file.Sync() -} diff --git a/vendor/github.com/boltdb/bolt/bucket.go b/vendor/github.com/boltdb/bolt/bucket.go deleted file mode 100644 index 0c5bf27..0000000 --- a/vendor/github.com/boltdb/bolt/bucket.go +++ /dev/null @@ -1,777 +0,0 @@ -package bolt - -import ( - "bytes" - "fmt" - "unsafe" -) - -const ( - // MaxKeySize is the maximum length of a key, in bytes. - MaxKeySize = 32768 - - // MaxValueSize is the maximum length of a value, in bytes. - MaxValueSize = (1 << 31) - 2 -) - -const ( - maxUint = ^uint(0) - minUint = 0 - maxInt = int(^uint(0) >> 1) - minInt = -maxInt - 1 -) - -const bucketHeaderSize = int(unsafe.Sizeof(bucket{})) - -const ( - minFillPercent = 0.1 - maxFillPercent = 1.0 -) - -// DefaultFillPercent is the percentage that split pages are filled. -// This value can be changed by setting Bucket.FillPercent. -const DefaultFillPercent = 0.5 - -// Bucket represents a collection of key/value pairs inside the database. -type Bucket struct { - *bucket - tx *Tx // the associated transaction - buckets map[string]*Bucket // subbucket cache - page *page // inline page reference - rootNode *node // materialized node for the root page. - nodes map[pgid]*node // node cache - - // Sets the threshold for filling nodes when they split. By default, - // the bucket will fill to 50% but it can be useful to increase this - // amount if you know that your write workloads are mostly append-only. - // - // This is non-persisted across transactions so it must be set in every Tx. - FillPercent float64 -} - -// bucket represents the on-file representation of a bucket. -// This is stored as the "value" of a bucket key. If the bucket is small enough, -// then its root page can be stored inline in the "value", after the bucket -// header. In the case of inline buckets, the "root" will be 0. -type bucket struct { - root pgid // page id of the bucket's root-level page - sequence uint64 // monotonically incrementing, used by NextSequence() -} - -// newBucket returns a new bucket associated with a transaction. -func newBucket(tx *Tx) Bucket { - var b = Bucket{tx: tx, FillPercent: DefaultFillPercent} - if tx.writable { - b.buckets = make(map[string]*Bucket) - b.nodes = make(map[pgid]*node) - } - return b -} - -// Tx returns the tx of the bucket. -func (b *Bucket) Tx() *Tx { - return b.tx -} - -// Root returns the root of the bucket. -func (b *Bucket) Root() pgid { - return b.root -} - -// Writable returns whether the bucket is writable. -func (b *Bucket) Writable() bool { - return b.tx.writable -} - -// Cursor creates a cursor associated with the bucket. -// The cursor is only valid as long as the transaction is open. -// Do not use a cursor after the transaction is closed. -func (b *Bucket) Cursor() *Cursor { - // Update transaction statistics. - b.tx.stats.CursorCount++ - - // Allocate and return a cursor. - return &Cursor{ - bucket: b, - stack: make([]elemRef, 0), - } -} - -// Bucket retrieves a nested bucket by name. -// Returns nil if the bucket does not exist. -// The bucket instance is only valid for the lifetime of the transaction. -func (b *Bucket) Bucket(name []byte) *Bucket { - if b.buckets != nil { - if child := b.buckets[string(name)]; child != nil { - return child - } - } - - // Move cursor to key. - c := b.Cursor() - k, v, flags := c.seek(name) - - // Return nil if the key doesn't exist or it is not a bucket. - if !bytes.Equal(name, k) || (flags&bucketLeafFlag) == 0 { - return nil - } - - // Otherwise create a bucket and cache it. - var child = b.openBucket(v) - if b.buckets != nil { - b.buckets[string(name)] = child - } - - return child -} - -// Helper method that re-interprets a sub-bucket value -// from a parent into a Bucket -func (b *Bucket) openBucket(value []byte) *Bucket { - var child = newBucket(b.tx) - - // If unaligned load/stores are broken on this arch and value is - // unaligned simply clone to an aligned byte array. - unaligned := brokenUnaligned && uintptr(unsafe.Pointer(&value[0]))&3 != 0 - - if unaligned { - value = cloneBytes(value) - } - - // If this is a writable transaction then we need to copy the bucket entry. - // Read-only transactions can point directly at the mmap entry. - if b.tx.writable && !unaligned { - child.bucket = &bucket{} - *child.bucket = *(*bucket)(unsafe.Pointer(&value[0])) - } else { - child.bucket = (*bucket)(unsafe.Pointer(&value[0])) - } - - // Save a reference to the inline page if the bucket is inline. - if child.root == 0 { - child.page = (*page)(unsafe.Pointer(&value[bucketHeaderSize])) - } - - return &child -} - -// CreateBucket creates a new bucket at the given key and returns the new bucket. -// Returns an error if the key already exists, if the bucket name is blank, or if the bucket name is too long. -// The bucket instance is only valid for the lifetime of the transaction. -func (b *Bucket) CreateBucket(key []byte) (*Bucket, error) { - if b.tx.db == nil { - return nil, ErrTxClosed - } else if !b.tx.writable { - return nil, ErrTxNotWritable - } else if len(key) == 0 { - return nil, ErrBucketNameRequired - } - - // Move cursor to correct position. - c := b.Cursor() - k, _, flags := c.seek(key) - - // Return an error if there is an existing key. - if bytes.Equal(key, k) { - if (flags & bucketLeafFlag) != 0 { - return nil, ErrBucketExists - } - return nil, ErrIncompatibleValue - } - - // Create empty, inline bucket. - var bucket = Bucket{ - bucket: &bucket{}, - rootNode: &node{isLeaf: true}, - FillPercent: DefaultFillPercent, - } - var value = bucket.write() - - // Insert into node. - key = cloneBytes(key) - c.node().put(key, key, value, 0, bucketLeafFlag) - - // Since subbuckets are not allowed on inline buckets, we need to - // dereference the inline page, if it exists. This will cause the bucket - // to be treated as a regular, non-inline bucket for the rest of the tx. - b.page = nil - - return b.Bucket(key), nil -} - -// CreateBucketIfNotExists creates a new bucket if it doesn't already exist and returns a reference to it. -// Returns an error if the bucket name is blank, or if the bucket name is too long. -// The bucket instance is only valid for the lifetime of the transaction. -func (b *Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) { - child, err := b.CreateBucket(key) - if err == ErrBucketExists { - return b.Bucket(key), nil - } else if err != nil { - return nil, err - } - return child, nil -} - -// DeleteBucket deletes a bucket at the given key. -// Returns an error if the bucket does not exists, or if the key represents a non-bucket value. -func (b *Bucket) DeleteBucket(key []byte) error { - if b.tx.db == nil { - return ErrTxClosed - } else if !b.Writable() { - return ErrTxNotWritable - } - - // Move cursor to correct position. - c := b.Cursor() - k, _, flags := c.seek(key) - - // Return an error if bucket doesn't exist or is not a bucket. - if !bytes.Equal(key, k) { - return ErrBucketNotFound - } else if (flags & bucketLeafFlag) == 0 { - return ErrIncompatibleValue - } - - // Recursively delete all child buckets. - child := b.Bucket(key) - err := child.ForEach(func(k, v []byte) error { - if v == nil { - if err := child.DeleteBucket(k); err != nil { - return fmt.Errorf("delete bucket: %s", err) - } - } - return nil - }) - if err != nil { - return err - } - - // Remove cached copy. - delete(b.buckets, string(key)) - - // Release all bucket pages to freelist. - child.nodes = nil - child.rootNode = nil - child.free() - - // Delete the node if we have a matching key. - c.node().del(key) - - return nil -} - -// Get retrieves the value for a key in the bucket. -// Returns a nil value if the key does not exist or if the key is a nested bucket. -// The returned value is only valid for the life of the transaction. -func (b *Bucket) Get(key []byte) []byte { - k, v, flags := b.Cursor().seek(key) - - // Return nil if this is a bucket. - if (flags & bucketLeafFlag) != 0 { - return nil - } - - // If our target node isn't the same key as what's passed in then return nil. - if !bytes.Equal(key, k) { - return nil - } - return v -} - -// Put sets the value for a key in the bucket. -// If the key exist then its previous value will be overwritten. -// Supplied value must remain valid for the life of the transaction. -// Returns an error if the bucket was created from a read-only transaction, if the key is blank, if the key is too large, or if the value is too large. -func (b *Bucket) Put(key []byte, value []byte) error { - if b.tx.db == nil { - return ErrTxClosed - } else if !b.Writable() { - return ErrTxNotWritable - } else if len(key) == 0 { - return ErrKeyRequired - } else if len(key) > MaxKeySize { - return ErrKeyTooLarge - } else if int64(len(value)) > MaxValueSize { - return ErrValueTooLarge - } - - // Move cursor to correct position. - c := b.Cursor() - k, _, flags := c.seek(key) - - // Return an error if there is an existing key with a bucket value. - if bytes.Equal(key, k) && (flags&bucketLeafFlag) != 0 { - return ErrIncompatibleValue - } - - // Insert into node. - key = cloneBytes(key) - c.node().put(key, key, value, 0, 0) - - return nil -} - -// Delete removes a key from the bucket. -// If the key does not exist then nothing is done and a nil error is returned. -// Returns an error if the bucket was created from a read-only transaction. -func (b *Bucket) Delete(key []byte) error { - if b.tx.db == nil { - return ErrTxClosed - } else if !b.Writable() { - return ErrTxNotWritable - } - - // Move cursor to correct position. - c := b.Cursor() - _, _, flags := c.seek(key) - - // Return an error if there is already existing bucket value. - if (flags & bucketLeafFlag) != 0 { - return ErrIncompatibleValue - } - - // Delete the node if we have a matching key. - c.node().del(key) - - return nil -} - -// Sequence returns the current integer for the bucket without incrementing it. -func (b *Bucket) Sequence() uint64 { return b.bucket.sequence } - -// SetSequence updates the sequence number for the bucket. -func (b *Bucket) SetSequence(v uint64) error { - if b.tx.db == nil { - return ErrTxClosed - } else if !b.Writable() { - return ErrTxNotWritable - } - - // Materialize the root node if it hasn't been already so that the - // bucket will be saved during commit. - if b.rootNode == nil { - _ = b.node(b.root, nil) - } - - // Increment and return the sequence. - b.bucket.sequence = v - return nil -} - -// NextSequence returns an autoincrementing integer for the bucket. -func (b *Bucket) NextSequence() (uint64, error) { - if b.tx.db == nil { - return 0, ErrTxClosed - } else if !b.Writable() { - return 0, ErrTxNotWritable - } - - // Materialize the root node if it hasn't been already so that the - // bucket will be saved during commit. - if b.rootNode == nil { - _ = b.node(b.root, nil) - } - - // Increment and return the sequence. - b.bucket.sequence++ - return b.bucket.sequence, nil -} - -// ForEach executes a function for each key/value pair in a bucket. -// If the provided function returns an error then the iteration is stopped and -// the error is returned to the caller. The provided function must not modify -// the bucket; this will result in undefined behavior. -func (b *Bucket) ForEach(fn func(k, v []byte) error) error { - if b.tx.db == nil { - return ErrTxClosed - } - c := b.Cursor() - for k, v := c.First(); k != nil; k, v = c.Next() { - if err := fn(k, v); err != nil { - return err - } - } - return nil -} - -// Stat returns stats on a bucket. -func (b *Bucket) Stats() BucketStats { - var s, subStats BucketStats - pageSize := b.tx.db.pageSize - s.BucketN += 1 - if b.root == 0 { - s.InlineBucketN += 1 - } - b.forEachPage(func(p *page, depth int) { - if (p.flags & leafPageFlag) != 0 { - s.KeyN += int(p.count) - - // used totals the used bytes for the page - used := pageHeaderSize - - if p.count != 0 { - // If page has any elements, add all element headers. - used += leafPageElementSize * int(p.count-1) - - // Add all element key, value sizes. - // The computation takes advantage of the fact that the position - // of the last element's key/value equals to the total of the sizes - // of all previous elements' keys and values. - // It also includes the last element's header. - lastElement := p.leafPageElement(p.count - 1) - used += int(lastElement.pos + lastElement.ksize + lastElement.vsize) - } - - if b.root == 0 { - // For inlined bucket just update the inline stats - s.InlineBucketInuse += used - } else { - // For non-inlined bucket update all the leaf stats - s.LeafPageN++ - s.LeafInuse += used - s.LeafOverflowN += int(p.overflow) - - // Collect stats from sub-buckets. - // Do that by iterating over all element headers - // looking for the ones with the bucketLeafFlag. - for i := uint16(0); i < p.count; i++ { - e := p.leafPageElement(i) - if (e.flags & bucketLeafFlag) != 0 { - // For any bucket element, open the element value - // and recursively call Stats on the contained bucket. - subStats.Add(b.openBucket(e.value()).Stats()) - } - } - } - } else if (p.flags & branchPageFlag) != 0 { - s.BranchPageN++ - lastElement := p.branchPageElement(p.count - 1) - - // used totals the used bytes for the page - // Add header and all element headers. - used := pageHeaderSize + (branchPageElementSize * int(p.count-1)) - - // Add size of all keys and values. - // Again, use the fact that last element's position equals to - // the total of key, value sizes of all previous elements. - used += int(lastElement.pos + lastElement.ksize) - s.BranchInuse += used - s.BranchOverflowN += int(p.overflow) - } - - // Keep track of maximum page depth. - if depth+1 > s.Depth { - s.Depth = (depth + 1) - } - }) - - // Alloc stats can be computed from page counts and pageSize. - s.BranchAlloc = (s.BranchPageN + s.BranchOverflowN) * pageSize - s.LeafAlloc = (s.LeafPageN + s.LeafOverflowN) * pageSize - - // Add the max depth of sub-buckets to get total nested depth. - s.Depth += subStats.Depth - // Add the stats for all sub-buckets - s.Add(subStats) - return s -} - -// forEachPage iterates over every page in a bucket, including inline pages. -func (b *Bucket) forEachPage(fn func(*page, int)) { - // If we have an inline page then just use that. - if b.page != nil { - fn(b.page, 0) - return - } - - // Otherwise traverse the page hierarchy. - b.tx.forEachPage(b.root, 0, fn) -} - -// forEachPageNode iterates over every page (or node) in a bucket. -// This also includes inline pages. -func (b *Bucket) forEachPageNode(fn func(*page, *node, int)) { - // If we have an inline page or root node then just use that. - if b.page != nil { - fn(b.page, nil, 0) - return - } - b._forEachPageNode(b.root, 0, fn) -} - -func (b *Bucket) _forEachPageNode(pgid pgid, depth int, fn func(*page, *node, int)) { - var p, n = b.pageNode(pgid) - - // Execute function. - fn(p, n, depth) - - // Recursively loop over children. - if p != nil { - if (p.flags & branchPageFlag) != 0 { - for i := 0; i < int(p.count); i++ { - elem := p.branchPageElement(uint16(i)) - b._forEachPageNode(elem.pgid, depth+1, fn) - } - } - } else { - if !n.isLeaf { - for _, inode := range n.inodes { - b._forEachPageNode(inode.pgid, depth+1, fn) - } - } - } -} - -// spill writes all the nodes for this bucket to dirty pages. -func (b *Bucket) spill() error { - // Spill all child buckets first. - for name, child := range b.buckets { - // If the child bucket is small enough and it has no child buckets then - // write it inline into the parent bucket's page. Otherwise spill it - // like a normal bucket and make the parent value a pointer to the page. - var value []byte - if child.inlineable() { - child.free() - value = child.write() - } else { - if err := child.spill(); err != nil { - return err - } - - // Update the child bucket header in this bucket. - value = make([]byte, unsafe.Sizeof(bucket{})) - var bucket = (*bucket)(unsafe.Pointer(&value[0])) - *bucket = *child.bucket - } - - // Skip writing the bucket if there are no materialized nodes. - if child.rootNode == nil { - continue - } - - // Update parent node. - var c = b.Cursor() - k, _, flags := c.seek([]byte(name)) - if !bytes.Equal([]byte(name), k) { - panic(fmt.Sprintf("misplaced bucket header: %x -> %x", []byte(name), k)) - } - if flags&bucketLeafFlag == 0 { - panic(fmt.Sprintf("unexpected bucket header flag: %x", flags)) - } - c.node().put([]byte(name), []byte(name), value, 0, bucketLeafFlag) - } - - // Ignore if there's not a materialized root node. - if b.rootNode == nil { - return nil - } - - // Spill nodes. - if err := b.rootNode.spill(); err != nil { - return err - } - b.rootNode = b.rootNode.root() - - // Update the root node for this bucket. - if b.rootNode.pgid >= b.tx.meta.pgid { - panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", b.rootNode.pgid, b.tx.meta.pgid)) - } - b.root = b.rootNode.pgid - - return nil -} - -// inlineable returns true if a bucket is small enough to be written inline -// and if it contains no subbuckets. Otherwise returns false. -func (b *Bucket) inlineable() bool { - var n = b.rootNode - - // Bucket must only contain a single leaf node. - if n == nil || !n.isLeaf { - return false - } - - // Bucket is not inlineable if it contains subbuckets or if it goes beyond - // our threshold for inline bucket size. - var size = pageHeaderSize - for _, inode := range n.inodes { - size += leafPageElementSize + len(inode.key) + len(inode.value) - - if inode.flags&bucketLeafFlag != 0 { - return false - } else if size > b.maxInlineBucketSize() { - return false - } - } - - return true -} - -// Returns the maximum total size of a bucket to make it a candidate for inlining. -func (b *Bucket) maxInlineBucketSize() int { - return b.tx.db.pageSize / 4 -} - -// write allocates and writes a bucket to a byte slice. -func (b *Bucket) write() []byte { - // Allocate the appropriate size. - var n = b.rootNode - var value = make([]byte, bucketHeaderSize+n.size()) - - // Write a bucket header. - var bucket = (*bucket)(unsafe.Pointer(&value[0])) - *bucket = *b.bucket - - // Convert byte slice to a fake page and write the root node. - var p = (*page)(unsafe.Pointer(&value[bucketHeaderSize])) - n.write(p) - - return value -} - -// rebalance attempts to balance all nodes. -func (b *Bucket) rebalance() { - for _, n := range b.nodes { - n.rebalance() - } - for _, child := range b.buckets { - child.rebalance() - } -} - -// node creates a node from a page and associates it with a given parent. -func (b *Bucket) node(pgid pgid, parent *node) *node { - _assert(b.nodes != nil, "nodes map expected") - - // Retrieve node if it's already been created. - if n := b.nodes[pgid]; n != nil { - return n - } - - // Otherwise create a node and cache it. - n := &node{bucket: b, parent: parent} - if parent == nil { - b.rootNode = n - } else { - parent.children = append(parent.children, n) - } - - // Use the inline page if this is an inline bucket. - var p = b.page - if p == nil { - p = b.tx.page(pgid) - } - - // Read the page into the node and cache it. - n.read(p) - b.nodes[pgid] = n - - // Update statistics. - b.tx.stats.NodeCount++ - - return n -} - -// free recursively frees all pages in the bucket. -func (b *Bucket) free() { - if b.root == 0 { - return - } - - var tx = b.tx - b.forEachPageNode(func(p *page, n *node, _ int) { - if p != nil { - tx.db.freelist.free(tx.meta.txid, p) - } else { - n.free() - } - }) - b.root = 0 -} - -// dereference removes all references to the old mmap. -func (b *Bucket) dereference() { - if b.rootNode != nil { - b.rootNode.root().dereference() - } - - for _, child := range b.buckets { - child.dereference() - } -} - -// pageNode returns the in-memory node, if it exists. -// Otherwise returns the underlying page. -func (b *Bucket) pageNode(id pgid) (*page, *node) { - // Inline buckets have a fake page embedded in their value so treat them - // differently. We'll return the rootNode (if available) or the fake page. - if b.root == 0 { - if id != 0 { - panic(fmt.Sprintf("inline bucket non-zero page access(2): %d != 0", id)) - } - if b.rootNode != nil { - return nil, b.rootNode - } - return b.page, nil - } - - // Check the node cache for non-inline buckets. - if b.nodes != nil { - if n := b.nodes[id]; n != nil { - return nil, n - } - } - - // Finally lookup the page from the transaction if no node is materialized. - return b.tx.page(id), nil -} - -// BucketStats records statistics about resources used by a bucket. -type BucketStats struct { - // Page count statistics. - BranchPageN int // number of logical branch pages - BranchOverflowN int // number of physical branch overflow pages - LeafPageN int // number of logical leaf pages - LeafOverflowN int // number of physical leaf overflow pages - - // Tree statistics. - KeyN int // number of keys/value pairs - Depth int // number of levels in B+tree - - // Page size utilization. - BranchAlloc int // bytes allocated for physical branch pages - BranchInuse int // bytes actually used for branch data - LeafAlloc int // bytes allocated for physical leaf pages - LeafInuse int // bytes actually used for leaf data - - // Bucket statistics - BucketN int // total number of buckets including the top bucket - InlineBucketN int // total number on inlined buckets - InlineBucketInuse int // bytes used for inlined buckets (also accounted for in LeafInuse) -} - -func (s *BucketStats) Add(other BucketStats) { - s.BranchPageN += other.BranchPageN - s.BranchOverflowN += other.BranchOverflowN - s.LeafPageN += other.LeafPageN - s.LeafOverflowN += other.LeafOverflowN - s.KeyN += other.KeyN - if s.Depth < other.Depth { - s.Depth = other.Depth - } - s.BranchAlloc += other.BranchAlloc - s.BranchInuse += other.BranchInuse - s.LeafAlloc += other.LeafAlloc - s.LeafInuse += other.LeafInuse - - s.BucketN += other.BucketN - s.InlineBucketN += other.InlineBucketN - s.InlineBucketInuse += other.InlineBucketInuse -} - -// cloneBytes returns a copy of a given slice. -func cloneBytes(v []byte) []byte { - var clone = make([]byte, len(v)) - copy(clone, v) - return clone -} diff --git a/vendor/github.com/boltdb/bolt/cursor.go b/vendor/github.com/boltdb/bolt/cursor.go deleted file mode 100644 index 1be9f35..0000000 --- a/vendor/github.com/boltdb/bolt/cursor.go +++ /dev/null @@ -1,400 +0,0 @@ -package bolt - -import ( - "bytes" - "fmt" - "sort" -) - -// Cursor represents an iterator that can traverse over all key/value pairs in a bucket in sorted order. -// Cursors see nested buckets with value == nil. -// Cursors can be obtained from a transaction and are valid as long as the transaction is open. -// -// Keys and values returned from the cursor are only valid for the life of the transaction. -// -// Changing data while traversing with a cursor may cause it to be invalidated -// and return unexpected keys and/or values. You must reposition your cursor -// after mutating data. -type Cursor struct { - bucket *Bucket - stack []elemRef -} - -// Bucket returns the bucket that this cursor was created from. -func (c *Cursor) Bucket() *Bucket { - return c.bucket -} - -// First moves the cursor to the first item in the bucket and returns its key and value. -// If the bucket is empty then a nil key and value are returned. -// The returned key and value are only valid for the life of the transaction. -func (c *Cursor) First() (key []byte, value []byte) { - _assert(c.bucket.tx.db != nil, "tx closed") - c.stack = c.stack[:0] - p, n := c.bucket.pageNode(c.bucket.root) - c.stack = append(c.stack, elemRef{page: p, node: n, index: 0}) - c.first() - - // If we land on an empty page then move to the next value. - // https://github.com/boltdb/bolt/issues/450 - if c.stack[len(c.stack)-1].count() == 0 { - c.next() - } - - k, v, flags := c.keyValue() - if (flags & uint32(bucketLeafFlag)) != 0 { - return k, nil - } - return k, v - -} - -// Last moves the cursor to the last item in the bucket and returns its key and value. -// If the bucket is empty then a nil key and value are returned. -// The returned key and value are only valid for the life of the transaction. -func (c *Cursor) Last() (key []byte, value []byte) { - _assert(c.bucket.tx.db != nil, "tx closed") - c.stack = c.stack[:0] - p, n := c.bucket.pageNode(c.bucket.root) - ref := elemRef{page: p, node: n} - ref.index = ref.count() - 1 - c.stack = append(c.stack, ref) - c.last() - k, v, flags := c.keyValue() - if (flags & uint32(bucketLeafFlag)) != 0 { - return k, nil - } - return k, v -} - -// Next moves the cursor to the next item in the bucket and returns its key and value. -// If the cursor is at the end of the bucket then a nil key and value are returned. -// The returned key and value are only valid for the life of the transaction. -func (c *Cursor) Next() (key []byte, value []byte) { - _assert(c.bucket.tx.db != nil, "tx closed") - k, v, flags := c.next() - if (flags & uint32(bucketLeafFlag)) != 0 { - return k, nil - } - return k, v -} - -// Prev moves the cursor to the previous item in the bucket and returns its key and value. -// If the cursor is at the beginning of the bucket then a nil key and value are returned. -// The returned key and value are only valid for the life of the transaction. -func (c *Cursor) Prev() (key []byte, value []byte) { - _assert(c.bucket.tx.db != nil, "tx closed") - - // Attempt to move back one element until we're successful. - // Move up the stack as we hit the beginning of each page in our stack. - for i := len(c.stack) - 1; i >= 0; i-- { - elem := &c.stack[i] - if elem.index > 0 { - elem.index-- - break - } - c.stack = c.stack[:i] - } - - // If we've hit the end then return nil. - if len(c.stack) == 0 { - return nil, nil - } - - // Move down the stack to find the last element of the last leaf under this branch. - c.last() - k, v, flags := c.keyValue() - if (flags & uint32(bucketLeafFlag)) != 0 { - return k, nil - } - return k, v -} - -// Seek moves the cursor to a given key and returns it. -// If the key does not exist then the next key is used. If no keys -// follow, a nil key is returned. -// The returned key and value are only valid for the life of the transaction. -func (c *Cursor) Seek(seek []byte) (key []byte, value []byte) { - k, v, flags := c.seek(seek) - - // If we ended up after the last element of a page then move to the next one. - if ref := &c.stack[len(c.stack)-1]; ref.index >= ref.count() { - k, v, flags = c.next() - } - - if k == nil { - return nil, nil - } else if (flags & uint32(bucketLeafFlag)) != 0 { - return k, nil - } - return k, v -} - -// Delete removes the current key/value under the cursor from the bucket. -// Delete fails if current key/value is a bucket or if the transaction is not writable. -func (c *Cursor) Delete() error { - if c.bucket.tx.db == nil { - return ErrTxClosed - } else if !c.bucket.Writable() { - return ErrTxNotWritable - } - - key, _, flags := c.keyValue() - // Return an error if current value is a bucket. - if (flags & bucketLeafFlag) != 0 { - return ErrIncompatibleValue - } - c.node().del(key) - - return nil -} - -// seek moves the cursor to a given key and returns it. -// If the key does not exist then the next key is used. -func (c *Cursor) seek(seek []byte) (key []byte, value []byte, flags uint32) { - _assert(c.bucket.tx.db != nil, "tx closed") - - // Start from root page/node and traverse to correct page. - c.stack = c.stack[:0] - c.search(seek, c.bucket.root) - ref := &c.stack[len(c.stack)-1] - - // If the cursor is pointing to the end of page/node then return nil. - if ref.index >= ref.count() { - return nil, nil, 0 - } - - // If this is a bucket then return a nil value. - return c.keyValue() -} - -// first moves the cursor to the first leaf element under the last page in the stack. -func (c *Cursor) first() { - for { - // Exit when we hit a leaf page. - var ref = &c.stack[len(c.stack)-1] - if ref.isLeaf() { - break - } - - // Keep adding pages pointing to the first element to the stack. - var pgid pgid - if ref.node != nil { - pgid = ref.node.inodes[ref.index].pgid - } else { - pgid = ref.page.branchPageElement(uint16(ref.index)).pgid - } - p, n := c.bucket.pageNode(pgid) - c.stack = append(c.stack, elemRef{page: p, node: n, index: 0}) - } -} - -// last moves the cursor to the last leaf element under the last page in the stack. -func (c *Cursor) last() { - for { - // Exit when we hit a leaf page. - ref := &c.stack[len(c.stack)-1] - if ref.isLeaf() { - break - } - - // Keep adding pages pointing to the last element in the stack. - var pgid pgid - if ref.node != nil { - pgid = ref.node.inodes[ref.index].pgid - } else { - pgid = ref.page.branchPageElement(uint16(ref.index)).pgid - } - p, n := c.bucket.pageNode(pgid) - - var nextRef = elemRef{page: p, node: n} - nextRef.index = nextRef.count() - 1 - c.stack = append(c.stack, nextRef) - } -} - -// next moves to the next leaf element and returns the key and value. -// If the cursor is at the last leaf element then it stays there and returns nil. -func (c *Cursor) next() (key []byte, value []byte, flags uint32) { - for { - // Attempt to move over one element until we're successful. - // Move up the stack as we hit the end of each page in our stack. - var i int - for i = len(c.stack) - 1; i >= 0; i-- { - elem := &c.stack[i] - if elem.index < elem.count()-1 { - elem.index++ - break - } - } - - // If we've hit the root page then stop and return. This will leave the - // cursor on the last element of the last page. - if i == -1 { - return nil, nil, 0 - } - - // Otherwise start from where we left off in the stack and find the - // first element of the first leaf page. - c.stack = c.stack[:i+1] - c.first() - - // If this is an empty page then restart and move back up the stack. - // https://github.com/boltdb/bolt/issues/450 - if c.stack[len(c.stack)-1].count() == 0 { - continue - } - - return c.keyValue() - } -} - -// search recursively performs a binary search against a given page/node until it finds a given key. -func (c *Cursor) search(key []byte, pgid pgid) { - p, n := c.bucket.pageNode(pgid) - if p != nil && (p.flags&(branchPageFlag|leafPageFlag)) == 0 { - panic(fmt.Sprintf("invalid page type: %d: %x", p.id, p.flags)) - } - e := elemRef{page: p, node: n} - c.stack = append(c.stack, e) - - // If we're on a leaf page/node then find the specific node. - if e.isLeaf() { - c.nsearch(key) - return - } - - if n != nil { - c.searchNode(key, n) - return - } - c.searchPage(key, p) -} - -func (c *Cursor) searchNode(key []byte, n *node) { - var exact bool - index := sort.Search(len(n.inodes), func(i int) bool { - // TODO(benbjohnson): Optimize this range search. It's a bit hacky right now. - // sort.Search() finds the lowest index where f() != -1 but we need the highest index. - ret := bytes.Compare(n.inodes[i].key, key) - if ret == 0 { - exact = true - } - return ret != -1 - }) - if !exact && index > 0 { - index-- - } - c.stack[len(c.stack)-1].index = index - - // Recursively search to the next page. - c.search(key, n.inodes[index].pgid) -} - -func (c *Cursor) searchPage(key []byte, p *page) { - // Binary search for the correct range. - inodes := p.branchPageElements() - - var exact bool - index := sort.Search(int(p.count), func(i int) bool { - // TODO(benbjohnson): Optimize this range search. It's a bit hacky right now. - // sort.Search() finds the lowest index where f() != -1 but we need the highest index. - ret := bytes.Compare(inodes[i].key(), key) - if ret == 0 { - exact = true - } - return ret != -1 - }) - if !exact && index > 0 { - index-- - } - c.stack[len(c.stack)-1].index = index - - // Recursively search to the next page. - c.search(key, inodes[index].pgid) -} - -// nsearch searches the leaf node on the top of the stack for a key. -func (c *Cursor) nsearch(key []byte) { - e := &c.stack[len(c.stack)-1] - p, n := e.page, e.node - - // If we have a node then search its inodes. - if n != nil { - index := sort.Search(len(n.inodes), func(i int) bool { - return bytes.Compare(n.inodes[i].key, key) != -1 - }) - e.index = index - return - } - - // If we have a page then search its leaf elements. - inodes := p.leafPageElements() - index := sort.Search(int(p.count), func(i int) bool { - return bytes.Compare(inodes[i].key(), key) != -1 - }) - e.index = index -} - -// keyValue returns the key and value of the current leaf element. -func (c *Cursor) keyValue() ([]byte, []byte, uint32) { - ref := &c.stack[len(c.stack)-1] - if ref.count() == 0 || ref.index >= ref.count() { - return nil, nil, 0 - } - - // Retrieve value from node. - if ref.node != nil { - inode := &ref.node.inodes[ref.index] - return inode.key, inode.value, inode.flags - } - - // Or retrieve value from page. - elem := ref.page.leafPageElement(uint16(ref.index)) - return elem.key(), elem.value(), elem.flags -} - -// node returns the node that the cursor is currently positioned on. -func (c *Cursor) node() *node { - _assert(len(c.stack) > 0, "accessing a node with a zero-length cursor stack") - - // If the top of the stack is a leaf node then just return it. - if ref := &c.stack[len(c.stack)-1]; ref.node != nil && ref.isLeaf() { - return ref.node - } - - // Start from root and traverse down the hierarchy. - var n = c.stack[0].node - if n == nil { - n = c.bucket.node(c.stack[0].page.id, nil) - } - for _, ref := range c.stack[:len(c.stack)-1] { - _assert(!n.isLeaf, "expected branch node") - n = n.childAt(int(ref.index)) - } - _assert(n.isLeaf, "expected leaf node") - return n -} - -// elemRef represents a reference to an element on a given page/node. -type elemRef struct { - page *page - node *node - index int -} - -// isLeaf returns whether the ref is pointing at a leaf page/node. -func (r *elemRef) isLeaf() bool { - if r.node != nil { - return r.node.isLeaf - } - return (r.page.flags & leafPageFlag) != 0 -} - -// count returns the number of inodes or page elements. -func (r *elemRef) count() int { - if r.node != nil { - return len(r.node.inodes) - } - return int(r.page.count) -} diff --git a/vendor/github.com/boltdb/bolt/db.go b/vendor/github.com/boltdb/bolt/db.go deleted file mode 100644 index f352ff1..0000000 --- a/vendor/github.com/boltdb/bolt/db.go +++ /dev/null @@ -1,1039 +0,0 @@ -package bolt - -import ( - "errors" - "fmt" - "hash/fnv" - "log" - "os" - "runtime" - "runtime/debug" - "strings" - "sync" - "time" - "unsafe" -) - -// The largest step that can be taken when remapping the mmap. -const maxMmapStep = 1 << 30 // 1GB - -// The data file format version. -const version = 2 - -// Represents a marker value to indicate that a file is a Bolt DB. -const magic uint32 = 0xED0CDAED - -// IgnoreNoSync specifies whether the NoSync field of a DB is ignored when -// syncing changes to a file. This is required as some operating systems, -// such as OpenBSD, do not have a unified buffer cache (UBC) and writes -// must be synchronized using the msync(2) syscall. -const IgnoreNoSync = runtime.GOOS == "openbsd" - -// Default values if not set in a DB instance. -const ( - DefaultMaxBatchSize int = 1000 - DefaultMaxBatchDelay = 10 * time.Millisecond - DefaultAllocSize = 16 * 1024 * 1024 -) - -// default page size for db is set to the OS page size. -var defaultPageSize = os.Getpagesize() - -// DB represents a collection of buckets persisted to a file on disk. -// All data access is performed through transactions which can be obtained through the DB. -// All the functions on DB will return a ErrDatabaseNotOpen if accessed before Open() is called. -type DB struct { - // When enabled, the database will perform a Check() after every commit. - // A panic is issued if the database is in an inconsistent state. This - // flag has a large performance impact so it should only be used for - // debugging purposes. - StrictMode bool - - // Setting the NoSync flag will cause the database to skip fsync() - // calls after each commit. This can be useful when bulk loading data - // into a database and you can restart the bulk load in the event of - // a system failure or database corruption. Do not set this flag for - // normal use. - // - // If the package global IgnoreNoSync constant is true, this value is - // ignored. See the comment on that constant for more details. - // - // THIS IS UNSAFE. PLEASE USE WITH CAUTION. - NoSync bool - - // When true, skips the truncate call when growing the database. - // Setting this to true is only safe on non-ext3/ext4 systems. - // Skipping truncation avoids preallocation of hard drive space and - // bypasses a truncate() and fsync() syscall on remapping. - // - // https://github.com/boltdb/bolt/issues/284 - NoGrowSync bool - - // If you want to read the entire database fast, you can set MmapFlag to - // syscall.MAP_POPULATE on Linux 2.6.23+ for sequential read-ahead. - MmapFlags int - - // MaxBatchSize is the maximum size of a batch. Default value is - // copied from DefaultMaxBatchSize in Open. - // - // If <=0, disables batching. - // - // Do not change concurrently with calls to Batch. - MaxBatchSize int - - // MaxBatchDelay is the maximum delay before a batch starts. - // Default value is copied from DefaultMaxBatchDelay in Open. - // - // If <=0, effectively disables batching. - // - // Do not change concurrently with calls to Batch. - MaxBatchDelay time.Duration - - // AllocSize is the amount of space allocated when the database - // needs to create new pages. This is done to amortize the cost - // of truncate() and fsync() when growing the data file. - AllocSize int - - path string - file *os.File - lockfile *os.File // windows only - dataref []byte // mmap'ed readonly, write throws SEGV - data *[maxMapSize]byte - datasz int - filesz int // current on disk file size - meta0 *meta - meta1 *meta - pageSize int - opened bool - rwtx *Tx - txs []*Tx - freelist *freelist - stats Stats - - pagePool sync.Pool - - batchMu sync.Mutex - batch *batch - - rwlock sync.Mutex // Allows only one writer at a time. - metalock sync.Mutex // Protects meta page access. - mmaplock sync.RWMutex // Protects mmap access during remapping. - statlock sync.RWMutex // Protects stats access. - - ops struct { - writeAt func(b []byte, off int64) (n int, err error) - } - - // Read only mode. - // When true, Update() and Begin(true) return ErrDatabaseReadOnly immediately. - readOnly bool -} - -// Path returns the path to currently open database file. -func (db *DB) Path() string { - return db.path -} - -// GoString returns the Go string representation of the database. -func (db *DB) GoString() string { - return fmt.Sprintf("bolt.DB{path:%q}", db.path) -} - -// String returns the string representation of the database. -func (db *DB) String() string { - return fmt.Sprintf("DB<%q>", db.path) -} - -// Open creates and opens a database at the given path. -// If the file does not exist then it will be created automatically. -// Passing in nil options will cause Bolt to open the database with the default options. -func Open(path string, mode os.FileMode, options *Options) (*DB, error) { - var db = &DB{opened: true} - - // Set default options if no options are provided. - if options == nil { - options = DefaultOptions - } - db.NoGrowSync = options.NoGrowSync - db.MmapFlags = options.MmapFlags - - // Set default values for later DB operations. - db.MaxBatchSize = DefaultMaxBatchSize - db.MaxBatchDelay = DefaultMaxBatchDelay - db.AllocSize = DefaultAllocSize - - flag := os.O_RDWR - if options.ReadOnly { - flag = os.O_RDONLY - db.readOnly = true - } - - // Open data file and separate sync handler for metadata writes. - db.path = path - var err error - if db.file, err = os.OpenFile(db.path, flag|os.O_CREATE, mode); err != nil { - _ = db.close() - return nil, err - } - - // Lock file so that other processes using Bolt in read-write mode cannot - // use the database at the same time. This would cause corruption since - // the two processes would write meta pages and free pages separately. - // The database file is locked exclusively (only one process can grab the lock) - // if !options.ReadOnly. - // The database file is locked using the shared lock (more than one process may - // hold a lock at the same time) otherwise (options.ReadOnly is set). - if err := flock(db, mode, !db.readOnly, options.Timeout); err != nil { - _ = db.close() - return nil, err - } - - // Default values for test hooks - db.ops.writeAt = db.file.WriteAt - - // Initialize the database if it doesn't exist. - if info, err := db.file.Stat(); err != nil { - return nil, err - } else if info.Size() == 0 { - // Initialize new files with meta pages. - if err := db.init(); err != nil { - return nil, err - } - } else { - // Read the first meta page to determine the page size. - var buf [0x1000]byte - if _, err := db.file.ReadAt(buf[:], 0); err == nil { - m := db.pageInBuffer(buf[:], 0).meta() - if err := m.validate(); err != nil { - // If we can't read the page size, we can assume it's the same - // as the OS -- since that's how the page size was chosen in the - // first place. - // - // If the first page is invalid and this OS uses a different - // page size than what the database was created with then we - // are out of luck and cannot access the database. - db.pageSize = os.Getpagesize() - } else { - db.pageSize = int(m.pageSize) - } - } - } - - // Initialize page pool. - db.pagePool = sync.Pool{ - New: func() interface{} { - return make([]byte, db.pageSize) - }, - } - - // Memory map the data file. - if err := db.mmap(options.InitialMmapSize); err != nil { - _ = db.close() - return nil, err - } - - // Read in the freelist. - db.freelist = newFreelist() - db.freelist.read(db.page(db.meta().freelist)) - - // Mark the database as opened and return. - return db, nil -} - -// mmap opens the underlying memory-mapped file and initializes the meta references. -// minsz is the minimum size that the new mmap can be. -func (db *DB) mmap(minsz int) error { - db.mmaplock.Lock() - defer db.mmaplock.Unlock() - - info, err := db.file.Stat() - if err != nil { - return fmt.Errorf("mmap stat error: %s", err) - } else if int(info.Size()) < db.pageSize*2 { - return fmt.Errorf("file size too small") - } - - // Ensure the size is at least the minimum size. - var size = int(info.Size()) - if size < minsz { - size = minsz - } - size, err = db.mmapSize(size) - if err != nil { - return err - } - - // Dereference all mmap references before unmapping. - if db.rwtx != nil { - db.rwtx.root.dereference() - } - - // Unmap existing data before continuing. - if err := db.munmap(); err != nil { - return err - } - - // Memory-map the data file as a byte slice. - if err := mmap(db, size); err != nil { - return err - } - - // Save references to the meta pages. - db.meta0 = db.page(0).meta() - db.meta1 = db.page(1).meta() - - // Validate the meta pages. We only return an error if both meta pages fail - // validation, since meta0 failing validation means that it wasn't saved - // properly -- but we can recover using meta1. And vice-versa. - err0 := db.meta0.validate() - err1 := db.meta1.validate() - if err0 != nil && err1 != nil { - return err0 - } - - return nil -} - -// munmap unmaps the data file from memory. -func (db *DB) munmap() error { - if err := munmap(db); err != nil { - return fmt.Errorf("unmap error: " + err.Error()) - } - return nil -} - -// mmapSize determines the appropriate size for the mmap given the current size -// of the database. The minimum size is 32KB and doubles until it reaches 1GB. -// Returns an error if the new mmap size is greater than the max allowed. -func (db *DB) mmapSize(size int) (int, error) { - // Double the size from 32KB until 1GB. - for i := uint(15); i <= 30; i++ { - if size <= 1< maxMapSize { - return 0, fmt.Errorf("mmap too large") - } - - // If larger than 1GB then grow by 1GB at a time. - sz := int64(size) - if remainder := sz % int64(maxMmapStep); remainder > 0 { - sz += int64(maxMmapStep) - remainder - } - - // Ensure that the mmap size is a multiple of the page size. - // This should always be true since we're incrementing in MBs. - pageSize := int64(db.pageSize) - if (sz % pageSize) != 0 { - sz = ((sz / pageSize) + 1) * pageSize - } - - // If we've exceeded the max size then only grow up to the max size. - if sz > maxMapSize { - sz = maxMapSize - } - - return int(sz), nil -} - -// init creates a new database file and initializes its meta pages. -func (db *DB) init() error { - // Set the page size to the OS page size. - db.pageSize = os.Getpagesize() - - // Create two meta pages on a buffer. - buf := make([]byte, db.pageSize*4) - for i := 0; i < 2; i++ { - p := db.pageInBuffer(buf[:], pgid(i)) - p.id = pgid(i) - p.flags = metaPageFlag - - // Initialize the meta page. - m := p.meta() - m.magic = magic - m.version = version - m.pageSize = uint32(db.pageSize) - m.freelist = 2 - m.root = bucket{root: 3} - m.pgid = 4 - m.txid = txid(i) - m.checksum = m.sum64() - } - - // Write an empty freelist at page 3. - p := db.pageInBuffer(buf[:], pgid(2)) - p.id = pgid(2) - p.flags = freelistPageFlag - p.count = 0 - - // Write an empty leaf page at page 4. - p = db.pageInBuffer(buf[:], pgid(3)) - p.id = pgid(3) - p.flags = leafPageFlag - p.count = 0 - - // Write the buffer to our data file. - if _, err := db.ops.writeAt(buf, 0); err != nil { - return err - } - if err := fdatasync(db); err != nil { - return err - } - - return nil -} - -// Close releases all database resources. -// All transactions must be closed before closing the database. -func (db *DB) Close() error { - db.rwlock.Lock() - defer db.rwlock.Unlock() - - db.metalock.Lock() - defer db.metalock.Unlock() - - db.mmaplock.RLock() - defer db.mmaplock.RUnlock() - - return db.close() -} - -func (db *DB) close() error { - if !db.opened { - return nil - } - - db.opened = false - - db.freelist = nil - - // Clear ops. - db.ops.writeAt = nil - - // Close the mmap. - if err := db.munmap(); err != nil { - return err - } - - // Close file handles. - if db.file != nil { - // No need to unlock read-only file. - if !db.readOnly { - // Unlock the file. - if err := funlock(db); err != nil { - log.Printf("bolt.Close(): funlock error: %s", err) - } - } - - // Close the file descriptor. - if err := db.file.Close(); err != nil { - return fmt.Errorf("db file close: %s", err) - } - db.file = nil - } - - db.path = "" - return nil -} - -// Begin starts a new transaction. -// Multiple read-only transactions can be used concurrently but only one -// write transaction can be used at a time. Starting multiple write transactions -// will cause the calls to block and be serialized until the current write -// transaction finishes. -// -// Transactions should not be dependent on one another. Opening a read -// transaction and a write transaction in the same goroutine can cause the -// writer to deadlock because the database periodically needs to re-mmap itself -// as it grows and it cannot do that while a read transaction is open. -// -// If a long running read transaction (for example, a snapshot transaction) is -// needed, you might want to set DB.InitialMmapSize to a large enough value -// to avoid potential blocking of write transaction. -// -// IMPORTANT: You must close read-only transactions after you are finished or -// else the database will not reclaim old pages. -func (db *DB) Begin(writable bool) (*Tx, error) { - if writable { - return db.beginRWTx() - } - return db.beginTx() -} - -func (db *DB) beginTx() (*Tx, error) { - // Lock the meta pages while we initialize the transaction. We obtain - // the meta lock before the mmap lock because that's the order that the - // write transaction will obtain them. - db.metalock.Lock() - - // Obtain a read-only lock on the mmap. When the mmap is remapped it will - // obtain a write lock so all transactions must finish before it can be - // remapped. - db.mmaplock.RLock() - - // Exit if the database is not open yet. - if !db.opened { - db.mmaplock.RUnlock() - db.metalock.Unlock() - return nil, ErrDatabaseNotOpen - } - - // Create a transaction associated with the database. - t := &Tx{} - t.init(db) - - // Keep track of transaction until it closes. - db.txs = append(db.txs, t) - n := len(db.txs) - - // Unlock the meta pages. - db.metalock.Unlock() - - // Update the transaction stats. - db.statlock.Lock() - db.stats.TxN++ - db.stats.OpenTxN = n - db.statlock.Unlock() - - return t, nil -} - -func (db *DB) beginRWTx() (*Tx, error) { - // If the database was opened with Options.ReadOnly, return an error. - if db.readOnly { - return nil, ErrDatabaseReadOnly - } - - // Obtain writer lock. This is released by the transaction when it closes. - // This enforces only one writer transaction at a time. - db.rwlock.Lock() - - // Once we have the writer lock then we can lock the meta pages so that - // we can set up the transaction. - db.metalock.Lock() - defer db.metalock.Unlock() - - // Exit if the database is not open yet. - if !db.opened { - db.rwlock.Unlock() - return nil, ErrDatabaseNotOpen - } - - // Create a transaction associated with the database. - t := &Tx{writable: true} - t.init(db) - db.rwtx = t - - // Free any pages associated with closed read-only transactions. - var minid txid = 0xFFFFFFFFFFFFFFFF - for _, t := range db.txs { - if t.meta.txid < minid { - minid = t.meta.txid - } - } - if minid > 0 { - db.freelist.release(minid - 1) - } - - return t, nil -} - -// removeTx removes a transaction from the database. -func (db *DB) removeTx(tx *Tx) { - // Release the read lock on the mmap. - db.mmaplock.RUnlock() - - // Use the meta lock to restrict access to the DB object. - db.metalock.Lock() - - // Remove the transaction. - for i, t := range db.txs { - if t == tx { - last := len(db.txs) - 1 - db.txs[i] = db.txs[last] - db.txs[last] = nil - db.txs = db.txs[:last] - break - } - } - n := len(db.txs) - - // Unlock the meta pages. - db.metalock.Unlock() - - // Merge statistics. - db.statlock.Lock() - db.stats.OpenTxN = n - db.stats.TxStats.add(&tx.stats) - db.statlock.Unlock() -} - -// Update executes a function within the context of a read-write managed transaction. -// If no error is returned from the function then the transaction is committed. -// If an error is returned then the entire transaction is rolled back. -// Any error that is returned from the function or returned from the commit is -// returned from the Update() method. -// -// Attempting to manually commit or rollback within the function will cause a panic. -func (db *DB) Update(fn func(*Tx) error) error { - t, err := db.Begin(true) - if err != nil { - return err - } - - // Make sure the transaction rolls back in the event of a panic. - defer func() { - if t.db != nil { - t.rollback() - } - }() - - // Mark as a managed tx so that the inner function cannot manually commit. - t.managed = true - - // If an error is returned from the function then rollback and return error. - err = fn(t) - t.managed = false - if err != nil { - _ = t.Rollback() - return err - } - - return t.Commit() -} - -// View executes a function within the context of a managed read-only transaction. -// Any error that is returned from the function is returned from the View() method. -// -// Attempting to manually rollback within the function will cause a panic. -func (db *DB) View(fn func(*Tx) error) error { - t, err := db.Begin(false) - if err != nil { - return err - } - - // Make sure the transaction rolls back in the event of a panic. - defer func() { - if t.db != nil { - t.rollback() - } - }() - - // Mark as a managed tx so that the inner function cannot manually rollback. - t.managed = true - - // If an error is returned from the function then pass it through. - err = fn(t) - t.managed = false - if err != nil { - _ = t.Rollback() - return err - } - - if err := t.Rollback(); err != nil { - return err - } - - return nil -} - -// Batch calls fn as part of a batch. It behaves similar to Update, -// except: -// -// 1. concurrent Batch calls can be combined into a single Bolt -// transaction. -// -// 2. the function passed to Batch may be called multiple times, -// regardless of whether it returns error or not. -// -// This means that Batch function side effects must be idempotent and -// take permanent effect only after a successful return is seen in -// caller. -// -// The maximum batch size and delay can be adjusted with DB.MaxBatchSize -// and DB.MaxBatchDelay, respectively. -// -// Batch is only useful when there are multiple goroutines calling it. -func (db *DB) Batch(fn func(*Tx) error) error { - errCh := make(chan error, 1) - - db.batchMu.Lock() - if (db.batch == nil) || (db.batch != nil && len(db.batch.calls) >= db.MaxBatchSize) { - // There is no existing batch, or the existing batch is full; start a new one. - db.batch = &batch{ - db: db, - } - db.batch.timer = time.AfterFunc(db.MaxBatchDelay, db.batch.trigger) - } - db.batch.calls = append(db.batch.calls, call{fn: fn, err: errCh}) - if len(db.batch.calls) >= db.MaxBatchSize { - // wake up batch, it's ready to run - go db.batch.trigger() - } - db.batchMu.Unlock() - - err := <-errCh - if err == trySolo { - err = db.Update(fn) - } - return err -} - -type call struct { - fn func(*Tx) error - err chan<- error -} - -type batch struct { - db *DB - timer *time.Timer - start sync.Once - calls []call -} - -// trigger runs the batch if it hasn't already been run. -func (b *batch) trigger() { - b.start.Do(b.run) -} - -// run performs the transactions in the batch and communicates results -// back to DB.Batch. -func (b *batch) run() { - b.db.batchMu.Lock() - b.timer.Stop() - // Make sure no new work is added to this batch, but don't break - // other batches. - if b.db.batch == b { - b.db.batch = nil - } - b.db.batchMu.Unlock() - -retry: - for len(b.calls) > 0 { - var failIdx = -1 - err := b.db.Update(func(tx *Tx) error { - for i, c := range b.calls { - if err := safelyCall(c.fn, tx); err != nil { - failIdx = i - return err - } - } - return nil - }) - - if failIdx >= 0 { - // take the failing transaction out of the batch. it's - // safe to shorten b.calls here because db.batch no longer - // points to us, and we hold the mutex anyway. - c := b.calls[failIdx] - b.calls[failIdx], b.calls = b.calls[len(b.calls)-1], b.calls[:len(b.calls)-1] - // tell the submitter re-run it solo, continue with the rest of the batch - c.err <- trySolo - continue retry - } - - // pass success, or bolt internal errors, to all callers - for _, c := range b.calls { - if c.err != nil { - c.err <- err - } - } - break retry - } -} - -// trySolo is a special sentinel error value used for signaling that a -// transaction function should be re-run. It should never be seen by -// callers. -var trySolo = errors.New("batch function returned an error and should be re-run solo") - -type panicked struct { - reason interface{} -} - -func (p panicked) Error() string { - if err, ok := p.reason.(error); ok { - return err.Error() - } - return fmt.Sprintf("panic: %v", p.reason) -} - -func safelyCall(fn func(*Tx) error, tx *Tx) (err error) { - defer func() { - if p := recover(); p != nil { - err = panicked{p} - } - }() - return fn(tx) -} - -// Sync executes fdatasync() against the database file handle. -// -// This is not necessary under normal operation, however, if you use NoSync -// then it allows you to force the database file to sync against the disk. -func (db *DB) Sync() error { return fdatasync(db) } - -// Stats retrieves ongoing performance stats for the database. -// This is only updated when a transaction closes. -func (db *DB) Stats() Stats { - db.statlock.RLock() - defer db.statlock.RUnlock() - return db.stats -} - -// This is for internal access to the raw data bytes from the C cursor, use -// carefully, or not at all. -func (db *DB) Info() *Info { - return &Info{uintptr(unsafe.Pointer(&db.data[0])), db.pageSize} -} - -// page retrieves a page reference from the mmap based on the current page size. -func (db *DB) page(id pgid) *page { - pos := id * pgid(db.pageSize) - return (*page)(unsafe.Pointer(&db.data[pos])) -} - -// pageInBuffer retrieves a page reference from a given byte array based on the current page size. -func (db *DB) pageInBuffer(b []byte, id pgid) *page { - return (*page)(unsafe.Pointer(&b[id*pgid(db.pageSize)])) -} - -// meta retrieves the current meta page reference. -func (db *DB) meta() *meta { - // We have to return the meta with the highest txid which doesn't fail - // validation. Otherwise, we can cause errors when in fact the database is - // in a consistent state. metaA is the one with the higher txid. - metaA := db.meta0 - metaB := db.meta1 - if db.meta1.txid > db.meta0.txid { - metaA = db.meta1 - metaB = db.meta0 - } - - // Use higher meta page if valid. Otherwise fallback to previous, if valid. - if err := metaA.validate(); err == nil { - return metaA - } else if err := metaB.validate(); err == nil { - return metaB - } - - // This should never be reached, because both meta1 and meta0 were validated - // on mmap() and we do fsync() on every write. - panic("bolt.DB.meta(): invalid meta pages") -} - -// allocate returns a contiguous block of memory starting at a given page. -func (db *DB) allocate(count int) (*page, error) { - // Allocate a temporary buffer for the page. - var buf []byte - if count == 1 { - buf = db.pagePool.Get().([]byte) - } else { - buf = make([]byte, count*db.pageSize) - } - p := (*page)(unsafe.Pointer(&buf[0])) - p.overflow = uint32(count - 1) - - // Use pages from the freelist if they are available. - if p.id = db.freelist.allocate(count); p.id != 0 { - return p, nil - } - - // Resize mmap() if we're at the end. - p.id = db.rwtx.meta.pgid - var minsz = int((p.id+pgid(count))+1) * db.pageSize - if minsz >= db.datasz { - if err := db.mmap(minsz); err != nil { - return nil, fmt.Errorf("mmap allocate error: %s", err) - } - } - - // Move the page id high water mark. - db.rwtx.meta.pgid += pgid(count) - - return p, nil -} - -// grow grows the size of the database to the given sz. -func (db *DB) grow(sz int) error { - // Ignore if the new size is less than available file size. - if sz <= db.filesz { - return nil - } - - // If the data is smaller than the alloc size then only allocate what's needed. - // Once it goes over the allocation size then allocate in chunks. - if db.datasz < db.AllocSize { - sz = db.datasz - } else { - sz += db.AllocSize - } - - // Truncate and fsync to ensure file size metadata is flushed. - // https://github.com/boltdb/bolt/issues/284 - if !db.NoGrowSync && !db.readOnly { - if runtime.GOOS != "windows" { - if err := db.file.Truncate(int64(sz)); err != nil { - return fmt.Errorf("file resize error: %s", err) - } - } - if err := db.file.Sync(); err != nil { - return fmt.Errorf("file sync error: %s", err) - } - } - - db.filesz = sz - return nil -} - -func (db *DB) IsReadOnly() bool { - return db.readOnly -} - -// Options represents the options that can be set when opening a database. -type Options struct { - // Timeout is the amount of time to wait to obtain a file lock. - // When set to zero it will wait indefinitely. This option is only - // available on Darwin and Linux. - Timeout time.Duration - - // Sets the DB.NoGrowSync flag before memory mapping the file. - NoGrowSync bool - - // Open database in read-only mode. Uses flock(..., LOCK_SH |LOCK_NB) to - // grab a shared lock (UNIX). - ReadOnly bool - - // Sets the DB.MmapFlags flag before memory mapping the file. - MmapFlags int - - // InitialMmapSize is the initial mmap size of the database - // in bytes. Read transactions won't block write transaction - // if the InitialMmapSize is large enough to hold database mmap - // size. (See DB.Begin for more information) - // - // If <=0, the initial map size is 0. - // If initialMmapSize is smaller than the previous database size, - // it takes no effect. - InitialMmapSize int -} - -// DefaultOptions represent the options used if nil options are passed into Open(). -// No timeout is used which will cause Bolt to wait indefinitely for a lock. -var DefaultOptions = &Options{ - Timeout: 0, - NoGrowSync: false, -} - -// Stats represents statistics about the database. -type Stats struct { - // Freelist stats - FreePageN int // total number of free pages on the freelist - PendingPageN int // total number of pending pages on the freelist - FreeAlloc int // total bytes allocated in free pages - FreelistInuse int // total bytes used by the freelist - - // Transaction stats - TxN int // total number of started read transactions - OpenTxN int // number of currently open read transactions - - TxStats TxStats // global, ongoing stats. -} - -// Sub calculates and returns the difference between two sets of database stats. -// This is useful when obtaining stats at two different points and time and -// you need the performance counters that occurred within that time span. -func (s *Stats) Sub(other *Stats) Stats { - if other == nil { - return *s - } - var diff Stats - diff.FreePageN = s.FreePageN - diff.PendingPageN = s.PendingPageN - diff.FreeAlloc = s.FreeAlloc - diff.FreelistInuse = s.FreelistInuse - diff.TxN = s.TxN - other.TxN - diff.TxStats = s.TxStats.Sub(&other.TxStats) - return diff -} - -func (s *Stats) add(other *Stats) { - s.TxStats.add(&other.TxStats) -} - -type Info struct { - Data uintptr - PageSize int -} - -type meta struct { - magic uint32 - version uint32 - pageSize uint32 - flags uint32 - root bucket - freelist pgid - pgid pgid - txid txid - checksum uint64 -} - -// validate checks the marker bytes and version of the meta page to ensure it matches this binary. -func (m *meta) validate() error { - if m.magic != magic { - return ErrInvalid - } else if m.version != version { - return ErrVersionMismatch - } else if m.checksum != 0 && m.checksum != m.sum64() { - return ErrChecksum - } - return nil -} - -// copy copies one meta object to another. -func (m *meta) copy(dest *meta) { - *dest = *m -} - -// write writes the meta onto a page. -func (m *meta) write(p *page) { - if m.root.root >= m.pgid { - panic(fmt.Sprintf("root bucket pgid (%d) above high water mark (%d)", m.root.root, m.pgid)) - } else if m.freelist >= m.pgid { - panic(fmt.Sprintf("freelist pgid (%d) above high water mark (%d)", m.freelist, m.pgid)) - } - - // Page id is either going to be 0 or 1 which we can determine by the transaction ID. - p.id = pgid(m.txid % 2) - p.flags |= metaPageFlag - - // Calculate the checksum. - m.checksum = m.sum64() - - m.copy(p.meta()) -} - -// generates the checksum for the meta. -func (m *meta) sum64() uint64 { - var h = fnv.New64a() - _, _ = h.Write((*[unsafe.Offsetof(meta{}.checksum)]byte)(unsafe.Pointer(m))[:]) - return h.Sum64() -} - -// _assert will panic with a given formatted message if the given condition is false. -func _assert(condition bool, msg string, v ...interface{}) { - if !condition { - panic(fmt.Sprintf("assertion failed: "+msg, v...)) - } -} - -func warn(v ...interface{}) { fmt.Fprintln(os.Stderr, v...) } -func warnf(msg string, v ...interface{}) { fmt.Fprintf(os.Stderr, msg+"\n", v...) } - -func printstack() { - stack := strings.Join(strings.Split(string(debug.Stack()), "\n")[2:], "\n") - fmt.Fprintln(os.Stderr, stack) -} diff --git a/vendor/github.com/boltdb/bolt/doc.go b/vendor/github.com/boltdb/bolt/doc.go deleted file mode 100644 index cc93784..0000000 --- a/vendor/github.com/boltdb/bolt/doc.go +++ /dev/null @@ -1,44 +0,0 @@ -/* -Package bolt implements a low-level key/value store in pure Go. It supports -fully serializable transactions, ACID semantics, and lock-free MVCC with -multiple readers and a single writer. Bolt can be used for projects that -want a simple data store without the need to add large dependencies such as -Postgres or MySQL. - -Bolt is a single-level, zero-copy, B+tree data store. This means that Bolt is -optimized for fast read access and does not require recovery in the event of a -system crash. Transactions which have not finished committing will simply be -rolled back in the event of a crash. - -The design of Bolt is based on Howard Chu's LMDB database project. - -Bolt currently works on Windows, Mac OS X, and Linux. - - -Basics - -There are only a few types in Bolt: DB, Bucket, Tx, and Cursor. The DB is -a collection of buckets and is represented by a single file on disk. A bucket is -a collection of unique keys that are associated with values. - -Transactions provide either read-only or read-write access to the database. -Read-only transactions can retrieve key/value pairs and can use Cursors to -iterate over the dataset sequentially. Read-write transactions can create and -delete buckets and can insert and remove keys. Only one read-write transaction -is allowed at a time. - - -Caveats - -The database uses a read-only, memory-mapped data file to ensure that -applications cannot corrupt the database, however, this means that keys and -values returned from Bolt cannot be changed. Writing to a read-only byte slice -will cause Go to panic. - -Keys and values retrieved from the database are only valid for the life of -the transaction. When used outside the transaction, these byte slices can -point to different data or can point to invalid memory which will cause a panic. - - -*/ -package bolt diff --git a/vendor/github.com/boltdb/bolt/errors.go b/vendor/github.com/boltdb/bolt/errors.go deleted file mode 100644 index a3620a3..0000000 --- a/vendor/github.com/boltdb/bolt/errors.go +++ /dev/null @@ -1,71 +0,0 @@ -package bolt - -import "errors" - -// These errors can be returned when opening or calling methods on a DB. -var ( - // ErrDatabaseNotOpen is returned when a DB instance is accessed before it - // is opened or after it is closed. - ErrDatabaseNotOpen = errors.New("database not open") - - // ErrDatabaseOpen is returned when opening a database that is - // already open. - ErrDatabaseOpen = errors.New("database already open") - - // ErrInvalid is returned when both meta pages on a database are invalid. - // This typically occurs when a file is not a bolt database. - ErrInvalid = errors.New("invalid database") - - // ErrVersionMismatch is returned when the data file was created with a - // different version of Bolt. - ErrVersionMismatch = errors.New("version mismatch") - - // ErrChecksum is returned when either meta page checksum does not match. - ErrChecksum = errors.New("checksum error") - - // ErrTimeout is returned when a database cannot obtain an exclusive lock - // on the data file after the timeout passed to Open(). - ErrTimeout = errors.New("timeout") -) - -// These errors can occur when beginning or committing a Tx. -var ( - // ErrTxNotWritable is returned when performing a write operation on a - // read-only transaction. - ErrTxNotWritable = errors.New("tx not writable") - - // ErrTxClosed is returned when committing or rolling back a transaction - // that has already been committed or rolled back. - ErrTxClosed = errors.New("tx closed") - - // ErrDatabaseReadOnly is returned when a mutating transaction is started on a - // read-only database. - ErrDatabaseReadOnly = errors.New("database is in read-only mode") -) - -// These errors can occur when putting or deleting a value or a bucket. -var ( - // ErrBucketNotFound is returned when trying to access a bucket that has - // not been created yet. - ErrBucketNotFound = errors.New("bucket not found") - - // ErrBucketExists is returned when creating a bucket that already exists. - ErrBucketExists = errors.New("bucket already exists") - - // ErrBucketNameRequired is returned when creating a bucket with a blank name. - ErrBucketNameRequired = errors.New("bucket name required") - - // ErrKeyRequired is returned when inserting a zero-length key. - ErrKeyRequired = errors.New("key required") - - // ErrKeyTooLarge is returned when inserting a key that is larger than MaxKeySize. - ErrKeyTooLarge = errors.New("key too large") - - // ErrValueTooLarge is returned when inserting a value that is larger than MaxValueSize. - ErrValueTooLarge = errors.New("value too large") - - // ErrIncompatibleValue is returned when trying create or delete a bucket - // on an existing non-bucket key or when trying to create or delete a - // non-bucket key on an existing bucket key. - ErrIncompatibleValue = errors.New("incompatible value") -) diff --git a/vendor/github.com/boltdb/bolt/freelist.go b/vendor/github.com/boltdb/bolt/freelist.go deleted file mode 100644 index aba48f5..0000000 --- a/vendor/github.com/boltdb/bolt/freelist.go +++ /dev/null @@ -1,252 +0,0 @@ -package bolt - -import ( - "fmt" - "sort" - "unsafe" -) - -// freelist represents a list of all pages that are available for allocation. -// It also tracks pages that have been freed but are still in use by open transactions. -type freelist struct { - ids []pgid // all free and available free page ids. - pending map[txid][]pgid // mapping of soon-to-be free page ids by tx. - cache map[pgid]bool // fast lookup of all free and pending page ids. -} - -// newFreelist returns an empty, initialized freelist. -func newFreelist() *freelist { - return &freelist{ - pending: make(map[txid][]pgid), - cache: make(map[pgid]bool), - } -} - -// size returns the size of the page after serialization. -func (f *freelist) size() int { - n := f.count() - if n >= 0xFFFF { - // The first element will be used to store the count. See freelist.write. - n++ - } - return pageHeaderSize + (int(unsafe.Sizeof(pgid(0))) * n) -} - -// count returns count of pages on the freelist -func (f *freelist) count() int { - return f.free_count() + f.pending_count() -} - -// free_count returns count of free pages -func (f *freelist) free_count() int { - return len(f.ids) -} - -// pending_count returns count of pending pages -func (f *freelist) pending_count() int { - var count int - for _, list := range f.pending { - count += len(list) - } - return count -} - -// copyall copies into dst a list of all free ids and all pending ids in one sorted list. -// f.count returns the minimum length required for dst. -func (f *freelist) copyall(dst []pgid) { - m := make(pgids, 0, f.pending_count()) - for _, list := range f.pending { - m = append(m, list...) - } - sort.Sort(m) - mergepgids(dst, f.ids, m) -} - -// allocate returns the starting page id of a contiguous list of pages of a given size. -// If a contiguous block cannot be found then 0 is returned. -func (f *freelist) allocate(n int) pgid { - if len(f.ids) == 0 { - return 0 - } - - var initial, previd pgid - for i, id := range f.ids { - if id <= 1 { - panic(fmt.Sprintf("invalid page allocation: %d", id)) - } - - // Reset initial page if this is not contiguous. - if previd == 0 || id-previd != 1 { - initial = id - } - - // If we found a contiguous block then remove it and return it. - if (id-initial)+1 == pgid(n) { - // If we're allocating off the beginning then take the fast path - // and just adjust the existing slice. This will use extra memory - // temporarily but the append() in free() will realloc the slice - // as is necessary. - if (i + 1) == n { - f.ids = f.ids[i+1:] - } else { - copy(f.ids[i-n+1:], f.ids[i+1:]) - f.ids = f.ids[:len(f.ids)-n] - } - - // Remove from the free cache. - for i := pgid(0); i < pgid(n); i++ { - delete(f.cache, initial+i) - } - - return initial - } - - previd = id - } - return 0 -} - -// free releases a page and its overflow for a given transaction id. -// If the page is already free then a panic will occur. -func (f *freelist) free(txid txid, p *page) { - if p.id <= 1 { - panic(fmt.Sprintf("cannot free page 0 or 1: %d", p.id)) - } - - // Free page and all its overflow pages. - var ids = f.pending[txid] - for id := p.id; id <= p.id+pgid(p.overflow); id++ { - // Verify that page is not already free. - if f.cache[id] { - panic(fmt.Sprintf("page %d already freed", id)) - } - - // Add to the freelist and cache. - ids = append(ids, id) - f.cache[id] = true - } - f.pending[txid] = ids -} - -// release moves all page ids for a transaction id (or older) to the freelist. -func (f *freelist) release(txid txid) { - m := make(pgids, 0) - for tid, ids := range f.pending { - if tid <= txid { - // Move transaction's pending pages to the available freelist. - // Don't remove from the cache since the page is still free. - m = append(m, ids...) - delete(f.pending, tid) - } - } - sort.Sort(m) - f.ids = pgids(f.ids).merge(m) -} - -// rollback removes the pages from a given pending tx. -func (f *freelist) rollback(txid txid) { - // Remove page ids from cache. - for _, id := range f.pending[txid] { - delete(f.cache, id) - } - - // Remove pages from pending list. - delete(f.pending, txid) -} - -// freed returns whether a given page is in the free list. -func (f *freelist) freed(pgid pgid) bool { - return f.cache[pgid] -} - -// read initializes the freelist from a freelist page. -func (f *freelist) read(p *page) { - // If the page.count is at the max uint16 value (64k) then it's considered - // an overflow and the size of the freelist is stored as the first element. - idx, count := 0, int(p.count) - if count == 0xFFFF { - idx = 1 - count = int(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[0]) - } - - // Copy the list of page ids from the freelist. - if count == 0 { - f.ids = nil - } else { - ids := ((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[idx:count] - f.ids = make([]pgid, len(ids)) - copy(f.ids, ids) - - // Make sure they're sorted. - sort.Sort(pgids(f.ids)) - } - - // Rebuild the page cache. - f.reindex() -} - -// write writes the page ids onto a freelist page. All free and pending ids are -// saved to disk since in the event of a program crash, all pending ids will -// become free. -func (f *freelist) write(p *page) error { - // Combine the old free pgids and pgids waiting on an open transaction. - - // Update the header flag. - p.flags |= freelistPageFlag - - // The page.count can only hold up to 64k elements so if we overflow that - // number then we handle it by putting the size in the first element. - lenids := f.count() - if lenids == 0 { - p.count = uint16(lenids) - } else if lenids < 0xFFFF { - p.count = uint16(lenids) - f.copyall(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[:]) - } else { - p.count = 0xFFFF - ((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[0] = pgid(lenids) - f.copyall(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[1:]) - } - - return nil -} - -// reload reads the freelist from a page and filters out pending items. -func (f *freelist) reload(p *page) { - f.read(p) - - // Build a cache of only pending pages. - pcache := make(map[pgid]bool) - for _, pendingIDs := range f.pending { - for _, pendingID := range pendingIDs { - pcache[pendingID] = true - } - } - - // Check each page in the freelist and build a new available freelist - // with any pages not in the pending lists. - var a []pgid - for _, id := range f.ids { - if !pcache[id] { - a = append(a, id) - } - } - f.ids = a - - // Once the available list is rebuilt then rebuild the free cache so that - // it includes the available and pending free pages. - f.reindex() -} - -// reindex rebuilds the free cache based on available and pending free lists. -func (f *freelist) reindex() { - f.cache = make(map[pgid]bool, len(f.ids)) - for _, id := range f.ids { - f.cache[id] = true - } - for _, pendingIDs := range f.pending { - for _, pendingID := range pendingIDs { - f.cache[pendingID] = true - } - } -} diff --git a/vendor/github.com/boltdb/bolt/node.go b/vendor/github.com/boltdb/bolt/node.go deleted file mode 100644 index 159318b..0000000 --- a/vendor/github.com/boltdb/bolt/node.go +++ /dev/null @@ -1,604 +0,0 @@ -package bolt - -import ( - "bytes" - "fmt" - "sort" - "unsafe" -) - -// node represents an in-memory, deserialized page. -type node struct { - bucket *Bucket - isLeaf bool - unbalanced bool - spilled bool - key []byte - pgid pgid - parent *node - children nodes - inodes inodes -} - -// root returns the top-level node this node is attached to. -func (n *node) root() *node { - if n.parent == nil { - return n - } - return n.parent.root() -} - -// minKeys returns the minimum number of inodes this node should have. -func (n *node) minKeys() int { - if n.isLeaf { - return 1 - } - return 2 -} - -// size returns the size of the node after serialization. -func (n *node) size() int { - sz, elsz := pageHeaderSize, n.pageElementSize() - for i := 0; i < len(n.inodes); i++ { - item := &n.inodes[i] - sz += elsz + len(item.key) + len(item.value) - } - return sz -} - -// sizeLessThan returns true if the node is less than a given size. -// This is an optimization to avoid calculating a large node when we only need -// to know if it fits inside a certain page size. -func (n *node) sizeLessThan(v int) bool { - sz, elsz := pageHeaderSize, n.pageElementSize() - for i := 0; i < len(n.inodes); i++ { - item := &n.inodes[i] - sz += elsz + len(item.key) + len(item.value) - if sz >= v { - return false - } - } - return true -} - -// pageElementSize returns the size of each page element based on the type of node. -func (n *node) pageElementSize() int { - if n.isLeaf { - return leafPageElementSize - } - return branchPageElementSize -} - -// childAt returns the child node at a given index. -func (n *node) childAt(index int) *node { - if n.isLeaf { - panic(fmt.Sprintf("invalid childAt(%d) on a leaf node", index)) - } - return n.bucket.node(n.inodes[index].pgid, n) -} - -// childIndex returns the index of a given child node. -func (n *node) childIndex(child *node) int { - index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, child.key) != -1 }) - return index -} - -// numChildren returns the number of children. -func (n *node) numChildren() int { - return len(n.inodes) -} - -// nextSibling returns the next node with the same parent. -func (n *node) nextSibling() *node { - if n.parent == nil { - return nil - } - index := n.parent.childIndex(n) - if index >= n.parent.numChildren()-1 { - return nil - } - return n.parent.childAt(index + 1) -} - -// prevSibling returns the previous node with the same parent. -func (n *node) prevSibling() *node { - if n.parent == nil { - return nil - } - index := n.parent.childIndex(n) - if index == 0 { - return nil - } - return n.parent.childAt(index - 1) -} - -// put inserts a key/value. -func (n *node) put(oldKey, newKey, value []byte, pgid pgid, flags uint32) { - if pgid >= n.bucket.tx.meta.pgid { - panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", pgid, n.bucket.tx.meta.pgid)) - } else if len(oldKey) <= 0 { - panic("put: zero-length old key") - } else if len(newKey) <= 0 { - panic("put: zero-length new key") - } - - // Find insertion index. - index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, oldKey) != -1 }) - - // Add capacity and shift nodes if we don't have an exact match and need to insert. - exact := (len(n.inodes) > 0 && index < len(n.inodes) && bytes.Equal(n.inodes[index].key, oldKey)) - if !exact { - n.inodes = append(n.inodes, inode{}) - copy(n.inodes[index+1:], n.inodes[index:]) - } - - inode := &n.inodes[index] - inode.flags = flags - inode.key = newKey - inode.value = value - inode.pgid = pgid - _assert(len(inode.key) > 0, "put: zero-length inode key") -} - -// del removes a key from the node. -func (n *node) del(key []byte) { - // Find index of key. - index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, key) != -1 }) - - // Exit if the key isn't found. - if index >= len(n.inodes) || !bytes.Equal(n.inodes[index].key, key) { - return - } - - // Delete inode from the node. - n.inodes = append(n.inodes[:index], n.inodes[index+1:]...) - - // Mark the node as needing rebalancing. - n.unbalanced = true -} - -// read initializes the node from a page. -func (n *node) read(p *page) { - n.pgid = p.id - n.isLeaf = ((p.flags & leafPageFlag) != 0) - n.inodes = make(inodes, int(p.count)) - - for i := 0; i < int(p.count); i++ { - inode := &n.inodes[i] - if n.isLeaf { - elem := p.leafPageElement(uint16(i)) - inode.flags = elem.flags - inode.key = elem.key() - inode.value = elem.value() - } else { - elem := p.branchPageElement(uint16(i)) - inode.pgid = elem.pgid - inode.key = elem.key() - } - _assert(len(inode.key) > 0, "read: zero-length inode key") - } - - // Save first key so we can find the node in the parent when we spill. - if len(n.inodes) > 0 { - n.key = n.inodes[0].key - _assert(len(n.key) > 0, "read: zero-length node key") - } else { - n.key = nil - } -} - -// write writes the items onto one or more pages. -func (n *node) write(p *page) { - // Initialize page. - if n.isLeaf { - p.flags |= leafPageFlag - } else { - p.flags |= branchPageFlag - } - - if len(n.inodes) >= 0xFFFF { - panic(fmt.Sprintf("inode overflow: %d (pgid=%d)", len(n.inodes), p.id)) - } - p.count = uint16(len(n.inodes)) - - // Stop here if there are no items to write. - if p.count == 0 { - return - } - - // Loop over each item and write it to the page. - b := (*[maxAllocSize]byte)(unsafe.Pointer(&p.ptr))[n.pageElementSize()*len(n.inodes):] - for i, item := range n.inodes { - _assert(len(item.key) > 0, "write: zero-length inode key") - - // Write the page element. - if n.isLeaf { - elem := p.leafPageElement(uint16(i)) - elem.pos = uint32(uintptr(unsafe.Pointer(&b[0])) - uintptr(unsafe.Pointer(elem))) - elem.flags = item.flags - elem.ksize = uint32(len(item.key)) - elem.vsize = uint32(len(item.value)) - } else { - elem := p.branchPageElement(uint16(i)) - elem.pos = uint32(uintptr(unsafe.Pointer(&b[0])) - uintptr(unsafe.Pointer(elem))) - elem.ksize = uint32(len(item.key)) - elem.pgid = item.pgid - _assert(elem.pgid != p.id, "write: circular dependency occurred") - } - - // If the length of key+value is larger than the max allocation size - // then we need to reallocate the byte array pointer. - // - // See: https://github.com/boltdb/bolt/pull/335 - klen, vlen := len(item.key), len(item.value) - if len(b) < klen+vlen { - b = (*[maxAllocSize]byte)(unsafe.Pointer(&b[0]))[:] - } - - // Write data for the element to the end of the page. - copy(b[0:], item.key) - b = b[klen:] - copy(b[0:], item.value) - b = b[vlen:] - } - - // DEBUG ONLY: n.dump() -} - -// split breaks up a node into multiple smaller nodes, if appropriate. -// This should only be called from the spill() function. -func (n *node) split(pageSize int) []*node { - var nodes []*node - - node := n - for { - // Split node into two. - a, b := node.splitTwo(pageSize) - nodes = append(nodes, a) - - // If we can't split then exit the loop. - if b == nil { - break - } - - // Set node to b so it gets split on the next iteration. - node = b - } - - return nodes -} - -// splitTwo breaks up a node into two smaller nodes, if appropriate. -// This should only be called from the split() function. -func (n *node) splitTwo(pageSize int) (*node, *node) { - // Ignore the split if the page doesn't have at least enough nodes for - // two pages or if the nodes can fit in a single page. - if len(n.inodes) <= (minKeysPerPage*2) || n.sizeLessThan(pageSize) { - return n, nil - } - - // Determine the threshold before starting a new node. - var fillPercent = n.bucket.FillPercent - if fillPercent < minFillPercent { - fillPercent = minFillPercent - } else if fillPercent > maxFillPercent { - fillPercent = maxFillPercent - } - threshold := int(float64(pageSize) * fillPercent) - - // Determine split position and sizes of the two pages. - splitIndex, _ := n.splitIndex(threshold) - - // Split node into two separate nodes. - // If there's no parent then we'll need to create one. - if n.parent == nil { - n.parent = &node{bucket: n.bucket, children: []*node{n}} - } - - // Create a new node and add it to the parent. - next := &node{bucket: n.bucket, isLeaf: n.isLeaf, parent: n.parent} - n.parent.children = append(n.parent.children, next) - - // Split inodes across two nodes. - next.inodes = n.inodes[splitIndex:] - n.inodes = n.inodes[:splitIndex] - - // Update the statistics. - n.bucket.tx.stats.Split++ - - return n, next -} - -// splitIndex finds the position where a page will fill a given threshold. -// It returns the index as well as the size of the first page. -// This is only be called from split(). -func (n *node) splitIndex(threshold int) (index, sz int) { - sz = pageHeaderSize - - // Loop until we only have the minimum number of keys required for the second page. - for i := 0; i < len(n.inodes)-minKeysPerPage; i++ { - index = i - inode := n.inodes[i] - elsize := n.pageElementSize() + len(inode.key) + len(inode.value) - - // If we have at least the minimum number of keys and adding another - // node would put us over the threshold then exit and return. - if i >= minKeysPerPage && sz+elsize > threshold { - break - } - - // Add the element size to the total size. - sz += elsize - } - - return -} - -// spill writes the nodes to dirty pages and splits nodes as it goes. -// Returns an error if dirty pages cannot be allocated. -func (n *node) spill() error { - var tx = n.bucket.tx - if n.spilled { - return nil - } - - // Spill child nodes first. Child nodes can materialize sibling nodes in - // the case of split-merge so we cannot use a range loop. We have to check - // the children size on every loop iteration. - sort.Sort(n.children) - for i := 0; i < len(n.children); i++ { - if err := n.children[i].spill(); err != nil { - return err - } - } - - // We no longer need the child list because it's only used for spill tracking. - n.children = nil - - // Split nodes into appropriate sizes. The first node will always be n. - var nodes = n.split(tx.db.pageSize) - for _, node := range nodes { - // Add node's page to the freelist if it's not new. - if node.pgid > 0 { - tx.db.freelist.free(tx.meta.txid, tx.page(node.pgid)) - node.pgid = 0 - } - - // Allocate contiguous space for the node. - p, err := tx.allocate((node.size() / tx.db.pageSize) + 1) - if err != nil { - return err - } - - // Write the node. - if p.id >= tx.meta.pgid { - panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", p.id, tx.meta.pgid)) - } - node.pgid = p.id - node.write(p) - node.spilled = true - - // Insert into parent inodes. - if node.parent != nil { - var key = node.key - if key == nil { - key = node.inodes[0].key - } - - node.parent.put(key, node.inodes[0].key, nil, node.pgid, 0) - node.key = node.inodes[0].key - _assert(len(node.key) > 0, "spill: zero-length node key") - } - - // Update the statistics. - tx.stats.Spill++ - } - - // If the root node split and created a new root then we need to spill that - // as well. We'll clear out the children to make sure it doesn't try to respill. - if n.parent != nil && n.parent.pgid == 0 { - n.children = nil - return n.parent.spill() - } - - return nil -} - -// rebalance attempts to combine the node with sibling nodes if the node fill -// size is below a threshold or if there are not enough keys. -func (n *node) rebalance() { - if !n.unbalanced { - return - } - n.unbalanced = false - - // Update statistics. - n.bucket.tx.stats.Rebalance++ - - // Ignore if node is above threshold (25%) and has enough keys. - var threshold = n.bucket.tx.db.pageSize / 4 - if n.size() > threshold && len(n.inodes) > n.minKeys() { - return - } - - // Root node has special handling. - if n.parent == nil { - // If root node is a branch and only has one node then collapse it. - if !n.isLeaf && len(n.inodes) == 1 { - // Move root's child up. - child := n.bucket.node(n.inodes[0].pgid, n) - n.isLeaf = child.isLeaf - n.inodes = child.inodes[:] - n.children = child.children - - // Reparent all child nodes being moved. - for _, inode := range n.inodes { - if child, ok := n.bucket.nodes[inode.pgid]; ok { - child.parent = n - } - } - - // Remove old child. - child.parent = nil - delete(n.bucket.nodes, child.pgid) - child.free() - } - - return - } - - // If node has no keys then just remove it. - if n.numChildren() == 0 { - n.parent.del(n.key) - n.parent.removeChild(n) - delete(n.bucket.nodes, n.pgid) - n.free() - n.parent.rebalance() - return - } - - _assert(n.parent.numChildren() > 1, "parent must have at least 2 children") - - // Destination node is right sibling if idx == 0, otherwise left sibling. - var target *node - var useNextSibling = (n.parent.childIndex(n) == 0) - if useNextSibling { - target = n.nextSibling() - } else { - target = n.prevSibling() - } - - // If both this node and the target node are too small then merge them. - if useNextSibling { - // Reparent all child nodes being moved. - for _, inode := range target.inodes { - if child, ok := n.bucket.nodes[inode.pgid]; ok { - child.parent.removeChild(child) - child.parent = n - child.parent.children = append(child.parent.children, child) - } - } - - // Copy over inodes from target and remove target. - n.inodes = append(n.inodes, target.inodes...) - n.parent.del(target.key) - n.parent.removeChild(target) - delete(n.bucket.nodes, target.pgid) - target.free() - } else { - // Reparent all child nodes being moved. - for _, inode := range n.inodes { - if child, ok := n.bucket.nodes[inode.pgid]; ok { - child.parent.removeChild(child) - child.parent = target - child.parent.children = append(child.parent.children, child) - } - } - - // Copy over inodes to target and remove node. - target.inodes = append(target.inodes, n.inodes...) - n.parent.del(n.key) - n.parent.removeChild(n) - delete(n.bucket.nodes, n.pgid) - n.free() - } - - // Either this node or the target node was deleted from the parent so rebalance it. - n.parent.rebalance() -} - -// removes a node from the list of in-memory children. -// This does not affect the inodes. -func (n *node) removeChild(target *node) { - for i, child := range n.children { - if child == target { - n.children = append(n.children[:i], n.children[i+1:]...) - return - } - } -} - -// dereference causes the node to copy all its inode key/value references to heap memory. -// This is required when the mmap is reallocated so inodes are not pointing to stale data. -func (n *node) dereference() { - if n.key != nil { - key := make([]byte, len(n.key)) - copy(key, n.key) - n.key = key - _assert(n.pgid == 0 || len(n.key) > 0, "dereference: zero-length node key on existing node") - } - - for i := range n.inodes { - inode := &n.inodes[i] - - key := make([]byte, len(inode.key)) - copy(key, inode.key) - inode.key = key - _assert(len(inode.key) > 0, "dereference: zero-length inode key") - - value := make([]byte, len(inode.value)) - copy(value, inode.value) - inode.value = value - } - - // Recursively dereference children. - for _, child := range n.children { - child.dereference() - } - - // Update statistics. - n.bucket.tx.stats.NodeDeref++ -} - -// free adds the node's underlying page to the freelist. -func (n *node) free() { - if n.pgid != 0 { - n.bucket.tx.db.freelist.free(n.bucket.tx.meta.txid, n.bucket.tx.page(n.pgid)) - n.pgid = 0 - } -} - -// dump writes the contents of the node to STDERR for debugging purposes. -/* -func (n *node) dump() { - // Write node header. - var typ = "branch" - if n.isLeaf { - typ = "leaf" - } - warnf("[NODE %d {type=%s count=%d}]", n.pgid, typ, len(n.inodes)) - - // Write out abbreviated version of each item. - for _, item := range n.inodes { - if n.isLeaf { - if item.flags&bucketLeafFlag != 0 { - bucket := (*bucket)(unsafe.Pointer(&item.value[0])) - warnf("+L %08x -> (bucket root=%d)", trunc(item.key, 4), bucket.root) - } else { - warnf("+L %08x -> %08x", trunc(item.key, 4), trunc(item.value, 4)) - } - } else { - warnf("+B %08x -> pgid=%d", trunc(item.key, 4), item.pgid) - } - } - warn("") -} -*/ - -type nodes []*node - -func (s nodes) Len() int { return len(s) } -func (s nodes) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s nodes) Less(i, j int) bool { return bytes.Compare(s[i].inodes[0].key, s[j].inodes[0].key) == -1 } - -// inode represents an internal node inside of a node. -// It can be used to point to elements in a page or point -// to an element which hasn't been added to a page yet. -type inode struct { - flags uint32 - pgid pgid - key []byte - value []byte -} - -type inodes []inode diff --git a/vendor/github.com/boltdb/bolt/page.go b/vendor/github.com/boltdb/bolt/page.go deleted file mode 100644 index cde403a..0000000 --- a/vendor/github.com/boltdb/bolt/page.go +++ /dev/null @@ -1,197 +0,0 @@ -package bolt - -import ( - "fmt" - "os" - "sort" - "unsafe" -) - -const pageHeaderSize = int(unsafe.Offsetof(((*page)(nil)).ptr)) - -const minKeysPerPage = 2 - -const branchPageElementSize = int(unsafe.Sizeof(branchPageElement{})) -const leafPageElementSize = int(unsafe.Sizeof(leafPageElement{})) - -const ( - branchPageFlag = 0x01 - leafPageFlag = 0x02 - metaPageFlag = 0x04 - freelistPageFlag = 0x10 -) - -const ( - bucketLeafFlag = 0x01 -) - -type pgid uint64 - -type page struct { - id pgid - flags uint16 - count uint16 - overflow uint32 - ptr uintptr -} - -// typ returns a human readable page type string used for debugging. -func (p *page) typ() string { - if (p.flags & branchPageFlag) != 0 { - return "branch" - } else if (p.flags & leafPageFlag) != 0 { - return "leaf" - } else if (p.flags & metaPageFlag) != 0 { - return "meta" - } else if (p.flags & freelistPageFlag) != 0 { - return "freelist" - } - return fmt.Sprintf("unknown<%02x>", p.flags) -} - -// meta returns a pointer to the metadata section of the page. -func (p *page) meta() *meta { - return (*meta)(unsafe.Pointer(&p.ptr)) -} - -// leafPageElement retrieves the leaf node by index -func (p *page) leafPageElement(index uint16) *leafPageElement { - n := &((*[0x7FFFFFF]leafPageElement)(unsafe.Pointer(&p.ptr)))[index] - return n -} - -// leafPageElements retrieves a list of leaf nodes. -func (p *page) leafPageElements() []leafPageElement { - if p.count == 0 { - return nil - } - return ((*[0x7FFFFFF]leafPageElement)(unsafe.Pointer(&p.ptr)))[:] -} - -// branchPageElement retrieves the branch node by index -func (p *page) branchPageElement(index uint16) *branchPageElement { - return &((*[0x7FFFFFF]branchPageElement)(unsafe.Pointer(&p.ptr)))[index] -} - -// branchPageElements retrieves a list of branch nodes. -func (p *page) branchPageElements() []branchPageElement { - if p.count == 0 { - return nil - } - return ((*[0x7FFFFFF]branchPageElement)(unsafe.Pointer(&p.ptr)))[:] -} - -// dump writes n bytes of the page to STDERR as hex output. -func (p *page) hexdump(n int) { - buf := (*[maxAllocSize]byte)(unsafe.Pointer(p))[:n] - fmt.Fprintf(os.Stderr, "%x\n", buf) -} - -type pages []*page - -func (s pages) Len() int { return len(s) } -func (s pages) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s pages) Less(i, j int) bool { return s[i].id < s[j].id } - -// branchPageElement represents a node on a branch page. -type branchPageElement struct { - pos uint32 - ksize uint32 - pgid pgid -} - -// key returns a byte slice of the node key. -func (n *branchPageElement) key() []byte { - buf := (*[maxAllocSize]byte)(unsafe.Pointer(n)) - return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos]))[:n.ksize] -} - -// leafPageElement represents a node on a leaf page. -type leafPageElement struct { - flags uint32 - pos uint32 - ksize uint32 - vsize uint32 -} - -// key returns a byte slice of the node key. -func (n *leafPageElement) key() []byte { - buf := (*[maxAllocSize]byte)(unsafe.Pointer(n)) - return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos]))[:n.ksize:n.ksize] -} - -// value returns a byte slice of the node value. -func (n *leafPageElement) value() []byte { - buf := (*[maxAllocSize]byte)(unsafe.Pointer(n)) - return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos+n.ksize]))[:n.vsize:n.vsize] -} - -// PageInfo represents human readable information about a page. -type PageInfo struct { - ID int - Type string - Count int - OverflowCount int -} - -type pgids []pgid - -func (s pgids) Len() int { return len(s) } -func (s pgids) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s pgids) Less(i, j int) bool { return s[i] < s[j] } - -// merge returns the sorted union of a and b. -func (a pgids) merge(b pgids) pgids { - // Return the opposite slice if one is nil. - if len(a) == 0 { - return b - } - if len(b) == 0 { - return a - } - merged := make(pgids, len(a)+len(b)) - mergepgids(merged, a, b) - return merged -} - -// mergepgids copies the sorted union of a and b into dst. -// If dst is too small, it panics. -func mergepgids(dst, a, b pgids) { - if len(dst) < len(a)+len(b) { - panic(fmt.Errorf("mergepgids bad len %d < %d + %d", len(dst), len(a), len(b))) - } - // Copy in the opposite slice if one is nil. - if len(a) == 0 { - copy(dst, b) - return - } - if len(b) == 0 { - copy(dst, a) - return - } - - // Merged will hold all elements from both lists. - merged := dst[:0] - - // Assign lead to the slice with a lower starting value, follow to the higher value. - lead, follow := a, b - if b[0] < a[0] { - lead, follow = b, a - } - - // Continue while there are elements in the lead. - for len(lead) > 0 { - // Merge largest prefix of lead that is ahead of follow[0]. - n := sort.Search(len(lead), func(i int) bool { return lead[i] > follow[0] }) - merged = append(merged, lead[:n]...) - if n >= len(lead) { - break - } - - // Swap lead and follow. - lead, follow = follow, lead[n:] - } - - // Append what's left in follow. - _ = append(merged, follow...) -} diff --git a/vendor/github.com/boltdb/bolt/tx.go b/vendor/github.com/boltdb/bolt/tx.go deleted file mode 100644 index 6700308..0000000 --- a/vendor/github.com/boltdb/bolt/tx.go +++ /dev/null @@ -1,684 +0,0 @@ -package bolt - -import ( - "fmt" - "io" - "os" - "sort" - "strings" - "time" - "unsafe" -) - -// txid represents the internal transaction identifier. -type txid uint64 - -// Tx represents a read-only or read/write transaction on the database. -// Read-only transactions can be used for retrieving values for keys and creating cursors. -// Read/write transactions can create and remove buckets and create and remove keys. -// -// IMPORTANT: You must commit or rollback transactions when you are done with -// them. Pages can not be reclaimed by the writer until no more transactions -// are using them. A long running read transaction can cause the database to -// quickly grow. -type Tx struct { - writable bool - managed bool - db *DB - meta *meta - root Bucket - pages map[pgid]*page - stats TxStats - commitHandlers []func() - - // WriteFlag specifies the flag for write-related methods like WriteTo(). - // Tx opens the database file with the specified flag to copy the data. - // - // By default, the flag is unset, which works well for mostly in-memory - // workloads. For databases that are much larger than available RAM, - // set the flag to syscall.O_DIRECT to avoid trashing the page cache. - WriteFlag int -} - -// init initializes the transaction. -func (tx *Tx) init(db *DB) { - tx.db = db - tx.pages = nil - - // Copy the meta page since it can be changed by the writer. - tx.meta = &meta{} - db.meta().copy(tx.meta) - - // Copy over the root bucket. - tx.root = newBucket(tx) - tx.root.bucket = &bucket{} - *tx.root.bucket = tx.meta.root - - // Increment the transaction id and add a page cache for writable transactions. - if tx.writable { - tx.pages = make(map[pgid]*page) - tx.meta.txid += txid(1) - } -} - -// ID returns the transaction id. -func (tx *Tx) ID() int { - return int(tx.meta.txid) -} - -// DB returns a reference to the database that created the transaction. -func (tx *Tx) DB() *DB { - return tx.db -} - -// Size returns current database size in bytes as seen by this transaction. -func (tx *Tx) Size() int64 { - return int64(tx.meta.pgid) * int64(tx.db.pageSize) -} - -// Writable returns whether the transaction can perform write operations. -func (tx *Tx) Writable() bool { - return tx.writable -} - -// Cursor creates a cursor associated with the root bucket. -// All items in the cursor will return a nil value because all root bucket keys point to buckets. -// The cursor is only valid as long as the transaction is open. -// Do not use a cursor after the transaction is closed. -func (tx *Tx) Cursor() *Cursor { - return tx.root.Cursor() -} - -// Stats retrieves a copy of the current transaction statistics. -func (tx *Tx) Stats() TxStats { - return tx.stats -} - -// Bucket retrieves a bucket by name. -// Returns nil if the bucket does not exist. -// The bucket instance is only valid for the lifetime of the transaction. -func (tx *Tx) Bucket(name []byte) *Bucket { - return tx.root.Bucket(name) -} - -// CreateBucket creates a new bucket. -// Returns an error if the bucket already exists, if the bucket name is blank, or if the bucket name is too long. -// The bucket instance is only valid for the lifetime of the transaction. -func (tx *Tx) CreateBucket(name []byte) (*Bucket, error) { - return tx.root.CreateBucket(name) -} - -// CreateBucketIfNotExists creates a new bucket if it doesn't already exist. -// Returns an error if the bucket name is blank, or if the bucket name is too long. -// The bucket instance is only valid for the lifetime of the transaction. -func (tx *Tx) CreateBucketIfNotExists(name []byte) (*Bucket, error) { - return tx.root.CreateBucketIfNotExists(name) -} - -// DeleteBucket deletes a bucket. -// Returns an error if the bucket cannot be found or if the key represents a non-bucket value. -func (tx *Tx) DeleteBucket(name []byte) error { - return tx.root.DeleteBucket(name) -} - -// ForEach executes a function for each bucket in the root. -// If the provided function returns an error then the iteration is stopped and -// the error is returned to the caller. -func (tx *Tx) ForEach(fn func(name []byte, b *Bucket) error) error { - return tx.root.ForEach(func(k, v []byte) error { - if err := fn(k, tx.root.Bucket(k)); err != nil { - return err - } - return nil - }) -} - -// OnCommit adds a handler function to be executed after the transaction successfully commits. -func (tx *Tx) OnCommit(fn func()) { - tx.commitHandlers = append(tx.commitHandlers, fn) -} - -// Commit writes all changes to disk and updates the meta page. -// Returns an error if a disk write error occurs, or if Commit is -// called on a read-only transaction. -func (tx *Tx) Commit() error { - _assert(!tx.managed, "managed tx commit not allowed") - if tx.db == nil { - return ErrTxClosed - } else if !tx.writable { - return ErrTxNotWritable - } - - // TODO(benbjohnson): Use vectorized I/O to write out dirty pages. - - // Rebalance nodes which have had deletions. - var startTime = time.Now() - tx.root.rebalance() - if tx.stats.Rebalance > 0 { - tx.stats.RebalanceTime += time.Since(startTime) - } - - // spill data onto dirty pages. - startTime = time.Now() - if err := tx.root.spill(); err != nil { - tx.rollback() - return err - } - tx.stats.SpillTime += time.Since(startTime) - - // Free the old root bucket. - tx.meta.root.root = tx.root.root - - opgid := tx.meta.pgid - - // Free the freelist and allocate new pages for it. This will overestimate - // the size of the freelist but not underestimate the size (which would be bad). - tx.db.freelist.free(tx.meta.txid, tx.db.page(tx.meta.freelist)) - p, err := tx.allocate((tx.db.freelist.size() / tx.db.pageSize) + 1) - if err != nil { - tx.rollback() - return err - } - if err := tx.db.freelist.write(p); err != nil { - tx.rollback() - return err - } - tx.meta.freelist = p.id - - // If the high water mark has moved up then attempt to grow the database. - if tx.meta.pgid > opgid { - if err := tx.db.grow(int(tx.meta.pgid+1) * tx.db.pageSize); err != nil { - tx.rollback() - return err - } - } - - // Write dirty pages to disk. - startTime = time.Now() - if err := tx.write(); err != nil { - tx.rollback() - return err - } - - // If strict mode is enabled then perform a consistency check. - // Only the first consistency error is reported in the panic. - if tx.db.StrictMode { - ch := tx.Check() - var errs []string - for { - err, ok := <-ch - if !ok { - break - } - errs = append(errs, err.Error()) - } - if len(errs) > 0 { - panic("check fail: " + strings.Join(errs, "\n")) - } - } - - // Write meta to disk. - if err := tx.writeMeta(); err != nil { - tx.rollback() - return err - } - tx.stats.WriteTime += time.Since(startTime) - - // Finalize the transaction. - tx.close() - - // Execute commit handlers now that the locks have been removed. - for _, fn := range tx.commitHandlers { - fn() - } - - return nil -} - -// Rollback closes the transaction and ignores all previous updates. Read-only -// transactions must be rolled back and not committed. -func (tx *Tx) Rollback() error { - _assert(!tx.managed, "managed tx rollback not allowed") - if tx.db == nil { - return ErrTxClosed - } - tx.rollback() - return nil -} - -func (tx *Tx) rollback() { - if tx.db == nil { - return - } - if tx.writable { - tx.db.freelist.rollback(tx.meta.txid) - tx.db.freelist.reload(tx.db.page(tx.db.meta().freelist)) - } - tx.close() -} - -func (tx *Tx) close() { - if tx.db == nil { - return - } - if tx.writable { - // Grab freelist stats. - var freelistFreeN = tx.db.freelist.free_count() - var freelistPendingN = tx.db.freelist.pending_count() - var freelistAlloc = tx.db.freelist.size() - - // Remove transaction ref & writer lock. - tx.db.rwtx = nil - tx.db.rwlock.Unlock() - - // Merge statistics. - tx.db.statlock.Lock() - tx.db.stats.FreePageN = freelistFreeN - tx.db.stats.PendingPageN = freelistPendingN - tx.db.stats.FreeAlloc = (freelistFreeN + freelistPendingN) * tx.db.pageSize - tx.db.stats.FreelistInuse = freelistAlloc - tx.db.stats.TxStats.add(&tx.stats) - tx.db.statlock.Unlock() - } else { - tx.db.removeTx(tx) - } - - // Clear all references. - tx.db = nil - tx.meta = nil - tx.root = Bucket{tx: tx} - tx.pages = nil -} - -// Copy writes the entire database to a writer. -// This function exists for backwards compatibility. Use WriteTo() instead. -func (tx *Tx) Copy(w io.Writer) error { - _, err := tx.WriteTo(w) - return err -} - -// WriteTo writes the entire database to a writer. -// If err == nil then exactly tx.Size() bytes will be written into the writer. -func (tx *Tx) WriteTo(w io.Writer) (n int64, err error) { - // Attempt to open reader with WriteFlag - f, err := os.OpenFile(tx.db.path, os.O_RDONLY|tx.WriteFlag, 0) - if err != nil { - return 0, err - } - defer func() { _ = f.Close() }() - - // Generate a meta page. We use the same page data for both meta pages. - buf := make([]byte, tx.db.pageSize) - page := (*page)(unsafe.Pointer(&buf[0])) - page.flags = metaPageFlag - *page.meta() = *tx.meta - - // Write meta 0. - page.id = 0 - page.meta().checksum = page.meta().sum64() - nn, err := w.Write(buf) - n += int64(nn) - if err != nil { - return n, fmt.Errorf("meta 0 copy: %s", err) - } - - // Write meta 1 with a lower transaction id. - page.id = 1 - page.meta().txid -= 1 - page.meta().checksum = page.meta().sum64() - nn, err = w.Write(buf) - n += int64(nn) - if err != nil { - return n, fmt.Errorf("meta 1 copy: %s", err) - } - - // Move past the meta pages in the file. - if _, err := f.Seek(int64(tx.db.pageSize*2), os.SEEK_SET); err != nil { - return n, fmt.Errorf("seek: %s", err) - } - - // Copy data pages. - wn, err := io.CopyN(w, f, tx.Size()-int64(tx.db.pageSize*2)) - n += wn - if err != nil { - return n, err - } - - return n, f.Close() -} - -// CopyFile copies the entire database to file at the given path. -// A reader transaction is maintained during the copy so it is safe to continue -// using the database while a copy is in progress. -func (tx *Tx) CopyFile(path string, mode os.FileMode) error { - f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode) - if err != nil { - return err - } - - err = tx.Copy(f) - if err != nil { - _ = f.Close() - return err - } - return f.Close() -} - -// Check performs several consistency checks on the database for this transaction. -// An error is returned if any inconsistency is found. -// -// It can be safely run concurrently on a writable transaction. However, this -// incurs a high cost for large databases and databases with a lot of subbuckets -// because of caching. This overhead can be removed if running on a read-only -// transaction, however, it is not safe to execute other writer transactions at -// the same time. -func (tx *Tx) Check() <-chan error { - ch := make(chan error) - go tx.check(ch) - return ch -} - -func (tx *Tx) check(ch chan error) { - // Check if any pages are double freed. - freed := make(map[pgid]bool) - all := make([]pgid, tx.db.freelist.count()) - tx.db.freelist.copyall(all) - for _, id := range all { - if freed[id] { - ch <- fmt.Errorf("page %d: already freed", id) - } - freed[id] = true - } - - // Track every reachable page. - reachable := make(map[pgid]*page) - reachable[0] = tx.page(0) // meta0 - reachable[1] = tx.page(1) // meta1 - for i := uint32(0); i <= tx.page(tx.meta.freelist).overflow; i++ { - reachable[tx.meta.freelist+pgid(i)] = tx.page(tx.meta.freelist) - } - - // Recursively check buckets. - tx.checkBucket(&tx.root, reachable, freed, ch) - - // Ensure all pages below high water mark are either reachable or freed. - for i := pgid(0); i < tx.meta.pgid; i++ { - _, isReachable := reachable[i] - if !isReachable && !freed[i] { - ch <- fmt.Errorf("page %d: unreachable unfreed", int(i)) - } - } - - // Close the channel to signal completion. - close(ch) -} - -func (tx *Tx) checkBucket(b *Bucket, reachable map[pgid]*page, freed map[pgid]bool, ch chan error) { - // Ignore inline buckets. - if b.root == 0 { - return - } - - // Check every page used by this bucket. - b.tx.forEachPage(b.root, 0, func(p *page, _ int) { - if p.id > tx.meta.pgid { - ch <- fmt.Errorf("page %d: out of bounds: %d", int(p.id), int(b.tx.meta.pgid)) - } - - // Ensure each page is only referenced once. - for i := pgid(0); i <= pgid(p.overflow); i++ { - var id = p.id + i - if _, ok := reachable[id]; ok { - ch <- fmt.Errorf("page %d: multiple references", int(id)) - } - reachable[id] = p - } - - // We should only encounter un-freed leaf and branch pages. - if freed[p.id] { - ch <- fmt.Errorf("page %d: reachable freed", int(p.id)) - } else if (p.flags&branchPageFlag) == 0 && (p.flags&leafPageFlag) == 0 { - ch <- fmt.Errorf("page %d: invalid type: %s", int(p.id), p.typ()) - } - }) - - // Check each bucket within this bucket. - _ = b.ForEach(func(k, v []byte) error { - if child := b.Bucket(k); child != nil { - tx.checkBucket(child, reachable, freed, ch) - } - return nil - }) -} - -// allocate returns a contiguous block of memory starting at a given page. -func (tx *Tx) allocate(count int) (*page, error) { - p, err := tx.db.allocate(count) - if err != nil { - return nil, err - } - - // Save to our page cache. - tx.pages[p.id] = p - - // Update statistics. - tx.stats.PageCount++ - tx.stats.PageAlloc += count * tx.db.pageSize - - return p, nil -} - -// write writes any dirty pages to disk. -func (tx *Tx) write() error { - // Sort pages by id. - pages := make(pages, 0, len(tx.pages)) - for _, p := range tx.pages { - pages = append(pages, p) - } - // Clear out page cache early. - tx.pages = make(map[pgid]*page) - sort.Sort(pages) - - // Write pages to disk in order. - for _, p := range pages { - size := (int(p.overflow) + 1) * tx.db.pageSize - offset := int64(p.id) * int64(tx.db.pageSize) - - // Write out page in "max allocation" sized chunks. - ptr := (*[maxAllocSize]byte)(unsafe.Pointer(p)) - for { - // Limit our write to our max allocation size. - sz := size - if sz > maxAllocSize-1 { - sz = maxAllocSize - 1 - } - - // Write chunk to disk. - buf := ptr[:sz] - if _, err := tx.db.ops.writeAt(buf, offset); err != nil { - return err - } - - // Update statistics. - tx.stats.Write++ - - // Exit inner for loop if we've written all the chunks. - size -= sz - if size == 0 { - break - } - - // Otherwise move offset forward and move pointer to next chunk. - offset += int64(sz) - ptr = (*[maxAllocSize]byte)(unsafe.Pointer(&ptr[sz])) - } - } - - // Ignore file sync if flag is set on DB. - if !tx.db.NoSync || IgnoreNoSync { - if err := fdatasync(tx.db); err != nil { - return err - } - } - - // Put small pages back to page pool. - for _, p := range pages { - // Ignore page sizes over 1 page. - // These are allocated using make() instead of the page pool. - if int(p.overflow) != 0 { - continue - } - - buf := (*[maxAllocSize]byte)(unsafe.Pointer(p))[:tx.db.pageSize] - - // See https://go.googlesource.com/go/+/f03c9202c43e0abb130669852082117ca50aa9b1 - for i := range buf { - buf[i] = 0 - } - tx.db.pagePool.Put(buf) - } - - return nil -} - -// writeMeta writes the meta to the disk. -func (tx *Tx) writeMeta() error { - // Create a temporary buffer for the meta page. - buf := make([]byte, tx.db.pageSize) - p := tx.db.pageInBuffer(buf, 0) - tx.meta.write(p) - - // Write the meta page to file. - if _, err := tx.db.ops.writeAt(buf, int64(p.id)*int64(tx.db.pageSize)); err != nil { - return err - } - if !tx.db.NoSync || IgnoreNoSync { - if err := fdatasync(tx.db); err != nil { - return err - } - } - - // Update statistics. - tx.stats.Write++ - - return nil -} - -// page returns a reference to the page with a given id. -// If page has been written to then a temporary buffered page is returned. -func (tx *Tx) page(id pgid) *page { - // Check the dirty pages first. - if tx.pages != nil { - if p, ok := tx.pages[id]; ok { - return p - } - } - - // Otherwise return directly from the mmap. - return tx.db.page(id) -} - -// forEachPage iterates over every page within a given page and executes a function. -func (tx *Tx) forEachPage(pgid pgid, depth int, fn func(*page, int)) { - p := tx.page(pgid) - - // Execute function. - fn(p, depth) - - // Recursively loop over children. - if (p.flags & branchPageFlag) != 0 { - for i := 0; i < int(p.count); i++ { - elem := p.branchPageElement(uint16(i)) - tx.forEachPage(elem.pgid, depth+1, fn) - } - } -} - -// Page returns page information for a given page number. -// This is only safe for concurrent use when used by a writable transaction. -func (tx *Tx) Page(id int) (*PageInfo, error) { - if tx.db == nil { - return nil, ErrTxClosed - } else if pgid(id) >= tx.meta.pgid { - return nil, nil - } - - // Build the page info. - p := tx.db.page(pgid(id)) - info := &PageInfo{ - ID: id, - Count: int(p.count), - OverflowCount: int(p.overflow), - } - - // Determine the type (or if it's free). - if tx.db.freelist.freed(pgid(id)) { - info.Type = "free" - } else { - info.Type = p.typ() - } - - return info, nil -} - -// TxStats represents statistics about the actions performed by the transaction. -type TxStats struct { - // Page statistics. - PageCount int // number of page allocations - PageAlloc int // total bytes allocated - - // Cursor statistics. - CursorCount int // number of cursors created - - // Node statistics - NodeCount int // number of node allocations - NodeDeref int // number of node dereferences - - // Rebalance statistics. - Rebalance int // number of node rebalances - RebalanceTime time.Duration // total time spent rebalancing - - // Split/Spill statistics. - Split int // number of nodes split - Spill int // number of nodes spilled - SpillTime time.Duration // total time spent spilling - - // Write statistics. - Write int // number of writes performed - WriteTime time.Duration // total time spent writing to disk -} - -func (s *TxStats) add(other *TxStats) { - s.PageCount += other.PageCount - s.PageAlloc += other.PageAlloc - s.CursorCount += other.CursorCount - s.NodeCount += other.NodeCount - s.NodeDeref += other.NodeDeref - s.Rebalance += other.Rebalance - s.RebalanceTime += other.RebalanceTime - s.Split += other.Split - s.Spill += other.Spill - s.SpillTime += other.SpillTime - s.Write += other.Write - s.WriteTime += other.WriteTime -} - -// Sub calculates and returns the difference between two sets of transaction stats. -// This is useful when obtaining stats at two different points and time and -// you need the performance counters that occurred within that time span. -func (s *TxStats) Sub(other *TxStats) TxStats { - var diff TxStats - diff.PageCount = s.PageCount - other.PageCount - diff.PageAlloc = s.PageAlloc - other.PageAlloc - diff.CursorCount = s.CursorCount - other.CursorCount - diff.NodeCount = s.NodeCount - other.NodeCount - diff.NodeDeref = s.NodeDeref - other.NodeDeref - diff.Rebalance = s.Rebalance - other.Rebalance - diff.RebalanceTime = s.RebalanceTime - other.RebalanceTime - diff.Split = s.Split - other.Split - diff.Spill = s.Spill - other.Spill - diff.SpillTime = s.SpillTime - other.SpillTime - diff.Write = s.Write - other.Write - diff.WriteTime = s.WriteTime - other.WriteTime - return diff -} diff --git a/vendor/github.com/go-playground/validator/.gitignore b/vendor/github.com/go-playground/validator/.gitignore deleted file mode 100644 index 792ca00..0000000 --- a/vendor/github.com/go-playground/validator/.gitignore +++ /dev/null @@ -1,29 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof -*.test -*.out -*.txt -cover.html -README.html \ No newline at end of file diff --git a/vendor/github.com/go-playground/validator/LICENSE b/vendor/github.com/go-playground/validator/LICENSE deleted file mode 100644 index 6a2ae9a..0000000 --- a/vendor/github.com/go-playground/validator/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/github.com/go-playground/validator/Makefile b/vendor/github.com/go-playground/validator/Makefile deleted file mode 100644 index b912cae..0000000 --- a/vendor/github.com/go-playground/validator/Makefile +++ /dev/null @@ -1,18 +0,0 @@ -GOCMD=go - -linters-install: - @golangci-lint --version >/dev/null 2>&1 || { \ - echo "installing linting tools..."; \ - curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s v1.19.1; \ - } - -lint: linters-install - golangci-lint run - -test: - $(GOCMD) test -cover -race ./... - -bench: - $(GOCMD) test -bench=. -benchmem ./... - -.PHONY: test lint linters-install \ No newline at end of file diff --git a/vendor/github.com/go-playground/validator/README.md b/vendor/github.com/go-playground/validator/README.md deleted file mode 100644 index b55f3ec..0000000 --- a/vendor/github.com/go-playground/validator/README.md +++ /dev/null @@ -1,155 +0,0 @@ -**NOTICE:** v9 has entered maintenance status as of 2019-12-24. Please make all new functionality PR's against master. - -Package validator -================ -[![Join the chat at https://gitter.im/go-playground/validator](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/go-playground/validator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -![Project status](https://img.shields.io/badge/version-9.31.0-green.svg) -[![Build Status](https://semaphoreci.com/api/v1/joeybloggs/validator/branches/v9/badge.svg)](https://semaphoreci.com/joeybloggs/validator) -[![Coverage Status](https://coveralls.io/repos/go-playground/validator/badge.svg?branch=v9&service=github)](https://coveralls.io/github/go-playground/validator?branch=v9) -[![Go Report Card](https://goreportcard.com/badge/github.com/go-playground/validator)](https://goreportcard.com/report/github.com/go-playground/validator) -[![GoDoc](https://godoc.org/gopkg.in/go-playground/validator.v9?status.svg)](https://godoc.org/gopkg.in/go-playground/validator.v9) -![License](https://img.shields.io/dub/l/vibe-d.svg) - -Package validator implements value validations for structs and individual fields based on tags. - -It has the following **unique** features: - -- Cross Field and Cross Struct validations by using validation tags or custom validators. -- Slice, Array and Map diving, which allows any or all levels of a multidimensional field to be validated. -- Ability to dive into both map keys and values for validation -- Handles type interface by determining it's underlying type prior to validation. -- Handles custom field types such as sql driver Valuer see [Valuer](https://golang.org/src/database/sql/driver/types.go?s=1210:1293#L29) -- Alias validation tags, which allows for mapping of several validations to a single tag for easier defining of validations on structs -- Extraction of custom defined Field Name e.g. can specify to extract the JSON name while validating and have it available in the resulting FieldError -- Customizable i18n aware error messages. -- Default validator for the [gin](https://github.com/gin-gonic/gin) web framework; upgrading from v8 to v9 in gin see [here](https://github.com/go-playground/validator/tree/v9/_examples/gin-upgrading-overriding) - -Installation ------------- - -Use go get. - - go get gopkg.in/go-playground/validator.v9 - -Then import the validator package into your own code. - - import "gopkg.in/go-playground/validator.v9" - -Error Return Value -------- - -Validation functions return type error - -They 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 InvalidValidationError for bad validation input, 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 check if error is InvalidValidationError ( if necessary, most of the time it isn't ) type cast it to type ValidationErrors like so: - -```go -err := validate.Struct(mystruct) -validationErrors := err.(validator.ValidationErrors) - ``` - -Usage and documentation ------- - -Please see http://godoc.org/gopkg.in/go-playground/validator.v9 for detailed usage docs. - -##### Examples: - -- [Simple](https://github.com/go-playground/validator/blob/v9/_examples/simple/main.go) -- [Custom Field Types](https://github.com/go-playground/validator/blob/v9/_examples/custom/main.go) -- [Struct Level](https://github.com/go-playground/validator/blob/v9/_examples/struct-level/main.go) -- [Translations & Custom Errors](https://github.com/go-playground/validator/blob/v9/_examples/translations/main.go) -- [Gin upgrade and/or override validator](https://github.com/go-playground/validator/tree/v9/_examples/gin-upgrading-overriding) -- [wash - an example application putting it all together](https://github.com/bluesuncorp/wash) - -Benchmarks ------- -###### Run on MacBook Pro (15-inch, 2017) go version go1.10.2 darwin/amd64 -```go -goos: darwin -goarch: amd64 -pkg: github.com/go-playground/validator -BenchmarkFieldSuccess-8 20000000 83.6 ns/op 0 B/op 0 allocs/op -BenchmarkFieldSuccessParallel-8 50000000 26.8 ns/op 0 B/op 0 allocs/op -BenchmarkFieldFailure-8 5000000 291 ns/op 208 B/op 4 allocs/op -BenchmarkFieldFailureParallel-8 20000000 107 ns/op 208 B/op 4 allocs/op -BenchmarkFieldArrayDiveSuccess-8 2000000 623 ns/op 201 B/op 11 allocs/op -BenchmarkFieldArrayDiveSuccessParallel-8 10000000 237 ns/op 201 B/op 11 allocs/op -BenchmarkFieldArrayDiveFailure-8 2000000 859 ns/op 412 B/op 16 allocs/op -BenchmarkFieldArrayDiveFailureParallel-8 5000000 335 ns/op 413 B/op 16 allocs/op -BenchmarkFieldMapDiveSuccess-8 1000000 1292 ns/op 432 B/op 18 allocs/op -BenchmarkFieldMapDiveSuccessParallel-8 3000000 467 ns/op 432 B/op 18 allocs/op -BenchmarkFieldMapDiveFailure-8 1000000 1082 ns/op 512 B/op 16 allocs/op -BenchmarkFieldMapDiveFailureParallel-8 5000000 425 ns/op 512 B/op 16 allocs/op -BenchmarkFieldMapDiveWithKeysSuccess-8 1000000 1539 ns/op 480 B/op 21 allocs/op -BenchmarkFieldMapDiveWithKeysSuccessParallel-8 3000000 613 ns/op 480 B/op 21 allocs/op -BenchmarkFieldMapDiveWithKeysFailure-8 1000000 1413 ns/op 721 B/op 21 allocs/op -BenchmarkFieldMapDiveWithKeysFailureParallel-8 3000000 575 ns/op 721 B/op 21 allocs/op -BenchmarkFieldCustomTypeSuccess-8 10000000 216 ns/op 32 B/op 2 allocs/op -BenchmarkFieldCustomTypeSuccessParallel-8 20000000 82.2 ns/op 32 B/op 2 allocs/op -BenchmarkFieldCustomTypeFailure-8 5000000 274 ns/op 208 B/op 4 allocs/op -BenchmarkFieldCustomTypeFailureParallel-8 20000000 116 ns/op 208 B/op 4 allocs/op -BenchmarkFieldOrTagSuccess-8 2000000 740 ns/op 16 B/op 1 allocs/op -BenchmarkFieldOrTagSuccessParallel-8 3000000 474 ns/op 16 B/op 1 allocs/op -BenchmarkFieldOrTagFailure-8 3000000 471 ns/op 224 B/op 5 allocs/op -BenchmarkFieldOrTagFailureParallel-8 3000000 414 ns/op 224 B/op 5 allocs/op -BenchmarkStructLevelValidationSuccess-8 10000000 213 ns/op 32 B/op 2 allocs/op -BenchmarkStructLevelValidationSuccessParallel-8 20000000 91.8 ns/op 32 B/op 2 allocs/op -BenchmarkStructLevelValidationFailure-8 3000000 473 ns/op 304 B/op 8 allocs/op -BenchmarkStructLevelValidationFailureParallel-8 10000000 234 ns/op 304 B/op 8 allocs/op -BenchmarkStructSimpleCustomTypeSuccess-8 5000000 385 ns/op 32 B/op 2 allocs/op -BenchmarkStructSimpleCustomTypeSuccessParallel-8 10000000 161 ns/op 32 B/op 2 allocs/op -BenchmarkStructSimpleCustomTypeFailure-8 2000000 640 ns/op 424 B/op 9 allocs/op -BenchmarkStructSimpleCustomTypeFailureParallel-8 5000000 318 ns/op 440 B/op 10 allocs/op -BenchmarkStructFilteredSuccess-8 2000000 597 ns/op 288 B/op 9 allocs/op -BenchmarkStructFilteredSuccessParallel-8 10000000 266 ns/op 288 B/op 9 allocs/op -BenchmarkStructFilteredFailure-8 3000000 454 ns/op 256 B/op 7 allocs/op -BenchmarkStructFilteredFailureParallel-8 10000000 214 ns/op 256 B/op 7 allocs/op -BenchmarkStructPartialSuccess-8 3000000 502 ns/op 256 B/op 6 allocs/op -BenchmarkStructPartialSuccessParallel-8 10000000 225 ns/op 256 B/op 6 allocs/op -BenchmarkStructPartialFailure-8 2000000 702 ns/op 480 B/op 11 allocs/op -BenchmarkStructPartialFailureParallel-8 5000000 329 ns/op 480 B/op 11 allocs/op -BenchmarkStructExceptSuccess-8 2000000 793 ns/op 496 B/op 12 allocs/op -BenchmarkStructExceptSuccessParallel-8 10000000 193 ns/op 240 B/op 5 allocs/op -BenchmarkStructExceptFailure-8 2000000 639 ns/op 464 B/op 10 allocs/op -BenchmarkStructExceptFailureParallel-8 5000000 300 ns/op 464 B/op 10 allocs/op -BenchmarkStructSimpleCrossFieldSuccess-8 3000000 417 ns/op 72 B/op 3 allocs/op -BenchmarkStructSimpleCrossFieldSuccessParallel-8 10000000 163 ns/op 72 B/op 3 allocs/op -BenchmarkStructSimpleCrossFieldFailure-8 2000000 645 ns/op 304 B/op 8 allocs/op -BenchmarkStructSimpleCrossFieldFailureParallel-8 5000000 285 ns/op 304 B/op 8 allocs/op -BenchmarkStructSimpleCrossStructCrossFieldSuccess-8 3000000 588 ns/op 80 B/op 4 allocs/op -BenchmarkStructSimpleCrossStructCrossFieldSuccessParallel-8 10000000 221 ns/op 80 B/op 4 allocs/op -BenchmarkStructSimpleCrossStructCrossFieldFailure-8 2000000 868 ns/op 320 B/op 9 allocs/op -BenchmarkStructSimpleCrossStructCrossFieldFailureParallel-8 5000000 337 ns/op 320 B/op 9 allocs/op -BenchmarkStructSimpleSuccess-8 5000000 260 ns/op 0 B/op 0 allocs/op -BenchmarkStructSimpleSuccessParallel-8 20000000 90.6 ns/op 0 B/op 0 allocs/op -BenchmarkStructSimpleFailure-8 2000000 619 ns/op 424 B/op 9 allocs/op -BenchmarkStructSimpleFailureParallel-8 5000000 296 ns/op 424 B/op 9 allocs/op -BenchmarkStructComplexSuccess-8 1000000 1454 ns/op 128 B/op 8 allocs/op -BenchmarkStructComplexSuccessParallel-8 3000000 579 ns/op 128 B/op 8 allocs/op -BenchmarkStructComplexFailure-8 300000 4140 ns/op 3041 B/op 53 allocs/op -BenchmarkStructComplexFailureParallel-8 1000000 2127 ns/op 3041 B/op 53 allocs/op -BenchmarkOneof-8 10000000 140 ns/op 0 B/op 0 allocs/op -BenchmarkOneofParallel-8 20000000 70.1 ns/op 0 B/op 0 allocs/op -``` - -Complementary Software ----------------------- - -Here is a list of software that complements using this library either pre or post validation. - -* [form](https://github.com/go-playground/form) - Decodes url.Values into Go value(s) and Encodes Go value(s) into url.Values. Dual Array and Full map support. -* [mold](https://github.com/go-playground/mold) - A general library to help modify or set data within data structures and other objects - -How to Contribute ------- - -Make a pull request... - -License ------- -Distributed under MIT License, please see license file within the code for more details. diff --git a/vendor/github.com/go-playground/validator/baked_in.go b/vendor/github.com/go-playground/validator/baked_in.go deleted file mode 100644 index cfc5686..0000000 --- a/vendor/github.com/go-playground/validator/baked_in.go +++ /dev/null @@ -1,2001 +0,0 @@ -package validator - -import ( - "bytes" - "context" - "crypto/sha256" - "fmt" - "net" - "net/url" - "os" - "reflect" - "strconv" - "strings" - "sync" - "time" - "unicode/utf8" - - urn "github.com/leodido/go-urn" -) - -// Func accepts a FieldLevel interface for all validation needs. The return -// value should be true when validation succeeds. -type Func func(fl FieldLevel) bool - -// FuncCtx accepts a context.Context and FieldLevel interface for all -// validation needs. The return value should be true when validation succeeds. -type FuncCtx func(ctx context.Context, fl FieldLevel) bool - -// wrapFunc wraps noramal Func makes it compatible with FuncCtx -func wrapFunc(fn Func) FuncCtx { - if fn == nil { - return nil // be sure not to wrap a bad function. - } - return func(ctx context.Context, fl FieldLevel) bool { - return fn(fl) - } -} - -var ( - restrictedTags = map[string]struct{}{ - diveTag: {}, - keysTag: {}, - endKeysTag: {}, - structOnlyTag: {}, - omitempty: {}, - skipValidationTag: {}, - utf8HexComma: {}, - utf8Pipe: {}, - noStructLevelTag: {}, - requiredTag: {}, - isdefault: {}, - } - - // BakedInAliasValidators is a default mapping of a single validation tag that - // defines a common or complex set of validation(s) to simplify - // adding validation to structs. - bakedInAliases = 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. - bakedInValidators = map[string]Func{ - "required": hasValue, - "required_with": requiredWith, - "required_with_all": requiredWithAll, - "required_without": requiredWithout, - "required_without_all": requiredWithoutAll, - "isdefault": isDefault, - "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, - "fieldcontains": fieldContains, - "fieldexcludes": fieldExcludes, - "alpha": isAlpha, - "alphanum": isAlphanum, - "alphaunicode": isAlphaUnicode, - "alphanumunicode": isAlphanumUnicode, - "numeric": isNumeric, - "number": isNumber, - "hexadecimal": isHexadecimal, - "hexcolor": isHEXColor, - "rgb": isRGB, - "rgba": isRGBA, - "hsl": isHSL, - "hsla": isHSLA, - "e164": isE164, - "email": isEmail, - "url": isURL, - "uri": isURI, - "urn_rfc2141": isUrnRFC2141, // RFC 2141 - "file": isFile, - "base64": isBase64, - "base64url": isBase64URL, - "contains": contains, - "containsany": containsAny, - "containsrune": containsRune, - "excludes": excludes, - "excludesall": excludesAll, - "excludesrune": excludesRune, - "startswith": startsWith, - "endswith": endsWith, - "isbn": isISBN, - "isbn10": isISBN10, - "isbn13": isISBN13, - "eth_addr": isEthereumAddress, - "btc_addr": isBitcoinAddress, - "btc_addr_bech32": isBitcoinBech32Address, - "uuid": isUUID, - "uuid3": isUUID3, - "uuid4": isUUID4, - "uuid5": isUUID5, - "uuid_rfc4122": isUUIDRFC4122, - "uuid3_rfc4122": isUUID3RFC4122, - "uuid4_rfc4122": isUUID4RFC4122, - "uuid5_rfc4122": isUUID5RFC4122, - "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, - "hostname": isHostnameRFC952, // RFC 952 - "hostname_rfc1123": isHostnameRFC1123, // RFC 1123 - "fqdn": isFQDN, - "unique": isUnique, - "oneof": isOneOf, - "html": isHTML, - "html_encoded": isHTMLEncoded, - "url_encoded": isURLEncoded, - "dir": isDir, - } -) - -var oneofValsCache = map[string][]string{} -var oneofValsCacheRWLock = sync.RWMutex{} - -func parseOneOfParam2(s string) []string { - oneofValsCacheRWLock.RLock() - vals, ok := oneofValsCache[s] - oneofValsCacheRWLock.RUnlock() - if !ok { - oneofValsCacheRWLock.Lock() - vals = strings.Fields(s) - oneofValsCache[s] = vals - oneofValsCacheRWLock.Unlock() - } - return vals -} - -func isURLEncoded(fl FieldLevel) bool { - return uRLEncodedRegex.MatchString(fl.Field().String()) -} - -func isHTMLEncoded(fl FieldLevel) bool { - return hTMLEncodedRegex.MatchString(fl.Field().String()) -} - -func isHTML(fl FieldLevel) bool { - return hTMLRegex.MatchString(fl.Field().String()) -} - -func isOneOf(fl FieldLevel) bool { - vals := parseOneOfParam2(fl.Param()) - - field := fl.Field() - - var v string - switch field.Kind() { - case reflect.String: - v = field.String() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - v = strconv.FormatInt(field.Int(), 10) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - v = strconv.FormatUint(field.Uint(), 10) - default: - panic(fmt.Sprintf("Bad field type %T", field.Interface())) - } - for i := 0; i < len(vals); i++ { - if vals[i] == v { - return true - } - } - return false -} - -// isUnique is the validation function for validating if each array|slice|map value is unique -func isUnique(fl FieldLevel) bool { - - field := fl.Field() - param := fl.Param() - v := reflect.ValueOf(struct{}{}) - - switch field.Kind() { - case reflect.Slice, reflect.Array: - if param == "" { - m := reflect.MakeMap(reflect.MapOf(field.Type().Elem(), v.Type())) - - for i := 0; i < field.Len(); i++ { - m.SetMapIndex(field.Index(i), v) - } - return field.Len() == m.Len() - } - - sf, ok := field.Type().Elem().FieldByName(param) - if !ok { - panic(fmt.Sprintf("Bad field name %s", param)) - } - - m := reflect.MakeMap(reflect.MapOf(sf.Type, v.Type())) - for i := 0; i < field.Len(); i++ { - m.SetMapIndex(field.Index(i).FieldByName(param), v) - } - return field.Len() == m.Len() - case reflect.Map: - m := reflect.MakeMap(reflect.MapOf(field.Type().Elem(), v.Type())) - - for _, k := range field.MapKeys() { - m.SetMapIndex(field.MapIndex(k), v) - } - return field.Len() == m.Len() - default: - panic(fmt.Sprintf("Bad field type %T", field.Interface())) - } -} - -// IsMAC is the validation function for validating if the field's value is a valid MAC address. -func isMAC(fl FieldLevel) bool { - - _, err := net.ParseMAC(fl.Field().String()) - - return err == nil -} - -// IsCIDRv4 is the validation function for validating if the field's value is a valid v4 CIDR address. -func isCIDRv4(fl FieldLevel) bool { - - ip, _, err := net.ParseCIDR(fl.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. -func isCIDRv6(fl FieldLevel) bool { - - ip, _, err := net.ParseCIDR(fl.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. -func isCIDR(fl FieldLevel) bool { - - _, _, err := net.ParseCIDR(fl.Field().String()) - - return err == nil -} - -// IsIPv4 is the validation function for validating if a value is a valid v4 IP address. -func isIPv4(fl FieldLevel) bool { - - ip := net.ParseIP(fl.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. -func isIPv6(fl FieldLevel) bool { - - ip := net.ParseIP(fl.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. -func isIP(fl FieldLevel) bool { - - ip := net.ParseIP(fl.Field().String()) - - return ip != nil -} - -// IsSSN is the validation function for validating if the field's value is a valid SSN. -func isSSN(fl FieldLevel) bool { - - field := fl.Field() - - 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. -func isLongitude(fl FieldLevel) bool { - field := fl.Field() - - var v string - switch field.Kind() { - case reflect.String: - v = field.String() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - v = strconv.FormatInt(field.Int(), 10) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - v = strconv.FormatUint(field.Uint(), 10) - case reflect.Float32: - v = strconv.FormatFloat(field.Float(), 'f', -1, 32) - case reflect.Float64: - v = strconv.FormatFloat(field.Float(), 'f', -1, 64) - default: - panic(fmt.Sprintf("Bad field type %T", field.Interface())) - } - - return longitudeRegex.MatchString(v) -} - -// IsLatitude is the validation function for validating if the field's value is a valid latitude coordinate. -func isLatitude(fl FieldLevel) bool { - field := fl.Field() - - var v string - switch field.Kind() { - case reflect.String: - v = field.String() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - v = strconv.FormatInt(field.Int(), 10) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - v = strconv.FormatUint(field.Uint(), 10) - case reflect.Float32: - v = strconv.FormatFloat(field.Float(), 'f', -1, 32) - case reflect.Float64: - v = strconv.FormatFloat(field.Float(), 'f', -1, 64) - default: - panic(fmt.Sprintf("Bad field type %T", field.Interface())) - } - - return latitudeRegex.MatchString(v) -} - -// IsDataURI is the validation function for validating if the field's value is a valid data URI. -func isDataURI(fl FieldLevel) bool { - - uri := strings.SplitN(fl.Field().String(), ",", 2) - - if len(uri) != 2 { - return false - } - - if !dataURIRegex.MatchString(uri[0]) { - return false - } - - return base64Regex.MatchString(uri[1]) -} - -// HasMultiByteCharacter is the validation function for validating if the field's value has a multi byte character. -func hasMultiByteCharacter(fl FieldLevel) bool { - - field := fl.Field() - - 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. -func isPrintableASCII(fl FieldLevel) bool { - return printableASCIIRegex.MatchString(fl.Field().String()) -} - -// IsASCII is the validation function for validating if the field's value is a valid ASCII character. -func isASCII(fl FieldLevel) bool { - return aSCIIRegex.MatchString(fl.Field().String()) -} - -// IsUUID5 is the validation function for validating if the field's value is a valid v5 UUID. -func isUUID5(fl FieldLevel) bool { - return uUID5Regex.MatchString(fl.Field().String()) -} - -// IsUUID4 is the validation function for validating if the field's value is a valid v4 UUID. -func isUUID4(fl FieldLevel) bool { - return uUID4Regex.MatchString(fl.Field().String()) -} - -// IsUUID3 is the validation function for validating if the field's value is a valid v3 UUID. -func isUUID3(fl FieldLevel) bool { - return uUID3Regex.MatchString(fl.Field().String()) -} - -// IsUUID is the validation function for validating if the field's value is a valid UUID of any version. -func isUUID(fl FieldLevel) bool { - return uUIDRegex.MatchString(fl.Field().String()) -} - -// IsUUID5RFC4122 is the validation function for validating if the field's value is a valid RFC4122 v5 UUID. -func isUUID5RFC4122(fl FieldLevel) bool { - return uUID5RFC4122Regex.MatchString(fl.Field().String()) -} - -// IsUUID4RFC4122 is the validation function for validating if the field's value is a valid RFC4122 v4 UUID. -func isUUID4RFC4122(fl FieldLevel) bool { - return uUID4RFC4122Regex.MatchString(fl.Field().String()) -} - -// IsUUID3RFC4122 is the validation function for validating if the field's value is a valid RFC4122 v3 UUID. -func isUUID3RFC4122(fl FieldLevel) bool { - return uUID3RFC4122Regex.MatchString(fl.Field().String()) -} - -// IsUUIDRFC4122 is the validation function for validating if the field's value is a valid RFC4122 UUID of any version. -func isUUIDRFC4122(fl FieldLevel) bool { - return uUIDRFC4122Regex.MatchString(fl.Field().String()) -} - -// IsISBN is the validation function for validating if the field's value is a valid v10 or v13 ISBN. -func isISBN(fl FieldLevel) bool { - return isISBN10(fl) || isISBN13(fl) -} - -// IsISBN13 is the validation function for validating if the field's value is a valid v13 ISBN. -func isISBN13(fl FieldLevel) bool { - - s := strings.Replace(strings.Replace(fl.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. -func isISBN10(fl FieldLevel) bool { - - s := strings.Replace(strings.Replace(fl.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 -} - -// IsEthereumAddress is the validation function for validating if the field's value is a valid ethereum address based currently only on the format -func isEthereumAddress(fl FieldLevel) bool { - address := fl.Field().String() - - if !ethAddressRegex.MatchString(address) { - return false - } - - if ethaddressRegexUpper.MatchString(address) || ethAddressRegexLower.MatchString(address) { - return true - } - - // checksum validation is blocked by https://github.com/golang/crypto/pull/28 - - return true -} - -// IsBitcoinAddress is the validation function for validating if the field's value is a valid btc address -func isBitcoinAddress(fl FieldLevel) bool { - address := fl.Field().String() - - if !btcAddressRegex.MatchString(address) { - return false - } - - alphabet := []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") - - decode := [25]byte{} - - for _, n := range []byte(address) { - d := bytes.IndexByte(alphabet, n) - - for i := 24; i >= 0; i-- { - d += 58 * int(decode[i]) - decode[i] = byte(d % 256) - d /= 256 - } - } - - h := sha256.New() - _, _ = h.Write(decode[:21]) - d := h.Sum([]byte{}) - h = sha256.New() - _, _ = h.Write(d) - - validchecksum := [4]byte{} - computedchecksum := [4]byte{} - - copy(computedchecksum[:], h.Sum(d[:0])) - copy(validchecksum[:], decode[21:]) - - return validchecksum == computedchecksum -} - -// IsBitcoinBech32Address is the validation function for validating if the field's value is a valid bech32 btc address -func isBitcoinBech32Address(fl FieldLevel) bool { - address := fl.Field().String() - - if !btcLowerAddressRegexBech32.MatchString(address) && !btcUpperAddressRegexBech32.MatchString(address) { - return false - } - - am := len(address) % 8 - - if am == 0 || am == 3 || am == 5 { - return false - } - - address = strings.ToLower(address) - - alphabet := "qpzry9x8gf2tvdw0s3jn54khce6mua7l" - - hr := []int{3, 3, 0, 2, 3} // the human readable part will always be bc - addr := address[3:] - dp := make([]int, 0, len(addr)) - - for _, c := range addr { - dp = append(dp, strings.IndexRune(alphabet, c)) - } - - ver := dp[0] - - if ver < 0 || ver > 16 { - return false - } - - if ver == 0 { - if len(address) != 42 && len(address) != 62 { - return false - } - } - - values := append(hr, dp...) - - GEN := []int{0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3} - - p := 1 - - for _, v := range values { - b := p >> 25 - p = (p&0x1ffffff)<<5 ^ v - - for i := 0; i < 5; i++ { - if (b>>uint(i))&1 == 1 { - p ^= GEN[i] - } - } - } - - if p != 1 { - return false - } - - b := uint(0) - acc := 0 - mv := (1 << 5) - 1 - var sw []int - - for _, v := range dp[1 : len(dp)-6] { - acc = (acc << 5) | v - b += 5 - for b >= 8 { - b -= 8 - sw = append(sw, (acc>>b)&mv) - } - } - - if len(sw) < 2 || len(sw) > 40 { - return false - } - - return true -} - -// ExcludesRune is the validation function for validating that the field's value does not contain the rune specified within the param. -func excludesRune(fl FieldLevel) bool { - return !containsRune(fl) -} - -// ExcludesAll is the validation function for validating that the field's value does not contain any of the characters specified within the param. -func excludesAll(fl FieldLevel) bool { - return !containsAny(fl) -} - -// Excludes is the validation function for validating that the field's value does not contain the text specified within the param. -func excludes(fl FieldLevel) bool { - return !contains(fl) -} - -// ContainsRune is the validation function for validating that the field's value contains the rune specified within the param. -func containsRune(fl FieldLevel) bool { - - r, _ := utf8.DecodeRuneInString(fl.Param()) - - return strings.ContainsRune(fl.Field().String(), r) -} - -// ContainsAny is the validation function for validating that the field's value contains any of the characters specified within the param. -func containsAny(fl FieldLevel) bool { - return strings.ContainsAny(fl.Field().String(), fl.Param()) -} - -// Contains is the validation function for validating that the field's value contains the text specified within the param. -func contains(fl FieldLevel) bool { - return strings.Contains(fl.Field().String(), fl.Param()) -} - -// StartsWith is the validation function for validating that the field's value starts with the text specified within the param. -func startsWith(fl FieldLevel) bool { - return strings.HasPrefix(fl.Field().String(), fl.Param()) -} - -// EndsWith is the validation function for validating that the field's value ends with the text specified within the param. -func endsWith(fl FieldLevel) bool { - return strings.HasSuffix(fl.Field().String(), fl.Param()) -} - -// FieldContains is the validation function for validating if the current field's value contains the field specified by the param's value. -func fieldContains(fl FieldLevel) bool { - field := fl.Field() - - currentField, _, ok := fl.GetStructFieldOK() - - if !ok { - return false - } - - return strings.Contains(field.String(), currentField.String()) -} - -// FieldExcludes is the validation function for validating if the current field's value excludes the field specified by the param's value. -func fieldExcludes(fl FieldLevel) bool { - field := fl.Field() - - currentField, _, ok := fl.GetStructFieldOK() - if !ok { - return true - } - - return !strings.Contains(field.String(), currentField.String()) -} - -// 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. -func isNeField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - currentField, currentKind, ok := fl.GetStructFieldOK() - - if !ok || currentKind != kind { - return true - } - - switch kind { - - 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: - - fieldType := field.Type() - - // 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. -func isNe(fl FieldLevel) bool { - return !isEq(fl) -} - -// 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. -func isLteCrossStructField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - topField, topKind, ok := fl.GetStructFieldOK() - if !ok || topKind != kind { - return false - } - - switch kind { - - 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: - - fieldType := field.Type() - - // 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(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - topField, topKind, ok := fl.GetStructFieldOK() - if !ok || topKind != kind { - return false - } - - switch kind { - - 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: - - fieldType := field.Type() - - // 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. -func isGteCrossStructField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - topField, topKind, ok := fl.GetStructFieldOK() - if !ok || topKind != kind { - return false - } - - switch kind { - - 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: - - fieldType := field.Type() - - // 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. -func isGtCrossStructField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - topField, topKind, ok := fl.GetStructFieldOK() - if !ok || topKind != kind { - return false - } - - switch kind { - - 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: - - fieldType := field.Type() - - // 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. -func isNeCrossStructField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - topField, currentKind, ok := fl.GetStructFieldOK() - if !ok || currentKind != kind { - return true - } - - switch kind { - - 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: - - fieldType := field.Type() - - // 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. -func isEqCrossStructField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - topField, topKind, ok := fl.GetStructFieldOK() - if !ok || topKind != kind { - return false - } - - switch kind { - - 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: - - fieldType := field.Type() - - // 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. -func isEqField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - currentField, currentKind, ok := fl.GetStructFieldOK() - if !ok || currentKind != kind { - return false - } - - switch kind { - - 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: - - fieldType := field.Type() - - // 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. -func isEq(fl FieldLevel) bool { - - field := fl.Field() - param := fl.Param() - - switch field.Kind() { - - 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. -func isBase64(fl FieldLevel) bool { - return base64Regex.MatchString(fl.Field().String()) -} - -// IsBase64URL is the validation function for validating if the current field's value is a valid base64 URL safe string. -func isBase64URL(fl FieldLevel) bool { - return base64URLRegex.MatchString(fl.Field().String()) -} - -// IsURI is the validation function for validating if the current field's value is a valid URI. -func isURI(fl FieldLevel) bool { - - field := fl.Field() - - switch field.Kind() { - - 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 len(s) == 0 { - 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. -func isURL(fl FieldLevel) bool { - - field := fl.Field() - - switch field.Kind() { - - 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 len(s) == 0 { - return false - } - - url, err := url.ParseRequestURI(s) - - if err != nil || url.Scheme == "" { - return false - } - - return err == nil - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// isUrnRFC2141 is the validation function for validating if the current field's value is a valid URN as per RFC 2141. -func isUrnRFC2141(fl FieldLevel) bool { - field := fl.Field() - - switch field.Kind() { - - case reflect.String: - - str := field.String() - - _, match := urn.Parse([]byte(str)) - - return match - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// IsFile is the validation function for validating if the current field's value is a valid file path. -func isFile(fl FieldLevel) bool { - field := fl.Field() - - switch field.Kind() { - case reflect.String: - fileInfo, err := os.Stat(field.String()) - if err != nil { - return false - } - - return !fileInfo.IsDir() - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// IsE164 is the validation function for validating if the current field's value is a valid e.164 formatted phone number. -func isE164(fl FieldLevel) bool { - return e164Regex.MatchString(fl.Field().String()) -} - -// IsEmail is the validation function for validating if the current field's value is a valid email address. -func isEmail(fl FieldLevel) bool { - return emailRegex.MatchString(fl.Field().String()) -} - -// IsHSLA is the validation function for validating if the current field's value is a valid HSLA color. -func isHSLA(fl FieldLevel) bool { - return hslaRegex.MatchString(fl.Field().String()) -} - -// IsHSL is the validation function for validating if the current field's value is a valid HSL color. -func isHSL(fl FieldLevel) bool { - return hslRegex.MatchString(fl.Field().String()) -} - -// IsRGBA is the validation function for validating if the current field's value is a valid RGBA color. -func isRGBA(fl FieldLevel) bool { - return rgbaRegex.MatchString(fl.Field().String()) -} - -// IsRGB is the validation function for validating if the current field's value is a valid RGB color. -func isRGB(fl FieldLevel) bool { - return rgbRegex.MatchString(fl.Field().String()) -} - -// IsHEXColor is the validation function for validating if the current field's value is a valid HEX color. -func isHEXColor(fl FieldLevel) bool { - return hexcolorRegex.MatchString(fl.Field().String()) -} - -// IsHexadecimal is the validation function for validating if the current field's value is a valid hexadecimal. -func isHexadecimal(fl FieldLevel) bool { - return hexadecimalRegex.MatchString(fl.Field().String()) -} - -// IsNumber is the validation function for validating if the current field's value is a valid number. -func isNumber(fl FieldLevel) bool { - switch fl.Field().Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64: - return true - default: - return numberRegex.MatchString(fl.Field().String()) - } -} - -// IsNumeric is the validation function for validating if the current field's value is a valid numeric value. -func isNumeric(fl FieldLevel) bool { - switch fl.Field().Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64: - return true - default: - return numericRegex.MatchString(fl.Field().String()) - } -} - -// IsAlphanum is the validation function for validating if the current field's value is a valid alphanumeric value. -func isAlphanum(fl FieldLevel) bool { - return alphaNumericRegex.MatchString(fl.Field().String()) -} - -// IsAlpha is the validation function for validating if the current field's value is a valid alpha value. -func isAlpha(fl FieldLevel) bool { - return alphaRegex.MatchString(fl.Field().String()) -} - -// IsAlphanumUnicode is the validation function for validating if the current field's value is a valid alphanumeric unicode value. -func isAlphanumUnicode(fl FieldLevel) bool { - return alphaUnicodeNumericRegex.MatchString(fl.Field().String()) -} - -// IsAlphaUnicode is the validation function for validating if the current field's value is a valid alpha unicode value. -func isAlphaUnicode(fl FieldLevel) bool { - return alphaUnicodeRegex.MatchString(fl.Field().String()) -} - -// isDefault is the opposite of required aka hasValue -func isDefault(fl FieldLevel) bool { - return !hasValue(fl) -} - -// HasValue is the validation function for validating if the current field's value is not the default static value. -func hasValue(fl FieldLevel) bool { - field := fl.Field() - switch field.Kind() { - case reflect.Slice, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func: - return !field.IsNil() - default: - if fl.(*validate).fldIsPointer && field.Interface() != nil { - return true - } - return field.IsValid() && field.Interface() != reflect.Zero(field.Type()).Interface() - } -} - -// requireCheckField is a func for check field kind -func requireCheckFieldKind(fl FieldLevel, param string, defaultNotFoundValue bool) bool { - field := fl.Field() - kind := field.Kind() - var nullable, found bool - if len(param) > 0 { - field, kind, nullable, found = fl.GetStructFieldOKAdvanced2(fl.Parent(), param) - if !found { - return defaultNotFoundValue - } - } - switch kind { - case reflect.Invalid: - return defaultNotFoundValue - case reflect.Slice, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func: - return field.IsNil() - default: - if nullable && field.Interface() != nil { - return false - } - return field.IsValid() && field.Interface() == reflect.Zero(field.Type()).Interface() - } -} - -// RequiredWith is the validation function -// The field under validation must be present and not empty only if any of the other specified fields are present. -func requiredWith(fl FieldLevel) bool { - params := parseOneOfParam2(fl.Param()) - for _, param := range params { - if !requireCheckFieldKind(fl, param, true) { - return hasValue(fl) - } - } - return true -} - -// RequiredWithAll is the validation function -// The field under validation must be present and not empty only if all of the other specified fields are present. -func requiredWithAll(fl FieldLevel) bool { - params := parseOneOfParam2(fl.Param()) - for _, param := range params { - if requireCheckFieldKind(fl, param, true) { - return true - } - } - return hasValue(fl) -} - -// RequiredWithout is the validation function -// The field under validation must be present and not empty only when any of the other specified fields are not present. -func requiredWithout(fl FieldLevel) bool { - if requireCheckFieldKind(fl, strings.TrimSpace(fl.Param()), true) { - return hasValue(fl) - } - return true -} - -// RequiredWithoutAll is the validation function -// The field under validation must be present and not empty only when all of the other specified fields are not present. -func requiredWithoutAll(fl FieldLevel) bool { - params := parseOneOfParam2(fl.Param()) - for _, param := range params { - if !requireCheckFieldKind(fl, param, true) { - return true - } - } - return hasValue(fl) -} - -// 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. -func isGteField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - currentField, currentKind, ok := fl.GetStructFieldOK() - if !ok || currentKind != kind { - return false - } - - switch kind { - - 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: - - fieldType := field.Type() - - // 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. -func isGtField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - currentField, currentKind, ok := fl.GetStructFieldOK() - if !ok || currentKind != kind { - return false - } - - switch kind { - - 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: - - fieldType := field.Type() - - // 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. -func isGte(fl FieldLevel) bool { - - field := fl.Field() - param := fl.Param() - - switch field.Kind() { - - 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 field.Type() == timeType { - - 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. -func isGt(fl FieldLevel) bool { - - field := fl.Field() - param := fl.Param() - - switch field.Kind() { - - 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 field.Type() == timeType { - - 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. -func hasLengthOf(fl FieldLevel) bool { - - field := fl.Field() - param := fl.Param() - - switch field.Kind() { - - 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. -func hasMinOf(fl FieldLevel) bool { - return isGte(fl) -} - -// 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. -func isLteField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - currentField, currentKind, ok := fl.GetStructFieldOK() - if !ok || currentKind != kind { - return false - } - - switch kind { - - 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: - - fieldType := field.Type() - - // 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. -func isLtField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - currentField, currentKind, ok := fl.GetStructFieldOK() - if !ok || currentKind != kind { - return false - } - - switch kind { - - 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: - - fieldType := field.Type() - - // 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. -func isLte(fl FieldLevel) bool { - - field := fl.Field() - param := fl.Param() - - switch field.Kind() { - - 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 field.Type() == timeType { - - 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. -func isLt(fl FieldLevel) bool { - - field := fl.Field() - param := fl.Param() - - switch field.Kind() { - - 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 field.Type() == timeType { - - 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. -func hasMaxOf(fl FieldLevel) bool { - return isLte(fl) -} - -// IsTCP4AddrResolvable is the validation function for validating if the field's value is a resolvable tcp4 address. -func isTCP4AddrResolvable(fl FieldLevel) bool { - - if !isIP4Addr(fl) { - return false - } - - _, err := net.ResolveTCPAddr("tcp4", fl.Field().String()) - return err == nil -} - -// IsTCP6AddrResolvable is the validation function for validating if the field's value is a resolvable tcp6 address. -func isTCP6AddrResolvable(fl FieldLevel) bool { - - if !isIP6Addr(fl) { - return false - } - - _, err := net.ResolveTCPAddr("tcp6", fl.Field().String()) - - return err == nil -} - -// IsTCPAddrResolvable is the validation function for validating if the field's value is a resolvable tcp address. -func isTCPAddrResolvable(fl FieldLevel) bool { - - if !isIP4Addr(fl) && !isIP6Addr(fl) { - return false - } - - _, err := net.ResolveTCPAddr("tcp", fl.Field().String()) - - return err == nil -} - -// IsUDP4AddrResolvable is the validation function for validating if the field's value is a resolvable udp4 address. -func isUDP4AddrResolvable(fl FieldLevel) bool { - - if !isIP4Addr(fl) { - return false - } - - _, err := net.ResolveUDPAddr("udp4", fl.Field().String()) - - return err == nil -} - -// IsUDP6AddrResolvable is the validation function for validating if the field's value is a resolvable udp6 address. -func isUDP6AddrResolvable(fl FieldLevel) bool { - - if !isIP6Addr(fl) { - return false - } - - _, err := net.ResolveUDPAddr("udp6", fl.Field().String()) - - return err == nil -} - -// IsUDPAddrResolvable is the validation function for validating if the field's value is a resolvable udp address. -func isUDPAddrResolvable(fl FieldLevel) bool { - - if !isIP4Addr(fl) && !isIP6Addr(fl) { - return false - } - - _, err := net.ResolveUDPAddr("udp", fl.Field().String()) - - return err == nil -} - -// IsIP4AddrResolvable is the validation function for validating if the field's value is a resolvable ip4 address. -func isIP4AddrResolvable(fl FieldLevel) bool { - - if !isIPv4(fl) { - return false - } - - _, err := net.ResolveIPAddr("ip4", fl.Field().String()) - - return err == nil -} - -// IsIP6AddrResolvable is the validation function for validating if the field's value is a resolvable ip6 address. -func isIP6AddrResolvable(fl FieldLevel) bool { - - if !isIPv6(fl) { - return false - } - - _, err := net.ResolveIPAddr("ip6", fl.Field().String()) - - return err == nil -} - -// IsIPAddrResolvable is the validation function for validating if the field's value is a resolvable ip address. -func isIPAddrResolvable(fl FieldLevel) bool { - - if !isIP(fl) { - return false - } - - _, err := net.ResolveIPAddr("ip", fl.Field().String()) - - return err == nil -} - -// IsUnixAddrResolvable is the validation function for validating if the field's value is a resolvable unix address. -func isUnixAddrResolvable(fl FieldLevel) bool { - - _, err := net.ResolveUnixAddr("unix", fl.Field().String()) - - return err == nil -} - -func isIP4Addr(fl FieldLevel) bool { - - val := fl.Field().String() - - if idx := strings.LastIndex(val, ":"); idx != -1 { - val = val[0:idx] - } - - ip := net.ParseIP(val) - - return ip != nil && ip.To4() != nil -} - -func isIP6Addr(fl FieldLevel) bool { - - val := fl.Field().String() - - if idx := strings.LastIndex(val, ":"); idx != -1 { - if idx != 0 && val[idx-1:idx] == "]" { - val = val[1 : idx-1] - } - } - - ip := net.ParseIP(val) - - return ip != nil && ip.To4() == nil -} - -func isHostnameRFC952(fl FieldLevel) bool { - return hostnameRegexRFC952.MatchString(fl.Field().String()) -} - -func isHostnameRFC1123(fl FieldLevel) bool { - return hostnameRegexRFC1123.MatchString(fl.Field().String()) -} - -func isFQDN(fl FieldLevel) bool { - val := fl.Field().String() - - if val == "" { - return false - } - - if val[len(val)-1] == '.' { - val = val[0 : len(val)-1] - } - - return strings.ContainsAny(val, ".") && - hostnameRegexRFC952.MatchString(val) -} - -// IsDir is the validation function for validating if the current field's value is a valid directory. -func isDir(fl FieldLevel) bool { - field := fl.Field() - - if field.Kind() == reflect.String { - fileInfo, err := os.Stat(field.String()) - if err != nil { - return false - } - - return fileInfo.IsDir() - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} diff --git a/vendor/github.com/go-playground/validator/cache.go b/vendor/github.com/go-playground/validator/cache.go deleted file mode 100644 index 0d18d6e..0000000 --- a/vendor/github.com/go-playground/validator/cache.go +++ /dev/null @@ -1,322 +0,0 @@ -package validator - -import ( - "fmt" - "reflect" - "strings" - "sync" - "sync/atomic" -) - -type tagType uint8 - -const ( - typeDefault tagType = iota - typeOmitEmpty - typeIsDefault - typeNoStructLevel - typeStructOnly - typeDive - typeOr - typeKeys - typeEndKeys -) - -const ( - invalidValidation = "Invalid validation tag on field '%s'" - undefinedValidation = "Undefined validation function '%s' on field '%s'" - keysTagNotDefined = "'" + endKeysTag + "' tag encountered without a corresponding '" + keysTag + "' tag" -) - -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 []*cField - fn StructLevelFuncCtx -} - -type cField struct { - idx int - name string - altName string - namesEqual bool - cTags *cTag -} - -type cTag struct { - tag string - aliasTag string - actualAliasTag string - param string - keys *cTag // only populated when using tag's 'keys' and 'endkeys' for map key validation - next *cTag - fn FuncCtx - typeof tagType - hasTag bool - hasAlias bool - hasParam bool // true if parameter used eg. eq= where the equal sign has been set - isBlockEnd bool // indicates the current tag represents the last validation in the block - runValidationWhenNil bool -} - -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([]*cField, 0), 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 && len(fld.PkgPath) > 0 { - continue - } - - tag = fld.Tag.Get(v.tagName) - - if tag == skipValidationTag { - continue - } - - customName = fld.Name - - if v.hasTagNameFunc { - name := v.tagNameFunc(fld) - if len(name) > 0 { - 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, "", 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 = append(cs.fields, &cField{ - idx: i, - name: fld.Name, - altName: customName, - cTags: ctag, - namesEqual: fld.Name == customName, - }) - } - 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 - noAlias := len(alias) == 0 - tags := strings.Split(tag, tagSeparator) - - for i := 0; i < len(tags); i++ { - t = tags[i] - if noAlias { - alias = t - } - - // check map for alias and process new tags, otherwise process as usual - if tagsVal, found := v.aliases[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 - } - - var prevTag tagType - - if i == 0 { - current = &cTag{aliasTag: alias, hasAlias: hasAlias, hasTag: true, typeof: typeDefault} - firstCtag = current - } else { - prevTag = current.typeof - current.next = &cTag{aliasTag: alias, hasAlias: hasAlias, hasTag: true} - current = current.next - } - - switch t { - case diveTag: - current.typeof = typeDive - continue - - case keysTag: - current.typeof = typeKeys - - if i == 0 || prevTag != typeDive { - panic(fmt.Sprintf("'%s' tag must be immediately preceded by the '%s' tag", keysTag, diveTag)) - } - - current.typeof = typeKeys - - // need to pass along only keys tag - // need to increment i to skip over the keys tags - b := make([]byte, 0, 64) - - i++ - - for ; i < len(tags); i++ { - - b = append(b, tags[i]...) - b = append(b, ',') - - if tags[i] == endKeysTag { - break - } - } - - current.keys, _ = v.parseFieldTagsRecursive(string(b[:len(b)-1]), fieldName, "", false) - continue - - case endKeysTag: - current.typeof = typeEndKeys - - // if there are more in tags then there was no keysTag defined - // and an error should be thrown - if i != len(tags)-1 { - panic(keysTagNotDefined) - } - return - - case omitempty: - current.typeof = typeOmitEmpty - continue - - case structOnlyTag: - current.typeof = typeStructOnly - continue - - case noStructLevelTag: - current.typeof = typeNoStructLevel - continue - - default: - if t == isdefault { - current.typeof = typeIsDefault - } - // 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.hasParam = len(vals) > 1 - - current.tag = vals[0] - if len(current.tag) == 0 { - panic(strings.TrimSpace(fmt.Sprintf(invalidValidation, fieldName))) - } - - if wrapper, ok := v.validations[current.tag]; ok { - current.fn = wrapper.fn - current.runValidationWhenNil = wrapper.runValidatinOnNil - } else { - panic(strings.TrimSpace(fmt.Sprintf(undefinedValidation, current.tag, fieldName))) - } - - if len(orVals) > 1 { - current.typeof = typeOr - } - - if len(vals) > 1 { - current.param = strings.Replace(strings.Replace(vals[1], utf8HexComma, ",", -1), utf8Pipe, "|", -1) - } - } - current.isBlockEnd = true - } - } - return -} - -func (v *Validate) fetchCacheTag(tag string) *cTag { - // find cached tag - ctag, found := v.tagCache.Get(tag) - if !found { - 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, found = v.tagCache.Get(tag) - if !found { - ctag, _ = v.parseFieldTagsRecursive(tag, "", "", false) - v.tagCache.Set(tag, ctag) - } - } - return ctag -} diff --git a/vendor/github.com/go-playground/validator/doc.go b/vendor/github.com/go-playground/validator/doc.go deleted file mode 100644 index 7ad9dea..0000000 --- a/vendor/github.com/go-playground/validator/doc.go +++ /dev/null @@ -1,1111 +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. - -see more examples https://github.com/go-playground/validator/tree/v9/_examples - -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 InvalidValidationError for bad validation input, 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 check if error is -InvalidValidationError ( if necessary, most of the time it isn't ) type cast -it to type ValidationErrors like so err.(validator.ValidationErrors). - -Custom Validation Functions - -Custom Validation functions can be added. Example: - - // Structure - func customFunc(fl validator.FieldLevel) bool { - - if fl.Field().String() == "invalid" { - 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 - - gtecsfield - - 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.VarWithValue(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 'or' validation tags deparator. 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 useful if inside of your 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 - -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. dive has some sub-tags, 'keys' & 'endkeys', please see -the Keys & EndKeys section just below. - - 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 - -Keys & EndKeys - -These are to be used together directly after the dive tag and tells the validator -that anything between 'keys' and 'endkeys' applies to the keys of a map and not the -values; think of it like the 'dive' tag, but for map keys instead of values. -Multidimensional nesting is also supported, each level you wish to validate will -require another 'keys' and 'endkeys' tag. These tags are only valid for maps. - - Usage: dive,keys,othertagvalidation(s),endkeys,valuevalidationtags - -Example #1 - - map[string]string with validation tag "gt=0,dive,keys,eg=1|eq=2,endkeys,required" - // gt=0 will be applied to the map itself - // eg=1|eq=2 will be applied to the map keys - // required will be applied to map values - -Example #2 - - map[[2]string]string with validation tag "gt=0,dive,keys,dive,eq=1|eq=2,endkeys,required" - // gt=0 will be applied to the map itself - // eg=1|eq=2 will be applied to each array element in the the map keys - // required will be applied to map values - -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 - -Required With - -The field under validation must be present and not empty only if any -of the other specified fields are present. For strings ensures value is -not "". For slices, maps, pointers, interfaces, channels and functions -ensures the value is not nil. - - Usage: required_with - -Examples: - - // require the field if the Field1 is present: - Usage: required_with=Field1 - - // require the field if the Field1 or Field2 is present: - Usage: required_with=Field1 Field2 - -Required With All - -The field under validation must be present and not empty only if all -of the other specified fields are present. For strings ensures value is -not "". For slices, maps, pointers, interfaces, channels and functions -ensures the value is not nil. - - Usage: required_with_all - -Example: - - // require the field if the Field1 and Field2 is present: - Usage: required_with_all=Field1 Field2 - -Required Without - -The field under validation must be present and not empty only when any -of the other specified fields are not present. For strings ensures value is -not "". For slices, maps, pointers, interfaces, channels and functions -ensures the value is not nil. - - Usage: required_without - -Examples: - - // require the field if the Field1 is not present: - Usage: required_without=Field1 - - // require the field if the Field1 or Field2 is not present: - Usage: required_without=Field1 Field2 - -Required Without All - -The field under validation must be present and not empty only when all -of the other specified fields are not present. For strings ensures value is -not "". For slices, maps, pointers, interfaces, channels and functions -ensures the value is not nil. - - Usage: required_without_all - -Example: - - // require the field if the Field1 and Field2 is not present: - Usage: required_without_all=Field1 Field2 - -Is Default - -This validates that the value is the default value and is almost the -opposite of required. - - Usage: isdefault - -Length - -For numbers, length 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 - -Minimum - -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 - -One Of - -For strings, ints, and uints, oneof will ensure that the value -is one of the values in the parameter. The parameter should be -a list of values separated by whitespace. Values may be -strings or numbers. - - Usage: oneof=red green - oneof=5 7 9 - -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.VarWithValue(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.VarWithValue(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.VarWithValue(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.VarWithValue(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.VarWithValue(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.VarWithValue(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 - -Field Contains Another Field - -This does the same as contains except for struct fields. It should only be used -with string types. See the behavior of reflect.Value.String() for behavior on -other types. - - Usage: containsfield=InnerStructField.Field - -Field Excludes Another Field - -This does the same as excludes except for struct fields. It should only be used -with string types. See the behavior of reflect.Value.String() for behavior on -other types. - - Usage: excludesfield=InnerStructField.Field - -Unique - -For arrays & slices, unique will ensure that there are no duplicates. -For maps, unique will ensure that there are no duplicate values. -For slices of struct, unique will ensure that there are no duplicate values -in a field of the struct specified via a parameter. - - // For arrays, slices, and maps: - Usage: unique - - // For slices of struct: - Usage: unique=field - -Alpha Only - -This validates that a string value contains ASCII alpha characters only - - Usage: alpha - -Alphanumeric - -This validates that a string value contains ASCII alphanumeric characters only - - Usage: alphanum - -Alpha Unicode - -This validates that a string value contains unicode alpha characters only - - Usage: alphaunicode - -Alphanumeric Unicode - -This validates that a string value contains unicode alphanumeric characters only - - Usage: alphanumunicode - -Numeric - -This validates that a string value contains a basic numeric value. -basic excludes exponents etc... -for integers or float it returns true. - - 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 possibilities. - - Usage: email - -File path - -This validates that a string value contains a valid file path and that -the file exists on the machine. -This is done using os.Stat, which is a platform independent function. - - Usage: file - -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 - -Urn RFC 2141 String - -This validataes that a string value contains a valid URN -according to the RFC 2141 spec. - - Usage: urn_rfc2141 - -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 - -Base64URL String - -This validates that a string value contains a valid base64 URL safe value -according the the RFC4648 spec. -Although an empty string is a valid base64 URL safe value, 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: base64url - -Bitcoin Address - -This validates that a string value contains a valid bitcoin address. -The format of the string is checked to ensure it matches one of the three formats -P2PKH, P2SH and performs checksum validation. - - Usage: btc_addr - -Bitcoin Bech32 Address (segwit) - -This validates that a string value contains a valid bitcoin Bech32 address as defined -by bip-0173 (https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki) -Special thanks to Pieter Wuille for providng reference implementations. - - Usage: btc_addr_bech32 - -Ethereum Address - -This validates that a string value contains a valid ethereum address. -The format of the string is checked to ensure it matches the standard Ethereum address format -Full validation is blocked by https://github.com/golang/crypto/pull/28 - - Usage: eth_addr - -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=@ - -Starts With - -This validates that a string value starts with the supplied string value - - Usage: startswith=hello - -Ends With - -This validates that a string value ends with the supplied string value - - Usage: endswith=goodbye - -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. Uppercase UUID values will not pass - use `uuid_rfc4122` instead. - - Usage: uuid - -Universally Unique Identifier UUID v3 - -This validates that a string value contains a valid version 3 UUID. Uppercase UUID values will not pass - use `uuid3_rfc4122` instead. - - Usage: uuid3 - -Universally Unique Identifier UUID v4 - -This validates that a string value contains a valid version 4 UUID. Uppercase UUID values will not pass - use `uuid4_rfc4122` instead. - - Usage: uuid4 - -Universally Unique Identifier UUID v5 - -This validates that a string value contains a valid version 5 UUID. Uppercase UUID values will not pass - use `uuid5_rfc4122` instead. - - 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: printascii - -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 Address. - - Usage: ip - -Internet Protocol Address IPv4 - -This validates that a string value contains a valid v4 IP Address. - - Usage: ipv4 - -Internet Protocol Address IPv6 - -This validates that a string value contains a valid v6 IP Address. - - Usage: ipv6 - -Classless Inter-Domain Routing CIDR - -This validates that a string value contains a valid CIDR Address. - - Usage: cidr - -Classless Inter-Domain Routing CIDRv4 - -This validates that a string value contains a valid v4 CIDR Address. - - Usage: cidrv4 - -Classless Inter-Domain Routing CIDRv6 - -This validates that a string value contains a valid v6 CIDR Address. - - Usage: cidrv6 - -Transmission Control Protocol Address TCP - -This validates that a string value contains a valid resolvable TCP Address. - - Usage: tcp_addr - -Transmission Control Protocol Address TCPv4 - -This validates that a string value contains a valid resolvable v4 TCP Address. - - Usage: tcp4_addr - -Transmission Control Protocol Address TCPv6 - -This validates that a string value contains a valid resolvable v6 TCP Address. - - Usage: tcp6_addr - -User Datagram Protocol Address UDP - -This validates that a string value contains a valid resolvable UDP Address. - - Usage: udp_addr - -User Datagram Protocol Address UDPv4 - -This validates that a string value contains a valid resolvable v4 UDP Address. - - Usage: udp4_addr - -User Datagram Protocol Address UDPv6 - -This validates that a string value contains a valid resolvable v6 UDP Address. - - Usage: udp6_addr - -Internet Protocol Address IP - -This validates that a string value contains a valid resolvable IP Address. - - Usage: ip_addr - -Internet Protocol Address IPv4 - -This validates that a string value contains a valid resolvable v4 IP Address. - - Usage: ip4_addr - -Internet Protocol Address IPv6 - -This validates that a string value contains a valid resolvable v6 IP Address. - - Usage: ip6_addr - -Unix domain socket end point Address - -This validates that a string value contains a valid Unix Address. - - Usage: unix_addr - -Media Access Control Address MAC - -This validates that a string value contains a valid MAC Address. - - Usage: mac - -Note: See Go's ParseMAC for accepted formats and types: - - http://golang.org/src/net/mac.go?s=866:918#L29 - -Hostname RFC 952 - -This validates that a string value is a valid Hostname according to RFC 952 https://tools.ietf.org/html/rfc952 - - Usage: hostname - -Hostname RFC 1123 - -This validates that a string value is a valid Hostname according to RFC 1123 https://tools.ietf.org/html/rfc1123 - - Usage: hostname_rfc1123 or if you want to continue to use 'hostname' in your tags, create an alias. - -Full Qualified Domain Name (FQDN) - -This validates that a string value contains a valid FQDN. - - Usage: fqdn - -HTML Tags - -This validates that a string value appears to be an HTML element tag -including those described at https://developer.mozilla.org/en-US/docs/Web/HTML/Element - - Usage: html - -HTML Encoded - -This validates that a string value is a proper character reference in decimal -or hexadecimal format - - Usage: html_encoded - -URL Encoded - -This validates that a string value is percent-encoded (URL encoded) according -to https://tools.ietf.org/html/rfc3986#section-2.1 - - Usage: url_encoded - -Directory - -This validates that a string value contains a valid directory and that -it exists on the machine. -This is done using os.Stat, which is a platform independent function. - - Usage: dir - -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 philosophy - 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! - -Non standard validators - -A collection of validation rules that are frequently needed but are more -complex than the ones found in the baked in validators. -A non standard validator must be registered manually like you would -with your own custom validation functions. - -Example of registration and use: - - type Test struct { - TestField string `validate:"yourtag"` - } - - t := &Test{ - TestField: "Test" - } - - validate := validator.New() - validate.RegisterValidation("yourtag", validators.NotBlank) - -Here is a list of the current non standard validators: - - NotBlank - This validates that the value is not blank or with length zero. - For strings ensures they do not contain only spaces. For channels, maps, slices and arrays - ensures they don't have zero length. For others, a non empty value is required. - - Usage: notblank - -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/github.com/go-playground/validator/errors.go b/vendor/github.com/go-playground/validator/errors.go deleted file mode 100644 index 46c24c9..0000000 --- a/vendor/github.com/go-playground/validator/errors.go +++ /dev/null @@ -1,272 +0,0 @@ -package validator - -import ( - "bytes" - "fmt" - "reflect" - "strings" - - ut "github.com/go-playground/universal-translator" -) - -const ( - fieldErrMsg = "Key: '%s' Error:Field validation for '%s' failed on the '%s' tag" -) - -// ValidationErrorsTranslations is the translation return type -type ValidationErrorsTranslations map[string]string - -// InvalidValidationError describes an invalid argument passed to -// `Struct`, `StructExcept`, StructPartial` or `Field` -type InvalidValidationError struct { - Type reflect.Type -} - -// Error returns InvalidValidationError message -func (e *InvalidValidationError) Error() string { - - if e.Type == nil { - return "validator: (nil)" - } - - return "validator: (nil " + e.Type.String() + ")" -} - -// ValidationErrors is an array of FieldError's -// for use in custom error messages post validation. -type ValidationErrors []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 array -func (ve ValidationErrors) Error() string { - - buff := bytes.NewBufferString("") - - var fe *fieldError - - for i := 0; i < len(ve); i++ { - - fe = ve[i].(*fieldError) - buff.WriteString(fe.Error()) - buff.WriteString("\n") - } - - return strings.TrimSpace(buff.String()) -} - -// Translate translates all of the ValidationErrors -func (ve ValidationErrors) Translate(ut ut.Translator) ValidationErrorsTranslations { - - trans := make(ValidationErrorsTranslations) - - var fe *fieldError - - for i := 0; i < len(ve); i++ { - fe = ve[i].(*fieldError) - - // // in case an Anonymous struct was used, ensure that the key - // // would be 'Username' instead of ".Username" - // if len(fe.ns) > 0 && fe.ns[:1] == "." { - // trans[fe.ns[1:]] = fe.Translate(ut) - // continue - // } - - trans[fe.ns] = fe.Translate(ut) - } - - return trans -} - -// FieldError contains all functions to get error details -type FieldError interface { - - // returns the validation tag that failed. if the - // validation was an alias, this will return the - // alias name and not the underlying tag that failed. - // - // eg. alias "iscolor": "hexcolor|rgb|rgba|hsl|hsla" - // will return "iscolor" - Tag() string - - // returns the validation tag that failed, even if an - // alias the actual tag within the alias will be returned. - // If an 'or' validation fails the entire or will be returned. - // - // eg. alias "iscolor": "hexcolor|rgb|rgba|hsl|hsla" - // will return "hexcolor|rgb|rgba|hsl|hsla" - ActualTag() string - - // returns the namespace for the field error, with the tag - // name taking precedence over the fields actual name. - // - // eg. JSON name "User.fname" - // - // See StructNamespace() for a version that returns actual names. - // - // NOTE: this field can be blank when validating a single primitive field - // using validate.Field(...) as there is no way to extract it's name - Namespace() string - - // returns the namespace for the field error, with the fields - // actual name. - // - // eq. "User.FirstName" see Namespace for comparison - // - // NOTE: this field can be blank when validating a single primitive field - // using validate.Field(...) as there is no way to extract it's name - StructNamespace() string - - // returns the fields name with the tag name taking precedence over the - // fields actual name. - // - // eq. JSON name "fname" - // see StructField for comparison - Field() string - - // returns the fields actual name from the struct, when able to determine. - // - // eq. "FirstName" - // see Field for comparison - StructField() string - - // returns the actual fields value in case needed for creating the error - // message - Value() interface{} - - // returns the param value, in string form for comparison; this will also - // help with generating an error message - Param() string - - // Kind returns the Field's reflect Kind - // - // eg. time.Time's kind is a struct - Kind() reflect.Kind - - // Type returns the Field's reflect Type - // - // // eg. time.Time's type is time.Time - Type() reflect.Type - - // returns the FieldError's translated error - // from the provided 'ut.Translator' and registered 'TranslationFunc' - // - // NOTE: if no registered translator can be found it returns the same as - // calling fe.Error() - Translate(ut ut.Translator) string -} - -// compile time interface checks -var _ FieldError = new(fieldError) -var _ error = new(fieldError) - -// fieldError contains a single field's validation error along -// with other properties that may be needed for error message creation -// it complies with the FieldError interface -type fieldError struct { - v *Validate - tag string - actualTag string - ns string - structNs string - fieldLen uint8 - structfieldLen uint8 - value interface{} - param string - kind reflect.Kind - typ reflect.Type -} - -// Tag returns the validation tag that failed. -func (fe *fieldError) Tag() string { - return fe.tag -} - -// ActualTag returns the validation tag that failed, even if an -// alias the actual tag within the alias will be returned. -func (fe *fieldError) ActualTag() string { - return fe.actualTag -} - -// Namespace returns the namespace for the field error, with the tag -// name taking precedence over the fields actual name. -func (fe *fieldError) Namespace() string { - return fe.ns -} - -// StructNamespace returns the namespace for the field error, with the fields -// actual name. -func (fe *fieldError) StructNamespace() string { - return fe.structNs -} - -// Field returns the fields name with the tag name taking precedence over the -// fields actual name. -func (fe *fieldError) Field() string { - - return fe.ns[len(fe.ns)-int(fe.fieldLen):] - // // return fe.field - // fld := fe.ns[len(fe.ns)-int(fe.fieldLen):] - - // log.Println("FLD:", fld) - - // if len(fld) > 0 && fld[:1] == "." { - // return fld[1:] - // } - - // return fld -} - -// returns the fields actual name from the struct, when able to determine. -func (fe *fieldError) StructField() string { - // return fe.structField - return fe.structNs[len(fe.structNs)-int(fe.structfieldLen):] -} - -// Value returns the actual fields value in case needed for creating the error -// message -func (fe *fieldError) Value() interface{} { - return fe.value -} - -// Param returns the param value, in string form for comparison; this will -// also help with generating an error message -func (fe *fieldError) Param() string { - return fe.param -} - -// Kind returns the Field's reflect Kind -func (fe *fieldError) Kind() reflect.Kind { - return fe.kind -} - -// Type returns the Field's reflect Type -func (fe *fieldError) Type() reflect.Type { - return fe.typ -} - -// Error returns the fieldError's error message -func (fe *fieldError) Error() string { - return fmt.Sprintf(fieldErrMsg, fe.ns, fe.Field(), fe.tag) -} - -// Translate returns the FieldError's translated error -// from the provided 'ut.Translator' and registered 'TranslationFunc' -// -// NOTE: is not registered translation can be found it returns the same -// as calling fe.Error() -func (fe *fieldError) Translate(ut ut.Translator) string { - - m, ok := fe.v.transTagFunc[ut] - if !ok { - return fe.Error() - } - - fn, ok := m[fe.tag] - if !ok { - return fe.Error() - } - - return fn(ut, fe) -} diff --git a/vendor/github.com/go-playground/validator/field_level.go b/vendor/github.com/go-playground/validator/field_level.go deleted file mode 100644 index f0e2a9a..0000000 --- a/vendor/github.com/go-playground/validator/field_level.go +++ /dev/null @@ -1,119 +0,0 @@ -package validator - -import "reflect" - -// FieldLevel contains all the information and helper functions -// to validate a field -type FieldLevel interface { - // returns the top level struct, if any - Top() reflect.Value - - // returns the current fields parent struct, if any or - // the comparison value if called 'VarWithValue' - Parent() reflect.Value - - // returns current field for validation - Field() reflect.Value - - // returns the field's name with the tag - // name taking precedence over the fields actual name. - FieldName() string - - // returns the struct field's name - StructFieldName() string - - // returns param for validation against current field - Param() string - - // GetTag returns the current validations tag name - GetTag() string - - // 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. - ExtractType(field reflect.Value) (value reflect.Value, kind reflect.Kind, nullable bool) - - // traverses the parent struct to retrieve a specific field denoted by the provided namespace - // in the param 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. - // - // Deprecated: Use GetStructFieldOK2() instead which also return if the value is nullable. - GetStructFieldOK() (reflect.Value, reflect.Kind, bool) - - // GetStructFieldOKAdvanced is the same as GetStructFieldOK except that it accepts the parent struct to start looking for - // the field and namespace allowing more extensibility for validators. - // - // Deprecated: Use GetStructFieldOKAdvanced2() instead which also return if the value is nullable. - GetStructFieldOKAdvanced(val reflect.Value, namespace string) (reflect.Value, reflect.Kind, bool) - - // traverses the parent struct to retrieve a specific field denoted by the provided namespace - // in the param and returns the field, field kind, if it's a nullable type 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. - GetStructFieldOK2() (reflect.Value, reflect.Kind, bool, bool) - - // GetStructFieldOKAdvanced is the same as GetStructFieldOK except that it accepts the parent struct to start looking for - // the field and namespace allowing more extensibility for validators. - GetStructFieldOKAdvanced2(val reflect.Value, namespace string) (reflect.Value, reflect.Kind, bool, bool) -} - -var _ FieldLevel = new(validate) - -// Field returns current field for validation -func (v *validate) Field() reflect.Value { - return v.flField -} - -// FieldName returns the field's name with the tag -// name taking precedence over the fields actual name. -func (v *validate) FieldName() string { - return v.cf.altName -} - -// GetTag returns the current validations tag name -func (v *validate) GetTag() string { - return v.ct.tag -} - -// StructFieldName returns the struct field's name -func (v *validate) StructFieldName() string { - return v.cf.name -} - -// Param returns param for validation against current field -func (v *validate) Param() string { - return v.ct.param -} - -// GetStructFieldOK returns Param returns param for validation against current field -// -// Deprecated: Use GetStructFieldOK2() instead which also return if the value is nullable. -func (v *validate) GetStructFieldOK() (reflect.Value, reflect.Kind, bool) { - current, kind, _, found := v.getStructFieldOKInternal(v.slflParent, v.ct.param) - return current, kind, found -} - -// GetStructFieldOKAdvanced is the same as GetStructFieldOK except that it accepts the parent struct to start looking for -// the field and namespace allowing more extensibility for validators. -// -// Deprecated: Use GetStructFieldOKAdvanced2() instead which also return if the value is nullable. -func (v *validate) GetStructFieldOKAdvanced(val reflect.Value, namespace string) (reflect.Value, reflect.Kind, bool) { - current, kind, _, found := v.GetStructFieldOKAdvanced2(val, namespace) - return current, kind, found -} - -// GetStructFieldOK returns Param returns param for validation against current field -func (v *validate) GetStructFieldOK2() (reflect.Value, reflect.Kind, bool, bool) { - return v.getStructFieldOKInternal(v.slflParent, v.ct.param) -} - -// GetStructFieldOKAdvanced is the same as GetStructFieldOK except that it accepts the parent struct to start looking for -// the field and namespace allowing more extensibility for validators. -func (v *validate) GetStructFieldOKAdvanced2(val reflect.Value, namespace string) (reflect.Value, reflect.Kind, bool, bool) { - return v.getStructFieldOKInternal(val, namespace) -} diff --git a/vendor/github.com/go-playground/validator/logo.png b/vendor/github.com/go-playground/validator/logo.png deleted file mode 100644 index 355000f..0000000 Binary files a/vendor/github.com/go-playground/validator/logo.png and /dev/null differ diff --git a/vendor/github.com/go-playground/validator/regexes.go b/vendor/github.com/go-playground/validator/regexes.go deleted file mode 100644 index 7ba7c73..0000000 --- a/vendor/github.com/go-playground/validator/regexes.go +++ /dev/null @@ -1,97 +0,0 @@ -package validator - -import "regexp" - -const ( - alphaRegexString = "^[a-zA-Z]+$" - alphaNumericRegexString = "^[a-zA-Z0-9]+$" - alphaUnicodeRegexString = "^[\\p{L}]+$" - alphaUnicodeNumericRegexString = "^[\\p{L}\\p{N}]+$" - 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}])))\\.?$" - e164RegexString = "^\\+[1-9]?[0-9]{7,14}$" - base64RegexString = "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$" - base64URLRegexString = "^(?:[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}$" - uUID3RFC4122RegexString = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-3[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" - uUID4RFC4122RegexString = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$" - uUID5RFC4122RegexString = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-5[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$" - uUIDRFC4122RegexString = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-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 = `^[0-9]{3}[ -]?(0[1-9]|[1-9][0-9])[ -]?([1-9][0-9]{3}|[0-9][1-9][0-9]{2}|[0-9]{2}[1-9][0-9]|[0-9]{3}[1-9])$` - hostnameRegexStringRFC952 = `^[a-zA-Z][a-zA-Z0-9\-\.]+[a-zA-Z0-9]$` // https://tools.ietf.org/html/rfc952 - hostnameRegexStringRFC1123 = `^[a-zA-Z0-9][a-zA-Z0-9\-\.]+[a-zA-Z0-9]$` // accepts hostname starting with a digit https://tools.ietf.org/html/rfc1123 - btcAddressRegexString = `^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$` // bitcoin address - btcAddressUpperRegexStringBech32 = `^BC1[02-9AC-HJ-NP-Z]{7,76}$` // bitcoin bech32 address https://en.bitcoin.it/wiki/Bech32 - btcAddressLowerRegexStringBech32 = `^bc1[02-9ac-hj-np-z]{7,76}$` // bitcoin bech32 address https://en.bitcoin.it/wiki/Bech32 - ethAddressRegexString = `^0x[0-9a-fA-F]{40}$` - ethAddressUpperRegexString = `^0x[0-9A-F]{40}$` - ethAddressLowerRegexString = `^0x[0-9a-f]{40}$` - uRLEncodedRegexString = `(%[A-Fa-f0-9]{2})` - hTMLEncodedRegexString = `&#[x]?([0-9a-fA-F]{2})|(>)|(<)|(")|(&)+[;]?` - hTMLRegexString = `<[/]?([a-zA-Z]+).*?>` -) - -var ( - alphaRegex = regexp.MustCompile(alphaRegexString) - alphaNumericRegex = regexp.MustCompile(alphaNumericRegexString) - alphaUnicodeRegex = regexp.MustCompile(alphaUnicodeRegexString) - alphaUnicodeNumericRegex = regexp.MustCompile(alphaUnicodeNumericRegexString) - 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) - e164Regex = regexp.MustCompile(e164RegexString) - emailRegex = regexp.MustCompile(emailRegexString) - base64Regex = regexp.MustCompile(base64RegexString) - base64URLRegex = regexp.MustCompile(base64URLRegexString) - iSBN10Regex = regexp.MustCompile(iSBN10RegexString) - iSBN13Regex = regexp.MustCompile(iSBN13RegexString) - uUID3Regex = regexp.MustCompile(uUID3RegexString) - uUID4Regex = regexp.MustCompile(uUID4RegexString) - uUID5Regex = regexp.MustCompile(uUID5RegexString) - uUIDRegex = regexp.MustCompile(uUIDRegexString) - uUID3RFC4122Regex = regexp.MustCompile(uUID3RFC4122RegexString) - uUID4RFC4122Regex = regexp.MustCompile(uUID4RFC4122RegexString) - uUID5RFC4122Regex = regexp.MustCompile(uUID5RFC4122RegexString) - uUIDRFC4122Regex = regexp.MustCompile(uUIDRFC4122RegexString) - 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) - hostnameRegexRFC952 = regexp.MustCompile(hostnameRegexStringRFC952) - hostnameRegexRFC1123 = regexp.MustCompile(hostnameRegexStringRFC1123) - btcAddressRegex = regexp.MustCompile(btcAddressRegexString) - btcUpperAddressRegexBech32 = regexp.MustCompile(btcAddressUpperRegexStringBech32) - btcLowerAddressRegexBech32 = regexp.MustCompile(btcAddressLowerRegexStringBech32) - ethAddressRegex = regexp.MustCompile(ethAddressRegexString) - ethaddressRegexUpper = regexp.MustCompile(ethAddressUpperRegexString) - ethAddressRegexLower = regexp.MustCompile(ethAddressLowerRegexString) - uRLEncodedRegex = regexp.MustCompile(uRLEncodedRegexString) - hTMLEncodedRegex = regexp.MustCompile(hTMLEncodedRegexString) - hTMLRegex = regexp.MustCompile(hTMLRegexString) -) diff --git a/vendor/github.com/go-playground/validator/struct_level.go b/vendor/github.com/go-playground/validator/struct_level.go deleted file mode 100644 index 57691ee..0000000 --- a/vendor/github.com/go-playground/validator/struct_level.go +++ /dev/null @@ -1,175 +0,0 @@ -package validator - -import ( - "context" - "reflect" -) - -// StructLevelFunc accepts all values needed for struct level validation -type StructLevelFunc func(sl StructLevel) - -// StructLevelFuncCtx accepts all values needed for struct level validation -// but also allows passing of contextual validation information via context.Context. -type StructLevelFuncCtx func(ctx context.Context, sl StructLevel) - -// wrapStructLevelFunc wraps normal StructLevelFunc makes it compatible with StructLevelFuncCtx -func wrapStructLevelFunc(fn StructLevelFunc) StructLevelFuncCtx { - return func(ctx context.Context, sl StructLevel) { - fn(sl) - } -} - -// StructLevel contains all the information and helper functions -// to validate a struct -type StructLevel interface { - - // returns the main validation object, in case one wants to call validations internally. - // this is so you don't have to use anonymous functions to get access to the validate - // instance. - Validator() *Validate - - // returns the top level struct, if any - Top() reflect.Value - - // returns the current fields parent struct, if any - Parent() reflect.Value - - // returns the current struct. - Current() reflect.Value - - // ExtractType gets the actual underlying type of field value. - // It will dive into pointers, customTypes and return you the - // underlying value and its kind. - ExtractType(field reflect.Value) (value reflect.Value, kind reflect.Kind, nullable bool) - - // reports an error just by passing the field and tag information - // - // NOTES: - // - // fieldName and altName get appended to the existing namespace that - // validator is on. e.g. pass 'FirstName' or 'Names[0]' depending - // on the nesting - // - // tag can be an existing validation tag or just something you make up - // and process on the flip side it's up to you. - ReportError(field interface{}, fieldName, structFieldName string, tag, param string) - - // reports an error just by passing ValidationErrors - // - // NOTES: - // - // relativeNamespace and relativeActualNamespace get appended to the - // existing namespace that validator is on. - // e.g. pass 'User.FirstName' or 'Users[0].FirstName' depending - // on the nesting. most of the time they will be blank, unless you validate - // at a level lower the the current field depth - ReportValidationErrors(relativeNamespace, relativeActualNamespace string, errs ValidationErrors) -} - -var _ StructLevel = new(validate) - -// Top returns the top level struct -// -// NOTE: this can be the same as the current struct being validated -// if not is a nested struct. -// -// this is only called when within Struct and Field Level validation and -// should not be relied upon for an acurate value otherwise. -func (v *validate) Top() reflect.Value { - return v.top -} - -// Parent returns the current structs parent -// -// NOTE: this can be the same as the current struct being validated -// if not is a nested struct. -// -// this is only called when within Struct and Field Level validation and -// should not be relied upon for an acurate value otherwise. -func (v *validate) Parent() reflect.Value { - return v.slflParent -} - -// Current returns the current struct. -func (v *validate) Current() reflect.Value { - return v.slCurrent -} - -// Validator returns the main validation object, in case one want to call validations internally. -func (v *validate) Validator() *Validate { - return v.v -} - -// ExtractType gets the actual underlying type of field value. -func (v *validate) ExtractType(field reflect.Value) (reflect.Value, reflect.Kind, bool) { - return v.extractTypeInternal(field, false) -} - -// ReportError reports an error just by passing the field and tag information -func (v *validate) ReportError(field interface{}, fieldName, structFieldName, tag, param string) { - - fv, kind, _ := v.extractTypeInternal(reflect.ValueOf(field), false) - - if len(structFieldName) == 0 { - structFieldName = fieldName - } - - v.str1 = string(append(v.ns, fieldName...)) - - if v.v.hasTagNameFunc || fieldName != structFieldName { - v.str2 = string(append(v.actualNs, structFieldName...)) - } else { - v.str2 = v.str1 - } - - if kind == reflect.Invalid { - - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: tag, - actualTag: tag, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(fieldName)), - structfieldLen: uint8(len(structFieldName)), - param: param, - kind: kind, - }, - ) - return - } - - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: tag, - actualTag: tag, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(fieldName)), - structfieldLen: uint8(len(structFieldName)), - value: fv.Interface(), - param: param, - kind: kind, - typ: fv.Type(), - }, - ) -} - -// ReportValidationErrors reports ValidationErrors obtained from running validations within the Struct Level validation. -// -// NOTE: this function prepends the current namespace to the relative ones. -func (v *validate) ReportValidationErrors(relativeNamespace, relativeStructNamespace string, errs ValidationErrors) { - - var err *fieldError - - for i := 0; i < len(errs); i++ { - - err = errs[i].(*fieldError) - err.ns = string(append(append(v.ns, relativeNamespace...), err.ns...)) - err.structNs = string(append(append(v.actualNs, relativeStructNamespace...), err.structNs...)) - - v.errs = append(v.errs, err) - } -} diff --git a/vendor/github.com/go-playground/validator/translations.go b/vendor/github.com/go-playground/validator/translations.go deleted file mode 100644 index 4d9d75c..0000000 --- a/vendor/github.com/go-playground/validator/translations.go +++ /dev/null @@ -1,11 +0,0 @@ -package validator - -import ut "github.com/go-playground/universal-translator" - -// TranslationFunc is the function type used to register or override -// custom translations -type TranslationFunc func(ut ut.Translator, fe FieldError) string - -// RegisterTranslationsFunc allows for registering of translations -// for a 'ut.Translator' for use within the 'TranslationFunc' -type RegisterTranslationsFunc func(ut ut.Translator) error diff --git a/vendor/github.com/go-playground/validator/util.go b/vendor/github.com/go-playground/validator/util.go deleted file mode 100644 index 71acbdc..0000000 --- a/vendor/github.com/go-playground/validator/util.go +++ /dev/null @@ -1,256 +0,0 @@ -package validator - -import ( - "reflect" - "strconv" - "strings" -) - -// extractTypeInternal gets the actual underlying type of field value. -// It will dive into pointers, customTypes and return you the -// underlying value and it's kind. -func (v *validate) extractTypeInternal(current reflect.Value, nullable bool) (reflect.Value, reflect.Kind, bool) { - -BEGIN: - switch current.Kind() { - case reflect.Ptr: - - nullable = true - - if current.IsNil() { - return current, reflect.Ptr, nullable - } - - current = current.Elem() - goto BEGIN - - case reflect.Interface: - - nullable = true - - if current.IsNil() { - return current, reflect.Interface, nullable - } - - current = current.Elem() - goto BEGIN - - case reflect.Invalid: - return current, reflect.Invalid, nullable - - default: - - if v.v.hasCustomFuncs { - - if fn, ok := v.v.customFuncs[current.Type()]; ok { - current = reflect.ValueOf(fn(current)) - goto BEGIN - } - } - - return current, current.Kind(), nullable - } -} - -// getStructFieldOKInternal 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) getStructFieldOKInternal(val reflect.Value, namespace string) (current reflect.Value, kind reflect.Kind, nullable bool, found bool) { - -BEGIN: - current, kind, nullable = v.ExtractType(val) - if kind == reflect.Invalid { - return - } - - if namespace == "" { - found = true - return - } - - switch kind { - - case reflect.Ptr, reflect.Interface: - return - - case reflect.Struct: - - typ := current.Type() - fld := namespace - var ns string - - if typ != timeType { - - idx := strings.Index(namespace, namespaceSeparator) - - if idx != -1 { - fld = namespace[:idx] - ns = namespace[idx+1:] - } else { - ns = "" - } - - bracketIdx := strings.Index(fld, leftBracket) - if bracketIdx != -1 { - fld = fld[:bracketIdx] - - ns = namespace[bracketIdx:] - } - - val = current.FieldByName(fld) - namespace = ns - goto BEGIN - } - - 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 - } - - startIdx := idx2 + 1 - - if startIdx < len(namespace) { - if namespace[startIdx:startIdx+1] == namespaceSeparator { - startIdx++ - } - } - - val = current.Index(arrIdx) - namespace = namespace[startIdx:] - goto BEGIN - - 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) - val = current.MapIndex(reflect.ValueOf(i)) - namespace = namespace[endIdx+1:] - - case reflect.Int8: - i, _ := strconv.ParseInt(key, 10, 8) - val = current.MapIndex(reflect.ValueOf(int8(i))) - namespace = namespace[endIdx+1:] - - case reflect.Int16: - i, _ := strconv.ParseInt(key, 10, 16) - val = current.MapIndex(reflect.ValueOf(int16(i))) - namespace = namespace[endIdx+1:] - - case reflect.Int32: - i, _ := strconv.ParseInt(key, 10, 32) - val = current.MapIndex(reflect.ValueOf(int32(i))) - namespace = namespace[endIdx+1:] - - case reflect.Int64: - i, _ := strconv.ParseInt(key, 10, 64) - val = current.MapIndex(reflect.ValueOf(i)) - namespace = namespace[endIdx+1:] - - case reflect.Uint: - i, _ := strconv.ParseUint(key, 10, 0) - val = current.MapIndex(reflect.ValueOf(uint(i))) - namespace = namespace[endIdx+1:] - - case reflect.Uint8: - i, _ := strconv.ParseUint(key, 10, 8) - val = current.MapIndex(reflect.ValueOf(uint8(i))) - namespace = namespace[endIdx+1:] - - case reflect.Uint16: - i, _ := strconv.ParseUint(key, 10, 16) - val = current.MapIndex(reflect.ValueOf(uint16(i))) - namespace = namespace[endIdx+1:] - - case reflect.Uint32: - i, _ := strconv.ParseUint(key, 10, 32) - val = current.MapIndex(reflect.ValueOf(uint32(i))) - namespace = namespace[endIdx+1:] - - case reflect.Uint64: - i, _ := strconv.ParseUint(key, 10, 64) - val = current.MapIndex(reflect.ValueOf(i)) - namespace = namespace[endIdx+1:] - - case reflect.Float32: - f, _ := strconv.ParseFloat(key, 32) - val = current.MapIndex(reflect.ValueOf(float32(f))) - namespace = namespace[endIdx+1:] - - case reflect.Float64: - f, _ := strconv.ParseFloat(key, 64) - val = current.MapIndex(reflect.ValueOf(f)) - namespace = namespace[endIdx+1:] - - case reflect.Bool: - b, _ := strconv.ParseBool(key) - val = current.MapIndex(reflect.ValueOf(b)) - namespace = namespace[endIdx+1:] - - // reflect.Type = string - default: - val = current.MapIndex(reflect.ValueOf(key)) - namespace = namespace[endIdx+1:] - } - - goto BEGIN - } - - // 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/github.com/go-playground/validator/validator.go b/vendor/github.com/go-playground/validator/validator.go deleted file mode 100644 index 342e72e..0000000 --- a/vendor/github.com/go-playground/validator/validator.go +++ /dev/null @@ -1,477 +0,0 @@ -package validator - -import ( - "context" - "fmt" - "reflect" - "strconv" -) - -// per validate construct -type validate struct { - v *Validate - top reflect.Value - ns []byte - actualNs []byte - errs ValidationErrors - includeExclude map[string]struct{} // reset only if StructPartial or StructExcept are called, no need otherwise - ffn FilterFunc - slflParent reflect.Value // StructLevel & FieldLevel - slCurrent reflect.Value // StructLevel & FieldLevel - flField reflect.Value // StructLevel & FieldLevel - cf *cField // StructLevel & FieldLevel - ct *cTag // StructLevel & FieldLevel - misc []byte // misc reusable - str1 string // misc reusable - str2 string // misc reusable - fldIsPointer bool // StructLevel & FieldLevel - isPartial bool - hasExcludes bool -} - -// parent and current will be the same the first run of validateStruct -func (v *validate) validateStruct(ctx context.Context, parent reflect.Value, current reflect.Value, typ reflect.Type, ns []byte, structNs []byte, ct *cTag) { - - cs, ok := v.v.structCache.Get(typ) - if !ok { - cs = v.v.extractStructCache(current, typ.Name()) - } - - if len(ns) == 0 && len(cs.name) != 0 { - - ns = append(ns, cs.name...) - ns = append(ns, '.') - - structNs = append(structNs, cs.name...) - structNs = append(structNs, '.') - } - - // ct is nil on top level struct, and structs as fields that have no tag info - // so if nil or if not nil and the structonly tag isn't present - if ct == nil || ct.typeof != typeStructOnly { - - var f *cField - - for i := 0; i < len(cs.fields); i++ { - - f = cs.fields[i] - - if v.isPartial { - - if v.ffn != nil { - // used with StructFiltered - if v.ffn(append(structNs, f.name...)) { - continue - } - - } else { - // used with StructPartial & StructExcept - _, ok = v.includeExclude[string(append(structNs, f.name...))] - - if (ok && v.hasExcludes) || (!ok && !v.hasExcludes) { - continue - } - } - } - - v.traverseField(ctx, parent, current.Field(f.idx), ns, structNs, f, f.cTags) - } - } - - // check if any struct level validations, after all field validations already checked. - // first iteration will have no info about nostructlevel tag, and is checked prior to - // calling the next iteration of validateStruct called from traverseField. - if cs.fn != nil { - - v.slflParent = parent - v.slCurrent = current - v.ns = ns - v.actualNs = structNs - - cs.fn(ctx, v) - } -} - -// 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(ctx context.Context, parent reflect.Value, current reflect.Value, ns []byte, structNs []byte, cf *cField, ct *cTag) { - var typ reflect.Type - var kind reflect.Kind - - current, kind, v.fldIsPointer = v.extractTypeInternal(current, false) - - switch kind { - case reflect.Ptr, reflect.Interface, reflect.Invalid: - - if ct == nil { - return - } - - if ct.typeof == typeOmitEmpty || ct.typeof == typeIsDefault { - return - } - - if ct.hasTag { - if kind == reflect.Invalid { - v.str1 = string(append(ns, cf.altName...)) - if v.v.hasTagNameFunc { - v.str2 = string(append(structNs, cf.name...)) - } else { - v.str2 = v.str1 - } - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: ct.aliasTag, - actualTag: ct.tag, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(cf.altName)), - structfieldLen: uint8(len(cf.name)), - param: ct.param, - kind: kind, - }, - ) - return - } - - v.str1 = string(append(ns, cf.altName...)) - if v.v.hasTagNameFunc { - v.str2 = string(append(structNs, cf.name...)) - } else { - v.str2 = v.str1 - } - if !ct.runValidationWhenNil { - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: ct.aliasTag, - actualTag: ct.tag, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(cf.altName)), - structfieldLen: uint8(len(cf.name)), - value: current.Interface(), - param: ct.param, - kind: kind, - typ: current.Type(), - }, - ) - return - } - } - - case reflect.Struct: - - typ = current.Type() - - if typ != timeType { - - if ct != nil { - - if ct.typeof == typeStructOnly { - goto CONTINUE - } else if ct.typeof == typeIsDefault { - // set Field Level fields - v.slflParent = parent - v.flField = current - v.cf = cf - v.ct = ct - - if !ct.fn(ctx, v) { - v.str1 = string(append(ns, cf.altName...)) - - if v.v.hasTagNameFunc { - v.str2 = string(append(structNs, cf.name...)) - } else { - v.str2 = v.str1 - } - - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: ct.aliasTag, - actualTag: ct.tag, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(cf.altName)), - structfieldLen: uint8(len(cf.name)), - value: current.Interface(), - param: ct.param, - kind: kind, - typ: typ, - }, - ) - return - } - } - - ct = ct.next - } - - if ct != nil && ct.typeof == typeNoStructLevel { - return - } - - CONTINUE: - // if len == 0 then validating using 'Var' or 'VarWithValue' - // Var - doesn't make much sense to do it that way, should call 'Struct', but no harm... - // VarWithField - this allows for validating against each field within the struct against a specific value - // pretty handy in certain situations - if len(cf.name) > 0 { - ns = append(append(ns, cf.altName...), '.') - structNs = append(append(structNs, cf.name...), '.') - } - - v.validateStruct(ctx, current, current, typ, ns, structNs, ct) - return - } - } - - if !ct.hasTag { - return - } - - typ = current.Type() - -OUTER: - for { - if ct == nil { - return - } - - switch ct.typeof { - - case typeOmitEmpty: - - // set Field Level fields - v.slflParent = parent - v.flField = current - v.cf = cf - v.ct = ct - - if !v.fldIsPointer && !hasValue(v) { - return - } - - ct = ct.next - continue - - case typeEndKeys: - return - - case typeDive: - - ct = ct.next - - // traverse slice or map here - // or panic ;) - switch kind { - case reflect.Slice, reflect.Array: - - var i64 int64 - reusableCF := &cField{} - - for i := 0; i < current.Len(); i++ { - - i64 = int64(i) - - v.misc = append(v.misc[0:0], cf.name...) - v.misc = append(v.misc, '[') - v.misc = strconv.AppendInt(v.misc, i64, 10) - v.misc = append(v.misc, ']') - - reusableCF.name = string(v.misc) - - if cf.namesEqual { - reusableCF.altName = reusableCF.name - } else { - - v.misc = append(v.misc[0:0], cf.altName...) - v.misc = append(v.misc, '[') - v.misc = strconv.AppendInt(v.misc, i64, 10) - v.misc = append(v.misc, ']') - - reusableCF.altName = string(v.misc) - } - v.traverseField(ctx, parent, current.Index(i), ns, structNs, reusableCF, ct) - } - - case reflect.Map: - - var pv string - reusableCF := &cField{} - - for _, key := range current.MapKeys() { - - pv = fmt.Sprintf("%v", key.Interface()) - - v.misc = append(v.misc[0:0], cf.name...) - v.misc = append(v.misc, '[') - v.misc = append(v.misc, pv...) - v.misc = append(v.misc, ']') - - reusableCF.name = string(v.misc) - - if cf.namesEqual { - reusableCF.altName = reusableCF.name - } else { - v.misc = append(v.misc[0:0], cf.altName...) - v.misc = append(v.misc, '[') - v.misc = append(v.misc, pv...) - v.misc = append(v.misc, ']') - - reusableCF.altName = string(v.misc) - } - - if ct != nil && ct.typeof == typeKeys && ct.keys != nil { - v.traverseField(ctx, parent, key, ns, structNs, reusableCF, ct.keys) - // can be nil when just keys being validated - if ct.next != nil { - v.traverseField(ctx, parent, current.MapIndex(key), ns, structNs, reusableCF, ct.next) - } - } else { - v.traverseField(ctx, parent, current.MapIndex(key), ns, structNs, reusableCF, 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: - - v.misc = v.misc[0:0] - - for { - - // set Field Level fields - v.slflParent = parent - v.flField = current - v.cf = cf - v.ct = ct - - if ct.fn(ctx, v) { - - // drain rest of the 'or' values, then continue or leave - for { - - ct = ct.next - - if ct == nil { - return - } - - if ct.typeof != typeOr { - continue OUTER - } - } - } - - v.misc = append(v.misc, '|') - v.misc = append(v.misc, ct.tag...) - - if ct.hasParam { - v.misc = append(v.misc, '=') - v.misc = append(v.misc, ct.param...) - } - - if ct.isBlockEnd || ct.next == nil { - // if we get here, no valid 'or' value and no more tags - v.str1 = string(append(ns, cf.altName...)) - - if v.v.hasTagNameFunc { - v.str2 = string(append(structNs, cf.name...)) - } else { - v.str2 = v.str1 - } - - if ct.hasAlias { - - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: ct.aliasTag, - actualTag: ct.actualAliasTag, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(cf.altName)), - structfieldLen: uint8(len(cf.name)), - value: current.Interface(), - param: ct.param, - kind: kind, - typ: typ, - }, - ) - - } else { - - tVal := string(v.misc)[1:] - - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: tVal, - actualTag: tVal, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(cf.altName)), - structfieldLen: uint8(len(cf.name)), - value: current.Interface(), - param: ct.param, - kind: kind, - typ: typ, - }, - ) - } - - return - } - - ct = ct.next - } - - default: - - // set Field Level fields - v.slflParent = parent - v.flField = current - v.cf = cf - v.ct = ct - - if !ct.fn(ctx, v) { - - v.str1 = string(append(ns, cf.altName...)) - - if v.v.hasTagNameFunc { - v.str2 = string(append(structNs, cf.name...)) - } else { - v.str2 = v.str1 - } - - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: ct.aliasTag, - actualTag: ct.tag, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(cf.altName)), - structfieldLen: uint8(len(cf.name)), - value: current.Interface(), - param: ct.param, - kind: kind, - typ: typ, - }, - ) - - return - } - ct = ct.next - } - } - -} diff --git a/vendor/github.com/go-playground/validator/validator_instance.go b/vendor/github.com/go-playground/validator/validator_instance.go deleted file mode 100644 index 4a89d40..0000000 --- a/vendor/github.com/go-playground/validator/validator_instance.go +++ /dev/null @@ -1,615 +0,0 @@ -package validator - -import ( - "context" - "errors" - "fmt" - "reflect" - "strings" - "sync" - "time" - - ut "github.com/go-playground/universal-translator" -) - -const ( - defaultTagName = "validate" - utf8HexComma = "0x2C" - utf8Pipe = "0x7C" - tagSeparator = "," - orSeparator = "|" - tagKeySeparator = "=" - structOnlyTag = "structonly" - noStructLevelTag = "nostructlevel" - omitempty = "omitempty" - isdefault = "isdefault" - requiredWithoutAllTag = "required_without_all" - requiredWithoutTag = "required_without" - requiredWithTag = "required_with" - requiredWithAllTag = "required_with_all" - skipValidationTag = "-" - diveTag = "dive" - keysTag = "keys" - endKeysTag = "endkeys" - requiredTag = "required" - 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 ( - timeType = reflect.TypeOf(time.Time{}) - defaultCField = &cField{namesEqual: true} -) - -// FilterFunc is the type used to filter fields using -// StructFiltered(...) function. -// returning true results in the field being filtered/skiped from -// validation -type FilterFunc func(ns []byte) bool - -// 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{} - -// TagNameFunc allows for adding of a custom tag name parser -type TagNameFunc func(field reflect.StructField) string - -type internalValidationFuncWrapper struct { - fn FuncCtx - runValidatinOnNil bool -} - -// Validate contains the validator settings and cache -type Validate struct { - tagName string - pool *sync.Pool - hasCustomFuncs bool - hasTagNameFunc bool - tagNameFunc TagNameFunc - structLevelFuncs map[reflect.Type]StructLevelFuncCtx - customFuncs map[reflect.Type]CustomTypeFunc - aliases map[string]string - validations map[string]internalValidationFuncWrapper - transTagFunc map[ut.Translator]map[string]TranslationFunc // map[]map[]TranslationFunc - tagCache *tagCache - structCache *structCache -} - -// New returns a new instance of 'validate' with sane defaults. -func New() *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: defaultTagName, - aliases: make(map[string]string, len(bakedInAliases)), - validations: make(map[string]internalValidationFuncWrapper, len(bakedInValidators)), - tagCache: tc, - structCache: sc, - } - - // must copy alias validators for separate validations to be used in each validator instance - for k, val := range bakedInAliases { - v.RegisterAlias(k, val) - } - - // must copy validators for separate validations to be used in each instance - for k, val := range bakedInValidators { - - switch k { - // these require that even if the value is nil that the validation should run, omitempty still overrides this behaviour - case requiredWithTag, requiredWithAllTag, requiredWithoutTag, requiredWithoutAllTag: - _ = v.registerValidation(k, wrapFunc(val), true, true) - default: - // no need to error check here, baked in will always be valid - _ = v.registerValidation(k, wrapFunc(val), true, false) - } - } - - v.pool = &sync.Pool{ - New: func() interface{} { - return &validate{ - v: v, - ns: make([]byte, 0, 64), - actualNs: make([]byte, 0, 64), - misc: make([]byte, 32), - } - }, - } - - return v -} - -// SetTagName allows for changing of the default tag name of 'validate' -func (v *Validate) SetTagName(name string) { - v.tagName = name -} - -// RegisterTagNameFunc registers a function to get alternate names for StructFields. -// -// eg. to use the names which have been specified for JSON representations of structs, rather than normal Go field names: -// -// validate.RegisterTagNameFunc(func(fld reflect.StructField) string { -// name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0] -// if name == "-" { -// return "" -// } -// return name -// }) -func (v *Validate) RegisterTagNameFunc(fn TagNameFunc) { - v.tagNameFunc = fn - v.hasTagNameFunc = true -} - -// RegisterValidation adds a validation with the given tag -// -// NOTES: -// - if the key already exists, the previous validation function will be replaced. -// - this method is not thread-safe it is intended that these all be registered prior to any validation -func (v *Validate) RegisterValidation(tag string, fn Func, callValidationEvenIfNull ...bool) error { - return v.RegisterValidationCtx(tag, wrapFunc(fn), callValidationEvenIfNull...) -} - -// RegisterValidationCtx does the same as RegisterValidation on accepts a FuncCtx validation -// allowing context.Context validation support. -func (v *Validate) RegisterValidationCtx(tag string, fn FuncCtx, callValidationEvenIfNull ...bool) error { - var nilCheckable bool - if len(callValidationEvenIfNull) > 0 { - nilCheckable = callValidationEvenIfNull[0] - } - return v.registerValidation(tag, fn, false, nilCheckable) -} - -func (v *Validate) registerValidation(tag string, fn FuncCtx, bakedIn bool, nilCheckable bool) error { - if len(tag) == 0 { - return errors.New("Function Key cannot be empty") - } - - if fn == nil { - return errors.New("Function cannot be empty") - } - - _, ok := restrictedTags[tag] - if !bakedIn && (ok || strings.ContainsAny(tag, restrictedTagChars)) { - panic(fmt.Sprintf(restrictedTagErr, tag)) - } - v.validations[tag] = internalValidationFuncWrapper{fn: fn, runValidatinOnNil: nilCheckable} - return nil -} - -// RegisterAlias registers a mapping of a single validation tag that -// defines a common or complex set of validation(s) to simplify adding validation -// to structs. -// -// NOTE: this function is not thread-safe it is intended that these all be registered prior to any validation -func (v *Validate) RegisterAlias(alias, tags string) { - - _, ok := restrictedTags[alias] - - if ok || strings.ContainsAny(alias, restrictedTagChars) { - panic(fmt.Sprintf(restrictedAliasErr, alias)) - } - - v.aliases[alias] = tags -} - -// 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.RegisterStructValidationCtx(wrapStructLevelFunc(fn), types...) -} - -// RegisterStructValidationCtx registers a StructLevelFuncCtx against a number of types and allows passing -// of contextual validation information via context.Context. -// -// NOTE: -// - this method is not thread-safe it is intended that these all be registered prior to any validation -func (v *Validate) RegisterStructValidationCtx(fn StructLevelFuncCtx, types ...interface{}) { - - if v.structLevelFuncs == nil { - v.structLevelFuncs = make(map[reflect.Type]StructLevelFuncCtx) - } - - for _, t := range types { - tv := reflect.ValueOf(t) - if tv.Kind() == reflect.Ptr { - t = reflect.Indirect(tv).Interface() - } - - v.structLevelFuncs[reflect.TypeOf(t)] = fn - } -} - -// 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{}) { - - if v.customFuncs == nil { - v.customFuncs = make(map[reflect.Type]CustomTypeFunc) - } - - for _, t := range types { - v.customFuncs[reflect.TypeOf(t)] = fn - } - - v.hasCustomFuncs = true -} - -// RegisterTranslation registers translations against the provided tag. -func (v *Validate) RegisterTranslation(tag string, trans ut.Translator, registerFn RegisterTranslationsFunc, translationFn TranslationFunc) (err error) { - - if v.transTagFunc == nil { - v.transTagFunc = make(map[ut.Translator]map[string]TranslationFunc) - } - - if err = registerFn(trans); err != nil { - return - } - - m, ok := v.transTagFunc[trans] - if !ok { - m = make(map[string]TranslationFunc) - v.transTagFunc[trans] = m - } - - m[tag] = translationFn - - return -} - -// Struct validates a structs exposed fields, and automatically validates nested structs, unless otherwise specified. -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) Struct(s interface{}) error { - return v.StructCtx(context.Background(), s) -} - -// StructCtx validates a structs exposed fields, and automatically validates nested structs, unless otherwise specified -// and also allows passing of context.Context for contextual validation information. -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) StructCtx(ctx context.Context, s interface{}) (err error) { - - val := reflect.ValueOf(s) - top := val - - if val.Kind() == reflect.Ptr && !val.IsNil() { - val = val.Elem() - } - - if val.Kind() != reflect.Struct || val.Type() == timeType { - return &InvalidValidationError{Type: reflect.TypeOf(s)} - } - - // good to validate - vd := v.pool.Get().(*validate) - vd.top = top - vd.isPartial = false - // vd.hasExcludes = false // only need to reset in StructPartial and StructExcept - - vd.validateStruct(ctx, top, val, val.Type(), vd.ns[0:0], vd.actualNs[0:0], nil) - - if len(vd.errs) > 0 { - err = vd.errs - vd.errs = nil - } - - v.pool.Put(vd) - - return -} - -// StructFiltered validates a structs exposed fields, that pass the FilterFunc check and automatically validates -// nested structs, unless otherwise specified. -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) StructFiltered(s interface{}, fn FilterFunc) error { - return v.StructFilteredCtx(context.Background(), s, fn) -} - -// StructFilteredCtx validates a structs exposed fields, that pass the FilterFunc check and automatically validates -// nested structs, unless otherwise specified and also allows passing of contextual validation information via -// context.Context -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) StructFilteredCtx(ctx context.Context, s interface{}, fn FilterFunc) (err error) { - val := reflect.ValueOf(s) - top := val - - if val.Kind() == reflect.Ptr && !val.IsNil() { - val = val.Elem() - } - - if val.Kind() != reflect.Struct || val.Type() == timeType { - return &InvalidValidationError{Type: reflect.TypeOf(s)} - } - - // good to validate - vd := v.pool.Get().(*validate) - vd.top = top - vd.isPartial = true - vd.ffn = fn - // vd.hasExcludes = false // only need to reset in StructPartial and StructExcept - - vd.validateStruct(ctx, top, val, val.Type(), vd.ns[0:0], vd.actualNs[0:0], nil) - - if len(vd.errs) > 0 { - err = vd.errs - vd.errs = nil - } - - v.pool.Put(vd) - - return -} - -// StructPartial validates the fields passed in only, ignoring all others. -// Fields may be provided in a namespaced fashion relative to the struct provided -// eg. NestedStruct.Field or NestedArrayField[0].Struct.Name -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) StructPartial(s interface{}, fields ...string) error { - return v.StructPartialCtx(context.Background(), s, fields...) -} - -// StructPartialCtx validates the fields passed in only, ignoring all others and allows passing of contextual -// validation validation information via context.Context -// Fields may be provided in a namespaced fashion relative to the struct provided -// eg. NestedStruct.Field or NestedArrayField[0].Struct.Name -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) StructPartialCtx(ctx context.Context, s interface{}, fields ...string) (err error) { - val := reflect.ValueOf(s) - top := val - - if val.Kind() == reflect.Ptr && !val.IsNil() { - val = val.Elem() - } - - if val.Kind() != reflect.Struct || val.Type() == timeType { - return &InvalidValidationError{Type: reflect.TypeOf(s)} - } - - // good to validate - vd := v.pool.Get().(*validate) - vd.top = top - vd.isPartial = true - vd.ffn = nil - vd.hasExcludes = false - vd.includeExclude = make(map[string]struct{}) - - typ := val.Type() - name := typ.Name() - - for _, k := range fields { - - flds := strings.Split(k, namespaceSeparator) - if len(flds) > 0 { - - vd.misc = append(vd.misc[0:0], name...) - vd.misc = append(vd.misc, '.') - - for _, s := range flds { - - idx := strings.Index(s, leftBracket) - - if idx != -1 { - for idx != -1 { - vd.misc = append(vd.misc, s[:idx]...) - vd.includeExclude[string(vd.misc)] = struct{}{} - - idx2 := strings.Index(s, rightBracket) - idx2++ - vd.misc = append(vd.misc, s[idx:idx2]...) - vd.includeExclude[string(vd.misc)] = struct{}{} - s = s[idx2:] - idx = strings.Index(s, leftBracket) - } - } else { - - vd.misc = append(vd.misc, s...) - vd.includeExclude[string(vd.misc)] = struct{}{} - } - - vd.misc = append(vd.misc, '.') - } - } - } - - vd.validateStruct(ctx, top, val, typ, vd.ns[0:0], vd.actualNs[0:0], nil) - - if len(vd.errs) > 0 { - err = vd.errs - vd.errs = nil - } - - v.pool.Put(vd) - - return -} - -// 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 -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) StructExcept(s interface{}, fields ...string) error { - return v.StructExceptCtx(context.Background(), s, fields...) -} - -// StructExceptCtx validates all fields except the ones passed in and allows passing of contextual -// validation validation information via context.Context -// Fields may be provided in a namespaced fashion relative to the struct provided -// i.e. NestedStruct.Field or NestedArrayField[0].Struct.Name -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) StructExceptCtx(ctx context.Context, s interface{}, fields ...string) (err error) { - val := reflect.ValueOf(s) - top := val - - if val.Kind() == reflect.Ptr && !val.IsNil() { - val = val.Elem() - } - - if val.Kind() != reflect.Struct || val.Type() == timeType { - return &InvalidValidationError{Type: reflect.TypeOf(s)} - } - - // good to validate - vd := v.pool.Get().(*validate) - vd.top = top - vd.isPartial = true - vd.ffn = nil - vd.hasExcludes = true - vd.includeExclude = make(map[string]struct{}) - - typ := val.Type() - name := typ.Name() - - for _, key := range fields { - - vd.misc = vd.misc[0:0] - - if len(name) > 0 { - vd.misc = append(vd.misc, name...) - vd.misc = append(vd.misc, '.') - } - - vd.misc = append(vd.misc, key...) - vd.includeExclude[string(vd.misc)] = struct{}{} - } - - vd.validateStruct(ctx, top, val, typ, vd.ns[0:0], vd.actualNs[0:0], nil) - - if len(vd.errs) > 0 { - err = vd.errs - vd.errs = nil - } - - v.pool.Put(vd) - - return -} - -// Var validates a single variable using tag style validation. -// eg. -// var i int -// validate.Var(i, "gt=1,lt=10") -// -// WARNING: a struct can be passed for validation eg. time.Time is a struct or -// if you have a custom type and have registered a custom type handler, so must -// allow it; however unforeseen validations will occur if trying to validate a -// struct that is meant to be passed to 'validate.Struct' -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -// validate Array, Slice and maps fields which may contain more than one error -func (v *Validate) Var(field interface{}, tag string) error { - return v.VarCtx(context.Background(), field, tag) -} - -// VarCtx validates a single variable using tag style validation and allows passing of contextual -// validation validation information via context.Context. -// eg. -// var i int -// validate.Var(i, "gt=1,lt=10") -// -// WARNING: a struct can be passed for validation eg. time.Time is a struct or -// if you have a custom type and have registered a custom type handler, so must -// allow it; however unforeseen validations will occur if trying to validate a -// struct that is meant to be passed to 'validate.Struct' -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -// validate Array, Slice and maps fields which may contain more than one error -func (v *Validate) VarCtx(ctx context.Context, field interface{}, tag string) (err error) { - if len(tag) == 0 || tag == skipValidationTag { - return nil - } - - ctag := v.fetchCacheTag(tag) - val := reflect.ValueOf(field) - vd := v.pool.Get().(*validate) - vd.top = val - vd.isPartial = false - vd.traverseField(ctx, val, val, vd.ns[0:0], vd.actualNs[0:0], defaultCField, ctag) - - if len(vd.errs) > 0 { - err = vd.errs - vd.errs = nil - } - v.pool.Put(vd) - return -} - -// VarWithValue validates a single variable, against another variable/field's value using tag style validation -// eg. -// s1 := "abcd" -// s2 := "abcd" -// validate.VarWithValue(s1, s2, "eqcsfield") // returns true -// -// WARNING: a struct can be passed for validation eg. time.Time is a struct or -// if you have a custom type and have registered a custom type handler, so must -// allow it; however unforeseen validations will occur if trying to validate a -// struct that is meant to be passed to 'validate.Struct' -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -// validate Array, Slice and maps fields which may contain more than one error -func (v *Validate) VarWithValue(field interface{}, other interface{}, tag string) error { - return v.VarWithValueCtx(context.Background(), field, other, tag) -} - -// VarWithValueCtx validates a single variable, against another variable/field's value using tag style validation and -// allows passing of contextual validation validation information via context.Context. -// eg. -// s1 := "abcd" -// s2 := "abcd" -// validate.VarWithValue(s1, s2, "eqcsfield") // returns true -// -// WARNING: a struct can be passed for validation eg. time.Time is a struct or -// if you have a custom type and have registered a custom type handler, so must -// allow it; however unforeseen validations will occur if trying to validate a -// struct that is meant to be passed to 'validate.Struct' -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -// validate Array, Slice and maps fields which may contain more than one error -func (v *Validate) VarWithValueCtx(ctx context.Context, field interface{}, other interface{}, tag string) (err error) { - if len(tag) == 0 || tag == skipValidationTag { - return nil - } - ctag := v.fetchCacheTag(tag) - otherVal := reflect.ValueOf(other) - vd := v.pool.Get().(*validate) - vd.top = otherVal - vd.isPartial = false - vd.traverseField(ctx, otherVal, reflect.ValueOf(field), vd.ns[0:0], vd.actualNs[0:0], defaultCField, ctag) - - if len(vd.errs) > 0 { - err = vd.errs - vd.errs = nil - } - v.pool.Put(vd) - return -} diff --git a/vendor/github.com/goat-systems/go-tezos/v2/README.md b/vendor/github.com/goat-systems/go-tezos/v2/README.md index 3746c1f..ae87f11 100644 --- a/vendor/github.com/goat-systems/go-tezos/v2/README.md +++ b/vendor/github.com/goat-systems/go-tezos/v2/README.md @@ -1,7 +1,7 @@ [![GoDoc](https://godoc.org/github.com/golang/gddo?status.svg)](https://godoc.org/github.com/goat-systems/go-tezos/v2) # A Tezos Go Library -Go Tezos is a GoLang driven library for your Tezos node. +Go Tezos is a GoLang driven library for your Tezos node. This library has received a grant from the Tezos Foundation to ensure it's continuous development through 2020. ## Installation diff --git a/vendor/github.com/goat-systems/go-tezos/v2/block.go b/vendor/github.com/goat-systems/go-tezos/v2/block.go index 6bd5d67..5e38a10 100644 --- a/vendor/github.com/goat-systems/go-tezos/v2/block.go +++ b/vendor/github.com/goat-systems/go-tezos/v2/block.go @@ -19,10 +19,8 @@ type Int struct { } // NewInt returns a pointer GoTezos's wrapper Int -func NewInt(bigint big.Int) (*Int, error) { - return &Int{ - Big: &bigint, - }, nil +func NewInt(i int) *Int { + return &Int{Big: big.NewInt(int64(i))} } func newInt(bigintstring []byte) (*Int, error) { @@ -183,7 +181,7 @@ Link: type BalanceUpdates struct { Kind string `json:"kind"` Contract string `json:"contract,omitempty"` - Change Int `json:"change"` + Change *Int `json:"change"` Category string `json:"category,omitempty"` Delegate string `json:"delegate,omitempty"` Cycle int `json:"cycle,omitempty"` @@ -203,7 +201,7 @@ type OperationResult struct { BalanceUpdates []BalanceUpdates `json:"balance_updates"` OriginatedContracts []string `json:"originated_contracts"` Status string `json:"status"` - ConsumedGas Int `json:"consumed_gas,omitempty"` + ConsumedGas *Int `json:"consumed_gas,omitempty"` Errors []Error `json:"errors,omitempty"` } @@ -237,18 +235,18 @@ Link: type Contents struct { Kind string `json:"kind,omitempty"` Source string `json:"source,omitempty"` - Fee Int `json:"fee,omitempty"` - Counter Int `json:"counter,omitempty"` - GasLimit Int `json:"gas_limit,omitempty"` - StorageLimit Int `json:"storage_limit,omitempty"` - Amount Int `json:"amount,omitempty"` + Fee *Int `json:"fee,omitempty"` + Counter *Int `json:"counter,omitempty"` + GasLimit *Int `json:"gas_limit,omitempty"` + StorageLimit *Int `json:"storage_limit,omitempty"` + Amount *Int `json:"amount,omitempty"` Destination string `json:"destination,omitempty"` Delegate string `json:"delegate,omitempty"` Phk string `json:"phk,omitempty"` Secret string `json:"secret,omitempty"` Level int `json:"level,omitempty"` ManagerPublicKey string `json:"managerPubkey,omitempty"` - Balance Int `json:"balance,omitempty"` + Balance *Int `json:"balance,omitempty"` Period int `json:"period,omitempty"` Proposal string `json:"proposal,omitempty"` Proposals []string `json:"proposals,omitempty"` @@ -375,19 +373,19 @@ Parameters: blockhash: The hash of block (height) of which you want to make the query. */ -func (t *GoTezos) OperationHashes(blockhash string) (*[][]string, error) { +func (t *GoTezos) OperationHashes(blockhash string) ([][]string, error) { resp, err := t.get(fmt.Sprintf("/chains/main/blocks/%s/operation_hashes", blockhash)) if err != nil { - return &[][]string{}, errors.Wrapf(err, "could not get operation hashes") + return [][]string{}, errors.Wrapf(err, "could not get operation hashes") } var operations [][]string err = json.Unmarshal(resp, &operations) if err != nil { - return &[][]string{}, errors.Wrapf(err, "could not unmarshal operation hashes") + return [][]string{}, errors.Wrapf(err, "could not unmarshal operation hashes") } - return &operations, nil + return operations, nil } func idToString(id interface{}) (string, error) { diff --git a/vendor/github.com/goat-systems/go-tezos/v2/chains.go b/vendor/github.com/goat-systems/go-tezos/v2/chains.go index 0f2fb31..dd4b609 100644 --- a/vendor/github.com/goat-systems/go-tezos/v2/chains.go +++ b/vendor/github.com/goat-systems/go-tezos/v2/chains.go @@ -81,19 +81,19 @@ Parameters: input: Modifies the Blocks RPC query by passing optional URL parameters. */ -func (t *GoTezos) Blocks(input *BlocksInput) (*[][]string, error) { +func (t *GoTezos) Blocks(input BlocksInput) ([][]string, error) { resp, err := t.get("/chains/main/blocks", input.contructRPCOptions()...) if err != nil { - return &[][]string{}, errors.Wrap(err, "failed to get blocks") + return [][]string{}, errors.Wrap(err, "failed to get blocks") } var blocks [][]string err = json.Unmarshal(resp, &blocks) if err != nil { - return &[][]string{}, errors.Wrap(err, "failed to unmarshal blocks") + return [][]string{}, errors.Wrap(err, "failed to unmarshal blocks") } - return &blocks, nil + return blocks, nil } func (b *BlocksInput) contructRPCOptions() []rpcOptions { @@ -131,19 +131,19 @@ Path: Link: https://tezos.gitlab.io/api/rpc.html#get-chains-chain-id-chain-id */ -func (t *GoTezos) ChainID() (*string, error) { +func (t *GoTezos) ChainID() (string, error) { resp, err := t.get("/chains/main/chain_id") if err != nil { - return nil, errors.Wrapf(err, "failed to get chain id") + return "", errors.Wrapf(err, "failed to get chain id") } var chainID string err = json.Unmarshal(resp, &chainID) if err != nil { - return nil, errors.Wrapf(err, "failed to unmarshal chain id") + return "", errors.Wrapf(err, "failed to unmarshal chain id") } - return &chainID, nil + return chainID, nil } /* @@ -155,19 +155,19 @@ Path: Link: https://tezos.gitlab.io/api/rpc.html#get-chains-chain-id-checkpoint */ -func (t *GoTezos) Checkpoint() (*Checkpoint, error) { +func (t *GoTezos) Checkpoint() (Checkpoint, error) { resp, err := t.get("/chains/main/checkpoint") if err != nil { - return &Checkpoint{}, errors.Wrap(err, "failed to get checkpoint") + return Checkpoint{}, errors.Wrap(err, "failed to get checkpoint") } var c Checkpoint err = json.Unmarshal(resp, &c) if err != nil { - return &c, errors.Wrap(err, "failed to unmarshal checkpoint") + return c, errors.Wrap(err, "failed to unmarshal checkpoint") } - return &c, nil + return c, nil } /* @@ -180,19 +180,19 @@ Path: Link: https://tezos.gitlab.io/api/rpc.html#get-chains-chain-id-invalid-blocks */ -func (t *GoTezos) InvalidBlocks() (*[]InvalidBlock, error) { +func (t *GoTezos) InvalidBlocks() ([]InvalidBlock, error) { resp, err := t.get("/chains/main/invalid_blocks") if err != nil { - return &[]InvalidBlock{}, errors.Wrap(err, "failed to get invalid blocks") + return []InvalidBlock{}, errors.Wrap(err, "failed to get invalid blocks") } var blocks []InvalidBlock err = json.Unmarshal(resp, &blocks) if err != nil { - return &[]InvalidBlock{}, errors.Wrap(err, "failed to unmarshal invalid blocks") + return []InvalidBlock{}, errors.Wrap(err, "failed to unmarshal invalid blocks") } - return &blocks, nil + return blocks, nil } /* @@ -204,19 +204,19 @@ Path: Link: https://tezos.gitlab.io/api/rpc.html#get-chains-chain-id-invalid-blocks-block-hash */ -func (t *GoTezos) InvalidBlock(blockHash string) (*InvalidBlock, error) { +func (t *GoTezos) InvalidBlock(blockHash string) (InvalidBlock, error) { resp, err := t.get(fmt.Sprintf("/chains/main/invalid_blocks/%s", blockHash)) if err != nil { - return &InvalidBlock{}, errors.Wrap(err, "failed to get invalid blocks") + return InvalidBlock{}, errors.Wrap(err, "failed to get invalid blocks") } var block InvalidBlock err = json.Unmarshal(resp, &block) if err != nil { - return &InvalidBlock{}, errors.Wrap(err, "failed to unmarshal invalid blocks") + return InvalidBlock{}, errors.Wrap(err, "failed to unmarshal invalid blocks") } - return &block, nil + return block, nil } /* diff --git a/vendor/github.com/goat-systems/go-tezos/v2/config.go b/vendor/github.com/goat-systems/go-tezos/v2/config.go index 77477f0..2f8f51f 100644 --- a/vendor/github.com/goat-systems/go-tezos/v2/config.go +++ b/vendor/github.com/goat-systems/go-tezos/v2/config.go @@ -29,17 +29,17 @@ Path: Link: https://tezos.gitlab.io/api/rpc.html#get-config-network-user-activated-protocol-overrides */ -func (t *GoTezos) UserActivatedProtocolOverrides() (*UserActivatedProtocolOverrides, error) { +func (t *GoTezos) UserActivatedProtocolOverrides() (UserActivatedProtocolOverrides, error) { resp, err := t.get("/config/network/user_activated_protocol_overrides") if err != nil { - return &UserActivatedProtocolOverrides{}, errors.Wrap(err, "failed to get blocks") + return UserActivatedProtocolOverrides{}, errors.Wrap(err, "failed to get blocks") } var userActivatedProtocolOverride UserActivatedProtocolOverrides err = json.Unmarshal(resp, &userActivatedProtocolOverride) if err != nil { - return &userActivatedProtocolOverride, errors.Wrap(err, "failed to unmarshal blocks") + return userActivatedProtocolOverride, errors.Wrap(err, "failed to unmarshal blocks") } - return &userActivatedProtocolOverride, nil + return userActivatedProtocolOverride, nil } diff --git a/vendor/github.com/goat-systems/go-tezos/v2/contracts.go b/vendor/github.com/goat-systems/go-tezos/v2/contracts.go index 033d3ae..9ee72b7 100644 --- a/vendor/github.com/goat-systems/go-tezos/v2/contracts.go +++ b/vendor/github.com/goat-systems/go-tezos/v2/contracts.go @@ -23,11 +23,11 @@ Parameters: KT1: The contract address. */ -func (t *GoTezos) ContractStorage(blockhash string, KT1 string) (*[]byte, error) { +func (t *GoTezos) ContractStorage(blockhash string, KT1 string) ([]byte, error) { query := fmt.Sprintf("/chains/main/blocks/%s/context/contracts/%s/storage", blockhash, KT1) resp, err := t.get(query) if err != nil { - return &resp, errors.Wrap(err, "could not get storage '%s'") + return resp, errors.Wrap(err, "could not get storage '%s'") } - return &resp, nil + return resp, nil } diff --git a/vendor/github.com/goat-systems/go-tezos/v2/delegate.go b/vendor/github.com/goat-systems/go-tezos/v2/delegate.go index 60f196b..0e82ec1 100644 --- a/vendor/github.com/goat-systems/go-tezos/v2/delegate.go +++ b/vendor/github.com/goat-systems/go-tezos/v2/delegate.go @@ -21,9 +21,9 @@ Link: https://tezos.gitlab.io/api/rpc.html#get-block-id-context-delegates-pkh-frozen-balance */ type FrozenBalance struct { - Deposits Int `json:"deposits"` - Fees Int `json:"fees"` - Rewards Int `json:"rewards"` + Deposits *Int `json:"deposits"` + Fees *Int `json:"fees"` + Rewards *Int `json:"rewards"` } /* @@ -39,10 +39,10 @@ type Delegate struct { Balance string `json:"balance"` FrozenBalance string `json:"frozen_balance"` FrozenBalanceByCycle []struct { - Cycle int `json:"cycle"` - Deposit Int `json:"deposit"` - Fees Int `json:"fees"` - Rewards Int `json:"rewards"` + Cycle int `json:"cycle"` + Deposit *Int `json:"deposit"` + Fees *Int `json:"fees"` + Rewards *Int `json:"rewards"` } `json:"frozen_balance_by_cycle"` StakingBalance string `json:"staking_balance"` DelegateContracts []string `json:"delegated_contracts"` @@ -163,19 +163,19 @@ Parameters: delegate: The tz(1-3) address of the delegate. */ -func (t *GoTezos) DelegatedContracts(blockhash, delegate string) (*[]string, error) { +func (t *GoTezos) DelegatedContracts(blockhash, delegate string) ([]*string, error) { resp, err := t.get(fmt.Sprintf("/chains/main/blocks/%s/context/delegates/%s/delegated_contracts", blockhash, delegate)) if err != nil { - return &[]string{}, errors.Wrapf(err, "could not get delegations for '%s'", delegate) + return []*string{}, errors.Wrapf(err, "could not get delegations for '%s'", delegate) } - var list []string + var list []*string err = json.Unmarshal(resp, &list) if err != nil { - return &[]string{}, errors.Wrapf(err, "could not unmarshal delegations for '%s'", delegate) + return []*string{}, errors.Wrapf(err, "could not unmarshal delegations for '%s'", delegate) } - return &list, nil + return list, nil } /* @@ -194,15 +194,15 @@ Parameters: delegate: The tz(1-3) address of the delegate. */ -func (t *GoTezos) DelegatedContractsAtCycle(cycle int, delegate string) (*[]string, error) { +func (t *GoTezos) DelegatedContractsAtCycle(cycle int, delegate string) ([]*string, error) { snapshot, err := t.Cycle(cycle) if err != nil { - return &[]string{}, errors.Wrapf(err, "could not get delegations for '%s' at cycle '%d'", delegate, cycle) + return []*string{}, errors.Wrapf(err, "could not get delegations for '%s' at cycle '%d'", delegate, cycle) } delegations, err := t.DelegatedContracts(snapshot.BlockHash, delegate) if err != nil { - return &[]string{}, errors.Wrapf(err, "could not get delegations at cycle '%d'", cycle) + return []*string{}, errors.Wrapf(err, "could not get delegations at cycle '%d'", cycle) } return delegations, nil @@ -224,26 +224,26 @@ Parameters: delegate: The tz(1-3) address of the delegate. */ -func (t *GoTezos) FrozenBalance(cycle int, delegate string) (*FrozenBalance, error) { +func (t *GoTezos) FrozenBalance(cycle int, delegate string) (FrozenBalance, error) { level := (cycle+1)*(t.networkConstants.BlocksPerCycle) + 1 head, err := t.Block(level) if err != nil { - return nil, errors.Wrapf(err, "failed to get frozen balance at cycle '%d' for delegate '%s'", cycle, delegate) + return FrozenBalance{}, errors.Wrapf(err, "failed to get frozen balance at cycle '%d' for delegate '%s'", cycle, delegate) } resp, err := t.get(fmt.Sprintf("/chains/main/blocks/%s/context/raw/json/contracts/index/%s/frozen_balance/%d/", head.Hash, delegate, cycle)) if err != nil { - return nil, errors.Wrapf(err, "failed to get frozen balance at cycle '%d' for delegate '%s'", cycle, delegate) + return FrozenBalance{}, errors.Wrapf(err, "failed to get frozen balance at cycle '%d' for delegate '%s'", cycle, delegate) } var frozenBalance FrozenBalance err = json.Unmarshal(resp, &frozenBalance) if err != nil { - return &frozenBalance, errors.Wrapf(err, "failed to unmarshal frozen balance at cycle '%d' for delegate '%s'", cycle, delegate) + return frozenBalance, errors.Wrapf(err, "failed to unmarshal frozen balance at cycle '%d' for delegate '%s'", cycle, delegate) } - return &frozenBalance, nil + return frozenBalance, nil } /* @@ -263,19 +263,19 @@ Parameters: delegate: The tz(1-3) address of the delegate. */ -func (t *GoTezos) Delegate(blockhash, delegate string) (*Delegate, error) { +func (t *GoTezos) Delegate(blockhash, delegate string) (Delegate, error) { resp, err := t.get(fmt.Sprintf("/chains/main/blocks/%s/context/delegates/%s", blockhash, delegate)) if err != nil { - return nil, errors.Wrapf(err, "could not get delegate '%s'", delegate) + return Delegate{}, errors.Wrapf(err, "could not get delegate '%s'", delegate) } var d Delegate err = json.Unmarshal(resp, &d) if err != nil { - return &d, errors.Wrapf(err, "could not unmarshal delegate '%s'", delegate) + return d, errors.Wrapf(err, "could not unmarshal delegate '%s'", delegate) } - return &d, nil + return d, nil } /* @@ -368,7 +368,7 @@ Parameters: Modifies the BakingRights RPC query by passing optional URL parameters. BlockHash is required. */ -func (t *GoTezos) BakingRights(input *BakingRightsInput) (*BakingRights, error) { +func (t *GoTezos) BakingRights(input BakingRightsInput) (*BakingRights, error) { err := validator.New().Struct(input) if err != nil { return &BakingRights{}, errors.Wrap(err, "invalid input") @@ -443,7 +443,7 @@ Parameters: Modifies the EndorsingRights RPC query by passing optional URL parameters. BlockHash is required. */ -func (t *GoTezos) EndorsingRights(input *EndorsingRightsInput) (*EndorsingRights, error) { +func (t *GoTezos) EndorsingRights(input EndorsingRightsInput) (*EndorsingRights, error) { err := validator.New().Struct(input) if err != nil { return &EndorsingRights{}, errors.Wrap(err, "invalid input") @@ -506,24 +506,24 @@ Parameters: delegate: The tz(1-3) address of the delegate. */ -func (t *GoTezos) Delegates(input *DelegatesInput) (*[]string, error) { +func (t *GoTezos) Delegates(input DelegatesInput) ([]*string, error) { err := validator.New().Struct(input) if err != nil { - return &[]string{}, errors.Wrap(err, "invalid input") + return []*string{}, errors.Wrap(err, "invalid input") } resp, err := t.get(fmt.Sprintf("/chains/main/blocks/%s/context/delegates", *input.BlockHash), input.contructRPCOptions()...) if err != nil { - return &[]string{}, errors.Wrap(err, "could not get delegates") + return []*string{}, errors.Wrap(err, "could not get delegates") } - var list []string + var list []*string err = json.Unmarshal(resp, &list) if err != nil { - return &[]string{}, errors.Wrap(err, "could not unmarshal delegates") + return []*string{}, errors.Wrap(err, "could not unmarshal delegates") } - return &list, nil + return list, nil } func (d *DelegatesInput) contructRPCOptions() []rpcOptions { diff --git a/vendor/github.com/goat-systems/go-tezos/v2/go.mod b/vendor/github.com/goat-systems/go-tezos/v2/go.mod index 6992291..4c92461 100644 --- a/vendor/github.com/goat-systems/go-tezos/v2/go.mod +++ b/vendor/github.com/goat-systems/go-tezos/v2/go.mod @@ -3,6 +3,7 @@ module github.com/goat-systems/go-tezos/v2 go 1.13 require ( + github.com/DefinitelyNotAGoat/go-tezos v1.0.9 // indirect github.com/Messer4/base58check v0.0.0-20180328134002-7531a92ae9ba github.com/btcsuite/btcutil v1.0.1 github.com/fzipp/gocyclo v0.0.0-20150627053110-6acd4345c835 // indirect diff --git a/vendor/github.com/goat-systems/go-tezos/v2/go.sum b/vendor/github.com/goat-systems/go-tezos/v2/go.sum index a38aba2..9966085 100644 --- a/vendor/github.com/goat-systems/go-tezos/v2/go.sum +++ b/vendor/github.com/goat-systems/go-tezos/v2/go.sum @@ -1,5 +1,7 @@ github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/DefinitelyNotAGoat/go-tezos v1.0.9 h1:XX+be9QVEELmRWhkzpZN2tumSH0qe/RuHzj17Up0qoo= +github.com/DefinitelyNotAGoat/go-tezos v1.0.9/go.mod h1:H1y57Sb48z7ats9Abq3fF0a3YdTcY5iZrsA2QdHW/Fw= github.com/Messer4/base58check v0.0.0-20180328134002-7531a92ae9ba h1:e0baDNoruF8YR/JRUmljBoQwxWSOL8MXPFPxWN0GOXk= github.com/Messer4/base58check v0.0.0-20180328134002-7531a92ae9ba/go.mod h1:NtsVEFPEMr0LH6B51gU0o+JYyiIb+jKEa49+t9tMbtM= github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII= @@ -35,12 +37,16 @@ github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm4 github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= +github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc= +github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg= github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ= github.com/kisielk/gotool v1.0.0 h1:AV2c/EiW3KqPNT9ZKl07ehoAGi4C5/01Cfbblndcapg= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= @@ -60,6 +66,7 @@ github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJy github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200115085410-6d4e4cb37c7d h1:2+ZP7EfsZV7Vvmx3TIqSlSzATMkTAKqM14YGFPoSKjI= @@ -107,6 +114,7 @@ google.golang.org/appengine v1.6.5 h1:tycE03LOZYQNhDpS27tcQdAzLCVMaj7QT2SXxebnpC google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= diff --git a/vendor/github.com/goat-systems/go-tezos/v2/gotezos.go b/vendor/github.com/goat-systems/go-tezos/v2/gotezos.go index 16559f2..2d99899 100644 --- a/vendor/github.com/goat-systems/go-tezos/v2/gotezos.go +++ b/vendor/github.com/goat-systems/go-tezos/v2/gotezos.go @@ -90,7 +90,7 @@ func New(host string) (*GoTezos, error) { if err != nil { return gt, errors.Wrap(err, "could not initialize library with network constants") } - gt.networkConstants = constants + gt.networkConstants = &constants return gt, nil } diff --git a/vendor/github.com/goat-systems/go-tezos/v2/iface.go b/vendor/github.com/goat-systems/go-tezos/v2/iface.go index 6d4a06e..4c3d670 100644 --- a/vendor/github.com/goat-systems/go-tezos/v2/iface.go +++ b/vendor/github.com/goat-systems/go-tezos/v2/iface.go @@ -4,36 +4,36 @@ import "math/big" // IFace is an interface mocking a GoTezos object. type IFace interface { - ActiveChains() (*ActiveChains, error) - BakingRights(input *BakingRightsInput) (*BakingRights, error) + ActiveChains() (ActiveChains, error) + BakingRights(input BakingRightsInput) (*BakingRights, error) Balance(blockhash, address string) (*big.Int, error) Block(id interface{}) (*Block, error) - Blocks(input *BlocksInput) (*[][]string, error) - Bootstrap() (*Bootstrap, error) - ChainID() (*string, error) - Checkpoint() (*Checkpoint, error) - Commit() (*string, error) - Connections() (*Connections, error) - Constants(blockhash string) (*Constants, error) - ContractStorage(blockhash string, KT1 string) (*[]byte, error) - Counter(blockhash, pkh string) (*int, error) - Cycle(cycle int) (*Cycle, error) - Delegate(blockhash, delegate string) (*Delegate, error) - Delegates(input *DelegatesInput) (*[]string, error) - DelegatedContracts(blockhash, delegate string) (*[]string, error) - DelegatedContractsAtCycle(cycle int, delegate string) (*[]string, error) + Blocks(input BlocksInput) ([][]string, error) + Bootstrap() (Bootstrap, error) + ChainID() (string, error) + Checkpoint() (Checkpoint, error) + Commit() (string, error) + Connections() (Connections, error) + Constants(blockhash string) (Constants, error) + ContractStorage(blockhash string, KT1 string) ([]byte, error) + Counter(blockhash, pkh string) (int, error) + Cycle(cycle int) (Cycle, error) + Delegate(blockhash, delegate string) (Delegate, error) + Delegates(input DelegatesInput) ([]*string, error) + DelegatedContracts(blockhash, delegate string) ([]*string, error) + DelegatedContractsAtCycle(cycle int, delegate string) ([]*string, error) DeleteInvalidBlock(blockHash string) error - EndorsingRights(input *EndorsingRightsInput) (*EndorsingRights, error) - FrozenBalance(cycle int, delegate string) (*FrozenBalance, error) + EndorsingRights(input EndorsingRightsInput) (*EndorsingRights, error) + FrozenBalance(cycle int, delegate string) (FrozenBalance, error) Head() (*Block, error) - InjectionBlock(input *InjectionBlockInput) (*[]byte, error) - InjectionOperation(input *InjectionOperationInput) (*[]byte, error) - InvalidBlock(blockHash string) (*InvalidBlock, error) - InvalidBlocks() (*[]InvalidBlock, error) - OperationHashes(blockhash string) (*[][]string, error) - PreapplyOperations(blockhash string, contents []Contents, signature string) (*[]byte, error) + InjectionBlock(input InjectionBlockInput) ([]byte, error) + InjectionOperation(input InjectionOperationInput) ([]byte, error) + InvalidBlock(blockHash string) (InvalidBlock, error) + InvalidBlocks() ([]InvalidBlock, error) + OperationHashes(blockhash string) ([][]string, error) + PreapplyOperations(blockhash string, contents []Contents, signature string) ([]byte, error) StakingBalance(blockhash, delegate string) (*big.Int, error) StakingBalanceAtCycle(cycle int, delegate string) (*big.Int, error) - UserActivatedProtocolOverrides() (*UserActivatedProtocolOverrides, error) - Version() (*Version, error) + UserActivatedProtocolOverrides() (UserActivatedProtocolOverrides, error) + Version() (Version, error) } diff --git a/vendor/github.com/goat-systems/go-tezos/v2/network.go b/vendor/github.com/goat-systems/go-tezos/v2/network.go index db15594..613bafa 100644 --- a/vendor/github.com/goat-systems/go-tezos/v2/network.go +++ b/vendor/github.com/goat-systems/go-tezos/v2/network.go @@ -45,19 +45,19 @@ type Constants struct { BlocksPerVotingPeriod int `json:"blocks_per_voting_period"` TimeBetweenBlocks []string `json:"time_between_blocks"` EndorsersPerBlock int `json:"endorsers_per_block"` - HardGasLimitPerOperation Int `json:"hard_gas_limit_per_operation"` - HardGasLimitPerBlock Int `json:"hard_gas_limit_per_block"` + HardGasLimitPerOperation *Int `json:"hard_gas_limit_per_operation"` + HardGasLimitPerBlock *Int `json:"hard_gas_limit_per_block"` ProofOfWorkThreshold string `json:"proof_of_work_threshold"` TokensPerRoll string `json:"tokens_per_roll"` MichelsonMaximumTypeSize int `json:"michelson_maximum_type_size"` SeedNonceRevelationTip string `json:"seed_nonce_revelation_tip"` OriginationSize int `json:"origination_size"` - BlockSecurityDeposit Int `json:"block_security_deposit"` - EndorsementSecurityDeposit Int `json:"endorsement_security_deposit"` - BlockReward []Int `json:"block_reward"` - EndorsementReward []Int `json:"endorsement_reward"` - CostPerByte Int `json:"cost_per_byte"` - HardStorageLimitPerOperation Int `json:"hard_storage_limit_per_operation"` + BlockSecurityDeposit *Int `json:"block_security_deposit"` + EndorsementSecurityDeposit *Int `json:"endorsement_security_deposit"` + BlockReward []*Int `json:"block_reward"` + EndorsementReward []*Int `json:"endorsement_reward"` + CostPerByte *Int `json:"cost_per_byte"` + HardStorageLimitPerOperation *Int `json:"hard_storage_limit_per_operation"` } /* @@ -144,19 +144,19 @@ Path: Link: https://tezos.gitlab.io/api/rpc.html#get-network-version */ -func (t *GoTezos) Version() (*Version, error) { +func (t *GoTezos) Version() (Version, error) { resp, err := t.get("/network/version") if err != nil { - return &Version{}, errors.Wrap(err, "could not get network version") + return Version{}, errors.Wrap(err, "could not get network version") } var version Version err = json.Unmarshal(resp, &version) if err != nil { - return &Version{}, errors.Wrap(err, "could not unmarshal network version") + return Version{}, errors.Wrap(err, "could not unmarshal network version") } - return &version, nil + return version, nil } /* @@ -168,19 +168,19 @@ Path: Link: https://tezos.gitlab.io/api/rpc.html#get-block-id-context-constants */ -func (t *GoTezos) Constants(blockhash string) (*Constants, error) { +func (t *GoTezos) Constants(blockhash string) (Constants, error) { resp, err := t.get(fmt.Sprintf("/chains/main/blocks/%s/context/constants", blockhash)) if err != nil { - return &Constants{}, errors.Wrapf(err, "could not get network constants") + return Constants{}, errors.Wrapf(err, "could not get network constants") } var constants Constants err = json.Unmarshal(resp, &constants) if err != nil { - return &constants, errors.Wrapf(err, "could not unmarshal network constants") + return constants, errors.Wrapf(err, "could not unmarshal network constants") } - return &constants, nil + return constants, nil } /* @@ -192,19 +192,19 @@ Path: Link: https://tezos.gitlab.io/api/rpc.html#get-network-connections */ -func (t *GoTezos) Connections() (*Connections, error) { +func (t *GoTezos) Connections() (Connections, error) { resp, err := t.get("/network/connections") if err != nil { - return &Connections{}, errors.Wrapf(err, "could not get network connections") + return Connections{}, errors.Wrapf(err, "could not get network connections") } var connections Connections err = json.Unmarshal(resp, &connections) if err != nil { - return &Connections{}, errors.Wrapf(err, "could not unmarshal network connections") + return Connections{}, errors.Wrapf(err, "could not unmarshal network connections") } - return &connections, nil + return connections, nil } /* @@ -218,19 +218,19 @@ Path: Link: https://tezos.gitlab.io/api/rpc.html#get-monitor-bootstrapped */ -func (t *GoTezos) Bootstrap() (*Bootstrap, error) { +func (t *GoTezos) Bootstrap() (Bootstrap, error) { resp, err := t.get("/monitor/bootstrapped") if err != nil { - return &Bootstrap{}, errors.Wrap(err, "could not get bootstrap") + return Bootstrap{}, errors.Wrap(err, "could not get bootstrap") } var bootstrap Bootstrap err = json.Unmarshal(resp, &bootstrap) if err != nil { - return &bootstrap, errors.Wrap(err, "could not unmarshal bootstrap") + return bootstrap, errors.Wrap(err, "could not unmarshal bootstrap") } - return &bootstrap, nil + return bootstrap, nil } /* @@ -242,19 +242,19 @@ Path: Link: https://tezos.gitlab.io/api/rpc.html#get-monitor-commit-hash */ -func (t *GoTezos) Commit() (*string, error) { +func (t *GoTezos) Commit() (string, error) { resp, err := t.get("/monitor/commit_hash") if err != nil { - return nil, errors.Wrap(err, "could not get commit hash") + return "", errors.Wrap(err, "could not get commit hash") } var commit string err = json.Unmarshal(resp, &commit) if err != nil { - return nil, errors.Wrap(err, "could unmarshal commit") + return "", errors.Wrap(err, "could unmarshal commit") } - return &commit, nil + return commit, nil } /* @@ -266,32 +266,32 @@ Path: Link: https://tezos.gitlab.io/api/rpc.html#get-block-id-context-raw-bytes */ -func (t *GoTezos) Cycle(cycle int) (*Cycle, error) { +func (t *GoTezos) Cycle(cycle int) (Cycle, error) { head, err := t.Head() if err != nil { - return &Cycle{}, errors.Wrapf(err, "could not get cycle '%d'", cycle) + return Cycle{}, errors.Wrapf(err, "could not get cycle '%d'", cycle) } if cycle > head.Metadata.Level.Cycle+t.networkConstants.PreservedCycles-1 { - return &Cycle{}, errors.Errorf("could not get cycle '%d': request is in the future", cycle) + return Cycle{}, errors.Errorf("could not get cycle '%d': request is in the future", cycle) } var c Cycle if cycle < head.Metadata.Level.Cycle { block, err := t.Block(cycle*t.networkConstants.BlocksPerCycle + 1) if err != nil { - return &Cycle{}, errors.Wrapf(err, "could not get cycle '%d'", cycle) + return Cycle{}, errors.Wrapf(err, "could not get cycle '%d'", cycle) } c, err = t.getCycleAtHash(block.Hash, cycle) if err != nil { - return &Cycle{}, errors.Wrapf(err, "could not get cycle '%d'", cycle) + return Cycle{}, errors.Wrapf(err, "could not get cycle '%d'", cycle) } } else { var err error c, err = t.getCycleAtHash(head.Hash, cycle) if err != nil { - return &Cycle{}, errors.Wrapf(err, "could not get cycle '%d'", cycle) + return Cycle{}, errors.Wrapf(err, "could not get cycle '%d'", cycle) } } @@ -302,11 +302,11 @@ func (t *GoTezos) Cycle(cycle int) (*Cycle, error) { block, err := t.Block(level) if err != nil { - return &c, errors.Wrapf(err, "could not get cycle '%d'", cycle) + return c, errors.Wrapf(err, "could not get cycle '%d'", cycle) } c.BlockHash = block.Hash - return &c, nil + return c, nil } func (t *GoTezos) getCycleAtHash(blockhash string, cycle int) (Cycle, error) { @@ -333,7 +333,7 @@ Path: Link: https://tezos.gitlab.io/api/rpc.html#get-monitor-active-chains */ -func (t *GoTezos) ActiveChains() (*ActiveChains, error) { +func (t *GoTezos) ActiveChains() (ActiveChains, error) { resp, err := t.get("/monitor/active_chains") if err != nil { return nil, errors.Wrap(err, "failed to get active chains") @@ -345,5 +345,5 @@ func (t *GoTezos) ActiveChains() (*ActiveChains, error) { return nil, errors.Wrap(err, "failed to unmarshal active chains") } - return &activeChains, nil + return activeChains, nil } diff --git a/vendor/github.com/goat-systems/go-tezos/v2/operations.go b/vendor/github.com/goat-systems/go-tezos/v2/operations.go index 3ca32ce..4c7cbfd 100644 --- a/vendor/github.com/goat-systems/go-tezos/v2/operations.go +++ b/vendor/github.com/goat-systems/go-tezos/v2/operations.go @@ -27,7 +27,7 @@ const ( InjectionOperationInput is the input for the goTezos.InjectionOperation function. Function: - func (t *GoTezos) InjectionOperation(input *InjectionOperationInput) (*[]byte, error) {} + func (t *GoTezos) InjectionOperation(input InjectionOperationInput) ([]byte, error) {} */ type InjectionOperationInput struct { // The operation string. @@ -44,7 +44,7 @@ type InjectionOperationInput struct { InjectionBlockInput is the input for the goTezos.InjectionBlock function. Function: - func (t *GoTezos) InjectionBlock(input *InjectionBlockInput) (**[]byte, error) {} + func (t *GoTezos) InjectionBlock(input InjectionBlockInput) ([]byte, error) {} */ type InjectionBlockInput struct { // Block to inject @@ -68,12 +68,12 @@ Function: */ type ForgeTransactionOperationInput struct { Source string `validate:"required"` - Fee Int `validate:"required"` + Fee *Int `validate:"required"` Counter int `validate:"required"` - GasLimit Int `validate:"required"` + GasLimit *Int `validate:"required"` Destination string `validate:"required"` - Amount Int `validate:"required"` - StorageLimit Int + Amount *Int `validate:"required"` + StorageLimit *Int // Code string TODO // ContractDestination string TODO } @@ -84,7 +84,7 @@ func (f *ForgeTransactionOperationInput) Contents() *Contents { Kind: TRANSACTIONOP, Source: f.Source, Fee: f.Fee, - Counter: Int{Big: big.NewInt(int64(f.Counter))}, + Counter: NewInt(f.Counter), GasLimit: f.GasLimit, Destination: f.Destination, Amount: f.Amount, @@ -100,11 +100,11 @@ Function: */ type ForgeRevealOperationInput struct { Source string `validate:"required"` - Fee Int `validate:"required"` + Fee *Int `validate:"required"` Counter int `validate:"required"` - GasLimit Int `validate:"required"` + GasLimit *Int `validate:"required"` Phk string `validate:"required"` - StorageLimit Int + StorageLimit *Int } // Contents returns ForgeRevealOperationInput as a pointer to Contents @@ -113,7 +113,7 @@ func (f *ForgeRevealOperationInput) Contents() *Contents { Kind: REVEALOP, Source: f.Source, Fee: f.Fee, - Counter: Int{Big: big.NewInt(int64(f.Counter))}, + Counter: NewInt(f.Counter), GasLimit: f.GasLimit, Phk: f.Phk, StorageLimit: f.StorageLimit, @@ -128,11 +128,11 @@ Function: */ type ForgeOriginationOperationInput struct { Source string `validate:"required"` - Fee Int `validate:"required"` + Fee *Int `validate:"required"` Counter int `validate:"required"` - GasLimit Int `validate:"required"` - Balance Int `validate:"required"` - StorageLimit Int + GasLimit *Int `validate:"required"` + Balance *Int `validate:"required"` + StorageLimit *Int Delegate string } @@ -142,7 +142,7 @@ func (f *ForgeOriginationOperationInput) Contents() *Contents { Kind: ORIGINATIONOP, Source: f.Source, Fee: f.Fee, - Counter: Int{Big: big.NewInt(int64(f.Counter))}, + Counter: NewInt(f.Counter), GasLimit: f.GasLimit, Balance: f.Balance, StorageLimit: f.StorageLimit, @@ -158,11 +158,11 @@ Function: */ type ForgeDelegationOperationInput struct { Source string `validate:"required"` - Fee Int `validate:"required"` + Fee *Int `validate:"required"` Counter int `validate:"required"` - GasLimit Int `validate:"required"` + GasLimit *Int `validate:"required"` Delegate string `validate:"required"` - StorageLimit Int + StorageLimit *Int } // Contents returns ForgeDelegationOperationInput as a pointer to Contents @@ -171,7 +171,7 @@ func (f *ForgeDelegationOperationInput) Contents() *Contents { Kind: ORIGINATIONOP, Source: f.Source, Fee: f.Fee, - Counter: Int{Big: big.NewInt(int64(f.Counter))}, + Counter: NewInt(f.Counter), GasLimit: f.GasLimit, StorageLimit: f.StorageLimit, Delegate: f.Delegate, @@ -198,7 +198,7 @@ Parameters: signature: The operation signature. */ -func (t *GoTezos) PreapplyOperations(blockhash string, contents []Contents, signature string) (*[]byte, error) { +func (t *GoTezos) PreapplyOperations(blockhash string, contents []Contents, signature string) ([]byte, error) { head, err := t.Head() if err != nil { return nil, errors.Wrap(err, "failed to preapply operation") @@ -220,10 +220,10 @@ func (t *GoTezos) PreapplyOperations(blockhash string, contents []Contents, sign resp, err := t.post(fmt.Sprintf("/chains/main/blocks/%s/helpers/preapply/operations", blockhash), op) if err != nil { - return &resp, errors.Wrap(err, "failed to preapply operation") + return resp, errors.Wrap(err, "failed to preapply operation") } - return &resp, nil + return resp, nil } /* @@ -246,21 +246,21 @@ Parameters: input: Modifies the InjectionOperation RPC query by passing optional URL parameters. Operation is required. */ -func (t *GoTezos) InjectionOperation(input *InjectionOperationInput) (*[]byte, error) { +func (t *GoTezos) InjectionOperation(input InjectionOperationInput) ([]byte, error) { err := validator.New().Struct(input) if err != nil { - return &[]byte{}, errors.Wrap(err, "invalid input") + return []byte{}, errors.Wrap(err, "invalid input") } v, err := json.Marshal(*input.Operation) if err != nil { - return &[]byte{}, errors.Wrap(err, "failed to inject operation") + return []byte{}, errors.Wrap(err, "failed to inject operation") } resp, err := t.post("/injection/operation", v, input.contructRPCOptions()...) if err != nil { - return &resp, errors.Wrap(err, "failed to inject operation") + return resp, errors.Wrap(err, "failed to inject operation") } - return &resp, nil + return resp, nil } func (i *InjectionOperationInput) contructRPCOptions() []rpcOptions { @@ -302,21 +302,21 @@ Parameters: input: Modifies the InjectionBlock RPC query by passing optional URL parameters. Block is required. */ -func (t *GoTezos) InjectionBlock(input *InjectionBlockInput) (*[]byte, error) { +func (t *GoTezos) InjectionBlock(input InjectionBlockInput) ([]byte, error) { err := validator.New().Struct(input) if err != nil { - return &[]byte{}, errors.Wrap(err, "invalid input") + return []byte{}, errors.Wrap(err, "invalid input") } v, err := json.Marshal(*input.Block) if err != nil { - return &[]byte{}, errors.Wrap(err, "failed to inject block") + return []byte{}, errors.Wrap(err, "failed to inject block") } resp, err := t.post("/injection/block", v, input.contructRPCOptions()...) if err != nil { - return &resp, errors.Wrap(err, "failed to inject block") + return resp, errors.Wrap(err, "failed to inject block") } - return &resp, nil + return resp, nil } func (i *InjectionBlockInput) contructRPCOptions() []rpcOptions { @@ -361,22 +361,22 @@ Parameters: pkh: The pkh (address) of the contract for the query. */ -func (t *GoTezos) Counter(blockhash, pkh string) (*int, error) { +func (t *GoTezos) Counter(blockhash, pkh string) (int, error) { resp, err := t.get(fmt.Sprintf("/chains/main/blocks/%s/context/contracts/%s/counter", blockhash, pkh)) if err != nil { - return nil, errors.Wrapf(err, "failed to get counter") + return 0, errors.Wrapf(err, "failed to get counter") } var strCounter string err = json.Unmarshal(resp, &strCounter) if err != nil { - return nil, errors.Wrapf(err, "failed to unmarshal counter") + return 0, errors.Wrapf(err, "failed to unmarshal counter") } counter, err := strconv.Atoi(strCounter) if err != nil { - return nil, errors.Wrapf(err, "failed to get counter") + return 0, errors.Wrapf(err, "failed to get counter") } - return &counter, nil + return counter, nil } /* @@ -466,7 +466,7 @@ func ForgeTransactionOperation(branch string, input ...ForgeTransactionOperation Source: transaction.Source, Destination: transaction.Destination, Fee: transaction.Fee, - Counter: Int{big.NewInt(int64(transaction.Counter))}, + Counter: NewInt(transaction.Counter), GasLimit: transaction.GasLimit, StorageLimit: transaction.StorageLimit, Amount: transaction.Amount, @@ -496,7 +496,7 @@ func forgeTransactionOperation(contents Contents) (string, error) { var sb strings.Builder sb.WriteString("6c") sb.WriteString(commonFields) - sb.WriteString(bigNumberToZarith(contents.Amount)) + sb.WriteString(bigNumberToZarith(*contents.Amount)) var cleanDestination string if strings.HasPrefix(strings.ToLower(contents.Destination), "kt") { @@ -543,7 +543,7 @@ func ForgeRevealOperation(branch string, input ForgeRevealOperationInput) (*stri contents := Contents{ Source: input.Source, Fee: input.Fee, - Counter: Int{big.NewInt(int64(input.Counter))}, + Counter: NewInt(input.Counter), GasLimit: input.GasLimit, StorageLimit: input.StorageLimit, Phk: input.Phk, @@ -603,7 +603,7 @@ func ForgeOriginationOperation(branch string, input ForgeOriginationOperationInp contents := Contents{ Source: input.Source, Fee: input.Fee, - Counter: Int{big.NewInt(int64(input.Counter))}, + Counter: NewInt(input.Counter), GasLimit: input.GasLimit, StorageLimit: input.StorageLimit, Balance: input.Balance, @@ -634,7 +634,7 @@ func forgeOriginationOperation(contents Contents) (string, error) { } sb.WriteString(common) - sb.WriteString(bigNumberToZarith(contents.Balance)) + sb.WriteString(bigNumberToZarith(*contents.Balance)) source, err := removeHexPrefix(contents.Source, tz1prefix) if err != nil { @@ -695,7 +695,7 @@ func ForgeDelegationOperation(branch string, input ForgeDelegationOperationInput contents := Contents{ Source: input.Source, Fee: input.Fee, - Counter: Int{big.NewInt(int64(input.Counter))}, + Counter: NewInt(input.Counter), GasLimit: input.GasLimit, StorageLimit: input.StorageLimit, Delegate: input.Delegate, @@ -773,10 +773,10 @@ func forgeCommonFields(contents Contents) (string, error) { var sb strings.Builder sb.WriteString(source) - sb.WriteString(bigNumberToZarith(contents.Fee)) - sb.WriteString(bigNumberToZarith(contents.Counter)) - sb.WriteString(bigNumberToZarith(contents.GasLimit)) - sb.WriteString(bigNumberToZarith(contents.StorageLimit)) + sb.WriteString(bigNumberToZarith(*contents.Fee)) + sb.WriteString(bigNumberToZarith(*contents.Counter)) + sb.WriteString(bigNumberToZarith(*contents.GasLimit)) + sb.WriteString(bigNumberToZarith(*contents.StorageLimit)) return sb.String(), nil } @@ -1273,13 +1273,13 @@ func findZarithEndIndex(hexString string) (int, error) { return 0, errors.New("provided hex string is not Zarith encoded") } -func zarithToBigNumber(hexString string) (Int, error) { +func zarithToBigNumber(hexString string) (*Int, error) { var bitString string for i := 0; i < len(hexString); i += 2 { byteSection := hexString[i : i+2] intSection, err := strconv.ParseInt(byteSection, 16, 64) if err != nil { - return Int{}, errors.New("failed to find Zarith end index") + return NewInt(0), errors.New("failed to find Zarith end index") } bitSection := fmt.Sprintf("00000000%s", strconv.FormatInt(intSection, 2)) @@ -1290,11 +1290,11 @@ func zarithToBigNumber(hexString string) (Int, error) { n := new(big.Int) n, ok := n.SetString(bitString, 2) if !ok { - return Int{}, errors.New("failed to find Zarith end index") + return NewInt(0), errors.New("failed to find Zarith end index") } b := Int{n} - return b, nil + return &b, nil } func prefixAndBase58Encode(hexPayload string, prefix prefix) (string, error) { @@ -1363,7 +1363,7 @@ func validateTransaction(contents Contents) error { errs = append(errs, errors.New("wrong kind for transaction")) } - if contents.Amount.Big == nil { + if contents.Amount == nil { errs = append(errs, errors.New("missing amount")) } @@ -1384,7 +1384,7 @@ func validateOrigination(contents Contents) error { errs = append(errs, errors.New("wrong kind for origination")) } - if contents.Balance.Big == nil { + if contents.Balance == nil { errs = append(errs, errors.New("missing balance")) } @@ -1431,13 +1431,13 @@ func validateReveal(contents Contents) error { func validateCommon(contents Contents) error { var errs []error - if contents.Fee.Big == nil { + if contents.Fee == nil { errs = append(errs, errors.New("missing fee")) } - if contents.GasLimit.Big == nil { + if contents.GasLimit == nil { errs = append(errs, errors.New("missing gas limit")) } - if contents.StorageLimit.Big == nil { + if contents.StorageLimit == nil { errs = append(errs, errors.New("missing storage limit")) } if contents.Source == "" { diff --git a/vendor/golang.org/x/crypto/blake2b/blake2b.go b/vendor/golang.org/x/crypto/blake2b/blake2b.go index c160e1a..d2e98d4 100644 --- a/vendor/golang.org/x/crypto/blake2b/blake2b.go +++ b/vendor/golang.org/x/crypto/blake2b/blake2b.go @@ -5,6 +5,8 @@ // Package blake2b implements the BLAKE2b hash algorithm defined by RFC 7693 // and the extendable output function (XOF) BLAKE2Xb. // +// BLAKE2b is optimized for 64-bit platforms—including NEON-enabled ARMs—and +// produces digests of any size between 1 and 64 bytes. // For a detailed specification of BLAKE2b see https://blake2.net/blake2.pdf // and for BLAKE2Xb see https://blake2.net/blake2x.pdf // diff --git a/vendor/golang.org/x/crypto/poly1305/mac_noasm.go b/vendor/golang.org/x/crypto/poly1305/mac_noasm.go index b0c2cd0..347c8b1 100644 --- a/vendor/golang.org/x/crypto/poly1305/mac_noasm.go +++ b/vendor/golang.org/x/crypto/poly1305/mac_noasm.go @@ -7,5 +7,3 @@ package poly1305 type mac struct{ macGeneric } - -func newMAC(key *[32]byte) mac { return mac{newMACGeneric(key)} } diff --git a/vendor/golang.org/x/crypto/poly1305/poly1305.go b/vendor/golang.org/x/crypto/poly1305/poly1305.go index 066159b..3c75c2a 100644 --- a/vendor/golang.org/x/crypto/poly1305/poly1305.go +++ b/vendor/golang.org/x/crypto/poly1305/poly1305.go @@ -46,10 +46,9 @@ func Verify(mac *[16]byte, m []byte, key *[32]byte) bool { // two different messages with the same key allows an attacker // to forge messages at will. func New(key *[32]byte) *MAC { - return &MAC{ - mac: newMAC(key), - finalized: false, - } + m := &MAC{} + initialize(key, &m.macState) + return m } // MAC is an io.Writer computing an authentication tag @@ -58,7 +57,7 @@ func New(key *[32]byte) *MAC { // MAC cannot be used like common hash.Hash implementations, // because using a poly1305 key twice breaks its security. // Therefore writing data to a running MAC after calling -// Sum causes it to panic. +// Sum or Verify causes it to panic. type MAC struct { mac // platform-dependent implementation @@ -71,10 +70,10 @@ func (h *MAC) Size() int { return TagSize } // Write adds more data to the running message authentication code. // It never returns an error. // -// It must not be called after the first call of Sum. +// It must not be called after the first call of Sum or Verify. func (h *MAC) Write(p []byte) (n int, err error) { if h.finalized { - panic("poly1305: write to MAC after Sum") + panic("poly1305: write to MAC after Sum or Verify") } return h.mac.Write(p) } @@ -87,3 +86,12 @@ func (h *MAC) Sum(b []byte) []byte { h.finalized = true return append(b, mac[:]...) } + +// Verify returns whether the authenticator of all data written to +// the message authentication code matches the expected value. +func (h *MAC) Verify(expected []byte) bool { + var mac [TagSize]byte + h.mac.Sum(&mac) + h.finalized = true + return subtle.ConstantTimeCompare(expected, mac[:]) == 1 +} diff --git a/vendor/golang.org/x/crypto/poly1305/sum_amd64.go b/vendor/golang.org/x/crypto/poly1305/sum_amd64.go index 35b9e38..99e5a1d 100644 --- a/vendor/golang.org/x/crypto/poly1305/sum_amd64.go +++ b/vendor/golang.org/x/crypto/poly1305/sum_amd64.go @@ -9,17 +9,6 @@ package poly1305 //go:noescape func update(state *macState, msg []byte) -func sum(out *[16]byte, m []byte, key *[32]byte) { - h := newMAC(key) - h.Write(m) - h.Sum(out) -} - -func newMAC(key *[32]byte) (h mac) { - initialize(key, &h.r, &h.s) - return -} - // mac is a wrapper for macGeneric that redirects calls that would have gone to // updateGeneric to update. // diff --git a/vendor/golang.org/x/crypto/poly1305/sum_generic.go b/vendor/golang.org/x/crypto/poly1305/sum_generic.go index 1187eab..c77ff17 100644 --- a/vendor/golang.org/x/crypto/poly1305/sum_generic.go +++ b/vendor/golang.org/x/crypto/poly1305/sum_generic.go @@ -31,9 +31,10 @@ func sumGeneric(out *[TagSize]byte, msg []byte, key *[32]byte) { h.Sum(out) } -func newMACGeneric(key *[32]byte) (h macGeneric) { - initialize(key, &h.r, &h.s) - return +func newMACGeneric(key *[32]byte) macGeneric { + m := macGeneric{} + initialize(key, &m.macState) + return m } // macState holds numbers in saturated 64-bit little-endian limbs. That is, @@ -97,11 +98,12 @@ const ( rMask1 = 0x0FFFFFFC0FFFFFFC ) -func initialize(key *[32]byte, r, s *[2]uint64) { - r[0] = binary.LittleEndian.Uint64(key[0:8]) & rMask0 - r[1] = binary.LittleEndian.Uint64(key[8:16]) & rMask1 - s[0] = binary.LittleEndian.Uint64(key[16:24]) - s[1] = binary.LittleEndian.Uint64(key[24:32]) +// initialize loads the 256-bit key into the two 128-bit secret values r and s. +func initialize(key *[32]byte, m *macState) { + m.r[0] = binary.LittleEndian.Uint64(key[0:8]) & rMask0 + m.r[1] = binary.LittleEndian.Uint64(key[8:16]) & rMask1 + m.s[0] = binary.LittleEndian.Uint64(key[16:24]) + m.s[1] = binary.LittleEndian.Uint64(key[24:32]) } // uint128 holds a 128-bit number as two 64-bit limbs, for use with the diff --git a/vendor/golang.org/x/crypto/poly1305/sum_noasm.go b/vendor/golang.org/x/crypto/poly1305/sum_noasm.go index 2e3ae34..2b55a29 100644 --- a/vendor/golang.org/x/crypto/poly1305/sum_noasm.go +++ b/vendor/golang.org/x/crypto/poly1305/sum_noasm.go @@ -2,12 +2,17 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// +build s390x,!go1.11 !amd64,!s390x,!ppc64le gccgo purego +// At this point only s390x has an assembly implementation of sum. All other +// platforms have assembly implementations of mac, and just define sum as using +// that through New. Once s390x is ported, this file can be deleted and the body +// of sum moved into Sum. + +// +build !go1.11 !s390x gccgo purego package poly1305 func sum(out *[TagSize]byte, msg []byte, key *[32]byte) { - h := newMAC(key) + h := New(key) h.Write(msg) - h.Sum(out) + h.Sum(out[:0]) } diff --git a/vendor/golang.org/x/crypto/poly1305/sum_ppc64le.go b/vendor/golang.org/x/crypto/poly1305/sum_ppc64le.go index 92597bb..2e7a120 100644 --- a/vendor/golang.org/x/crypto/poly1305/sum_ppc64le.go +++ b/vendor/golang.org/x/crypto/poly1305/sum_ppc64le.go @@ -9,17 +9,6 @@ package poly1305 //go:noescape func update(state *macState, msg []byte) -func sum(out *[16]byte, m []byte, key *[32]byte) { - h := newMAC(key) - h.Write(m) - h.Sum(out) -} - -func newMAC(key *[32]byte) (h mac) { - initialize(key, &h.r, &h.s) - return -} - // mac is a wrapper for macGeneric that redirects calls that would have gone to // updateGeneric to update. // diff --git a/vendor/golang.org/x/sys/unix/README.md b/vendor/golang.org/x/sys/unix/README.md index ab433cc..579d2d7 100644 --- a/vendor/golang.org/x/sys/unix/README.md +++ b/vendor/golang.org/x/sys/unix/README.md @@ -89,7 +89,7 @@ constants. Adding new syscall numbers is mostly done by running the build on a sufficiently new installation of the target OS (or updating the source checkouts for the -new build system). However, depending on the OS, you make need to update the +new build system). However, depending on the OS, you may need to update the parsing in mksysnum. ### mksyscall.go @@ -163,7 +163,7 @@ The merge is performed in the following steps: ## Generated files -### `zerror_${GOOS}_${GOARCH}.go` +### `zerrors_${GOOS}_${GOARCH}.go` A file containing all of the system's generated error numbers, error strings, signal numbers, and constants. Generated by `mkerrors.sh` (see above). diff --git a/vendor/golang.org/x/sys/unix/errors_freebsd_386.go b/vendor/golang.org/x/sys/unix/errors_freebsd_386.go index c56bc8b..761db66 100644 --- a/vendor/golang.org/x/sys/unix/errors_freebsd_386.go +++ b/vendor/golang.org/x/sys/unix/errors_freebsd_386.go @@ -8,6 +8,7 @@ package unix const ( + DLT_HHDLC = 0x79 IFF_SMART = 0x20 IFT_1822 = 0x2 IFT_A12MPPSWITCH = 0x82 @@ -210,13 +211,18 @@ const ( IFT_XETHER = 0x1a IPPROTO_MAXID = 0x34 IPV6_FAITH = 0x1d + IPV6_MIN_MEMBERSHIPS = 0x1f IP_FAITH = 0x16 + IP_MAX_SOURCE_FILTER = 0x400 + IP_MIN_MEMBERSHIPS = 0x1f MAP_NORESERVE = 0x40 MAP_RENAME = 0x20 NET_RT_MAXID = 0x6 RTF_PRCLONING = 0x10000 RTM_OLDADD = 0x9 RTM_OLDDEL = 0xa + RT_CACHING_CONTEXT = 0x1 + RT_NORTREF = 0x2 SIOCADDRT = 0x8030720a SIOCALIFADDR = 0x8118691b SIOCDELRT = 0x8030720b diff --git a/vendor/golang.org/x/sys/unix/errors_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/errors_freebsd_amd64.go index 3e97711..070f44b 100644 --- a/vendor/golang.org/x/sys/unix/errors_freebsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/errors_freebsd_amd64.go @@ -8,6 +8,7 @@ package unix const ( + DLT_HHDLC = 0x79 IFF_SMART = 0x20 IFT_1822 = 0x2 IFT_A12MPPSWITCH = 0x82 @@ -210,13 +211,18 @@ const ( IFT_XETHER = 0x1a IPPROTO_MAXID = 0x34 IPV6_FAITH = 0x1d + IPV6_MIN_MEMBERSHIPS = 0x1f IP_FAITH = 0x16 + IP_MAX_SOURCE_FILTER = 0x400 + IP_MIN_MEMBERSHIPS = 0x1f MAP_NORESERVE = 0x40 MAP_RENAME = 0x20 NET_RT_MAXID = 0x6 RTF_PRCLONING = 0x10000 RTM_OLDADD = 0x9 RTM_OLDDEL = 0xa + RT_CACHING_CONTEXT = 0x1 + RT_NORTREF = 0x2 SIOCADDRT = 0x8040720a SIOCALIFADDR = 0x8118691b SIOCDELRT = 0x8040720b diff --git a/vendor/golang.org/x/sys/unix/errors_freebsd_arm64.go b/vendor/golang.org/x/sys/unix/errors_freebsd_arm64.go new file mode 100644 index 0000000..946dcf3 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/errors_freebsd_arm64.go @@ -0,0 +1,17 @@ +// Copyright 2020 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. + +// Constants that were deprecated or moved to enums in the FreeBSD headers. Keep +// them here for backwards compatibility. + +package unix + +const ( + DLT_HHDLC = 0x79 + IPV6_MIN_MEMBERSHIPS = 0x1f + IP_MAX_SOURCE_FILTER = 0x400 + IP_MIN_MEMBERSHIPS = 0x1f + RT_CACHING_CONTEXT = 0x1 + RT_NORTREF = 0x2 +) diff --git a/vendor/golang.org/x/sys/unix/mkall.sh b/vendor/golang.org/x/sys/unix/mkall.sh index fa0c69b..ece31e9 100644 --- a/vendor/golang.org/x/sys/unix/mkall.sh +++ b/vendor/golang.org/x/sys/unix/mkall.sh @@ -124,7 +124,7 @@ freebsd_arm) freebsd_arm64) mkerrors="$mkerrors -m64" mksysnum="go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" + mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" ;; netbsd_386) mkerrors="$mkerrors -m32" @@ -190,6 +190,12 @@ solaris_amd64) mksysnum= mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; +illumos_amd64) + mksyscall="go run mksyscall_solaris.go" + mkerrors= + mksysnum= + mktypes= + ;; *) echo 'unrecognized $GOOS_$GOARCH: ' "$GOOSARCH" 1>&2 exit 1 @@ -217,6 +223,11 @@ esac echo "$mksyscall -tags $GOOS,$GOARCH,go1.12 $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go"; # 1.13 and later, syscalls via libSystem (including syscallPtr) echo "$mksyscall -tags $GOOS,$GOARCH,go1.13 syscall_darwin.1_13.go |gofmt >zsyscall_$GOOSARCH.1_13.go"; + elif [ "$GOOS" == "illumos" ]; then + # illumos code generation requires a --illumos switch + echo "$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go"; + # illumos implies solaris, so solaris code generation is also required + echo "$mksyscall -tags solaris,$GOARCH syscall_solaris.go syscall_solaris_$GOARCH.go |gofmt >zsyscall_solaris_$GOARCH.go"; else echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go"; fi diff --git a/vendor/golang.org/x/sys/unix/mkerrors.sh b/vendor/golang.org/x/sys/unix/mkerrors.sh index 96bf2a9..ab09aaf 100644 --- a/vendor/golang.org/x/sys/unix/mkerrors.sh +++ b/vendor/golang.org/x/sys/unix/mkerrors.sh @@ -105,6 +105,7 @@ includes_FreeBSD=' #include #include #include +#include #include #include #include @@ -199,6 +200,7 @@ struct ltchars { #include #include #include +#include #include #include #include @@ -280,6 +282,11 @@ struct ltchars { // for the tipc_subscr timeout __u32 field. #undef TIPC_WAIT_FOREVER #define TIPC_WAIT_FOREVER 0xffffffff + +// Copied from linux/l2tp.h +// Including linux/l2tp.h here causes conflicts between linux/in.h +// and netinet/in.h included via net/route.h above. +#define IPPROTO_L2TP 115 ' includes_NetBSD=' @@ -479,6 +486,7 @@ ccflags="$@" $2 ~ /^LINUX_REBOOT_MAGIC[12]$/ || $2 ~ /^MODULE_INIT_/ || $2 !~ "NLA_TYPE_MASK" && + $2 !~ /^RTC_VL_(ACCURACY|BACKUP|DATA)/ && $2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ || $2 ~ /^SIOC/ || $2 ~ /^TIOC/ || @@ -488,6 +496,7 @@ ccflags="$@" $2 !~ "RTF_BITS" && $2 ~ /^(IFF|IFT|NET_RT|RTM(GRP)?|RTF|RTV|RTA|RTAX)_/ || $2 ~ /^BIOC/ || + $2 ~ /^DIOC/ || $2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ || $2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ || $2 ~ /^PRIO_(PROCESS|PGRP|USER)/ || @@ -499,7 +508,8 @@ ccflags="$@" $2 ~ /^CAP_/ || $2 ~ /^ALG_/ || $2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE)/ || - $2 ~ /^FS_IOC_.*ENCRYPTION/ || + $2 ~ /^FS_IOC_.*(ENCRYPTION|VERITY|GETFLAGS)/ || + $2 ~ /^FS_VERITY_/ || $2 ~ /^FSCRYPT_/ || $2 ~ /^GRND_/ || $2 ~ /^RND/ || diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd.go b/vendor/golang.org/x/sys/unix/syscall_freebsd.go index 6b2eca4..6932e7c 100644 --- a/vendor/golang.org/x/sys/unix/syscall_freebsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_freebsd.go @@ -521,10 +521,6 @@ func PtraceGetFpRegs(pid int, fpregsout *FpReg) (err error) { return ptrace(PTRACE_GETFPREGS, pid, uintptr(unsafe.Pointer(fpregsout)), 0) } -func PtraceGetFsBase(pid int, fsbase *int64) (err error) { - return ptrace(PTRACE_GETFSBASE, pid, uintptr(unsafe.Pointer(fsbase)), 0) -} - func PtraceGetRegs(pid int, regsout *Reg) (err error) { return ptrace(PTRACE_GETREGS, pid, uintptr(unsafe.Pointer(regsout)), 0) } diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go b/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go index 0a5a66f..72a506d 100644 --- a/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go +++ b/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go @@ -55,6 +55,10 @@ func sendfile(outfd int, infd int, offset *int64, count int) (written int, err e func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) +func PtraceGetFsBase(pid int, fsbase *int64) (err error) { + return ptrace(PTRACE_GETFSBASE, pid, uintptr(unsafe.Pointer(fsbase)), 0) +} + func PtraceIO(req int, pid int, addr uintptr, out []byte, countin int) (count int, err error) { ioDesc := PtraceIoDesc{Op: int32(req), Offs: (*byte)(unsafe.Pointer(addr)), Addr: (*byte)(unsafe.Pointer(&out[0])), Len: uint32(countin)} err = ptrace(PTRACE_IO, pid, uintptr(unsafe.Pointer(&ioDesc)), 0) diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go index 8025b22..d5e376a 100644 --- a/vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go @@ -55,6 +55,10 @@ func sendfile(outfd int, infd int, offset *int64, count int) (written int, err e func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) +func PtraceGetFsBase(pid int, fsbase *int64) (err error) { + return ptrace(PTRACE_GETFSBASE, pid, uintptr(unsafe.Pointer(fsbase)), 0) +} + func PtraceIO(req int, pid int, addr uintptr, out []byte, countin int) (count int, err error) { ioDesc := PtraceIoDesc{Op: int32(req), Offs: (*byte)(unsafe.Pointer(addr)), Addr: (*byte)(unsafe.Pointer(&out[0])), Len: uint64(countin)} err = ptrace(PTRACE_IO, pid, uintptr(unsafe.Pointer(&ioDesc)), 0) diff --git a/vendor/golang.org/x/sys/unix/syscall_illumos.go b/vendor/golang.org/x/sys/unix/syscall_illumos.go new file mode 100644 index 0000000..99e62dc --- /dev/null +++ b/vendor/golang.org/x/sys/unix/syscall_illumos.go @@ -0,0 +1,57 @@ +// 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. + +// illumos system calls not present on Solaris. + +// +build amd64,illumos + +package unix + +import "unsafe" + +func bytes2iovec(bs [][]byte) []Iovec { + iovecs := make([]Iovec, len(bs)) + for i, b := range bs { + iovecs[i].SetLen(len(b)) + if len(b) > 0 { + // somehow Iovec.Base on illumos is (*int8), not (*byte) + iovecs[i].Base = (*int8)(unsafe.Pointer(&b[0])) + } else { + iovecs[i].Base = (*int8)(unsafe.Pointer(&_zero)) + } + } + return iovecs +} + +//sys readv(fd int, iovs []Iovec) (n int, err error) + +func Readv(fd int, iovs [][]byte) (n int, err error) { + iovecs := bytes2iovec(iovs) + n, err = readv(fd, iovecs) + return n, err +} + +//sys preadv(fd int, iovs []Iovec, off int64) (n int, err error) + +func Preadv(fd int, iovs [][]byte, off int64) (n int, err error) { + iovecs := bytes2iovec(iovs) + n, err = preadv(fd, iovecs, off) + return n, err +} + +//sys writev(fd int, iovs []Iovec) (n int, err error) + +func Writev(fd int, iovs [][]byte) (n int, err error) { + iovecs := bytes2iovec(iovs) + n, err = writev(fd, iovecs) + return n, err +} + +//sys pwritev(fd int, iovs []Iovec, off int64) (n int, err error) + +func Pwritev(fd int, iovs [][]byte, off int64) (n int, err error) { + iovecs := bytes2iovec(iovs) + n, err = pwritev(fd, iovecs, off) + return n, err +} diff --git a/vendor/golang.org/x/sys/unix/syscall_linux.go b/vendor/golang.org/x/sys/unix/syscall_linux.go index 95f7a15..bbe1abb 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux.go @@ -839,6 +839,40 @@ func (sa *SockaddrTIPC) sockaddr() (unsafe.Pointer, _Socklen, error) { return unsafe.Pointer(&sa.raw), SizeofSockaddrTIPC, nil } +// SockaddrL2TPIP implements the Sockaddr interface for IPPROTO_L2TP/AF_INET sockets. +type SockaddrL2TPIP struct { + Addr [4]byte + ConnId uint32 + raw RawSockaddrL2TPIP +} + +func (sa *SockaddrL2TPIP) sockaddr() (unsafe.Pointer, _Socklen, error) { + sa.raw.Family = AF_INET + sa.raw.Conn_id = sa.ConnId + for i := 0; i < len(sa.Addr); i++ { + sa.raw.Addr[i] = sa.Addr[i] + } + return unsafe.Pointer(&sa.raw), SizeofSockaddrL2TPIP, nil +} + +// SockaddrL2TPIP6 implements the Sockaddr interface for IPPROTO_L2TP/AF_INET6 sockets. +type SockaddrL2TPIP6 struct { + Addr [16]byte + ZoneId uint32 + ConnId uint32 + raw RawSockaddrL2TPIP6 +} + +func (sa *SockaddrL2TPIP6) sockaddr() (unsafe.Pointer, _Socklen, error) { + sa.raw.Family = AF_INET6 + sa.raw.Conn_id = sa.ConnId + sa.raw.Scope_id = sa.ZoneId + for i := 0; i < len(sa.Addr); i++ { + sa.raw.Addr[i] = sa.Addr[i] + } + return unsafe.Pointer(&sa.raw), SizeofSockaddrL2TPIP6, nil +} + func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) { switch rsa.Addr.Family { case AF_NETLINK: @@ -889,25 +923,58 @@ func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) { return sa, nil case AF_INET: - pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa)) - sa := new(SockaddrInet4) - p := (*[2]byte)(unsafe.Pointer(&pp.Port)) - sa.Port = int(p[0])<<8 + int(p[1]) - for i := 0; i < len(sa.Addr); i++ { - sa.Addr[i] = pp.Addr[i] + proto, err := GetsockoptInt(fd, SOL_SOCKET, SO_PROTOCOL) + if err != nil { + return nil, err + } + + switch proto { + case IPPROTO_L2TP: + pp := (*RawSockaddrL2TPIP)(unsafe.Pointer(rsa)) + sa := new(SockaddrL2TPIP) + sa.ConnId = pp.Conn_id + for i := 0; i < len(sa.Addr); i++ { + sa.Addr[i] = pp.Addr[i] + } + return sa, nil + default: + pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa)) + sa := new(SockaddrInet4) + p := (*[2]byte)(unsafe.Pointer(&pp.Port)) + sa.Port = int(p[0])<<8 + int(p[1]) + for i := 0; i < len(sa.Addr); i++ { + sa.Addr[i] = pp.Addr[i] + } + return sa, nil } - return sa, nil case AF_INET6: - pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa)) - sa := new(SockaddrInet6) - p := (*[2]byte)(unsafe.Pointer(&pp.Port)) - sa.Port = int(p[0])<<8 + int(p[1]) - sa.ZoneId = pp.Scope_id - for i := 0; i < len(sa.Addr); i++ { - sa.Addr[i] = pp.Addr[i] + proto, err := GetsockoptInt(fd, SOL_SOCKET, SO_PROTOCOL) + if err != nil { + return nil, err + } + + switch proto { + case IPPROTO_L2TP: + pp := (*RawSockaddrL2TPIP6)(unsafe.Pointer(rsa)) + sa := new(SockaddrL2TPIP6) + sa.ConnId = pp.Conn_id + sa.ZoneId = pp.Scope_id + for i := 0; i < len(sa.Addr); i++ { + sa.Addr[i] = pp.Addr[i] + } + return sa, nil + default: + pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa)) + sa := new(SockaddrInet6) + p := (*[2]byte)(unsafe.Pointer(&pp.Port)) + sa.Port = int(p[0])<<8 + int(p[1]) + sa.ZoneId = pp.Scope_id + for i := 0; i < len(sa.Addr); i++ { + sa.Addr[i] = pp.Addr[i] + } + return sa, nil } - return sa, nil case AF_VSOCK: pp := (*RawSockaddrVM)(unsafe.Pointer(rsa)) diff --git a/vendor/golang.org/x/sys/unix/syscall_unix.go b/vendor/golang.org/x/sys/unix/syscall_unix.go index 3de3756..8f710d0 100644 --- a/vendor/golang.org/x/sys/unix/syscall_unix.go +++ b/vendor/golang.org/x/sys/unix/syscall_unix.go @@ -76,7 +76,7 @@ func SignalName(s syscall.Signal) string { // The signal name should start with "SIG". func SignalNum(s string) syscall.Signal { signalNameMapOnce.Do(func() { - signalNameMap = make(map[string]syscall.Signal) + signalNameMap = make(map[string]syscall.Signal, len(signalList)) for _, signal := range signalList { signalNameMap[signal.name] = signal.num } diff --git a/vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go b/vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go index b72544f..8482458 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go +++ b/vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go @@ -355,6 +355,22 @@ const ( CTL_KERN = 0x1 CTL_MAXNAME = 0x18 CTL_NET = 0x4 + DIOCGATTR = 0xc144648e + DIOCGDELETE = 0x80106488 + DIOCGFLUSH = 0x20006487 + DIOCGFRONTSTUFF = 0x40086486 + DIOCGFWHEADS = 0x40046483 + DIOCGFWSECTORS = 0x40046482 + DIOCGIDENT = 0x41006489 + DIOCGMEDIASIZE = 0x40086481 + DIOCGPHYSPATH = 0x4400648d + DIOCGPROVIDERNAME = 0x4400648a + DIOCGSECTORSIZE = 0x40046480 + DIOCGSTRIPEOFFSET = 0x4008648c + DIOCGSTRIPESIZE = 0x4008648b + DIOCSKERNELDUMP = 0x804c6490 + DIOCSKERNELDUMP_FREEBSD11 = 0x80046485 + DIOCZONECMD = 0xc06c648f DLT_A429 = 0xb8 DLT_A653_ICM = 0xb9 DLT_AIRONET_HEADER = 0x78 @@ -379,11 +395,14 @@ const ( DLT_CHAOS = 0x5 DLT_CHDLC = 0x68 DLT_CISCO_IOS = 0x76 + DLT_CLASS_NETBSD_RAWAF = 0x2240000 DLT_C_HDLC = 0x68 DLT_C_HDLC_WITH_DIR = 0xcd DLT_DBUS = 0xe7 DLT_DECT = 0xdd + DLT_DISPLAYPORT_AUX = 0x113 DLT_DOCSIS = 0x8f + DLT_DOCSIS31_XRA31 = 0x111 DLT_DVB_CI = 0xeb DLT_ECONET = 0x73 DLT_EN10MB = 0x1 @@ -393,6 +412,7 @@ const ( DLT_ERF = 0xc5 DLT_ERF_ETH = 0xaf DLT_ERF_POS = 0xb0 + DLT_ETHERNET_MPACKET = 0x112 DLT_FC_2 = 0xe0 DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 DLT_FDDI = 0xa @@ -406,7 +426,6 @@ const ( DLT_GPRS_LLC = 0xa9 DLT_GSMTAP_ABIS = 0xda DLT_GSMTAP_UM = 0xd9 - DLT_HHDLC = 0x79 DLT_IBM_SN = 0x92 DLT_IBM_SP = 0x91 DLT_IEEE802 = 0x6 @@ -429,6 +448,7 @@ const ( DLT_IPV4 = 0xe4 DLT_IPV6 = 0xe5 DLT_IP_OVER_FC = 0x7a + DLT_ISO_14443 = 0x108 DLT_JUNIPER_ATM1 = 0x89 DLT_JUNIPER_ATM2 = 0x87 DLT_JUNIPER_ATM_CEMIC = 0xee @@ -461,8 +481,9 @@ const ( DLT_LINUX_PPP_WITHDIRECTION = 0xa6 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c + DLT_LORATAP = 0x10e DLT_LTALK = 0x72 - DLT_MATCHING_MAX = 0x104 + DLT_MATCHING_MAX = 0x113 DLT_MATCHING_MIN = 0x68 DLT_MFR = 0xb6 DLT_MOST = 0xd3 @@ -478,14 +499,16 @@ const ( DLT_NFC_LLCP = 0xf5 DLT_NFLOG = 0xef DLT_NG40 = 0xf4 + DLT_NORDIC_BLE = 0x110 DLT_NULL = 0x0 + DLT_OPENFLOW = 0x10b DLT_PCI_EXP = 0x7d DLT_PFLOG = 0x75 DLT_PFSYNC = 0x79 DLT_PKTAP = 0x102 DLT_PPI = 0xc0 DLT_PPP = 0x9 - DLT_PPP_BSDOS = 0x10 + DLT_PPP_BSDOS = 0xe DLT_PPP_ETHER = 0x33 DLT_PPP_PPPD = 0xa6 DLT_PPP_SERIAL = 0x32 @@ -496,19 +519,25 @@ const ( DLT_PRONET = 0x4 DLT_RAIF1 = 0xc6 DLT_RAW = 0xc + DLT_RDS = 0x109 + DLT_REDBACK_SMARTEDGE = 0x20 DLT_RIO = 0x7c DLT_RTAC_SERIAL = 0xfa DLT_SCCP = 0x8e DLT_SCTP = 0xf8 + DLT_SDLC = 0x10c DLT_SITA = 0xc4 DLT_SLIP = 0x8 - DLT_SLIP_BSDOS = 0xf + DLT_SLIP_BSDOS = 0xd DLT_STANAG_5066_D_PDU = 0xed DLT_SUNATM = 0x7b DLT_SYMANTEC_FIREWALL = 0x63 + DLT_TI_LLN_SNIFFER = 0x10d DLT_TZSP = 0x80 DLT_USB = 0xba DLT_USBPCAP = 0xf9 + DLT_USB_DARWIN = 0x10a + DLT_USB_FREEBSD = 0xba DLT_USB_LINUX = 0xbd DLT_USB_LINUX_MMAPPED = 0xdc DLT_USER0 = 0x93 @@ -527,10 +556,14 @@ const ( DLT_USER7 = 0x9a DLT_USER8 = 0x9b DLT_USER9 = 0x9c + DLT_VSOCK = 0x10f + DLT_WATTSTOPPER_DLM = 0x107 DLT_WIHART = 0xdf DLT_WIRESHARK_UPPER_PDU = 0xfc DLT_X2E_SERIAL = 0xd5 DLT_X2E_XORAYA = 0xd6 + DLT_ZWAVE_R1_R2 = 0x105 + DLT_ZWAVE_R3 = 0x106 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 @@ -548,6 +581,7 @@ const ( ECHONL = 0x10 ECHOPRT = 0x20 EVFILT_AIO = -0x3 + EVFILT_EMPTY = -0xd EVFILT_FS = -0x9 EVFILT_LIO = -0xa EVFILT_PROC = -0x5 @@ -555,11 +589,12 @@ const ( EVFILT_READ = -0x1 EVFILT_SENDFILE = -0xc EVFILT_SIGNAL = -0x6 - EVFILT_SYSCOUNT = 0xc + EVFILT_SYSCOUNT = 0xd EVFILT_TIMER = -0x7 EVFILT_USER = -0xb EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 + EVNAMEMAP_NAME_SIZE = 0x40 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 @@ -576,6 +611,7 @@ const ( EV_RECEIPT = 0x40 EV_SYSFLAGS = 0xf000 EXTA = 0x4b00 + EXTATTR_MAXNAMELEN = 0xff EXTATTR_NAMESPACE_EMPTY = 0x0 EXTATTR_NAMESPACE_SYSTEM = 0x2 EXTATTR_NAMESPACE_USER = 0x1 @@ -617,6 +653,7 @@ const ( IEXTEN = 0x400 IFAN_ARRIVAL = 0x0 IFAN_DEPARTURE = 0x1 + IFCAP_WOL_MAGIC = 0x2000 IFF_ALLMULTI = 0x200 IFF_ALTPHYS = 0x4000 IFF_BROADCAST = 0x2 @@ -633,6 +670,7 @@ const ( IFF_MONITOR = 0x40000 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 + IFF_NOGROUP = 0x800000 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PPROMISC = 0x20000 @@ -807,6 +845,7 @@ const ( IPV6_DSTOPTS = 0x32 IPV6_FLOWID = 0x43 IPV6_FLOWINFO_MASK = 0xffffff0f + IPV6_FLOWLABEL_LEN = 0x14 IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FLOWTYPE = 0x44 IPV6_FRAGTTL = 0x78 @@ -827,13 +866,13 @@ const ( IPV6_MAX_GROUP_SRC_FILTER = 0x200 IPV6_MAX_MEMBERSHIPS = 0xfff IPV6_MAX_SOCK_SRC_FILTER = 0x80 - IPV6_MIN_MEMBERSHIPS = 0x1f IPV6_MMTU = 0x500 IPV6_MSFILTER = 0x4a IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_NEXTHOP = 0x30 + IPV6_ORIGDSTADDR = 0x48 IPV6_PATHMTU = 0x2c IPV6_PKTINFO = 0x2e IPV6_PORTRANGE = 0xe @@ -845,6 +884,7 @@ const ( IPV6_RECVFLOWID = 0x46 IPV6_RECVHOPLIMIT = 0x25 IPV6_RECVHOPOPTS = 0x27 + IPV6_RECVORIGDSTADDR = 0x48 IPV6_RECVPATHMTU = 0x2b IPV6_RECVPKTINFO = 0x24 IPV6_RECVRSSBUCKETID = 0x47 @@ -905,10 +945,8 @@ const ( IP_MAX_MEMBERSHIPS = 0xfff IP_MAX_SOCK_MUTE_FILTER = 0x80 IP_MAX_SOCK_SRC_FILTER = 0x80 - IP_MAX_SOURCE_FILTER = 0x400 IP_MF = 0x2000 IP_MINTTL = 0x42 - IP_MIN_MEMBERSHIPS = 0x1f IP_MSFILTER = 0x4a IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 @@ -918,6 +956,7 @@ const ( IP_OFFMASK = 0x1fff IP_ONESBCAST = 0x17 IP_OPTIONS = 0x1 + IP_ORIGDSTADDR = 0x1b IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 @@ -926,6 +965,7 @@ const ( IP_RECVFLOWID = 0x5d IP_RECVIF = 0x14 IP_RECVOPTS = 0x5 + IP_RECVORIGDSTADDR = 0x1b IP_RECVRETOPTS = 0x6 IP_RECVRSSBUCKETID = 0x5e IP_RECVTOS = 0x44 @@ -975,6 +1015,7 @@ const ( MAP_EXCL = 0x4000 MAP_FILE = 0x0 MAP_FIXED = 0x10 + MAP_GUARD = 0x2000 MAP_HASSEMAPHORE = 0x200 MAP_NOCORE = 0x20000 MAP_NOSYNC = 0x800 @@ -986,6 +1027,15 @@ const ( MAP_RESERVED0100 = 0x100 MAP_SHARED = 0x1 MAP_STACK = 0x400 + MCAST_BLOCK_SOURCE = 0x54 + MCAST_EXCLUDE = 0x2 + MCAST_INCLUDE = 0x1 + MCAST_JOIN_GROUP = 0x50 + MCAST_JOIN_SOURCE_GROUP = 0x52 + MCAST_LEAVE_GROUP = 0x51 + MCAST_LEAVE_SOURCE_GROUP = 0x53 + MCAST_UNBLOCK_SOURCE = 0x55 + MCAST_UNDEFINED = 0x0 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MNT_ACLS = 0x8000000 @@ -1026,10 +1076,12 @@ const ( MNT_SUSPEND = 0x4 MNT_SYNCHRONOUS = 0x2 MNT_UNION = 0x20 + MNT_UNTRUSTED = 0x800000000 MNT_UPDATE = 0x10000 - MNT_UPDATEMASK = 0x2d8d0807e + MNT_UPDATEMASK = 0xad8d0807e MNT_USER = 0x8000 - MNT_VISFLAGMASK = 0x3fef0ffff + MNT_VERIFIED = 0x400000000 + MNT_VISFLAGMASK = 0xffef0ffff MNT_WAIT = 0x1 MSG_CMSG_CLOEXEC = 0x40000 MSG_COMPAT = 0x8000 @@ -1058,6 +1110,7 @@ const ( NFDBITS = 0x20 NOFLSH = 0x80000000 NOKERNINFO = 0x2000000 + NOTE_ABSTIME = 0x10 NOTE_ATTRIB = 0x8 NOTE_CHILD = 0x4 NOTE_CLOSE = 0x100 @@ -1212,7 +1265,6 @@ const ( RTV_WEIGHT = 0x100 RT_ALL_FIBS = -0x1 RT_BLACKHOLE = 0x40 - RT_CACHING_CONTEXT = 0x1 RT_DEFAULT_FIB = 0x0 RT_HAS_GW = 0x80 RT_HAS_HEADER = 0x10 @@ -1222,15 +1274,17 @@ const ( RT_LLE_CACHE = 0x100 RT_MAY_LOOP = 0x8 RT_MAY_LOOP_BIT = 0x3 - RT_NORTREF = 0x2 RT_REJECT = 0x20 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_BINTIME = 0x4 SCM_CREDS = 0x3 + SCM_MONOTONIC = 0x6 + SCM_REALTIME = 0x5 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x2 + SCM_TIME_INFO = 0x7 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 @@ -1246,6 +1300,7 @@ const ( SIOCGETSGCNT = 0xc0147210 SIOCGETVIFCNT = 0xc014720f SIOCGHIWAT = 0x40047301 + SIOCGHWADDR = 0xc020693e SIOCGI2C = 0xc020693d SIOCGIFADDR = 0xc0206921 SIOCGIFBRDADDR = 0xc0206923 @@ -1267,8 +1322,11 @@ const ( SIOCGIFPDSTADDR = 0xc0206948 SIOCGIFPHYS = 0xc0206935 SIOCGIFPSRCADDR = 0xc0206947 + SIOCGIFRSSHASH = 0xc0186997 + SIOCGIFRSSKEY = 0xc0946996 SIOCGIFSTATUS = 0xc331693b SIOCGIFXMEDIA = 0xc028698b + SIOCGLANPCP = 0xc0206998 SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGPRIVATE_0 = 0xc0206950 @@ -1299,6 +1357,7 @@ const ( SIOCSIFPHYS = 0x80206936 SIOCSIFRVNET = 0xc020695b SIOCSIFVNET = 0xc020695a + SIOCSLANPCP = 0x80206999 SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SIOCSTUNFIB = 0x8020695f @@ -1317,6 +1376,7 @@ const ( SO_BINTIME = 0x2000 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 + SO_DOMAIN = 0x1019 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 @@ -1325,6 +1385,7 @@ const ( SO_LISTENINCQLEN = 0x1013 SO_LISTENQLEN = 0x1012 SO_LISTENQLIMIT = 0x1011 + SO_MAX_PACING_RATE = 0x1018 SO_NOSIGPIPE = 0x800 SO_NO_DDP = 0x8000 SO_NO_OFFLOAD = 0x4000 @@ -1337,11 +1398,19 @@ const ( SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 + SO_REUSEPORT_LB = 0x10000 SO_SETFIB = 0x1014 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_TIMESTAMP = 0x400 + SO_TS_BINTIME = 0x1 + SO_TS_CLOCK = 0x1017 + SO_TS_CLOCK_MAX = 0x3 + SO_TS_DEFAULT = 0x0 + SO_TS_MONOTONIC = 0x3 + SO_TS_REALTIME = 0x2 + SO_TS_REALTIME_MICRO = 0x0 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 SO_USER_COOKIE = 0x1015 @@ -1385,10 +1454,45 @@ const ( TCOFLUSH = 0x2 TCOOFF = 0x1 TCOON = 0x2 + TCP_BBR_ACK_COMP_ALG = 0x448 + TCP_BBR_DRAIN_INC_EXTRA = 0x43c + TCP_BBR_DRAIN_PG = 0x42e + TCP_BBR_EXTRA_GAIN = 0x449 + TCP_BBR_IWINTSO = 0x42b + TCP_BBR_LOWGAIN_FD = 0x436 + TCP_BBR_LOWGAIN_HALF = 0x435 + TCP_BBR_LOWGAIN_THRESH = 0x434 + TCP_BBR_MAX_RTO = 0x439 + TCP_BBR_MIN_RTO = 0x438 + TCP_BBR_ONE_RETRAN = 0x431 + TCP_BBR_PACE_CROSS = 0x442 + TCP_BBR_PACE_DEL_TAR = 0x43f + TCP_BBR_PACE_PER_SEC = 0x43e + TCP_BBR_PACE_SEG_MAX = 0x440 + TCP_BBR_PACE_SEG_MIN = 0x441 + TCP_BBR_PROBE_RTT_GAIN = 0x44d + TCP_BBR_PROBE_RTT_INT = 0x430 + TCP_BBR_PROBE_RTT_LEN = 0x44e + TCP_BBR_RACK_RTT_USE = 0x44a + TCP_BBR_RECFORCE = 0x42c + TCP_BBR_REC_OVER_HPTS = 0x43a + TCP_BBR_RETRAN_WTSO = 0x44b + TCP_BBR_RWND_IS_APP = 0x42f + TCP_BBR_STARTUP_EXIT_EPOCH = 0x43d + TCP_BBR_STARTUP_LOSS_EXIT = 0x432 + TCP_BBR_STARTUP_PG = 0x42d + TCP_BBR_UNLIMITED = 0x43b + TCP_BBR_USEDEL_RATE = 0x437 + TCP_BBR_USE_LOWGAIN = 0x433 TCP_CA_NAME_MAX = 0x10 TCP_CCALGOOPT = 0x41 TCP_CONGESTION = 0x40 + TCP_DATA_AFTER_CLOSE = 0x44c + TCP_DELACK = 0x48 TCP_FASTOPEN = 0x401 + TCP_FASTOPEN_MAX_COOKIE_LEN = 0x10 + TCP_FASTOPEN_MIN_COOKIE_LEN = 0x4 + TCP_FASTOPEN_PSK_LEN = 0x10 TCP_FUNCTION_BLK = 0x2000 TCP_FUNCTION_NAME_LEN_MAX = 0x20 TCP_INFO = 0x20 @@ -1396,6 +1500,12 @@ const ( TCP_KEEPIDLE = 0x100 TCP_KEEPINIT = 0x80 TCP_KEEPINTVL = 0x200 + TCP_LOG = 0x22 + TCP_LOGBUF = 0x23 + TCP_LOGDUMP = 0x25 + TCP_LOGDUMPID = 0x26 + TCP_LOGID = 0x24 + TCP_LOG_ID_LEN = 0x40 TCP_MAXBURST = 0x4 TCP_MAXHLEN = 0x3c TCP_MAXOLEN = 0x28 @@ -1411,8 +1521,30 @@ const ( TCP_NOPUSH = 0x4 TCP_PCAP_IN = 0x1000 TCP_PCAP_OUT = 0x800 + TCP_RACK_EARLY_RECOV = 0x423 + TCP_RACK_EARLY_SEG = 0x424 + TCP_RACK_IDLE_REDUCE_HIGH = 0x444 + TCP_RACK_MIN_PACE = 0x445 + TCP_RACK_MIN_PACE_SEG = 0x446 + TCP_RACK_MIN_TO = 0x422 + TCP_RACK_PACE_ALWAYS = 0x41f + TCP_RACK_PACE_MAX_SEG = 0x41e + TCP_RACK_PACE_REDUCE = 0x41d + TCP_RACK_PKT_DELAY = 0x428 + TCP_RACK_PROP = 0x41b + TCP_RACK_PROP_RATE = 0x420 + TCP_RACK_PRR_SENDALOT = 0x421 + TCP_RACK_REORD_FADE = 0x426 + TCP_RACK_REORD_THRESH = 0x425 + TCP_RACK_SESS_CWV = 0x42a + TCP_RACK_TLP_INC_VAR = 0x429 + TCP_RACK_TLP_REDUCE = 0x41c + TCP_RACK_TLP_THRESH = 0x427 + TCP_RACK_TLP_USE = 0x447 TCP_VENDOR = 0x80000000 TCSAFLUSH = 0x2 + TIMER_ABSTIME = 0x1 + TIMER_RELTIME = 0x0 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 @@ -1476,6 +1608,8 @@ const ( TIOCTIMESTAMP = 0x40087459 TIOCUCNTL = 0x80047466 TOSTOP = 0x400000 + UTIME_NOW = -0x1 + UTIME_OMIT = -0x2 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 @@ -1487,6 +1621,8 @@ const ( VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 + VM_BCACHE_SIZE_MAX = 0x70e0000 + VM_SWZONE_SIZE_MAX = 0x2280000 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc diff --git a/vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go index 9f38267..4acd101 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go @@ -355,6 +355,22 @@ const ( CTL_KERN = 0x1 CTL_MAXNAME = 0x18 CTL_NET = 0x4 + DIOCGATTR = 0xc148648e + DIOCGDELETE = 0x80106488 + DIOCGFLUSH = 0x20006487 + DIOCGFRONTSTUFF = 0x40086486 + DIOCGFWHEADS = 0x40046483 + DIOCGFWSECTORS = 0x40046482 + DIOCGIDENT = 0x41006489 + DIOCGMEDIASIZE = 0x40086481 + DIOCGPHYSPATH = 0x4400648d + DIOCGPROVIDERNAME = 0x4400648a + DIOCGSECTORSIZE = 0x40046480 + DIOCGSTRIPEOFFSET = 0x4008648c + DIOCGSTRIPESIZE = 0x4008648b + DIOCSKERNELDUMP = 0x80506490 + DIOCSKERNELDUMP_FREEBSD11 = 0x80046485 + DIOCZONECMD = 0xc080648f DLT_A429 = 0xb8 DLT_A653_ICM = 0xb9 DLT_AIRONET_HEADER = 0x78 @@ -379,11 +395,14 @@ const ( DLT_CHAOS = 0x5 DLT_CHDLC = 0x68 DLT_CISCO_IOS = 0x76 + DLT_CLASS_NETBSD_RAWAF = 0x2240000 DLT_C_HDLC = 0x68 DLT_C_HDLC_WITH_DIR = 0xcd DLT_DBUS = 0xe7 DLT_DECT = 0xdd + DLT_DISPLAYPORT_AUX = 0x113 DLT_DOCSIS = 0x8f + DLT_DOCSIS31_XRA31 = 0x111 DLT_DVB_CI = 0xeb DLT_ECONET = 0x73 DLT_EN10MB = 0x1 @@ -393,6 +412,7 @@ const ( DLT_ERF = 0xc5 DLT_ERF_ETH = 0xaf DLT_ERF_POS = 0xb0 + DLT_ETHERNET_MPACKET = 0x112 DLT_FC_2 = 0xe0 DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 DLT_FDDI = 0xa @@ -406,7 +426,6 @@ const ( DLT_GPRS_LLC = 0xa9 DLT_GSMTAP_ABIS = 0xda DLT_GSMTAP_UM = 0xd9 - DLT_HHDLC = 0x79 DLT_IBM_SN = 0x92 DLT_IBM_SP = 0x91 DLT_IEEE802 = 0x6 @@ -429,6 +448,7 @@ const ( DLT_IPV4 = 0xe4 DLT_IPV6 = 0xe5 DLT_IP_OVER_FC = 0x7a + DLT_ISO_14443 = 0x108 DLT_JUNIPER_ATM1 = 0x89 DLT_JUNIPER_ATM2 = 0x87 DLT_JUNIPER_ATM_CEMIC = 0xee @@ -461,8 +481,9 @@ const ( DLT_LINUX_PPP_WITHDIRECTION = 0xa6 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c + DLT_LORATAP = 0x10e DLT_LTALK = 0x72 - DLT_MATCHING_MAX = 0x104 + DLT_MATCHING_MAX = 0x113 DLT_MATCHING_MIN = 0x68 DLT_MFR = 0xb6 DLT_MOST = 0xd3 @@ -478,14 +499,16 @@ const ( DLT_NFC_LLCP = 0xf5 DLT_NFLOG = 0xef DLT_NG40 = 0xf4 + DLT_NORDIC_BLE = 0x110 DLT_NULL = 0x0 + DLT_OPENFLOW = 0x10b DLT_PCI_EXP = 0x7d DLT_PFLOG = 0x75 DLT_PFSYNC = 0x79 DLT_PKTAP = 0x102 DLT_PPI = 0xc0 DLT_PPP = 0x9 - DLT_PPP_BSDOS = 0x10 + DLT_PPP_BSDOS = 0xe DLT_PPP_ETHER = 0x33 DLT_PPP_PPPD = 0xa6 DLT_PPP_SERIAL = 0x32 @@ -496,19 +519,25 @@ const ( DLT_PRONET = 0x4 DLT_RAIF1 = 0xc6 DLT_RAW = 0xc + DLT_RDS = 0x109 + DLT_REDBACK_SMARTEDGE = 0x20 DLT_RIO = 0x7c DLT_RTAC_SERIAL = 0xfa DLT_SCCP = 0x8e DLT_SCTP = 0xf8 + DLT_SDLC = 0x10c DLT_SITA = 0xc4 DLT_SLIP = 0x8 - DLT_SLIP_BSDOS = 0xf + DLT_SLIP_BSDOS = 0xd DLT_STANAG_5066_D_PDU = 0xed DLT_SUNATM = 0x7b DLT_SYMANTEC_FIREWALL = 0x63 + DLT_TI_LLN_SNIFFER = 0x10d DLT_TZSP = 0x80 DLT_USB = 0xba DLT_USBPCAP = 0xf9 + DLT_USB_DARWIN = 0x10a + DLT_USB_FREEBSD = 0xba DLT_USB_LINUX = 0xbd DLT_USB_LINUX_MMAPPED = 0xdc DLT_USER0 = 0x93 @@ -527,10 +556,14 @@ const ( DLT_USER7 = 0x9a DLT_USER8 = 0x9b DLT_USER9 = 0x9c + DLT_VSOCK = 0x10f + DLT_WATTSTOPPER_DLM = 0x107 DLT_WIHART = 0xdf DLT_WIRESHARK_UPPER_PDU = 0xfc DLT_X2E_SERIAL = 0xd5 DLT_X2E_XORAYA = 0xd6 + DLT_ZWAVE_R1_R2 = 0x105 + DLT_ZWAVE_R3 = 0x106 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 @@ -548,6 +581,7 @@ const ( ECHONL = 0x10 ECHOPRT = 0x20 EVFILT_AIO = -0x3 + EVFILT_EMPTY = -0xd EVFILT_FS = -0x9 EVFILT_LIO = -0xa EVFILT_PROC = -0x5 @@ -555,11 +589,12 @@ const ( EVFILT_READ = -0x1 EVFILT_SENDFILE = -0xc EVFILT_SIGNAL = -0x6 - EVFILT_SYSCOUNT = 0xc + EVFILT_SYSCOUNT = 0xd EVFILT_TIMER = -0x7 EVFILT_USER = -0xb EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 + EVNAMEMAP_NAME_SIZE = 0x40 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 @@ -576,6 +611,7 @@ const ( EV_RECEIPT = 0x40 EV_SYSFLAGS = 0xf000 EXTA = 0x4b00 + EXTATTR_MAXNAMELEN = 0xff EXTATTR_NAMESPACE_EMPTY = 0x0 EXTATTR_NAMESPACE_SYSTEM = 0x2 EXTATTR_NAMESPACE_USER = 0x1 @@ -617,6 +653,7 @@ const ( IEXTEN = 0x400 IFAN_ARRIVAL = 0x0 IFAN_DEPARTURE = 0x1 + IFCAP_WOL_MAGIC = 0x2000 IFF_ALLMULTI = 0x200 IFF_ALTPHYS = 0x4000 IFF_BROADCAST = 0x2 @@ -633,6 +670,7 @@ const ( IFF_MONITOR = 0x40000 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 + IFF_NOGROUP = 0x800000 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PPROMISC = 0x20000 @@ -807,6 +845,7 @@ const ( IPV6_DSTOPTS = 0x32 IPV6_FLOWID = 0x43 IPV6_FLOWINFO_MASK = 0xffffff0f + IPV6_FLOWLABEL_LEN = 0x14 IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FLOWTYPE = 0x44 IPV6_FRAGTTL = 0x78 @@ -827,13 +866,13 @@ const ( IPV6_MAX_GROUP_SRC_FILTER = 0x200 IPV6_MAX_MEMBERSHIPS = 0xfff IPV6_MAX_SOCK_SRC_FILTER = 0x80 - IPV6_MIN_MEMBERSHIPS = 0x1f IPV6_MMTU = 0x500 IPV6_MSFILTER = 0x4a IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_NEXTHOP = 0x30 + IPV6_ORIGDSTADDR = 0x48 IPV6_PATHMTU = 0x2c IPV6_PKTINFO = 0x2e IPV6_PORTRANGE = 0xe @@ -845,6 +884,7 @@ const ( IPV6_RECVFLOWID = 0x46 IPV6_RECVHOPLIMIT = 0x25 IPV6_RECVHOPOPTS = 0x27 + IPV6_RECVORIGDSTADDR = 0x48 IPV6_RECVPATHMTU = 0x2b IPV6_RECVPKTINFO = 0x24 IPV6_RECVRSSBUCKETID = 0x47 @@ -905,10 +945,8 @@ const ( IP_MAX_MEMBERSHIPS = 0xfff IP_MAX_SOCK_MUTE_FILTER = 0x80 IP_MAX_SOCK_SRC_FILTER = 0x80 - IP_MAX_SOURCE_FILTER = 0x400 IP_MF = 0x2000 IP_MINTTL = 0x42 - IP_MIN_MEMBERSHIPS = 0x1f IP_MSFILTER = 0x4a IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 @@ -918,6 +956,7 @@ const ( IP_OFFMASK = 0x1fff IP_ONESBCAST = 0x17 IP_OPTIONS = 0x1 + IP_ORIGDSTADDR = 0x1b IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 @@ -926,6 +965,7 @@ const ( IP_RECVFLOWID = 0x5d IP_RECVIF = 0x14 IP_RECVOPTS = 0x5 + IP_RECVORIGDSTADDR = 0x1b IP_RECVRETOPTS = 0x6 IP_RECVRSSBUCKETID = 0x5e IP_RECVTOS = 0x44 @@ -976,6 +1016,7 @@ const ( MAP_EXCL = 0x4000 MAP_FILE = 0x0 MAP_FIXED = 0x10 + MAP_GUARD = 0x2000 MAP_HASSEMAPHORE = 0x200 MAP_NOCORE = 0x20000 MAP_NOSYNC = 0x800 @@ -987,6 +1028,15 @@ const ( MAP_RESERVED0100 = 0x100 MAP_SHARED = 0x1 MAP_STACK = 0x400 + MCAST_BLOCK_SOURCE = 0x54 + MCAST_EXCLUDE = 0x2 + MCAST_INCLUDE = 0x1 + MCAST_JOIN_GROUP = 0x50 + MCAST_JOIN_SOURCE_GROUP = 0x52 + MCAST_LEAVE_GROUP = 0x51 + MCAST_LEAVE_SOURCE_GROUP = 0x53 + MCAST_UNBLOCK_SOURCE = 0x55 + MCAST_UNDEFINED = 0x0 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MNT_ACLS = 0x8000000 @@ -1027,10 +1077,12 @@ const ( MNT_SUSPEND = 0x4 MNT_SYNCHRONOUS = 0x2 MNT_UNION = 0x20 + MNT_UNTRUSTED = 0x800000000 MNT_UPDATE = 0x10000 - MNT_UPDATEMASK = 0x2d8d0807e + MNT_UPDATEMASK = 0xad8d0807e MNT_USER = 0x8000 - MNT_VISFLAGMASK = 0x3fef0ffff + MNT_VERIFIED = 0x400000000 + MNT_VISFLAGMASK = 0xffef0ffff MNT_WAIT = 0x1 MSG_CMSG_CLOEXEC = 0x40000 MSG_COMPAT = 0x8000 @@ -1059,6 +1111,7 @@ const ( NFDBITS = 0x40 NOFLSH = 0x80000000 NOKERNINFO = 0x2000000 + NOTE_ABSTIME = 0x10 NOTE_ATTRIB = 0x8 NOTE_CHILD = 0x4 NOTE_CLOSE = 0x100 @@ -1213,7 +1266,6 @@ const ( RTV_WEIGHT = 0x100 RT_ALL_FIBS = -0x1 RT_BLACKHOLE = 0x40 - RT_CACHING_CONTEXT = 0x1 RT_DEFAULT_FIB = 0x0 RT_HAS_GW = 0x80 RT_HAS_HEADER = 0x10 @@ -1223,15 +1275,17 @@ const ( RT_LLE_CACHE = 0x100 RT_MAY_LOOP = 0x8 RT_MAY_LOOP_BIT = 0x3 - RT_NORTREF = 0x2 RT_REJECT = 0x20 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_BINTIME = 0x4 SCM_CREDS = 0x3 + SCM_MONOTONIC = 0x6 + SCM_REALTIME = 0x5 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x2 + SCM_TIME_INFO = 0x7 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 @@ -1247,6 +1301,7 @@ const ( SIOCGETSGCNT = 0xc0207210 SIOCGETVIFCNT = 0xc028720f SIOCGHIWAT = 0x40047301 + SIOCGHWADDR = 0xc020693e SIOCGI2C = 0xc020693d SIOCGIFADDR = 0xc0206921 SIOCGIFBRDADDR = 0xc0206923 @@ -1268,8 +1323,11 @@ const ( SIOCGIFPDSTADDR = 0xc0206948 SIOCGIFPHYS = 0xc0206935 SIOCGIFPSRCADDR = 0xc0206947 + SIOCGIFRSSHASH = 0xc0186997 + SIOCGIFRSSKEY = 0xc0946996 SIOCGIFSTATUS = 0xc331693b SIOCGIFXMEDIA = 0xc030698b + SIOCGLANPCP = 0xc0206998 SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGPRIVATE_0 = 0xc0206950 @@ -1300,6 +1358,7 @@ const ( SIOCSIFPHYS = 0x80206936 SIOCSIFRVNET = 0xc020695b SIOCSIFVNET = 0xc020695a + SIOCSLANPCP = 0x80206999 SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SIOCSTUNFIB = 0x8020695f @@ -1318,6 +1377,7 @@ const ( SO_BINTIME = 0x2000 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 + SO_DOMAIN = 0x1019 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 @@ -1326,6 +1386,7 @@ const ( SO_LISTENINCQLEN = 0x1013 SO_LISTENQLEN = 0x1012 SO_LISTENQLIMIT = 0x1011 + SO_MAX_PACING_RATE = 0x1018 SO_NOSIGPIPE = 0x800 SO_NO_DDP = 0x8000 SO_NO_OFFLOAD = 0x4000 @@ -1338,11 +1399,19 @@ const ( SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 + SO_REUSEPORT_LB = 0x10000 SO_SETFIB = 0x1014 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_TIMESTAMP = 0x400 + SO_TS_BINTIME = 0x1 + SO_TS_CLOCK = 0x1017 + SO_TS_CLOCK_MAX = 0x3 + SO_TS_DEFAULT = 0x0 + SO_TS_MONOTONIC = 0x3 + SO_TS_REALTIME = 0x2 + SO_TS_REALTIME_MICRO = 0x0 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 SO_USER_COOKIE = 0x1015 @@ -1386,10 +1455,45 @@ const ( TCOFLUSH = 0x2 TCOOFF = 0x1 TCOON = 0x2 + TCP_BBR_ACK_COMP_ALG = 0x448 + TCP_BBR_DRAIN_INC_EXTRA = 0x43c + TCP_BBR_DRAIN_PG = 0x42e + TCP_BBR_EXTRA_GAIN = 0x449 + TCP_BBR_IWINTSO = 0x42b + TCP_BBR_LOWGAIN_FD = 0x436 + TCP_BBR_LOWGAIN_HALF = 0x435 + TCP_BBR_LOWGAIN_THRESH = 0x434 + TCP_BBR_MAX_RTO = 0x439 + TCP_BBR_MIN_RTO = 0x438 + TCP_BBR_ONE_RETRAN = 0x431 + TCP_BBR_PACE_CROSS = 0x442 + TCP_BBR_PACE_DEL_TAR = 0x43f + TCP_BBR_PACE_PER_SEC = 0x43e + TCP_BBR_PACE_SEG_MAX = 0x440 + TCP_BBR_PACE_SEG_MIN = 0x441 + TCP_BBR_PROBE_RTT_GAIN = 0x44d + TCP_BBR_PROBE_RTT_INT = 0x430 + TCP_BBR_PROBE_RTT_LEN = 0x44e + TCP_BBR_RACK_RTT_USE = 0x44a + TCP_BBR_RECFORCE = 0x42c + TCP_BBR_REC_OVER_HPTS = 0x43a + TCP_BBR_RETRAN_WTSO = 0x44b + TCP_BBR_RWND_IS_APP = 0x42f + TCP_BBR_STARTUP_EXIT_EPOCH = 0x43d + TCP_BBR_STARTUP_LOSS_EXIT = 0x432 + TCP_BBR_STARTUP_PG = 0x42d + TCP_BBR_UNLIMITED = 0x43b + TCP_BBR_USEDEL_RATE = 0x437 + TCP_BBR_USE_LOWGAIN = 0x433 TCP_CA_NAME_MAX = 0x10 TCP_CCALGOOPT = 0x41 TCP_CONGESTION = 0x40 + TCP_DATA_AFTER_CLOSE = 0x44c + TCP_DELACK = 0x48 TCP_FASTOPEN = 0x401 + TCP_FASTOPEN_MAX_COOKIE_LEN = 0x10 + TCP_FASTOPEN_MIN_COOKIE_LEN = 0x4 + TCP_FASTOPEN_PSK_LEN = 0x10 TCP_FUNCTION_BLK = 0x2000 TCP_FUNCTION_NAME_LEN_MAX = 0x20 TCP_INFO = 0x20 @@ -1397,6 +1501,12 @@ const ( TCP_KEEPIDLE = 0x100 TCP_KEEPINIT = 0x80 TCP_KEEPINTVL = 0x200 + TCP_LOG = 0x22 + TCP_LOGBUF = 0x23 + TCP_LOGDUMP = 0x25 + TCP_LOGDUMPID = 0x26 + TCP_LOGID = 0x24 + TCP_LOG_ID_LEN = 0x40 TCP_MAXBURST = 0x4 TCP_MAXHLEN = 0x3c TCP_MAXOLEN = 0x28 @@ -1412,8 +1522,30 @@ const ( TCP_NOPUSH = 0x4 TCP_PCAP_IN = 0x1000 TCP_PCAP_OUT = 0x800 + TCP_RACK_EARLY_RECOV = 0x423 + TCP_RACK_EARLY_SEG = 0x424 + TCP_RACK_IDLE_REDUCE_HIGH = 0x444 + TCP_RACK_MIN_PACE = 0x445 + TCP_RACK_MIN_PACE_SEG = 0x446 + TCP_RACK_MIN_TO = 0x422 + TCP_RACK_PACE_ALWAYS = 0x41f + TCP_RACK_PACE_MAX_SEG = 0x41e + TCP_RACK_PACE_REDUCE = 0x41d + TCP_RACK_PKT_DELAY = 0x428 + TCP_RACK_PROP = 0x41b + TCP_RACK_PROP_RATE = 0x420 + TCP_RACK_PRR_SENDALOT = 0x421 + TCP_RACK_REORD_FADE = 0x426 + TCP_RACK_REORD_THRESH = 0x425 + TCP_RACK_SESS_CWV = 0x42a + TCP_RACK_TLP_INC_VAR = 0x429 + TCP_RACK_TLP_REDUCE = 0x41c + TCP_RACK_TLP_THRESH = 0x427 + TCP_RACK_TLP_USE = 0x447 TCP_VENDOR = 0x80000000 TCSAFLUSH = 0x2 + TIMER_ABSTIME = 0x1 + TIMER_RELTIME = 0x0 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 @@ -1477,6 +1609,8 @@ const ( TIOCTIMESTAMP = 0x40107459 TIOCUCNTL = 0x80047466 TOSTOP = 0x400000 + UTIME_NOW = -0x1 + UTIME_OMIT = -0x2 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 diff --git a/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go b/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go index 16db56a..e471987 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go @@ -355,6 +355,22 @@ const ( CTL_KERN = 0x1 CTL_MAXNAME = 0x18 CTL_NET = 0x4 + DIOCGATTR = 0xc144648e + DIOCGDELETE = 0x80106488 + DIOCGFLUSH = 0x20006487 + DIOCGFRONTSTUFF = 0x40086486 + DIOCGFWHEADS = 0x40046483 + DIOCGFWSECTORS = 0x40046482 + DIOCGIDENT = 0x41006489 + DIOCGMEDIASIZE = 0x40086481 + DIOCGPHYSPATH = 0x4400648d + DIOCGPROVIDERNAME = 0x4400648a + DIOCGSECTORSIZE = 0x40046480 + DIOCGSTRIPEOFFSET = 0x4008648c + DIOCGSTRIPESIZE = 0x4008648b + DIOCSKERNELDUMP = 0x804c6490 + DIOCSKERNELDUMP_FREEBSD11 = 0x80046485 + DIOCZONECMD = 0xc06c648f DLT_A429 = 0xb8 DLT_A653_ICM = 0xb9 DLT_AIRONET_HEADER = 0x78 diff --git a/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm64.go b/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm64.go index 1a1de34..5e49769 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm64.go @@ -355,6 +355,22 @@ const ( CTL_KERN = 0x1 CTL_MAXNAME = 0x18 CTL_NET = 0x4 + DIOCGATTR = 0xc148648e + DIOCGDELETE = 0x80106488 + DIOCGFLUSH = 0x20006487 + DIOCGFRONTSTUFF = 0x40086486 + DIOCGFWHEADS = 0x40046483 + DIOCGFWSECTORS = 0x40046482 + DIOCGIDENT = 0x41006489 + DIOCGMEDIASIZE = 0x40086481 + DIOCGPHYSPATH = 0x4400648d + DIOCGPROVIDERNAME = 0x4400648a + DIOCGSECTORSIZE = 0x40046480 + DIOCGSTRIPEOFFSET = 0x4008648c + DIOCGSTRIPESIZE = 0x4008648b + DIOCSKERNELDUMP = 0x80506490 + DIOCSKERNELDUMP_FREEBSD11 = 0x80046485 + DIOCZONECMD = 0xc080648f DLT_A429 = 0xb8 DLT_A653_ICM = 0xb9 DLT_AIRONET_HEADER = 0x78 @@ -379,11 +395,14 @@ const ( DLT_CHAOS = 0x5 DLT_CHDLC = 0x68 DLT_CISCO_IOS = 0x76 + DLT_CLASS_NETBSD_RAWAF = 0x2240000 DLT_C_HDLC = 0x68 DLT_C_HDLC_WITH_DIR = 0xcd DLT_DBUS = 0xe7 DLT_DECT = 0xdd + DLT_DISPLAYPORT_AUX = 0x113 DLT_DOCSIS = 0x8f + DLT_DOCSIS31_XRA31 = 0x111 DLT_DVB_CI = 0xeb DLT_ECONET = 0x73 DLT_EN10MB = 0x1 @@ -393,6 +412,7 @@ const ( DLT_ERF = 0xc5 DLT_ERF_ETH = 0xaf DLT_ERF_POS = 0xb0 + DLT_ETHERNET_MPACKET = 0x112 DLT_FC_2 = 0xe0 DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 DLT_FDDI = 0xa @@ -406,7 +426,6 @@ const ( DLT_GPRS_LLC = 0xa9 DLT_GSMTAP_ABIS = 0xda DLT_GSMTAP_UM = 0xd9 - DLT_HHDLC = 0x79 DLT_IBM_SN = 0x92 DLT_IBM_SP = 0x91 DLT_IEEE802 = 0x6 @@ -429,6 +448,7 @@ const ( DLT_IPV4 = 0xe4 DLT_IPV6 = 0xe5 DLT_IP_OVER_FC = 0x7a + DLT_ISO_14443 = 0x108 DLT_JUNIPER_ATM1 = 0x89 DLT_JUNIPER_ATM2 = 0x87 DLT_JUNIPER_ATM_CEMIC = 0xee @@ -461,8 +481,9 @@ const ( DLT_LINUX_PPP_WITHDIRECTION = 0xa6 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c + DLT_LORATAP = 0x10e DLT_LTALK = 0x72 - DLT_MATCHING_MAX = 0x104 + DLT_MATCHING_MAX = 0x113 DLT_MATCHING_MIN = 0x68 DLT_MFR = 0xb6 DLT_MOST = 0xd3 @@ -478,14 +499,16 @@ const ( DLT_NFC_LLCP = 0xf5 DLT_NFLOG = 0xef DLT_NG40 = 0xf4 + DLT_NORDIC_BLE = 0x110 DLT_NULL = 0x0 + DLT_OPENFLOW = 0x10b DLT_PCI_EXP = 0x7d DLT_PFLOG = 0x75 DLT_PFSYNC = 0x79 DLT_PKTAP = 0x102 DLT_PPI = 0xc0 DLT_PPP = 0x9 - DLT_PPP_BSDOS = 0x10 + DLT_PPP_BSDOS = 0xe DLT_PPP_ETHER = 0x33 DLT_PPP_PPPD = 0xa6 DLT_PPP_SERIAL = 0x32 @@ -496,19 +519,25 @@ const ( DLT_PRONET = 0x4 DLT_RAIF1 = 0xc6 DLT_RAW = 0xc + DLT_RDS = 0x109 + DLT_REDBACK_SMARTEDGE = 0x20 DLT_RIO = 0x7c DLT_RTAC_SERIAL = 0xfa DLT_SCCP = 0x8e DLT_SCTP = 0xf8 + DLT_SDLC = 0x10c DLT_SITA = 0xc4 DLT_SLIP = 0x8 - DLT_SLIP_BSDOS = 0xf + DLT_SLIP_BSDOS = 0xd DLT_STANAG_5066_D_PDU = 0xed DLT_SUNATM = 0x7b DLT_SYMANTEC_FIREWALL = 0x63 + DLT_TI_LLN_SNIFFER = 0x10d DLT_TZSP = 0x80 DLT_USB = 0xba DLT_USBPCAP = 0xf9 + DLT_USB_DARWIN = 0x10a + DLT_USB_FREEBSD = 0xba DLT_USB_LINUX = 0xbd DLT_USB_LINUX_MMAPPED = 0xdc DLT_USER0 = 0x93 @@ -527,10 +556,14 @@ const ( DLT_USER7 = 0x9a DLT_USER8 = 0x9b DLT_USER9 = 0x9c + DLT_VSOCK = 0x10f + DLT_WATTSTOPPER_DLM = 0x107 DLT_WIHART = 0xdf DLT_WIRESHARK_UPPER_PDU = 0xfc DLT_X2E_SERIAL = 0xd5 DLT_X2E_XORAYA = 0xd6 + DLT_ZWAVE_R1_R2 = 0x105 + DLT_ZWAVE_R3 = 0x106 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 @@ -548,6 +581,7 @@ const ( ECHONL = 0x10 ECHOPRT = 0x20 EVFILT_AIO = -0x3 + EVFILT_EMPTY = -0xd EVFILT_FS = -0x9 EVFILT_LIO = -0xa EVFILT_PROC = -0x5 @@ -555,11 +589,12 @@ const ( EVFILT_READ = -0x1 EVFILT_SENDFILE = -0xc EVFILT_SIGNAL = -0x6 - EVFILT_SYSCOUNT = 0xc + EVFILT_SYSCOUNT = 0xd EVFILT_TIMER = -0x7 EVFILT_USER = -0xb EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 + EVNAMEMAP_NAME_SIZE = 0x40 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 @@ -576,6 +611,7 @@ const ( EV_RECEIPT = 0x40 EV_SYSFLAGS = 0xf000 EXTA = 0x4b00 + EXTATTR_MAXNAMELEN = 0xff EXTATTR_NAMESPACE_EMPTY = 0x0 EXTATTR_NAMESPACE_SYSTEM = 0x2 EXTATTR_NAMESPACE_USER = 0x1 @@ -617,6 +653,7 @@ const ( IEXTEN = 0x400 IFAN_ARRIVAL = 0x0 IFAN_DEPARTURE = 0x1 + IFCAP_WOL_MAGIC = 0x2000 IFF_ALLMULTI = 0x200 IFF_ALTPHYS = 0x4000 IFF_BROADCAST = 0x2 @@ -633,6 +670,7 @@ const ( IFF_MONITOR = 0x40000 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 + IFF_NOGROUP = 0x800000 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PPROMISC = 0x20000 @@ -807,6 +845,7 @@ const ( IPV6_DSTOPTS = 0x32 IPV6_FLOWID = 0x43 IPV6_FLOWINFO_MASK = 0xffffff0f + IPV6_FLOWLABEL_LEN = 0x14 IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FLOWTYPE = 0x44 IPV6_FRAGTTL = 0x78 @@ -827,13 +866,13 @@ const ( IPV6_MAX_GROUP_SRC_FILTER = 0x200 IPV6_MAX_MEMBERSHIPS = 0xfff IPV6_MAX_SOCK_SRC_FILTER = 0x80 - IPV6_MIN_MEMBERSHIPS = 0x1f IPV6_MMTU = 0x500 IPV6_MSFILTER = 0x4a IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_NEXTHOP = 0x30 + IPV6_ORIGDSTADDR = 0x48 IPV6_PATHMTU = 0x2c IPV6_PKTINFO = 0x2e IPV6_PORTRANGE = 0xe @@ -845,6 +884,7 @@ const ( IPV6_RECVFLOWID = 0x46 IPV6_RECVHOPLIMIT = 0x25 IPV6_RECVHOPOPTS = 0x27 + IPV6_RECVORIGDSTADDR = 0x48 IPV6_RECVPATHMTU = 0x2b IPV6_RECVPKTINFO = 0x24 IPV6_RECVRSSBUCKETID = 0x47 @@ -905,10 +945,8 @@ const ( IP_MAX_MEMBERSHIPS = 0xfff IP_MAX_SOCK_MUTE_FILTER = 0x80 IP_MAX_SOCK_SRC_FILTER = 0x80 - IP_MAX_SOURCE_FILTER = 0x400 IP_MF = 0x2000 IP_MINTTL = 0x42 - IP_MIN_MEMBERSHIPS = 0x1f IP_MSFILTER = 0x4a IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 @@ -918,6 +956,7 @@ const ( IP_OFFMASK = 0x1fff IP_ONESBCAST = 0x17 IP_OPTIONS = 0x1 + IP_ORIGDSTADDR = 0x1b IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 @@ -926,6 +965,7 @@ const ( IP_RECVFLOWID = 0x5d IP_RECVIF = 0x14 IP_RECVOPTS = 0x5 + IP_RECVORIGDSTADDR = 0x1b IP_RECVRETOPTS = 0x6 IP_RECVRSSBUCKETID = 0x5e IP_RECVTOS = 0x44 @@ -976,6 +1016,7 @@ const ( MAP_EXCL = 0x4000 MAP_FILE = 0x0 MAP_FIXED = 0x10 + MAP_GUARD = 0x2000 MAP_HASSEMAPHORE = 0x200 MAP_NOCORE = 0x20000 MAP_NOSYNC = 0x800 @@ -987,6 +1028,15 @@ const ( MAP_RESERVED0100 = 0x100 MAP_SHARED = 0x1 MAP_STACK = 0x400 + MCAST_BLOCK_SOURCE = 0x54 + MCAST_EXCLUDE = 0x2 + MCAST_INCLUDE = 0x1 + MCAST_JOIN_GROUP = 0x50 + MCAST_JOIN_SOURCE_GROUP = 0x52 + MCAST_LEAVE_GROUP = 0x51 + MCAST_LEAVE_SOURCE_GROUP = 0x53 + MCAST_UNBLOCK_SOURCE = 0x55 + MCAST_UNDEFINED = 0x0 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MNT_ACLS = 0x8000000 @@ -1027,10 +1077,12 @@ const ( MNT_SUSPEND = 0x4 MNT_SYNCHRONOUS = 0x2 MNT_UNION = 0x20 + MNT_UNTRUSTED = 0x800000000 MNT_UPDATE = 0x10000 - MNT_UPDATEMASK = 0x2d8d0807e + MNT_UPDATEMASK = 0xad8d0807e MNT_USER = 0x8000 - MNT_VISFLAGMASK = 0x3fef0ffff + MNT_VERIFIED = 0x400000000 + MNT_VISFLAGMASK = 0xffef0ffff MNT_WAIT = 0x1 MSG_CMSG_CLOEXEC = 0x40000 MSG_COMPAT = 0x8000 @@ -1059,6 +1111,7 @@ const ( NFDBITS = 0x40 NOFLSH = 0x80000000 NOKERNINFO = 0x2000000 + NOTE_ABSTIME = 0x10 NOTE_ATTRIB = 0x8 NOTE_CHILD = 0x4 NOTE_CLOSE = 0x100 @@ -1213,7 +1266,6 @@ const ( RTV_WEIGHT = 0x100 RT_ALL_FIBS = -0x1 RT_BLACKHOLE = 0x40 - RT_CACHING_CONTEXT = 0x1 RT_DEFAULT_FIB = 0x0 RT_HAS_GW = 0x80 RT_HAS_HEADER = 0x10 @@ -1223,15 +1275,17 @@ const ( RT_LLE_CACHE = 0x100 RT_MAY_LOOP = 0x8 RT_MAY_LOOP_BIT = 0x3 - RT_NORTREF = 0x2 RT_REJECT = 0x20 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_BINTIME = 0x4 SCM_CREDS = 0x3 + SCM_MONOTONIC = 0x6 + SCM_REALTIME = 0x5 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x2 + SCM_TIME_INFO = 0x7 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 @@ -1247,6 +1301,7 @@ const ( SIOCGETSGCNT = 0xc0207210 SIOCGETVIFCNT = 0xc028720f SIOCGHIWAT = 0x40047301 + SIOCGHWADDR = 0xc020693e SIOCGI2C = 0xc020693d SIOCGIFADDR = 0xc0206921 SIOCGIFBRDADDR = 0xc0206923 @@ -1268,8 +1323,11 @@ const ( SIOCGIFPDSTADDR = 0xc0206948 SIOCGIFPHYS = 0xc0206935 SIOCGIFPSRCADDR = 0xc0206947 + SIOCGIFRSSHASH = 0xc0186997 + SIOCGIFRSSKEY = 0xc0946996 SIOCGIFSTATUS = 0xc331693b SIOCGIFXMEDIA = 0xc030698b + SIOCGLANPCP = 0xc0206998 SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGPRIVATE_0 = 0xc0206950 @@ -1300,6 +1358,7 @@ const ( SIOCSIFPHYS = 0x80206936 SIOCSIFRVNET = 0xc020695b SIOCSIFVNET = 0xc020695a + SIOCSLANPCP = 0x80206999 SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SIOCSTUNFIB = 0x8020695f @@ -1318,6 +1377,7 @@ const ( SO_BINTIME = 0x2000 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 + SO_DOMAIN = 0x1019 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 @@ -1326,6 +1386,7 @@ const ( SO_LISTENINCQLEN = 0x1013 SO_LISTENQLEN = 0x1012 SO_LISTENQLIMIT = 0x1011 + SO_MAX_PACING_RATE = 0x1018 SO_NOSIGPIPE = 0x800 SO_NO_DDP = 0x8000 SO_NO_OFFLOAD = 0x4000 @@ -1338,11 +1399,19 @@ const ( SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 + SO_REUSEPORT_LB = 0x10000 SO_SETFIB = 0x1014 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_TIMESTAMP = 0x400 + SO_TS_BINTIME = 0x1 + SO_TS_CLOCK = 0x1017 + SO_TS_CLOCK_MAX = 0x3 + SO_TS_DEFAULT = 0x0 + SO_TS_MONOTONIC = 0x3 + SO_TS_REALTIME = 0x2 + SO_TS_REALTIME_MICRO = 0x0 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 SO_USER_COOKIE = 0x1015 @@ -1386,10 +1455,45 @@ const ( TCOFLUSH = 0x2 TCOOFF = 0x1 TCOON = 0x2 + TCP_BBR_ACK_COMP_ALG = 0x448 + TCP_BBR_DRAIN_INC_EXTRA = 0x43c + TCP_BBR_DRAIN_PG = 0x42e + TCP_BBR_EXTRA_GAIN = 0x449 + TCP_BBR_IWINTSO = 0x42b + TCP_BBR_LOWGAIN_FD = 0x436 + TCP_BBR_LOWGAIN_HALF = 0x435 + TCP_BBR_LOWGAIN_THRESH = 0x434 + TCP_BBR_MAX_RTO = 0x439 + TCP_BBR_MIN_RTO = 0x438 + TCP_BBR_ONE_RETRAN = 0x431 + TCP_BBR_PACE_CROSS = 0x442 + TCP_BBR_PACE_DEL_TAR = 0x43f + TCP_BBR_PACE_PER_SEC = 0x43e + TCP_BBR_PACE_SEG_MAX = 0x440 + TCP_BBR_PACE_SEG_MIN = 0x441 + TCP_BBR_PROBE_RTT_GAIN = 0x44d + TCP_BBR_PROBE_RTT_INT = 0x430 + TCP_BBR_PROBE_RTT_LEN = 0x44e + TCP_BBR_RACK_RTT_USE = 0x44a + TCP_BBR_RECFORCE = 0x42c + TCP_BBR_REC_OVER_HPTS = 0x43a + TCP_BBR_RETRAN_WTSO = 0x44b + TCP_BBR_RWND_IS_APP = 0x42f + TCP_BBR_STARTUP_EXIT_EPOCH = 0x43d + TCP_BBR_STARTUP_LOSS_EXIT = 0x432 + TCP_BBR_STARTUP_PG = 0x42d + TCP_BBR_UNLIMITED = 0x43b + TCP_BBR_USEDEL_RATE = 0x437 + TCP_BBR_USE_LOWGAIN = 0x433 TCP_CA_NAME_MAX = 0x10 TCP_CCALGOOPT = 0x41 TCP_CONGESTION = 0x40 + TCP_DATA_AFTER_CLOSE = 0x44c + TCP_DELACK = 0x48 TCP_FASTOPEN = 0x401 + TCP_FASTOPEN_MAX_COOKIE_LEN = 0x10 + TCP_FASTOPEN_MIN_COOKIE_LEN = 0x4 + TCP_FASTOPEN_PSK_LEN = 0x10 TCP_FUNCTION_BLK = 0x2000 TCP_FUNCTION_NAME_LEN_MAX = 0x20 TCP_INFO = 0x20 @@ -1397,6 +1501,12 @@ const ( TCP_KEEPIDLE = 0x100 TCP_KEEPINIT = 0x80 TCP_KEEPINTVL = 0x200 + TCP_LOG = 0x22 + TCP_LOGBUF = 0x23 + TCP_LOGDUMP = 0x25 + TCP_LOGDUMPID = 0x26 + TCP_LOGID = 0x24 + TCP_LOG_ID_LEN = 0x40 TCP_MAXBURST = 0x4 TCP_MAXHLEN = 0x3c TCP_MAXOLEN = 0x28 @@ -1412,8 +1522,30 @@ const ( TCP_NOPUSH = 0x4 TCP_PCAP_IN = 0x1000 TCP_PCAP_OUT = 0x800 + TCP_RACK_EARLY_RECOV = 0x423 + TCP_RACK_EARLY_SEG = 0x424 + TCP_RACK_IDLE_REDUCE_HIGH = 0x444 + TCP_RACK_MIN_PACE = 0x445 + TCP_RACK_MIN_PACE_SEG = 0x446 + TCP_RACK_MIN_TO = 0x422 + TCP_RACK_PACE_ALWAYS = 0x41f + TCP_RACK_PACE_MAX_SEG = 0x41e + TCP_RACK_PACE_REDUCE = 0x41d + TCP_RACK_PKT_DELAY = 0x428 + TCP_RACK_PROP = 0x41b + TCP_RACK_PROP_RATE = 0x420 + TCP_RACK_PRR_SENDALOT = 0x421 + TCP_RACK_REORD_FADE = 0x426 + TCP_RACK_REORD_THRESH = 0x425 + TCP_RACK_SESS_CWV = 0x42a + TCP_RACK_TLP_INC_VAR = 0x429 + TCP_RACK_TLP_REDUCE = 0x41c + TCP_RACK_TLP_THRESH = 0x427 + TCP_RACK_TLP_USE = 0x447 TCP_VENDOR = 0x80000000 TCSAFLUSH = 0x2 + TIMER_ABSTIME = 0x1 + TIMER_RELTIME = 0x0 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 @@ -1477,6 +1609,8 @@ const ( TIOCTIMESTAMP = 0x40107459 TIOCUCNTL = 0x80047466 TOSTOP = 0x400000 + UTIME_NOW = -0x1 + UTIME_OMIT = -0x2 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 @@ -1488,6 +1622,7 @@ const ( VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 + VM_BCACHE_SIZE_MAX = 0x19000000 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux.go b/vendor/golang.org/x/sys/unix/zerrors_linux.go index 5be454c..2197394 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux.go @@ -216,6 +216,7 @@ const ( BPF_F_RDONLY = 0x8 BPF_F_RDONLY_PROG = 0x80 BPF_F_RECOMPUTE_CSUM = 0x1 + BPF_F_REPLACE = 0x4 BPF_F_REUSE_STACKID = 0x400 BPF_F_SEQ_NUMBER = 0x8 BPF_F_SKIP_FIELD_MASK = 0xff @@ -389,6 +390,7 @@ const ( CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 + CLONE_NEWTIME = 0x80 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 @@ -671,6 +673,7 @@ const ( FS_IOC_ADD_ENCRYPTION_KEY = 0xc0506617 FS_IOC_GET_ENCRYPTION_KEY_STATUS = 0xc080661a FS_IOC_GET_ENCRYPTION_POLICY_EX = 0xc0096616 + FS_IOC_MEASURE_VERITY = 0xc0046686 FS_IOC_REMOVE_ENCRYPTION_KEY = 0xc0406618 FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS = 0xc0406619 FS_KEY_DESCRIPTOR_SIZE = 0x8 @@ -683,6 +686,9 @@ const ( FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0xf + FS_VERITY_FL = 0x100000 + FS_VERITY_HASH_ALG_SHA256 = 0x1 + FS_VERITY_HASH_ALG_SHA512 = 0x2 FUTEXFS_SUPER_MAGIC = 0xbad1dea F_ADD_SEALS = 0x409 F_DUPFD = 0x0 @@ -733,6 +739,7 @@ const ( GENL_NAMSIZ = 0x10 GENL_START_ALLOC = 0x13 GENL_UNS_ADMIN_PERM = 0x10 + GRND_INSECURE = 0x4 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HDIO_DRIVE_CMD = 0x31f @@ -890,6 +897,7 @@ const ( IPPROTO_IP = 0x0 IPPROTO_IPIP = 0x4 IPPROTO_IPV6 = 0x29 + IPPROTO_L2TP = 0x73 IPPROTO_MH = 0x87 IPPROTO_MPLS = 0x89 IPPROTO_MTP = 0x5c @@ -1482,6 +1490,7 @@ const ( PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_FP_MODE = 0x2e + PR_GET_IO_FLUSHER = 0x3a PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_NO_NEW_PRIVS = 0x27 @@ -1517,6 +1526,7 @@ const ( PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc PR_SET_FP_MODE = 0x2d + PR_SET_IO_FLUSHER = 0x39 PR_SET_KEEPCAPS = 0x8 PR_SET_MM = 0x23 PR_SET_MM_ARG_END = 0x9 @@ -1745,12 +1755,15 @@ const ( RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d + RTM_DELVLAN = 0x71 RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_FIB_MATCH = 0x2000 RTM_F_LOOKUP_TABLE = 0x1000 RTM_F_NOTIFY = 0x100 + RTM_F_OFFLOAD = 0x4000 RTM_F_PREFIX = 0x800 + RTM_F_TRAP = 0x8000 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a @@ -1772,7 +1785,8 @@ const ( RTM_GETSTATS = 0x5e RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e - RTM_MAX = 0x6f + RTM_GETVLAN = 0x72 + RTM_MAX = 0x73 RTM_NEWACTION = 0x30 RTM_NEWADDR = 0x14 RTM_NEWADDRLABEL = 0x48 @@ -1787,6 +1801,7 @@ const ( RTM_NEWNETCONF = 0x50 RTM_NEWNEXTHOP = 0x68 RTM_NEWNSID = 0x58 + RTM_NEWNVLAN = 0x70 RTM_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 @@ -1794,8 +1809,8 @@ const ( RTM_NEWSTATS = 0x5c RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c - RTM_NR_FAMILIES = 0x18 - RTM_NR_MSGTYPES = 0x60 + RTM_NR_FAMILIES = 0x19 + RTM_NR_MSGTYPES = 0x64 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 @@ -2085,7 +2100,7 @@ const ( TASKSTATS_GENL_NAME = "TASKSTATS" TASKSTATS_GENL_VERSION = 0x1 TASKSTATS_TYPE_MAX = 0x6 - TASKSTATS_VERSION = 0x9 + TASKSTATS_VERSION = 0xa TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 @@ -2266,7 +2281,7 @@ const ( VMADDR_CID_ANY = 0xffffffff VMADDR_CID_HOST = 0x2 VMADDR_CID_HYPERVISOR = 0x0 - VMADDR_CID_RESERVED = 0x1 + VMADDR_CID_LOCAL = 0x1 VMADDR_PORT_ANY = 0xffffffff VM_SOCKETS_INVALID_VERSION = 0xffffffff VQUIT = 0x1 @@ -2393,6 +2408,7 @@ const ( XENFS_SUPER_MAGIC = 0xabba1974 XFS_SUPER_MAGIC = 0x58465342 Z3FOLD_MAGIC = 0x33 + ZONEFS_MAGIC = 0x5a4f4653 ZSMALLOC_MAGIC = 0x58295829 ) diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go index 0876cf9..028c9d8 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go @@ -73,6 +73,8 @@ const ( FFDLY = 0x8000 FLUSHO = 0x1000 FP_XSTATE_MAGIC2 = 0x46505845 + FS_IOC_ENABLE_VERITY = 0x40806685 + FS_IOC_GETFLAGS = 0x80046601 FS_IOC_GET_ENCRYPTION_POLICY = 0x400c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x40106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x800c6613 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go index d5be2e8..005970f 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go @@ -73,6 +73,8 @@ const ( FFDLY = 0x8000 FLUSHO = 0x1000 FP_XSTATE_MAGIC2 = 0x46505845 + FS_IOC_ENABLE_VERITY = 0x40806685 + FS_IOC_GETFLAGS = 0x80086601 FS_IOC_GET_ENCRYPTION_POLICY = 0x400c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x40106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x800c6613 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go index fbeef83..0541f36 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go @@ -72,6 +72,8 @@ const ( FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 + FS_IOC_ENABLE_VERITY = 0x40806685 + FS_IOC_GETFLAGS = 0x80046601 FS_IOC_GET_ENCRYPTION_POLICY = 0x400c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x40106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x800c6613 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go index 06daa50..9ee8d1b 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go @@ -75,6 +75,8 @@ const ( FFDLY = 0x8000 FLUSHO = 0x1000 FPSIMD_MAGIC = 0x46508001 + FS_IOC_ENABLE_VERITY = 0x40806685 + FS_IOC_GETFLAGS = 0x80086601 FS_IOC_GET_ENCRYPTION_POLICY = 0x400c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x40106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x800c6613 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go index 7c866b8..4826bd7 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go @@ -72,6 +72,8 @@ const ( FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x2000 + FS_IOC_ENABLE_VERITY = 0x80806685 + FS_IOC_GETFLAGS = 0x40046601 FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go index c42966d..2346dc5 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go @@ -72,6 +72,8 @@ const ( FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x2000 + FS_IOC_ENABLE_VERITY = 0x80806685 + FS_IOC_GETFLAGS = 0x40086601 FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go index a5b2b42..e758b61 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go @@ -72,6 +72,8 @@ const ( FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x2000 + FS_IOC_ENABLE_VERITY = 0x80806685 + FS_IOC_GETFLAGS = 0x40086601 FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go index 7f91881..2dfe6bb 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go @@ -72,6 +72,8 @@ const ( FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x2000 + FS_IOC_ENABLE_VERITY = 0x80806685 + FS_IOC_GETFLAGS = 0x40046601 FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go index 63df355..5185866 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go @@ -72,6 +72,8 @@ const ( FF1 = 0x4000 FFDLY = 0x4000 FLUSHO = 0x800000 + FS_IOC_ENABLE_VERITY = 0x80806685 + FS_IOC_GETFLAGS = 0x40086601 FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go index 7ab68f7..4231b20 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go @@ -72,6 +72,8 @@ const ( FF1 = 0x4000 FFDLY = 0x4000 FLUSHO = 0x800000 + FS_IOC_ENABLE_VERITY = 0x80806685 + FS_IOC_GETFLAGS = 0x40086601 FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go index f99cf1b..6a0b2d2 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go @@ -72,6 +72,8 @@ const ( FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 + FS_IOC_ENABLE_VERITY = 0x40806685 + FS_IOC_GETFLAGS = 0x80086601 FS_IOC_GET_ENCRYPTION_POLICY = 0x400c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x40106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x800c6613 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go index 613ee23..95e950f 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go @@ -72,6 +72,8 @@ const ( FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 + FS_IOC_ENABLE_VERITY = 0x40806685 + FS_IOC_GETFLAGS = 0x80086601 FS_IOC_GET_ENCRYPTION_POLICY = 0x400c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x40106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x800c6613 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go index 1f7a68d..079762f 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go @@ -76,6 +76,8 @@ const ( FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 + FS_IOC_ENABLE_VERITY = 0x80806685 + FS_IOC_GETFLAGS = 0x40086601 FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613 diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go index c9058f3..600f1d2 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go @@ -214,22 +214,6 @@ func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, ne // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { - var _p0 unsafe.Pointer - if len(mib) > 0 { - _p0 = unsafe.Pointer(&mib[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func utimes(path string, timeval *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) @@ -376,8 +360,15 @@ func pipe2(p *[2]_C_int, flags int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func ptrace(request int, pid int, addr uintptr, data int) (err error) { - _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) +func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) if e1 != 0 { err = errnoErr(e1) } @@ -386,15 +377,24 @@ func ptrace(request int, pid int, addr uintptr, data int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Getcwd(buf []byte) (n int, err error) { +func ioctl(fd int, req uint, arg uintptr) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) - n = int(r0) + _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = errnoErr(e1) } @@ -403,8 +403,8 @@ func Getcwd(buf []byte) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func ioctl(fd int, req uint, arg uintptr) (err error) { - _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) +func ptrace(request int, pid int, addr uintptr, data int) (err error) { + _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } @@ -1352,7 +1352,7 @@ func mknodat_freebsd12(fd int, path string, mode uint32, dev uint64) (err error) if err != nil { return } - _, _, e1 := Syscall6(SYS_MKNODAT_FREEBSD12, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + _, _, e1 := Syscall6(SYS_MKNODAT_FREEBSD12, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), uintptr(dev>>32), 0) if e1 != 0 { err = errnoErr(e1) } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go index 49b20c2..064934b 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go @@ -350,22 +350,6 @@ func Munlockall() (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { - var _p0 unsafe.Pointer - if len(mib) > 0 { - _p0 = unsafe.Pointer(&mib[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func pipe2(p *[2]_C_int, flags int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { @@ -403,6 +387,22 @@ func ioctl(fd int, req uint, arg uintptr) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ptrace(request int, pid int, addr uintptr, data int) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go index abab3d7..4adaaa5 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go @@ -1,4 +1,4 @@ -// go run mksyscall.go -tags freebsd,arm64 -- syscall_bsd.go syscall_freebsd.go syscall_freebsd_arm64.go +// go run mksyscall.go -tags freebsd,arm64 syscall_bsd.go syscall_freebsd.go syscall_freebsd_arm64.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build freebsd,arm64 @@ -350,22 +350,6 @@ func Munlockall() (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { - var _p0 unsafe.Pointer - if len(mib) > 0 { - _p0 = unsafe.Pointer(&mib[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func pipe2(p *[2]_C_int, flags int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { @@ -403,6 +387,22 @@ func ioctl(fd int, req uint, arg uintptr) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ptrace(request int, pid int, addr uintptr, data int) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_illumos_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_illumos_amd64.go new file mode 100644 index 0000000..92efa1d --- /dev/null +++ b/vendor/golang.org/x/sys/unix/zsyscall_illumos_amd64.go @@ -0,0 +1,87 @@ +// go run mksyscall_solaris.go -illumos -tags illumos,amd64 syscall_illumos.go +// Code generated by the command above; see README.md. DO NOT EDIT. + +// +build illumos,amd64 + +package unix + +import ( + "unsafe" +) + +//go:cgo_import_dynamic libc_readv readv "libc.so" +//go:cgo_import_dynamic libc_preadv preadv "libc.so" +//go:cgo_import_dynamic libc_writev writev "libc.so" +//go:cgo_import_dynamic libc_pwritev pwritev "libc.so" + +//go:linkname procreadv libc_readv +//go:linkname procpreadv libc_preadv +//go:linkname procwritev libc_writev +//go:linkname procpwritev libc_pwritev + +var ( + procreadv, + procpreadv, + procwritev, + procpwritev syscallFunc +) + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func readv(fd int, iovs []Iovec) (n int, err error) { + var _p0 *Iovec + if len(iovs) > 0 { + _p0 = &iovs[0] + } + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procreadv)), 3, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(iovs)), 0, 0, 0) + n = int(r0) + if e1 != 0 { + err = e1 + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func preadv(fd int, iovs []Iovec, off int64) (n int, err error) { + var _p0 *Iovec + if len(iovs) > 0 { + _p0 = &iovs[0] + } + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procpreadv)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(iovs)), uintptr(off), 0, 0) + n = int(r0) + if e1 != 0 { + err = e1 + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writev(fd int, iovs []Iovec) (n int, err error) { + var _p0 *Iovec + if len(iovs) > 0 { + _p0 = &iovs[0] + } + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procwritev)), 3, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(iovs)), 0, 0, 0) + n = int(r0) + if e1 != 0 { + err = e1 + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func pwritev(fd int, iovs []Iovec, off int64) (n int, err error) { + var _p0 *Iovec + if len(iovs) > 0 { + _p0 = &iovs[0] + } + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procpwritev)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(iovs)), uintptr(off), 0, 0) + n = int(r0) + if e1 != 0 { + err = e1 + } + return +} diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go index 7aae554..54559a8 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go @@ -431,4 +431,6 @@ const ( SYS_FSPICK = 433 SYS_PIDFD_OPEN = 434 SYS_CLONE3 = 435 + SYS_OPENAT2 = 437 + SYS_PIDFD_GETFD = 438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go index 7968439..054a741 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go @@ -353,4 +353,6 @@ const ( SYS_FSPICK = 433 SYS_PIDFD_OPEN = 434 SYS_CLONE3 = 435 + SYS_OPENAT2 = 437 + SYS_PIDFD_GETFD = 438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go index 3c663c6..307f2ba 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go @@ -395,4 +395,6 @@ const ( SYS_FSPICK = 433 SYS_PIDFD_OPEN = 434 SYS_CLONE3 = 435 + SYS_OPENAT2 = 437 + SYS_PIDFD_GETFD = 438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go index 1f3b4d1..e9404dd 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go @@ -298,4 +298,6 @@ const ( SYS_FSPICK = 433 SYS_PIDFD_OPEN = 434 SYS_CLONE3 = 435 + SYS_OPENAT2 = 437 + SYS_PIDFD_GETFD = 438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go index 00da3de..68bb6d2 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go @@ -416,4 +416,6 @@ const ( SYS_FSPICK = 4433 SYS_PIDFD_OPEN = 4434 SYS_CLONE3 = 4435 + SYS_OPENAT2 = 4437 + SYS_PIDFD_GETFD = 4438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go index d404fbd..4e52511 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go @@ -346,4 +346,6 @@ const ( SYS_FSPICK = 5433 SYS_PIDFD_OPEN = 5434 SYS_CLONE3 = 5435 + SYS_OPENAT2 = 5437 + SYS_PIDFD_GETFD = 5438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go index bfbf242..4d9aa30 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go @@ -346,4 +346,6 @@ const ( SYS_FSPICK = 5433 SYS_PIDFD_OPEN = 5434 SYS_CLONE3 = 5435 + SYS_OPENAT2 = 5437 + SYS_PIDFD_GETFD = 5438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go index 3826f49..64af070 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go @@ -416,4 +416,6 @@ const ( SYS_FSPICK = 4433 SYS_PIDFD_OPEN = 4434 SYS_CLONE3 = 4435 + SYS_OPENAT2 = 4437 + SYS_PIDFD_GETFD = 4438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go index 52e3da6..cc3c067 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go @@ -395,4 +395,6 @@ const ( SYS_FSPICK = 433 SYS_PIDFD_OPEN = 434 SYS_CLONE3 = 435 + SYS_OPENAT2 = 437 + SYS_PIDFD_GETFD = 438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go index 6141f90..4050ff9 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go @@ -395,4 +395,6 @@ const ( SYS_FSPICK = 433 SYS_PIDFD_OPEN = 434 SYS_CLONE3 = 435 + SYS_OPENAT2 = 437 + SYS_PIDFD_GETFD = 438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go index 4f7261a..529abb6 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go @@ -297,4 +297,6 @@ const ( SYS_FSPICK = 433 SYS_PIDFD_OPEN = 434 SYS_CLONE3 = 435 + SYS_OPENAT2 = 437 + SYS_PIDFD_GETFD = 438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go index f47014a..2766500 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go @@ -360,4 +360,6 @@ const ( SYS_FSPICK = 433 SYS_PIDFD_OPEN = 434 SYS_CLONE3 = 435 + SYS_OPENAT2 = 437 + SYS_PIDFD_GETFD = 438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go index dd78abb..4dc82bb 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go @@ -374,4 +374,6 @@ const ( SYS_FSMOUNT = 432 SYS_FSPICK = 433 SYS_PIDFD_OPEN = 434 + SYS_OPENAT2 = 437 + SYS_PIDFD_GETFD = 438 ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go b/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go index 0ec1596..2a3ec61 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go +++ b/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go @@ -128,9 +128,9 @@ type Statfs_t struct { Owner uint32 Fsid Fsid Charspare [80]int8 - Fstypename [16]int8 - Mntfromname [1024]int8 - Mntonname [1024]int8 + Fstypename [16]byte + Mntfromname [1024]byte + Mntonname [1024]byte } type statfs_freebsd11_t struct { @@ -153,9 +153,9 @@ type statfs_freebsd11_t struct { Owner uint32 Fsid Fsid Charspare [80]int8 - Fstypename [16]int8 - Mntfromname [88]int8 - Mntonname [88]int8 + Fstypename [16]byte + Mntfromname [88]byte + Mntonname [88]byte } type Flock_t struct { @@ -375,15 +375,15 @@ type PtraceLwpInfoStruct struct { } type __Siginfo struct { - Signo int32 - Errno int32 - Code int32 - Pid int32 - Uid uint32 - Status int32 - Addr *byte - Value [4]byte - X_reason [32]byte + Signo int32 + Errno int32 + Code int32 + Pid int32 + Uid uint32 + Status int32 + Addr *byte + Value [4]byte + _ [32]byte } type Sigset_t struct { @@ -458,7 +458,7 @@ type ifMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte + _ uint16 Data ifData } @@ -469,7 +469,6 @@ type IfMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte Data IfData } @@ -536,7 +535,7 @@ type IfaMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte + _ uint16 Metric int32 } @@ -547,7 +546,7 @@ type IfmaMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte + _ uint16 } type IfAnnounceMsghdr struct { @@ -564,7 +563,7 @@ type RtMsghdr struct { Version uint8 Type uint8 Index uint16 - _ [2]byte + _ uint16 Flags int32 Addrs int32 Pid int32 diff --git a/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go index 8340f57..e11e954 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go @@ -123,9 +123,9 @@ type Statfs_t struct { Owner uint32 Fsid Fsid Charspare [80]int8 - Fstypename [16]int8 - Mntfromname [1024]int8 - Mntonname [1024]int8 + Fstypename [16]byte + Mntfromname [1024]byte + Mntonname [1024]byte } type statfs_freebsd11_t struct { @@ -148,9 +148,9 @@ type statfs_freebsd11_t struct { Owner uint32 Fsid Fsid Charspare [80]int8 - Fstypename [16]int8 - Mntfromname [88]int8 - Mntonname [88]int8 + Fstypename [16]byte + Mntfromname [88]byte + Mntonname [88]byte } type Flock_t struct { @@ -275,10 +275,8 @@ type IPv6Mreq struct { type Msghdr struct { Name *byte Namelen uint32 - _ [4]byte Iov *Iovec Iovlen int32 - _ [4]byte Control *byte Controllen uint32 Flags int32 @@ -463,7 +461,7 @@ type ifMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte + _ uint16 Data ifData } @@ -474,7 +472,6 @@ type IfMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte Data IfData } @@ -541,7 +538,7 @@ type IfaMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte + _ uint16 Metric int32 } @@ -552,7 +549,7 @@ type IfmaMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte + _ uint16 } type IfAnnounceMsghdr struct { @@ -569,7 +566,7 @@ type RtMsghdr struct { Version uint8 Type uint8 Index uint16 - _ [2]byte + _ uint16 Flags int32 Addrs int32 Pid int32 @@ -623,7 +620,6 @@ type BpfZbuf struct { type BpfProgram struct { Len uint32 - _ [4]byte Insns *BpfInsn } diff --git a/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go b/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go index e751e00..c6fe1d0 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go @@ -1,4 +1,4 @@ -// cgo -godefs types_freebsd.go | go run mkpost.go +// cgo -godefs -- -fsigned-char types_freebsd.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build arm64,freebsd @@ -123,9 +123,9 @@ type Statfs_t struct { Owner uint32 Fsid Fsid Charspare [80]int8 - Fstypename [16]int8 - Mntfromname [1024]int8 - Mntonname [1024]int8 + Fstypename [16]byte + Mntfromname [1024]byte + Mntonname [1024]byte } type statfs_freebsd11_t struct { @@ -148,9 +148,9 @@ type statfs_freebsd11_t struct { Owner uint32 Fsid Fsid Charspare [80]int8 - Fstypename [16]int8 - Mntfromname [88]int8 - Mntonname [88]int8 + Fstypename [16]byte + Mntfromname [88]byte + Mntonname [88]byte } type Flock_t struct { @@ -275,10 +275,8 @@ type IPv6Mreq struct { type Msghdr struct { Name *byte Namelen uint32 - _ [4]byte Iov *Iovec Iovlen int32 - _ [4]byte Control *byte Controllen uint32 Flags int32 @@ -326,11 +324,9 @@ const ( PTRACE_CONT = 0x7 PTRACE_DETACH = 0xb PTRACE_GETFPREGS = 0x23 - PTRACE_GETFSBASE = 0x47 PTRACE_GETLWPLIST = 0xf PTRACE_GETNUMLWPS = 0xe PTRACE_GETREGS = 0x21 - PTRACE_GETXSTATE = 0x45 PTRACE_IO = 0xc PTRACE_KILL = 0x8 PTRACE_LWPEVENTS = 0x18 @@ -373,15 +369,15 @@ type PtraceLwpInfoStruct struct { } type __Siginfo struct { - Signo int32 - Errno int32 - Code int32 - Pid int32 - Uid uint32 - Status int32 - Addr *byte - Value [8]byte - X_reason [40]byte + Signo int32 + Errno int32 + Code int32 + Pid int32 + Uid uint32 + Status int32 + Addr *byte + Value [8]byte + _ [40]byte } type Sigset_t struct { @@ -394,12 +390,14 @@ type Reg struct { Sp uint64 Elr uint64 Spsr uint32 + _ [4]byte } type FpReg struct { - Fp_q [512]uint8 - Fp_sr uint32 - Fp_cr uint32 + Q [32][16]uint8 + Sr uint32 + Cr uint32 + _ [8]byte } type PtraceIoDesc struct { @@ -441,7 +439,7 @@ type ifMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte + _ uint16 Data ifData } @@ -452,7 +450,6 @@ type IfMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte Data IfData } @@ -519,7 +516,7 @@ type IfaMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte + _ uint16 Metric int32 } @@ -530,7 +527,7 @@ type IfmaMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte + _ uint16 } type IfAnnounceMsghdr struct { @@ -547,7 +544,7 @@ type RtMsghdr struct { Version uint8 Type uint8 Index uint16 - _ [2]byte + _ uint16 Flags int32 Addrs int32 Pid int32 @@ -601,7 +598,6 @@ type BpfZbuf struct { type BpfProgram struct { Len uint32 - _ [4]byte Insns *BpfInsn } diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux.go b/vendor/golang.org/x/sys/unix/ztypes_linux.go index 6c81e75..af5ab45 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux.go @@ -114,7 +114,8 @@ type FscryptKeySpecifier struct { type FscryptAddKeyArg struct { Key_spec FscryptKeySpecifier Raw_size uint32 - _ [9]uint32 + Key_id uint32 + _ [8]uint32 } type FscryptRemoveKeyArg struct { @@ -243,6 +244,23 @@ type RawSockaddrTIPC struct { Addr [12]byte } +type RawSockaddrL2TPIP struct { + Family uint16 + Unused uint16 + Addr [4]byte /* in_addr */ + Conn_id uint32 + _ [4]uint8 +} + +type RawSockaddrL2TPIP6 struct { + Family uint16 + Unused uint16 + Flowinfo uint32 + Addr [16]byte /* in6_addr */ + Scope_id uint32 + Conn_id uint32 +} + type _Socklen uint32 type Linger struct { @@ -353,6 +371,8 @@ const ( SizeofSockaddrXDP = 0x10 SizeofSockaddrPPPoX = 0x1e SizeofSockaddrTIPC = 0x10 + SizeofSockaddrL2TPIP = 0x10 + SizeofSockaddrL2TPIP6 = 0x20 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc @@ -460,7 +480,7 @@ const ( IFLA_NEW_IFINDEX = 0x31 IFLA_MIN_MTU = 0x32 IFLA_MAX_MTU = 0x33 - IFLA_MAX = 0x35 + IFLA_MAX = 0x36 IFLA_INFO_KIND = 0x1 IFLA_INFO_DATA = 0x2 IFLA_INFO_XSTATS = 0x3 @@ -2272,3 +2292,49 @@ const ( DEVLINK_DPIPE_HEADER_IPV4 = 0x1 DEVLINK_DPIPE_HEADER_IPV6 = 0x2 ) + +type FsverityDigest struct { + Algorithm uint16 + Size uint16 +} + +type FsverityEnableArg struct { + Version uint32 + Hash_algorithm uint32 + Block_size uint32 + Salt_size uint32 + Salt_ptr uint64 + Sig_size uint32 + _ uint32 + Sig_ptr uint64 + _ [11]uint64 +} + +type Nhmsg struct { + Family uint8 + Scope uint8 + Protocol uint8 + Resvd uint8 + Flags uint32 +} + +type NexthopGrp struct { + Id uint32 + Weight uint8 + Resvd1 uint8 + Resvd2 uint16 +} + +const ( + NHA_UNSPEC = 0x0 + NHA_ID = 0x1 + NHA_GROUP = 0x2 + NHA_GROUP_TYPE = 0x3 + NHA_BLACKHOLE = 0x4 + NHA_OIF = 0x5 + NHA_GATEWAY = 0x6 + NHA_ENCAP_TYPE = 0x7 + NHA_ENCAP = 0x8 + NHA_GROUPS = 0x9 + NHA_MASTER = 0xa +) 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 fc6b3fb..761b67c 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_386.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_386.go @@ -287,6 +287,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint32 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 26c30b8..201fb34 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go @@ -298,6 +298,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint64 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 814d42d..8051b56 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go @@ -276,6 +276,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint32 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 d9664c7..a936f21 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go @@ -277,6 +277,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint64 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 0d72145..aaca03d 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go @@ -281,6 +281,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint32 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 ef69768..2e7f3b8 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go @@ -280,6 +280,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint64 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 485fda7..16add5a 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go @@ -280,6 +280,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint64 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 569477e..4ed2c8e 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go @@ -281,6 +281,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint32 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 602d8b4..7415190 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go @@ -287,6 +287,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint64 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 6db9a7b..046c2de 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go @@ -287,6 +287,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint64 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go index 52b5348..0f2f61a 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go @@ -305,6 +305,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint64 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 a111387..cca1b6b 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go @@ -300,6 +300,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint64 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go index 8153af1..33a73bf 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go @@ -282,6 +282,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint64 diff --git a/vendor/modules.txt b/vendor/modules.txt index 28f79e3..6fdc6f9 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,8 +1,6 @@ # github.com/Messer4/base58check v0.0.0-20180328134002-7531a92ae9ba github.com/Messer4/base58check -# github.com/boltdb/bolt v1.3.1 -github.com/boltdb/bolt -# github.com/btcsuite/btcutil v1.0.1 +# github.com/btcsuite/btcutil v1.0.2 github.com/btcsuite/btcutil/base58 # github.com/caarlos0/env/v6 v6.2.1 github.com/caarlos0/env/v6 @@ -13,11 +11,9 @@ github.com/go-playground/locales github.com/go-playground/locales/currency # github.com/go-playground/universal-translator v0.17.0 github.com/go-playground/universal-translator -# github.com/go-playground/validator v9.31.0+incompatible -github.com/go-playground/validator # github.com/go-playground/validator/v10 v10.2.0 github.com/go-playground/validator/v10 -# github.com/goat-systems/go-tezos/v2 v2.6.0-alpha +# github.com/goat-systems/go-tezos/v2 v2.7.0-alpha github.com/goat-systems/go-tezos/v2 # github.com/inconshreveable/mousetrap v1.0.0 github.com/inconshreveable/mousetrap @@ -41,7 +37,7 @@ github.com/spf13/cobra github.com/spf13/pflag # github.com/stretchr/testify v1.5.1 github.com/stretchr/testify/assert -# golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073 +# golang.org/x/crypto v0.0.0-20200427165652-729f1e841bcc golang.org/x/crypto/blake2b golang.org/x/crypto/ed25519 golang.org/x/crypto/ed25519/internal/edwards25519 @@ -50,7 +46,7 @@ golang.org/x/crypto/nacl/secretbox golang.org/x/crypto/pbkdf2 golang.org/x/crypto/poly1305 golang.org/x/crypto/salsa20/salsa -# golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527 +# golang.org/x/sys v0.0.0-20200427175716-29b57079015a golang.org/x/sys/cpu golang.org/x/sys/unix # gopkg.in/yaml.v2 v2.2.4