github.com/decred/politeia@v1.4.0/politeiawww/cmd/shared/shared.go (about) 1 // Copyright (c) 2017-2020 The Decred developers 2 // Use of this source code is governed by an ISC 3 // license that can be found in the LICENSE file. 4 5 package shared 6 7 import ( 8 "bytes" 9 "encoding/hex" 10 "encoding/json" 11 "errors" 12 "fmt" 13 "os" 14 15 "github.com/decred/politeia/politeiad/api/v1/identity" 16 "github.com/decred/politeia/util" 17 "golang.org/x/crypto/ed25519" 18 "golang.org/x/crypto/sha3" 19 ) 20 21 var ( 22 // Global variables for shared commands 23 cfg *Config 24 client *Client 25 26 // ErrUserIdentityNotFound is emitted when a user identity is 27 // required but the config object does not contain one. 28 ErrUserIdentityNotFound = errors.New("user identity not found; " + 29 "you must either create a new user or update the user key to " + 30 "generate a new identity for the logged in user") 31 ) 32 33 // PrintJSON prints the passed in JSON using the style specified by the global 34 // config variable. 35 func PrintJSON(body interface{}) error { 36 switch { 37 case cfg.Silent: 38 // Keep quiet 39 case cfg.Verbose: 40 // Verbose printing is handled by the http client 41 // since it prints details like the url and response 42 // codes. 43 case cfg.RawJSON: 44 // Print raw JSON with no formatting 45 b, err := json.Marshal(body) 46 if err != nil { 47 return fmt.Errorf("Marshal: %v", err) 48 } 49 fmt.Printf("%v\n", string(b)) 50 default: 51 // Pretty print the body 52 b, err := json.MarshalIndent(body, "", " ") 53 if err != nil { 54 return fmt.Errorf("MarshalIndent: %v", err) 55 } 56 fmt.Fprintf(os.Stdout, "%s\n", b) 57 } 58 59 return nil 60 } 61 62 // DigestSHA3 returns the hex encoded SHA3-256 of a string. 63 func DigestSHA3(s string) string { 64 h := sha3.New256() 65 h.Write([]byte(s)) 66 return hex.EncodeToString(h.Sum(nil)) 67 } 68 69 // NewIdentity generates a new FullIdentity using randomly generated data to 70 // create the public/private key pair. 71 func NewIdentity() (*identity.FullIdentity, error) { 72 b, err := util.Random(32) 73 if err != nil { 74 return nil, err 75 } 76 77 r := bytes.NewReader(b) 78 pub, priv, err := ed25519.GenerateKey(r) 79 if err != nil { 80 return nil, err 81 } 82 83 id := &identity.FullIdentity{} 84 copy(id.Public.Key[:], pub[:]) 85 copy(id.PrivateKey[:], priv[:]) 86 return id, nil 87 } 88 89 // SetConfig sets the global config variable. 90 func SetConfig(config *Config) { 91 cfg = config 92 } 93 94 // SetClient sets the global client variable. 95 func SetClient(c *Client) { 96 client = c 97 }