holepunch-hop 0.2.8 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "holepunch-hop",
3
- "version": "0.2.8",
3
+ "version": "0.3.0",
4
4
  "description": "data interface to HOP",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
@@ -49,6 +49,29 @@ class SqliteAdapter extends EventEmitter {
49
49
  return newSqlite
50
50
  }
51
51
 
52
+ /**
53
+ * setup sqlite db and get tables and columns
54
+ * @method discoverColumns
55
+ *
56
+ */
57
+ discoverColumns = async function (table) {
58
+ // columns in table
59
+ let header = []
60
+ const res = await new Promise((resolve, reject) => {
61
+ let sqlTableCols = `PRAGMA table_info('` + table + `')`
62
+ this.dataBase.all(sqlTableCols, [], (err, rows) => {
63
+ if (err) {
64
+ reject(err)
65
+ }
66
+ rows.forEach((row) => {
67
+ header.push(row)
68
+ })
69
+ resolve(header)
70
+ })
71
+ })
72
+ return res
73
+ }
74
+
52
75
  /**
53
76
  * setup sqlite db and get tables and columns
54
77
  * @method createDbConnection
@@ -88,28 +111,6 @@ class SqliteAdapter extends EventEmitter {
88
111
  return res
89
112
  }
90
113
 
91
- /**
92
- * setup sqlite db and get tables and columns
93
- * @method discoverColumns
94
- *
95
- */
96
- discoverColumns = async function (table) {
97
- // columns in table
98
- let header = []
99
- const res = await new Promise((resolve, reject) => {
100
- let sqlTableCols = `PRAGMA table_info('` + table + `')`
101
- this.dataBase.all(sqlTableCols, [], (err, rows) => {
102
- if (err) {
103
- reject(err)
104
- }
105
- rows.forEach((row) => {
106
- header.push(row)
107
- })
108
- resolve(header)
109
- })
110
- })
111
- return res
112
- }
113
114
 
114
115
  /**
115
116
  * query a table for data
@@ -117,11 +118,48 @@ class SqliteAdapter extends EventEmitter {
117
118
  *
118
119
  */
119
120
  queryTable = async function (table) {
121
+ console.log('HP--first SQL query')
122
+ console.log(table)
123
+ let tableName = table.context.deviceTable
124
+ // let devicetableName = table.context.devicetablename
125
+ let tableTimestamp = table.context.timestamp // timecolumn
126
+ let deviceColumn = ''
127
+ if (table?.context?.deviceCol) {
128
+ deviceColumn = table?.context?.deviceCol?.name
129
+ } else {
130
+ deviceColumn = ''
131
+ }
132
+ let queryDevice = 0
133
+ if (table.context?.deviceID) {
134
+ queryDevice = table.context?.deviceID
135
+ } else {
136
+ queryDevice = 1 // table?.context?.device?._id
137
+ }
138
+ let queryLimit = true
139
+ let queryLevel = 1400
140
+ let blindTimestart = 0
141
+ let blindTimeend = 0
120
142
  // columns in table
121
143
  let data = []
122
144
  const res = await new Promise((resolve, reject) => {
123
- let sqlQuery = `SELECT * FROM MI_BAND_ACTIVITY_SAMPLE WHERE DEVICE_ID = 3 ORDER BY TIMESTAMP DESC LIMIT 1400` // AND TIMESTAMP BETWEEN 1627677840 AND 1627678380`
124
-
145
+ let sqlQuery = `SELECT * FROM ` + tableName
146
+ // now build filter of query based on input if any
147
+ if (deviceColumn.length > 0) {
148
+ sqlQuery += ` WHERE ` + deviceColumn + ` = ` + queryDevice
149
+ }
150
+ if (tableTimestamp.length > 0) {
151
+ sqlQuery += ` ORDER BY TIMESTAMP DEC` // + tableTimestamp
152
+ }
153
+ if (blindTimestart) {
154
+ sqlQuery += ` AND TIMESTAMP BETWEEN ` + blindTimestart + ` AND ` + blindTimeend
155
+
156
+ }
157
+ // lastly set hard limit on length
158
+ if (queryLimit) {
159
+ sqlQuery += ` LIMIT ` + queryLevel
160
+ }
161
+ console.log('HP------formed ----------')
162
+ console.log(sqlQuery)
125
163
  this.dataBase.all(sqlQuery, [], (err, rows) => {
126
164
  if (err) {
127
165
  reject(err)
@@ -135,12 +173,14 @@ class SqliteAdapter extends EventEmitter {
135
173
  return res
136
174
  }
137
175
 
176
+
138
177
  /**
139
178
  * query device table
140
179
  * @method deviceQuery
141
180
  *
142
181
  */
143
182
  deviceQuery = async function (table) {
183
+ console.log('HOLEP---adtpSQL--query device SQLite ad')
144
184
  let data = []
145
185
  const res = await new Promise((resolve, reject) => {
146
186
  let sqlQuery = `SELECT * FROM ` + table
package/src/bees.js CHANGED
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * @class HypBee
6
6
  * @package HypBee
7
- * @copyright Copyright (c) 2022 James Littlejohn
7
+ * @copyright Copyright (c) 2024 James Littlejohn
8
8
  * @license http://www.gnu.org/licenses/old-licenses/gpl-3.0.html
9
9
  * @version $Id$
10
10
  */
@@ -20,6 +20,7 @@ class HyperBee extends EventEmitter {
20
20
  this.store = store
21
21
  this.swarm = swarm
22
22
  this.liveBees = {}
23
+ this.confirmPubLibList = {}
23
24
  }
24
25
 
25
26
  /**
@@ -45,14 +46,12 @@ class HyperBee extends EventEmitter {
45
46
  valueEncoding: 'json' // same options as above
46
47
  })
47
48
  await this.dbPublicLibrary.ready()
48
- beePubkeys.push({ store: 'pubilclibrary', pubkey: b4a.toString(core.key, 'hex')})
49
- // console.log(this.dbPublicLibrary._feed)
49
+ beePubkeys.push({ store: 'publiclibrary', pubkey: b4a.toString(core.key, 'hex')})
50
50
  // allow other peer access to public library (need to check for DDOS ie over asked)
51
51
  // join a topic
52
52
  const discovery = this.swarm.join(this.dbPublicLibrary.discoveryKey)
53
53
  // Only display the key once the Hyperbee has been announced to the DHT
54
54
  discovery.flushed().then(() => {
55
- // console.log('bee key:', b4a.toString(core.key, 'hex'))
56
55
  })
57
56
 
58
57
 
@@ -113,7 +112,6 @@ class HyperBee extends EventEmitter {
113
112
  *
114
113
  */
115
114
  savePubliclibrary = async function (refContract) {
116
- console.log(refContract)
117
115
  let beeSave = await this.dbPublicLibrary.put(refContract.data.hash, refContract.data.contract)
118
116
  // go query the key are return the info. to ensure data save asplanned.
119
117
  let saveCheck = await this.getPublicLibrary(refContract.data.hash)
@@ -343,6 +341,17 @@ class HyperBee extends EventEmitter {
343
341
  return nodeData
344
342
  }
345
343
 
344
+ /**
345
+ * filter peer library to get compute modules with a key
346
+ * @method getPeerLibComputeModules
347
+ *
348
+ */
349
+ getPeerLibComputeModules = async function () {
350
+ const moduleData = await this.dbPeerLibrary.createHistoryStream({ reverse: true, limit: 10 })
351
+ return moduleData
352
+ }
353
+
354
+
346
355
  /**
347
356
  * get all kbl entries
348
357
  * @method KBLentries
@@ -433,9 +442,9 @@ class HyperBee extends EventEmitter {
433
442
  * @method replicatePubliclibrary
434
443
  *
435
444
  */
436
- replicatePubliclibrary = async function (keylib) {
445
+ replicatePubliclibrary = async function (dataIn) {
437
446
  // create or get the hypercore using the public key supplied as command-line argument
438
- const coreRep = this.store.get({ key: b4a.from(keylib, 'hex') })
447
+ const coreRep = this.store.get({ key: b4a.from(dataIn.data.datastores, 'hex') })
439
448
 
440
449
  // create a hyperbee instance using the hypercore instance
441
450
  const beePlib = new Hyperbee(coreRep, {
@@ -454,23 +463,83 @@ class HyperBee extends EventEmitter {
454
463
 
455
464
  await coreRep.update()
456
465
 
466
+ // if provided with specific boarnxp key then just get the contract, extract module contracts and get those contracts and then inform the peer and save to their public library
467
+ const boardNXPcontract = await beePlib.get(dataIn.data.boardID)
468
+ let unString = JSON.parse(boardNXPcontract.value)
469
+ let moduleContracts = []
470
+ for (let mod of unString.modules) {
471
+ let modC = await beePlib.get(mod)
472
+ moduleContracts.push(modC)
473
+ }
474
+ // next reference contracts, then ref within refs i.e. packaging datatypes
475
+ let referenceContracts = []
476
+ for (let modRef of moduleContracts) {
477
+ let unString = JSON.parse(modRef.value)
478
+ if (unString.style === 'packaging') {
479
+ // get list of datatypes
480
+ for (let ref of unString.info.value.concept.tablestructure) {
481
+ if (ref?.refcontract) {
482
+ let refC = await beePlib.get(ref.refcontract)
483
+ referenceContracts.push(refC)
484
+ }
485
+ }
486
+ } else if (unString.style === 'compute') {
487
+ // console.log('compute TODO')
488
+ // console.log(unString)
489
+ } else if (unString.style === 'visualise') {
490
+ // console.log('visualise TODO')
491
+ // console.log(unString)
492
+ } else if (unString.style === 'question') {
493
+ let questRef = {}
494
+ questRef.key = unString.info.key
495
+ questRef.value = JSON.stringify(unString.info.value)
496
+ referenceContracts.push(questRef)
497
+ }
498
+ }
499
+ // notify and get confirmation to accept and save to public library
500
+ if (moduleContracts.length > 0) {
501
+ // keep hold of data ready to be confirmed
502
+ let holderConfirm = {}
503
+ holderConfirm.boardNXP = [boardNXPcontract]
504
+ holderConfirm.modules = moduleContracts
505
+ holderConfirm.refcontracts = referenceContracts
506
+ this.confirmPubLibList[dataIn.data.datastores] = holderConfirm
507
+ this.emit('publibbeebee-notification', dataIn.data)
508
+ }
509
+ // or
457
510
  // now ask for whole of public library
458
511
  /* read all of repliate connect bee and displays */
459
512
  const chathistoryData = beePlib.createReadStream() // { gt: 'a', lt: 'z' }) // anything >a and <z
460
513
  let chatData = []
461
514
  for await (const { key, value } of chathistoryData) {
462
- chatData.push({ key, value })
515
+ if (key === dataIn.data.boardID) {
516
+ chatData.push({ key, value })
517
+ }
463
518
  }
464
-
465
519
  // now replicate with peer own public library in whole or per nxp
466
- let savePublib = await this.updatePublicLibrary(beePlib)
520
+ /* let savePublib = await this.updatePublicLibrary(beePlib)
467
521
  let repMessage = {}
468
522
  repMessage.type = 'library'
469
523
  repMessage.action = 'replicate-publiclibrary'
470
524
  repMessage.task = 'replicate'
471
525
  repMessage.reftype = 'publiclibrary'
472
526
  repMessage.data = savePublib
473
- return repMessage
527
+ return repMessage */
528
+ }
529
+
530
+
531
+ /**
532
+ * peer confirmed add to public library
533
+ * @method addConfrimPublicLibrary
534
+ *
535
+ */
536
+ addConfrimPublicLibrary = async function (data) {
537
+ // add board nxp
538
+ await this.updatePublicLibrary(this.confirmPubLibList[data.datastores].boardNXP)
539
+ // add modules
540
+ await this.updatePublicLibrary(this.confirmPubLibList[data.datastores].modules)
541
+ // add reference
542
+ await this.updatePublicLibrary(this.confirmPubLibList[data.datastores].refcontracts)
474
543
  }
475
544
 
476
545
  /**
@@ -478,17 +547,10 @@ class HyperBee extends EventEmitter {
478
547
  * @method updatePublicLibrary
479
548
  *
480
549
  */
481
- updatePublicLibrary = async function (updateLib) {
482
- /* read all of repliate connect bee and displays */
483
- const chathistoryData = updateLib.createReadStream() // { gt: 'a', lt: 'z' }) // anything >a and <z
484
- let libData = []
485
- for await (const { key, value } of chathistoryData) {
486
- libData.push({ key, value })
487
- }
488
-
550
+ updatePublicLibrary = async function (libContracts) {
489
551
  // save entries required
490
552
  const batch = this.dbPublicLibrary.batch()
491
- for (const { key, value } of libData) {
553
+ for (const { key, value } of libContracts) {
492
554
  await batch.put(key, JSON.parse(value))
493
555
  }
494
556
  await batch.flush()
@@ -566,10 +628,8 @@ class HyperBee extends EventEmitter {
566
628
  let rs = beeResults.createReadStream() // anything >=a and <=d
567
629
 
568
630
  for await (const { key, value } of rs) {
569
- // console.log(`${key} -> ${value}`)
570
631
  // need a save funnction in here
571
632
  if (key === 'bdb6a7db0b479d9b30406cd24f3cc2f315fd3ba0') {
572
- // console.log(`${key} -> ${value}`)
573
633
  let dataR = {}
574
634
  dataR.hash = key
575
635
  dataR.data = value
package/src/drive.js CHANGED
@@ -300,27 +300,37 @@ class HypDrive extends EventEmitter {
300
300
  *
301
301
  */
302
302
  SQLiteQuery = async function (dataInfo) {
303
+ console.log('HP--DRIVE--sqlite')
303
304
  let timestampCol = ''
304
305
  // is the sqliite database sill accive?
305
306
  // const stream = this.liveDataAPI.DriveFiles.listFilesFolder('sqlite/')
306
307
  let dbFile = await this.hyperdriveLocalfile('sqlite/' + dataInfo.file.file)
307
308
  let queryData = await this.AdapterSqlite.queryTable(dataInfo)
308
- let contextKeys = Object.keys(queryData[0])
309
- timestampCol = contextKeys[dataInfo.context.timestamp]
310
- // now prepare into data and labels
311
- let blindData = {}
312
- let extractCol = []
313
- let extractLabel = []
314
- for (let rowi of queryData) {
315
- extractCol.push(rowi[dataInfo.context.name.name])
316
- // assume data column for now and parse to mills seconds
317
- let testCH1 = chrono.parseDate(rowi[timestampCol])
318
- let parseDate = testCH1 * 1000 // this.testDataExtact(testCH1)
319
- extractLabel.push(parseDate)
309
+ if (queryData.length > 0) {
310
+ let contextKeys = Object.keys(queryData[0])
311
+ timestampCol = contextKeys[dataInfo.context.timestamp]
312
+ // now prepare into data and labels
313
+ let blindData = {}
314
+ let extractCol = []
315
+ let extractLabel = []
316
+ for (let rowi of queryData) {
317
+ extractCol.push(rowi[dataInfo.context.name.name])
318
+ // assume data column for now and parse to mills seconds
319
+ let testCH1 = chrono.parseDate(rowi[timestampCol])
320
+ let parseDate = testCH1 * 1000 // this.testDataExtact(testCH1)
321
+ extractLabel.push(parseDate)
322
+ }
323
+ blindData.data = extractCol
324
+ blindData.label = extractLabel
325
+ return blindData
326
+ } else {
327
+ console.log('no data for that query')
328
+ let blindData = {}
329
+ blindData.data = []
330
+ blindData.label = []
331
+ return blindData
320
332
  }
321
- blindData.data = extractCol
322
- blindData.label = extractLabel
323
- return blindData
333
+
324
334
  }
325
335
 
326
336
 
package/src/fileParser.js CHANGED
@@ -137,6 +137,26 @@ FileParser.prototype.webCSVparse = function (fData) {
137
137
  // this.convertJSON(o, ws, headerInfo, praser, 'web', fileNewName)
138
138
  }
139
139
 
140
+ /**
141
+ * TEMP blind json content
142
+ * @method TEMPwebJSONparse
143
+ *
144
+ */
145
+ FileParser.prototype.TEMPwebJSONparse = function (fjData) {
146
+ console.log(fjData)
147
+ let extractLabel = []
148
+ let extractCol = []
149
+ for (let df of fjData.content) {
150
+ extractLabel.push(df[fjData.context.timestampname])
151
+ extractCol.push(df[fjData.context.name])
152
+ }
153
+ // extract out price and time
154
+ let extractedPair = {}
155
+ extractedPair.label = extractLabel
156
+ extractedPair.data = extractCol
157
+ return extractedPair
158
+ }
159
+
140
160
  /**
141
161
  * TEMP blind csv content files from web
142
162
  * @method TEMPwebCSVparse
package/src/index.js CHANGED
@@ -91,12 +91,27 @@ class HolepunchWorker extends EventEmitter {
91
91
  })
92
92
  // peer connection active
93
93
  this.Peers.on('peer-connect', (data) => {
94
- this.Peers.writeTonetwork(data)
94
+ // if (this.Peers.peerHolder[data].data.boardID !== undefined) {
95
+ // any existing peers
96
+ let holderCheck = Object.keys(this.Peers.peerHolder)
97
+ if (holderCheck.length !== 0) {
98
+ this.Peers.writeToPublicLibrary(data)
99
+ } else {
100
+ this.Peers.writeTonetwork(data)
101
+ }
102
+
95
103
  })
96
104
  // data for beebee
97
105
  this.Peers.on('beebee-data', (data) => {
98
106
  this.emit('peer-topeer', data)
99
107
  })
108
+ // public library notification
109
+ this.Peers.on('publiclibrarynotification', (data) => {
110
+ this.BeeData.replicatePubliclibrary(data)
111
+ })
112
+ this.BeeData.on('publibbeebee-notification', (data) => {
113
+ this.emit('beebee-publib-notification', data)
114
+ })
100
115
  // new warm incoming peer
101
116
  this.Peers.on('connect-warm', (data) => {
102
117
  let peerId = {}
@@ -115,21 +130,33 @@ class HolepunchWorker extends EventEmitter {
115
130
  */
116
131
  networkPath = function (message) {
117
132
  if (message.action === 'share') {
118
- if (message.task === 'peer-join') {
119
- // has the peer joined already?
120
- let peerMatch = false
121
- for (let wpeer of this.warmPeers) {
122
- if (wpeer.publickey = message.data.publickey) {
123
- peerMatch = true
124
- }
133
+ // has the peer joined already?
134
+ let peerMatch = false
135
+ for (let wpeer of this.warmPeers) {
136
+ if (wpeer.publickey = message.data.publickey) {
137
+ peerMatch = true
125
138
  }
139
+ }
140
+
141
+ if (message.task === 'peer-join') {
126
142
  if (peerMatch === true) {
127
- this.Peers.peerAlreadyJoin(message.data)
143
+ this.Peers.peerAlreadyJoinSetData(message.data)
128
144
  this.Peers.writeTonetwork(message.data.publickey)
129
145
  } else {
130
146
  this.warmPeers.push(message.data)
131
147
  this.Peers.peerJoin(message.data)
132
148
  }
149
+ } else if (message.task === 'peer-board') {
150
+ if (peerMatch === true) {
151
+ this.Peers.peerAlreadyJoinSetData(message.data)
152
+ this.Peers.writeToPublicLibrary(message.data.publickey)
153
+ } else {
154
+ this.warmPeers.push(message.data)
155
+ this.Peers.peerJoin(message.data)
156
+ // now set data and write to public library info.
157
+ this.Peers.peerAlreadyJoinSetData(message.data)
158
+ this.Peers.writeToPublicLibrary(message.data.publickey)
159
+ }
133
160
  } else if (message.task === 'peer-write') {
134
161
  this.emit('peer-write', message.data)
135
162
  } else if (message.task === 'topic') {
package/src/peers.js CHANGED
@@ -18,7 +18,6 @@ class NetworkPeers extends EventEmitter {
18
18
 
19
19
  constructor(store, swarm) {
20
20
  super()
21
- console.log('peer manager')
22
21
  this.hello = 'hyperpeers'
23
22
  this.store = store
24
23
  this.swarm = swarm
@@ -60,9 +59,6 @@ class NetworkPeers extends EventEmitter {
60
59
  this.emit('peer-connect', publicKeylive)
61
60
  // process network message
62
61
  conn.on('data', data =>
63
- // console.log('recieve network message:', data.toString()),
64
- // console.log(data.toString()),
65
- // console.log('emit to be verified and acted upon appropriately'),
66
62
  // assess data
67
63
  this.assessData(publicKeylive, data)
68
64
  )
@@ -76,9 +72,7 @@ class NetworkPeers extends EventEmitter {
76
72
  *
77
73
  */
78
74
  assessData = function (peer, data) {
79
- console.log('assess---data receive peer-----------')
80
75
  if (Buffer.isBuffer(data)) {
81
- console.log('1 buffer')
82
76
  try {
83
77
  let dataShareIn = JSON.parse(data.toString())
84
78
  if (dataShareIn.type === 'chart') {
@@ -87,12 +81,13 @@ class NetworkPeers extends EventEmitter {
87
81
  // Need to replicate public library for contracts (repliate hyberbee)
88
82
  // Need to ask for data source e.g. file (replicate hyberdrive)
89
83
  // Lastly put together SafeFlowECS query to produce chart
84
+ } else if (dataShareIn.type === 'public-library') {
85
+ this.emit('publiclibrarynotification', dataShareIn)
90
86
  } else if (dataShareIn.type === 'peer') {
91
- console.log('3 buffer')
92
87
  }
93
88
  console.log(a)
94
89
  } catch (e) {
95
- return console.error('ignore')
90
+ return console.error('ignore err')
96
91
  }
97
92
  }
98
93
  }
@@ -118,6 +113,27 @@ class NetworkPeers extends EventEmitter {
118
113
  }
119
114
  }
120
115
 
116
+ /**
117
+ * write message connect public library
118
+ * @method writeToPublicLibrary
119
+ *
120
+ */
121
+ writeToPublicLibrary = function (publickey) {
122
+ // check this peer has asked for chart data
123
+ let connectTrue = publickey in this.peerConnect
124
+ let libraryTrue = publickey in this.peerHolder
125
+ if (connectTrue === true && libraryTrue === true) {
126
+ let libraryData = this.peerHolder[publickey]
127
+ let dataShare = {}
128
+ dataShare.data = libraryData.data
129
+ dataShare.type = 'public-library'
130
+ this.peerConnect[publickey].write(JSON.stringify(dataShare))
131
+ } else {
132
+ console.log('no board to write ie share with a peer')
133
+ }
134
+ }
135
+
136
+
121
137
 
122
138
  /**
123
139
  * join peer to peer private (server)
@@ -134,10 +150,10 @@ class NetworkPeers extends EventEmitter {
134
150
 
135
151
  /**
136
152
  * already joined but keep track context data
137
- * @method peerAlreadyJoin
153
+ * @method peerAlreadyJoinSetData
138
154
  *
139
155
  */
140
- peerAlreadyJoin = function (peerContext) {
156
+ peerAlreadyJoinSetData = function (peerContext) {
141
157
  this.peerHolder[peerContext.publickey] = peerContext
142
158
  }
143
159