아래는 BitcoinSV의 실시간 event를 받을수 있는 bitsocket의 example이다.
Node.js로 작성했으며, 다음과 같은 패키지를 npm으로 설치해야 한다.
>npm i -S btoa
>npm i -S eventsource
var btoa = require('btoa')
var EventSource = require('eventsource')
// Write a bitquery
var query = {
"v": 3, "q": { "find": {} }
}
// Encode it in base64 format
var b64 = btoa(JSON.stringify(query))
// Subscribe
var bitsocket = new EventSource('https://genesis.bitdb.network/s/1FnauZ9aUH2Bex6JzdcV4eNX7oLSSEbxtN/'+b64)
// Event handler
bitsocket.onmessage = function(e) {
console.log(e.data)
}
//호출결과는 다음과 같으며 실시간으로 계속 메세지가 추가된다.
{"type":"open","data":[]}
{
"type": "u",
"data": [{
"tx": {
"h": "0c07b01307b14e3935bcdbaf50770c0e4a4e23aeb9c09c49550e09a5ad570652"
},
"in": [{
"i": 0,
"b0": "MEUCIQD6VwsndQUrrpmFCJPlxuAF1fUmZcPAx5UgC803Som2cQIgZuwlNDM3Puu/3wqqzTd5cFbUO8fEX4Q5Y9jCBdKMoDtB",
"b1": "A8ydsZIv8Hew5jLQLoKpxqunqCx2xT18H1aKd3XIlURe",
"str": "3045022100fa570b2775052bae99850893e5c6e005d5f52665c3c0c795200bcd374a89b671022066ec253433373eebbfdf0aaacd37797056d43bc7c45f843963d8c205d28ca03b41 03cc9db1922ff077b0e632d02e82a9c6aba7a82c76c53d7c1f568a7775c895445e",
"e": {
"h": "07225863412d4d037cb5514ccf94a29583691367218f28eced772c0ef1e9a866",
"i": 1,
"a": "1EomR6yvfRUCUeR9RdiLE8AUkveW6wA2uz"
},
"h0": "3045022100fa570b2775052bae99850893e5c6e005d5f52665c3c0c795200bcd374a89b671022066ec253433373eebbfdf0aaacd37797056d43bc7c45f843963d8c205d28ca03b41",
"h1": "03cc9db1922ff077b0e632d02e82a9c6aba7a82c76c53d7c1f568a7775c895445e"
}],
"out": [{
"i": 0,
"b0": {
"op": 118
},
"b1": {
"op": 169
},
"b2": "4QBR3rSIWSQI33JyQGzqWd/mEcY=",
"s2": "�\u0000Q�Y$\b�rr@l�Y��\u0011�",
"b3": {
"op": 136
},
"b4": {
"op": 172
},
"e": {
"v": 1000,
"i": 0,
"a": "1MWhRPAtAdXFSTgZrkrRuDy5xsofz63nHD"
},
"h2": "e10051deb488592408df7272406cea59dfe611c6"
}, {
"i": 1,
"b0": {
"op": 118
},
"b1": {
"op": 169
},
"b2": "l3HYfq/xcSUVBLXAClhqHDwqGj4=",
"s2": "�q�~��q%\u0015\u0004��\nXj\u001c<*\u001a>",
"b3": {
"op": 136
},
"b4": {
"op": 172
},
"e": {
"v": 6695136,
"i": 1,
"a": "1EomR6yvfRUCUeR9RdiLE8AUkveW6wA2uz"
},
"h2": "9771d87eaff171251504b5c00a586a1c3c2a1a3e"
}],
"_id": "5cbe972233dedb166dc469c8"
}]
}
Tuesday, September 3, 2019
Node.js SSE example
Node.js로 작성한 SSE(Server Sent Event) 예제이다.
//서버
const express = require('express')
const serveStatic = require('serve-static')
const SseStream = require('ssestream')
const app = express()
app.use(serveStatic(__dirname))
app.get('/sse', (req, res) => {
console.log('new connection')
const sseStream = new SseStream(req)
sseStream.pipe(res)
const pusher = setInterval(() => {
sseStream.write({
data: new Date().toTimeString()
})
}, 1000)
res.on('close', () => {
console.log('lost connection')
clearInterval(pusher)
sseStream.unpipe(res)
})
})
app.listen(8080, (err) => {
if (err) throw err
console.log('server ready on http://localhost:8080')
})
//클라이언트
var EventSource = require('eventsource')
var es = new EventSource('http://localhost:8080/sse')
es.onmessage = e => {
console.log(e.data)
}
//서버
const express = require('express')
const serveStatic = require('serve-static')
const SseStream = require('ssestream')
const app = express()
app.use(serveStatic(__dirname))
app.get('/sse', (req, res) => {
console.log('new connection')
const sseStream = new SseStream(req)
sseStream.pipe(res)
const pusher = setInterval(() => {
sseStream.write({
data: new Date().toTimeString()
})
}, 1000)
res.on('close', () => {
console.log('lost connection')
clearInterval(pusher)
sseStream.unpipe(res)
})
})
app.listen(8080, (err) => {
if (err) throw err
console.log('server ready on http://localhost:8080')
})
//클라이언트
var EventSource = require('eventsource')
var es = new EventSource('http://localhost:8080/sse')
es.onmessage = e => {
console.log(e.data)
}
Wednesday, August 28, 2019
BitcoinSV generate new address javascript
BitcoinSV는 기존의 Bitcoin Core의 라이브러리인 bitcoinjs-lib(https://github.com/bitcoinjs/bitcoinjs-lib)를 사용할수도 있지만, MoneyButton에서 제공한 bsv(https://github.com/moneybutton/bsv)가 현재로서는 최선의 선택이다.
다음과 같이 bsv라이브러리를 설치하자.
> npm i -S bsv
그리고 다음과 같이 network에 맞는 코드를 사용해서 address를 생성하자.
### testnet address 생성
const bsv = require('bsv')const privateKey = bsv.PrivateKey.fromRandom('testnet')
// WIF는 저장해야할 private key의 string이다.
// 콘솔에 출력되는 값을 복사하여 보관하면 된다.
console.log(privateKey.toWIF())
// 마찬가지로 address 문자열을 복사하여 보관하자.
const address = bsv.Address.fromPrivateKey(privateKey, 'testnet')
console.log(address.toString())
### mainnet address 생성
const bsv = require('bsv')const privateKey = bsv.PrivateKey.fromRandom()
// WIF는 저장해야할 private key의 string이다.
// 콘솔에 출력되는 값을 복사하여 보관하면 된다.
console.log(privateKey.toWIF())
// 마찬가지로 address 문자열을 복사하여 보관하자.
const address = bsv.Address.fromPrivateKey(privateKey)
console.log(address.toString())
testnet과 mainnet의 차이는 단순히 fromRandom, fromPrivateKey를 호출할 때 'testnet'이라는 문자열을 추가적으로 전달함으로서 가능하다.
mainnet은 private key가 K, L로 시작되고 testnet은 c로 시작되는 점이 차이점이다.
다음과 같이 bsv라이브러리를 설치하자.
> npm i -S bsv
그리고 다음과 같이 network에 맞는 코드를 사용해서 address를 생성하자.
### testnet address 생성
const bsv = require('bsv')const privateKey = bsv.PrivateKey.fromRandom('testnet')
// WIF는 저장해야할 private key의 string이다.
// 콘솔에 출력되는 값을 복사하여 보관하면 된다.
console.log(privateKey.toWIF())
// 마찬가지로 address 문자열을 복사하여 보관하자.
const address = bsv.Address.fromPrivateKey(privateKey, 'testnet')
console.log(address.toString())
### mainnet address 생성
const bsv = require('bsv')const privateKey = bsv.PrivateKey.fromRandom()
// WIF는 저장해야할 private key의 string이다.
// 콘솔에 출력되는 값을 복사하여 보관하면 된다.
console.log(privateKey.toWIF())
// 마찬가지로 address 문자열을 복사하여 보관하자.
const address = bsv.Address.fromPrivateKey(privateKey)
console.log(address.toString())
testnet과 mainnet의 차이는 단순히 fromRandom, fromPrivateKey를 호출할 때 'testnet'이라는 문자열을 추가적으로 전달함으로서 가능하다.
mainnet은 private key가 K, L로 시작되고 testnet은 c로 시작되는 점이 차이점이다.
Wednesday, August 21, 2019
Node.js destructing typescript
아래와 같이 req.body의 userId, contentId, amount를 destructing을 할때 javascript에서는 다음과 같이 했었다.
const { userId, contentId, amount} = req.body
그러나 우리는 typescript를 사용할 것이므로 userId 등에 각각 정확한 타입을 기입하고 싶을 때는 아래와 같이 하면된다.
const {
userId, contentId, amount
}: {
userId: string, contentId: string, amount: number
} = req.body
userId: string, contentId: string, amount: number
} = req.body
Node.js check top level module environment require.main
Python의 아래와 같이 Node.js의 node에서 바로 실행되는 함수 여부임을 알수 있게 해주는 것이 있다.
if __name__ == "__main__":
다음과 같이 하면 된다.
if (require.main === module) {
}
if __name__ == "__main__":
다음과 같이 하면 된다.
if (require.main === module) {
}
Subscribe to:
Posts (Atom)