|
| 1 | +package gh |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/ed25519" |
| 5 | + "encoding/hex" |
| 6 | + "std" |
| 7 | + |
| 8 | + "gno.land/p/demo/avl" |
| 9 | +) |
| 10 | + |
| 11 | +var ( |
| 12 | + addressToAccount avl.Tree // address -> Account |
| 13 | + guardianPublicKey string // guardian public (maybe should an array) |
| 14 | +) |
| 15 | + |
| 16 | +func init() { |
| 17 | + addressToAccount = avl.Tree{} |
| 18 | + setAdminAddress(std.GetOrigCaller()) |
| 19 | +} |
| 20 | + |
| 21 | +// Todo maybe we should gave multi guardian |
| 22 | +func SetGuardianPublicKey(publicKey string) { |
| 23 | + assertIsAdmin() |
| 24 | + guardianPublicKey = publicKey |
| 25 | +} |
| 26 | + |
| 27 | +func LinkAccount(accountID string, address std.Address, signature string) { |
| 28 | + if !verifySignature(accountID, address, signature) { |
| 29 | + panic("signature verification failed") |
| 30 | + } |
| 31 | + |
| 32 | + account := AccountByID(accountID) |
| 33 | + if account == nil { |
| 34 | + panic("account not found") |
| 35 | + } |
| 36 | + |
| 37 | + addressToAccount.Set(address.String(), account) |
| 38 | +} |
| 39 | + |
| 40 | +func RenderAccount(address std.Address) string { |
| 41 | + account, ok := addressToAccount.Get(address.String()) |
| 42 | + if !ok { |
| 43 | + panic("account not found") |
| 44 | + } |
| 45 | + |
| 46 | + return account.(*Account).Render() |
| 47 | +} |
| 48 | + |
| 49 | +func Render(address string) string { |
| 50 | + if address != "" { |
| 51 | + return RenderAccount(std.Address(address)) |
| 52 | + } |
| 53 | + str := "[" |
| 54 | + addressToAccount.Iterate("", "", func(key string, value interface{}) bool { |
| 55 | + account := value.(*Account) |
| 56 | + str += account.Render() |
| 57 | + str += "," |
| 58 | + return false |
| 59 | + }) |
| 60 | + str += "]" |
| 61 | + |
| 62 | + return str |
| 63 | +} |
| 64 | + |
| 65 | +func verifySignature(accountID string, address std.Address, signature string) bool { |
| 66 | + publicKey, err := hex.DecodeString(guardianPublicKey) |
| 67 | + if err != nil { |
| 68 | + panic("invalid guardian public key") |
| 69 | + } |
| 70 | + |
| 71 | + sign, err := hex.DecodeString(signature) |
| 72 | + if err != nil { |
| 73 | + panic("invalid signature") |
| 74 | + } |
| 75 | + return ed25519.Verify(publicKey, []byte(accountID+" "+address.String()), sign) |
| 76 | +} |
0 commit comments