1 package blockchain
2 3 import (
4 "fmt"
5 )
6 7 // NotificationType represents the type of a notification message.
8 type NotificationType int
9 10 // NotificationCallback is used for a caller to provide a callback for notifications about various chain events.
11 type NotificationCallback func(*Notification)
12 13 // Constants for the type of a notification message.
14 const (
15 // NTBlockAccepted indicates the associated block was accepted into the block chain. Note that this does not
16 // necessarily mean it was added to the main chain. For that, use NTBlockConnected.
17 NTBlockAccepted NotificationType = iota
18 // NTBlockConnected indicates the associated block was connected to the main chain.
19 NTBlockConnected
20 // NTBlockDisconnected indicates the associated block was disconnected from the main chain.
21 NTBlockDisconnected
22 )
23 24 // notificationTypeStrings is a map of notification types back to their constant names for pretty printing.
25 var notificationTypeStrings = map[NotificationType]string{
26 NTBlockAccepted: "NTBlockAccepted",
27 NTBlockConnected: "NTBlockConnected",
28 NTBlockDisconnected: "NTBlockDisconnected",
29 }
30 31 // String returns the NotificationType in human-readable form.
32 func (n NotificationType) String() string {
33 if s, ok := notificationTypeStrings[n]; ok {
34 return s
35 }
36 return fmt.Sprintf("Unknown Notification Type (%d)", int(n))
37 }
38 39 // Notification defines notification that is sent to the caller via the callback function provided during the call to
40 // New and consists of a notification type as well as associated data that depends on the type as follows:
41 //
42 // - NTBlockAccepted: *util.Block
43 //
44 // - NTBlockConnected: *util.Block
45 //
46 // - NTBlockDisconnected: *util.Block
47 type Notification struct {
48 Type NotificationType
49 Data interface{}
50 }
51 52 // Subscribe to block chain notifications. Registers a callback to be executed when various events take place. See the
53 // documentation on Notification and NotificationType for details on the types and contents of notifications.
54 func (b *BlockChain) Subscribe(callback NotificationCallback) {
55 b.notificationsLock.Lock()
56 b.notifications = append(b.notifications, callback)
57 b.notificationsLock.Unlock()
58 }
59 60 // sendNotification sends a notification with the passed type and data if the caller requested notifications by
61 // providing a callback function in the call to New.
62 func (b *BlockChain) sendNotification(typ NotificationType, data interface{}) {
63 // Generate and send the notification.
64 n := Notification{Type: typ, Data: data}
65 b.notificationsLock.RLock()
66 for _, callback := range b.notifications {
67 callback(&n)
68 }
69 b.notificationsLock.RUnlock()
70 }
71