electrum.post.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /* Import modules. */
  2. import { sha256 } from '@nexajs/crypto'
  3. import {
  4. binToHex,
  5. hexToBin,
  6. } from '@nexajs/utils'
  7. import BCHJS from '@psf/bch-js'
  8. import { ElectrumCluster } from 'electrum-cash'
  9. /* Initialize BCHJS. */
  10. const bchjs = new BCHJS()
  11. /* Initialize globals. */
  12. let electrum
  13. ;(async () => {
  14. // Initialize an electrum cluster where 2 out of 3 needs to be consistent,
  15. // polled randomly with fail-over (default).
  16. electrum = new ElectrumCluster('Electrum cluster example', '1.4.1', 2, 3)
  17. // Add some servers to the cluster.
  18. electrum.addServer('bch.imaginary.cash')
  19. electrum.addServer('electroncash.de')
  20. electrum.addServer('electroncash.dk')
  21. electrum.addServer('electron.jochen-hoenicke.de', 51002)
  22. electrum.addServer('electrum.imaginary.cash')
  23. // Wait for enough connections to be available.
  24. await electrum.ready()
  25. })()
  26. export default defineEventHandler(async (event) => {
  27. /* Initialize locals. */
  28. let address
  29. let body
  30. let hash160
  31. let method
  32. let params
  33. let response
  34. let script
  35. let scriptHash
  36. /* Set (request) body. */
  37. body = await readBody(event)
  38. // console.log('BODY', body)
  39. if (!body || !body.method || !body.params) {
  40. return `Request FAILED!`
  41. }
  42. /* Set method. */
  43. method = body.method
  44. /* Handle method. */
  45. switch(method) {
  46. case 'blockchain.transaction.get':
  47. /* Handle parameters. */
  48. if (typeof body.params == 'string') {
  49. params = body.params
  50. } else {
  51. params = body.params[0]
  52. }
  53. break
  54. case 'blockchain.scripthash.listunspent':
  55. /* Handle parameters. */
  56. if (typeof body.params == 'string') {
  57. params = body.params
  58. } else {
  59. params = body.params[0]
  60. }
  61. /* Set address. */
  62. address = params
  63. /* Convert to script hash. */
  64. hash160 = bchjs.Address.toHash160(params)
  65. console.log('HASH160', hash160)
  66. /* Set script. */
  67. // FIXME Use `OP` and TypedArray.
  68. script = `76a914${hash160}88ac`
  69. // console.log('SCRIPT', script)
  70. /* Conver to hex. */
  71. script = hexToBin(script)
  72. /* Generate script hash. */
  73. scriptHash = sha256(script)
  74. scriptHash = scriptHash.reverse()
  75. /* Set params. */
  76. params = binToHex(scriptHash)
  77. break
  78. default:
  79. setResponseStatus(event, 401)
  80. return 'Oops! Invalid request!'
  81. }
  82. // Request the full transaction hex for the transaction ID.
  83. response = await electrum.request(body.method, params)
  84. // console.log('RESPONSE', response)
  85. return response
  86. })