public StructuredNode(AHAddress add, string realm):base(add,realm) { // Instantiate rpc early! RpcManager rpc = RpcManager.GetInstance(this); /** * Here are the ConnectionOverlords */ _leafco = new LeafConnectionOverlord(this); _snco = new StructuredNearConnectionOverlord(this); _ssco = new StructuredShortcutConnectionOverlord(this); _cco = new ChotaConnectionOverlord(this); _mco = new ManagedConnectionOverlord(this); #if !BRUNET_SIMULATOR _localco = new LocalConnectionOverlord(this); _iphandler = new IPHandler(); _iphandler.Subscribe(this, null); #endif /** * Turn on some protocol support : */ /// Turn on Packet Forwarding Support : GetTypeSource(PType.Protocol.Forwarding).Subscribe(new PacketForwarder(this), null); //Handles AHRouting: GetTypeSource(PType.Protocol.AH).Subscribe(new AHHandler(this), this); GetTypeSource(PType.Protocol.Echo).Subscribe(new EchoHandler(), this); //Add the standard RPC handlers: rpc.AddHandler("sys:ctm", new CtmRequestHandler(this)); sys_link = new ConnectionPacketHandler(this); rpc.AddHandler("sys:link", sys_link); rpc.AddHandler("trace", new TraceRpcHandler(this)); //Serve some public information about our ConnectionTable rpc.AddHandler("ConnectionTable", new ConnectionTableRpc(ConnectionTable, rpc)); //Add a map-reduce handlers: _mr_handler = new MapReduceHandler(this); //Subscribe it with the RPC handler: rpc.AddHandler("mapreduce", _mr_handler); //Subscribe map-reduce tasks _mr_handler.SubscribeTask(new MapReduceTrace(this)); _mr_handler.SubscribeTask(new MapReduceRangeCounter(this)); /* * Handle Node state changes. */ StateChangeEvent += delegate(Node n, Node.ConnectionState s) { if( s == Node.ConnectionState.Leaving ) { //Start our StructuredNode specific leaving: Leave(); } }; _connection_table.ConnectionEvent += new EventHandler(this.EstimateSize); _connection_table.ConnectionEvent += new EventHandler(this.UpdateNeighborStatus); _connection_table.DisconnectionEvent += new EventHandler(this.EstimateSize); _connection_table.DisconnectionEvent += new EventHandler(this.UpdateNeighborStatus); }
public AHRouter(AHAddress local) { _local = local; _sync = new object(); /* * Store the 100 most commonly used routes. * Since this may cause us to keep an extra 100 * AHAddress objects in memory, each of which requires * about 20 bytes, this costs on the order of 10-100 KB */ _route_cache = new Cache(100); }
public LocalHT() { AHAddress addr = new AHAddress(new RNGCryptoServiceProvider()); Node brunetNode = new StructuredNode(addr); RpcManager rpc = RpcManager.GetInstance(brunetNode); this._ts = new TableServer(brunetNode); this._node = brunetNode; #if FUSE_DEBUG //Having some init data isn't bad string key = FuseDhtUtil.GenDhtKey("testbasedir", "testkey1", "ipop_ns"); this.Put(key, "testvalue1", 5000); this.Put(key, "testvalue2", 3000); #endif }
///This tester simply establishes the Brunet network and log the edges made static void Main(string[] args) { String config_file = args[0]; NetworkConfiguration network_configuration = NetworkConfiguration.Deserialize(config_file); for(int i = 0; i < network_configuration.Nodes.Count; i++){ NodeConfiguration this_node_configuration = (NodeConfiguration)network_configuration.Nodes[i]; TransportAddressConfiguration local_ta_configuration = (TransportAddressConfiguration)this_node_configuration.TransportAddresses[0]; short port = local_ta_configuration.Port; SHA1 sha = new SHA1CryptoServiceProvider(); String local_ta = local_ta_configuration.GetTransportAddressURI(); //We take the local transport address plus the port number to be hashed to obtain a random AHAddress byte[] hashedbytes = sha.ComputeHash(Encoding.UTF8.GetBytes(local_ta + port)); //inforce type 0 hashedbytes[Address.MemSize - 1] &= 0xFE; AHAddress _local_ahaddress = new AHAddress(hashedbytes); Console.WriteLine(_local_ahaddress.ToBigInteger().ToString() + ' ' + local_ta_configuration.Address + ' ' + (port%25000)); } }
/** Utility method to determine if this address is between start and end * from the right, i.e. its satisfies the following constraints: * 1. Is to the right of start, and * 2. Is to the left of end * @return 1 in case its within * @return -1 in case it is not */ public bool IsBetweenFromRight(AHAddress start, AHAddress end){ int se_comp = start.CompareTo(end); //simple case of no wrap around where "within" is lesser if (se_comp > 0) { return start.CompareTo(this) > 0 && this.CompareTo(end) > 0; } else if( se_comp == 0 ) { //When start == end, nothing is between them return false; } else { //in case there is a wrap around //"within" has become greater than "this" return start.CompareTo(this) > 0 || this.CompareTo(end) > 0; } }
/** * The Left (increasing, clockwise) distance to * the given AHAddress * @param addr the AHAddress to compute the distance to * @return the distance */ public BigInteger LeftDistanceTo(AHAddress addr) { BigInteger n_x = ToBigInteger(); BigInteger n_y = addr.ToBigInteger(); BigInteger dist; if (n_y > n_x) { //The given address is larger than us, just subtract dist = n_y - n_x; } else { //We need to add AHAddress.Full to the result: dist = n_y - n_x + AHAddress.Full; } return dist; }
/** * Use the DistanceTo function. If this node is * positive distance from add it is right of. */ public bool IsRightOf(AHAddress add) { return (add.DistanceTo(this) < 0); }
private static void add_node() { int local_port = 0; // while(taken_ports.Contains(local_port = rand.Next(0, max_range) + base_port)); AHAddress address = new AHAddress(new RNGCryptoServiceProvider()); Node node = new StructuredNode(address, brunet_namespace); /* ArrayList arr_tas = new ArrayList(); for(int j = 0; j < max_range / 10; j++) { int remote_port = 0; do { remote_port = rand.Next(0, max_range) + base_port; } while(remote_port == local_port); PortTAAuthorizer port_auth = new PortTAAuthorizer(remote_port); arr_tas.Add(port_auth); } arr_tas.Add(new ConstantAuthorizer(TAAuthorizer.Decision.Allow)); TAAuthorizer ta_auth = new SeriesTAAuthorizer(arr_tas);*/ node.AddEdgeListener(new FunctionEdgeListener((new Random()).Next(1024, 65535))); //local_port, null));//, ta_auth)); // node.AddEdgeListener(new TunnelEdgeListener(node)); // node.RemoteTAs = RemoteTA; (new Thread(node.Connect)).Start(); // taken_ports[local_port] = node; nodes.Add((Address) address, node); dhts.Add(node, new Dht(node, DEGREE)); network_size++; }
static void Main(string[] args) { //first, remove the log file if(File.Exists("time_stamp.log")){ File.Delete("time_stamp.log"); } String config_file = args[0]; NetworkConfiguration network_configuration = NetworkConfiguration.Deserialize(config_file); int port_selection = Convert.ToInt32(args[1]); //There will be 10 different ports available for use: 0, 1, 2.. //for example, node 0 on a machine will use port_selection # 0, node 1 on a machine will use port_selection # 1 ///There will be multiple BruNet nodes on the same machine. The following is a list of possible ports used int list_size = 10; int [] port_list = new int[list_size]; for(int i = 0; i < list_size; i++){ port_list[i] = 25010 + i*10; } ///The line below is used when there is only one node per machine //int local_host_index = network_configuration.GetLocalHostIndex(); int desired_port = port_list[port_selection]; int local_host_index = network_configuration.GetLocalHostIndex(desired_port); NodeConfiguration this_node_configuration = (NodeConfiguration)network_configuration.Nodes[local_host_index]; TransportAddressConfiguration local_ta_configuration = (TransportAddressConfiguration)this_node_configuration.TransportAddresses[0]; short port = local_ta_configuration.Port; SHA1 sha = new SHA1CryptoServiceProvider(); String local_ta = local_ta_configuration.GetTransportAddressURI(); //We take the local transport address plus the port number to be hashed to obtain a random AHAddress byte[] hashedbytes = sha.ComputeHash(Encoding.UTF8.GetBytes(local_ta + port)); //inforce type 0 hashedbytes[Address.MemSize - 1] &= 0xFE; AHAddress _local_ahaddress = new AHAddress(hashedbytes); Node this_node = new StructuredNode( _local_ahaddress ); ///Node this_node = new HybridNode( new AHAddress( new BigInteger( 2*(local_host_index+1) ) ) ); String file_string = "brunetadd" + Convert.ToString(desired_port) + ".log"; StreamWriter sw = new StreamWriter(file_string, false); sw.WriteLine( "local_address " + this_node.Address.ToBigInteger().ToString() + " " + Dns.GetHostName()); sw.Close(); if ( local_ta_configuration.Protocol == "tcp" ) { this_node.AddEdgeListener( new TcpEdgeListener(port) ); } else if( local_ta_configuration.Protocol == "udp" ) { this_node.AddEdgeListener( new UdpEdgeListener(port) ); } int remote_node_index = local_host_index-1; int num_remote_ta = 20; //20 nodes on the list to try to bootstrap to if (local_host_index!=0) { NodeConfiguration remote_node_configuration = (NodeConfiguration)network_configuration.Nodes[0]; TransportAddressConfiguration remote_ta_configuration = (TransportAddressConfiguration)remote_node_configuration.TransportAddresses[0]; String remote_ta = remote_ta_configuration.GetTransportAddressURI(); this_node.RemoteTAs.Add( TransportAddressFactory.CreateInstance( remote_ta ) ); } while ( (remote_node_index>=0) && (num_remote_ta>=0) ) { NodeConfiguration remote_node_configuration = (NodeConfiguration)network_configuration.Nodes[remote_node_index]; TransportAddressConfiguration remote_ta_configuration = (TransportAddressConfiguration)remote_node_configuration.TransportAddresses[0]; String remote_ta = remote_ta_configuration.GetTransportAddressURI(); this_node.RemoteTAs.Add( TransportAddressFactory.CreateInstance( remote_ta ) ); System.Console.WriteLine("Adding {0}", remote_ta); remote_node_index--; num_remote_ta--; } //EchoTester echo_printer = new EchoTester(); //this_node.Subscribe(AHPacket.Protocol.Echo, echo_printer); StreamWriter stamp_sw = new StreamWriter("time_stamp.log", true); stamp_sw.WriteLine("Local_node: {0} start_time_GMT: {1}:{2}", Dns.GetHostName(), DateTime.Now.ToUniversalTime().ToString(), DateTime.Now.ToUniversalTime().Millisecond ); stamp_sw.Close(); this_node.Connect(); }
/** * When a node is out of the range, this method is called. * This method tries to find the nearest node to the middle of range using greedty algorithm. * return list of MapReduceInfo */ private ArrayList GenerateTreeOutRange(AHAddress start, AHAddress end, MapReduceArgs mr_args, int timeout) { ArrayList retval = new ArrayList(); BigInteger up = start.ToBigInteger(); BigInteger down = end.ToBigInteger(); BigInteger mid_range = (up + down) /2; if (mid_range % 2 == 1) {mid_range = mid_range -1; } AHAddress mid_addr = new AHAddress(mid_range); if (!mid_addr.IsBetweenFromLeft(start, end) ) { mid_range += Address.Half; mid_addr = new AHAddress(mid_range); } ArrayList gen_arg = new ArrayList(); if (NextGreedyClosest(mid_addr) != null ) { AHGreedySender ags = new AHGreedySender(_node, mid_addr); string start_range = start.ToString(); string end_range = end.ToString(); gen_arg.Add(start_range); gen_arg.Add(end_range); MapReduceInfo mr_info = new MapReduceInfo( (ISender) ags, new MapReduceArgs(this.TaskName, mr_args.MapArg, gen_arg, mr_args.ReduceArg, timeout)); Log("{0}: {1}, out of range, moving to the closest node to mid_range: {2} to target node, range start: {3}, range end: {4}", this.TaskName, _node.Address, mid_addr, start, end); retval.Add(mr_info); } else { // cannot find a node in the range. } return retval; }
/** * Generate tree within the range. * return list of MapReduceInfo */ private ArrayList GenerateTreeInRange(AHAddress this_addr, AHAddress start, AHAddress end, List<Connection> cons, bool left, MapReduceArgs mr_args, int timeout) { //Divide the range and trigger bounded broadcasting again in divided range starting with neighbor. //Deivided ranges are (start, n_1), (n_1, n_2), ... , (n_m, end) ArrayList retval = new ArrayList(); if (cons.Count != 0) //make sure if connection list is not empth! { //con_list is sorted. AHAddress last = this_addr; //the first element of cons is the nearest. for (int i = 0; i < cons.Count; i++) { Connection next_c = (Connection)cons[i]; AHAddress next_addr = (AHAddress)next_c.Address; ISender sender = (ISender) next_c.Edge; string front = last.ToString(); string back = next_addr.ToString(); string rg_start = start.ToString(); string rg_end = end.ToString(); ArrayList gen_arg = new ArrayList(); if (i==cons.Count -1) { // The last bit if (left) { // the left farthest neighbor gen_arg.Add(front); gen_arg.Add(rg_end); } else { // the right farthest neighbor gen_arg.Add(rg_start); gen_arg.Add(front); } } else { if (left) { //left connections gen_arg.Add(front); gen_arg.Add(back); } else { //right connections gen_arg.Add(back); gen_arg.Add(front); } } MapReduceInfo mr_info = new MapReduceInfo( (ISender) sender, new MapReduceArgs(this.TaskName, mr_args.MapArg, gen_arg, mr_args.ReduceArg, timeout // timeout )); Log("{0}: {1}, adding address: {2} to sender list, range start: {3}, range end: {4}", this.TaskName, _node.Address, next_c.Address, gen_arg[0], gen_arg[1]); last = next_addr; retval.Add(mr_info); } } return retval; }
/// <summary>This is the generic Put that is used by both the regular Put /// and Create methods. The use of the unique variable differentiates the /// two. This is asynchronous. Results are stored in the Channel returns. /// Creates and Puts return true if successful or exception if there are /// network errors in adding the entry, creates also fail if a previous /// entry exists. The work of determining success is handled in /// PutEnqueueHandler and PutCloseHandler.</summary> /// <param name="key">The index to store the value at.</param> /// <param name="value">The value to store.</param> /// <param name="ttl">The dht lease time for the key:value pair.</param> /// <param name="returns">The Channel where the result will be placed.</param> /// <param name="unique">True to do a create, false otherwise.</param> public void AsyncPut(MemBlock key, MemBlock value, int ttl, Channel returns, bool unique) { if(!_online) { throw new DhtException("The Node is (going) offline, DHT is offline."); } AsDhtPutState adps = new AsDhtPutState(returns); MemBlock[] brunet_address_for_key = MapToRing(key); Channel[] q = new Channel[DEGREE]; lock(_adps_table.SyncRoot) { for (int k = 0; k < DEGREE; k++) { Channel queue = new Channel(1); queue.CloseEvent += this.PutCloseHandler; _adps_table[queue] = adps; q[k] = queue; } } for (int k = 0; k < DEGREE; k++) { Address target = new AHAddress(brunet_address_for_key[k]); AHSender s = new AHSender(Node, target, AHPacket.AHOptions.Greedy); _rpc.Invoke(s, q[k], "dht.Put", brunet_address_for_key[k], value, ttl, unique); } }
/// <summary>Restores any of the Dht results that don't return all their /// values. We only get here at the end of a Dht return operation.</summary> /// <remarks>This analyzes the holes and fills them in individually. This only /// fills holes where there was a positive result (MAJORITY of results /// received).</remarks> /// <param name="adgs">The AsDhtGetState to analyze for follow up.</param> protected void GetFollowUp(AsDhtGetState adgs) { foreach (DictionaryEntry de in adgs.results) { if(de.Value == null || de.Key == null) { continue; } Hashtable res = (Hashtable) de.Value; if(res.Count < MAJORITY || res.Count == DEGREE) { if(res.Count < MAJORITY) { if(Dht.DhtLog.Enabled) { ProtocolLog.Write(Dht.DhtLog, String.Format( "Failed get count:total = {0}:{1}", res.Count, DEGREE)); } } res.Clear(); continue; } MemBlock value = (MemBlock) de.Key; int ttl = (int) adgs.ttls[value] / res.Count; if(Dht.DhtLog.Enabled) { ProtocolLog.Write(Dht.DhtLog, String.Format( "Doing follow up put count:total = {0}:{1}", res.Count, DEGREE)); } for(int i = 0; i < DEGREE; i++) { if(!res.Contains(i)) { MemBlock key = adgs.brunet_address_for_key[i]; Channel queue = new Channel(); Address target = new AHAddress(key); AHSender s = new AHSender(Node, target, AHPacket.AHOptions.Greedy); try { _rpc.Invoke(s, queue, "dht.Put", key, value, ttl, false); } catch(Exception) {} } } res.Clear(); } adgs.ttls.Clear(); adgs.results.Clear(); }
/// <remarks>This starts the get process by sending dht.Get to all the remote /// end points that contain the key we're looking up. The next step is /// is when the results are placed in the channel and GetEnqueueHandler is /// called or GetCloseHandler is called. This means the get needs to be /// stateful, that information is stored in the _adgs_table.</remarks> public void AsyncGet(MemBlock key, Channel returns) { if(!_online) { throw new DhtException("The Node is (going) offline, DHT is offline."); } // create a GetState and map in our table map its queues to it // so when we get a GetHandler we know which state to load AsDhtGetState adgs = new AsDhtGetState(returns); Channel[] q = new Channel[DEGREE]; lock(_adgs_table.SyncRoot) { for (int k = 0; k < DEGREE; k++) { Channel queue = new Channel(1); _adgs_table[queue] = adgs; q[k] = queue; } } // Setting up our Channels for (int k = 0; k < DEGREE; k++) { Channel queue = q[k]; queue.EnqueueEvent += this.GetEnqueueHandler; queue.CloseEvent += this.GetCloseHandler; adgs.queueMapping[queue] = k; } // Sending off the request! adgs.brunet_address_for_key = MapToRing(key); for (int k = 0; k < DEGREE; k++) { Address target = new AHAddress(adgs.brunet_address_for_key[k]); AHSender s = new AHSender(Node, target, AHPacket.AHOptions.Greedy); // 1024 is in there for backwards compatibility _rpc.Invoke(s, q[k], "dht.Get", adgs.brunet_address_for_key[k], 1024, null); } }
/** * Initiates shortcut connection creation to a random shortcut target with the * correct distance distribution. */ protected void CreateShortcut() { /* * If there are k nodes out of a total possible * number of N ( =2^(160) ), the average distance * between them is d_ave = N/k. So we want to select a distance * that is at least N/k from us. We want to do this * with prob(dist = d) ~ 1/d. We can do this by selecting * a uniformly distributed p, and sample: * * d = d_ave(d_max/d_ave)^p * = d_ave( 2^(p log d_max - p log d_ave) ) * = 2^( p log d_max + (1 - p) log d_ave ) * * since we can go all the way around the ring d_max = N * and: log d_ave = log N - log k, but k is the size of the network: * * d = 2^( p log N + (1 - p) log N - (1-p) log k) * = 2^( log N - (1-p)log k) * */ double logN = (double)(Address.MemSize * 8); double logk = Math.Log( (double)_node.NetworkSize, 2.0 ); double p = _rand.NextDouble(); double ex = logN - (1.0 - p)*logk; int ex_i = (int)Math.Floor(ex); double ex_f = ex - Math.Floor(ex); //Make sure 2^(ex_long+1) will fit in a long: int ex_long = ex_i % 63; int ex_big = ex_i - ex_long; ulong dist_long = (ulong)Math.Pow(2.0, ex_long + ex_f); //This is 2^(ex_big): BigInteger big_one = 1; BigInteger dist_big = big_one << ex_big; BigInteger rand_dist = dist_big * dist_long; // Add or subtract random distance to the current address BigInteger t_add = _node.Address.ToBigInteger(); // Random number that is 0 or 1 if( _rand.Next(2) == 0 ) { t_add += rand_dist; } else { t_add -= rand_dist; } byte[] target_int = Address.ConvertToAddressBuffer(new BigInteger(t_add % Address.Full)); Address.SetClass(target_int, _node.Address.Class); Address start = new AHAddress(target_int); if (LogEnabled) { ProtocolLog.Write(ProtocolLog.SCO, String.Format("SCO local: {0}, Selecting shortcut to create close to start: {1}.", _node.Address, start)); } //make a call to the target selector to find the optimal _target_selector.ComputeCandidates(start, (int) Math.Ceiling(logk), CreateShortcutCallback, null); }
public RemotingTester(int p, NetworkConfiguration nc, StreamWriter fs) { int desired_port = p; _port = (short)p; _sw = fs; Console.WriteLine("Z {0}",_port); int local_host_index = nc.GetLocalHostIndex(desired_port); NodeConfiguration this_node_configuration = (NodeConfiguration)nc.Nodes[local_host_index]; Console.WriteLine("A"); TransportAddressConfiguration local_ta_configuration = (TransportAddressConfiguration)this_node_configuration.TransportAddresses[0]; Console.WriteLine("B"); short this_port = local_ta_configuration.Port; SHA1 sha = new SHA1CryptoServiceProvider(); String local_ta = local_ta_configuration.GetTransportAddressURI(); //We take the local transport address plus the port number to be hashed to obtain a random AHAddress byte[] hashedbytes = sha.ComputeHash(Encoding.UTF8.GetBytes(local_ta + desired_port)); //inforce type 0 hashedbytes[Address.MemSize - 1] &= 0xFE; AHAddress _local_ahaddress = new AHAddress(hashedbytes); Node this_node = new HybridNode( _local_ahaddress ); //Node this_node = new StructuredNode( _local_ahaddress ); node = this_node; if ( local_ta_configuration.Protocol == "tcp" ) { node.AddEdgeListener( new TcpEdgeListener(this_port) ); } else if( local_ta_configuration.Protocol == "udp" ) { node.AddEdgeListener( new UdpEdgeListener(this_port) ); } Console.WriteLine("C"); int remote_node_index = local_host_index-1; int num_remote_ta = 150; //20 nodes on the list to try to bootstrap to if (local_host_index!=0) { Console.WriteLine("C--"); NodeConfiguration remote_node_configuration = (NodeConfiguration)nc.Nodes[0]; Console.WriteLine("C++"); TransportAddressConfiguration remote_ta_configuration = (TransportAddressConfiguration)remote_node_configuration.TransportAddresses[0]; Console.WriteLine("D"); String remote_ta = remote_ta_configuration.GetTransportAddressURI(); node.RemoteTAs.Add( new TransportAddress( remote_ta ) ); } while ( (remote_node_index>=0) && (num_remote_ta>=0) ) { NodeConfiguration remote_node_configuration = (NodeConfiguration)nc.Nodes[remote_node_index]; Console.WriteLine("E"); TransportAddressConfiguration remote_ta_configuration = (TransportAddressConfiguration)remote_node_configuration.TransportAddresses[0]; String remote_ta = remote_ta_configuration.GetTransportAddressURI(); node.RemoteTAs.Add( new TransportAddress( remote_ta ) ); //System.Console.WriteLine("Adding {0}", remote_ta); remote_node_index--; num_remote_ta--; } bool net_stream = false; String server_ipadd = "cantor.ee.ucla.edu"; int server_port = 8002; int time_diff = 0; String td_file_string = "~/joe/time_diff.txt"; if(File.Exists(td_file_string)){ StreamReader sr = new StreamReader(td_file_string); time_diff = Convert.ToInt32( sr.ReadLine() ); sr.Close(); } //String file_string = "./data/brunetadd" + Convert.ToString(desired_port) + ".log"; fs.WriteLine( "local_address " + node.Address.ToBigInteger().ToString() + " " + Dns.GetHostName() + ":" + desired_port); fs.Write( DateTime.Now.ToUniversalTime().ToString("MM'/'dd'/'yyyy' 'HH':'mm':'ss") + ":" + DateTime.Now.ToUniversalTime().Millisecond + " Start Start " + node.Address.ToBigInteger().ToString() + '\n'); fs.Flush(); #if PLAB_LOG BrunetLogger bl = new BrunetLogger(desired_port, (AHAddress)node.Address, net_stream, server_ipadd, server_port, time_diff, fs); node.Logger = bl; #endif //bool log_rdp = false; #if PACKET_LOG String file_packet = "./data/packet" + Convert.ToString(desired_port) + ".log"; StreamWriter packet_sw = new StreamWriter(file_packet, false); packet_sw.WriteLine("Local_node: {0}:{1} start_time_GMT: {2}:{3} local_address {4}", Dns.GetHostName(), desired_port, DateTime.Now.ToUniversalTime().ToString("MM'/'dd'/'yyyy' 'HH':'mm':'ss"), DateTime.Now.ToUniversalTime().Millisecond, node.Address.ToBigInteger().ToString() ); packet_sw.Close(); #endif }
// adds a node to the pool protected static void add_node(bool output) { AHAddress address = new AHAddress(new RNGCryptoServiceProvider()); Node node = new StructuredNode(address, brunet_namespace); NodeMapping nm = new NodeMapping(); nm.Node = node; nodes.Add((Address) address, nm); nm.Port = TakenPorts.Count; while(TakenPorts.Contains(nm.Port)) { nm.Port = rand.Next(0, 65535); } TAAuthorizer auth = null; if(broken != 0) { auth = new BrokenTAAuth(broken); } EdgeListener el = new FunctionEdgeListener(nm.Port, 0, auth, true); node.AddEdgeListener(el); if(broken != 0) { el = new TunnelEdgeListener(node); node.AddEdgeListener(el); } ArrayList RemoteTAs = new ArrayList(); for(int i = 0; i < 5 && i < TakenPorts.Count; i++) { int rport = (int) TakenPorts.GetByIndex(rand.Next(0, TakenPorts.Count)); RemoteTAs.Add(TransportAddressFactory.CreateInstance("brunet.function://127.0.0.1:" + rport)); } node.RemoteTAs = RemoteTAs; TakenPorts[nm.Port] = nm.Port; if(output) { Console.WriteLine("Adding: " + nm.Node.Address); } node.Connect(); network_size++; }
protected Connection NextGreedyClosest(AHAddress a) { /* * First find the Connection pointing to the node closest to a, if * there is one closer than us */ ConnectionTable tab = _node.ConnectionTable; ConnectionList structs = tab.GetConnections(ConnectionType.Structured); Connection next_closest = null; int idx = structs.IndexOf(a); if( idx < 0 ) { //a is not the table: Connection right = structs.GetRightNeighborOf(a); Connection left = structs.GetLeftNeighborOf(a); BigInteger my_dist = ((AHAddress)_node.Address).DistanceTo(a).abs(); BigInteger ld = ((AHAddress)left.Address).DistanceTo(a).abs(); BigInteger rd = ((AHAddress)right.Address).DistanceTo(a).abs(); if( (ld < rd) && (ld < my_dist) ) { next_closest = left; } if( (rd < ld) && (rd < my_dist) ) { next_closest = right; } } else { next_closest = structs[idx]; } return next_closest; }
public void Test14(ref int op) { Console.WriteLine("Test 14: Testing 1000 puts and 1 get with 1000 " + "results with the same key. Then we remove the main owner of the " + "key."); RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte[] key = new byte[10]; byte[] value = new byte[value_size]; rng.GetBytes(key); ArrayList al_results = new ArrayList(); int count = 60; BlockingQueue[] results_queue = new BlockingQueue[count]; for(int i = 0; i < count; i++) { value = new byte[value_size]; rng.GetBytes(value); al_results.Add(value); results_queue[i] = new BlockingQueue(); default_dht.AsyncPut(key, value, 3000, results_queue[i]); } for (int i = 0; i < count; i++) { try { bool res = (bool) results_queue[i].Dequeue(); Console.WriteLine("success in put : " + i); } catch { Console.WriteLine("Failure in put : " + i); } } Console.WriteLine("Insertion done..."); Console.WriteLine("Disconnecting nodes..."); MemBlock[] b = default_dht.MapToRing(key); BigInteger[] baddrs = new BigInteger[default_dht.DEGREE]; BigInteger[] addrs = new BigInteger[default_dht.DEGREE]; bool first_run = true; foreach(DictionaryEntry de in nodes) { Address addr = (Address) de.Key; for(int j = 0; j < b.Length; j++) { if(first_run) { addrs[j] = addr.ToBigInteger(); baddrs[j] = (new AHAddress(b[j])).ToBigInteger(); } else { BigInteger caddr = addr.ToBigInteger(); BigInteger new_diff = baddrs[j] - caddr; if(new_diff < 0) { new_diff *= -1; } BigInteger c_diff = baddrs[j] - addrs[j]; if(c_diff < 0) { c_diff *= -1; } if(c_diff > new_diff) { addrs[j] = caddr; } } } first_run = false; } for(int i = 0; i < addrs.Length; i++) { Console.WriteLine(new AHAddress(baddrs[i]) + " " + new AHAddress(addrs[i])); Address laddr = new AHAddress(addrs[i]); Node node = (Node) nodes[laddr]; node.Disconnect(); nodes.Remove(laddr); tables.Remove(laddr); network_size--; } default_dht = new Dht((Node) nodes.GetByIndex(0), degree); // Checking the ring every 5 seconds.. do { Thread.Sleep(5000);} while(!CheckAllConnections()); Console.WriteLine("Going to sleep now..."); Thread.Sleep(15000); Console.WriteLine("Timeout done.... now attempting gets"); this.SerialAsyncGet(key, (byte[][]) al_results.ToArray(typeof(byte[])), op++); Thread.Sleep(5000); Console.WriteLine("This checks to make sure our follow up Puts succeeded"); this.SerialAsyncGet(key, (byte[][]) al_results.ToArray(typeof(byte[])), op++); Console.WriteLine("If no error messages successful up to: " + (op - 1)); foreach(TableServer ts in tables.Values) { Console.WriteLine("Count ... " + ts.Count); } }
/** * Find neighbor connections within the range * return ArrayList of List<Connection> for left and right neighbors. */ private ArrayList GetConnectionInfo(AHAddress t_addr, AHAddress start, AHAddress end, ConnectionList cl) { //this node is within the given range (start_addr, end_addr) ArrayList ret = new ArrayList(); List<Connection> left_con_list = new List<Connection>(); List<Connection> right_con_list = new List<Connection>(); foreach(Connection c in cl) { AHAddress adr = (AHAddress)c.Address; if(adr.IsBetweenFromLeft(t_addr, end) ) { left_con_list.Add(c); } else if (adr.IsBetweenFromLeft(start, t_addr) ) { right_con_list.Add(c); } else { //Out of Range. Do nothing! } } //Make a compare and add it to ConnectionTable to sort by Address ConnectionLeftComparer left_cmp = new ConnectionLeftComparer(t_addr); left_con_list.Sort(left_cmp); ConnectionRightComparer right_cmp = new ConnectionRightComparer(t_addr); right_con_list.Sort(right_cmp); ret.Add(left_con_list); ret.Add(right_con_list); return ret; }
// adds a node to the pool private static void add_node(bool output) { AHAddress address = new AHAddress(new RNGCryptoServiceProvider()); Node node = new StructuredNode(address, brunet_namespace); NodeMapping nm = new NodeMapping(); nm.Node = node; nodes.Add((Address) address, nm); nm.Port = rand.Next(1024, 65535); while(TakenPorts.Contains(nm.Port)) { nm.Port = rand.Next(1024, 65535); } EdgeListener el = null; if(edge_type.Equals("function")) { el = new FunctionEdgeListener(nm.Port, 0, null); } else if(edge_type.Equals("tcp")) { el = new TcpEdgeListener(nm.Port); } else if(edge_type.Equals("udp")) { el = new UdpEdgeListener(nm.Port); } node.AddEdgeListener(el); if(!discovery) { ArrayList RemoteTAs = new ArrayList(); for(int i = 0; i < 5 && i < TakenPorts.Count; i++) { int rport = (int) TakenPorts.GetByIndex(rand.Next(0, TakenPorts.Count)); RemoteTAs.Add(TransportAddressFactory.CreateInstance("brunet." + edge_type + "://127.0.0.1:" + rport)); } node.RemoteTAs = RemoteTAs; } TakenPorts[nm.Port] = nm.Port; if(dht_enabled) { nm.Dht = new Dht(node, 3); } if(output) { Console.WriteLine("Adding: " + nm.Node.Address); } (new Thread(node.Connect)).Start(); network_size++; }
//returns true if addr is in a given range including boundary. /** * This returns true if addr is between start and end in a ring. * IsBetweenFrom*() excludes both start and end, but InRange() includes both. * @param addr, this node's address * @param start, the beginning address of range * @param end, the ending address of range */ public bool InRange(AHAddress addr, AHAddress start, AHAddress end) { bool betw = addr.IsBetweenFromLeft(start,end); if (addr == start || addr == end) {return true;} else { return betw; } }
/** * Compute the distance from this to add such that * the magnitude is less than or equal to Address.Half */ public virtual BigInteger DistanceTo(AHAddress a) { BigInteger n_x = this.ToBigInteger(); BigInteger n_y = a.ToBigInteger(); BigInteger dist = n_y - n_x; if (n_y > n_x) { //(n_y > n_x ) == (dist > 0), //but the former is faster for BigInteger if (dist >= Address.Half) { dist = dist - AHAddress.Full; } } else { //we know dist <= 0: //If dist < -Address.Half //if (0 > (Address.Half + dist)) { //same as below, but below doesn't require BigInteger(0), //so it saves memory and CPU: if (n_x > (Address.Half + n_y)) { // dist = dist + AHAddress.Full; } } return dist; }
public void Test() { RandomNumberGenerator rng = new RNGCryptoServiceProvider(); AHAddress tmp_add = new AHAddress(rng); Node n = new StructuredNode(tmp_add, "unittest"); AHSender ah = new AHSender(n, AddressParser.Parse("brunet:node:JOJZG7VO6RFOEZJ6CJJ2WOIJWTXRVRP4")); ForwardingSender fs = new ForwardingSender(n, AddressParser.Parse("brunet:node:JOJZG7VO6RFOEZJ6CJJ2WOIJWTXRVRP4"), AddressParser.Parse("brunet:node:5FMQW3KKJWOOGVDO6QAQP65AWVZQ4VUQ")); string uri = "sender:ah?dest=JOJZG7VO6RFOEZJ6CJJ2WOIJWTXRVRP4&mode=exact"; ISender s = SenderFactory.CreateInstance(n, uri); Assert.IsTrue(s is AHSender); Assert.AreEqual(uri, s.ToUri()); uri = "sender:ah?dest=JOJZG7VO6RFOEZJ6CJJ2WOIJWTXRVRP4&mode=greedy"; //Create the above programatically IDictionary<string, string> param_args = new Dictionary<string,string>(); param_args["dest"] = "JOJZG7VO6RFOEZJ6CJJ2WOIJWTXRVRP4"; param_args["mode"] = "greedy"; string uri0 = SenderFactory.EncodeUri("ah", param_args); Assert.AreEqual(uri, uri0, "EncodeUri works"); //Check decode: string scheme; param_args = SenderFactory.DecodeUri(uri, out scheme); Assert.AreEqual(scheme, "ah", "Scheme decoded"); Assert.AreEqual(param_args.Count, 2, "2 parameters in uri"); Assert.AreEqual(param_args["dest"], "JOJZG7VO6RFOEZJ6CJJ2WOIJWTXRVRP4", "Extracted address"); Assert.AreEqual(param_args["mode"], "greedy", "got mode"); s = SenderFactory.CreateInstance(n, uri); Assert.IsTrue(s is AHSender); Assert.AreEqual(uri, s.ToUri()); string furi = "sender:fw?relay=JOJZG7VO6RFOEZJ6CJJ2WOIJWTXRVRP4&init_mode=greedy&dest=5FMQW3KKJWOOGVDO6QAQP65AWVZQ4VUQ&ttl=3&mode=path"; s = SenderFactory.CreateInstance(n, furi); Assert.IsTrue(s is ForwardingSender); Assert.AreEqual(furi, s.ToUri()); }
/** * Use the DistanceTo function. If this node is * positive distance from add, it is left of. */ public bool IsLeftOf(AHAddress add) { return (add.DistanceTo(this) > 0); }
public static void Main(string []args) { if (args.Length < 1) { Console.WriteLine("please specify the number of p2p nodes."); Environment.Exit(0); } else if (args.Length < 2) { Console.WriteLine("please specify the number of missing edges."); Environment.Exit(0); } int base_port = 54111; int network_size = Int32.Parse(args[0]); int missing_edges_count = Int32.Parse(args[1]); string brunet_namespace = "testing"; SortedList nodes = new SortedList(); Console.WriteLine("Initializing..."); ArrayList RemoteTA = new ArrayList(); for(int i = 0; i < network_size; i++) { RemoteTA.Add(TransportAddressFactory.CreateInstance("brunet.udp://127.0.0.1:" + (base_port + i))); } Random rand = new Random(); for(int i = 0; i < network_size; i++) { Console.WriteLine("Starting node: {0}", i); AHAddress address = new AHAddress(new RNGCryptoServiceProvider()); Node node = new StructuredNode(address, brunet_namespace); ArrayList arr_tas = new ArrayList(); for(int j = 0; j < missing_edges_count; j++) { int remote_port = 0; do { remote_port = rand.Next(0, network_size - 1) + base_port; } while(remote_port == base_port + i); PortTAAuthorizer port_auth = new PortTAAuthorizer(remote_port); arr_tas.Add(port_auth); } arr_tas.Add(new ConstantAuthorizer(TAAuthorizer.Decision.Allow)); TAAuthorizer ta_auth = new SeriesTAAuthorizer(arr_tas); node.AddEdgeListener(new UdpEdgeListener(base_port + i, null, ta_auth)); node.AddEdgeListener(new Tunnel.TunnelEdgeListener(node)); node.RemoteTAs = RemoteTA; Thread t = new Thread(new ThreadStart(node.Connect)); t.Start(); nodes.Add((Address) address, node); Console.WriteLine("Sleeping for 2 seconds"); System.Threading.Thread.Sleep(2000); } //wait for 60 more seconds int count = 0; while(true) { Console.WriteLine("Going to sleep for 5 seconds."); System.Threading.Thread.Sleep(5000); Console.WriteLine("Checking ring..."); Address start_addr = (Address) nodes.GetKeyList()[0]; Address curr_addr = start_addr; for (int i = 0; i < network_size; i++) { Node node = (Node) nodes[curr_addr]; ConnectionTable con_table = node.ConnectionTable; Connection con = con_table.GetLeftStructuredNeighborOf((AHAddress) curr_addr); Console.WriteLine("Hop {2}\t Address {0}\n\t Connection to left {1}\n", curr_addr, con, i); Address next_addr = con.Address; if (next_addr == null) { Console.WriteLine("Found disconnection."); break; } Connection lc = ((Node)nodes[next_addr]).ConnectionTable.GetRightStructuredNeighborOf((AHAddress) next_addr); if( (lc == null) || !curr_addr.Equals(lc.Address)) { Address left_addr = lc.Address; Console.WriteLine(curr_addr + " != " + left_addr); Console.WriteLine("Right had edge, but left has no record of it!\n{0} != {1}", con, lc); break; } else if(next_addr.Equals(start_addr) && i != network_size -1) { Console.WriteLine("Completed circle too early. Only {0} nodes in the ring.", (i + 1)); break; } curr_addr = next_addr; } count++; if(start_addr.Equals(curr_addr)) { Console.WriteLine("Ring properly formed!"); Console.WriteLine("This only took .... {0} seconds", (count * 5)); break; } } count = 0; while(true) { Console.WriteLine("Going to sleep for 5 seconds."); System.Threading.Thread.Sleep(5000); Console.WriteLine("Checking ring..."); Address start_addr = (Address) nodes.GetKeyList()[0]; Address curr_addr = start_addr; for (int i = 0; i < network_size; i++) { Node node = (Node) nodes[curr_addr]; ConnectionTable con_table = node.ConnectionTable; Connection con = con_table.GetRightStructuredNeighborOf((AHAddress) curr_addr); Console.WriteLine("Hop {2}\t Address {0}\n\t Connection to right {1}\n", curr_addr, con, i); Address next_addr = con.Address; if (next_addr == null) { Console.WriteLine("Found disconnection."); } Connection left_con = ((Node)nodes[next_addr]).ConnectionTable.GetLeftStructuredNeighborOf((AHAddress) next_addr); if(left_con == null) { Console.WriteLine("Found disconnection."); } else if(!curr_addr.Equals(left_con.Address)) { Address left_addr = left_con.Address; Console.WriteLine(curr_addr + " != " + left_addr); Console.WriteLine("Left had edge, but right has no record of it! {0}", left_con); break; } else if(next_addr.Equals(start_addr) && i != network_size -1) { Console.WriteLine("Completed circle too early. Only " + count + " nodes in the ring."); break; } curr_addr = next_addr; } count++; if(start_addr.Equals(curr_addr)) { Console.WriteLine("Ring properly formed!"); Console.WriteLine("This only took .... {0} seconds", (count * 5)); break; } } foreach(DictionaryEntry de in nodes) { Node node = (Node)de.Value; node.Disconnect(); } }
/** * The Right (decreasing, counterclockwise) distance to * the given AHAddress * @param addr the AHAddress to compute the distance to * @return the distance */ public BigInteger RightDistanceTo(AHAddress addr) { BigInteger n_x = ToBigInteger(); BigInteger n_y = addr.ToBigInteger(); BigInteger dist; if (n_y < n_x) { //The given address is smaller than us, just subtract dist = n_x - n_y; } else { //We need to add AHAddress.Full to the result: dist = n_x - n_y + AHAddress.Full; } return dist; }
void ToDotFile(ArrayList node_list, int index) { string file_name = string.Format("BootGraph_{0:000000}",index); StreamWriter sw = File.CreateText(file_name); sw.WriteLine("digraph bootgraph { "); //sw.WriteLine("size=\"8,8\";"); sw.WriteLine("graph [bb=\"0,0,800,800\"];"); AHAddress add = new AHAddress(new BigInteger(0)); ArrayList all_adds = new ArrayList(); AHAddressComparer cmp = new AHAddressComparer(add); foreach( Node item in node_list) { int ins_index = all_adds.BinarySearch(item.Address, cmp); if (ins_index < 0) { ins_index = ~ins_index; all_adds.Insert(ins_index,item.Address); } } double nodesize = .50; int canvassize = 576; double r = (double)canvassize/2.0 - 1.0 -36.0*nodesize; int c = canvassize/2; int nodes = all_adds.Count; int position = 0; double phi = Math.PI/(2*((double)nodes)); //double r = Math.Cos(phi)/(2.0*nodesize); //double r =((double)(canvassize-1-2-Math.Ceiling(nodesize )))/2.0; double theta = 0.0; int ringlayoutx = 0; int ringlayouty = 0; foreach( Address item in all_adds) { theta = (double)(4*(position))*phi; ringlayoutx = c + (int)(r*Math.Sin(theta)); ringlayouty = c - (int)(r*Math.Cos(theta)); string node_line = String.Format("{0} [pos=\"{1:D},{2:D}\", width=\"{3:F2}\",height=\"{4:F2}\"];", item.ToBigInteger().IntValue(), ringlayoutx, ringlayouty, nodesize, nodesize); sw.WriteLine(node_line); position++; } foreach( Node item in node_list) { ConnectionList leafs = item.ConnectionTable.GetConnections(ConnectionType.Leaf); foreach(Connection con in leafs) { Address leaf_item = con.Address; string graph_line = String.Format("{0} -> {1} [color= blue];", item.Address.ToBigInteger().IntValue(), leaf_item.ToBigInteger().IntValue() ); sw.WriteLine(graph_line); } ConnectionList structs = item.ConnectionTable.GetConnections(ConnectionType.Structured); foreach(Connection con in structs) { Address struct_item = con.Address; string graph_line = String.Format("{0} -> {1} [color= red];", item.Address.ToBigInteger().IntValue(), struct_item.ToBigInteger().IntValue() ); sw.WriteLine(graph_line); } } sw.WriteLine("}"); sw.Close(); SHA1 sha1 = (SHA1) CryptoConfig.CreateFromName("SHA1"); string neato_command = String.Format("/usr/bin/neato"); string neato_args =String.Format("-Tps -o {0}_circle.ps -n -s72 {0}",file_name ); string dot_command = String.Format("/usr/bin/dot"); string dot_args = String.Format("-Tps -o {0}.ps {1}",file_name,file_name); //string touch_cmd = String.Format("/usr/bin/touch"); //string touch_args = String.Format(" t_movie.ps movie.ps"); //string cat_cmd = String.Format("/bin/cat"); //string cat_args = String.Format(" t_movie.ps {0}.ps > t_movie.ps",file_name); //string ps2ps_cmd = String.Format("/usr/bin/ps2ps"); //string ps2ps_args = String.Format("t_movie.ps movie.ps"); FileStream fs_this = new FileStream (file_name, FileMode.Open, FileAccess.Read); if ( l_u_f != null ) { string this_hash_string = Base32.Encode(sha1.ComputeHash (fs_this)); if( l_u_h == this_hash_string ) { if (File.Exists(file_name)) { File.Delete(file_name); } } else { ProgramRunner(dot_command,dot_args); ProgramRunner(neato_command,neato_args); l_u_f = file_name; FileStream fs_last = new FileStream (l_u_f, FileMode.Open, FileAccess.Read); l_u_h = Base32.Encode(sha1.ComputeHash (fs_last)); fs_last.Close (); //ProgramRunner(cat_cmd,cat_args); //ProgramRunner(ps2ps_cmd,ps2ps_args); } } else { //ProgramRunner(touch_cmd,touch_args); ProgramRunner(dot_command,dot_args); ProgramRunner(neato_command,neato_args); l_u_f = file_name; FileStream fs_last = new FileStream ( l_u_f, FileMode.Open, FileAccess.Read); l_u_h = Base32.Encode(sha1.ComputeHash (fs_last)) ; fs_last.Close (); //ProgramRunner(cat_cmd,cat_args); //ProgramRunner(ps2ps_cmd,ps2ps_args); } fs_this.Close (); }
public void Test() { byte[] buf1 = new byte[20]; for (int i = 0; i <= 18; i++) { buf1[i] = 0x00; } buf1[19] = 0x0A; AHAddress test_address_1 = new AHAddress( MemBlock.Reference(buf1, 0, buf1.Length) ); byte[] buf2 = new byte[20]; for (int i = 0; i <= 18; i++) { buf2[i] = 0xFF; } buf2[19] = 0xFE; AHAddress test_address_2 = new AHAddress( MemBlock.Reference(buf2, 0, buf2.Length) ); //test_address_1 is to the left of test_address_2 //because it only a few steps in the clockwise direction: Assert.IsTrue( test_address_1.IsLeftOf( test_address_2 ), "IsLeftOf"); Assert.IsTrue( test_address_2.IsRightOf( test_address_1 ), "IsRightOf"); //This distance is twelve: Assert.AreEqual( test_address_2.DistanceTo( test_address_1), new BigInteger(12), "DistanceTo"); Assert.IsTrue( test_address_1.CompareTo(test_address_2) < 0, "CompareTo"); Assert.IsTrue( test_address_2.CompareTo(test_address_1) > 0, "CompareTo"); byte[] buf3 = new byte[Address.MemSize]; test_address_2.CopyTo(buf3); AHAddress test3 = new AHAddress(MemBlock.Reference(buf3,0,buf3.Length)); Assert.IsTrue( test3.CompareTo( test_address_2 ) == 0 , "CompareTo"); Assert.IsTrue( test3.CompareTo( test3 ) == 0, "CompareTo"); //As long as the address does not wrap around, adding should increase it: AHAddress a4 = new AHAddress( test_address_1.ToBigInteger() + 100 ); Assert.IsTrue( a4.CompareTo( test_address_1 ) > 0, "adding increases"); Assert.IsTrue( a4.CompareTo( test_address_2 ) < 0, "smaller than biggest"); //Here are some consistency tests: for( int i = 0; i < 100; i++) { System.Random r = new Random(); byte[] b1 = new byte[Address.MemSize]; r.NextBytes(b1); //Make sure it is class 0: Address.SetClass(b1, 0); byte[] b2 = new byte[Address.MemSize]; r.NextBytes(b2); //Make sure it is class 0: Address.SetClass(b2, 0); byte[] b3 = new byte[Address.MemSize]; r.NextBytes(b3); //Make sure it is class 0: Address.SetClass(b3, 0); AHAddress a5 = new AHAddress( MemBlock.Reference(b1,0,b1.Length) ); AHAddress a6 = new AHAddress( MemBlock.Reference(b2,0,b2.Length) ); AHAddress a7 = new AHAddress( MemBlock.Reference(b3,0,b3.Length) ); Assert.IsTrue( a5.CompareTo(a6) == -1 * a6.CompareTo(a5), "consistency"); //Nothing is between the same address: Assert.IsFalse( a5.IsBetweenFromLeft(a6, a6), "Empty Between Left"); Assert.IsFalse( a5.IsBetweenFromRight(a7, a7), "Empty Between Right"); //Endpoints are not between: Assert.IsFalse( a6.IsBetweenFromLeft(a6, a7), "End point Between Left"); Assert.IsFalse( a6.IsBetweenFromRight(a6, a7), "End point Between Right"); Assert.IsFalse( a7.IsBetweenFromLeft(a6, a7), "End point Between Left"); Assert.IsFalse( a7.IsBetweenFromRight(a6, a7), "End point Between Right"); if ( a5.IsBetweenFromLeft(a6, a7) ) { //Then the following must be true: Assert.IsTrue( a6.LeftDistanceTo(a5) < a6.LeftDistanceTo(a7), "BetweenLeft true"); } else { //Then the following must be false: Assert.IsFalse( a6.LeftDistanceTo(a5) < a6.LeftDistanceTo(a7), "BetweenLeft false"); } if ( a5.IsBetweenFromRight(a6, a7) ) { //Then the following must be true: Assert.IsTrue( a6.RightDistanceTo(a5) < a6.RightDistanceTo(a7), "BetweenRight true"); } else { //Then the following must be false: Assert.IsFalse( a6.RightDistanceTo(a5) < a6.RightDistanceTo(a7), "BetweenRight false"); } Assert.IsFalse(a5.IsBetweenFromLeft(a6, a7) == a5.IsBetweenFromRight(a6, a7), "can't be between left and between right"); } }
public static void testAddressComparer(ArrayList node_list) { AHAddress add = new AHAddress(new BigInteger(0)); ArrayList all_adds = new ArrayList(); AHAddressComparer cmp = new AHAddressComparer(add); System.Console.WriteLine("Address comparison test:"); AHAddress a0 = (AHAddress)(((Node)node_list[0]).Address); AHAddress a1 = (AHAddress)(((Node)node_list[1]).Address); System.Console.WriteLine("Address: {0}", a0); System.Console.WriteLine("Address: {0}", a1); System.Console.WriteLine("Distance between a0 and a1:{0}", a0.DistanceTo(a1)); System.Console.WriteLine("Compare a0 and a1:{0}", cmp.Compare(a0,a1)); System.Console.WriteLine("------------------------"); foreach( Node item in node_list) { int ins_index = all_adds.BinarySearch(item.Address, cmp); if (ins_index < 0) { ins_index = ~ins_index; all_adds.Insert(ins_index,item.Address); } } for (int i=0; i<all_adds.Count; i++) { Address item = (Address)all_adds[i]; System.Console.WriteLine("Adress is {0}", item); } }