(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[104],{3592:function(e){function t(e){var t=Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}t.keys=function(){return[]},t.resolve=t,t.id=3592,e.exports=t},42480:function(){},75992:function(){},78110:function(){},55024:function(){},24754:function(e,t,r){"use strict";r.d(t,{j:function(){return v}});var s=r(14635),a=r(69893),n=r(78967),i=r(3682),o=r(36393),c=r(62052);let d=(0,c.hu)("PeerDB",c.$5.databases.peerDB);class l extends s.ZP{constructor(e={}){super("PeerDB",e),this.version(2).stores({peers:"synthientId, lastSeen"})}}class h{async updateChainIdentities(e,t,r){return await Promise.all(r.map(async r=>{e.find(e=>e.chain===r.chain&&e.address===r.address)||(await (0,i.N1)(t,r.synthientIdSignature)?e.push(r):d.error("Could not verify identity for ".concat(t," on chain ").concat(r.chain," with address ").concat(r.address)))})),e}async getNetworkTotalTokens(){return(await this.db.peers.toArray()).reduce((e,t)=>e+t.totalTokens,0)}async getPeerStats(e){let t=await this.db.peers.where("lastSeen").above(e).count();return{totalTokens:(await this.db.peers.where("lastSeen").above(e).toArray()).reduce((e,t)=>e+(!isNaN(t.totalTokens)&&t.totalTokens||0),0),totalPeers:t,totalWorkers:(await this.db.peers.where("lastSeen").above(e).toArray()).reduce((e,t)=>e+(!isNaN(t.totalWorkers)&&t.totalWorkers||0),0)}}async getLastPeers(e,t){return this.db.peers.where("lastSeen").aboveOrEqual(e).limit(t).toArray()}async getPeerCount(e){return e?this.db.peers.where("lastSeen").aboveOrEqual(e).count():this.db.peers.count()}async processPackets(e){let t=e.map(e=>e.synthientId),r=(await this.db.peers.bulkGet(t)).filter(e=>!!e),s=!1,a=await Promise.all(Array.from(new Set(t)).map(async t=>{let a=e.filter(e=>e.synthientId===t).sort((e,t)=>{var r,s;return((null===(r=t.receivedTime)||void 0===r?void 0:r.getTime())||0)-((null===(s=e.receivedTime)||void 0===s?void 0:s.getTime())||0)}),n=r.find(e=>e.synthientId===t);n||(s=!0);let i=a.filter(e=>"peerConnectedChain"===e.packet.type).flatMap(e=>e.packet.identities),o=a.map(e=>"peerStatusUpdate"===e.packet.type&&("completed_inference"===e.packet.status||"boot"===e.packet.status)?e.packet.totalTokens:0).concat([(null==n?void 0:n.totalTokens)||0]).filter(e=>!isNaN(e)&&e>0),c=a.map(e=>"peerStatusUpdate"===e.packet.type&&"loaded_worker"===e.packet.status?e.packet.totalWorkers:0).concat([(null==n?void 0:n.totalWorkers)||0]).filter(e=>!isNaN(e)&&e>0),d=o.length>0?Math.max(...o):0,l=n||{synthientId:t,seenOn:[],totalTokens:0,totalWorkers:0,lastSeen:a[0].receivedTime||new Date,chainIds:[]};return l.seenOn=Array.from(new Set([...l.seenOn,...a.map(e=>e.deliveredThrough).filter(e=>!!e)])),l.chainIds=await this.updateChainIdentities(l.chainIds,t,i),l.totalTokens=Math.max(d,l.totalTokens||0),l.totalWorkers=Math.max(c.length>0?Math.max(...c):0,l.totalWorkers||0),l}));await this.db.peers.bulkPut(a);let n=e.filter(e=>"knownPeers"===e.packet.type);return n.length>0&&this.loadKnownPeerPackets(n),s}async loadKnownPeerPackets(e){let t=e.flatMap(e=>e.packet.peerList.map(e=>e.synthientId)),r=(await this.db.peers.bulkGet(t)).filter(e=>!!e),s={},a={};e.forEach(e=>{e.packet.peerList.forEach(t=>{a[t.synthientId]&&a[t.synthientId].latestUpdate>=new Date(e.packet.createdAt)||(a[t.synthientId]={peer:{totalTokens:t.totalTokens,synthientId:t.synthientId,seenOn:t.seenOn,totalWorkers:t.totalWorkers,lastSeen:new Date(t.lastSeen),chainIds:t.identities||[]},latestUpdate:new Date(e.packet.createdAt)})})}),await Promise.all(Object.values(a).map(async e=>{let{peer:t}=e,a=r.find(e=>e.synthientId===t.synthientId)||s[t.synthientId]||{synthientId:t.synthientId,seenOn:t.seenOn,lastSeen:new Date(t.lastSeen),chainIds:[]};a.seenOn=Array.from(new Set([...a.seenOn,...t.seenOn])),a.chainIds=await this.updateChainIdentities(a.chainIds,t.synthientId,t.chainIds),a.lastSeen=a.lastSeen&&new Date(Math.max(a.lastSeen.getTime(),new Date(t.lastSeen).getTime())||new Date(t.lastSeen)),d.debug("UpdatedPeer totalTokens: ".concat(t.totalTokens," ").concat(a.totalTokens));let n=[t.totalTokens,a.totalTokens].filter(e=>!isNaN(e)&&e>0);a.totalTokens=n.length>0?Math.max(...n):0,a.totalWorkers=Math.max(t.totalWorkers,a.totalWorkers),s[t.synthientId]=a})),await this.db.peers.bulkPut(Object.values(s))}async getPeer(e){return this.db.peers.get(e)}async getAllPeers(){return this.db.peers.toArray()}async deletePeer(e){await this.db.peers.delete(e)}constructor(e={}){this.db=new l(e)}}var u=r(22170),p=r.n(u),k=r(13201),y=r(89028);let m=(0,c.hu)("PacketDB",c.$5.databases.packetDB);a.UG.sha512Sync=function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return(0,n.o)(a.UG.concatBytes(...t))};let g=(0,y.ri)().packetDBSettings;class f extends s.ZP{constructor(e={}){super("PacketDatabase",e),this.version(2).stores({packets:"[synthientId+signature], receivedTime"})}}class v extends o.Z{async getStats(e){return{peerStats:await this.peerDB.getPeerStats(e),packetCount:await this.db.packets.count()}}async getLastPackets(e){return{packets:await this.db.packets.orderBy("receivedTime").reverse().limit(e).toArray(),total:await this.db.packets.count()}}async emitNewPacketEvents(e){"p2pInferenceRequest"===e.packet.type&&this.emit("newP2PInferenceRequest",e.packet,e.synthientId),"inferenceQuorumComputed"===e.packet.type&&(e.packet.verifiedBy!==e.synthientId?m.debug("Received inferenceQuorumComputed not directly from the sender, dropping",e):this.emit("consensusPacketReceived",e.packet)),"inferenceCommit"===e.packet.type&&this.emit("newInferenceCommit",e),"inferenceRevealRequest"===e.packet.type&&this.validateInferenceRevealRequest(e),"inferenceReveal"==e.packet.type&&this.emit("newInferenceRevealed",e)}async validateInferenceRevealRequest(e){"inferenceRevealRequest"===e.packet.type&&e.packet.quorum.some(e=>e.synthientId===this.clientInfo.synthientId)&&(m.debug("Received inferenceRevealRequest for own synthientId"),this.emit("newInferenceRevealRequest",e))}async transmitPacket(e){let t={synthientId:this.clientInfo.synthientId,signature:"",packet:e};t.signature=(0,i.K4)(this.clientInfo.synthientPrivKey,e),await this.db.packets.add({...t,receivedTime:new Date}),this.emitNewPacketEvents(t),m.debug("Transmitting packet ".concat(t.packet.type),t),await this.sendPacketOverP2P(t)}async getAllPackets(){return await this.db.packets.toArray()}fixEmbeddingArraysInPackets(e){"inferenceReveal"===e.packet.type?(e.packet.embedding=Object.values(e.packet.embedding),e.packet.bEmbedding=Object.values(e.packet.bEmbedding)):"inferenceRevealRejected"===e.packet.type&&("computed_bembedding_fails_threshold"===e.packet.rejectReason.type&&(e.packet.rejectReason.computedBEmbedding=Object.values(e.packet.rejectReason.computedBEmbedding)),e.packet.rejectReason.revealedBEmbedding=Object.values(e.packet.rejectReason.revealedBEmbedding))}async getPacket(e,t){return await this.db.packets.get({synthientId:e,signature:t})}verifyAndDedupeReceivedPacketQueue(e){let t=e.filter(e=>{let t=(0,i.yj)(e.synthientId,e.signature,e.packet);return t||m.debug("Invalid signature on packet, dropping packet from ".concat(e.synthientId),e),t}),r={};return t.forEach(e=>{let t=e.synthientId+e.signature;r[t]||(r[t]=e)}),Object.values(r)}async transmitPeerList(){let e=new Date(Date.now()-432e5),t=await this.peerDB.getLastPeers(e,200);if(Math.random()<g.peerCommunicationCount/t.length){let e={type:"knownPeers",peerList:t.map(e=>({synthientId:e.synthientId,identities:e.chainIds,totalWorkers:e.totalWorkers||0,totalTokens:!isNaN(e.totalTokens)&&e.totalTokens||0,lastSeen:e.lastSeen&&(0,k.MQ)(e.lastSeen),seenOn:e.seenOn})),createdAt:(0,k.MQ)(new Date)};m.debug("Transmitting peer list with ".concat(Object.values(e).length),e),await this.transmitPacket(e)}}emitPeerHeart(e){this.emit("peerHeart",e)}receivePacket(e){m.trace("Queued received packet: ",e),this.receivedPacketQueue.push(e),this.processReceivedPacketQueue(),this.receivedPacketQueue.length>=g.maxReceivedPacketQueueSize&&this.processReceivedPacketQueue.flush()}async printPackets(){await this.db.packets.toArray()}async dropOldPackets(e){let t=new Date(Date.now()-e);await this.db.packets.where("receivedTime").below(t).delete(),m.debug("Dropped packets older than ".concat(e,"ms"))}async clearPackets(){await this.db.packets.clear(),m.debug("Cleared all packets from the database.")}constructor(e,t,r={}){super(),this.clientInfo=e,this.sendPacketOverP2P=t,this.receivedPacketQueue=[],this.cleanUpOldPackets=p()(async()=>{m.debug("Cleaning up old packets."),await this.db.packets.orderBy("receivedTime").reverse().offset(g.maxPacketDBSize+50).delete()},5e3),this.processReceivedPacketQueue=p()(async()=>{let e=this.receivedPacketQueue;this.receivedPacketQueue=[];let t=this.verifyAndDedupeReceivedPacketQueue(e),r=await this.db.packets.where("[synthientId+signature]").anyOf(t.map(e=>[e.synthientId,e.signature])).toArray(),a=t.filter(e=>!r.some(t=>t.synthientId===e.synthientId&&t.signature===e.signature)).map(e=>(this.fixEmbeddingArraysInPackets(e),e));try{await this.db.packets.bulkPut(a).catch(s.ZP.BulkError,function(e){m.error("".concat(e.failures.length," packets were added successfully, but some others could not be. Check console for errors"),e)})}catch(e){m.error("Different error adding packets to the database",e)}let n=!!a.some(e=>"peerStatusUpdate"===e.packet.type&&"boot"===e.packet.status);this.peerDB.processPackets(a).then(e=>{(e||n)&&this.transmitPeerList()}),a.forEach(e=>this.emitNewPacketEvents(e)),a.filter(e=>"peerHeart"===e.packet.type).slice(0,g.peerHeartLimit).forEach(e=>this.emitPeerHeart(e)),setTimeout(()=>this.cleanUpOldPackets(),0)},g.receivePacketQueueDebounceMs,{trailing:!0}),this.db=new f(r),this.peerDB=new h,this.clientInfo=e,this.sendPacketOverP2P=t}}},18951:function(e,t,r){"use strict";let s;r.d(t,{K6:function(){return h},il:function(){return l}});var a=r(3682),n=r(69893),i=r(78967),o=r(13201),c=r(89028);n.UG.sha512Sync=function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return(0,i.o)(n.UG.concatBytes(...t))};let d=c.wK;async function l(e,t){let r=await (0,a.q6)(e,t);localStorage.setItem(d,r)}async function h(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(s)return s;if(!t&&localStorage.getItem(d)&&e)try{let t=localStorage.getItem(d),r=await (0,a.ow)(t,e);r.synthientId||console.log("Could not properly decrypt with this password"),s=r}catch(e){throw console.error("Could not decrypt saved identity",e),e}else{let t=function(){let e=n.P6.randomPrivateKey(),t=n.$3(e);return{synthientId:n.UG.bytesToHex(t),synthientPrivKey:n.UG.bytesToHex(e),chainIds:[],deviceInfo:(0,o.dz)()}}();await l(t,e),s=t}return s}},12683:function(e,t,r){"use strict";r.d(t,{t:function(){return c}});var s=r(2105),a=r(33987),n=r(28580),i=r(62052);let o=(0,i.hu)("P2P: NKN",i.$5.p2pNetworks.nkn);class c extends a.l{async waitForReady(){return this.loadingPromise.promise}async broadcastPacket(e){if(this.nknClient){o.debug("Sending message",e);try{return await this.nknClient.publish(this.nknTopic,JSON.stringify(e),{txPool:!0}),!0}catch(e){o.error("Error sending message",e),this.transmissionErrorCount++,this.transmissionErrorCount>this.p2pNKNSettings.maxSendErrorsBeforeRestart&&this.errorHandlers.forEach(t=>t(e,!0))}}return!1}listenForPacket(e){return this.packetReceivedCallbacks.push(e),()=>{this.packetReceivedCallbacks=this.packetReceivedCallbacks.filter(t=>t!==e)}}registerErrorHandler(e){return this.errorHandlers.push(e),()=>{this.errorHandlers=this.errorHandlers.filter(t=>t!==e)}}async gracefulShutdown(){this.renewalIntervalId&&clearInterval(this.renewalIntervalId),await this.nknClient.close()}constructor(e,t,r){super(e,t),this.p2pNKNSettings=r,this.loadingPromise=new n.C,this.transmissionErrorCount=0,this.packetReceivedCallbacks=[],this.errorHandlers=[],this.nknTopic=t.nknTopic;let a=new s.Wallet({password:t.nknWalletPassword});this.nknClient=new s.MultiClient({identifier:e,seed:a.getSeed()}),o.debug("NKN client created with id ".concat(e)),this.nknClient.onMessage(e=>{let{src:t,payload:r}=e,s=JSON.parse(r);s.receivedTime=new Date,s.deliveredThrough="nkn",this.packetReceivedCallbacks.forEach(e=>{e(s,{nknAddress:t})})}),this.nknClient.onConnect(e=>{let{addr:t}=e;o.debug("Connected"),this.loadingPromise.resolve(!0)}),this.nknClient.onConnectFailed(()=>{o.debug("Connection failed"),this.loadingPromise.resolve(!1),this.errorHandlers.forEach(e=>{e(Error("Connection failed"),!0)})}),a.subscribe(this.nknTopic,1e3,this.synthientId,"").then(e=>{o.debug("Subscribed to events in tx ".concat(e)),this.renewalIntervalId=setInterval(async()=>{await a.subscribe(this.nknTopic,1e3,this.synthientId,"").then(e=>{o.debug("Renewed subscription in tx ".concat(e))})},198e5)})}}},30701:function(e,t,r){"use strict";function s(e){return a.PEWPEW.topic=e.topic,a.NKN.topic=e.topic,a.TRYSTERO.appId=e.topic,a.TRYSTERO.topic=e.topic+"T",a.NKN.maxSendErrorsBeforeRestart=e.maxTransmissionErrorsBeforeRestart,a.TRYSTERO.maxTransmissionErrorsBeforeRestart=e.maxTransmissionErrorsBeforeRestart,a}r.d(t,{e:function(){return s}});let a={PEWPEW:{topic:"rakis0",bootFixedDelayMs:1e3,bootstrapPeers:["https://gun-manhattan.herokuapp.com/gun","https://peer.wallie.io/gun","https://plankton-app-6qfp3.ondigitalocean.app/"]},NKN:{maxSendErrorsBeforeRestart:5,topic:"rakis0"},TRYSTERO:{maxTransmissionErrorsBeforeRestart:5,appId:"rakis",topic:"rakis0",relayRedundancy:4,rtcConfig:{iceServers:[{urls:"stun:stun.relay.metered.ca:80"},{urls:"turn:a.relay.metered.ca:80",username:"fd396a3275680a085c4d66cd",credential:"hFQmauZyx0Mv0bCK"},{urls:"turn:a.relay.metered.ca:80?transport=tcp",username:"fd396a3275680a085c4d66cd",credential:"hFQmauZyx0Mv0bCK"},{urls:"turn:a.relay.metered.ca:443",username:"fd396a3275680a085c4d66cd",credential:"hFQmauZyx0Mv0bCK"},{urls:"turn:a.relay.metered.ca:443?transport=tcp",username:"fd396a3275680a085c4d66cd",credential:"hFQmauZyx0Mv0bCK"}]}}}},33987:function(e,t,r){"use strict";r.d(t,{l:function(){return s}});class s{constructor(e,t){this.synthientId=e,this.options=t}}},37678:function(e,t,r){"use strict";r.d(t,{p:function(){return d}});var s=r(24364),a=r.n(s),n=r(33987),i=r(28580),o=r(62052);let c=(0,o.hu)("P2P: PewPewDB",o.$5.p2pNetworks.pewpewdb);class d extends n.l{async waitForReady(){return await this.loadingPromise.promise,!0}async broadcastPacket(e){let t={...e,packet:JSON.stringify(e.packet)};return c.debug("Transmitting packet with gun",t),new Promise(e=>{this.gun.get(this.gunTopic).put(t,t=>t.err?(c.error("Error sending gun message: ",t.err),e(!1)):e(!0))})}listenForPacket(e){let t=this.packetHandlerIdCouinter++;return this.packetHandlerIds.push(t),this.gun.get(this.gunTopic).on((r,s,a,n)=>{if(!this.packetHandlerIds.includes(t)){n.off();return}c.debug("Received packet",r),e({...r,receivedTime:new Date,deliveredThrough:"gun",packet:JSON.parse(r.packet)},{})}),()=>{this.packetHandlerIds=this.packetHandlerIds.filter(e=>e!==t)}}registerErrorHandler(e){return this.errorHandlers.push(e),()=>{this.errorHandlers=this.errorHandlers.filter(t=>t!==e)}}gracefulShutdown(){}constructor(e,t){super(e,t),this.packetHandlerIds=[],this.packetHandlerIdCouinter=0,this.loadingPromise=new i.C,this.errorHandlers=[],this.gunTopic=t.gunTopic,this.gun=a()({peers:t.gunPeers,localStorage:!1}),setTimeout(()=>{this.loadingPromise.resolve()},t.startupDelayMs)}}},31406:function(e,t,r){"use strict";r.d(t,{f:function(){return c}});var s=r(18210),a=r(97481),n=r(33987),i=r(28580),o=r(62052);class c extends n.l{async waitForReady(){return this.loadingPromise.promise}async broadcastPacket(e){if(this.trysteroRoom)try{let[t]=this.trysteroRoom.makeAction(this.options.trysteroTopic);return t(e),!0}catch(e){this.transmissionErrorCount++,this.logger.error("Error sending message",e),this.errorHandlers.forEach(t=>t(e,this.transmissionErrorCount>this.trysteroP2PSettings.maxTransmissionErrorsBeforeRestart))}return!1}listenForPacket(e){return this.packetReceivedCallbacks.push(e),()=>{this.packetReceivedCallbacks=this.packetReceivedCallbacks.filter(t=>t!==e)}}registerErrorHandler(e){return this.errorHandlers.push(e),()=>{this.errorHandlers=this.errorHandlers.filter(t=>t!==e)}}async gracefulShutdown(){this.trysteroRoom.leave()}constructor(e,t,r){super(e,t),this.trysteroP2PSettings=r,this.loadingPromise=new i.C,this.transmissionErrorCount=0,this.packetReceivedCallbacks=[],this.errorHandlers=[],this.logger=(0,o.hu)("P2P: ".concat(t.trysteroType," (trystero)"),o.$5.p2pNetworks[t.trysteroType]);try{this.trysteroRoom="nostr"===this.options.trysteroType?(0,a.Ls)({appId:this.options.trysteroAppId,relayRedundancy:this.options.relayRedundancy,rtcConfig:this.options.rtcConfig},this.options.trysteroTopic):(0,s.Ls)({appId:this.options.trysteroAppId,relayRedundancy:this.options.relayRedundancy,rtcConfig:this.options.rtcConfig},this.options.trysteroTopic),this.logger.debug("Trystero client created",this.trysteroRoom);let[,e]=this.trysteroRoom.makeAction(this.options.trysteroTopic);e((e,t)=>{let r={...e,receivedTime:new Date,deliveredThrough:this.options.trysteroType};this.packetReceivedCallbacks.forEach(e=>{e(r,{peerId:t})})}),this.loadingPromise.resolve(!0)}catch(e){throw this.logger.error("Error setting up Trystero",e),this.loadingPromise.resolve(!1),this.errorHandlers.forEach(t=>t(e,!0)),e}}}}}]); |