How to use NewCtx method of main Package

Best Syzkaller code snippet using main.NewCtx

ante.go

Source:ante.go Github

copy

Full Screen

1package auth2import (3 "bytes"4 "encoding/hex"5 "fmt"6 "math/big"7 sdk "github.com/cosmos/cosmos-sdk/types"8 "github.com/tendermint/tendermint/crypto"9 "github.com/tendermint/tendermint/crypto/secp256k1"10 authTypes "github.com/maticnetwork/heimdall/auth/types"11 "github.com/maticnetwork/heimdall/chainmanager"12 "github.com/maticnetwork/heimdall/helper"13 "github.com/maticnetwork/heimdall/types"14)15var (16 // simulation signature values used to estimate gas consumption17 simSecp256k1Pubkey secp256k1.PubKeySecp256k118 simSecp256k1Sig [64]byte19 // fee wanted for checkpoint transaction20 gasWantedPerCheckpoinTx sdk.Gas = 1000000021 gasUsedPerCheckpointTx sdk.Gas = gasWantedPerCheckpoinTx - 100000022 // DefaultFeeInMatic represents default fee in matic23 DefaultFeeInMatic = big.NewInt(10).Exp(big.NewInt(10), big.NewInt(15), nil)24 // DefaultFeeWantedPerTx fee wanted per tx25 DefaultFeeWantedPerTx = sdk.Coins{sdk.Coin{Denom: authTypes.FeeToken, Amount: sdk.NewIntFromBigInt(DefaultFeeInMatic)}}26)27func init() {28 // This decodes a valid hex string into a sepc256k1Pubkey for use in transaction simulation29 bz, _ := hex.DecodeString("035AD6810A47F073553FF30D2FCC7E0D3B1C0B74B61A1AAA2582344037151E143A")30 copy(simSecp256k1Pubkey[:], bz)31}32// SignatureVerificationGasConsumer is the type of function that is used to both consume gas when verifying signatures33// and also to accept or reject different types of PubKey's. This is where apps can define their own PubKey34type SignatureVerificationGasConsumer = func(meter sdk.GasMeter, sig authTypes.StdSignature, params authTypes.Params) sdk.Result35//36// Collect fees interface37//38// FeeCollector interface for fees collector39type FeeCollector interface {40 GetModuleAddress(string) types.HeimdallAddress41 SendCoinsFromAccountToModule(42 sdk.Context,43 types.HeimdallAddress,44 string,45 sdk.Coins,46 ) sdk.Error47}48//49// MainTxMsg tx hash50//51type MainTxMsg interface {52 GetTxHash() types.HeimdallHash53 GetLogIndex() uint6454}55// NewAnteHandler returns an AnteHandler that checks and increments sequence56// numbers, checks signatures & account numbers, and deducts fees from the first57// signer.58func NewAnteHandler(59 ak AccountKeeper,60 chainKeeper chainmanager.Keeper,61 feeCollector FeeCollector,62 contractCaller helper.IContractCaller,63 sigGasConsumer SignatureVerificationGasConsumer,64) sdk.AnteHandler {65 return func(ctx sdk.Context, tx sdk.Tx, simulate bool) (newCtx sdk.Context, res sdk.Result, abort bool) {66 // get module address67 if addr := feeCollector.GetModuleAddress(authTypes.FeeCollectorName); addr.Empty() {68 return newCtx, sdk.ErrInternal(fmt.Sprintf("%s module account has not been set", authTypes.FeeCollectorName)).Result(), true69 }70 // all transactions must be of type auth.StdTx71 stdTx, ok := tx.(authTypes.StdTx)72 if !ok {73 // Set a gas meter with limit 0 as to prevent an infinite gas meter attack74 // during runTx.75 newCtx = SetGasMeter(simulate, ctx, 0)76 return newCtx, sdk.ErrInternal("tx must be StdTx").Result(), true77 }78 // get account params79 params := ak.GetParams(ctx)80 // gas for tx81 gasForTx := params.MaxTxGas // stdTx.Fee.Gas82 amount, ok := sdk.NewIntFromString(params.TxFees)83 if !ok {84 return newCtx, sdk.ErrInternal("Invalid param tx fees").Result(), true85 }86 feeForTx := sdk.Coins{sdk.Coin{Denom: authTypes.FeeToken, Amount: amount}} // stdTx.Fee.Amount87 // checkpoint gas limit88 if stdTx.Msg.Type() == "checkpoint" && stdTx.Msg.Route() == "checkpoint" {89 gasForTx = gasWantedPerCheckpoinTx // stdTx.Fee.Gas90 }91 // new gas meter92 newCtx = SetGasMeter(simulate, ctx, gasForTx)93 // AnteHandlers must have their own defer/recover in order for the BaseApp94 // to know how much gas was used! This is because the GasMeter is created in95 // the AnteHandler, but if it panics the context won't be set properly in96 // runTx's recover call.97 defer func() {98 if r := recover(); r != nil {99 switch rType := r.(type) {100 case sdk.ErrorOutOfGas:101 log := fmt.Sprintf(102 "out of gas in location: %v; gasWanted: %d, gasUsed: %d",103 rType.Descriptor, gasForTx, newCtx.GasMeter().GasConsumed(),104 )105 res = sdk.ErrOutOfGas(log).Result()106 res.GasWanted = gasForTx107 res.GasUsed = newCtx.GasMeter().GasConsumed()108 abort = true109 default:110 panic(r)111 }112 }113 }()114 // validate tx115 if err := tx.ValidateBasic(); err != nil {116 return newCtx, err.Result(), true117 }118 if res := ValidateMemo(stdTx, params); !res.IsOK() {119 return newCtx, res, true120 }121 // stdSigs contains the sequence number, account number, and signatures.122 // When simulating, this would just be a 0-length slice.123 signerAddrs := stdTx.GetSigners()124 if len(signerAddrs) == 0 {125 return newCtx, sdk.ErrNoSignatures("no signers").Result(), true126 }127 if len(signerAddrs) > 1 {128 return newCtx, sdk.ErrUnauthorized("wrong number of signers").Result(), true129 }130 isGenesis := ctx.BlockHeight() == 0131 // fetch first signer, who's going to pay the fees132 signerAcc, res := GetSignerAcc(newCtx, ak, types.AccAddressToHeimdallAddress(signerAddrs[0]))133 if !res.IsOK() {134 return newCtx, res, true135 }136 // deduct the fees137 if !feeForTx.IsZero() {138 res = DeductFees(feeCollector, newCtx, signerAcc, feeForTx)139 if !res.IsOK() {140 return newCtx, res, true141 }142 // reload the account as fees have been deducted143 signerAcc = ak.GetAccount(newCtx, signerAcc.GetAddress())144 }145 // get chain manager params146 chainParams := chainKeeper.GetParams(ctx)147 // check main chain tx is confirmed transaction148 mainTxMsg, ok := stdTx.Msg.(MainTxMsg)149 if ok && !contractCaller.IsTxConfirmed(ctx.BlockTime(), mainTxMsg.GetTxHash().EthHash(), chainParams.TxConfirmationTime) {150 return newCtx, sdk.ErrInternal(fmt.Sprintf("Not enough tx confirmations for %s", mainTxMsg.GetTxHash().Hex())).Result(), true151 }152 // stdSigs contains the sequence number, account number, and signatures.153 // When simulating, this would just be a 0-length slice.154 stdSigs := stdTx.GetSignatures()155 // check signature, return account with incremented nonce156 signBytes := GetSignBytes(newCtx.ChainID(), stdTx, signerAcc, isGenesis)157 signerAcc, res = processSig(newCtx, signerAcc, stdSigs[0], signBytes, simulate, params, sigGasConsumer)158 if !res.IsOK() {159 return newCtx, res, true160 }161 ak.SetAccount(newCtx, signerAcc)162 // TODO: tx tags (?)163 return newCtx, sdk.Result{GasWanted: gasForTx}, false // continue...164 }165}166// GetSignerAcc returns an account for a given address that is expected to sign167// a transaction.168func GetSignerAcc(169 ctx sdk.Context,170 ak AccountKeeper,171 addr types.HeimdallAddress,172) (authTypes.Account, sdk.Result) {173 if acc := ak.GetAccount(ctx, addr); acc != nil {174 return acc, sdk.Result{}175 }176 return nil, sdk.ErrUnknownAddress(fmt.Sprintf("account %s does not exist", addr)).Result()177}178// ValidateMemo validates the memo size.179func ValidateMemo(stdTx authTypes.StdTx, params authTypes.Params) sdk.Result {180 memoLength := len(stdTx.GetMemo())181 if uint64(memoLength) > params.MaxMemoCharacters {182 return sdk.ErrMemoTooLarge(183 fmt.Sprintf(184 "maximum number of characters is %d but received %d characters",185 params.MaxMemoCharacters, memoLength,186 ),187 ).Result()188 }189 return sdk.Result{}190}191// verify the signature and increment the sequence. If the account doesn't have192// a pubkey, set it.193func processSig(194 ctx sdk.Context,195 acc authTypes.Account,196 sig authTypes.StdSignature,197 signBytes []byte,198 simulate bool,199 params authTypes.Params,200 sigGasConsumer SignatureVerificationGasConsumer,201) (updatedAcc authTypes.Account, res sdk.Result) {202 if res := sigGasConsumer(ctx.GasMeter(), sig, params); !res.IsOK() {203 return nil, res204 }205 if !simulate {206 var pk secp256k1.PubKeySecp256k1207 p, err := authTypes.RecoverPubkey(signBytes, sig.Bytes())208 copy(pk[:], p[:])209 if err != nil || !bytes.Equal(acc.GetAddress().Bytes(), pk.Address().Bytes()) {210 return nil, sdk.ErrUnauthorized("signature verification failed; verify correct account sequence and chain-id").Result()211 }212 if acc.GetPubKey() == nil {213 var cryptoPk crypto.PubKey = pk214 if err := acc.SetPubKey(cryptoPk); err != nil {215 return nil, sdk.ErrUnauthorized("error while updating account pubkey").Result()216 }217 }218 }219 if err := acc.SetSequence(acc.GetSequence() + 1); err != nil {220 return nil, sdk.ErrUnauthorized("error while updating account sequence").Result()221 }222 return acc, res223}224// DefaultSigVerificationGasConsumer is the default implementation of SignatureVerificationGasConsumer. It consumes gas225// for signature verification based upon the public key type. The cost is fetched from the given params and is matched226// by the concrete type.227func DefaultSigVerificationGasConsumer(228 meter sdk.GasMeter, sig authTypes.StdSignature, params authTypes.Params,229) sdk.Result {230 meter.ConsumeGas(params.SigVerifyCostSecp256k1, "ante verify: secp256k1")231 return sdk.Result{}232}233// DeductFees deducts fees from the given account.234//235// NOTE: We could use the CoinKeeper (in addition to the AccountKeeper, because236// the CoinKeeper doesn't give us accounts), but it seems easier to do this.237func DeductFees(feeCollector FeeCollector, ctx sdk.Context, acc authTypes.Account, fees sdk.Coins) sdk.Result {238 blockTime := ctx.BlockHeader().Time239 coins := acc.GetCoins()240 if !fees.IsValid() {241 return sdk.ErrInsufficientFee(fmt.Sprintf("invalid fee amount: %s", fees)).Result()242 }243 // verify the account has enough funds to pay for fees244 _, hasNeg := coins.SafeSub(fees)245 if hasNeg {246 return sdk.ErrInsufficientFunds(247 fmt.Sprintf("insufficient funds to pay for fees; %s < %s", coins, fees),248 ).Result()249 }250 // Validate the account has enough "spendable" coins251 spendableCoins := acc.SpendableCoins(blockTime)252 if _, hasNeg := spendableCoins.SafeSub(fees); hasNeg {253 return sdk.ErrInsufficientFunds(254 fmt.Sprintf("insufficient funds to pay for fees; %s < %s", spendableCoins, fees),255 ).Result()256 }257 err := feeCollector.SendCoinsFromAccountToModule(ctx, acc.GetAddress(), authTypes.FeeCollectorName, fees)258 if err != nil {259 return err.Result()260 }261 return sdk.Result{}262}263// SetGasMeter returns a new context with a gas meter set from a given context.264func SetGasMeter(simulate bool, ctx sdk.Context, gasLimit uint64) sdk.Context {265 // In various cases such as simulation and during the genesis block, we do not266 // meter any gas utilization.267 if simulate || ctx.BlockHeight() == 0 {268 return ctx.WithGasMeter(sdk.NewInfiniteGasMeter())269 }270 return ctx.WithGasMeter(sdk.NewGasMeter(gasLimit))271}272// GetSignBytes returns a slice of bytes to sign over for a given transaction273// and an account.274func GetSignBytes(chainID string, stdTx authTypes.StdTx, acc authTypes.Account, genesis bool) []byte {275 var accNum uint64276 if !genesis {277 accNum = acc.GetAccountNumber()278 }279 return authTypes.StdSignBytes(chainID, accNum, acc.GetSequence(), stdTx.Msg, stdTx.Memo)280}...

Full Screen

Full Screen

func.go

Source:func.go Github

copy

Full Screen

1package main2import (3 "context"4 "encoding/json"5 "fmt"6 "io"7 "log"8 "strconv"9 "time"10 fdk "github.com/fnproject/fdk-go"11 zipkin "github.com/openzipkin/zipkin-go"12 "github.com/openzipkin/zipkin-go/model"13 zipkinHttpReporter "github.com/openzipkin/zipkin-go/reporter/http"14)15func main() {16 fdk.Handle(fdk.HandlerFunc(myHandler))17}18type Person struct {19 Name string `json:"name"`20}21func myHandler(ctx context.Context, in io.Reader, out io.Writer) {22 p := &Person{Name: "World"}23 json.NewDecoder(in).Decode(p)24 newCtx := fdk.GetContext(ctx)25 // Span main method26 // set up a span reporter27 reporter := zipkinHttpReporter.NewReporter(newCtx.TracingContextData().TraceCollectorURL())28 defer reporter.Close()29 // create our local service endpoint30 endpoint, err := zipkin.NewEndpoint(newCtx.ServiceName(), "")31 if err != nil {32 log.Fatalf("unable to create local endpoint: %+v\n", err)33 }34 // initialize our tracer35 tracer, err := zipkin.NewTracer(reporter, zipkin.WithLocalEndpoint(endpoint))36 // Set Context37 sctx := setContext(newCtx)38 sopt := zipkin.Parent(sctx)39 span, ctx := tracer.StartSpanFromContext(context.Background(), "Main Method", sopt)40 time.Sleep(15 * time.Millisecond)41 if err != nil {42 log.Fatalf("unable to create tracer: %+v\n", err)43 }44 oneMethod(ctx, tracer)45 msg := struct {46 Msg string `json:"message"`47 }{48 Msg: fmt.Sprintf("Hello %s :: and Service :: %s", newCtx.AppID(), newCtx.AppName()),49 }50 log.Print("Inside Go Hello World function")51 json.NewEncoder(out).Encode(&msg)52 span.Finish()53}54func setContext(ctx fdk.Context) model.SpanContext {55 traceId, err := model.TraceIDFromHex(ctx.TracingContextData().TraceId())56 if err != nil {57 log.Println("TRACE ID NOT DEFINED.....")58 return model.SpanContext{}59 }60 id, err := strconv.ParseUint(ctx.TracingContextData().SpanId(), 16, 64)61 if err != nil {62 log.Println("SPAN ID NOT DEFINED.....")63 return model.SpanContext{}64 }65 i := model.ID(id)66 sctx := model.SpanContext{67 TraceID: traceId,68 ID: i,69 ParentID: nil,70 Sampled: BoolAddr(ctx.TracingContextData().IsSampled()),71 }72 return sctx73}74func BoolAddr(b bool) *bool {75 boolVar := b76 return &boolVar77}78func oneMethod(ctx context.Context, tracer *zipkin.Tracer) {79 span, newCtx := tracer.StartSpanFromContext(ctx, "OneChildSpan")80 time.Sleep(80 * time.Millisecond)81 ctx = newCtx82 secMethod(ctx, tracer)83 span.Finish()84}85func secMethod(ctx context.Context, tracer *zipkin.Tracer) {86 span, newCtx := tracer.StartSpanFromContext(ctx, "SecChildSpan")87 time.Sleep(100 * time.Millisecond)88 ctx = newCtx89 span.Finish()90}...

Full Screen

Full Screen

main.go

Source:main.go Github

copy

Full Screen

1package main2import (3 "context"4 "fmt"5 "github.com/10hin/cache-eks-creds/cmd"6 "github.com/10hin/cache-eks-creds/pkg/cache"7 "github.com/10hin/cache-eks-creds/pkg/kubeconfig_resolver"8 "github.com/10hin/cache-eks-creds/pkg/profile_resolver"9 "os"10 "os/signal"11 "syscall"12)13func main() {14 emptyCtx := context.Background()15 ctxWithComponents := storeComponents(emptyCtx, map[string]interface{}{16 cache.Key: cache.NewFileCache(),17 profile_resolver.Key: profile_resolver.NewProfileResolver(),18 kubeconfig_resolver.Key: kubeconfig_resolver.NewKubeconfigResolver(),19 })20 ctx, cancel := context.WithCancel(ctxWithComponents)21 defer cancel()22 sigChan := make(chan os.Signal, 0)23 signal.Notify(sigChan, syscall.SIGINT)24 complete := make(chan struct{}, 0)25 go func(ctx1 context.Context, complete1 chan<- struct{}) {26 defer func() {27 close(complete1)28 }()29 err1 := cmd.ExecuteContext(ctx1)30 if err1 != nil {31 panic(err1)32 }33 }(ctx, complete)34 select {35 case <-sigChan:36 fmt.Println("SIGINT received!")37 panic(fmt.Errorf("interrpted"))38 case <-complete:39 }40}41func storeComponents(ctx context.Context, components map[string]interface{}) context.Context {42 var newCtx context.Context = nil43 for key, comp := range components {44 if newCtx == nil {45 newCtx = context.WithValue(ctx, key, comp)46 } else {47 newCtx = context.WithValue(newCtx, key, comp)48 }49 }50 return newCtx51}...

Full Screen

Full Screen

NewCtx

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx, cancel := context.WithCancel(context.Background())4 defer cancel()5 go doSomething(ctx, 5*time.Second)6 time.Sleep(10 * time.Second)7}8func doSomething(ctx context.Context, duration time.Duration) {9 select {10 case <-time.After(duration):11 fmt.Println("Done")12 case <-ctx.Done():13 fmt.Println("Canceled")14 }15}

Full Screen

Full Screen

NewCtx

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 ctx, cancel := context.WithCancel(ctx)5 go func() {6 time.Sleep(5 * time.Second)7 cancel()8 }()9 select {10 case <-time.After(6 * time.Second):11 fmt.Println("overslept")12 case <-ctx.Done():13 fmt.Println("context done")14 }15}

Full Screen

Full Screen

NewCtx

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := main.NewCtx()4 fmt.Println(ctx)5}6&{0xc00000e020 0xc00000e040 0xc00000e060 0xc00000e080 0xc00000e0a0 0xc00000e0c0 0xc00000e0e0 0xc00000e100 0xc00000e120 0xc00000e140 0xc00000e160 0xc00000e180 0xc00000e1a0 0xc00000e1c0 0xc00000e1e0 0xc00000e200 0xc00000e220 0xc00000e240 0xc00000e260 0xc00000e280 0xc00000e2a0 0xc00000e2c0 0xc00000e2e0 0xc00000e300 0xc00000e320 0xc00000e340 0xc00000e360 0xc00000e380 0xc00000e3a0 0xc00000e3c0 0xc00000e3e0 0xc00000e400 0xc00000e420 0xc00000e440 0xc00000e460 0xc00000e480 0xc00000e4a0 0xc00000e4c0 0xc00000e4e0 0xc00000e500 0xc00000e520 0xc00000e540 0xc00000e560 0xc00000e580 0xc00000e5a0 0xc00000e5c0 0xc00000e5e0 0xc00000e600 0xc00000e620 0xc00000e640 0xc00000e660 0xc00000e680 0xc00000e6a0 0xc00000e6c0 0xc00000e6e0 0xc00000e700 0xc00000e720 0xc00000e740 0xc00000

Full Screen

Full Screen

NewCtx

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := ctx.NewCtx()4 fmt.Println(ctx)5}6&{0xc0000101e0}7import (8func main() {9 ctx := context.Background()10 fmt.Println(ctx)11}12context.Background.WithCancel.WithValue(type string, val ).WithValue(type string, val )

Full Screen

Full Screen

NewCtx

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := NewCtx()4 ctx1 := NewCtx()5 fmt.Println(ctx)6 fmt.Println(ctx1)7}8import (9func main() {10 ctx := NewCtx()11 ctx1 := context.WithValue(ctx, "key", "value")12 fmt.Println(ctx)13 fmt.Println(ctx1)14}15import (

Full Screen

Full Screen

NewCtx

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := main.NewCtx()4 fmt.Println(ctx)5}6&{0xc00000e1e0}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Syzkaller automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful