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