Best Go-testdeep code snippet using json.hex
trade.go
Source:trade.go
1package types2import (3 "encoding/json"4 "fmt"5 "math/big"6 "time"7 "github.com/tomochain/tomox-sdk/errors"8 "github.com/ethereum/go-ethereum/common"9 "github.com/ethereum/go-ethereum/crypto/sha3"10 "github.com/tomochain/tomox-sdk/utils/math"11 "github.com/globalsign/mgo/bson"12)13const (14 TradeStatusPending = "PENDING"15 TradeStatusSuccess = "SUCCESS"16 TradeStatusError = "ERROR"17)18// Trade struct holds arguments corresponding to a "Taker Order"19// To be valid an accept by the matching engine (and ultimately the exchange smart-contract),20// the trade signature must be made from the trader Maker account21type Trade struct {22 ID bson.ObjectId `json:"id,omitempty" bson:"_id"`23 Taker common.Address `json:"taker" bson:"taker"`24 Maker common.Address `json:"maker" bson:"maker"`25 BaseToken common.Address `json:"baseToken" bson:"baseToken"`26 QuoteToken common.Address `json:"quoteToken" bson:"quoteToken"`27 MakerOrderHash common.Hash `json:"makerOrderHash" bson:"makerOrderHash"`28 TakerOrderHash common.Hash `json:"takerOrderHash" bson:"takerOrderHash"`29 Hash common.Hash `json:"hash" bson:"hash"`30 TxHash common.Hash `json:"txHash" bson:"txHash"`31 PairName string `json:"pairName" bson:"pairName"`32 PricePoint *big.Int `json:"pricepoint" bson:"pricepoint"`33 Amount *big.Int `json:"amount" bson:"amount"`34 MakeFee *big.Int `json:"makeFee" bson:"makeFee"`35 TakeFee *big.Int `json:"takeFee" bson:"takeFee"`36 Status string `json:"status" bson:"status"`37 CreatedAt time.Time `json:"createdAt" bson:"createdAt"`38 UpdatedAt time.Time `json:"updatedAt" bson:"updatedAt"`39 TakerOrderSide string `json:"takerOrderSide" bson:"takerOrderSide"`40 TakerOrderType string `json:"takerOrderType" bson:"takerOrderType"`41 MakerOrderType string `json:"makerOrderType" bson:"makerOrderType"`42 MakerExchange common.Address `json:"makerExchange" bson:"makerExchange"`43 TakerExchange common.Address `json:"takerExchange" bson:"takerExchange"`44}45// TradeSpec for query46type TradeSpec struct {47 BaseToken string48 QuoteToken string49 RelayerAddress common.Address50 DateFrom int6451 DateTo int6452}53// TradeRes response api54type TradeRes struct {55 Total int `json:"total" bson:"total"`56 Trades []*Trade `json:"trades" bson:"orders"`57}58type TradeRecord struct {59 ID bson.ObjectId `json:"id" bson:"_id"`60 Taker string `json:"taker" bson:"taker"`61 Maker string `json:"maker" bson:"maker"`62 BaseToken string `json:"baseToken" bson:"baseToken"`63 QuoteToken string `json:"quoteToken" bson:"quoteToken"`64 MakerOrderHash string `json:"makerOrderHash" bson:"makerOrderHash"`65 TakerOrderHash string `json:"takerOrderHash" bson:"takerOrderHash"`66 Hash string `json:"hash" bson:"hash"`67 TxHash string `json:"txHash" bson:"txHash"`68 PairName string `json:"pairName" bson:"pairName"`69 Amount string `json:"amount" bson:"amount"`70 MakeFee string `json:"makeFee" bson:"makeFee"`71 TakeFee string `json:"takeFee" bson:"takeFee"`72 PricePoint string `json:"pricepoint" bson:"pricepoint"`73 Status string `json:"status" bson:"status"`74 CreatedAt time.Time `json:"createdAt" bson:"createdAt"`75 UpdatedAt time.Time `json:"updatedAt" bson:"updatedAt"`76 TakerOrderSide string `json:"takerOrderSide" bson:"takerOrderSide"`77 TakerOrderType string `json:"takerOrderType" bson:"takerOrderType"`78 MakerOrderType string `json:"makerOrderType" bson:"makerOrderType"`79 MakerExchange string `json:"makerExchange" bson:"makerExchange"`80 TakerExchange string `json:"takerExchange" bson:"takerExchange"`81}82// NewTrade returns a new unsigned trade corresponding to an Order, amount and taker address83func NewTrade(mo *Order, to *Order, amount *big.Int, pricepoint *big.Int) *Trade {84 t := &Trade{85 Maker: mo.UserAddress,86 Taker: to.UserAddress,87 BaseToken: mo.BaseToken,88 QuoteToken: mo.QuoteToken,89 MakerOrderHash: mo.Hash,90 TakerOrderHash: to.Hash,91 PairName: mo.PairName,92 Amount: amount,93 PricePoint: pricepoint,94 Status: TradeStatusPending,95 }96 t.Hash = t.ComputeHash()97 return t98}99func (t *Trade) Validate() error {100 if (t.Taker == common.Address{}) {101 return errors.New("Trade 'taker' parameter is required'")102 }103 if (t.Maker == common.Address{}) {104 return errors.New("Trade 'maker' parameter is required")105 }106 if (t.TakerOrderHash == common.Hash{}) {107 return errors.New("Trade 'takerOrderHash' parameter is required")108 }109 if (t.MakerOrderHash == common.Hash{}) {110 return errors.New("Trade 'makerOrderHash' parameter is required")111 }112 if (t.BaseToken == common.Address{}) {113 return errors.New("Trade 'baseToken' parameter is required")114 }115 if (t.QuoteToken == common.Address{}) {116 return errors.New("Trade 'quoteToken' parameter is required")117 }118 if t.Amount == nil {119 return errors.New("Trade 'amount' parameter is required")120 }121 if t.PricePoint == nil {122 return errors.New("Trade 'pricepoint' paramter is required")123 }124 if math.IsEqualOrSmallerThan(t.PricePoint, big.NewInt(0)) {125 return errors.New("Trade 'pricepoint' parameter should be positive")126 }127 if math.IsEqualOrSmallerThan(t.Amount, big.NewInt(0)) {128 return errors.New("Trade 'amount' parameter should be positive")129 }130 // validations for hash131 if t.Hash != t.ComputeHash() {132 return errors.New("Trade 'hash' is incorrect")133 }134 return nil135}136// MarshalJSON returns the json encoded byte array representing the trade struct137func (t *Trade) MarshalJSON() ([]byte, error) {138 trade := map[string]interface{}{139 "taker": t.Taker,140 "maker": t.Maker,141 "status": t.Status,142 "hash": t.Hash,143 "pairName": t.PairName,144 "pricepoint": t.PricePoint.String(),145 "amount": t.Amount.String(),146 "makeFee": t.MakeFee.String(),147 "takeFee": t.TakeFee.String(),148 "createdAt": t.CreatedAt.Format(time.RFC3339Nano),149 "takerOrderSide": t.TakerOrderSide,150 "takerOrderType": t.TakerOrderType,151 "makerOrderType": t.MakerOrderType,152 "makerExchange": t.MakerExchange,153 "takerExchange": t.TakerExchange,154 }155 if (t.BaseToken != common.Address{}) {156 trade["baseToken"] = t.BaseToken.Hex()157 }158 if (t.QuoteToken != common.Address{}) {159 trade["quoteToken"] = t.QuoteToken.Hex()160 }161 if (t.TxHash != common.Hash{}) {162 trade["txHash"] = t.TxHash.Hex()163 }164 if (t.TakerOrderHash != common.Hash{}) {165 trade["takerOrderHash"] = t.TakerOrderHash.Hex()166 }167 if (t.MakerOrderHash != common.Hash{}) {168 trade["makerOrderHash"] = t.MakerOrderHash.Hex()169 }170 return json.Marshal(trade)171}172// UnmarshalJSON creates a trade object from a json byte string173func (t *Trade) UnmarshalJSON(b []byte) error {174 trade := map[string]interface{}{}175 err := json.Unmarshal(b, &trade)176 if err != nil {177 return err178 }179 if trade["makerOrderHash"] == nil {180 return errors.New("Order Hash is not set")181 } else {182 t.MakerOrderHash = common.HexToHash(trade["makerOrderHash"].(string))183 }184 if trade["takerOrderHash"] != nil {185 t.TakerOrderHash = common.HexToHash(trade["takerOrderHash"].(string))186 }187 if trade["hash"] == nil {188 return errors.New("Hash is not set")189 } else {190 t.Hash = common.HexToHash(trade["hash"].(string))191 }192 if trade["quoteToken"] == nil {193 return errors.New("Quote token is not set")194 } else {195 t.QuoteToken = common.HexToAddress(trade["quoteToken"].(string))196 }197 if trade["baseToken"] == nil {198 return errors.New("Base token is not set")199 } else {200 t.BaseToken = common.HexToAddress(trade["baseToken"].(string))201 }202 if trade["maker"] == nil {203 return errors.New("Maker is not set")204 } else {205 t.Taker = common.HexToAddress(trade["taker"].(string))206 }207 if trade["taker"] == nil {208 return errors.New("Taker is not set")209 } else {210 t.Maker = common.HexToAddress(trade["maker"].(string))211 }212 if trade["id"] != nil && bson.IsObjectIdHex(trade["id"].(string)) {213 t.ID = bson.ObjectIdHex(trade["id"].(string))214 }215 if trade["txHash"] != nil {216 t.TxHash = common.HexToHash(trade["txHash"].(string))217 }218 if trade["pairName"] != nil {219 t.PairName = trade["pairName"].(string)220 }221 if trade["status"] != nil {222 t.Status = trade["status"].(string)223 }224 if trade["pricepoint"] != nil {225 t.PricePoint = math.ToBigInt(fmt.Sprintf("%v", trade["pricepoint"]))226 }227 if trade["amount"] != nil {228 t.Amount = new(big.Int)229 t.Amount.UnmarshalJSON([]byte(fmt.Sprintf("%v", trade["amount"])))230 }231 if trade["makeFee"] != nil {232 t.MakeFee = new(big.Int)233 t.MakeFee.UnmarshalJSON([]byte(fmt.Sprintf("%v", trade["makeFee"])))234 }235 if trade["takeFee"] != nil {236 t.TakeFee = new(big.Int)237 t.TakeFee.UnmarshalJSON([]byte(fmt.Sprintf("%v", trade["takeFee"])))238 }239 if trade["createdAt"] != nil {240 tm, _ := time.Parse(time.RFC3339Nano, trade["createdAt"].(string))241 t.CreatedAt = tm242 }243 if trade["takerOrderSide"] != nil {244 t.TakerOrderSide = trade["takerOrderSide"].(string)245 }246 if trade["takerOrderType"] != nil {247 t.TakerOrderType = trade["takerOrderType"].(string)248 }249 if trade["makerOrderType"] != nil {250 t.TakerOrderType = trade["makerOrderType"].(string)251 }252 if trade["makerExchange"] != nil {253 t.MakerExchange = common.HexToAddress(trade["makerExchange"].(string))254 }255 if trade["takerExchange"] != nil {256 t.TakerExchange = common.HexToAddress(trade["takerExchange"].(string))257 }258 return nil259}260func (t *Trade) QuoteAmount(p *Pair) *big.Int {261 pairMultiplier := p.PairMultiplier()262 return math.Div(math.Mul(t.Amount, t.PricePoint), pairMultiplier)263}264func (t *Trade) GetBSON() (interface{}, error) {265 tr := TradeRecord{266 ID: t.ID,267 PairName: t.PairName,268 Maker: t.Maker.Hex(),269 Taker: t.Taker.Hex(),270 BaseToken: t.BaseToken.Hex(),271 QuoteToken: t.QuoteToken.Hex(),272 MakerOrderHash: t.MakerOrderHash.Hex(),273 Hash: t.Hash.Hex(),274 TxHash: t.TxHash.Hex(),275 TakerOrderHash: t.TakerOrderHash.Hex(),276 CreatedAt: t.CreatedAt,277 UpdatedAt: t.UpdatedAt,278 PricePoint: t.PricePoint.String(),279 Status: t.Status,280 Amount: t.Amount.String(),281 MakeFee: t.MakeFee.String(),282 TakeFee: t.TakeFee.String(),283 TakerOrderSide: t.TakerOrderSide,284 TakerOrderType: t.TakerOrderType,285 MakerOrderType: t.MakerOrderType,286 MakerExchange: t.MakerExchange.Hex(),287 TakerExchange: t.TakerExchange.Hex(),288 }289 return tr, nil290}291func (t *Trade) SetBSON(raw bson.Raw) error {292 decoded := new(struct {293 ID bson.ObjectId `json:"id,omitempty" bson:"_id"`294 PairName string `json:"pairName" bson:"pairName"`295 Taker string `json:"taker" bson:"taker"`296 Maker string `json:"maker" bson:"maker"`297 BaseToken string `json:"baseToken" bson:"baseToken"`298 QuoteToken string `json:"quoteToken" bson:"quoteToken"`299 MakerOrderHash string `json:"makerOrderHash" bson:"makerOrderHash"`300 TakerOrderHash string `json:"takerOrderHash" bson:"takerOrderHash"`301 Hash string `json:"hash" bson:"hash"`302 TxHash string `json:"txHash" bson:"txHash"`303 CreatedAt time.Time `json:"createdAt" bson:"createdAt"`304 UpdatedAt time.Time `json:"updatedAt" bson:"updatedAt"`305 PricePoint string `json:"pricepoint" bson:"pricepoint"`306 Status string `json:"status" bson:"status"`307 Amount string `json:"amount" bson:"amount"`308 MakeFee string `json:"makeFee" bson:"makeFee"`309 TakeFee string `json:"takeFee" bson:"takeFee"`310 TakerOrderSide string `json:"takerOrderSide" bson:"takerOrderSide"`311 TakerOrderType string `json:"takerOrderType" bson:"takerOrderType"`312 MakerOrderType string `json:"makerOrderType" bson:"makerOrderType"`313 MakerExchange string `json:"makerExchange" bson:"makerExchange"`314 TakerExchange string `json:"takerExchange" bson:"takerExchange"`315 })316 err := raw.Unmarshal(decoded)317 if err != nil {318 return err319 }320 t.ID = decoded.ID321 t.PairName = decoded.PairName322 t.Taker = common.HexToAddress(decoded.Taker)323 t.Maker = common.HexToAddress(decoded.Maker)324 t.BaseToken = common.HexToAddress(decoded.BaseToken)325 t.QuoteToken = common.HexToAddress(decoded.QuoteToken)326 t.MakerOrderHash = common.HexToHash(decoded.MakerOrderHash)327 t.TakerOrderHash = common.HexToHash(decoded.TakerOrderHash)328 t.Hash = common.HexToHash(decoded.Hash)329 t.TxHash = common.HexToHash(decoded.TxHash)330 t.Status = decoded.Status331 t.Amount = math.ToBigInt(decoded.Amount)332 t.PricePoint = math.ToBigInt(decoded.PricePoint)333 t.MakeFee = math.ToBigInt(decoded.MakeFee)334 t.TakeFee = math.ToBigInt(decoded.TakeFee)335 t.CreatedAt = decoded.CreatedAt336 t.UpdatedAt = decoded.UpdatedAt337 t.TakerOrderSide = decoded.TakerOrderSide338 t.TakerOrderType = decoded.TakerOrderType339 t.MakerOrderType = decoded.TakerOrderType340 t.MakerExchange = common.HexToAddress(decoded.MakerExchange)341 t.TakerExchange = common.HexToAddress(decoded.TakerExchange)342 return nil343}344// ComputeHash returns hashes the trade345// The OrderHash, Amount, Taker and TradeNonce attributes must be346// set before attempting to compute the trade hash347func (t *Trade) ComputeHash() common.Hash {348 sha := sha3.NewKeccak256()349 sha.Write(t.MakerOrderHash.Bytes())350 sha.Write(t.TakerOrderHash.Bytes())351 return common.BytesToHash(sha.Sum(nil))352}353func (t *Trade) Pair() (*Pair, error) {354 if (t.BaseToken == common.Address{}) {355 return nil, errors.New("Base token is not set")356 }357 if (t.QuoteToken == common.Address{}) {358 return nil, errors.New("Quote token is set")359 }360 return &Pair{361 BaseTokenAddress: t.BaseToken,362 QuoteTokenAddress: t.QuoteToken,363 }, nil364}365type TradeBSONUpdate struct {366 *Trade367}368func (t TradeBSONUpdate) GetBSON() (interface{}, error) {369 now := time.Now()370 set := bson.M{371 "taker": t.Taker.Hex(),372 "maker": t.Maker.Hex(),373 "baseToken": t.BaseToken.Hex(),374 "quoteToken": t.QuoteToken.Hex(),375 "makerOrderHash": t.MakerOrderHash.Hex(),376 "takerOrderHash": t.TakerOrderHash.Hex(),377 "txHash": t.TxHash.Hex(),378 "pairName": t.PairName,379 "status": t.Status,380 }381 if t.PricePoint != nil {382 set["pricepoint"] = t.PricePoint.String()383 }384 if t.Amount != nil {385 set["amount"] = t.Amount.String()386 }387 setOnInsert := bson.M{388 "_id": bson.NewObjectId(),389 "hash": t.Hash.Hex(),390 "createdAt": now,391 }392 update := bson.M{393 "$set": set,394 "$setOnInsert": setOnInsert,395 }396 return update, nil397}398type TradeChangeEvent struct {399 ID interface{} `bson:"_id"`400 OperationType string `bson:"operationType"`401 FullDocument *Trade `bson:"fullDocument,omitempty"`402 Ns evNamespace `bson:"ns"`403 DocumentKey M `bson:"documentKey"`404 UpdateDescription *updateDesc `bson:"updateDescription,omitempty"`405}...
serialize_test.go
Source:serialize_test.go
1package types2import (3 "encoding/hex"4 "encoding/json"5 "testing"6)7func TestSerializeScript(t *testing.T) {8 script := `{9 "code_hash": "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8",10 "hash_type": "type",11 "args": "0xc8328aabcd9b9e8e64fbc566c4385c3bdeb219d7"12 }`13 expectHex := "490000001000000030000000310000009bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce80114000000c8328aabcd9b9e8e64fbc566c4385c3bdeb219d7"14 var s Script15 err := json.Unmarshal([]byte(script), &s)16 if err != nil {17 t.Errorf("fail to unmarshal test script json: %s\n", err)18 return19 }20 got, err := s.Serialize()21 if err != nil {22 t.Errorf("fail to serialize: %s\n", err)23 return24 }25 gotHex := hex.EncodeToString(got)26 if expectHex != gotHex {27 t.Errorf("mismatch result, expect %v, got %v", expectHex, gotHex)28 return29 }30}31func TestSerializeOutPoint(t *testing.T) {32 outpoint := `{33 "tx_hash": "0xe49352ee4984694d88eb3c1493a33d69d61c786dc5b0a32c4b3978d4fad64379",34 "index": "0x6"35 }`36 expectHex := "e49352ee4984694d88eb3c1493a33d69d61c786dc5b0a32c4b3978d4fad6437906000000"37 var o OutPoint38 err := json.Unmarshal([]byte(outpoint), &o)39 if err != nil {40 t.Errorf("fail to unmarshal test outpoint json: %s\n", err)41 return42 }43 got, err := o.Serialize()44 if err != nil {45 t.Errorf("fail to serialize through native: %s\n", err)46 return47 }48 gotHex := hex.EncodeToString(got)49 if gotHex != expectHex {50 t.Errorf("mismatch result, expect %v, got %v", expectHex, gotHex)51 return52 }53}54func TestSerializeCellInput(t *testing.T) {55 input := `{56 "previous_output": {57 "tx_hash": "0xe49352ee4984694d88eb3c1493a33d69d61c786dc5b0a32c4b3978d4fad64379",58 "index": "0x6"59 },60 "since": "0x0"61 }`62 expectHex := "0000000000000000e49352ee4984694d88eb3c1493a33d69d61c786dc5b0a32c4b3978d4fad6437906000000"63 var i CellInput64 err := json.Unmarshal([]byte(input), &i)65 if err != nil {66 t.Errorf("fail to unmarshal test cell input json: %s\n", err)67 return68 }69 got, err := i.Serialize()70 if err != nil {71 t.Errorf("fail to serialize through native: %s\n", err)72 return73 }74 gotHex := hex.EncodeToString(got)75 if gotHex != expectHex {76 t.Errorf("mismatch result, expect %v, got %v", expectHex, gotHex)77 return78 }79}80func TestSerializeCellOutput(t *testing.T) {81 output := `{82 "capacity": "0x666",83 "lock": {84 "code_hash": "0xe49352ee4984694d88eb3c1493a33d69d61c786dc5b0a32c4b3978d4fad64379",85 "hash_type": "type",86 "args": "0x470dcdc5e44064909650113a274b3b36aecb6dc7"87 },88 "type": null89 }`90 expectHex := "61000000100000001800000061000000660600000000000049000000100000003000000031000000e49352ee4984694d88eb3c1493a33d69d61c786dc5b0a32c4b3978d4fad643790114000000470dcdc5e44064909650113a274b3b36aecb6dc7"91 var o CellOutput92 err := json.Unmarshal([]byte(output), &o)93 if err != nil {94 t.Errorf("fail to unmarshal test cell output json: %s\n", err)95 return96 }97 got, err := o.Serialize()98 if err != nil {99 t.Errorf("fail to serialize through native: %s\n", err)100 return101 }102 gotHex := hex.EncodeToString(got)103 if gotHex != expectHex {104 t.Errorf("mismatch result, expect %v, got %v", expectHex, gotHex)105 return106 }107 // Test with type script108 expectHex = "aa000000100000001800000061000000660600000000000049000000100000003000000031000000e49352ee4984694d88eb3c1493a33d69d61c786dc5b0a32c4b3978d4fad643790114000000470dcdc5e44064909650113a274b3b36aecb6dc749000000100000003000000031000000e49352ee4984694d88eb3c1493a33d69d61c786dc5b0a32c4b3978d4fad643790114000000470dcdc5e44064909650113a274b3b36aecb6dc7"109 o.Type = &o.Lock110 got, err = o.Serialize()111 if err != nil {112 t.Errorf("fail to serialize through native: %s\n", err)113 return114 }115 gotHex = hex.EncodeToString(got)116 if gotHex != expectHex {117 t.Errorf("mismatch result, expect %v, got %v", expectHex, gotHex)118 return119 }120}121func TestSerializeCellDep(t *testing.T) {122 dep := `{123 "out_point": {124 "tx_hash": "0xb815a396c5226009670e89ee514850dcde452bca746cdd6b41c104b50e559c70",125 "index": "0x0"126 },127 "dep_type": "dep_group"128 }`129 expectHex := "b815a396c5226009670e89ee514850dcde452bca746cdd6b41c104b50e559c700000000001"130 var d CellDep131 err := json.Unmarshal([]byte(dep), &d)132 if err != nil {133 t.Errorf("fail to unmarshal test cell dep json: %s\n", err)134 return135 }136 got, err := d.Serialize()137 if err != nil {138 t.Errorf("fail to serialize: %s\n", err)139 return140 }141 gotHex := hex.EncodeToString(got)142 if gotHex != expectHex {143 t.Errorf("mismatch result, expect %v, got %v", expectHex, gotHex)144 return145 }146}147func TestSerializeTransaction(t *testing.T) {148 transaction := `{149 "cell_deps": [150 {151 "out_point": {152 "tx_hash": "0xb815a396c5226009670e89ee514850dcde452bca746cdd6b41c104b50e559c70",153 "index": "0x0"154 },155 "dep_type": "dep_group"156 }157 ],158 "header_deps": [],159 "inputs": [160 {161 "previous_output": {162 "tx_hash": "0xee046ce2baeda575266d4164f394c53f66009f64759f7a9f12a014c692e79390",163 "index": "0x6"164 },165 "since": "0x0"166 }167 ],168 "outputs": [169 {170 "capacity": "0x1c6bf52634000",171 "lock": {172 "args": "0x470dcdc5e44064909650113a274b3b36aecb6dc7",173 "code_hash": "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8",174 "hash_type": "type"175 },176 "type": null177 },178 {179 "capacity": "0x1c6bf52634000",180 "lock": {181 "args": "0xc8328aabcd9b9e8e64fbc566c4385c3bdeb219d7",182 "code_hash": "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8",183 "hash_type": "type"184 },185 "type": null186 }187 ],188 "outputs_data": ["0x", "0x"],189 "version": "0x0",190 "witnesses": []191 }`192 expectHex := "5f0100001c00000020000000490000004d0000007d0000004b0100000000000001000000b815a396c5226009670e89ee514850dcde452bca746cdd6b41c104b50e559c70000000000100000000010000000000000000000000ee046ce2baeda575266d4164f394c53f66009f64759f7a9f12a014c692e7939006000000ce0000000c0000006d0000006100000010000000180000006100000000406352bfc60100490000001000000030000000310000009bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce80114000000470dcdc5e44064909650113a274b3b36aecb6dc76100000010000000180000006100000000406352bfc60100490000001000000030000000310000009bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce80114000000c8328aabcd9b9e8e64fbc566c4385c3bdeb219d7140000000c000000100000000000000000000000"193 var tx Transaction194 err := json.Unmarshal([]byte(transaction), &tx)195 if err != nil {196 t.Errorf("fail to unmarshal test transaction json: %s\n", err)197 return198 }199 got, err := tx.Serialize()200 if err != nil {201 t.Errorf("fail to serialize: %s\n", err)202 return203 }204 gotHex := hex.EncodeToString(got)205 if gotHex != expectHex {206 t.Errorf("mismatch result, expect %v, got %v", expectHex, gotHex)207 return208 }209}...
gen_genesis.go
Source:gen_genesis.go
...3 "encoding/json"4 "errors"5 "math/big"6 "github.com/Cryptochain-VON/common"7 "github.com/Cryptochain-VON/common/hexutil"8 "github.com/Cryptochain-VON/common/math"9 "github.com/Cryptochain-VON/params"10)11var _ = (*genesisSpecMarshaling)(nil)12func (g Genesis) MarshalJSON() ([]byte, error) {13 type Genesis struct {14 Config *params.ChainConfig `json:"config"`15 Nonce math.HexOrDecimal64 `json:"nonce"`16 Timestamp math.HexOrDecimal64 `json:"timestamp"`17 ExtraData hexutil.Bytes `json:"extraData"`18 GasLimit math.HexOrDecimal64 `json:"gasLimit" gencodec:"required"`19 Difficulty *math.HexOrDecimal256 `json:"difficulty" gencodec:"required"`20 Mixhash common.Hash `json:"mixHash"`21 Coinbase common.Address `json:"coinbase"`22 Alloc map[common.UnprefixedAddress]GenesisAccount `json:"alloc" gencodec:"required"`23 Number math.HexOrDecimal64 `json:"number"`24 GasUsed math.HexOrDecimal64 `json:"gasUsed"`25 ParentHash common.Hash `json:"parentHash"`26 }27 var enc Genesis28 enc.Config = g.Config29 enc.Nonce = math.HexOrDecimal64(g.Nonce)30 enc.Timestamp = math.HexOrDecimal64(g.Timestamp)31 enc.ExtraData = g.ExtraData32 enc.GasLimit = math.HexOrDecimal64(g.GasLimit)33 enc.Difficulty = (*math.HexOrDecimal256)(g.Difficulty)34 enc.Mixhash = g.Mixhash35 enc.Coinbase = g.Coinbase36 if g.Alloc != nil {37 enc.Alloc = make(map[common.UnprefixedAddress]GenesisAccount, len(g.Alloc))38 for k, v := range g.Alloc {39 enc.Alloc[common.UnprefixedAddress(k)] = v40 }41 }42 enc.Number = math.HexOrDecimal64(g.Number)43 enc.GasUsed = math.HexOrDecimal64(g.GasUsed)44 enc.ParentHash = g.ParentHash45 return json.Marshal(&enc)46}47func (g *Genesis) UnmarshalJSON(input []byte) error {48 type Genesis struct {49 Config *params.ChainConfig `json:"config"`50 Nonce *math.HexOrDecimal64 `json:"nonce"`51 Timestamp *math.HexOrDecimal64 `json:"timestamp"`52 ExtraData *hexutil.Bytes `json:"extraData"`53 GasLimit *math.HexOrDecimal64 `json:"gasLimit" gencodec:"required"`54 Difficulty *math.HexOrDecimal256 `json:"difficulty" gencodec:"required"`55 Mixhash *common.Hash `json:"mixHash"`56 Coinbase *common.Address `json:"coinbase"`57 Alloc map[common.UnprefixedAddress]GenesisAccount `json:"alloc" gencodec:"required"`58 Number *math.HexOrDecimal64 `json:"number"`59 GasUsed *math.HexOrDecimal64 `json:"gasUsed"`60 ParentHash *common.Hash `json:"parentHash"`61 }62 var dec Genesis63 if err := json.Unmarshal(input, &dec); err != nil {64 return err65 }66 if dec.Config != nil {...
hex
Using AI Code Generation
1import (2type Person struct {3}4func main() {5 p1 := Person{"James", "Bond", 20}6 bs, _ := json.Marshal(p1)7 fmt.Println(bs)8 fmt.Printf("%T \n", bs)9 fmt.Println(string(bs))10}11{"First":"James","Last":"Bond","Age":20}12import (13type Person struct {14}15func main() {16 p1 := Person{"James", "Bond", 20}17 bs, _ := json.Marshal(p1)18 fmt.Println(bs)19 fmt.Printf("%T \n", bs)20 fmt.Println(string(bs))21}22{"First":"James","Last":"Bond","Age":20}23import (24type Person struct {25}26func main() {27 p1 := Person{"James", "Bond", 20}28 bs, _ := json.Marshal(p1)29 fmt.Println(bs)30 fmt.Printf("%T \n", bs)31 fmt.Println(string(bs))32}
hex
Using AI Code Generation
1import (2func main() {3 var data = []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)4 var f interface{}5 err := json.Unmarshal(data, &f)6 if err != nil {7 panic(err)8 }9 m := f.(map[string]interface{})10 for k, v := range m {11 switch vv := v.(type) {12 fmt.Println(k, "is string", vv)13 fmt.Println(k, "is int", vv)14 case []interface{}:15 fmt.Println(k, "is an array:")16 for i, u := range vv {17 fmt.Println(i, u)18 }19 fmt.Println(k, "is of a type I don't know how to handle")20 }21 }22}23import (24func main() {25 var data = []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)26 var f interface{}27 err := json.Unmarshal(data, &f)28 if err != nil {29 panic(err)30 }31 m := f.(map[string]interface{})32 for k, v := range m {33 switch vv := v.(type) {34 fmt.Println(k, "is string", vv)35 fmt.Println(k, "is int", vv)36 case []interface{}:37 fmt.Println(k, "is an array:")38 for i, u := range vv {39 fmt.Println(i, u)40 }41 fmt.Println(k, "is of a type I don't know how to handle")42 }43 }44}45import (46func main() {47 var data = []byte(`{"Name":"Wednesday","Age":6,"Parents":["G
hex
Using AI Code Generation
1import (2func main() {3 var data = []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)4 var f interface{}5 err := json.Unmarshal(data, &f)6 if err != nil {7 panic(err)8 }9 m := f.(map[string]interface{})10 fmt.Println(m["Name"])11 fmt.Println(m["Age"])12 for _, v := range m["Parents"].([]interface{}) {13 fmt.Println(v)14 }15}
hex
Using AI Code Generation
1import (2type Person struct {3}4func main() {5 p := Person{6 }7 b, _ := json.Marshal(p)8 fmt.Println(string(b))9}10import (11type Person struct {12}13func main() {14 p := Person{15 }16 b, _ := json.Marshal(p)17 fmt.Println(string(b))18}19import (20type Person struct {21}22func main() {23 p := Person{24 }25 b, _ := json.Marshal(p)26 fmt.Println(string(b))27}28import (29type Person struct {30}31func main() {32 p := Person{33 }34 b, _ := json.Marshal(p)35 fmt.Println(string(b))36}37import (38type Person struct {39}40func main() {41 p := Person{42 }43 b, _ := json.Marshal(p)44 fmt.Println(string(b))45}
hex
Using AI Code Generation
1import (2type Person struct {3}4func main() {5 p1 := Person{"James", 20}6 bs, _ := json.Marshal(p1)7 fmt.Println(bs)8 fmt.Printf("%T9 fmt.Println(string(bs))10}11import (12type Person struct {13}14func main() {15 p1 := Person{"James", 20}16 bs, _ := json.Marshal(p1)17 fmt.Println(bs)18 fmt.Printf("%T19 fmt.Println(string(bs))20 fmt.Println(json.Marshal(p1))21}22import (23type Person struct {24}25func main() {26 p1 := Person{"James", 20}27 bs, _ := json.Marshal(p1)28 fmt.Println(bs)29 fmt.Printf("%T30 fmt.Println(string(bs))31 fmt.Println(json.Marshal(p1))32 fmt.Println(json.MarshalIndent(p1, "", " "))33}34import (35type Person struct {36}37func main() {38 p1 := Person{"James", 20}39 bs, _ := json.Marshal(p1)40 fmt.Println(bs)41 fmt.Printf("%T42 fmt.Println(string(bs))43 fmt.Println(json.Marshal(p1))44 fmt.Println(json.MarshalIndent(p1, "", " "))45 fmt.Println(json.MarshalIndent(p1, "", " "))46 fmt.Println(json.MarshalIndent(p1, "", " "))47}48import (49type Person struct {50}51func main() {52 p1 := Person{"James", 20}53 bs, _ := json.Marshal(p1)54 fmt.Println(bs)55 fmt.Printf("%
hex
Using AI Code Generation
1import (2func main() {3 var data map[string]interface{}4 json.Unmarshal([]byte(`{"Name": "Wednesday", "Age": 6, "Parents": ["Gomez", "Morticia"]}`), &data)5 fmt.Printf("%+v6}7import (8func main() {9 var data map[string]interface{}10 json.Unmarshal([]byte(`{"Name": "Wednesday", "Age": 6, "Parents": ["Gomez", "Morticia"]}`), &data)11 fmt.Printf("%+v12}13import (14func main() {15 var data map[string]interface{}16 json.Unmarshal([]byte(`{"Name": "Wednesday", "Age": 6, "Parents": ["Gomez", "Morticia"]}`), &data)17 fmt.Printf("%+v18}19import (20func main() {21 var data map[string]interface{}22 json.Unmarshal([]byte(`{"Name": "Wednesday", "Age": 6, "Parents": ["Gomez", "Morticia"]}`), &data)23 fmt.Printf("%+v24}25import (26func main() {27 var data map[string]interface{}28 json.Unmarshal([]byte(`{"Name": "Wednesday", "Age": 6, "Parents": ["Gomez", "Morticia"]}`), &data)29 fmt.Printf("%+v30}
hex
Using AI Code Generation
1import (2type Person struct {3}4func main() {5 p := Person{"John", 30}6 b, _ := json.Marshal(p)7 fmt.Println(string(b))8}9import (10type Person struct {11}12func main() {13 p := Person{"John", 30}14 b, _ := json.Marshal(p)15 fmt.Println(string(b))16}17import (18type Person struct {19}20func main() {21 p := Person{"John", 30}22 b, _ := json.Marshal(p)23 fmt.Println(string(b))24}25import (26type Person struct {27}28func main() {29 p := Person{"John", 30}30 b, _ := json.Marshal(p)31 fmt.Println(string(b))32}33import (34type Person struct {35}36func main() {37 p := Person{"John", 30}38 b, _ := json.Marshal(p)39 fmt.Println(string(b))40}41import (42type Person struct {43}44func main() {45 p := Person{"John", 30}46 b, _ := json.Marshal(p)47 fmt.Println(string(b))48}49import (50type Person struct {51}52func main() {53 p := Person{"John", 30
hex
Using AI Code Generation
1import (2func main() {3 var jsonStr = `{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`4 var jsonData map[string]interface{}5 data = []byte(jsonStr)6 err = json.Unmarshal(data, &jsonData)7 if err != nil {8 fmt.Println(err)9 }10 fmt.Println(jsonData)11 fmt.Println(jsonData["Name"])12 fmt.Println(jsonData["Age"])13 fmt.Println(jsonData["Parents"])14 fmt.Println(jsonData["Parents"].([]interface{})[0])15 fmt.Println(jsonData["Parents"].([]interface{})[1])16 jsonData["Parents"] = []string{"Gomez", "Morticia"}17 fmt.Println(jsonData)18 data, err = json.Marshal(jsonData)19 if err != nil {20 fmt.Println(err)21 }22 fmt.Println(string(data))23}24{"Age":7,"Name":"Thursday","Parents":["Gomez","Morticia"]}25import (26type Person struct {27}28func main() {29 var jsonStr = `{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`30 data = []byte(jsonStr)31 err = json.Unmarshal(data, &jsonData)32 if err != nil {33 fmt.Println(err)34 }35 fmt.Println(jsonData)36 fmt.Println(jsonData.Name)37 fmt.Println(jsonData.Age)38 fmt.Println(jsonData.Parents)39 fmt.Println(jsonData.Parents[0])40 fmt.Println(jsonData.Parents[1])41 jsonData.Parents = []string{"Gomez", "Morticia"}42 fmt.Println(jsonData)
hex
Using AI Code Generation
1import (2func main() {3 s = `{"Name":"Gopher","Age":4}`4 fmt.Println(s)5 var m map[string]interface{}6 json.Unmarshal([]byte(s), &m)7 fmt.Println(m)8 fmt.Println(m["Name"])9 fmt.Println(m["Age"])10}11{"Name":"Gopher","Age":4}12import (13func main() {14 s = `{"Name":"Gopher","Age":4}`15 fmt.Println(s)16 var m map[string]interface{}17 json.Unmarshal([]byte(s), &m)18 fmt.Println(m)19 fmt.Println(m["Name"])20 fmt.Println(m["Age"])21}22{"Name":"Gopher","Age":4}23import (24func main() {25 s = `{"Name":"Gopher","Age":4}`26 fmt.Println(s)27 var m map[string]interface{}28 json.Unmarshal([]byte(s), &m)29 fmt.Println(m)30 fmt.Println(m["Name"])31 fmt.Println(m["Age"])32}33{"Name":"Gopher","Age":4}34import (35func main() {36 s = `{"Name":"Gopher","Age":4}`37 fmt.Println(s)38 var m map[string]interface{}39 json.Unmarshal([]byte(s), &m)40 fmt.Println(m)41 fmt.Println(m["Name"])42 fmt.Println(m["Age"])43}44{"Name":"Gopher","Age":4}
hex
Using AI Code Generation
1import (2func main() {3 jsonString := []byte(`{"Name":"Rajat","Age":22,"Address":"Mumbai"}`)4 var data map[string]interface{}5 json.Unmarshal(jsonString, &data)6 fmt.Println(data)7}8import (9type Person struct {10}11func main() {12 jsonString := []byte(`{"Name":"Rajat","Age":22,"Address":"Mumbai"}`)13 json.Unmarshal(jsonString, &person)14 fmt.Println(person)15}16import (17type Person struct {18}19func main() {20 person := Person{21 }22 data, err := json.Marshal(person)23 if err != nil {24 fmt.Println(err)25 }26 fmt.Println(string(data))27}28import (29type Person struct {30}31func main() {32 person := Person{33 }34 data, err := json.MarshalIndent(person, "", " ")35 if err != nil {36 fmt.Println(err)37 }38 fmt.Println(string(data))39}40import (41type Person struct {42}43func main() {44 person := Person{45 }46 data, err := json.MarshalIndent(person, "", " ")47 if err != nil {48 fmt.Println(err)49 }50 fmt.Println(string(data))51}
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!!