|
| 1 | +package message |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "time" |
| 7 | + |
| 8 | + "github.com/libp2p/go-libp2p/core/crypto" |
| 9 | + "github.com/libp2p/go-libp2p/core/peer" |
| 10 | +) |
| 11 | + |
| 12 | +const Version = "1" |
| 13 | + |
| 14 | +type Message struct { |
| 15 | + From string `json:"from"` |
| 16 | + To string `json:"to"` |
| 17 | + Version string `json:"version"` |
| 18 | + Data []byte `json:"data"` |
| 19 | + Created time.Time `json:"created"` |
| 20 | + Received time.Time `json:"received"` |
| 21 | + Signature []byte `json:"signature"` |
| 22 | +} |
| 23 | + |
| 24 | +func New(from string, to string, data []byte) *Message { |
| 25 | + return &Message{ |
| 26 | + From: from, |
| 27 | + To: to, |
| 28 | + Version: Version, |
| 29 | + Created: time.Now(), |
| 30 | + Data: data, |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +func Marshal(m *Message) ([]byte, error) { |
| 35 | + return json.Marshal(m) |
| 36 | +} |
| 37 | + |
| 38 | +func (m *Message) UnsignedMessage() *Message { |
| 39 | + |
| 40 | + // This returns |
| 41 | + c := &Message{ |
| 42 | + To: m.To, |
| 43 | + From: m.From, |
| 44 | + Data: m.Data, |
| 45 | + Created: m.Created, |
| 46 | + Version: m.Version, |
| 47 | + } |
| 48 | + |
| 49 | + return c |
| 50 | +} |
| 51 | + |
| 52 | +func Unmarshal(data []byte) (*Message, error) { |
| 53 | + var msg Message |
| 54 | + if err := json.Unmarshal(data, &msg); err != nil { |
| 55 | + return nil, err |
| 56 | + } |
| 57 | + return &msg, nil |
| 58 | +} |
| 59 | + |
| 60 | +func (m *Message) Sign(privateKey crypto.PrivKey) error { |
| 61 | + data, err := Marshal(m.UnsignedMessage()) |
| 62 | + if err != nil { |
| 63 | + return fmt.Errorf("failed to marshal message: %v", err) |
| 64 | + } |
| 65 | + |
| 66 | + sig, err := privateKey.Sign(data) |
| 67 | + if err != nil { |
| 68 | + return fmt.Errorf("failed to sign message: %v", err) |
| 69 | + } |
| 70 | + m.Signature = sig |
| 71 | + return nil |
| 72 | +} |
| 73 | + |
| 74 | +func (m *Message) Verify() (bool, error) { |
| 75 | + publicKey, err := extractPublicKeyFromIPNS(m.From) |
| 76 | + if err != nil { |
| 77 | + return false, err |
| 78 | + } |
| 79 | + |
| 80 | + data, err := Marshal(m.UnsignedMessage()) |
| 81 | + if err != nil { |
| 82 | + return false, fmt.Errorf("failed to marshal message: %v", err) |
| 83 | + } |
| 84 | + |
| 85 | + isValid, err := publicKey.Verify(data, m.Signature) |
| 86 | + if err != nil { |
| 87 | + return false, fmt.Errorf("error verifying message: %v", err) |
| 88 | + } |
| 89 | + |
| 90 | + return isValid, nil |
| 91 | +} |
| 92 | + |
| 93 | +func extractPublicKeyFromIPNS(ipns string) (crypto.PubKey, error) { |
| 94 | + pid, err := peer.Decode(ipns) |
| 95 | + if err != nil { |
| 96 | + return nil, err |
| 97 | + } |
| 98 | + |
| 99 | + return pid.ExtractPublicKey() |
| 100 | +} |
0 commit comments