github.com/piotrnar/gocoin@v0.0.0-20240512203912-faa0448c5e96/lib/others/sys/stuff.go (about) 1 package sys 2 3 import ( 4 "os" 5 "runtime" 6 "io/ioutil" 7 "crypto/rand" 8 "encoding/hex" 9 "runtime/debug" 10 ) 11 12 13 14 15 func BitcoinHome() (res string) { 16 res = os.Getenv("APPDATA") 17 if res!="" { 18 res += "\\Bitcoin\\" 19 return 20 } 21 res = os.Getenv("HOME") 22 if res!="" { 23 res += "/.bitcoin/" 24 } 25 return 26 } 27 28 29 func is_hex_string(s []byte) (string) { 30 var res string 31 for i := range s { 32 c := byte(s[i]) 33 if c<='9' && c>='0' || c<='f' && c>='a' || c<='F' && c>='A' { 34 res += string(c) 35 } else if c!=' ' && c!='\n' && c!='\r' && c!='\t' { 36 return "" 37 } 38 } 39 return res 40 } 41 42 // reads tx from the file or (if there is no such a file) decodes the text 43 func GetRawData(fn string) (dat []byte) { 44 d, er := ioutil.ReadFile(fn) 45 if er == nil { 46 hexdump := is_hex_string(d) 47 if len(hexdump)>=2 || (len(hexdump)&1)==1 { 48 dat, _ = hex.DecodeString(hexdump) 49 } else { 50 dat = d 51 } 52 } else { 53 dat, _ = hex.DecodeString(fn) 54 } 55 return 56 } 57 58 59 func ClearBuffer(buf []byte) { 60 rand.Read(buf[:]) 61 } 62 63 64 var secrespass func([]byte) int 65 66 func getline(buf []byte) (n int) { 67 n, er := os.Stdin.Read(buf[:]) 68 if er != nil { 69 ClearBuffer(buf) 70 return -1 71 } 72 for n>0 && buf[n-1]<' ' { 73 n-- 74 buf[n] = 0 75 } 76 return n 77 } 78 79 // ReadPassword reads a password from console. 80 // Returns -1 on error. 81 func ReadPassword(buf []byte) (n int) { 82 if secrespass != nil { 83 return secrespass(buf) 84 } 85 return getline(buf) 86 } 87 88 // MemUsed returns Alloc and Sys (how much memory is used). 89 func MemUsed() (uint64, uint64) { 90 var ms runtime.MemStats 91 runtime.ReadMemStats(&ms) 92 return ms.Alloc, ms.Sys 93 } 94 95 // FreeMem runs the GC and frees as much memory as possible. 96 func FreeMem() { 97 runtime.GC() 98 debug.FreeOSMemory() 99 }