github.com/BlockABC/godash@v0.0.0-20191112120524-f4aa3a32c566/blockchain/notifications.go (about) 1 // Copyright (c) 2013-2016 The btcsuite developers 2 // Copyright (c) 2016 The Dash developers 3 // Use of this source code is governed by an ISC 4 // license that can be found in the LICENSE file. 5 6 package blockchain 7 8 import ( 9 "fmt" 10 ) 11 12 // NotificationType represents the type of a notification message. 13 type NotificationType int 14 15 // NotificationCallback is used for a caller to provide a callback for 16 // notifications about various chain events. 17 type NotificationCallback func(*Notification) 18 19 // Constants for the type of a notification message. 20 const ( 21 // NTBlockAccepted indicates the associated block was accepted into 22 // the block chain. Note that this does not necessarily mean it was 23 // added to the main chain. For that, use NTBlockConnected. 24 NTBlockAccepted NotificationType = iota 25 26 // NTBlockConnected indicates the associated block was connected to the 27 // main chain. 28 NTBlockConnected 29 30 // NTBlockDisconnected indicates the associated block was disconnected 31 // from the main chain. 32 NTBlockDisconnected 33 ) 34 35 // notificationTypeStrings is a map of notification types back to their constant 36 // names for pretty printing. 37 var notificationTypeStrings = map[NotificationType]string{ 38 NTBlockAccepted: "NTBlockAccepted", 39 NTBlockConnected: "NTBlockConnected", 40 NTBlockDisconnected: "NTBlockDisconnected", 41 } 42 43 // String returns the NotificationType in human-readable form. 44 func (n NotificationType) String() string { 45 if s, ok := notificationTypeStrings[n]; ok { 46 return s 47 } 48 return fmt.Sprintf("Unknown Notification Type (%d)", int(n)) 49 } 50 51 // Notification defines notification that is sent to the caller via the callback 52 // function provided during the call to New and consists of a notification type 53 // as well as associated data that depends on the type as follows: 54 // - NTBlockAccepted: *godashutil.Block 55 // - NTBlockConnected: *godashutil.Block 56 // - NTBlockDisconnected: *godashutil.Block 57 type Notification struct { 58 Type NotificationType 59 Data interface{} 60 } 61 62 // sendNotification sends a notification with the passed type and data if the 63 // caller requested notifications by providing a callback function in the call 64 // to New. 65 func (b *BlockChain) sendNotification(typ NotificationType, data interface{}) { 66 // Ignore it if the caller didn't request notifications. 67 if b.notifications == nil { 68 return 69 } 70 71 // Generate and send the notification. 72 n := Notification{Type: typ, Data: data} 73 b.notifications(&n) 74 }