main.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. // This is a simple Whisper node. It could be used as a stand-alone bootstrap node.
  17. // Also, could be used for different test and diagnostics purposes.
  18. package main
  19. import (
  20. "bufio"
  21. "crypto/ecdsa"
  22. "crypto/sha512"
  23. "encoding/binary"
  24. "encoding/hex"
  25. "flag"
  26. "fmt"
  27. "os"
  28. "strconv"
  29. "strings"
  30. "time"
  31. "github.com/ethereum/go-ethereum/cmd/utils"
  32. "github.com/ethereum/go-ethereum/common"
  33. "github.com/ethereum/go-ethereum/console"
  34. "github.com/ethereum/go-ethereum/crypto"
  35. "github.com/ethereum/go-ethereum/logger"
  36. "github.com/ethereum/go-ethereum/logger/glog"
  37. "github.com/ethereum/go-ethereum/p2p"
  38. "github.com/ethereum/go-ethereum/p2p/discover"
  39. "github.com/ethereum/go-ethereum/p2p/nat"
  40. "github.com/ethereum/go-ethereum/whisper/mailserver"
  41. whisper "github.com/ethereum/go-ethereum/whisper/whisperv5"
  42. "golang.org/x/crypto/pbkdf2"
  43. )
  44. const quitCommand = "~Q"
  45. const symKeyName = "da919ea33001b04dfc630522e33078ec0df11"
  46. // singletons
  47. var (
  48. server *p2p.Server
  49. shh *whisper.Whisper
  50. done chan struct{}
  51. mailServer mailserver.WMailServer
  52. input = bufio.NewReader(os.Stdin)
  53. )
  54. // encryption
  55. var (
  56. symKey []byte
  57. pub *ecdsa.PublicKey
  58. asymKey *ecdsa.PrivateKey
  59. nodeid *ecdsa.PrivateKey
  60. topic whisper.TopicType
  61. filterID string
  62. symPass string
  63. msPassword string
  64. )
  65. // cmd arguments
  66. var (
  67. echoMode = flag.Bool("e", false, "echo mode: prints some arguments for diagnostics")
  68. bootstrapMode = flag.Bool("b", false, "boostrap node: don't actively connect to peers, wait for incoming connections")
  69. forwarderMode = flag.Bool("f", false, "forwarder mode: only forward messages, neither send nor decrypt messages")
  70. mailServerMode = flag.Bool("s", false, "mail server mode: delivers expired messages on demand")
  71. requestMail = flag.Bool("r", false, "request expired messages from the bootstrap server")
  72. asymmetricMode = flag.Bool("a", false, "use asymmetric encryption")
  73. testMode = flag.Bool("t", false, "use of predefined parameters for diagnostics")
  74. generateKey = flag.Bool("k", false, "generate and show the private key")
  75. argVerbosity = flag.Int("verbosity", logger.Warn, "log verbosity level")
  76. argTTL = flag.Uint("ttl", 30, "time-to-live for messages in seconds")
  77. argWorkTime = flag.Uint("work", 5, "work time in seconds")
  78. argPoW = flag.Float64("pow", whisper.MinimumPoW, "PoW for normal messages in float format (e.g. 2.7)")
  79. argServerPoW = flag.Float64("mspow", whisper.MinimumPoW, "PoW requirement for Mail Server request")
  80. argIP = flag.String("ip", "", "IP address and port of this node (e.g. 127.0.0.1:30303)")
  81. argPub = flag.String("pub", "", "public key for asymmetric encryption")
  82. argDBPath = flag.String("dbpath", "", "path to the server's DB directory")
  83. argIDFile = flag.String("idfile", "", "file name with node id (private key)")
  84. argEnode = flag.String("boot", "", "bootstrap node you want to connect to (e.g. enode://e454......08d50@52.176.211.200:16428)")
  85. argTopic = flag.String("topic", "", "topic in hexadecimal format (e.g. 70a4beef)")
  86. )
  87. func main() {
  88. processArgs()
  89. initialize()
  90. run()
  91. }
  92. func processArgs() {
  93. flag.Parse()
  94. if len(*argIDFile) > 0 {
  95. var err error
  96. nodeid, err = crypto.LoadECDSA(*argIDFile)
  97. if err != nil {
  98. utils.Fatalf("Failed to load file [%s]: %s.", *argIDFile, err)
  99. }
  100. }
  101. const enodePrefix = "enode://"
  102. if len(*argEnode) > 0 {
  103. if (*argEnode)[:len(enodePrefix)] != enodePrefix {
  104. *argEnode = enodePrefix + *argEnode
  105. }
  106. }
  107. if len(*argTopic) > 0 {
  108. x, err := hex.DecodeString(*argTopic)
  109. if err != nil {
  110. utils.Fatalf("Failed to parse the topic: %s", err)
  111. }
  112. topic = whisper.BytesToTopic(x)
  113. }
  114. if *asymmetricMode && len(*argPub) > 0 {
  115. pub = crypto.ToECDSAPub(common.FromHex(*argPub))
  116. if !isKeyValid(pub) {
  117. utils.Fatalf("invalid public key")
  118. }
  119. }
  120. if *echoMode {
  121. echo()
  122. }
  123. }
  124. func echo() {
  125. fmt.Printf("ttl = %d \n", *argTTL)
  126. fmt.Printf("workTime = %d \n", *argWorkTime)
  127. fmt.Printf("pow = %f \n", *argPoW)
  128. fmt.Printf("mspow = %f \n", *argServerPoW)
  129. fmt.Printf("ip = %s \n", *argIP)
  130. fmt.Printf("pub = %s \n", common.ToHex(crypto.FromECDSAPub(pub)))
  131. fmt.Printf("idfile = %s \n", *argIDFile)
  132. fmt.Printf("dbpath = %s \n", *argDBPath)
  133. fmt.Printf("boot = %s \n", *argEnode)
  134. }
  135. func initialize() {
  136. glog.SetV(*argVerbosity)
  137. glog.SetToStderr(true)
  138. done = make(chan struct{})
  139. var peers []*discover.Node
  140. var err error
  141. if *generateKey {
  142. key, err := crypto.GenerateKey()
  143. if err != nil {
  144. utils.Fatalf("Failed to generate private key: %s", err)
  145. }
  146. k := hex.EncodeToString(crypto.FromECDSA(key))
  147. fmt.Printf("Random private key: %s \n", k)
  148. os.Exit(0)
  149. }
  150. if *testMode {
  151. symPass = "wwww" // ascii code: 0x77777777
  152. msPassword = "mail server test password"
  153. }
  154. if *bootstrapMode {
  155. if len(*argIP) == 0 {
  156. argIP = scanLineA("Please enter your IP and port (e.g. 127.0.0.1:30348): ")
  157. }
  158. } else {
  159. if len(*argEnode) == 0 {
  160. argEnode = scanLineA("Please enter the peer's enode: ")
  161. }
  162. peer := discover.MustParseNode(*argEnode)
  163. peers = append(peers, peer)
  164. }
  165. if *mailServerMode {
  166. if len(msPassword) == 0 {
  167. msPassword, err = console.Stdin.PromptPassword("Please enter the Mail Server password: ")
  168. if err != nil {
  169. utils.Fatalf("Failed to read Mail Server password: %s", err)
  170. }
  171. }
  172. shh = whisper.New()
  173. shh.RegisterServer(&mailServer)
  174. mailServer.Init(shh, *argDBPath, msPassword, *argServerPoW)
  175. } else {
  176. shh = whisper.New()
  177. }
  178. asymKey = shh.NewIdentity()
  179. if nodeid == nil {
  180. nodeid = shh.NewIdentity()
  181. }
  182. maxPeers := 80
  183. if *bootstrapMode {
  184. maxPeers = 800
  185. }
  186. server = &p2p.Server{
  187. Config: p2p.Config{
  188. PrivateKey: nodeid,
  189. MaxPeers: maxPeers,
  190. Name: common.MakeName("whisper-go", "5.0"),
  191. Protocols: shh.Protocols(),
  192. ListenAddr: *argIP,
  193. NAT: nat.Any(),
  194. BootstrapNodes: peers,
  195. StaticNodes: peers,
  196. TrustedNodes: peers,
  197. },
  198. }
  199. }
  200. func startServer() {
  201. err := server.Start()
  202. if err != nil {
  203. utils.Fatalf("Failed to start Whisper peer: %s.", err)
  204. }
  205. fmt.Printf("my public key: %s \n", common.ToHex(crypto.FromECDSAPub(&asymKey.PublicKey)))
  206. fmt.Println(server.NodeInfo().Enode)
  207. if *bootstrapMode {
  208. configureNode()
  209. fmt.Println("Bootstrap Whisper node started")
  210. } else {
  211. fmt.Println("Whisper node started")
  212. // first see if we can establish connection, then ask for user input
  213. waitForConnection(true)
  214. configureNode()
  215. }
  216. if !*forwarderMode {
  217. fmt.Printf("Please type the message. To quit type: '%s'\n", quitCommand)
  218. }
  219. }
  220. func isKeyValid(k *ecdsa.PublicKey) bool {
  221. return k.X != nil && k.Y != nil
  222. }
  223. func configureNode() {
  224. var err error
  225. var p2pAccept bool
  226. if *forwarderMode {
  227. return
  228. }
  229. if *asymmetricMode {
  230. if len(*argPub) == 0 {
  231. s := scanLine("Please enter the peer's public key: ")
  232. pub = crypto.ToECDSAPub(common.FromHex(s))
  233. if !isKeyValid(pub) {
  234. utils.Fatalf("Error: invalid public key")
  235. }
  236. }
  237. }
  238. if *requestMail {
  239. p2pAccept = true
  240. if len(msPassword) == 0 {
  241. msPassword, err = console.Stdin.PromptPassword("Please enter the Mail Server password: ")
  242. if err != nil {
  243. utils.Fatalf("Failed to read Mail Server password: %s", err)
  244. }
  245. }
  246. }
  247. if !*asymmetricMode && !*forwarderMode {
  248. if len(symPass) == 0 {
  249. symPass, err = console.Stdin.PromptPassword("Please enter the password: ")
  250. if err != nil {
  251. utils.Fatalf("Failed to read passphrase: %v", err)
  252. }
  253. }
  254. shh.AddSymKey(symKeyName, []byte(symPass))
  255. symKey = shh.GetSymKey(symKeyName)
  256. if len(*argTopic) == 0 {
  257. generateTopic([]byte(symPass))
  258. }
  259. }
  260. if *mailServerMode {
  261. if len(*argDBPath) == 0 {
  262. argDBPath = scanLineA("Please enter the path to DB file: ")
  263. }
  264. }
  265. filter := whisper.Filter{
  266. KeySym: symKey,
  267. KeyAsym: asymKey,
  268. Topics: []whisper.TopicType{topic},
  269. AcceptP2P: p2pAccept,
  270. }
  271. filterID, err = shh.Watch(&filter)
  272. if err != nil {
  273. utils.Fatalf("Failed to install filter: %s", err)
  274. }
  275. fmt.Printf("Filter is configured for the topic: %x \n", topic)
  276. }
  277. func generateTopic(password []byte) {
  278. x := pbkdf2.Key(password, password, 8196, 128, sha512.New)
  279. for i := 0; i < len(x); i++ {
  280. topic[i%whisper.TopicLength] ^= x[i]
  281. }
  282. }
  283. func waitForConnection(timeout bool) {
  284. var cnt int
  285. var connected bool
  286. for !connected {
  287. time.Sleep(time.Millisecond * 50)
  288. connected = server.PeerCount() > 0
  289. if timeout {
  290. cnt++
  291. if cnt > 1000 {
  292. utils.Fatalf("Timeout expired, failed to connect")
  293. }
  294. }
  295. }
  296. fmt.Println("Connected to peer.")
  297. }
  298. func run() {
  299. defer mailServer.Close()
  300. startServer()
  301. defer server.Stop()
  302. shh.Start(nil)
  303. defer shh.Stop()
  304. if !*forwarderMode {
  305. go messageLoop()
  306. }
  307. if *requestMail {
  308. requestExpiredMessagesLoop()
  309. } else {
  310. sendLoop()
  311. }
  312. }
  313. func sendLoop() {
  314. for {
  315. s := scanLine("")
  316. if s == quitCommand {
  317. fmt.Println("Quit command received")
  318. close(done)
  319. break
  320. }
  321. sendMsg([]byte(s))
  322. if *asymmetricMode {
  323. // print your own message for convenience,
  324. // because in asymmetric mode it is impossible to decrypt it
  325. timestamp := time.Now().Unix()
  326. from := crypto.PubkeyToAddress(asymKey.PublicKey)
  327. fmt.Printf("\n%d <%x>: %s\n", timestamp, from, s)
  328. }
  329. }
  330. }
  331. func scanLine(prompt string) string {
  332. if len(prompt) > 0 {
  333. fmt.Print(prompt)
  334. }
  335. txt, err := input.ReadString('\n')
  336. if err != nil {
  337. utils.Fatalf("input error: %s", err)
  338. }
  339. txt = strings.TrimRight(txt, "\n\r")
  340. return txt
  341. }
  342. func scanLineA(prompt string) *string {
  343. s := scanLine(prompt)
  344. return &s
  345. }
  346. func scanUint(prompt string) uint32 {
  347. s := scanLine(prompt)
  348. i, err := strconv.Atoi(s)
  349. if err != nil {
  350. utils.Fatalf("Fail to parse the lower time limit: %s", err)
  351. }
  352. return uint32(i)
  353. }
  354. func sendMsg(payload []byte) {
  355. params := whisper.MessageParams{
  356. Src: asymKey,
  357. Dst: pub,
  358. KeySym: symKey,
  359. Payload: payload,
  360. Topic: topic,
  361. TTL: uint32(*argTTL),
  362. PoW: *argPoW,
  363. WorkTime: uint32(*argWorkTime),
  364. }
  365. msg := whisper.NewSentMessage(&params)
  366. envelope, err := msg.Wrap(&params)
  367. if err != nil {
  368. fmt.Printf("failed to seal message: %v \n", err)
  369. return
  370. }
  371. err = shh.Send(envelope)
  372. if err != nil {
  373. fmt.Printf("failed to send message: %v \n", err)
  374. }
  375. }
  376. func messageLoop() {
  377. f := shh.GetFilter(filterID)
  378. if f == nil {
  379. utils.Fatalf("filter is not installed")
  380. }
  381. ticker := time.NewTicker(time.Millisecond * 50)
  382. for {
  383. select {
  384. case <-ticker.C:
  385. messages := f.Retrieve()
  386. for _, msg := range messages {
  387. printMessageInfo(msg)
  388. }
  389. case <-done:
  390. return
  391. }
  392. }
  393. }
  394. func printMessageInfo(msg *whisper.ReceivedMessage) {
  395. timestamp := fmt.Sprintf("%d", msg.Sent) // unix timestamp for diagnostics
  396. text := string(msg.Payload)
  397. var address common.Address
  398. if msg.Src != nil {
  399. address = crypto.PubkeyToAddress(*msg.Src)
  400. }
  401. if whisper.IsPubKeyEqual(msg.Src, &asymKey.PublicKey) {
  402. fmt.Printf("\n%s <%x>: %s\n", timestamp, address, text) // message from myself
  403. } else {
  404. fmt.Printf("\n%s [%x]: %s\n", timestamp, address, text) // message from a peer
  405. }
  406. }
  407. func requestExpiredMessagesLoop() {
  408. var key, peerID []byte
  409. var timeLow, timeUpp uint32
  410. var t string
  411. var xt, empty whisper.TopicType
  412. err := shh.AddSymKey(mailserver.MailServerKeyName, []byte(msPassword))
  413. if err != nil {
  414. utils.Fatalf("Failed to create symmetric key for mail request: %s", err)
  415. }
  416. key = shh.GetSymKey(mailserver.MailServerKeyName)
  417. peerID = extractIdFromEnode(*argEnode)
  418. shh.MarkPeerTrusted(peerID)
  419. for {
  420. timeLow = scanUint("Please enter the lower limit of the time range (unix timestamp): ")
  421. timeUpp = scanUint("Please enter the upper limit of the time range (unix timestamp): ")
  422. t = scanLine("Please enter the topic (hexadecimal): ")
  423. if len(t) >= whisper.TopicLength*2 {
  424. x, err := hex.DecodeString(t)
  425. if err != nil {
  426. utils.Fatalf("Failed to parse the topic: %s", err)
  427. }
  428. xt = whisper.BytesToTopic(x)
  429. }
  430. if timeUpp == 0 {
  431. timeUpp = 0xFFFFFFFF
  432. }
  433. data := make([]byte, 8+whisper.TopicLength)
  434. binary.BigEndian.PutUint32(data, timeLow)
  435. binary.BigEndian.PutUint32(data[4:], timeUpp)
  436. copy(data[8:], xt[:])
  437. if xt == empty {
  438. data = data[:8]
  439. }
  440. var params whisper.MessageParams
  441. params.PoW = *argServerPoW
  442. params.Payload = data
  443. params.KeySym = key
  444. params.Src = nodeid
  445. params.WorkTime = 5
  446. msg := whisper.NewSentMessage(&params)
  447. env, err := msg.Wrap(&params)
  448. if err != nil {
  449. utils.Fatalf("Wrap failed: %s", err)
  450. }
  451. err = shh.RequestHistoricMessages(peerID, env)
  452. if err != nil {
  453. utils.Fatalf("Failed to send P2P message: %s", err)
  454. }
  455. time.Sleep(time.Second * 5)
  456. }
  457. }
  458. func extractIdFromEnode(s string) []byte {
  459. n, err := discover.ParseNode(s)
  460. if err != nil {
  461. utils.Fatalf("Failed to parse enode: %s", err)
  462. return nil
  463. }
  464. return n.ID[:]
  465. }