Best K6 code snippet using core.IsTainted
processing.go
Source:processing.go
1package blockchain2import (3 "crypto/sha256"4 "errors"5 "math"6 "reflect"7 "strconv"8 "time"9 "github.com/0x5eba/Dexm/dexm-core/util"10 "github.com/0x5eba/Dexm/dexm-core/wallet"11 protobufs "github.com/0x5eba/Dexm/protobufs/build/blockchain"12 "github.com/golang/protobuf/proto"13 pq "github.com/jupp0r/go-priority-queue"14 log "github.com/sirupsen/logrus"15 "github.com/syndtr/goleveldb/leveldb"16)17type MissingBlockStruct struct {18 sequenceBlock uint6419 arrivalOrder float6420 hightestBlock string21 blocksToRecalculate []string22}23func (mb MissingBlockStruct) GetMBSequenceBlock() uint64 {24 return mb.sequenceBlock25}26func (mb MissingBlockStruct) GetMBArrivalOrder() float64 {27 return mb.arrivalOrder28}29func (mb MissingBlockStruct) GetMBHightestBlock() string {30 return mb.hightestBlock31}32func (mb MissingBlockStruct) GetMBbBlocksToRecalculate() []string {33 return mb.blocksToRecalculate34}35func (bc *Blockchain) ModifyMissingBlock(key string, mb MissingBlockStruct, hashCurrentBlock string) {36 bc.MissingBlock[key] = MissingBlockStruct{mb.sequenceBlock + 1, mb.arrivalOrder, mb.hightestBlock, append(mb.blocksToRecalculate, hashCurrentBlock)}37}38func (bc *Blockchain) AddMissingBlock(key string, arrivalOrder float64, hightestBlock string) {39 bc.MissingBlock[key] = MissingBlockStruct{1, arrivalOrder, hightestBlock, []string{}}40}41// Blockchain is an internal representation of a blockchain42type Blockchain struct {43 balancesDb *leveldb.DB44 BlockDb *leveldb.DB45 ContractDb *leveldb.DB46 StateDb *leveldb.DB47 CasperVotesDb *leveldb.DB48 Mempool *mempool49 Schnorr map[string][]byte50 MTReceipt [][]byte51 RSchnorr [][]byte52 PSchnorr [][]byte53 MessagesReceipt [][]byte54 GenesisTimestamp uint6455 CurrentBlock uint6456 CurrentVote uint6457 CurrentCheckpoint uint6458 CurrentValidator map[uint64]string59 PriorityBlocks pq.PriorityQueue60 MissingBlock map[string]MissingBlockStruct61 HashBlocks map[string]uint6462}63// BeaconChain is an internal representation of a beacon chain64type BeaconChain struct {65 MerkleRootsDb map[uint32]*leveldb.DB66 Validators *ValidatorsBook67 CurrentBlock map[uint32]uint6468}69// NewBeaconChain create a new beacon chain70func NewBeaconChain(dbPath string) (*BeaconChain, error) {71 mrdb := make(map[uint32]*leveldb.DB)72 cb := make(map[uint32]uint64)73 for i := uint32(1); i < nShard+1; i++ {74 db, err := leveldb.OpenFile(dbPath+".merkleroots"+strconv.Itoa(int(i)), nil)75 if err != nil {76 return nil, err77 }78 mrdb[i] = db79 cb[i] = 080 }81 vd := NewValidatorsBook()82 return &BeaconChain{83 MerkleRootsDb: mrdb,84 Validators: vd,85 CurrentBlock: cb,86 }, nil87}88// NewBlockchain creates a database db89func NewBlockchain(dbPath string, index uint64) (*Blockchain, error) {90 db, err := leveldb.OpenFile(dbPath+".balances", nil)91 if err != nil {92 return nil, err93 }94 dbb, err := leveldb.OpenFile(dbPath+".blocks", nil)95 if err != nil {96 return nil, err97 }98 cdb, err := leveldb.OpenFile(dbPath+".code", nil)99 if err != nil {100 return nil, err101 }102 sdb, err := leveldb.OpenFile(dbPath+".memory", nil)103 if err != nil {104 return nil, err105 }106 cvdb, err := leveldb.OpenFile(dbPath+".votes", nil)107 if err != nil {108 return nil, err109 }110 // 1MB blocks111 mp := newMempool(1000000, 100)112 currentValidators := make(map[uint64]string)113 currentValidators[0] = "Dexm0135yvZqn8V7S88emfcJFzQMMMn3ARDCA241D2"114 currentValidators[1] = ""115 return &Blockchain{116 balancesDb: db,117 BlockDb: dbb,118 ContractDb: cdb,119 StateDb: sdb,120 CasperVotesDb: cvdb,121 Mempool: mp,122 Schnorr: make(map[string][]byte),123 MTReceipt: [][]byte{},124 RSchnorr: [][]byte{},125 PSchnorr: [][]byte{},126 MessagesReceipt: [][]byte{},127 CurrentBlock: index,128 CurrentCheckpoint: 0,129 CurrentVote: 0,130 CurrentValidator: currentValidators,131 PriorityBlocks: pq.New(),132 MissingBlock: make(map[string]MissingBlockStruct),133 HashBlocks: make(map[string]uint64),134 }, err135}136// GetWalletState returns the state of a wallet in the current block137func (bc *Blockchain) GetWalletState(wallet string) (protobufs.AccountState, error) {138 state := protobufs.AccountState{}139 raw, err := bc.balancesDb.Get([]byte(wallet), nil)140 if err != nil {141 return state, err142 }143 proto.Unmarshal(raw, &state)144 return state, nil145}146func (beaconChain *BeaconChain) SaveMerkleRoots(mr *protobufs.MerkleRootsSigned) error {147 res, _ := proto.Marshal(mr)148 currShard := mr.GetShard()149 log.Info("SaveMerkleRoots on shard ", currShard)150 beaconChain.CurrentBlock[currShard]++151 return beaconChain.MerkleRootsDb[currShard].Put([]byte(strconv.Itoa(int(beaconChain.CurrentBlock[currShard]))), res, nil)152}153func (beaconChain *BeaconChain) GetMerkleRoots(index uint64, shard uint32) ([]byte, error) {154 return beaconChain.MerkleRootsDb[shard].Get([]byte(strconv.Itoa(int(index))), nil)155}156// GetBlockBeacon returns the array of blocks at an index and at a specific shard157func (beaconChain *BeaconChain) GetBlockBeacon(index int64, shard uint32) ([]byte, error) {158 return beaconChain.MerkleRootsDb[shard].Get([]byte(strconv.Itoa(int(index))), nil)159}160// GetBlock returns the array of blocks at an index161func (bc *Blockchain) GetBlock(index uint64) ([]byte, error) {162 return bc.BlockDb.Get([]byte(strconv.Itoa(int(index))), nil)163}164// GetContractCode returns the code of a contract at an address. Used165// as a wrapper so when we add diffed contracts in the future it's easier166// to change without breaking everything167func (bc *Blockchain) GetContractCode(address []byte) ([]byte, error) {168 return bc.ContractDb.Get(address, nil)169}170// ValidateBlock checks the validity of a block. It uses the current171// blockchain state so the passed block might become valid in the future.172func (bc *Blockchain) ValidateBlock(block *protobufs.Block) (bool, error) {173 isTainted := make(map[string]bool)174 taintedState := make(map[string]protobufs.AccountState)175 // Genesis block is fine176 if block.GetIndex() == 0 {177 return true, nil178 }179 for i, t := range block.GetTransactions() {180 sender := wallet.BytesToAddress(t.GetSender(), t.GetShard())181 result, _ := proto.Marshal(t)182 bhash := sha256.Sum256(result)183 hash := bhash[:]184 valid, err := wallet.SignatureValid(t.GetSender(), t.GetR(), t.GetS(), hash)185 if !valid || err != nil {186 log.Error("SignatureValid ", err)187 return false, err188 }189 balance := protobufs.AccountState{}190 // Check if the address state changed while processing this block191 // If it hasn't changed then pull the state from the blockchain, otherwise192 // get the updated copy instead193 if !isTainted[sender] {194 balance, err = bc.GetWalletState(sender)195 if err != nil {196 log.Error("getwalletstate ", err)197 return false, err198 }199 } else {200 balance = taintedState[sender]201 }202 // Check if balance is sufficient203 requiredBal, ok := util.AddU64O(t.GetAmount(), uint64(t.GetGas()))204 if requiredBal > balance.GetBalance() && ok {205 return false, errors.New("Balance is insufficient in transaction " + strconv.Itoa(i))206 }207 // Check if has already been send208 res, _ := proto.Marshal(t)209 dbKeyS := sha256.Sum256(res)210 dbKey := dbKeyS[:]211 data, err := bc.BlockDb.Get(dbKey, nil)212 if err == nil {213 tr := &protobufs.Transaction{}214 err = proto.Unmarshal(data, tr)215 if err != nil {216 return false, errors.New("Transaction was already included in db")217 }218 }219 // Taint sender and update his balance. Reciver will be able to spend220 // his cash from the next block221 isTainted[sender] = true222 newBal, ok := util.SubU64O(balance.Balance, requiredBal)223 if !ok {224 return false, errors.New("Overflow in transaction " + strconv.Itoa(i))225 }226 balance.Balance = newBal227 taintedState[sender] = balance228 // To save a DB query we don't check the reciver for an overflow. If someone229 // gets that much cash we are gonna be fucked anyways because of PoS230 }231 merkleRoot, err := GenerateMerkleTree(block.GetTransactions(), block.GetReceiptsContracts())232 if err != nil {233 log.Error(err)234 return false, err235 }236 if !reflect.DeepEqual(merkleRoot, block.GetMerkleRootReceipt()) {237 return false, errors.New("merkleRoot != block.GetMerkleRootReceipt())")238 }239 return true, nil240}241func (bc *Blockchain) SetState(wallet string, newState *protobufs.AccountState) error {242 stateBytes, err := proto.Marshal(newState)243 if err != nil {244 return err245 }246 return bc.balancesDb.Put([]byte(wallet), stateBytes, nil)247}248// ValidateTransaction validates a transaction with the current state.249// Different from ValidateBlock because that has to verify for double spends250// inside the same block.251func (bc *Blockchain) ValidateTransaction(t *protobufs.Transaction) error {252 sender := wallet.BytesToAddress(t.GetSender(), t.GetShard())253 if !wallet.IsWalletValid(t.GetRecipient()) {254 return errors.New("Invalid recipient")255 }256 result, _ := proto.Marshal(t)257 bhash := sha256.Sum256(result)258 hash := bhash[:]259 valid, err := wallet.SignatureValid(t.GetSender(), t.GetR(), t.GetS(), hash)260 if !valid {261 return err262 }263 balance, err := bc.GetWalletState(sender)264 if err != nil {265 return err266 }267 // Check if gas is sufficient, right now is minimal 16000, that are 12 gwei268 // 1 gwei = 1000000000 iska269 if t.GetGas() < 16000 {270 return errors.New("Not enough gas")271 }272 // Check if balance is sufficient273 requiredBal, ok := util.AddU64O(t.GetAmount(), uint64(t.GetGas()*1000000000))274 if requiredBal > balance.GetBalance() && ok {275 return errors.New("Balance is insufficient in transaction")276 }277 return nil278}279// GetNetworkIndex returns the current block index of the network280func (bc *Blockchain) GetNetworkIndex() int64 {281 timeSinceGenesis := time.Now().Unix() - int64(bc.GenesisTimestamp)282 index := math.Floor(float64(timeSinceGenesis) / 5.0)283 return int64(index)284}...
pool.go
Source:pool.go
1package blockchain2import (3 "crypto/sha256"4 "errors"5 "time"6 "github.com/0x5eba/Dexm/dexm-core/util"7 "github.com/0x5eba/Dexm/dexm-core/wallet"8 protobufs "github.com/0x5eba/Dexm/protobufs/build/blockchain"9 "github.com/golang/protobuf/proto"10 pq "github.com/jupp0r/go-priority-queue"11 log "github.com/sirupsen/logrus"12)13type mempool struct {14 maxBlockBytes int15 maxGasPerByte float6416 queue pq.PriorityQueue17}18func newMempool(maxBlockSize int, maxGas float64) *mempool {19 return &mempool{maxBlockSize, maxGas, pq.New()}20}21var countMempoolTransactions = 022var countBlockTransactions = 023func DashMempoolTransactions() func() float64 {24 return func() float64 {25 tmp := float64(countMempoolTransactions)26 countMempoolTransactions = 027 return tmp28 }29}30func DashBlockTransactions() func() float64 {31 return func() float64 {32 tmp := float64(countBlockTransactions)33 countBlockTransactions = 034 return tmp35 }36}37// AddMempoolTransaction adds a transaction to the mempool38func (bc *Blockchain) AddMempoolTransaction(pb *protobufs.Transaction, transaction []byte) error {39 err := bc.ValidateTransaction(pb)40 if err != nil {41 log.Error(err)42 return err43 }44 // save the hash of the transaction and put it on blockdb45 dbKeyS := sha256.Sum256(transaction)46 dbKey := dbKeyS[:]47 _, err = bc.BlockDb.Get(dbKey, nil)48 if err == nil {49 return errors.New("Already in db")50 }51 countMempoolTransactions++52 bc.BlockDb.Put(dbKey, transaction, nil)53 bc.Mempool.queue.Insert(&dbKey, float64(pb.GetGas()))54 return nil55}56// GenerateBlock generates a valid unsigned block with transactions from the mempool57func (bc *Blockchain) GenerateBlock(miner string, shard uint32, validators *ValidatorsBook) (*protobufs.Block, error) {58 hash := []byte{}59 hashInterface, err := bc.PriorityBlocks.Pop()60 if err != nil || hashInterface == nil {61 return nil, err62 }63 hashString := interface{}(hashInterface).(string)64 hash = []byte(hashString)65 block := protobufs.Block{66 Index: bc.CurrentBlock,67 Timestamp: uint64(time.Now().Unix()),68 Miner: miner,69 PrevHash: hash,70 Shard: shard,71 }72 blockHeader, err := proto.Marshal(&block)73 if err != nil {74 return nil, err75 }76 var transactions []*protobufs.Transaction77 receiptsContracts := []*protobufs.Receipt{}78 currentLen := len(blockHeader)79 isTainted := make(map[string]bool)80 taintedState := make(map[string]protobufs.AccountState)81 // Check that the len is smaller than the max82 for currentLen < bc.Mempool.maxBlockBytes {83 txB, err := bc.Mempool.queue.Pop()84 // The mempool is empty, that's all the transactions we can include85 if err != nil {86 break87 }88 txKey := interface{}(txB).(*[]byte)89 txData, err := bc.BlockDb.Get(*txKey, nil)90 if err != nil {91 continue92 }93 rtx := &protobufs.Transaction{}94 proto.Unmarshal(txData, rtx)95 // Don't include invalid transactions96 err = bc.ValidateTransaction(rtx)97 if err != nil {98 continue99 }100 // check if the transazion is for my shard101 senderWallet := wallet.BytesToAddress(rtx.GetSender(), rtx.GetShard())102 shardSender, err := validators.GetShard(senderWallet)103 if err != nil {104 log.Error(err)105 continue106 }107 currentShard, err := validators.GetShard(miner)108 if err != nil {109 log.Error(err)110 continue111 }112 if shardSender != currentShard {113 continue114 }115 balance := protobufs.AccountState{}116 // Check if the address state changed while processing this block117 // If it hasn't changed then pull the state from the blockchain, otherwise118 // get the updated copy instead119 if !isTainted[senderWallet] {120 balance, err = bc.GetWalletState(senderWallet)121 if err != nil {122 continue123 }124 } else {125 balance = taintedState[senderWallet]126 }127 // If a function identifier is specified then fetch the contract and execute128 // If the contract reverts take the gas and return the transaction value129 if rtx.GetFunction() != "" {130 c, err := GetContract(rtx.GetRecipient(), bc, rtx, balance.Balance)131 if err != nil {132 continue133 }134 returnState := c.ExecuteContract(rtx.GetFunction(), rtx.GetArgs())135 if err != nil {136 continue137 }138 receiptsContracts = append(receiptsContracts, returnState.Outputs...)139 }140 // Check if balance is sufficient141 requiredBal, ok := util.AddU64O(rtx.GetAmount(), uint64(rtx.GetGas()))142 if requiredBal > balance.GetBalance() && ok {143 continue144 }145 newBal, ok := util.SubU64O(balance.Balance, requiredBal)146 if !ok {147 continue148 }149 balance.Balance = newBal150 isTainted[senderWallet] = true151 taintedState[senderWallet] = balance152 rawTx, err := proto.Marshal(rtx)153 if err != nil {154 continue155 }156 transactions = append(transactions, rtx)157 currentLen += len(rawTx)158 for _, r := range receiptsContracts {159 rByte, _ := proto.Marshal(r)160 currentLen += len(rByte)161 }162 }163 block.Transactions = transactions164 block.ReceiptsContracts = receiptsContracts165 countBlockTransactions = len(transactions)166 // create the merkletree with the transactions and get its root167 merkleRootReceipt := []byte{}168 if len(transactions) != 0 {169 merkleRootReceipt, err = GenerateMerkleTree(transactions, receiptsContracts)170 if err != nil {171 return nil, err172 }173 }174 // put the merkleroot inside the block175 block.MerkleRootReceipt = merkleRootReceipt176 return &block, nil177}...
status.go
Source:status.go
...40 Paused: null.BoolFrom(executionState.IsPaused()),41 Stopped: engine.IsStopped(),42 VUs: null.IntFrom(executionState.GetCurrentlyActiveVUsCount()),43 VUsMax: null.IntFrom(executionState.GetInitializedVUsCount()),44 Tainted: engine.IsTainted(),45 }46}...
IsTainted
Using AI Code Generation
1import (2func main() {3 s := core.Source{}4 s1 := core.Source{}5 s2 := core.Source{}6 s3 := core.Source{}7 s4 := core.Source{}8 s5 := core.Source{}9 fmt.Println("Hello, playground")10}11import (12func main() {13 s := core.Source{}14 s1 := core.Source{}15 s2 := core.Source{}16 s3 := core.Source{}17 s4 := core.Source{}18 s5 := core.Source{}
IsTainted
Using AI Code Generation
1import (2func main() {3 fmt.Println(s)4 if levee.IsTainted(s) {5 fmt.Println("source is tainted")6 }7}8import (9func main() {10 fmt.Println(s)11 if levee.IsTainted(s) {12 fmt.Println("source is tainted")13 }14}15import (16func main() {17 fmt.Println(s)18 if levee.IsTainted(s) {19 fmt.Println("source is tainted")20 }21}22import (23func main() {24 fmt.Println(s)25 if levee.IsTainted(s) {26 fmt.Println("source is tainted")27 }28}29import (30func main() {31 fmt.Println(s)32 if levee.IsTainted(s) {33 fmt.Println("source is tainted")34 }35}36import (37func main() {38 fmt.Println(s)
IsTainted
Using AI Code Generation
1import (2func main() {3 fmt.Println(taint.IsTainted(a))4}5import (6func main() {7 taint.SetTaint(&a)8 fmt.Println(taint.IsTainted(a))9}10import (11func main() {12 taint.SetTaint(&a)13 fmt.Println(taint.IsTainted(a))14 taint.UnsetTaint(&a)15 fmt.Println(taint.IsTainted(a))16}17import (18func main() {19 taint.SetTaint(&a)20 fmt.Println(taint.IsTainted(a))21 taint.UnsetTaint(&a)22 fmt.Println(taint.IsTainted(a))23 fmt.Println(taint.GetTaintSource(a))24}25import (
IsTainted
Using AI Code Generation
1import (2func main() {3 import (4 func main() {5 fmt.Println(gosec.IsTainted(s))6 }7 cfg := &gosec.Config{IncludeGosecLib: true, IncludeImports: true}8 issues, err := gosec.NewAnalyzer(cfg).ScanSrc(src)9 if err != nil {10 panic(err)11 }12 fmt.Println(issues)13}14[{"severity":"HIGH","confidence":"HIGH","rule_id":"G101","details":"Potential hardcoded credentials","file":"1.go","code":"\tfmt.Println(gosec.IsTainted(s))\r15","line":"15"}]16import (17func main() {18 import (19 func main() {20 fmt.Println(gosec.IsTainted(s))21 }22 cfg := &gosec.Config{IncludeGosecLib: true, IncludeImports: true}23 issues, err := gosec.NewAnalyzer(cfg).ScanSrc(src)24 if err != nil {25 panic(err)26 }27 fmt.Println(issues)28}29[{"severity":"HIGH","confidence":"HIGH","rule_id":"G101","details":"Potential hardcoded credentials","file":"2.go","code":"\tfmt.Println(gosec.IsTainted(s))\r30","line":"15"}]31import (32func main() {33 import (34 func main() {
IsTainted
Using AI Code Generation
1import (2func main() {3 fmt.Println(gosec.IsTainted(s))4 s = gosec.GetTaintSource()5 fmt.Println(gosec.IsTainted(s))6}7import (8func main() {9 fmt.Println(gosec.IsTainted(s))10 s = gosec.GetTaintSource()11 fmt.Println(gosec.IsTainted(s))12}13import (14func main() {15 fmt.Println(gosec.IsTainted(s))16 s = gosec.GetTaintSource()17 fmt.Println(gosec.IsTainted(s))18}19import (20func main() {21 fmt.Println(gosec.IsTainted(s))22 s = gosec.GetTaintSource()23 fmt.Println(gosec.IsTainted(s))24}25import (26func main() {27 fmt.Println(gosec.IsTainted(s))28 s = gosec.GetTaintSource()29 fmt.Println(gosec.IsTainted(s))30}31import (
IsTainted
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello World")4 if csrf.IsTainted(a) {5 fmt.Println("Tainted")6 } else {7 fmt.Println("Not Tainted")8 }9 if csrf.IsTainted(b) {10 fmt.Println("Tainted")11 } else {12 fmt.Println("Not Tainted")13 }14}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!