@Override public Parcel getParcel(HashId itemId, NodeInfo nodeInfo, Duration maxTimeout) throws InterruptedException { try { // URL url = new URL("http://localhost:8080/contracts/" + itemId.toBase64String()); URL url = new URL(nodeInfo.publicUrlString() + "/parcels/" + itemId.toBase64String()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent", "Universa JAVA API Client"); connection.setRequestProperty("Connection", "close"); connection.setRequestMethod("GET"); if (200 != connection.getResponseCode()) return null; byte[] data = Do.read(connection.getInputStream()); Parcel parcel = Parcel.unpack(data); // tp.trace(); // Contract c = Contract.fromPackedTransaction(data); return parcel; } catch (Exception e) { report(getLabel(), "download failure. from: " + nodeInfo.getNumber() + " by: " + myInfo.getNumber() +" reason: " + e); return null; } }
public static NodeInfo initFrom(ResultSet rs) throws SQLException, EncryptionError { return new NodeInfo(new PublicKey(rs.getBytes("public_key")), rs.getInt("node_number"), rs.getString("node_name"), rs.getString("host"),rs.getString("public_host"), rs.getInt("udp_server_port"), rs.getInt("http_client_port"), rs.getInt("http_server_port")); } }
@Override public void addNode(NodeInfo nodeInfo) { try (PooledDb db = dbPool.db()) { String sqlText = "insert into config(http_client_port,http_server_port,udp_server_port, node_number, node_name, public_host,host,public_key) values(?,?,?,?,?,?,?,?);"; try ( PreparedStatement statement = db.statementReturningKeys(sqlText) ) { statement.setInt(1, nodeInfo.getClientAddress().getPort()); statement.setInt(2, nodeInfo.getServerAddress().getPort()); statement.setInt(3, nodeInfo.getNodeAddress().getPort()); statement.setInt(4, nodeInfo.getNumber()); statement.setString(5, nodeInfo.getName()); statement.setString(6, nodeInfo.getPublicHost()); statement.setString(7, nodeInfo.getClientAddress().getHostName()); statement.setBytes(8, nodeInfo.getPublicKey().pack()); db.updateWithStatement(statement); } catch (Exception e) { e.printStackTrace(); throw e; } } catch (SQLException se) { se.printStackTrace(); throw new Failure("add node failed:" + se); } catch (Exception e) { e.printStackTrace(); } }
/** * Start new client protocol session. It doesn't load network configuration. Only creates client protocol session with given node * @param myPrivateKey client private key * @param nodeInfo node info specifying node public key and url * @param session set to null or to the reconstructed instance * @throws IOException */ public Client(PrivateKey myPrivateKey, NodeInfo nodeInfo, BasicHttpClientSession session) throws IOException { httpClient = new BasicHttpClient(nodeInfo.publicUrlString()); this.clientPrivateKey = myPrivateKey; this.nodePublicKey = nodeInfo.getPublicKey(); httpClient.start(myPrivateKey, nodeInfo.getPublicKey(), session); }
public String getLabel() { return "Network Node " + myInfo.getNumber() + ": "; }
public static void createLocalNetwork() throws Exception { for (int i = 0; i < 3; i++) localNodes.add(createMain("node" + (i + 1), false)); Main main = localNodes.get(0); assertEquals("http://localhost:8080", main.myInfo.internalUrlString()); assertEquals("http://localhost:8080", main.myInfo.publicUrlString()); assertEquals(main.cache, main.node.getCache()); }
/** * This is first step of creation and installation of the session. * @param session is {@link Session} in which sending is. */ private void sendHello(Session session) { try { report(logLabel, () -> "send hello to " + session.remoteNodeInfo.getNumber(), VerboseLevel.BASE); byte[] helloNonce = Do.randomBytes(64); Packet packet = new Packet(getNextPacketId(), myNodeInfo.getNumber(), session.remoteNodeInfo.getNumber(), PacketTypes.HELLO, new PublicKey(session.remoteNodeInfo.getPublicKey().pack()).encrypt(helloNonce)); sendPacket(session.remoteNodeInfo, packet); session.addPacketToRetransmitMap(packet.packetId, packet, helloNonce); } catch (EncryptionError e) { callErrorCallbacks("(sendHello) EncryptionError: " + e); } }
netConfig.forEachNode(node -> { nodes.add(Binder.of( "url", node.publicUrlString(), "key", node.getPublicKey().pack(), "number", node.getNumber() )); });
private void loadNodeConfig() throws IOException, SQLException { Yaml yaml = new Yaml(); configRoot = (String) options.valueOf("config"); nodeKey = null; Binder settings = Binder.of(yaml.load(new FileInputStream(configRoot + "/config/config.yaml"))); log("node settings: " + settings); String nodeKeyFileName = configRoot + "/tmp/" + settings.getStringOrThrow("node_name") + ".private.unikey"; log(nodeKeyFileName); nodeKey = new PrivateKey(Do.read(nodeKeyFileName)); myInfo = new NodeInfo(nodeKey.getPublicKey(), settings.getIntOrThrow("node_number"), settings.getStringOrThrow("node_name"), (String) settings.getListOrThrow("ip").get(0), settings.getStringOrThrow("public_host"), settings.getIntOrThrow("udp_server_port"), settings.getIntOrThrow("http_client_port"), settings.getIntOrThrow("http_server_port") ); config.setIsFreeRegistrationsAllowedFromYaml(settings.getBoolean("allow_free_registrations", false)); config.setPermanetMode(settings.getBoolean("permanet_mode", false)); ledger = new PostgresLedger(settings.getStringOrThrow("database")); log("ledger constructed"); log("key loaded: " + nodeKey.info()); log("node local URL: " + myInfo.publicUrlString()); log("node info: " + myInfo.toBinder()); }
private Contract createNetConfigContract(Contract contract, List<NodeInfo> netConfig, Collection<PrivateKey> currentConfigKeys) throws IOException { contract = contract.createRevision(); ListRole listRole = new ListRole("owner"); for(NodeInfo ni: netConfig) { SimpleRole role = new SimpleRole(ni.getName()); contract.registerRole(role); role.addKeyRecord(new KeyRecord(ni.getPublicKey())); listRole.addRole(role); } listRole.setQuorum(netConfig.size()-1); contract.registerRole(listRole); contract.getStateData().set("net_config",netConfig); List<KeyRecord> creatorKeys = new ArrayList<>(); for(PrivateKey key : currentConfigKeys) { creatorKeys.add(new KeyRecord(key.getPublicKey())); contract.addSignerKey(key); } contract.setCreator(creatorKeys); contract.seal(); return contract; }
super(ownPrivateKey, sessionKey, myNodeInfo, netConfig); logLabel = "udp" + myNodeInfo.getNumber() + ": "; socket = new DatagramSocket(myNodeInfo.getNodeAddress().getPort()); socket.setReuseAddress(true);
log("node local URL: " + myInfo.publicUrlString()); log("node info: " + myInfo.toBinder());
public PublicKey getNodeKey() { return myInfo.getPublicKey(); }
resyncBreak += 1; log(myInfo.getNumber() + ": Network consensus is set to (negative/positive/resyncBreak): " + negative + " / " + positive + " / " + resyncBreak); config.setPositiveConsensus(positive); config.setNegativeConsensus(negative); clientHTTPServer.setParcelCache(parcelCache); clientHTTPServer.setEnvCache(envCache); clientHTTPServer.setLocalCors(myInfo.getPublicHost().equals("localhost"));
/** * Method creates {@link DatagramPacket} from given {@link Packet} and sends it to address:port from destination. * @param destination instance of {@link NodeInfo} with net address for sending. * @param packet data to send. It's {@link Packet#makeByteArray()} should returns data with size less than {@link DatagramAdapter#MAX_PACKET_SIZE} */ private void sendPacket(NodeInfo destination, Packet packet) { byte[] payload = packet.makeByteArray(); DatagramPacket dp = new DatagramPacket(payload, payload.length, destination.getNodeAddress().getAddress(), destination.getNodeAddress().getPort()); try { report(logLabel, ()->"sendPacket datagram size: " + payload.length, VerboseLevel.DETAILED); if ((testMode == TestModes.LOST_PACKETS || testMode == TestModes.LOST_AND_SHUFFLE_PACKETS) && (new Random().nextInt(100) < lostPacketsPercent)) report(logLabel, ()->"test mode: skip socket.send", VerboseLevel.BASE); else socket.send(dp); } catch (Exception e) { callErrorCallbacks("sendPacket exception: " + e); } }
/** * Deliver notification to all nodes except one * * @param exceptNode if not null, do not deliver to it. * @param notification notification fo deliver */ public void broadcast(NodeInfo exceptNode, Notification notification) { netConfig.forEachNode(node -> { if (exceptNode != null && !exceptNode.equals(node)) deliver(node, notification); }); }
private void startClientHttpServer() throws Exception { log("prepare to start client HTTP server on " + myInfo.getClientAddress().getPort()); clientHTTPServer = new ClientHTTPServer(nodeKey, myInfo.getClientAddress().getPort(), logger); clientHTTPServer.setCache(cache); clientHTTPServer.setParcelCache(parcelCache); clientHTTPServer.setNetConfig(netConfig); // node = new Node() }
public int getNumber() { return myInfo.getNumber(); }
private TestSpace prepareTestSpace(PrivateKey key) throws Exception { TestSpace testSpace = new TestSpace(); testSpace.nodes = new ArrayList<>(); for (int i = 0; i < 4; i++) testSpace.nodes.add(createMain("node" + (i + 1), false)); testSpace.node = testSpace.nodes.get(0); assertEquals("http://localhost:8080", testSpace.node.myInfo.internalUrlString()); assertEquals("http://localhost:8080", testSpace.node.myInfo.publicUrlString()); testSpace.myKey = key; testSpace.client = new Client(testSpace.myKey, testSpace.node.myInfo, null); testSpace.clients = new ArrayList(); for (int i = 0; i < 4; i++) testSpace.clients.add(new Client(testSpace.myKey, testSpace.nodes.get(i).myInfo, null)); return testSpace; }