Skip to content

Instantly share code, notes, and snippets.

@m1noon
Created November 1, 2018 07:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m1noon/bd59a741ca1cd553654c688249ff7250 to your computer and use it in GitHub Desktop.
Save m1noon/bd59a741ca1cd553654c688249ff7250 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
)
func main() {
// method id. this is byte array [33 26 23 197]
id := getMethodID("someTransactionMethod()");
fmt.Println("id: ", id)
fmt.Println("--- Cast String ---")
// cast string
str := string(id)
strAfter := throughJSON(str)
check("str", str, strAfter)
strDecoded := []byte(strAfter)
fmt.Println("[Result]str decoded: ", strDecoded)
fmt.Println("--- Hex ---")
// hex
hex := hexutil.Encode(id)
hexAfter := throughJSON(hex)
hexDecoded, _ := hexutil.Decode(hexAfter)
check("hex", hex, hexAfter)
fmt.Println("[Result]hex decoded: ", hexDecoded)
}
func getMethodID(sig string) []byte {
// method string signature -> byte array -> keccak hash
sigByte := []byte(sig)
sigHash := crypto.Keccak256(sigByte)
// hash -> id (getting head 4 bytes from hash)
id := sigHash[:4]
return id
}
func throughJSON(text string) string {
// marshal to json byte
j, _ := json.Marshal(map[string]interface{}{
"text": text,
})
// unmarshal to json byte and return unmarshaled value
m := map[string]interface{}{}
json.Unmarshal(j, &m)
return m["text"].(string)
}
func check(label, before, after string) {
fmt.Printf("[Check] '%s' : same='%v', before='%v', after='%v'\n", label, before == after, before, after)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment